text:
package floatgeom

import (
	"math"

	"github.com/oakmound/oak/v4/alg"
)

// Point2 represents a 2D point on a plane.
type Point2 [2]float64

// Point3 represents a 3D point in space.
type Point3 [3]float64

// Point4 represents a 4D point, in space + some additional dimension.
type Point4 [4]float64

// AnglePoint creates a unit vector from the given angle in degrees as a Point2.
func AnglePoint(angle float64) Point2 {
	return RadianPoint(angle * alg.DegToRad)
}

// RadianPoint creates a unit vector from the given angle in radians as a Point2.
func RadianPoint(radians float64) Point2 {
	return Point2{math.Cos(radians), math.Sin(radians)}
}

// Dim returns the value of p in the ith dimension.
// Panics if i > 1.
func (p Point2) Dim(i int) float64 {
	return p[i]
}

// Dim returns the value of p in the ith dimension.
// Panics if i > 2.
func (p Point3) Dim(i int) float64 {
	return p[i]
}

// Dim returns the value of p in the ith dimension.
// Panics if i > 3.
func (p Point4) Dim(i int) float64 {
	return p[i]
}

// X returns p's value on the X axis.
func (p Point2) X() float64 {
	return p.Dim(0)
}

// Y returns p's value on the Y axis.
func (p Point2) Y() float64 {
	return p.Dim(1)
}

// X returns p's value on the X axis.
func (p Point3) X() float64 {
	return p.Dim(0)
}

// Y returns p's value on the Y axis.
func (p Point3) Y() float64 {
	return p.Dim(1)
}

// Z returns p's value on the Z axis.
func (p Point3) Z() float64 {
	return p.Dim(2)
}

// W returns p's value on the W axis.
func (p Point4) W() float64 {
	return p.Dim(0)
}

// X returns p's value on the X axis.
func (p Point4) X() float64 {
	return p.Dim(1)
}

// Y returns p's value on the Y axis.
func (p Point4) Y() float64 {
	return p.Dim(2)
}

// Z returns p's value on the Z axis.
func (p Point4) Z() float64 {
	return p.Dim(3)
}

// Distance calculates the distance between this Point2 and another.
func (p Point2) Distance(p2 Point2) float64 {
	return Distance2(p.X(), p.Y(), p2.X(), p2.Y())
}

// Distance calculates the distance between this Point3 and another.
func (p Point3) Distance(p2 Point3) float64 {
	return Distance3(p.X(), p.Y(), p.Z(), p2.X(), p2.Y(), p2.Z())
}

// Distance2 calculates the euclidean distance between two points, as two (x,y) pairs
func Distance2(x1, y1, x2, y2 float64) float64 {
	return math.Sqrt(
		math.Pow(x1-x2, 2) +
			math.Pow(y1-y2, 2))
}

// Distance3 calculates the euclidean distance between two points, as two (x,y,z) triplets
func Distance3(x1, y1, z1, x2, y2, z2 float64) float64 {
	return math.Sqrt(
		math.Pow(x1-x2, 2) +
			math.Pow(y1-y2, 2) +
			math.Pow(z1-z2, 2))
}

// LesserOf returns the lowest values on each axis of the input points as a point.
func (p Point2) LesserOf(ps ...Point2) Point2 {
	for _, p2 := range ps {
		p[0] = math.Min(p[0], p2[0])
		p[1] = math.Min(p[1], p2[1])
	}
	return p
}

// LesserOf returns the lowest values on each axis of the input points as a point.
func (p Point3) LesserOf(ps ...Point3) Point3 {
	for _, p2 := range ps {
		p[0] = math.Min(p[0], p2[0])
		p[1] = math.Min(p[1], p2[1])
		p[2] = math.Min(p[2], p2[2])
	}
	return p
}

// GreaterOf returns the highest values on each axis of the input points as a point.
func (p Point2) GreaterOf(ps ...Point2) Point2 {
	for _, p2 := range ps {
		p[0] = math.Max(p[0], p2[0])
		p[1] = math.Max(p[1], p2[1])
	}
	return p
}

// GreaterOf returns the highest values on each axis of the input points as a point.
func (p Point3) GreaterOf(ps ...Point3) Point3 {
	for _, p2 := range ps {
		p[0] = math.Max(p[0], p2[0])
		p[1] = math.Max(p[1], p2[1])
		p[2] = math.Max(p[2], p2[2])
	}
	return p
}

// Add combines the input points via addition.
func (p Point2) Add(ps ...Point2) Point2 {
	for _, p2 := range ps {
		p[0] += p2[0]
		p[1] += p2[1]
	}
	return p
}

// Sub combines the input points via subtraction.
func (p Point2) Sub(ps ...Point2) Point2 {
	for _, p2 := range ps {
		p[0] -= p2[0]
		p[1] -= p2[1]
	}
	return p
}

// Mul combines in the input points via multiplication.
func (p Point2) Mul(ps ...Point2) Point2 {
	for _, p2 := range ps {
		p[0] *= p2[0]
		p[1] *= p2[1]
	}
	return p
}

// MulConst multiplies all elements of a point by the input floats
func (p Point2) MulConst(fs ...float64) Point2 {
	for _, f := range fs {
		p[0] *= f
		p[1] *= f
	}
	return p
}

// Cross gets the cross product of two Point 3s
func (p Point3) Cross(p2 Point3) Point3 {
	return Point3{p.Y()*p2.Z() - p.Z()*p2.Y(), p.Z()*p2.X() - p.X()*p2.Z(), p.X()*p2.Y() - p.Y()*p2.X()}
}

// Div combines the input points via division.
// Div does not check that the inputs are non zero before operating,
// and can panic if that is not true.
func (p Point2) Div(ps ...Point2) Point2 {
	for _, p2 := range ps {
		p[0] /= p2[0]
		p[1] /= p2[1]
	}
	return p
}

// DivConst divides all elements of a point by the input floats
// DivConst does not check that the inputs are non zero before operating,
// and can panic if that is not true.
func (p Point2) DivConst(fs ...float64) Point2 {
	for _, f := range fs {
		p[0] /= f
		p[1] /= f
	}
	return p
}

// Add combines the input points via addition.
func (p Point3) Add(ps ...Point3) Point3 {
	for _, p2 := range ps {
		p[0] += p2[0]
		p[1] += p2[1]
		p[2] += p2[2]
	}
	return p
}

// Sub combines the input points via subtraction.
func (p Point3) Sub(ps ...Point3) Point3 {
	for _, p2 := range ps {
		p[0] -= p2[0]
		p[1] -= p2[1]
		p[2] -= p2[2]
	}
	return p
}

// Mul combines in the input points via multiplication.
func (p Point3) Mul(ps ...Point3) Point3 {
	for _, p2 := range ps {
		p[0] *= p2[0]
		p[1] *= p2[1]
		p[2] *= p2[2]
	}
	return p
}

// MulConst multiplies all elements of a point by the input floats
func (p Point3) MulConst(fs ...float64) Point3 {
	for _, f := range fs {
		p[0] *= f
		p[1] *= f
		p[2] *= f
	}
	return p
}

// Div combines the input points via division.
// Div does not check that the inputs are non zero before operating,
// and can panic if that is not true.
func (p Point3) Div(ps ...Point3) Point3 {
	for _, p2 := range ps {
		p[0] /= p2[0]
		p[1] /= p2[1]
		p[2] /= p2[2]
	}
	return p
}

// DivConst divides all elements of a point by the input floats
// DivConst does not check that the inputs are non zero before operating,
// and can panic if that is not true.
func (p Point3) DivConst(fs ...float64) Point3 {
	for _, f := range fs {
		p[0] /= f
		p[1] /= f
		p[2] /= f
	}
	return p
}

// MulConst multiplies all elements of a point by the input floats
func (p Point4) MulConst(fs ...float64) Point4 {
	for _, f := range fs {
		p[0] *= f
		p[1] *= f
		p[2] *= f
		p[3] *= f
	}
	return p
}

// DivConst divides all elements of a point by the input floats
// DivConst does not check that the inputs are non zero before operating,
// and can panic if that is not true.
func (p Point4) DivConst(fs ...float64) Point4 {
	for _, f := range fs {
		p[0] /= f
		p[1] /= f
		p[2] /= f
		p[3] /= f
	}
	return p
}

// Dot returns the dot product of the input points
func (p Point2) Dot(p2 Point2) float64 {
	return p[0]*p2[0] + p[1]*p2[1]
}

// Dot returns the dot product of the input points
func (p Point3) Dot(p2 Point3) float64 {
	return p[0]*p2[0] + p[1]*p2[1] + p[2]*p2[2]
}

// Dot returns the dot product of the input points
func (p Point4) Dot(p2 Point4) float64 {
	return p[0]*p2[0] + p[1]*p2[1] + p[2]*p2[2] + p[3]*p2[3]
}

// Magnitude returns the magnitude of the combined components of a Point
func (p Point2) Magnitude() float64 {
	return math.Sqrt(p.Dot(p))
}

// Magnitude returns the magnitude of the combined components of a Point
func (p Point3) Magnitude() float64 {
	return math.Sqrt(p.Dot(p))
}

// Magnitude returns the magnitude of the combined components of a Point
func (p Point4) Magnitude() float64 {
	return math.Sqrt(p.Dot(p))
}

// Normalize converts this point into a unit vector.
func (p Point2) Normalize() Point2 {
	mgn := p.Magnitude()
	if mgn == 0 {
		return p
	}
	return p.DivConst(mgn)
}

// Normalize converts this point into a unit vector.
func (p Point3) Normalize() Point3 {
	mgn := p.Magnitude()
	if mgn == 0 {
		return p
	}
	return p.DivConst(mgn)
}

// Normalize converts this point into a unit vector.
func (p Point4) Normalize() Point4 {
	mgn := p.Magnitude()
	if mgn == 0 {
		return p
	}
	return p.DivConst(mgn)
}

// Rotate takes in a set of angles and rotates v by their sum
// the input angles are expected to be in degrees.
func (p Point2) Rotate(fs ...float64) Point2 {
	angle := 0.0
	for _, f := range fs {
		angle += f
	}
	mgn := p.Magnitude()
	angle = p.ToRadians() + (angle * alg.DegToRad)

	return Point2{math.Cos(angle) * mgn, math.Sin(angle) * mgn}
}

// RotateRadians takes in a set of angles and rotates v by their sum
// the input angles are expected to be in radians.
func (p Point2) RotateRadians(fs ...float64) Point2 {
	angle := p.ToRadians()
	for _, f := range fs {
		angle += f
	}
	mgn := p.Magnitude()

	return Point2{math.Cos(angle) * mgn, math.Sin(angle) * mgn}
}

// ToRect converts this point into a rectangle spanning span distance
// in each axis.
func (p Point2) ToRect(span float64) Rect2 {
	return NewRect2WH(p[0], p[1], span, span)
}

// ToRect converts this point into a rectangle spanning span distance
// in each axis.
func (p Point3) ToRect(span float64) Rect3 {
	return NewRect3WH(p[0], p[1], p[2], span, span, span)
}

// ProjectX projects the Point3 onto the x axis, removing it's
// x component and returning a Point2
func (p Point3) ProjectX() Point2 {
	return Point2{p[1], p[2]}
}

// ProjectY projects the Point3 onto the y axis, removing it's
// y component and returning a Point2
func (p Point3) ProjectY() Point2 {
	return Point2{p[0], p[2]}
}

// ProjectZ projects the Point3 onto the z axis, removing it's
// z component and returning a Point2
func (p Point3) ProjectZ() Point2 {
	return Point2{p[0], p[1]}
}

// ToAngle returns this point as an angle in degrees.
func (p Point2) ToAngle() float64 {
	return p.ToRadians() * alg.RadToDeg
}

// ToRadians returns this point as an angle in radians.
func (p Point2) ToRadians() float64 {
	return math.Atan2(p[1], p[0])
}

// AngleTo returns the angle from p to p2 in degrees.
func (p Point2) AngleTo(p2 Point2) float64 {
	return p.Sub(p2).ToAngle()
}

// RadiansTo returns the angle from p to p2 in radians.
func (p Point2) RadiansTo(p2 Point2) float64 {
	return p.Sub(p2).ToRadians()
}

// Conjugate returns a value of a Point4 often obtained to calculate the inverse
func (p Point4) Conjugate() Point4 {
	return Point4{
		p[0],
		-1 * p[1],
		-1 * p[2],
		-1 * p[3],
	}
}

// Inverse of a Point4, often used to get the inverse rotation of a quaternion
func (p Point4) Inverse() Point4 {
	cng := p.Conjugate()
	return cng.Normalize()
}

// MulQuat multiplies two quaternions to generate a combined quarternion that represents both rotations
// ref: https://www.mathworks.com/help/aeroblks/quaternionmultiplication.html
func (p Point4) MulQuat(p2 Point4) Point4 {
	return Point4{
		p2[0]*p[0] - p2[1]*p[1] - p2[2]*p[2] - p2[3]*p[3],
		p2[0]*p[1] + p2[1]*p[0] - p2[2]*p[3] + p2[3]*p[2],
		p2[0]*p[2] + p2[1]*p[3] + p2[2]*p[0] - p2[3]*p[1],
		p2[0]*p[3] - p2[1]*p[2] + p2[2]*p[1] + p2[3]*p[0],
	}
}


text:
using System;
using System.IO;
using Microsoft.TeamFoundation.Client;
using Microsoft.TeamFoundation.Server;
using GitTfs.VsCommon;
using StructureMap;
using GitTfs.Core.TfsInterop;

namespace GitTfs.Vs2010
{
    public class TfsHelper : TfsHelperBase
    {
        public TfsHelper(TfsApiBridge bridge, IContainer container) : base(bridge, container)
        {
        }

        private string vsInstallDir;
        protected override string GetVsInstallDir()
        {
            if (vsInstallDir == null)
            {
                vsInstallDir = TryGetRegString(@"Software\Microsoft\VisualStudio\10.0", "InstallDir")
                    ?? TryGetRegString(@"Software\WOW6432Node\Microsoft\VisualStudio\10.0", "InstallDir");
            }
            return vsInstallDir;
        }

        private IGroupSecurityService GroupSecurityService
        {
            get { return GetService<IGroupSecurityService>(); }
        }

        public override IIdentity GetIdentity(string username)
        {
            return _bridge.Wrap<WrapperForIdentity, Identity>(Retry.Do(() => GroupSecurityService.ReadIdentity(SearchFactor.AccountName, username, QueryMembership.None)));
        }

        protected override TfsTeamProjectCollection GetTfsCredential(Uri uri)
        {
            return HasCredentials ?
                    new TfsTeamProjectCollection(uri, GetCredential(), new UICredentialsProvider()) :
                    new TfsTeamProjectCollection(uri, new UICredentialsProvider());
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
package mysqltest

import (
	"bytes"
	"database/sql"
	"fmt"
	"net"
	"os"
	"os/exec"
	"time"
)

type MysqldConfig struct {
	Tag     string
	Timeout time.Duration
}

func NewMysqldConfig() *MysqldConfig {
	return &MysqldConfig{
		Tag:     "mysql:latest",
		Timeout: 30,
	}
}

type Mysqld struct {
	port      string
	host      string
	config    *MysqldConfig
	container string
}

func NewMysqld(config *MysqldConfig) (*Mysqld, error) {
	if config == nil {
		config = NewMysqldConfig()
	}
	mysqld := &Mysqld{
		config: config,
	}
	if err := mysqld.start(); err != nil {
		return nil, err
	}
	return mysqld, nil
}

func (m *Mysqld) DSN() string {
	return fmt.Sprintf("%s@tcp(%s:%s)/%s", "root", m.host, m.port, "test")
}

func (m *Mysqld) Stop() {
	killCointainer(m.container)
	removeContainer(m.container)
}

func (m *Mysqld) start() error {
	cmd, port, err := m.dockerRunCommand()
	if err != nil {
		return err
	}
	_container, err := cmd.Output()
	container := string(chomp(_container))
	if err != nil {
		return err
	}

	m.container = container
	m.port = port

	if inDockerContainer() {
		o, err := exec.Command("docker", "inspect", "--format={{range .NetworkSettings.Networks}}{{.IPAddress}}{{end}}", m.container).Output()
		if err != nil {
			return err
		}
		m.host = string(chomp(o))
	} else {
		m.host = "127.0.0.1"
	}

	timeout := time.NewTimer(time.Second * m.config.Timeout)
	connect := time.NewTicker(time.Second)
	dsn := m.DSN()

	for {
		select {
		case <-timeout.C:
			killCointainer(container)
			removeContainer(container)
			return fmt.Errorf("timeout: failed to connect mysqld")
		case <-connect.C:
			db, err := sql.Open("mysql", dsn)
			if err != nil {
				return err
			}
			if err := db.Ping(); err != nil {
				continue
			}
			return nil
		}
	}
}

func (m *Mysqld) dockerRunCommand() (*exec.Cmd, string, error) {
	var args = []string{"run"}
	var port string
	if inDockerContainer() {
		o, err := exec.Command("docker", "inspect", "--format={{.HostConfig.NetworkMode}}", os.Getenv("HOSTNAME")).Output()
		if err != nil {
			return nil, "", err
		}
		network := chomp(o)
		args = append(args, "--network", string(network))
		port = "3306"
	} else {
		forward, err := emptyPort()
		if err != nil {
			return nil, "", err
		}
		args = append(args, "-p", fmt.Sprintf("%s:3306", forward))
		port = forward
	}
	args = append(args, "-e", "MYSQL_ALLOW_EMPTY_PASSWORD=1")
	args = append(args, "-e", "MYSQL_DATABASE=test")
	args = append(args, "-d", m.config.Tag)
	return exec.Command("docker", args...), port, nil
}

func inDockerContainer() bool {
	_, err := os.Stat("/.dockerenv")
	return err == nil
}

func killCointainer(id string) error {
	return exec.Command("docker", "kill", id).Run()
}

func removeContainer(id string) error {
	return exec.Command("docker", "rm", "-v", id).Run()
}

func emptyPort() (string, error) {
	l, err := net.Listen("tcp", "127.0.0.1:0")
	if err != nil {
		return "", err
	}
	_, port, err := net.SplitHostPort(l.Addr().String())
	if err != nil {
		return "", err
	}
	l.Close()
	return port, nil
}

func chomp(v []byte) []byte {
	return bytes.TrimRight(v, "\n")
}


text:
github-clone
============

clone github repositories to the local box.

> __Or in layman's terms -__ it clones all your github repositories to a computer and updates ones that were already there. with one command. fastly.

## How?

you can just `npm install github-clone -g` and then `github-clone --directory <dir> --access_token <token>`.
this installs an alias to the command into the system's path, meaning you can run `github-clone` from anywhere.

on windows, I schedule a task such that it calls `%APPDATA%/npm/github-clone.cmd` with `--access_token <token>` as an argument. I specify the directory i want them cloned into, as the working directory.

## Examples

you can use a json or yaml configuration file (and call `github-clone --config path/to/config`)
```
{
  directory: "path/to/clone/into",
  repositories: {
    type: "public",
    sort: "updated"
  },
  access_token: "token"
}
```

# A bit more info..

the __repositories object__ contains a type and a sort, as defined by [the github repo](http://developer.github.com/v3/repos).
the __directory key__ specifies a path to the directory in wich we wanna clone all your repositories.
the __access_token key__ specifies a personal access token from [here](https://github.com/settings/tokens/new).

you can use cron or scheduled tasks to make this happen at a regular interval, which is good fun.


text:
using System;
using System.IO;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;

using C1.WPF.FlexGrid;

namespace Memento.Component.WPF.C1FlexGridExt
{
    public class TreeCellFactory : CellFactory
    {
        #region 成员变量

        internal static Thickness _tEmpty = new Thickness(0);
        internal static BitmapImage _bmpCollapsed, _bmpExpanded, _bmpNoChildren;
        internal static Brush _connBrush = new SolidColorBrush(Color.FromArgb(0xff, 0xc0, 0xc0, 0xc0));
        internal const double _connThickness = 1.5;

        #endregion

        public TreeCellFactory()
        {
            // load bitmaps (once)
            if (_bmpCollapsed == null)
            {
                _bmpCollapsed = LoadBitmap("collapsed.png");
                _bmpExpanded = LoadBitmap("expanded.png");
                _bmpNoChildren = null;// LoadBitmap("nochildren.png");
            }
        }

        public override void CreateCellContent(C1FlexGrid grid, Border bdr, CellRange rng)
        {
            base.CreateCellContent(grid, bdr, rng);

            var row = grid.Rows[rng.Row] as GroupRow;
            if (rng.Column == 0 && row != null)
            {
                bdr.Padding = _tEmpty;
                var cellGrid = bdr.Child as Grid;
                cellGrid.Children.RemoveAt(0);
                var treeNode = CreateTreeNode(grid, row);
                cellGrid.Children.Add(treeNode);
            }
        }

        // creates the element that represents a tree node
        FrameworkElement CreateTreeNode(C1FlexGrid flex, GroupRow row)
        {
            var g = new Grid();

            for (int i = 0; i <= row.Level; i++)
            {
                var cd = new ColumnDefinition();
                cd.Width = new GridLength(flex.TreeIndent);
                g.ColumnDefinitions.Add(cd);
            }

            // icon connectors (left and up)
            if (row.Level > 0)
            {
                var rc = CreateConnector(flex.TreeIndent, _connThickness);
                rc.HorizontalAlignment = HorizontalAlignment.Left;
                rc.VerticalAlignment = VerticalAlignment.Center;
                rc.Margin = new Thickness(flex.TreeIndent / 2, 0, 0, 0);
                rc.SetValue(Grid.ColumnProperty, row.Level - 1);
                rc.SetValue(Grid.ColumnSpanProperty, 2);
                g.Children.Add(rc);

                rc = CreateConnector(_connThickness, row.ActualHeight / 2);
                rc.HorizontalAlignment = HorizontalAlignment.Center;
                rc.VerticalAlignment = VerticalAlignment.Top;
                rc.SetValue(Grid.ColumnProperty, row.Level - 1);
                g.Children.Add(rc);
            }

            // icon connector (down)
            if (row.HasChildren && !row.IsCollapsed)
            {
                var rc = CreateConnector(_connThickness, row.ActualHeight / 2);
                rc.HorizontalAlignment = HorizontalAlignment.Center;
                rc.VerticalAlignment = VerticalAlignment.Bottom;
                rc.SetValue(Grid.ColumnProperty, row.Level);
                g.Children.Add(rc);
            }

            // inter-node connectors
            for (int i = row.Level; i > 0; i--)
            {
                if (CheckNodeAfter(row, i))
                {
                    var rc = CreateConnector(_connThickness, row.ActualHeight);
                    rc.HorizontalAlignment = HorizontalAlignment.Center;
                    rc.VerticalAlignment = VerticalAlignment.Top;
                    rc.SetValue(Grid.ColumnProperty, i - 1);
                    g.Children.Add(rc);
                }
            }

            // icon
            var nodeIcon = new Image();
            nodeIcon.Source =
                row.HasChildren == false ? _bmpNoChildren :
                row.IsCollapsed ? _bmpCollapsed : _bmpExpanded;
            nodeIcon.Stretch = Stretch.None;
            nodeIcon.SetValue(Grid.ColumnProperty, row.Level + 1);
            g.Children.Add(nodeIcon);
            if (row.HasChildren)
            {
                nodeIcon.MouseLeftButtonDown += (s, e) => { row.IsCollapsed = !row.IsCollapsed; };
            }

            // done
            g.Margin = new Thickness(0, 0, 4, 0);

            return g;
        }

        // creates a Rectangle element to use as a tree connector
        static Rectangle CreateConnector(double width, double height)
        {
            var rc = new Rectangle();
            rc.Width = width;
            rc.Height = height;
            rc.Fill = _connBrush;

            return rc;
        }

        // checks whether there is a row after this one with a given level
        private static bool CheckNodeAfter(GroupRow row, int level)
        {
            var rows = row.Grid.Rows;
            for (int i = row.Index + 1; i < rows.Count; i++)
            {
                var r = rows[i] as GroupRow;
                if (r.Level < level)
                {
                    return false;
                }
                if (r.Level == level)
                {
                    return true;
                }
            }

            return false;
        }

        // loads a bitmap from an embedded resource
        private static BitmapImage LoadBitmap(string bmpName)
        {
            var bmp = new BitmapImage();
            bmp.BeginInit();
            bmp.StreamSource = GetResourceStream(bmpName);
            bmp.EndInit();

            return bmp;
        }

        // gets an embedded resource stream
        private static Stream GetResourceStream(string resName)
        {
            var asm = System.Reflection.Assembly.GetExecutingAssembly();
            foreach (var rn in asm.GetManifestResourceNames())
            {
                if (rn.EndsWith(resName))
                {
                    return asm.GetManifestResourceStream(rn);
                }
            }
            throw new Exception("Embedded resource not found: " + resName);
        }
    }
}


text:
// Copyright 2017 Google LLC
//
// 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.

package com.google.api.graphql.execution;

import com.google.common.util.concurrent.FutureCallback;
import com.google.common.util.concurrent.Futures;
import com.google.common.util.concurrent.ListenableFuture;
import com.google.common.util.concurrent.MoreExecutors;
import graphql.execution.instrumentation.Instrumentation;
import graphql.execution.instrumentation.SimpleInstrumentation;
import graphql.execution.instrumentation.parameters.InstrumentationFieldFetchParameters;
import graphql.schema.DataFetcher;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.Executor;

/** Adds support for ListenableFuture return values. */
public final class GuavaListenableFutureSupport {
  private GuavaListenableFutureSupport() {}

  /**
   * Converts a {@link ListenableFuture} to a Java8 {@link java.util.concurrent.CompletableFuture}.
   *
   *
{@see CompletableFuture} is supported by the provided {@link
   * graphql.execution.AsyncExecutionStrategy}.
   *
   *
Note: This should be installed before any other instrumentation.
   */
  public static Instrumentation listenableFutureInstrumentation() {
    return listenableFutureInstrumentation(MoreExecutors.directExecutor());
  }

  /**
   * Converts a {@link ListenableFuture} to a Java8 {@link java.util.concurrent.CompletableFuture}.
   *
   *
{@see CompletableFuture} is supported by the provided {@link
   * graphql.execution.AsyncExecutionStrategy}.
   *
   *
Note: This should be installed before any other instrumentation.
   */
  public static Instrumentation listenableFutureInstrumentation(Executor executor) {
    return new SimpleInstrumentation() {
      @Override
      public DataFetcher<?> instrumentDataFetcher(
          DataFetcher<?> dataFetcher, InstrumentationFieldFetchParameters parameters) {
        return (DataFetcher<Object>)
            dataFetchingEnvironment -> {
              Object data = dataFetcher.get(dataFetchingEnvironment);
              if (data instanceof ListenableFuture) {
                ListenableFuture<Object> listenableFuture = (ListenableFuture<Object>) data;
                CompletableFuture<Object> completableFuture = new CompletableFuture<>();
                Futures.addCallback(
                    listenableFuture,
                    new FutureCallback<Object>() {
                      @Override
                      public void onSuccess(Object result) {
                        completableFuture.complete(result);
                      }

                      @Override
                      public void onFailure(Throwable t) {
                        completableFuture.completeExceptionally(t);
                      }
                    },
                    executor);
                return completableFuture;
              }
              return data;
            };
      }
    };
  }
}


text:
'use strict';

var WorldState = require('worldstate');

var input = require('./graph/example');
console.profile('total');

var graph = WorldState.create(input);
var friendsOfBruceBanner = graph.nodes({name: 'Bruce Banner'}).out('friend');
console.log('friends of Bruce Banner:', friendsOfBruceBanner.all());

var testNodes = [];
for (var i = 5, l = 2000000; i < l; i++) {
  testNodes.push({id: i, name: 'Random Evil Bad Guy'});
}

graph.add({
  nodes: testNodes,
  edges: [{
    source: 6,
    target: 1,
    label: 2
  }
  ],
  edgeLabels: {
    enemy: {
      id: 2
    }
  }
});

console.log('friends of friends of Bruce Banner:', friendsOfBruceBanner.out('friend').all());
var bestFriendOfTonyStark = graph.nodes({name: 'Tony Stark'}).out('friend', {greaterThan: .5});
console.log('best friend(s) of Tony Stark:', bestFriendOfTonyStark.all());

// TODO: removal

console.log('nr of added bad guys:', graph.nodes({name:'Random Evil Bad Guy'}).all().length);
console.log(graph.nodes({name:'Bruce Banner'}).in('enemy').all());
console.log(graph.nodes({name:'Bruce Banner'}).outEdges());
console.log('filter testing:', graph.filter(function(node){
  return node.name.indexOf('ony') > -1;
}).all());

var bruce = graph.nodes({name: 'Tony Stark'}).all();
console.log(bruce);

console.log('pleh:', graph.nodes(bruce).in('friend').all());

console.profileEnd('total');

//
//friendsOfSander.observe(function() {
//  console.log(friendsOfSander.all());
//});
//
//graph.add([
//  {
//    // vertex
//  },
//  {
//    // edge
//  },
//  {
//    // edgeLabel
//  }
//]);


text:
@interface PodsDummy_Pods_FTFoldableTableView_Tests : NSObject
@end
@implementation PodsDummy_Pods_FTFoldableTableView_Tests
@end


text:
package com.vaadin.ui.components.grid;

import java.io.Serializable;

import com.vaadin.ui.Grid;

/**
 * An event listener for column resize events in the Grid.
 *
 * @author Vaadin Ltd
 * @since 8.0
 */
@FunctionalInterface
public interface ColumnResizeListener extends Serializable {

    /**
     * Called when the columns of the grid have been resized.
     *
     * @param event
     *            An event providing more information
     */
    void columnResize(Grid.ColumnResizeEvent event);
}


text:
using System;
using System.Collections.Generic;
using System.Text;

namespace BBDCL
{

    /// <summary>
    /// 动漫app由9miao社团研发,如有问题请登陆http://www.9miao.com/官网
    /// </summary>
    ///

    [Serializable]
    public  class BBSUserInfo
    {
        public string UserId { get; set; }
        public string UserType { get; set; }
        public string UserName { get; set; }
        public string UserLoginCheckCode { get; set; }
    }
}


text:
package com.microsoft.office365.snippetapp.helpers;

import android.util.Log;

import com.google.common.util.concurrent.FutureCallback;
import com.google.common.util.concurrent.Futures;
import com.google.common.util.concurrent.ListenableFuture;
import com.google.common.util.concurrent.SettableFuture;
import com.microsoft.discoveryservices.ServiceInfo;
import com.microsoft.discoveryservices.odata.DiscoveryClient;
import com.microsoft.services.odata.impl.ADALDependencyResolver;

import java.util.List;
import java.util.NoSuchElementException;

/**
 * Handles the discovery of the service endpoints
 * for the capabilities that the user has access to
 * in Office 365.
 */
public class DiscoveryController {

    private static final String TAG = "DiscoveryController";
    private static DiscoveryController INSTANCE;
    private List<ServiceInfo> mServices;

    public static synchronized DiscoveryController getInstance() {
        if (INSTANCE == null) {
            INSTANCE = new DiscoveryController();
        }
        return INSTANCE;
    }

    public static synchronized void resetInstance() {
        INSTANCE = null;
    }

    /**
     * Provides information about the service that corresponds to the provided
     * capability.
     *
     * @param capability A string that contains the capability of the service that
     *                   is going to be discovered.
     * @return A signal to wait on before continuing execution. The signal contains the
     * ServiceInfo object with extra information about discovered service.
     */
    public SettableFuture<ServiceInfo> getServiceInfo(final String capability) {

        final SettableFuture<ServiceInfo> result = SettableFuture.create();

        // First, look in the locally cached services.
        if (mServices != null) {
            boolean serviceFound = false;
            for (ServiceInfo service : mServices) {
                if (service.getcapability().equals(capability)) {
                    Log.i(TAG,
                            "getServiceInfo - "
                                    + service.getserviceName()
                                    + " service for "
                                    + capability
                                    + " was found in local cached services");
                    result.set(service);
                    serviceFound = true;
                    break;
                }
            }

            if (!serviceFound) {
                NoSuchElementException noSuchElementException = new NoSuchElementException(
                        "The "
                                + capability
                                + " capability was not found in the local cached services.");
                Log.e(TAG, "getServiceInfo - " + noSuchElementException.getMessage());
                result.setException(noSuchElementException);
            }
        } else { // The services have not been cached yet. Go ask the discovery service.
            AuthenticationController.getInstance().setResourceId(Constants.DISCOVERY_RESOURCE_ID);
            ADALDependencyResolver dependencyResolver = (ADALDependencyResolver) AuthenticationController
                    .getInstance()
                    .getDependencyResolver();

            DiscoveryClient discoveryClient = new DiscoveryClient(Constants.DISCOVERY_RESOURCE_URL,
                    dependencyResolver);

            try {
                ListenableFuture<List<ServiceInfo>> future = discoveryClient
                        .getservices()
                        .select("serviceResourceId,serviceEndpointUri,capability")
                        .read();
                Futures.addCallback(future,
                        new FutureCallback<List<ServiceInfo>>() {
                            @Override
                            public void onSuccess(final List<ServiceInfo> services) {
                                Log.i(TAG, "getServiceInfo - Services discovered\n");
                                // Save the discovered services to serve further requests from the local cache.
                                mServices = services;

                                boolean serviceFound = false;
                                for (ServiceInfo service : services) {
                                    if (service.getcapability().equals(capability)) {
                                        Log.i(TAG,
                                                "getServiceInfo - "
                                                        + service.getserviceName()
                                                        + " service for "
                                                        + capability
                                                        + " was found in services retrieved from discovery");
                                        result.set(service);
                                        serviceFound = true;
                                        break;
                                    }
                                }

                                if (!serviceFound) {
                                    NoSuchElementException noSuchElementException = new NoSuchElementException(
                                            "The "
                                                    + capability
                                                    + " capability was not found in the user services.");
                                    Log.e(TAG,
                                            "getServiceInfo - " + noSuchElementException.getMessage());
                                    result.setException(noSuchElementException);
                                }
                            }

                            @Override
                            public void onFailure(Throwable t) {
                                Log.e(TAG, "getServiceInfo - " + t.getMessage());
                                result.setException(t);
                            }
                        });
            } catch (Exception e) {
                Log.e(TAG, "getServiceInfo - " + e.getMessage());
                result.setException(e);
            }
        }
        return result;
    }
}

// *********************************************************
//
// O365-Android-Snippets, https://github.com/OfficeDev/O365-Android-Snippets
//
// Copyright (c) Microsoft Corporation
// All rights reserved.
//
// MIT License:
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
// *********************************************************


text:
class Sheet(object):
	""" sheet: Top level object.
		Models the entire music sheet """
	def __init__(self, name):
		super(Sheet, self).__init__()
		self.name = name
		self.bars = list()

class Bar(object):
	""" bar: Models a measure.
		Compose the sheet as the temporal layer
			=> Where the notes are displayed on the sheet """
	def __init__(self, time_signature=4):
		super(Bar, self).__init__()
		self.time_signature = time_signature
		self.voices = list()

class Note(object):
	""" note: Models the unit in music representation"""
	def __init__(self, pitch, duration=1):
		super(Note, self).__init__()
		self.pitch = pitch
		self.duration = duration


text:
<#
.SYNOPSIS

.DESCRIPTION

.PARAMETER SubscriptionName
    Name of the Azure Subscription.

.PARAMETER ApplicationName
    Name of the Application.

.PARAMETER StorageAccountName
    Name of the storage account name.

.PARAMETER ContainerName
    Name of the container use to store output from the Stream Analytics job.

.PARAMETER ConsumerGroupName
    Stream Analytics consumer group for blob storage.

.PARAMETER EventHubName
    Name of the EventHub that will receive events from the simulator.

.PARAMETER EventHubSharedAccessPolicyName
    Shared Access Policy

.PARAMETER Location
    Location

.PARAMETER ResourceGroupPrefix
    Prefix that will be combined with Location to produce the ResourceGroupName

.PARAMETER ServiceBusNamespace
    Name of the Namespace tha will contain the EventHub instance.

.PARAMETER StreamAnalyticsBlobsJobName
    Name of the Stream Analytics Job name used to output to blob storage.

.EXAMPLE
  .\Provision-ColdStorageAzureStreamAnalytics.ps1 -SubscriptionName [YourAzureSubscriptionName] -ApplicationName [YourApplicationName] -Verbose
#>
[CmdletBinding()]
Param
(
    [ValidateNotNullOrEmpty()][Parameter (Mandatory = $True)][string]$SubscriptionName,
    [ValidateNotNullOrEmpty()][Parameter (Mandatory = $True)][String]$ApplicationName,
    [ValidateNotNullOrEmpty()][Parameter (Mandatory = $False)][bool]$AddAccount = $True,
    [ValidateNotNullOrEmpty()][Parameter (Mandatory = $False)][String]$StorageAccountName =$ApplicationName,
    [ValidateNotNullOrEmpty()][Parameter (Mandatory = $False)][String]$ContainerName = "blobs-asa",
    [ValidateNotNullOrEmpty()][Parameter (Mandatory = $False)][String]$ConsumerGroupName  = "cg-blobs-asa",
    [ValidateNotNullOrEmpty()][Parameter (Mandatory = $False)][String]$EventHubName = "eventhub-iot",
    [ValidateNotNullOrEmpty()][Parameter (Mandatory = $False)][String]$EventHubSharedAccessPolicyName = "ManagePolicy",
    [ValidateNotNullOrEmpty()][Parameter (Mandatory = $False)][String]$Location = "Central US",
    [ValidateNotNullOrEmpty()][Parameter (Mandatory = $False)][String]$ResourceGroupPrefix = $ApplicationName,
    [ValidateNotNullOrEmpty()][Parameter (Mandatory = $False)][String]$ServiceBusNamespace = $ApplicationName,
    [ValidateNotNullOrEmpty()][Parameter (Mandatory = $False)][String]$StreamAnalyticsJobName = $ApplicationName+"ToBlob",

    [ValidateNotNullOrEmpty()][Parameter (Mandatory = $False)][ValidateScript({ Test-FileName "JobDefinitionPath" $_})]
    [String]$JobDefinitionPath = "..\src\LongTermStorage\AzureStreamAnalytics\StreamAnalyticsJobDefinitionColdStorage.json"

)
PROCESS
{
    $ErrorActionPreference = "Stop"

    .\Init.ps1

    Load-Module -ModuleName Validation -ModuleLocation .\modules

    # Validate input.
    Test-OnlyLettersAndNumbers "StorageAccountName" $StorageAccountName
    Test-OnlyLettersNumbersAndHyphens "ConsumerGroupName" $ConsumerGroupName
    Test-OnlyLettersNumbersHyphensPeriodsAndUnderscores "EventHubName" $EventHubName
    Test-OnlyLettersNumbersAndHyphens "ServiceBusNamespace" $ServiceBusNamespace
    Test-OnlyLettersNumbersAndHyphens "ContainerName" $ContainerName

    # Load modules.
    Load-Module -ModuleName Config -ModuleLocation .\modules
    Load-Module -ModuleName Utility -ModuleLocation .\modules
    Load-Module -ModuleName AzureARM -ModuleLocation .\modules
    Load-Module -ModuleName AzureStorage -ModuleLocation .\modules
    Load-Module -ModuleName AzureServiceBus -ModuleLocation .\modules
    Load-Module -ModuleName AzureStreamAnalytics -ModuleLocation .\modules

    if($AddAccount)
    {
        Add-AzureAccount
    }

    Select-AzureSubscription $SubscriptionName

    New-ProvisionedStorageAccount -StorageAccountName $StorageAccountName `
                                  -ContainerName $ContainerName `
                                  -Location $Location

    $EventHubInfo = New-ProvisionedEventHub -SubscriptionName $SubscriptionName `
                                    -ServiceBusNamespace $ServiceBusNamespace `
                                    -EventHubName $EventHubName `
                                    -ConsumerGroupName $ConsumerGroupName `
                                    -EventHubSharedAccessPolicyName $EventHubSharedAccessPolicyName `
                                    -Location $Location `
                                    -PartitionCount 16 `
                                    -MessageRetentionInDays 7

    # Update settings

    $simulatorSettings = @{
        'Simulator.EventHubNamespace'= $EventHubInfo.EventHubNamespace;
        'Simulator.EventHubName' = $EventHubInfo.EventHubName;
        'Simulator.EventHubSasKeyName' = $EventHubInfo.EventHubSasKeyName;
        'Simulator.EventHubPrimaryKey' = $EventHubInfo.EventHubPrimaryKey;
        'Simulator.EventHubTokenLifetimeDays' = ($EventHubInfo.EventHubTokenLifetimeDays -as [string]);
    }

    Write-SettingsFile -configurationTemplateFile (Join-Path $PSScriptRoot -ChildPath "..\src\Simulator\ScenarioSimulator.ConsoleHost.Template.config") `
                       -configurationFile (Join-Path $PSScriptRoot -ChildPath "..\src\Simulator\ScenarioSimulator.ConsoleHost.config") `
                       -appSettings $simulatorSettings

    $ResourceGroupName = $ResourceGroupPrefix + "-" + $Location.Replace(" ","-")

    $EventHubSharedAccessPolicyKey = Get-EventHubSharedAccessPolicyKey -ServiceBusNamespace $ServiceBusNamespace `
                                                                           -EventHubName $EventHubName `
                                                                           -EventHubSharedAccessPolicyName $EventHubSharedAccessPolicyName

    # Get Storage Account Key
    $storageAccountKey = Get-AzureStorageKey -StorageAccountName $StorageAccountName
    $storageAccountKeyPrimary = $storageAccountKey.Primary

    # Create Job Definition
    [string]$JobDefinitionText = (Get-Content -LiteralPath (Join-Path $PSScriptRoot -ChildPath $JobDefinitionPath)).
                                    Replace("_StreamAnalyticsJobName",$StreamAnalyticsJobName).
                                    Replace("_Location",$Location).
                                    Replace("_ConsumerGroupName",$ConsumerGroupName).
                                    Replace("_EventHubName",$EventHubName).
                                    Replace("_ServiceBusNamespace",$ServiceBusNamespace).
                                    Replace("_EventHubSharedAccessPolicyName",$EventHubSharedAccessPolicyName).
                                    Replace("_EventHubSharedAccessPolicyKey",$EventHubSharedAccessPolicyKey).
                                    Replace("_AccountName",$StorageAccountName).
                                    Replace("_AccountKey",$storageAccountKeyPrimary).
                                    Replace("_Container",$ContainerName)

    Provision-StreamAnalyticsJob -ServiceBusNamespace $ServiceBusNamespace `
                                 -EventHubName $EventHubName `
                                 -EventHubSharedAccessPolicyName $EventHubSharedAccessPolicyName `
                                 -StorageAccountName $StorageAccountName `
                                 -ContainerName $ContainerName `
                                 -ResourceGroupName $ResourceGroupName `
                                 -Location $Location `
                                 -JobDefinitionText $JobDefinitionText

    Write-Output "Provision Finished OK"
}


text:
package org.apache.mxnet

import org.scalatest.{BeforeAndAfterAll, FunSuite}
import org.apache.mxnet.CheckUtils._
import org.apache.mxnet.module._
import org.apache.mxnet.optimizer._
import org.apache.mxnet.io._

class ModuleSuite extends FunSuite with BeforeAndAfterAll {
  test ("model dtype") {
    val dType = DType.Float16
    val dShape = Shape(3, 8, 7)

    var sym = Symbol.Variable("data")
    sym = Symbol.Activation(attr = Map("__layout__" -> "TNC"))()(
      Map("data" -> sym, "act_type" -> "relu"))

    val mod = new Module(sym, IndexedSeq("data"), null,
      contexts = Array(Context.cpu(0), Context.cpu(1)))
    mod.bind(dataShapes = IndexedSeq(DataDesc("data", dShape, dType, "TNC")))
    mod.initParams()
    mod.forward(new DataBatch(
      data = IndexedSeq(NDArray.ones(dShape, dtype = dType)),
      label = null, index = null, pad = 0))
    mod.backward(Array(NDArray.ones(dShape, dtype = dType)))

    assert(mod.getOutputs.flatten.forall(_.dtype == dType))
  }

  test ("module input_grads") {
    val a = Symbol.Variable("a", kwargs = Map("__layout__" -> "NC"))
    val b = Symbol.Variable("b", kwargs = Map("__layout__" -> "NC"))
    var c = Symbol.Variable("c", kwargs = Map("__layout__" -> "NC"))

    import SymbolConversions._
    c = a + 2 * b + 3 * c

    val mod = new Module(c, IndexedSeq("b", "c", "a"), null,
      contexts = Array(Context.cpu(0), Context.cpu(1)))
    mod.bind(dataShapes = IndexedSeq(
      DataDesc("b", Shape(5, 5), layout = "NT"),
      DataDesc("c", Shape(5, 5), layout = "NT"),
      DataDesc("a", Shape(5, 5), layout = "NT")),
      inputsNeedGrad = true
    )
    mod.initParams()
    mod.forward(new DataBatch(
      data = IndexedSeq(
        NDArray.ones(5, 5), NDArray.ones(5, 5), NDArray.ones(5, 5)),
      label = null, index = null, pad = 0))
    mod.backward(Array(NDArray.ones(5, 5)))

    val inputGrads = mod.getInputGradsMerged()
    val aGrad = inputGrads(0).toArray
    val bGrad = inputGrads(1).toArray
    val cGrad = inputGrads(2).toArray

    assert(aGrad.forall(_ == 1f))
    assert(bGrad.forall(_ == 2f))
    assert(cGrad.forall(_ == 3f))
  }

  test ("module layout") {
    var sym = Symbol.Variable("data")
    sym = Symbol.Activation(attr = Map("__layout__" -> "TNC"))()(
      Map("data" -> sym, "act_type" -> "relu"))

    val dShape = Shape(3, 8, 7)
    val mod = new Module(sym, IndexedSeq("data"), null,
      contexts = Array(Context.cpu(0), Context.cpu(1)))
    mod.bind(dataShapes = IndexedSeq(DataDesc("data", dShape, layout = "TNC")))
    mod.initParams()
    mod.forward(new DataBatch(
      data = IndexedSeq(NDArray.ones(dShape)),
      label = null, index = null, pad = 0))
    mod.backward(Array(NDArray.ones(dShape)))
    assert(mod.getOutputsMerged()(0).shape == dShape)

    val hdShape = Shape(3, 4, 7)
    for (x <- mod.getOutputs) assert(x(0).shape == hdShape)
  }

  test ("save load") {
    def mapEqu(a: Map[String, NDArray], b: Map[String, NDArray]): Unit = {
      assert(a.toSet == b.toSet)
      for (k <- a.keys) assert(a(k) == b(k))
    }

    var sym = Symbol.Variable("data")
    sym = Symbol.FullyConnected()()(Map("data" -> sym, "num_hidden" -> 100))

    // single device
    var mod = new Module(sym, IndexedSeq("data"), null)
    mod.bind(dataShapes = IndexedSeq(DataDesc("data", Shape(10, 10), layout = "NT")))
    mod.initParams()
    mod.initOptimizer(optimizer = new SGD(learningRate = 0.1f, momentum = 0.9f))
    mod.update()
    mod.saveCheckpoint("test", 0, saveOptStates = true)

    var mod2 = Module.loadCheckpoint("test", 0, loadOptimizerStates = true)
    mod2.bind(dataShapes = IndexedSeq(DataDesc("data", Shape(10, 10), layout = "NT")))
    mod2.initOptimizer(optimizer = new SGD(learningRate = 0.1f, momentum = 0.9f))
    assert(mod.getSymbol.toJson == mod2.getSymbol.toJson)
    mapEqu(mod.getParams._1, mod2.getParams._1)

    // multi device
    mod = new Module(sym, IndexedSeq("data"), null,
      contexts = Array(Context.cpu(0), Context.cpu(1)))
    mod.bind(dataShapes = IndexedSeq(DataDesc("data", Shape(10, 10), layout = "NT" )))
    mod.initParams()
    mod.initOptimizer(optimizer = new SGD(learningRate = 0.1f, momentum = 0.9f))
    mod.update()
    mod.saveCheckpoint("test", 0, saveOptStates = true)

    mod2 = Module.loadCheckpoint("test", 0, loadOptimizerStates = true)
    mod2.bind(dataShapes = IndexedSeq(DataDesc("data", Shape(10, 10), layout = "NT")))
    mod2.initOptimizer(optimizer = new SGD(learningRate = 0.1f, momentum = 0.9f))
    assert(mod.getSymbol.toJson == mod2.getSymbol.toJson)
    mapEqu(mod.getParams._1, mod2.getParams._1)
  }

  test ("module reshape") {
    var sym = Symbol.Variable("data")
    sym = Symbol.FullyConnected("fc")()(Map("data" -> sym, "num_hidden" -> 20))

    var dShape = Shape(7, 20)
    val mod = new Module(sym, IndexedSeq("data"), null,
      contexts = Array(Context.cpu(0), Context.cpu(1)))
    mod.bind(dataShapes = IndexedSeq(DataDesc("data", dShape, layout = "NT")))
    mod.initParams()
    mod.initOptimizer(optimizer = new SGD(learningRate = 1f))

    mod.forward(new DataBatch(
      data = IndexedSeq(NDArray.ones(dShape)),
      label = null, index = null, pad = 0))
    mod.backward(Array(NDArray.ones(dShape)))
    mod.update()
    assert(mod.getOutputsMerged()(0).shape == dShape)
    assert(mod.getParams._1("fc_bias").toArray.forall(_ == -1f))

    dShape = Shape(14, 20)
    mod.reshape(IndexedSeq(DataDesc("data", dShape, layout = "NT")))
    mod.forward(new DataBatch(
      data = IndexedSeq(NDArray.ones(dShape)),
      label = null, index = null, pad = 0))
    mod.backward(Array(NDArray.ones(dShape)))
    mod.update()
    assert(mod.getOutputsMerged()(0).shape == dShape)
    assert(mod.getParams._1("fc_bias").toArray.forall(x => (x - -3f) < 1e-3))
  }

  test ("module setParams") {
    val data = NDArray.array(Array(0.05f, 0.1f), Shape(1, 1, 1, 2))
    val label = NDArray.array(Array(0.01f, 0.99f), Shape(1, 1, 1, 2))
    val trainData = new NDArrayIter(
      IndexedSeq(data), IndexedSeq(label), labelName = "softmax_label")

    // symbols
    var x = Symbol.Variable("data")
    x = Symbol.FullyConnected(name = "fc_0")()(Map("data" -> x, "num_hidden" -> 2))
    x = Symbol.Activation(name = "act_0")()(Map("data" -> x, "act_type" -> "sigmoid"))
    x = Symbol.FullyConnected(name = "fc_1")()(Map("data" -> x, "num_hidden" -> 2))
    x = Symbol.Activation(name = "act_1")()(Map("data" -> x, "act_type" -> "sigmoid"))
    x = Symbol.LinearRegressionOutput(name = "softmax")()(Map("data" -> x, "grad_scale" -> 2))

    // create module
    val mod = new Module(x, contexts = Array(Context.cpu()))
    mod.bind(dataShapes = trainData.provideData,
      Option(trainData.provideLabel))
    val argParamsCorrect = Map(
      "fc_0_weight" -> NDArray.array(Array(0.15f, 0.2f, 0.25f, 0.3f), Shape(2, 2)),
      "fc_0_bias" -> NDArray.array(Array(0.35f, 0.35f), Shape(2)),
      "fc_1_weight" -> NDArray.array(Array(0.4f, 0.45f, 0.5f, 0.55f), Shape(2, 2)),
      "fc_1_bias" -> NDArray.array(Array(0.6f, 0.6f), Shape(2))
    )
    val argParamsMissing = Map(
      "fc_0_weight" -> NDArray.array(Array(0.15f, 0.2f, 0.25f, 0.3f), Shape(2, 2)),
      "fc_0_bias" -> NDArray.array(Array(0.35f, 0.35f), Shape(2)),
      "fc_1_weight" -> NDArray.array(Array(0.4f, 0.45f, 0.5f, 0.55f), Shape(2, 2))
    )
    val argParamsExtra = Map(
      "fc_0_weight" -> NDArray.array(Array(0.15f, 0.2f, 0.25f, 0.3f), Shape(2, 2)),
      "fc_0_bias" -> NDArray.array(Array(0.35f, 0.35f), Shape(2)),
      "fc_1_weight" -> NDArray.array(Array(0.4f, 0.45f, 0.5f, 0.55f), Shape(2, 2)),
      "fc_1_bias" -> NDArray.array(Array(0.6f, 0.6f), Shape(2)),
      "fc_2_weight" -> NDArray.array(Array(0.6f, 0.6f), Shape(2))
    )

    mod.setParams(forceInit = true, argParams = argParamsCorrect,
      auxParams = null)

    // test allow missing
    mod.setParams(forceInit = true, argParams = argParamsMissing,
      auxParams = null, allowMissing = true)

    // test allow extra
    mod.setParams(forceInit = true, argParams = argParamsExtra, auxParams = null,
      allowMissing = true, allowExtra = true)
  }

  test ("monitor") {
    // data iter
    val data = NDArray.array(Array(0.05f, 0.1f), Shape(1, 1, 1, 2))
    val label = NDArray.array(Array(0.01f, 0.99f), Shape(1, 1, 1, 2))
    val trainData = new NDArrayIter(
      IndexedSeq(data), IndexedSeq(label), labelName = "softmax_label")

    // symbols
    var x = Symbol.Variable("data")
    x = Symbol.FullyConnected(name = "fc_0")()(Map("data" -> x, "num_hidden" -> 2))
    x = Symbol.Activation(name = "act_0")()(Map("data" -> x, "act_type" -> "sigmoid"))
    x = Symbol.FullyConnected(name = "fc_1")()(Map("data" -> x, "num_hidden" -> 2))
    x = Symbol.Activation(name = "act_1")()(Map("data" -> x, "act_type" -> "sigmoid"))
    x = Symbol.LinearRegressionOutput(name = "softmax")()(Map("data" -> x, "grad_scale" -> 2))

    // create monitor
    def meanAbs(x: NDArray): NDArray = {
      val sumAbs = NDArray.sum(NDArray.abs(x))
      sumAbs / x.shape.product
    }
    val mon = new Monitor(1, statFunc = meanAbs)

    // create module
    val mod = new Module(x, contexts = Array(Context.cpu()))
    mod.bind(dataShapes = trainData.provideData,
      Option(trainData.provideLabel))
    mod.installMonitor(mon)
    val argParams = Map(
      "fc_0_weight" -> NDArray.array(Array(0.15f, 0.2f, 0.25f, 0.3f), Shape(2, 2)),
      "fc_0_bias" -> NDArray.array(Array(0.35f, 0.35f), Shape(2)),
      "fc_1_weight" -> NDArray.array(Array(0.4f, 0.45f, 0.5f, 0.55f), Shape(2, 2)),
      "fc_1_bias" -> NDArray.array(Array(0.6f, 0.6f), Shape(2))
    )
    mod.initParams(argParams = argParams)

    val dataBatch = trainData.next()
    mon.tic()
    mod.forwardBackward(dataBatch)
    val res = mon.toc()
    val keys = Array("act_0", "act_1", "data", "fc_0", "fc_1", "softmax")
    val monResultCounts = Array(0, 0, 0, 0, 0, 0)
    assert(res.length == 21)
    for ((n, k, v) <- res) {
      var break = false
      for ((key, idx) <- keys.zipWithIndex) {
        if (!break && k.startsWith(key)) {
          monResultCounts(idx) += 1
          break = true
        }
      }
    }
    assert(monResultCounts.zip(Array(2, 2, 1, 6, 6, 4)).forall(x => x._1 == x._2))
  }

  test ("forward reshape") {
    val numClass = 10
    val data1 = Symbol.Variable("data1")
    val data2 = Symbol.Variable("data2")
    val conv1 = Symbol.Convolution()()(Map("data" -> data1,
        "kernel" -> "(2, 2)", "num_filter" -> 2, "stride" -> "(2, 2)"))
    val conv2 = Symbol.Convolution()()(Map("data" -> data2,
        "kernel" -> "(3, 3)", "num_filter" -> 3, "stride" -> "(1, 1)"))
    val pooling1 = Symbol.Pooling()()(Map("data" -> conv1,
        "kernel" -> "(2, 2)", "pool_type" -> "avg", "stride" -> "(1, 1)"))
    val pooling2 = Symbol.Pooling()()(Map("data" -> conv2,
        "kernel" -> "(2, 2)", "pool_type" -> "max", "stride" -> "(1, 1)"))
    val flatten1 = Symbol.flatten()()(Map("data" -> pooling1))
    val flatten2 = Symbol.flatten()()(Map("data" -> pooling2))
    val sum = Symbol.sum()()(Map("data" -> flatten1, "axis" -> 1)) +
      Symbol.sum()()(Map("data" -> flatten2, "axis" -> 1))
    val fc = Symbol.FullyConnected()()(
      Map("data" -> sum, "num_hidden" -> numClass))
    val sym = Symbol.SoftmaxOutput(name = "softmax")()(Map("data" -> fc))

    var dShape1 = Shape(10, 3, 64, 64)
    var dShape2 = Shape(10, 3, 32, 32)
    var lShape = Shape(10)

    val mod = new Module(sym, IndexedSeq("data1", "data2"))
    mod.bind(dataShapes = IndexedSeq(
      DataDesc("data1", dShape1), DataDesc("data2", dShape2, layout = "NCHW")),
      labelShapes = Option(IndexedSeq(DataDesc("softmax_label", lShape, layout = "N")))
    )
    mod.initParams()
    mod.initOptimizer(optimizer = new SGD(learningRate = 0.01f))

    // Train with original data shapes
    var dataBatch = new DataBatch(
      data = IndexedSeq(
        NDArray.random_uniform(Map("low" -> 0, "high" -> 9, "shape" -> dShape1.toString()))(),
        NDArray.random_uniform(Map("low" -> 5, "high" -> 15, "shape" -> dShape2.toString()))()),
      label = IndexedSeq(NDArray.ones(lShape)), index = null, pad = 0)
    mod.forward(dataBatch)
    assert(mod.getOutputsMerged()(0).shape == Shape(lShape(0), numClass))
    mod.backward()
    mod.update()

    dShape1 = Shape(3, 3, 64, 64)
    dShape2 = Shape(3, 3, 32, 32)
    lShape = Shape(3)
    dataBatch = new DataBatch(
      data = IndexedSeq(
        NDArray.random_uniform(Map("low" -> 0, "high" -> 9, "shape" -> dShape1.toString()))(),
        NDArray.random_uniform(Map("low" -> 5, "high" -> 15, "shape" -> dShape2.toString()))()),
      label = IndexedSeq(NDArray.ones(lShape)), index = null, pad = 0)
    mod.forward(dataBatch)
    assert(mod.getOutputsMerged()(0).shape == Shape(lShape(0), numClass))
    mod.backward()
    mod.update()

    dShape1 = Shape(20, 3, 64, 64)
    dShape2 = Shape(20, 3, 32, 32)
    lShape = Shape(20)
    dataBatch = new DataBatch(
      data = IndexedSeq(
        NDArray.random_uniform(Map("low" -> 3, "high" -> 5, "shape" -> dShape1.toString()))(),
        NDArray.random_uniform(Map("low" -> 10, "high" -> 25, "shape" -> dShape2.toString()))()),
      label = IndexedSeq(NDArray.ones(lShape)), index = null, pad = 0)
    mod.forward(dataBatch)
    assert(mod.getOutputsMerged()(0).shape == Shape(lShape(0), numClass))
    mod.backward()
    mod.update()

    // Train with both different batch size and data shapes
    dShape1 = Shape(20, 3, 120, 120)
    dShape2 = Shape(20, 3, 32, 64)
    lShape = Shape(20)
    dataBatch = new DataBatch(
      data = IndexedSeq(
        NDArray.random_uniform(Map("low" -> 0, "high" -> 9, "shape" -> dShape1.toString()))(),
        NDArray.random_uniform(Map("low" -> 5, "high" -> 15, "shape" -> dShape2.toString()))()),
      label = IndexedSeq(NDArray.ones(lShape)), index = null, pad = 0)
    mod.forward(dataBatch)
    assert(mod.getOutputsMerged()(0).shape == Shape(lShape(0), numClass))
    mod.backward()
    mod.update()

    dShape1 = Shape(5, 3, 28, 40)
    dShape2 = Shape(5, 3, 24, 16)
    lShape = Shape(5)
    dataBatch = new DataBatch(
      data = IndexedSeq(
        NDArray.random_uniform(Map("low" -> 0, "high" -> 9, "shape" -> dShape1.toString()))(),
        NDArray.random_uniform(Map("low" -> 15, "high" -> 25, "shape" -> dShape2.toString()))()),
      label = IndexedSeq(NDArray.ones(lShape)), index = null, pad = 0)
    mod.forward(dataBatch)
    assert(mod.getOutputsMerged()(0).shape == Shape(lShape(0), numClass))
    mod.backward()
    mod.update()
  }
}


text:
<?php

namespace Guave\SearchConsole\Modules;

use function Symfony\Component\HttpKernel\Tests\controller_func;

class SearchConsole extends \BackendModule
{

    protected $modules = array();

    /**
     * @var null|string
     */
    protected $query = null;

    protected $allowedSqlOperators = array(
        '||',
        'OR',
        'AND',
        '&&'
    );

    /**
     * @return string
     */
    public function generate() {

        $search = \Input::postRaw('search_console');
        if(!$search) {
            $search = \Input::get('search');
        }

        if(!$search) {
            $search = \Session::getInstance()->get('lastSearchConsoleSearch');
        }
        \Session::getInstance()->set('lastSearchConsoleSearch', $search);

        $result = $this->doSearch($search);

        $resultCount = count($result['items']);

        if($resultCount) {
            foreach ($result['items'] as $item) {
                if($item['action'] == 'redirect') {
                    if($item['value'] == $search) {
                        header('Location:'. $item['url']);
                        exit;
                    }
                }
            }
        } else if($resultCount == 1 && $result['items'][0]['action'] == 'redirect') {
           header('Location:'. $result['items'][0]['url']);
            exit;
        }

        if($result['resultCount'] == 1) {

            $result = $result['results'][0];
            header('Location:'.$result['link']);
            exit;
        }

        return $result['resultHtml'];

    }

    public function doSearch($search = null)
    {
        global $GLOBALS;

        if($search == '%' || strstr($search, '%' !== false)) {
            $search = '';
        }

        \Session::getInstance()->set('lastSearchConsoleSearch', $search);

        $search = str_replace(array(' = ', ' < ', ' != ', '>'), array('=', '<', '!=', '>'), $search);

        $return = array();
        $return['items'] = array();

        $fragements = explode(' ', $search);

        $shortCuts = $this->getAvailableShortcuts($search);
        if(!empty($shortCuts)){
            $return['items'] = array_merge($return['items'], $shortCuts);
        }

        $template = new \FrontendTemplate('search_console_result');
        $template->search = $search;
        $return['resultCount'] = 0;
        $return['results'] = array();

        if(strlen($search) >= 1 && empty($shortCuts)) {

            //get last fragment
            $newSearch = $fragements[count($fragements)-1];

            $module = $this->getModuleByShortcut($fragements[0]);
            if(count($fragements) > 1) {
                $fields = $this->getFields($newSearch, $module);
            }

            ////check for autocomplete from db field
            if(strstr($newSearch,'=') !== false && $module) {
                $dbFields = $this->getFields('',$module);

                if($dbFields) {
                    $dbAutocompleteExplode = explode('=', $newSearch, 2);
                    foreach ($dbFields as $data) {
                        if($data['value'] == $dbAutocompleteExplode[0]) {
                            $autoCompleteFromDbField = $this->getAutocompleteFromDbField($this->getTableNameFromModule($module), $dbAutocompleteExplode[0], $dbAutocompleteExplode[1]);
                            if(!empty($autoCompleteFromDbField)){
                                $return['items'] = array_merge($return['items'], $autoCompleteFromDbField);
                            }

                            break;
                        }
                    }
                }

            }

            if(!empty($fields)){
                $return['items'] = array_merge($return['items'], $fields);
            }

            $data = $this->buildQueryAndGetData($search, $module);
            $return['query'] = $this->getQuery();
            if($data) {
                $return['resultCount'] = count($data);

                foreach($data as &$v) {

                    \Controller::loadDataContainer($v['tableName']);
                    $links = array();

                    if($GLOBALS['TL_DCA'][$v['tableName']]['fields']['pid'] && $v['pid']) {

                        $parents = array();

                        if($GLOBALS['TL_DCA'][$v['tableName']]['list']['sorting']['mode'] == 5) { //treeview
                            $parents = $this->getParentElements($v['pid'], $v['tableName'], $v['module']);
                        } else if($GLOBALS['TL_DCA'][$v['tableName']]['config']['ptable'] || $v['ptable']) {
                            $pTable = ($GLOBALS['TL_DCA'][$v['tableName']]['config']['ptable']) ? $GLOBALS['TL_DCA'][$v['tableName']]['config']['ptable'] : $v['ptable'];
                            $parents = $this->getParentElements($v['pid'], $pTable, str_replace('tl_', '',$pTable));

                        }

                        if(!empty($parents)) {
                            krsort($parents);
                            foreach ($parents as $parent) {
                                $links[] = $parent;
                            }
                        }
                    }

                    #original link
                    if($v['module'] == 'theme') {
                        $v['module'] = 'themes';
                    }
                    $links[] = $v;

                    $linkString = '';
                    $activeModule = null;
                    $counter = 0;
                    $linksCount = count($links);

                    for($i = 0; $i < $linksCount; $i++) {
                        if($activeModule != $links[$i]['module']) {
                            if($activeModule != null) {
                                $linkString .= ' | ';
                            }

                            if(!$links[$i]['label'] || strlen($links[$i]['label']) == 1) {
                                $links[$i]['label'] = $links[$i]['module'];
                            }

                            $linkString.= ''.$links[$i]['label'].': ';
                            $activeModule = $links[$i]['module'];
                        } else {
                            if($counter <= $linksCount) {
                                $linkString .= ' < ';
                            }
                        }

                        \Controller::loadDataContainer($links[$i]['tableName']);

                        $name = (($links[$i]['name']) ? $links[$i]['name'] : $links[$i]['id']);
                        foreach ($fragements as $fragement) {

                            $name =  preg_replace('#'. preg_quote($fragement) .'#i', '\\0', $name);

                        }

                        if($GLOBALS['TL_DCA'][$links[$i]['tableName']]['list']['sorting']['mode'] == 4) { //display child record

                            $do = str_replace('tl_', '', $pTable);
                            if($do == 'theme') {
                                $do = 'themes';
                            };

                            $link = $this->getBaseUrl()
                                . '?do=' . str_replace('tl_', '', $do)
                                . '&table=' . $links[$i]['tableName'] . '&act=edit&id=' . $links[$i]['id']
                                . '&ref=' . TL_REFERER_ID
                                . '&rt=' . \RequestToken::get();
                        } else if($GLOBALS['TL_DCA'][$links[$i]['tableName']]['list']['sorting']['mode'] == 6) { //Displays the child records within a tree structure
                            $link = $this->getBaseUrl()
                                . '?do=' . $links[$i]['module']
                                . '&table=' . $GLOBALS['TL_DCA'][$links[$i]['tableName']]['config']['ctable'][0] . '&id=' . $links[$i]['id']
                                . '&ref=' . TL_REFERER_ID
                                . '&rt=' . \RequestToken::get();
                        } else {
                            $link = $this->getBaseUrl()
                                . '?do=' . $links[$i]['module'] . '&act=edit&id=' . $links[$i]['id']
                                . '&ref=' . TL_REFERER_ID
                                . '&rt=' . \RequestToken::get();
                        }

                        $linkString .= ''. $name. '';

                        $counter++;
                    }

                    $v['links'] = $linkString;
                    if(!empty($links)) {
                        $v['link'] = $link;
                    }
                }

                $template->results = $data;
                $return['results'] = $data;
            }
        }

        $template->query = $query;
        $template->resultCount = $return['resultCount'];
        $result = $template->parse();
        $return['resultHtml'] = $result;

        return $return;

    }

   protected function getParentElements($pid, $table = null, $module) {

        if(!$table) {
            return;
        }

        if($module == 'theme') {
            $module = 'themes';
        }

//        echo $pid.'-'.$table.'
';

        $return = array();

       $query = 'SELECT * FROM '.$table.' WHERE id = ? LIMIT 1';
       $data = \Database::getInstance()->prepare($query)->execute($pid)->fetchAssoc();
       $allowedNameFields = array('name', 'title', 'alias');
       $nameField = 'id';
       if($data) {
           foreach ($allowedNameFields as $field) {
               if($data[$field]) {
                   $nameField = $field;
                   break;
               }
           }

           $return[] = array(
               'label' => $this->getLabelOfModule($module),
               'name' => $data[$nameField],
               'id' => $data['id'],
               'pid' => $data['pid'],
               'module' => $module,
               'tableName' => $table
           );
           if($data['pid'] > 0 && $GLOBALS['TL_DCA'][$table]['fields']['pid']) {

               if($GLOBALS['TL_DCA'][$table]['list']['sorting']['mode'] == 5) { //treeview
                   $pTable = $table;
               } else if($GLOBALS['TL_DCA'][$table]['config']['ptable'] || $table) {
                   $pTable = ($GLOBALS['TL_DCA'][$table]['config']['ptable']) ? $GLOBALS['TL_DCA'][$table]['config']['ptable'] : $table;
                   $module = str_replace('tl_', '',$pTable);
               }

               $r = $this->getParentElements($data['pid'], $pTable, $module);
               if(!empty($r)) {
                   $return[] = $r[0];
               }
           }
       }

       return $return;

   }

    protected function buildQueryAndGetData($search, $module = null, $fields = array()) {

        global $GLOBALS;

        $queries = array();

        $params = array();

        foreach ($this->modules as $m => $data) {
            if($module) {
                if($module != $m) {
                    continue;
                }
            }

            $moduleArray = $GLOBALS['search_console']['modules'][$m];

            if($moduleArray['doNotSearch']) {
                continue;
            }

            if(strstr($moduleArray['module'], 'tl_') === false) {
				$table = 'tl_'.$moduleArray['module'];
			} else {
            	$table = $moduleArray['module'];
			}
            if($moduleArray['table']) {
                $table = $moduleArray['table'];
            }

            //remove shortcut from search
            $fragments = explode(' ', $search);
            if($fragments[0] && $moduleArray['shortcut'] == $fragments[0]) {
                $search = substr($search, strlen($fragments[0])+1);
                $fragments = explode(' ', $search);
            }

            if (isset($moduleArray['customSearch']) && is_array($moduleArray['customSearch'])) { //do custom query?
                $subQuery = \System::importStatic($moduleArray['customSearch'][0])->{$moduleArray['customSearch'][1]}($search, $params);
                if($subQuery) {
                    $queries[] = '('.$subQuery.')';
                }
            } else {

                $nameFields = $this->getFields('', $m);

                $nameField = 'id';
                $allowedNameFields = array('name', 'title', 'alias');
                foreach ($nameFields as $field) {

                    if(in_array($field['id'], $allowedNameFields) && isset($GLOBALS['TL_DCA'][$table]['fields'][$field['id']])) {
                        $nameField = $field['id'];
                        break;
                    }
                }

                if($GLOBALS['TL_DCA'][$table]['fields']['pid']) {
                    $pid = ','.$m.'.pid';
                } else {
                    $pid = ',"" AS pid';
                }

                if($GLOBALS['TL_DCA'][$table]['fields']['ptable']) {
                    $ptable = ','.$m.'.ptable';
                } else {
                    $ptable = ',"" AS ptable';
                }

                $subQuery = 'SELECT '.$m.'.id'.$pid.$ptable.', '.$m.'.'.$nameField.' AS name, "'.$m.'" AS module, "'.$data['label'].'" AS label, "'.$table.'" AS tableName FROM '.$table.' AS '.$m;

                if($moduleArray) {

                    $buildSelectFields = array();

                    $i = 0;
                    foreach($fragments as $fragment) {

                        $sqlOpperator = 'OR';

                        if($i != 0) {
                            if(in_array($fragments[$i-1], $this->allowedSqlOperators)) {
                                $sqlOpperator = $fragments[$i-1];
                            }
                        }

                        if(in_array($fragment, $this->allowedSqlOperators)) {
                            $i++;
                            continue;
                        }

                        $fields = $this->getFields($fragment, $m);

                        $re = '/(.*)(=|>|<|!=)(.*)/';
                        preg_match($re, html_entity_decode($fragment), $matches);

                        //do operator search
                        if($matches && $matches[3]) {
                            $check = $this->getFields($matches[1], $m);
                            if($check) {
                                if(isset($GLOBALS['TL_DCA'][$table]['fields'][$matches[1]])) {
                                    if(strstr($matches[3], '%') !== false) {
                                        $buildSelectFields[$sqlOpperator][] = $matches[1] . ' like ?';
                                        $params[] = $this->getLikeSql($matches[3]);
                                    } else {
                                        $buildSelectFields[$sqlOpperator][] = $matches[1] . $matches[2] .'?';
                                        $params[] = $matches[3];
                                    }
                                }
                            }
                            $i++;
                            continue;
                        }

                        //do like search on fragment
                        foreach($fields as $field) {
                            if($field == $fragment) {
                                if(isset($GLOBALS['TL_DCA'][$table]['fields'][$field])) {
                                    $buildSelectFields[$sqlOpperator][] = $field . ' like ?';
                                    $params[] = $this->getLikeSql($fragment);
                                }
                            }
                        }
                        $i++;
                    }

                    $sqlOpperator = 'OR';

                    if(empty($buildSelectFields)) {
                        if ($moduleArray['defaultSearchFields']) {
                            foreach ($moduleArray['defaultSearchFields'] as $field) {
                                if (isset($GLOBALS['TL_DCA'][$table]['fields'][$field])) {
                                    $buildSelectFields[$sqlOpperator][] = $field . ' like ?' ;
                                    $params[] = $this->getLikeSql($fragment);
                                }
                            }
                        }
                    }

                    if(!empty($buildSelectFields)) {
                        $subQuery .= ' WHERE ';
                        $i = 0;
                        foreach ($buildSelectFields as $opperator => $wheres) {
                            if($i != 0) {
                                if(count($opperator) == 1) {
                                    $subQuery .= ' '.$opperator.' ';
                                } else {
                                    $subQuery .= ' OR ';
                                }
                            }
                            $subQuery .= '('.implode(' '.$opperator.' ', $wheres).')';
                            $i++;
                        }
                    }
                    $subQuery .= ' LIMIT 20';

                    $queries[] = '('.$subQuery.')';

                }
            }

        }

        if($queries) {
            $query = 'SELECT allData.* FROM (';
            $query .= implode(' UNION ', $queries);
            $query .= ') AS allData LIMIT 20';

            if($_GET['debugQuery']) {
                echo $query;
                var_dump($params);
                exit;
            }

            $result = \Database::getInstance()->prepare($query)->execute($params);
            $this->query = $result->query;
            $data = $result->fetchAllAssoc();
            return $data;

        } else {
            return null;
        }

    }

    public function getModuleLink($module, $id)
    {

        global $GLOBALS;

        $modules = $this->modules;
        $table = 't_'.$module;
        if($GLOBALS['search_console'][$module]['table']) {
            $table = $GLOBALS['search_console'][$module]['table'];
        }

        \Controller::loadDataContainer();
    }

    public function getLikeSql($str)
    {
        return '%'.$str.'%';
    }

    public function search($action) {

        if($action != 'search_console') {
            return;
        }
        $search = \Input::postRaw('term');

        $return = $this->doSearch($search);

        header('Content-Type: application/json; charset=utf-8');
        echo json_encode($return);

        exit;

    }

    public function getModules()
    {

        global $GLOBALS;

        if(empty($this->modules)) {

            $modules = array();
            if($GLOBALS['search_console']['modules'] && is_array($GLOBALS['search_console']['modules'])) {

                $user = \BackendUser::getInstance();

                \Controller::loadLanguageFile('default');
                foreach ($GLOBALS['search_console']['modules'] as $module => $data) {

                    if($user->isAdmin || $user->hasAccess($data['module'], 'modules')) {

                    	if($data['table'] || $data['module']) {
	                        $label = $this->getLabelOfModule(($data['table']) ? $data['table'] : $data['module']);
    	                    $data['label'] = $label;
                        }
                        $modules[$module] = $data;
                    }
                }

                $this->modules = $modules;
            }

            return $this->modules;

        }

        return $this->modules;

    }

    /**
     * @return null|string
     */
    public function getQuery()
    {
        return $this->query;
    }

    protected function compile()
    {
        // TODO: Implement compile() method.
    }

    public function getAvailableShortcuts($search = null)
    {
        $modules = $this->getModules();

        $return = array();
        foreach ($modules as $module => $data) {

            //go to
            if($data['enableGoTo']) {
                $return[] = array(
                    'label' => 'go to '.$data['label'].'(g '.$data['shortcut'].')',
                    'value' => 'g '.$data['shortcut'],
                    'id' => 'g '.$data['shortcut'],
                    'category' => 'cmd',
                    'action' => 'redirect',
                    'url' => $this->getBaseUrl().'?do='.$data['module'].'&ref='.TL_REFERER_ID.'&rt='.\RequestToken::get()
                );
            }

            //new
            if($data['enableNew']) {
                $return[] = array(
                    'label' => 'new '.$data['label'].'(n '.$data['shortcut'].')',
                    'value' => 'n '.$data['shortcut'],
                    'id' => 'n '.$data['shortcut'],
                    'category' => 'cmd',
                    'action' => 'redirect',
                    'url' => $this->getBaseUrl().'?do='.$data['module'].'&act=paste&mode=create&ref='.TL_REFERER_ID.'&rt='.\RequestToken::get()
                );
            }

        }

        //cleanup
        if($search) {
            foreach($return as $k => $v) {
                if(substr($v['value'],0, strlen($search)) != $search) {
                    unset($return[$k]);
                }
            }
        }

        return $return;

    }

    public function getModuleByShortcut($shortcut)
    {

        $modules = $this->getModules();
        foreach($modules as $m => $data) {
            if($data['shortcut'] == $shortcut) {
                return $m;
            }
        }

        return null;

    }

    public function getFieldsFromDca($table, $search=null)
    {

        $return = array();

        \Controller::loadDataContainer($table);

        if($GLOBALS['TL_DCA'][$table]) {
            if($GLOBALS['TL_DCA'][$table]['fields']) {
                foreach($GLOBALS['TL_DCA'][$table]['fields'] as $field => $data) {

                    if(!in_array($field, $return)) {

                        $return[] = array(
                            'label' => $field.' '.$data['label'][0],
                            'value' => $field,
                            'id' => $field,
                            'category' => 'fields',
                        );
                    }
                }
            }
        }

        //cleanup
        if($search) {
            foreach($return as $k => $v) {
                if(substr($v['value'],0, strlen($search)) != $search) {
                    unset($return[$k]);
                }
            }
        }

        return $return;

    }

    public function getFields($search, $module = null) {

        global $GLOBALS;

        $return = array();

        $modules = $this->getModules();

        foreach($modules as $m => $data) {

            if($module) { //only fields from module
                if($m != $module) {
                    continue;
                }
            }

            if(strstr($GLOBALS['search_console']['modules'][$m]['module'], 'tl_') === false) {
            	$table = 'tl_'.$GLOBALS['search_console']['modules'][$m]['module'];
			} else {
            	$table = $GLOBALS['search_console']['modules'][$m]['module'];
			}
            if($GLOBALS['search_console']['modules'][$m]['table']) {
                $table = $GLOBALS['search_console']['modules'][$m]['table'];
            }

            $fields = $this->getFieldsFromDca($table, $search);

            if($GLOBALS['TL_DCA'][$table]) {
                if($GLOBALS['TL_DCA'][$table]['fields']) {
                    foreach($fields as $data) {
                        $return[] = $data;
                    }
                }
            }

        }

        //cleanup
        if($search) {
            foreach($return as $k => $v) {
                if(substr($v['value'],0, strlen($search)) != $search) {
                    unset($return[$k]);
                }
            }
        }

        return $return;
    }

    public function getBaseUrl()
    {
        $url = substr(\Idna::decode(\Environment::get('base')), 0, -1).\Environment::get('requestUri');
        $explode = explode('?', $url);
        return $explode[0];
    }

    public function injectJavascript($buffer, $template)
    {

        $user = \BackendUser::getInstance();
        if(!$user->authenticate()) {
            return $buffer;
        }

        if(!$user->enableSearchConsole) {
            return $buffer;
        }

		$hasJquery = strstr($buffer, 'jquery.');
        $hasJqueryUi = strstr($buffer, 'jquery-ui.');

        $script = '';
        if(!$hasJquery) {
            $script .= '';
        }
        if (!$hasJqueryUi) {
            $script .= '';
        }
        $js = array();
        $js['search_console_main'] = '/system/modules/search_console/html/js/search_console.js';

        foreach($js as $s) {
            $script .= '' . "\n";
        }

        $script .= '' . "\n";

        $css = array();
        if(!$hasJqueryUi) {
            $css['jquery_ui_css'] = '//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css';
        }
        $css['search_console_main'] = '/system/modules/search_console/html/css/search_console.css';
        foreach($css as $c) {
			$script .=  '<link rel="stylesheet" href="' . \Controller::addStaticUrlTo($c) . '">' . "\n";
        }

        $buffer = str_replace('', ''.$script, $buffer);
        return $buffer;

    }

    /**
     * @param $data
     * @return mixed
     */
    protected function getLabelOfModule($module)
    {

    	$table = $module;
        if(strstr($table, 'tl_') === false) {
			$table = 'tl_'.$table;
        }

		\Controller::loadDataContainer($module);

        $label = '';
        if ($module == 'tl_content') {
            $label = $GLOBALS['TL_LANG']['CTE']['alias'][0];
        } else if($GLOBALS['TL_LANG']['MOD'][$module][0]) {
            $label = $GLOBALS['TL_LANG']['MOD'][$module][0];
        } else if ($GLOBALS['TL_LANG']['CTE'][$module][0]) {
			$label = $GLOBALS['TL_LANG']['CTE'][$module][0];
		} else if ($GLOBALS['TL_LANG']['CTE'][$table][0]) {
            $label = $GLOBALS['TL_LANG']['CTE'][$table][0];
        } else if($GLOBALS['TL_LANG']['MOD'][$table][0]) {
			$label = $GLOBALS['TL_LANG']['MOD'][$table][0];
		}

		return $label;

    }

    public function getTableNameFromModule($module)
    {
        global $GLOBALS;

        $moduleArray = $GLOBALS['search_console']['modules'][$module];

        $table = '';

        if(strstr($moduleArray['module'], 'tl_') === false) {
            $table = 'tl_'.$moduleArray['module'];
        } else {
            $table = $moduleArray['module'];
        }
        if($moduleArray['table']) {
            $table = $moduleArray['table'];
        }

        return $table;

    }

    public function getAutocompleteFromDbField($table, $field, $search = null)
    {

        $query = '
                SELECT
                    '.$field.'
                FROM
                    '.$table.'
                GROUP BY
                    '.$field.'
                LIMIT
                    20
                ';

        $result = \Database::getInstance()->prepare($query)->execute()->fetchAllAssoc();

        $return = array();

        if($result) {
            foreach ($result as $data) {

                if(!$data[$field]) {
                    continue;
                }

                $return[] = array(
                    'label' => $data[$field],
                    'value' => $field.'='.$data[$field],
                    'id' => $data[$field],
                    'category' => 'fields',
                );
            }
        }

        //cleanup
        if($search) {
            foreach($return as $k => $v) {
                if(substr($v['label'],0, strlen($search)) != $search) {
                    unset($return[$k]);
                }
            }
        }

        return $return;

    }

}


text:
<?php

namespace Botonomous\listener;

use Botonomous\BotonomousException;
use Botonomous\Event;
use Botonomous\utility\StringUtility;

/**
 * Class EventListener.
 */
class EventListener extends AbstractBaseListener
{
    const KEY = 'event';
    const MISSING_TOKEN_OR_APP_ID_MESSAGE = 'Token or api_app_id is not provided';
    const MISSING_APP_ID_MESSAGE = 'Api app id must be provided';
    const MISSING_VERIFICATION_TOKEN_MESSAGE = 'Verification token must be provided';
    const MISSING_EVENT_TYPE_MESSAGE = 'Event type must be specified';

    private $token;
    private $teamId;
    private $appId;
    private $event;
    private $requestEventMaps = [
        'ts'       => 'timestamp',
        'event_ts' => 'eventTimestamp',
    ];

    /**
     * @return mixed
     */
    public function extractRequest()
    {
        return $this->getRequestUtility()->getPostedBody();
    }

    /**
     * @return string
     */
    public function getToken(): string
    {
        return $this->token;
    }

    /**
     * @param string $token
     */
    public function setToken(string $token)
    {
        $this->token = $token;
    }

    /**
     * @return string
     */
    public function getTeamId(): string
    {
        return $this->teamId;
    }

    /**
     * @param string $teamId
     */
    public function setTeamId(string $teamId)
    {
        $this->teamId = $teamId;
    }

    /**
     * @return string
     */
    public function getAppId(): string
    {
        return $this->appId;
    }

    /**
     * @param string $appId
     */
    public function setAppId(string $appId)
    {
        $this->appId = $appId;
    }

    /**
     * @throws \Exception
     *
     * @return Event
     */
    public function getEvent()
    {
        if (!isset($this->event)) {
            $this->loadEvent();
        }

        return $this->event;
    }

    /**
     * @param Event $event
     */
    public function setEvent(Event $event)
    {
        $this->event = $event;
    }

    /**
     * @throws \Exception
     */
    private function loadEvent()
    {
        $request = $this->getRequest();
        $eventKey = 'event';

        if (!isset($request[$eventKey])) {
            return;
        }

        $request = $request[$eventKey];
        if (!isset($request['type'])) {
            throw new BotonomousException(self::MISSING_EVENT_TYPE_MESSAGE);
        }

        // create the event
        $eventObject = new Event($request['type']);

        // exclude type from the args since it's already passed
        unset($request['type']);

        $stringUtility = new StringUtility();
        foreach ($request as $argKey => $argValue) {
            if (array_key_exists($argKey, $this->requestEventMaps)) {
                $argKey = $this->requestEventMaps[$argKey];
            }

            $setterName = 'set'.$stringUtility->snakeCaseToCamelCase($argKey);

            // ignore calling the method if setter does not exist
            if (!method_exists($eventObject, $setterName)) {
                continue;
            }

            $eventObject->$setterName($argValue);
        }

        // set it
        $this->setEvent($eventObject);
    }

    /**
     * @throws \Exception
     *
     * @return array<string,boolean|string>
     */
    public function verifyOrigin()
    {
        $request = $this->getRequest();

        if (!isset($request['token']) || !isset($request['api_app_id'])) {
            return [
                parent::ORIGIN_VERIFICATION_SUCCESS_KEY => false,
                parent::ORIGIN_VERIFICATION_MESSAGE_KEY => self::MISSING_TOKEN_OR_APP_ID_MESSAGE,
            ];
        }

        $verificationToken = $this->getConfig()->get('verificationToken');

        if (empty($verificationToken)) {
            throw new BotonomousException('Verification token must be provided');
        }

        $expectedAppId = $this->getConfig()->get('appId');

        if (empty($expectedAppId)) {
            throw new BotonomousException(self::MISSING_APP_ID_MESSAGE);
        }

        if ($verificationToken === $request['token'] &&
            $expectedAppId === $request['api_app_id']) {
            return [
                parent::ORIGIN_VERIFICATION_SUCCESS_KEY => true,
                parent::ORIGIN_VERIFICATION_MESSAGE_KEY => 'O La la!',
            ];
        }

        return [
            parent::ORIGIN_VERIFICATION_SUCCESS_KEY => false,
            parent::ORIGIN_VERIFICATION_MESSAGE_KEY => 'Token or api_app_id mismatch',
        ];
    }

    /**
     * Check if the request belongs to the bot itself.
     *
     * @throws \Exception
     *
     * @return bool
     */
    public function isThisBot(): bool
    {
        $subType = $this->getRequest('subtype');

        if ($subType === 'bot_message') {
            return true;
        }

        $event = $this->getEvent();

        return $event instanceof Event && !empty($event->getBotId());
    }

    /**
     * @throws \Exception
     *
     * @return string
     */
    public function getChannelId(): string
    {
        return $this->getEvent()->getChannel();
    }
}


text:
/* @flow */
import { objectReduce, hoistStatics } from 'fela-utils'
import generateDisplayName from './generateDisplayName'

export default function connectFactory(
  BaseComponent: any,
  createElement: Function,
  withTheme: Function,
  contextTypes?: Object
): Function {
  return function connect(rules: Object): Function {
    return (component: any): any => {
      class EnhancedComponent extends BaseComponent {
        static displayName = generateDisplayName(component)

        render() {
          const { renderer } = this.context

          const styles = objectReduce(
            rules,
            (styleMap, rule, name) => {
              styleMap[name] = renderer.renderRule(rule, this.props)
              return styleMap
            },
            {}
          )

          const { theme, ...propsWithoutTheme } = this.props
          return createElement(component, {
            ...propsWithoutTheme,
            styles
          })
        }
      }

      if (contextTypes) {
        EnhancedComponent.contextTypes = contextTypes
      }

      const themedComponent = withTheme(EnhancedComponent)
      return hoistStatics(themedComponent, component)
    }
  }
}


text:
layout: post
title: LMV to FITS
---

The documentation to [CLASS](https://www.iram.fr/IRAMFR/GILDAS/doc/html/class-html/class.html) is opaque.  Thus, trying to find how to convert LMV to FITS files is tricky.  Adam Ginsburg solved this, of course, and I simply consulted the [Codex Ginsburgium](http://keflavich.blogspot.ch/2010/12/converting-gildas-class-data-cubes-lmv.html).

To wit:

```
vector\fits outfile.fits from infile.lmv
```


text:
const issueRecover = require('./../emailTemplates/issueRecover');

const transporter = require('./email').transporter;

module.exports.sendConfidentialIssues = (from, to, recoveredUser, issues) => {
  mailOptions.from = from;
  mailOptions.to = to;
  mailOptions.attachments = [
    {
          path: "confidential.pdf"
    },
  ];
  mailOptions.subject = "Recovered confidetial issues for " + recoveredUser;

  mailOptions.html = issueRecover(recoveredUser);

  // mailOptions.text = 'You have recovered confidential issues for member' + recoveredUser + "\n" +
  //             "In the attachment confidential.pdf you can see all the confidential issues from the user";

  return transporter.sendMail(mailOptions);
};


text:
<?php

namespace d3acc;

class Module extends \yii\base\Module
{
    public $tableModels = [];

    public function getLabel(){
        return \Yii::t('d3acc', 'D3Acc');
    }
}


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
in Rabenhorst, Rabenh. Krypt. -Fl. (Leipzig) 1(3): 317 (1887)

#### Original name
Gibbera winteri Rehm

### Remarks
null


text:
package org.http4s

import cats.kernel.laws.discipline.EqTests
import org.http4s.laws.discipline.arbitrary._
import org.scalacheck.Arbitrary.arbitrary
import org.scalacheck.Prop.forAll
import org.scalacheck.Prop.propBoolean

class CharsetRangeSuite extends Http4sSuite {
  test("* should match all charsets") {
    forAll { (range: CharsetRange.`*`, cs: Charset) =>
      range.matches(cs)
    }
  }

  test("atomic charset ranges should match their own charsets") {
    forAll(arbitrary[CharsetRange.Atom]) { range =>
      range.matches(range.charset)
    }
  }

  test("atomic charset ranges should not be satisfied by any other charsets") {
    forAll { (range: CharsetRange.Atom, cs: Charset) =>
      range.charset != cs ==> !range.matches(cs)
    }
  }

  checkAll("CharsetRange", EqTests[CharsetRange].eqv)
}