text:
package org.apache.hadoop.cli.util;

import java.util.ArrayList;

/**
 *
 * Class to store CLI Test Data
 */
public class CLITestData {
  private String testDesc = null;
  private ArrayList<CLICommand> testCommands = null;
  private ArrayList<CLICommand> cleanupCommands = null;
  private ArrayList<ComparatorData> comparatorData = null;
  private boolean testResult = false;

  public CLITestData() {

  }

  /**
   * @return the testDesc
   */
  public String getTestDesc() {
    return testDesc;
  }

  /**
   * @param testDesc the testDesc to set
   */
  public void setTestDesc(String testDesc) {
    this.testDesc = testDesc;
  }

  /**
   * @return the testCommands
   */
  public ArrayList<CLICommand> getTestCommands() {
    return testCommands;
  }

  /**
   * @param testCommands the testCommands to set
   */
  public void setTestCommands(ArrayList<CLICommand> testCommands) {
    this.testCommands = testCommands;
  }

  /**
   * @return the comparatorData
   */
  public ArrayList<ComparatorData> getComparatorData() {
    return comparatorData;
  }

  /**
   * @param comparatorData the comparatorData to set
   */
  public void setComparatorData(ArrayList<ComparatorData> comparatorData) {
    this.comparatorData = comparatorData;
  }

  /**
   * @return the testResult
   */
  public boolean getTestResult() {
    return testResult;
  }

  /**
   * @param testResult the testResult to set
   */
  public void setTestResult(boolean testResult) {
    this.testResult = testResult;
  }

  /**
   * @return the cleanupCommands
   */
  public ArrayList<CLICommand> getCleanupCommands() {
    return cleanupCommands;
  }

  /**
   * @param cleanupCommands the cleanupCommands to set
   */
  public void setCleanupCommands(ArrayList<CLICommand> cleanupCommands) {
    this.cleanupCommands = cleanupCommands;
  }
}


text:
        Name
        Description
        Color
        Icon
        Is Selectable
        Created At
        Updated At
        Action

    <?php foreach($activities as $activity): ?>

            <?php echo $activity->name; ?>
            <?php echo $activity->description; ?>
            <?php echo $activity->color; ?>
            <?php echo $activity->icon; ?>
            <?php echo $activity->is_selectable; ?>
            <?php echo $activity->created_at; ?>
            <?php echo $activity->updated_at; ?>

                <?php echo Form::open(['route' => ['activities.destroy', $activity->id], 'method' => 'delete']); ?>

                    <a href="<?php echo route('activities.show', [$activity->id]); ?>" class='btn btn-default btn-xs'>
                    <a href="<?php echo route('activities.edit', [$activity->id]); ?>" class='btn btn-default btn-xs'>
                    <?php echo Form::button('', ['type' => 'submit', 'class' => 'btn btn-danger btn-xs', 'onclick' => "return confirm('Are you sure?')"]); ?>

                <?php echo Form::close(); ?>

    <?php endforeach; ?>

redpajama_set_name: RedPajamaGithub


text:
using OpenQA.Selenium;
using OpenQA.Selenium.Firefox;
using NUnit.Framework;
using Orasi.Toolkit.Utils;

namespace Orasi.Toolkit.Test.Utils
{
    [TestFixture, Category("Unit")]
    public class FrameHandlerTest
    {
        FirefoxDriver _driver;

        [TestFixtureSetUp]
        public void Startup()
        {
            _driver = new FirefoxDriver();
            _driver.Navigate().GoToUrl("http://orasi.github.io/Selenium-Java-Core/sites/unitTests/orasi/utils/frameHandler.html");
        }

        [Test, Category("Unit")]
        public void _01_MoveToChildFrame()
        {
            FrameHandler.MoveToChildFrame(_driver, By.Name("menu_page"));
            Assert.True(_driver.FindElement(By.Id("googleLink")).Displayed, "Link was not found in 'menu_page'");
        }

        [Test, Category("Unit")]
        public void _02_GetCurrentFrameName()
        {
            Assert.True(FrameHandler.GetCurrentFrameName(_driver).Equals("menu_page"), "Frame name was not 'menu_page' ");
        }

        [Test, Category("Unit")]
        public void _03_GetDefaultContext()
        {
            FrameHandler.MoveToDefaultContext(_driver);
            Assert.Null(FrameHandler.GetCurrentFrameName(_driver), "Failed to move to default Content ");
        }

        [Test, Category("Unit")]
        public void _04_MoveToChildFrameArray()
        {
            By locatorParentFrame = By.Name("main_page");
            By locatorChildFrame = By.Name("main_frame1");
            FrameHandler.MoveToChildFrame(_driver, new By[] { locatorParentFrame, locatorChildFrame });
            Assert.True(FrameHandler.GetCurrentFrameName(_driver).Equals("main_frame1"), "Failed to move to 'main_frame1'  ");
        }

        [Test, Category("Unit")]
        public void _05_MoveToParentFrame()
        {
            FrameHandler.MoveToParentFrame(_driver);
            Assert.True(FrameHandler.GetCurrentFrameName(_driver).Equals("main_page"), "Frame name was not 'main_page' ");
        }

        [Test, Category("Unit")]
        public void _06_MoveToSiblingFrame()
        {
            FrameHandler.MoveToChildFrame(_driver, By.Name("main_frame1"));
            FrameHandler.MoveToSiblingFrame(_driver,By.Name("main_frame2"));
            Assert.True(FrameHandler.GetCurrentFrameName(_driver).Equals("main_frame2"), "Frame name was not 'main_frame2' ");
        }

        [TestFixtureTearDown]
        public void TearDown()
        {
            _driver.Quit();
        }
    }
}


text:
require 'rubygems'
require 'sprout'
sprout 'as3'

asunit_home = ENV['ASUNIT_HOME'] || File.dirname(__FILE__) + '/../AsUnit-bacc/asunit-4.0'

def apply_as3_meta_data_args(t)
  [
    "After",
    "AfterClass",
    "Before",
    "BeforeClass",
    "Ignore",
    "Inject",
    "RunWith",
    "Suite",
    "Test"
  ].each do |arg|
    t.keep_as3_metadata << arg
  end
end

mxmlc "bin/AS3SignalsRunner.swf" do |t|
  t.default_size = '1000 500'
  t.input = 'tests/org/osflash/signals/AllTestsRunner.as'
  #t.allow_source_path_overlap = true
  t.source_path << 'src'
  t.source_path << 'tests'
  t.library_path << 'libs/asunit4-alpha.swc'
  t.gem_version = '3.3.1'
end

mxmlc "bin/AS3SignalsAsUnitRunner.swf" do |t|
  t.default_size = '1000 500'
  t.input = 'tests/org/osflash/signals/AllTestsRunner.as'
  t.source_path << 'src'
  t.library_path << "#{asunit_home}/lib/Reflection.swc"
  t.source_path << "#{asunit_home}/src"
  t.gem_version = '3.3.1'
  apply_as3_meta_data_args(t)
end

desc "Run the Test Harness"
flashplayer :test => 'bin/AS3SignalsRunner.swf'

desc "Run the Test Harness against AsUnit source"
flashplayer :test_asunit => 'bin/AS3SignalsAsUnitRunner.swf'


text:
// +build linux freebsd

package zfs

import (
	"fmt"
	"os"
	"os/exec"
	"path"
	"strconv"
	"strings"
	"sync"
	"syscall"
	"time"

	"github.com/Sirupsen/logrus"
	"github.com/docker/docker/daemon/graphdriver"
	"github.com/docker/docker/pkg/mount"
	"github.com/docker/docker/pkg/parsers"
	zfs "github.com/mistifyio/go-zfs"
	"github.com/opencontainers/runc/libcontainer/label"
)

type zfsOptions struct {
	fsName    string
	mountPath string
}

func init() {
	graphdriver.Register("zfs", Init)
}

// Logger returns a zfs logger implmentation.
type Logger struct{}

// Log wraps log message from ZFS driver with a prefix '[zfs]'.
func (*Logger) Log(cmd []string) {
	logrus.Debugf("[zfs] %s", strings.Join(cmd, " "))
}

// Init returns a new ZFS driver.
// It takes base mount path and a array of options which are represented as key value pairs.
// Each option is in the for key=value. 'zfs.fsname' is expected to be a valid key in the options.
func Init(base string, opt []string) (graphdriver.Driver, error) {
	var err error

	if _, err := exec.LookPath("zfs"); err != nil {
		logrus.Debugf("[zfs] zfs command is not available: %v", err)
		return nil, graphdriver.ErrPrerequisites
	}

	file, err := os.OpenFile("/dev/zfs", os.O_RDWR, 600)
	if err != nil {
		logrus.Debugf("[zfs] cannot open /dev/zfs: %v", err)
		return nil, graphdriver.ErrPrerequisites
	}
	defer file.Close()

	options, err := parseOptions(opt)
	if err != nil {
		return nil, err
	}
	options.mountPath = base

	rootdir := path.Dir(base)

	if options.fsName == "" {
		err = checkRootdirFs(rootdir)
		if err != nil {
			return nil, err
		}
	}

	if options.fsName == "" {
		options.fsName, err = lookupZfsDataset(rootdir)
		if err != nil {
			return nil, err
		}
	}

	zfs.SetLogger(new(Logger))

	filesystems, err := zfs.Filesystems(options.fsName)
	if err != nil {
		return nil, fmt.Errorf("Cannot find root filesystem %s: %v", options.fsName, err)
	}

	filesystemsCache := make(map[string]bool, len(filesystems))
	var rootDataset *zfs.Dataset
	for _, fs := range filesystems {
		if fs.Name == options.fsName {
			rootDataset = fs
		}
		filesystemsCache[fs.Name] = true
	}

	if rootDataset == nil {
		return nil, fmt.Errorf("BUG: zfs get all -t filesystem -rHp '%s' should contain '%s'", options.fsName, options.fsName)
	}

	d := &Driver{
		dataset:          rootDataset,
		options:          options,
		filesystemsCache: filesystemsCache,
	}
	return graphdriver.NewNaiveDiffDriver(d), nil
}

func parseOptions(opt []string) (zfsOptions, error) {
	var options zfsOptions
	options.fsName = ""
	for _, option := range opt {
		key, val, err := parsers.ParseKeyValueOpt(option)
		if err != nil {
			return options, err
		}
		key = strings.ToLower(key)
		switch key {
		case "zfs.fsname":
			options.fsName = val
		default:
			return options, fmt.Errorf("Unknown option %s", key)
		}
	}
	return options, nil
}

func lookupZfsDataset(rootdir string) (string, error) {
	var stat syscall.Stat_t
	if err := syscall.Stat(rootdir, &stat); err != nil {
		return "", fmt.Errorf("Failed to access '%s': %s", rootdir, err)
	}
	wantedDev := stat.Dev

	mounts, err := mount.GetMounts()
	if err != nil {
		return "", err
	}
	for _, m := range mounts {
		if err := syscall.Stat(m.Mountpoint, &stat); err != nil {
			logrus.Debugf("[zfs] failed to stat '%s' while scanning for zfs mount: %v", m.Mountpoint, err)
			continue // may fail on fuse file systems
		}

		if stat.Dev == wantedDev && m.Fstype == "zfs" {
			return m.Source, nil
		}
	}

	return "", fmt.Errorf("Failed to find zfs dataset mounted on '%s' in /proc/mounts", rootdir)
}

// Driver holds information about the driver, such as zfs dataset, options and cache.
type Driver struct {
	dataset          *zfs.Dataset
	options          zfsOptions
	sync.Mutex       // protects filesystem cache against concurrent access
	filesystemsCache map[string]bool
}

func (d *Driver) String() string {
	return "zfs"
}

// Cleanup is used to implement graphdriver.ProtoDriver. There is no cleanup required for this driver.
func (d *Driver) Cleanup() error {
	return nil
}

// Status returns information about the ZFS filesystem. It returns a two dimensional array of information
// such as pool name, dataset name, disk usage, parent quota and compression used.
// Currently it return 'Zpool', 'Zpool Health', 'Parent Dataset', 'Space Used By Parent',
// 'Space Available', 'Parent Quota' and 'Compression'.
func (d *Driver) Status() [][2]string {
	parts := strings.Split(d.dataset.Name, "/")
	pool, err := zfs.GetZpool(parts[0])

	var poolName, poolHealth string
	if err == nil {
		poolName = pool.Name
		poolHealth = pool.Health
	} else {
		poolName = fmt.Sprintf("error while getting pool information %v", err)
		poolHealth = "not available"
	}

	quota := "no"
	if d.dataset.Quota != 0 {
		quota = strconv.FormatUint(d.dataset.Quota, 10)
	}

	return [][2]string{
		{"Zpool", poolName},
		{"Zpool Health", poolHealth},
		{"Parent Dataset", d.dataset.Name},
		{"Space Used By Parent", strconv.FormatUint(d.dataset.Used, 10)},
		{"Space Available", strconv.FormatUint(d.dataset.Avail, 10)},
		{"Parent Quota", quota},
		{"Compression", d.dataset.Compression},
	}
}

// GetMetadata returns image/container metadata related to graph driver
func (d *Driver) GetMetadata(id string) (map[string]string, error) {
	return nil, nil
}

func (d *Driver) cloneFilesystem(name, parentName string) error {
	snapshotName := fmt.Sprintf("%d", time.Now().Nanosecond())
	parentDataset := zfs.Dataset{Name: parentName}
	snapshot, err := parentDataset.Snapshot(snapshotName /*recursive */, false)
	if err != nil {
		return err
	}

	_, err = snapshot.Clone(name, map[string]string{"mountpoint": "legacy"})
	if err == nil {
		d.Lock()
		d.filesystemsCache[name] = true
		d.Unlock()
	}

	if err != nil {
		snapshot.Destroy(zfs.DestroyDeferDeletion)
		return err
	}
	return snapshot.Destroy(zfs.DestroyDeferDeletion)
}

func (d *Driver) zfsPath(id string) string {
	return d.options.fsName + "/" + id
}

func (d *Driver) mountPath(id string) string {
	return path.Join(d.options.mountPath, "graph", getMountpoint(id))
}

// Create prepares the dataset and filesystem for the ZFS driver for the given id under the parent.
func (d *Driver) Create(id string, parent string) error {
	err := d.create(id, parent)
	if err == nil {
		return nil
	}
	if zfsError, ok := err.(*zfs.Error); ok {
		if !strings.HasSuffix(zfsError.Stderr, "dataset already exists\n") {
			return err
		}
		// aborted build -> cleanup
	} else {
		return err
	}

	dataset := zfs.Dataset{Name: d.zfsPath(id)}
	if err := dataset.Destroy(zfs.DestroyRecursiveClones); err != nil {
		return err
	}

	// retry
	return d.create(id, parent)
}

func (d *Driver) create(id, parent string) error {
	name := d.zfsPath(id)
	if parent == "" {
		mountoptions := map[string]string{"mountpoint": "legacy"}
		fs, err := zfs.CreateFilesystem(name, mountoptions)
		if err == nil {
			d.Lock()
			d.filesystemsCache[fs.Name] = true
			d.Unlock()
		}
		return err
	}
	return d.cloneFilesystem(name, d.zfsPath(parent))
}

// Remove deletes the dataset, filesystem and the cache for the given id.
func (d *Driver) Remove(id string) error {
	name := d.zfsPath(id)
	dataset := zfs.Dataset{Name: name}
	err := dataset.Destroy(zfs.DestroyRecursive)
	if err == nil {
		d.Lock()
		delete(d.filesystemsCache, name)
		d.Unlock()
	}
	return err
}

// Get returns the mountpoint for the given id after creating the target directories if necessary.
func (d *Driver) Get(id, mountLabel string) (string, error) {
	mountpoint := d.mountPath(id)
	filesystem := d.zfsPath(id)
	options := label.FormatMountLabel("", mountLabel)
	logrus.Debugf(`[zfs] mount("%s", "%s", "%s")`, filesystem, mountpoint, options)

	// Create the target directories if they don't exist
	if err := os.MkdirAll(mountpoint, 0755); err != nil {
		return "", err
	}

	err := mount.Mount(filesystem, mountpoint, "zfs", options)
	if err != nil {
		return "", fmt.Errorf("error creating zfs mount of %s to %s: %v", filesystem, mountpoint, err)
	}

	return mountpoint, nil
}

// Put removes the existing mountpoint for the given id if it exists.
func (d *Driver) Put(id string) error {
	mountpoint := d.mountPath(id)
	logrus.Debugf(`[zfs] unmount("%s")`, mountpoint)

	if err := mount.Unmount(mountpoint); err != nil {
		return fmt.Errorf("error unmounting to %s: %v", mountpoint, err)
	}
	return nil
}

// Exists checks to see if the cache entry exists for the given id.
func (d *Driver) Exists(id string) bool {
	return d.filesystemsCache[d.zfsPath(id)] == true
}


text:
#ifndef NFI_STATE_MACHINE_H
#define NFI_STATE_MACHINE_H

#include "NFIState.h"

class NFIStateMachine
	: public NFIModule
{
public:

    virtual const NFAI_STATE  CurrentState() const = 0;
	virtual const NFAI_STATE  LastState() const = 0;

	virtual NFIState* GetState(const NFAI_STATE eState) const = 0;

    //change to a new state
    virtual void ChangeState(const NFAI_STATE eState) = 0;

    //return last state
    virtual void RevertToLastState() = 0;

protected:

private:
};

#endif


text:
<title>ClearBillboards</title>

ClearBillboards()

Syntax

ClearBillboards(#BillboardGroup)

Description

Removes and destroys all billboards in the specified billboard group.

Parameters

#BillboardGroup

The billboard group to clear.

Return value

None.

Supported OS
All

<- BillboardZ() - Billboard Index - CountBillboards() ->


text:
import {Entity} from "../../../../../src/decorator/entity/Entity";
import {PrimaryGeneratedColumn} from "../../../../../src/decorator/columns/PrimaryGeneratedColumn";
import {ManyToOne} from "../../../../../src/decorator/relations/ManyToOne";
import {Post} from "./Post";
import {Column} from "../../../../../src/decorator/columns/Column";

@Entity()
export class Category {

    @PrimaryGeneratedColumn()
    id: number;

    @ManyToOne(type => Post, post => post.categories)
    post: Post;

    @Column()
    name: string;

}


text:
from __future__ import unicode_literals

def refine_get_multilang_urls(original):
    def get_multilang_urls():
        from django.conf.urls import url
        from .views import ChangeLangView

        urlpatterns = [
            url(r'^activate_language', ChangeLangView.as_view(), name='activate_language')
        ]
        return urlpatterns + original()

    return get_multilang_urls


text:
using System;
using NUnit.Framework;
using FluentMigrator.Runner.Generators.Oracle;
using NUnit.Should;

namespace FluentMigrator.Tests.Unit.Generators.Oracle
{
    public class OracleDataTests : BaseDataTests
    {
        private OracleGenerator generator;
	    private OracleGenerator quotedIdentiferGenerator;

	    [SetUp]
        public void Setup()
        {
            generator = new OracleGenerator();
			quotedIdentiferGenerator = new OracleGenerator(true);

        }
        [Test]
        public override void CanInsertData()
        {
            var expression = GeneratorTestHelper.GetInsertDataExpression();
            string sql = quotedIdentiferGenerator.Generate(expression);

            string expected = "INSERT ALL INTO \"TestTable1\" (\"Id\", \"Name\", \"Website\") VALUES (1, 'Just''in', 'codethinked.com')";
            expected += " INTO \"TestTable1\" (\"Id\", \"Name\", \"Website\") VALUES (2, 'Na\\te', 'kohari.org')";
            expected += " SELECT 1 FROM DUAL";

            sql.ShouldBe(expected);

			sql = generator.Generate(expression);
			sql.ShouldBe(expected.Replace("\"",""));
        }

        [Test]
        public override void CanDeleteData()
        {
            var expression = GeneratorTestHelper.GetDeleteDataExpression();

            var sql = generator.Generate(expression);
            sql.ShouldBe("DELETE FROM TestTable1 WHERE Name = 'Just''in' AND Website IS NULL");

			sql = quotedIdentiferGenerator.Generate(expression);
			sql.ShouldBe("DELETE FROM \"TestTable1\" WHERE \"Name\" = 'Just''in' AND \"Website\" IS NULL");
        }

        [Test]
        public override void CanDeleteDataAllRows()
        {
            var expression = GeneratorTestHelper.GetDeleteDataAllRowsExpression();

            var sql = generator.Generate(expression);
            sql.ShouldBe("DELETE FROM TestTable1 WHERE 1 = 1");

			sql = quotedIdentiferGenerator.Generate(expression);
			sql.ShouldBe("DELETE FROM \"TestTable1\" WHERE 1 = 1");
        }

        [Test]
        public override void CanDeleteDataMultipleRows()
        {
            var expression = GeneratorTestHelper.GetDeleteDataMultipleRowsExpression();

            var sql = generator.Generate(expression);
            sql.ShouldBe("DELETE FROM TestTable1 WHERE Name = 'Just''in' AND Website IS NULL; DELETE FROM TestTable1 WHERE Website = 'github.com'");

			sql = quotedIdentiferGenerator.Generate(expression);
			sql.ShouldBe("DELETE FROM \"TestTable1\" WHERE \"Name\" = 'Just''in' AND \"Website\" IS NULL; DELETE FROM \"TestTable1\" WHERE \"Website\" = 'github.com'");
        }

        [Test]
        public override void CanInsertGuidData()
        {
            //Oracle can not insert GUID data using string representation
            var expression = GeneratorTestHelper.GetInsertGUIDExpression();

            string sql = generator.Generate(expression);
            sql.ShouldBe(String.Format("INSERT ALL INTO TestTable1 (guid) VALUES ('{0}') SELECT 1 FROM DUAL", GeneratorTestHelper.TestGuid.ToString()));

			sql = quotedIdentiferGenerator.Generate(expression);
			sql.ShouldBe(String.Format("INSERT ALL INTO \"TestTable1\" (\"guid\") VALUES ('{0}') SELECT 1 FROM DUAL", GeneratorTestHelper.TestGuid.ToString()));
        }

        [Test]
        public override void CanUpdateData()
        {
            var expression = GeneratorTestHelper.GetUpdateDataExpression();

            var sql = generator.Generate(expression);
            sql.ShouldBe("UPDATE TestTable1 SET Name = 'Just''in', Age = 25 WHERE Id = 9 AND Homepage IS NULL");

			sql = quotedIdentiferGenerator.Generate(expression);
			sql.ShouldBe("UPDATE \"TestTable1\" SET \"Name\" = 'Just''in', \"Age\" = 25 WHERE \"Id\" = 9 AND \"Homepage\" IS NULL");
        }

        [Test]
        public void CanUpdateDataForAllRows()
        {
            var expression = GeneratorTestHelper.GetUpdateDataExpressionWithAllRows();

            var sql = generator.Generate(expression);
            sql.ShouldBe("UPDATE TestTable1 SET Name = 'Just''in', Age = 25 WHERE 1 = 1");

			sql = quotedIdentiferGenerator.Generate(expression);
			sql.ShouldBe("UPDATE \"TestTable1\" SET \"Name\" = 'Just''in', \"Age\" = 25 WHERE 1 = 1");
        }
    }
}


text:
#include <assert.h>
#include <string.h>
#include <stdint.h>

#include "py/nlr.h"
#include "py/runtime.h"
#include "py/objtuple.h"
#include "py/binary.h"

#if MICROPY_PY_UCTYPES

/// \module uctypes - Access data structures in memory
///
/// The module allows to define layout of raw data structure (using terms
/// of C language), and then access memory buffers using this definition.
/// The module also provides convenience functions to access memory buffers
/// contained in Python objects or wrap memory buffers in Python objects.
/// \constant UINT8_1 - uint8_t value type

/// \class struct - C-like structure
///
/// Encapsulalation of in-memory data structure. This class doesn't define
/// any methods, only attribute access (for structure fields) and
/// indexing (for pointer and array fields).
///
/// Usage:
///
///     # Define layout of a structure with 2 fields
///     # 0 and 4 are byte offsets of fields from the beginning of struct
///     # they are logically ORed with field type
///     FOO_STRUCT = {"a": 0 | uctypes.UINT32, "b": 4 | uctypes.UINT8}
///
///     # Example memory buffer to access (contained in bytes object)
///     buf = b"\x64\0\0\0\0x14"
///
///     # Create structure object referring to address of
///     # the data in the buffer above
///     s = uctypes.struct(FOO_STRUCT, uctypes.addressof(buf))
///
///     # Access fields
///     print(s.a, s.b)
///     # Result:
///     # 100, 20

#define LAYOUT_LITTLE_ENDIAN (0)
#define LAYOUT_BIG_ENDIAN    (1)
#define LAYOUT_NATIVE        (2)

#define VAL_TYPE_BITS 4
#define BITF_LEN_BITS 5
#define BITF_OFF_BITS 5
#define OFFSET_BITS 17
#if VAL_TYPE_BITS + BITF_LEN_BITS + BITF_OFF_BITS + OFFSET_BITS != 31
#error Invalid encoding field length
#endif

enum {
    UINT8, INT8, UINT16, INT16,
    UINT32, INT32, UINT64, INT64,

    BFUINT8, BFINT8, BFUINT16, BFINT16,
    BFUINT32, BFINT32,

    FLOAT32, FLOAT64,
};

#define AGG_TYPE_BITS 2

enum {
    STRUCT, PTR, ARRAY, BITFIELD,
};

// Here we need to set sign bit right
#define TYPE2SMALLINT(x, nbits) ((((int)x) << (32 - nbits)) >> 1)
#define GET_TYPE(x, nbits) (((x) >> (31 - nbits)) & ((1 << nbits) - 1))
// Bit 0 is "is_signed"
#define GET_SCALAR_SIZE(val_type) (1 << ((val_type) >> 1))
#define VALUE_MASK(type_nbits) ~((int)0x80000000 >> type_nbits)

#define IS_SCALAR_ARRAY(tuple_desc) ((tuple_desc)->len == 2)
// We cannot apply the below to INT8, as their range [-128, 127]
#define IS_SCALAR_ARRAY_OF_BYTES(tuple_desc) (GET_TYPE(MP_OBJ_SMALL_INT_VALUE((tuple_desc)->items[1]), VAL_TYPE_BITS) == UINT8)

// "struct" in uctypes context means "structural", i.e. aggregate, type.
STATIC const mp_obj_type_t uctypes_struct_type;

typedef struct _mp_obj_uctypes_struct_t {
    mp_obj_base_t base;
    mp_obj_t desc;
    byte *addr;
    uint32_t flags;
} mp_obj_uctypes_struct_t;

STATIC NORETURN void syntax_error(void) {
    mp_raise_TypeError("syntax error in uctypes descriptor");
}

STATIC mp_obj_t uctypes_struct_make_new(const mp_obj_type_t *type, size_t n_args, size_t n_kw, const mp_obj_t *args) {
    mp_arg_check_num(n_args, n_kw, 2, 3, false);
    mp_obj_uctypes_struct_t *o = m_new_obj(mp_obj_uctypes_struct_t);
    o->base.type = type;
    o->addr = (void*)(uintptr_t)mp_obj_int_get_truncated(args[0]);
    o->desc = args[1];
    o->flags = LAYOUT_NATIVE;
    if (n_args == 3) {
        o->flags = mp_obj_get_int(args[2]);
    }
    return MP_OBJ_FROM_PTR(o);
}

STATIC void uctypes_struct_print(const mp_print_t *print, mp_obj_t self_in, mp_print_kind_t kind) {
    (void)kind;
    mp_obj_uctypes_struct_t *self = MP_OBJ_TO_PTR(self_in);
    const char *typen = "unk";
    if (MP_OBJ_IS_TYPE(self->desc, &mp_type_dict)) {
        typen = "STRUCT";
    } else if (MP_OBJ_IS_TYPE(self->desc, &mp_type_tuple)) {
        mp_obj_tuple_t *t = MP_OBJ_TO_PTR(self->desc);
        mp_int_t offset = MP_OBJ_SMALL_INT_VALUE(t->items[0]);
        uint agg_type = GET_TYPE(offset, AGG_TYPE_BITS);
        switch (agg_type) {
            case PTR: typen = "PTR"; break;
            case ARRAY: typen = "ARRAY"; break;
        }
    } else {
        typen = "ERROR";
    }
    mp_printf(print, "<struct %s %p>", typen, self->addr);
}

// Get size of any type descriptor
STATIC mp_uint_t uctypes_struct_size(mp_obj_t desc_in, int layout_type, mp_uint_t *max_field_size);

// Get size of scalar type descriptor
static inline mp_uint_t uctypes_struct_scalar_size(int val_type) {
    if (val_type == FLOAT32) {
        return 4;
    } else {
        return GET_SCALAR_SIZE(val_type & 7);
    }
}

// Get size of aggregate type descriptor
STATIC mp_uint_t uctypes_struct_agg_size(mp_obj_tuple_t *t, int layout_type, mp_uint_t *max_field_size) {
    mp_uint_t total_size = 0;

    mp_int_t offset_ = MP_OBJ_SMALL_INT_VALUE(t->items[0]);
    mp_uint_t agg_type = GET_TYPE(offset_, AGG_TYPE_BITS);

    switch (agg_type) {
        case STRUCT:
            return uctypes_struct_size(t->items[1], layout_type, max_field_size);
        case PTR:
            if (sizeof(void*) > *max_field_size) {
                *max_field_size = sizeof(void*);
            }
            return sizeof(void*);
        case ARRAY: {
            mp_int_t arr_sz = MP_OBJ_SMALL_INT_VALUE(t->items[1]);
            uint val_type = GET_TYPE(arr_sz, VAL_TYPE_BITS);
            arr_sz &= VALUE_MASK(VAL_TYPE_BITS);
            mp_uint_t item_s;
            if (t->len == 2) {
                // Elements of array are scalar
                item_s = GET_SCALAR_SIZE(val_type);
                if (item_s > *max_field_size) {
                    *max_field_size = item_s;
                }
            } else {
                // Elements of array are aggregates
                item_s = uctypes_struct_size(t->items[2], layout_type, max_field_size);
            }

            return item_s * arr_sz;
        }
        default:
            assert(0);
    }

    return total_size;
}

STATIC mp_uint_t uctypes_struct_size(mp_obj_t desc_in, int layout_type, mp_uint_t *max_field_size) {
    if (!MP_OBJ_IS_TYPE(desc_in, &mp_type_dict)) {
        if (MP_OBJ_IS_TYPE(desc_in, &mp_type_tuple)) {
            return uctypes_struct_agg_size((mp_obj_tuple_t*)MP_OBJ_TO_PTR(desc_in), layout_type, max_field_size);
        } else if (MP_OBJ_IS_SMALL_INT(desc_in)) {
            // We allow sizeof on both type definitions and structures/structure fields,
            // but scalar structure field is lowered into native Python int, so all
            // type info is lost. So, we cannot say if it's scalar type description,
            // or such lowered scalar.
            mp_raise_TypeError("Cannot unambiguously get sizeof scalar");
        }
        syntax_error();
    }

    mp_obj_dict_t *d = MP_OBJ_TO_PTR(desc_in);
    mp_uint_t total_size = 0;

    for (mp_uint_t i = 0; i < d->map.alloc; i++) {
        if (MP_MAP_SLOT_IS_FILLED(&d->map, i)) {
            mp_obj_t v = d->map.table[i].value;
            if (MP_OBJ_IS_SMALL_INT(v)) {
                mp_uint_t offset = MP_OBJ_SMALL_INT_VALUE(v);
                mp_uint_t val_type = GET_TYPE(offset, VAL_TYPE_BITS);
                offset &= VALUE_MASK(VAL_TYPE_BITS);
                if (val_type >= BFUINT8 && val_type <= BFINT32) {
                    offset &= (1 << OFFSET_BITS) - 1;
                }
                mp_uint_t s = uctypes_struct_scalar_size(val_type);
                if (s > *max_field_size) {
                    *max_field_size = s;
                }
                if (offset + s > total_size) {
                    total_size = offset + s;
                }
            } else {
                if (!MP_OBJ_IS_TYPE(v, &mp_type_tuple)) {
                    syntax_error();
                }
                mp_obj_tuple_t *t = MP_OBJ_TO_PTR(v);
                mp_int_t offset = MP_OBJ_SMALL_INT_VALUE(t->items[0]);
                offset &= VALUE_MASK(AGG_TYPE_BITS);
                mp_uint_t s = uctypes_struct_agg_size(t, layout_type, max_field_size);
                if (offset + s > total_size) {
                    total_size = offset + s;
                }
            }
        }
    }

    // Round size up to alignment of biggest field
    if (layout_type == LAYOUT_NATIVE) {
        total_size = (total_size + *max_field_size - 1) & ~(*max_field_size - 1);
    }
    return total_size;
}

STATIC mp_obj_t uctypes_struct_sizeof(mp_obj_t obj_in) {
    mp_uint_t max_field_size = 0;
    if (MP_OBJ_IS_TYPE(obj_in, &mp_type_bytearray)) {
        return mp_obj_len(obj_in);
    }
    int layout_type = LAYOUT_NATIVE;
    // We can apply sizeof either to structure definition (a dict)
    // or to instantiated structure
    if (MP_OBJ_IS_TYPE(obj_in, &uctypes_struct_type)) {
        // Extract structure definition
        mp_obj_uctypes_struct_t *obj = MP_OBJ_TO_PTR(obj_in);
        obj_in = obj->desc;
        layout_type = obj->flags;
    }
    mp_uint_t size = uctypes_struct_size(obj_in, layout_type, &max_field_size);
    return MP_OBJ_NEW_SMALL_INT(size);
}
STATIC MP_DEFINE_CONST_FUN_OBJ_1(uctypes_struct_sizeof_obj, uctypes_struct_sizeof);

static inline mp_obj_t get_unaligned(uint val_type, byte *p, int big_endian) {
    char struct_type = big_endian ? '>' : '<';
    static const char type2char[16] = "BbHhIiQq------fd";
    return mp_binary_get_val(struct_type, type2char[val_type], &p);
}

static inline void set_unaligned(uint val_type, byte *p, int big_endian, mp_obj_t val) {
    char struct_type = big_endian ? '>' : '<';
    static const char type2char[16] = "BbHhIiQq------fd";
    mp_binary_set_val(struct_type, type2char[val_type], val, &p);
}

static inline mp_uint_t get_aligned_basic(uint val_type, void *p) {
    switch (val_type) {
        case UINT8:
            return *(uint8_t*)p;
        case UINT16:
            return *(uint16_t*)p;
        case UINT32:
            return *(uint32_t*)p;
    }
    assert(0);
    return 0;
}

static inline void set_aligned_basic(uint val_type, void *p, mp_uint_t v) {
    switch (val_type) {
        case UINT8:
            *(uint8_t*)p = (uint8_t)v; return;
        case UINT16:
            *(uint16_t*)p = (uint16_t)v; return;
        case UINT32:
            *(uint32_t*)p = (uint32_t)v; return;
    }
    assert(0);
}

STATIC mp_obj_t get_aligned(uint val_type, void *p, mp_int_t index) {
    switch (val_type) {
        case UINT8:
            return MP_OBJ_NEW_SMALL_INT(((uint8_t*)p)[index]);
        case INT8:
            return MP_OBJ_NEW_SMALL_INT(((int8_t*)p)[index]);
        case UINT16:
            return MP_OBJ_NEW_SMALL_INT(((uint16_t*)p)[index]);
        case INT16:
            return MP_OBJ_NEW_SMALL_INT(((int16_t*)p)[index]);
        case UINT32:
            return mp_obj_new_int_from_uint(((uint32_t*)p)[index]);
        case INT32:
            return mp_obj_new_int(((int32_t*)p)[index]);
        case UINT64:
            return mp_obj_new_int_from_ull(((uint64_t*)p)[index]);
        case INT64:
            return mp_obj_new_int_from_ll(((int64_t*)p)[index]);
        #if MICROPY_PY_BUILTINS_FLOAT
        case FLOAT32:
            return mp_obj_new_float(((float*)p)[index]);
        case FLOAT64:
            return mp_obj_new_float(((double*)p)[index]);
        #endif
        default:
            assert(0);
            return MP_OBJ_NULL;
    }
}

STATIC void set_aligned(uint val_type, void *p, mp_int_t index, mp_obj_t val) {
    #if MICROPY_PY_BUILTINS_FLOAT
    if (val_type == FLOAT32 || val_type == FLOAT64) {
        mp_float_t v = mp_obj_get_float(val);
        if (val_type == FLOAT32) {
            ((float*)p)[index] = v;
        } else {
            ((double*)p)[index] = v;
        }
        return;
    }
    #endif
    mp_int_t v = mp_obj_get_int_truncated(val);
    switch (val_type) {
        case UINT8:
            ((uint8_t*)p)[index] = (uint8_t)v; return;
        case INT8:
            ((int8_t*)p)[index] = (int8_t)v; return;
        case UINT16:
            ((uint16_t*)p)[index] = (uint16_t)v; return;
        case INT16:
            ((int16_t*)p)[index] = (int16_t)v; return;
        case UINT32:
            ((uint32_t*)p)[index] = (uint32_t)v; return;
        case INT32:
            ((int32_t*)p)[index] = (int32_t)v; return;
        case INT64:
        case UINT64:
            if (sizeof(mp_int_t) == 8) {
                ((uint64_t*)p)[index] = (uint64_t)v;
            } else {
                // TODO: Doesn't offer atomic store semantics, but should at least try
                set_unaligned(val_type, p, MP_ENDIANNESS_BIG, val);
            }
            return;
        default:
            assert(0);
    }
}

STATIC mp_obj_t uctypes_struct_attr_op(mp_obj_t self_in, qstr attr, mp_obj_t set_val) {
    mp_obj_uctypes_struct_t *self = MP_OBJ_TO_PTR(self_in);

    // TODO: Support at least OrderedDict in addition
    if (!MP_OBJ_IS_TYPE(self->desc, &mp_type_dict)) {
            mp_raise_TypeError("struct: no fields");
    }

    mp_obj_t deref = mp_obj_dict_get(self->desc, MP_OBJ_NEW_QSTR(attr));
    if (MP_OBJ_IS_SMALL_INT(deref)) {
        mp_int_t offset = MP_OBJ_SMALL_INT_VALUE(deref);
        mp_uint_t val_type = GET_TYPE(offset, VAL_TYPE_BITS);
        offset &= VALUE_MASK(VAL_TYPE_BITS);
//printf("scalar type=%d offset=%x\n", val_type, offset);

        if (val_type <= INT64 || val_type == FLOAT32 || val_type == FLOAT64) {
//            printf("size=%d\n", GET_SCALAR_SIZE(val_type));
            if (self->flags == LAYOUT_NATIVE) {
                if (set_val == MP_OBJ_NULL) {
                    return get_aligned(val_type, self->addr + offset, 0);
                } else {
                    set_aligned(val_type, self->addr + offset, 0, set_val);
                    return set_val; // just !MP_OBJ_NULL
                }
            } else {
                if (set_val == MP_OBJ_NULL) {
                    return get_unaligned(val_type, self->addr + offset, self->flags);
                } else {
                    set_unaligned(val_type, self->addr + offset, self->flags, set_val);
                    return set_val; // just !MP_OBJ_NULL
                }
            }
        } else if (val_type >= BFUINT8 && val_type <= BFINT32) {
            uint bit_offset = (offset >> 17) & 31;
            uint bit_len = (offset >> 22) & 31;
            offset &= (1 << 17) - 1;
            mp_uint_t val;
            if (self->flags == LAYOUT_NATIVE) {
                val = get_aligned_basic(val_type & 6, self->addr + offset);
            } else {
                val = mp_binary_get_int(GET_SCALAR_SIZE(val_type & 7), val_type & 1, self->flags, self->addr + offset);
            }
            if (set_val == MP_OBJ_NULL) {
                val >>= bit_offset;
                val &= (1 << bit_len) - 1;
                // TODO: signed
                assert((val_type & 1) == 0);
                return mp_obj_new_int(val);
            } else {
                mp_uint_t set_val_int = (mp_uint_t)mp_obj_get_int(set_val);
                mp_uint_t mask = (1 << bit_len) - 1;
                set_val_int &= mask;
                set_val_int <<= bit_offset;
                mask <<= bit_offset;
                val = (val & ~mask) | set_val_int;

                if (self->flags == LAYOUT_NATIVE) {
                    set_aligned_basic(val_type & 6, self->addr + offset, val);
                } else {
                    mp_binary_set_int(GET_SCALAR_SIZE(val_type & 7), self->flags == LAYOUT_BIG_ENDIAN,
                        self->addr + offset, val);
                }
                return set_val; // just !MP_OBJ_NULL
            }
        }

        assert(0);
        return MP_OBJ_NULL;
    }

    if (!MP_OBJ_IS_TYPE(deref, &mp_type_tuple)) {
        syntax_error();
    }

    if (set_val != MP_OBJ_NULL) {
        // Cannot assign to aggregate
        syntax_error();
    }

    mp_obj_tuple_t *sub = MP_OBJ_TO_PTR(deref);
    mp_int_t offset = MP_OBJ_SMALL_INT_VALUE(sub->items[0]);
    mp_uint_t agg_type = GET_TYPE(offset, AGG_TYPE_BITS);
    offset &= VALUE_MASK(AGG_TYPE_BITS);
//printf("agg type=%d offset=%x\n", agg_type, offset);

    switch (agg_type) {
        case STRUCT: {
            mp_obj_uctypes_struct_t *o = m_new_obj(mp_obj_uctypes_struct_t);
            o->base.type = &uctypes_struct_type;
            o->desc = sub->items[1];
            o->addr = self->addr + offset;
            o->flags = self->flags;
            return MP_OBJ_FROM_PTR(o);
        }
        case ARRAY: {
            mp_uint_t dummy;
            if (IS_SCALAR_ARRAY(sub) && IS_SCALAR_ARRAY_OF_BYTES(sub)) {
                return mp_obj_new_bytearray_by_ref(uctypes_struct_agg_size(sub, self->flags, &dummy), self->addr + offset);
            }
            // Fall thru to return uctypes struct object
        }
        case PTR: {
            mp_obj_uctypes_struct_t *o = m_new_obj(mp_obj_uctypes_struct_t);
            o->base.type = &uctypes_struct_type;
            o->desc = MP_OBJ_FROM_PTR(sub);
            o->addr = self->addr + offset;
            o->flags = self->flags;
//printf("PTR/ARR base addr=%p\n", o->addr);
            return MP_OBJ_FROM_PTR(o);
        }
    }

    // Should be unreachable once all cases are handled
    return MP_OBJ_NULL;
}

STATIC void uctypes_struct_attr(mp_obj_t self_in, qstr attr, mp_obj_t *dest) {
    if (dest[0] == MP_OBJ_NULL) {
        // load attribute
        mp_obj_t val = uctypes_struct_attr_op(self_in, attr, MP_OBJ_NULL);
        dest[0] = val;
    } else {
        // delete/store attribute
        if (uctypes_struct_attr_op(self_in, attr, dest[1]) != MP_OBJ_NULL) {
            dest[0] = MP_OBJ_NULL; // indicate success
        }
    }
}

STATIC mp_obj_t uctypes_struct_subscr(mp_obj_t self_in, mp_obj_t index_in, mp_obj_t value) {
    mp_obj_uctypes_struct_t *self = MP_OBJ_TO_PTR(self_in);

    if (value == MP_OBJ_NULL) {
        // delete
        return MP_OBJ_NULL; // op not supported
    } else {
        // load / store
        if (!MP_OBJ_IS_TYPE(self->desc, &mp_type_tuple)) {
            mp_raise_TypeError("struct: cannot index");
        }

        mp_obj_tuple_t *t = MP_OBJ_TO_PTR(self->desc);
        mp_int_t offset = MP_OBJ_SMALL_INT_VALUE(t->items[0]);
        uint agg_type = GET_TYPE(offset, AGG_TYPE_BITS);

        mp_int_t index = MP_OBJ_SMALL_INT_VALUE(index_in);

        if (agg_type == ARRAY) {
            mp_int_t arr_sz = MP_OBJ_SMALL_INT_VALUE(t->items[1]);
            uint val_type = GET_TYPE(arr_sz, VAL_TYPE_BITS);
            arr_sz &= VALUE_MASK(VAL_TYPE_BITS);
            if (index >= arr_sz) {
                nlr_raise(mp_obj_new_exception_msg(&mp_type_IndexError, "struct: index out of range"));
            }

            if (t->len == 2) {
                // array of scalars
                if (self->flags == LAYOUT_NATIVE) {
                    if (value == MP_OBJ_SENTINEL) {
                        return get_aligned(val_type, self->addr, index);
                    } else {
                        set_aligned(val_type, self->addr, index, value);
                        return value; // just !MP_OBJ_NULL
                    }
                } else {
                    byte *p = self->addr + GET_SCALAR_SIZE(val_type) * index;
                    if (value == MP_OBJ_SENTINEL) {
                        return get_unaligned(val_type, p, self->flags);
                    } else {
                        set_unaligned(val_type, p, self->flags, value);
                        return value; // just !MP_OBJ_NULL
                    }
                }
            } else if (value == MP_OBJ_SENTINEL) {
                mp_uint_t dummy = 0;
                mp_uint_t size = uctypes_struct_size(t->items[2], self->flags, &dummy);
                mp_obj_uctypes_struct_t *o = m_new_obj(mp_obj_uctypes_struct_t);
                o->base.type = &uctypes_struct_type;
                o->desc = t->items[2];
                o->addr = self->addr + size * index;
                o->flags = self->flags;
                return MP_OBJ_FROM_PTR(o);
            } else {
                return MP_OBJ_NULL; // op not supported
            }

        } else if (agg_type == PTR) {
            byte *p = *(void**)self->addr;
            if (MP_OBJ_IS_SMALL_INT(t->items[1])) {
                uint val_type = GET_TYPE(MP_OBJ_SMALL_INT_VALUE(t->items[1]), VAL_TYPE_BITS);
                return get_aligned(val_type, p, index);
            } else {
                mp_uint_t dummy = 0;
                mp_uint_t size = uctypes_struct_size(t->items[1], self->flags, &dummy);
                mp_obj_uctypes_struct_t *o = m_new_obj(mp_obj_uctypes_struct_t);
                o->base.type = &uctypes_struct_type;
                o->desc = t->items[1];
                o->addr = p + size * index;
                o->flags = self->flags;
                return MP_OBJ_FROM_PTR(o);
            }
        }

        assert(0);
        return MP_OBJ_NULL;
    }
}

STATIC mp_int_t uctypes_get_buffer(mp_obj_t self_in, mp_buffer_info_t *bufinfo, mp_uint_t flags) {
    (void)flags;
    mp_obj_uctypes_struct_t *self = MP_OBJ_TO_PTR(self_in);
    mp_uint_t max_field_size = 0;
    mp_uint_t size = uctypes_struct_size(self->desc, self->flags, &max_field_size);

    bufinfo->buf = self->addr;
    bufinfo->len = size;
    bufinfo->typecode = BYTEARRAY_TYPECODE;
    return 0;
}

/// \function addressof()
/// Return address of object's data (applies to object providing buffer
/// interface).
STATIC mp_obj_t uctypes_struct_addressof(mp_obj_t buf) {
    mp_buffer_info_t bufinfo;
    mp_get_buffer_raise(buf, &bufinfo, MP_BUFFER_READ);
    return mp_obj_new_int((mp_int_t)(uintptr_t)bufinfo.buf);
}
MP_DEFINE_CONST_FUN_OBJ_1(uctypes_struct_addressof_obj, uctypes_struct_addressof);

/// \function bytearray_at()
/// Capture memory at given address of given size as bytearray. Memory is
/// captured by reference (and thus memory pointed by bytearray may change
/// or become invalid at later time). Use bytes_at() to capture by value.
STATIC mp_obj_t uctypes_struct_bytearray_at(mp_obj_t ptr, mp_obj_t size) {
    return mp_obj_new_bytearray_by_ref(mp_obj_int_get_truncated(size), (void*)(uintptr_t)mp_obj_int_get_truncated(ptr));
}
MP_DEFINE_CONST_FUN_OBJ_2(uctypes_struct_bytearray_at_obj, uctypes_struct_bytearray_at);

/// \function bytes_at()
/// Capture memory at given address of given size as bytes. Memory is
/// captured by value, i.e. copied. Use bytearray_at() to capture by reference
/// ("zero copy").
STATIC mp_obj_t uctypes_struct_bytes_at(mp_obj_t ptr, mp_obj_t size) {
    return mp_obj_new_bytes((void*)(uintptr_t)mp_obj_int_get_truncated(ptr), mp_obj_int_get_truncated(size));
}
MP_DEFINE_CONST_FUN_OBJ_2(uctypes_struct_bytes_at_obj, uctypes_struct_bytes_at);

STATIC const mp_obj_type_t uctypes_struct_type = {
    { &mp_type_type },
    .name = MP_QSTR_struct,
    .print = uctypes_struct_print,
    .make_new = uctypes_struct_make_new,
    .attr = uctypes_struct_attr,
    .subscr = uctypes_struct_subscr,
    .buffer_p = { .get_buffer = uctypes_get_buffer },
};

STATIC const mp_rom_map_elem_t mp_module_uctypes_globals_table[] = {
    { MP_ROM_QSTR(MP_QSTR___name__), MP_ROM_QSTR(MP_QSTR_uctypes) },
    { MP_ROM_QSTR(MP_QSTR_struct), MP_ROM_PTR(&uctypes_struct_type) },
    { MP_ROM_QSTR(MP_QSTR_sizeof), MP_ROM_PTR(&uctypes_struct_sizeof_obj) },
    { MP_ROM_QSTR(MP_QSTR_addressof), MP_ROM_PTR(&uctypes_struct_addressof_obj) },
    { MP_ROM_QSTR(MP_QSTR_bytes_at), MP_ROM_PTR(&uctypes_struct_bytes_at_obj) },
    { MP_ROM_QSTR(MP_QSTR_bytearray_at), MP_ROM_PTR(&uctypes_struct_bytearray_at_obj) },

    /// \moduleref uctypes

    /// \constant NATIVE - Native structure layout - native endianness,
    /// platform-specific field alignment
    { MP_ROM_QSTR(MP_QSTR_NATIVE), MP_ROM_INT(LAYOUT_NATIVE) },
    /// \constant LITTLE_ENDIAN - Little-endian structure layout, tightly packed
    /// (no alignment constraints)
    { MP_ROM_QSTR(MP_QSTR_LITTLE_ENDIAN), MP_ROM_INT(LAYOUT_LITTLE_ENDIAN) },
    /// \constant BIG_ENDIAN - Big-endian structure layout, tightly packed
    /// (no alignment constraints)
    { MP_ROM_QSTR(MP_QSTR_BIG_ENDIAN), MP_ROM_INT(LAYOUT_BIG_ENDIAN) },

    /// \constant VOID - void value type, may be used only as pointer target type.
    { MP_ROM_QSTR(MP_QSTR_VOID), MP_ROM_INT(TYPE2SMALLINT(UINT8, VAL_TYPE_BITS)) },

    /// \constant UINT8 - uint8_t value type
    { MP_ROM_QSTR(MP_QSTR_UINT8), MP_ROM_INT(TYPE2SMALLINT(UINT8, 4)) },
    /// \constant INT8 - int8_t value type
    { MP_ROM_QSTR(MP_QSTR_INT8), MP_ROM_INT(TYPE2SMALLINT(INT8, 4)) },
    /// \constant UINT16 - uint16_t value type
    { MP_ROM_QSTR(MP_QSTR_UINT16), MP_ROM_INT(TYPE2SMALLINT(UINT16, 4)) },
    /// \constant INT16 - int16_t value type
    { MP_ROM_QSTR(MP_QSTR_INT16), MP_ROM_INT(TYPE2SMALLINT(INT16, 4)) },
    /// \constant UINT32 - uint32_t value type
    { MP_ROM_QSTR(MP_QSTR_UINT32), MP_ROM_INT(TYPE2SMALLINT(UINT32, 4)) },
    /// \constant INT32 - int32_t value type
    { MP_ROM_QSTR(MP_QSTR_INT32), MP_ROM_INT(TYPE2SMALLINT(INT32, 4)) },
    /// \constant UINT64 - uint64_t value type
    { MP_ROM_QSTR(MP_QSTR_UINT64), MP_ROM_INT(TYPE2SMALLINT(UINT64, 4)) },
    /// \constant INT64 - int64_t value type
    { MP_ROM_QSTR(MP_QSTR_INT64), MP_ROM_INT(TYPE2SMALLINT(INT64, 4)) },

    { MP_ROM_QSTR(MP_QSTR_BFUINT8), MP_ROM_INT(TYPE2SMALLINT(BFUINT8, 4)) },
    { MP_ROM_QSTR(MP_QSTR_BFINT8), MP_ROM_INT(TYPE2SMALLINT(BFINT8, 4)) },
    { MP_ROM_QSTR(MP_QSTR_BFUINT16), MP_ROM_INT(TYPE2SMALLINT(BFUINT16, 4)) },
    { MP_ROM_QSTR(MP_QSTR_BFINT16), MP_ROM_INT(TYPE2SMALLINT(BFINT16, 4)) },
    { MP_ROM_QSTR(MP_QSTR_BFUINT32), MP_ROM_INT(TYPE2SMALLINT(BFUINT32, 4)) },
    { MP_ROM_QSTR(MP_QSTR_BFINT32), MP_ROM_INT(TYPE2SMALLINT(BFINT32, 4)) },

    { MP_ROM_QSTR(MP_QSTR_BF_POS), MP_ROM_INT(17) },
    { MP_ROM_QSTR(MP_QSTR_BF_LEN), MP_ROM_INT(22) },

    #if MICROPY_PY_BUILTINS_FLOAT
    { MP_ROM_QSTR(MP_QSTR_FLOAT32), MP_ROM_INT(TYPE2SMALLINT(FLOAT32, 4)) },
    { MP_ROM_QSTR(MP_QSTR_FLOAT64), MP_ROM_INT(TYPE2SMALLINT(FLOAT64, 4)) },
    #endif

    { MP_ROM_QSTR(MP_QSTR_PTR), MP_ROM_INT(TYPE2SMALLINT(PTR, AGG_TYPE_BITS)) },
    { MP_ROM_QSTR(MP_QSTR_ARRAY), MP_ROM_INT(TYPE2SMALLINT(ARRAY, AGG_TYPE_BITS)) },
};

STATIC MP_DEFINE_CONST_DICT(mp_module_uctypes_globals, mp_module_uctypes_globals_table);

const mp_obj_module_t mp_module_uctypes = {
    .base = { &mp_type_module },
    .globals = (mp_obj_dict_t*)&mp_module_uctypes_globals,
};

#endif


text:
'use strict';

import AppKernel from 'core/kernel';
import IndexController from 'app/controllers/index-controller';
import PageController from 'app/controllers/page-controller';
import Services from 'app/services';

export default class App extends AppKernel {
    constructor(options) {
        let indexController = new IndexController();
        let pageController = new PageController();
        super(options);
    }
}


text:
package mcjty.rftools.blocks.screens;

import mcjty.lib.thirteen.ConfigSpec;

public class ScreenConfiguration {

    public static final String CATEGORY_SCREEN = "screen";

    public static ConfigSpec.IntValue CONTROLLER_MAXENERGY; //60000;
    public static ConfigSpec.IntValue CONTROLLER_RECEIVEPERTICK; //1000;
    public static ConfigSpec.IntValue BUTTON_RFPERTICK; //0;
    public static ConfigSpec.IntValue DUMP_RFPERTICK; //0;
    public static ConfigSpec.IntValue ELEVATOR_BUTTON_RFPERTICK; //0;
    public static ConfigSpec.IntValue CLOCK_RFPERTICK; //1;
    public static ConfigSpec.IntValue COMPUTER_RFPERTICK; //4;
    public static ConfigSpec.IntValue COUNTERPLUS_RFPERTICK; //30;
    public static ConfigSpec.IntValue COUNTER_RFPERTICK; //4;
    public static ConfigSpec.IntValue DIMENSION_RFPERTICK; //6;
    public static ConfigSpec.IntValue ENERGY_RFPERTICK; //4;
    public static ConfigSpec.IntValue ENERGYPLUS_RFPERTICK; //30;
    public static ConfigSpec.IntValue FLUID_RFPERTICK; //4;
    public static ConfigSpec.IntValue FLUIDPLUS_RFPERTICK; //30;
    public static ConfigSpec.IntValue ITEMSTACKPLUS_RFPERTICK; //30;
    public static ConfigSpec.IntValue ITEMSTACK_RFPERTICK; //4;
    public static ConfigSpec.IntValue MACHINEINFO_RFPERTICK; //4;
    public static ConfigSpec.IntValue REDSTONE_RFPERTICK; //4;
    public static ConfigSpec.IntValue TEXT_RFPERTICK; //0;
    public static ConfigSpec.IntValue STORAGE_CONTROL_RFPERTICK; //6;
    public static ConfigSpec.IntValue SCREEN_REFRESH_TIMING; //500;

    public static ConfigSpec.BooleanValue useTruetype;
    public static ConfigSpec.ConfigValue<String> font;
    public static ConfigSpec.DoubleValue fontSize;
    public static ConfigSpec.ConfigValue<String> additionalCharacters;

    public static void init(ConfigSpec.Builder SERVER_BUILDER, ConfigSpec.Builder CLIENT_BUILDER) {
        SERVER_BUILDER.comment("Settings for the screen system").push(CATEGORY_SCREEN);
        CLIENT_BUILDER.comment("Settings for the screen system").push(CATEGORY_SCREEN);

        CONTROLLER_MAXENERGY = SERVER_BUILDER
                .comment("Maximum RF storage that the screen controller can hold")
                .defineInRange("screenControllerMaxRF", 60000, 0, Integer.MAX_VALUE);
        CONTROLLER_RECEIVEPERTICK = SERVER_BUILDER
                .comment("RF per tick that the the screen controller can receive")
                .defineInRange("screenControllerRFPerTick", 1000, 0, Integer.MAX_VALUE);

        BUTTON_RFPERTICK = SERVER_BUILDER
                .comment("RF per tick/per block for the button module")
                .defineInRange("buttonRFPerTick", 9, 0, Integer.MAX_VALUE);
        DUMP_RFPERTICK = SERVER_BUILDER
                .comment("RF per tick/per block for the dump module")
                .defineInRange("dumpRFPerTick", 0, 0, Integer.MAX_VALUE);
        ELEVATOR_BUTTON_RFPERTICK = SERVER_BUILDER
                .comment("RF per tick/per block for the elevator button module")
                .defineInRange("elevatorButtonRFPerTick", 0, 0, Integer.MAX_VALUE);
        CLOCK_RFPERTICK = SERVER_BUILDER
                .comment("RF per tick/per block for the clock module")
                .defineInRange("clockRFPerTick", 1, 0, Integer.MAX_VALUE);
        COMPUTER_RFPERTICK = SERVER_BUILDER
                .comment("RF per tick/per block for the computer module")
                .defineInRange("computerRFPerTick", 4, 0, Integer.MAX_VALUE);
        COUNTERPLUS_RFPERTICK = SERVER_BUILDER
                .comment("RF per tick/per block for the counter plus module")
                .defineInRange("counterPlusRFPerTick", 30, 0, Integer.MAX_VALUE);
        COUNTER_RFPERTICK = SERVER_BUILDER
                .comment("RF per tick/per block for the counter module")
                .defineInRange("counterRFPerTick", 4, 0, Integer.MAX_VALUE);
        DIMENSION_RFPERTICK = SERVER_BUILDER
                .comment("RF per tick/per block for the dimension module")
                .defineInRange("dimensionRFPerTick", 6, 0, Integer.MAX_VALUE);
        ENERGY_RFPERTICK = SERVER_BUILDER
                .comment("RF per tick/per block for the energy module")
                .defineInRange("energyRFPerTick", 4, 0, Integer.MAX_VALUE);
        ENERGYPLUS_RFPERTICK = SERVER_BUILDER
                .comment("RF per tick/per block for the energy plus module")
                .defineInRange("energyPlusRFPerTick", 30, 0, Integer.MAX_VALUE);
        FLUID_RFPERTICK = SERVER_BUILDER
                .comment("RF per tick/per block for the fluid module")
                .defineInRange("fluidRFPerTick", 4, 0, Integer.MAX_VALUE);
        FLUIDPLUS_RFPERTICK = SERVER_BUILDER
                .comment("RF per tick/per block for the fluid plus module")
                .defineInRange("fluidPlusRFPerTick", 30, 0, Integer.MAX_VALUE);
        ITEMSTACKPLUS_RFPERTICK = SERVER_BUILDER
                .comment("RF per tick/per block for the itemstack plus module")
                .defineInRange("itemstackPlusRFPerTick", 30, 0, Integer.MAX_VALUE);
        ITEMSTACK_RFPERTICK = SERVER_BUILDER
                .comment("RF per tick/per block for the itemstack module")
                .defineInRange("itemstackRFPerTick", 4, 0, Integer.MAX_VALUE);
        MACHINEINFO_RFPERTICK = SERVER_BUILDER
                .comment("RF per tick/per block for the machine information module")
                .defineInRange("machineInfoRFPerTick", 4, 0, Integer.MAX_VALUE);
        REDSTONE_RFPERTICK = SERVER_BUILDER
                .comment("RF per tick/per block for the redstone module")
                .defineInRange("redstoneRFPerTick", 4, 0, Integer.MAX_VALUE);
        TEXT_RFPERTICK = SERVER_BUILDER
                .comment("RF per tick/per block for the text module")
                .defineInRange("textRFPerTick", 0, 0, Integer.MAX_VALUE);
        STORAGE_CONTROL_RFPERTICK = SERVER_BUILDER
                .comment("RF per tick/per block for the storage control module")
                .defineInRange("storageControlRFPerTick", 0, 0, Integer.MAX_VALUE);

        useTruetype = CLIENT_BUILDER
                .comment("Set to true for TrueType font, set to false for vanilla font")
                .define("useTruetype", true);
        font = CLIENT_BUILDER
                .comment("The default truetype font to use")
                .define("fontName", "rftools:fonts/ubuntu.ttf");
        fontSize = CLIENT_BUILDER
                .comment("The size of the font")
                .defineInRange("fontSize", 40.0, 0, 1000000);
        additionalCharacters = CLIENT_BUILDER
                .comment("Additional characters that should be supported by the truetype system")
                .define("additionalCharacters", "");

        SCREEN_REFRESH_TIMING = SERVER_BUILDER
                .comment("How many times the screen will update. Higher numbers make the screens less accurate but better for network bandwidth")
                .defineInRange("screenRefreshTiming", 500, 0, Integer.MAX_VALUE);

        CLIENT_BUILDER.pop();
        SERVER_BUILDER.pop();
    }

}


text:
./cleanup.sh

#set -e

aclocal
automake --add-missing
autoconf
mkdir build


text:
var path = require('path');

function getRelativeModulePath(sourceModuleName, targetModuleName) {
    var relativePath = path.relative(sourceModuleName.replace(/\/[^\/]+$/, '/'), targetModuleName);
    if (relativePath === '' || /\/$/.test(relativePath)) {
        relativePath += sourceModuleName.replace(/^.*\//, '');
    }
    if (!/^\.\.?\//.test(relativePath)) {
        relativePath = './' + relativePath;
    }
    return relativePath;
}

module.exports = function wrapInUmd(moduleName, factoryAst, dependencies) {
    var moduleNameFragments = moduleName.split('/'),
        defineArgAsts = [['name', 'factory']],
        commonJsRequireArgAsts = [];

    if (Array.isArray(dependencies)) {
        defineArgAsts.unshift(['array', dependencies.map(function (dependency) {
            return ['string', dependency];
        })]);
        dependencies.forEach(function (dependency) {
            commonJsRequireArgAsts.push(['string', getRelativeModulePath(moduleName, dependency)]);
        });
    }

    var fallbackBlock = ['block', []],
        dotAst = ['name', 'root'];
    for (var i = 0 ; i < moduleNameFragments.length ; i += 1) {
        dotAst = ['dot', dotAst, moduleNameFragments[i]];
        fallbackBlock[1].push(
            [
                'assign',
                true,
                dotAst,
                i === moduleNameFragments.length - 1 ?
                    [ 'call', [ 'name', 'factory' ], dependencies.map(function (dependency) {
                        var dependencyDotAst = ['name', 'root'];
                        dependency.split('/').forEach(function (dependencyFragment) {
                            dependencyDotAst = ['dot', dependencyDotAst, dependencyFragment];
                        });
                        return dependencyDotAst;
                    }) ] :
                    [ 'binary', '||', dotAst, [ 'object', [] ] ]
            ]
        );
    }

    return (
        [ 'toplevel',
          [ [ 'stat',
              [ 'call',
                [ 'function',
                  null,
                  [ 'root', 'factory' ],
                  [ [ 'stat',
                      [ 'conditional',
                        [ 'binary',
                          '!=',
                          [ 'unary-prefix', 'typeof', [ 'name', 'module' ] ],
                          [ 'string', 'undefined' ] ],
                        [ 'assign',
                          true,
                          [ 'dot', [ 'name', 'module' ], 'exports' ],
                          [ 'call', [ 'name', 'factory' ], commonJsRequireArgAsts ] ],
                        [ 'conditional',
                          [ 'binary',
                            '&&',
                            [ 'binary',
                              '==',
                              [ 'unary-prefix',
                                'typeof',
                                [ 'dot', [ 'name', 'root' ], 'define' ] ],
                              [ 'string', 'function' ] ],
                            [ 'dot', [ 'name', 'define' ], 'amd' ] ],
                          [ 'call', [ 'name', 'define' ], defineArgAsts ],
                          fallbackBlock
                          ] ] ] ] ],
                [ [ 'name', 'this' ], factoryAst ] ] ] ] ]
    );
};


text:
 .treeview .list-group-item {
	cursor: pointer;
}

.treeview span.indent {
	margin-left: 10px;
	margin-right: 10px;
}

.treeview span.icon {
	width: 12px;
	margin-right: 5px;
}

.treeview .node-disabled {
	color: silver;
	cursor: not-allowed;
}


text:
package org.apache.lucene.search;

import java.util.Random;

import junit.framework.TestCase;

import org.apache.lucene.analysis.SimpleAnalyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.store.RAMDirectory;

public class BaseTestRangeFilter extends TestCase {

    public static final boolean F = false;
    public static final boolean T = true;

    RAMDirectory index = new RAMDirectory();
    Random rand = new Random(101); // use a set seed to test is deterministic

    int maxR = Integer.MIN_VALUE;
    int minR = Integer.MAX_VALUE;

    int minId = 0;
    int maxId = 10000;

    static final int intLength = Integer.toString(Integer.MAX_VALUE).length();

    /**
     * a simple padding function that should work with any int
     */
    public static String pad(int n) {
        StringBuffer b = new StringBuffer(40);
        String p = "0";
        if (n < 0) {
            p = "-";
            n = Integer.MAX_VALUE + n + 1;
        }
        b.append(p);
        String s = Integer.toString(n);
        for (int i = s.length(); i <= intLength; i++) {
            b.append("0");
        }
        b.append(s);

        return b.toString();
    }

    public BaseTestRangeFilter(String name) {
	super(name);
        build();
    }
    public BaseTestRangeFilter() {
        build();
    }

    private void build() {
        try {

            /* build an index */
            IndexWriter writer = new IndexWriter(index,
                                                 new SimpleAnalyzer(), T);

            for (int d = minId; d <= maxId; d++) {
                Document doc = new Document();
                doc.add(new Field("id",pad(d), Field.Store.YES, Field.Index.UN_TOKENIZED));
                int r= rand.nextInt();
                if (maxR < r) {
                    maxR = r;
                }
                if (r < minR) {
                    minR = r;
                }
                doc.add(new Field("rand",pad(r), Field.Store.YES, Field.Index.UN_TOKENIZED));
                doc.add(new Field("body","body", Field.Store.YES, Field.Index.UN_TOKENIZED));
                writer.addDocument(doc);
            }

            writer.optimize();
            writer.close();

        } catch (Exception e) {
            throw new RuntimeException("can't build index", e);
        }

    }

    public void testPad() {

        int[] tests = new int[] {
            -9999999, -99560, -100, -3, -1, 0, 3, 9, 10, 1000, 999999999
        };
        for (int i = 0; i < tests.length - 1; i++) {
            int a = tests[i];
            int b = tests[i+1];
            String aa = pad(a);
            String bb = pad(b);
            String label = a + ":" + aa + " vs " + b + ":" + bb;
            assertEquals("length of " + label, aa.length(), bb.length());
            assertTrue("compare less than " + label, aa.compareTo(bb) < 0);
        }

    }

}


text:
package vreplication

import (
	"fmt"
	"math/rand"
	"os"
	"os/exec"
	"path"
	"strings"
	"sync"
	"testing"
	"time"

	"github.com/stretchr/testify/require"

	"vitess.io/vitess/go/test/endtoend/cluster"
	"vitess.io/vitess/go/vt/log"
)

var (
	debug = false // set to true for local debugging: this uses the local env vtdataroot and does not teardown clusters

	originalVtdataroot    string
	vtdataroot            string
	mainClusterConfig     *ClusterConfig
	externalClusterConfig *ClusterConfig
)

// ClusterConfig defines the parameters like ports, tmpDir, tablet types which uniquely define a vitess cluster
type ClusterConfig struct {
	hostname            string
	topoPort            int
	vtctldPort          int
	vtctldGrpcPort      int
	vtdataroot          string
	tmpDir              string
	vtgatePort          int
	vtgateGrpcPort      int
	vtgateMySQLPort     int
	tabletTypes         string
	tabletPortBase      int
	tabletGrpcPortBase  int
	tabletMysqlPortBase int

	vreplicationCompressGTID bool
}

// VitessCluster represents all components within the test cluster
type VitessCluster struct {
	ClusterConfig *ClusterConfig
	Name          string
	Cells         map[string]*Cell
	Topo          *cluster.TopoProcess
	Vtctld        *cluster.VtctldProcess
	Vtctl         *cluster.VtctlProcess
	VtctlClient   *cluster.VtctlClientProcess
}

// Cell represents a Vitess cell within the test cluster
type Cell struct {
	Name      string
	Keyspaces map[string]*Keyspace
	Vtgates   []*cluster.VtgateProcess
}

// Keyspace represents a Vitess keyspace contained by a cell within the test cluster
type Keyspace struct {
	Name    string
	Shards  map[string]*Shard
	VSchema string
	Schema  string
}

// Shard represents a Vitess shard in a keyspace
type Shard struct {
	Name      string
	IsSharded bool
	Tablets   map[string]*Tablet
}

// Tablet represents a vttablet within a shard
type Tablet struct {
	Name     string
	Vttablet *cluster.VttabletProcess
	DbServer *cluster.MysqlctlProcess
}

func setTempVtDataRoot() string {
	dirSuffix := 100000 + rand.Intn(999999-100000) // 6 digits
	if debug {
		vtdataroot = originalVtdataroot
	} else {
		vtdataroot = path.Join(originalVtdataroot, fmt.Sprintf("vreple2e_%d", dirSuffix))
	}
	if _, err := os.Stat(vtdataroot); os.IsNotExist(err) {
		os.Mkdir(vtdataroot, 0700)
	}
	_ = os.Setenv("VTDATAROOT", vtdataroot)
	fmt.Printf("VTDATAROOT is %s\n", vtdataroot)
	return vtdataroot
}

func getClusterConfig(idx int, dataRootDir string) *ClusterConfig {
	basePort := 15000
	etcdPort := 2379

	basePort += idx * 10000
	etcdPort += idx * 10000
	if _, err := os.Stat(dataRootDir); os.IsNotExist(err) {
		os.Mkdir(dataRootDir, 0700)
	}

	return &ClusterConfig{
		hostname:            "localhost",
		topoPort:            etcdPort,
		vtctldPort:          basePort,
		vtctldGrpcPort:      basePort + 999,
		tmpDir:              dataRootDir + "/tmp",
		vtgatePort:          basePort + 1,
		vtgateGrpcPort:      basePort + 991,
		vtgateMySQLPort:     basePort + 306,
		tabletTypes:         "master",
		vtdataroot:          dataRootDir,
		tabletPortBase:      basePort + 1000,
		tabletGrpcPortBase:  basePort + 1991,
		tabletMysqlPortBase: basePort + 1306,
	}
}

func init() {
	// for local debugging set this variable so that each run uses VTDATAROOT instead of a random dir
	// and also does not teardown the cluster for inspecting logs and the databases
	if os.Getenv("VREPLICATION_E2E_DEBUG") != "" {
		debug = true
	}
	rand.Seed(time.Now().UTC().UnixNano())
	originalVtdataroot = os.Getenv("VTDATAROOT")
	var mainVtDataRoot string
	if debug {
		mainVtDataRoot = originalVtdataroot
	} else {
		mainVtDataRoot = setTempVtDataRoot()
	}
	mainClusterConfig = getClusterConfig(0, mainVtDataRoot)
	externalClusterConfig = getClusterConfig(1, mainVtDataRoot+"/ext")
}

// NewVitessCluster starts a basic cluster with vtgate, vtctld and the topo
func NewVitessCluster(t *testing.T, name string, cellNames []string, clusterConfig *ClusterConfig) *VitessCluster {
	vc := &VitessCluster{Name: name, Cells: make(map[string]*Cell), ClusterConfig: clusterConfig}
	require.NotNil(t, vc)
	topo := cluster.TopoProcessInstance(vc.ClusterConfig.topoPort, vc.ClusterConfig.topoPort+1, vc.ClusterConfig.hostname, "etcd2", "global")

	require.NotNil(t, topo)
	require.Nil(t, topo.Setup("etcd2", nil))
	topo.ManageTopoDir("mkdir", "/vitess/global")
	vc.Topo = topo
	for _, cellName := range cellNames {
		topo.ManageTopoDir("mkdir", "/vitess/"+cellName)
	}

	vtctld := cluster.VtctldProcessInstance(vc.ClusterConfig.vtctldPort, vc.ClusterConfig.vtctldGrpcPort,
		vc.ClusterConfig.topoPort, vc.ClusterConfig.hostname, vc.ClusterConfig.tmpDir)
	vc.Vtctld = vtctld
	require.NotNil(t, vc.Vtctld)
	// use first cell as `-cell`
	vc.Vtctld.Setup(cellNames[0])

	vc.Vtctl = cluster.VtctlProcessInstance(vc.ClusterConfig.topoPort, vc.ClusterConfig.hostname)
	require.NotNil(t, vc.Vtctl)
	for _, cellName := range cellNames {
		vc.Vtctl.AddCellInfo(cellName)
		cell, err := vc.AddCell(t, cellName)
		require.NoError(t, err)
		require.NotNil(t, cell)
	}

	vc.VtctlClient = cluster.VtctlClientProcessInstance(vc.ClusterConfig.hostname, vc.Vtctld.GrpcPort, vc.ClusterConfig.tmpDir)
	require.NotNil(t, vc.VtctlClient)

	return vc
}

// AddKeyspace creates a keyspace with specified shard keys and number of replica/read-only tablets
func (vc *VitessCluster) AddKeyspace(t *testing.T, cells []*Cell, ksName string, shards string, vschema string, schema string, numReplicas int, numRdonly int, tabletIDBase int) (*Keyspace, error) {
	keyspace := &Keyspace{
		Name:   ksName,
		Shards: make(map[string]*Shard),
	}

	if err := vc.Vtctl.CreateKeyspace(keyspace.Name); err != nil {
		t.Fatalf(err.Error())
	}
	cellsToWatch := ""
	for i, cell := range cells {
		if i > 0 {
			cellsToWatch = cellsToWatch + ","
		}
		cell.Keyspaces[ksName] = keyspace
		cellsToWatch = cellsToWatch + cell.Name
	}
	require.NoError(t, vc.AddShards(t, cells, keyspace, shards, numReplicas, numRdonly, tabletIDBase))

	if schema != "" {
		if err := vc.VtctlClient.ApplySchema(ksName, schema); err != nil {
			t.Fatalf(err.Error())
		}
	}
	keyspace.Schema = schema
	if vschema != "" {
		if err := vc.VtctlClient.ApplyVSchema(ksName, vschema); err != nil {
			t.Fatalf(err.Error())
		}
	}
	keyspace.VSchema = vschema
	for _, cell := range cells {
		if len(cell.Vtgates) == 0 {
			log.Infof("Starting vtgate")
			vc.StartVtgate(t, cell, cellsToWatch)
		}
	}
	_ = vc.VtctlClient.ExecuteCommand("RebuildKeyspaceGraph", ksName)
	return keyspace, nil
}

// AddTablet creates new tablet with specified attributes
func (vc *VitessCluster) AddTablet(t testing.TB, cell *Cell, keyspace *Keyspace, shard *Shard, tabletType string, tabletID int) (*Tablet, *exec.Cmd, error) {
	tablet := &Tablet{}

	options := []string{
		"-queryserver-config-schema-reload-time", "5",
		"-enable-lag-throttler",
		"-heartbeat_enable",
		"-heartbeat_interval", "250ms",
	} //FIXME: for multi-cell initial schema doesn't seem to load without "-queryserver-config-schema-reload-time"

	if mainClusterConfig.vreplicationCompressGTID {
		options = append(options, "-vreplication_store_compressed_gtid=true")
	}

	vttablet := cluster.VttabletProcessInstance(
		vc.ClusterConfig.tabletPortBase+tabletID,
		vc.ClusterConfig.tabletGrpcPortBase+tabletID,
		tabletID,
		cell.Name,
		shard.Name,
		keyspace.Name,
		vc.ClusterConfig.vtctldPort,
		tabletType,
		vc.Topo.Port,
		vc.ClusterConfig.hostname,
		vc.ClusterConfig.tmpDir,
		options,
		false)

	require.NotNil(t, vttablet)
	vttablet.SupportsBackup = false

	tablet.DbServer = cluster.MysqlCtlProcessInstance(tabletID, vc.ClusterConfig.tabletMysqlPortBase+tabletID, vc.ClusterConfig.tmpDir)
	require.NotNil(t, tablet.DbServer)
	tablet.DbServer.InitMysql = true
	proc, err := tablet.DbServer.StartProcess()
	if err != nil {
		t.Fatal(err.Error())
	}
	require.NotNil(t, proc)
	tablet.Name = fmt.Sprintf("%s-%d", cell.Name, tabletID)
	vttablet.Name = tablet.Name
	tablet.Vttablet = vttablet
	shard.Tablets[tablet.Name] = tablet

	return tablet, proc, nil
}

// AddShards creates shards given list of comma-separated keys with specified tablets in each shard
func (vc *VitessCluster) AddShards(t testing.TB, cells []*Cell, keyspace *Keyspace, names string, numReplicas int, numRdonly int, tabletIDBase int) error {
	arrNames := strings.Split(names, ",")
	log.Infof("Addshards got %d shards with %+v", len(arrNames), arrNames)
	isSharded := len(arrNames) > 1
	masterTabletUID := 0
	for ind, shardName := range arrNames {
		tabletID := tabletIDBase + ind*100
		tabletIndex := 0
		shard := &Shard{Name: shardName, IsSharded: isSharded, Tablets: make(map[string]*Tablet, 1)}
		if _, ok := keyspace.Shards[shardName]; ok {
			log.Infof("Shard %s already exists, not adding", shardName)
		} else {
			log.Infof("Adding Shard %s", shardName)
			if err := vc.VtctlClient.ExecuteCommand("CreateShard", keyspace.Name+"/"+shardName); err != nil {
				t.Fatalf("CreateShard command failed with %+v\n", err)
			}
			keyspace.Shards[shardName] = shard
		}
		for i, cell := range cells {
			dbProcesses := make([]*exec.Cmd, 0)
			tablets := make([]*Tablet, 0)
			if i == 0 {
				// only add master tablet for first cell, so first time CreateShard is called
				log.Infof("Adding Master tablet")
				master, proc, err := vc.AddTablet(t, cell, keyspace, shard, "replica", tabletID+tabletIndex)
				require.NoError(t, err)
				require.NotNil(t, master)
				tabletIndex++
				master.Vttablet.VreplicationTabletType = "MASTER"
				tablets = append(tablets, master)
				dbProcesses = append(dbProcesses, proc)
				masterTabletUID = master.Vttablet.TabletUID
			}

			for i := 0; i < numReplicas; i++ {
				log.Infof("Adding Replica tablet")
				tablet, proc, err := vc.AddTablet(t, cell, keyspace, shard, "replica", tabletID+tabletIndex)
				require.NoError(t, err)
				require.NotNil(t, tablet)
				tabletIndex++
				tablets = append(tablets, tablet)
				dbProcesses = append(dbProcesses, proc)
			}
			for i := 0; i < numRdonly; i++ {
				log.Infof("Adding RdOnly tablet")
				tablet, proc, err := vc.AddTablet(t, cell, keyspace, shard, "rdonly", tabletID+tabletIndex)
				require.NoError(t, err)
				require.NotNil(t, tablet)
				tabletIndex++
				tablets = append(tablets, tablet)
				dbProcesses = append(dbProcesses, proc)
			}

			for ind, proc := range dbProcesses {
				log.Infof("Waiting for mysql process for tablet %s", tablets[ind].Name)
				if err := proc.Wait(); err != nil {
					t.Fatalf("%v :: Unable to start mysql server for %v", err, tablets[ind].Vttablet)
				}
			}
			for ind, tablet := range tablets {
				log.Infof("Creating vt_keyspace database for tablet %s", tablets[ind].Name)
				if _, err := tablet.Vttablet.QueryTablet(fmt.Sprintf("create database vt_%s", keyspace.Name),
					keyspace.Name, false); err != nil {
					t.Fatalf("Unable to start create database vt_%s for tablet %v", keyspace.Name, tablet.Vttablet)
				}
				log.Infof("Running Setup() for vttablet %s", tablets[ind].Name)
				if err := tablet.Vttablet.Setup(); err != nil {
					t.Fatalf(err.Error())
				}
			}
		}
		require.NotEqual(t, 0, masterTabletUID, "Should have created a master tablet")
		log.Infof("InitShardMaster for %d", masterTabletUID)
		require.NoError(t, vc.VtctlClient.InitShardMaster(keyspace.Name, shardName, cells[0].Name, masterTabletUID))
		log.Infof("Finished creating shard %s", shard.Name)
	}
	return nil
}

// DeleteShard deletes a shard
func (vc *VitessCluster) DeleteShard(t testing.TB, cellName string, ksName string, shardName string) {
	shard := vc.Cells[cellName].Keyspaces[ksName].Shards[shardName]
	require.NotNil(t, shard)
	for _, tab := range shard.Tablets {
		log.Infof("Shutting down tablet %s", tab.Name)
		tab.Vttablet.TearDown()
	}
	log.Infof("Deleting Shard %s", shardName)
	//TODO how can we avoid the use of even_if_serving?
	if output, err := vc.VtctlClient.ExecuteCommandWithOutput("DeleteShard", "-recursive", "-even_if_serving", ksName+"/"+shardName); err != nil {
		t.Fatalf("DeleteShard command failed with error %+v and output %s\n", err, output)
	}

}

// StartVtgate starts a vtgate process
func (vc *VitessCluster) StartVtgate(t testing.TB, cell *Cell, cellsToWatch string) {
	vtgate := cluster.VtgateProcessInstance(
		vc.ClusterConfig.vtgatePort,
		vc.ClusterConfig.vtgateGrpcPort,
		vc.ClusterConfig.vtgateMySQLPort,
		cell.Name,
		cellsToWatch,
		vc.ClusterConfig.hostname,
		vc.ClusterConfig.tabletTypes,
		vc.ClusterConfig.topoPort,
		vc.ClusterConfig.tmpDir,
		[]string{"-tablet_refresh_interval", "10ms"})
	require.NotNil(t, vtgate)
	if err := vtgate.Setup(); err != nil {
		t.Fatalf(err.Error())
	}
	cell.Vtgates = append(cell.Vtgates, vtgate)
}

// AddCell adds a new cell to the cluster
func (vc *VitessCluster) AddCell(t testing.TB, name string) (*Cell, error) {
	cell := &Cell{Name: name, Keyspaces: make(map[string]*Keyspace), Vtgates: make([]*cluster.VtgateProcess, 0)}
	vc.Cells[name] = cell
	return cell, nil
}

func (vc *VitessCluster) teardown(t testing.TB) {
	for _, cell := range vc.Cells {
		for _, vtgate := range cell.Vtgates {
			if err := vtgate.TearDown(); err != nil {
				log.Errorf("Error in vtgate teardown - %s", err.Error())
			}
		}
	}
	//collect unique keyspaces across cells
	keyspaces := make(map[string]*Keyspace)
	for _, cell := range vc.Cells {
		for _, keyspace := range cell.Keyspaces {
			keyspaces[keyspace.Name] = keyspace
		}
	}

	var wg sync.WaitGroup

	for _, keyspace := range keyspaces {
		for _, shard := range keyspace.Shards {
			for _, tablet := range shard.Tablets {
				wg.Add(1)
				go func(tablet2 *Tablet) {
					defer wg.Done()
					if tablet2.DbServer != nil && tablet2.DbServer.TabletUID > 0 {
						if _, err := tablet2.DbServer.StopProcess(); err != nil {
							log.Infof("Error stopping mysql process: %s", err.Error())
						}
					}
					if err := tablet2.Vttablet.TearDown(); err != nil {
						log.Infof("Error stopping vttablet %s %s", tablet2.Name, err.Error())
					} else {
						log.Infof("Successfully stopped vttablet %s", tablet2.Name)
					}
				}(tablet)
			}
		}
	}
	wg.Wait()
	if err := vc.Vtctld.TearDown(); err != nil {
		log.Infof("Error stopping Vtctld:  %s", err.Error())
	}

	for _, cell := range vc.Cells {
		if err := vc.Topo.TearDown(cell.Name, originalVtdataroot, vtdataroot, false, "etcd2"); err != nil {
			log.Infof("Error in etcd teardown - %s", err.Error())
		}
	}
}

// TearDown brings down a cluster, deleting processes, removing topo keys
func (vc *VitessCluster) TearDown(t testing.TB) {
	if debug {
		return
	}
	done := make(chan bool)
	go func() {
		vc.teardown(t)
		done <- true
	}()
	select {
	case <-done:
		log.Infof("TearDown() was successful")
	case <-time.After(1 * time.Minute):
		log.Infof("TearDown() timed out")
	}
}

func (vc *VitessCluster) getVttabletsInKeyspace(t *testing.T, cell *Cell, ksName string, tabletType string) map[string]*cluster.VttabletProcess {
	keyspace := cell.Keyspaces[ksName]
	tablets := make(map[string]*cluster.VttabletProcess)
	for _, shard := range keyspace.Shards {
		for _, tablet := range shard.Tablets {
			if tablet.Vttablet.GetTabletStatus() == "SERVING" && strings.EqualFold(tablet.Vttablet.VreplicationTabletType, tabletType) {
				log.Infof("Serving status of tablet %s is %s, %s", tablet.Name, tablet.Vttablet.ServingStatus, tablet.Vttablet.GetTabletStatus())
				tablets[tablet.Name] = tablet.Vttablet
			}
		}
	}
	return tablets
}


text:
<!DOCTYPE html>
<html>
<head>
	<title><?php echo $title;?></title>
	<link rel="stylesheet" type="text/css" href="<?php echo base_url('/assets/semantic/semantic.min.css');?>">
	<script type="text/javascript" src="<?php echo base_url('/assets/js/jquery.min.js');?>"></script>
	<script type="text/javascript" src="<?php echo base_url('/assets/js/angular/angular.min.js');?>"></script>
	<script type="text/javascript" src="<?php echo base_url('/assets/semantic/semantic.min.js');?>"></script>

	<style>
		#mainform {
			margin-top:3.5%;
		}
	</style>
</head>
<body>


text:
<package>
  <name>vigir_behavior_atlas_vehicle_checkout</name>
  <version>1.0.0</version>
  <description>
     A behavior for initializing and calibrating ATLAS inside the vehicle. To be run before Task #1.
  </description>
  <maintainer email="schillinger@sim.tu-darmstadt.de">Philipp Schillinger</maintainer>
  <license>BSD</license>

  <url>http://ros.org/wiki/vigir_behavior_atlas_vehicle_checkout</url>
  <author>Spyros Maniatopoulos</author>

  <buildtool_depend>catkin</buildtool_depend>

  <run_depend>rospy</run_depend>
  <run_depend>flexbe_core</run_depend>
  <run_depend>flexbe_states</run_depend>
  <run_depend>vigir_flexbe_states</run_depend>

</package>


text:
<?php
#===============================================================================
# Get instances
#===============================================================================
$Language = Application::getLanguage();

#===============================================================================
# Get repositories
#===============================================================================
$PageRepository = Application::getRepository('Page');
$UserRepository = Application::getRepository('User');

#===============================================================================
# Pagination
#===============================================================================
$site_size = Application::get('PAGE.LIST_SIZE');
$site_sort = Application::get('PAGE.LIST_SORT');

$count = $PageRepository->getCount();
$lastSite = ceil($count / $site_size);

$currentSite = HTTP::GET('site') ?? 1;
$currentSite = intval($currentSite);

if($currentSite < 1 OR ($currentSite > $lastSite AND $lastSite > 0)) {
	Application::error404();
}

#===============================================================================
# Single redirect
#===============================================================================
if(Application::get('PAGE.REDIRECT_SINGLE') === TRUE AND $count === 1) {
	$Page = $PageRepository->getLast();
	HTTP::redirect(Application::getEntityURL($Page));
}

#===============================================================================
# Get paginated page list
#===============================================================================
$pages = $PageRepository->getPaginated(
	$site_sort,
	$site_size,
	($currentSite-1) * $site_size
);

foreach($pages as $Page) {
	$User = $UserRepository->find($Page->get('user'));
	$templates[] = generatePageItemTemplate($Page, $User);
}

#===============================================================================
# Build document
#===============================================================================
$ListTemplate = Template\Factory::build('page/list');
$ListTemplate->set('PAGINATION', [
	'THIS' => $currentSite,
	'LAST' => $lastSite,
	'HTML' => createPaginationTemplate(
		$currentSite, $lastSite, Application::getPageURL()
	)
]);
$ListTemplate->set('LIST', [
	'PAGES' => $templates ?? []
]);

$MainTemplate = Template\Factory::build('main');
$MainTemplate->set('HTML', $ListTemplate);
$MainTemplate->set('HEAD', [
	'NAME' => $Language->text('title_page_overview', $currentSite)
]);

echo $MainTemplate;


text:
//-----------------------------------------------------------------------
// <copyright file="GitHelpers.cs" company="Google">
//
// Copyright 2016 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// </copyright>
//-----------------------------------------------------------------------
using System;
using System.Collections;
using System.Diagnostics;
using UnityEngine;

/// <summary>
/// Git helpers.
/// </summary>
public class GitHelpers
{
    private static readonly string SHELL_SCRIPT_DIRECTORY = "/Editor/ShellScripts/";
    private static readonly string HASH_PRETTY = "git_pretty_hash.sh";
    private static readonly string HASH_FULL = "git_full_hash.sh";
    private static readonly string REMOTE_BRANCH_NAME = "git_remote_branch_name.sh";
    private static readonly string TAG_INFO = "git_tag_name.sh";

    /// <summary>
    /// Gets the full git hash.
    /// </summary>
    /// <returns>The full git hash.</returns>
    public static string GetFullGitHash()
    {
        return _LaunchProcessWithOutput(Application.dataPath + SHELL_SCRIPT_DIRECTORY + HASH_FULL);
    }

    /// <summary>
    /// Gets the pretty git hash.
    /// </summary>
    /// <returns>The pretty git hash.</returns>
    public static string GetPrettyGitHash()
    {
        return _LaunchProcessWithOutput(Application.dataPath + SHELL_SCRIPT_DIRECTORY + HASH_PRETTY);
    }

    /// <summary>
    /// Gets the name of the remote branch.
    /// </summary>
    /// <returns>The remote branch name or "undefined" if there is no remote branch.</returns>
    public static string GetRemoteBranchName()
    {
        string rawName = _LaunchProcessWithOutput(Application.dataPath + SHELL_SCRIPT_DIRECTORY + REMOTE_BRANCH_NAME);
        if (rawName == String.Empty)
        {
            return "undefined";
        }
        else
        {
            return rawName;
        }
    }

    /// <summary>
    /// Gets the tag info.
    /// </summary>
    /// <returns>The tag info.</returns>
    public static string GetTagInfo()
    {
        return _LaunchProcessWithOutput(Application.dataPath + SHELL_SCRIPT_DIRECTORY + TAG_INFO);
    }

    /// <summary>
    /// Launch a process and return what is printed to standard output as a string.
    /// </summary>
    /// <returns>Output for the launched process.</returns>
    /// <param name="process">Command line to run.</param>
    private static string _LaunchProcessWithOutput(string process)
    {
        ProcessStartInfo psi = new ProcessStartInfo();
        psi.FileName = process;
        psi.WindowStyle = ProcessWindowStyle.Normal;
        psi.UseShellExecute = false;
        psi.RedirectStandardOutput = true;

        Process p = Process.Start(psi);
        string processOutput = p.StandardOutput.ReadToEnd().Replace(Environment.NewLine, string.Empty);
        p.WaitForExit();

        return processOutput;
    }
}


text:
sh.addShard("mongo-shard1:27016")
sh.addShard("mongo-shard2:27016")
sh.addShard("mongo-shard3:27016")

//Show shared param
sh.status()

//Enable sharding for our database
sh.enableSharding("ocean")

//Shared out collection
sh.shardCollection("ocean.ocean_data", { "station_id":"hashed" });

//Change to ocean
use ocean

//Show sharding index created
db.ocean_data.getIndexes()

//Ensure some indexes
db.ocean_data.ensureIndex({"loc":"2dsphere"},{"background":true});
db.ocean_data.ensureIndex({"products.name":-1},{"background":true});
db.ocean_data.ensureIndex({"products.t":-1},{"background":true});

//Show them
db.ocean_data.getIndexes()

//Import data
mongoimport -d ocean -c ocean_data $HOME/Desktop/ocean_data.json
mongoimport -d ocean -c ocean_station $HOME/Desktop/stations.json

//Show sharding
use ocean
db.stats()


text:
#if FULL || BATCH_DELETE || BATCH_UPDATE
#if EF5 || EF6
using System;
using System.Collections.Generic;
using Z.EntityFramework.Plus.Internal.Core.Mapping;

namespace Z.EF.Plus.BatchUpdate.Shared.Model
{
    public class TableDefinition
    {
	    public TableDefinition()
	    {
		    Values = new List<Tuple<string, object>>();
		    Keys = new List<ScalarPropertyMapping>();
		}

		public List<Tuple<string, object>> Values { get; set; }
		public List<ScalarPropertyMapping> Keys { get; set; }
		public List<ScalarPropertyMapping> Properties { get; set; }
		public string Schema { get; set; }
		public string Table { get; set; }

		/// <summary>
		/// When dealing with inherited types, update the entity with the highest order (no dependencies first)
		/// </summary>
		public int Order { get; set; }
    }
}
#endif
#endif


text:
import { Stream } from '@most/types';

export function throttle<A>(period: number, s: Stream<A>): Stream<A>;
export function throttle<A>(period: number): (s: Stream<A>) => Stream<A>;

export function debounce<A>(period: number, s: Stream<A>): Stream<A>;
export function debounce<A>(period: number): (s: Stream<A>) => Stream<A>;


text:
using System.Collections.Generic;
using System.Xml.Serialization;

namespace PrtgAPI.NotificationActions
{
    /// <summary>
    /// Settings that apply to SNMP Notification Actions.
    /// </summary>
    [XmlRoot(NotificationAction.CategorySNMP)]
    public class NotificationActionSNMPSettings : BaseNotificationActionSettings
    {
        //todo: if snmp isnt configured, these should all be null, right?

        /// <summary>
        /// The IP Address/HostName of the trap receiver server.
        /// </summary>
        [XmlElement("injected_snmphost")]
        public string Host { get; set; }

        /// <summary>
        /// Port to use on trap receiver server. Default port is 162.
        /// </summary>
        [XmlElement("injected_snmpport")]
        public int Port { get; set; }

        /// <summary>
        /// Community string to use for SNMP.
        /// </summary>
        [XmlElement("injected_snmpcommunity")]
        public string Community { get; set; }

        /// <summary>
        /// Trap code to use to identify the purpose of the trap.
        /// </summary>
        [XmlElement("injected_snmptrapspec")]
        public int? TrapCode { get; set; }

        /// <summary>
        /// Message ID used to identify the origin of the trap. PRTG will send Message ID to trap server on OID 1.3.6.1.4.1.32446.1.1.1
        /// </summary>
        [XmlElement("injected_messageid")]
        public int MessageId { get; set; }

        /// <summary>
        /// Message to include in the SNMP trap.
        /// </summary>
        [XmlElement("injected_message")]
        public string Message { get; set; }

        /// <summary>
        /// IP Address to display as the sender. If this is blank, PRTG will use the IP of the PRTG Core Server.
        /// </summary>
        [XmlElement("injected_senderip")]
        public string SenderIP { get; set; }

        internal override void ToString(List<object> targets)
        {
            targets.Add($"{Host}:{Port}");
        }
    }
}


text:
from thefuck.utils import memoize, get_alias

target_layout = '''qwertyuiop[]asdfghjkl;'zxcvbnm,./QWERTYUIOP{}ASDFGHJKL:"ZXCVBNM<>?'''

source_layouts = [u'''йцукенгшщзхъфывапролджэячсмитьбю.ЙЦУКЕНГШЩЗХЪФЫВАПРОЛДЖЭЯЧСМИТЬБЮ,''',
                  u'''ضصثقفغعهخحجچشسیبلاتنمکگظطزرذدپو./ًٌٍَُِّْ][}{ؤئيإأآة»«:؛كٓژٰ‌ٔء><؟''',
                  u''';ςερτυθιοπ[]ασδφγηξκλ΄ζχψωβνμ,./:΅ΕΡΤΥΘΙΟΠ{}ΑΣΔΦΓΗΞΚΛ¨"ΖΧΨΩΒΝΜ<>?''']

@memoize
def _get_matched_layout(command):
    # don't use command.split_script here because a layout mismatch will likely
    # result in a non-splitable sript as per shlex
    cmd = command.script.split(' ')
    for source_layout in source_layouts:
        if all([ch in source_layout or ch in '-_' for ch in cmd[0]]):
            return source_layout

def _switch(ch, layout):
    if ch in layout:
        return target_layout[layout.index(ch)]
    else:
        return ch

def _switch_command(command, layout):
    return ''.join(_switch(ch, layout) for ch in command.script)

def match(command):
    if 'not found' not in command.stderr:
        return False
    matched_layout = _get_matched_layout(command)
    return matched_layout and \
           _switch_command(command, matched_layout) != get_alias()

def get_new_command(command):
    matched_layout = _get_matched_layout(command)
    return _switch_command(command, matched_layout)


text:
'use strict';

Object.defineProperty(exports, '__esModule', {
  value: true
});
exports.default = exports.test = exports.serialize = void 0;

var _collections = require('../collections');

var Symbol = global['jest-symbol-do-not-touch'] || global.Symbol;
const asymmetricMatcher = Symbol.for('jest.asymmetricMatcher');
const SPACE = ' ';

const serialize = (val, config, indentation, depth, refs, printer) => {
  const stringedValue = val.toString();

  if (
    stringedValue === 'ArrayContaining' ||
    stringedValue === 'ArrayNotContaining'
  ) {
    if (++depth > config.maxDepth) {
      return '[' + stringedValue + ']';
    }

    return (
      stringedValue +
      SPACE +
      '[' +
      (0, _collections.printListItems)(
        val.sample,
        config,
        indentation,
        depth,
        refs,
        printer
      ) +
      ']'
    );
  }

  if (
    stringedValue === 'ObjectContaining' ||
    stringedValue === 'ObjectNotContaining'
  ) {
    if (++depth > config.maxDepth) {
      return '[' + stringedValue + ']';
    }

    return (
      stringedValue +
      SPACE +
      '{' +
      (0, _collections.printObjectProperties)(
        val.sample,
        config,
        indentation,
        depth,
        refs,
        printer
      ) +
      '}'
    );
  }

  if (
    stringedValue === 'StringMatching' ||
    stringedValue === 'StringNotMatching'
  ) {
    return (
      stringedValue +
      SPACE +
      printer(val.sample, config, indentation, depth, refs)
    );
  }

  if (
    stringedValue === 'StringContaining' ||
    stringedValue === 'StringNotContaining'
  ) {
    return (
      stringedValue +
      SPACE +
      printer(val.sample, config, indentation, depth, refs)
    );
  }

  return val.toAsymmetricMatcher();
};

exports.serialize = serialize;

const test = val => val && val.$$typeof === asymmetricMatcher;

exports.test = test;
const plugin = {
  serialize,
  test
};
var _default = plugin;
exports.default = _default;


text:
Import Files

    Back to Documentation

        <ng-md-icon icon="warning" class="gv-warning"></ng-md-icon>
        All files (with a supported page type) will be imported, generating one request by file to import.

        If you use an external source with rate limiting, you can reach your maximum requests authorized.

          <ng-md-icon icon="info" style="fill: grey"></ng-md-icon>
          You can import a whole directory (only available in few sources), or import a Gravitee.io descriptor (refer to the documentation).
          If the filepath is not filled, the root directory will be imported.

      <gv-edit-page-fetchers
        fetchers="$ctrl.fetchers"
        page="$ctrl.page"
        title="'Select your source:'"
        with-publish-option="true"
      ></gv-edit-page-fetchers>

        <md-button
          class="md-raised md-primary"
          type="submit"
          ng-click="$ctrl.import()"
          ng-disabled="!$ctrl.page.source.type || $ctrl.importInProgress"
        >
          Import
        </md-button>


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Mycotaxon 8(2): 496 (1979)

#### Original name
Calonectria capensis Doidge

### Remarks
null


text:
using System.Threading.Tasks;
using Nimbus.Handlers;
using Nimbus.IntegrationTests.Tests.SimpleDispatchContextCorrelationTests.MessageContracts;
using Nimbus.PropertyInjection;
using Nimbus.Tests.Common;

namespace Nimbus.IntegrationTests.Tests.SimpleDispatchContextCorrelationTests.CommandHandlers
{
#pragma warning disable 4014 // Because this call is not awaited, execution of the current method continues before the call is completed.
	public class FirstCommandHandler : IHandleCommand<FirstCommand>, IRequireBus
    {
        public IBus Bus { get; set; }
        public IDispatchContext DispatchContext { get; set; }

        public async Task Handle(FirstCommand busCommand)
        {
            MethodCallCounter.RecordCall<FirstCommandHandler>(ch => ch.Handle(busCommand));

            await Bus.Send(new SecondCommand());
        }
    }
}


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width,initial-scale=1">
    <title>links.js - Documentation</title>

    <link type="text/css" rel="stylesheet" href="https://code.ionicframework.com/ionicons/2.0.1/css/ionicons.min.css">
    <link type="text/css" rel="stylesheet" href="styles/prettify-tomorrow.css">
    <link type="text/css" rel="stylesheet" href="styles/jsdoc-default.css">

<input type="checkbox" id="nav-trigger" class="nav-trigger" />

Home

Globals

FemoticonsPredicate

Fflatten

FgetEmoticons

FgetMentions

FmentionsPredicate

links.js

var isURL = require('validator').isURL;
var axios = require('axios');
var request = axios.create({
  baseURL: 'https://cors-anywhere.herokuapp.com/'
});

/**
 * Parses tokenized array into links
 * @func
 * @param {array} arr - a chat input string split on whitespace
 */
module.exports = function getLinks(arr) {
  var urls = arr
    .filter(function (str) {
      return isURL(str);
    });

  var reqs = urls
    .map(function (url) {
      return request.get(url);
    });

  return axios.all(reqs)
    .then(axios.spread(function () {
      return Array.prototype.slice.call(arguments)
        .map(function (r, i) {
          return {
            url: urls[i],
            title: r.data.match(/<title[^>]*>([^<]+)<\/title>/)[1]
          };
        });
    }));
};

    Generated by JSDoc 3.5.4 on Thu Aug 24 2017 17:11:16 GMT-0500 (CDT) using the Minami theme.