text:
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <dimen name="list_text_padding">6dp</dimen>
    <dimen name="list_text_size">14dp</dimen>
    <dimen name="list_time_text_size">14dp</dimen>
    <dimen name="date_text_size">10pt</dimen>
    <dimen name="plusminusminwidth">40dp</dimen>
    <dimen name="nationality_width">30dp</dimen>
    <dimen name="time_box_width">60dp</dimen>
    <dimen name="list_time_margin_left">4dp</dimen>
    <dimen name="list_time_margin_right">4dp</dimen>
    <dimen name="list_edit_margin_left">4dp</dimen>
    <dimen name="list_checkbox_margin_left">4dp</dimen>
    <dimen name="list_checkbox_margin_right">30dp</dimen>
    <dimen name="newrider_margin_top">10dp</dimen>
</resources>


text:
-
# Docs
"""
aaa bbb ccc
:param ddd   eee fff ggg
:remarks hhhhhhh iiiiiii jjjjjjj kkkkkkk lllllll mmmmmmm nnnnnnn
:todo ooooooooooooooooooooooooooooooooooooooooooooooooo
"""
-

redpajama_set_name: RedPajamaGithub


text:
<?php

class Comments extends Pas_Db_Table_Abstract {

    protected $_name = 'comments';

    protected $_primary = 'id';

    /** Get comments by id
     * @param int $id
     * @return array
     */
    public function getFindComments($id){
	$comments = $this->getAdapter();
	$select = $comments->select()
                ->from($this->_name, array(
                    $this->_primary, 'df' => 'DATE_FORMAT(comments.created,"%T on the %D %M %Y")',
                    'comment_author', 'comment_author_url', 'comment_content',
                    'comment_author_email'
                    ))
                ->joinLeft('finds','finds.id = comments.contentID',array())
                ->where('finds.id = ?', (int)$id)
                ->where('comments.comment_type  = ?','findComment')
                ->where('comments.comment_approved = ?','approved')
                ->order('comments.created ASC');
	return $comments->fetchAll($select);
    }

    /** Get comments by id on news articles
     * @access public
     * @param int $id
     * @todo remove date formating and put into view?
     * @return array
     */
    public function getCommentsNews($id) {
        if (!$data = $this->_cache->load('newscomments' . $id)) {
            $comments = $this->getAdapter();
            $select = $comments->select()
                    ->from($this->_name, array(
                        $this->_primary, 'df' => 'DATE_FORMAT(comments.created,"%T on the  %D %M %Y")',
                        'comment_author', 'comment_author_url', 'comment_content',
                        'comment_author_email'))
                    ->joinLeft('finds','finds.id = comments.contentID', array())
                    ->where('finds.id = ?', (int)$id)
                    ->where('comments.comment_type  = ?','newsComment')
                    ->where('comments.comment_approved = ?','approved')
                    ->order('comments.created ASC');
            $data = $comments->fetchAll($select);
            $this->_cache->save($data, 'newscomments' . $id);
	}
	return $data;
    }

    /** Get comments list
     * @param array $params
     * @param integer $userid
     * @todo perhaps insert switch on approval status?
     * @todo remove date formating and put into view?
     * @return array
     */
    public function getComments(array $params, $userID) {
	$comments = $this->getAdapter();
	$select = $comments->select()
		->from($this->_name, array(
                    $this->_primary,'df' => 'DATE_FORMAT(comments.created,"%T @ %D %M %Y")',
                    'comment_author', 'comment_author_url', 'comment_content',
                    'comment_approved', 'user_ip', 'comment_author_email',
                    'comment_type', 'contentID', 'user_agent',
                    'commentID' => 'id'
                    ))
                ->joinLeft('finds','finds.id = comments.contentID',
                        array(
                            'id', 'old_findID', 'broadperiod',
                            'objecttype'
                            ))
		->order('comments.created DESC');
        if(isset($params['approval']) && $params['approval'] == 'spam') {
            $select->where('comments.commentStatus = ?', (string)'spam');
	}
	if(isset($params['approval']) && $params['approval'] == 'approved'){
            $select->where('comments.comment_approved = ?', (string)'approved');
	}
	if(isset($params['approval']) && $params['approval'] == 'moderation'){
            $select->where('comments.comment_approved = ?', (string)'moderation')
                    ->where('comments.commentStatus != ?', (string)'spam');
	}
	if(isset($userID)){
            $select->where('comments.createdBy = ?',(int)$userID);
	}
	$data = $comments->fetchAll($select);
	$paginator = Zend_Paginator::factory($data);
	$paginator->setItemCountPerPage(30)
		->setPageRange(10);
	if(isset($params['page']) && ($params['page'] != ""))  {
            $paginator->setCurrentPageNumber($params['page']);
	}
	return $paginator;
    }

    /** Get comments by id
     * @access public@
     * @param int $id
     * @todo remove date formating and put into view?
     * @todo change to fetchrow?
     * @return array
     */
    protected function getComment($id) {
        $comments = $this->getAdapter();
        $select = $comments->select()
                ->from($this->_name)
                ->where('id = ?', (int)$id);
        return $comments->fetchAll($select);
    }

    /** Get comments by userid and level of approval
     * @access public
     * @param integer $userid
     * @param integer $page
     * @param integer $approval
     * @todo perhaps insert switch on approval status?
     * @todo remove date formating and put into view?
     * @return array
     */

    public function getCommentsOnMyRecords( $userid ,$page, $approval ) {
        $comments = $this->getAdapter();
        $select = $comments->select()
                ->from($this->_name,array(
                    $this->_primary, 'df' => 'DATE_FORMAT(comments.created,"%T @ %D %M %Y")',
                    'comment_author', 'comment_author_url', 'comment_content',
                    'comment_approved','user_ip','comment_author_email'
                    ))
                ->joinLeft('finds','finds.id = comments.contentID',
                        array(
                            'id','old_findID','broadperiod',
                            'objecttype'
                            ))
                ->where('finds.createdBy = ?',(int)$userid)
                ->where('comments.comment_type = ?', 'findComment');
        if(isset($approval) && $approval == 'spam') {
            $select->where('comments.comment_approved = ?',(string)'spam');
        }
        if(isset($approval) && $approval== 'approved'){
            $select->where('comments.comment_approved = ?',(string)'approved');
        }
        if(isset($approval) && $approval == 'moderation'){
            $select->where('comments.comment_approved = ?',(string)'moderation');
        }
        $paginator = Zend_Paginator::factory($select);
        $paginator->setItemCountPerPage(30)
                ->setPageRange(10);
        if(isset($page) && ($page != "")) {
            $paginator->setCurrentPageNumber($page);
        }
        return $paginator;
    }

    /** Get comments on finds records
     * @access public
     * @param int $page
     * @todo remove date formating and put into view?
     * @return array
     */
    public function getCommentsToFinds($page) {
        $comments = $this->getAdapter();
        $select = $comments->select()
                ->from($this->_name,array(
                    $this->_primary, 'df' => 'DATE_FORMAT(comments.created,"%T @ %D %M %Y")',
                    'comment_author', 'comment_author_url', 'comment_content',
                    'comment_approved', 'user_IP', 'comment_author_email',
                    'comment_type', 'updated', 'created'
                    ))
                ->joinLeft('finds','finds.id = comments.contentID',
                        array(
                            'id', 'old_findID', 'broadperiod',
                            'objecttype'
                            ))
                ->joinLeft('finds_images','finds.secuid = finds_images.find_id',
                        array())
                ->joinLeft('slides','slides.secuid = finds_images.image_id',
                        array('i' => 'imageID', 'f' => 'filename'))
                ->joinLeft(array('u' => 'users'),'slides.createdBy = u.id',
                        array('imagedir'))
                ->joinLeft('findspots','finds.secuid = findspots.findID',
                        array('county'))
                ->where('comment_type = ?','findComment')
                ->where('comment_approved = ?',(string)'approved')
                ->order('created DESC,finds.id ')
                ->group('comments.id');
        $paginator = Zend_Paginator::factory($select);
        $paginator->setItemCountPerPage(30)
                ->setPageRange(10);
        if(isset($page) && ($page != "")) {
            $paginator->setCurrentPageNumber($page);
        }
        return $paginator;
    }
}


text:
/*

The 2D House Robber Problem

Given a City laid out on a grid, there are R rows and C columns of houses.
Each house is known to contain some amount of valuables v_ij.
Your task is to rob as many houses as possible to maximize the amount of loot.
However there is a security system in place and if you rob two adjacent houses
an alarm will go off.

Find the optimum set of non-adjacent houses to rob.

Example:
            Houses:  alignment:
          10 20 10     0  1  0
          20 30 20 =>  1  0  1
          10 20 10     0  1  0
        This alignment results in the maximum value of 80.

Dynamic Programming

Dynamic Programming requires comparing all possible alignments to
determine which alignment produces the optimal score. I first compute
the set of valid alignments in a single row then generate the pairs of
alignments that can be stacked vertically. Next for each row the optimal
alignment given the solution to all previous rows is computed. Once the
final row is processed the overall maximum value can be found. The solutions
can then be read back in reverse to determine which alignment produced this
result

Maximum Flow

This problem is an example of Maximum Bipartite Matching and can be
represented a Maximum Flow problem. Partition the input table into
two sets U and V such that no element in either set is adjacent to another
within the same set. Create a source vertex S and a sink vertex T. For
every node u in U with weight w connect an edge from s to u with weight w.
For every node v in V with weight w connect an edge from v to t with
weight w. Finally compute the maximum flow through the network. The
maximum flow equals the minimum cut and is isomorphic to the selection
of vertices's. Thus the maximum value is equal to the total value minus the
maximum flow. The code here is loosely based on the Dinic's Algorithm for Max
Flow. The Dynamic Trees are embedded inside the matrix structure.

*/
package hr2d

// Use dynamic programming to determine maximum value
func SolveDP(R, C int, table [][]int) (int) {
	alignments := generate_alignments(C)
	pairs := generate_alignment_pairs(alignments)

	N := len(alignments)

	// predecessors array each index p[i][j] is the index of the
	// alignment from the previous row.

	// current and previous best scores for the current row i
	// given the set of all possible valid alignments.
	dc := make([]int, N)
	dp := make([]int, N)

	for j, ali := range alignments {
		dp[j] = ali.Dot(table[0])
	}

	row_scores := make([]int, N)

	// process each row
	for i := 1; i < R; i++ {

		// determine alignment scores for the current row
		for j, ali := range alignments {
			row_scores[j] = ali.Dot(table[i])
			dc[j] = 0 //reset this rows current best score
		}

		// determine best score for each alignment given previous answers
		for a := 0; a < N; a++ {
			for _, b := range pairs[a] {
				c := dp[a] + row_scores[b]
				if c > dc[b] {
					dc[b] = c
				}
			}
		}

		// copy current best scores to the previous scores table
		for j := 0; j < N; j++ {
			dp[j] = dc[j]
		}
	}

	var maximum_value int
	for _, v := range dp {
		if v > maximum_value {
			maximum_value = v
		}
	}

	return maximum_value
}

// Use dynamic programming to determine maximum value and alignment
func SolveDP2(R, C int, table [][]int) (int, Alignments, error) {
	alignments := generate_alignments(C)
	pairs := generate_alignment_pairs(alignments)

	N := len(alignments)

	// predecessors array each index p[i][j] is the index of the
	// alignment from the previous row.
	p := make([][]int, R)

	//p[0] = make([]int, N) p[0] is not interesting

	// current and previous best scores for the current row i
	// given the set of all possible valid alignments.
	dc := make([]int, N)
	dp := make([]int, N)

	for j, ali := range alignments {
		dp[j] = ali.Dot(table[0])
	}

	row_scores := make([]int, N)

	// process each row
	for i := 1; i < R; i++ {

		p[i] = make([]int, N)

		// determine alignment scores for the current row
		for j, ali := range alignments {
			row_scores[j] = ali.Dot(table[i])
			dc[j] = 0 //reset this rows current best score
		}

		// determine best score for each alignment given previous answers
		for a := 0; a < N; a++ {
			for _, b := range pairs[a] {
				c := dp[a] + row_scores[b]
				if c > dc[b] {
					dc[b] = c
					p[i][b] = a
				}
			}
		}

		// copy current best scores to the previous scores table
		for j := 0; j < N; j++ {
			dp[j] = dc[j]
		}
	}

	final := make(Alignments, R)

	// determine which alignment generated the highest score in the final row
	var a, c int // best alignment index; best cost
	for j, v := range dp {
		if v > c {
			c = v
			a = j
		}
	}

	// walk the parent array in reverse
	// select the optimal alignment at each row
	for i := R - 1; i > 0; i-- {
		final[i] = alignments[a]
		a = p[i][a]
	}
	final[0] = alignments[a]

	return c, final, nil
}

// Use Maximum Flow to determine maximum value
func SolveFlow(R, C int, table [][]int) (int) {

	var total_value int;
	var max_flow int;

	// O(N^2)
	// determine total value of all houses
	for i:=0; i<R; i++ {
		for j:=0; j<C; j++ {
			total_value += table[i][j];
		}
	}

	// O(N * 4*(N/2)) => O(2*N^2) => O(N^2)
	// determine the maximum flow, by finding the min cut
	// of all paths from the source to the sink.
	// This loop iterates over all vertices's in U, then determines
	// the min cut for all adjacent vertices's in V.
	for i:=0; i<R; i++ {
		for j:=i%2; j<C; j+=2 {
			if i>0 {
				max_flow += update_path(table,i,j,i-1,j);
			}
			if j>0 {
				max_flow += update_path(table,i,j,i,j-1);
			}
			if j+1 < C {
				max_flow += update_path(table,i,j,i,j+1);
			}
			if i+1 < R {
				max_flow += update_path(table,i,j,i+1,j);
			}
		}
	}

	maximum_value := total_value - max_flow;

	return maximum_value
}

// compute blocking flow through s->u->v->t
func update_path(table [][]int, i, j, x, y int) int {

	u := table[i][j]
	v := table[x][y]

	// determine the blocking flow
	f := u
	if v < u {
		f = v
	}

	// ensure that this path has not been cut already
	if f > 0 {
		table[i][j] -= f
		table[x][y] -= f
	}

	return f;
}


text:
'''
performance.py
author: Luke de Oliveira (lukedeo@stanford.edu)

Usage:

>>> weights = np.ones(n_samples)
>>> # -- going to match bkg to signal
>>> weights[signal == True] = get_weights(sig_pt, bkg_pt)
>>> discs = {}
>>> add_curve(r'\tau_{32}', 'red', calculate_roc(signal, tau_32, weights=weights))
>>> fg = ROC_plotter(discs)
>>> fg.savefig('myroc.pdf')

'''

import numpy as np
import matplotlib.pyplot as plt

def get_weights(target, actual, bins = 10, cap = 10, match = True):
	'''
	re-weights a actual distribution to a target.

	Args:
		target (array/list): observations drawn from target distribution
		actual (array/list): observations drawn from distribution to
			match to the target.

		bins (numeric or list/array of numerics): bins to use to do weighting

		cap (numeric): maximum weight value.

		match (bool): whether to make the sum of weights in actual equal to the
			number of samples in target

	Returns:
		numpy.array: returns array of shape len(actual).

	'''
	target_counts, target_bins = np.histogram(target, bins=bins)
	counts, _ = np.histogram(actual, bins=target_bins)
	counts = (1.0 * counts)
	counts = np.array([max(a, 0.0001) for a in counts])
	multiplier = np.array((target_counts / counts).tolist() + [1.0])

	weights = np.array([min(multiplier[target_bins.searchsorted(point) - 1], cap) for point in actual])
	# weights = np.array([target_bins.searchsorted(point) for point in actual])

	if match:
		weights *= (len(target) / np.sum(weights))

	return weights

def calculate_roc(labels, discriminant, weights=None, bins = 2000):
	'''
	makes a weighted ROC curve

	Args:
		labels (numpy.array): an array of 1/0 representing signal/background
		discriminant (numpy.array): an array that represents the discriminant
		weights: sample weights for each point.
			`assert(weights.shape == discriminant.shape)
		bins: binning to use -- can be an int or a list/array of bins.

	Returns:
		tuple: (signal_efficiency, background_rejection) where each are arrays

	'''
	sig_ind = labels == 1
	bkg_ind = labels == 0
	if weights is None:
		bkg_total = np.sum(labels == 0)
		sig_total = np.sum(labels == 1)
	else:
		bkg_total = np.sum(weights[bkg_ind])
		sig_total = np.sum(weights[sig_ind])

	discriminant_bins = np.linspace(np.min(discriminant), np.max(discriminant), bins)

	if weights is None:
		sig, _ = np.histogram(discriminant[sig_ind], discriminant_bins)
		bkd, _ = np.histogram(discriminant[bkg_ind], discriminant_bins)
	else:
		sig, _ = np.histogram(discriminant[sig_ind], discriminant_bins, weights = weights[sig_ind])
		bkd, _ = np.histogram(discriminant[bkg_ind], discriminant_bins, weights = weights[bkg_ind])

	sig_eff = np.add.accumulate(sig[::-1]) / float(sig_total)
	bkg_rej = 1 / (np.add.accumulate(bkd[::-1]) / float(bkg_total))

	return sig_eff, bkg_rej

def ROC_plotter(curves, min_eff = 0, max_eff = 1, linewidth = 1.4,
	pp = False, signal = "$Z\rightarrow t\bar{t}$", background = "QCD",
	title = "Jet Image Tagging Comparison", logscale = True, ymax=10**4, ymin=1):

	fig = plt.figure(figsize=(11.69, 8.27), dpi=100)
	ax = fig.add_subplot(111)
	plt.xlim(min_eff,max_eff)
	plt.grid(b = True, which = 'minor')
	plt.grid(b = True, which = 'major')
	max_ = 0
	for tagger, data in curves.iteritems():
		sel = (data['efficiency'] >= min_eff) & (data['efficiency'] <= max_eff)
		if np.max(data['rejection'][sel]) > max_:
			max_ = np.max(data['rejection'][sel])
		plt.plot(data['efficiency'][sel], data['rejection'][sel], '-', label = r''+tagger, color = data['color'], linewidth=linewidth)

	ax = plt.subplot(1,1,1)
	for item in ([ax.title, ax.xaxis.label, ax.yaxis.label] + ax.get_xticklabels() + ax.get_yticklabels()):
		item.set_fontsize(20)
	if logscale == True:
		plt.ylim(ymin,ymax)
		ax.set_yscale('log')
	ax.set_xlabel(r'$\epsilon_{\mathrm{signal}}$')
	ax.set_ylabel(r"$1 / \epsilon_{\mathrm{bkg}}$")

	plt.legend()
	plt.title(r''+title)
	if pp:
		pp.savefig(fig)
	else:
		plt.show()
		return fig

def add_curve(name, color, curve_pair, dictref):
	dictref.update(
		{
			name : {
						'efficiency' : curve_pair[0],
						'rejection' : curve_pair[1],
						'color' : color
					}
		}
	)


text:
<?xml version="1.0" encoding="utf-8"?>
<shape android:shape="rectangle"
  xmlns:android="http://schemas.android.com/apk/res/android">
    <corners android:radius="@dimen/control_corner_material" />
    <solid android:color="?colorButtonNormal" />
</shape>


text:
package service

import (
	"reflect"
	"testing"

	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
	"k8s.io/apimachinery/pkg/types"
	"k8s.io/client-go/tools/record"
	"k8s.io/kubernetes/pkg/api/testapi"
	"k8s.io/kubernetes/pkg/api/v1"
	"k8s.io/kubernetes/pkg/client/clientset_generated/clientset/fake"
	informers "k8s.io/kubernetes/pkg/client/informers/informers_generated/externalversions"
	fakecloud "k8s.io/kubernetes/pkg/cloudprovider/providers/fake"
	"k8s.io/kubernetes/pkg/controller"
)

const region = "us-central"

func newService(name string, uid types.UID, serviceType v1.ServiceType) *v1.Service {
	return &v1.Service{ObjectMeta: metav1.ObjectMeta{Name: name, Namespace: "namespace", UID: uid, SelfLink: testapi.Default.SelfLink("services", name)}, Spec: v1.ServiceSpec{Type: serviceType}}
}

func alwaysReady() bool { return true }

func newController() (*ServiceController, *fakecloud.FakeCloud, *fake.Clientset) {
	cloud := &fakecloud.FakeCloud{}
	cloud.Region = region

	client := fake.NewSimpleClientset()

	informerFactory := informers.NewSharedInformerFactory(client, controller.NoResyncPeriodFunc())
	serviceInformer := informerFactory.Core().V1().Services()
	nodeInformer := informerFactory.Core().V1().Nodes()

	controller, _ := New(cloud, client, serviceInformer, nodeInformer, "test-cluster")
	controller.nodeListerSynced = alwaysReady
	controller.serviceListerSynced = alwaysReady
	controller.eventRecorder = record.NewFakeRecorder(100)

	controller.init()
	cloud.Calls = nil     // ignore any cloud calls made in init()
	client.ClearActions() // ignore any client calls made in init()

	return controller, cloud, client
}

func TestCreateExternalLoadBalancer(t *testing.T) {
	table := []struct {
		service             *v1.Service
		expectErr           bool
		expectCreateAttempt bool
	}{
		{
			service: &v1.Service{
				ObjectMeta: metav1.ObjectMeta{
					Name:      "no-external-balancer",
					Namespace: "default",
				},
				Spec: v1.ServiceSpec{
					Type: v1.ServiceTypeClusterIP,
				},
			},
			expectErr:           false,
			expectCreateAttempt: false,
		},
		{
			service: &v1.Service{
				ObjectMeta: metav1.ObjectMeta{
					Name:      "udp-service",
					Namespace: "default",
					SelfLink:  testapi.Default.SelfLink("services", "udp-service"),
				},
				Spec: v1.ServiceSpec{
					Ports: []v1.ServicePort{{
						Port:     80,
						Protocol: v1.ProtocolUDP,
					}},
					Type: v1.ServiceTypeLoadBalancer,
				},
			},
			expectErr:           false,
			expectCreateAttempt: true,
		},
		{
			service: &v1.Service{
				ObjectMeta: metav1.ObjectMeta{
					Name:      "basic-service1",
					Namespace: "default",
					SelfLink:  testapi.Default.SelfLink("services", "basic-service1"),
				},
				Spec: v1.ServiceSpec{
					Ports: []v1.ServicePort{{
						Port:     80,
						Protocol: v1.ProtocolTCP,
					}},
					Type: v1.ServiceTypeLoadBalancer,
				},
			},
			expectErr:           false,
			expectCreateAttempt: true,
		},
	}

	for _, item := range table {
		controller, cloud, client := newController()
		err, _ := controller.createLoadBalancerIfNeeded("foo/bar", item.service)
		if !item.expectErr && err != nil {
			t.Errorf("unexpected error: %v", err)
		} else if item.expectErr && err == nil {
			t.Errorf("expected error creating %v, got nil", item.service)
		}
		actions := client.Actions()
		if !item.expectCreateAttempt {
			if len(cloud.Calls) > 0 {
				t.Errorf("unexpected cloud provider calls: %v", cloud.Calls)
			}
			if len(actions) > 0 {
				t.Errorf("unexpected client actions: %v", actions)
			}
		} else {
			var balancer *fakecloud.FakeBalancer
			for k := range cloud.Balancers {
				if balancer == nil {
					b := cloud.Balancers[k]
					balancer = &b
				} else {
					t.Errorf("expected one load balancer to be created, got %v", cloud.Balancers)
					break
				}
			}
			if balancer == nil {
				t.Errorf("expected one load balancer to be created, got none")
			} else if balancer.Name != controller.loadBalancerName(item.service) ||
				balancer.Region != region ||
				balancer.Ports[0].Port != item.service.Spec.Ports[0].Port {
				t.Errorf("created load balancer has incorrect parameters: %v", balancer)
			}
			actionFound := false
			for _, action := range actions {
				if action.GetVerb() == "update" && action.GetResource().Resource == "services" {
					actionFound = true
				}
			}
			if !actionFound {
				t.Errorf("expected updated service to be sent to client, got these actions instead: %v", actions)
			}
		}
	}
}

// TODO: Finish converting and update comments
func TestUpdateNodesInExternalLoadBalancer(t *testing.T) {
	nodes := []*v1.Node{
		{ObjectMeta: metav1.ObjectMeta{Name: "node0"}},
		{ObjectMeta: metav1.ObjectMeta{Name: "node1"}},
		{ObjectMeta: metav1.ObjectMeta{Name: "node73"}},
	}
	table := []struct {
		services            []*v1.Service
		expectedUpdateCalls []fakecloud.FakeUpdateBalancerCall
	}{
		{
			// No services present: no calls should be made.
			services:            []*v1.Service{},
			expectedUpdateCalls: nil,
		},
		{
			// Services do not have external load balancers: no calls should be made.
			services: []*v1.Service{
				newService("s0", "111", v1.ServiceTypeClusterIP),
				newService("s1", "222", v1.ServiceTypeNodePort),
			},
			expectedUpdateCalls: nil,
		},
		{
			// Services does have an external load balancer: one call should be made.
			services: []*v1.Service{
				newService("s0", "333", v1.ServiceTypeLoadBalancer),
			},
			expectedUpdateCalls: []fakecloud.FakeUpdateBalancerCall{
				{Service: newService("s0", "333", v1.ServiceTypeLoadBalancer), Hosts: nodes},
			},
		},
		{
			// Three services have an external load balancer: three calls.
			services: []*v1.Service{
				newService("s0", "444", v1.ServiceTypeLoadBalancer),
				newService("s1", "555", v1.ServiceTypeLoadBalancer),
				newService("s2", "666", v1.ServiceTypeLoadBalancer),
			},
			expectedUpdateCalls: []fakecloud.FakeUpdateBalancerCall{
				{Service: newService("s0", "444", v1.ServiceTypeLoadBalancer), Hosts: nodes},
				{Service: newService("s1", "555", v1.ServiceTypeLoadBalancer), Hosts: nodes},
				{Service: newService("s2", "666", v1.ServiceTypeLoadBalancer), Hosts: nodes},
			},
		},
		{
			// Two services have an external load balancer and two don't: two calls.
			services: []*v1.Service{
				newService("s0", "777", v1.ServiceTypeNodePort),
				newService("s1", "888", v1.ServiceTypeLoadBalancer),
				newService("s3", "999", v1.ServiceTypeLoadBalancer),
				newService("s4", "123", v1.ServiceTypeClusterIP),
			},
			expectedUpdateCalls: []fakecloud.FakeUpdateBalancerCall{
				{Service: newService("s1", "888", v1.ServiceTypeLoadBalancer), Hosts: nodes},
				{Service: newService("s3", "999", v1.ServiceTypeLoadBalancer), Hosts: nodes},
			},
		},
		{
			// One service has an external load balancer and one is nil: one call.
			services: []*v1.Service{
				newService("s0", "234", v1.ServiceTypeLoadBalancer),
				nil,
			},
			expectedUpdateCalls: []fakecloud.FakeUpdateBalancerCall{
				{Service: newService("s0", "234", v1.ServiceTypeLoadBalancer), Hosts: nodes},
			},
		},
	}
	for _, item := range table {
		controller, cloud, _ := newController()

		var services []*v1.Service
		for _, service := range item.services {
			services = append(services, service)
		}
		if err := controller.updateLoadBalancerHosts(services, nodes); err != nil {
			t.Errorf("unexpected error: %v", err)
		}
		if !reflect.DeepEqual(item.expectedUpdateCalls, cloud.UpdateCalls) {
			t.Errorf("expected update calls mismatch, expected %+v, got %+v", item.expectedUpdateCalls, cloud.UpdateCalls)
		}
	}
}

func TestGetNodeConditionPredicate(t *testing.T) {
	tests := []struct {
		node         v1.Node
		expectAccept bool
		name         string
	}{
		{
			node:         v1.Node{},
			expectAccept: false,
			name:         "empty",
		},
		{
			node: v1.Node{
				Status: v1.NodeStatus{
					Conditions: []v1.NodeCondition{
						{Type: v1.NodeReady, Status: v1.ConditionTrue},
					},
				},
			},
			expectAccept: true,
			name:         "basic",
		},
		{
			node: v1.Node{
				Spec: v1.NodeSpec{Unschedulable: true},
				Status: v1.NodeStatus{
					Conditions: []v1.NodeCondition{
						{Type: v1.NodeReady, Status: v1.ConditionTrue},
					},
				},
			},
			expectAccept: false,
			name:         "unschedulable",
		},
	}
	pred := getNodeConditionPredicate()
	for _, test := range tests {
		accept := pred(&test.node)
		if accept != test.expectAccept {
			t.Errorf("Test failed for %s, expected %v, saw %v", test.name, test.expectAccept, accept)
		}
	}
}

// TODO(a-robinson): Add tests for update/sync/delete.


text:
/*!
 * pixi-compressed-textures - v1.1.2
 * Compiled Wed, 18 Jan 2017 23:44:30 UTC
 *
 * pixi-compressed-textures is licensed under the MIT License.
 * http://www.opensource.org/licenses/mit-license
 */
(function(f){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}g.pixiCompressedTextures = f()}})(function(){var define,module,exports;return (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){
function CompressedImage(src, data, type, width, height, levels, internalFormat) {
    CompressedImage.prototype.init.apply(this, arguments);
}

module.exports = CompressedImage;

CompressedImage.prototype.init = function(src, data, type, width, height, levels, internalFormat) {
    this.src = src;
    this.width = width;
    this.height = height;
    this.data = data;
    this.type = type;
    this.levels = levels;
    this.internalFormat = internalFormat;
    this.isCompressedImage = true;

    var oldComplete = this.complete;
    this.complete = !!data;
    if (!oldComplete && this.complete && this.onload) {
        this.onload( { target: this } );
    }
    return this;
};

CompressedImage.prototype.dispose = function() {
    this.data = null;
};

CompressedImage.prototype.generateWebGLTexture = function (gl, preserveSource) {
    if (this.data === null) {
        throw "Trying to create a second (or more) webgl texture from the same CompressedImage : " + this.src;
    }

    var width = this.width;
    var height = this.height;
    var levels = this.levels;
    var offset = 0;
    // Loop through each mip level of compressed texture data provided and upload it to the given texture.
    for (var i = 0; i < this.levels; ++i) {
        // Determine how big this level of compressed texture data is in bytes.
        var levelSize = textureLevelSize(this.internalFormat, width, height);
        // Get a view of the bytes for this level of DXT data.
        var dxtLevel = new Uint8Array(this.data.buffer, this.data.byteOffset + offset, levelSize);
        // Upload!
        gl.compressedTexImage2D(gl.TEXTURE_2D, i, this.internalFormat, width, height, 0, dxtLevel);
        // The next mip level will be half the height and width of this one.
        width = width >> 1;
        if (width < 1)
            width = 1;
        height = height >> 1;
        if (height < 1)
            height = 1;
        // Advance the offset into the compressed texture data past the current mip level's data.
        offset += levelSize;
    }

    // We can't use gl.generateMipmaps with compressed textures, so only use
    // mipmapped filtering if the compressed texture data contained mip levels.
    if (levels > 1) {
        gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
        gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR_MIPMAP_NEAREST);
    }
    else {
        gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
        gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
    }

    // Cleaning the data to save memory. NOTE : BECAUSE OF THIS WE CANNOT CREATE TWO GL TEXTURE FROM THE SAME COMPRESSED IMAGE !
    if (!preserveSource)
        this.data = null;
};

/**
 * Load a compressed image from an array buffer
 * @param arrayBuffer the buffer contains the image
 * @return the loaded CompressedImage
 */
CompressedImage.loadFromArrayBuffer = function (arrayBuffer, src) {
    return new CompressedImage(src).loadFromArrayBuffer(arrayBuffer);
};

CompressedImage.prototype.loadFromArrayBuffer = function(arrayBuffer) {
    var head = new Uint8Array(arrayBuffer, 0, 3);

    //todo: implement onload

    if (head[0] == "DDS".charCodeAt(0) && head[1] == "DDS".charCodeAt(1) && head[2] == "DDS".charCodeAt(2))
        return this._loadDDS(arrayBuffer);
    else if (head[0] == "PVR".charCodeAt(0) && head[1] == "PVR".charCodeAt(1) && head[2] == "PVR".charCodeAt(2))
        return this._loadPVR(arrayBuffer);
    else
        throw "Compressed texture format is not recognized: " + src;
    return this;
};

/**
 * Load a DDS compressed image from an array buffer
 * @param arrayBuffer the buffer contains the image
 * @return the loaded CompressedImage
 */
CompressedImage.prototype._loadDDS = function(arrayBuffer) {
    // Get a view of the arrayBuffer that represents the DDS header.
    var header = new Int32Array(arrayBuffer, 0, DDS_HEADER_LENGTH);

    // Do some sanity checks to make sure this is a valid DDS file.
    if (header[DDS_HEADER_MAGIC] != DDS_MAGIC)
        throw "Invalid magic number in DDS header";

    if (!header[DDS_HEADER_PF_FLAGS] & DDPF_FOURCC)
        throw "Unsupported format, must contain a FourCC code";

    // Determine what type of compressed data the file contains.
    var fourCC = header[DDS_HEADER_PF_FOURCC];
    var internalFormat;
    switch (fourCC) {
        case FOURCC_DXT1:
            internalFormat = COMPRESSED_RGB_S3TC_DXT1_EXT;
            break;
        case FOURCC_DXT3:
            internalFormat = COMPRESSED_RGBA_S3TC_DXT3_EXT;
            break;
        case FOURCC_DXT5:
            internalFormat = COMPRESSED_RGBA_S3TC_DXT5_EXT;
            break;
        case FOURCC_ATC:
            internalFormat = COMPRESSED_RGB_ATC_WEBGL;
            break;
        case FOURCC_ATCA:
            internalFormat = COMPRESSED_RGBA_ATC_EXPLICIT_ALPHA_WEBGL;
            break;
        case FOURCC_ATCI:
            internalFormat = COMPRESSED_RGBA_ATC_INTERPOLATED_ALPHA_WEBGL;
            break;
        default:
            throw "Unsupported FourCC code: " + int32ToFourCC(fourCC);
    }

    // Determine how many mipmap levels the file contains.
    var levels = 1;
    if (header[DDS_HEADER_FLAGS] & DDSD_MIPMAPCOUNT) {
        levels = Math.max(1, header[DDS_HEADER_MIPMAPCOUNT]);
    }

    // Gather other basic metrics and a view of the raw the DXT data.
    var width = header[DDS_HEADER_WIDTH];
    var height = header[DDS_HEADER_HEIGHT];
    var dataOffset = header[DDS_HEADER_SIZE] + 4;
    var dxtData = new Uint8Array(arrayBuffer, dataOffset);

    return this.init(this.src, dxtData, 'DDS', width, height, levels, internalFormat);
};

/**
 * Load a PVR compressed image from an array buffer
 * @param arrayBuffer the buffer contains the image
 * @return the loaded CompressedImage
 */
CompressedImage.prototype._loadPVR = function(arrayBuffer) {
    // Get a view of the arrayBuffer that represents the DDS header.
    var header = new Int32Array(arrayBuffer, 0, PVR_HEADER_LENGTH);

    // Do some sanity checks to make sure this is a valid DDS file.
    if (header[PVR_HEADER_MAGIC] != PVR_MAGIC)
        throw "Invalid magic number in PVR header";

    // Determine what type of compressed data the file contains.
    var format = header[PVR_HEADER_FORMAT];
    var internalFormat;
    switch (format) {
        case PVR_FORMAT_2BPP_RGB:
            internalFormat = COMPRESSED_RGB_PVRTC_2BPPV1_IMG;
            break;
        case PVR_FORMAT_2BPP_RGBA:
            internalFormat = COMPRESSED_RGBA_PVRTC_2BPPV1_IMG;
            break;
        case PVR_FORMAT_4BPP_RGB:
            internalFormat = COMPRESSED_RGB_PVRTC_4BPPV1_IMG;
            break;
        case PVR_FORMAT_4BPP_RGBA:
            internalFormat = COMPRESSED_RGBA_PVRTC_4BPPV1_IMG;
            break;
        case PVR_FORMAT_ETC1:
            internalFormat = COMPRESSED_RGB_ETC1_WEBGL;
            break;
        case PVR_FORMAT_DXT1:
            internalFormat = COMPRESSED_RGB_S3TC_DXT1_EXT;
            break;
        case PVR_FORMAT_DXT3:
            internalFormat = COMPRESSED_RGBA_S3TC_DXT3_EXT;
            break;
        case PVR_FORMAT_DXT5:
            internalFormat = COMPRESSED_RGBA_S3TC_DXT5_EXT;
            break;
        default:
            throw "Unsupported PVR format: " + format;
    }

    // Gather other basic metrics and a view of the raw the DXT data.
    var width = header[PVR_HEADER_WIDTH];
    var height = header[PVR_HEADER_HEIGHT];
    var levels = header[PVR_HEADER_MIPMAPCOUNT];
    var dataOffset = header[PVR_HEADER_METADATA] + 52;
    var pvrtcData = new Uint8Array(arrayBuffer, dataOffset);

    return this.init(this.src, pvrtcData, 'PVR', width, height, levels, internalFormat);
};

//============================//
// DXT constants and utilites //
//============================//

// Utility functions
// Builds a numeric code for a given fourCC string
function fourCCToInt32(value) {
    return value.charCodeAt(0) +
        (value.charCodeAt(1) << 8) +
        (value.charCodeAt(2) << 16) +
        (value.charCodeAt(3) << 24);
}

// Turns a fourCC numeric code into a string
function int32ToFourCC(value) {
    return String.fromCharCode(
        value & 0xff,
        (value >> 8) & 0xff,
        (value >> 16) & 0xff,
        (value >> 24) & 0xff
    );
}

// Calcualates the size of a compressed texture level in bytes
function textureLevelSize(format, width, height) {
    switch (format) {
        case COMPRESSED_RGB_S3TC_DXT1_EXT:
        case COMPRESSED_RGB_ATC_WEBGL:
        case COMPRESSED_RGB_ETC1_WEBGL:
            return ((width + 3) >> 2) * ((height + 3) >> 2) * 8;

        case COMPRESSED_RGBA_S3TC_DXT3_EXT:
        case COMPRESSED_RGBA_S3TC_DXT5_EXT:
        case COMPRESSED_RGBA_ATC_EXPLICIT_ALPHA_WEBGL:
        case COMPRESSED_RGBA_ATC_INTERPOLATED_ALPHA_WEBGL:
            return ((width + 3) >> 2) * ((height + 3) >> 2) * 16;

        case COMPRESSED_RGB_PVRTC_4BPPV1_IMG:
        case COMPRESSED_RGBA_PVRTC_4BPPV1_IMG:
            return Math.floor((Math.max(width, 8) * Math.max(height, 8) * 4 + 7) / 8);

        case COMPRESSED_RGB_PVRTC_2BPPV1_IMG:
        case COMPRESSED_RGBA_PVRTC_2BPPV1_IMG:
            return Math.floor((Math.max(width, 16) * Math.max(height, 8) * 2 + 7) / 8);

        default:
            return 0;
    }
}

// DXT formats, from:
// http://www.khronos.org/registry/webgl/extensions/WEBGL_compressed_texture_s3tc/
var COMPRESSED_RGB_S3TC_DXT1_EXT = 0x83F0;
var COMPRESSED_RGBA_S3TC_DXT1_EXT = 0x83F1;
var COMPRESSED_RGBA_S3TC_DXT3_EXT = 0x83F2;
var COMPRESSED_RGBA_S3TC_DXT5_EXT = 0x83F3;

// ATC formats, from:
// http://www.khronos.org/registry/webgl/extensions/WEBGL_compressed_texture_atc/
var COMPRESSED_RGB_ATC_WEBGL = 0x8C92;
var COMPRESSED_RGBA_ATC_EXPLICIT_ALPHA_WEBGL = 0x8C93;
var COMPRESSED_RGBA_ATC_INTERPOLATED_ALPHA_WEBGL = 0x87EE;

// DXT values and structures referenced from:
// http://msdn.microsoft.com/en-us/library/bb943991.aspx/
var DDS_MAGIC = 0x20534444;
var DDSD_MIPMAPCOUNT = 0x20000;
var DDPF_FOURCC = 0x4;

var DDS_HEADER_LENGTH = 31; // The header length in 32 bit ints.

// Offsets into the header array.
var DDS_HEADER_MAGIC = 0;

var DDS_HEADER_SIZE = 1;
var DDS_HEADER_FLAGS = 2;
var DDS_HEADER_HEIGHT = 3;
var DDS_HEADER_WIDTH = 4;

var DDS_HEADER_MIPMAPCOUNT = 7;

var DDS_HEADER_PF_FLAGS = 20;
var DDS_HEADER_PF_FOURCC = 21;

// FourCC format identifiers.
var FOURCC_DXT1 = fourCCToInt32("DXT1");
var FOURCC_DXT3 = fourCCToInt32("DXT3");
var FOURCC_DXT5 = fourCCToInt32("DXT5");

var FOURCC_ATC = fourCCToInt32("ATC ");
var FOURCC_ATCA = fourCCToInt32("ATCA");
var FOURCC_ATCI = fourCCToInt32("ATCI");

//===============//
// PVR constants //
//===============//

// PVR formats, from:
// http://www.khronos.org/registry/webgl/extensions/WEBGL_compressed_texture_pvrtc/
var COMPRESSED_RGB_PVRTC_4BPPV1_IMG = 0x8C00;
var COMPRESSED_RGB_PVRTC_2BPPV1_IMG = 0x8C01;
var COMPRESSED_RGBA_PVRTC_4BPPV1_IMG = 0x8C02;
var COMPRESSED_RGBA_PVRTC_2BPPV1_IMG = 0x8C03;

// ETC1 format, from:
// http://www.khronos.org/registry/webgl/extensions/WEBGL_compressed_texture_etc1/
var COMPRESSED_RGB_ETC1_WEBGL = 0x8D64;

var PVR_FORMAT_2BPP_RGB = 0;
var PVR_FORMAT_2BPP_RGBA = 1;
var PVR_FORMAT_4BPP_RGB = 2;
var PVR_FORMAT_4BPP_RGBA = 3;
var PVR_FORMAT_ETC1 = 6;
var PVR_FORMAT_DXT1 = 7;
var PVR_FORMAT_DXT3 = 9;
var PVR_FORMAT_DXT5 = 5;

var PVR_HEADER_LENGTH = 13; // The header length in 32 bit ints.
var PVR_MAGIC = 0x03525650; //0x50565203;

// Offsets into the header array.
var PVR_HEADER_MAGIC = 0;
var PVR_HEADER_FORMAT = 2;
var PVR_HEADER_HEIGHT = 6;
var PVR_HEADER_WIDTH = 7;
var PVR_HEADER_MIPMAPCOUNT = 11;
var PVR_HEADER_METADATA = 12;

},{}],2:[function(require,module,exports){
/**
 * Created by Liza on 12.12.2015.
 */

var core = PIXI,
    CompressedImage = require('./CompressedImage'),
    WebGLManager = core.WebGLManager;
/**
 * @class
 * @memberof PIXI.compressedTextures
 * @extends PIXI.WebGlManager
 * @param renderer {PIXI.WebGLRenderer} The renderer this manager works for.
 */
function CompressedTextureManager(renderer) {
    WebGLManager.call(this, renderer);
}

CompressedTextureManager.prototype = Object.create(WebGLManager.prototype);
CompressedTextureManager.prototype.constructor = CompressedTextureManager;
module.exports = CompressedTextureManager;

core.WebGLRenderer.registerPlugin('compressedTextureManager', CompressedTextureManager);

CompressedTextureManager.prototype.getSupportedExtensions = function () {
    var gl = this.renderer.gl;
    function getExtension(gl, name) {
        var vendorPrefixes = ["", "WEBKIT_", "MOZ_"];
        var ext = null;
        for (var i in vendorPrefixes) {
            ext = gl.getExtension(vendorPrefixes[i] + name);
            if (ext) {
                break;
            }
        }
        return ext;
    }

    return {
        dxt: getExtension(gl, "WEBGL_compressed_texture_s3tc"),
        pvrtc: getExtension(gl, "WEBGL_compressed_texture_pvrtc"),
        atc: getExtension(gl, "WEBGL_compressed_texture_atc")
    };
};

},{"./CompressedImage":1}],3:[function(require,module,exports){
var CompressedImage = require('./CompressedImage');
var GLTexture = PIXI.glCore.GLTexture;

/**
 * @mixin
 */
var GLTextureMixin = {
    uploadNotCompressed: GLTexture.prototype.upload,
    isCompressed: false,
    upload: function(source)
    {
        if (!(source instanceof CompressedImage)) {
            return this.uploadNotCompressed(source);
        }
        this.bind();

        var gl = this.gl;

        gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, this.premultiplyAlpha);

        this.isCompressed = true;

        source.generateWebGLTexture(gl, true);
    },

    enableMipmap: function() {
        if (this.isCompressed) {
            return;
        }
        var gl = this.gl;

        this.bind();

        this.mipmap = true;

        gl.generateMipmap(gl.TEXTURE_2D);
    }
};

module.exports = GLTextureMixin;

},{"./CompressedImage":1}],4:[function(require,module,exports){
function extensionChooser(supportedExtensions) {
    supportedExtensions = supportedExtensions || [];

    var imageParser = require('./imageParser')();

    return function (resource, next) {
        var ext = resource.metadata.choice;
        if (!ext) {
            return next();
        }
        //let us choose extension!
        var url = resource.url;
        if (!resource._defaultUrlChoice) {
            resource._defaultUrlChoice = url;
            var k = url.lastIndexOf(".");
            if (k >= 0) {
                resource._baseUrl = url.substring(0, k);
            } else {
                return next();
            }
        }
        for (var i = ext.length - 1; i >= 0; i--) {
            url = resource._baseUrl + ext[i];
            var isSupported = false;
            for (var j = 0; j < supportedExtensions.length; j++) {
                if (ext[i] === supportedExtensions[j]) {
                    resource.url = url;
                    resource.loadType = resource._determineLoadType();
                    return imageParser(resource, next);
                }
            }
        }
        return imageParser(resource, next);
    };
}

module.exports = extensionChooser;

},{"./imageParser":6}],5:[function(require,module,exports){
var core = PIXI,
    utils = core.utils,
    extensionFixer = require('./CompressedImage');

function textureExtensionFixer(supportedExtensions) {
    return function (resource, next) {
        if (resource.texture && resource._defaultUrlChoice && resource._defaultUrl != resource.url) {
            var texture = resource.texture;
            var baseTexture = texture.baseTexture;
            delete utils.BaseTextureCache[baseTexture.imageUrl];
            delete utils.TextureCache[baseTexture.imageUrl];
            baseTexture.imageUrl = resource._defaultUrlChoice;
            core.utils.BaseTextureCache[baseTexture.imageUrl] = baseTexture;
            core.utils.TextureCache[baseTexture.imageUrl] = texture;
        }
        next();
    };
}

module.exports = textureExtensionFixer;

},{"./CompressedImage":1}],6:[function(require,module,exports){
var core = PIXI,
    utils = core.utils,
    CompressedImage = require('./CompressedImage'),
    Resource = core.loaders.Resource;

Resource.setExtensionXhrType('dds', Resource.XHR_RESPONSE_TYPE.BUFFER);
Resource.setExtensionXhrType('pvr', Resource.XHR_RESPONSE_TYPE.BUFFER);
Resource.setExtensionXhrType('etc1', Resource.XHR_RESPONSE_TYPE.BUFFER);

function imageParser() {
    return function (resource, next) {
        if (resource.url.indexOf('.dds') != -1 || resource.url.indexOf('.pvr') != -1 || resource.url.indexOf('.etc1') != -1) {
            var compressedImage = resource.compressedImage || new CompressedImage(resource.url);
            if (resource.data) {
                throw "compressedImageParser middleware must be specified in loader.before() and must have zero resource.data";
            }
            resource.isCompressedImage = true;
            resource.data = compressedImage;
            resource.onComplete.add(function() {
                resource.type = Resource.TYPE.IMAGE;
                compressedImage.loadFromArrayBuffer(resource.data);
                resource.data = compressedImage;
            });
        }
        next();
    };
}

module.exports = imageParser;

},{"./CompressedImage":1}],7:[function(require,module,exports){
(function (global){
var plugin = {
    CompressedTextureManager: require('./CompressedTextureManager'),
    imageParser: require('./imageParser'),
    extensionChooser: require('./extensionChooser'),
    extensionFixer: require('./extensionFixer'),
    GLTextureMixin: require('./GLTextureMixin'),
    detectExtensions: function (renderer, resolution) {
        var extensions = [];
        if (renderer instanceof PIXI.WebGLRenderer) {
            var data = renderer.plugins.compressedTextureManager.getSupportedExtensions();
            if (data.dxt) extensions.push('.dds');
            if (data.pvrtc) extensions.push('.pvr');
            if (data.atc) extensions.push('.atc');
        } else if (renderer instanceof PIXI.CanvasRenderer) {
            //nothing special for canvas
        }
        //retina or not
        resolution = resolution || renderer.resolution;
        var res = "@"+resolution+"x";
        var ext = extensions.slice(0);
        while (ext.length > 0) {
            extensions.push(res + ext.pop());
        }
        extensions.push(res + ".png");
        extensions.push(res + ".jpg");
        //atlas support @1x @2x @.5x
        extensions.push(res + ".json");
        extensions.push(res + ".atlas");
        return extensions;
    }
};

Object.assign(PIXI.glCore.GLTexture.prototype, plugin.GLTextureMixin);

PIXI.loaders.Loader.addPixiMiddleware(plugin.extensionFixer);
PIXI.loader.use(plugin.extensionFixer());

module.exports = global.PIXI.compressedTextures = plugin;

}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})

},{"./CompressedTextureManager":2,"./GLTextureMixin":3,"./extensionChooser":4,"./extensionFixer":5,"./imageParser":6}]},{},[7])(7)
});

//# sourceMappingURL=pixi-compressed-textures.js.map


text:
<?php

function smarty_function_total($params, &$smarty)
{

	$subtotal = 0;
	foreach ($params['cost'] as $key=>$value)
	{

		if ($value['product']['custom_field1'] == $params['group'])
		{
			$subtotal = $value['total'] + $subtotal;
		}
	}
	$subtotal = siLocal::number($subtotal);
	return $subtotal;

}

?>


text:
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@android:color/black"
    android:keepScreenOn="true">

    <VideoView
        android:id="@+id/detail_video"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_gravity="center" />

    <include
        layout="@layout/layout_loading_progress"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center" />

    <android.support.v7.widget.Toolbar
        android:id="@+id/toolbar"
        android:layout_width="match_parent"
        android:layout_height="?attr/actionBarSize"
        android:background="@drawable/scrim_reversed"
        android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar" />

    <TextView
        android:id="@+id/list_item_image_textview"
        style="@style/TextAppearance"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="bottom"
        android:height="?attr/actionBarSize"
        android:background="@drawable/scrim"
        android:ellipsize="end"
        android:gravity="center_vertical|end"
        android:lines="1"
        android:padding="@dimen/text_horizontal_padding"
        android:textColor="@android:color/white"
        tools:text="@string/app_name" />

</FrameLayout>


text:
/*
 * $OpenBSD: common.h,v 1.26 2006/03/11 19:41:30 otto Exp $
 * $DragonFly: src/usr.bin/patch/common.h,v 1.5 2008/08/10 23:50:12 joerg Exp $
 * $NetBSD: common.h,v 1.19.38.2 2015/08/04 21:03:33 snj Exp $
 */

/*
 * patch - a program to apply diffs to original files
 *
 * Copyright 1986, Larry Wall
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following condition is met:
 * 1. Redistributions of source code must retain the above copyright notice,
 * this condition and the following disclaimer.
 *
 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR 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 AUTHOR 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.
 *
 * -C option added in 1998, original code by Marc Espie, based on FreeBSD
 * behaviour
 */

#include <sys/types.h>

#include <stdbool.h>
#include <stdint.h>

#define DEBUGGING

/* constants */

#define MAXHUNKSIZE 100000	/* is this enough lines? */
#define INITHUNKMAX 125		/* initial dynamic allocation size */
#define MAXLINELEN 8192
#define BUFFERSIZE 1024
#define LINENUM_MAX LONG_MAX

#define SCCSPREFIX "s."
#define GET "get -e %s"
#define SCCSDIFF "get -p %s | diff - %s >/dev/null"

#define RCSSUFFIX ",v"
#define CHECKOUT "/usr/bin/co"
#define RCSDIFF "/usr/bin/rcsdiff"

#define ORIGEXT ".orig"
#define REJEXT ".rej"

/* handy definitions */

#define strNE(s1,s2) (strcmp(s1, s2))
#define strEQ(s1,s2) (!strcmp(s1, s2))
#define strnNE(s1,s2,l) (strncmp(s1, s2, l))
#define strnEQ(s1,s2,l) (!strncmp(s1, s2, l))

/* typedefs */

typedef long    LINENUM;	/* must be signed */

/* globals */

extern mode_t	filemode;

extern char	buf[MAXLINELEN];/* general purpose buffer */
extern size_t	buf_len;

extern bool	using_plan_a;	/* try to keep everything in memory */
extern bool	out_of_mem;	/* ran out of memory in plan a */

#define MAXFILEC 2

extern char	*filearg[MAXFILEC];
extern bool	ok_to_create_file;
extern char	*outname;
extern char	*origprae;

extern char	*TMPOUTNAME;
extern char	*TMPINNAME;
extern char	*TMPREJNAME;
extern char	*TMPPATNAME;
extern bool	toutkeep;
extern bool	trejkeep;

#ifdef DEBUGGING
extern int	debug;
#endif

extern bool	force;
extern bool	batch;
extern bool	verbose;
extern bool	reverse;
extern bool	noreverse;
extern bool	skip_rest_of_patch;
extern int	strippath;
extern bool	canonicalize;
/* TRUE if -C was specified on command line.  */
extern bool	check_only;
extern bool	warn_on_invalid_line;
extern bool	last_line_missing_eol;

#define CONTEXT_DIFF 1
#define NORMAL_DIFF 2
#define ED_DIFF 3
#define NEW_CONTEXT_DIFF 4
#define UNI_DIFF 5

extern int	diff_type;
extern char	*revision;	/* prerequisite revision, if any */
extern LINENUM	input_lines;	/* how long is input file in lines */

extern int	posix;


text:
The high-quality [iOS native search bar](https://developer.apple.com/library/ios/documentation/UserExperience/Conceptual/UIKitUICatalog/UISearchBar.html) for react native.

<img src="SearchBar.png"/>

## Installation

In your react native project, run `npm install react-native-search-bar --save`

To link this library, please follow the first two steps in the [Linking Libraries (iOS)](http://facebook.github.io/react-native/docs/linking-libraries-ios.html) guide on React Native website. The `.xcodeproj` file is in `node_modules/react-native-search-bar/`. In the end, you should have `RNSearchBar.xcodeproj` in the `Libaries` group on Xcode and `libRNSearchBar.a` in the `Link Binary With Libraries` section inside the `Build Phases` tab of your project target.

## Update

In your react native project, run

```Bash
npm install react-native@latest --save # optional, just for the latest react-native
npm install react-native-search-bar@latest --save
```

## Usage

```JSX
<SearchBar
	placeholder='Search'
	onChangeText={...}
	onSearchButtonPress={...}
	onCancelButtonPress={...}
	/>
```

For all supportted propertied, please check out `propTypes` in either [SearchBar.coffee](SearchBar.coffee) or [SearchBar.js](SearchBar.js).

There is also an example project in the [SearchBarExample](SearchBarExample) directory.

## Contribution

For now, implemented are only some of the features of [UISearchBar](https://developer.apple.com/library/ios/documentation/UIKit/Reference/UISearchBar_Class/).
Feel free to send a pull request. To get started, you can read the ["Native UI Components (iOS)"](http://facebook.github.io/react-native/docs/nativecomponentsios.html) guide on React Native website.

## License

MIT


text:
A story card painter for creating a physical scrum

## I/O file format

Input: `CSV`

Output: `PDF`

### CSV rules

The input backlog file should be CSV format with 6 columns according to the order of: `ID`, `Name`, `Importance`, `Estimate`, `How to demo`, `Notes` for the stories.

Notice that the first row would be ignored as header.

## Usage

- `normal-painter.py`: 1/2 A4
- `small-painter.py`: 1/4 A4, less fields

Set I/O paths in the `main` function.


text:
static void RollingBloom(benchmark::Bench& bench)
{
    CRollingBloomFilter filter(120000, 0.000001);
    std::vector<unsigned char> data(32);
    uint32_t count = 0;
    bench.run([&] {
        count++;
        WriteLE32(data.data(), count);
        filter.insert(data);

        WriteBE32(data.data(), count);
        filter.contains(data);
    });
}

static void RollingBloomReset(benchmark::Bench& bench)
{
    CRollingBloomFilter filter(120000, 0.000001);
    bench.run([&] {
        filter.reset();
    });
}

BENCHMARK(RollingBloom, benchmark::PriorityLevel::HIGH);
BENCHMARK(RollingBloomReset, benchmark::PriorityLevel::HIGH);


text:
readonly API_RESPONSE_FILE="$RUNTIME_DIR/.api_response"

__initialize() {
  ADMIRAL_URL="http://$ADMIRAL_IP:$ADMIRAL_PORT/api"
  ADMIRAL_TOKEN=$LOGIN_TOKEN
  RESPONSE_CODE=404
  RESPONSE_DATA=""
  CURL_EXIT_CODE=0

  touch $API_RESPONSE_FILE
}

__shippable_get() {
  __initialize

  local url="$ADMIRAL_URL/$1"
  {
    RESPONSE_CODE=$(curl \
      -H "Content-Type: application/json" \
      -H "Authorization: apiToken $ADMIRAL_TOKEN" \
      -X GET $url \
      --silent --write-out "%{http_code}\n" \
      --output $API_RESPONSE_FILE)
  } || {
    CURL_EXIT_CODE=$(echo $?)
  }

  if [ $CURL_EXIT_CODE -gt 0 ]; then
    # we are assuming that if curl cmd failed, API is unavailable
    response="curl failed with error code $CURL_EXIT_CODE. API might be down."
    response_status_code=503
  else
    response_status_code="$RESPONSE_CODE"
    response=$(cat $API_RESPONSE_FILE)
  fi

  rm -f $API_RESPONSE_FILE
}

__shippable_post() {
  __initialize

  local url="$ADMIRAL_URL/$1"
  local body="$2"
  {
    RESPONSE_CODE=$(curl \
      -H "Content-Type: application/json" \
      -H "Authorization: apiToken $ADMIRAL_TOKEN" \
      -X POST $url \
      -d "$body" \
      --write-out "%{http_code}\n" \
      --silent \
      --output $API_RESPONSE_FILE)
  } || {
    CURL_EXIT_CODE=$(echo $?)
  }

  if [ $CURL_EXIT_CODE -gt 0 ]; then
    # we are assuming that if curl cmd failed, API is unavailable
    response="curl failed with error code $CURL_EXIT_CODE. API might be down."
    response_status_code=503
  else
    response_status_code="$RESPONSE_CODE"
    response=$(cat $API_RESPONSE_FILE)
  fi

  rm -f $API_RESPONSE_FILE
}

__shippable_put() {
  __initialize

  local url="$ADMIRAL_URL/$1"
  local update="$2"
  {
    RESPONSE_CODE=$(curl \
      -H "Content-Type: application/json" \
      -H "Authorization: apiToken $ADMIRAL_TOKEN" \
      -X PUT $url \
      -d "$update" \
      --write-out "%{http_code}\n" \
      --silent \
      --output $API_RESPONSE_FILE)
  } || {
    CURL_EXIT_CODE=$(echo $?)
  }

  if [ $CURL_EXIT_CODE -gt 0 ]; then
    # we are assuming that if curl cmd failed, API is unavailable
    response="curl failed with error code $CURL_EXIT_CODE. API might be down."
    response_status_code=503
  else
    response_status_code="$RESPONSE_CODE"
    response=$(cat $API_RESPONSE_FILE)
  fi

  rm -f $API_RESPONSE_FILE
}

__shippable_delete() {
  __initialize

  local url="$ADMIRAL_URL/$1"
  local body="$2"
  {
    RESPONSE_CODE=$(curl \
      -H "Content-Type: application/json" \
      -H "Authorization: apiToken $ADMIRAL_TOKEN" \
      -X DELETE $url \
      -d "$body" \
      --write-out "%{http_code}\n" \
      --silent \
      --output $API_RESPONSE_FILE)
  } || {
    CURL_EXIT_CODE=$(echo $?)
  }

  if [ $CURL_EXIT_CODE -gt 0 ]; then
    # we are assuming that if curl cmd failed, API is unavailable
    response="curl failed with error code $CURL_EXIT_CODE. API might be down."
    response_status_code=503
  else
    response_status_code="$RESPONSE_CODE"
    response=$(cat $API_RESPONSE_FILE)
  fi

  rm -f $API_RESPONSE_FILE
}

### GET

_shippable_get_admiral() {
  local admiral_get_endpoint="admiral"
  __shippable_get $admiral_get_endpoint
}

_shippable_get_secrets() {
  local secrets_get_endpoint="secrets"
  __shippable_get $secrets_get_endpoint
}

_shippable_get_msg() {
  local msg_get_endpoint="msg"
  __shippable_get $msg_get_endpoint
}

_shippable_get_state() {
  local state_get_endpoint="state"
  __shippable_get $state_get_endpoint
}

_shippable_get_redis() {
  local redis_get_endpoint="redis"
  __shippable_get $redis_get_endpoint
}

_shippable_get_systemSettings() {
  local system_settings_get_endpoint="systemSettings"
  __shippable_get $system_settings_get_endpoint
}

_shippable_get_workers() {
  local workers_get_endpoint="workers"
  __shippable_get $workers_get_endpoint
}

_shippable_get_services() {
  local service="$1"
  local services_get_endpoint="services"
  if [ "$service" != "" ]; then
    services_get_endpoint="services?name=$service"
  fi
  __shippable_get $services_get_endpoint
}

_shippable_get_db() {
  local db_get_endpoint="db"
  __shippable_get $db_get_endpoint
}

_shippable_get_secrets_status() {
  local secrets_status_get_endpoint="secrets/status"
  __shippable_get $secrets_status_get_endpoint
}

_shippable_get_masterIntegrations() {
  local query="$1"
  local masterIntegrations_get_endpoint="masterIntegrations"
  if [ "$query" != "" ]; then
    masterIntegrations_get_endpoint="masterIntegrations?$query"
  fi
  __shippable_get $masterIntegrations_get_endpoint
}

### POST
_shippable_post_db() {
  local body="{}"
  local db_post_endpoint="db"
  __shippable_post $db_post_endpoint "$body"
}

_shippable_post_cleanup() {
  local body="{}"
  local db_cleanup_endpoint="db/cleanup"
  __shippable_post $db_cleanup_endpoint "$body"
}

_shippable_post_services() {
  local body="$1"
  local db_post_endpoint="services"
  __shippable_post $db_post_endpoint "$body"
}

_shippable_post_master_cleanup() {
  local master_post_endpoint="master/cleanup"
  __shippable_post $master_post_endpoint
}

_shippable_post_worker_cleanup() {
  local body="$1"
  local worker_post_endpoint="workers/cleanup"
  __shippable_post $worker_post_endpoint "$body"
}

_shippable_post_secrets_initialize() {
  local secrets_post_initialize_endpoint="secrets/initialize"
  __shippable_post $secrets_post_initialize_endpoint
}

### PUT

_shippable_put_system_settings() {
  local systemSettingsId=1
  local update="$1"
  local system_settings_put_endpoint="systemSettings/$systemSettingsId"
  __shippable_put $system_settings_put_endpoint "$update"
}

_shippable_put_masterIntegrations() {
  local master_integration_id="$1"
  local update="$2"
  local master_integrations_put_endpoint="masterIntegrations/$master_integration_id"
  __shippable_put $master_integrations_put_endpoint "$update"
}

### DELETE
_shippable_delete_service() {
  local serviceName=$1
  local body=$2
  local service_delete_by_name_endpoint="services/$serviceName"
  __shippable_delete $service_delete_by_name_endpoint $body
}


text:
<?php

namespace TestBundle\Controller;

use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;
use TestBundle\Entity\Teacher;
use TestBundle\Form\TeacherAddType;

/**
 * @Route("/teacher")
 * Class TeacherController
 * @package TestBundle\Controller
 */
class TeacherController extends Controller
{
    /**
     * @Route("/", name="teacher/index")
     * @Template()
     */
    public function indexAction()
    {
        $maxResult = 5;
        $em = $this->getDoctrine()->getManager();
        $users = $em->getRepository('TestBundle:User')->findBy(array(), array('id' => 'DESC'), $maxResult);
        $tests = $em->getRepository('TestBundle:Test')->findBy(array(), array('id' => 'DESC'), $maxResult);
        $subjects = $em->getRepository('TestBundle:Subject')->findBy(array(), array('id' => 'DESC'), $maxResult);
        $noLimitedSubjects = $em->getRepository('TestBundle:Subject')->findAll();
        $noLimitedUsers = $em->getRepository('TestBundle:User')->findAll();

        return array(
            'users' => $users,
            'tests' => $tests,
            'subjects' => $subjects,
            'noLimitedSubjects' => $noLimitedSubjects,
            'noLimitedUsers' => $noLimitedUsers,
        );
    }

    /**
     * @Route("/register", name="teacher/add")
     * @Template()
     */
    public function addAction(Request $request)
    {
        $teacher = new Teacher();
        $form = $this->createForm(new TeacherAddType(), $teacher);
        $form->handleRequest($request);
        $factory = $this->get('security.encoder_factory');
        $encoder = $factory->getEncoder($teacher);

        if($form->isValid()) {
            $password = $encoder->encodePassword($teacher->getPassword(), $teacher->getSalt());
            $teacher->setPassword($password);
            $em = $this->getDoctrine()->getManager();
            $em->persist($teacher);
            $em->flush();

            $this->get('session')->getFlashBag()->add('success', '<b>Výborne!</b> Učiteľ bol zaregistrovaný. Teraz sa môže prihlásiť');
        }

        return array(
          'form' => $form->createView()
        );
    }

    /**
     * @Route("/directory", name="teacher/student-list")
     * @Template()
     */
    public function studentListAction()
    {
        $users = $this->getDoctrine()->getRepository('TestBundle:User')->findAll();

        return array(
            'users' => $users
        );
    }

    /**
     * @Route("/teacher-list", name="teacher/teacher-list")
     * @Template()
     */
    public function teacherListAction()
    {
        $teachers = $this->getDoctrine()->getRepository('TestBundle:Teacher')->findAll();

        return array(
            'teachers' => $teachers
        );
    }

}


text:
This check collects metrics from your YARN ResourceManager, including:

* Cluster-wide metrics: number of running apps, running containers, unhealthy nodes, etc
* Per-application metrics: app progress, elapsed running time, running containers, memory use, etc
* Node metrics: available vCores, time of last health update, etc

And more.
## Setup
### Installation

The YARN check is packaged with the Agent, so simply [install the Agent](https://app.datadoghq.com/account/settings#agent) on your YARN ResourceManager. If you need the newest version of the check, install the `dd-check-yarn` package.

### Configuration

Create a file `yarn.yaml` in the Agent's `conf.d` directory:

```
init_config:

instances:
  - resourcemanager_uri: http://localhost:8088 # or whatever your resource manager listens
    cluster_name: MyCluster # used to tag metrics, i.e. 'cluster_name:MyCluster'; default is 'default_cluster'
    collect_app_metrics: true
```

See the [example check configuration](https://github.com/DataDog/integrations-core/blob/master/yarn/conf.yaml.example) for a comprehensive list and description of all check options.

Restart the Agent to start sending YARN metrics to Datadog.

### Validation

Run the Agent's `info` subcommand and look for `yarn` under the Checks section:

```
  Checks
  ======
    [...]

    yarn
    -------
      - instance #0 [OK]
      - Collected 26 metrics, 0 events & 1 service check

    [...]
```

## Compatibility

The yarn check is compatible with all major platforms.

## Data Collected
### Metrics

See [metadata.csv](https://github.com/DataDog/integrations-core/blob/master/yarn/metadata.csv) for a list of metrics provided by this check.

### Events
The Yarn check does not include any event at this time.

### Service Checks
**yarn.can_connect**:

Returns CRITICAL if the Agent cannot connect to the ResourceManager URI to collect metrics, otherwise OK.

## Troubleshooting
Need help? Contact [Datadog Support](http://docs.datadoghq.com/help/).

## Further Reading

* [Hadoop architectural overview](https://www.datadoghq.com/blog/hadoop-architecture-overview/)
* [How to monitor Hadoop metrics](https://www.datadoghq.com/blog/monitor-hadoop-metrics/)
* [How to collect Hadoop metrics](https://www.datadoghq.com/blog/collecting-hadoop-metrics/)
* [How to monitor Hadoop with Datadog](https://www.datadoghq.com/blog/monitor-hadoop-metrics-datadog/)


text:
package com.all.browser.impl;

import static org.junit.Assert.assertEquals;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;

import java.awt.Container;
import java.awt.Rectangle;
import java.awt.event.HierarchyBoundsListener;
import java.awt.event.HierarchyEvent;

import javax.swing.JPanel;

import org.junit.Before;
import org.junit.Test;
import org.mockito.ArgumentCaptor;
import org.mockito.Captor;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.mozilla.browser.MozillaPanel;

public class TestMozillaBrowser {

	@InjectMocks
	private MozillaBrowser mozilla = new MozillaBrowser();
	@Mock
	private MozillaPanel mozillaPanel;
	@Captor
	private ArgumentCaptor<HierarchyBoundsListener> listenerCaptor;

	@Before
	public void setup() {
		MockitoAnnotations.initMocks(this);
	}

	@Test
	public void shouldGetBrowserPanel() throws Exception {
		JPanel browserPanel = mozilla.getPanel();
		assertEquals(mozillaPanel, browserPanel);
	}

	@Test
	public void shouldSetUrl() throws Exception {
		String url = "http://josdem.blogspot.com/";
		mozilla.loadUrl(url);
		verify(mozillaPanel).load(url);
	}

	@Test
	public void shouldUpdateBoundsWhenAncestorResized() throws Exception {
		mozilla.initialize();

		verify(mozillaPanel).addHierarchyBoundsListener(listenerCaptor.capture());

		HierarchyBoundsListener boundsListener = listenerCaptor.getValue();
		HierarchyEvent boundsEvent = mock(HierarchyEvent.class);
		Container container = mock(Container.class);
		when(boundsEvent.getChangedParent()).thenReturn(container);
		Rectangle bounds = mock(Rectangle.class);
		when(container.getBounds()).thenReturn(bounds);
		boundsListener.ancestorResized(boundsEvent);

		verify(mozillaPanel).setBounds(bounds);
	}

	@Test
	public void shouldReload() throws Exception {
		mozilla.refresh();
		verify(mozillaPanel).reload();
	}
}


text:
FactoryGirl.define do
  factory :hour do
    project
    category
    description ""
    value 1
    date "2014-02-26"
    user

    factory :hour_with_client do
      project { create(:project, client: create(:client)) }
    end
  end
end


text:
@interface TYMActivityIndicatorView ()

@property (nonatomic) BOOL animating;
@property (nonatomic) UIImageView *spinnerImageView;
@property (nonatomic) UIImageView *backgroundImageView;
@property (nonatomic) NSMutableDictionary *backgroundImageStorage;
@property (nonatomic) NSMutableDictionary *spinnerImageStorage;

@end

@implementation TYMActivityIndicatorView

#pragma mark - Accessors

@synthesize activityIndicatorViewStyle = _activityIndicatorViewStyle;
@synthesize animating = _animating;
@synthesize backgroundImageView = _backgroundImageView;
@synthesize backgroundImageStorage = _backgroundImageStorage;
@synthesize spinnerImageView = _spinnerImageView;
@synthesize spinnerImageStorage = _spinnerImageStorage;
@synthesize clockwise = _clockwise;
@synthesize hidesWhenStopped = _hidesWhenStopped;
@synthesize fullRotationDuration = _fullRotationDuration;
@synthesize minProgressUnit = _minProgressUnit;
@synthesize progress = _progress;

- (UIImageView *)backgroundImageView {
    if (!_backgroundImageView) {
        _backgroundImageView = [[UIImageView alloc] initWithFrame:self.bounds];
        _backgroundImageView.translatesAutoresizingMaskIntoConstraints = NO;
    }
    return _backgroundImageView;
}

- (UIImageView *)spinnerImageView {
    if (!_spinnerImageView) {
        _spinnerImageView = [[UIImageView alloc] initWithFrame:self.bounds];
        _spinnerImageView.translatesAutoresizingMaskIntoConstraints = NO;
    }
    return _spinnerImageView;
}

- (NSMutableDictionary *)backgroundImageStorage {
    if (!_backgroundImageStorage) {
        _backgroundImageStorage = [NSMutableDictionary dictionary];
    }
    return _backgroundImageStorage;
}

- (NSMutableDictionary *)spinnerImageStorage {
    if (!_spinnerImageStorage) {
        _spinnerImageStorage = [NSMutableDictionary dictionary];
    }
    return _spinnerImageStorage;
}

- (void)setBackgroundImage:(UIImage *)backgroundImage forActivityIndicatorStyle:(TYMActivityIndicatorViewStyle)style {
    [self.backgroundImageStorage setObject:backgroundImage forKey:@(style)];
}

- (UIImage *)backgroundImageForActivityIndicatorStyle:(TYMActivityIndicatorViewStyle)style {
    UIImage *backgroundImage = [self.backgroundImageStorage objectForKey:@(style)];
    if (!backgroundImage) {
        backgroundImage = [[[self class] appearance] backgroundImageForActivityIndicatorStyle:style];
    }
    return backgroundImage;
}

- (void)setSpinnerImage:(UIImage *)spinnerImage forActivityIndicatorStyle:(TYMActivityIndicatorViewStyle)style {
    [self.spinnerImageStorage setObject:spinnerImage forKey:@(style)];
}

- (UIImage *)spinnerImageForActivityIndicatorStyle:(TYMActivityIndicatorViewStyle)style {
    UIImage *spinnerImage =  [self.spinnerImageStorage objectForKey:@(style)];
    if (!spinnerImage) {
        spinnerImage = [[[self class] appearance] spinnerImageForActivityIndicatorStyle:style];
    }
    return spinnerImage;
}

- (void)setActivityIndicatorViewStyle:(TYMActivityIndicatorViewStyle)activityIndicatorViewStyle {
    _activityIndicatorViewStyle = activityIndicatorViewStyle;
    self.backgroundImageView.image = [self backgroundImageForActivityIndicatorStyle:activityIndicatorViewStyle];
    self.spinnerImageView.image = [self spinnerImageForActivityIndicatorStyle:activityIndicatorViewStyle];
}

- (BOOL)isAnimating {
    return self.animating;
}

#pragma mark - Class Methods

+ (void)initialize {
    if (self == [TYMActivityIndicatorView class]) {
        TYMActivityIndicatorView *appearance = [TYMActivityIndicatorView appearance];
        [appearance setClockwise:YES];
        [appearance setHidesWhenStopped:NO];
        [appearance setFullRotationDuration:1.0];
        [appearance setMinProgressUnit:0.01f];
        [appearance setBackgroundImage:[UIImage imageNamed:@"TYMActivityIndicatorView.bundle/background-normal"] forActivityIndicatorStyle:TYMActivityIndicatorViewStyleNormal];
        [appearance setSpinnerImage:[UIImage imageNamed:@"TYMActivityIndicatorView.bundle/spinner-normal"] forActivityIndicatorStyle:TYMActivityIndicatorViewStyleNormal];
        [appearance setBackgroundImage:[UIImage imageNamed:@"TYMActivityIndicatorView.bundle/background-small"] forActivityIndicatorStyle:TYMActivityIndicatorViewStyleSmall];
        [appearance setSpinnerImage:[UIImage imageNamed:@"TYMActivityIndicatorView.bundle/spinner-small"] forActivityIndicatorStyle:TYMActivityIndicatorViewStyleSmall];
        [appearance setBackgroundImage:[UIImage imageNamed:@"TYMActivityIndicatorView.bundle/background-large"] forActivityIndicatorStyle:TYMActivityIndicatorViewStyleLarge];
        [appearance setSpinnerImage:[UIImage imageNamed:@"TYMActivityIndicatorView.bundle/spinner-large"] forActivityIndicatorStyle:TYMActivityIndicatorViewStyleLarge];
    }
}

#pragma mark - UIView

- (id)initWithCoder:(NSCoder *)aDecoder {
    if ((self = [super initWithCoder:aDecoder])) {
        [self initialize];
    }
    return self;
}

- (id)initWithFrame:(CGRect)frame {
    if ((self = [super initWithFrame:frame])) {
        [self initialize];
    }
    return self;
}

- (id)initWithActivityIndicatorStyle:(TYMActivityIndicatorViewStyle)style {
    if ((self = [self initWithFrame:CGRectZero])) {
        self.activityIndicatorViewStyle = style;
    }
    return self;
}

- (CGSize)intrinsicContentSize {
    return [self sizeThatFits:CGSizeZero];
}

- (CGSize)sizeThatFits:(CGSize)size {
    CGSize backgroundImageSize = self.backgroundImageView.image.size;
    CGSize indicatorImageSize = self.spinnerImageView.image.size;

    return CGSizeMake(fmaxf(backgroundImageSize.width, indicatorImageSize.width), fmaxf(backgroundImageSize.height, indicatorImageSize.height));
}

#pragma mark - Public

- (void)startAnimating {
    if (self.animating) return;

    self.animating = YES;
    self.hidden = NO;
    CGFloat toValue = self.clockwise ? M_PI * 2 : -M_PI * 2;

    [self rotateView:self.spinnerImageView from:0.0 to:toValue duration:self.fullRotationDuration repeatCount:HUGE_VALF forKey:@"rotation" removeAnimationOnCompletion:NO];
}

- (void)stopAnimating {
    if (!self.animating) return;

    self.animating = NO;
    [self.spinnerImageView.layer removeAnimationForKey:@"rotation"];
    if (self.hidesWhenStopped) {
        self.hidden = YES;
    }
}

- (void)setProgress:(CGFloat)progress {
    if (progress < 0.0 || progress > 1.0) return;
    if (fabs(_progress - progress) < self.minProgressUnit) return;

    CGFloat fromValue = M_PI * 2 * _progress;
    CGFloat toValue = M_PI * 2 * progress;
    if (!self.clockwise) {
        fromValue = -fromValue;
        toValue = -toValue;
    }

    [self rotateView:self.spinnerImageView from:fromValue to:toValue duration:0.15f repeatCount:0 forKey:@"rotation" removeAnimationOnCompletion:NO];

    _progress = progress;
}

#pragma mark - Private

- (void)initialize {
    self.userInteractionEnabled = NO;
    [self addSubview:self.backgroundImageView];
    [self addSubview:self.spinnerImageView];

    [self setupViewConstraints];
}

- (void)setupViewConstraints {
    NSDictionary *views = @{
        @"backgroundImageView": self.backgroundImageView,
        @"spinnerImageView": self.spinnerImageView
    };
    [self addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|[backgroundImageView]|" options:kNilOptions metrics:nil views:views]];
    [self addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|[backgroundImageView]|" options:kNilOptions metrics:nil views:views]];
    [self addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|[spinnerImageView]|" options:kNilOptions metrics:nil views:views]];
    [self addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|[spinnerImageView]|" options:kNilOptions metrics:nil views:views]];
}

- (void)rotateView:(UIView *)view from:(CGFloat)fromValue to:(CGFloat)toValue duration:(CGFloat)duration repeatCount:(CGFloat)repeatCount forKey:(NSString *)key removeAnimationOnCompletion:(BOOL)removeOnCompletion {
    CABasicAnimation *rotationAnimation = [CABasicAnimation animation];
    rotationAnimation.keyPath = @"transform.rotation.z";
    rotationAnimation.fromValue = @(fromValue);
    rotationAnimation.toValue = @(toValue);
    rotationAnimation.duration = duration;
    rotationAnimation.repeatCount = repeatCount;
    rotationAnimation.removedOnCompletion = removeOnCompletion;
    rotationAnimation.fillMode = kCAFillModeForwards;
    [view.layer addAnimation:rotationAnimation forKey:key];
}

@end


text:
layout: default
title: Home
---
<!DOCTYPE html>

<meta charset="UTF-8">
<title>Make a Reservation</title>
<link href="jquery-ui.min.css" rel="stylesheet">
<link href="site.css" rel="stylesheet">
<link href="form.css" rel="stylesheet">

		JAVASCRIPT & jQUERY: THE MISSING MANUAL

One-Way Airlines: Let's make a reservation

			<form>

			    Pick a departure date
			    <input type="text" id="departure" name="departure">

			    Find an airport
			    <input type="text" id="airport" name="airport">

			  	Meal Options
			  	<select name="meal" id="meal">
			  		<option>No meal</option>
			  		<option>Vegan</option>
			  		<option>Gluten Free</option>
			  		<option>Vegetarian</option>
			  		<option>Meat eater</option>
			  	</select>

Number of bags to check

			    <input type="radio" id="none" name="bags" checked="checked">
      		0

      		<input type="radio" id="one" name="bags">
      		1

      		<input type="radio" id="two" name="bags">
      		2

Type of seat you'd like

          <input type="checkbox" id="aisle" name="aisle">
          Aisle

          <input type="checkbox" id="window" name="window">
          Window

          <input type="checkbox" id="exit" name="exit">
          Exit Row

          <input type="checkbox" id="any" name="any">
          Any seat

				  <button id="next">Continue reservation process</button>

			</form>

JavaScript & jQuery: The Missing Manual, 3rd Edition, by David McFarland. Published by O'Reilly Media, Inc.


text:
package io.sgr.telegram.bot.api.models;

import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;

/**
 * This object represents a parameter of the inline keyboard button used to automatically authorize a user. Serves as a great replacement for the Telegram Login
 * Widget when the user is coming from Telegram.
 *
 * @author SgrAlpha
 */
@JsonIgnoreProperties(ignoreUnknown = true)
@JsonInclude(JsonInclude.Include.NON_NULL)
public class LoginUrl {

    private final String url;
    private final String forwardText;
    private final String botUsername;
    private final Boolean requestWriteAccess;

    /**
     * @param url An HTTP URL to be opened with user authorization data added to the query string when the button is pressed. If the user refuses to provide
     * authorization data, the original URL without information about the user will be opened. The data added is the same as described in Receiving
     * authorization data.
     * @param forwardText Optional. New text of the button in forwarded messages.
     * @param botUsername Optional. Username of a bot, which will be used for user authorization. See Setting up a bot for more details. If not specified, the
     * current bot's username will be assumed. The url's domain must be the same as the domain linked with the bot. See Linking your domain to the bot for more
     * details.
     * @param requestWriteAccess Optional. Pass True to request the permission for your bot to send messages to the user.
     */
    @JsonCreator
    public LoginUrl(
            @JsonProperty("url") final String url,
            @JsonProperty("forward_text") final String forwardText,
            @JsonProperty("bot_username") final String botUsername,
            @JsonProperty("request_write_access") final Boolean requestWriteAccess
    ) {
        this.url = url;
        this.forwardText = forwardText;
        this.botUsername = botUsername;
        this.requestWriteAccess = requestWriteAccess;
    }

    @JsonProperty("url")
    public String getUrl() {
        return url;
    }

    @JsonProperty("forward_text")
    public String getForwardText() {
        return forwardText;
    }

    @JsonProperty("bot_username")
    public String getBotUsername() {
        return botUsername;
    }

    @JsonProperty("request_write_access")
    public Boolean getRequestWriteAccess() {
        return requestWriteAccess;
    }
}


text:
package v2

import (
	"encoding/json"
	"net/http"

	"github.com/SpectoLabs/hoverfly/core/handlers"
	"github.com/SpectoLabs/hoverfly/core/metrics"
	"github.com/codegangsta/negroni"
	"github.com/go-zoo/bone"
)

type Hoverfly interface {
	GetDestination() string
	GetMiddleware() (string, string, string)
	GetMode() string
	GetStats() metrics.Stats
	GetVersion() string
	GetUpstreamProxy() string
}

type HoverflyHandler struct {
	Hoverfly Hoverfly
}

func (this *HoverflyHandler) RegisterRoutes(mux *bone.Mux, am *handlers.AuthHandler) {
	mux.Get("/api/v2/hoverfly", negroni.New(
		negroni.HandlerFunc(am.RequireTokenAuthentication),
		negroni.HandlerFunc(this.Get),
	))
}

func (this *HoverflyHandler) Get(w http.ResponseWriter, req *http.Request, next http.HandlerFunc) {
	var hoverflyView HoverflyView

	hoverflyView.Destination = this.Hoverfly.GetDestination()
	hoverflyView.Mode = this.Hoverfly.GetMode()
	hoverflyView.Binary, hoverflyView.Script, hoverflyView.Remote = this.Hoverfly.GetMiddleware()
	hoverflyView.Usage = this.Hoverfly.GetStats()
	hoverflyView.Version = this.Hoverfly.GetVersion()
	hoverflyView.UpstreamProxy = this.Hoverfly.GetUpstreamProxy()

	bytes, _ := json.Marshal(hoverflyView)

	handlers.WriteResponse(w, bytes)
}


text:
@implementation ESAddressLookupOperation

NSString * const isExecutingName = @"isExecuting";
NSString * const isFinishedName = @"isFinished";

- (instancetype) initWithPeople:(NSArray *)people {
	self = [super initWithPeople:people];
	if (self) {
		executing = NO;
		finished = NO;
		_addressesToLookup = [NSMutableArray array];
	}
	return self;
}

# pragma mark Run the Operation asynchronously

- (void) start {
	if (self.isCancelled) {
		[self cancelOperation];
		return;
	}

	// If the operation is not cancelled, begin executing the task.
	[self willChangeValueForKey:isExecutingName];
	[self main];
	executing = YES;
	[self didChangeValueForKey:isExecutingName];
}

- (void) cancelOperation {
	self.statusMessage = NSLocalizedString(@"Address lookup cancelled", @"Status message for cancelled address lookup.");
	[self.addressesToLookup removeAllObjects];

	[self willChangeValueForKey:isFinishedName];
	finished = YES;
	[self didChangeValueForKey:isFinishedName];
}

- (void) main {
	self.progress = .000001;

	ABPerson * myPerson;
	self.previousLookup = 0;
	self.secondsBetweenCoordinateLookups = ((NSNumber *)[[NSUserDefaultsController sharedUserDefaultsController] valueForKeyPath:@"values.secondsBetweenCoordinateLookups"]).doubleValue;

	[self fillAddressesToLookup];
	[self processNextAddress];
}

- (void) completeOperation {
	[self willChangeValueForKey:isFinishedName];
	[self willChangeValueForKey:isExecutingName];
	executing = NO;
	finished = YES;
	[self didChangeValueForKey:isExecutingName];
	[self didChangeValueForKey:isFinishedName];
}

#pragma mark Address lookup

- (void) fillAddressesToLookup {
	for (ABPerson * person in self.people) {
		ABMultiValue * personAddresses = [person valueForProperty:kABAddressProperty];
		NSUInteger addressCount = [personAddresses count];

		for (NSUInteger addressIndex = 0; addressIndex < addressCount; addressIndex++) {
			NSDictionary * addressDict = [self.addressHelper normaliseAddress:[personAddresses valueAtIndex:addressIndex]];
			NSString * addressString = [self.addressHelper keyForAddress:addressDict];
			if (!self.locations[addressString] && !self.failLocations[addressString]) {
				// This address has not been looked up yet.
				[self.addressesToLookup addObject:addressDict];
			}
		}
	}
}

- (void) processNextAddress {
	if (self.isCancelled) {
		[self cancelOperation];
	}

	if (self.addressesToLookup.count > 0) {
		// Take the first address from the list and look it up.
		NSDictionary * addressDict = self.addressesToLookup[0];
		[self.addressesToLookup removeObjectAtIndex:0];
		[self geocodeAddress:addressDict];
	}
	else {
		// If there are no addresses left, finish the operation.
		[self completeOperation];
	}
}

- (void) geocodeAddress:(NSDictionary *)addressDict {
	NSString * addressString = [self.addressHelper keyForAddress:addressDict];
	NSString * displayString = [[ABAddressBook sharedAddressBook] formattedAddressFromDictionary:addressDict].string;
	displayString = [displayString stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
	displayString = [displayString stringByReplacingOccurrencesOfString:@"\n\\s*" withString:@", " options:NSRegularExpressionSearch range:NSMakeRange(0, displayString.length)];
	self.statusMessage = [NSString stringWithFormat:NSLocalizedString(@"Looking up: %@", @"Status message for address lookup with current address."), displayString];

	// throttle queries
	if (self.previousLookup != 0) {
		NSDate * wakeUpTime = [NSDate dateWithTimeIntervalSinceReferenceDate:self.previousLookup + self.secondsBetweenCoordinateLookups];
		[NSThread sleepUntilDate:wakeUpTime];
	}
	self.previousLookup = [NSDate timeIntervalSinceReferenceDate];

	self.geocoder = [[CLGeocoder alloc] init];
	[self.geocoder geocodeAddressDictionary:addressDict completionHandler:^(NSArray * placemarks, NSError * lookupError) {
		if (placemarks.count == 1) {
			CLPlacemark * placemark = placemarks[0];
			CLLocation * location = placemark.location;
			self.locations[addressString] = @{
				@"lat": @(location.coordinate.latitude),
				@"lon": @(location.coordinate.longitude),
				@"accuracy": @(location.horizontalAccuracy),
				@"timestamp": @(location.timestamp.timeIntervalSince1970),
				@"resultType": @"unique"
			};
		}
		else if (placemarks.count > 1) {
			NSMutableArray * locationStrings = [NSMutableArray array];
			[placemarks enumerateObjectsUsingBlock:^(CLPlacemark * placemark, NSUInteger idx, BOOL * stop) {
				[locationStrings addObject:placemark.location.description];
			}];
			NSDictionary * failInfo = @{
				@"type": @"multiple",
				@"locations": locationStrings
			};
			self.failLocations[addressString] = failInfo;
		}
		else {
			if (lookupError && !self.isCancelled) {
				if (lookupError.domain == kCLErrorDomain && lookupError.code == kCLErrorNetwork) {
					// Network problem
					self.statusMessage = NSLocalizedString(@"Network error. Will attempt to look this address up the next time.", @"Error message shown when address lookup failed with a netork error.");
				}
				else {
					NSDictionary * errorInfo = @{
						@"type": @"error",
						@"domain": lookupError.domain,
						@"code": @(lookupError.code)
					};
					self.failLocations[addressString] = errorInfo;
					self.statusMessage = [NSString stringWithFormat:NSLocalizedString(@"Lookup failed for: %@", @"Error message shown when address lookup failed."), addressString];
				}
			}
		}

		self.progress += 1;
		self.geocoder = nil;

		[self processNextAddress];
	}];
}

#pragma mark KVO

- (BOOL) isExecuting {
	return executing;
}

- (BOOL) isFinished {
	return finished;
}

@end


text:
<?php

/**
 * @file
 * Contains \Drupal\Console\Utils\Create\VocabularyData.
 */

namespace Drupal\Console\Utils\Create;

use Drupal\Component\Utility\Unicode;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\Core\Entity\EntityFieldManagerInterface;
use Drupal\Core\Datetime\DateFormatterInterface;
use Drupal\Core\Language\LanguageInterface;

/**
 * Class Vocabularies
 *
 * @package Drupal\Console\Utils
 */
class VocabularyData extends Base
{
    /**
     * Create and returns an array of new Vocabularies.
     *
     * @param $limit
     * @param $nameWords
     *
     * @return array
     */
    public function create(
        $limit,
        $nameWords
    ) {
        $vocabularies = [];
        for ($i = 0; $i < $limit; $i++) {
            try {
                // Create a vocabulary.
                $vocabulary = $this->entityTypeManager->getStorage('taxonomy_vocabulary')->create(
                    [
                        'name' => $this->getRandom()->sentences(mt_rand(1, $nameWords), true),
                        'description' => $this->getRandom()->sentences(mt_rand(1, $nameWords)),
                        'vid' => Unicode::strtolower($this->getRandom()->name()),
                        'langcode' => LanguageInterface::LANGCODE_NOT_SPECIFIED,
                        'weight' => mt_rand(0, 10),
                    ]
                );
                $vocabulary->save();
                $vocabularies['success'][] = [
                    'vid' => $vocabulary->id(),
                    'vocabulary' => $vocabulary->get('name'),
                ];
            } catch (\Exception $error) {
                $vocabularies['error'][] = $error->getMessage();
            }
        }

        return $vocabularies;
    }
}


text:
Bots allow you to

* Send content into and out of Zulip.
* Send content to and from another product.
* Automate tasks a human user could do.

A bot that sends content to or from another product is often called an
**integration**.

### Pre-made bots

Zulip natively supports integrations with over one hundred products, and with
almost a thousand more through Zapier and IFTTT. If you're looking to add an
integration with an existing product, see our
[list of integrations](/integrations), along with those of
[Zapier](https://zapier.com/apps) and [IFTTT](https://ifttt.com/search).

## Anatomy of a bot

You can think of a bot as a special kind of user, with limited permissions.
Each bot has a **name**, **profile picture**, **email**, **bot type** and **API key**.

* The **name** and **profile picture** play the same role they do for human users. They
are the most visible attributes of a bot.

* The **email** is not used for anything, and will likely be removed in a
future version of Zulip.

* The **bot type** determines what the bot can and can't do (see below).

* The **API key** is how the bot identifies itself to Zulip. Anyone with the
  bot's API key can impersonate the bot.

## Bot type

The **bot type** determines what the bot can do.

Bot type | Permissions | Common uses
---|---|---
Incoming webhook | Send messages into Zulip | Third party integrations
Outgoing webhook | Send messages into Zulip, read messages where the bot is addressed | Third party integrations, most custom bots
Generic | Anything the bot creator can do | Automating tasks, bots that listen to all messages on a stream
API super bot (self-hosted only) | Anything any user can do | Mirroring

It's generally best to pick the most restricted bot type that is sufficient
to do the task at hand. Anyone with the bot's API key can do anything the
bot can.

A few more details:

* **Outgoing webhook**: The bot can read private messages where the bot is a
  participant, and stream messages where the bot is [mentioned](/help/mention-a-user-or-group). When the
  bot is PM'd or mentioned, it POSTs the message content to a URL of your
  choice. The POST request format can be in a Zulip format or a
  Slack-compatible format.

    This is the preferred bot type for interactive bots built on top of Zulip
    botserver.

* **Generic**: Note that if you truly want to impersonate yourself
  (e.g. write messages that come from you, rather than from a look-a-like),
  you'll need to use your **personal API key**.

* **API super bot**: You cannot create this from the web interface.
  [Contact us](/help/contact-support) if you'd like information on how to set this up.

## Adding bots

By default, anyone other than guests can [add a bot](/help/add-a-bot-or-integration) to a
Zulip organization, but administrators can
[restrict bot creation](/help/restrict-bot-creation). Any bot that is added
is visible and available for anyone to use.


text:
namespace LiteCppDB
{
	// Implement a Index service - Add/Remove index nodes on SkipList
	// Based on: http://igoro.com/archive/skip-lists-are-fascinating/
	class IndexService
	{
	private:
		PageService _pager;
		Logger _log;
		//Random _rand = Random();

	public:
		// Max size of a index entry - usde for string, binary, array and documents
		const int32_t MAX_INDEX_LENGTH = 512;

		IndexService() noexcept;
		virtual ~IndexService() noexcept {};

		IndexService(const IndexService& src) noexcept;
		virtual IndexService& operator=(const IndexService& rhs) noexcept;

		IndexService(const IndexService&& src) noexcept;
		virtual IndexService& operator=(IndexService&& rhs) noexcept;

		IndexService(PageService pager, Logger log) noexcept;

		// Create a new index and returns head page address (skip list)
		CollectionIndex CreateIndex(CollectionPage col) noexcept;

		// Insert a new node index inside an collection index. Flip coin to know level
		IndexNode AddNode(CollectionIndex index, BsonValue key, IndexNode last);

	private:
		// Insert a new node index inside an collection index.
		IndexNode AddNode(CollectionIndex index, BsonValue key, uint8_t level, IndexNode last);

		// Gets all node list from any index node (go forward and backward)
		std::vector<IndexNode> GetNodeList(IndexNode node, bool includeInitial) noexcept;

		// Deletes an indexNode from a Index and adjust Next/Prev nodes
		void Delete(CollectionIndex index, PageAddress nodeAddress) noexcept;

		// Drop all indexes pages. Each index use a single page sequence
		void DropIndex(CollectionIndex index) noexcept;

		// Get a node inside a page using PageAddress - Returns null if address IsEmpty
		IndexNode GetNode(PageAddress address);

		// Flip coin - skip list - returns level node (start in 1)
		uint8_t FlipCoin() noexcept;

	public:

#pragma region Find

		std::vector<IndexNode> FindAll(CollectionIndex index, int order) noexcept;

		// Find first node that index match with value. If not found but sibling = true, returns near node (only non-unique index)
		// Before find, value must be normalized
		IndexNode Find(CollectionIndex index, BsonValue value, bool sibling, int order);

	private:
		// Goto the first/last occurrence of this index value
		IndexNode FindBoundary(CollectionIndex index, IndexNode cur, BsonValue value, int order, int level);

#pragma endregion Find
	};
}