text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<TITLE>
Point
</TITLE>

<META NAME="keywords" CONTENT="mdes.slick.sui.Point class">

<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../stylesheet.css" TITLE="Style">

      Overview
      Package
    Class
      Use
      Tree
      Deprecated
      Index
      Help

 PREV CLASS
 NEXT CLASS

  FRAMES
 NO FRAMES

  All Classes

  SUMMARY: NESTED | FIELD | CONSTR | METHOD

DETAIL: FIELD | CONSTR | METHOD

mdes.slick.sui

Class Point

java.lang.Object
  mdes.slick.sui.Point

public class Point
extends java.lang.Object

A simple Point class to hold (x,y) coordinates.

Since:

b2.0

Field Summary

 float
x

          The x position of this point.

 float
y

          The y position of this point.

Constructor Summary

Point()

          Creates a new instance of Point at (0,0).

Point(float x,
      float y)

          Creates a new instance of Point with the specified x and y location.

Point(Point p)

          Creates a new instance of Point using the (x,y) coordinates from the specified
 point.

Method Summary

 java.lang.Object
clone()

          Creates a new object of the same class as this object.

 boolean
equals(java.lang.Object o)

          Returns <tt>true</tt> if the given Object is an instance of Point with the
 same location as this point, otherwise returns <tt>false</tt>.

 void
setLocation(float x,
            float y)

          Sets the location of this Point to the specified x and y positions.

 void
setLocation(Point p)

          Sets the location of this Point using the location of the specified
 Point object.

 java.lang.String
toString()

          Returns a String representation of this Point.

Methods inherited from class java.lang.Object

finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait

Field Detail

x

public float x

The x position of this point.

y

public float y

The y position of this point.

Constructor Detail

Point

public Point()

Creates a new instance of Point at (0,0).

Point

public Point(float x,
             float y)

Creates a new instance of Point with the specified x and y location.

Parameters:
x - the x position in the coordinate space
y - the y position in the coordinate space

Point

public Point(Point p)

Creates a new instance of Point using the (x,y) coordinates from the specified
 point.

Parameters:
p - a point

Method Detail

setLocation

public void setLocation(float x,
                        float y)

Sets the location of this Point to the specified x and y positions.

Parameters:
x - the new x position
y - the new y position

setLocation

public void setLocation(Point p)

Sets the location of this Point using the location of the specified
 Point object.

Parameters:
p - a point to use for new x and y positions

equals

public boolean equals(java.lang.Object o)

Returns <tt>true</tt> if the given Object is an instance of Point with the
 same location as this point, otherwise returns <tt>false</tt>.

Parameters:
o - the object to check against

Returns:
<tt>true</tt> if the two points are equal

clone

public java.lang.Object clone()

Creates a new object of the same class as this object.

Returns:
a clone of this instance.

toString

public java.lang.String toString()

Returns a String representation of this Point.

Returns:
a String representing this Point

      Overview
      Package
    Class
      Use
      Tree
      Deprecated
      Index
      Help

 PREV CLASS
 NEXT CLASS

  FRAMES
 NO FRAMES

  All Classes

  SUMMARY: NESTED | FIELD | CONSTR | METHOD

DETAIL: FIELD | CONSTR | METHOD

redpajama_set_name: RedPajamaGithub


text:
r"""
This code was generated by
\ / _    _  _|   _  _
 | (_)\/(_)(_|\/| |(/_  v1.0.0
      /       /
"""

from twilio.base.domain import Domain
from twilio.rest.voice.v1 import V1

class Voice(Domain):

    def __init__(self, twilio):
        """
        Initialize the Voice Domain

        :returns: Domain for Voice
        :rtype: twilio.rest.voice.Voice
        """
        super(Voice, self).__init__(twilio)

        self.base_url = 'https://voice.twilio.com'

        # Versions
        self._v1 = None

    @property
    def v1(self):
        """
        :returns: Version v1 of voice
        :rtype: twilio.rest.voice.v1.V1
        """
        if self._v1 is None:
            self._v1 = V1(self)
        return self._v1

    @property
    def dialing_permissions(self):
        """
        :rtype: twilio.rest.voice.v1.dialing_permissions.DialingPermissionsList
        """
        return self.v1.dialing_permissions

    def __repr__(self):
        """
        Provide a friendly representation

        :returns: Machine friendly representation
        :rtype: str
        """
        return '<Twilio.Voice>'


text:
/*
  README:  Test multiple OpenMP threads
           The main thread creates NUM_THREADS handles/streams
           Each OpenMP thread calls a rocblas routine asscociated with one handle, one stream
           The main thread finally destroy all handles/streams
           An alternate valid way is each thread creates its own handle/stream and destroy it locally.
           But in the second way, the handles/streams can not persist across multiple parallel regions.
           In this example, we have two parallel regions

           It is NOT recommended that multiple thread share the same rocblas handle.
           Yet, it is safe that multiple thread shared the same stream.
           If users do not create streams explicitely like what I am doing here,
           all rocblas routine take the NULL (0) stream.
*/

#include <omp.h>
#include <stdlib.h>
#include <stdio.h>
#include <vector>

#include "rocblas.hpp"
#include "utility.h"

using namespace std;

#define NUM_THREADS 4

/* ============================================================================================ */

int main()
{

    rocblas_int N = 102400;
    float alpha = 10.0;

    omp_set_num_threads(NUM_THREADS);
    int thread_id;
    printf("%d OpenMP threads performing rocblas_scal \n", NUM_THREADS);

    //Naming: dX is in GPU (device) memory. hK is in CPU (host) memory, plz follow this practice
    vector<float> hx(N * NUM_THREADS);
    vector<float> hz(N * NUM_THREADS);
    float *dx, *dy;

    double gpu_time_used;

    rocblas_handle handles[NUM_THREADS];
    hipStream_t streams[NUM_THREADS];

    //Create handle/stream have overhead
    for(rocblas_int i=0;i<NUM_THREADS;i++){
        rocblas_create_handle(&handles[i]);
        hipStreamCreate(&streams[i]);
    }

    //allocate memory on device
    hipMalloc(&dx, N * NUM_THREADS * sizeof(float));
    hipMalloc(&dy, N * NUM_THREADS * sizeof(float));

    //Initial Data on CPU
    srand(1);
    rocblas_init<float>(hx, 1, N * NUM_THREADS, 1);

    //copy vector is easy in STL; hz = hx: save a copy in hz which will be output of CPU BLAS
    hz = hx;

    hipMemcpy(dx, hx.data(), sizeof(float)*N * NUM_THREADS, hipMemcpyHostToDevice);

    printf("N        rocblas(us)     \n");

    gpu_time_used = get_time_us();// in microseconds

    //1st parallel rocblas routine call : scal x
    //spawn openmp threads
    #pragma omp parallel private(thread_id)
    {

        int thread_id = omp_get_thread_num(); // thread_id from 0,...,NUM_THREADS-1
        //associate each handle with a stream
        rocblas_set_stream(handles[thread_id], streams[thread_id]);

        /* =====================================================================
             ROCBLAS  template interface
        =================================================================== */
        rocblas_scal<float>(handles[thread_id],
                        N,
                        &alpha,
                        dx + thread_id*N, 1);

        //Blocks until all stream has completed all operations.
        hipStreamSynchronize(streams[thread_id]);
    }

    //2nd parallel rocblas routine call : copy x to y
    //spawn openmp threads
    #pragma omp parallel private(thread_id)
    {

        int thread_id = omp_get_thread_num(); // thread_id from 0,...,NUM_THREADS-1
        //associate each handle with a stream
        rocblas_set_stream(handles[thread_id], streams[thread_id]);

        /* =====================================================================
             ROCBLAS  template interface
        =================================================================== */
        rocblas_copy<float>(handles[thread_id],
                        N,
                        dx + thread_id*N, 1,
                        dy + thread_id*N, 1);

        //Blocks until all stream has completed all operations.
        hipStreamSynchronize(streams[thread_id]);
    }

    gpu_time_used = get_time_us() - gpu_time_used;

    //copy output from device to CPU
    hipMemcpy(hx.data(), dy, sizeof(float)*N * NUM_THREADS, hipMemcpyDeviceToHost);

#if 0
    //verify rocblas_scal result
    for(rocblas_int i=0;i<N*NUM_THREADS;i++){
        if(hz[i] * alpha != hx[i]){
            printf("error in element %d: CPU=%f, GPU=%f ", i, hz[i]*alpha, hx[i]);
            break;
        }
    }

#endif

    printf("%d    %8.2f         \n", (int)N * NUM_THREADS, gpu_time_used);

    hipFree(dx);
    hipFree(dy);

    //Destroy handle/streams
    for(rocblas_int i=0;i<NUM_THREADS;i++){
        rocblas_destroy_handle(handles[i]);
        hipStreamDestroy(streams[i]);
    }

    return 0;
}


text:
using System;

namespace UnTest.Tests {

    class MockEquatable<T> : IEquatable<MockEquatable<T>> where T : IEquatable<T> {

        public MockEquatable(T value) {
            Value = value;
        }

        public T Value;

        public override int GetHashCode() {
            return Value.GetHashCode();
        }

        public override bool Equals(Object obj) {
            if (obj is MockEquatable<T>) {
                return Equals((MockEquatable<T>)obj);
            } else {
                return base.Equals(obj);
            }
        }

        public bool Equals(MockEquatable<T> other) {
            return Value.Equals(other.Value);
        }
    }
}


text:
===============
MathProgBase.jl
===============

.. module:: MathProgBase
   :synopsis: Solver-independent functions and low-level interfaces for Mathematical Programming

`MathProgBase.jl <https://github.com/JuliaOpt/MathProgBase.jl>`_ provides high-level
one-shot functions for linear and mixed-integer programming,
as well as a solver-independent low-level interface for implementing advanced techniques
that require efficiently solving a sequence of linear programming problems.

To use MathProgBase, an external solver must be installed. See :ref:`choosing solvers <choosing-solvers>`.

Contents
--------

.. toctree::
    :maxdepth: 2

    linprog.rst
    mixintprog.rst
    quadprog.rst
    lowlevel.rst
    solvers.rst
    mipcallbacks.rst
    conic.rst
    sdp.rst
    nlp.rst


text:
app.controller("AngularFormController", ["$http", "$scope", function($http, $scope) {
	/**
	 * State variable to store alerts generated from submit event
	 * @type {Array}
	 **/
	$scope.alerts = [];

	/**
	 * State variable that keeps track of data entered
	 * @type {Object}
	 **/
	$scope.formData = {product:null, name:null, email:null, phone: null, website:null, comment:null};

	/**
	 * Method to reset form data when submit and cancel buttons are pressed
	 **/
	$scope.reset = function() {
		$scope.formData = {product:null, name:null, email:null, phone: null, website:null, comment:null};
		$scope.quoteForm.$setUntouched();
		$scope.quoteForm.$setPristine();
	};

	/**
	 * Method to process action from submit button
	 *
	 * @param formData object containing submitted form data
	 * @param validated true if pressed validation, false if not
	 **/
	$scope.submit = function(formData, validated) {
		if(validated === true){
			$http.post("lib/mailer.php", formData)
				.then(function(reply) {
					$scope.alerts[0] = {
						type: "danger",
						msg: reply.data.message
					};
					if(reply.data.status === 200) {
						$scope.alerts[0].type = "success";
					}
				});
		} else {
			$scope.alerts[0] = {
				type: "danger",
				msg: "Please make sure you've entered everything correctly and try again."
			};
		}
		$scope.reset();
	};
}]);


text:
[![Greenkeeper badge](https://badges.greenkeeper.io/istanbuljs/istanbul-reports.svg)](https://greenkeeper.io/)
[![Build Status](https://travis-ci.org/istanbuljs/istanbul-reports.svg?branch=master)](https://travis-ci.org/istanbuljs/istanbul-reports)

-   node.getRelativeName

-   context.getSource(filePath)
-   context.classForPercent(type, percent)
-   context.console.colorize(str, class)
-   context.writer
-   context.console.write
-   context.console.println


text:
    <title>Discrpition</title>
    <meta name="author" content="Mailina">
    <meta name="editor" content="html-editor phase 5">
    <link rel="stylesheet" href="/static/css/Vorlage.css" type="text/css">

Description

    SmartWindow is a student project of the HAW Hamburg.

The Idea

    We asked ourselves what disturbs us during lectures. The answer was the air. Sometimes it is too cold, too hot, too sticky, too humid.

    So we asked ourselves how we could change this. The answer was to open a window.

    The last question we asked ourselves was about the possibility to automate it. This answer was easy. Yes, squire!

    A word and a blow.

The Concept

    Manual

    After choosing the manual mode on the homepage, the window can be opened and closed by the buttons on the homepage as long as the wind is calm.

    Automatic

    As standard limits the following values are used.

    Conditions for the best working environment:

    * Temperature between 20°C and 26°C.

    * Humidity between 30% and 65%.

    * Air quality higher than 1 Vol. %.

    Closing is forced by the following condition:

    * Outside volume higher than 60dB.

    Priority:

    The priority defines which alarm is paid attention to. If all alarms are examined, it is possible that the window stays open. This would be caused by the unknown dependence of all alarm causes.

    General

    When the Wind is stronger than 21 m/s, the window will not open or close immediately.


text:
namespace sync_file_system {

MockSyncStatusObserver::MockSyncStatusObserver() {
}

MockSyncStatusObserver::~MockSyncStatusObserver() {
}

}  // namespace sync_file_system


text:
/*****************************************************************************/
/*  Copyright (c) 2015, Alessandro Pieropan                                  */
/*  All rights reserved.                                                     */
/*                                                                           */
/*  Redistribution and use in source and binary forms, with or without       */
/*  modification, are permitted provided that the following conditions       */
/*  are met:                                                                 */
/*                                                                           */
/*  1. Redistributions of source code must retain the above copyright        */
/*  notice, this list of conditions and the following disclaimer.            */
/*                                                                           */
/*  2. Redistributions in binary form must reproduce the above copyright     */
/*  notice, this list of conditions and the following disclaimer in the      */
/*  documentation and/or other materials provided with the distribution.     */
/*                                                                           */
/*  3. Neither the name of the copyright holder nor the names of its         */
/*  contributors may be used to endorse or promote products derived from     */
/*  this software without specific prior written permission.                 */
/*                                                                           */
/*  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS      */
/*  "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT        */
/*  LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR    */
/*  A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT     */
/*  HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,   */
/*  SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT         */
/*  LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,    */
/*  DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY    */
/*  THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT      */
/*  (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE    */
/*  OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.     */
/*****************************************************************************/

#include "../include/tracker_2d_v2.h"

#include <utilities.h>
#include <DebugFunctions.h>
#include <DBScanClustering.h>
#include <opencv2/features2d/features2d.hpp>
#include <opencv2/highgui/highgui.hpp>
#define _USE_MATH_DEFINES
#include <math.h>
#include <limits>
#include <algorithm>
#include <utility>

#include "../include/pose_estimation.h"
#include "../../utilities/include/profiler.h"

using namespace std;
using namespace cv;

namespace fato {

TrackerV2::TrackerV2()
    : matcher_confidence_(0.75),
      matcher_ratio_(0.75){}
//      m_featuresDetector(30, 3, 1.0f) {
//  m_featuresDetector.create("Feature2D.BRISK");
//}

TrackerV2::TrackerV2(const TrackerParams& params)
    : matcher_confidence_(0.75),
      matcher_ratio_(0.75){}
//      m_featuresDetector(30, 3, 1.0f) {
//  m_featuresDetector.create("Feature2D.BRISK");
//}

TrackerV2::TrackerV2(const TrackerParams& params, const cv::Mat& camera_matrix)
    : matcher_confidence_(0.75),
      matcher_ratio_(0.75),
      //m_featuresDetector(30, 3, 1.0f),
      camera_matrix_(camera_matrix) {
  //m_featuresDetector.create("Feature2D.BRISK");
  ransac_iterations_ = params.ransac_iterations;
  ransac_distance_ = params.ransac_distance;
}

TrackerV2::~TrackerV2() { taskFinished(); }

bool TrackerV2::isPointValid(const int& id) {
  return m_pointsStatus[id] == KpStatus::TRACK;
}

void TrackerV2::init(const cv::Mat& rgb, const cv::Point2d& fst,
                     const cv::Point2d& scd) {
  auto mask = getMask(rgb.rows, rgb.cols, fst, scd);
  init(rgb, mask);
}

void TrackerV2::init(const Mat& rgb, const Mat& mask) {
  Mat gray;

  m_width = rgb.cols;
  m_height = rgb.rows;

  cvtColor(rgb, gray, CV_BGR2GRAY);

  // BRISK featuresDetector;
  m_featuresDetector.detect(gray, m_initKeypoints);
  m_featuresDetector.compute(gray, m_initKeypoints, m_initDescriptors);

  for (int i = 0; i < m_initKeypoints.size(); i++) {
    Point2f pt = m_initKeypoints[i].pt;

    m_points.push_back(pt);
  }

  // m_init_to_upd_ids.resize(m_initKeypoints.size(), -1);

  for (int i = 0; i < m_initKeypoints.size(); i++) {
    Point2f& pt = m_points[i];

    if (mask.at<uchar>(pt) == 255) {
      m_pointsStatus.push_back(KpStatus::INIT);
    } else {
      m_pointsStatus.push_back(KpStatus::BACKGROUND);
    }
    m_updatedPoints.push_back(m_points[i]);
    m_votes.push_back(Point2f(0, 0));
    m_upd_to_init_ids.push_back(i);
    m_init_to_upd_ids.push_back(i);
  }

  m_points_status_debug = m_pointsStatus;
  m_original_model_size = m_points.size();
  /****************************************************************************/
  /*                          INIT CENTROID                                   */
  /****************************************************************************/
  // cout << "Init centroid" << endl;
  m_initCentroid = initCentroid(m_updatedPoints);
  m_updatedCentroid = m_initCentroid;
  // cout << m_updatedCentroid << endl;
  /****************************************************************************/
  /*                          INIT RELATIVE DISTANCES                         */
  /****************************************************************************/
  // cout << "Init relative distance" << endl;
  initRelativeDistance(m_updatedPoints, m_initCentroid, m_relativeDistances);
  /****************************************************************************/
  /*                          INIT BOUNDING BOX                               */
  /****************************************************************************/
  // cout << "Init bounding box" << endl;
  initBoundingBox(mask, m_initCentroid, m_boundingBox, m_boundingBoxRelative,
                  m_boundingBoxUpdated);
  /****************************************************************************/
  /*                          INIT LEARNING                                   */
  /****************************************************************************/
  m_learned_poses.insert(make_pair<float, float>(0, 0));
  m_angle = 0;
  m_scale = 1;
  m_scale_old = m_scale;
  m_angle_old = m_angle;
  m_centroid_old = m_initCentroid;
  /****************************************************************************/
  /*                          INIT THREADS                                    */
  /****************************************************************************/
  m_isRunning = true;
  m_trackerStatus = async(launch::async, &TrackerV2::runTracker, this);
  m_detectorStatus = async(launch::async, &TrackerV2::runDetector, this);
  /****************************************************************************/
  /*                          LOADING IMGS ON GPU                             */
  /****************************************************************************/
  // cout << "load images" << endl;
  rgb.copyTo(m_init_rgb_img);
  gray.copyTo(prev_gray_);
}

void TrackerV2::setMatcerParameters(float confidence, float second_ratio) {
  matcher_confidence_ = confidence;
  matcher_ratio_ = second_ratio;
}

Point2f TrackerV2::initCentroid(const vector<Point2f>& points) {
  Point2f centroid(0, 0);
  int validPoints = 0;

  for (size_t i = 0; i < points.size(); i++) {
    if (m_pointsStatus[i] == KpStatus::INIT) {
      centroid += points[i];
      validPoints++;
    }
  }

  centroid.x = centroid.x / static_cast<float>(validPoints);
  centroid.y = centroid.y / static_cast<float>(validPoints);

  return centroid;
}

void TrackerV2::extractFeatures(const Mat& gray,
                                std::vector<KeyPoint>& keypoints,
                                Mat& descriptors) {
  m_featuresDetector.detect(gray, keypoints);
  m_featuresDetector.compute(gray, keypoints, descriptors);
}

void TrackerV2::initRelativeDistance(const vector<Point2f>& points,
                                     const Point2f& centroid,
                                     vector<Point2f>& relDistances) {
  relDistances.reserve(points.size());

  for (size_t i = 0; i < points.size(); i++) {
    relDistances.push_back(points[i] - centroid);
  }
}

void TrackerV2::initBoundingBox(const Mat& mask, const Point2f& centroid,
                                vector<Point2f>& initBox,
                                vector<Point2f>& relativeBox,
                                vector<Point2f>& updBox) {
  int minX = numeric_limits<int>::max();
  int minY = minX;
  int maxX = 0;
  int maxY = 0;

  for (size_t j = 0; j < mask.rows; j++) {
    for (size_t i = 0; i < mask.cols; i++) {
      if (mask.at<uchar>(j, i) != 0) {
        minX = minX < i ? minX : i;
        maxX = maxX > i ? maxX : i;
        minY = minY < j ? minY : j;
        maxY = maxY > j ? maxY : j;
      }
    }
  }

  initBox.push_back(Point2f(minX, minY));
  initBox.push_back(Point2f(maxX, minY));
  initBox.push_back(Point2f(maxX, maxY));
  initBox.push_back(Point2f(minX, maxY));

  for (size_t i = 0; i < initBox.size(); i++) {
    relativeBox.push_back(initBox[i] - centroid);
  }

  updBox = initBox;
}

void TrackerV2::getOpticalFlow(const Mat& prev, const Mat& next,
                               vector<Point2f>& points, vector<int>& ids,
                               vector<KpStatus>& status) {
  vector<Point2f> next_points, prev_points;
  vector<uchar> next_status, prev_status;
  vector<float> next_errors, prev_errors;

  calcOpticalFlowPyrLK(prev, next, points, next_points, next_status,
                       next_errors);

  calcOpticalFlowPyrLK(next, prev, next_points, prev_points, prev_status,
                       prev_errors);
  m_flow_counter = 0;
  for (int i = 0; i < next_points.size(); ++i) {
    float error = fato::getDistance(points[i], prev_points[i]);

    KpStatus& s = status[ids[i]];

    if (prev_status[i] == 1 && error < 20) {
      // const int& id = ids[i];
      auto id = i;

      if (s == KpStatus::MATCH) {
        status[id] = KpStatus::TRACK;
        m_flow_counter++;
      } else if (s == KpStatus::LOST)
        status[id] = KpStatus::LOST;
      else if (s == KpStatus::NOCLUSTER) {
        status[id] = KpStatus::LOST;
      } else if (s == KpStatus::TRACK || s == KpStatus::INIT) {
        status[id] = KpStatus::TRACK;
        m_flow_counter++;
      }

      points[i] = next_points[i];
    } else {
      // status[ids[i]] = Status::LOST;
      if (status[i] != KpStatus::BACKGROUND) status[i] = KpStatus::LOST;
      // TODO: remove pointer and ids if lost, it will still be in the detector
      // list
    }
  }
}

float TrackerV2::getMedianRotation(const vector<Point2f>& initPoints,
                                   const vector<Point2f>& updPoints,
                                   const vector<int>& ids) {
  vector<double> angles;
  angles.reserve(updPoints.size());

  for (size_t i = 0; i < updPoints.size(); i++) {
    for (size_t j = 0; j < updPoints.size(); j++) {
      if (isPointValid(ids[i]) && isPointValid(ids[j])) {
        Point2f a = updPoints[i] - updPoints[j];
        Point2f b = initPoints[ids[i]] - initPoints[ids[j]];

        double val = atan2(a.y, a.x) - atan2(b.y, b.x);

        if (abs(val) > M_PI) {
          int sign = (val < 0) ? -1 : 1;
          val = val - sign * 2 * M_PI;
        }
        angles.push_back(val);
      }
    }
  }

  sort(angles.begin(), angles.end());

  double median;
  size_t size = angles.size();

  if (size == 0) return 0;

  if (size % 2 == 0) {
    median = (angles[size / 2 - 1] + angles[size / 2]) / 2;
  } else {
    median = angles[size / 2];
  }

  return static_cast<float>(median);
}

float TrackerV2::getMedianScale(const vector<Point2f>& initPoints,
                                const vector<Point2f>& updPoints,
                                const vector<int>& ids) {
  vector<float> scales;

  for (size_t i = 0; i < updPoints.size(); ++i) {
    for (size_t j = 0; j < updPoints.size(); j++) {
      if (isPointValid(ids[i]) && isPointValid(ids[j])) {
        float nextDistance =
            fato::getDistance(updPoints[i], updPoints[j]);
        float currDistance =
            fato::getDistance(initPoints[ids[i]], initPoints[ids[j]]);

        if (currDistance != 0 && i != j) {
          scales.push_back(nextDistance / currDistance);
        }
      }
    }
  }

  sort(scales.begin(), scales.end());

  float median;
  size_t size = scales.size();

  if (size == 0) {
    return 1;
  }

  if (size % 2 == 0) {
    median = (scales[size / 2 - 1] + scales[size / 2]) / 2;
  } else {
    median = scales[size / 2];
  }

  return median;
}

void TrackerV2::voteForCentroid(const vector<Point2f>& relativeDistances,
                                const vector<Point2f>& updPoints,
                                const float& angle, const float& scale,
                                vector<Point2f>& votes) {
  Mat2f rotMat(2, 2);

  rotMat.at<float>(0, 0) = cosf(angle);
  rotMat.at<float>(0, 1) = sinf(angle);
  rotMat.at<float>(1, 0) = -sinf(angle);
  rotMat.at<float>(1, 1) = cosf(angle);

  // int voteCount = 0;

  // cout << "VOTES: P " << updPoints.size() << " V: " << votes.size() << endl;

  for (size_t i = 0; i < updPoints.size(); i++) {
    if (isPointValid(i)) {
      const Point2f& a = updPoints[i];
      const Point2f& rm = relativeDistances[i];

      votes[i] = a - scale * mult(rotMat, rm);
    }
  }
}

void TrackerV2::clusterVotes(vector<Point2f>& centroidVotes,
                             vector<bool>& isClustered) {
  DBScanClustering<Point2f*> clusterer;

  vector<Point2f*> votes;
  vector<unsigned int> indices;

  for (unsigned int i = 0; i < centroidVotes.size(); i++) {
    if (isPointValid(i)) {
      votes.push_back(&centroidVotes[i]);
      indices.push_back(i);
    }
  }

  clusterer.clusterPoints(&votes, 15, 5, [](Point2f* a, Point2f* b) {
    return sqrt(pow(a->x - b->x, 2) + pow(a->y - b->y, 2));
  });

  auto res = clusterer.getClusters();
  int maxVal = 0;
  int maxId = -1;

  for (size_t i = 0; i < res.size(); i++) {
    if (res[i].size() > maxVal) {
      maxVal = res[i].size();
      maxId = i;
    }
  }

  isClustered.resize(centroidVotes.size(), false);

  int clusterVoteSize = 0;

  if (maxId > -1) {
    for (size_t i = 0; i < res[maxId].size(); i++) {
      unsigned int& id = indices[res[maxId][i]];
      isClustered[id] = true;
    }

    clusterVoteSize = res[maxId].size();
  }
}

void TrackerV2::updateCentroid(const float& angle, const float& scale,
                               const vector<Point2f>& votes,
                               const vector<bool>& isClustered,
                               Point2f& updCentroid) {
  updCentroid.x = 0;
  updCentroid.y = 0;

  int validKp = 0;

  for (int i = 0; i < votes.size(); ++i) {
    if (isPointValid(i) && isClustered[i]) {
      updCentroid += votes[i];
      validKp++;
    }
  }

  if (validKp == 0) {
    m_is_object_lost = true;
  } else {
    m_is_object_lost = false;
    updCentroid.x = updCentroid.x / static_cast<float>(validKp);
    updCentroid.y = updCentroid.y / static_cast<float>(validKp);
  }
}

void TrackerV2::updatePointsStatus(const vector<bool>& isClustered,
                                   vector<Point2f>& points,
                                   vector<Point2f>& votes,
                                   vector<Point2f>& relDistances,
                                   vector<int>& ids,
                                   vector<KpStatus>& pointsStatus) {
  vector<int> toBeRemoved;

  for (int i = 0; i < isClustered.size(); ++i) {
    if (!isClustered[i]) {
      toBeRemoved.push_back(i);
      pointsStatus[ids[i]] = KpStatus::LOST;
    }
  }

  int back = points.size() - 1;

  for (int i = 0; i < toBeRemoved.size(); ++i) {
    const int dest = back - i;
    const int src = toBeRemoved[i];
    std::swap(points[src], points[dest]);
    std::swap(votes[src], votes[dest]);
    std::swap(ids[src], ids[dest]);
    std::swap(relDistances[src], relDistances[dest]);
  }

  int reducedSize = points.size() - toBeRemoved.size();
  points.resize(reducedSize);
  votes.resize(reducedSize);
  ids.resize(reducedSize);
  relDistances.resize(reducedSize);
}

void TrackerV2::labelNotClusteredPts(const vector<bool>& isClustered,
                                     vector<Point2f>& points,
                                     vector<Point2f>& votes,
                                     vector<Point2f>& relDistances,
                                     vector<int>& ids,
                                     vector<KpStatus>& pointsStatus) {
  for (int i = 0; i < isClustered.size(); ++i) {
    if (!isClustered[i] && m_pointsStatus[ids[i]] != KpStatus::BACKGROUND) {
      pointsStatus[ids[i]] = KpStatus::LOST;
    }
    // else if (isClustered[i] && pointsStatus[ids[i]] == Status::NOCLUSTER)
    //  pointsStatus[ids[i]] = Status::TRACK;
  }
}

void TrackerV2::discardNotClustered(std::vector<Point2f>& upd_points,
                                    std::vector<Point2f>& init_pts,
                                    cv::Point2f& upd_centroid,
                                    cv::Point2f& init_centroid,
                                    std::vector<int>& ids,
                                    std::vector<KpStatus>& pointsStatus) {
  for (auto i = 0; i < upd_points.size(); ++i) {
    auto id = ids[i];

    if (pointsStatus[id] == KpStatus::NOCLUSTER) {
      float init_dist = fato::getDistance(init_pts[id], init_centroid);
      float upd_dist =
          fato::getDistance(upd_points[i], upd_centroid) * m_scale;

      float ratio = min(init_dist, upd_dist) / max(init_dist, upd_dist);

      if (ratio < 0.85) pointsStatus[id] = KpStatus::LOST;
    }
  }
}

void TrackerV2::removeLostPoints(const std::vector<bool>& isClustered,
                                 std::vector<Point2f>& points,
                                 std::vector<Point2f>& votes,
                                 std::vector<Point2f>& relDistances,
                                 std::vector<int>& ids,
                                 std::vector<KpStatus>& pointsStatus) {
  vector<int> toBeRemoved;

  for (int i = 0; i < points.size(); ++i) {
    const int& id = ids[i];
    if (pointsStatus[i] == KpStatus::LOST) {
      toBeRemoved.push_back(i);
    }
  }

  int back = points.size() - 1;

  for (int i = 0; i < toBeRemoved.size(); ++i) {
    const int dest = back - i;
    const int src = toBeRemoved[i];
    std::swap(points[src], points[dest]);
    std::swap(votes[src], votes[dest]);
    std::swap(ids[src], ids[dest]);
    std::swap(relDistances[src], relDistances[dest]);
  }

  int reducedSize = points.size() - toBeRemoved.size();
  points.resize(reducedSize);
  votes.resize(reducedSize);
  ids.resize(reducedSize);
  relDistances.resize(reducedSize);
}

void TrackerV2::updateBoundingBox(const float& angle, const float& scale,
                                  const vector<Point2f>& boundingBoxRelative,
                                  const Point2f& updCentroid,
                                  vector<Point2f>& updBox) {
  Mat2f rotMat(2, 2);

  rotMat.at<float>(0, 0) = cosf(angle);
  rotMat.at<float>(0, 1) = sinf(angle);
  rotMat.at<float>(1, 0) = -sinf(angle);
  rotMat.at<float>(1, 1) = cosf(angle);

  for (int i = 0; i < updBox.size(); ++i) {
    updBox[i] = updCentroid + scale * mult(rotMat, boundingBoxRelative[i]);
  }
}

void TrackerV2::computeNext(const Mat& next) {
  // cout << "Computing next! " << endl;

  m_nextRgb = next;
  m_completed = 0;
  m_trackerDone = false;
  m_matcherDone = false;

  m_learn_new_pose = false;

  m_trackerCondition.notify_one();
  m_detectorCondition.notify_one();

  std::chrono::microseconds sleepTime(1);

  while (!m_trackerDone || !m_matcherDone) {
    std::this_thread::sleep_for(sleepTime);
  }
  /****************************************************************************/
  /*                LEARNING PROCEDURE                                        */
  /****************************************************************************/
  // m_learn_new_pose = evaluatePose(m_angle, m_scale);
  /*if (m_learn_new_pose && !m_is_object_lost) {
    learnPose(m_boundingBoxUpdated, dm_prevGray, m_points, m_updatedPoints,
              m_pointsStatus, m_init_to_upd_ids);
  }*/
  /****************************************************************************/
  /*                STORE COMPUTATIONS                                        */
  /****************************************************************************/
  m_scale_old = m_scale;
  m_angle_old = m_angle;
  m_centroid_old = m_updatedCentroid;
}

void TrackerV2::taskFinished() {
  m_isRunning = false;
  m_trackerCondition.notify_one();
  m_detectorCondition.notify_one();
}

int TrackerV2::runTracker() {
  // cv::gpu::setDevice(0);

  m_trackerFrameCount = 0;
  m_trackerTime = 0;

  cout << "Tracker process initialized! \n" << endl;

  while (m_isRunning) {
    unique_lock<mutex> lock(m_trackerMutex);
    m_trackerCondition.wait(lock);
    if (!m_isRunning) break;
    if (m_nextRgb.empty()) break;
    /*********************************************************************************/
    /*********************************************************************************/
    Mat rgb = m_nextRgb;
    //    cout << "before tracker \n" << endl;
    trackNext(rgb);
    //    cout << "after tracker \n" << endl;
    m_completed++;
    m_trackerDone = true;
    /*********************************************************************************/
    m_trackerFrameCount++;
    /*********************************************************************************/
  }

  cout << "Tracker stopped!" << endl;
  return 0;
}

int TrackerV2::runDetector() {
  m_detectorFrameCount = 0;
  m_detectorTime = 0;

  cout << "Detector porcess initialized! \n" << endl;

  while (m_isRunning) {
    unique_lock<mutex> lock(m_detectorMutex);
    m_detectorCondition.wait(lock);
    if (!m_isRunning) break;
    if (m_nextRgb.empty()) break;
    /*********************************************************************************/

    /*********************************************************************************/
    Mat rgb = m_nextRgb;
    //    cout << "before detector \n" << endl;
    detectNext(rgb);
    //    cout << "after detector \n" << endl;
    m_matcherDone = true;
    m_completed++;
    /*********************************************************************************/
    m_detectorFrameCount++;
    /*********************************************************************************/
  }

  cout << "Matcher stopped!" << endl;
  return 0;
}

void TrackerV2::trackNext(Mat next) {
  /*************************************************************************************/
  /*                       LOADING IMAGES */
  /*************************************************************************************/
  Mat next_gray;
  cvtColor(next, next_gray, CV_BGR2GRAY);
  /*************************************************************************************/
  /*                       TRACKING */
  /*************************************************************************************/
  //  cout << "Optical flow " << endl;
  getOpticalFlow(prev_gray_, next_gray, m_updatedPoints, m_upd_to_init_ids,
                 m_pointsStatus);
  /*************************************************************************************/
  /*                             POSE ESTIMATION /
  /*************************************************************************************/
  auto& profiler = Profiler::getInstance();
  //  profiler->start("pose");
  //  float angle = getMedianRotation(m_points, m_updatedPoints,
  //  m_upd_to_init_ids);
  //  float scale = getMedianScale(m_points, m_updatedPoints,
  //  m_upd_to_init_ids);
  //  m_angle = angle;
  //  m_scale = scale;
  //  profiler->stop("pose");

  vector<Point2f*> model_pts;
  vector<Point2f*> tracked_pts;
  profiler->start("pose_n");
  getTrackedPoints(m_points, m_updatedPoints, m_upd_to_init_ids, model_pts,
                   tracked_pts);
  float scale, angle;
  getPose2D(model_pts, tracked_pts, scale, angle);
  profiler->stop("pose_n");
  //  cout << "angle: " << angle << " - " << angle_n << " scale " << scale << "
  //  - "
  //       << scale_n << "\n";

  //  vector<Point3f> model_pts_alt;
  //  vector<Point2f> tracked_pts_alt;
  //  getTrackedPoints(m_points, m_updatedPoints, m_upd_to_init_ids,
  //  model_pts_alt,
  //                   tracked_pts_alt);
  //  vector<int> inliers;
  //  Mat rotation, translation;
  //  profiler->start("ransac");
  //getPose2D(model_pts_alt, tracked_pts_alt, camera_matrix_,
  //  ransac_iterations_,
  //            ransac_distance_, inliers, rotation, translation);
  //  profiler->stop("ransac");

  // angle = 0;
  // m_angle = 0.0f;
  //  cout << "Angle " << angle << endl;
  /*************************************************************************************/
  /*                             VOTING */
  /*************************************************************************************/
  //   cout << "Vote " << endl;
  voteForCentroid(m_relativeDistances, m_updatedPoints, angle, scale, m_votes);
  /*************************************************************************************/
  /*                             CLUSTERING */
  /*************************************************************************************/
  //   cout << "Cluster " << endl;
  vector<bool> isClustered;
  clusterVotes(m_votes, isClustered);
  /*************************************************************************************/
  /*                             UPDATING LIST OF POINTS */
  /*************************************************************************************/
  // updatePointsStatus(isClustered, m_updatedPoints, m_votes,
  // m_relativeDistances,
  //                   m_pointsIds, m_pointsStatus);
  // TODO: tracker works better without removing points here, WHY?!?
  labelNotClusteredPts(isClustered, m_updatedPoints, m_votes,
                       m_relativeDistances, m_upd_to_init_ids, m_pointsStatus);

  // discardNotClustered(m_updatedPoints, m_points, m_updatedCentroid,
  //                    m_initCentroid, m_upd_to_init_ids, m_pointsStatus);

  // removeLostPoints(isClustered, m_updatedPoints, m_votes,
  //                 m_relativeDistances, m_pointsIds, m_pointsStatus);
  /*************************************************************************************/
  /*                             UPDATING CENTROID */
  /*************************************************************************************/
  //   cout << "Upd centroid " << endl;
  updateCentroid(angle, scale, m_votes, isClustered, m_updatedCentroid);
  /*************************************************************************************/
  /*                             UPDATING BOX */
  /*************************************************************************************/
  //   cout << "Upd box " << endl;
  updateBoundingBox(angle, scale, m_boundingBoxRelative, m_updatedCentroid,
                    m_boundingBoxUpdated);
  /*************************************************************************************/
  /*                       SWAP MEMORY */
  /*************************************************************************************/
  next_gray.copyTo(prev_gray_);
}

void TrackerV2::detectNext(Mat next) {
  /*************************************************************************************/
  /*                       LOADING IMAGES */
  /*************************************************************************************/

  // GpuMat d_next, d_nextGray, d_keypoints, d_descriptors;
  // GpuTimer tm;
  // tm.Start();
  // d_next.upload(next);
  // cvtColor(d_next, d_nextGray, CV_BGR2GRAY);
  // tm.Stop();
  // cout << "Upload and grayscale in " << tm.Elapsed() << " ms " << endl;
  /*************************************************************************************/
  /*                       FEATURE EXTRACTION */
  /*************************************************************************************/
  vector<KeyPoint> keypoints;
  Mat gray, descriptors;
  cvtColor(next, gray, CV_BGR2GRAY);
  m_featuresDetector.detect(gray, keypoints);
  m_featuresDetector.compute(gray, keypoints, descriptors);

  /*************************************************************************************/
  /*                       FEATURE MATCHING */
  /*************************************************************************************/
  vector<vector<DMatch>> matches;
  m_customMatcher.match(descriptors, m_initDescriptors, 2, matches);
  /*************************************************************************************/
  /*                      SYNC WITH TRACKER */
  /*************************************************************************************/
  std::chrono::microseconds sleepTime(10);
  while (!m_trackerDone) {
    // sleep doing anything
    this_thread::sleep_for(sleepTime);
  }
  /*************************************************************************************/
  /*                       ADD FEATURES TO TRACKER */
  /*************************************************************************************/
  m_match_counter = 0;

  for (size_t i = 0; i < matches.size(); i++) {
    const int& queryId = matches[i][0].queryIdx;
    const int& trainId = matches[i][0].trainIdx;

    if (queryId < 0 && queryId >= keypoints.size()) continue;
    if (trainId < 0 && trainId >= m_initKeypoints.size()) continue;

    float confidence = 1 - (matches[i][0].distance / 512.0);
    float ratio = matches[i][0].distance / matches[i][1].distance;

    KpStatus& s = m_pointsStatus[trainId];

    if (confidence < 0.80f) continue;

    if (ratio > 0.8f) continue;

    if (s == KpStatus::BACKGROUND) continue;

    // if (s == Status::TRACK) continue;

    m_pointsStatus[trainId] = KpStatus::MATCH;
    // m_updatedPoints.push_back(keypoints[queryId].pt);
    // m_votes.push_back(Point2f(0, 0));
    // m_pointsIds.push_back(trainId);
    // m_relativeDistances.push_back(m_initKeypoints[trainId].pt -
    // m_initCentroid);
    // auto id = m_init_to_upd_ids[trainId];
    // cout << "TID " << trainId << " id " << id << endl;
    m_updatedPoints[trainId] = keypoints[queryId].pt;
    // m_votes[trainId] = Point2f(0, 0);
  }

  /*Mat debug_img;
  debug_img.create(Size(m_width*2, m_height), next.type());
  next.copyTo(debug_img(Rect(0, 0, m_width, m_height)));
  m_init_rgb_img.copyTo(debug_img(Rect(m_width, 0, m_width, m_height)));

  for(auto i = 0; i < m_pointsStatus.size(); i++)
  {
    if(m_pointsStatus[i] == Status::MATCH)
    {
      circle(debug_img, m_updatedPoints[i], 3, Scalar(0,255,0), 1);
      Point2f p = m_points[i];
      p.x += next.cols;
      circle(debug_img, p, 3, Scalar(0,255,0), 1);
      line(debug_img, m_updatedPoints[i], p, Scalar(0,255,0), 1);
    }
  }

  imshow("Matcher debug", debug_img);*/
  // waitKey(0);
}

bool TrackerV2::evaluatePose(const float& angle, const float& scale) {
  // discretize angle
  float angle_change = fato::roundDownToNearest(angle, 0.30);
  // discretize scale
  float scale_change = fato::roundDownToNearest(scale - 1, 0.30);

  /****************************************************************************/
  /**                adding to history                                        */
  /****************************************************************************/
  if (m_angle_history.size() > 15) m_angle_history.pop_front();
  m_angle_history.push_back(angle);

  if (m_scale_history.size() > 15) m_scale_history.pop_front();
  m_scale_history.push_back(scale);

  if (m_center_history.size() > 15) m_center_history.pop_front();
  m_center_history.push_back(m_updatedCentroid);
  /****************************************************************************/
  /**                Computing variation                                      */
  /****************************************************************************/

  auto it_scale = m_scale_history.begin();
  auto prev_val_scale = *it_scale;
  auto max_variation_scale = 0.0f;
  while (it_scale != m_scale_history.end()) {
    max_variation_scale =
        std::max(max_variation_scale, abs(prev_val_scale - *it_scale));
    prev_val_scale = *it_scale;
    ++it_scale;
  }

  auto it_angle = m_angle_history.begin();
  auto prev_val_angle = *it_angle;
  auto max_variation_angle = 0.0f;
  while (it_angle != m_angle_history.end()) {
    max_variation_angle =
        std::max(max_variation_angle, abs(prev_val_angle - *it_angle));
    prev_val_angle = *it_angle;
    ++it_angle;
  }

  auto it_mov = m_center_history.begin();
  auto prev_val_mov = *it_mov;
  auto max_variation_mov = 0.0f;
  while (it_mov != m_center_history.end()) {
    max_variation_mov = std::max(
        max_variation_mov, fato::getDistance(prev_val_mov, *it_mov));
    prev_val_mov = *it_mov;
    ++it_mov;
  }

  // check if the new pose in already stored in the tracker
  pair<float, float> p(angle_change, scale_change);

  if (max_variation_angle > 0.9 || max_variation_mov > 3.0 ||
      max_variation_scale > 0.5)
    return false;

  auto it_pose = m_learned_poses.find(p);

  bool is_new_pose = false;
  if (it_pose == m_learned_poses.end()) {
    m_learned_poses.insert(p);
    is_new_pose = true;
  }

  if (is_new_pose) {
    cout << fixed << setprecision(2) << "Angle change " << angle_change
         << " scale change " << scale_change << " angle delta "
         << max_variation_angle << " scale delta " << max_variation_scale
         << " mov_delta " << max_variation_mov << endl;

    // waitKey(0);
  }

  return is_new_pose;
}

void TrackerV2::getTrackedPoints(std::vector<cv::Point2f>& model_pts,
                                 std::vector<cv::Point2f>& current_pts,
                                 const std::vector<int>& ids,
                                 std::vector<cv::Point2f*>& model_valid_pts,
                                 std::vector<cv::Point2f*>& current_valid_pts) {
  for (auto i = 0; i < model_pts.size(); ++i) {
    if (isPointValid(ids[i])) {
      model_valid_pts.push_back(&model_pts[i]);
      current_valid_pts.push_back(&current_pts[i]);
    }
  }
}

void TrackerV2::getTrackedPoints(std::vector<cv::Point2f>& model_pts,
                                 std::vector<cv::Point2f>& current_pts,
                                 const std::vector<int>& ids,
                                 std::vector<cv::Point3f>& model_valid_pts,
                                 std::vector<cv::Point2f>& current_valid_pts) {
  for (auto i = 0; i < model_pts.size(); ++i) {
    if (isPointValid(ids[i])) {
      model_valid_pts.push_back(Point3f(model_pts[i].x, model_pts[i].y, 0));
      current_valid_pts.push_back(current_pts[i]);
    }
  }
}

void TrackerV2::projectPointsToModel(const Point2f& model_centroid,
                                     const Point2f& upd_centroid,
                                     const float angle, const float scale,
                                     const std::vector<Point2f>& pts,
                                     std::vector<Point2f>& proj_pts) {
  Mat2f rotMat(2, 2);
  rotMat.at<float>(0, 0) = cosf(angle);
  rotMat.at<float>(0, 1) = -sinf(angle);
  rotMat.at<float>(1, 0) = sinf(angle);
  rotMat.at<float>(1, 1) = cosf(angle);

  for (auto i = 0; i < pts.size(); i++) {
    Point2f rm = pts[i] - upd_centroid;
    if (scale != 0) {
      rm.x = rm.x / scale;
      rm.y = rm.y / scale;
    }
    rm = mult(rotMat, rm);

    proj_pts.push_back(model_centroid + rm);
  }
}

}  // end namespace pinot


text:
// JavaScript Document

/***
    Utility functions available across the site
***/
var CARDINAL = {
  size: function(){
    // return window size based on visibility as calculated by CSS
    var size = 'lg';

    // if we don't already have the size-detect div's, add them
    if ( $('.size-detect-xs').length == 0 ) {
      $('body')
        .append('
')
        .append('
')
        .append('
')
        .append('
');
    }

    $(['xs', 'sm', 'md', 'lg']).each(function(i, sz) {
      if ($('.size-detect-'+sz).css('display') != 'none') {
        size = sz;
      }
    });
    return size;
  },

  stickFooter: function(){
    // adjust css to make footer sticky
    var h = $('#footer').height() + 'px';
    $('#su-content').css('padding-bottom', h);
    $('#footer').css('margin-top', '-'+h);
  }
};

$(document).ready(function() {
  CARDINAL.stickFooter();

  // note resize events and trigger resizeEnd event when resizing stops
  $(window).resize(function() {
    if(this.resizeTO) clearTimeout(this.resizeTO);
    this.resizeTO = setTimeout(function() {
      $(this).trigger('resizeEnd');
    }, 200);
  });
  // Call responsive funtion when browser window resizing is complete
  $(window).bind('resizeEnd', function() {
    // show or hide the hamburger based on window size
    var size = CARDINAL.size(); // what size is our window (xs, sm, md or lg)
    if (size == 'md' || size == 'lg') { // if size is md or lg, unhide search and gateway blocks
      $('.navbar-collapse').collapse('hide');
      // $('.navbar-collapse').removeClass('in').addClass('collapse');
    }
    // re-stick the footer in case its height has changed
    CARDINAL.stickFooter();
  });

  $('.navbar-collapse').collapse({toggle: false}); // activate collapsibility without toggling state

  $('#skip > a').click(function(e){
    var href = $(this).attr('href').substr(1); // remove the #
    var target = $('a[name="' + href + '"]');
    target.focus();
  });

});


text:
package org.spongepowered.common.registry.type.extra;

import static com.google.common.base.Preconditions.checkNotNull;

import com.google.common.collect.ImmutableSet;
import org.spongepowered.api.block.BlockTypes;
import org.spongepowered.api.extra.fluid.FluidType;
import org.spongepowered.api.extra.fluid.FluidTypes;
import org.spongepowered.api.registry.util.RegisterCatalog;
import org.spongepowered.api.registry.util.RegistrationDependency;
import org.spongepowered.common.data.type.SpongeCommonFluidType;
import org.spongepowered.common.registry.SpongeAdditionalCatalogRegistryModule;
import org.spongepowered.common.registry.type.BlockTypeRegistryModule;

import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;

@RegistrationDependency(BlockTypeRegistryModule.class)
public final class FluidTypeRegistryModule implements SpongeAdditionalCatalogRegistryModule<FluidType> {

    public static FluidTypeRegistryModule getInstance() {
        return Holder.INSTANCE;
    }

    @RegisterCatalog(FluidTypes.class)
    private final Map<String, FluidType> fluidTypeMap = new HashMap<>();

    @Override
    public boolean allowsApiRegistration() {
        return false;
    }

    @Override
    public void registerAdditionalCatalog(FluidType extraCatalog) {

    }

    public void registerForge(FluidType fluidType) {
        checkNotNull(fluidType, "Someone is registering a null FluidType!");
        this.fluidTypeMap.put(fluidType.getId(), fluidType);
    }

    @Override
    public Optional<FluidType> getById(String id) {
        return Optional.ofNullable(this.fluidTypeMap.get(checkNotNull(id, "FluidType id cannot be null!").toLowerCase()));
    }

    @Override
    public Collection<FluidType> getAll() {
        return ImmutableSet.copyOf(this.fluidTypeMap.values());
    }

    @Override
    public void registerDefaults() {
        if (!this.fluidTypeMap.containsKey("water")) {
            this.fluidTypeMap.put("water", new SpongeCommonFluidType("water", BlockTypes.WATER));
        }
        if (!this.fluidTypeMap.containsKey("lava")) {
            this.fluidTypeMap.put("lava", new SpongeCommonFluidType("lava", BlockTypes.LAVA));
        }
    }

    FluidTypeRegistryModule() {
    }

    private static final class Holder {
        static final FluidTypeRegistryModule INSTANCE = new FluidTypeRegistryModule();
    }
}


text:
<?php

/**
 * @see Zym_Controller_Action_Abstract
 */
require_once 'Zym/Controller/Action/Abstract.php';

/**
 * @see Zym_Notification
 */
require_once 'Zym/Navigation.php';

/**
 * @author     Robin Skoglund
 * @copyright  Copyright (c) 2008 Zym. (http://www.zym-project.com/)
 * @license    http://www.zym-project.com/license    New BSD License
 */
class Demo_NavigationController extends Zym_Controller_Action_Abstract
{
    /**
     * Contexts
     *
     * @var array
     */
    public $contexts = array(
        'sitemap' => array('xml')
    );

    /**
     * init
     *
     * @return void
     */
    public function init()
    {
        // Setup navigation
        $this->_setupNavigation();
    }

    /**
     * Index
     *
     * @return void
     */
    public function indexAction()
    {
        $this->view->navSetup = highlight_file('App/Demo/Navigation.setup.php', true);
        $this->view->navSetup = str_replace('Zym_Navigation_Demo',
                                            'Zym_Navigation',
                                            $this->view->navSetup);
    }

    /**
     * Prints an XML sitemap
     *
     * Call sitemap/format/xml for xml sitemap, else it's html
     */
    public function sitemapAction()
    {
    }

    /**
     * Setup navigation
     *
     * @return void
     */
    protected function _setupNavigation()
    {
        require_once 'App/Demo/Navigation.setup.php';
    }
}


text:
package talecraft.decorator;

import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.util.math.BlockPos;
import net.minecraft.world.World;
import net.minecraft.world.gen.feature.WorldGenTrees;

public class TreeDecoration extends StaticDecoration {

	WorldGenTrees gen;

	public TreeDecoration() {
		super();
		gen = new WorldGenTrees(true);
	}

	@Override
	public int plant(World world, BlockPos[] positions, NBTTagCompound options) {
		for(BlockPos pos : positions){
			gen.generate(world, rand, pos);
		}
		return 0;
	}

	@Override
	public String name() {
		return "Tree";
	}

}


text:
#include "test.h"

#include <genomics/helpers/dna_helper.h>
#include <genomics/data/dna_codec.h>

#include <core/system/memory.h>
#include <core/system/debugger.h>

#include <stdlib.h>
#include <stdio.h>
#include <string.h>

/*
#define USE_TWO_BIT_ENCODING
*/

int main(int argc, char **argv)
{
    BEGIN_TESTS();

    struct biosal_dna_codec codec;
    void *encoded_sequence;
    int encoded_length;
    int sequence_length;
    /*
    char dna[] = "AAAATGAAAAAAATTAAAA";
    */
    char dna[] = "CACCCAGGGAGAGGGAGGACGCACCGAAAGAGAAA";
    char *sequence2;
    char *expected_sequence;

    biosal_dna_codec_init(&codec);

#ifdef USE_TWO_BIT_ENCODING
    biosal_dna_codec_enable_two_bit_encoding(&codec);
#endif

    sequence_length = strlen(dna);

    encoded_length = biosal_dna_codec_encoded_length(&codec, sequence_length);

    /*TEST_INT_IS_LOWER_THAN(encoded_length, sequence_length);*/
    TEST_INT_IS_GREATER_THAN(encoded_length, 0);
    TEST_INT_IS_GREATER_THAN(sequence_length, 0);

    encoded_sequence = core_memory_allocate(encoded_length, -1);

    biosal_dna_codec_encode(&codec, sequence_length, dna, encoded_sequence);

    sequence2 = core_memory_allocate(sequence_length + 1, -1);
    expected_sequence = core_memory_allocate(sequence_length + 1, -1);

    TEST_POINTER_NOT_EQUALS(sequence2, NULL);

    biosal_dna_codec_decode(&codec, sequence_length, encoded_sequence, sequence2);

    /*
    printf("%s and\n%s\n", dna, sequence2);
    */

    TEST_BOOLEAN_EQUALS(strcmp(dna, sequence2) == 0, 1);

    /* test the codec reverse-complement feature
     */
    strcpy(expected_sequence, sequence2);
    biosal_dna_helper_reverse_complement_in_place(expected_sequence);

    biosal_dna_codec_reverse_complement_in_place(&codec, sequence_length, encoded_sequence);

    biosal_dna_codec_decode(&codec, sequence_length, encoded_sequence, sequence2);

    if (strcmp(sequence2, expected_sequence) != 0) {
        printf("Origin   %s\n", dna);
        printf("Actual   %s\n", sequence2);
        printf("Expected %s\n", expected_sequence);
    }

#if 0
#endif
    TEST_BOOLEAN_EQUALS(strcmp(sequence2, expected_sequence) == 0, 1);

    biosal_dna_codec_set_nucleotide(&codec, encoded_sequence, 3, 'T');
    biosal_dna_codec_set_nucleotide(&codec, encoded_sequence, 2, 'T');
    biosal_dna_codec_set_nucleotide(&codec, encoded_sequence, 1, 'T');
    biosal_dna_codec_set_nucleotide(&codec, encoded_sequence, 4, 'T');
    biosal_dna_codec_set_nucleotide(&codec, encoded_sequence, 3, 'A');

#ifdef USE_TWO_BIT_ENCODING
    TEST_BOOLEAN_EQUALS(biosal_dna_codec_get_nucleotide(&codec, encoded_sequence, 3) == 'A', 1);
#endif

    core_memory_free(encoded_sequence, -1);
    core_memory_free(sequence2, -1);
    core_memory_free(expected_sequence, -1);

    biosal_dna_codec_destroy(&codec);

    {
        struct biosal_dna_codec codec;
        char sequence2[] = "CGCGATCTGTTGCTGGGCCTAACGTGGTA";
        char sequence[] = "TACCACGTTAGGCCCAGCAACAGATCGCG";
        int kmer_length;
        void *encoded_data;
        void *encoded_data2;
        int encoded_length;

        biosal_dna_codec_init(&codec);
        biosal_dna_codec_enable_two_bit_encoding(&codec);

        kmer_length = strlen(sequence);

        encoded_length = biosal_dna_codec_encoded_length(&codec, kmer_length);

        encoded_data = core_memory_allocate(encoded_length, -1);
        encoded_data2 = core_memory_allocate(encoded_length, -1);

        memset(encoded_data, 0xff, encoded_length);

        biosal_dna_codec_encode(&codec, kmer_length, sequence, encoded_data);
        biosal_dna_codec_encode(&codec, kmer_length, sequence2, encoded_data2);

#if 0
        printf("Seq= %s\n", sequence);
        biosal_debugger_examine(encoded_data, encoded_length);
#endif

#if 0
        printf("after rev comp\n");
#endif
        biosal_dna_codec_reverse_complement_in_place(&codec, kmer_length, encoded_data);

#if 0
        biosal_debugger_examine(encoded_data, encoded_length);

        printf("Seq2 %s\n", sequence2);
        biosal_debugger_examine(encoded_data2, encoded_length);
#endif

        TEST_INT_EQUALS(memcmp(encoded_data, encoded_data2, encoded_length), 0);

        core_memory_free(encoded_data, -1);
        core_memory_free(encoded_data2, -1);

        biosal_dna_codec_destroy(&codec);

    }

    END_TESTS();

    return 0;
}


text:
package net.imagej.updater.util;

import java.awt.GraphicsEnvironment;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.security.DigestInputStream;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Collections;
import java.util.Comparator;
import java.util.Enumeration;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.scijava.log.LogService;
import org.scijava.log.StderrLogService;

/**
 * Utility methods for use with the {@link net.imagej.updater} package and
 * subpackages.
 *

 * Class functionality:
 *

 *
Calculate timestamps of files

 *
Calculate the checksums of files

 *
Get the absolute path (prefix()) of the ImageJ directory

 *
Copy a file over to a particular location

 *
Get details of the Operating System ImageJ application is on

 *

 *
 * @author Johannes Schindelin
 */
public class UpdaterUtil {

	public static String MAIN_URL = "http://update.imagej.net/";
	public static String UPDATE_DIRECTORY = "/home/imagej/update-site";
	public static String SSH_HOST = "update.imagej.net";

	public static final String XML_COMPRESSED = "db.xml.gz";

	// Prefix for the preference key names
	public static final String PREFS_USER = "imagej.updater.login";

	public final static String macPrefix = "Contents/MacOS/";

	public final String platform;
	public final String[] platforms, launchers;
	protected final Set<String> updateablePlatforms;

	protected final DropboxURLMapper dropboxURLMapper;

	public UpdaterUtil(final File imagejRoot) {
		platform = getPlatform();

		platforms =
			new String[] { "linux32", "linux64", "macosx", "tiger", "win32", "win64" };
		final int macIndex = 2;
		Arrays.sort(platforms);

		launchers = platforms.clone();
		for (int i = 0; i < launchers.length; i++)
			launchers[i] =
				(i == macIndex || i == macIndex + 1 ? macPrefix : "") + "ImageJ-" +
					platforms[i] + (platforms[i].startsWith("win") ? ".exe" : "");
		Arrays.sort(launchers);

		updateablePlatforms = new HashSet<String>();
		updateablePlatforms.add(platform);
		if (imagejRoot != null && new File(imagejRoot, launchers[macIndex]).exists()) {
			updateablePlatforms.add("macosx");
		}
		final String[] files = imagejRoot == null ? null : imagejRoot.list();
		for (final String name : files == null ? new String[0] : files) {
			if (name.startsWith("ImageJ-")) {
				updateablePlatforms.add(platformForLauncher(name));
			}
		}
		dropboxURLMapper = new DropboxURLMapper(this);
	}

	public static String platformForLauncher(final String fileName) {
		final int dash = fileName.lastIndexOf('-');
		if (dash < 0) return null;
		String name = fileName.substring(dash + 1);
		if (name.endsWith(".exe")) name = name.substring(0, name.length() - 4);
		if (name.equals("tiger") || name.equals("panther")) name = "macosx";
		else if (name.equals("linux")) name = "linux32";
		return name;
	}

	public static String stripSuffix(final String string, final String suffix) {
		if (!string.endsWith(suffix)) return string;
		return string.substring(0, string.length() - suffix.length());
	}

	public static String stripPrefix(final String string, final String prefix) {
		if (!string.startsWith(prefix)) return string;
		return string.substring(prefix.length());
	}

	public static String getPlatform() {
		final boolean is64bit =
			System.getProperty("os.arch", "").indexOf("64") >= 0;
		final String osName = System.getProperty("os.name", "<unknown>");
		if (osName.equals("Linux")) return "linux" + (is64bit ? "64" : "32");
		if (osName.equals("Mac OS X")) return "macosx";
		if (osName.startsWith("Windows")) return "win" + (is64bit ? "64" : "32");
		// System.err.println("Unknown platform: " + osName);
		return osName.toLowerCase();
	}

	// get digest of the file as according to fullPath
	public static String getDigest(final String path, final File file)
		throws NoSuchAlgorithmException, FileNotFoundException, IOException,
		UnsupportedEncodingException
	{
		if (path.endsWith(".jar")) return getJarDigest(file);
		final MessageDigest digest = getDigest();
		digest.update(path.getBytes("ASCII"));
		if (file != null) updateDigest(new FileInputStream(file), digest);
		return toHex(digest.digest());
	}

	public static MessageDigest getDigest() throws NoSuchAlgorithmException {
		return MessageDigest.getInstance("SHA-1");
	}

	/**
	 * Handle previous methods to calculate the checksums gracefully Earlier, we
	 * simply checksummed all the contents in .jar files. But that leads to files
	 * marked as modified all the time when Maven rebuilds them. So we changed the
	 * way they are checksummed. Let's handle old checksums, too, though, by
	 * simply adding them to the previous versions.
	 *
	 * @param path the path relative to the ImageJ directory
	 * @param file the file
	 * @throws IOException
	 * @throws FileNotFoundException
	 */
	public static List<String> getObsoleteDigests(final String path,
		final File file) throws FileNotFoundException, IOException
	{
		if (!path.endsWith(".jar")) return null;
		final List<String> result = new ArrayList<String>();
		result.add(getJarDigest(file, true, true, false));
		result.add(getJarDigest(file, true, false, false));
		result.add(getJarDigest(file, false, false, false));
		return result;
	}

	public static void updateDigest(final InputStream input,
		final MessageDigest digest) throws IOException
	{
		final byte[] buffer = new byte[65536];
		final DigestInputStream digestStream = new DigestInputStream(input, digest);
		while (digestStream.read(buffer) >= 0); /* do nothing */
		digestStream.close();
	}

	public final static char[] hex = { '0', '1', '2', '3', '4', '5', '6', '7',
		'8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };

	public static String toHex(final byte[] bytes) {
		final char[] buffer = new char[bytes.length * 2];
		for (int i = 0; i < bytes.length; i++) {
			buffer[i * 2] = hex[(bytes[i] & 0xf0) >> 4];
			buffer[i * 2 + 1] = hex[bytes[i] & 0xf];
		}
		return new String(buffer);
	}

	public static String getJarDigest(final File file) throws FileNotFoundException, IOException {
		return getJarDigest(file, true, true, true);
	}

	public static String getJarDigest(final File file, boolean treatPropertiesSpecially, boolean treatManifestsSpecially) throws FileNotFoundException, IOException {
		return getJarDigest(file, treatPropertiesSpecially, treatManifestsSpecially, false);
	}

	public static String getJarDigest(final File file, boolean treatPropertiesSpecially, boolean treatManifestsSpecially, boolean keepOnlyMainClassInManifest) throws FileNotFoundException, IOException {
		MessageDigest digest = null;
		try {
			digest = getDigest();
		}
		catch (final NoSuchAlgorithmException e) {
			throw new RuntimeException(e);
		}

		if (file != null) {
			final JarFile jar = new JarFile(file);
			final List<JarEntry> list = Collections.list(jar.entries());
			Collections.sort(list, new JarEntryComparator());

			for (final JarEntry entry : list) {
				digest.update(entry.getName().getBytes("ASCII"));
				InputStream inputStream = jar.getInputStream(entry);
				// .properties files have a date in a comment; let's ignore this for the checksum
				// For backwards-compatibility, activate the .properties mangling only from June 15th, 2012
				if (treatPropertiesSpecially && entry.getName().endsWith(".properties")) {
					inputStream = new SkipHashedLines(inputStream);
				}
				// same for manifests, but with July 6th, 2012
				if (treatManifestsSpecially && entry.getName().equals("META-INF/MANIFEST.MF")) {
					inputStream = new FilterManifest(inputStream, keepOnlyMainClassInManifest);
				}
				updateDigest(inputStream, digest);
			}
			jar.close();
		}
		return toHex(digest.digest());
	}

	private static class JarEntryComparator implements Comparator<JarEntry> {

		@Override
		public int compare(final JarEntry entry1, final JarEntry entry2) {
			final String name1 = entry1.getName();
			final String name2 = entry2.getName();
			return name1.compareTo(name2);
		}

	}

	public static long getTimestamp(final File file) {
		final long modified = file.lastModified();
		return Long.parseLong(timestamp(modified));
	}

	public static String timestamp(final long millis) {
		final Calendar date = Calendar.getInstance();
		date.setTimeInMillis(millis);
		return timestamp(date);
	}

	public static String timestamp(final Calendar date) {
		final DecimalFormat format = new DecimalFormat("00");
		final int month = date.get(Calendar.MONTH) + 1;
		final int day = date.get(Calendar.DAY_OF_MONTH);
		final int hour = date.get(Calendar.HOUR_OF_DAY);
		final int minute = date.get(Calendar.MINUTE);
		final int second = date.get(Calendar.SECOND);
		return "" + date.get(Calendar.YEAR) + format.format(month) +
			format.format(day) + format.format(hour) + format.format(minute) +
			format.format(second);
	}

	public static long timestamp2millis(final long timestamp) {
		return timestamp2millis("" + timestamp);
	}

	public static long timestamp2millis(final String timestamp) {
		final Calendar calendar = Calendar.getInstance();
		calendar.set(Integer.parseInt(timestamp.substring(0, 4)), Integer
			.parseInt(timestamp.substring(4, 6)) - 1, Integer.parseInt(timestamp
			.substring(6, 8)), Integer.parseInt(timestamp.substring(8, 10)), Integer
			.parseInt(timestamp.substring(10, 12)), Integer.parseInt(timestamp
			.substring(12, 14)));
		return calendar.getTimeInMillis();
	}

	private static final String[] months = { "Zero", "Jan", "Feb", "Mar", "Apr",
		"May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" };

	public static String prettyPrintTimestamp(final long timestamp) {
		final String t = "" + timestamp + "00000000000000";
		return t.substring(6, 8) + " " +
			months[Integer.parseInt(t.substring(4, 6))] + " " + t.substring(0, 4) + " " +
			t.substring(8, 10) + ":" + t.substring(10, 12) + ":" + t.substring(12,14);
	}

	public boolean isLauncher(final String filename) {
		return Arrays.binarySearch(launchers, filename) >= 0;
	}

	public boolean isUpdateablePlatform(final String platform) {
		return updateablePlatforms.contains(platform);
	}

	public void setUpdateablePlatforms(final String... platforms) {
		updateablePlatforms.clear();
		for (String platform : platforms) {
			if (platform == null) continue;
			platform = platform.trim();
			if ("all".equals(platform)) {
				updateablePlatforms.add(this.platform);
				updateablePlatforms.addAll(Arrays.asList(this.platforms));
			} else {
				updateablePlatforms.add(platform);
			}
		}
	}

	public boolean isMacOSX() {
		return platform.equals("macosx");
	}

	public static <T> String join(final String delimiter, final Iterable<T> list)
	{
		final StringBuilder builder = new StringBuilder();
		for (final T object : list)
			builder.append((builder.length() > 0 ? delimiter : "") + object.toString());
		return builder.toString();
	}

	public static void useSystemProxies() {
		/*
		 * Avoid those pesky
		 * "GConf-WARNING **: Client failed to connect to the D-BUS daemon"
		 * messages in headless mode (e.g. Jenkins).
		 */
		final String osName = System.getProperty("os.name", "<unknown>");
		if (osName.equals("Linux") && GraphicsEnvironment.isHeadless()) return;

		System.setProperty("java.net.useSystemProxies", "true");
	}

	@Deprecated
	public static long getLastModified(final String url) {
		try {
			return new UpdaterUtil(null).getLastModified(new URL(url));
		} catch (MalformedURLException e) {
			throw new RuntimeException(e);
		}
	}

	public long getLastModified(final URL url) {
		try {
			final URLConnection connection = openConnection(url);
			if (connection instanceof HttpURLConnection) ((HttpURLConnection) connection)
				.setRequestMethod("HEAD");
			connection.setUseCaches(false);
			final long lastModified = connection.getLastModified();
			connection.getInputStream().close();
			return lastModified;
		}
		catch (final IOException e) {
			if (e.getMessage().startsWith("Server returned HTTP response code: 407")) return -111381;
			if (e.getMessage().startsWith("Server returned HTTP response code: 405")) try {
				final URLConnection connection = openConnection(url);
				connection.setUseCaches(false);
				final long lastModified = connection.getLastModified();
				connection.getInputStream().close();
				return lastModified;
			} catch (IOException e2) {
				e.printStackTrace();
				e2.printStackTrace();
			}
			// assume no network; so let's pretend everything's ok.
			return -1;
		}
	}

	/**
	 * Open a stream to a {@link URL}.
	 *
	 * ... possibly mapping Dropbox URLs.
	 *
	 * @param url the URL to open
	 */
	public InputStream openStream(final URL url) throws IOException {
		return openConnection(url).getInputStream();
	}

	/**
	 * Open a connection to a {@link URL}.
	 *
	 * ... possibly mapping Dropbox URLs.
	 *
	 * @param url the URL to open
	 */
	public URLConnection openConnection(final URL url) throws IOException {
		final URLConnection connection = dropboxURLMapper.get(url).openConnection();
		if (connection instanceof HttpURLConnection) {
			HttpURLConnection http = (HttpURLConnection)connection;
			final String javaVmVersion = System.getProperty("java.runtime.version");
			final String javaVersion = javaVmVersion != null ?
					javaVmVersion : System.getProperty("java.version");
			final String osVersion = System.getProperty("os.version");
			final String os = "" + System.getProperty("os.name") + "-"
					+ (osVersion != null ? osVersion + "-" : "")
					+ System.getProperty("os.arch");
			http.setRequestProperty("User-Agent",
					"curl/7.22.0 compatible ImageJ updater/2.0.0-SNAPSHOT (Java "
					+ javaVersion + "/" + os + ")");
		}
		return connection;
	}

	// Get entire byte data
	public static byte[] readStreamAsBytes(final InputStream input)
		throws IOException
	{
		byte[] buffer = new byte[1024];
		int offset = 0, len = 0;
		for (;;) {
			if (offset == buffer.length) buffer = realloc(buffer, 2 * buffer.length);
			len = input.read(buffer, offset, buffer.length - offset);
			if (len < 0) return realloc(buffer, offset);
			offset += len;
		}
	}

	private static byte[] realloc(final byte[] buffer, final int newLength) {
		if (newLength == buffer.length) return buffer;
		final byte[] newBuffer = new byte[newLength];
		System.arraycopy(buffer, 0, newBuffer, 0, Math
			.min(newLength, buffer.length));
		return newBuffer;
	}

	protected static String readFile(final File file) throws IOException {
		final StringBuilder builder = new StringBuilder();
		final BufferedReader reader = new BufferedReader(new FileReader(file));
		for (;;) {
			final String line = reader.readLine();
			if (line == null) break;
			builder.append(line).append('\n');
		}
		reader.close();

		return builder.toString();
	}

	// This method writes to a .bup file and then renames; this might not work on
	// Windows
	protected static void writeFile(final File file, final String contents)
		throws IOException
	{
		final File result =
			new File(file.getAbsoluteFile().getParentFile(), file.getName() + ".new");
		final FileOutputStream out = new FileOutputStream(result);
		out.write(contents.getBytes());
		out.close();
		result.renameTo(file);
	}

	// This method protects us from Java5's absence of File.canExecute
	public static boolean canExecute(File file) {
		try {
			return file.canExecute();
		} catch (Throwable t) {
			// ignore
			return false;
		}
	}

	private static Set<File> protectedFiles;
	private final static Pattern majorVersionPattern = Pattern.compile("([0-9]+).*");

	/**
	 * Determines whether the ImageJ root directory is in an area protected by the OS.
	 *
	 *
On Windows Vista and later, C:\Program Files is a protected location.
	 *
	 * @param ijRoot the root directory to test
	 * @return whether the directory is protected by the OS
	 */
	public static boolean isProtectedLocation(final File ijRoot) {
		if (getPlatform().startsWith("win")) {
			final String osVersion = System.getProperty("os.version");
			if (osVersion == null) return false;
			final Matcher matcher = majorVersionPattern.matcher(osVersion);
			/*
			 * Vista is 6.0, Server 2008, too, to keep it confusing, Server 2008
			 * R2 is 6.1, to keep it more confusing, Windows 7 is 6.1 (just to
			 * keep it even more confusing). See:
			 * http://msdn.microsoft.com/en-us/library/windows/desktop/ms724832%28v=vs.85%29.aspx
			 */
			if (!matcher.matches() || Integer.parseInt(matcher.group(1)) < 6) return false;
			try {
				if (protectedFiles == null) {
					protectedFiles = new HashSet<File>();
					for (final String key : new String[] {
									"PROGRAMFILES", "PROGRAMFILES(X86)", "SystemRoot", "ALLUSERSPROFILE"
					}) {
						final String path = System.getenv(key);
						if (path != null) protectedFiles.add(new File(path).getCanonicalFile());
					}
				}
				for (File dir = ijRoot.getCanonicalFile(); dir != null; dir = dir.getParentFile()) {
					if (protectedFiles.contains(dir)) {
						protectedFiles.add(ijRoot);
						return true;
					}
				}
			} catch (final IOException e) {
				e.printStackTrace(); // but ignore otherwise
			}
		}
		return false;
	}

	public static boolean patchInfoPList(final File infoPList, final String executable)
		throws IOException
	{
		if (!infoPList.exists()) return false;
		String contents = readFile(infoPList);
		final Pattern pattern =
			Pattern.compile(".*<key>CFBundleExecutable</key>[^<]*<string>([^<]*).*",
				Pattern.DOTALL | Pattern.MULTILINE);
		final Matcher matcher = pattern.matcher(contents);
		if (!matcher.matches()) return false;
		contents =
			contents.substring(0, matcher.start(1)) + executable +
				contents.substring(matcher.end(1));
		writeFile(infoPList, contents);
		return true;
	}

	public static<T> Iterable<T> iterate(final Enumeration<T> en) {
        final Iterator<T> iterator = new Iterator<T>() {
            @Override
			public boolean hasNext() {
                    return en.hasMoreElements();
            }

            @Override
			public T next() {
                    return en.nextElement();
            }

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

	    return new Iterable<T>() {
            @Override
			public Iterator<T> iterator() {
                    return iterator;
            }
	    };
	}

	/**
	 * Get a log service.
	 *
	 * This works around version skews (where the
	 * {@link org.scijava.log.StderrLogService} cannot be found).
	 *
	 * @return the log service
	 */
	public static LogService getLogService() {
		return new StderrLogService();
	}

	/**
	 * CamelCases a {@link String}.
	 */
	public static String toCamelCase(final String string) {
		if (string == null || string.length() == 0) return string;
		final StringBuilder builder = new StringBuilder();
		boolean upCase = true;
		for (char ch : string.toCharArray()) {
			if (Character.isLetterOrDigit(ch)) {
				builder.append(upCase ? Character.toUpperCase(ch) : Character.toLowerCase(ch));
				upCase = false;
			} else {
				upCase = true;
			}
		}
		return builder.toString();
	}

}


text:
/**
 * We encode using encodeURIComponent but we want to
 * preserver certain characters which are commonly used
 * (sub delimiters and ':')
 *
 * https://www.ietf.org/rfc/rfc3986.txt
 *
 * reserved    = gen-delims / sub-delims
 *
 * gen-delims  = ":" / "/" / "?" / "#" / "[" / "]" / "@"
 *
 * sub-delims  = "!" / "$" / "&" / "'" / "(" / ")"
              / "*" / "+" / "," / ";" / "="
 */

const excludeSubDelimiters = /[^!$'()*+,;|:]/g

export type URLParamsEncodingType =
  | 'default'
  | 'uri'
  | 'uriComponent'
  | 'none'
  | 'legacy'

export const encodeURIComponentExcludingSubDelims = (segment: string): string =>
  segment.replace(excludeSubDelimiters, match => encodeURIComponent(match))

const encodingMethods: Record<
  URLParamsEncodingType,
  (param: string) => string
> = {
  default: encodeURIComponentExcludingSubDelims,
  uri: encodeURI,
  uriComponent: encodeURIComponent,
  none: val => val,
  legacy: encodeURI
}

const decodingMethods: Record<
  URLParamsEncodingType,
  (param: string) => string
> = {
  default: decodeURIComponent,
  uri: decodeURI,
  uriComponent: decodeURIComponent,
  none: val => val,
  legacy: decodeURIComponent
}

export const encodeParam = (
  param: string | number | boolean,
  encoding: URLParamsEncodingType,
  isSpatParam: boolean
): string => {
  const encoder =
    encodingMethods[encoding] || encodeURIComponentExcludingSubDelims

  if (isSpatParam) {
    return String(param)
      .split('/')
      .map(encoder)
      .join('/')
  }

  return encoder(String(param))
}

export const decodeParam = (
  param: string,
  encoding: URLParamsEncodingType
): string => (decodingMethods[encoding] || decodeURIComponent)(param)


text:
package common

import (
	"context"
	"os"
	"strings"
	"testing"
	"time"

	clientv3 "go.etcd.io/etcd/client/v3"
	"go.etcd.io/etcd/tests/v3/framework/config"
	"go.etcd.io/etcd/tests/v3/framework/testutils"
)

func TestAlarm(t *testing.T) {
	testRunner.BeforeTest(t)
	ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
	defer cancel()
	clus := testRunner.NewCluster(ctx, t, config.ClusterConfig{ClusterSize: 1, QuotaBackendBytes: int64(13 * os.Getpagesize())})
	defer clus.Close()
	testutils.ExecuteUntil(ctx, t, func() {
		// test small put still works
		smallbuf := strings.Repeat("a", 64)
		if err := clus.Client().Put("1st_test", smallbuf, config.PutOptions{}); err != nil {
			t.Fatalf("alarmTest: put kv error (%v)", err)
		}

		// write some chunks to fill up the database
		buf := strings.Repeat("b", os.Getpagesize())
		for {
			if err := clus.Client().Put("2nd_test", buf, config.PutOptions{}); err != nil {
				if !strings.Contains(err.Error(), "etcdserver: mvcc: database space exceeded") {
					t.Fatal(err)
				}
				break
			}
		}

		// quota alarm should now be on
		alarmResp, err := clus.Client().AlarmList()
		if err != nil {
			t.Fatalf("alarmTest: Alarm error (%v)", err)
		}

		// check that Put is rejected when alarm is on
		if err := clus.Client().Put("3rd_test", smallbuf, config.PutOptions{}); err != nil {
			if !strings.Contains(err.Error(), "etcdserver: mvcc: database space exceeded") {
				t.Fatal(err)
			}
		}

		// get latest revision to compact
		sresp, err := clus.Client().Status()
		if err != nil {
			t.Fatalf("get endpoint status error: %v", err)
		}
		var rvs int64
		for _, resp := range sresp {
			if resp != nil && resp.Header != nil {
				rvs = resp.Header.Revision
				break
			}
		}

		// make some space
		_, err = clus.Client().Compact(rvs, config.CompactOption{Physical: true, Timeout: 10 * time.Second})
		if err != nil {
			t.Fatalf("alarmTest: Compact error (%v)", err)
		}

		if err = clus.Client().Defragment(config.DefragOption{Timeout: 10 * time.Second}); err != nil {
			t.Fatalf("alarmTest: defrag error (%v)", err)
		}

		// turn off alarm
		for _, alarm := range alarmResp.Alarms {
			alarmMember := &clientv3.AlarmMember{
				MemberID: alarm.MemberID,
				Alarm:    alarm.Alarm,
			}
			_, err = clus.Client().AlarmDisarm(alarmMember)
			if err != nil {
				t.Fatalf("alarmTest: Alarm error (%v)", err)
			}
		}

		// put one more key below quota
		if err := clus.Client().Put("4th_test", smallbuf, config.PutOptions{}); err != nil {
			t.Fatal(err)
		}
	})
}


text:
namespace gfx {

class GFX_EXPORT SurfaceFactoryWayland : public gfx::SurfaceFactoryOzone {
 public:
  SurfaceFactoryWayland();
  virtual ~SurfaceFactoryWayland();

  virtual SurfaceFactoryOzone::HardwareState InitializeHardware() OVERRIDE;
  virtual intptr_t GetNativeDisplay() OVERRIDE;
  virtual void ShutdownHardware() OVERRIDE;
  // GetAcceleratedWidget return's a opaque handle associated with a accelerated
  // widget.
  virtual gfx::AcceleratedWidget GetAcceleratedWidget() OVERRIDE;
  // RealizeAcceleratedWidget takes opaque handle as parameter and returns
  // eglwindow assosicated with it.
  virtual gfx::AcceleratedWidget RealizeAcceleratedWidget(
    gfx::AcceleratedWidget w) OVERRIDE;
  virtual bool LoadEGLGLES2Bindings(
    gfx::SurfaceFactoryOzone::AddGLLibraryCallback add_gl_library,
    gfx::SurfaceFactoryOzone::SetGLGetProcAddressProcCallback
        proc_address) OVERRIDE;
  // Returns true if resizing of eglwindow associated with opaque handle was
  // successful else returns false.
  virtual bool AttemptToResizeAcceleratedWidget(
      gfx::AcceleratedWidget w, const gfx::Rect& bounds) OVERRIDE;
  virtual scoped_ptr<gfx::VSyncProvider> CreateVSyncProvider(
      gfx::AcceleratedWidget w) OVERRIDE;
  virtual bool SchedulePageFlip(gfx::AcceleratedWidget w) OVERRIDE;
  virtual const int32* GetEGLSurfaceProperties(
      const int32* desired_list) OVERRIDE;

 private:
  unsigned last_realized_widget_handle_;

  DISALLOW_COPY_AND_ASSIGN(SurfaceFactoryWayland);
};

}  // namespace gfx

#endif  // OZONE_UI_GFX_SURFACE_FACTORY_WAYLAND_H_


text:
[Try it live!](http://retentionizer.herokuapp.com/)
_____

Using the techniques in [How to Project Customer Retention](https://marketing.wharton.upenn.edu/files/?whdmsaction=public:main.file&fileID=327) by Fader & Hardie (2006), and an implementation of those techniques by [JD Maturen](https://github.com/jdmaturen), Retentionizer will fit a shifted-beta-geometric distribution to the data, show the projected retention rates for each cohort, show the imputed beta distribution for each cohort, and calculate the LTV of a given customer in that cohort.

Basically, it turns a sample of cohort survival rates:

| t  | past 30 |
|----|---------|
| 0  | 1.0     |
| 1  | .81     |
| 2  | .80     |
| 3  | .76     |
| 4  | .75     |
| 5  | .72     |
| 6  | .70     |
| 7  | .67     |
| 8  | .66     |
| 9  | .65     |
| 10 | .64     |

Into this:

![sample-output](https://raw.githubusercontent.com/chrisclark/retentionizer/master/static/img/sample-output.png)

Retentionizer is built by [David Chudzicki](https://www.github.com/dchudz) and [Chris Clark](https://blog.untrod.com/).


text:
author: slowe
comments: true
date: 2014-11-03 09:00:00+00:00
layout: post
slug: learning-nsx-part-18-routing-without-network-address-translation
title: 'Learning NSX, Part 18: Routing Without Network Address Translation'
wordpress_id: 3556
categories: Tutorial
tags:
- Networking
- Neutron
- NSX
- OpenStack
- Virtualization
- VMware
---

This is part 18 of the Learning NSX blog series, in which I talk about using layer 3 (L3) routing with VMware NSX but without network address translation (NAT). This post describes a configuration that offers yet another connectivity option for OpenStack cloud administrators and operators.

In [part 6][p6], I showed you how to add a gateway appliance to your NSX installation. [Part 9][p9] leveraged the gateway appliances to create a L3 gateway service, which---as I explained in [part 15][p15]---provides the functionality for logical routers in OpenStack. (Logical routing was covered in [part 14][p14].) [Part 16][p16] expanded the routing configuration to support multiple external networks. This post expands the options again by showing you how to do logical routing without using network address translation (NAT). Of course, it would probably be helpful to read the entire series; links to all posts can be found on the [Learning NVP/NSX page][all].

As I mentioned, so far you've seen three different external connectivity options:

* Routing (layer 3 connectivity) to a single external network

* Routing (layer 3 connectivity) to multiple external networks using VLANs

* Bridging (layer 2 connectivity) between a logical network and a physical broadcast domain

Both of the routed connectivity options you've seen so far have involved the use of NAT (specifically, source NAT, or SNAT) on the logical router in order to establish outbound connectivity. You've had to use floating IP addresses to establish inbound connectivity to instances. However, NSX is absolutely capable of supporting routed connectivity options that do not involve NAT, allowing cloud administrators and operators to use fully routable IP address spaces inside NSX logical networks.

Assuming that you already have logical routing working, the steps to establish a no-NAT routing configuration are pretty straightforward. Note that because the IP address space used in the logical network must interoperate with the IP addressing scheme used on the public network, this configuration is typically set up by a cloud administrator and not by a tenant.

To set up a no-NAT configuration, follow these steps (all commands are assumed to be run using admin credentials):

1. Store the tenant's ID in an environment variable, as you'll be needing it quite a bit over the next few minutes. You can do that using `keystone tenant-list` and `awk`. For example, if the tenant's name was blue, then you could use `keystone tenant-list | awk '/\ blue\ / {print $2}'` to find the tenant ID and assign it to an environment variable. The following commands will assume you've stored the tenant's ID as `$TID`.

2. Create a logical router and assign it to the tenant. The command to do this is `neutron router-create --tenant-id $TID <Name of router>`. It _might_ be possible to re-use an existing logical router, but you're really much better off just creating another logical router for this purpose.

3. Create a logical network on behalf of the tenant, using `neutron net-create --tenant-id $TID <Name of network>`.

4. Create a subnet and associate it with the new logical network you just created. You can do that with this command: `neutron subnet-create --tenant-id $TID --name <Subnet name> --gateway <IP address for logical router> <Name of network> <CIDR>`.

5. Attach the logical router to the logical network and associated subnet with `neutron router-interface-add <Router ID> <Subnet name>`. The IP address of this interface will be the IP address provided to the `--gateway` parameter when you created the subnet.

6. Attach the logical router to the external network that will serve as its uplink. _This is where you'll tell Neutron and NSX that NAT should not be active._ The command to use is `neutron router-gateway-set --disable-snat <Router ID> <External network ID>`.

You're almost done---you now have a logical network using IP addresses from a subnet that is routable within your larger network without any use of NAT. However, you still need to let the rest of the network know about this new subnet, and as NSX in multi-hypervisor environments doesn't yet support dynamic routing via protocols like OSPF and BGP, then you'll need to do static routing.

To do static routing, you'll need the IP address assigned to the router during step 6 above. `neutron port-list` will show you the list of ports in Neutron; depending on the size of your installation, this list might be quite sizable. This command might help:

    neutron port-list -c id -c fixed_ips -c device_owner | awk '/network:router_gateway/'

This will show you only the ports that are acting as router gateway ports. In large environments, even this list may not be short enough to know for sure which IP address is assigned to the router. For now, though, let's assume that you're able to determine the IP address assigned to the logical router on the external network.

Once you have this address, then it's just a simple matter of adding that route to other network devices. Often, this is some form of `ip route add`; the specific commands and syntax will depend on the network device and are outside the scope of this article. Once you get the IP routing table(s) updated on the other network devices, then you're ready to roll!

I hope you find this article (and this series) helpful. As always, if you have any questions, corrections, clarifications, or concerns, I invite you to speak up in the comments below. All courteous comments are welcome!

[all]: {{ site.url }}/learning-nvp-nsx/
[p6]: {% post_url 2013-10-28-learning-nvp-part-6-adding-an-nvp-gateway %}
[p9]: {% post_url 2014-02-26-learning-nsx-part-9-adding-a-gateway-service %}
[p14]: {% post_url 2014-06-20-learning-nsx-part-14-using-logical-routing %}
[p15]: {% post_url 2014-07-16-learning-nsx-part-15-nsx-gateways-gateway-services-and-logical-routers %}
[p16]: {% post_url 2014-10-13-learning-nsx-part-16-routing-to-multiple-external-vlans %}