text:
{-# LANGUAGE OverloadedStrings, RankNTypes, RecordWildCards,
    ScopedTypeVariables #-}
{-# OPTIONS_GHC -fno-warn-incomplete-patterns -fno-warn-missing-signatures
    -fno-warn-unused-binds #-}

module UnitTests (testWith) where

import Control.Arrow (first)
import Control.Applicative ((<$>))
import Control.Concurrent (forkIO, killThread)
import Control.Concurrent.MVar (newEmptyMVar, putMVar, takeMVar)
import Control.Exception (Exception, throwIO)
import Control.Lens ((^.), (^?), (.~), (?~), (&), iso, ix, Traversal')
import Control.Monad (unless, void)
import Data.Aeson hiding (Options)
import Data.Aeson.Lens (key, AsValue, _Object)
import Data.ByteString (ByteString)
import Data.Char (toUpper)
import Data.Maybe (isJust)
import Data.Monoid ((<>))
import HttpBin.Server (serve)
import Network.HTTP.Client (HttpException(..), HttpExceptionContent(..))
import Network.HTTP.Types.Status (status200, status401)
import Network.HTTP.Types.Version (http11)
import Network.Wreq hiding
  (get, post, head_, put, options, delete,
   getWith, postWith, headWith, putWith, optionsWith, deleteWith)
import Network.Wreq.Lens
import Network.Wreq.Types (Postable, Putable)
import Snap.Http.Server.Config
import System.IO (hClose, hPutStr)
import System.IO.Temp (withSystemTempFile)
import Test.Framework (Test, defaultMain, testGroup)
import Test.Framework.Providers.HUnit (testCase)
import Test.HUnit (assertBool, assertEqual, assertFailure)
import qualified Control.Exception as E
import qualified Data.CaseInsensitive as CI
import qualified Data.HashMap.Strict as HMap
import qualified Data.Text as T
import qualified Network.Wreq.Session as Session
import qualified Data.ByteString.Lazy as L
import qualified Network.Wreq as Wreq

data Verb = Verb {
    get :: String -> IO (Response L.ByteString)
  , getWith :: Options -> String -> IO (Response L.ByteString)
  , post :: forall a. Postable a => String -> a -> IO (Response L.ByteString)
  , postWith :: forall a. Postable a => Options -> String -> a
             -> IO (Response L.ByteString)
  , head_ :: String -> IO (Response ())
  , headWith :: Options -> String -> IO (Response ())
  , put :: forall a. Putable a => String -> a -> IO (Response L.ByteString)
  , putWith :: forall a. Putable a => Options -> String -> a -> IO (Response L.ByteString)
  , options :: String -> IO (Response ())
  , optionsWith :: Options -> String -> IO (Response ())
  , delete :: String -> IO (Response L.ByteString)
  , deleteWith :: Options -> String -> IO (Response L.ByteString)
  }

basic :: Verb
basic = Verb { get = Wreq.get, getWith = Wreq.getWith, post = Wreq.post
             , postWith = Wreq.postWith, head_ = Wreq.head_
             , headWith = Wreq.headWith, put = Wreq.put
             , putWith = Wreq.putWith, options = Wreq.options
             , optionsWith = Wreq.optionsWith, delete = Wreq.delete
             , deleteWith = Wreq.deleteWith }

session :: Session.Session -> Verb
session s = Verb { get = Session.get s
                 , getWith = flip Session.getWith s
                 , post = Session.post s
                 , postWith = flip Session.postWith s
                 , head_ = Session.head_ s
                 , headWith = flip Session.headWith s
                 , put = Session.put s
                 , putWith = flip Session.putWith s
                 , options = Session.options s
                 , optionsWith = flip Session.optionsWith s
                 , delete = Session.delete s
                 , deleteWith = flip Session.deleteWith s }

-- Helper aeson lens for case insensitive keys
-- The test 'snap' server unfortunately lowercases all headers, we have to be case-insensitive
-- when checking the returned header list.
cikey :: AsValue t => T.Text -> Traversal' t Value
cikey i = _Object . toInsensitive . ix (CI.mk i)
  where
    toInsensitive = iso toCi fromCi
    toCi = HMap.fromList . map (first CI.mk) . HMap.toList
    fromCi = HMap.fromList . map (first CI.original) . HMap.toList

basicGet Verb{..} site = do
  r <- get (site "/get")
  assertBool "GET request has User-Agent header" $
    isJust (r ^. responseBody ^? key "headers" . cikey "User-Agent")
  -- test the various lenses
  assertEqual "GET succeeds" status200 (r ^. responseStatus)
  assertEqual "GET succeeds 200" 200 (r ^. responseStatus . statusCode)
  assertEqual "GET succeeds OK" "OK" (r ^. responseStatus . statusMessage)
  assertEqual "GET response has HTTP/1.1 version" http11 (r ^. responseVersion)
  assertBool "GET response has Content-Type header" $
    isJust (r ^? responseHeader "Content-Type")
  assertBool "GET response has Date header" $
    isJust (lookup "Date" <$> r ^? responseHeaders)

basicPost Verb{..} site = do
  r <- post (site "/post") ("wibble" :: ByteString) >>= asValue
  let body = r ^. responseBody
  assertEqual "POST succeeds" status200 (r ^. responseStatus)
  assertEqual "POST echoes input" (Just "wibble") (body ^? key "data")
  assertEqual "POST is binary" (Just "application/octet-stream")
                               (body ^? key "headers" . cikey "Content-Type")

multipartPost Verb{..} site =
  withSystemTempFile "foo.html" $ \name handle -> do
    hPutStr handle "<!DOCTYPE html><html></html"
    hClose handle
    r <- post (site "/post") (partFile "html" name)
    assertEqual "POST succeeds" status200 (r ^. responseStatus)

basicHead Verb{..} site = do
  r <- head_ (site "/get")
  assertEqual "HEAD succeeds" status200 (r ^. responseStatus)

basicPut Verb{..} site = do
  r <- put (site "/put") ("wibble" :: ByteString)
  assertEqual "PUT succeeds" status200 (r ^. responseStatus)

data SolrAdd = SolrAdd
    { doc          :: String
    , boost        :: Float
    , overwrite    :: Bool
    , commitWithin :: Integer
    }

instance ToJSON SolrAdd where
    toJSON (SolrAdd doc boost overwrite commitWithin) =
        object
            [
                "add" .= object
                [ "doc" .= toJSON doc
                , "boost" .= boost
                , "overwrite" .= overwrite
                , "commitWithin" .= commitWithin
                ]
            ]

solrAdd :: SolrAdd
solrAdd = SolrAdd "wibble" 1.0 True 10000

jsonPut Verb{..} site = do
  r <- put (site "/put") $ toJSON solrAdd
  assertEqual "toJSON PUT request has correct Content-Type header"
    (Just "application/json")
    (r ^. responseBody ^? key "headers" . cikey "Content-Type")

byteStringPut Verb{..} site = do
  let opts = defaults & header "Content-Type" .~ ["application/json"]
  r <- putWith opts (site "/put") $ encode solrAdd
  assertEqual "ByteString PUT request has correct Content-Type header"
    (Just "application/json")
    (r ^. responseBody ^? key "headers" . cikey "Content-Type")

basicDelete Verb{..} site = do
  r <- delete (site "/delete")
  assertEqual "DELETE succeeds" status200 (r ^. responseStatus)

throwsStatusCode Verb{..} site =
    assertThrows "404 causes exception to be thrown" inspect $
    head_ (site "/status/404")
  where inspect (HttpExceptionRequest _ e) = case e of
                      StatusCodeException _ _ -> return ()
                      _ -> assertFailure "unexpected exception thrown"
        inspect _ = assertFailure "unexpected exception thrown"

getBasicAuth Verb{..} site = do
  let opts = defaults & auth ?~ basicAuth "user" "passwd"
  r <- getWith opts (site "/basic-auth/user/passwd")
  assertEqual "basic auth GET succeeds" status200 (r ^. responseStatus)
  let inspect (HttpExceptionRequest _ e) = case e of
                    StatusCodeException resp _ ->
                      assertEqual "basic auth failed GET gives 401"
                        status401 (resp ^. responseStatus)
      inspect _ = assertFailure "unexpected exception thrown"

  assertThrows "basic auth GET fails if password is bad" inspect $
    getWith opts (site "/basic-auth/user/asswd")

getOAuth2 Verb{..} kind ctor site = do
  let opts = defaults & auth ?~ ctor "token1234"
  r <- getWith opts (site $ "/oauth2/" <> kind <> "/token1234")
  assertEqual ("oauth2 " <> kind <> " GET succeeds")
    status200 (r ^. responseStatus)
  let inspect (HttpExceptionRequest _ e) = case e of
                    StatusCodeException resp _ ->
                      assertEqual ("oauth2 " <> kind <> " failed GET gives 401")
                        status401 (resp ^. responseStatus)
      inspect _ = assertFailure "unexpected exception thrown"
  assertThrows ("oauth2 " <> kind <> " GET fails if token is bad") inspect $
    getWith opts (site $ "/oauth2/" <> kind <> "/token123")

getRedirect Verb{..} site = do
  r <- get (site "/redirect/3")
  let stripProto = T.dropWhile (/=':')
      smap f (String s) = String (f s)
  assertEqual "redirect goes to /get"
    (Just . String . stripProto . T.pack . site $ "/get")
    (smap stripProto <$> (r ^. responseBody ^? key "url"))

getParams Verb{..} site = do
  let opts1 = defaults & param "foo" .~ ["bar"]
  r1 <- getWith opts1 (site "/get")
  assertEqual "params set correctly 1" (Just (object [("foo","bar")]))
    (r1 ^. responseBody ^? key "args")
  let opts2 = defaults & params .~ [("quux","baz")]
  r2 <- getWith opts2 (site "/get")
  assertEqual "params set correctly 2" (Just (object [("quux","baz")]))
    (r2 ^. responseBody ^? key "args")
  r3 <- getWith opts2 (site "/get?whee=wat")
  assertEqual "correctly handle mix of params from URI and Options"
    (Just (object [("quux","baz"),("whee","wat")]))
    (r3 ^. responseBody ^? key "args")

getHeaders Verb{..} site = do
  let opts = defaults & header "X-Wibble" .~ ["bar"]
  r <- getWith opts (site "/get")
  assertEqual "extra header set correctly"
    (Just "bar")
    (r ^. responseBody ^? key "headers" . cikey "X-Wibble")

getCheckStatus Verb {..} site = do
  let opts = defaults & checkResponse .~ Just customRc
  r <- getWith opts (site "/status/404")
  assertThrows "Non 404 throws error" inspect $
    getWith opts (site "/get")
  assertEqual "Status 404"
    404
    (r ^. responseStatus . statusCode)
  where
    customRc :: ResponseChecker
    customRc _ resp
        | resp ^. responseStatus . statusCode == 404 = return ()
    customRc req resp = throwIO $ HttpExceptionRequest req (StatusCodeException (void resp) "")

    inspect (HttpExceptionRequest _ e) = case e of
        (StatusCodeException resp _) ->
            assertEqual "200 Status Error" (resp ^. responseStatus) status200
    inspect _ = assertFailure "unexpected exception thrown"

getGzip Verb{..} site = do
  r <- get (site "/gzip")
  assertEqual "gzip decoded for us" (Just (Bool True))
    (r ^. responseBody ^? key "gzipped")

headRedirect Verb{..} site = do
  assertThrows "HEAD of redirect throws exception" inspect $
    head_ (site "/redirect/3")
  where inspect (HttpExceptionRequest _ e) = case e of
                      StatusCodeException resp _ ->
                        let code = resp ^. responseStatus . statusCode
                        in assertBool "code is redirect"
                           (code >= 300 && code < 400)
        inspect _ = assertFailure "unexpected exception thrown"

redirectOverflow Verb{..} site =
  assertThrows "GET with too many redirects throws exception" inspect $
    getWith (defaults & redirects .~ 3) (site "/redirect/5")
  where inspect (HttpExceptionRequest _ e) = case e of TooManyRedirects _ -> return ()
        inspect _ = assertFailure "unexpected exception thrown"

invalidURL Verb{..} _site = do
  let noProto (InvalidUrlException _ _) = return ()
  assertThrows "exception if no protocol" noProto (get "wheeee")
  let noHost (HttpExceptionRequest _ (InvalidDestinationHost _)) = return ()
  assertThrows "exception if no host" noHost (get "http://")

funkyScheme Verb{..} site = do
  -- schemes are case insensitive, per RFC 3986 section 3.1
  let (scheme, rest) = break (==':') $ site "/get"
  void . get $ map toUpper scheme <> rest

cookiesSet Verb{..} site = do
  r <- get (site "/cookies/set?x=y")
  assertEqual "cookies are set correctly" (Just "y")
    (r ^? responseCookie "x" . cookieValue)

cookieSession site = do
  s <- Session.newSession
  r0 <- Session.get s (site "/cookies/set?foo=bar")
  assertEqual "after set foo, foo set" (Just "bar")
    (r0 ^? responseCookie "foo" . cookieValue)
  assertEqual "a different accessor works" (Just "bar")
    (r0 ^. responseBody ^? key "cookies" . key "foo")

  r1 <- Session.get s (site "/cookies")
  assertEqual "long after set foo, foo still set" (Just "bar")
    (r1 ^? responseCookie "foo" . cookieValue)

  r2 <- Session.get s (site "/cookies/set?baz=quux")
  assertEqual "after set baz, foo still set" (Just "bar")
    (r2 ^? responseCookie "foo" . cookieValue)
  assertEqual "after set baz, baz set" (Just "quux")
    (r2 ^? responseCookie "baz" . cookieValue)

  r3 <- Session.get s (site "/cookies")
  assertEqual "long after set baz, foo still set" (Just "bar")
    (r3 ^? responseCookie "foo" . cookieValue)
  assertEqual "long after set baz, baz still set" (Just "quux")
    (r3 ^? responseCookie "baz" . cookieValue)

  r4 <- Session.get s (site "/cookies/delete?foo")
  assertEqual "after delete foo, foo deleted" Nothing
    (r4 ^? responseCookie "foo" . cookieValue)
  assertEqual "after delete foo, baz still set" (Just "quux")
    (r4 ^? responseCookie "baz" . cookieValue)

  r5 <- Session.get s (site "/cookies")
  assertEqual "long after delete foo, foo still deleted" Nothing
    (r5 ^? responseCookie "foo" . cookieValue)
  assertEqual "long after delete foo, baz still set" (Just "quux")
    (r5 ^? responseCookie "baz" . cookieValue)

getWithManager site = withManager $ \opts -> do
  void $ Wreq.getWith opts (site "/get?a=b")
  void $ Wreq.getWith opts (site "/get?b=c")

assertThrows :: (Show e, Exception e) => String -> (e -> IO ()) -> IO a -> IO ()
assertThrows desc inspect act = do
  let myInspect e = inspect e `E.catch` \(ee :: E.PatternMatchFail) ->
        assertFailure (desc <> ": unexpected exception (" <>
                       show e <> "): " <> show ee)
  caught <- (act >> return False) `E.catch` \e -> myInspect e >> return True
  unless caught (assertFailure desc)

commonTestsWith verb site = [
    testGroup "basic" [
      testCase "get" $ basicGet verb site
    , testCase "post" $ basicPost verb site
    , testCase "head" $ basicHead verb site
    , testCase "put" $ basicPut verb site
    , testCase "delete" $ basicDelete verb site
    , testCase "404" $ throwsStatusCode verb site
    , testCase "headRedirect" $ headRedirect verb site
    , testCase "redirectOverflow" $ redirectOverflow verb site
    , testCase "invalidURL" $ invalidURL verb site
    , testCase "funkyScheme" $ funkyScheme verb site
    ]
  , testGroup "fancy" [
      testCase "basic auth" $ getBasicAuth verb site
    , testCase "redirect" $ getRedirect verb site
    , testCase "params" $ getParams verb site
    , testCase "headers" $ getHeaders verb site
    , testCase "gzip" $ getGzip verb site
    , testCase "json put" $ jsonPut verb site
    , testCase "bytestring put" $ byteStringPut verb site
    , testCase "cookiesSet" $ cookiesSet verb site
    , testCase "getWithManager" $ getWithManager site
    , testCase "cookieSession" $ cookieSession site
    , testCase "getCheckStatus" $ getCheckStatus verb site
    ]
  ]

-- Snap responds incorrectly to HEAD (by sending a response body),
-- thereby killing http-client's ability to continue a session.
-- https://github.com/snapframework/snap-core/issues/192
snapHeadSessionBug site = do
  s <- Session.newSession
  basicHead (session s) site
  -- will crash with (InvalidStatusLine "0")
  basicGet (session s) site

httpbinTestsWith verb site = commonTestsWith verb site <> [
  ]

-- Tests that our local httpbin clone doesn't yet support.
httpbinTests verb = [testGroup "httpbin" [
    testGroup "http" $ httpbinTestsWith verb ("http://httpbin.org" <>)
  , testGroup "https" $ httpbinTestsWith verb ("https://httpbin.org" <>)
  ]]

-- Tests that httpbin.org doesn't support.
localTests verb site = commonTestsWith verb site <> [
    testCase "oauth2 Bearer" $ getOAuth2 verb "Bearer" oauth2Bearer site
  , testCase "oauth2 token" $ getOAuth2 verb "token" oauth2Token site
  ]

startServer = do
  started <- newEmptyMVar
  let go n | n >= 100 = putMVar started Nothing
           | otherwise = do
        let port = 8000 + n
            startedUp p = putMVar started (Just ("http://0.0.0.0:" <> p))
            mkCfg = return . setBind ("0.0.0.0") . setPort port .
                    setVerbose False .
                    setStartupHook (const (startedUp (show port)))
        serve mkCfg `E.catch` \(_::E.IOException) -> go (n+1)
  tid <- forkIO $ go 0
  (,) tid <$> takeMVar started

testWith :: [Test] -> IO ()
testWith tests = do
  (tid, mserv) <- startServer
  s <- Session.newSession
  flip E.finally (killThread tid) .
    defaultMain $ tests <>
                  [ testGroup "plain" $ httpbinTests basic
                  , testGroup "session" $ httpbinTests (session s)] <>
      case mserv of
        Nothing -> []
        Just binding -> [
            testGroup "localhost" [
              testGroup "plain" $ localTests basic (binding <>)
            , testGroup "session" $ localTests (session s) (binding <>)
            ]
          ]


text:
<!doctype html>

	<?php echo $head ?>

	<?php echo $header; ?>

<?php echo $error_title ?>

<?php echo $error_description ?>

	<?php echo $footer ?>

redpajama_set_name: RedPajamaGithub


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

using AndroidAsync.Http;

namespace AndroidAsyncSample
{
	public class BasicAuthMiddleware : SimpleMiddleware
	{
		private readonly Dictionary<string, string> auths = new Dictionary<string, string> ();

		public override void OnRequest (AsyncHttpClientMiddlewareOnRequestData data)
		{
			base.OnRequest (data);

			// do more checking here, since uri may not necessarily be http or have a host, etc.
			string host = data.Request.Uri.Host;
			if (auths.ContainsKey (host)) {
				string auth = auths [host];
				if (!string.IsNullOrEmpty (auth))
					data.Request.SetHeader ("Authorization", auth);
			}
		}

		public void SetAuthorization (string host, string username, string password)
		{
			string text = string.Format ("{0}:{1}", username, password);
			byte [] bytes = Encoding.ASCII.GetBytes (text);
			string base64 = Convert.ToBase64String (bytes);
			string auth = "Basic " + base64;

			auths [host] = auth;
		}

		public static BasicAuthMiddleware Add (AsyncHttpClient client)
		{
			BasicAuthMiddleware ret = new BasicAuthMiddleware ();
			client.Middleware.Add (ret);
			return ret;
		}
	}
}


text:
module Main where
import Math.Statistics.WCC(wcc)
import DebugPrint(debugPrint)
import Output(toPNG,toRaw)
import Parse(parseFile)
import CommandLine(withArgs,OutputFormat(..))
--import Data.ByteString.Lazy.Progress
--import Control.Applicative((<*>))
--import Control.Monad(liftM2,(>=>))
import Data.ByteString.Lazy(ByteString)
import qualified Data.ByteString.Lazy.Char8 as B
--import System.IO(openBinaryFile,hFileSize,IOMode(ReadMode))
main :: IO ()
main = withArgs main'
main' infile outfile debug outputFormat params =
  B.readFile infile >>= eatData debug . computeWCC params
    where eatData True  = debugPrint infile outfile params
          eatData False = B.writeFile outfile . toOutput outputFormat
computeWCC p = uncurry (wcc p) . parseFile
toOutput :: OutputFormat -> [[Double]] -> ByteString
toOutput PNG = toPNG
toOutput RAW = toRaw

-- the tracker wasn't very useful, so I commented it out

-- readFileWithTracker :: FilePath -> IO B.ByteString
-- readFileWithTracker = flip openBinaryFile ReadMode >=> hFileSize &=& B.hGetContents
--                                                    >=> uncurry tracker
-- tracker size = trackProgressWithChunkSize (fromIntegral $ size `div` 100)
--                                           (const $ const $ putStr ".")
-- infixr 3 &=& -- (&&&) for monads
-- f &=& g = \a -> liftM2 (,) (f a) (g a)

--tracker = undefined
--readFileWithTracker f = B.readFile f >>= tracker
--tracker = trackProgressWithChunkSize 8 (const $ const $ putStr ".")
-- tracker _ = trackProgressString "Bytes read: %B, rate %R" Nothing putStrLn
--tracker = trackProgressStringWithChunkSize "." 8 Nothing putStr
--tracker size = trackProgressString "Time left: %T" -- , procent done %p"
--                                   (Just . fromIntegral $ size)
--                                   putStrLn
-- progressString = "Bytes read: %%B, current rate: %R"
-- progressPrinter = putStrLn
-- tracker = trackProgressString progressString Nothing progressPrinter

-- computeWCC outputFormat p = showData outputFormat . uncurry (wcc p) . parseFile
--   where showData :: OutputFormat -> [[Double]] -> B.ByteString
--         showData PNG  = png . map (map toColor)
--         showData RAW  = B.unlines . map (B.intercalate spacing . map showFloat)
--         spacing = B.pack "  "

-- showParam infile outfile outputPNG p =
--   do putStrLn $ "infile: " ++ infile
--      putStrLn $ "outfile: " ++ outfile
--      putStrLn $ if outputPNG then "output: PNG" else "output: RAW"
--      putStrLn $ "Params: " ++ show p


text:
.action-link {
  @apply tw-no-underline !important;
  @apply tw-flex !important;
  @apply tw-items-center !important;
  @apply tw-transition-opacity !important;
  @apply tw-duration-100 !important;
  @apply tw-text-zinc-900 !important;
  @apply tw-text-opacity-50;
  @apply dark:tw-text-zinc-50 !important;
  @apply dark:hover:tw-text-zinc-50 !important;
  @apply dark:focus:tw-text-zinc-50 !important;
  @apply dark:tw-text-opacity-75;
}

.action-link:hover {
  @apply tw-text-opacity-100 !important;
}


text:
package mapstructure

import (
	"errors"
	"fmt"
	"sort"
	"strings"
)

// Error implements the error interface and can represents multiple
// errors that occur in the course of a single decode.
type Error struct {
	Errors []string
}

func (e *Error) Error() string {
	points := make([]string, len(e.Errors))
	for i, err := range e.Errors {
		points[i] = fmt.Sprintf("* %s", err)
	}

	sort.Strings(points)
	return fmt.Sprintf(
		"%d error(s) decoding:\n\n%s",
		len(e.Errors), strings.Join(points, "\n"))
}

// WrappedErrors implements the errwrap.Wrapper interface to make this
// return value more useful with the errwrap and go-multierror libraries.
func (e *Error) WrappedErrors() []error {
	if e == nil {
		return nil
	}

	result := make([]error, len(e.Errors))
	for i, e := range e.Errors {
		result[i] = errors.New(e)
	}

	return result
}

func appendErrors(errors []string, err error) []string {
	switch e := err.(type) {
	case *Error:
		return append(errors, e.Errors...)
	default:
		return append(errors, e.Error())
	}
}


text:
<?php
//get and set url protocol
$protocol = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off' || $_SERVER['SERVER_PORT'] == 443) ? 'https://' : 'http://';
//set and sanitize global variables for URL construction
$server = isset($_SERVER['SERVER_NAME']) ? htmlentities(strip_tags($_SERVER['SERVER_NAME'])) : null;
$path = isset($_SERVER['PHP_SELF']) ? htmlentities(strip_tags(dirname($_SERVER['PHP_SELF']))) : null;
$fileName = isset($_SERVER['SCRIPT_NAME']) ? htmlentities(strip_tags(basename($_SERVER['SCRIPT_NAME']))) : null;
$fileNameURI = isset($_SERVER['REQUEST_URI']) ? htmlentities(strip_tags($_SERVER['REQUEST_URI'])) : null;
$fileExtension = isset($_SERVER['PATH_INFO']) ? pathinfo($fileName, PATHINFO_EXTENSION) : null;
//assign value for title of page
$pageTitle = 'Linked Bioscience (Demo) - Alphabetical List of People';
//declare filename and filepath for screen/projection stylesheet variable - "none"
$customCSS = 'none';
//pass database parameters and connect to database
include_once './meta/assets/database-params.inc';
//create an array with filepaths for multiple page scripts - default is "none"
$customScript[0] = 'none';
?>
<!DOCTYPE html>

<meta charset="utf-8"/>
<meta http-equiv="x-ua-compatible" content="ie=edge"/>
<meta name="viewport" content="width=device-width, initial-scale=1"/>
<title><?php echo($pageTitle); ?>: Montana State University (MSU) Library</title>
<meta name="description" content="<?php echo($pageTitle); ?>: Code prototype for Linked People"/>
<link rel="canonical" href="<?php echo $protocol.$server.$path; ?>/<?php echo $fileName; ?>"/>
<link rel="stylesheet prefetch" href="https://fonts.googleapis.com/css?family=Oswald"/>

<?php
if ($customCSS = (empty($customCSS)) ? null : $customCSS) {
  $countedCSS = count($customCSS);
  for ($i = 0; $i < $countedCSS; $i++) {
?>
<link rel="stylesheet" href="<?php echo $customCSS[$i]; ?>">
<?php
  }
}
?>

<body id="page" vocab="https://schema.org/" typeof="AboutPage" resource="<?php echo $protocol.$server.$path; ?>/<?php echo $fileName; ?>#page">
<link property="isPartOf" typeof="CollectionPage" href="<?php echo $protocol.$server.$path; ?>/"/>

Linked People

  Home Search Browse

Browse Alphabetical List of People

    <form class="search" name="searchform" action="search.html" method="get">
	<input class="text" type="text" name="q" id="q" maxlength="55" placeholder="Enter people or topics..."/>
	  <select name="facet">
        <option name="keyword" id="keyword" value="keyword" selected>People</option>
        <option name="topic" id="topic" value="topic">Topics</option>
      </select>
	<button class="submit" id="submit" role="button" type="submit">Search</button>
    </form>

Browse by staff last name

A B C | D E F | G H I | J K L | M N O | P Q R | S T U | V W X | Y Z | Other

A B C [^]

	<?php
	//request people with letters "ABC" in last name
	$query = "SELECT person_id, familyName, givenName, jobTitle, person_status FROM linked_people.person WHERE familyName >='a' AND familyName <='d' AND person_status = 'a'  ORDER BY familyName ASC";
	$getpeopleAtoC = $connectLinkedpeople->query($query);
	if (!$getpeopleAtoC) {
	  die('
Error retrieving people data from database!
'.
		  'Error: ' . $connectLinkedpeople->error() . '
');
	}
	while ($row = $getpeopleAtoC->fetch_object()) {
		$person_id = stripslashes($row->person_id);
		$person_name = html_entity_decode(stripslashes($row->givenName  . ' ' . $row->familyName));
		$person_title = stripslashes($row->jobTitle);
		echo '

'.$person_name.'
'."\n";
		echo '
'.$person_title.'
'."\n";
		echo '
Learn more...

'."\n";
		echo '
'."\n";
	}
	?>

D E F [^]

	<?php
	//request people with letters "DEF" in last name
	$query = "SELECT person_id, familyName, givenName, jobTitle, person_status  FROM linked_people.person WHERE familyName >='d' AND familyName <='g' AND person_status = 'a' ORDER BY familyName ASC";
	$getpeopleDtoF = $connectLinkedpeople->query($query);
	if (!$getpeopleDtoF) {
	  die('
Error retrieving people data from database!
'.
		  'Error: ' . $connectLinkedpeople->error() . '
');
	}
	while ($row = $getpeopleDtoF->fetch_object()) {
		$person_id = stripslashes($row->person_id);
		$person_name = html_entity_decode(stripslashes($row->givenName  . ' ' . $row->familyName));
		$person_title = stripslashes($row->jobTitle);
		echo '

'.$person_name.'
'."\n";
		echo '
'.$person_title.'
'."\n";
		echo '
Learn more...

'."\n";
		echo '
'."\n";
	}
	?>

G H I [^]

	<?php
	//request people with letters "GHI" in last name
	$query = "SELECT person_id, familyName, givenName, jobTitle, person_status FROM linked_people.person WHERE familyName >='g' AND familyName <='j' AND person_status = 'a' ORDER BY familyName ASC";
	$getpeopleGtoI = $connectLinkedpeople->query($query);
	if (!$getpeopleGtoI) {
	  die('
Error retrieving people data from database!
'.
		  'Error: ' . $connectLinkedpeople->error() . '
');
	}
	while ($row = $getpeopleGtoI->fetch_object()) {
		$person_id = stripslashes($row->person_id);
		$person_name = html_entity_decode(stripslashes($row->givenName  . ' ' . $row->familyName));
		$person_title = stripslashes($row->jobTitle);
		echo '

'.$person_name.'
'."\n";
		echo '
'.$person_title.'
'."\n";
		echo '
Learn more...

'."\n";
		echo '
'."\n";
	}
	?>

J K L [^]

	<?php
	//request people with letters "JKL" in last name
	$query = "SELECT person_id, familyName, givenName, jobTitle, person_status FROM linked_people.person WHERE familyName >='j' AND familyName <='m' AND person_status = 'a' ORDER BY familyName ASC";
	$getpeopleJtoL = $connectLinkedpeople->query($query);
	if (!$getpeopleJtoL) {
	  die('
Error retrieving people data from database!
'.
		  'Error: ' . $connectLinkedpeople->error() . '
');
	}
	while ($row = $getpeopleJtoL->fetch_object()) {
		$person_id = stripslashes($row->person_id);
		$person_name = html_entity_decode(stripslashes($row->givenName  . ' ' . $row->familyName));
		$person_title = stripslashes($row->jobTitle);
		echo '

'.$person_name.'
'."\n";
		echo '
'.$person_title.'
'."\n";
		echo '
Learn more...

'."\n";
		echo '
'."\n";
	}
	?>

M N O [^]

	<?php
	//request people with letters "MNO" in last name
	$query = "SELECT person_id, familyName, givenName, jobTitle, person_status FROM linked_people.person WHERE familyName >='m' AND familyName <='p' AND person_status = 'a' ORDER BY familyName ASC";
	$getpeopleMtoO = $connectLinkedpeople->query($query);
	if (!$getpeopleMtoO) {
	  die('
Error retrieving people data from database!
'.
		  'Error: ' . $connectLinkedpeople->error() . '
');
	}
	while ($row = $getpeopleMtoO->fetch_object()) {
		$person_id = stripslashes($row->person_id);
		$person_name = html_entity_decode(stripslashes($row->givenName  . ' ' . $row->familyName));
		$person_title = stripslashes($row->jobTitle);
		echo '

'.$person_name.'
'."\n";
		echo '
'.$person_title.'
'."\n";
		echo '
Learn more...

'."\n";
		echo '
'."\n";
	}
	?>

P Q R [^]

	<?php
	//request people with letters "PQR" in last name
	$query = "SELECT person_id, familyName, givenName, jobTitle, person_status FROM linked_people.person WHERE familyName >='p' AND familyName <='s' AND person_status = 'a' ORDER BY familyName ASC";
	$getpeoplePtoR = $connectLinkedpeople->query($query);
	if (!$getpeoplePtoR) {
	  die('
Error retrieving people data from database!
'.
		  'Error: ' . $connectLinkedpeople->error() . '
');
	}
	while ($row = $getpeoplePtoR->fetch_object()) {
		$person_id = stripslashes($row->person_id);
		$person_name = html_entity_decode(stripslashes($row->givenName  . ' ' . $row->familyName));
		$person_title = stripslashes($row->jobTitle);
		echo '

'.$person_name.'
'."\n";
		echo '
'.$person_title.'
'."\n";
		echo '
Learn more...

'."\n";
		echo '
'."\n";
	}
	?>

S T U [^]

	<?php
	//request people with letters "STU" in last name
	$query = "SELECT person_id, familyName, givenName, jobTitle, person_status FROM linked_people.person WHERE familyName >='s' AND familyName <='v' AND person_status = 'a' ORDER BY familyName ASC";
	$getpeopleStoU = $connectLinkedpeople->query($query);
	if (!$getpeopleStoU) {
	  die('
Error retrieving people data from database!
'.
		  'Error: ' . $connectLinkedpeople->error() . '
');
	}
	while ($row = $getpeopleStoU->fetch_object()) {
		$person_id = stripslashes($row->person_id);
		$person_name = html_entity_decode(stripslashes($row->givenName  . ' ' . $row->familyName));
		$person_title = stripslashes($row->jobTitle);
		echo '

'.$person_name.'
'."\n";
		echo '
'.$person_title.'
'."\n";
		echo '
Learn more...

'."\n";
		echo '
'."\n";
	}
	?>

V W X [^]

	<?php
	//request people with letters "VWX" in last name
	$query = "SELECT person_id, familyName, givenName, jobTitle, person_status FROM linked_people.person WHERE familyName >='v' AND familyName <='y' AND person_status = 'a'  ORDER BY familyName ASC";
	$getpeopleVtoX = $connectLinkedpeople->query($query);
	if (!$getpeopleVtoX) {
	  die('
Error retrieving people data from database!
'.
		  'Error: ' . $connectLinkedpeople->error() . '
');
	}
	while ($row = $getpeopleVtoX->fetch_object()) {
		$person_id = stripslashes($row->person_id);
		$person_name = html_entity_decode(stripslashes($row->givenName  . ' ' . $row->familyName));
		$person_title = stripslashes($row->jobTitle);
		echo '

'.$person_name.'
'."\n";
		echo '
'.$person_title.'
'."\n";
		echo '
Learn more...

'."\n";
		echo '
'."\n";
	}
	?>

Y Z [^]

	<?php
	//request people with letters "VWX" in last name
	$query = "SELECT person_id, familyName, givenName, jobTitle, person_status FROM linked_people.person WHERE familyName >='y' AND person_status = 'a' ORDER BY familyName ASC";
	$getpeopleYtoZ = $connectLinkedpeople->query($query);
	if (!$getpeopleYtoZ) {
	  die('
Error retrieving people data from database!
'.
		  'Error: ' . $connectLinkedpeople->error() . '
');
	}
	while ($row = $getpeopleYtoZ->fetch_object()) {
		$person_id = stripslashes($row->person_id);
		$person_name = html_entity_decode(stripslashes($row->givenName  . ' ' . $row->familyName));
		$person_title = stripslashes($row->jobTitle);
		echo '

'.$person_name.'
'."\n";
		echo '
'.$person_title.'
'."\n";
		echo '
Learn more...

'."\n";
		echo '
'."\n";
	}
	?>

Other [^]

	<?php
	//request people with letters "VWX" in last name
	$query = "SELECT person_id, familyName, givenName, jobTitle, person_status FROM linked_people.person WHERE familyName <='a' AND person_status = 'a' ORDER BY familyName ASC";
	$getpeopleYtoZ = $connectLinkedpeople->query($query);
	if (!$getpeopleYtoZ) {
	  die('
Error retrieving people data from database!
'.
		  'Error: ' . $connectLinkedpeople->error() . '
');
	}
	while ($row = $getpeopleYtoZ->fetch_object()) {
		$person_id = stripslashes($row->person_id);
		$person_name = html_entity_decode(stripslashes($row->givenName  . ' ' . $row->familyName));
		$person_title = stripslashes($row->jobTitle);
		echo '

'.$person_name.'
'."\n";
		echo '
'.$person_title.'
'."\n";
		echo '
Learn more...

'."\n";
		echo '
'."\n";
	}
	?>

    Sitemap
    GitHub
    Article
    Library

    © Montana State University (MSU) Library  <time property="dateModified lastReviewed" datetime="2017-09-08T18:57:03-07:00" title="published 2017-09-08T18:57:03-07:00">2017</time>

<?php
if ($customScript = (empty($customScript)) ? null : $customScript) {
  $counted = count($customScript);
  for ($i = 0; $i < $counted; $i++) {
?>

<?php
  }
}
?>


text:
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package de.hsbo.fbg.sm4c.common.dao.geonames;

import de.hsbo.fbg.sm4c.common.model.geonames.Admin1;
import de.hsbo.fbg.sm4c.common.dao.BaseDao;
import java.util.Optional;

/**
 *
 * @author Seba
 */
public interface Admin01Dao extends BaseDao<Admin1>{

}


text:
// Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "extensions/browser/api/bluetooth_low_energy/bluetooth_low_energy_event_router.h"

#include "base/bind.h"
#include "base/logging.h"
#include "base/values.h"
#include "content/public/browser/browser_thread.h"
#include "device/bluetooth/bluetooth_adapter_factory.h"
#include "device/bluetooth/bluetooth_gatt_characteristic.h"
#include "device/bluetooth/bluetooth_gatt_connection.h"
#include "device/bluetooth/bluetooth_gatt_descriptor.h"
#include "extensions/browser/api/bluetooth_low_energy/bluetooth_low_energy_connection.h"
#include "extensions/browser/api/bluetooth_low_energy/bluetooth_low_energy_notify_session.h"
#include "extensions/browser/api/bluetooth_low_energy/utils.h"
#include "extensions/browser/event_router.h"
#include "extensions/browser/extension_registry.h"
#include "extensions/common/api/bluetooth/bluetooth_manifest_data.h"

using content::BrowserThread;

using device::BluetoothAdapter;
using device::BluetoothAdapterFactory;
using device::BluetoothDevice;
using device::BluetoothGattCharacteristic;
using device::BluetoothGattConnection;
using device::BluetoothGattDescriptor;
using device::BluetoothGattService;

namespace apibtle = extensions::core_api::bluetooth_low_energy;

namespace {

void PopulateService(const BluetoothGattService* service,
                     apibtle::Service* out) {
  DCHECK(out);

  out->uuid = service->GetUUID().canonical_value();
  out->is_primary = service->IsPrimary();
  out->is_local = service->IsLocal();
  out->instance_id.reset(new std::string(service->GetIdentifier()));

  if (!service->GetDevice())
    return;

  out->device_address.reset(
      new std::string(service->GetDevice()->GetAddress()));
}

void PopulateCharacteristicProperties(
    BluetoothGattCharacteristic::Properties properties,
    std::vector<apibtle::CharacteristicProperty>* api_properties) {
  DCHECK(api_properties && api_properties->empty());

  if (properties == BluetoothGattCharacteristic::PROPERTY_NONE)
    return;

  if (properties & BluetoothGattCharacteristic::PROPERTY_BROADCAST)
    api_properties->push_back(apibtle::CHARACTERISTIC_PROPERTY_BROADCAST);
  if (properties & BluetoothGattCharacteristic::PROPERTY_READ)
    api_properties->push_back(apibtle::CHARACTERISTIC_PROPERTY_READ);
  if (properties &
      BluetoothGattCharacteristic::PROPERTY_WRITE_WITHOUT_RESPONSE) {
    api_properties->push_back(
        apibtle::CHARACTERISTIC_PROPERTY_WRITEWITHOUTRESPONSE);
  }
  if (properties & BluetoothGattCharacteristic::PROPERTY_WRITE)
    api_properties->push_back(apibtle::CHARACTERISTIC_PROPERTY_WRITE);
  if (properties & BluetoothGattCharacteristic::PROPERTY_NOTIFY)
    api_properties->push_back(apibtle::CHARACTERISTIC_PROPERTY_NOTIFY);
  if (properties & BluetoothGattCharacteristic::PROPERTY_INDICATE)
    api_properties->push_back(apibtle::CHARACTERISTIC_PROPERTY_INDICATE);
  if (properties &
      BluetoothGattCharacteristic::PROPERTY_AUTHENTICATED_SIGNED_WRITES) {
    api_properties->push_back(
        apibtle::CHARACTERISTIC_PROPERTY_AUTHENTICATEDSIGNEDWRITES);
  }
  if (properties & BluetoothGattCharacteristic::PROPERTY_EXTENDED_PROPERTIES) {
    api_properties->push_back(
        apibtle::CHARACTERISTIC_PROPERTY_EXTENDEDPROPERTIES);
  }
  if (properties & BluetoothGattCharacteristic::PROPERTY_RELIABLE_WRITE)
    api_properties->push_back(apibtle::CHARACTERISTIC_PROPERTY_RELIABLEWRITE);
  if (properties & BluetoothGattCharacteristic::PROPERTY_WRITABLE_AUXILIARIES) {
    api_properties->push_back(
        apibtle::CHARACTERISTIC_PROPERTY_WRITABLEAUXILIARIES);
  }
}

void PopulateCharacteristic(const BluetoothGattCharacteristic* characteristic,
                            apibtle::Characteristic* out) {
  DCHECK(out);

  out->uuid = characteristic->GetUUID().canonical_value();
  out->is_local = characteristic->IsLocal();
  out->instance_id.reset(new std::string(characteristic->GetIdentifier()));

  PopulateService(characteristic->GetService(), &out->service);
  PopulateCharacteristicProperties(characteristic->GetProperties(),
                                   &out->properties);

  const std::vector<uint8>& value = characteristic->GetValue();
  if (value.empty())
    return;

  out->value.reset(new std::vector<char>(value.begin(), value.end()));
}

void PopulateDescriptor(const BluetoothGattDescriptor* descriptor,
                        apibtle::Descriptor* out) {
  DCHECK(out);

  out->uuid = descriptor->GetUUID().canonical_value();
  out->is_local = descriptor->IsLocal();
  out->instance_id.reset(new std::string(descriptor->GetIdentifier()));

  PopulateCharacteristic(descriptor->GetCharacteristic(), &out->characteristic);

  const std::vector<uint8>& value = descriptor->GetValue();
  if (value.empty())
    return;

  out->value.reset(new std::vector<char>(value.begin(), value.end()));
}

typedef extensions::ApiResourceManager<extensions::BluetoothLowEnergyConnection>
    ConnectionResourceManager;
ConnectionResourceManager* GetConnectionResourceManager(
    content::BrowserContext* context) {
  ConnectionResourceManager* manager = ConnectionResourceManager::Get(context);
  DCHECK(manager)
      << "There is no Bluetooth low energy connection manager. "
         "If this assertion is failing during a test, then it is likely that "
         "TestExtensionSystem is failing to provide an instance of "
         "ApiResourceManager<BluetoothLowEnergyConnection>.";
  return manager;
}

typedef extensions::ApiResourceManager<
    extensions::BluetoothLowEnergyNotifySession> NotifySessionResourceManager;
NotifySessionResourceManager* GetNotifySessionResourceManager(
    content::BrowserContext* context) {
  NotifySessionResourceManager* manager =
      NotifySessionResourceManager::Get(context);
  DCHECK(manager)
      << "There is no Bluetooth low energy value update session manager."
         "If this assertion is failing during a test, then it is likely that "
         "TestExtensionSystem is failing to provide an instance of "
         "ApiResourceManager<BluetoothLowEnergyNotifySession>.";
  return manager;
}

// Translates GattErrorCodes to RouterError Codes
extensions::BluetoothLowEnergyEventRouter::Status GattErrorToRouterError(
    BluetoothGattService::GattErrorCode error_code) {
  extensions::BluetoothLowEnergyEventRouter::Status error_status =
      extensions::BluetoothLowEnergyEventRouter::kStatusErrorFailed;
  if (error_code == BluetoothGattService::GATT_ERROR_IN_PROGRESS) {
    error_status =
        extensions::BluetoothLowEnergyEventRouter::kStatusErrorInProgress;
  } else if (error_code == BluetoothGattService::GATT_ERROR_INVALID_LENGTH) {
    error_status =
        extensions::BluetoothLowEnergyEventRouter::kStatusErrorInvalidLength;
  } else if (error_code == BluetoothGattService::GATT_ERROR_NOT_PERMITTED) {
    error_status =
        extensions::BluetoothLowEnergyEventRouter::kStatusErrorPermissionDenied;
  } else if (error_code == BluetoothGattService::GATT_ERROR_NOT_AUTHORIZED) {
    error_status = extensions::BluetoothLowEnergyEventRouter::
        kStatusErrorInsufficientAuthorization;
  } else if (error_code == BluetoothGattService::GATT_ERROR_NOT_PAIRED) {
    error_status =
        extensions::BluetoothLowEnergyEventRouter::kStatusErrorHigherSecurity;
  } else if (error_code == BluetoothGattService::GATT_ERROR_NOT_SUPPORTED) {
    error_status =
        extensions::BluetoothLowEnergyEventRouter::kStatusErrorGattNotSupported;
  }

  return error_status;
}

}  // namespace

namespace extensions {

BluetoothLowEnergyEventRouter::BluetoothLowEnergyEventRouter(
    content::BrowserContext* context)
    : adapter_(NULL), browser_context_(context), weak_ptr_factory_(this) {
  DCHECK_CURRENTLY_ON(BrowserThread::UI);
  DCHECK(browser_context_);
  VLOG(1) << "Initializing BluetoothLowEnergyEventRouter.";

  if (!IsBluetoothSupported()) {
    VLOG(1) << "Bluetooth not supported on the current platform.";
    return;
  }
}

BluetoothLowEnergyEventRouter::~BluetoothLowEnergyEventRouter() {
  DCHECK_CURRENTLY_ON(BrowserThread::UI);
  if (!adapter_.get())
    return;

  adapter_->RemoveObserver(this);
  adapter_ = NULL;
}

bool BluetoothLowEnergyEventRouter::IsBluetoothSupported() const {
  DCHECK_CURRENTLY_ON(BrowserThread::UI);
  return adapter_.get() ||
         BluetoothAdapterFactory::IsBluetoothAdapterAvailable();
}

bool BluetoothLowEnergyEventRouter::InitializeAdapterAndInvokeCallback(
    const base::Closure& callback) {
  if (!IsBluetoothSupported())
    return false;

  if (adapter_.get()) {
    callback.Run();
    return true;
  }

  BluetoothAdapterFactory::GetAdapter(
      base::Bind(&BluetoothLowEnergyEventRouter::OnGetAdapter,
                 weak_ptr_factory_.GetWeakPtr(),
                 callback));
  return true;
}

bool BluetoothLowEnergyEventRouter::HasAdapter() const {
  return (adapter_.get() != NULL);
}

void BluetoothLowEnergyEventRouter::Connect(
    bool persistent,
    const Extension* extension,
    const std::string& device_address,
    const base::Closure& callback,
    const ErrorCallback& error_callback) {
  DCHECK_CURRENTLY_ON(BrowserThread::UI);
  if (!adapter_.get()) {
    VLOG(1) << "BluetoothAdapter not ready.";
    error_callback.Run(kStatusErrorFailed);
    return;
  }

  const std::string extension_id = extension->id();
  const std::string connect_id = extension_id + device_address;

  if (connecting_devices_.count(connect_id) != 0) {
    error_callback.Run(kStatusErrorInProgress);
    return;
  }

  BluetoothLowEnergyConnection* conn =
      FindConnection(extension_id, device_address);
  if (conn) {
    if (conn->GetConnection()->IsConnected()) {
      VLOG(1) << "Application already connected to device: " << device_address;
      error_callback.Run(kStatusErrorAlreadyConnected);
      return;
    }

    // There is a connection object but it's no longer active. Simply remove it.
    RemoveConnection(extension_id, device_address);
  }

  BluetoothDevice* device = adapter_->GetDevice(device_address);
  if (!device) {
    VLOG(1) << "Bluetooth device not found: " << device_address;
    error_callback.Run(kStatusErrorNotFound);
    return;
  }

  connecting_devices_.insert(connect_id);
  device->CreateGattConnection(
      base::Bind(&BluetoothLowEnergyEventRouter::OnCreateGattConnection,
                 weak_ptr_factory_.GetWeakPtr(),
                 persistent,
                 extension_id,
                 device_address,
                 callback),
      base::Bind(&BluetoothLowEnergyEventRouter::OnConnectError,
                 weak_ptr_factory_.GetWeakPtr(),
                 extension_id,
                 device_address,
                 error_callback));
}

void BluetoothLowEnergyEventRouter::Disconnect(
    const Extension* extension,
    const std::string& device_address,
    const base::Closure& callback,
    const ErrorCallback& error_callback) {
  DCHECK_CURRENTLY_ON(BrowserThread::UI);
  if (!adapter_.get()) {
    VLOG(1) << "BluetoothAdapter not ready.";
    error_callback.Run(kStatusErrorFailed);
    return;
  }

  const std::string extension_id = extension->id();
  const std::string disconnect_id = extension_id + device_address;

  if (disconnecting_devices_.count(disconnect_id) != 0) {
    error_callback.Run(kStatusErrorInProgress);
    return;
  }

  BluetoothLowEnergyConnection* conn =
      FindConnection(extension_id, device_address);
  if (!conn || !conn->GetConnection()->IsConnected()) {
    VLOG(1) << "Application not connected to device: " << device_address;
    error_callback.Run(kStatusErrorNotConnected);
    return;
  }

  disconnecting_devices_.insert(disconnect_id);
  conn->GetConnection()->Disconnect(
      base::Bind(&BluetoothLowEnergyEventRouter::OnDisconnect,
                 weak_ptr_factory_.GetWeakPtr(),
                 extension_id,
                 device_address,
                 callback));
}

bool BluetoothLowEnergyEventRouter::GetServices(
    const std::string& device_address,
    ServiceList* out_services) const {
  DCHECK_CURRENTLY_ON(BrowserThread::UI);
  DCHECK(out_services);
  if (!adapter_.get()) {
    VLOG(1) << "BluetoothAdapter not ready.";
    return false;
  }

  BluetoothDevice* device = adapter_->GetDevice(device_address);
  if (!device) {
    VLOG(1) << "Bluetooth device not found: " << device_address;
    return false;
  }

  out_services->clear();

  const std::vector<BluetoothGattService*>& services =
      device->GetGattServices();
  for (std::vector<BluetoothGattService*>::const_iterator iter =
           services.begin();
       iter != services.end();
       ++iter) {
    // Populate an API service and add it to the return value.
    const BluetoothGattService* service = *iter;
    linked_ptr<apibtle::Service> api_service(new apibtle::Service());
    PopulateService(service, api_service.get());

    out_services->push_back(api_service);
  }

  return true;
}

BluetoothLowEnergyEventRouter::Status BluetoothLowEnergyEventRouter::GetService(
    const std::string& instance_id,
    apibtle::Service* out_service) const {
  DCHECK_CURRENTLY_ON(BrowserThread::UI);
  DCHECK(out_service);
  if (!adapter_.get()) {
    VLOG(1) << "BluetoothAdapter not ready.";
    return kStatusErrorFailed;
  }

  BluetoothGattService* gatt_service = FindServiceById(instance_id);
  if (!gatt_service) {
    VLOG(1) << "Service not found: " << instance_id;
    return kStatusErrorNotFound;
  }

  PopulateService(gatt_service, out_service);
  return kStatusSuccess;
}

BluetoothLowEnergyEventRouter::Status
BluetoothLowEnergyEventRouter::GetIncludedServices(
    const std::string& instance_id,
    ServiceList* out_services) const {
  DCHECK_CURRENTLY_ON(BrowserThread::UI);
  DCHECK(out_services);
  if (!adapter_.get()) {
    VLOG(1) << "BluetoothAdapter not ready.";
    return kStatusErrorFailed;
  }

  BluetoothGattService* service = FindServiceById(instance_id);
  if (!service) {
    VLOG(1) << "Service not found: " << instance_id;
    return kStatusErrorNotFound;
  }

  out_services->clear();

  const std::vector<BluetoothGattService*>& includes =
      service->GetIncludedServices();
  for (std::vector<BluetoothGattService*>::const_iterator iter =
           includes.begin();
       iter != includes.end();
       ++iter) {
    // Populate an API service and add it to the return value.
    const BluetoothGattService* included = *iter;
    linked_ptr<apibtle::Service> api_service(new apibtle::Service());
    PopulateService(included, api_service.get());

    out_services->push_back(api_service);
  }

  return kStatusSuccess;
}

BluetoothLowEnergyEventRouter::Status
BluetoothLowEnergyEventRouter::GetCharacteristics(
    const Extension* extension,
    const std::string& instance_id,
    CharacteristicList* out_characteristics) const {
  DCHECK_CURRENTLY_ON(BrowserThread::UI);
  DCHECK(extension);
  DCHECK(out_characteristics);
  if (!adapter_.get()) {
    VLOG(1) << "BlutoothAdapter not ready.";
    return kStatusErrorFailed;
  }

  BluetoothGattService* service = FindServiceById(instance_id);
  if (!service) {
    VLOG(1) << "Service not found: " << instance_id;
    return kStatusErrorNotFound;
  }

  BluetoothPermissionRequest request(service->GetUUID().value());
  if (!BluetoothManifestData::CheckRequest(extension, request)) {
    VLOG(1) << "App has no permission to access the characteristics of this "
            << "service: " << instance_id;
    return kStatusErrorPermissionDenied;
  }

  out_characteristics->clear();

  const std::vector<BluetoothGattCharacteristic*>& characteristics =
      service->GetCharacteristics();
  for (std::vector<BluetoothGattCharacteristic*>::const_iterator iter =
           characteristics.begin();
       iter != characteristics.end();
       ++iter) {
    // Populate an API characteristic and add it to the return value.
    const BluetoothGattCharacteristic* characteristic = *iter;
    linked_ptr<apibtle::Characteristic> api_characteristic(
        new apibtle::Characteristic());
    PopulateCharacteristic(characteristic, api_characteristic.get());

    out_characteristics->push_back(api_characteristic);
  }

  return kStatusSuccess;
}

BluetoothLowEnergyEventRouter::Status
BluetoothLowEnergyEventRouter::GetCharacteristic(
    const Extension* extension,
    const std::string& instance_id,
    apibtle::Characteristic* out_characteristic) const {
  DCHECK_CURRENTLY_ON(BrowserThread::UI);
  DCHECK(extension);
  DCHECK(out_characteristic);
  if (!adapter_.get()) {
    VLOG(1) << "BluetoothAdapter not ready.";
    return kStatusErrorFailed;
  }

  BluetoothGattCharacteristic* characteristic =
      FindCharacteristicById(instance_id);
  if (!characteristic) {
    VLOG(1) << "Characteristic not found: " << instance_id;
    return kStatusErrorNotFound;
  }

  BluetoothPermissionRequest request(
      characteristic->GetService()->GetUUID().value());
  if (!BluetoothManifestData::CheckRequest(extension, request)) {
    VLOG(1) << "App has no permission to access this characteristic: "
            << instance_id;
    return kStatusErrorPermissionDenied;
  }

  PopulateCharacteristic(characteristic, out_characteristic);
  return kStatusSuccess;
}

BluetoothLowEnergyEventRouter::Status
BluetoothLowEnergyEventRouter::GetDescriptors(
    const Extension* extension,
    const std::string& instance_id,
    DescriptorList* out_descriptors) const {
  DCHECK_CURRENTLY_ON(BrowserThread::UI);
  DCHECK(extension);
  DCHECK(out_descriptors);
  if (!adapter_.get()) {
    VLOG(1) << "BlutoothAdapter not ready.";
    return kStatusErrorFailed;
  }

  BluetoothGattCharacteristic* characteristic =
      FindCharacteristicById(instance_id);
  if (!characteristic) {
    VLOG(1) << "Characteristic not found: " << instance_id;
    return kStatusErrorNotFound;
  }

  BluetoothPermissionRequest request(
      characteristic->GetService()->GetUUID().value());
  if (!BluetoothManifestData::CheckRequest(extension, request)) {
    VLOG(1) << "App has no permission to access the descriptors of this "
            << "characteristic: " << instance_id;
    return kStatusErrorPermissionDenied;
  }

  out_descriptors->clear();

  const std::vector<BluetoothGattDescriptor*>& descriptors =
      characteristic->GetDescriptors();
  for (std::vector<BluetoothGattDescriptor*>::const_iterator iter =
           descriptors.begin();
       iter != descriptors.end();
       ++iter) {
    // Populate an API descriptor and add it to the return value.
    const BluetoothGattDescriptor* descriptor = *iter;
    linked_ptr<apibtle::Descriptor> api_descriptor(new apibtle::Descriptor());
    PopulateDescriptor(descriptor, api_descriptor.get());

    out_descriptors->push_back(api_descriptor);
  }

  return kStatusSuccess;
}

BluetoothLowEnergyEventRouter::Status
BluetoothLowEnergyEventRouter::GetDescriptor(
    const Extension* extension,
    const std::string& instance_id,
    core_api::bluetooth_low_energy::Descriptor* out_descriptor) const {
  DCHECK_CURRENTLY_ON(BrowserThread::UI);
  DCHECK(extension);
  DCHECK(out_descriptor);
  if (!adapter_.get()) {
    VLOG(1) << "BluetoothAdapter not ready.";
    return kStatusErrorFailed;
  }

  BluetoothGattDescriptor* descriptor = FindDescriptorById(instance_id);
  if (!descriptor) {
    VLOG(1) << "Descriptor not found: " << instance_id;
    return kStatusErrorNotFound;
  }

  BluetoothPermissionRequest request(
      descriptor->GetCharacteristic()->GetService()->GetUUID().value());
  if (!BluetoothManifestData::CheckRequest(extension, request)) {
    VLOG(1) << "App has no permission to access this descriptor: "
            << instance_id;
    return kStatusErrorPermissionDenied;
  }

  PopulateDescriptor(descriptor, out_descriptor);
  return kStatusSuccess;
}

void BluetoothLowEnergyEventRouter::ReadCharacteristicValue(
    const Extension* extension,
    const std::string& instance_id,
    const base::Closure& callback,
    const ErrorCallback& error_callback) {
  DCHECK_CURRENTLY_ON(BrowserThread::UI);
  DCHECK(extension);
  if (!adapter_.get()) {
    VLOG(1) << "BluetoothAdapter not ready.";
    error_callback.Run(kStatusErrorFailed);
    return;
  }

  BluetoothGattCharacteristic* characteristic =
      FindCharacteristicById(instance_id);
  if (!characteristic) {
    VLOG(1) << "Characteristic not found: " << instance_id;
    error_callback.Run(kStatusErrorNotFound);
    return;
  }

  BluetoothPermissionRequest request(
      characteristic->GetService()->GetUUID().value());
  if (!BluetoothManifestData::CheckRequest(extension, request)) {
    VLOG(1) << "App has no permission to access this characteristic: "
            << instance_id;
    error_callback.Run(kStatusErrorPermissionDenied);
    return;
  }

  characteristic->ReadRemoteCharacteristic(
      base::Bind(&BluetoothLowEnergyEventRouter::OnValueSuccess,
                 weak_ptr_factory_.GetWeakPtr(),
                 callback),
      base::Bind(&BluetoothLowEnergyEventRouter::OnError,
                 weak_ptr_factory_.GetWeakPtr(),
                 error_callback));
}

void BluetoothLowEnergyEventRouter::WriteCharacteristicValue(
    const Extension* extension,
    const std::string& instance_id,
    const std::vector<uint8>& value,
    const base::Closure& callback,
    const ErrorCallback& error_callback) {
  DCHECK_CURRENTLY_ON(BrowserThread::UI);
  DCHECK(extension);
  if (!adapter_.get()) {
    VLOG(1) << "BluetoothAdapter not ready.";
    error_callback.Run(kStatusErrorFailed);
    return;
  }

  BluetoothGattCharacteristic* characteristic =
      FindCharacteristicById(instance_id);
  if (!characteristic) {
    VLOG(1) << "Characteristic not found: " << instance_id;
    error_callback.Run(kStatusErrorNotFound);
    return;
  }

  BluetoothPermissionRequest request(
      characteristic->GetService()->GetUUID().value());
  if (!BluetoothManifestData::CheckRequest(extension, request)) {
    VLOG(1) << "App has no permission to access this characteristic: "
            << instance_id;
    error_callback.Run(kStatusErrorPermissionDenied);
    return;
  }

  characteristic->WriteRemoteCharacteristic(
      value,
      callback,
      base::Bind(&BluetoothLowEnergyEventRouter::OnError,
                 weak_ptr_factory_.GetWeakPtr(),
                 error_callback));
}

void BluetoothLowEnergyEventRouter::StartCharacteristicNotifications(
    bool persistent,
    const Extension* extension,
    const std::string& instance_id,
    const base::Closure& callback,
    const ErrorCallback& error_callback) {
  DCHECK_CURRENTLY_ON(BrowserThread::UI);
  if (!adapter_.get()) {
    VLOG(1) << "BluetoothAdapter not ready.";
    error_callback.Run(kStatusErrorFailed);
    return;
  }

  const std::string extension_id = extension->id();
  const std::string session_id = extension_id + instance_id;

  if (pending_session_calls_.count(session_id) != 0) {
    error_callback.Run(kStatusErrorInProgress);
    return;
  }

  BluetoothLowEnergyNotifySession* session =
      FindNotifySession(extension_id, instance_id);
  if (session) {
    if (session->GetSession()->IsActive()) {
      VLOG(1) << "Application has already enabled notifications from "
              << "characteristic: " << instance_id;
      error_callback.Run(kStatusErrorAlreadyNotifying);
      return;
    }

    RemoveNotifySession(extension_id, instance_id);
  }

  BluetoothGattCharacteristic* characteristic =
      FindCharacteristicById(instance_id);
  if (!characteristic) {
    VLOG(1) << "Characteristic not found: " << instance_id;
    error_callback.Run(kStatusErrorNotFound);
    return;
  }

  BluetoothPermissionRequest request(
      characteristic->GetService()->GetUUID().value());
  if (!BluetoothManifestData::CheckRequest(extension, request)) {
    VLOG(1) << "App has no permission to access this characteristic: "
            << instance_id;
    error_callback.Run(kStatusErrorPermissionDenied);
    return;
  }

  pending_session_calls_.insert(session_id);
  characteristic->StartNotifySession(
      base::Bind(&BluetoothLowEnergyEventRouter::OnStartNotifySession,
                 weak_ptr_factory_.GetWeakPtr(),
                 persistent,
                 extension_id,
                 instance_id,
                 callback),
      base::Bind(&BluetoothLowEnergyEventRouter::OnStartNotifySessionError,
                 weak_ptr_factory_.GetWeakPtr(),
                 extension_id,
                 instance_id,
                 error_callback));
}

void BluetoothLowEnergyEventRouter::StopCharacteristicNotifications(
    const Extension* extension,
    const std::string& instance_id,
    const base::Closure& callback,
    const ErrorCallback& error_callback) {
  DCHECK_CURRENTLY_ON(BrowserThread::UI);
  if (!adapter_.get()) {
    VLOG(1) << "BluetoothAdapter not ready.";
    error_callback.Run(kStatusErrorFailed);
    return;
  }

  const std::string extension_id = extension->id();

  BluetoothLowEnergyNotifySession* session =
      FindNotifySession(extension_id, instance_id);
  if (!session || !session->GetSession()->IsActive()) {
    VLOG(1) << "Application has not enabled notifications from "
            << "characteristic: " << instance_id;
    error_callback.Run(kStatusErrorNotNotifying);
    return;
  }

  session->GetSession()->Stop(
      base::Bind(&BluetoothLowEnergyEventRouter::OnStopNotifySession,
                 weak_ptr_factory_.GetWeakPtr(),
                 extension_id,
                 instance_id,
                 callback));
}

void BluetoothLowEnergyEventRouter::ReadDescriptorValue(
    const Extension* extension,
    const std::string& instance_id,
    const base::Closure& callback,
    const ErrorCallback& error_callback) {
  DCHECK_CURRENTLY_ON(BrowserThread::UI);
  DCHECK(extension);
  if (!adapter_.get()) {
    VLOG(1) << "BluetoothAdapter not ready.";
    error_callback.Run(kStatusErrorFailed);
    return;
  }

  BluetoothGattDescriptor* descriptor = FindDescriptorById(instance_id);
  if (!descriptor) {
    VLOG(1) << "Descriptor not found: " << instance_id;
    error_callback.Run(kStatusErrorNotFound);
    return;
  }

  BluetoothPermissionRequest request(
      descriptor->GetCharacteristic()->GetService()->GetUUID().value());
  if (!BluetoothManifestData::CheckRequest(extension, request)) {
    VLOG(1) << "App has no permission to access this descriptor: "
            << instance_id;
    error_callback.Run(kStatusErrorPermissionDenied);
    return;
  }

  descriptor->ReadRemoteDescriptor(
      base::Bind(&BluetoothLowEnergyEventRouter::OnValueSuccess,
                 weak_ptr_factory_.GetWeakPtr(),
                 callback),
      base::Bind(&BluetoothLowEnergyEventRouter::OnError,
                 weak_ptr_factory_.GetWeakPtr(),
                 error_callback));
}

void BluetoothLowEnergyEventRouter::WriteDescriptorValue(
    const Extension* extension,
    const std::string& instance_id,
    const std::vector<uint8>& value,
    const base::Closure& callback,
    const ErrorCallback& error_callback) {
  DCHECK_CURRENTLY_ON(BrowserThread::UI);
  DCHECK(extension);
  if (!adapter_.get()) {
    VLOG(1) << "BluetoothAdapter not ready.";
    error_callback.Run(kStatusErrorFailed);
    return;
  }

  BluetoothGattDescriptor* descriptor = FindDescriptorById(instance_id);
  if (!descriptor) {
    VLOG(1) << "Descriptor not found: " << instance_id;
    error_callback.Run(kStatusErrorNotFound);
    return;
  }

  BluetoothPermissionRequest request(
      descriptor->GetCharacteristic()->GetService()->GetUUID().value());
  if (!BluetoothManifestData::CheckRequest(extension, request)) {
    VLOG(1) << "App has no permission to access this descriptor: "
            << instance_id;
    error_callback.Run(kStatusErrorPermissionDenied);
    return;
  }

  descriptor->WriteRemoteDescriptor(
      value,
      callback,
      base::Bind(&BluetoothLowEnergyEventRouter::OnError,
                 weak_ptr_factory_.GetWeakPtr(),
                 error_callback));
}

void BluetoothLowEnergyEventRouter::SetAdapterForTesting(
    device::BluetoothAdapter* adapter) {
  adapter_ = adapter;
  InitializeIdentifierMappings();
}

void BluetoothLowEnergyEventRouter::GattServiceAdded(
    BluetoothAdapter* adapter,
    BluetoothDevice* device,
    BluetoothGattService* service) {
  DCHECK_CURRENTLY_ON(BrowserThread::UI);
  DCHECK_EQ(adapter, adapter_.get());
  VLOG(2) << "GATT service added: " << service->GetIdentifier();

  DCHECK(service_id_to_device_address_.find(service->GetIdentifier()) ==
         service_id_to_device_address_.end());

  service_id_to_device_address_[service->GetIdentifier()] =
      device->GetAddress();
}

void BluetoothLowEnergyEventRouter::GattServiceRemoved(
    BluetoothAdapter* adapter,
    BluetoothDevice* device,
    BluetoothGattService* service) {
  DCHECK_CURRENTLY_ON(BrowserThread::UI);
  DCHECK_EQ(adapter, adapter_.get());
  VLOG(2) << "GATT service removed: " << service->GetIdentifier();

  DCHECK(service_id_to_device_address_.find(service->GetIdentifier()) !=
         service_id_to_device_address_.end());

  DCHECK(device->GetAddress() ==
         service_id_to_device_address_[service->GetIdentifier()]);
  service_id_to_device_address_.erase(service->GetIdentifier());

  // Signal API event.
  apibtle::Service api_service;
  PopulateService(service, &api_service);

  scoped_ptr<base::ListValue> args =
      apibtle::OnServiceRemoved::Create(api_service);
  scoped_ptr<Event> event(
      new Event(apibtle::OnServiceRemoved::kEventName, args.Pass()));
  EventRouter::Get(browser_context_)->BroadcastEvent(event.Pass());
}

void BluetoothLowEnergyEventRouter::GattDiscoveryCompleteForService(
    BluetoothAdapter* adapter,
    BluetoothGattService* service) {
  DCHECK_CURRENTLY_ON(BrowserThread::UI);
  DCHECK_EQ(adapter, adapter_.get());
  VLOG(2) << "GATT service discovery complete: " << service->GetIdentifier();

  DCHECK(service_id_to_device_address_.find(service->GetIdentifier()) !=
         service_id_to_device_address_.end());

  // Signal the service added event here.
  apibtle::Service api_service;
  PopulateService(service, &api_service);

  scoped_ptr<base::ListValue> args =
      apibtle::OnServiceAdded::Create(api_service);
  scoped_ptr<Event> event(
      new Event(apibtle::OnServiceAdded::kEventName, args.Pass()));
  EventRouter::Get(browser_context_)->BroadcastEvent(event.Pass());
}

void BluetoothLowEnergyEventRouter::GattServiceChanged(
    BluetoothAdapter* adapter,
    BluetoothGattService* service) {
  DCHECK_CURRENTLY_ON(BrowserThread::UI);
  DCHECK_EQ(adapter, adapter_.get());
  VLOG(2) << "GATT service changed: " << service->GetIdentifier();
  DCHECK(service_id_to_device_address_.find(service->GetIdentifier()) !=
         service_id_to_device_address_.end());

  // Signal API event.
  apibtle::Service api_service;
  PopulateService(service, &api_service);

  DispatchEventToExtensionsWithPermission(
      apibtle::OnServiceChanged::kEventName,
      service->GetUUID(),
      "" /* characteristic_id */,
      apibtle::OnServiceChanged::Create(api_service));
}

void BluetoothLowEnergyEventRouter::GattCharacteristicAdded(
    BluetoothAdapter* adapter,
    BluetoothGattCharacteristic* characteristic) {
  DCHECK_CURRENTLY_ON(BrowserThread::UI);
  DCHECK_EQ(adapter, adapter_.get());
  VLOG(2) << "GATT characteristic added: " << characteristic->GetIdentifier();

  BluetoothGattService* service = characteristic->GetService();
  DCHECK(service);

  DCHECK(chrc_id_to_service_id_.find(characteristic->GetIdentifier()) ==
         chrc_id_to_service_id_.end());
  DCHECK(service_id_to_device_address_.find(service->GetIdentifier()) !=
         service_id_to_device_address_.end());

  chrc_id_to_service_id_[characteristic->GetIdentifier()] =
      service->GetIdentifier();
}

void BluetoothLowEnergyEventRouter::GattCharacteristicRemoved(
    BluetoothAdapter* adapter,
    BluetoothGattCharacteristic* characteristic) {
  DCHECK_CURRENTLY_ON(BrowserThread::UI);
  DCHECK_EQ(adapter, adapter_.get());
  VLOG(2) << "GATT characteristic removed: " << characteristic->GetIdentifier();

  BluetoothGattService* service = characteristic->GetService();
  DCHECK(service);

  DCHECK(chrc_id_to_service_id_.find(characteristic->GetIdentifier()) !=
         chrc_id_to_service_id_.end());
  DCHECK(service->GetIdentifier() ==
         chrc_id_to_service_id_[characteristic->GetIdentifier()]);

  chrc_id_to_service_id_.erase(characteristic->GetIdentifier());
}

void BluetoothLowEnergyEventRouter::GattDescriptorAdded(
    BluetoothAdapter* adapter,
    BluetoothGattDescriptor* descriptor) {
  DCHECK_CURRENTLY_ON(BrowserThread::UI);
  DCHECK_EQ(adapter, adapter_.get());
  VLOG(2) << "GATT descriptor added: " << descriptor->GetIdentifier();

  BluetoothGattCharacteristic* characteristic = descriptor->GetCharacteristic();
  DCHECK(characteristic);

  DCHECK(desc_id_to_chrc_id_.find(descriptor->GetIdentifier()) ==
         desc_id_to_chrc_id_.end());
  DCHECK(chrc_id_to_service_id_.find(characteristic->GetIdentifier()) !=
         chrc_id_to_service_id_.end());

  desc_id_to_chrc_id_[descriptor->GetIdentifier()] =
      characteristic->GetIdentifier();
}

void BluetoothLowEnergyEventRouter::GattDescriptorRemoved(
    BluetoothAdapter* adapter,
    BluetoothGattDescriptor* descriptor) {
  DCHECK_CURRENTLY_ON(BrowserThread::UI);
  DCHECK_EQ(adapter, adapter_.get());
  VLOG(2) << "GATT descriptor removed: " << descriptor->GetIdentifier();

  BluetoothGattCharacteristic* characteristic = descriptor->GetCharacteristic();
  DCHECK(characteristic);

  DCHECK(desc_id_to_chrc_id_.find(descriptor->GetIdentifier()) !=
         desc_id_to_chrc_id_.end());
  DCHECK(characteristic->GetIdentifier() ==
         desc_id_to_chrc_id_[descriptor->GetIdentifier()]);

  desc_id_to_chrc_id_.erase(descriptor->GetIdentifier());
}

void BluetoothLowEnergyEventRouter::GattCharacteristicValueChanged(
    BluetoothAdapter* adapter,
    BluetoothGattCharacteristic* characteristic,
    const std::vector<uint8>& value) {
  DCHECK_CURRENTLY_ON(BrowserThread::UI);
  DCHECK_EQ(adapter, adapter_.get());
  VLOG(2) << "GATT characteristic value changed: "
          << characteristic->GetIdentifier();

  BluetoothGattService* service = characteristic->GetService();
  DCHECK(service);

  DCHECK(service_id_to_device_address_.find(service->GetIdentifier()) !=
         service_id_to_device_address_.end());
  DCHECK(chrc_id_to_service_id_.find(characteristic->GetIdentifier()) !=
         chrc_id_to_service_id_.end());
  DCHECK(chrc_id_to_service_id_[characteristic->GetIdentifier()] ==
         service->GetIdentifier());

  // Send the event; manually construct the arguments, instead of using
  // apibtle::OnCharacteristicValueChanged::Create, as it doesn't convert
  // lists of enums correctly.
  apibtle::Characteristic api_characteristic;
  PopulateCharacteristic(characteristic, &api_characteristic);
  scoped_ptr<base::ListValue> args(new base::ListValue());
  args->Append(apibtle::CharacteristicToValue(&api_characteristic).release());

  DispatchEventToExtensionsWithPermission(
      apibtle::OnCharacteristicValueChanged::kEventName,
      service->GetUUID(),
      characteristic->GetIdentifier(),
      args.Pass());
}

void BluetoothLowEnergyEventRouter::GattDescriptorValueChanged(
    BluetoothAdapter* adapter,
    BluetoothGattDescriptor* descriptor,
    const std::vector<uint8>& value) {
  DCHECK_CURRENTLY_ON(BrowserThread::UI);
  DCHECK_EQ(adapter, adapter_.get());
  VLOG(2) << "GATT descriptor value changed: " << descriptor->GetIdentifier();

  BluetoothGattCharacteristic* characteristic = descriptor->GetCharacteristic();
  DCHECK(characteristic);

  DCHECK(desc_id_to_chrc_id_.find(descriptor->GetIdentifier()) !=
         desc_id_to_chrc_id_.end());
  DCHECK(characteristic->GetIdentifier() ==
         desc_id_to_chrc_id_[descriptor->GetIdentifier()]);

  // Send the event; manually construct the arguments, instead of using
  // apibtle::OnDescriptorValueChanged::Create, as it doesn't convert
  // lists of enums correctly.
  apibtle::Descriptor api_descriptor;
  PopulateDescriptor(descriptor, &api_descriptor);
  scoped_ptr<base::ListValue> args(new base::ListValue());
  args->Append(apibtle::DescriptorToValue(&api_descriptor).release());

  DispatchEventToExtensionsWithPermission(
      apibtle::OnDescriptorValueChanged::kEventName,
      characteristic->GetService()->GetUUID(),
      "" /* characteristic_id */,
      args.Pass());
}

void BluetoothLowEnergyEventRouter::OnGetAdapter(
    const base::Closure& callback,
    scoped_refptr<device::BluetoothAdapter> adapter) {
  adapter_ = adapter;

  // Initialize instance ID mappings for all discovered GATT objects and add
  // observers.
  InitializeIdentifierMappings();
  adapter_->AddObserver(this);

  callback.Run();
}

void BluetoothLowEnergyEventRouter::InitializeIdentifierMappings() {
  DCHECK_CURRENTLY_ON(BrowserThread::UI);
  DCHECK(service_id_to_device_address_.empty());
  DCHECK(chrc_id_to_service_id_.empty());

  // Devices
  BluetoothAdapter::DeviceList devices = adapter_->GetDevices();
  for (BluetoothAdapter::DeviceList::iterator iter = devices.begin();
       iter != devices.end();
       ++iter) {
    BluetoothDevice* device = *iter;

    // Services
    std::vector<BluetoothGattService*> services = device->GetGattServices();
    for (std::vector<BluetoothGattService*>::iterator siter = services.begin();
         siter != services.end();
         ++siter) {
      BluetoothGattService* service = *siter;

      const std::string& service_id = service->GetIdentifier();
      service_id_to_device_address_[service_id] = device->GetAddress();

      // Characteristics
      const std::vector<BluetoothGattCharacteristic*>& characteristics =
          service->GetCharacteristics();
      for (std::vector<BluetoothGattCharacteristic*>::const_iterator citer =
               characteristics.begin();
           citer != characteristics.end();
           ++citer) {
        BluetoothGattCharacteristic* characteristic = *citer;

        const std::string& chrc_id = characteristic->GetIdentifier();
        chrc_id_to_service_id_[chrc_id] = service_id;

        // Descriptors
        const std::vector<BluetoothGattDescriptor*>& descriptors =
            characteristic->GetDescriptors();
        for (std::vector<BluetoothGattDescriptor*>::const_iterator diter =
                 descriptors.begin();
             diter != descriptors.end();
             ++diter) {
          BluetoothGattDescriptor* descriptor = *diter;

          const std::string& desc_id = descriptor->GetIdentifier();
          desc_id_to_chrc_id_[desc_id] = chrc_id;
        }
      }
    }
  }
}

void BluetoothLowEnergyEventRouter::DispatchEventToExtensionsWithPermission(
    const std::string& event_name,
    const device::BluetoothUUID& uuid,
    const std::string& characteristic_id,
    scoped_ptr<base::ListValue> args) {
  // Obtain the listeners of |event_name|. The list can contain multiple
  // entries for the same extension, so we keep track of the extensions that we
  // already sent the event to, since we want the send an event to an extension
  // only once.
  BluetoothPermissionRequest request(uuid.value());
  std::set<std::string> handled_extensions;
  const EventListenerMap::ListenerList listeners =
      EventRouter::Get(browser_context_)->listeners().GetEventListenersByName(
          event_name);

  for (EventListenerMap::ListenerList::const_iterator iter = listeners.begin();
       iter != listeners.end();
       ++iter) {
    const std::string extension_id = (*iter)->extension_id();
    if (handled_extensions.find(extension_id) != handled_extensions.end())
      continue;

    handled_extensions.insert(extension_id);

    const Extension* extension =
        ExtensionRegistry::Get(browser_context_)
            ->GetExtensionById(extension_id, ExtensionRegistry::EVERYTHING);

    // For all API methods, the "low_energy" permission check is handled by
    // BluetoothLowEnergyExtensionFunction but for events we have to do the
    // check here.
    if (!BluetoothManifestData::CheckRequest(extension, request) ||
        !BluetoothManifestData::CheckLowEnergyPermitted(extension))
      continue;

    // If |event_name| is "onCharacteristicValueChanged", then send the
    // event only if the extension has requested notifications from the
    // related characteristic.
    if (event_name == apibtle::OnCharacteristicValueChanged::kEventName &&
        !characteristic_id.empty() &&
        !FindNotifySession(extension_id, characteristic_id))
      continue;

    // Send the event.
    scoped_ptr<base::ListValue> args_copy(args->DeepCopy());
    scoped_ptr<Event> event(new Event(event_name, args_copy.Pass()));
    EventRouter::Get(browser_context_)->DispatchEventToExtension(
        extension_id, event.Pass());
  }
}

BluetoothGattService* BluetoothLowEnergyEventRouter::FindServiceById(
    const std::string& instance_id) const {
  InstanceIdMap::const_iterator iter =
      service_id_to_device_address_.find(instance_id);
  if (iter == service_id_to_device_address_.end()) {
    VLOG(1) << "GATT service identifier unknown: " << instance_id;
    return NULL;
  }

  const std::string& address = iter->second;

  BluetoothDevice* device = adapter_->GetDevice(address);
  if (!device) {
    VLOG(1) << "Bluetooth device not found: " << address;
    return NULL;
  }

  BluetoothGattService* service = device->GetGattService(instance_id);
  if (!service) {
    VLOG(1) << "GATT service with ID \"" << instance_id
            << "\" not found on device \"" << address << "\"";
    return NULL;
  }

  return service;
}

BluetoothGattCharacteristic*
BluetoothLowEnergyEventRouter::FindCharacteristicById(
    const std::string& instance_id) const {
  InstanceIdMap::const_iterator iter = chrc_id_to_service_id_.find(instance_id);
  if (iter == chrc_id_to_service_id_.end()) {
    VLOG(1) << "GATT characteristic identifier unknown: " << instance_id;
    return NULL;
  }

  const std::string& service_id = iter->second;

  BluetoothGattService* service = FindServiceById(service_id);
  if (!service) {
    VLOG(1) << "Failed to obtain service for characteristic: " << instance_id;
    return NULL;
  }

  BluetoothGattCharacteristic* characteristic =
      service->GetCharacteristic(instance_id);
  if (!characteristic) {
    VLOG(1) << "GATT characteristic with ID \"" << instance_id
            << "\" not found on service \"" << service_id << "\"";
    return NULL;
  }

  return characteristic;
}

BluetoothGattDescriptor* BluetoothLowEnergyEventRouter::FindDescriptorById(
    const std::string& instance_id) const {
  InstanceIdMap::const_iterator iter = desc_id_to_chrc_id_.find(instance_id);
  if (iter == desc_id_to_chrc_id_.end()) {
    VLOG(1) << "GATT descriptor identifier unknown: " << instance_id;
    return NULL;
  }

  const std::string& chrc_id = iter->second;
  BluetoothGattCharacteristic* chrc = FindCharacteristicById(chrc_id);
  if (!chrc) {
    VLOG(1) << "Failed to obtain characteristic for descriptor: "
            << instance_id;
    return NULL;
  }

  BluetoothGattDescriptor* descriptor = chrc->GetDescriptor(instance_id);
  if (!descriptor) {
    VLOG(1) << "GATT descriptor with ID \"" << instance_id
            << "\" not found on characteristic \"" << chrc_id << "\"";
    return NULL;
  }

  return descriptor;
}

void BluetoothLowEnergyEventRouter::OnValueSuccess(
    const base::Closure& callback,
    const std::vector<uint8>& value) {
  VLOG(2) << "Remote characteristic/descriptor value read successful.";
  callback.Run();
}

void BluetoothLowEnergyEventRouter::OnCreateGattConnection(
    bool persistent,
    const std::string& extension_id,
    const std::string& device_address,
    const base::Closure& callback,
    scoped_ptr<BluetoothGattConnection> connection) {
  VLOG(2) << "GATT connection created.";
  DCHECK(connection.get());
  DCHECK(!FindConnection(extension_id, device_address));
  DCHECK_EQ(device_address, connection->GetDeviceAddress());

  const std::string connect_id = extension_id + device_address;
  DCHECK_NE(0U, connecting_devices_.count(connect_id));

  BluetoothLowEnergyConnection* conn = new BluetoothLowEnergyConnection(
      persistent, extension_id, connection.Pass());
  ConnectionResourceManager* manager =
      GetConnectionResourceManager(browser_context_);
  manager->Add(conn);

  connecting_devices_.erase(connect_id);
  callback.Run();
}

void BluetoothLowEnergyEventRouter::OnDisconnect(
    const std::string& extension_id,
    const std::string& device_address,
    const base::Closure& callback) {
  VLOG(2) << "GATT connection terminated.";

  const std::string disconnect_id = extension_id + device_address;
  DCHECK_NE(0U, disconnecting_devices_.count(disconnect_id));

  if (!RemoveConnection(extension_id, device_address)) {
    VLOG(1) << "The connection was removed before disconnect completed, id: "
            << extension_id << ", device: " << device_address;
  }

  disconnecting_devices_.erase(disconnect_id);
  callback.Run();
}

void BluetoothLowEnergyEventRouter::OnError(
    const ErrorCallback& error_callback,
    BluetoothGattService::GattErrorCode error_code) {
  VLOG(2) << "Remote characteristic/descriptor value read/write failed.";

  error_callback.Run(GattErrorToRouterError(error_code));
}

void BluetoothLowEnergyEventRouter::OnConnectError(
    const std::string& extension_id,
    const std::string& device_address,
    const ErrorCallback& error_callback,
    BluetoothDevice::ConnectErrorCode error_code) {
  VLOG(2) << "Failed to create GATT connection: " << error_code;

  const std::string connect_id = extension_id + device_address;
  DCHECK_NE(0U, connecting_devices_.count(connect_id));

  connecting_devices_.erase(connect_id);
  Status error_status = kStatusErrorFailed;
  if (error_code == BluetoothDevice::ERROR_INPROGRESS) {
    error_status = kStatusErrorInProgress;
  } else if (error_code == BluetoothDevice::ERROR_AUTH_FAILED ||
             error_code == BluetoothDevice::ERROR_AUTH_REJECTED) {
    error_status = kStatusErrorAuthenticationFailed;
  } else if (error_code == BluetoothDevice::ERROR_AUTH_CANCELED) {
    error_status = kStatusErrorCanceled;
  } else if (error_code == BluetoothDevice::ERROR_AUTH_TIMEOUT) {
    error_status = kStatusErrorTimeout;
  } else if (error_code == BluetoothDevice::ERROR_UNSUPPORTED_DEVICE) {
    error_status = kStatusErrorUnsupportedDevice;
  }
  // ERROR_UNKNOWN and ERROR_FAILED defaulted to kStatusErrorFailed

  error_callback.Run(error_status);
}

void BluetoothLowEnergyEventRouter::OnStartNotifySession(
    bool persistent,
    const std::string& extension_id,
    const std::string& characteristic_id,
    const base::Closure& callback,
    scoped_ptr<device::BluetoothGattNotifySession> session) {
  VLOG(2) << "Value update session created for characteristic: "
          << characteristic_id;
  DCHECK(session.get());
  DCHECK(!FindNotifySession(extension_id, characteristic_id));
  DCHECK_EQ(characteristic_id, session->GetCharacteristicIdentifier());

  const std::string session_id = extension_id + characteristic_id;
  DCHECK_NE(0U, pending_session_calls_.count(session_id));

  BluetoothLowEnergyNotifySession* resource =
      new BluetoothLowEnergyNotifySession(
          persistent, extension_id, session.Pass());

  NotifySessionResourceManager* manager =
      GetNotifySessionResourceManager(browser_context_);
  manager->Add(resource);

  pending_session_calls_.erase(session_id);
  callback.Run();
}

void BluetoothLowEnergyEventRouter::OnStartNotifySessionError(
    const std::string& extension_id,
    const std::string& characteristic_id,
    const ErrorCallback& error_callback,
    device::BluetoothGattService::GattErrorCode error_code) {
  VLOG(2) << "Failed to create value update session for characteristic: "
          << characteristic_id;

  const std::string session_id = extension_id + characteristic_id;
  DCHECK_NE(0U, pending_session_calls_.count(session_id));

  pending_session_calls_.erase(session_id);
  error_callback.Run(GattErrorToRouterError(error_code));
}

void BluetoothLowEnergyEventRouter::OnStopNotifySession(
    const std::string& extension_id,
    const std::string& characteristic_id,
    const base::Closure& callback) {
  VLOG(2) << "Value update session terminated.";

  if (!RemoveNotifySession(extension_id, characteristic_id)) {
    VLOG(1) << "The value update session was removed before Stop completed, "
            << "id: " << extension_id
            << ", characteristic: " << characteristic_id;
  }

  callback.Run();
}

BluetoothLowEnergyConnection* BluetoothLowEnergyEventRouter::FindConnection(
    const std::string& extension_id,
    const std::string& device_address) {
  ConnectionResourceManager* manager =
      GetConnectionResourceManager(browser_context_);

  base::hash_set<int>* connection_ids = manager->GetResourceIds(extension_id);
  if (!connection_ids)
    return NULL;

  for (base::hash_set<int>::const_iterator iter = connection_ids->begin();
       iter != connection_ids->end();
       ++iter) {
    extensions::BluetoothLowEnergyConnection* conn =
        manager->Get(extension_id, *iter);
    if (!conn)
      continue;

    if (conn->GetConnection()->GetDeviceAddress() == device_address)
      return conn;
  }

  return NULL;
}

bool BluetoothLowEnergyEventRouter::RemoveConnection(
    const std::string& extension_id,
    const std::string& device_address) {
  ConnectionResourceManager* manager =
      GetConnectionResourceManager(browser_context_);

  base::hash_set<int>* connection_ids = manager->GetResourceIds(extension_id);
  if (!connection_ids)
    return false;

  for (base::hash_set<int>::const_iterator iter = connection_ids->begin();
       iter != connection_ids->end();
       ++iter) {
    extensions::BluetoothLowEnergyConnection* conn =
        manager->Get(extension_id, *iter);
    if (!conn || conn->GetConnection()->GetDeviceAddress() != device_address)
      continue;

    manager->Remove(extension_id, *iter);
    return true;
  }

  return false;
}

BluetoothLowEnergyNotifySession*
BluetoothLowEnergyEventRouter::FindNotifySession(
    const std::string& extension_id,
    const std::string& characteristic_id) {
  NotifySessionResourceManager* manager =
      GetNotifySessionResourceManager(browser_context_);

  base::hash_set<int>* ids = manager->GetResourceIds(extension_id);
  if (!ids)
    return NULL;

  for (base::hash_set<int>::const_iterator iter = ids->begin();
       iter != ids->end();
       ++iter) {
    BluetoothLowEnergyNotifySession* session =
        manager->Get(extension_id, *iter);
    if (!session)
      continue;

    if (session->GetSession()->GetCharacteristicIdentifier() ==
        characteristic_id)
      return session;
  }

  return NULL;
}

bool BluetoothLowEnergyEventRouter::RemoveNotifySession(
    const std::string& extension_id,
    const std::string& characteristic_id) {
  NotifySessionResourceManager* manager =
      GetNotifySessionResourceManager(browser_context_);

  base::hash_set<int>* ids = manager->GetResourceIds(extension_id);
  if (!ids)
    return false;

  for (base::hash_set<int>::const_iterator iter = ids->begin();
       iter != ids->end();
       ++iter) {
    BluetoothLowEnergyNotifySession* session =
        manager->Get(extension_id, *iter);
    if (!session ||
        session->GetSession()->GetCharacteristicIdentifier() !=
            characteristic_id)
      continue;

    manager->Remove(extension_id, *iter);
    return true;
  }

  return false;
}

}  // namespace extensions


text:
module Spree
  class PrototypeTaxon < Spree::Base
    belongs_to :taxon, class_name: 'Spree::Taxon'
    belongs_to :prototype, class_name: 'Spree::Prototype'

    validates :prototype, :taxon, presence: true
    validates :prototype_id, uniqueness: { scope: :taxon_id }
  end
end


text:
require 'rails_helper'

RSpec.describe "blink/make_blink.html.erb", :type => :view do
  pending "add some examples to (or delete) #{__FILE__}"
end


text:
import scala.tools.nsc._
import interpreter.ILoop
import scala.tools.partest.ReplTest

object Test extends ReplTest {
  override def extraSettings = "-Yinline"
  def code = """
    val n = 2
    () => n
  """
}


text:
package Apache::Session::Store::DB_File;

use strict;
use vars qw($VERSION);
use DB_File;

$VERSION = '1.01';

sub new {
    my $class = shift;

    return bless {dbm => {}}, $class;
}

sub insert {
    my $self    = shift;
    my $session = shift;

    if (!tied %{$self->{dbm}}) {
        my $rv = tie %{$self->{dbm}}, 'DB_File', $session->{args}->{FileName};

        if (!$rv) {
            die "Could not open dbm file $session->{args}->{FileName}: $!";
        }
    }

    if (exists $self->{dbm}->{$session->{data}->{_session_id}}) {
        die "Object already exists in the data store";
    }

    $self->{dbm}->{$session->{data}->{_session_id}} = $session->{serialized};
}

sub update {
    my $self = shift;
    my $session = shift;

    if (!tied %{$self->{dbm}}) {
        my $rv = tie %{$self->{dbm}}, 'DB_File', $session->{args}->{FileName};

        if (!$rv) {
            die "Could not open dbm file $session->{args}->{FileName}: $!";
        }
    }

    $self->{dbm}->{$session->{data}->{_session_id}} = $session->{serialized};
}

sub materialize {
    my $self = shift;
    my $session = shift;

    if (!tied %{$self->{dbm}}) {
        my $rv = tie %{$self->{dbm}}, 'DB_File', $session->{args}->{FileName};

        if (!$rv) {
            die "Could not open dbm file $session->{args}->{FileName}: $!";
        }
    }

    $session->{serialized} = $self->{dbm}->{$session->{data}->{_session_id}};

    if (!defined $session->{serialized}) {
        die "Object does not exist in data store";
    }
}

sub remove {
    my $self = shift;
    my $session = shift;

    if (!tied %{$self->{dbm}}) {
        my $rv = tie %{$self->{dbm}}, 'DB_File', $session->{args}->{FileName};

        if (!$rv) {
            die "Could not open dbm file $session->{args}->{FileName}: $!";
        }
    }

    delete $self->{dbm}->{$session->{data}->{_session_id}};
}

1;

=pod

=head1 NAME

Apache::Session::Store::DB_File - Use DB_File to store persistent objects

=head1 SYNOPSIS

 use Apache::Session::Store::DB_File;

 my $store = new Apache::Session::Store::DB_File;

 $store->insert($ref);
 $store->update($ref);
 $store->materialize($ref);
 $store->remove($ref);

=head1 DESCRIPTION

This module fulfills the storage interface of Apache::Session.  The serialized
objects are stored in a Berkeley DB file using the DB_File Perl module.  If
DB_File works on your platform, this module should also work.

=head1 OPTIONS

This module requires one argument in the usual Apache::Session style.  The
name of the option is FileName, and the value is the full path of the database
file to be used as the backing store.  If the database file does not exist,
it will be created.  Example:

 tie %s, 'Apache::Session::DB_File', undef,
    {FileName => '/tmp/sessions'};

=head1 AUTHOR

This module was written by Jeffrey William Baker <jwbaker@acm.org>.

=head1 SEE ALSO

L<Apache::Session>, L<DB_File>


text:
module hirespace.specs {
    'use strict';

    describe('Modal', () => {
        it('should listen for clicks on elements with toggle-modal class', () => {
            expect(hirespace.Modal.listen).toBeDefined();
        });
    });
}


text:
<?php

namespace App\Article\Models;

class Category extends \App\Common\Models\Article\Category
{

    /**
     * 默认排序方式
     * @return array
     */
    public function getDefaultSort()
    {
        $sort = array();
        return $sort;
    }

    /**
     * 默认查询条件
     *
     * @return array
     */
    public function getDefaultQuery()
    {
        $query = array();
        return $query;
    }
}


text:
var d = {
    init : function(){
        d.catkey_raw = Drupal.settings.sirsi_parser.catkey;

        $.ajax({
            url: Drupal.settings.sirsi_parser.base_url + '/sites/default/files/techlending/devices_data/' + d.catkey_raw +'.json',
            error: function (e, t, n) {
                console.log(t + ": " + n);
                console.log(e);
            },
            success: function (e, t, n) {
                console.log(Drupal.settings.sirsi_parser.base_url + '/sites/default/files/techlending/devices_data/' + d.catkey_raw +'.json')
                d.data = e;
                // make sure there is actual data for device
                if(e.buildings){
                    d.compileHTML();
                }
            }
        });
    },

    compileHTML : function(){
        var p = d.data.buildings;
        // build html string
        d.str = '
';
        d.str += '
';
        d.str += '
';
        d.str += '
';
        d.str += 'Library	';
        d.str += 'Lending Period	';
        d.str += 'Available for Checkout	';
        d.str += '
';
        d.str += '
';
        d.str += '
';

        // loop through to get buildings and lending periods
        for (var key in p) {
            if (p.hasOwnProperty(key)) {
                var building = d.getBuilding(key);
                if(building == 'Textiles Library'){continue;}
                var lendPeriod = p[key]['lending-periods'];
                var c = 0;
                for(var lend in lendPeriod){
                    var total = lendPeriod[lend]['total'];
                    var available = lendPeriod[lend]['techlend'];
                    if(d.getLendPeriod(lend) != ""){

                        if(!available){
                            var hold = lendPeriod[lend]['techhold'] != undefined ? lendPeriod[lend]['techhold'] : 0;
                            var repair = lendPeriod[lend]['repair'] != undefined ? lendPeriod[lend]['repair'] : 0;
                            var checkedout = lendPeriod[lend]['checkedout'];
                            available = total - checkedout - repair - hold;
                        }
                        d.str += '
';
                        if(c < 1){
                            d.str += ''+building+'	';
                        } else{
                            d.str += '	';
                        }
                        d.str += ''+d.getLendPeriod(lend)+'	';
                        d.str += ''+available+' of '+total+'	';
                        d.str += '
';
                    }
                    c++;
                }

            }
        }

        d.str += '
';
        d.str += '
';
        d.str += '
';

        $(".hb").html(d.str);
    },

    getBuilding : function(val){
        switch (val) {
            case "hunt":
                return "James B. Hunt Jr. Library";
            case "dhhill":
                return "D. H. Hill Library";
            case "design":
                return "Design Library";
            case "vetmed":
                return "Veternary Medicine Library";
            case "nrl":
                return "Natural Resources Library";
            case "textiles":
                return "Textiles Library";
            default:
                break;
        }
    },

    getLendPeriod : function(val){
        switch (val) {
            case "equip-4hr":
                return "4 hour";
            case "equ-4h-low":
                return "4 hour";
            case "laptop-pat":
                return "4 hour";
            case "equip-1day":
                return "1 day";
            case "equ-1w-low":
                return "1 week";
            case "equip-1wk":
                return "1 week";
            case "laptop-any":
                return "2 hour";
            default:
                return "";
        }
    }
}

$(function(){
    d.init();
})


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">

<title>Agilla</title>

<link rel="stylesheet" href="../styles.css" type="text/css" />
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">

randnbr

Class: B

	(legend)

    Operand Stack
    Heap
    Condition Codes

Initial (operands):

  N/A

Final (return values):

	 Value - A random neighbor's address

N/A

1 if a random
    neighbor was found, 0 otherwise

Description

Pushes the location of a random
neighbor onto the stack.

 This page was last updated
on
December 7, 2005 3:51 AM.

This work is supported by the ONR MURI Project CONTESSA
and the NSF under grant number CCR-9970939.


text:
module m1

end module m1


text:
<?php
/**
 * Created by PhpStorm.
 * User: kilingzhang
 * Date: 2020-04-19
 * Time: 14:01
 */

namespace NeteaseCloudMusicApi\V1\Login;

use NeteaseCloudMusicApi\Controller;
use Utils\Request;

/**
 * Class Cellphone
 * @package NeteaseCloudMusicApi\V1\Login
 *
 * 必选参数 :
 * email: 163 网易邮箱
 *
 * password: 密码
 *
 * 接口地址 : /login
 *
 * 调用例子 : http://i.music.163.com/login?email=xxx@163.com&password=yyy
 *
 */
class Email extends Controller
{
    protected $uri = 'https://music.163.com/weapi/login';

    protected $params = [
        'email' => [
            'value' => null,
            'as' => 'username'
        ],
        'password' => [
            'value' => null,
        ],
        'rememberLogin' => true,
    ];

    protected $options = [
        'ua' => 'pc'
    ];

    protected function newRequest(Request $request): Request
    {
        return $request->setCookie('os', 'pc');
    }

    protected function parseParams($params): array
    {
        $params['password'] = md5($params['password']);
        return $params;
    }
}


text:
export default `

        {{tab.title}}
        <svg-icon-label
            *ngIf="tab.titleIcon"
            [name]="tab.titleIcon"
            [mode]="tab.titleIconMode"
            [size]="_size">
        </svg-icon-label>

<ng-content></ng-content>
`;


text:
require 'pry'
# First defines the CLI class thats responsible for all the input and output.
class BeerMe::CLI

# Displays menu and asking for input from user
  def self.start
    BeerMe::Scraper.get_beers
    menu
    get_input
  end

# Puts menu for user to pick which beer they'd like more info about.
  def self.menu
    puts "BeerAdvocate.com's Top 10 Beers of All Time"
    puts "-------------------------------------------"
    BeerMe::Beer.all.each do |beer|
      puts "#{beer.rank}. #{beer.name}, #{beer.style}, #{beer.rating}"
    end
    puts "-------------------------------------------"
  end

# Gets input from user.
# If user knows what they would like to choose from it lists the beer.
# If user picks number between 1 & 10 and prints input.
# If user types exit, the program will close.
# If user types something other than '1-10', 'list' or 'exit' will notify user again what to choose from.
  def self.get_input
    input=nil
    until input=='exit'
      puts "Please enter a number for details, 'list' to review the top ten, or 'exit' to quit."
      input = gets.strip.downcase
      if input == 'list'
        menu
      elsif input.to_i.between?(1,10)
        show_beer_details(input)
      elsif input == 'exit'
        goodbye
      else
        puts "I don't recognize that command.  Please try again."
      end
    end
  end

# Puts out info about chosen beer.
  def self.show_beer_details(selection)
    beer = BeerMe::Beer.find(selection.to_i)
    puts ""
    puts "Name: #{beer.name}"
    puts "Brewed by: #{beer.brewery}"
    puts "Style: #{beer.style} #{beer.abv}"
    puts "Description: #{beer.description}"
    puts ""
  end

# Goodbye message when user exits program.
  def self.goodbye
    puts ""
    puts "Thanks for stopping by! Don't drink them all in one night!"
  end
end