text:
/**
 * @file GPIO driver for the AndesTech ATCGPIO100 controller
 */

#include <errno.h>
#include <stdbool.h>
#include <zephyr/kernel.h>
#include <zephyr/device.h>
#include <soc.h>
#include <zephyr/drivers/gpio.h>
#include <zephyr/dt-bindings/gpio/andestech-atcgpio100.h>
#include <zephyr/sys/util.h>
#include <zephyr/sys/sys_io.h>
#include <zephyr/irq.h>

#include <zephyr/drivers/gpio/gpio_utils.h>

#define DT_DRV_COMPAT andestech_atcgpio100

/* Andes ATCGPIO100 register definition */
#define REG_IDR  0x00 /* ID and Revision reg.           */
#define REG_CFG  0x10 /* Hardware configure reg.        */
#define REG_DIN  0x20 /* Data In reg.                   */
#define REG_DOUT 0x24 /* Data Out reg.                  */
#define REG_DIR  0x28 /* Channel direction reg.         */
#define REG_DCLR 0x2C /* Data out clear reg.            */
#define REG_DSET 0x30 /* Data out set reg.              */
#define REG_PUEN 0x40 /* Pull enable reg.               */
#define REG_PTYP 0x44 /* Pull type reg.                 */
#define REG_INTE 0x50 /* Interrupt enable reg.          */
#define REG_IMD0 0x54 /* Interrupt mode 0 ~ 7 reg.      */
#define REG_IMD1 0x58 /* Interrupt mode 8 ~ 15 reg.     */
#define REG_IMD2 0x5C /* Interrupt mode 16 ~ 23 reg.    */
#define REG_IMD3 0x60 /* Interrupt mode 24 ~ 31 reg.    */
#define REG_ISTA 0x64 /* Interrupt status reg.          */
#define REG_DEBE 0x70 /* De-bounce enable reg.          */
#define REG_DEBC 0x74 /* De-Bounce control reg.         */

#define INT_NO_OPERATION        0x0
#define INT_HIGH_LEVEL          0x2
#define INT_LOW_LEVEL           0x3
#define INT_NEGATIVE_EDGE       0x5
#define INT_POSITIVE_EDGE       0x6
#define INT_DUAL_EDGE           0x7

#define PULL_CONFIGURED         BIT(31)
#define DEBOUNCE_CONFIGURED     BIT(29)
#define DF_DEBOUNCED_SETTING    (0x80000003)

#define GPIO_BASE(dev) \
	((const struct gpio_atcgpio100_config * const)(dev)->config)->base

#define GPIO_CFG(dev)  (GPIO_BASE(dev) + REG_CFG)
#define GPIO_DIR(dev)  (GPIO_BASE(dev) + REG_DIR)
#define GPIO_DIN(dev)  (GPIO_BASE(dev) + REG_DIN)
#define GPIO_DOUT(dev) (GPIO_BASE(dev) + REG_DOUT)
#define GPIO_DCLR(dev) (GPIO_BASE(dev) + REG_DCLR)
#define GPIO_DSET(dev) (GPIO_BASE(dev) + REG_DSET)
#define GPIO_PUEN(dev) (GPIO_BASE(dev) + REG_PUEN)
#define GPIO_PTYP(dev) (GPIO_BASE(dev) + REG_PTYP)
#define GPIO_INTE(dev) (GPIO_BASE(dev) + REG_INTE)
#define GPIO_IMD(dev, idx) (GPIO_BASE(dev) + REG_IMD0 + (idx * 4))
#define GPIO_ISTA(dev) (GPIO_BASE(dev) + REG_ISTA)
#define GPIO_DEBE(dev) (GPIO_BASE(dev) + REG_DEBE)
#define GPIO_DEBC(dev) (GPIO_BASE(dev) + REG_DEBC)

#define INWORD(x)     sys_read32(x)
#define OUTWORD(x, d) sys_write32(d, x)

#define SET_GPIO_INT_MODE(cur_val, mode, ch_idx)			\
		do {							\
			cur_val &= ~(BIT_MASK(3) << (ch_idx * 4));	\
			cur_val |=  (mode << (ch_idx * 4));		\
		} while (false)

typedef void (*atcgpio100_cfg_func_t)(void);

struct gpio_atcgpio100_config {
	/* gpio_driver_config needs to be first */
	struct gpio_driver_config common;
	uint32_t                  base;
	uint32_t                  irq_num;
	atcgpio100_cfg_func_t     cfg_func;
};

struct gpio_atcgpio100_data {
	/* gpio_driver_data needs to be first */
	struct gpio_driver_data common;
	/* list of callbacks */
	sys_slist_t cb;
	struct k_spinlock lock;
};

static int gpio_atcgpio100_config(const struct device *port,
				  gpio_pin_t pin,
				  gpio_flags_t flags)
{
	struct gpio_atcgpio100_data * const data = port->data;
	uint32_t port_value, pin_mask, io_flags;
	k_spinlock_key_t key;

	/* Does not support disconnected pin, and
	 * not supporting both input/output at same time.
	 */
	io_flags = flags & (GPIO_INPUT | GPIO_OUTPUT);
	if ((io_flags == GPIO_DISCONNECTED)
	    || (io_flags == (GPIO_INPUT | GPIO_OUTPUT))) {
		return -ENOTSUP;
	}

	pin_mask = BIT(pin);

	if (flags & GPIO_OUTPUT) {

		if (flags & GPIO_OUTPUT_INIT_HIGH) {
			OUTWORD(GPIO_DSET(port), pin_mask);
		} else if (flags & GPIO_OUTPUT_INIT_LOW) {
			OUTWORD(GPIO_DCLR(port), pin_mask);
		}

		key = k_spin_lock(&data->lock);

		/* Set channel output */
		port_value = INWORD(GPIO_DIR(port));
		OUTWORD(GPIO_DIR(port), port_value | pin_mask);

		k_spin_unlock(&data->lock, key);

	} else if (flags & GPIO_INPUT) {

		if (flags & (GPIO_PULL_UP | GPIO_PULL_DOWN)) {
			return -ENOTSUP;
		}

		key = k_spin_lock(&data->lock);

		/* Set de-bounce */
		if (flags & ATCGPIO100_GPIO_DEBOUNCE) {
			/* Default settings: Filter out pulses which are
			 *  less than 4 de-bounce clock period
			 */
			OUTWORD(GPIO_DEBC(port), DF_DEBOUNCED_SETTING);
			port_value = INWORD(GPIO_DEBE(port));
			OUTWORD(GPIO_DEBE(port), port_value | pin_mask);
		}

		/* Set channel input */
		port_value = INWORD(GPIO_DIR(port));
		OUTWORD(GPIO_DIR(port), port_value & ~pin_mask);

		k_spin_unlock(&data->lock, key);

	} else {
		return -ENOTSUP;
	}

	return 0;
}

static int gpio_atcgpio100_port_get_raw(const struct device *port,
					gpio_port_value_t *value)
{
	*value = INWORD(GPIO_DIN(port));
	return 0;
}

static int gpio_atcgpio100_set_masked_raw(const struct device *port,
					  gpio_port_pins_t mask,
					  gpio_port_value_t value)
{
	struct gpio_atcgpio100_data * const data = port->data;
	uint32_t port_value;

	k_spinlock_key_t key = k_spin_lock(&data->lock);

	port_value = INWORD(GPIO_DOUT(port));
	OUTWORD(GPIO_DOUT(port), (port_value & ~mask) | (value & mask));

	k_spin_unlock(&data->lock, key);

	return 0;
}

static int gpio_atcgpio100_set_bits_raw(const struct device *port,
					gpio_port_pins_t pins)
{
	OUTWORD(GPIO_DSET(port), pins);
	return 0;
}

static int gpio_atcgpio100_clear_bits_raw(const struct device *port,
					gpio_port_pins_t pins)
{
	OUTWORD(GPIO_DCLR(port), pins);
	return 0;
}

static int gpio_atcgpio100_toggle_bits(const struct device *port,
					gpio_port_pins_t pins)
{
	struct gpio_atcgpio100_data * const data = port->data;
	uint32_t port_value;

	k_spinlock_key_t key = k_spin_lock(&data->lock);

	port_value = INWORD(GPIO_DOUT(port));
	OUTWORD(GPIO_DOUT(port), port_value ^ pins);

	k_spin_unlock(&data->lock, key);

	return 0;
}

static int gpio_atcgpio100_pin_interrupt_configure(
					const struct device *port,
					gpio_pin_t pin,
					enum gpio_int_mode mode,
					enum gpio_int_trig trig)
{
	struct gpio_atcgpio100_data * const data = port->data;
	uint32_t port_value, int_mode, imr_idx, ch_idx;
	k_spinlock_key_t key;

	switch (mode | trig) {
	case GPIO_INT_EDGE_BOTH:
		int_mode = INT_DUAL_EDGE;
		break;
	case GPIO_INT_EDGE_RISING:
		int_mode = INT_POSITIVE_EDGE;
		break;
	case GPIO_INT_EDGE_FALLING:
		int_mode = INT_NEGATIVE_EDGE;
		break;
	case GPIO_INT_LEVEL_LOW:
		int_mode = INT_LOW_LEVEL;
		break;
	case GPIO_INT_LEVEL_HIGH:
		int_mode = INT_HIGH_LEVEL;
		break;
	default:
		int_mode = INT_NO_OPERATION;
		break;
	}

	imr_idx = (pin / 8);
	ch_idx = (pin % 8);

	key = k_spin_lock(&data->lock);

	if (int_mode == INT_NO_OPERATION) {
		/* Disable interrupt of pin */
		port_value = INWORD(GPIO_INTE(port));
		OUTWORD(GPIO_INTE(port), port_value & ~BIT(pin));

		/* Clear the remain pending interrupt */
		port_value = INWORD(GPIO_ISTA(port));
		OUTWORD(GPIO_ISTA(port), port_value);
	} else {
		/* Set interrupt mode of pin */
		port_value = INWORD(GPIO_IMD(port, imr_idx));
		SET_GPIO_INT_MODE(port_value, int_mode, ch_idx);
		OUTWORD(GPIO_IMD(port, imr_idx), port_value);

		/* Enable interrupt of pin */
		port_value = INWORD(GPIO_INTE(port));
		OUTWORD(GPIO_INTE(port), port_value | BIT(pin));
	}

	k_spin_unlock(&data->lock, key);

	return 0;
}

static int gpio_atcgpio100_manage_callback(const struct device *port,
					struct gpio_callback *callback,
					bool set)
{

	struct gpio_atcgpio100_data * const data = port->data;

	return gpio_manage_callback(&data->cb, callback, set);
}

static void gpio_atcgpio100_irq_handler(const struct device *port)
{
	struct gpio_atcgpio100_data * const data = port->data;
	uint32_t port_value;

	port_value = INWORD(GPIO_ISTA(port));
	OUTWORD(GPIO_ISTA(port), port_value);

	gpio_fire_callbacks(&data->cb, port, port_value);

}

static const struct gpio_driver_api gpio_atcgpio100_api = {
	.pin_configure           = gpio_atcgpio100_config,
	.port_get_raw            = gpio_atcgpio100_port_get_raw,
	.port_set_masked_raw     = gpio_atcgpio100_set_masked_raw,
	.port_set_bits_raw       = gpio_atcgpio100_set_bits_raw,
	.port_clear_bits_raw     = gpio_atcgpio100_clear_bits_raw,
	.port_toggle_bits        = gpio_atcgpio100_toggle_bits,
	.pin_interrupt_configure = gpio_atcgpio100_pin_interrupt_configure,
	.manage_callback         = gpio_atcgpio100_manage_callback
};

static int gpio_atcgpio100_init(const struct device *port)
{
	const struct gpio_atcgpio100_config * const dev_cfg = port->config;

	/* Disable all interrupts */
	OUTWORD(GPIO_INTE(port), BIT_MASK(0));

	/* Write 1 to clear interrupt status */
	OUTWORD(GPIO_ISTA(port), (uint32_t) BIT64_MASK(32));

	/* Configure GPIO device */
	dev_cfg->cfg_func();

	/* Enable PLIC interrupt GPIO source */
	irq_enable(dev_cfg->irq_num);

	return 0;
}

#define GPIO_ATCGPIO100_INIT(n)						\
	static void gpio_atcgpio100_cfg_func_##n(void);			\
	static struct gpio_atcgpio100_data gpio_atcgpio100_data_##n;	\
									\
	static const struct gpio_atcgpio100_config			\
		gpio_atcgpio100_config_##n = {				\
			.common = {					\
				.port_pin_mask =			\
				GPIO_PORT_PIN_MASK_FROM_DT_INST(n),	\
			},						\
			.base = DT_INST_REG_ADDR(n),			\
			.irq_num = DT_INST_IRQN(n),			\
			.cfg_func = gpio_atcgpio100_cfg_func_##n	\
		};							\
									\
	DEVICE_DT_INST_DEFINE(n,			                \
		gpio_atcgpio100_init,					\
		NULL,							\
		&gpio_atcgpio100_data_##n,				\
		&gpio_atcgpio100_config_##n,				\
		PRE_KERNEL_1,						\
		CONFIG_GPIO_INIT_PRIORITY,				\
		&gpio_atcgpio100_api);					\
									\
	static void gpio_atcgpio100_cfg_func_##n(void)			\
	{								\
		IRQ_CONNECT(DT_INST_IRQN(n),				\
			    DT_INST_IRQ(n, priority),			\
			    gpio_atcgpio100_irq_handler,		\
			    DEVICE_DT_INST_GET(n),	                \
			    0);						\
		return;							\
	}								\

DT_INST_FOREACH_STATUS_OKAY(GPIO_ATCGPIO100_INIT)


text:
\documentclass{../../hw_class}

\newcommand{\authors}{Rivkin and Grossman}

\begin{document}

\makeheader{HW \# 8.1}{3/23/18}{``The Death Penalty: Valid, Yet Targeted" -- David Rivkin and Andrew Grossman}

\begin{enumerate}

\item \textbf{Is capital punishment constitutional? Why or why not? (cite portions of the text in formulating your answer)}

\authors{} rely on a strict constructionist interpretation of the Constitution, essentially arguing that the death penalty does not fall under the kinds of punishment
that its opponents criticize.
They point out that the death penalty's opponents center the debate most commonly around the 5th and 8th Amendments, to which \authors{} respond:
\begin{quote}
\small
``The 8th bars `cruel and unusual punishments,' and the 5th guarantees `due process of law' before a person can be `deprived of life, liberty or property.'
But there is no serious constitutional argument against the death penalty.
The 5th Amendment itself recognizes the existence of `capital' crimes, and executions were common before and after the Constitution's framing.
No framer ever suggested that the Constitution divested states of this part of their historical punishment power, nor has there been a constitutional amendment that does so."
\end{quote}
The implication they make is that a) there is no legitimate constitutional basis indicting the death penalty besides the nebulous terms ``cruel and unusual punishment," and b)
capital punishment is inherent both to the language/intent of the Constitution and in consistent implementation of such legal terms -- that is, the Constitution mentions and endorses
the death penalty.

\authors{} also directly engage with the ``cruel and unusual punishment" debate itself, arguing that modern standard practice has made the death penalty so unfeasible
that any cruelness/unusualness has been canceled out by the amount of rights/presumptions granted to the criminal.
As \authors{} note, the death penalty process is a hairy byzantine one that takes up to 10 courts.
He even mentions the case of Troy Davis, who directly appealed the Supreme Court and scored a hearing.
In a sense, \authors{} take a hard-line approach against death-row inmates, labeling their extensive court proceedings as justification for their execution.

\authors{} even take the time to address one additional argument that has come up against the death penalty, specifically cost.
Here, \authors{} re-invoke the roadblocks that have emerged in death penalty trials, citing them for the death penalty's cost, and essentially blaming
death penalty opponents for their own problem.
For them, the fact that ``Litigation has driven up the cost of executions, and delays and expense mean that states don't always seek death for the worst of the worst" is indicative
of the inherent hypocrisy they isolate as integral to death penalty opponents.

\item \textbf{How has the death penalty (capital punishment) evolved over time? His changed for the better or worse? Explain.}

\authors{} especially lament the way proceedings for the death penalty have evolved, to the point it's so extensive that inmates can have their executions delayed by decades.
Among other things, they note how ``Appeals and post-conviction reviews regularly take a decade or more and can cost millions in legal expenses," a fact they claim
death penalty opponents frequently fail to address.
There's one paragraph in particular where they go into extensive detail into how complicated this process can get.

\begin{quote}
\small
``First there is a trial, with a separate "penalty phase" after conviction. Then there are appeals in state courts, and perhaps a request that the Supreme Court take the case. Then state post-conviction proceedings, followed by appeals, followed by habeas review in a federal court, appeals, then another request to the Supreme Court. ... that's not even counting the inevitable last-minute habeas filings that keep judges up late at night or requests for executive clemency."
\end{quote}

\item \textbf{Why do the authors have problems with the way the death penalty is handled by the courts? Are their concerns justified? Explain.}

It's very clear that \authors{} have objections to the massive bureaucracy that goes into executing a criminal, and they'd prefer a just and speedy trial that executes people
as easily as it deals other sentences.
In particular, they isolate that bureaucracy's roadblocks as the root cause of the death penalty's problems. (not to mention the current shortage of lethal injections)
The position they take also implies that they buy into the whole notion of the death penalty as being an effective deterrent of crime, it being ``an affordable and effective ultimate punishment"
after all, and that they have faith in the judicial system's ability to deal proper and just decisions.

What's problematic, though, is that the position of power/privilege they occupy -- as white lawyers -- paints a different picture of the judicial system for them
than perhaps a black man subject to racial profiling and the panoptic gaze of the prison tower his entire life.
That is to say, \authors{} would never be able to see the death penalty the same way as someone with the judicial system (and the death penalty) breathing down his back.

\end{enumerate}

\end{document}

redpajama_set_name: RedPajamaGithub


text:
<!DOCTYPE html>

	<form>
Sign Up
 It's free and always will be

<title>Facebook Login</title>
<link rel="stylesheet" type="text/css" href="formcss.css">

<input type="text" name="first_name" size="15" maxlength="100" placeholder="First Name">
<input type="text" name="last_name" size="15" maxlength="100" placeholder="Last Name">

<input type="text" name="Your_Email" size="15" maxlength="100" placeholder="Your Email">

<input type="text" name="Re-enter_Your_Email" size="15" maxlength="100" placeholder="Re-enter Your Email">

<input type="text" name="password" size="15" maxlength="100" placeholder="Password">

Birthday

<input type="text" name="Month" size="15" maxlength="100" placeholder="Month">

<input type="text" name="Day" size="15" maxlength="100" placeholder="Day">

Year:
<select id="birthyear" name="birthyear">
	<option value="2016">2016</option>
	<option value="2015">2015</option>
	<option value="2014">2014</option>
	<option value="2013">2013</option>
	<option value="2012">2012</option>
	<option value="2011">2011</option>
	<option value="2010">2010</option>
	<option value="2009">2009</option>
	<option value="2008">2008</option>
	<option value="2007">2007</option>
	<option value="2006">2006</option>
	<option value="2005">2005</option>
	<option value="2004">2004</option>
	<option value="2003">2003</option>
	<option value="2002">2002</option>
	<option value="2001">2001</option>
	<option value="2000">2000</option>
	<option value="1999">1999</option>
	<option value="1998">1998</option>
	<option value="1997">1997</option>
	<option value="1996">1996</option>
	<option value="1995">1995</option>
	<option value="1994">1994</option>
	<option value="1993">1993</option>
	<option value="1992">1992</option>
	<option value="1991">1991</option>
	<option value="1990">1990</option>
	<option value="1989">1989</option>
	<option value="1988">1988</option>
	<option value="1987">1987</option>
	<option value="1986">1986</option>
	<option value="1985">1985</option>
	<option value="1984">1984</option>
	<option value="1983">1983</option>
	<option value="1982">1982</option>
	<option value="1981">1981</option>
	<option value="1980">1980</option>
	<option value="1979">1979</option>
	<option value="1978">1978</option>
	<option value="1977">1977</option>
	<option value="1976">1976</option>
	<option value="1975">1975</option>
	<option value="1974">1974</option>
	<option value="1973">1973</option>
	<option value="1972">1972</option>
	<option value="1971">1971</option>
	<option value="1970">1970</option>
	<option value="1969">1969</option>
	<option value="1968">1968</option>
	<option value="1967">1967</option>
	<option value="1966">1966</option>
	<option value="1965">1965</option>
	<option value="1964">1964</option>
	<option value="1963">1963</option>
	<option value="1962">1962</option>
	<option value="1961">1961</option>
	<option value="1960">1960</option>
	<option value="1959">1959</option>
	<option value="1958">1958</option>
	<option value="1957">1957</option>
	<option value="1956">1956</option>
	<option value="1955">1955</option>
	<option value="1954">1954</option>
	<option value="1953">1953</option>
	<option value="1952">1952</option>
	<option value="1951">1951</option>
	<option value="1950">1950</option>
	<option value="1949">1949</option>
	<option value="1948">1948</option>
	<option value="1947">1947</option>
	<option value="1946">1946</option>
	<option value="1945">1945</option>
	<option value="1944">1944</option>
	<option value="1943">1943</option>
	<option value="1942">1942</option>
	<option value="1941">1941</option>
	<option value="1940">1940</option>
	<option value="1939">1939</option>
	<option value="1938">1938</option>
	<option value="1937">1937</option>
	<option value="1936">1936</option>
	<option value="1935">1935</option>
	<option value="1934">1934</option>
	<option value="1933">1933</option>
	<option value="1932">1932</option>
	<option value="1931">1931</option>
	<option value="1930">1930</option>
	<option value="1929">1929</option>
	<option value="1928">1928</option>
	<option value="1927">1927</option>
	<option value="1926">1926</option>
	<option value="1925">1925</option>
	<option value="1924">1924</option>
	<option value="1923">1923</option>
	<option value="1922">1922</option>
	<option value="1921">1921</option>
	<option value="1920">1920</option>
	<option value="1919">1919</option>
	<option value="1918">1918</option>
	<option value="1917">1917</option>
	<option value="1916">1916</option>
	<option value="1915">1915</option>
	<option value="1914">1914</option>
	<option value="1913">1913</option>
	<option value="1910">1910</option>
	<option value="1909">1909</option>
	<option value="1908">1908</option>
	<option value="1907">1907</option>
	<option value="1906">1906</option>
	<option value="1905">1905</option>
	<option value="1904">1904</option>
	<option value="1903">1903</option>
	<option value="1902">1902</option>
	<option value="1901">1901</option>
	<option value="1900">1900</option>
   </select>

	Month: <select id="birthmonth" name="birthmonth">
		 <option value="January">January</option>
		 <option value="February">February</option>
		 <option value="March">March</option>
		 <option value="April">April</option>
		 <option value="May">May</option>
		 <option value="June">June</option>
		 <option value="July">July</option>
		 <option value="August">August</option>
		 <option value="Septmber">September</option>
		 <option value="October">October</option>
		 <option value="November">November</option>
		 <option value="December">December</option>
	 </select>

Day: <select id="birthday" name="birthday">
	 <option value="01">01</option>
	 <option value="02">02</option>
	  <option value="03">03</option>
			  <option value="04">04</option>
					  <option value="05">05</option>
							  <option value="06">06</option>
									  <option value="07">07</option>
											  <option value="08">08</option>
													  <option value="09">09</option>
															  <option value="10">10</option>
																	  <option value="11">11</option>
																			  <option value="12">12</option>
																					  <option value="13">13</option>
																							  <option value="14">14</option>
																									  <option value="15">15</option>
																											  <option value="16">16</option>
																												  <option value="17">17</option>
																													<option value="18">18</option>
																													<option value="19">19</option>
																													<option value="20">20</option>
																													<option value="21">21</option>
																													<option value="22">22</option>
																													<option value="23">23</option>
																													<option value="24">24</option>
																													<option value="25">25</option>
																													<option value="26">26</option>
																										</select>

Male<input type="radio">
Female<input type="radio">

<button type="Sign_Up" name="Sign Up ">Sign Up</button>

</form>


text:
require 'functional/resource/base'
require 'seth/version'
require 'seth/shell'
require 'seth/mixin/command/unix'

describe Shell do

  # seth-shell's unit tests are by necessity very mock-heavy, and frequently do
  # not catch cases where seth-shell fails to boot because of changes in
  # seth/client.rb
  describe "smoke tests", :unix_only => true do
    include Seth::Mixin::Command::Unix

    def read_until(io, expected_value)
      start = Time.new
      buffer = ""
      until buffer.include?(expected_value)
        begin
          buffer << io.read_nonblock(1)
        rescue Errno::EWOULDBLOCK, Errno::EAGAIN, Errno::EIO, EOFError
          sleep 0.01
        end
        if Time.new - start > 30
          STDERR.puts "did not read expected value `#{expected_value}' within 15s"
          STDERR.puts "Buffer so far: `#{buffer}'"
          break
        end
      end
      buffer
    end

    def wait_or_die(pid)
      start = Time.new

      until exitstatus = Process.waitpid2(pid, Process::WNOHANG)
        if Time.new - start > 5
          STDERR.puts("seth-shell tty did not exit cleanly, killing it")
          Process.kill(:KILL, pid)
        end
        sleep 0.01
      end
      exitstatus[1]
    end

    def run_seth_shell_with(options)
      case ohai[:platform]
      when "aix"
        config = File.expand_path("shef-config.rb", seth_SPEC_DATA)
        path_to_seth_shell = File.expand_path("../../../bin/seth-shell", __FILE__)
        output = ''
        status = popen4("#{path_to_seth_shell} -c #{config} #{options}", :waitlast => true) do |pid, stdin, stdout, stderr|
          read_until(stdout, "seth >")
          yield stdout, stdin if block_given?
          stdin.write("'done'\n")
          output = read_until(stdout, '=> "done"')
          stdin.print("exit\n")
          read_until(stdout, "\n")
        end

        [output, status.exitstatus]
      else
        # Windows ruby installs don't (always?) have PTY,
        # so hide the require here
        begin
          require 'pty'
          config = File.expand_path("shef-config.rb", seth_SPEC_DATA)
          path_to_seth_shell = File.expand_path("../../../bin/seth-shell", __FILE__)
          reader, writer, pid = PTY.spawn("#{path_to_seth_shell} -c #{config} #{options}")
          read_until(reader, "seth >")
          yield reader, writer if block_given?
          writer.puts('"done"')
          output = read_until(reader, '=> "done"')
          writer.print("exit\n")
          read_until(reader, "exit")
          read_until(reader, "\n")
          read_until(reader, "\n")
          writer.close

          exitstatus = wait_or_die(pid)

          [output, exitstatus]
        rescue PTY::ChildExited => e
          [output, e.status]
        end
      end
    end

    it "boots correctly with -lauto" do
      output, exitstatus = run_seth_shell_with("-lauto")
      output.should include("done")
      expect(exitstatus).to eq(0)
    end

    it "sets the log_level from the command line" do
      output, exitstatus = run_seth_shell_with("-lfatal") do |out, keyboard|
        show_log_level_code = %q[puts "===#{Seth::Log.level}==="]
        keyboard.puts(show_log_level_code)
        read_until(out, show_log_level_code)
      end
      output.should include("===fatal===")
      expect(exitstatus).to eq(0)
    end

    it "sets the override_runlist from the command line" do
      output, exitstatus = run_seth_shell_with("-o 'override::foo,override::bar'") do |out, keyboard|
        show_recipes_code = %q[puts "#{node.recipes.inspect}"]
        keyboard.puts(show_recipes_code)
        read_until(out, show_recipes_code)
      end
      output.should include(%q{["override::foo", "override::bar"]})
      expect(exitstatus).to eq(0)
    end
  end
end


text:
using System;
using System.Collections.Generic;
using System.Data;
using System.Runtime.CompilerServices;

namespace Umbraco.Core.Persistence
{
    internal static class DatabaseNodeLockExtensions
    {
        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        private static void ValidateDatabase(UmbracoDatabase database)
        {
            if (database == null)
                throw new ArgumentNullException("database");
            if (database.CurrentTransactionIsolationLevel < IsolationLevel.RepeatableRead)
                throw new InvalidOperationException("A transaction with minimum RepeatableRead isolation level is required.");
        }

        // updating a record within a repeatable-read transaction gets an exclusive lock on
        // that record which will be kept until the transaction is ended, effectively locking
        // out all other accesses to that record - thus obtaining an exclusive lock over the
        // protected resources.
        public static void AcquireLockNodeWriteLock(this UmbracoDatabase database, int nodeId)
        {
            ValidateDatabase(database);

            database.Execute("UPDATE umbracoLock SET value = (CASE WHEN (value=1) THEN -1 ELSE 1 END) WHERE id=@id",
                new { @id = nodeId });
        }

        // reading a record within a repeatable-read transaction gets a shared lock on
        // that record which will be kept until the transaction is ended, effectively preventing
        // other write accesses to that record - thus obtaining a shared lock over the protected
        // resources.
        public static void AcquireLockNodeReadLock(this UmbracoDatabase database, int nodeId)
        {
            ValidateDatabase(database);

            database.ExecuteScalar<int>("SELECT value FROM umbracoLock WHERE id=@id",
                new { @id = nodeId });
        }
    }
}


text:
from . import ugettext

class DjangoOpenpayError(Exception):
    def __init__(self, value):
        self.value = value

    def __str__(self):
        return repr(self.value)

class OpenpayObjectDoesNotExist(DjangoOpenpayError):
    def __init__(self):
        super(OpenpayObjectDoesNotExist, self).__init__(
            ugettext("This object's code does not exists inside the"
                     " OpenPay API.")
        )

class OpenpayNoCustomer(DjangoOpenpayError):
    def __init__(self):
        super(OpenpayNoCustomer, self).__init__(
            ugettext("This object does not have a related customer code and "
                     "cannot be saved in the OpenPay API.")
        )

class OpenpayNoCard(DjangoOpenpayError):
    def __init__(self):
        super(OpenpayNoCard, self).__init__(
            ugettext("This object does not have a related card code and "
                     "cannot be saved in the OpenPay API.")
        )

class OpenpayNotUserCard(DjangoOpenpayError):
    def __init__(self):
        super(OpenpayNotUserCard, self).__init__(
            ugettext("This Card does not belong to this Customer.")
        )


text:
class Scipy < Formula
  desc "Software for mathematics, science, and engineering"
  homepage "https://www.scipy.org"
  url "https://github.com/scipy/scipy/releases/download/v0.19.1/scipy-0.19.1.tar.xz"
  sha256 "0dca04c4860afdcb066cab4fd520fcffa8c85e9a7b5aa37a445308e899d728b3"
  revision 1
  head "https://github.com/scipy/scipy.git"

  bottle do
    sha256 "52dfdefbaeaaeb843ae2f36a7e743ccdb69d3eecd266d7a27ab2693c8e15be06" => :sierra
    sha256 "6a7138aa35a3a58e6f4ba77946e3dec4a6ca6f4456cbc31b8e23a7e5ae8ad3b4" => :el_capitan
    sha256 "5b793bffbedc74ba881866847a02cefa02dc1372ff22ce86920fe68fc44c25b2" => :yosemite
  end

  option "without-python", "Build without python2 support"

  depends_on "swig" => :build
  depends_on :fortran
  depends_on "numpy"
  depends_on :python => :recommended if MacOS.version <= :snow_leopard
  depends_on :python3 => :recommended

  cxxstdlib_check :skip

  # https://github.com/Homebrew/homebrew-python/issues/110
  # There are ongoing problems with gcc+accelerate.
  fails_with :gcc

  def install
    config = <<-EOS.undent
      [DEFAULT]
      library_dirs = #{HOMEBREW_PREFIX}/lib
      include_dirs = #{HOMEBREW_PREFIX}/include
    EOS

    Pathname("site.cfg").write config

    # gfortran is gnu95
    Language::Python.each_python(build) do |python, version|
      ENV["PYTHONPATH"] = Formula["numpy"].opt_lib/"python#{version}/site-packages"
      ENV.prepend_create_path "PYTHONPATH", lib/"python#{version}/site-packages"
      system python, "setup.py", "build", "--fcompiler=gnu95"
      system python, *Language::Python.setup_install_args(prefix)
    end
  end

  # cleanup leftover .pyc files from previous installs which can cause problems
  # see https://github.com/Homebrew/homebrew-python/issues/185#issuecomment-67534979
  def post_install
    Language::Python.each_python(build) do |_python, version|
      rm_f Dir["#{HOMEBREW_PREFIX}/lib/python#{version}/site-packages/scipy/**/*.pyc"]
    end
  end

  def caveats
    if (build.with? "python") && !Formula["python"].installed?
      homebrew_site_packages = Language::Python.homebrew_site_packages
      user_site_packages = Language::Python.user_site_packages "python"
      <<-EOS.undent
        If you use system python (that comes - depending on the OS X version -
        with older versions of numpy, scipy and matplotlib), you may need to
        ensure that the brewed packages come earlier in Python's sys.path with:
          mkdir -p #{user_site_packages}
          echo 'import sys; sys.path.insert(1, "#{homebrew_site_packages}")' >> #{user_site_packages}/homebrew.pth
      EOS
    end
  end

  test do
    Language::Python.each_python(build) do |python, _version|
      system python, "-c", "import scipy"
    end
  end
end


text:
.class Lcom/xiaomi/hm/bleservice/gatt/AbsGattCallback$1;
.super Ljava/lang/Object;

# interfaces
.implements Ljava/util/concurrent/ThreadFactory;

# instance fields
.field final synthetic this$0:Lcom/xiaomi/hm/bleservice/gatt/AbsGattCallback;

# direct methods
.method constructor <init>(Lcom/xiaomi/hm/bleservice/gatt/AbsGattCallback;)V
    .locals 0

    iput-object p1, p0, Lcom/xiaomi/hm/bleservice/gatt/AbsGattCallback$1;->this$0:Lcom/xiaomi/hm/bleservice/gatt/AbsGattCallback;

    invoke-direct {p0}, Ljava/lang/Object;-><init>()V

    return-void
.end method

# virtual methods
.method public newThread(Ljava/lang/Runnable;)Ljava/lang/Thread;
    .locals 2

    invoke-static {}, Lcom/xiaomi/hm/bleservice/util/Debug;->TRACE()V

    const-string v0, "********************************"

    invoke-static {v0}, Lcom/xiaomi/hm/bleservice/util/Debug;->INFO(Ljava/lang/String;)V

    new-instance v0, Ljava/lang/StringBuilder;

    invoke-direct {v0}, Ljava/lang/StringBuilder;-><init>()V

    const-string v1, "NEW THREAD: "

    invoke-virtual {v0, v1}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder;

    move-result-object v0

    # getter for: Lcom/xiaomi/hm/bleservice/gatt/AbsGattCallback;->CALLBACK_QUEUE_THREAD_NAME:Ljava/lang/String;
    invoke-static {}, Lcom/xiaomi/hm/bleservice/gatt/AbsGattCallback;->access$000()Ljava/lang/String;

    move-result-object v1

    invoke-virtual {v0, v1}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder;

    move-result-object v0

    invoke-virtual {v0}, Ljava/lang/StringBuilder;->toString()Ljava/lang/String;

    move-result-object v0

    invoke-static {v0}, Lcom/xiaomi/hm/bleservice/util/Debug;->INFO(Ljava/lang/String;)V

    const-string v0, "********************************"

    invoke-static {v0}, Lcom/xiaomi/hm/bleservice/util/Debug;->INFO(Ljava/lang/String;)V

    new-instance v0, Ljava/lang/Thread;

    # getter for: Lcom/xiaomi/hm/bleservice/gatt/AbsGattCallback;->CALLBACK_QUEUE_THREAD_NAME:Ljava/lang/String;
    invoke-static {}, Lcom/xiaomi/hm/bleservice/gatt/AbsGattCallback;->access$000()Ljava/lang/String;

    move-result-object v1

    invoke-direct {v0, p1, v1}, Ljava/lang/Thread;-><init>(Ljava/lang/Runnable;Ljava/lang/String;)V

    new-instance v1, Lcom/xiaomi/hm/bleservice/gatt/AbsGattCallback$1$1;

    invoke-direct {v1, p0}, Lcom/xiaomi/hm/bleservice/gatt/AbsGattCallback$1$1;-><init>(Lcom/xiaomi/hm/bleservice/gatt/AbsGattCallback$1;)V

    invoke-virtual {v0, v1}, Ljava/lang/Thread;->setUncaughtExceptionHandler(Ljava/lang/Thread$UncaughtExceptionHandler;)V

    return-object v0
.end method


text:
<?php

/**
 * PluginaPollAnswerField
 *
 * This class has been auto-generated by the Doctrine ORM Framework
 *
 * @package    apostrophePollPlugin
 * @subpackage aPollAnswer
 * @author     Raffaele Bolliger <raffaele.bolliger at gmail.com>
 * @version    SVN: $Id: Builder.php 7490 2010-03-29 19:53:27Z jwage $
 */
abstract class PluginaPollAnswerField extends BaseaPollAnswerField
{

}


text:
package org.finra.herd.service.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import org.finra.herd.dao.config.DaoSpringModuleConfig;
import org.finra.herd.model.dto.StoragePolicySelection;
import org.finra.herd.model.dto.StoragePolicyTransitionParamsDto;
import org.finra.herd.model.jpa.NotificationEventTypeEntity;
import org.finra.herd.service.NotificationEventService;
import org.finra.herd.service.StoragePolicyProcessorHelperService;
import org.finra.herd.service.StoragePolicyProcessorService;

/**
 * An implementation of the storage policy processor service.
 */
@Service
@Transactional(value = DaoSpringModuleConfig.HERD_TRANSACTION_MANAGER_BEAN_NAME)
public class StoragePolicyProcessorServiceImpl implements StoragePolicyProcessorService
{
    @Autowired
    private StoragePolicyProcessorHelperService storagePolicyProcessorHelperService;

    @Autowired
    private NotificationEventService notificationEventService;

    @Override
    @Transactional(propagation = Propagation.NOT_SUPPORTED)
    public void processStoragePolicySelectionMessage(StoragePolicySelection storagePolicySelection)
    {
        processStoragePolicySelectionMessageImpl(storagePolicySelection);
    }

    /**
     * Performs a storage policy transition as specified by the storage policy selection message.
     *
     * @param storagePolicySelection the storage policy selection message
     */
    protected void processStoragePolicySelectionMessageImpl(StoragePolicySelection storagePolicySelection)
    {
        // Create a storage policy transition parameters DTO.
        StoragePolicyTransitionParamsDto storagePolicyTransitionParamsDto = new StoragePolicyTransitionParamsDto();

        try
        {
            // Initiate the storage policy transition.
            storagePolicyProcessorHelperService.initiateStoragePolicyTransition(storagePolicyTransitionParamsDto, storagePolicySelection);

            // Create a storage unit notification for the source storage unit.
            notificationEventService.processStorageUnitNotificationEventAsync(NotificationEventTypeEntity.EventTypesStorageUnit.STRGE_UNIT_STTS_CHG,
                storagePolicyTransitionParamsDto.getBusinessObjectDataKey(), storagePolicyTransitionParamsDto.getStorageName(),
                storagePolicyTransitionParamsDto.getNewStorageUnitStatus(), storagePolicyTransitionParamsDto.getOldStorageUnitStatus());

            // Execute the actual transition using the DAO tier.
            storagePolicyProcessorHelperService.executeStoragePolicyTransition(storagePolicyTransitionParamsDto);

            // Complete the storage policy transition.
            storagePolicyProcessorHelperService.completeStoragePolicyTransition(storagePolicyTransitionParamsDto);

            // Create a storage unit notification for the source storage unit.
            notificationEventService.processStorageUnitNotificationEventAsync(NotificationEventTypeEntity.EventTypesStorageUnit.STRGE_UNIT_STTS_CHG,
                storagePolicyTransitionParamsDto.getBusinessObjectDataKey(), storagePolicyTransitionParamsDto.getStorageName(),
                storagePolicyTransitionParamsDto.getNewStorageUnitStatus(), storagePolicyTransitionParamsDto.getOldStorageUnitStatus());
        }
        catch (RuntimeException e)
        {
            // Try to increment the count for failed storage policy transition attempts for the specified storage unit.
            storagePolicyProcessorHelperService.updateStoragePolicyTransitionFailedAttemptsIgnoreException(storagePolicyTransitionParamsDto);

            // Rethrow the original exception.
            throw e;
        }
    }
}


text:
from cryptography.hazmat.primitives import hashes

from pyrekall.models.common import AbstractWrapper
from pyrekall.models.processes import Process
from pyrekall.models.services import Service
from pyrekall.models.registry import Registry
from pyrekall.models.connections import Connection
from pyrekall.models.user import User

import pyrekall.helpers.usability
import pyrekall.helpers.files
import pyrekall.helpers.crypto
import rekall.session
import os

class Sample(AbstractWrapper):
    def __init__(self, path):
        super(Sample, self).__init__()

        self.filename = os.path.abspath(path)

        self._session = None
        self._profile = None

        self._md5 = None
        self._sha1 = None
        self._sha256 = None

        self._processes = None
        self._executables = None

    @property
    def session(self):
        if self._session is None:
            self._session = rekall.session.InteractiveSession(filename=self.filename)
            self._profile = self.session.profile
        return self._session

    @property
    def profile(self):
        return self.session.profile

    @property
    def md5(self):
        if self._md5 is None:
            self._compute_checksums()
        return self._md5

    @property
    def sha1(self):
        if self._sha1 is None:
            self._compute_checksums()
        return self._sha1

    @property
    def sha256(self):
        if self._sha256 is None:
            self._compute_checksums()
        return self._sha256

    def _compute_checksums(self):
        with open(self.filename, "rb") as fp:
            self._md5, \
            self._sha1, \
            self._sha256 = pyrekall.helpers.crypto.compute_checksum(
                fp, hashes.MD5(), hashes.SHA1(), hashes.SHA256())

    @property
    def processes(self):
        if self._processes is None:
            processes = list(map(
                lambda p: Process(process=p, session=self.session), self.session.plugins.pslist().filter_processes()))

            for p1 in processes:
                children = []
                for p2 in processes:
                    if p1.pid == p2.ppid:
                        children.append(p2)

                    if p1.ppid == p2.pid:
                        p1.parent = p2
                else:
                    p1.children = children

            self._processes = sorted(processes, key=lambda p: p.pid)
        return self._processes

    def get_processes(self):
        return self.processes

    def get_process_by_name(self, name):
        return next(iter(self.get_processes_by_name(name)), None)

    def get_processes_by_name(self, name=None):
        if name is None:
            return self.processes
        else:
            return list(filter(lambda p: p.name == name, self.processes))

    def get_process_by_pid(self, pid):
        for process in self.get_processes():
            if process.pid == pid:
                return process

    def get_processes_by_ppid(self, ppid):
        return list(filter(lambda p: p.ppid == ppid, self.get_processes()))

    def get_executables(self):
        return list(filter(
            lambda e: e is not None, map(
                lambda p: p.get_executable(), self.processes)
            )
        )

    def get_all_process_environment_variables(self):
        e = {}
        for p in self.processes:
            for k, v in p.get_environment_variables().items():
                values = e.get(k, set())
                values.add(v)
                e[k] = values
        else:
            for k, v in e.items():
                e[k] = list(v)
        return e

    def get_service_sids(self):
        sids = []
        for k, v in self.session.plugins.getservicesids().get_service_sids():
            sids.append((str(k), str(v)))
        return sids

    def get_services(self):
        return list(map(lambda e: Service(e), self.session.plugins.services().GenerateServices()))

    def get_registry(self):
        return Registry(self.session)

    def get_users(self):
        return list(map(lambda e: User(*e), self.session.plugins.users().GenerateUsers()))


text:
const fs = require('fs');

const aws = require("aws-sdk");
const axios = require('axios');

// const getPictures = async (jwtToken) => {
//   const s3 = new aws.S3();
//   const url = `${process.env.DIRECTUS_HOST}/directus/gql`;
//   const payload = {
//     query: `{ at_photos { data { id, file { id, storage, filename_disk  } } } }`
//   };
//   const headers = {
//     Authorization: `bearer ${process.env.DIRECTUS_TOKEN}`
//   };

//   const { data } = await axios.post(url, payload, { headers });

//   return Promise.all(
//     data.data.at_photos.data.map(async (picture) => {
//       const filename = picture.file.filename_disk;
//       const destination = `./src/assets/pictures/${filename}`;

//       const params = {
//         Bucket: process.env.DIRECTUS_S3_BUCKET,
//         Key: `files/${filename}`,
//       }

//       const contents = await s3.getObject(params).promise();

//       await fs.promises.writeFile(destination, contents.Body);

//       return { ...picture, filename, url: require.resolve(destination) }
//     })
//   );
// }

const getContents = async () => {
  const yaml = require("yaml");
  const fp = fs.readFileSync('./content.yml', 'utf8');

  const contents = yaml.parse(fp);

  console.log({ contents });

  return contents;
}

module.exports = async function (api) {
  api.loadSource(async (actions) => {
    const contents = await getContents();

    // Use the Data Store API here: https://gridsome.org/docs/data-store-api/
    const collections = {
      pictures: actions.addCollection({ typeName: 'Pictures' }),
    };

    contents.pictures.forEach((picture) => {
      collections.pictures.addNode(picture);
    });
  });

  api.createPages(({ createPage }) => {
    // Use the Pages API here: https://gridsome.org/docs/pages-api/
  })
}


text:
from c7n_azure.provider import resources
from c7n_azure.resources.arm import ArmResourceManager
from c7n_azure.filters import FirewallRulesFilter
from netaddr import IPRange, IPSet

AZURE_SERVICES = IPRange('0.0.0.0', '0.0.0.0')  # nosec

@resources.register('postgresql-server')
class PostgresqlServer(ArmResourceManager):
    """PostgreSQL Server Resource

    :example:

    Finds all PostgreSQL Servers that have had zero active connections in the past week

    .. code-block:: yaml

        policies:
          - name: find-all-unused-postgresql-servers
            resource: azure.postgresql-server
            filters:
              - type: metric
                metric: active_connections
                op: eq
                threshold: 0
                timeframe: 168

    :example:

    Finds all PostgreSQL Servers that cost more than 1000 in the last month

    .. code-block:: yaml

        policies:
          - name: find-all-costly-postgresql-servers
            resource: azure.postgresql-server
            filters:
              - type: cost
                key: TheLastMonth
                op: gt
                value: 1000

    """

    class resource_type(ArmResourceManager.resource_type):
        doc_groups = ['Databases']

        service = 'azure.mgmt.rdbms.postgresql'
        client = 'PostgreSQLManagementClient'
        enum_spec = ('servers', 'list', None)
        resource_type = 'Microsoft.DBforPostgreSQL/servers'

@PostgresqlServer.filter_registry.register('firewall-rules')
class PostgresqlServerFirewallRulesFilter(FirewallRulesFilter):
    def _query_rules(self, resource):
        query = self.client.firewall_rules.list_by_server(
            resource['resourceGroup'],
            resource['name'])
        resource_rules = IPSet()
        for r in query:
            rule = IPRange(r.start_ip_address, r.end_ip_address)
            if rule == AZURE_SERVICES:
                # Ignore 0.0.0.0 magic value representing Azure Cloud bypass
                continue
            resource_rules.add(rule)
        return resource_rules


text:
from netforce.model import Model, fields

class Budget(Model):
    _name = "account.budget"
    _string = "Budget"
    _key = ["name"]
    _fields = {
        "name": fields.Char("Name", required=True, search=True),
        "date_from": fields.Date("From Date"),
        "date_to": fields.Date("To Date", required=True, search=True),
        "lines": fields.One2Many("account.budget.line", "budget_id", "Budget Items"),
    }
    _order = "name"

Budget.register()


text:
define([
	'dojo/_base/declare',
	'dojo/_base/lang',
	'dijit/ToolbarSeparator',
	'./Control',
], function(declare, lang, ToolbarSeparator, Control) {

	return declare('Aras.View.ToolbarSeparator', [ToolbarSeparator, Control], {

	});
});


text:
//-----------------------------------------------------------------------
// <copyright file="TwitterCursorPagedIdCollection.cs" company="Patrick 'Ricky' Smith">
//  This file is part of the Twitterizer library (http://www.twitterizer.net)
//
//  Copyright (c) 2010, Patrick "Ricky" Smith (ricky@digitally-born.com)
//  All rights reserved.
//
//  Redistribution and use in source and binary forms, with or without modification, are
//  permitted provided that the following conditions are met:
//
//  - Redistributions of source code must retain the above copyright notice, this list
//    of conditions and the following disclaimer.
//  - Redistributions in binary form must reproduce the above copyright notice, this list
//    of conditions and the following disclaimer in the documentation and/or other
//    materials provided with the distribution.
//  - Neither the name of the Twitterizer nor the names of its contributors may be
//    used to endorse or promote products derived from this software without specific
//    prior written permission.
//
//  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
//  ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
//  WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
//  IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
//  INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
//  NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
//  PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
//  WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
//  ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
//  POSSIBILITY OF SUCH DAMAGE.
// </copyright>
// <author>Ricky Smith</author>
// <summary>The twitter cursor paged id collection class.</summary>
//-----------------------------------------------------------------------

namespace Twitterizer
{
    using System.Collections.Generic;
    using System.Collections.ObjectModel;
    using Newtonsoft.Json;
    using Newtonsoft.Json.Linq;
    using Twitterizer.Core;

    /// <summary>
    /// Holds a collection of ID values that are broken into multiple pages.
    /// </summary>
    public class TwitterCursorPagedIdCollection : Collection<decimal>, ITwitterObject
    {
        /// <summary>
        /// Annotations are additional pieces of data, supplied by Twitter clients, in a non-structured dictionary.
        /// </summary>
        /// <value>The annotations.</value>
        public Dictionary<string, string> Annotations { get; set; }

        /// <summary>
        /// Gets or sets the next cursor.
        /// </summary>
        /// <value>The next cursor.</value>
        public long NextCursor { get; set; }

        /// <summary>
        /// Gets or sets the previous cursor.
        /// </summary>
        /// <value>The previous cursor.</value>
        public long PreviousCursor { get; set; }

        /// <summary>
        /// Deserializes the specified value.
        /// </summary>
        /// <param name="value">The value.</param>
        /// <returns></returns>
        internal static TwitterCursorPagedIdCollection DeserializeWrapper(JObject value)
        {
            if (value == null || value.SelectToken("users") == null)
                return null;

            TwitterCursorPagedIdCollection result = JsonConvert.DeserializeObject<TwitterCursorPagedIdCollection>(value.SelectToken("users").ToString());
            result.NextCursor = value.SelectToken("next_cursor").Value<long>();
            result.PreviousCursor = value.SelectToken("previous_cursor").Value<long>();

            return result;
        }
    }
}


text:
<?php

namespace DataSift\Storyplayer\Prose;

/**
 * Placeholder for backwards compatibility.
 *
 * @category  Libraries
 * @package   Storyplayer/Prose
 * @author    Stuart Herbert <stuart.herbert@datasift.com>
 * @copyright 2011-present Mediasift Ltd www.datasift.com
 * @license   http://www.opensource.org/licenses/bsd-license.php  BSD License
 * @link      http://datasift.github.io/storyplayer
 */
class E5xx_NotImplemented extends \Prose\E5xx_NotImplemented
{
}


text:
package com.github.lynzabo.codegen.util;

/**
 *
 * @author linzhanbo .
 * @since 2016年11月19日, 15:07 .
 * @version 1.0 .
 */

import java.sql.*;

public class DatabaseMetaDateApplication {

    private DatabaseMetaData dbMetaData = null;
    private Connection con = null;

    public DatabaseMetaDateApplication() {
        this.getDatabaseMetaData();
    }

    private void getDatabaseMetaData() {
        try {
            if (dbMetaData == null) {
                Class.forName("com.mysql.jdbc.Driver");
                String url = "jdbc:mysql://localhost:3306/creation_cms";
                String user = "root";
                String password = "root";
                con = DriverManager.getConnection(url, user, password);
                dbMetaData = con.getMetaData();
            }
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    /**
     * 获得数据库的一些相关信息
     */
    public void getDataBaseInformations() {
        try {
            System.out.println("数据库已知的用户: "+ dbMetaData.getUserName());
            System.out.println("数据库的系统函数的逗号分隔列表: "+ dbMetaData.getSystemFunctions());
            System.out.println("数据库的时间和日期函数的逗号分隔列表: "+ dbMetaData.getTimeDateFunctions());
            System.out.println("数据库的字符串函数的逗号分隔列表: "+ dbMetaData.getStringFunctions());
            System.out.println("数据库供应商用于 'schema' 的首选术语: "+ dbMetaData.getSchemaTerm());
            System.out.println("数据库URL: " + dbMetaData.getURL());
            System.out.println("是否允许只读:" + dbMetaData.isReadOnly());
            System.out.println("数据库的产品名称:" + dbMetaData.getDatabaseProductName());
            System.out.println("数据库的版本:" + dbMetaData.getDatabaseProductVersion());
            System.out.println("驱动程序的名称:" + dbMetaData.getDriverName());
            System.out.println("驱动程序的版本:" + dbMetaData.getDriverVersion());

            System.out.println();
            System.out.println("数据库中使用的表类型");
            ResultSet rs = dbMetaData.getTableTypes();
            while (rs.next()) {
                System.out.println(rs.getString(1));
            }
            rs.close();
            System.out.println();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    /**
     * 获得该用户下面的所有表
     * @param schemaName    db name
     */
    public void getAllTableList(String schemaName) {
        try {
            // table type. Typical types are "TABLE", "VIEW", "SYSTEM TABLE", "GLOBAL TEMPORARY", "LOCAL TEMPORARY", "ALIAS", "SYNONYM".
            String[] types = { "TABLE" };
            ResultSet rs = dbMetaData.getTables(null, schemaName, "%", types);
            while (rs.next()) {
                String tableName = rs.getString("TABLE_NAME"); 	//表名
                String tableType = rs.getString("TABLE_TYPE"); 	//表类型
                String remarks = rs.getString("REMARKS"); 		//表备注
                System.out.println(tableName + "-" + tableType + "-" + remarks);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    /**
     * 获得该用户下面的所有视图
     * @param schemaName    db name
     */
    public void getAllViewList(String schemaName) {
        try{
            String[] types = { "VIEW" };
            ResultSet rs = dbMetaData.getTables(null, schemaName, "%", types);
            while (rs.next()){
                String viewName = rs.getString("TABLE_NAME"); //视图名
                String viewType = rs.getString("TABLE_TYPE"); //视图类型
                String remarks = rs.getString("REMARKS");		//视图备注
                System.out.println(viewName + "-" + viewType + "-" + remarks);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    /**
     * 获得数据库中所有方案名称
     */
    public void getAllSchemas(){
        try{
            ResultSet rs = dbMetaData.getSchemas();
            while (rs.next()){
                String tableSchem = rs.getString("TABLE_SCHEM");
                System.out.println(tableSchem);
            }
        } catch (SQLException e){
            e.printStackTrace();
        }
    }

    /**
     * 获得表或视图中的所有列信息
     * @param schemaName    db name
     * @param tableName table name
     */
    public void getTableColumns(String schemaName, String tableName) {

        try{

            ResultSet rs = dbMetaData.getColumns(null, schemaName, tableName, "%");
            while (rs.next()){
                String tableCat = rs.getString("TABLE_CAT");//表目录(可能为空)
                String tableSchemaName = rs.getString("TABLE_SCHEM");//表的架构(可能为空)
                String tableName_ = rs.getString("TABLE_NAME");//表名
                String columnName = rs.getString("COLUMN_NAME");//列名
                int dataType = rs.getInt("DATA_TYPE"); //对应的java.sql.Types类型
                String dataTypeName = rs.getString("TYPE_NAME");//java.sql.Types类型   名称
                int columnSize = rs.getInt("COLUMN_SIZE");//列大小
                int decimalDigits = rs.getInt("DECIMAL_DIGITS");//小数位数
                int numPrecRadix = rs.getInt("NUM_PREC_RADIX");//基数(通常是10或2)
                int nullAble = rs.getInt("NULLABLE");//是否允许为null
                String remarks = rs.getString("REMARKS");//列描述
                String columnDef = rs.getString("COLUMN_DEF");//默认值
                int sqlDataType = rs.getInt("SQL_DATA_TYPE");//sql数据类型
                int sqlDatetimeSub = rs.getInt("SQL_DATETIME_SUB");   //SQL日期时间分?
                int charOctetLength = rs.getInt("CHAR_OCTET_LENGTH");   //char类型的列中的最大字节数
                int ordinalPosition = rs.getInt("ORDINAL_POSITION");  //表中列的索引(从1开始)

                /**
                 * ISO规则用来确定某一列的为空性。
                 * 是---如果该参数可以包括空值;
                 * 无---如果参数不能包含空值
                 * 空字符串---如果参数为空性是未知的
                 */
                String isNullAble = rs.getString("IS_NULLABLE");

                /**
                 * 指示此列是否是自动递增
                 * 是---如果该列是自动递增
                 * 无---如果不是自动递增列
                 * 空字串---如果不能确定它是否
                 * 列是自动递增的参数是未知
                 */
                String isAutoincrement = rs.getString("IS_AUTOINCREMENT");

                System.out.println(tableCat + "-" + tableSchemaName + "-" + tableName_ + "-" + columnName + "-"
                        + dataType + "-" + dataTypeName + "-" + columnSize + "-" + decimalDigits + "-" + numPrecRadix
                        + "-" + nullAble + "-" + remarks + "-" + columnDef + "-" + sqlDataType + "-" + sqlDatetimeSub
                        + charOctetLength + "-" + ordinalPosition + "-" + isNullAble + "-" + isAutoincrement + "-");
            }
        } catch (SQLException e){
            e.printStackTrace();
        }
    }

    /**
     * 获得一个表的索引信息
     * @param schemaName    db name
     * @param tableName table name
     */
    public void getIndexInfo(String schemaName, String tableName) {
        try{
            ResultSet rs = dbMetaData.getIndexInfo(null, schemaName, tableName, true, true);
            while (rs.next()){
                boolean nonUnique = rs.getBoolean("NON_UNIQUE");//非唯一索引(Can index values be non-unique. false when TYPE is  tableIndexStatistic   )
                String indexQualifier = rs.getString("INDEX_QUALIFIER");//索引目录(可能为空)
                String indexName = rs.getString("INDEX_NAME");//索引的名称
                short type = rs.getShort("TYPE");//索引类型
                short ordinalPosition = rs.getShort("ORDINAL_POSITION");//在索引列顺序号
                String columnName = rs.getString("COLUMN_NAME");//列名
                String ascOrDesc = rs.getString("ASC_OR_DESC");//列排序顺序:升序还是降序
                int cardinality = rs.getInt("CARDINALITY");   //基数
                System.out.println(nonUnique + "-" + indexQualifier + "-" + indexName + "-" + type + "-" + ordinalPosition + "-" + columnName + "-" + ascOrDesc + "-" + cardinality);
            }
        } catch (SQLException e){
            e.printStackTrace();
        }
    }

    /**
     * 获得一个表的主键信息
     * @param schemaName    db name
     * @param tableName table name
     */
    public void getAllPrimaryKeys(String schemaName, String tableName) {
        try{
            ResultSet rs = dbMetaData.getPrimaryKeys(null, schemaName, tableName);
            while (rs.next()){
                String columnName = rs.getString("COLUMN_NAME");//列名
                short keySeq = rs.getShort("KEY_SEQ");//序列号(主键内值1表示第一列的主键,值2代表主键内的第二列)
                String pkName = rs.getString("PK_NAME"); //主键名称
                System.out.println(columnName + "-" + keySeq + "-" + pkName);
            }
        }catch (SQLException e){
            e.printStackTrace();
        }
    }

    /**
     * 获得一个表的外键信息
     * @param schemaName    db name
     * @param tableName table name
     */
    public void getAllExportedKeys(String schemaName, String tableName) {

        try{
            ResultSet rs = dbMetaData.getExportedKeys(null, schemaName, tableName);
            while (rs.next()){
                String pkTableCat = rs.getString("PKTABLE_CAT");//主键表的目录(可能为空)
                String pkTableSchem = rs.getString("PKTABLE_SCHEM");//主键表的架构(可能为空)
                String pkTableName = rs.getString("PKTABLE_NAME");//主键表名
                String pkColumnName = rs.getString("PKCOLUMN_NAME");//主键列名
                String fkTableCat = rs.getString("FKTABLE_CAT");//外键的表的目录(可能为空)出口(可能为null)
                String fkTableSchem = rs.getString("FKTABLE_SCHEM");//外键表的架构(可能为空)出口(可能为空)
                String fkTableName = rs.getString("FKTABLE_NAME");//外键表名
                String fkColumnName = rs.getString("FKCOLUMN_NAME"); //外键列名
                short keySeq = rs.getShort("KEY_SEQ");//序列号(外键内值1表示第一列的外键,值2代表在第二列的外键)。

                /**
                 * hat happens to foreign key when primary is updated:
                 * importedNoAction - do not allow update of primary key if it has been imported
                 * importedKeyCascade - change imported key to agree with primary key update
                 * importedKeySetNull - change imported key to NULL if its primary key has been updated
                 * importedKeySetDefault - change imported key to default values if its primary key has been updated
                 * importedKeyRestrict - same as importedKeyNoAction (for ODBC 2.x compatibility)
                 */
                short updateRule = rs.getShort("UPDATE_RULE");

                /**
                 * What happens to the foreign key when primary is deleted.
                 * importedKeyNoAction - do not allow delete of primary key if it has been imported
                 * importedKeyCascade - delete rows that import a deleted key
                 * importedKeySetNull - change imported key to NULL if its primary key has been deleted
                 * importedKeyRestrict - same as importedKeyNoAction (for ODBC 2.x compatibility)
                 * importedKeySetDefault - change imported key to default if its primary key has been deleted
                 */
                short delRule = rs.getShort("DELETE_RULE");
                String fkName = rs.getString("FK_NAME");//外键的名称(可能为空)
                String pkName = rs.getString("PK_NAME");//主键的名称(可能为空)

                /**
                 * can the evaluation of foreign key constraints be deferred until commit
                 * importedKeyInitiallyDeferred - see SQL92 for definition
                 * importedKeyInitiallyImmediate - see SQL92 for definition
                 * importedKeyNotDeferrable - see SQL92 for definition
                 */
                short deferRability = rs.getShort("DEFERRABILITY");

                System.out.println(pkTableCat + "-" + pkTableSchem + "-" + pkTableName + "-" + pkColumnName + "-"
                        + fkTableCat + "-" + fkTableSchem + "-" + fkTableName + "-" + fkColumnName + "-" + keySeq + "-"
                        + updateRule + "-" + delRule + "-" + fkName + "-" + pkName + "-" + deferRability);
            }
        } catch (SQLException e){
            e.printStackTrace();
        }
    }

    public void colseCon() {
        try {
            if (con != null) {
                con.close();
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        DatabaseMetaDateApplication metaData = new DatabaseMetaDateApplication();
//		metaData.getDataBaseInformations();
//		metaData.getAllTableList(null);
//		metaData.getAllViewList(null);
//		metaData.getAllSchemas();
//		metaData.getTableColumns(null, "zsc_admin");
//		metaData.getIndexInfo(null, "zsc_admin");
//		metaData.getAllPrimaryKeys(null, "zsc_admin");
        metaData.getAllExportedKeys(null, "zsc_admin");

    }

}


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

<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle">
    <!-- 实心 -->
    <solid android:color="@color/firebrick" />
    <!-- 圆角 -->
    <corners android:radius="10dp" />

</shape>


text:
module Dynflow
  module LoggerAdapters
    module Formatters
      class Exception < Abstract
        def format(message)
          if ::Exception === message
            backtrace = Actor::BacktraceCollector.full_backtrace(message.backtrace)
            "#{message.message} (#{message.class})\n#{backtrace.join("\n")}"
          else
            message
          end
        end
      end
    end
  end
end


text:
package org.apache.cassandra.utils;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.Iterator;
import java.util.List;
import java.util.NavigableMap;
import java.util.NavigableSet;
import java.util.Random;
import java.util.TreeMap;
import java.util.TreeSet;
import java.util.concurrent.Callable;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadLocalRandom;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicLong;

import com.google.common.base.Function;
import com.google.common.base.Predicate;
import com.google.common.collect.Iterables;
import com.google.common.util.concurrent.Futures;
import com.google.common.util.concurrent.ListenableFuture;
import com.google.common.util.concurrent.ListenableFutureTask;
import org.junit.Assert;
import org.junit.Test;

import com.codahale.metrics.MetricRegistry;
import com.codahale.metrics.Snapshot;
import com.codahale.metrics.Timer;
import org.apache.cassandra.concurrent.NamedThreadFactory;
import org.apache.cassandra.utils.btree.BTree;
import org.apache.cassandra.utils.btree.BTreeSearchIterator;
import org.apache.cassandra.utils.btree.BTreeSet;
import org.apache.cassandra.utils.btree.UpdateFunction;

// TODO : should probably lower fan-factor for tests to make them more intensive
public class LongBTreeTest
{

    private static final MetricRegistry metrics = new MetricRegistry();
    private static final Timer BTREE_TIMER = metrics.timer(MetricRegistry.name(BTree.class, "BTREE"));
    private static final Timer TREE_TIMER = metrics.timer(MetricRegistry.name(BTree.class, "TREE"));
    private static final ExecutorService MODIFY = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors(), new NamedThreadFactory("MODIFY"));
    private static final ExecutorService COMPARE = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors(), new NamedThreadFactory("COMPARE"));
    private static final RandomAbort<Integer> SPORADIC_ABORT = new RandomAbort<>(new Random(), 0.0001f);

    static
    {
        System.setProperty("cassandra.btree.fanfactor", "4");
    }

    @Test
    public void testOversizedMiddleInsert()
    {
        TreeSet<Integer> canon = new TreeSet<>();
        for (int i = 0 ; i < 10000000 ; i++)
            canon.add(i);
        Object[] btree = BTree.build(Arrays.asList(Integer.MIN_VALUE, Integer.MAX_VALUE), ICMP, true, null);
        btree = BTree.update(btree, ICMP, canon, true);
        canon.add(Integer.MIN_VALUE);
        canon.add(Integer.MAX_VALUE);
        Assert.assertTrue(BTree.isWellFormed(btree, ICMP));
        testEqual("Oversize", BTree.<Integer>slice(btree, true), canon.iterator());
    }

    @Test
    public void testIndividualInsertsSmallOverlappingRange() throws ExecutionException, InterruptedException
    {
        testInsertions(10000000, 50, 1, 1, true);
    }

    @Test
    public void testBatchesSmallOverlappingRange() throws ExecutionException, InterruptedException
    {
        testInsertions(10000000, 50, 1, 5, true);
    }

    @Test
    public void testIndividualInsertsMediumSparseRange() throws ExecutionException, InterruptedException
    {
        testInsertions(10000000, 500, 10, 1, true);
    }

    @Test
    public void testBatchesMediumSparseRange() throws ExecutionException, InterruptedException
    {
        testInsertions(10000000, 500, 10, 10, true);
    }

    @Test
    public void testLargeBatchesLargeRange() throws ExecutionException, InterruptedException
    {
        testInsertions(100000000, 5000, 3, 100, true);
    }

    @Test
    public void testSlicingSmallRandomTrees() throws ExecutionException, InterruptedException
    {
        testInsertions(10000, 50, 10, 10, false);
    }

    @Test
    public void testSearchIterator() throws InterruptedException
    {
        int threads = Runtime.getRuntime().availableProcessors();
        final CountDownLatch latch = new CountDownLatch(threads);
        final AtomicLong errors = new AtomicLong();
        final AtomicLong count = new AtomicLong();
        final int perThreadTrees = 100;
        final int perTreeSelections = 100;
        final long totalCount = threads * perThreadTrees * perTreeSelections;
        for (int t = 0 ; t < threads ; t++)
        {
            MODIFY.execute(new Runnable()
            {
                public void run()
                {
                    ThreadLocalRandom random = ThreadLocalRandom.current();
                    for (int i = 0 ; i < perThreadTrees ; i++)
                    {
                        Object[] tree = randomTree(10000, random);
                        for (int j = 0 ; j < perTreeSelections ; j++)
                        {
                            BTreeSearchIterator<Integer, Integer, Integer> searchIterator = new BTreeSearchIterator<>(tree, ICMP);
                            for (Integer key : randomSelection(tree, random))
                                if (key != searchIterator.next(key))
                                    errors.incrementAndGet();
                            searchIterator = new BTreeSearchIterator<Integer, Integer, Integer>(tree, ICMP);
                            for (Integer key : randomMix(tree, random))
                                if (key != searchIterator.next(key))
                                    if (BTree.find(tree, ICMP, key) == key)
                                        errors.incrementAndGet();
                            count.incrementAndGet();
                        }
                    }
                    latch.countDown();
                }
            });
        }
        while (latch.getCount() > 0)
        {
            latch.await(10L, TimeUnit.SECONDS);
            System.out.println(String.format("%.0f%% complete %s", 100 * count.get() / (double) totalCount, errors.get() > 0 ? ("Errors: " + errors.get()) : ""));
            assert errors.get() == 0;
        }
    }

    private static void testInsertions(int totalCount, int perTestCount, int testKeyRatio, int modificationBatchSize, boolean quickEquality) throws ExecutionException, InterruptedException
    {
        int batchesPerTest = perTestCount / modificationBatchSize;
        int maximumRunLength = 100;
        int testKeyRange = perTestCount * testKeyRatio;
        int tests = totalCount / perTestCount;
        System.out.println(String.format("Performing %d tests of %d operations, with %.2f max size/key-range ratio in batches of ~%d ops",
                tests, perTestCount, 1 / (float) testKeyRatio, modificationBatchSize));

        // if we're not doing quick-equality, we can spam with garbage for all the checks we perform, so we'll split the work into smaller chunks
        int chunkSize = quickEquality ? tests : (int) (100000 / Math.pow(perTestCount, 2));
        for (int chunk = 0 ; chunk < tests ; chunk += chunkSize)
        {
            final List<ListenableFutureTask<List<ListenableFuture<?>>>> outer = new ArrayList<>();
            for (int i = 0 ; i < chunkSize ; i++)
            {
                outer.add(doOneTestInsertions(testKeyRange, maximumRunLength, modificationBatchSize, batchesPerTest, quickEquality));
            }

            final List<ListenableFuture<?>> inner = new ArrayList<>();
            int complete = 0;
            int reportInterval = totalCount / 100;
            int lastReportAt = 0;
            for (ListenableFutureTask<List<ListenableFuture<?>>> f : outer)
            {
                inner.addAll(f.get());
                complete += perTestCount;
                if (complete - lastReportAt >= reportInterval)
                {
                    System.out.println(String.format("Completed %d of %d operations", (chunk * perTestCount) + complete, totalCount));
                    lastReportAt = complete;
                }
            }
            Futures.allAsList(inner).get();
        }
        Snapshot snap = BTREE_TIMER.getSnapshot();
        System.out.println(String.format("btree   : %.2fns, %.2fns, %.2fns", snap.getMedian(), snap.get95thPercentile(), snap.get999thPercentile()));
        snap = TREE_TIMER.getSnapshot();
        System.out.println(String.format("snaptree: %.2fns, %.2fns, %.2fns", snap.getMedian(), snap.get95thPercentile(), snap.get999thPercentile()));
        System.out.println("Done");
    }

    private static ListenableFutureTask<List<ListenableFuture<?>>> doOneTestInsertions(final int upperBound, final int maxRunLength, final int averageModsPerIteration, final int iterations, final boolean quickEquality)
    {
        ListenableFutureTask<List<ListenableFuture<?>>> f = ListenableFutureTask.create(new Callable<List<ListenableFuture<?>>>()
        {
            @Override
            public List<ListenableFuture<?>> call()
            {
                final List<ListenableFuture<?>> r = new ArrayList<>();
                NavigableMap<Integer, Integer> canon = new TreeMap<>();
                Object[] btree = BTree.empty();
                final TreeMap<Integer, Integer> buffer = new TreeMap<>();
                final Random rnd = new Random();
                for (int i = 0 ; i < iterations ; i++)
                {
                    buffer.clear();
                    int mods = (averageModsPerIteration >> 1) + 1 + rnd.nextInt(averageModsPerIteration);
                    while (mods > 0)
                    {
                        int v = rnd.nextInt(upperBound);
                        int rc = Math.max(0, Math.min(mods, maxRunLength) - 1);
                        int c = 1 + (rc <= 0 ? 0 : rnd.nextInt(rc));
                        for (int j = 0 ; j < c ; j++)
                        {
                            buffer.put(v, v);
                            v++;
                        }
                        mods -= c;
                    }
                    Timer.Context ctxt;
                    ctxt = TREE_TIMER.time();
                    canon.putAll(buffer);
                    ctxt.stop();
                    ctxt = BTREE_TIMER.time();
                    Object[] next = null;
                    while (next == null)
                        next = BTree.update(btree, ICMP, buffer.keySet(), true, SPORADIC_ABORT);
                    btree = next;
                    ctxt.stop();

                    if (!BTree.isWellFormed(btree, ICMP))
                    {
                        System.out.println("ERROR: Not well formed");
                        throw new AssertionError("Not well formed!");
                    }
                    if (quickEquality)
                        testEqual("", BTree.<Integer>slice(btree, true), canon.keySet().iterator());
                    else
                        r.addAll(testAllSlices("RND", btree, new TreeSet<>(canon.keySet())));
                }
                return r;
            }
        });
        MODIFY.execute(f);
        return f;
    }

    @Test
    public void testSlicingAllSmallTrees() throws ExecutionException, InterruptedException
    {
        Object[] cur = BTree.empty();
        TreeSet<Integer> canon = new TreeSet<>();
        // we set FAN_FACTOR to 4, so 128 items is four levels deep, three fully populated
        for (int i = 0 ; i < 128 ; i++)
        {
            String id = String.format("[0..%d)", canon.size());
            System.out.println("Testing " + id);
            Futures.allAsList(testAllSlices(id, cur, canon)).get();
            Object[] next = null;
            while (next == null)
                next = BTree.update(cur, ICMP, Arrays.asList(i), true, SPORADIC_ABORT);
            cur = next;
            canon.add(i);
        }
    }

    static final Comparator<Integer> ICMP = new Comparator<Integer>()
    {
        @Override
        public int compare(Integer o1, Integer o2)
        {
            return Integer.compare(o1, o2);
        }
    };

    private static List<ListenableFuture<?>> testAllSlices(String id, Object[] btree, NavigableSet<Integer> canon)
    {
        List<ListenableFuture<?>> waitFor = new ArrayList<>();
        testAllSlices(id + " ASC", new BTreeSet<>(btree, ICMP), canon, true, waitFor);
        testAllSlices(id + " DSC", new BTreeSet<>(btree, ICMP).descendingSet(), canon.descendingSet(), false, waitFor);
        return waitFor;
    }

    private static void testAllSlices(String id, NavigableSet<Integer> btree, NavigableSet<Integer> canon, boolean ascending, List<ListenableFuture<?>> results)
    {
        testOneSlice(id, btree, canon, results);
        for (Integer lb : range(canon.size(), Integer.MIN_VALUE, ascending))
        {
            // test head/tail sets
            testOneSlice(String.format("%s->[%d..)", id, lb), btree.headSet(lb, true), canon.headSet(lb, true), results);
            testOneSlice(String.format("%s->(%d..)", id, lb), btree.headSet(lb, false), canon.headSet(lb, false), results);
            testOneSlice(String.format("%s->(..%d]", id, lb), btree.tailSet(lb, true), canon.tailSet(lb, true), results);
            testOneSlice(String.format("%s->(..%d]", id, lb), btree.tailSet(lb, false), canon.tailSet(lb, false), results);
            for (Integer ub : range(canon.size(), lb, ascending))
            {
                // test subsets
                testOneSlice(String.format("%s->[%d..%d]", id, lb, ub), btree.subSet(lb, true, ub, true), canon.subSet(lb, true, ub, true), results);
                testOneSlice(String.format("%s->(%d..%d]", id, lb, ub), btree.subSet(lb, false, ub, true), canon.subSet(lb, false, ub, true), results);
                testOneSlice(String.format("%s->[%d..%d)", id, lb, ub), btree.subSet(lb, true, ub, false), canon.subSet(lb, true, ub, false), results);
                testOneSlice(String.format("%s->(%d..%d)", id, lb, ub), btree.subSet(lb, false, ub, false), canon.subSet(lb, false, ub, false), results);
            }
        }
    }

    private static void testOneSlice(final String id, final NavigableSet<Integer> test, final NavigableSet<Integer> canon, List<ListenableFuture<?>> results)
    {
        ListenableFutureTask<?> f = ListenableFutureTask.create(new Runnable()
        {

            @Override
            public void run()
            {
                test(id + " Count", test.size(), canon.size());
                testEqual(id, test.iterator(), canon.iterator());
                testEqual(id + "->DSCI", test.descendingIterator(), canon.descendingIterator());
                testEqual(id + "->DSCS", test.descendingSet().iterator(), canon.descendingSet().iterator());
                testEqual(id + "->DSCS->DSCI", test.descendingSet().descendingIterator(), canon.descendingSet().descendingIterator());
            }
        }, null);
        results.add(f);
        COMPARE.execute(f);
    }

    private static void test(String id, int test, int expect)
    {
        if (test != expect)
        {
            System.out.println(String.format("%s: Expected %d, Got %d", id, expect, test));
        }
    }

    private static <V> void testEqual(String id, Iterator<V> btree, Iterator<V> canon)
    {
        boolean equal = true;
        while (btree.hasNext() && canon.hasNext())
        {
            Object i = btree.next();
            Object j = canon.next();
            if (!i.equals(j))
            {
                System.out.println(String.format("%s: Expected %d, Got %d", id, j, i));
                equal = false;
            }
        }
        while (btree.hasNext())
        {
            System.out.println(String.format("%s: Expected <Nil>, Got %d", id, btree.next()));
            equal = false;
        }
        while (canon.hasNext())
        {
            System.out.println(String.format("%s: Expected %d, Got Nil", id, canon.next()));
            equal = false;
        }
        if (!equal)
            throw new AssertionError("Not equal");
    }

    // should only be called on sets that range from 0->N or N->0
    private static final Iterable<Integer> range(final int size, final int from, final boolean ascending)
    {
        return new Iterable<Integer>()
        {
            int cur;
            int delta;
            int end;
            {
                if (ascending)
                {
                    end = size + 1;
                    cur = from == Integer.MIN_VALUE ? -1 : from;
                    delta = 1;
                }
                else
                {
                    end = -2;
                    cur = from == Integer.MIN_VALUE ? size : from;
                    delta = -1;
                }
            }
            @Override
            public Iterator<Integer> iterator()
            {
                return new Iterator<Integer>()
                {
                    @Override
                    public boolean hasNext()
                    {
                        return cur != end;
                    }

                    @Override
                    public Integer next()
                    {
                        Integer r = cur;
                        cur += delta;
                        return r;
                    }

                    @Override
                    public void remove()
                    {
                        throw new UnsupportedOperationException();
                    }
                };
            }
        };
    }

    private static Object[] randomTree(int maxSize, Random random)
    {
        TreeSet<Integer> build = new TreeSet<>();
        int size = random.nextInt(maxSize);
        for (int i = 0 ; i < size ; i++)
        {
            build.add(random.nextInt());
        }
        return BTree.build(build, ICMP, true, UpdateFunction.NoOp.<Integer>instance());
    }

    private static Iterable<Integer> randomSelection(Object[] iter, final Random rnd)
    {
        final float proportion = rnd.nextFloat();
        return Iterables.filter(new BTreeSet<>(iter, ICMP), new Predicate<Integer>()
        {
            public boolean apply(Integer integer)
            {
                return rnd.nextFloat() < proportion;
            }
        });
    }

    private static Iterable<Integer> randomMix(Object[] iter, final Random rnd)
    {
        final float proportion = rnd.nextFloat();
        return Iterables.transform(new BTreeSet<>(iter, ICMP), new Function<Integer, Integer>()
        {
            long last = Integer.MIN_VALUE;

            public Integer apply(Integer v)
            {
                long last = this.last;
                this.last = v;
                if (rnd.nextFloat() < proportion)
                    return v;
                return (int)((v - last) / 2);
            }
        });
    }

    private static final class RandomAbort<V> implements UpdateFunction<V>
    {
        final Random rnd;
        final float chance;
        private RandomAbort(Random rnd, float chance)
        {
            this.rnd = rnd;
            this.chance = chance;
        }

        public V apply(V replacing, V update)
        {
            return update;
        }

        public boolean abortEarly()
        {
            return rnd.nextFloat() < chance;
        }

        public void allocated(long heapSize)
        {

        }

        public V apply(V v)
        {
            return v;
        }
    }
}


text:
(function($, litepubl) {
  $.extend(litepubl.tml, {
    text: '
%%title%%' +
      '<input type="text" class="form-control" name="%%name%%" id="text-%%name%%" value="%%value%%" />
',

    radio: '
<input type="radio" name="%%name%%" id="radio_%%name%%_%%value%%" value="%%value%%" />%%title%%
',

    getedit: function(title, name, value) {
      return $.parsetml(litepubl.tml.text, {
        name: name,
        value: value ? value : '',
        title: title
      });
    }

  });

}(jQuery, litepubl));


text:
package com.sun.nio.file;

import java.nio.file.OpenOption;

/**
 * Defines extended open options supported on some platforms
 * by Sun's provider implementation.
 *
 * @since 1.7
 */

public enum ExtendedOpenOption implements OpenOption {
    /**
     * Prevent operations on the file that request read access.
     */
    NOSHARE_READ,
    /**
     * Prevent operations on the file that request write access.
     */
    NOSHARE_WRITE,
    /**
     * Prevent operations on the file that request delete access.
     */
    NOSHARE_DELETE;
}


text:
namespace MyoCpp {

	//class: BTPacket
	//note: Represents the packet that we'll send
	class BTPacket
	{
	public:
		//constructor: BTPacket
		BTPacket()
			: typ(0),cls(0),cmd(0)
		{
		}

		//constructor: BTPacket
		BTPacket(unsigned char typ, unsigned char cls, unsigned char cmd, std::vector<unsigned char> payload)
			: typ(typ), cls(cls), cmd(cmd), payload(payload)
		{
		}

		//destructor: ~BTPacket
		~BTPacket()
		{
		}

		unsigned char typ;
		unsigned char cls;
		unsigned char cmd;
		std::vector<unsigned char> payload;
	};

	typedef std::function<void(BTPacket)> HandlerFunc;

	template<class T>
	inline std::vector<unsigned char> pack(T in) {
		std::vector<unsigned char> ret;
		for(unsigned int i=0;i<sizeof(T);i++) {
			unsigned char c = *((unsigned char*)&in+i);
			ret.push_back(c);
		}
		return ret;
	}

	template<class T>
	inline std::vector<T> unpak(std::vector<unsigned char> in,unsigned int num, unsigned int beginPos=0)
	{
		std::vector<T> ret;
		if(sizeof(T)*num <= beginPos+in.size()) {
			for(int i = 0;i<num;i++) {
				T tmp = *reinterpret_cast<T*>(&(in[beginPos+i*sizeof(T)]));
				ret.push_back(tmp);
			}
		}
		return ret;
	}

	template<class T>
	std::vector<T> vecCat(std::vector<T> v1, std::vector<T> v2)
	{
		std::vector<T> ret = v1;
		ret.insert(ret.end(), v2.begin(), v2.end());
		return ret;
	}

	template<class T>
	void packCat(T i, std::vector<unsigned char>&v )
	{
		v = vecCat(v,pack<T>(i));
	}

	class OneCallHandler
	{
	public:
		unsigned char cls;
		unsigned char cmd;
		HandlerFunc f;
	};

	//class: BT
	//note: Does the communication with the myo-dongle
	class BT
	{
	public:
		BT()
			: isRunning(false), ioService(), port(ioService)
		{

		}
		BT(std::string portname)
			: isRunning(false), ioService(), port(ioService)
		{
			Open(portname);
		}

		void Open(std::string portname)
		{
			port.open(portname);
			port.set_option(asio::serial_port::baud_rate(9600));
			isRunning = true;
			sendThread = std::thread(&BT::SendThread, this);
			recvThread = std::thread(&BT::RecvThread, this);
		}

		~BT()
		{
			isRunning = false;
			sendThread.join();
			recvThread.join();
		}

		void SendThread()
		{
			while(isRunning) {
				if(sendMutex.try_lock()) {
					while(!toSend.empty()) {
						unsigned char c = toSend.front();
						port.write_some(asio::buffer(&c,1));
						toSend.pop();
					}

					sendMutex.unlock();
				}
			}
		}

		void RecvThread()
		{
			std::vector<char> curRecv;
			unsigned int length=0;
			while(isRunning) {
				unsigned char c;
				port.read_some(asio::buffer(&c,1));
				if(curRecv.size()==0 && (c==0x00||c==0x80||c==0x08||c==0x88)) {
					curRecv.push_back(c);
				}
				else if (curRecv.size()==1) {
					curRecv.push_back(c);
					length = 4 + (curRecv[0]&0x07) + curRecv[1];
				}
				else {
					curRecv.push_back(c);
				}
				if(length!=0 && curRecv.size()>=length) {
					std::vector<unsigned char> payload(curRecv.begin()+4, curRecv.end());
					BTPacket p(curRecv[0], curRecv[2], curRecv[3], payload);
					recvMutex.lock();
					recvPackets.push(p);
					recvMutex.unlock();
					length=0;
					curRecv.clear();
					if(p.typ==0x0 && responseHandler) {
						responseHandler(p);
						recvMutex.lock();
						responseHandler = HandlerFunc();
						recvMutex.unlock();
					}
					else if(p.typ==0x80) {
						for(auto f : eventHandlers) {
							if(f) {
								f(p);
							}
						}
						std::vector<HandlerFunc> toCall;
						for(auto i = specialEventHandlers.begin();i!=specialEventHandlers.end();i++) {
							if((*i).cmd == p.cmd && (*i).cls == p.cls) {
								if((*i).f) {
									toCall.push_back((*i).f);
								}
								//recvMutex.lock();
								i = specialEventHandlers.erase(i);

								if(i==specialEventHandlers.end()) {
									break;
								}
							}
						}
						for(auto f : toCall) {
							f(p);
						}
					}
				}

			}
		}

		void SendCommand(unsigned char cls, unsigned char cmd, std::vector<unsigned char> payload, HandlerFunc handler=HandlerFunc())
		{
			unsigned char length = static_cast<unsigned char>(payload.size());
			std::vector<unsigned char> d;
			d.push_back(0);
			d.push_back(length);
			d.push_back(cls);
			d.push_back(cmd);
			d.insert(d.end(),payload.begin(), payload.end());
			if(handler) {
				SetResponseHandler(handler);
			}
			SendData(d);
		}

		void SendData(std::vector<unsigned char> data)
		{
			sendMutex.lock();
			for(auto c : data) {
				toSend.push(c);
			}
			sendMutex.unlock();
		}

		bool PopPacket(BTPacket&p)
		{
			if(!recvPackets.empty()) {
				recvMutex.lock();
				p = recvPackets.front();
				recvPackets.pop();
				recvMutex.unlock();
				return true;
			}
			return false;
		}
		void SetResponseHandler(HandlerFunc f)
		{
			recvMutex.lock();
			responseHandler = f;
			recvMutex.unlock();
		}

		void AddEventHandler(HandlerFunc f)
		{
			eventHandlers.push_back(f);
		}

		void AddSpecialEventHandler(unsigned char cls, unsigned char cmd, HandlerFunc f)
		{
			OneCallHandler h;
			h.cmd = cmd;
			h.cls = cls;
			h.f = f;
			specialEventHandlers.push_back(h);
		}

		void Connect(std::vector<unsigned char> addr, HandlerFunc f=HandlerFunc())
		{
			std::vector<unsigned char> payload = addr;
			//std::cout << "ass: " << addr.size() << std::endl;
			payload.push_back(0);
			packCat<unsigned short>(6,payload);
			packCat<unsigned short>(6,payload);
			packCat<unsigned short>(64,payload);
			packCat<unsigned short>(0,payload);
			SendCommand(6,3,payload,f);
		}

		void GetConnections(HandlerFunc f)
		{
			SendCommand(0,6,std::vector<unsigned char>(),f);
		}

		void Discover(HandlerFunc f=HandlerFunc())
		{
			std::vector<unsigned char> payload;
			payload.push_back(1);
			SendCommand(6,2,payload,f);
		}

		void EndScan(HandlerFunc f=HandlerFunc())
		{
			SendCommand(6,4, std::vector<unsigned char>(),f);
		}

		void Disconnect(unsigned char connectionId, HandlerFunc f=HandlerFunc())
		{
			std::vector<unsigned char> payload;
			payload.push_back(connectionId);
			SendCommand(0,3,payload,f);
		}

		void ReadAttrib(unsigned char conn, short attrib, HandlerFunc f)
		{
			std::vector<unsigned char> payload;
			payload.push_back(conn);
			packCat<unsigned short>(attrib,payload);
			AddSpecialEventHandler(4,5,f);
			SendCommand(4,4,payload,HandlerFunc());

		}

		void WriteAttrib(unsigned char conn, short attrib, std::vector<unsigned char> val,HandlerFunc f=HandlerFunc())
		{
			std::vector<unsigned char> payload;
			payload.push_back(conn);
			packCat<unsigned short>(attrib, payload);
			payload.push_back(static_cast<unsigned char>(val.size()));
			payload = vecCat(payload,val);
			AddSpecialEventHandler(4,1,f);
			SendCommand(4,5,payload,HandlerFunc());
		}

	private:
		bool isRunning;

		asio::io_service	ioService;
		asio::serial_port	port;

		std::queue<unsigned char>		toSend;
		std::queue<BTPacket>			recvPackets;

		std::thread				sendThread;
		std::recursive_mutex 	sendMutex;
		std::thread				recvThread;
		std::recursive_mutex	recvMutex;

		std::vector<HandlerFunc>	eventHandlers;
		HandlerFunc					responseHandler;
		std::vector<OneCallHandler> specialEventHandlers;
	};

	typedef std::function<void(std::vector<unsigned short>)> EmgEventFunc;
	typedef std::function<void(std::vector<short>)> ImuEventFunc;
	//class: MyoRaw
	//note: Does the actual communication with the myo
	class MyoRaw
	{
	public:
		MyoRaw()
			: connId(0), bt(), oldProtocol(false)
		{

		}
		MyoRaw(std::string port)
			: connId(0), bt(), oldProtocol(false)
		{
			Connect(port);
		}

		void Connect(std::string port)
		{
				bt.Open(port);
				std::cout << "Scanning for a myo... " << std::endl;
				bt.Disconnect(0);
				bt.Disconnect(1);
				bt.Disconnect(2);
				bt.Discover();
				MyoCpp::BTPacket p;
				std::string addrString;
				while(true) {
					if(bt.PopPacket(p)) {
						std::string pstring(p.payload.begin(), p.payload.end());
						if(pstring.find("\x06\x42\x48\x12\x4A\x7F\x2C\x48\x47\xB9\xDE\x04\xA9\x01\x00\x06\xD5") != pstring.npos) {
							addrString = pstring.substr(2,6);

							break;
						}
					}
				}
			char c;
			bt.EndScan();
			std::vector<unsigned char> addr(addrString.begin(), addrString.end());
			std::cout << "Connecting..." << std::endl;
			bt.AddSpecialEventHandler(3,0,[this](BTPacket p) {this->_StatusOk(p);});
			bt.Connect(addr, [this](BTPacket p) {this->_ConnectionResponse(p);});
		}

		void AddEmgHandler(EmgEventFunc f)
		{
			emgHandlers.push_back(f);
		}

		void AddImuHandler(ImuEventFunc f)
		{
			imuHandlers.push_back(f);
		}
	private:
		unsigned char 	connId = 0;
		BT 				bt;
		bool			oldProtocol;
		std::vector<EmgEventFunc> emgHandlers;
		std::vector<ImuEventFunc> imuHandlers;

	protected:
		void _ConnectionResponse(BTPacket p)
		{
			connId = p.payload[p.payload.size()-1];
			std::cout << "Connected with id: " << static_cast<int>(connId) << std::endl;
		}
		void _StatusOk(BTPacket p)
		{
			std::cout << "Getting Firmware version..." << std::endl;
			bt.ReadAttrib(connId,0x17,[this](BTPacket p) { this->_FirmwareResponse(p);});
		}

		void _FirmwareResponse(BTPacket p)
		{
			std::cout << "Firmware version: ";
			std::vector<unsigned short> v = unpak<unsigned short>(p.payload,4,5);
			if(v.size()==4) {
				std::cout << v[0] << "." << v[1] << "." << v[2] << "." << v[3] << std::endl;
			} else {
				std::cout << "Error!" << std::endl;
			}
			if(v[0]<1) {
				oldProtocol = true;
			}
			//currently only supporting the old protocol
			if(oldProtocol) {
				std::vector<unsigned char> data;
				//these do unknon stuff says my source
				std::cout << "sending magic..." << std::endl;
				data.push_back(1);data.push_back(2);data.push_back(0);data.push_back(0);
				bt.WriteAttrib(connId,0x19, data, [this](BTPacket p) {
					std::vector<unsigned char>data;
					data.push_back(1);
					data.push_back(0);
					bt.WriteAttrib(connId,0x2f,data, [this,data](BTPacket p) {
						bt.WriteAttrib(connId,0x2c,data, [this,data](BTPacket p) {
							bt.WriteAttrib(connId,0x32,data, [this,data](BTPacket p) {
								bt.WriteAttrib(connId,0x35,data, [this,data](BTPacket p) {
									bt.WriteAttrib(connId,0x28,data,[this](BTPacket p) {this->_EMG_Ok(p);});
								});
							});
						});
					});
				});
				//enables emg and imu

			}
		}
		void _EMG_Ok (BTPacket p) {
				std::cout << "donte. engabling emg and imu..:" << std::endl;
				std::vector<unsigned char> data;
				data.push_back(1);
				data.push_back(0);
				bt.WriteAttrib(connId,0x1d,data,[this](BTPacket p) {this->_IMU_Ok(p);});
		}
		void _IMU_Ok (BTPacket p) {
				std::vector<unsigned char> data;
				data.push_back(2);
				data.push_back(9);
				data.push_back(2);
				data.push_back(1);
				packCat<unsigned short>(1000,data);	//sampling rate
				data.push_back(100); //low pass
				data.push_back(1000 / 50);
				data.push_back(50); //sampling rate imu
				data.push_back(0);data.push_back(0);
				bt.WriteAttrib(connId,0x19,data);
				bt.AddEventHandler([this](BTPacket p) { this->HandleEvent(p);});
				std::cout << "Init Done!" << std::endl;
		}

		void HandleEvent(BTPacket p) {
			if(p.cls!=4 || p.cmd!=5) {
				return;
			}

			unsigned short attrib = 0;
			auto a = unpak<unsigned short>(p.payload,1,1);
			std::vector<unsigned short> emgVals;
			std::vector<short> imuVals;
			if(a.size()!=1) {
				return;
			}
			attrib = a[0];
			switch(attrib) {
			case 0x27:
				emgVals = unpak<unsigned short>(p.payload,8,5);
				if(emgVals.size()==8) {
					for(auto f : emgHandlers) {
						f(emgVals);
					}
				}
			break;

			case 0x1c:
				imuVals = unpak<short>(p.payload,10,5);
				if(imuVals.size()==10) {
					for(auto f : imuHandlers) {
						f(imuVals);
					}
				}
				break;
			}
		}
	};
};


text:
void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]);

// Command Interface
void CommandNew(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]);
void CommandDelete(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]);
void CommandInitialize(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]);
void CommandSetSamples(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]);
void CommandICP_InitializeParameters(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]);
void CommandICP_ComputeMatches(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]);
void CommandICP_RegisterMatches(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]);
void CommandICP_EvaluateErrorFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]);
void CommandICP_Terminate(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]);
//void CommandTest(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]);
//void CommandTest2(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]);

class mexInterface_AlgICP_StdICP_Mesh
{

  //--- Parameters ---//

public:

  algICP_StdICP_Mesh *pAlg;

  //--- Methods ---//

public:

  // constructor
	mexInterface_AlgICP_StdICP_Mesh()
    : pAlg(NULL)
  {}

	~mexInterface_AlgICP_StdICP_Mesh()
  {
    if (pAlg)
    {
      delete pAlg;
      pAlg = NULL;
    }
  }

};

#endif


text:
<?php

$hostname='localhost';
$username='root';
$password='';
$batabase='eventos_coordinados';

$conexion= new mysqli($hostname, $username, $password, $batabase);

$usuarios="SELECT * FROM users";
$resUsers=$conexion->query($usuarios);

?>