text:
package yara

import (
	"bytes"
	"compress/bzip2"
	"fmt"
	"io/ioutil"
	"os"
	"os/exec"
	"reflect"
	"runtime"
	"testing"
)

func makeRules(t *testing.T, rule string) *Rules {
	c, err := NewCompiler()
	if c == nil || err != nil {
		t.Fatal("NewCompiler():", err)
	}
	if err = c.AddString(rule, ""); err != nil {
		t.Fatal("AddString():", err)
	}
	r, err := c.GetRules()
	if err != nil {
		t.Fatal("GetRules:", err)
	}
	return r
}

func TestSimpleMatch(t *testing.T) {
	r := makeRules(t,
		"rule test : tag1 { meta: author = \"Hilko Bengen\" strings: $a = \"abc\" fullword condition: $a }")
	var m MatchRules
	err := r.ScanMem([]byte(" abc "), 0, 0, &m)
	if err != nil {
		t.Errorf("ScanMem: %s", err)
	}
	t.Logf("Matches: %+v", m)
}

func TestSimpleFileMatch(t *testing.T) {
	r, _ := Compile(
		"rule test : tag1 { meta: author = \"Hilko Bengen\" strings: $a = \"abc\" fullword condition: $a }",
		nil)
	tf, _ := ioutil.TempFile("", "TestSimpleFileMatch")
	defer os.Remove(tf.Name())
	tf.Write([]byte(" abc "))
	tf.Close()
	var m MatchRules
	err := r.ScanFile(tf.Name(), 0, 0, &m)
	if err != nil {
		t.Errorf("ScanFile(%s): %s", tf.Name(), err)
	}
	t.Logf("Matches: %+v", m)
}

func TestSimpleFileDescriptorMatch(t *testing.T) {
	r, _ := Compile(
		"rule test : tag1 { meta: author = \"Hilko Bengen\" strings: $a = \"abc\" fullword condition: $a }",
		nil)
	tf, _ := ioutil.TempFile("", "TestSimpleFileMatch")
	defer os.Remove(tf.Name())
	tf.Write([]byte(" abc "))
	tf.Seek(0, os.SEEK_SET)
	var m MatchRules
	err := r.ScanFileDescriptor(tf.Fd(), 0, 0, &m)
	if err != nil {
		t.Errorf("ScanFileDescriptor(%s): %s", tf.Name(), err)
	}
	t.Logf("Matches: %+v", m)
}

func TestEmpty(t *testing.T) {
	r, _ := Compile("rule test { condition: true }", nil)
	r.ScanMem([]byte{}, 0, 0, nil)
	t.Log("Scan of null-byte slice did not crash. Yay.")
}

func assertTrueRules(t *testing.T, rules []string, data []byte) {
	for _, rule := range rules {
		r := makeRules(t, rule)
		var m MatchRules
		if err := r.ScanMem(data, 0, 0, &m); len(m) == 0 {
			t.Errorf("Rule < %s > did not match data < %v >", rule, data)
		} else if err != nil {
			t.Errorf("Error %s", err)
		}
	}
}

func assertFalseRules(t *testing.T, rules []string, data []byte) {
	for _, rule := range rules {
		r := makeRules(t, rule)
		var m MatchRules
		if err := r.ScanMem(data, 0, 0, &m); len(m) > 0 {
			t.Errorf("Rule < %s > matched data < %v >", rule, data)
		} else if err != nil {
			t.Errorf("Error %s", err)
		}
	}
}

func TestLoad(t *testing.T) {
	r, err := LoadRules(compiledTestRulesPath)
	if r == nil || err != nil {
		t.Fatalf("LoadRules: %s", err)
	}
}

func TestReader(t *testing.T) {
	rd, err := os.Open(compiledTestRulesPath)
	if err != nil {
		t.Fatalf("os.Open: %s", err)
	}
	r, err := ReadRules(rd)
	if err != nil {
		t.Fatalf("ReadRules: %+v", err)
	}
	var m MatchRules
	if err := r.ScanMem([]byte(" abc "), 0, 0, &m); err != nil {
		t.Errorf("ScanMem: %s", err)
	}
	t.Logf("Matches: %+v", m)
}

func TestWriter(t *testing.T) {
	rd, err := os.Open(compiledTestRulesPath)
	if err != nil {
		t.Fatalf("os.Open: %s", err)
	}
	compareBuf, _ := ioutil.ReadAll(rd)
	r, _ := Compile("rule test : tag1 { meta: author = \"Hilko Bengen\" strings: $a = \"abc\" fullword condition: $a }",
		nil)
	wr := bytes.Buffer{}
	if err := r.Write(&wr); err != nil {
		t.Fatal(err)
	}
	newBuf := wr.Bytes()
	if len(compareBuf) != len(newBuf) {
		t.Errorf("len(compareBuf) = %d, len(newBuf) = %d", len(compareBuf), len(newBuf))
	}
	if bytes.Compare(compareBuf, newBuf) != 0 {
		t.Error("buffers are not equal")
	}
}

// in Go 1.8 this code does not work in go-yara 1.0.2
// go 1.8/debian stretch panics
// go 1.8/darwin produces stack overflow
func TestWriterBuffer(t *testing.T) {
	rulesBuf := bytes.NewBuffer(nil)
	for i := 0; i < 10000; i++ {
		fmt.Fprintf(rulesBuf, "rule test%d : tag%d { meta: author = \"Hilko Bengen\" strings: $a = \"abc\" fullword condition: $a }", i, i)
	}
	r, _ := Compile(string(rulesBuf.Bytes()), nil)
	buf := new(bytes.Buffer)
	if err := r.Write(buf); err != nil {
		t.Fatalf("write to bytes.Buffer: %s", err)
	}
}

// compress/bzip2 seems to return short reads which apparently leads
// to YARA complaining about corrupt files. Tested with Go 1.4, 1.5.
func TestReaderBZIP2(t *testing.T) {
	rulesBuf := bytes.NewBuffer(nil)
	for i := 0; i < 10000; i++ {
		fmt.Fprintf(rulesBuf, "rule test%d : tag%d { meta: author = \"Hilko Bengen\" strings: $a = \"abc\" fullword condition: $a }", i, i)
	}
	r, err := Compile(string(rulesBuf.Bytes()), nil)
	if err != nil {
		t.Fatalf("compile text for bzip2 rule compression: %s", err)
	}
	cmd := exec.Command("bzip2", "-c")
	compressStream, _ := cmd.StdinPipe()
	buf := bytes.NewBuffer(nil)
	cmd.Stdout = buf
	if err := cmd.Start(); err != nil {
		t.Fatalf("start bzip2 process: %s", err)
	}
	if err := r.Write(compressStream); err != nil {
		t.Fatalf("pipe to bzip2 process: %s", err)
	}
	compressStream.Close()
	if err := cmd.Wait(); err != nil {
		t.Fatalf("wait for bzip2 process: %s", err)
	}
	if _, err := ReadRules(bzip2.NewReader(bytes.NewReader(buf.Bytes()))); err != nil {
		t.Fatalf("read using compress/bzip2: %s", err)
	}
}

// See https://github.com/hillu/go-yara/issues/5
func TestScanMemCgoPointer(t *testing.T) {
	r := makeRules(t,
		"rule test : tag1 { meta: author = \"Hilko Bengen\" strings: $a = \"abc\" fullword condition: $a }")
	buf := &bytes.Buffer{}
	buf.Write([]byte(" abc "))
	if err := func() (p interface{}) {
		defer func() { p = recover() }()
		r.ScanMem(buf.Bytes(), 0, 0, nil)
		return nil
	}(); err != nil {
		t.Errorf("ScanMem panicked: %s", err)
	}
}

type rule struct {
	identifier      string
	tags            []string
	metas           []Meta
	private, global bool
}

func TestRule(t *testing.T) {
	rs := makeRules(t, `
		rule t1 : tag1 { meta: author = "Author One" strings: $a = "abc" fullword condition: $a }
        rule t2 : tag2 x y { meta: author = "Author Two" strings: $b = "def" condition: $b }
        rule t3 : tag3 x y z { meta: author = "Author Three" strings: $c = "ghi" condition: $c }
		rule t4 { strings: $d = "qwe" condition: $d }
		private rule t5 { condition: false }
		global rule t6 { condition: false }`)
	expected := []rule{
		rule{"t1", []string{"tag1"}, []Meta{{"author", "Author One"}}, false, false},
		rule{"t2", []string{"tag2", "x", "y"}, []Meta{{"author", "Author Two"}}, false, false},
		rule{"t3", []string{"tag3", "x", "y", "z"}, []Meta{{"author", "Author Three"}}, false, false},
		rule{"t4", nil, nil, false, false},
		rule{"t5", nil, nil, true, false},
		rule{"t6", nil, nil, false, true},
	}
	var got []rule
	for _, r := range rs.GetRules() {
		got = append(got, rule{identifier: r.Identifier(), metas: r.Metas(), tags: r.Tags(), private: r.IsPrivate(), global: r.IsGlobal()})
	}
	if !reflect.DeepEqual(got, expected) {
		t.Errorf("Got %+v , expected %+v", got, expected)
	}
}

type testCallback struct {
	t          *testing.T
	finished   bool
	modules    map[string]struct{}
	matched    map[string]struct{}
	notMatched map[string]struct{}
	logged     []string
}

func newTestCallback(t *testing.T) *testCallback {
	return &testCallback{
		t, false,
		make(map[string]struct{}),
		make(map[string]struct{}),
		make(map[string]struct{}),
		nil,
	}
}

func (c *testCallback) RuleMatching(_ *ScanContext, r *Rule) (bool, error) {
	c.t.Logf("RuleMatching callback called: rule=%s", r.Identifier())
	c.matched[r.Identifier()] = struct{}{}
	return false, nil
}
func (c *testCallback) RuleNotMatching(_ *ScanContext, r *Rule) (bool, error) {
	c.t.Logf("RuleNotMatching callback called: rule=%s", r.Identifier())
	c.notMatched[r.Identifier()] = struct{}{}
	return false, nil
}
func (c *testCallback) ScanFinished(*ScanContext) (bool, error) {
	c.t.Log("ScanFinished callback called")
	c.finished = true
	return false, nil
}
func (c *testCallback) ImportModule(_ *ScanContext, s string) ([]byte, bool, error) {
	c.t.Logf("ImportModule callback called: module=%s", s)
	c.modules[s] = struct{}{}
	if s == "tests" {
		return []byte("callback-data-for-tests-module"), false, nil
	}
	return nil, false, nil
}
func (c *testCallback) ModuleImported(*ScanContext, *Object) (bool, error) {
	c.t.Log("ModuleImported callback called")
	return false, nil
}
func (c *testCallback) ConsoleLog(_ *ScanContext, s string) {
	c.logged = append(c.logged, s)
}

func TestImportDataCallback(t *testing.T) {
	cb := newTestCallback(t)
	r := makeRules(t, `
		import "tests"
		import "pe"
		rule t1 { condition: true }
		rule t2 { condition: false }
		rule t3 {
			condition: tests.module_data == "callback-data-for-tests-module"
		}`)
	if err := r.ScanMem([]byte(""), 0, 0, cb); err != nil {
		t.Error(err)
	}
	for _, module := range []string{"tests", "pe"} {
		if _, ok := cb.modules[module]; !ok {
			t.Errorf("ImportModule was not called for %s", module)
		}
	}
	for _, rule := range []string{"t1", "t3"} {
		if _, ok := cb.matched["t1"]; !ok {
			t.Errorf("RuleMatching was not called for %s", rule)
		}
	}
	if _, ok := cb.notMatched["t2"]; !ok {
		t.Errorf("RuleNotMatching was not called for %s", "t2")
	}
	if !cb.finished {
		t.Errorf("ScanFinished was not called")
	}
	runtime.GC()
}

func TestConsoleCallback(t *testing.T) {
	cb := newTestCallback(t)
	r := makeRules(t, `
        import "console"
		rule t { condition: console.log("hello world") }
        `)

	if err := r.ScanMem([]byte(""), 0, 0, cb); err != nil {
		t.Error(err)
	}
	if len(cb.logged) < 1 || cb.logged[0] != "hello world" {
		t.Errorf("console log does not containi expected hello world string: %v", cb.logged)
	}
}


text:
module Inthegra
  class Client
    # Define methods related to bus_stops
    module BusStops

      # Return a list of all bus_stops
      #
      # @return [Array::BusStop] All bus stops
      # @example Return all bus stops
      #   Inthegra.bus_stops
      # @authenticated true
      # @see https://inthegra.strans.teresina.pi.gov.br/docs#paradas
      def bus_stops
        response = get('paradas')

        CollectionSerializer.parse(response, BusStop)
      end

      # Return a list of all searched bus stops
      #
      # @param query [String] An search query
      # @return [Array::BusStop] All bus stops returned by search
      # @example Return a list of all bus stops localized in 'ininga' neighborhood
      #   Inthegra.bus_stops_search('ininga')
      # @authenticated true
      # @see https://inthegra.strans.teresina.pi.gov.br/docs#paradas
      def bus_stops_search(query)
        response = get('paradas', { busca: URI::encode(query) })

        CollectionSerializer.parse(response, BusStop)
      end

      # Return all bus stops of the line code passed
      #
      # @param line_code [String] An line code
      # @return [Array::BusStop] All bus stops in the line
      # @example Return a list of all bus stops by the line code passed
      #   Inthegra.line_search('0401')
      # @authenticated true
      # @see https://inthegra.strans.teresina.pi.gov.br/docs#paradas
      def bus_stops_by_line(line_code)
        response = get('paradasLinha', { busca: URI::encode(line_code) })

        CollectionSerializer.parse(response['Paradas'], BusStop)
      end

    end
  end
end

redpajama_set_name: RedPajamaGithub


text:
namespace ceres {

// Trivial wrapper to index linear arrays as matrices, given a fixed
// column and row stride. When an array "T* array" is wrapped by a
//
//   (const) MatrixAdapter<T, row_stride, col_stride> M"
//
// the expression  M(i, j) is equivalent to
//
//   arrary[i * row_stride + j * col_stride]
//
// Conversion functions to and from rotation matrices accept
// MatrixAdapters to permit using row-major and column-major layouts,
// and rotation matrices embedded in larger matrices (such as a 3x4
// projection matrix).
template <typename T, int row_stride, int col_stride>
struct MatrixAdapter;

// Convenience functions to create a MatrixAdapter that treats the
// array pointed to by "pointer" as a 3x3 (contiguous) column-major or
// row-major matrix.
template <typename T>
MatrixAdapter<T, 1, 3> ColumnMajorAdapter3x3(T* pointer);

template <typename T>
MatrixAdapter<T, 3, 1> RowMajorAdapter3x3(T* pointer);

// Convert a value in combined axis-angle representation to a quaternion.
// The value angle_axis is a triple whose norm is an angle in radians,
// and whose direction is aligned with the axis of rotation,
// and quaternion is a 4-tuple that will contain the resulting quaternion.
// The implementation may be used with auto-differentiation up to the first
// derivative, higher derivatives may have unexpected results near the origin.
template<typename T>
void AngleAxisToQuaternion(const T* angle_axis, T* quaternion);

// Convert a quaternion to the equivalent combined axis-angle representation.
// The value quaternion must be a unit quaternion - it is not normalized first,
// and angle_axis will be filled with a value whose norm is the angle of
// rotation in radians, and whose direction is the axis of rotation.
// The implemention may be used with auto-differentiation up to the first
// derivative, higher derivatives may have unexpected results near the origin.
template<typename T>
void QuaternionToAngleAxis(const T* quaternion, T* angle_axis);

// Conversions between 3x3 rotation matrix (in column major order) and
// quaternion rotation representations.  Templated for use with
// autodifferentiation.
template <typename T>
void RotationMatrixToQuaternion(const T* R, T* quaternion);

template <typename T, int row_stride, int col_stride>
void RotationMatrixToQuaternion(
    const MatrixAdapter<const T, row_stride, col_stride>& R,
    T* quaternion);

// Conversions between 3x3 rotation matrix (in column major order) and
// axis-angle rotation representations.  Templated for use with
// autodifferentiation.
template <typename T>
void RotationMatrixToAngleAxis(const T* R, T* angle_axis);

template <typename T, int row_stride, int col_stride>
void RotationMatrixToAngleAxis(
    const MatrixAdapter<const T, row_stride, col_stride>& R,
    T* angle_axis);

template <typename T>
void AngleAxisToRotationMatrix(const T* angle_axis, T* R);

template <typename T, int row_stride, int col_stride>
void AngleAxisToRotationMatrix(
    const T* angle_axis,
    const MatrixAdapter<T, row_stride, col_stride>& R);

// Conversions between 3x3 rotation matrix (in row major order) and
// Euler angle (in degrees) rotation representations.
//
// The {pitch,roll,yaw} Euler angles are rotations around the {x,y,z}
// axes, respectively.  They are applied in that same order, so the
// total rotation R is Rz * Ry * Rx.
template <typename T>
void EulerAnglesToRotationMatrix(const T* euler, int row_stride, T* R);

template <typename T, int row_stride, int col_stride>
void EulerAnglesToRotationMatrix(
    const T* euler,
    const MatrixAdapter<T, row_stride, col_stride>& R);

// Convert a 4-vector to a 3x3 scaled rotation matrix.
//
// The choice of rotation is such that the quaternion [1 0 0 0] goes to an
// identity matrix and for small a, b, c the quaternion [1 a b c] goes to
// the matrix
//
//         [  0 -c  b ]
//   I + 2 [  c  0 -a ] + higher order terms
//         [ -b  a  0 ]
//
// which corresponds to a Rodrigues approximation, the last matrix being
// the cross-product matrix of [a b c]. Together with the property that
// R(q1 * q2) = R(q1) * R(q2) this uniquely defines the mapping from q to R.
//
// No normalization of the quaternion is performed, i.e.
// R = ||q||^2 * Q, where Q is an orthonormal matrix
// such that det(Q) = 1 and Q*Q' = I
//
// WARNING: The rotation matrix is ROW MAJOR
template <typename T> inline
void QuaternionToScaledRotation(const T q[4], T R[3 * 3]);

template <typename T, int row_stride, int col_stride> inline
void QuaternionToScaledRotation(
    const T q[4],
    const MatrixAdapter<T, row_stride, col_stride>& R);

// Same as above except that the rotation matrix is normalized by the
// Frobenius norm, so that R * R' = I (and det(R) = 1).
//
// WARNING: The rotation matrix is ROW MAJOR
template <typename T> inline
void QuaternionToRotation(const T q[4], T R[3 * 3]);

template <typename T, int row_stride, int col_stride> inline
void QuaternionToRotation(
    const T q[4],
    const MatrixAdapter<T, row_stride, col_stride>& R);

// Rotates a point pt by a quaternion q:
//
//   result = R(q) * pt
//
// Assumes the quaternion is unit norm. This assumption allows us to
// write the transform as (something)*pt + pt, as is clear from the
// formula below. If you pass in a quaternion with |q|^2 = 2 then you
// WILL NOT get back 2 times the result you get for a unit quaternion.
template <typename T> inline
void UnitQuaternionRotatePoint(const T q[4], const T pt[3], T result[3]);

// With this function you do not need to assume that q has unit norm.
// It does assume that the norm is non-zero.
template <typename T> inline
void QuaternionRotatePoint(const T q[4], const T pt[3], T result[3]);

// zw = z * w, where * is the Quaternion product between 4 vectors.
template<typename T> inline
void QuaternionProduct(const T z[4], const T w[4], T zw[4]);

// xy = x cross y;
template<typename T> inline
void CrossProduct(const T x[3], const T y[3], T x_cross_y[3]);

template<typename T> inline
T DotProduct(const T x[3], const T y[3]);

// y = R(angle_axis) * x;
template<typename T> inline
void AngleAxisRotatePoint(const T angle_axis[3], const T pt[3], T result[3]);

// --- IMPLEMENTATION

template<typename T, int row_stride, int col_stride>
struct MatrixAdapter {
  T* pointer_;
  explicit MatrixAdapter(T* pointer)
    : pointer_(pointer)
  {}

  T& operator()(int r, int c) const {
    return pointer_[r * row_stride + c * col_stride];
  }
};

template <typename T>
MatrixAdapter<T, 1, 3> ColumnMajorAdapter3x3(T* pointer) {
  return MatrixAdapter<T, 1, 3>(pointer);
}

template <typename T>
MatrixAdapter<T, 3, 1> RowMajorAdapter3x3(T* pointer) {
  return MatrixAdapter<T, 3, 1>(pointer);
}

template<typename T>
inline void AngleAxisToQuaternion(const T* angle_axis, T* quaternion) {
  const T& a0 = angle_axis[0];
  const T& a1 = angle_axis[1];
  const T& a2 = angle_axis[2];
  const T theta_squared = a0 * a0 + a1 * a1 + a2 * a2;

  // For points not at the origin, the full conversion is numerically stable.
  if (theta_squared > T(0.0)) {
    const T theta = sqrt(theta_squared);
    const T half_theta = theta * T(0.5);
    const T k = sin(half_theta) / theta;
    quaternion[0] = cos(half_theta);
    quaternion[1] = a0 * k;
    quaternion[2] = a1 * k;
    quaternion[3] = a2 * k;
  } else {
    // At the origin, sqrt() will produce NaN in the derivative since
    // the argument is zero.  By approximating with a Taylor series,
    // and truncating at one term, the value and first derivatives will be
    // computed correctly when Jets are used.
    const T k(0.5);
    quaternion[0] = T(1.0);
    quaternion[1] = a0 * k;
    quaternion[2] = a1 * k;
    quaternion[3] = a2 * k;
  }
}

template<typename T>
inline void QuaternionToAngleAxis(const T* quaternion, T* angle_axis) {
  const T& q1 = quaternion[1];
  const T& q2 = quaternion[2];
  const T& q3 = quaternion[3];
  const T sin_squared_theta = q1 * q1 + q2 * q2 + q3 * q3;

  // For quaternions representing non-zero rotation, the conversion
  // is numerically stable.
  if (sin_squared_theta > T(0.0)) {
    const T sin_theta = sqrt(sin_squared_theta);
    const T& cos_theta = quaternion[0];

    // If cos_theta is negative, theta is greater than pi/2, which
    // means that angle for the angle_axis vector which is 2 * theta
    // would be greater than pi.
    //
    // While this will result in the correct rotation, it does not
    // result in a normalized angle-axis vector.
    //
    // In that case we observe that 2 * theta ~ 2 * theta - 2 * pi,
    // which is equivalent saying
    //
    //   theta - pi = atan(sin(theta - pi), cos(theta - pi))
    //              = atan(-sin(theta), -cos(theta))
    //
    const T two_theta =
        T(2.0) * ((cos_theta < 0.0)
                  ? atan2(-sin_theta, -cos_theta)
                  : atan2(sin_theta, cos_theta));
    const T k = two_theta / sin_theta;
    angle_axis[0] = q1 * k;
    angle_axis[1] = q2 * k;
    angle_axis[2] = q3 * k;
  } else {
    // For zero rotation, sqrt() will produce NaN in the derivative since
    // the argument is zero.  By approximating with a Taylor series,
    // and truncating at one term, the value and first derivatives will be
    // computed correctly when Jets are used.
    const T k(2.0);
    angle_axis[0] = q1 * k;
    angle_axis[1] = q2 * k;
    angle_axis[2] = q3 * k;
  }
}

template <typename T>
void RotationMatrixToQuaternion(const T* R, T* angle_axis) {
  RotationMatrixToQuaternion(ColumnMajorAdapter3x3(R), angle_axis);
}

// This algorithm comes from "Quaternion Calculus and Fast Animation",
// Ken Shoemake, 1987 SIGGRAPH course notes
template <typename T, int row_stride, int col_stride>
void RotationMatrixToQuaternion(
    const MatrixAdapter<const T, row_stride, col_stride>& R,
    T* quaternion) {
  const T trace = R(0, 0) + R(1, 1) + R(2, 2);
  if (trace >= 0.0) {
    T t = sqrt(trace + T(1.0));
    quaternion[0] = T(0.5) * t;
    t = T(0.5) / t;
    quaternion[1] = (R(2, 1) - R(1, 2)) * t;
    quaternion[2] = (R(0, 2) - R(2, 0)) * t;
    quaternion[3] = (R(1, 0) - R(0, 1)) * t;
  } else {
    int i = 0;
    if (R(1, 1) > R(0, 0)) {
      i = 1;
    }

    if (R(2, 2) > R(i, i)) {
      i = 2;
    }

    const int j = (i + 1) % 3;
    const int k = (j + 1) % 3;
    T t = sqrt(R(i, i) - R(j, j) - R(k, k) + T(1.0));
    quaternion[i + 1] = T(0.5) * t;
    t = T(0.5) / t;
    quaternion[0] = (R(k, j) - R(j, k)) * t;
    quaternion[j + 1] = (R(j, i) + R(i, j)) * t;
    quaternion[k + 1] = (R(k, i) + R(i, k)) * t;
  }
}

// The conversion of a rotation matrix to the angle-axis form is
// numerically problematic when then rotation angle is close to zero
// or to Pi. The following implementation detects when these two cases
// occurs and deals with them by taking code paths that are guaranteed
// to not perform division by a small number.
template <typename T>
inline void RotationMatrixToAngleAxis(const T* R, T* angle_axis) {
  RotationMatrixToAngleAxis(ColumnMajorAdapter3x3(R), angle_axis);
}

template <typename T, int row_stride, int col_stride>
void RotationMatrixToAngleAxis(
    const MatrixAdapter<const T, row_stride, col_stride>& R,
    T* angle_axis) {
  T quaternion[4];
  RotationMatrixToQuaternion(R, quaternion);
  QuaternionToAngleAxis(quaternion, angle_axis);
  return;
}

template <typename T>
inline void AngleAxisToRotationMatrix(const T* angle_axis, T* R) {
  AngleAxisToRotationMatrix(angle_axis, ColumnMajorAdapter3x3(R));
}

template <typename T, int row_stride, int col_stride>
void AngleAxisToRotationMatrix(
    const T* angle_axis,
    const MatrixAdapter<T, row_stride, col_stride>& R) {
  static const T kOne = T(1.0);
  const T theta2 = DotProduct(angle_axis, angle_axis);
  if (theta2 > T(std::numeric_limits<double>::epsilon())) {
    // We want to be careful to only evaluate the square root if the
    // norm of the angle_axis vector is greater than zero. Otherwise
    // we get a division by zero.
    const T theta = sqrt(theta2);
    const T wx = angle_axis[0] / theta;
    const T wy = angle_axis[1] / theta;
    const T wz = angle_axis[2] / theta;

    const T costheta = cos(theta);
    const T sintheta = sin(theta);

    R(0, 0) =     costheta   + wx*wx*(kOne -    costheta);
    R(1, 0) =  wz*sintheta   + wx*wy*(kOne -    costheta);
    R(2, 0) = -wy*sintheta   + wx*wz*(kOne -    costheta);
    R(0, 1) =  wx*wy*(kOne - costheta)     - wz*sintheta;
    R(1, 1) =     costheta   + wy*wy*(kOne -    costheta);
    R(2, 1) =  wx*sintheta   + wy*wz*(kOne -    costheta);
    R(0, 2) =  wy*sintheta   + wx*wz*(kOne -    costheta);
    R(1, 2) = -wx*sintheta   + wy*wz*(kOne -    costheta);
    R(2, 2) =     costheta   + wz*wz*(kOne -    costheta);
  } else {
    // Near zero, we switch to using the first order Taylor expansion.
    R(0, 0) =  kOne;
    R(1, 0) =  angle_axis[2];
    R(2, 0) = -angle_axis[1];
    R(0, 1) = -angle_axis[2];
    R(1, 1) =  kOne;
    R(2, 1) =  angle_axis[0];
    R(0, 2) =  angle_axis[1];
    R(1, 2) = -angle_axis[0];
    R(2, 2) = kOne;
  }
}

template <typename T>
inline void EulerAnglesToRotationMatrix(const T* euler,
                                        const int row_stride_parameter,
                                        T* R) {
  CHECK_EQ(row_stride_parameter, 3);
  EulerAnglesToRotationMatrix(euler, RowMajorAdapter3x3(R));
}

template <typename T, int row_stride, int col_stride>
void EulerAnglesToRotationMatrix(
    const T* euler,
    const MatrixAdapter<T, row_stride, col_stride>& R) {
  const double kPi = 3.14159265358979323846;
  const T degrees_to_radians(kPi / 180.0);

  const T pitch(euler[0] * degrees_to_radians);
  const T roll(euler[1] * degrees_to_radians);
  const T yaw(euler[2] * degrees_to_radians);

  const T c1 = cos(yaw);
  const T s1 = sin(yaw);
  const T c2 = cos(roll);
  const T s2 = sin(roll);
  const T c3 = cos(pitch);
  const T s3 = sin(pitch);

  R(0, 0) = c1*c2;
  R(0, 1) = -s1*c3 + c1*s2*s3;
  R(0, 2) = s1*s3 + c1*s2*c3;

  R(1, 0) = s1*c2;
  R(1, 1) = c1*c3 + s1*s2*s3;
  R(1, 2) = -c1*s3 + s1*s2*c3;

  R(2, 0) = -s2;
  R(2, 1) = c2*s3;
  R(2, 2) = c2*c3;
}

template <typename T> inline
void QuaternionToScaledRotation(const T q[4], T R[3 * 3]) {
  QuaternionToScaledRotation(q, RowMajorAdapter3x3(R));
}

template <typename T, int row_stride, int col_stride> inline
void QuaternionToScaledRotation(
    const T q[4],
    const MatrixAdapter<T, row_stride, col_stride>& R) {
  // Make convenient names for elements of q.
  T a = q[0];
  T b = q[1];
  T c = q[2];
  T d = q[3];
  // This is not to eliminate common sub-expression, but to
  // make the lines shorter so that they fit in 80 columns!
  T aa = a * a;
  T ab = a * b;
  T ac = a * c;
  T ad = a * d;
  T bb = b * b;
  T bc = b * c;
  T bd = b * d;
  T cc = c * c;
  T cd = c * d;
  T dd = d * d;

  R(0, 0) = aa + bb - cc - dd; R(0, 1) = T(2) * (bc - ad);  R(0, 2) = T(2) * (ac + bd);  // NOLINT
  R(1, 0) = T(2) * (ad + bc);  R(1, 1) = aa - bb + cc - dd; R(1, 2) = T(2) * (cd - ab);  // NOLINT
  R(2, 0) = T(2) * (bd - ac);  R(2, 1) = T(2) * (ab + cd);  R(2, 2) = aa - bb - cc + dd; // NOLINT
}

template <typename T> inline
void QuaternionToRotation(const T q[4], T R[3 * 3]) {
  QuaternionToRotation(q, RowMajorAdapter3x3(R));
}

template <typename T, int row_stride, int col_stride> inline
void QuaternionToRotation(const T q[4],
                          const MatrixAdapter<T, row_stride, col_stride>& R) {
  QuaternionToScaledRotation(q, R);

  T normalizer = q[0]*q[0] + q[1]*q[1] + q[2]*q[2] + q[3]*q[3];
  CHECK_NE(normalizer, T(0));
  normalizer = T(1) / normalizer;

  for (int i = 0; i < 3; ++i) {
    for (int j = 0; j < 3; ++j) {
      R(i, j) *= normalizer;
    }
  }
}

template <typename T> inline
void UnitQuaternionRotatePoint(const T q[4], const T pt[3], T result[3]) {
  const T t2 =  q[0] * q[1];
  const T t3 =  q[0] * q[2];
  const T t4 =  q[0] * q[3];
  const T t5 = -q[1] * q[1];
  const T t6 =  q[1] * q[2];
  const T t7 =  q[1] * q[3];
  const T t8 = -q[2] * q[2];
  const T t9 =  q[2] * q[3];
  const T t1 = -q[3] * q[3];
  result[0] = T(2) * ((t8 + t1) * pt[0] + (t6 - t4) * pt[1] + (t3 + t7) * pt[2]) + pt[0];  // NOLINT
  result[1] = T(2) * ((t4 + t6) * pt[0] + (t5 + t1) * pt[1] + (t9 - t2) * pt[2]) + pt[1];  // NOLINT
  result[2] = T(2) * ((t7 - t3) * pt[0] + (t2 + t9) * pt[1] + (t5 + t8) * pt[2]) + pt[2];  // NOLINT
}

template <typename T> inline
void QuaternionRotatePoint(const T q[4], const T pt[3], T result[3]) {
  // 'scale' is 1 / norm(q).
  const T scale = T(1) / sqrt(q[0] * q[0] +
                              q[1] * q[1] +
                              q[2] * q[2] +
                              q[3] * q[3]);

  // Make unit-norm version of q.
  const T unit[4] = {
    scale * q[0],
    scale * q[1],
    scale * q[2],
    scale * q[3],
  };

  UnitQuaternionRotatePoint(unit, pt, result);
}

template<typename T> inline
void QuaternionProduct(const T z[4], const T w[4], T zw[4]) {
  zw[0] = z[0] * w[0] - z[1] * w[1] - z[2] * w[2] - z[3] * w[3];
  zw[1] = z[0] * w[1] + z[1] * w[0] + z[2] * w[3] - z[3] * w[2];
  zw[2] = z[0] * w[2] - z[1] * w[3] + z[2] * w[0] + z[3] * w[1];
  zw[3] = z[0] * w[3] + z[1] * w[2] - z[2] * w[1] + z[3] * w[0];
}

// xy = x cross y;
template<typename T> inline
void CrossProduct(const T x[3], const T y[3], T x_cross_y[3]) {
  x_cross_y[0] = x[1] * y[2] - x[2] * y[1];
  x_cross_y[1] = x[2] * y[0] - x[0] * y[2];
  x_cross_y[2] = x[0] * y[1] - x[1] * y[0];
}

template<typename T> inline
T DotProduct(const T x[3], const T y[3]) {
  return (x[0] * y[0] + x[1] * y[1] + x[2] * y[2]);
}

template<typename T> inline
void AngleAxisRotatePoint(const T angle_axis[3], const T pt[3], T result[3]) {
  const T theta2 = DotProduct(angle_axis, angle_axis);
  if (theta2 > T(std::numeric_limits<double>::epsilon())) {
    // Away from zero, use the rodriguez formula
    //
    //   result = pt costheta +
    //            (w x pt) * sintheta +
    //            w (w . pt) (1 - costheta)
    //
    // We want to be careful to only evaluate the square root if the
    // norm of the angle_axis vector is greater than zero. Otherwise
    // we get a division by zero.
    //
    const T theta = sqrt(theta2);
    const T costheta = cos(theta);
    const T sintheta = sin(theta);
    const T theta_inverse = 1.0 / theta;

    const T w[3] = { angle_axis[0] * theta_inverse,
                     angle_axis[1] * theta_inverse,
                     angle_axis[2] * theta_inverse };

    // Explicitly inlined evaluation of the cross product for
    // performance reasons.
    const T w_cross_pt[3] = { w[1] * pt[2] - w[2] * pt[1],
                              w[2] * pt[0] - w[0] * pt[2],
                              w[0] * pt[1] - w[1] * pt[0] };
    const T tmp =
        (w[0] * pt[0] + w[1] * pt[1] + w[2] * pt[2]) * (T(1.0) - costheta);

    result[0] = pt[0] * costheta + w_cross_pt[0] * sintheta + w[0] * tmp;
    result[1] = pt[1] * costheta + w_cross_pt[1] * sintheta + w[1] * tmp;
    result[2] = pt[2] * costheta + w_cross_pt[2] * sintheta + w[2] * tmp;
  } else {
    // Near zero, the first order Taylor approximation of the rotation
    // matrix R corresponding to a vector w and angle w is
    //
    //   R = I + hat(w) * sin(theta)
    //
    // But sintheta ~ theta and theta * w = angle_axis, which gives us
    //
    //  R = I + hat(w)
    //
    // and actually performing multiplication with the point pt, gives us
    // R * pt = pt + w x pt.
    //
    // Switching to the Taylor expansion near zero provides meaningful
    // derivatives when evaluated using Jets.
    //
    // Explicitly inlined evaluation of the cross product for
    // performance reasons.
    const T w_cross_pt[3] = { angle_axis[1] * pt[2] - angle_axis[2] * pt[1],
                              angle_axis[2] * pt[0] - angle_axis[0] * pt[2],
                              angle_axis[0] * pt[1] - angle_axis[1] * pt[0] };

    result[0] = pt[0] + w_cross_pt[0];
    result[1] = pt[1] + w_cross_pt[1];
    result[2] = pt[2] + w_cross_pt[2];
  }
}

}  // namespace ceres

#endif  // CERES_PUBLIC_ROTATION_H_


text:
names = ["dora", "spider man ", "papa smurf", "captain america", "mario"]
# The first element of the sequence is at index 0
print("First element in the list", names[0])
print("First element in the list", names[-0])
# The last element of the sequence is at index -1
print("First element in the list", names[-5])

# Slicing is a form of extended indexing which allows us to refer to portions of a list
print("Slicing")
print("Get three elements from index 1", names[1:1 + 3])
print("Get all elements in the except first and last", names[1:-1])
print("Get all elements in the list", names[0:])
print("Get all elements in the list from starting to index 2", names[:2])
print("All elements", names[:2], names[2:])
print("All elements", names[:])

# copying list
# You must be aware, however, that all of these techniques perform a shallow copy. That is, they create a new list containing the same object references as the source list, but don't copy the referred to objects.
names1 = names[:]
print("names1 is names", names1 is names)
print("names1 == names", names1 == names)

names1 = names.copy()
print("names1 is names", names1 is names)
print("names1 == names", names1 == names)

names1 = list(names)
print("names1 is names", names1 is names)
print("names1 == names", names1 == names)

print("Shallow copy demo")
a = [[1, 2], [2, 3]]
acopy = list(a)  # Note shallow copy
acopy[0][0] = 5
print(a[0])
print(acopy[0])
acopy[0] = [-1, -1]  # This is not a problem. We are changing whole element
print(a[0])
print(acopy[0])

# List repetition
l = [1, 2]
print("Repetition: ", l * 3)

print("list with 9 zero elements: ", [0] * 9)

# Note repetition is shallow
l = [0, 1]
new_l = l * 5
print("new_l", new_l)
l.append(-1)
print("new_l", new_l)
print(l)

# finding elements in list
names = ["dora", "spider man ", "papa smurf", "captain america", "mario"]
print("find dora", names.index("dora"))

# count the occurance of elements in the list
print("number of  doras in list", names.count("dora"))

# Find membership
print("Membership", "mario" in ["dora", "spider man ", "papa smurf", "captain america", "mario"])

# Remove element in list
del names[4]
print("Removed mario from the list" , names)
# Remove element by value
names.remove("dora")
print("Removed dora from the list" , names)

x = [1, 2, 3]
x.insert(0, 0)
print("inserted element at 0 in the list", x)
# Converting list to string
print("Convert list to string: ", "|".join(names))

# concatenation
x = [1, 2, 3]
y = [4, 5]
print("concatenation creates new lists", x + y)
x += [4, 5]
print("In-place extension", x)
x.extend([6])  # Modifies existing list
print("Extending list", x)

# reverse an element in the list
x = [1, 2, 3, 4]
x.reverse()
print("Reverse elements in the list", x)
x = [2, 1, 4, 3]
x.sort()
print("Sorted list", x)

# sorted function
x = [2,1,4,3]
y = sorted(x)
print("x: ", x, "y: ", y)


text:
galpy.orbit.Orbit.Oz
======================

.. automethod:: galpy.orbit.Orbit.Oz


text:
#include <config.h>

#include <stdio.h>

#include <X11/Xlib.h>
#include <X11/Xutil.h>

#include "display.h"
#include "fuse.h"
#include "keyboard.h"
#include "menu.h"
#include "settings.h"
#include "ui/ui.h"
#include "ui/uidisplay.h"
#include "xdisplay.h"
#include "xkeyboard.h"
#include "xui.h"

Display *display;		/* Which display are we connected to */
int xui_screenNum;		/* Which screen are we using on our
				   X server? */
Window xui_mainWindow;		/* Window ID for the main Fuse window */

Cursor nullpointer;

static Atom delete_window_atom;

int
ui_init( int *argc, char ***argv )
{
  char *displayName=NULL;	/* Use default display */
  XWMHints *wmHints;
  XSizeHints *sizeHints;
  XClassHint *classHint;
  char *windowNameList=(char *)"Fuse",*iconNameList=(char *)"Fuse";
  XTextProperty windowName, iconName;
  unsigned long windowFlags;
  XSetWindowAttributes windowAttributes;

  /* Allocate memory for various things */

  if( ui_widget_init() ) return 1;

  if(!(wmHints = XAllocWMHints())) {
    fprintf(stderr,"%s: failure allocating memory\n", fuse_progname);
    return 1;
  }

  if(!(sizeHints = XAllocSizeHints())) {
    fprintf(stderr,"%s: failure allocating memory\n", fuse_progname);
    return 1;
  }

  if(!(classHint = XAllocClassHint())) {
    fprintf(stderr,"%s: failure allocating memory\n", fuse_progname);
    return 1;
  }

  if(XStringListToTextProperty(&windowNameList,1,&windowName) == 0 ) {
    fprintf(stderr,"%s: structure allocation for windowName failed\n",
	    fuse_progname);
    return 1;
  }

  if(XStringListToTextProperty(&iconNameList,1,&iconName) == 0 ) {
    fprintf(stderr,"%s: structure allocation for iconName failed\n",
	    fuse_progname);
    return 1;
  }

  /* Open a connection to the X server */

  if ( ( display=XOpenDisplay(displayName)) == NULL ) {
    fprintf(stderr,"%s: cannot connect to X server %s\n", fuse_progname,
	    XDisplayName(displayName));
    return 1;
  }

  /* Set up our error handler */
  xerror_expecting = xerror_error = 0;
  XSetErrorHandler( xerror_handler );

  xui_screenNum = DefaultScreen(display);

  /* Create the main window */

  xui_mainWindow = XCreateSimpleWindow(
    display, RootWindow( display, xui_screenNum ), 0, 0,
    DISPLAY_ASPECT_WIDTH, DISPLAY_SCREEN_HEIGHT, 0,
    BlackPixel( display, xui_screenNum ), WhitePixel( display, xui_screenNum )
  );

  /* Set standard window properties */

  sizeHints->flags = PBaseSize | PResizeInc | PMaxSize | PMinSize;

  sizeHints->base_width = 0;
  sizeHints->base_height = 0;

  sizeHints->min_width    =     DISPLAY_ASPECT_WIDTH;
  sizeHints->min_height   =     DISPLAY_SCREEN_HEIGHT;
  sizeHints->width_inc    =     DISPLAY_ASPECT_WIDTH;
  sizeHints->height_inc   =     DISPLAY_SCREEN_HEIGHT;
  sizeHints->max_width    = 3 * DISPLAY_ASPECT_WIDTH;
  sizeHints->max_height   = 3 * DISPLAY_SCREEN_HEIGHT;

  if( settings_current.aspect_hint ) {
    sizeHints->flags |= PAspect;
    sizeHints->min_aspect.x = 4;
    sizeHints->min_aspect.y = 3;
    sizeHints->max_aspect.x = 4;
    sizeHints->max_aspect.y = 3;
  }

  wmHints->flags=StateHint | InputHint;
  wmHints->initial_state=NormalState;
  wmHints->input=True;

  classHint->res_name=(char *)fuse_progname;
  classHint->res_class=(char *)"Fuse";

  XSetWMProperties(display, xui_mainWindow, &windowName, &iconName,
		   *argv, *argc, sizeHints, wmHints, classHint);

  XFree( windowName.value );
  XFree( iconName.value );
  XFree( sizeHints );
  XFree( wmHints );
  XFree( classHint );

  /* Ask the server to use its backing store for this window */

  windowFlags=CWBackingStore;
  windowAttributes.backing_store=WhenMapped;

  XChangeWindowAttributes(display, xui_mainWindow, windowFlags,
			  &windowAttributes);

  /* Select which types of event we want to receive */

  XSelectInput(display, xui_mainWindow, ExposureMask | KeyPressMask |
	       KeyReleaseMask | ButtonPressMask | ButtonReleaseMask |
	       StructureNotifyMask | FocusChangeMask | PointerMotionMask );

  {
    static XColor dummy = { 0, 0, 0, 0, 4, 0 };
    XGCValues xgc;
    GC gc;

    Pixmap mask =
      XCreatePixmap( display, RootWindow( display, xui_screenNum ), 1, 1, 1 );

    xgc.function = GXclear;
    gc = XCreateGC( display, mask, GCFunction, &xgc );
    XFillRectangle( display, mask, gc, 0, 0, 1, 1 );
    nullpointer = XCreatePixmapCursor( display, mask,mask, &dummy,&dummy, 0,0 );
    XFreePixmap( display, mask );
    XFreeGC( display, gc );
  }

  /* Ask to be notified of window close requests */

  delete_window_atom = XInternAtom( display, "WM_DELETE_WINDOW", 0 );
  XSetWMProtocols( display, xui_mainWindow, &delete_window_atom, 1 );

  if( xdisplay_init() ) return 1;

  /* And finally display the window */
  XMapWindow(display,xui_mainWindow);

  ui_mouse_present = 1;

  return 0;
}

int ui_event(void)
{
  XEvent event;

  XFlush( display );
  while( XEventsQueued( display, QueuedAlready ) ) {
    XNextEvent( display, &event );

    switch(event.type) {
    case ConfigureNotify:
      xdisplay_configure_notify(event.xconfigure.width,
				event.xconfigure.height);
      break;
    case Expose:
      xdisplay_area( event.xexpose.x, event.xexpose.y,
		     event.xexpose.width, event.xexpose.height );
      break;
    case ButtonPress:
      ui_mouse_button( event.xbutton.button, 1 );
      break;
    case ButtonRelease:
      ui_mouse_button( event.xbutton.button, 0 );
      break;
    case MotionNotify:
      if( ui_mouse_grabbed ) {
        ui_mouse_motion( event.xmotion.x - 128, event.xmotion.y - 128 );
        if( event.xmotion.x != 128 || event.xmotion.y != 128 )
          XWarpPointer( display, None, xui_mainWindow, 0, 0, 0, 0, 128, 128 );
      }
      break;
    case FocusOut:
      keyboard_release_all();
      ui_mouse_suspend();
      break;
    case FocusIn:
      ui_mouse_resume();
      break;
    case KeyPress:
      xkeyboard_keypress(&(event.xkey));
      break;
    case KeyRelease:
      xkeyboard_keyrelease(&(event.xkey));
      break;
    case ClientMessage:
      if( event.xclient.format == 32 &&
          event.xclient.data.l[0] == delete_window_atom ) {
        fuse_emulation_pause();
        menu_file_exit(0);
        fuse_emulation_unpause();
      }
      break;
    }
  }
  return 0;
}

int ui_end(void)
{
  int error;

  /* Don't display the window whilst doing all this */
  XUnmapWindow(display,xui_mainWindow);

  /* Tidy up the low level stuff */
  error = xdisplay_end(); if( error ) return error;

  /* Now free up the window itself */
  XDestroyWindow(display,xui_mainWindow);

  /* And disconnect from the X server */
  XCloseDisplay(display);

  ui_widget_end();

  return 0;
}

int
ui_mouse_grab( int startup )
{
  if( startup ) return 0;

  switch( XGrabPointer( display, xui_mainWindow, True,
			ButtonPressMask | ButtonReleaseMask | PointerMotionMask,
			GrabModeAsync, GrabModeAsync, xui_mainWindow,
			nullpointer, CurrentTime )
	) {
  case GrabSuccess:
  case GrabNotViewable:
    XWarpPointer( display, None, xui_mainWindow, 0, 0, 0, 0, 128, 128 );
    return 1;
  default:
    ui_error( UI_ERROR_WARNING, "Mouse grab failed" );
    return 0;
  }
}

int
ui_mouse_release( int suspend GCC_UNUSED )
{
  XUngrabPointer( display, CurrentTime );
  return 0;
}


text:
package io.yawp.repository;

import io.yawp.commons.utils.JsonUtils;

import java.io.Serializable;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.List;

public final class LazyJson<T> implements Serializable {

    private static final long serialVersionUID = 6613992940340254518L;

    private Type type;

    private T object;

    private String json;

    public static <T> LazyJson<T> create(T object) {
        LazyJson<T> lazyJson = new LazyJson<T>();
        lazyJson.set(object);
        return lazyJson;
    }

    public void set(T value) {
        if (value == null) {
            setNull();
            return;
        }

        Type type = value.getClass();

        this.type = type;
        this.object = value;
    }

    public T get() {
        if (object == null && json == null) {
            return null;
        }

        if (object == null) {
            object = (T) JsonUtils.from(Yawp.yawp(), json, type);
        }

        return object;
    }

    public String getJson() {
        if (object != null) {
            json = JsonUtils.to(object);
        }
        return json;
    }

    public boolean isJsonArray() {
        if (type instanceof ParameterizedType) {
            return List.class.isAssignableFrom((Class<?>) ((ParameterizedType) type).getRawType());
        }
        return List.class.isAssignableFrom((Class<?>) type);
    }

    private void setNull() {
        this.type = null;
        this.object = null;
        this.json = null;
    }

    /**
     * Internal only method.
     */
    public static LazyJson<?> $create(Type type, String json) {
        LazyJson<?> lazyJson = new LazyJson<>();
        lazyJson.type = type;
        lazyJson.json = json;
        return lazyJson;
    }

}


text:
section: Download
permalink: download/
layout: section
---

Download
========

## Source Code ##

The Aperture Tiles source code is available on GitHub. Aperture Tiles is freely available for download under [The MIT License](http://www.opensource.org/licenses/MIT) (MIT) open source licensing. Unlike GNU General Public License (GPL), MIT freely permits distribution of derivative work under proprietary license, without requiring the release of source code.

Aperture Tiles Source Code

For information on full installations of Aperture Tiles, see the [Installation](../docs/development/getting-started/installation/) page.

## Packaged Distribution ##

The following pre-built distribution can be used to quickly generate and display tiles without having to build the software. See the [Quick Start](../docs/development/getting-started/quick-start/) documentation to help you quickly learn how to process a dataset, transform it and create an Aperture Tiles project that allows you to visualize it in a web browser.

- **Tile Generator**: Enables you to generate a set of tiles that can be viewed using the Tile Client Application available below. This version was built for Apache Spark 1.3.0 and CDH 5.4.7.

Tile Generator

- **Tile Quick Start Application**: An example Tile Client application to display tiles in a browser. You can quickly copy and deploy this application to your web server after minimal modification.

Tile Quick Start Application

Interested in Learning More?

Tour: Take our tour to learn more about Aperture Tiles.

Documentation: Learn how to install, implement and test your Aperture Tiles applications.

Quick Start: Our Julia dataset provides an example of the process for generating tiles and visualizing them using Aperture Tiles.

Live Examples: See our demos page to explore live examples of the capabilities of Aperture Tiles.


text:
/**
 * @fileOverview This file acts as the central import point for the other JavaScript files that make
 *               up the visualizer.
 * @author Marco Leise
 */

$import('Util');
$import('Ant');
$import('Application');
$import('Buttons');
$import('Config');
$import('Const');
$import('Director');
$import('ImageManager');
$import('Replay');
$import('CanvasElement');

var $import_base;

/**
 * Imports a file in Java package notation.
 *
 * @param {String}
 *        file the 'package' name
 */
function $import(file) {
	var ends_with = function(str, pat) {
		return str.slice(-pat.length) == pat;
	};
	var scripts = document.getElementsByTagName("script");
	if ($import_base === undefined) {
		for ( var i = 0, len = scripts.length; i < len; ++i) {
			if (ends_with(scripts[i].src, 'visualizer.js')) {
				var pathLen = scripts[i].src.lastIndexOf('/') + 1;
				$import_base = scripts[i].src.substr(0, pathLen);
				break;
			}
		}
	}
	file = $import_base + file.replace(/[.]/g, '/') + '.js';
	for ( var i = 0; i < scripts.length; i++) {
		if (scripts[i].src === file) {
			return;
		}
	}
	document.write('');
}


text:
/**
 * Created by coney on 13-10-22.
 */
/**
 * Created by coney on 13-10-22.
 * cfg = {drop_class:"thedrop",
 * callback:function(obj,e){},
 * hover_class:}
 */
(function($){
    $.fn.dragdrop = function(cfg){
        var _this = this;
        cfg = $.extend({drop_class:"drop",hover_class:"hover"},cfg)

        var mousemove = function(ev){
                ev.data.dragging.offset({
                    left:ev.pageX+1,
                    top:ev.pageY+1
                })

            },
            mouseup = function(e){
                if($.isFunction(e.data && e.data.callback)){
                    e.data.callback($(this),e);
                }

            },
            mouseup_win = function(e){
                e.data.dragging.remove();
                $(window).off("mousemove",mousemove);
                $(window).off("mouseup",mouseup_win);
                e.data.drop_items.off("mouseup",mouseup);
                e.data.drop_items.off("mouseleave", mouseleave);
                e.data.drop_items.off("mouseover", mouseover);
            },
            mouseover = function(e){
                if(e.data && e.data.dragging){
                    $(this).addClass(cfg.hover_class);
                }

            },
            mouseleave = function(e){
                if(e.data && e.data.dragging){
                    $(this).removeClass(cfg.hover_class);
                }
            };

        _this.mousedown(function(e){
            var d ={};
            d.src = $(this);
            d.dragging = $("

");
            d.dragging.html(d.src.html());
            d.dragging.appendTo($("body"));
            d.dragging.css({width:cfg.width || "200px",position:"absolute","z-index":1000});

            d.callback = cfg.callback || false;

            d.drop_items = $("."+cfg.drop_class);
            d.drop_items.on("mouseup",d, mouseup);
            d.drop_items.on("mouseleave",d, mouseleave);
            d.drop_items.on("mouseover",d, mouseover);
            $(window).on("mousemove",d, mousemove);
            $(window).on("mouseup",d, mouseup_win);
            return false;

        })

    }
})();


text:
package androidx.remotecallback.compiler;

import com.squareup.javapoet.JavaFile;
import com.squareup.javapoet.MethodSpec;
import com.squareup.javapoet.TypeName;
import com.squareup.javapoet.TypeSpec;

import java.io.IOException;
import java.util.ArrayList;

import javax.annotation.processing.Messager;
import javax.annotation.processing.ProcessingEnvironment;
import javax.lang.model.element.Element;
import javax.lang.model.element.Modifier;
import javax.tools.Diagnostic;

/**
 * Holder class that is created for each class instance that is a
 * CallbackReceiver and has methods tagged with @RemoteCallable.
 */
class CallbackReceiver {

    @SuppressWarnings("unused")
    private static final String RESET = "reset";
    @SuppressWarnings("unused")
    private static final String GET_METHOD = "getMethod";
    @SuppressWarnings("unused")
    private static final String GET_ARGUMENTS = "getArguments";
    @SuppressWarnings("unused")
    private static final String GET_CLS_NAME = "getClsName";

    private final ProcessingEnvironment mEnv;
    private final Element mElement;
    private final String mClsName;
    private final ArrayList<CallableMethod> mMethods = new ArrayList<>();
    private final Messager mMessager;

    CallbackReceiver(Element c, ProcessingEnvironment env,
            Messager messager) {
        mEnv = env;
        mElement = c;
        mClsName = c.toString();
        mMessager = messager;
    }

    /**
     * Adds a method tagged with @RemoteCallable to this receiver.
     */
    void addMethod(Element element) {
        for (CallableMethod method: mMethods) {
            if (method.getName().equals(element.getSimpleName().toString())) {
                mMessager.printMessage(Diagnostic.Kind.ERROR,
                        "Multiple methods named " + element.getSimpleName());
                return;
            }
        }
        mMethods.add(new CallableMethod(mClsName, element, mEnv));
    }

    /**
     * Generates the code to handle creating and executing callbacks. The code
     * is assembled in one class that implements runnable that when run,
     * registers all of the CallbackHandlers.
     */
    void finish(ProcessingEnvironment env, Messager messager) {
        if (mMethods.size() == 0) {
            messager.printMessage(Diagnostic.Kind.ERROR, "No methods found for " + mClsName);
            return;
        }
        TypeSpec.Builder genClass = TypeSpec
                .classBuilder(findInitClass(mElement))
                .addOriginatingElement(mElement)
                .superclass(TypeName.get(mElement.asType()))
                .addModifiers(Modifier.PUBLIC);

        MethodSpec.Builder runBuilder = MethodSpec
                .constructorBuilder()
                .addModifiers(Modifier.PUBLIC);
        for (CallableMethod method: mMethods) {
            method.addMethods(genClass, runBuilder, env, messager);
        }
        genClass.addMethod(runBuilder.build());
        try {
            TypeSpec typeSpec = genClass.build();
            String pkg = getPkg(mElement);
            JavaFile.builder(pkg, typeSpec)
                    .build()
                    .writeTo(mEnv.getFiler());
        } catch (IOException e) {
            messager.printMessage(Diagnostic.Kind.ERROR, "Exception writing " + e);
        }
    }

    private String findInitClass(Element element) {
        return String.format("%sInitializer", element.getSimpleName());
    }

    private String getPkg(Element s) {
        String pkg = mEnv.getElementUtils().getPackageOf(s).toString();
        return pkg;
    }
}


text:
class SponsorsController < ApplicationController
  before_filter :login_required, :except => :index

  def index
    respond_to do |format|
      format.html do
        @sponsors = Sponsor.find(:all)
      end

      format.json do
        @sponsors = Sponsor.all(:with_deleted => true)
      end
    end
  end

  def new
    @sponsor = Sponsor.new
  end

  def create
    @sponsor = Sponsor.create(params[:sponsor])
    if @sponsor.save
      flash[:notice] = "Sponsor created"
      redirect_to root_path
    else
      render :action => "new"
    end
  end

  def edit
    @sponsor = Sponsor.find(params[:id])
  end

  def update
    @sponsor = Sponsor.find(params[:id])
    @sponsor.update_attributes(params[:sponsor])
    if @sponsor.save
      flash[:notice] = "Sponsor updated"
      redirect_to root_path
    else
      render :action => "edit"
    end
  end

  def destroy
    Sponsor.destroy(params[:id])
    redirect_to sponsors_path
  end

end


text:
using System;
using System.Collections.Generic;
using System.Text;
using wojilu.Members.Users.Domain;
using wojilu.Web.Context;
using wojilu.Web.Mvc.Utils;
using wojilu.Caching;
using wojilu.Web.Controller.Common.Caching;
using wojilu.Apps.Blog.Domain;

namespace wojilu.Web.Controller.Blog.Caching {

    public class BlogHomeViewCacher {

        public static void Update( User owner, int appId ) {

            String key = GetCacheKey( owner.Url, appId );

            String content = getHomeCache( appId, owner );

            CacheManager.GetApplicationCache().Put( key, content );

        }

        public static String GetCacheKey( String userUrl, int appId ) {
            return typeof( User ).FullName + userUrl + "_blogapp" + appId;
        }

        private static string getHomeCache( int appId, User owner ) {
            MvcContext ctx = MockContext.GetOne( owner, typeof( BlogApp ), appId );
            String content = ControllerRunner.Run( ctx, new wojilu.Web.Controller.Blog.BlogController().Index );

            return content;
        }

    }
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using HealthMonitoring.AcceptanceTests.Helpers;
using HealthMonitoring.AcceptanceTests.Helpers.Entities;
using HealthMonitoring.AcceptanceTests.Helpers.Http;
using LightBDD.Framework.Formatting;
using LightBDD.XUnit2;
using Newtonsoft.Json;
using RestSharp;
using Xunit;
using Xunit.Abstractions;

namespace HealthMonitoring.AcceptanceTests.Scenarios
{
    public partial class Endpoint_registration : FeatureFixture, IDisposable
    {
        private RestClient _client;
        private IRestResponse _response;
        private Guid _identifier;
        private readonly List<MockWebEndpoint> _endpoints = new List<MockWebEndpoint>();
        private readonly CredentialsProvider _credentials = new CredentialsProvider();

        public Endpoint_registration(ITestOutputHelper output)
            : base(output)
        {
        }

        public void Dispose()
        {
            foreach (var endpoint in _endpoints)
                endpoint.Dispose();
        }

        private void Given_a_monitor_api_client()
        {
            _client = ClientHelper.Build();
        }

        private void When_client_requests_endpoint_registration_via_url_with_name_address_group_and_monitor(string url, string name, string address, string group, string monitor)
        {
            RegisterEndpoint(url, name, group, monitor, address);
        }

        private void Then_a_new_endpoint_identifier_should_be_returned()
        {
            _response.VerifyValidStatus(HttpStatusCode.Created);
            _identifier = JsonConvert.DeserializeObject<Guid>(_response.Content);
            Assert.NotEqual(Guid.Empty, _identifier);
            _response.VerifyLocationHeader($"api/endpoints/{_identifier}");
        }

        private void When_client_requests_endpoint_details_via_url(string url)
        {
            _response = _client.Get(new RestRequest(url));
        }

        private void Then_endpoint_information_should_be_returned_including_name_address_group_and_monitor(string name, string address, string group, string monitor)
        {
            var entity = _response.DeserializeEndpointDetails();
            AssertEntity(entity, name, address, group, monitor);
        }

        private static void AssertEntity(EndpointEntity entity, string name, string address, string group, string monitor)
        {
            Assert.Equal(name, entity.Name);
            Assert.Equal(address, entity.Address);
            Assert.Equal(group, entity.Group);
            Assert.Equal(monitor, entity.MonitorType);
        }

        private void When_client_requests_endpoint_details_for_inexistent_endpoint_identifier()
        {
            When_client_requests_endpoint_details_via_url($"api/endpoints/{Guid.NewGuid()}");
        }

        private void Then_status_should_be_returned(HttpStatusCode status)
        {
            _response.VerifyValidStatus(status);
        }

        private void Given_endpoint_with_name_address_group_and_monitor_is_registered(string name, string address, string group, string monitor)
        {
            When_client_requests_endpoint_registration_via_url_with_name_address_group_and_monitor("/api/endpoints/register", name, address, group, monitor);
            Then_a_new_endpoint_identifier_should_be_returned();
        }

        private void When_client_requests_all_endpoints_details_via_url(string url)
        {
            _response = _client.Get(new RestRequest(url));
        }

        private void Then_returned_endpoint_list_should_include_endpoint_with_name_address_group_and_monitor(string name, string address, string group, string monitor)
        {
            _response.VerifyValidStatus(HttpStatusCode.OK);
            var entities = JsonConvert.DeserializeObject<EndpointEntity[]>(_response.Content);
            var entity = entities.SingleOrDefault(e => e.MonitorType == monitor && e.Address == address);
            AssertEntity(entity, name, address, group, monitor);
        }

        private void Then_client_should_receive_STATUS_code(HttpStatusCode status)
        {
            _response.VerifyValidStatus(status);
        }

        private void Then_response_should_contain_message(string message)
        {
            var error = JsonConvert.DeserializeObject<ErrorEntity>(_response.Content).Message;
            Assert.Equal(message, error);
        }

        private void When_client_requests_endpoint_deletion_via_url_with_admin_credentials(string url)
        {
            DeleteEndpoint(url, _credentials.AdminCredentials);
        }

        private void When_client_requests_endpoint_deletion_for_inexistent_endpoint_identifier()
        {
            DeleteEndpoint($"api/endpoints/{Guid.NewGuid()}", _credentials.AdminCredentials);
        }

        private void When_client_requests_tags_updating_via_url_with_admin_credentials(string url, string[] tags)
        {
            PostTags(url, tags, _credentials.AdminCredentials);
        }

        private void When_client_requests_tags_updating_via_url_with_personal_credentials(string url, string[] tags)
        {
            PostTags(url, tags, _credentials.PersonalCredentials);
        }

        private void Then_the_endpoint_tags_should_be(string[] tags)
        {
            var entity = _response.DeserializeEndpointDetails();
            AssertTags(tags, entity.Tags);
        }

        private void Given_endpoint_with_password_is_registered(
            string name, string address, string group,
            string monitor, string password)
        {
            RegisterEndpoint("/api/endpoints/register", name, group, monitor, address, null, password);
            Then_a_new_endpoint_identifier_should_be_returned();
        }

        private void When_client_request_endpoint_update_without_personal_credentials(string name, string address, string group, string monitor)
        {
            RegisterEndpoint("/api/endpoints/register", name, group, monitor, address);
        }

        private void Given_endpoint_id_is_received()
        {
            var registrationId = JsonConvert.DeserializeObject<Guid>(_response.Content);
            _credentials.PersonalCredentials.Id = registrationId;
        }

        private void When_client_request_endpoint_update_with_credentials(
            string name, string address, string group, string monitor,
            string[] tags, string password)
        {
            RegisterEndpoint("/api/endpoints/register", name, group, monitor, address, tags, password);
        }

        private void Then_response_should_contain_only_id_and_address_and_monitortype(Guid id, string address,
            string monitor)
        {
            _response.VerifyValidStatus(HttpStatusCode.OK);
            var identities = JsonConvert.DeserializeObject<EndpointIdentity[]>(_response.Content);
            Assert.NotNull(identities.Single(m => m.Id == id && m.Address == address && m.MonitorType == monitor));
        }

        private void When_client_request_endpoint_health_update_with_credentials(Guid endpointId, EndpointStatus status, Credentials credentials)
        {
            var updates = new []
            {
                new EndpointHealthUpdate
                {
                    EndpointId = endpointId,
                    Status = status,
                    CheckTimeUtc = DateTime.UtcNow,
                    ResponseTime = TimeSpan.FromSeconds(5)
                }
            };
            PostHealth(updates, credentials);
        }

        private void PostTags(string url, string[] tags, Credentials credentials)
        {
            _response = _client
                .Authorize(credentials)
                .Put(new RestRequest(url)
                .AddJsonBody(tags)
               );
        }

        private void PostHealth(EndpointHealthUpdate[] healthUpdate, Credentials credentials)
        {
            _response = _client
                .Authorize(credentials)
                .Post(new RestRequest("api/endpoints/health")
                .AddJsonBody(healthUpdate)
               );
        }

        private void RegisterEndpoint(
            string url, string name, string group, string monitor,
            string address, string[] tags = null, string password = null,
            Credentials credentials = null)
        {
            object body = new { name, group, monitorType = monitor, address, tags, password };

            _response = _client
                .Authorize(credentials)
                .Post(new RestRequest(url)
                .AddJsonBody(body)
                );
        }

        private void DeleteEndpoint(string url, Credentials credentials)
        {
            _response = _client
                .Authorize(credentials)
                .Delete(new RestRequest(url)
                );
        }

        private void AssertTags(string[] existing, string[] expected)
        {
            Assert.Equal(existing.Length, expected.Length);
            existing = existing.OrderBy(x => x).ToArray();
            expected = expected.OrderBy(x => x).ToArray();

            for (int i = 0; i < expected.Length; i++)
            {
                Assert.Equal(expected[i], existing[i]);
            }
        }

        private void Given_a_healthy_endpoint_with_name_group_and_tags(string name, string group, [FormatCollection] string[] tags)
        {
            SetupHttpEndpoint(HttpStatusCode.OK, name, group, tags, EndpointStatus.Healthy);
        }

        private void Given_a_faulty_endpoint_with_name_group_and_tags(string name, string group, [FormatCollection] string[] tags)
        {
            SetupHttpEndpoint(HttpStatusCode.InternalServerError, name, group, tags, EndpointStatus.Faulty);
        }

        private void Given_a_offline_endpoint_with_name_group_and_tags(string name, string group, [FormatCollection] string[] tags)
        {
            SetupHttpEndpoint(HttpStatusCode.ServiceUnavailable, name, group, tags, EndpointStatus.Offline);
        }

        private void SetupHttpEndpoint(HttpStatusCode httpStatusCode, string name, string group, string[] tags, EndpointStatus expectedStatus)
        {
            var endpoint = MockWebEndpointFactory.CreateNew();
            _endpoints.Add(endpoint);

            endpoint.SetupStatusResponse(httpStatusCode);
            var identifier = _client.RegisterEndpoint(MonitorTypes.Http, endpoint.StatusAddress, group, name, tags);
            _client.EnsureStatusChanged(identifier, expectedStatus);
        }

        private void When_client_requests_all_endpoints_details_via_url_and_group_filter_GROUPFILTER(string url, string groupFilter)
        {
            _response = _client.Get(new RestRequest(url).AddQueryParameter("filterGroup", groupFilter));
        }

        private void When_client_requests_all_endpoints_details_via_url_and_group_filter_GROUPFILTER_as_well_as_tag_filter_TAGFILTER(string url, string groupFilter, [FormatCollection] string[] tagFilter)
        {
            var request = new RestRequest(url).AddQueryParameter("filterGroup", groupFilter);
            foreach (var tag in tagFilter)
                request.AddQueryParameter("filterTags", tag);

            _response = _client.Get(request);
        }

        private void When_client_requests_all_endpoints_details_via_url_and_group_filter_GROUPFILTER_as_well_as_status_filter_STATUSFILTER(string url, string groupFilter, [FormatCollection]EndpointStatus[] statusFilter)
        {
            var request = new RestRequest(url).AddQueryParameter("filterGroup", groupFilter);
            foreach (var status in statusFilter)
                request.AddQueryParameter("filterStatus", status.ToString());

            _response = _client.Get(request);
        }

        private void When_client_requests_all_endpoints_details_via_url_and_group_filter_GROUPFILTER_as_well_as_text_filter_TEXTFILTER(string url, string groupFilter, string textFilter)
        {
            _response = _client.Get(new RestRequest(url).AddQueryParameter("filterGroup", groupFilter).AddQueryParameter("filterText", textFilter));
        }

        private void Then_returned_endpoint_list_should_contain_endpoints([FormatCollection]params string[] endpoints)
        {
            _response.VerifyValidStatus(HttpStatusCode.OK);
            var actual = JsonConvert.DeserializeObject<EndpointEntity[]>(_response.Content).Select(e => e.Name).OrderBy(n => n).ToArray();
            var expected = endpoints.OrderBy(e => e).ToArray();
            Assert.Equal(expected, actual);
        }

        private void When_client_request_endpoint_registration_with_short_password()
        {
            string password = "1234567";
            RegisterEndpoint("/api/endpoints/register", "name", "group", MonitorTypes.HttpJson, "address", null, password);
        }
    }
}


text:
#include "../../include/montador/token.h"

//Declaracao do construtor da classe Token
Token::Token(std::string a){
    this -> nome = a;
    this -> type = token_type::undefined;
};

//Analisa se um determinado Token eh rotulo, tambem recebe a linha que esse token esta contido pra possiveis analises
bool Token::isRotulo(std::string token, std::string linha, std::vector<Mnemonic> instructionList){
    if (Token::have2points(token)){
        return true;
    }

    //algumas strings que queremos comparar, esta sendo feito assim pq de outras maneiras nao poderiamos ter um rotulo
    std::stringstream Line (linha);
    std::string aux;

    //pega o primeiro elemento da linha
    Line >> aux;

    //ve se a linha eh uma linha do tipo section
    if (aux == "section"){
        Line >> aux;
        if((aux == "data") || (aux == "text")){
            return false;
        }
    }

    //testa se eh uma instrucao
    for (size_t i = 0; i < instructionList.size(); i++){
        if (token == instructionList[i].nome){
            return false;
        }
    }

    //testa outros comandos que nao podem ser rotulos
    if ((token == "equ") || (token == "if") || (token == "macro") || (token == "end") ||
        (token == "space") || (token == "const") || (isInteger(token))){
        return false;
    }

    return true;
}

//Retorna 1 para rotulos de declaracao e 2 para chamadas de rotulo
//Se essa funcao for chamada, ja sabemos que se trata de um rotulo, portanto faz apenas o teste de ser declaracao
//se nao for,eh pq eh chamada
int Token::KindOfRotulo(std::string token)
{
    if (Token::have2points(token))
    {
        return tipo_rotulo::declaracao;
    } else
    {
        return tipo_rotulo::chamada;
    }

}

//testa se o ultimo char da string eh ':', pois isso indica que ele eh uma declaracao de rotulo
bool Token::have2points(std::string token){
    char* ptr;
    ptr = &(token[0]);
    int tam = strlen(ptr);

    for(int i = 0; i < tam; i++){
        if ((token[i] == ':') &&(tam - i == 1)){
            return true;
        }
    }
    return false;
}

bool Token::isInteger(const std::string & aux)
{
   if(aux.empty() || ((!isdigit(aux[0])) && (aux[0] != '-') && (aux[0] != '+'))){
    return false;
   }

   char* ptr;
   strtol(aux.c_str(), &ptr, 10);

   return (*ptr == 0) ;
}

//testa se o ultimo char da string eh ',', pois isso faz parte do argumento para o copy
bool Token::haveVirgula(std::string token){
    char* ptr;
    ptr = &(token[0]);
    int tam = strlen(ptr);

    for(int i = 0; i < tam; i++){
        if ((token[i] == ',') &&(tam - i == 1)){
            return true;
        }
    }
    return false;
}

//Testa se tem o + na string
bool Token::haveSoma(std::string token){
    char* ptr;
    ptr = &(token[0]);
    int tam = strlen(ptr);

    for(int i = 0; i < tam; i++){
        if ((token[i] == '+')&&(tam - i == 1)){
            return true;
        }
    }
    return false;
}

/* Podem ser úteis */
// // Função teste: extrair cada token do arquivo de entrada e escrevê-los de forma padrão na saída
// void Montador::tokenizar()
// {
//     //string de suporte para capturar os tokens
//     std::string aux;
//     //Loop para ler todas as linhas do codigo aberto e "tokenizar" elas (o token leva o : em consideracao ainda)
//     while (getline(this->fileText, aux)){
//         char* ptr;  //ponteiro de suporte para o funcionamento do strlen dentro da funcao minuscula
//         ptr = &(aux[0]);  //ponteiro apontando pro primeiro caracter da string
//         aux = Montador::minuscula (ptr);
//
//
//         std::stringstream lineStream (aux);
//         Token token(aux);
//
//         while (lineStream >> token.nome){
//             this->tokensList.push_back(token);
//         }
//     }
// }
//
// /* Imprime Tokens guardades em tokensList */
// void Montador::printTokens()
// {
//     if(this->tokensList.empty())
//     {
//         std::cout << "Token list empty" << '\n';
//         return;
//     }
//     for(size_t i = 0; i < tokensList.size(); i++)
//     {
//         std::cout << tokensList[i].nome << " " << '\n';
//     }
//     std::cout << '\n';
// }
//
// /* Escreve um arquivo de saida a partir de tokensList */
// void Montador::writeTokensToOutput()
// {
//     for(size_t i = 0; i < tokensList.size(); i++)
//     {
//         this->fileOutput << tokensList[i].nome << '\n';
//     }
//     this->fileOutput << std::endl;
// }
//
// //transforma toda a string em letras minusculas
// std::string Montador::minuscula (char* aux){
//     int tam = strlen (aux);
//
//     for (int i = 0; i < tam; i++){
//         aux[i] = (char) std::tolower(aux[i]);
//     }
//
//     return aux;
// }


text:
[![Build Status](https://travis-ci.com/ember-spaniel/ember-spaniel.svg?branch=master)](https://travis-ci.com/ember-spaniel/ember-spaniel)
[![npm version](https://badge.fury.io/js/ember-spaniel.svg)](https://www.npmjs.com/package/ember-spaniel)

Ember addon wrapping [spaniel](https://github.com/linkedin/spaniel), a viewport tracking library, [IntersectionObserver](https://github.com/WICG/IntersectionObserver) polyfill, and `requestAnimationFrame` task utility.

## Compatibility

- Ember.js v3.4 or above
- Ember CLI v2.13 or above
- Node.js v8 or above

## Installation

```bash
ember install my-addon
```

## Usage

Including this addon will add Spaniel to your application, available for direct use in the app.

```JavaScript
import * as spaniel from 'spaniel';
```

The rest of the API is contained in a service.

## `viewport` service API

You can set your `ember-spaniel` config in `config/environment.js`, there are 3 options `defaultRootMargin`, `watcherTime` and `watcherRatio`.

The `viewport` service will look for a `defaultRootMargin` object property on the application config. If not found, will default to `0, 0, 0, 0`. The `watcherTime` and `watcherRatio` will be used as the config of watcher return by `getWatcher()`.

```JavaScript
// environment.js
module.exports = {
  ...
  'ember-spaniel': {
    watcherTime: 100,
    watcherRatio: 0.8,
    defaultRootMargin: {
      top: 100,
      bottom: 200
    }
  }
}
```

### `onInViewportOnce(el, callback, { context, rootMargin, ratio, root, ALLOW_CACHED_SCHEDULER })` => `Function`

Register a callback that will be called when the provided element first enters the viewport. Will get called on the next `requestAnimationFrame` if the element is already in the viewport. Returns a function that, when called, will cancel and clear the callback.

Optionally includes the ability to specify a custom root, which defaults to `window`. When passing a custom root, the common case would include handling state invalidation (referenced below `invalidate()`).

An optional flag `ALLOW_CACHED_SCHEDULER` which defaults to `true`. This feature flag when passed as `false` will disable caching of `getBoundingClientRect` on elements within the `Spaniel#ElementScheduler`.

```JavaScript
export default Ember.Component.extend({
  viewport: Ember.inject.service(),
  didInsertElement() {
    let viewport = this.get('viewport');
    let el = this.get('element');
    this.clearViewportCallback = viewport.onInViewportOnce(el, () => {
      console.log('I am in the viewport');
    });
  },
  willDestroyElement() {
    this._super(...arguments);
    this.clearViewportCallback();
  }
});
```

```JavaScript
export default Ember.Component.extend({
  viewport: Ember.inject.service(),
  didInsertElement() {
    let viewport = this.get('viewport');
    let fooChildElement = this.get('element');

    this.clearViewportCallback = viewport.onInViewportOnce(fooChildElement, () => {
      console.log('I am in the viewport');
    }, {
      root: fooCustomRoot,
      ALLOW_CACHED_SCHEDULER: false
    });
  },
  willDestroyElement() {
    this._super(...arguments);
    this.clearViewportCallback();
  }
});
```

### `isInViewport(el, { ratio, rootMargin } = {})` => `Promise`

Returns a promise that resolves if the element is in the viewport, otherwise rejects.

```JavaScript
export default Ember.Component.extend({
  viewport: Ember.inject.service(),
  didInsertElement() {
    let viewport = this.get('viewport');
    let el = this.get('element');
    viewport.isInViewport(el).then(() => {
      console.log('In the viewport');
    }, () => {
      console.log('Not in the viewport');
    });
  }
});
```

### `getWatcher()`

The service has a `Watcher` instance available for direct use.

```JavaScript
export default Ember.Component.extend({
  viewport: Ember.inject.service(),
  didInsertElement() {
    let watcher = this.get('viewport').getWatcher();
    let el = this.get('element');
    watcher.watch(el, (e) => {
      console.log(`${e} happened`);
    });
  }
});
```

### `invalidate()`

Triggers Spaniel#invalidate on the viewport to invalidate cached state. Due to negative performance implications, this method should not be abused and as such should handle edge case scenarios only, such as when leveraging a custom root. The recommended pattern below binds an event to viewports custom root, that when fired triggers the viewports `invalidate()` method. Optionally leveraging Ember's Util #debounce method for improved performance and/or https://github.com/ember-lifeline/ember-lifeline#addeventlistener.

```JavaScript
export default Ember.Component.extend({
  viewport: Ember.inject.service(),
  didInsertElement() {
    let viewport = this.get('viewport');
    let el = this.get('element');
    viewport.isInViewport(el).then(() => {
      console.log('In the viewport');
    }, () => {
      console.log('Not in the viewport');
    });

    fooCustomRoot.addEventListener('foo-event', this.onFooMethod.bind(this), false);
  },
  onFooMethod() {
    let viewport = this.get('viewport');

    viewport.invalidate();
  },
  willDestroyElement() {
    this._super(...arguments);
    let viewport = this.get('viewport');

    fooCustomRoot.removeEventListener('foo-event', this.onFooMethod.bind(this), false);
  }
});
```

## Contributing

See the [Contributing](CONTRIBUTING.md) guide for details.

## License

This project is licensed under the [MIT License](LICENSE.md).


text:
multiple-demo-project
=====================

Demonstration project CLI Multik


text:
var _ = require('underscore'),
    Benchmark = require("benchmark");

var BenchWarmer = function(names) {
  this.benchmarks = [];
  this.currentBenches = [];
  this.names = [];
  this.times = {};
  this.minimum = Infinity;
  this.maximum = -Infinity;
  this.errors = {};
};

var print = require("sys").print;

BenchWarmer.prototype = {
  winners: function(benches) {
    return Benchmark.filter(benches, 'fastest');
  },
  suite: function(suite, fn) {
    this.suiteName = suite;
    this.times[suite] = {};
    this.first = true;

    var self = this;

    fn(function(name, benchFn) {
      self.push(name, benchFn);
    });
  },
  push: function(name, fn) {
    if(this.names.indexOf(name) == -1) {
      this.names.push(name);
    }

    var first = this.first, suiteName = this.suiteName, self = this;
    this.first = false;

    var bench = new Benchmark(fn, {
      name: this.suiteName + ": " + name,
      onComplete: function() {
        if(first) { self.startLine(suiteName); }
        self.writeBench(bench);
        self.currentBenches.push(bench);
      }, onError: function() {
        self.errors[this.name] = this;
      }
    });
    bench.suiteName = this.suiteName;
    bench.benchName = name;

    this.benchmarks.push(bench);
  },

  bench: function(callback) {
    var self = this;

    this.printHeader('ops/msec', true);

    Benchmark.invoke(this.benchmarks, {
      name: "run",
      onComplete: function() {
        self.scaleTimes();

        self.startLine('');

        print('\n');
        self.printHeader('scaled');
        _.each(self.scaled, function(value, name) {
          self.startLine(name);

          _.each(self.names, function(lang) {
            self.writeValue(value[lang] || '');
          });
        });
        print('\n');

        var errors = false, prop, bench;
        for(prop in self.errors) {
          if (self.errors.hasOwnProperty(prop)
              && self.errors[prop].error.message !== 'EWOT') {
            errors = true;
            break;
          }
        }

        if(errors) {
          print("\n\nErrors:\n");
          for(prop in self.errors) {
            if (self.errors.hasOwnProperty(prop)
                && self.errors[prop].error.message !== 'EWOT') {
              bench = self.errors[prop];
              print("\n" + bench.name + ":\n");
              print(bench.error.message);
              if(bench.error.stack) {
                print(bench.error.stack.join("\n"));
              }
              print("\n");
            }
          }
        }

        callback();
      }
    });

    print("\n");
  },

  scaleTimes: function() {
    var scaled = this.scaled = {};
    _.each(this.times, function(times, name) {
      var output = scaled[name] = {};

      _.each(times, function(time, lang) {
        output[lang] = ((time - this.minimum) / (this.maximum - this.minimum) * 100).toFixed(2);
      }, this);
    }, this);
  },

  printHeader: function(title, winners) {
    var benchSize = 0, names = this.names, i, l;

    for(i=0, l=names.length; i<l; i++) {
      var name = names[i];

      if(benchSize < name.length) { benchSize = name.length; }
    }

    this.nameSize = benchSize + 2;
    this.benchSize = 20;
    var horSize = 0;

    this.startLine(title);
    horSize = horSize + this.benchSize;
    for(i=0, l=names.length; i<l; i++) {
      this.writeValue(names[i]);
      horSize = horSize + this.benchSize;
    }

    if (winners) {
      print("WINNER(S)");
      horSize = horSize + "WINNER(S)".length;
    }

    print("\n" + new Array(horSize + 1).join("-"));
  },

  startLine: function(name) {
    var winners = Benchmark.map(this.winners(this.currentBenches), function(bench) {
      return bench.name.split(": ")[1];
    });

    this.currentBenches = [];

    print(winners.join(", "));
    print("\n");

    if (name) {
      this.writeValue(name);
    }
  },
  writeBench: function(bench) {
    var out;

    if(!bench.error) {
      var count = bench.hz,
          moe   = count * bench.stats.rme / 100,
          minimum,
          maximum;

      count = Math.round(count / 1000);
      moe = Math.round(moe / 1000);
      minimum = count - moe;
      maximum = count + moe;

      out = count + " ±" + moe + " (" + bench.cycles + ")";

      this.times[bench.suiteName][bench.benchName] = count;
      this.minimum = Math.min(this.minimum, minimum);
      this.maximum = Math.max(this.maximum, maximum);
    } else {
      if (bench.error.message === 'EWOT') {
        out = 'NA';
      } else {
        out = 'E';
      }
    }
    this.writeValue(out);
  },

  writeValue: function(out) {
    var padding = this.benchSize - out.length + 1;
    out = out + new Array(padding).join(" ");
    print(out);
  }
};

module.exports = BenchWarmer;


text:
package edu.washington.escience.myria.api.encoding;

import edu.washington.escience.myria.api.encoding.QueryConstruct.ConstructArgs;
import edu.washington.escience.myria.operator.SymmetricHashCountingJoin;

public class SymmetricHashCountingJoinEncoding extends BinaryOperatorEncoding<SymmetricHashCountingJoin> {

  @Required
  public int[] argColumns1;
  @Required
  public int[] argColumns2;

  @Override
  public SymmetricHashCountingJoin construct(ConstructArgs args) {
    return new SymmetricHashCountingJoin(null, null, argColumns1, argColumns2);
  }
}


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Consent Docs</title>

 We do ask survey questions about your health history. You may decline to answer if that makes you uncomfortable.


text:
ENV["RACK_ENV"] = "test"

require "rspec"
require "rspec-html-matchers"
require "rack/test"
require "pry"
require "faker"
require "ostruct"
require "date"

require "factories/feed_factory"
require "factories/story_factory"
require "factories/user_factory"
require "factories/group_factory"

require "./app"

RSpec.configure do |config|
  config.include Rack::Test::Methods
  config.include RSpecHtmlMatchers
end

def app_require(file)
  require File.expand_path(File.join("app", file))
end

def app
  Stringer
end

def session
  last_request.env["rack.session"]
end


text:
<!DOCTYPE html>

	<meta charset="utf-8">
	<meta name="robots" content="noindex">

	<title>File barcodegen/class/BCGFontFile.php | TPS Broadcast</title>

	<link rel="stylesheet" href="resources/style.css?e99947befd7bf673c6b43ff75e9e0f170c88a60e">

		Overview

Namespaces

						None

						PHP

						TPS

Classes

Barcode

Barcode11

Barcode128

Barcode39

Barcode93

BarcodeCodabar

BarcodeDatamatrix

BarcodeEAN

BarcodeI25

BarcodeMSI

BarcodeUPC

BCGBarcode

BCGBarcode1D

BCGcodabar

BCGcode11

BCGcode128

BCGcode39

BCGcode39extended

BCGcode93

BCGColor

BCGDraw

BCGDrawing

BCGDrawJPG

BCGDrawPNG

BCGean13

BCGean8

BCGFontFile

BCGFontPhp

BCGgs1128

BCGi25

BCGintelligentmail

BCGisbn

BCGLabel

BCGmsi

BCGothercode

BCGpostnet

BCGs25

BCGupca

BCGupce

BCGupcext2

BCGupcext5

JoinDraw

LibraryAPI

playing

standardResult

TPS\alert

TPS\emergencyAlert

TPS\episode

TPS\genre

TPS\genreTest

TPS\label

TPS\library

TPS\logger

TPS\program

TPS\Report

TPS\reviews

TPS\song

TPS\station

TPS\submissionTracking

TPS\TPS

TPS\TPSTest

TPS_Cron

Interfaces

BCGFont

Exceptions

BCGArgumentException

BCGDrawException

BCGParseException

Exception

Functions

absolute_include

ApplyUpdate

baseCustomSetup

checkbrute

CheckStorage

CheckTTF

CheckUpdate

CheckUpdateStatus

convertTime

customSetup

DatabaseUpdateApply

DatabaseUpdateCheck

DB_Auth

db_close

db_conn

decrypt

drawCross

easy_crypt

easy_decrypt

encrypt

esc_url

Extensions

file_put_contents

findHOME

findLocal

findValueFromKey

gen_trivial_password

getBrowser

getButton

getCheckboxHtml

getElementHtml

getImageKeys

getInputTextHtml

GetLabelbyId

GetLibraryfull

GetLibraryRefcode

getOptionGroup

getOptionHtml

getRealIpAddr

GetResponse

getSelectHtml

GetWebsitesbyRefCode

is_session_started

LDAP_AUTH

listbarcodes

listfonts

ListLibrary

LoadStorage

login

login_check

MakeFont

MakeFontDescriptor

MakeFontEncoding

MakeWidthArray

ReadAFM

ReadLong

ReadMap

ReadShort

registerImageKey

remove_utf8_bom

SaveStorage

SaveToFile

SearchLibrary

sec_session_start

set_db_params

showError

to12hour

to24hour

track_can_play

UPCAbarcode

UpdateMeta

validate_EAN13Barcode

validate_UPCABarcode

Versions

	<form id="search">
		<input type="hidden" name="cx" value="">
		<input type="hidden" name="ie" value="UTF-8">
		<input type="text" name="q" class="text" placeholder="Search">
	</form>

				Overview

Namespace

Class

				Tree

						Todo

  1: <?php
  2:
 11: include_once('BCGArgumentException.php');
 12: include_once('BCGFont.php');
 13:
 14: class BCGFontFile implements BCGFont {
 15:     const PHP_BOX_FIX = 0;
 16:
 17:     private $path;
 18:     private $size;
 19:     private $text = '';
 20:     private $rotationAngle = 0;
 21:     private $box;
 22:     private $underlineX;
 23:     private $underlineY;
 24:     private $boxFix;
 25:
 26:     /**
 27:      * Constructor.
 28:      *
 29:      * @param string $fontPath path to the file
 30:      * @param int $size size in point
 31:      */
 32:     public function __construct($fontPath, $size) {
 33:         if (!file_exists($fontPath)) {
 34:             throw new BCGArgumentException('The font path is incorrect.', 'fontPath');
 35:         }
 36:
 37:         $this->path = $fontPath;
 38:         $this->size = $size;
 39:         $this->setRotationAngle(0);
 40:         $this->setBoxFix(self::PHP_BOX_FIX);
 41:     }
 42:
 43:     /**
 44:      * Gets the text associated to the font.
 45:      *
 46:      * @return string
 47:      */
 48:     public function getText() {
 49:         return $this->text;
 50:     }
 51:
 52:     /**
 53:      * Sets the text associated to the font.
 54:      *
 55:      * @param string text
 56:      */
 57:     public function setText($text) {
 58:         $this->text = $text;
 59:         $this->rebuildBox();
 60:     }
 61:
 62:     /**
 63:      * Gets the rotation in degree.
 64:      *
 65:      * @return int
 66:      */
 67:     public function getRotationAngle() {
 68:         return $this->rotationAngle;
 69:     }
 70:
 71:     /**
 72:      * Sets the rotation in degree.
 73:      *
 74:      * @param int
 75:      */
 76:     public function setRotationAngle($rotationAngle) {
 77:         $this->rotationAngle = (int)$rotationAngle;
 78:         if ($this->rotationAngle !== 90 && $this->rotationAngle !== 180 && $this->rotationAngle !== 270) {
 79:             $this->rotationAngle = 0;
 80:         }
 81:
 82:         $this->rebuildBox();
 83:     }
 84:
 85:     /**
 86:      * Gets the background color.
 87:      *
 88:      * @return BCGColor
 89:      */
 90:     public function getBackgroundColor() {
 91:     }
 92:
 93:     /**
 94:      * Sets the background color.
 95:      *
 96:      * @param BCGColor $backgroundColor
 97:      */
 98:     public function setBackgroundColor($backgroundColor) {
 99:     }
100:
101:     public function getBoxFix() {
102:         return $this->boxFix;
103:     }
104:
105:     public function setBoxFix($value) {
106:         $this->boxFix = intval($value);
107:     }
108:
109:     /**
110:      * Returns the width and height that the text takes to be written.
111:      *
112:      * @return int[]
113:      */
114:     public function getDimension() {
115:         $w = 0.0;
116:         $h = 0.0;
117:
118:         if ($this->box !== null) {
119:             $minX = min(array($this->box[0], $this->box[2], $this->box[4], $this->box[6]));
120:             $maxX = max(array($this->box[0], $this->box[2], $this->box[4], $this->box[6]));
121:             $minY = min(array($this->box[1], $this->box[3], $this->box[5], $this->box[7]));
122:             $maxY = max(array($this->box[1], $this->box[3], $this->box[5], $this->box[7]));
123:
124:             $w = $maxX - $minX;
125:             $h = $maxY - $minY;
126:         }
127:
128:         if ($this->rotationAngle === 90 || $this->rotationAngle === 270) {
129:             return array($h + self::PHP_BOX_FIX, $w);
130:         } else {
131:             return array($w + self::PHP_BOX_FIX, $h);
132:         }
133:     }
134:
135:     /**
136:      * Draws the text on the image at a specific position.
137:      * $x and $y represent the left bottom corner.
138:      *
139:      * @param resource $im
140:      * @param int $color
141:      * @param int $x
142:      * @param int $y
143:      */
144:     public function draw($im, $color, $x, $y) {
145:         $drawingPosition = $this->getDrawingPosition($x, $y);
146:         imagettftext($im, $this->size, $this->rotationAngle, $drawingPosition[0], $drawingPosition[1], $color, $this->path, $this->text);
147:     }
148:
149:     private function getDrawingPosition($x, $y) {
150:         $dimension = $this->getDimension();
151:         if ($this->rotationAngle === 0) {
152:             $y += abs(min($this->box[5], $this->box[7]));
153:         } elseif ($this->rotationAngle === 90) {
154:             $x += abs(min($this->box[5], $this->box[7]));
155:             $y += $dimension[1];
156:         } elseif ($this->rotationAngle === 180) {
157:             $x += $dimension[0];
158:             $y += abs(max($this->box[1], $this->box[3]));
159:         } elseif ($this->rotationAngle === 270) {
160:             $x += abs(max($this->box[1], $this->box[3]));
161:         }
162:
163:         return array($x, $y);
164:     }
165:
166:     private function rebuildBox() {
167:         $gd = imagecreate(1, 1);
168:         $this->box = imagettftext($gd, $this->size, 0, 0, 0, 0, $this->path, $this->text);
169:
170:         $this->underlineX = abs($this->box[0]);
171:         $this->underlineY = abs($this->box[1]);
172:
173:         if ($this->rotationAngle === 90 || $this->rotationAngle === 270) {
174:             $this->underlineX ^= $this->underlineY ^= $this->underlineX ^= $this->underlineY;
175:         }
176:     }
177: }
178: ?>

		TPS Broadcast API documentation generated by ApiGen


text:
'use strict';

var leftVideo = document.getElementById('leftVideo');
var rightVideo = document.getElementById('rightVideo');

var stream;

leftVideo.onplay = function() {
  if (leftVideo.captureStream) {
    stream = leftVideo.captureStream();
    rightVideo.srcObject = stream;
    console.log('Captured stream from leftVideo with captureStream',
      stream);
  } else if (leftVideo.mozCaptureStream) {
    stream = leftVideo.mozCaptureStream();
    rightVideo.srcObject = stream;
    console.log('Captured stream from leftVideo with mozCaptureStream()',
      stream);
  } else {
    console.log('captureStream() not supported');
  }
};

leftVideo.play();


text:
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Data;
using System.Linq;
using System.Text;

namespace ServiceRegistry
{
    public static class ServiceStatus
    {
        private const string BaseUrl = "https://mobile-messaging.appspot.com/_ah/api/services/v1.3/";
        private const string RegisterServiceString = "services/{0}";
        private const string UpdateStatusString = "services/{0}/{1}";

        public static void RegisterService(string serviceId, string serviceGroup)
        {
            RestClient.Post(BaseUrl + string.Format(RegisterServiceString, serviceGroup),
                new Service
                {
                    serviceId = serviceId,
                    serviceGroup = serviceGroup,
                    status = 2
                });
        }

        public static void UpdateStatus(string serviceId, string serviceGroup, int status)
        {
            RestClient.Put(BaseUrl + string.Format(UpdateStatusString, serviceGroup, serviceId), new Service
            {
                status = status
            });
        }

        public class Service
        {
            public string serviceId { get; set; }
            public string serviceGroup { get; set; }
            public int status { get; set; }
            public long lastUpdate { get; set; }
        }
    }
}


text:
declare namespace Bokeh {
    export interface Range extends Model, IRange {}
    export interface IRange extends IModel {
        callback?: Callback;
    }

    export var Range1d: {
        new(attributes?: IRange1d, options?: ModelOpts): Range1d;
        (start: number, end: number): Range1d;
    }
    export interface Range1d extends Range {}
    export interface IRange1d extends IRange {
        start?: number;
        end?: number;
        bounds?: Auto | [number, number] /*| [Datetime, Datetime]*/;
    }

    export interface DataRange extends Range, IDataRange {}
    export interface IDataRange extends IRange {
        names?: Array<string>;
        renderers?: Array<Renderer>;
    }

    export var DataRange1d: { new(attributes?: IDataRange1d, options?: ModelOpts): DataRange1d };
    export interface DataRange1d extends DataRange, IDataRange1d {}
    export interface IDataRange1d extends IDataRange {
        range_padding?: number;

        start?: number;
        end?: number;

        bounds?: Auto | [number, number];

        flipped?: boolean;
        follow?: StartEnd;
        follow_interval?: number;
        default_span?: number;
    }

    export var FactorRange: { new(attributes?: IFactorRange, options?: ModelOpts): FactorRange };
    export interface FactorRange extends Range, IFactorRange {}
    export interface IFactorRange extends IRange {
        offset?: number;
        factors?: Array<string> | Array<Int>;
        bounds?: Auto | Array<string> | Array<Int>;
    }
}