text:
{-# LANGUAGE CPP, ForeignFunctionInterface #-}

module Network.Wai.Handler.Warp.SendFile (
    sendFile
  , readSendFile
  , packHeader -- for testing
#ifndef WINDOWS
  , positionRead
#endif
  ) where

import Control.Monad (void)
import Data.ByteString (ByteString)
import qualified Data.ByteString as BS
import Network.Socket (Socket)
import Network.Wai.Handler.Warp.Buffer
import Network.Wai.Handler.Warp.Types

#ifdef WINDOWS
import Control.Monad (when)
import Data.ByteString.Internal (ByteString(..))
import Foreign.ForeignPtr (newForeignPtr_)
import Foreign.Ptr (plusPtr)
import qualified System.IO as IO
#else
# if __GLASGOW_HASKELL__ < 709
import Control.Applicative ((<$>))
# endif
import Control.Exception
import Foreign.C.Types
import Foreign.Ptr (Ptr, castPtr, plusPtr)
import Network.Sendfile
import System.Posix.IO (openFd, OpenFileFlags(..), defaultFileFlags, OpenMode(ReadOnly), closeFd)
import System.Posix.Types
#endif

----------------------------------------------------------------

-- | Function to send a file based on sendfile() for Linux\/Mac\/FreeBSD.
--   This makes use of the file descriptor cache.
--   For other OSes, this is identical to 'readSendFile'.
--
-- Since: 3.1.0
sendFile :: Socket -> Buffer -> BufSize -> (ByteString -> IO ()) -> SendFile
#ifdef SENDFILEFD
sendFile s _ _ _ fid off len act hdr = case mfid of
    -- settingsFdCacheDuration is 0
    Nothing -> sendfileWithHeader   s path (PartOfFile off len) act hdr
    Just fd -> sendfileFdWithHeader s fd   (PartOfFile off len) act hdr
  where
    mfid = fileIdFd fid
    path = fileIdPath fid
#else
sendFile _ = readSendFile
#endif

----------------------------------------------------------------

packHeader :: Buffer -> BufSize -> (ByteString -> IO ())
           -> IO () -> [ByteString]
           -> Int
           -> IO Int
packHeader _   _   _    _    [] n = return n
packHeader buf siz send hook (bs:bss) n
  | len < room = do
      let dst = buf `plusPtr` n
      void $ copy dst bs
      packHeader buf siz send hook bss (n + len)
  | otherwise  = do
      let dst = buf `plusPtr` n
          (bs1, bs2) = BS.splitAt room bs
      void $ copy dst bs1
      bufferIO buf siz send
      hook
      packHeader buf siz send hook (bs2:bss) 0
  where
    len = BS.length bs
    room = siz - n

mini :: Int -> Integer -> Int
mini i n
  | fromIntegral i < n = i
  | otherwise          = fromIntegral n

-- | Function to send a file based on pread()\/send() for Unix.
--   This makes use of the file descriptor cache.
--   For Windows, this is emulated by 'Handle'.
--
-- Since: 3.1.0
#ifdef WINDOWS
readSendFile :: Buffer -> BufSize -> (ByteString -> IO ()) -> SendFile
readSendFile buf siz send fid off0 len0 hook headers = do
    hn <- packHeader buf siz send hook headers 0
    let room = siz - hn
        buf' = buf `plusPtr` hn
    IO.withBinaryFile path IO.ReadMode $ \h -> do
        IO.hSeek h IO.AbsoluteSeek off0
        n <- IO.hGetBufSome h buf' (mini room len0)
        bufferIO buf (hn + n) send
        hook
        let n' = fromIntegral n
        fptr <- newForeignPtr_ buf
        loop h fptr (len0 - n')
  where
    path = fileIdPath fid
    loop h fptr len
      | len <= 0  = return ()
      | otherwise = do
        n <- IO.hGetBufSome h buf (mini siz len)
        when (n /= 0) $ do
            let bs = PS fptr 0 n
                n' = fromIntegral n
            send bs
            hook
            loop h fptr (len - n')
#else
readSendFile :: Buffer -> BufSize -> (ByteString -> IO ()) -> SendFile
readSendFile buf siz send fid off0 len0 hook headers =
  bracket setup teardown $ \fd -> do
    hn <- packHeader buf siz send hook headers 0
    let room = siz - hn
        buf' = buf `plusPtr` hn
    n <- positionRead fd buf' (mini room len0) off0
    bufferIO buf (hn + n) send
    hook
    let n' = fromIntegral n
    loop fd (len0 - n') (off0 + n')
  where
    path = fileIdPath fid
    setup = case fileIdFd fid of
       Just fd -> return fd
       Nothing -> openFd path ReadOnly Nothing defaultFileFlags{nonBlock=True}
    teardown fd = case fileIdFd fid of
       Just _  -> return ()
       Nothing -> closeFd fd
    loop fd len off
      | len <= 0  = return ()
      | otherwise = do
          n <- positionRead fd buf (mini siz len) off
          bufferIO buf n send
          let n' = fromIntegral n
          hook
          loop fd (len - n') (off + n')

positionRead :: Fd -> Buffer -> BufSize -> Integer -> IO Int
positionRead fd buf siz off =
    fromIntegral <$> c_pread fd (castPtr buf) (fromIntegral siz) (fromIntegral off)

foreign import ccall unsafe "pread"
  c_pread :: Fd -> Ptr CChar -> ByteCount -> FileOffset -> IO CSsize
#endif


text:
"use strict";
var path = require('path');
var webpack_1 = require('@ngtools/webpack');
var g = global;
var webpackLoader = g['angularCliIsLocal']
    ? g.angularCliPackages['@ngtools/webpack'].main
    : '@ngtools/webpack';
exports.getWebpackNonAotConfigPartial = function (projectRoot, appConfig) {
    return {
        module: {
            rules: [
                {
                    test: /\.ts$/,
                    loader: webpackLoader,
                    exclude: [/\.(spec|e2e)\.ts$/]
                }
            ]
        },
        plugins: [
            new webpack_1.AotPlugin({
                tsConfigPath: path.resolve(projectRoot, appConfig.root, appConfig.tsconfig),
                mainPath: path.join(projectRoot, appConfig.root, appConfig.main),
                exclude: [
                    path.join(projectRoot, appConfig.root, appConfig.test),
                    '**/*.spec.ts'
                ],
                skipCodeGeneration: true
            }),
        ]
    };
};
exports.getWebpackAotConfigPartial = function (projectRoot, appConfig, i18nFile, i18nFormat, locale) {
    return {
        module: {
            rules: [
                {
                    test: /\.ts$/,
                    loader: webpackLoader,
                    exclude: [/\.(spec|e2e)\.ts$/]
                }
            ]
        },
        plugins: [
            new webpack_1.AotPlugin({
                tsConfigPath: path.resolve(projectRoot, appConfig.root, appConfig.tsconfig),
                mainPath: path.join(projectRoot, appConfig.root, appConfig.main),
                i18nFile: i18nFile,
                i18nFormat: i18nFormat,
                locale: locale,
                exclude: [
                    path.join(projectRoot, appConfig.root, appConfig.test),
                    '**/*.spec.ts'
                ]
            })
        ]
    };
};
//# sourceMappingURL=/Users/hans/Sources/angular-cli/packages/angular-cli/models/webpack-build-typescript.js.map

redpajama_set_name: RedPajamaGithub


text:
layout: posts_by_tag
tag: mistake
permalink: mistake/
---


text:
namespace PSim {

struct systemState {
	int nParticles;
	double concentration;
	int boxSize;
	int cellSize;
	int cellScale;
	double temp;
	double currentTime;
	double dTime;
	int seed;
	int outputFreq;
	double endTime;
};

}
#endif // SYSTEM_STATE_H


text:
<?php
//author: Bao

//class for login, logout, sign up, google login, forget password
class Account {
    private $db;

    //Get db string
    public function __construct($db) {
        $this->db = $db;
    }

    //search all account related to one email address
    public function searchEmails($email) {
        //search all accounts with same email
        $query = 'SELECT * FROM user WHERE user_email = :email';
        $pdostmt = $this->db->prepare($query);
        $pdostmt->bindValue(':email', $email, PDO::PARAM_STR);
        $pdostmt->execute();
        return $pdostmt->fetchAll(PDO::FETCH_ASSOC);
    }

    //change email valid field to valid for valid email page
    public function validEmail($email, $name) {
        $uQuery = 'Update user SET email_valid = 1 WHERE user_name = :username AND user_email = :email';
        try {
            $uPdostmt = $this->db->prepare($uQuery);
            $uPdostmt->bindValue(':username', $name, PDO::PARAM_STR);
            $uPdostmt->bindValue(':email', $email, PDO::PARAM_STR);
            $this->db->beginTransaction();
            $uPdostmt->execute();
            $this->db->commit();
            return '1';
        } catch(PDOExecption $e) {
            $this->db->rollback();
            return '0';
        }
    }

    //create a record for success signup before email valid
    public function createRecord($name, $password, $email, $reg, $encrypted, $google) {
        //create new row into user
        $upQuery = 'INSERT INTO user (user_name, user_password, user_email, user_reg, accept_term, email_valid, google_id)
                    VALUES (:name, :password, :email, :reg, 1, :valid, :google)';
        try {
            $upPdostmt = $this->db->prepare($upQuery);
            $upPdostmt->bindValue(':name', $name, PDO::PARAM_STR);
            $upPdostmt->bindValue(':password', $password, PDO::PARAM_STR);
            $upPdostmt->bindValue(':email', $email, PDO::PARAM_STR);
            $upPdostmt->bindValue(':reg', $reg);
            $upPdostmt->bindValue(':valid', $encrypted, PDO::PARAM_STR);
            $upPdostmt->bindValue(':google', $google);
            $this->db->beginTransaction();
            $upPdostmt->execute();
            $id = $this->db->lastInsertId();
            $this->db->commit();
            return $id;
        } catch(PDOExecption $e) {
            $this->db->rollback();
            return '0';
        }
    }

    //delete all related record for one email address
    public function deleteRecord($email) {
        $delQuery = 'DELETE FROM user WHERE user_email = :email';
        try {
            $delPdostmt = $this->db->prepare($delQuery);
            $delPdostmt->bindValue(':email', $email, PDO::PARAM_STR);
            $this->db->beginTransaction();
            $delPdostmt->execute();
            $this->db->commit();
            return '1';
        } catch(PDOExecption $e) {
            $this->db->rollback();
            return '0';
        }
    }

    //insert into user detail for valid account
    public function createDetail($id, $name, $reg, $image) {
        $sQuery = 'INSERT INTO user_details (user_id, first_name, joined_on, image_src)
                              VALUES (:user_id, :first_name, :joined_on, :image_src)';
        try {
            $PDOStmt2 = $this->db->prepare($sQuery);
            $PDOStmt2->bindValue(':user_id', $id, PDO::PARAM_INT);
            $PDOStmt2->bindValue(':first_name', $name, PDO::PARAM_STR);
            $PDOStmt2->bindValue(':joined_on', $reg);
            $PDOStmt2->bindValue(':image_src', $image, PDO::PARAM_STR);
            $this->db->beginTransaction();
            $PDOStmt2->execute();
            $this->db->commit();
            return '1';
        } catch(PDOExecption $e) {
            $this->db->rollback();
            return '0';
        }
    }

    //link google id with current account
    public function linkGoogle($id, $email) {
        $query1 = 'UPDATE user SET google_id = :google WHERE user_email = :email AND email_valid = 1';
        try {
            $pdostmt1 = $this->db->prepare($query1);
            $pdostmt1->bindValue(':google', $id, PDO::PARAM_INT);
            $pdostmt1->bindValue(':email', $email, PDO::PARAM_STR);
            $this->db->beginTransaction();
            $pdostmt1->execute();
            $this->db->commit();
        } catch(PDOExecption $e) {
            $this->db->rollback();
        }
    }

    //active cookie if user want and login success
    public function activeCookie($email, $string) {
        $query = 'UPDATE user SET cookie_token = :token WHERE user_email = :email';
        try {
            $pdostmt = $this->db->prepare($query);
            $pdostmt->bindValue(':email', $email, PDO::PARAM_STR);
            $pdostmt->bindValue(':token', $string, PDO::PARAM_STR);
            $this->db->beginTransaction();
            $pdostmt->execute();
            $this->db->commit();
            if ($pdostmt->rowCount() == 1) {
                $expire = new DateTime('+1 month');
                setcookie('token', $string, $expire->getTimestamp(), '/', 'localhost', false, true);
            }
        } catch(PDOExecption $e) {
            $this->db->rollback();
        }
    }

    //use cookie to login user
    public function checkCookie($token) {
        $query = 'SELECT user_id, user_name FROM user WHERE cookie_token = :token';
        try {
            $pdostmt = $this->db->prepare($query);
            $pdostmt->bindValue(':token', $token, PDO::PARAM_STR);
            $pdostmt->execute();
            $result = $pdostmt->fetchAll(PDO::FETCH_ASSOC);
            //when record exist, return result
            if ($pdostmt->rowCount() == 1) {
                return $result[0];
            } else {
                return false;
            }
        } catch(PDOExecption $e) {
            return false;
        }
    }

    //create forget token for user find password back
    public function setForget($token, $email) {
        $query1 = 'UPDATE user SET forget_token = :string WHERE user_email = :email';
        try {
            $pdostmt1 = $this->db->prepare($query1);
            $pdostmt1->bindValue(':string', $token, PDO::PARAM_STR);
            $pdostmt1->bindValue(':email', $email, PDO::PARAM_STR);
            $this->db->beginTransaction();
            $pdostmt1->execute();
            $this->db->commit();
            return '1';
        } catch(PDOExecption $e) {
            $this->db->rollback();
            return '0';
        }
    }

    //retrieve password
    public function retrievePass($email, $password, $token){
        $query = 'UPDATE user SET user_password = :password, forget_token = NULL WHERE user_email = :email AND forget_token = :token';
        try {
            $pdostmt = $this->db->prepare($query);
            $pdostmt->bindValue(':password', $password, PDO::PARAM_STR);
            $pdostmt->bindValue(':email', $email, PDO::PARAM_STR);
            $pdostmt->bindValue(':token', $token, PDO::PARAM_STR);
            $this->db->beginTransaction();
            $pdostmt->execute();
            $this->db->commit();
            return '1';
        } catch(PDOExecption $e) {
            $this->db->rollback();
            return '0';
        }
    }

}


text:
package pilosa_test

import (
	"context"
	"io"
	"io/ioutil"
	"net/http"
	"strings"
	"testing"
	"time"

	"github.com/pilosa/pilosa"
	"github.com/pilosa/pilosa/test"
)

// TestMultiStatClient_Expvar run the multistat client with exp var
// since the EXPVAR data is stored in a global we should run these in one test function
func TestMultiStatClient_Expvar(t *testing.T) {
	hldr := test.MustOpenHolder()
	defer hldr.Close()

	c := pilosa.NewExpvarStatsClient()
	ms := make(pilosa.MultiStatsClient, 1)
	ms[0] = c
	hldr.Stats = ms

	hldr.Stats.SetLogger(ioutil.Discard)
	hldr.MustCreateFragmentIfNotExists("d", "f", pilosa.ViewStandard, 0).SetBit(0, 0)
	hldr.MustCreateFragmentIfNotExists("d", "f", pilosa.ViewStandard, 0).SetBit(0, 1)
	hldr.MustCreateFragmentIfNotExists("d", "f", pilosa.ViewStandard, 1).SetBit(0, SliceWidth)
	hldr.MustCreateFragmentIfNotExists("d", "f", pilosa.ViewStandard, 1).SetBit(0, SliceWidth+2)
	hldr.MustCreateFragmentIfNotExists("d", "f", pilosa.ViewStandard, 0).ClearBit(0, 1)

	if pilosa.Expvar.String() != `{"index:d": {"frame:f": {"view:standard": {"slice:0": {"clearBit": 1, "rows": 0, "setBit": 2}, "slice:1": {"rows": 0, "setBit": 2}}}}}` {
		t.Fatalf("unexpected expvar : %s", pilosa.Expvar.String())
	}

	hldr.Stats.CountWithCustomTags("cc", 1, 1.0, []string{"foo:bar"})
	if pilosa.Expvar.String() != `{"cc": 1, "index:d": {"frame:f": {"view:standard": {"slice:0": {"clearBit": 1, "rows": 0, "setBit": 2}, "slice:1": {"rows": 0, "setBit": 2}}}}}` {
		t.Fatalf("unexpected expvar : %s", pilosa.Expvar.String())
	}

	// Gauge creates a unique key, subsequent Gauge calls will overwrite
	hldr.Stats.Gauge("g", 5, 1.0)
	hldr.Stats.Gauge("g", 8, 1.0)
	if pilosa.Expvar.String() != `{"cc": 1, "g": 8, "index:d": {"frame:f": {"view:standard": {"slice:0": {"clearBit": 1, "rows": 0, "setBit": 2}, "slice:1": {"rows": 0, "setBit": 2}}}}}` {
		t.Fatalf("unexpected expvar : %s", pilosa.Expvar.String())
	}

	// Set creates a unique key, subsequent sets will overwrite
	hldr.Stats.Set("s", "4", 1.0)
	hldr.Stats.Set("s", "7", 1.0)
	if pilosa.Expvar.String() != `{"cc": 1, "g": 8, "index:d": {"frame:f": {"view:standard": {"slice:0": {"clearBit": 1, "rows": 0, "setBit": 2}, "slice:1": {"rows": 0, "setBit": 2}}}}, "s": "7"}` {
		t.Fatalf("unexpected expvar : %s", pilosa.Expvar.String())
	}

	// Record timing duration and a uniquely Set key/value
	dur, _ := time.ParseDuration("123us")
	hldr.Stats.Timing("tt", dur, 1.0)
	if pilosa.Expvar.String() != `{"cc": 1, "g": 8, "index:d": {"frame:f": {"view:standard": {"slice:0": {"clearBit": 1, "rows": 0, "setBit": 2}, "slice:1": {"rows": 0, "setBit": 2}}}}, "s": "7", "tt": 123µs}` {
		t.Fatalf("unexpected expvar : %s", pilosa.Expvar.String())
	}

	// Expvar histogram is implemented as a gauge
	hldr.Stats.Histogram("hh", 3, 1.0)
	if pilosa.Expvar.String() != `{"cc": 1, "g": 8, "hh": 3, "index:d": {"frame:f": {"view:standard": {"slice:0": {"clearBit": 1, "rows": 0, "setBit": 2}, "slice:1": {"rows": 0, "setBit": 2}}}}, "s": "7", "tt": 123µs}` {
		t.Fatalf("unexpected expvar : %s", pilosa.Expvar.String())
	}

	// Expvar should ignore earlier set tags from setbit
	if hldr.Stats.Tags() != nil {
		t.Fatalf("unexpected tag")
	}
}

func TestStatsCount_TopN(t *testing.T) {
	hldr := test.MustOpenHolder()
	defer hldr.Close()

	hldr.MustCreateFragmentIfNotExists("d", "f", pilosa.ViewStandard, 0).SetBit(0, 0)
	hldr.MustCreateFragmentIfNotExists("d", "f", pilosa.ViewStandard, 0).SetBit(0, 1)
	hldr.MustCreateFragmentIfNotExists("d", "f", pilosa.ViewStandard, 1).SetBit(0, SliceWidth)
	hldr.MustCreateFragmentIfNotExists("d", "f", pilosa.ViewStandard, 1).SetBit(0, SliceWidth+2)

	// Execute query.
	called := false
	e := test.NewExecutor(hldr.Holder, test.NewCluster(1))
	e.Holder.Stats = &MockStats{
		mockCountWithTags: func(name string, value int64, rate float64, tags []string) {
			if name != "TopN" {
				t.Errorf("Expected TopN, Results %s", name)
			}

			if tags[0] != "index:d" {
				t.Errorf("Expected db, Results %s", tags[0])
			}

			called = true
			return
		},
	}
	if _, err := e.Execute(context.Background(), "d", test.MustParse(`TopN(frame=f, n=2)`), nil, nil); err != nil {
		t.Fatal(err)
	}
	if !called {
		t.Error("CountWithCustomTags name isn't called")
	}
}

func TestStatsCount_Bitmap(t *testing.T) {
	hldr := test.MustOpenHolder()
	defer hldr.Close()

	hldr.MustCreateFragmentIfNotExists("d", "f", pilosa.ViewStandard, 0).SetBit(0, 0)
	hldr.MustCreateFragmentIfNotExists("d", "f", pilosa.ViewStandard, 0).SetBit(0, 1)
	called := false
	e := test.NewExecutor(hldr.Holder, test.NewCluster(1))
	e.Holder.Stats = &MockStats{
		mockCountWithTags: func(name string, value int64, rate float64, tags []string) {
			if name != "Bitmap" {
				t.Errorf("Expected Bitmap, Results %s", name)
			}

			if tags[0] != "index:d" {
				t.Errorf("Expected db, Results %s", tags[0])
			}

			called = true
			return
		},
	}
	if _, err := e.Execute(context.Background(), "d", test.MustParse(`Bitmap(frame=f, rowID=0)`), nil, nil); err != nil {
		t.Fatal(err)
	}
	if !called {
		t.Error("CountWithCustomTags name isn't called")
	}
}

func TestStatsCount_SetBitmapAttrs(t *testing.T) {
	hldr := test.MustOpenHolder()
	defer hldr.Close()

	hldr.MustCreateFragmentIfNotExists("d", "f", pilosa.ViewStandard, 0).SetBit(10, 0)
	hldr.MustCreateFragmentIfNotExists("d", "f", pilosa.ViewStandard, 0).SetBit(10, 1)

	called := false
	e := test.NewExecutor(hldr.Holder, test.NewCluster(1))
	frame := e.Holder.Frame("d", "f")
	if frame == nil {
		t.Fatal("frame not found")
	}

	frame.Stats = &MockStats{
		mockCount: func(name string, value int64, rate float64) {
			if name != "SetBitmapAttrs" {
				t.Errorf("Expected SetBitmapAttrs, Results %s", name)
			}
			called = true
			return
		},
	}
	if _, err := e.Execute(context.Background(), "d", test.MustParse(`SetRowAttrs(rowID=10, frame=f, foo="bar")`), nil, nil); err != nil {
		t.Fatal(err)
	}
	if !called {
		t.Error("Count isn't called")
	}
}

func TestStatsCount_SetProfileAttrs(t *testing.T) {
	hldr := test.MustOpenHolder()
	defer hldr.Close()

	hldr.MustCreateFragmentIfNotExists("d", "f", pilosa.ViewStandard, 0).SetBit(10, 0)
	hldr.MustCreateFragmentIfNotExists("d", "f", pilosa.ViewStandard, 0).SetBit(10, 1)

	called := false
	e := test.NewExecutor(hldr.Holder, test.NewCluster(1))
	idx := e.Holder.Index("d")
	if idx == nil {
		t.Fatal("idex not found")
	}

	idx.Stats = &MockStats{
		mockCount: func(name string, value int64, rate float64) {
			if name != "SetProfileAttrs" {
				t.Errorf("Expected SetProfilepAttrs, Results %s", name)
			}

			called = true
			return
		},
	}
	if _, err := e.Execute(context.Background(), "d", test.MustParse(`SetColumnAttrs(id=10, frame=f, foo="bar")`), nil, nil); err != nil {
		t.Fatal(err)
	}
	if !called {
		t.Error("Count isn't called")
	}
}

func TestStatsCount_CreateIndex(t *testing.T) {
	hldr := test.MustOpenHolder()
	defer hldr.Close()
	s := test.NewServer()
	s.Handler.Holder = hldr.Holder
	defer s.Close()
	called := false
	s.Handler.Holder.Stats = &MockStats{
		mockCount: func(name string, value int64, rate float64) {
			if name != "createIndex" {
				t.Errorf("Expected createIndex, Results %s", name)
			}

			called = true
			return
		},
	}
	http.DefaultClient.Do(test.MustNewHTTPRequest("POST", s.URL+"/index/i", nil))
	if !called {
		t.Error("Count isn't called")
	}
}

func TestStatsCount_DeleteIndex(t *testing.T) {
	hldr := test.MustOpenHolder()
	defer hldr.Close()

	s := test.NewServer()
	s.Handler.Holder = hldr.Holder
	defer s.Close()

	// Create index.
	if _, err := hldr.CreateIndexIfNotExists("i", pilosa.IndexOptions{}); err != nil {
		t.Fatal(err)
	}
	called := false
	s.Handler.Holder.Stats = &MockStats{
		mockCount: func(name string, value int64, rate float64) {
			if name != "deleteIndex" {
				t.Errorf("Expected deleteIndex, Results %s", name)
			}

			called = true
			return
		},
	}
	http.DefaultClient.Do(test.MustNewHTTPRequest("DELETE", s.URL+"/index/i", strings.NewReader("")))
	if !called {
		t.Error("Count isn't called")
	}
}

func TestStatsCount_CreateFrame(t *testing.T) {
	hldr := test.MustOpenHolder()
	defer hldr.Close()

	s := test.NewServer()
	s.Handler.Holder = hldr.Holder
	defer s.Close()

	// Create index.
	if _, err := hldr.CreateIndexIfNotExists("i", pilosa.IndexOptions{}); err != nil {
		t.Fatal(err)
	}
	called := false
	s.Handler.Holder.Stats = &MockStats{
		mockCountWithTags: func(name string, value int64, rate float64, index []string) {
			if name != "createFrame" {
				t.Errorf("Expected createFrame, Results %s", name)
			}
			if index[0] != "index:i" {
				t.Errorf("Expected index:i, Results %s", index)
			}

			called = true
			return
		},
	}
	http.DefaultClient.Do(test.MustNewHTTPRequest("POST", s.URL+"/index/i/frame/f", nil))
	if !called {
		t.Error("Count isn't called")
	}
}

func TestStatsCount_DeleteFrame(t *testing.T) {
	hldr := test.MustOpenHolder()
	defer hldr.Close()

	s := test.NewServer()
	s.Handler.Holder = hldr.Holder
	defer s.Close()
	called := false
	// Create index.
	indx, _ := hldr.CreateIndexIfNotExists("i", pilosa.IndexOptions{})
	if _, err := indx.CreateFrameIfNotExists("test", pilosa.FrameOptions{}); err != nil {
		t.Fatal(err)
	}
	s.Handler.Holder.Stats = &MockStats{
		mockCountWithTags: func(name string, value int64, rate float64, index []string) {
			if name != "deleteFrame" {
				t.Errorf("Expected deleteFrame, Results %s", name)
			}
			if index[0] != "index:i" {
				t.Errorf("Expected index:i, Results %s", index)
			}

			called = true
			return
		},
	}
	http.DefaultClient.Do(test.MustNewHTTPRequest("DELETE", s.URL+"/index/i/frame/f", strings.NewReader("")))
	if !called {
		t.Error("Count isn't called")
	}
}

type MockStats struct {
	mockCount         func(name string, value int64, rate float64)
	mockCountWithTags func(name string, value int64, rate float64, tags []string)
}

func (s *MockStats) Count(name string, value int64, rate float64) {
	if s.mockCount != nil {
		s.mockCount(name, value, rate)
		return
	}
	return
}

func (s *MockStats) CountWithCustomTags(name string, value int64, rate float64, tags []string) {
	if s.mockCountWithTags != nil {
		s.mockCountWithTags(name, value, rate, tags)
		return
	}
	return
}

func (c *MockStats) Tags() []string                                        { return nil }
func (c *MockStats) WithTags(tags ...string) pilosa.StatsClient            { return c }
func (c *MockStats) Gauge(name string, value float64, rate float64)        {}
func (c *MockStats) Histogram(name string, value float64, rate float64)    {}
func (c *MockStats) Set(name string, value string, rate float64)           {}
func (c *MockStats) Timing(name string, value time.Duration, rate float64) {}
func (c *MockStats) SetLogger(logger io.Writer)                            {}


text:
#ifndef CPP2_PROTOCOL_PROTOCOLREADER_WITHREFILL_H_
#define CPP2_PROTOCOL_PROTOCOLREADER_WITHREFILL_H_ 1

#include <folly/FBString.h>
#include <thrift/lib/cpp2/protocol/VirtualProtocol.h>
#include <thrift/lib/cpp2/protocol/BinaryProtocol.h>
#include <thrift/lib/cpp2/protocol/CompactProtocol.h>

namespace apache { namespace thrift {

template<typename ProtocolT> class ProtocolReaderWithRefill;

using VirtualBinaryReader = ProtocolReaderWithRefill<BinaryProtocolReader>;
using VirtualCompactReader = ProtocolReaderWithRefill<CompactProtocolReader>;
using Refiller = std::function<std::unique_ptr<folly::IOBuf>(
    const uint8_t*, int, int, int)>;

/**
 * Used by python fastproto module. Read methods must check if there are
 * enough bytes to read. If not, call the refiller to read more from python.
 */
template<typename ProtocolT>
class ProtocolReaderWithRefill : public VirtualReader<ProtocolT> {
  public:
    explicit ProtocolReaderWithRefill(Refiller refiller)
      : refiller_(refiller)
      , buffer_(nullptr)
      , bufferLength_(0) {}

    uint32_t totalBytesRead() {
      return bufferLength_ - this->protocol_.in_.length();
    }

    using VirtualReader<ProtocolT>::setInput;
    void setInput(const folly::io::Cursor& cursor) override {
      VirtualReader<ProtocolT>::setInput(cursor);
      bufferLength_ = cursor.length();
    }

  protected:
    void ensureBuffer(uint32_t size) {
      if (this->protocol_.in_.length() >= size) {
        return;
      }

      auto avail = this->protocol_.in_.peekBytes();
      buffer_ = refiller_(avail.data(), avail.size(), totalBytesRead(), size);
      if (!buffer_) {
        throw std::runtime_error("Empty buffer returned when refilling");
      }
      setInput(buffer_.get());
    }

    Refiller refiller_;
    std::unique_ptr<folly::IOBuf> buffer_;
    uint32_t bufferLength_;
};

class CompactProtocolReaderWithRefill : public VirtualCompactReader {
  public:
    explicit CompactProtocolReaderWithRefill(Refiller refiller)
      : VirtualCompactReader(refiller) {}

    inline uint32_t readMessageBegin(std::string& /*name*/,
                                     MessageType& /*messageType*/,
                                     int32_t& /*seqid*/) override {
      // Only called in python so leave it unimplemented.
      throw std::runtime_error("not implemented");
    }

    inline uint32_t readFieldBegin(std::string& name,
                                   TType& fieldType,
                                   int16_t& fieldId) override {
      ensureFieldBegin();
      return protocol_.readFieldBegin(name, fieldType, fieldId);
    }

    inline uint32_t readMapBegin(TType& keyType,
                                 TType& valType,
                                 uint32_t& size) override {
      ensureMapBegin();
      return protocol_.readMapBegin(keyType, valType, size);
    }

    inline uint32_t readListBegin(TType& elemType, uint32_t& size) override {
      ensureListBegin();
      return protocol_.readListBegin(elemType, size);
    }

    inline uint32_t readBool(bool& value) override {
      if (!protocol_.boolValue_.hasBoolValue) {
        ensureBuffer(1);
      }
      return protocol_.readBool(value);
    }

    inline uint32_t readBool(std::vector<bool>::reference value) override {
      bool ret = false;
      uint32_t sz = readBool(ret);
      value = ret;
      return sz;
    }

    inline uint32_t readByte(int8_t& byte) override {
      ensureBuffer(1);
      return protocol_.readByte(byte);
    }

    inline uint32_t readI16(int16_t& i16) override {
      ensureInteger();
      return protocol_.readI16(i16);
    }

    inline uint32_t readI32(int32_t& i32) override {
      ensureInteger();
      return protocol_.readI32(i32);
    }

    inline uint32_t readI64(int64_t& i64) override {
      ensureInteger();
      return protocol_.readI64(i64);
    }

    inline uint32_t readDouble(double& dub) override {
      ensureBuffer(8);
      return protocol_.readDouble(dub);
    }

    inline uint32_t readFloat(float& flt) override {
      ensureBuffer(4);
      return protocol_.readFloat(flt);
    }

    inline uint32_t readString(std::string& str) override {
      return readStringImpl(str);
    }

    inline uint32_t readString(folly::fbstring& str) override {
      return readStringImpl(str);
    }

    inline uint32_t readBinary(std::string& str) override {
      return readStringImpl(str);
    }

    inline uint32_t readBinary(folly::fbstring& str) override {
      return readStringImpl(str);
    }

    inline uint32_t readBinary(std::unique_ptr<folly::IOBuf>& str) override {
      return readBinaryIOBufImpl(str);
    }

    inline uint32_t readBinary(folly::IOBuf& str) override {
      return readBinaryIOBufImpl(str);
    }

    inline uint32_t skip(TType type) override {
      return apache::thrift::skip(*this, type);
    }

  private:
    /**
     * Make sure a varint can be read from the current buffer after idx bytes.
     * If not, call the refiller to read more bytes.
     *
     * A varint is stored with up to 10 bytes and only the last byte's
     * MSB isn't set. If the current buffer size is >= idx + 10, return. The
     * following call to readVarint may still fail if the first 10 bytes
     * all have MSB set, but it's not the problem to be addressed here.
     *
     * Otherwise, check if a byte with MSB not set can be found. If so, return.
     * Otherwise, call the refiller to ask for 1 more byte because the exact
     * size of the varint is still unknown but at leat 1 more byte is required.
     * A sane transport reads more data even if asked for just 1 byte so this
     * should not cause any performance problem. After the new buffer is ready,
     * start all over again.
     **/
    void ensureInteger(int idx = 0) {
      while (protocol_.in_.length() - idx < 10) {
        if (protocol_.in_.length() <= idx) {
          ensureBuffer(idx + 1);
        } else {
          auto avail = protocol_.in_.peekBytes();
          const uint8_t *b = avail.data() + idx;
          while (idx < avail.size()) {
            if (!(*b++ & 0x80))
              return;
            idx++;
          }

          ensureBuffer(avail.size() + 1);
        }
      }
    }

    void ensureFieldBegin() {
      // Fast path: at most 4 bytes are needed to read field begin.
      if (protocol_.in_.length() >= 4)
        return;

      // At least 1 byte is needed to read ftype.
      ensureBuffer(1);
      if (protocol_.in_.length() >= 4)
        return;
      auto avail = protocol_.in_.peekBytes();
      const uint8_t *b = avail.data();
      int8_t byte = folly::Endian::big(*b);
      int8_t type = (byte & 0x0f);

      if (type == TType::T_STOP)
        return;

      int16_t modifier = (int16_t)(((uint8_t)byte & 0xf0) >> 4);
      if (modifier == 0) {
        ensureInteger(1);
      }
    }

    void ensureMapBegin() {
      // Fast path: at most 11 bytes are needed to read map begin.
      if (protocol_.in_.length() >= 11)
        return;

      ensureInteger();
      if (protocol_.in_.length() >= 11)
        return;

      auto avail = protocol_.in_.peekBytes();
      const uint8_t *b = avail.data();
      int bytes = 1;
      while (bytes <= avail.size()) {
        if (!(*b++ & 0x80))
          break;
        bytes++;
      }
      // Non-empty maps have an additional byte for the key/value type.
      if (bytes == avail.size() && *avail.data()) {
        ensureBuffer(avail.size() + 1);
      }
    }

    void ensureListBegin() {
      // Fast path: at most 11 bytes are needed to read list begin.
      if (protocol_.in_.length() >= 11)
        return;

      ensureBuffer(1);
      auto avail = protocol_.in_.peekBytes();
      const uint8_t *b = avail.data();
      int8_t size_and_type = folly::Endian::big(*b);
      int32_t lsize = ((uint8_t)size_and_type >> 4) & 0x0f;
      if (lsize == 15) {
        ensureInteger(1);
      }
    }

    template<typename StrType>
    uint32_t readStringImpl(StrType& str) {
      ensureInteger();
      int32_t size = 0;
      uint32_t rsize = protocol_.readStringSize(size);

      ensureBuffer(size);
      return rsize + protocol_.readStringBody(str, size);
    }

    template<typename StrType>
    uint32_t readBinaryIOBufImpl(StrType& str) {
      ensureInteger();
      int32_t size = 0;
      uint32_t rsize = protocol_.readStringSize(size);

      ensureBuffer(size);
      protocol_.in_.clone(str, size);
      return rsize + (uint32_t)size;
    }
};

class BinaryProtocolReaderWithRefill : public VirtualBinaryReader {
  public:
    explicit BinaryProtocolReaderWithRefill(Refiller refiller)
      : VirtualBinaryReader(refiller) {}

    inline uint32_t readMessageBegin(std::string& /*name*/,
                                     MessageType& /*messageType*/,
                                     int32_t& /*seqid*/) override {
      // This is only called in python so leave it unimplemented.
      throw std::runtime_error("not implemented");
    }

    inline uint32_t readFieldBegin(std::string& /*name*/,
                                   TType& fieldType,
                                   int16_t& fieldId) override {
      uint32_t result = 0;
      int8_t type;
      result += readByte(type);
      fieldType = (TType)type;
      if (fieldType == TType::T_STOP) {
        fieldId = 0;
        return result;
      }
      result += readI16(fieldId);
      return result;
    }

    inline uint32_t readMapBegin(TType& keyType,
                                 TType& valType,
                                 uint32_t& size) override {
      ensureBuffer(6);
      return protocol_.readMapBegin(keyType, valType, size);
    }

    inline uint32_t readListBegin(TType& elemType, uint32_t& size) override {
      ensureBuffer(5);
      return protocol_.readListBegin(elemType, size);
    }

    inline uint32_t readSetBegin(TType& elemType, uint32_t& size) override {
      return readListBegin(elemType, size);
    }

    inline uint32_t readBool(bool& value) override {
      ensureBuffer(1);
      return protocol_.readBool(value);
    }

    inline uint32_t readBool(std::vector<bool>::reference value) override {
      ensureBuffer(1);
      return protocol_.readBool(value);
    }

    inline uint32_t readByte(int8_t& byte) override {
      ensureBuffer(1);
      return protocol_.readByte(byte);
    }

    inline uint32_t readI16(int16_t& i16) override {
      ensureBuffer(2);
      return protocol_.readI16(i16);
    }

    inline uint32_t readI32(int32_t& i32) override {
      ensureBuffer(4);
      return protocol_.readI32(i32);
    }

    inline uint32_t readI64(int64_t& i64) override {
      ensureBuffer(8);
      return protocol_.readI64(i64);
    }

    inline uint32_t readDouble(double& dub) override {
      ensureBuffer(8);
      return protocol_.readDouble(dub);
    }

    inline uint32_t readFloat(float& flt) override {
      ensureBuffer(4);
      return protocol_.readFloat(flt);
    }

    inline uint32_t readString(std::string& str) override {
      return readStringImpl(str);
    }

    inline uint32_t readString(folly::fbstring& str) override {
      return readStringImpl(str);
    }

    inline uint32_t readBinary(std::string& str) override {
      return readStringImpl(str);
    }

    inline uint32_t readBinary(folly::fbstring& str) override {
      return readStringImpl(str);
    }

    inline uint32_t readBinary(std::unique_ptr<folly::IOBuf>& str) override {
      return readBinaryIOBufImpl(str);
    }

    inline uint32_t readBinary(folly::IOBuf& str) override {
      return readBinaryIOBufImpl(str);
    }

    inline uint32_t skip(TType type) override {
      return apache::thrift::skip(*this, type);
    }

  private:
    template<typename StrType>
    uint32_t readStringImpl(StrType& str) {
      uint32_t result;
      int32_t size;
      result = readI32(size);
      protocol_.checkStringSize(size);

      ensureBuffer(size);
      return result + protocol_.readStringBody(str, size);
    }

    template<typename StrType>
    uint32_t readBinaryIOBufImpl(StrType& str) {
      uint32_t result;
      int32_t size;
      result = readI32(size);
      protocol_.checkStringSize(size);

      ensureBuffer(size);
      protocol_.in_.clone(str, size);
      return result + (uint32_t)size;
    }
};

}} //apache::thrift

#endif // #ifndef CPP2_PROTOCOL_PROTOCOLREADER_WITHREFILL_H_


text:
namespace optimization_guide {

// A BERT-based mode executor for page topics annotations. All the derived
// functionality of this class is exclusive to the UI thread, but may post
// things to the background task runner.
class PageTopicsModelExecutor : public PageContentAnnotationJobExecutor,
                                public BertModelHandler {
 public:
  PageTopicsModelExecutor(
      OptimizationGuideModelProvider* model_provider,
      scoped_refptr<base::SequencedTaskRunner> background_task_runner,
      const absl::optional<proto::Any>& model_metadata);
  ~PageTopicsModelExecutor() override;

  // PageContentAnnotationJobExecutor:
  void ExecuteJob(base::OnceClosure on_job_complete_callback,
                  std::unique_ptr<PageContentAnnotationJob> job) override;
  void ExecuteOnSingleInput(
      AnnotationType annotation_type,
      const std::string& raw_input,
      base::OnceCallback<void(const BatchAnnotationResult&)> callback) override;

  // BertModelHandler:
  void UnloadModel() override;
  void OnModelUpdated(proto::OptimizationTarget optimization_target,
                      const ModelInfo& model_info) override;

  // Creates a BatchAnnotationResult from the output of the model, calling
  // |ExtractCategoriesFromModelOutput| in the process.
  // Public for testing.
  void PostprocessCategoriesToBatchAnnotationResult(
      base::OnceCallback<void(const BatchAnnotationResult&)> callback,
      AnnotationType annotation_type,
      const std::string& raw_input,
      const absl::optional<std::vector<tflite::task::core::Category>>& output);

  // Extracts the scored categories from the output of the model.
  // Public for testing.
  absl::optional<std::vector<WeightedIdentifier>>
  ExtractCategoriesFromModelOutput(
      const std::vector<tflite::task::core::Category>& model_output) const;

 private:
  void OnOverrideListLoadAttemptDone(
      base::OnceClosure on_job_complete_callback,
      std::unique_ptr<PageContentAnnotationJob> job,
      absl::optional<
          std::unordered_map<std::string, std::vector<WeightedIdentifier>>>
          override_list);

  // Does the required preprocessing on a input domain.
  std::string PreprocessHost(const std::string& host) const;

  scoped_refptr<base::SequencedTaskRunner> background_task_runner_;

  // Set whenever a valid override list file is passed along with the model file
  // update. This will be reset if the provided file is deemed invalid on the
  // first attempted load.
  // Used on the UI thread.
  absl::optional<base::FilePath> override_list_file_path_;

  // Set whenever an override list file is available and the model file is
  // loaded into memory. Reset whenever the model file is unloaded.
  // Used on the UI thread. Lookups in this mapping should have |PreprocessHost|
  // applied first.
  absl::optional<
      std::unordered_map<std::string, std::vector<WeightedIdentifier>>>
      override_list_;

  // The version of topics model provided by the server in the model metadata
  // which specifies the expected functionality of execution not contained
  // within the model itself (e.g., preprocessing/post processing).
  int version_ = 0;

  SEQUENCE_CHECKER(sequence_checker_);

  base::WeakPtrFactory<PageTopicsModelExecutor> weak_ptr_factory_{this};
};

}  // namespace optimization_guide

#endif  // COMPONENTS_OPTIMIZATION_GUIDE_CORE_PAGE_TOPICS_MODEL_EXECUTOR_H_


text:
/** @scratch /panels/5
 *
 * include::panels/histogram.asciidoc[]
 */

/** @scratch /panels/histogram/0
 *
 * == Histogram
 * Status: *Stable*
 *
 * The histogram panel allow for the display of time charts. It includes several modes and tranformations
 * to display event counts, mean, min, max and total of numeric fields, and derivatives of counter
 * fields.
 *
 */
define([
  'angular',
  'app',
  'jquery',
  'lodash',
  'kbn',
  'moment',
  './timeSeries',
  'numeral',
  'jquery.flot',
  'jquery.flot.events',
  'jquery.flot.selection',
  'jquery.flot.time',
  'jquery.flot.byte',
  'jquery.flot.stack',
  'jquery.flot.stackpercent'
],
function (angular, app, $, _, kbn, moment, timeSeries, numeral) {

  'use strict';

  var module = angular.module('kibana.panels.histogram', []);
  app.useModule(module);

  module.controller('histogram', function($scope, querySrv, dashboard, filterSrv) {
    $scope.panelMeta = {
      modals : [
        {
          description: "Inspect",
          icon: "icon-info-sign",
          partial: "app/partials/inspector.html",
          show: $scope.panel.spyable
        }
      ],
      editorTabs : [
        {
          title:'Style',
          src:'app/panels/histogram/styleEditor.html'
        },
        {
          title:'Queries',
          src:'app/panels/histogram/queriesEditor.html'
        },
      ],
      status  : "Stable",
      description : "A bucketed time series chart of the current query or queries. Uses the "+
        "Elasticsearch date_histogram facet. If using time stamped indices this panel will query"+
        " them sequentially to attempt to apply the lighest possible load to your Elasticsearch cluster"
    };

    // Set and populate defaults
    var _d = {
      /** @scratch /panels/histogram/3
       *
       * === Parameters
       * ==== Axis options
       * mode:: Value to use for the y-axis. For all modes other than count, +value_field+ must be
       * defined. Possible values: count, mean, max, min, total.
       */
      mode          : 'count',
      /** @scratch /panels/histogram/3
       * time_field:: x-axis field. This must be defined as a date type in Elasticsearch.
       */
      time_field    : '@timestamp',
      /** @scratch /panels/histogram/3
       * value_field:: y-axis field if +mode+ is set to mean, max, min or total. Must be numeric.
       */
      value_field   : null,
      /** @scratch /panels/histogram/3
       * x-axis:: Show the x-axis
       */
      'x-axis'      : true,
      /** @scratch /panels/histogram/3
       * y-axis:: Show the y-axis
       */
      'y-axis'      : true,
      /** @scratch /panels/histogram/3
       * scale:: Scale the y-axis by this factor
       */
      scale         : 1,
      /** @scratch /panels/histogram/3
       * y_format:: 'none','bytes','short '
       */
      y_format    : 'none',
      /** @scratch /panels/histogram/5
       * grid object:: Min and max y-axis values
       * grid.min::: Minimum y-axis value
       * grid.max::: Maximum y-axis value
       */
      grid          : {
        max: null,
        min: 0
      },
      /** @scratch /panels/histogram/5
       *
       * ==== Queries
       * queries object:: This object describes the queries to use on this panel.
       * queries.mode::: Of the queries available, which to use. Options: +all, pinned, unpinned, selected+
       * queries.ids::: In +selected+ mode, which query ids are selected.
       */
      queries     : {
        mode        : 'all',
        ids         : []
      },
      /** @scratch /panels/histogram/3
       *
       * ==== Annotations
       * annotate object:: A query can be specified, the results of which will be displayed as markers on
       * the chart. For example, for noting code deploys.
       * annotate.enable::: Should annotations, aka markers, be shown?
       * annotate.query::: Lucene query_string syntax query to use for markers.
       * annotate.size::: Max number of markers to show
       * annotate.field::: Field from documents to show
       * annotate.sort::: Sort array in format [field,order], For example [`@timestamp',`desc']
       */
      annotate      : {
        enable      : false,
        query       : "*",
        size        : 20,
        field       : '_type',
        sort        : ['_score','desc']
      },
      /** @scratch /panels/histogram/3
       * ==== Interval options
       * auto_int:: Automatically scale intervals?
       */
      auto_int      : true,
      /** @scratch /panels/histogram/3
       * resolution:: If auto_int is true, shoot for this many bars.
       */
      resolution    : 100,
      /** @scratch /panels/histogram/3
       * interval:: If auto_int is set to false, use this as the interval.
       */
      interval      : '5m',
      /** @scratch /panels/histogram/3
       * interval:: Array of possible intervals in the *View* selector. Example [`auto',`1s',`5m',`3h']
       */
      intervals     : ['auto','1s','1m','5m','10m','30m','1h','3h','12h','1d','1w','1y'],
      /** @scratch /panels/histogram/3
       * ==== Drawing options
       * lines:: Show line chart
       */
      lines         : false,
      /** @scratch /panels/histogram/3
       * fill:: Area fill factor for line charts, 1-10
       */
      fill          : 0,
      /** @scratch /panels/histogram/3
       * linewidth:: Weight of lines in pixels
       */
      linewidth     : 3,
      /** @scratch /panels/histogram/3
       * points:: Show points on chart
       */
      points        : false,
      /** @scratch /panels/histogram/3
       * pointradius:: Size of points in pixels
       */
      pointradius   : 5,
      /** @scratch /panels/histogram/3
       * bars:: Show bars on chart
       */
      bars          : true,
      /** @scratch /panels/histogram/3
       * stack:: Stack multiple series
       */
      stack         : true,
      /** @scratch /panels/histogram/3
       * spyable:: Show inspect icon
       */
      spyable       : true,
      /** @scratch /panels/histogram/3
       * zoomlinks:: Show `Zoom Out' link
       */
      zoomlinks     : true,
      /** @scratch /panels/histogram/3
       * options:: Show quick view options section
       */
      options       : true,
      /** @scratch /panels/histogram/3
       * legend:: Display the legond
       */
      legend        : true,
      /** @scratch /panels/histogram/3
       * show_query:: If no alias is set, should the query be displayed?
       */
      show_query    : true,
      /** @scratch /panels/histogram/3
       * interactive:: Enable click-and-drag to zoom functionality
       */
      interactive   : true,
      /** @scratch /panels/histogram/3
       * legend_counts:: Show counts in legend
       */
      legend_counts : true,
      /** @scratch /panels/histogram/3
       * ==== Transformations
       * timezone:: Correct for browser timezone?. Valid values: browser, utc
       */
      timezone      : 'browser', // browser or utc
      /** @scratch /panels/histogram/3
       * percentage:: Show the y-axis as a percentage of the axis total. Only makes sense for multiple
       * queries
       */
      percentage    : false,
      /** @scratch /panels/histogram/3
       * zerofill:: Improves the accuracy of line charts at a small performance cost.
       */
      zerofill      : true,
      /** @scratch /panels/histogram/3
       * derivative:: Show each point on the x-axis as the change from the previous point
       */
      derivative    : false,
      /** @scratch /panels/histogram/3
       * tooltip object::
       * tooltip.value_type::: Individual or cumulative controls how tooltips are display on stacked charts
       * tooltip.query_as_alias::: If no alias is set, should the query be displayed?
       */
      tooltip       : {
        value_type: 'cumulative',
        query_as_alias: true
      }
    };

    _.defaults($scope.panel,_d);
    _.defaults($scope.panel.tooltip,_d.tooltip);
    _.defaults($scope.panel.annotate,_d.annotate);
    _.defaults($scope.panel.grid,_d.grid);

    $scope.init = function() {
      // Hide view options by default
      $scope.options = false;

      // Always show the query if an alias isn't set. Users can set an alias if the query is too
      // long
      $scope.panel.tooltip.query_as_alias = true;

      $scope.get_data();

    };

    $scope.set_interval = function(interval) {
      if(interval !== 'auto') {
        $scope.panel.auto_int = false;
        $scope.panel.interval = interval;
      } else {
        $scope.panel.auto_int = true;
      }
    };

    $scope.interval_label = function(interval) {
      return $scope.panel.auto_int && interval === $scope.panel.interval ? interval+" (auto)" : interval;
    };

    /**
     * The time range effecting the panel
     * @return {[type]} [description]
     */
    $scope.get_time_range = function () {
      var range = $scope.range = filterSrv.timeRange('last');
      return range;
    };

    $scope.get_interval = function () {
      var interval = $scope.panel.interval,
                      range;
      if ($scope.panel.auto_int) {
        range = $scope.get_time_range();
        if (range) {
          interval = kbn.secondsToHms(
            kbn.calculate_interval(range.from, range.to, $scope.panel.resolution, 0) / 1000
          );
        }
      }
      $scope.panel.interval = interval || '10m';
      return $scope.panel.interval;
    };

    /**
     * Fetch the data for a chunk of a queries results. Multiple segments occur when several indicies
     * need to be consulted (like timestamped logstash indicies)
     *
     * The results of this function are stored on the scope's data property. This property will be an
     * array of objects with the properties info, time_series, and hits. These objects are used in the
     * render_panel function to create the historgram.
     *
     * @param {number} segment   The segment count, (0 based)
     * @param {number} query_id  The id of the query, generated on the first run and passed back when
     *                            this call is made recursively for more segments
     */
    $scope.get_data = function(data, segment, query_id) {
      var
        _range,
        _interval,
        request,
        queries,
        results;

      if (_.isUndefined(segment)) {
        segment = 0;
      }
      delete $scope.panel.error;

      // Make sure we have everything for the request to complete
      if(dashboard.indices.length === 0) {
        return;
      }
      _range = $scope.get_time_range();
      _interval = $scope.get_interval(_range);

      if ($scope.panel.auto_int) {
        $scope.panel.interval = kbn.secondsToHms(
          kbn.calculate_interval(_range.from,_range.to,$scope.panel.resolution,0)/1000);
      }

      $scope.panelMeta.loading = true;
      request = $scope.ejs.Request().indices(dashboard.indices[segment]);
      if (!$scope.panel.annotate.enable) {
        request.searchType("count");
      }

      $scope.panel.queries.ids = querySrv.idsByMode($scope.panel.queries);

      queries = querySrv.getQueryObjs($scope.panel.queries.ids);

      // Build the query
      _.each(queries, function(q) {
        var query = $scope.ejs.FilteredQuery(
          querySrv.toEjsObj(q),
          filterSrv.getBoolFilter(filterSrv.ids())
        );

        var facet = $scope.ejs.DateHistogramFacet(q.id);

        if($scope.panel.mode === 'count') {
          facet = facet.field($scope.panel.time_field).global(true);
        } else {
          if(_.isNull($scope.panel.value_field)) {
            $scope.panel.error = "In " + $scope.panel.mode + " mode a field must be specified";
            return;
          }
          facet = facet.keyField($scope.panel.time_field).valueField($scope.panel.value_field).global(true);
        }
        facet = facet.interval(_interval).facetFilter($scope.ejs.QueryFilter(query));
        request = request.facet(facet)
          .size($scope.panel.annotate.enable ? $scope.panel.annotate.size : 0);
      });

      if($scope.panel.annotate.enable) {
        var query = $scope.ejs.FilteredQuery(
          $scope.ejs.QueryStringQuery($scope.panel.annotate.query || '*'),
          filterSrv.getBoolFilter(filterSrv.idsByType('time'))
        );
        request = request.query(query);

        // This is a hack proposed by @boaz to work around the fact that we can't get
        // to field data values directly, and we need timestamps as normalized longs
        request = request.sort([
          $scope.ejs.Sort($scope.panel.annotate.sort[0]).order($scope.panel.annotate.sort[1]),
          $scope.ejs.Sort($scope.panel.time_field).desc()
        ]);
      }

      // Populate the inspector panel
      $scope.populate_modal(request);

      // Then run it
      results = request.doSearch();

      // Populate scope when we have results
      return results.then(function(results) {
        $scope.panelMeta.loading = false;
        if(segment === 0) {
          $scope.legend = [];
          $scope.hits = 0;
          data = [];
          $scope.annotations = [];
          query_id = $scope.query_id = new Date().getTime();
        }

        // Check for error and abort if found
        if(!(_.isUndefined(results.error))) {
          $scope.panel.error = $scope.parse_error(results.error);
        }
        // Make sure we're still on the same query/queries
        else if($scope.query_id === query_id) {

          var i = 0,
            time_series,
            hits,
            counters; // Stores the bucketed hit counts.

          _.each(queries, function(q) {
            var query_results = results.facets[q.id];
            // we need to initialize the data variable on the first run,
            // and when we are working on the first segment of the data.
            if(_.isUndefined(data[i]) || segment === 0) {
              var tsOpts = {
                interval: _interval,
                start_date: _range && _range.from,
                end_date: _range && _range.to,
                fill_style: $scope.panel.derivative ? 'null' : 'minimal'
              };
              time_series = new timeSeries.ZeroFilled(tsOpts);
              hits = 0;
              counters = {};
            } else {
              time_series = data[i].time_series;
              hits = data[i].hits;
              counters = data[i].counters;
            }

            // push each entry into the time series, while incrementing counters
            _.each(query_results.entries, function(entry) {
              var value;

              hits += entry.count; // The series level hits counter
              $scope.hits += entry.count; // Entire dataset level hits counter
              counters[entry.time] = (counters[entry.time] || 0) + entry.count;

              if($scope.panel.mode === 'count') {
                value = (time_series._data[entry.time] || 0) + entry.count;
              } else if ($scope.panel.mode === 'mean') {
                // Compute the ongoing mean by
                // multiplying the existing mean by the existing hits
                // plus the new mean multiplied by the new hits
                // divided by the total hits
                value = (((time_series._data[entry.time] || 0)*(counters[entry.time]-entry.count)) +
                  entry.mean*entry.count)/(counters[entry.time]);
              } else if ($scope.panel.mode === 'min'){
                if(_.isUndefined(time_series._data[entry.time])) {
                  value = entry.min;
                } else {
                  value = time_series._data[entry.time] < entry.min ? time_series._data[entry.time] : entry.min;
                }
              } else if ($scope.panel.mode === 'max'){
                if(_.isUndefined(time_series._data[entry.time])) {
                  value = entry.max;
                } else {
                  value = time_series._data[entry.time] > entry.max ? time_series._data[entry.time] : entry.max;
                }
              } else if ($scope.panel.mode === 'total'){
                value = (time_series._data[entry.time] || 0) + entry.total;
              }
              time_series.addValue(entry.time, value);
            });

            $scope.legend[i] = {query:q,hits:hits};

            data[i] = {
              info: q,
              time_series: time_series,
              hits: hits,
              counters: counters
            };

            i++;
          });

          if($scope.panel.annotate.enable) {
            $scope.annotations = $scope.annotations.concat(_.map(results.hits.hits, function(hit) {
              var _p = _.omit(hit,'_source','sort','_score');
              var _h = _.extend(kbn.flatten_json(hit._source),_p);
              return  {
                min: hit.sort[1],
                max: hit.sort[1],
                eventType: "annotation",
                title: null,
                description: " "+
                  _h[$scope.panel.annotate.field]+"
"+
                  moment(hit.sort[1]).format('YYYY-MM-DD HH:mm:ss'),
                score: hit.sort[0]
              };
            }));
            // Sort the data
            $scope.annotations = _.sortBy($scope.annotations, function(v){
              // Sort in reverse
              return v.score*($scope.panel.annotate.sort[1] === 'desc' ? -1 : 1);
            });
            // And slice to the right size
            $scope.annotations = $scope.annotations.slice(0,$scope.panel.annotate.size);
          }
        }

        // Tell the histogram directive to render.
        $scope.$emit('render', data);

        // If we still have segments left, get them
        if(segment < dashboard.indices.length-1) {
          $scope.get_data(data,segment+1,query_id);
        }
      });
    };

    // function $scope.zoom
    // factor :: Zoom factor, so 0.5 = cuts timespan in half, 2 doubles timespan
    $scope.zoom = function(factor) {
      var _range = filterSrv.timeRange('last');
      var _timespan = (_range.to.valueOf() - _range.from.valueOf());
      var _center = _range.to.valueOf() - _timespan/2;

      var _to = (_center + (_timespan*factor)/2);
      var _from = (_center - (_timespan*factor)/2);

      // If we're not already looking into the future, don't.
      if(_to > Date.now() && _range.to < Date.now()) {
        var _offset = _to - Date.now();
        _from = _from - _offset;
        _to = Date.now();
      }

      if(factor > 1) {
        filterSrv.removeByType('time');
      }
      filterSrv.set({
        type:'time',
        from:moment.utc(_from).toDate(),
        to:moment.utc(_to).toDate(),
        field:$scope.panel.time_field
      });
    };

    // I really don't like this function, too much dom manip. Break out into directive?
    $scope.populate_modal = function(request) {
      $scope.inspector = angular.toJson(JSON.parse(request.toString()),true);
    };

    $scope.set_refresh = function (state) {
      $scope.refresh = state;
    };

    $scope.close_edit = function() {
      if($scope.refresh) {
        $scope.get_data();
      }
      $scope.refresh =  false;
      $scope.$emit('render');
    };

    $scope.render = function() {
      $scope.$emit('render');
    };

  });

  module.directive('histogramChart', function(dashboard, filterSrv) {
    return {
      restrict: 'A',
      template: '

',
      link: function(scope, elem) {
        var data, plot;

        scope.$on('refresh',function(){
          scope.get_data();
        });

        // Receive render events
        scope.$on('render',function(event,d){
          data = d || data;
          render_panel(data);
        });

        scope.$watch('panel.span', function(){
          render_panel(data);
        });

        // Re-render if the window is resized
        angular.element(window).bind('resize', function(){
          render_panel(data);
        });

        var scale = function(series,factor) {
          return _.map(series,function(p) {
            return [p[0],p[1]*factor];
          });
        };

        var scaleSeconds = function(series,interval) {
          return _.map(series,function(p) {
            return [p[0],p[1]/kbn.interval_to_seconds(interval)];
          });
        };

        var derivative = function(series) {
          return _.map(series, function(p,i) {
            var _v;
            if(i === 0 || p[1] === null) {
              _v = [p[0],null];
            } else {
              _v = series[i-1][1] === null ? [p[0],null] : [p[0],p[1]-(series[i-1][1])];
            }
            return _v;
          });
        };

        // Function for rendering panel
        function render_panel(data) {
          // IE doesn't work without this
          try {
            elem.css({height:scope.row.height});
          } catch(e) {return;}

          // Populate from the query service
          try {
            _.each(data, function(series) {
              series.label = series.info.alias;
              series.color = series.info.color;
            });
          } catch(e) {return;}

          // Set barwidth based on specified interval
          var barwidth = kbn.interval_to_ms(scope.panel.interval);

          var stack = scope.panel.stack ? true : null;

          // Populate element
          try {
            var options = {
              legend: { show: false },
              series: {
                stackpercent: scope.panel.stack ? scope.panel.percentage : false,
                stack: scope.panel.percentage ? null : stack,
                lines:  {
                  show: scope.panel.lines,
                  // Silly, but fixes bug in stacked percentages
                  fill: scope.panel.fill === 0 ? 0.001 : scope.panel.fill/10,
                  lineWidth: scope.panel.linewidth,
                  steps: false
                },
                bars:   {
                  show: scope.panel.bars,
                  fill: 1,
                  barWidth: barwidth/1.5,
                  zero: false,
                  lineWidth: 0
                },
                points: {
                  show: scope.panel.points,
                  fill: 1,
                  fillColor: false,
                  radius: scope.panel.pointradius
                },
                shadowSize: 1
              },
              yaxis: {
                show: scope.panel['y-axis'],
                min: scope.panel.grid.min,
                max: scope.panel.percentage && scope.panel.stack ? 100 : scope.panel.grid.max
              },
              xaxis: {
                timezone: scope.panel.timezone,
                show: scope.panel['x-axis'],
                mode: "time",
                min: _.isUndefined(scope.range.from) ? null : scope.range.from.getTime(),
                max: _.isUndefined(scope.range.to) ? null : scope.range.to.getTime(),
                timeformat: time_format(scope.panel.interval),
                label: "Datetime",
                ticks: elem.width()/100
              },
              grid: {
                backgroundColor: null,
                borderWidth: 0,
                hoverable: true,
                color: '#c8c8c8'
              }
            };

            if (scope.panel.y_format === 'bytes') {
              options.yaxis.mode = "byte";
              options.yaxis.tickFormatter = function (val, axis) {
                return kbn.byteFormat(val, 0, axis.tickSize);
              };
            }

            if (scope.panel.y_format === 'short') {
              options.yaxis.tickFormatter = function (val, axis) {
                return kbn.shortFormat(val, 0, axis.tickSize);
              };
            }

            if(scope.panel.annotate.enable) {
              options.events = {
                clustering: true,
                levels: 1,
                data: scope.annotations,
                types: {
                  'annotation': {
                    level: 1,
                    icon: {
                      width: 20,
                      height: 21,
                      icon: "histogram-marker"
                    }
                  }
                }
                //xaxis: int    // the x axis to attach events to
              };
            }

            if(scope.panel.interactive) {
              options.selection = { mode: "x", color: '#666' };
            }

            // when rendering stacked bars, we need to ensure each point that has data is zero-filled
            // so that the stacking happens in the proper order
            var required_times = [];
            if (data.length > 1) {
              required_times = Array.prototype.concat.apply([], _.map(data, function (query) {
                return query.time_series.getOrderedTimes();
              }));
              required_times = _.uniq(required_times.sort(function (a, b) {
                // decending numeric sort
                return a-b;
              }), true);
            }

            for (var i = 0; i < data.length; i++) {
              var _d = data[i].time_series.getFlotPairs(required_times);
              if(scope.panel.derivative) {
                _d = derivative(_d);
              }
              if(scope.panel.scale !== 1) {
                _d = scale(_d,scope.panel.scale);
              }
              if(scope.panel.scaleSeconds) {
                _d = scaleSeconds(_d,scope.panel.interval);
              }
              data[i].data = _d;
            }

            plot = $.plot(elem, data, options);

          } catch(e) {
            // Nothing to do here
          }
        }

        function time_format(interval) {
          var _int = kbn.interval_to_seconds(interval);
          if(_int >= 2628000) {
            return "%Y-%m";
          }
          if(_int >= 86400) {
            return "%Y-%m-%d";
          }
          if(_int >= 60) {
            return "%H:%M
%m-%d";
          }

          return "%H:%M:%S";
        }

        var $tooltip = $('
');
        elem.bind("plothover", function (event, pos, item) {
          var group, value, timestamp, interval;
          interval = " per " + (scope.panel.scaleSeconds ? '1s' : scope.panel.interval);
          if (item) {
            if (item.series.info.alias || scope.panel.tooltip.query_as_alias) {
              group = '' +
                '' + ' ' +
                (item.series.info.alias || item.series.info.query)+
              '
';
            } else {
              group = kbn.query_color_dot(item.series.color, 15) + ' ';
            }
            value = (scope.panel.stack && scope.panel.tooltip.value_type === 'individual') ?
              item.datapoint[1] - item.datapoint[2] :
              item.datapoint[1];
            if(scope.panel.y_format === 'bytes') {
              value = kbn.byteFormat(value,2);
            }
            if(scope.panel.y_format === 'short') {
              value = kbn.shortFormat(value,2);
            } else {
              value = numeral(value).format('0,0[.]000');
            }
            timestamp = scope.panel.timezone === 'browser' ?
              moment(item.datapoint[0]).format('YYYY-MM-DD HH:mm:ss') :
              moment.utc(item.datapoint[0]).format('YYYY-MM-DD HH:mm:ss');
            $tooltip
              .html(
                group + value + interval + " @ " + timestamp
              )
              .place_tt(pos.pageX, pos.pageY);
          } else {
            $tooltip.detach();
          }
        });

        elem.bind("plotselected", function (event, ranges) {
          filterSrv.set({
            type  : 'time',
            from  : moment.utc(ranges.xaxis.from).toDate(),
            to    : moment.utc(ranges.xaxis.to).toDate(),
            field : scope.panel.time_field
          });
        });
      }
    };
  });

});


text:
;( function( $, window, undefined ) {

	'use strict';

	// http://www.hardcode.nl/subcategory_1/article_317-array-shuffle-function
	Array.prototype.shuffle = function() {
		var i=this.length,p,t;
		while (i--) {
			p = Math.floor(Math.random()*i);
			t = this[i];
			this[i]=this[p];
			this[p]=t;
		}
		return this;
	};

	/*
	* debouncedresize: special jQuery event that happens once after a window resize
	*
	* latest version and complete README available on Github:
	* https://github.com/louisremi/jquery-smartresize/blob/master/jquery.debouncedresize.js
	*
	* Copyright 2011 @louis_remi
	* Licensed under the MIT license.
	*/
	var $event = $.event,
	$special,
	resizeTimeout;

	$special = $event.special.debouncedresize = {
		setup: function() {
			$( this ).on( "resize", $special.handler );
		},
		teardown: function() {
			$( this ).off( "resize", $special.handler );
		},
		handler: function( event, execAsap ) {
			// Save the context
			var context = this,
				args = arguments,
				dispatch = function() {
					// set correct event type
					event.type = "debouncedresize";
					$event.dispatch.apply( context, args );
				};

			if ( resizeTimeout ) {
				clearTimeout( resizeTimeout );
			}

			execAsap ?
				dispatch() :
				resizeTimeout = setTimeout( dispatch, $special.threshold );
		},
		threshold: 50
	};

	// global
	var $window				= $( window ),
		Modernizr			= window.Modernizr;

	$.GridRotator			= function( options, element ) {

		this.$el	= $( element );
		if( Modernizr.backgroundsize ) {

			var _self = this;
			this.$el.addClass( 'ri-grid-loading' );

			$( '<img/>' ).load( function() {

				_self._init( options );

			} ).attr( 'src', '/static/mozillians/img/mosaic/loading.gif' );

		}

	};

	$.GridRotator.defaults	= {
		// number of rows
		rows			: 4,
		// number of columns
		columns			: 10,
		w1024			: {
			rows	: 3,
			columns	: 8
		},
		w768			: {
			rows	: 3,
			columns	: 7
		},
		w480			: {
			rows	: 3,
			columns	: 5
		},
		w320			: {
			rows	: 2,
			columns	: 4
		},
		w240			: {
			rows	: 2,
			columns	: 3
		},
		// step: number of items that are replaced at the same time
		// random || [some number]
		// note: for performance issues, the number "can't" be > options.maxStep
		step			: 'random',
		maxStep			: 3,
		// prevent user to click the items
		preventClick	: true,
		// animation type
		// showHide || fadeInOut || slideLeft ||
		// slideRight || slideTop || slideBottom ||
		// rotateLeft || rotateRight || rotateTop ||
		// rotateBottom || scale || rotate3d ||
		// rotateLeftScale || rotateRightScale ||
		// rotateTopScale || rotateBottomScale || random
		animType		: 'random',
		// animation speed
		animSpeed		: 500,
		// animation easings
		animEasingOut	: 'linear',
		animEasingIn	: 'linear',
		// the item(s) will be replaced every 3 seconds
		// note: for performance issues, the time "can't" be < 300 ms
		interval		: 3000
	};

	$.GridRotator.prototype	= {

		_init				: function( options ) {

			var _self			= this;

			// options
			this.options		= $.extend( true, {}, $.GridRotator.defaults, options );

			// all types of animations
			this.animTypesAll	= [ 'fadeInOut', 'slideLeft', 'slideRight', 'slideTop', 'slideBottom', 'rotateLeft', 'rotateRight', 'rotateTop', 'rotateBottom', 'scale', 'rotate3d', 'rotateLeftScale', 'rotateRightScale', 'rotateTopScale', 'rotateBottomScale' ];
			// types of animations for "older" browsers
			this.animTypesCond	= [ 'fadeInOut', 'slideLeft', 'slideRight', 'slideTop', 'slideBottom' ];

			// array containing the animation types to choose from when the options.animType is set to 'random'
			this.animTypes		= this.animTypesCond;
			if( Modernizr.csstransforms3d ) {

				this.animTypes = this.animTypesAll;

			}

			this.animType		= this.options.animType;
			if( this.animType !== 'random' ) {

				if( !Modernizr.csstransforms3d && $.inArray( this.animType, this.animTypesCond ) === -1 && this.animType !== 'showHide' ) {

					// fallback to 'fadeInOut' if user sets a type which is not supported
					this.animType = 'fadeInOut';

				}

			}
			this.animTypesTotal	= this.animTypes.length;

			// the <ul> where the items are placed
			this.$list			= this.$el.children( 'ul' );
			// remove img's and add background-image to anchors
			// preload the images before
			var loaded			= 0,
				$imgs			= this.$list.find( 'img' ),
				count			= $imgs.length;

			$imgs.each( function() {

				var $img	= $( this ),
					src		= $img.attr( 'src' );

				$( '<img/>' ).load( function() {

					++loaded;
					$img.parent().css( 'background-image', 'url(' + src + ')' );
					if( loaded === count ) {

						$imgs.remove();

						_self.$el.removeClass( 'ri-grid-loading' );

			// the items
						_self.$items		= _self.$list.children( 'li' );
			// make a copy of the items
						_self.$itemsCache	= _self.$items.clone();
			// total number of items
						_self.itemsTotal	= _self.$items.length;
			// the items that will be out of the grid
			// actually the item's child (anchor element)
						_self.outItems		= [];

						_self._layout();
						_self._initEvents();
			// replace "options.step" items after "options.interval" time
			// the items that go out are randomly chosen, while the ones that get in
			// respect the order (first in first out)
						_self._start();

					}

				} ).attr( 'src', src )

			} );

		},
		_layout				: function( callback ) {

			var _self		= this;

			// sets the grid dimentions based on the container's width
			this._setGridDim();

			// reset
			this.$list.empty();
			this.$items		= this.$itemsCache.clone().appendTo( this.$list );

			var $outItems	= this.$items.filter( ':gt(' + ( this.showTotal - 1 ) + ')' ),
				$outAItems	= $outItems.children( 'a' );

			this.outItems.length = 0;

			$outAItems.each( function( i ) {

				_self.outItems.push( $( this ) );

			} );

			$outItems.remove();

				// container's width
			var containerWidth	= ( document.defaultView ) ? parseInt( document.defaultView.getComputedStyle( this.$el.get( 0 ), null ).width ) : this.$el.width(),
				// item's width
				itemWidth		= Math.floor( containerWidth / this.columns ),
				// calculate gap
				gapWidth		= containerWidth - ( this.columns * Math.floor( itemWidth ) );

			for( var i = 0; i < this.rows; ++i ) {

				for( var j = 0; j < this.columns; ++j ) {

					var $item	= this.$items.eq( this.columns * i + j ),
						h		= itemWidth,
						w		= ( j < Math.floor( gapWidth ) ) ? itemWidth + 1 : itemWidth;

					$item.css( {
						width	: w,
						height	: h
					} );

/*
					if( gapWidth % 1 !== 0 && j === this.columns - 1 ) {

						$item.children( 'a' ).css( {
							width	: '+=1',
							height	: '+=1'
						} );

					}
*/

				}

			}

			if( this.options.preventClick ) {

				this.$items.children().css( 'cursor', 'default' ).on( 'click.gridrotator', false );

			}

			if( callback ) {

				callback.call();

			}

		},
		// set the grid rows and columns
		_setGridDim			: function() {

			// container's width
			var c_w			= this.$el.width();

			// we will choose the number of rows/columns according to the container's width and the values set on the plugin options
			switch( true ) {

				case ( c_w < 240 )	: this.rows = this.options.w240.rows; this.columns = this.options.w240.columns; break;
				case ( c_w < 320 )	: this.rows = this.options.w320.rows; this.columns = this.options.w320.columns; break;
				case ( c_w < 480 )	: this.rows = this.options.w480.rows; this.columns = this.options.w480.columns; break;
				case ( c_w < 768 )	: this.rows = this.options.w768.rows; this.columns = this.options.w768.columns; break;
				case ( c_w < 1024 )	: this.rows = this.options.w1024.rows; this.columns = this.options.w1024.columns; break;
				default				: this.rows = this.options.rows; this.columns = this.options.columns; break;

			}

			this.showTotal	= this.rows * this.columns;

		},
		// init window resize event
		_initEvents			: function() {

			var _self = this;

			$window.on( 'debouncedresize.gridrotator', function( event ) {

				clearTimeout( _self.playtimeout );

				_self._layout( function() {

					_self._start();

				} );

			} );

		},
		// start rotating elements
		_start				: function() {

			if( this.showTotal < this.itemsTotal ) {

				this._showNext();

			}

		},
		// get which type of animation
		_getAnimType		: function() {

			if( this.animType === 'random' ) {

				return this.animTypes[ Math.floor( Math.random() * this.animTypesTotal ) ];

			}
			else {

				return this.animType;

			}

		},
		// get css properties for the transition effect
		_getAnimProperties 	: function( $in, $out ) {

			var startInProp		= {},
				startOutProp	= {},
				endInProp		= {},
				endOutProp		= {},

				animType		= this._getAnimType(),
				speed;

			switch( animType ) {

				case 'showHide'	:
					speed = 0;

					endOutProp.opacity	= 0;

					break;
				case 'fadeInOut'	:
					endOutProp.opacity	= 0;

					break;
				case 'slideLeft'	:
					startInProp.left 	= $out.width();

					endInProp.left		= 0;
					endOutProp.left		= -$out.width();

					break;
				case 'slideRight'	:
					startInProp.left 	= -$out.width();

					endInProp.left		= 0;
					endOutProp.left		= $out.width();

					break;
				case 'slideTop'		:
					startInProp.top 	= $out.height();

					endInProp.top		= 0;
					endOutProp.top		= -$out.height();

					break;
				case 'slideBottom'	:
					startInProp.top 	= -$out.height();

					endInProp.top		= 0;
					endOutProp.top		= $out.height();

					break;
				case 'rotateLeft'	:
					speed					= this.options.animSpeed / 2;

					startInProp.rotateY		= '90deg';

					endInProp.rotateY		= '0deg';
					endInProp.delay			= speed;
					endOutProp.rotateY		= '-90deg';

					break;
				case 'rotateRight'	:
					speed					= this.options.animSpeed / 2;

					startInProp.rotateY		= '-90deg';

					endInProp.rotateY		= '0deg';
					endInProp.delay			= speed;
					endOutProp.rotateY		= '90deg';

					break;
				case 'rotateTop'	:
					speed					= this.options.animSpeed / 2;

					startInProp.rotateX		= '90deg';

					endInProp.rotateX		= '0deg';
					endInProp.delay			= speed;
					endOutProp.rotateX		= '-90deg';

					break;
				case 'rotateBottom'	:
					speed					= this.options.animSpeed / 2;

					startInProp.rotateX		= '-90deg';

					endInProp.rotateX		= '0deg';
					endInProp.delay			= speed;
					endOutProp.rotateX		= '90deg';

					break;
				case 'scale'		:
					speed					= this.options.animSpeed / 2;

					startInProp.scale		= '0';
					startOutProp.scale		= '1';

					endInProp.scale			= '1';
					endInProp.delay			= speed;
					endOutProp.scale		= '0';

					break;
				case 'rotateLeftScale'	:
					startInProp.scale		= '0.3';
					startOutProp.scale		= '1';
					endInProp.scale			= '1';
					endOutProp.scale		= '0.3';

					speed					= this.options.animSpeed / 2;

					startInProp.rotateY		= '90deg';

					endInProp.rotateY		= '0deg';
					endInProp.delay			= speed;
					endOutProp.rotateY		= '-90deg';

					break;
				case 'rotateRightScale'	:
					startInProp.scale		= '0.3';
					startOutProp.scale		= '1';
					endInProp.scale			= '1';
					endOutProp.scale		= '0.3';

					speed					= this.options.animSpeed / 2;

					startInProp.rotateY		= '-90deg';

					endInProp.rotateY		= '0deg';
					endInProp.delay			= speed;
					endOutProp.rotateY		= '90deg';

					break;
				case 'rotateTopScale'	:
					startInProp.scale		= '0.3';
					startOutProp.scale		= '1';
					endInProp.scale			= '1';
					endOutProp.scale		= '0.3';

					speed					= this.options.animSpeed / 2;

					startInProp.rotateX		= '90deg';

					endInProp.rotateX		= '0deg';
					endInProp.delay			= speed;
					endOutProp.rotateX		= '-90deg';

					break;
				case 'rotateBottomScale'	:
					startInProp.scale		= '0.3';
					startOutProp.scale		= '1';
					endInProp.scale			= '1';
					endOutProp.scale		= '0.3';

					speed					= this.options.animSpeed / 2;

					startInProp.rotateX		= '-90deg';

					endInProp.rotateX		= '0deg';
					endInProp.delay			= speed;
					endOutProp.rotateX		= '90deg';

					break;
				case 'rotate3d'		:
					speed					= this.options.animSpeed / 2;

					startInProp.rotate3d	= '1, 1, 0, 90deg';

					endInProp.rotate3d		= '1, 1, 0, 0deg';
					endInProp.delay			= speed;
					endOutProp.rotate3d		= '1, 1, 0, -90deg';

					break;

			}

			var animSpeed = ( speed != undefined ) ? speed : this.options.animSpeed;

			return {
				startInProp		: startInProp,
				startOutProp	: startOutProp,
				endInProp		: endInProp,
				endOutProp		: endOutProp,
				animSpeed		: animSpeed
			};

		},
		// show next "option.step" elements
		_showNext			: function( t ) {

			var _self = this;

			clearTimeout( this.playtimeout );

			this.playtimeout = setTimeout( function() {

				var step		= _self.options.step,
					max			= _self.options.maxStep,
					min			= 1;

				if( max > _self.showTotal ) {

					max = _self.showTotal;

				}

				var $items	= _self.$items,
					outs	= [],
					// number of items to swith at this point of time
					nmbOut	= ( step === 'random' ) ? Math.floor( Math.random() * max + min ) : Math.min( Math.abs( step ) , max ) ,
					// array with random indexes. These will be the indexes of the items we will replace
					randArr	= _self._getRandom( nmbOut, _self.showTotal );

				for( var i = 0; i < nmbOut; ++i ) {

					// element to go out
					var $out = $items.eq( randArr[ i ] );

					// if element is active, which means it is currently animating,
					// then we need to get different positions..
					if( $out.data( 'active' ) ) {

						// one of the items is active, call again..
						_self._showNext( 1 );
						return false;

					}

					// add it to outs array
					outs.push( $out );

				}

				for( var i = 0; i < nmbOut; ++i ) {

					var $out		= outs[ i ],
						$outA		= $out.children( 'a:last' ),
						newElProp	= {
							width	: $outA.width(),
							height	: $outA.height()
						};

					// element stays active
					$out.data( 'active', true );

					// get the element (anchor) that will go in (first one inserted in _self.outItems)
					var $inA		= _self.outItems.shift();

					// save element that went out
					_self.outItems.push( $outA.clone() );

					// prepend in element
					$inA.css( newElProp ).prependTo( $out );

					var animProp	= _self._getAnimProperties( $inA, $outA );

					if( Modernizr.csstransitions ) {

						$inA.css( animProp.startInProp ).transition( animProp.endInProp, animProp.animSpeed, _self.options.animEasingIn );
						$outA.css( animProp.startOutProp ).transition( animProp.endOutProp, animProp.animSpeed, _self.options.animEasingOut, function() {

							$( this ).parent().data( 'active', false ).end().remove();

						} );

					}

					// fallback to jQuery animate
					else {

						$inA.css( animProp.startInProp ).stop().animate( animProp.endInProp, animProp.animSpeed );
						$outA.css( animProp.startOutProp ).stop().animate( animProp.endOutProp, animProp.animSpeed, function() {

							$( this ).parent().data( 'active', false ).end().remove();

						} )

					}

				}

				// again and again..
				_self._showNext();

			}, t || Math.max( Math.abs( this.options.interval ) , 300 ) );

		},
		_getRandom			: function( cnt, limit ) {

			var randArray = [];

			for( var i = 0; i < limit; ++i ) {

				randArray.push( i )

			}

			return randArray.shuffle().slice(0,cnt);

		}

	};

	var logError		= function( message ) {

		if ( window.console ) {

			window.console.error( message );

		}

	};

	$.fn.gridrotator	= function( options ) {

		if ( typeof options === 'string' ) {

			var args = Array.prototype.slice.call( arguments, 1 );

			this.each(function() {

				var instance = $.data( this, 'gridrotator' );

				if ( !instance ) {

					logError( "cannot call methods on gridrotator prior to initialization; " +
					"attempted to call method '" + options + "'" );
					return;

				}

				if ( !$.isFunction( instance[options] ) || options.charAt(0) === "_" ) {

					logError( "no such method '" + options + "' for gridrotator instance" );
					return;

				}

				instance[ options ].apply( instance, args );

			});

		}
		else {

			this.each(function() {

				var instance = $.data( this, 'gridrotator' );

				if ( instance ) {

					instance._init();

				}
				else {

					$.data( this, 'gridrotator', new $.GridRotator( options, this ) );

				}

			});

		}

		return this;

	};

} )( jQuery, window );


text:
<?php

/**
 * @file
 * Contains \Drupal\Core\Access\RouteProcessorCsrf.
 */

namespace Drupal\Core\Access;

use Drupal\Core\Render\BubbleableMetadata;
use Drupal\Core\RouteProcessor\OutboundRouteProcessorInterface;
use Symfony\Component\Routing\Route;

/**
 * Processes the outbound route to handle the CSRF token.
 */
class RouteProcessorCsrf implements OutboundRouteProcessorInterface {

  /**
   * The CSRF token generator.
   *
   * @var \Drupal\Core\Access\CsrfTokenGenerator
   */
  protected $csrfToken;

  /**
   * Constructs a RouteProcessorCsrf object.
   *
   * @param \Drupal\Core\Access\CsrfTokenGenerator $csrf_token
   *   The CSRF token generator.
   */
  function __construct(CsrfTokenGenerator $csrf_token) {
    $this->csrfToken = $csrf_token;
  }

  /**
   * {@inheritdoc}
   */
  public function processOutbound($route_name, Route $route, array &$parameters, BubbleableMetadata $bubbleable_metadata = NULL) {
    if ($route->hasRequirement('_csrf_token')) {
      $path = ltrim($route->getPath(), '/');
      // Replace the path parameters with values from the parameters array.
      foreach ($parameters as $param => $value) {
        $path = str_replace("{{$param}}", $value, $path);
      }
      // Adding this to the parameters means it will get merged into the query
      // string when the route is compiled.
      if (!$bubbleable_metadata) {
        $parameters['token'] = $this->csrfToken->get($path);
      }
      else {
        // Generate a placeholder and a render array to replace it.
        $placeholder = hash('sha1', $path);
        $placeholder_render_array = [
          '#lazy_builder' => ['route_processor_csrf:renderPlaceholderCsrfToken', [$path]],
        ];

        // Instead of setting an actual CSRF token as the query string, we set
        // the placeholder, which will be replaced at the very last moment. This
        // ensures links with CSRF tokens don't break cacheability.
        $parameters['token'] = $placeholder;
        $bubbleable_metadata->addAttachments(['placeholders' => [$placeholder => $placeholder_render_array]]);
      }
    }
  }

  /**
   * #lazy_builder callback; gets a CSRF token for the given path.
   *
   * @param string $path
   *   The path to get a CSRF token for.
   *
   * @return array
   *   A renderable array representing the CSRF token.
   */
  public function renderPlaceholderCsrfToken($path) {
    return [
      '#markup' => $this->csrfToken->get($path),
      // Tokens are per session.
      '#cache' => [
        'contexts' => [
          'session',
        ],
      ],
    ];
  }

}


text:
exports.topic = {
  type: "Topic",
  description: "Corresponding topic for this markdown",
  resolve(source, args, context /*, info*/) {
    if (!source.fields || !source.fields.isTopic) return
    const { name } = source.fields

    return context.nodeModel
      .getAllNodes({ type: "Topic" })
      .find(t => t.name === name)
  },
}


text:
<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/texview"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:gravity="center"
    android:padding="20dp"
    android:text="@string/copyrights"
    android:textAppearance="?android:attr/textAppearanceMedium"
    android:textColor="@color/wallet_bright_foreground_holo_light" />


text:
package rocfox.rdf2xml.transformation.dom;

import rocfox.rdf2xml.select.dom.SelectExpression;

/**
 *
 * @author Nicolas
 */
public class ValueOf implements TransformNode
{
	public static final String ElementName = "value-of";

	public static final String AttributeNameSelect = "select";

	private SelectExpression select;

	public SelectExpression getSelect()
	{
		return select;
	}

	public void setSelect(SelectExpression select)
	{
		this.select = select;
	}
}


text:
#ifndef __TZC_COMMON_H__
#define __TZC_COMMON_H__

/*
 * Offset of core registers from the start of the base of configuration
 * registers for each region.
 */

/* ID Registers */
#define PID0_OFF					0xfe0
#define PID1_OFF					0xfe4
#define PID2_OFF					0xfe8
#define PID3_OFF					0xfec
#define PID4_OFF					0xfd0
#define CID0_OFF					0xff0
#define CID1_OFF					0xff4
#define CID2_OFF					0xff8
#define CID3_OFF					0xffc

/* Bit positions of TZC_ACTION registers */
#define TZC_ACTION_RV_SHIFT				0
#define TZC_ACTION_RV_MASK				0x3
#define TZC_ACTION_RV_LOWOK				0x0
#define TZC_ACTION_RV_LOWERR				0x1
#define TZC_ACTION_RV_HIGHOK				0x2
#define TZC_ACTION_RV_HIGHERR				0x3

/* Used along with 'tzc_region_attributes_t' below */
#define TZC_REGION_ATTR_S_RD_SHIFT			30
#define TZC_REGION_ATTR_S_WR_SHIFT			31
#define TZC_REGION_ATTR_F_EN_SHIFT			0
#define TZC_REGION_ATTR_SEC_SHIFT			30
#define TZC_REGION_ATTR_S_RD_MASK			0x1
#define TZC_REGION_ATTR_S_WR_MASK			0x1
#define TZC_REGION_ATTR_SEC_MASK			0x3

#define TZC_REGION_ACCESS_WR_EN_SHIFT			16
#define TZC_REGION_ACCESS_RD_EN_SHIFT			0
#define TZC_REGION_ACCESS_ID_MASK			0xf

/* Macros for allowing Non-Secure access to a region based on NSAID */
#define TZC_REGION_ACCESS_RD(nsaid)				\
	((1 << (nsaid & TZC_REGION_ACCESS_ID_MASK)) <<		\
	 TZC_REGION_ACCESS_RD_EN_SHIFT)
#define TZC_REGION_ACCESS_WR(nsaid)				\
	((1 << (nsaid & TZC_REGION_ACCESS_ID_MASK)) <<		\
	 TZC_REGION_ACCESS_WR_EN_SHIFT)
#define TZC_REGION_ACCESS_RDWR(nsaid)				\
	(TZC_REGION_ACCESS_RD(nsaid) |				\
	TZC_REGION_ACCESS_WR(nsaid))

#ifndef __ASSEMBLY__

/* Returns offset of registers to program for a given region no */
#define TZC_REGION_OFFSET(region_size, region_no)	\
				((region_size) * (region_no))

/*
 * What type of action is expected when an access violation occurs.
 * The memory requested is returned as zero. But we can also raise an event to
 * let the system know it happened.
 * We can raise an interrupt(INT) and/or cause an exception(ERR).
 *  TZC_ACTION_NONE    - No interrupt, no Exception
 *  TZC_ACTION_ERR     - No interrupt, raise exception -> sync external
 *                       data abort
 *  TZC_ACTION_INT     - Raise interrupt, no exception
 *  TZC_ACTION_ERR_INT - Raise interrupt, raise exception -> sync
 *                       external data abort
 */
typedef enum {
	TZC_ACTION_NONE = 0,
	TZC_ACTION_ERR = 1,
	TZC_ACTION_INT = 2,
	TZC_ACTION_ERR_INT = (TZC_ACTION_ERR | TZC_ACTION_INT)
} tzc_action_t;

/*
 * Controls secure access to a region. If not enabled secure access is not
 * allowed to region.
 */
typedef enum {
	TZC_REGION_S_NONE = 0,
	TZC_REGION_S_RD = 1,
	TZC_REGION_S_WR = 2,
	TZC_REGION_S_RDWR = (TZC_REGION_S_RD | TZC_REGION_S_WR)
} tzc_region_attributes_t;

#endif /* __ASSEMBLY__ */
#endif /* __TZC_COMMON_H__ */


text:
package sandbox;

import com.almasb.fxgl.app.GameApplication;
import com.almasb.fxgl.app.GameSettings;
import com.almasb.fxgl.dsl.components.ExpireCleanComponent;
import com.almasb.fxgl.entity.components.CollidableComponent;
import com.almasb.fxgl.input.UserAction;
import com.almasb.fxgl.physics.BoundingShape;
import com.almasb.fxgl.physics.HitBox;
import com.almasb.fxgl.physics.PhysicsComponent;
import com.almasb.fxgl.physics.box2d.dynamics.BodyType;
import com.almasb.fxgl.physics.box2d.dynamics.FixtureDef;
import javafx.scene.input.MouseButton;
import javafx.scene.paint.Color;
import javafx.util.Duration;

import static com.almasb.fxgl.dsl.FXGL.*;

/**
 * @author Almas Baimagambetov (AlmasB) (almaslvl@gmail.com)
 */
public class PhysicsBounceSample extends GameApplication {

    private enum TType {
        BULLET, WALL
    }

    @Override
    protected void initSettings(GameSettings settings) {
        settings.setWidth(1280);
        settings.setHeight(720);
    }

    @Override
    protected void initInput() {
        getInput().addAction(new UserAction("LMB") {
            private double x;
            private double y;

            @Override
            protected void onActionBegin() {
                x = getInput().getMouseXWorld();
                y = getInput().getMouseYWorld();
            }

            @Override
            protected void onActionEnd() {
                var endx = getInput().getMouseXWorld();
                var endy = getInput().getMouseYWorld();

                spawnBullet(x, y, endx - x, endy - y);
            }
        }, MouseButton.PRIMARY);
    }

    @Override
    protected void initGame() {
        getGameScene().setBackgroundColor(Color.LIGHTGRAY);

        var screenBounds = entityBuilder().buildScreenBoundsAndAttach(50);

        screenBounds.addComponent(new CollidableComponent(true));
        screenBounds.setType(TType.WALL);
    }

    @Override
    protected void initPhysics() {
        onCollisionBegin(TType.WALL, TType.BULLET, (wall, bullet) -> {
            var vx = bullet.getComponent(PhysicsComponent.class).getVelocityX();
            var vy = bullet.getComponent(PhysicsComponent.class).getVelocityY();

            // limit proximity spawns to 10
            if (getGameWorld().getEntitiesInRange(bullet.getBoundingBoxComponent().range(100, 100)).size() < 10) {
                spawnBullet(bullet.getX() + 30 * -Math.signum(vx), bullet.getY() + 30 * -Math.signum(vy), -Math.signum(vx) * 20, -Math.signum(vy) * 20);
            }
        });
    }

    private void spawnBullet(double x, double y, double vx, double vy) {
        var physics = new PhysicsComponent();
        physics.setFixtureDef(new FixtureDef().density(25.5f).restitution(0.36f));
        physics.setBodyType(BodyType.DYNAMIC);

        physics.setOnPhysicsInitialized(() -> {
            physics.setLinearVelocity(vx * 10, vy * 10);
        });

        entityBuilder()
                .at(x, y)
                .type(TType.BULLET)
                .bbox(new HitBox(BoundingShape.circle(450 / 15.0 / 2.0)))
                .view(texture("ball.png", 450 / 15.0, 449 / 15.0))
                .with(physics)
                .with(new ExpireCleanComponent(Duration.seconds(5)).animateOpacity())
                .collidable()
                .buildAndAttach();
    }

    public static void main(String[] args) {
        launch(args);
    }
}


text:
package com.github.barteksc.pdfviewer.model;

import android.graphics.RectF;

import com.shockwave.pdfium.PdfDocument;

public class LinkTapEvent {
    private float originalX;
    private float originalY;
    private float documentX;
    private float documentY;
    private RectF mappedLinkRect;
    private PdfDocument.Link link;

    public LinkTapEvent(float originalX, float originalY, float documentX, float documentY, RectF mappedLinkRect, PdfDocument.Link link) {
        this.originalX = originalX;
        this.originalY = originalY;
        this.documentX = documentX;
        this.documentY = documentY;
        this.mappedLinkRect = mappedLinkRect;
        this.link = link;
    }

    public float getOriginalX() {
        return originalX;
    }

    public float getOriginalY() {
        return originalY;
    }

    public float getDocumentX() {
        return documentX;
    }

    public float getDocumentY() {
        return documentY;
    }

    public RectF getMappedLinkRect() {
        return mappedLinkRect;
    }

    public PdfDocument.Link getLink() {
        return link;
    }
}