text:
{-# LANGUAGE ScopedTypeVariables #-}
module Yesod.Helpers.Logger  where

import ClassyPrelude

import Data.Default                         (Default(..))
import qualified Data.Text                  as T
import Control.DeepSeq                      (force)

import Network.Wai.Logger                   (DateCacheGetter)
import Yesod.Core.Types
import System.FilePath                      (splitFileName, takeFileName)
import System.Directory                     (renameFile)
import qualified Text.Parsec.Number         as PN
import Text.Parsec                          (parse, eof)
import qualified Text.Parsec
import Data.Conduit
import Data.Conduit.Combinators             (sourceDirectory)
import System.Posix.Files                   (getFileStatus, fileSize)
import System.Posix.Types                   (COff(..))
import Control.Monad.Trans.Resource         (runResourceT)
import Control.Monad.Logger
import System.Log.FastLogger

import Data.Aeson
import qualified Data.Aeson.Types           as AT

import Yesod.Helpers.Aeson                  ( parseTextByRead, nullValueToNothing, parseSomeObjects
                                            , parseTextByParsec
                                            )
import Yesod.Helpers.Parsec                 ( parseByteSizeWithUnit )

type LoggingFunc = Loc -> LogSource -> LogLevel -> LogStr -> IO ()

class LoggingTRunner a where
    runLoggingTWith :: a -> LoggingT m r -> m r

-- | Use a map to implement 'shouldLog' of Yesod class.
-- The logic is the following:
-- 1) Lookup the LogLevel according to the requested LogSource in the map,
--    If found, compare the requested LogLevel to the found one.
--    If not found, go to step 2.
-- 2) repeat step 1, but using a special LogSource "_".
--    If this failed too, the whole process failed.
-- see: shouldLogByLogSourceLevelMap
type LogSourceLevelMap = Map LogSource (Maybe LogLevel)

-- | Use this function to implement 'shouldLog' or 'shouldLogIO'
shouldLogByLogSourceLevelMap :: LogSourceLevelMap -> LogSource -> LogLevel -> Maybe Bool
shouldLogByLogSourceLevelMap the_map source level = do
    fmap (fromMaybe False . fmap (level >=)) $
        lookup source the_map <|> lookup "_" the_map

-- | A helper for reading LogSourceLevelMap from YAML.
-- Example YAML section:
--  min-log-level:
--    SQL     : LevelWarn
--    _       : LevelDebug
parseLogSourceLevelMap :: Value -> AT.Parser LogSourceLevelMap
parseLogSourceLevelMap val = do
    the_map :: HashMap _ _ <- parseJSON val
    fmap mapFromList $ forM (mapToList the_map) $ \(k, v) -> do
        let new_k = fromString k
        new_v <- nullValueToNothing v >>= traverse (parseTextByRead "LogLevel")
        return (new_k, new_v)

logLevelFromText :: Text -> LogLevel
logLevelFromText "debug"        = LevelDebug
logLevelFromText "LevelDebug"   = LevelDebug

logLevelFromText "info"         = LevelInfo
logLevelFromText "LevelInfo"    = LevelInfo

logLevelFromText "warning"      = LevelWarn
logLevelFromText "warn"         = LevelWarn
logLevelFromText "LevelWarn"    = LevelWarn

logLevelFromText "error"        = LevelError
logLevelFromText "LevelError"   = LevelError

logLevelFromText x              = LevelOther x

data LogDest = LogDestFile BufSize FilePath
            | LogDestStdout BufSize
            | LogDestStderr BufSize
            deriving (Eq, Ord, Show)

newLoggerSetByDest :: LogDest -> IO LoggerSet
newLoggerSetByDest (LogDestStdout buf_size)     = newStdoutLoggerSet buf_size
newLoggerSetByDest (LogDestStderr buf_size)     = newStderrLoggerSet buf_size
newLoggerSetByDest (LogDestFile buf_size fp)    = newFileLoggerSet buf_size fp

type LogArchiveAction = IO ()

type ShouldLogPred = LogSource -> LogLevel -> IO Bool

class LogStore a where
    lxPushLogStr  :: a -> LogStr -> IO ()
    lxGetLoggerSet :: a -> LoggerSet

data SomeLogStore = forall h. LogStore h => SomeLogStore h

class ShouldLogPredicator a where
    lxShouldLog     :: a -> ShouldLogPred

data SomeShouldLogPredicator = forall a. ShouldLogPredicator a => SomeShouldLogPredicator a

shouldLogByLevel ::
    LogLevel        -- ^ minimum level
    -> LogLevel     -- ^ level to be tested
    -> Bool
shouldLogByLevel (LevelOther lmin) (LevelOther lv) = lmin == lv
shouldLogByLevel x y = x <= y

shoudLogBySrcLevelMap ::
    HashMap LogSource LogLevel
    -> LogSource
    -> LogLevel
    -> Bool
shoudLogBySrcLevelMap hm src level =
    case lookup src hm <|> lookup "*" hm of
        Nothing         -> False
        Just req_level  -> shouldLogByLevel req_level level

instance ShouldLogPredicator (HashMap LogSource LogLevel) where
    lxShouldLog hm src level = return $ shoudLogBySrcLevelMap hm src level

instance LogStore LoggerSet where
    lxPushLogStr = pushLogStr
    lxGetLoggerSet = id

data LogFileAtMaxSize = LogFileAtMaxSize
                            Int64           -- max size
                            FilePath        -- log file path
                            (IORef Int64)   -- dest. file size, increase when push log
                            LoggerSet

instance LogStore LogFileAtMaxSize where
    lxPushLogStr lf@(LogFileAtMaxSize max_sz _fp size_cnt ls) log_str = do
        lxPushLogStr ls log_str
        new_sz <- atomicModifyIORef' size_cnt $
          \x -> let y = x + fromIntegral (logStrLength log_str) in force (y, y)

        when (new_sz >= max_sz) $ do
            renewLogFileAtMaxSize lf

    lxGetLoggerSet (LogFileAtMaxSize _max_sz _fp _size_cnt ls) = ls

renewLogFileAtMaxSize :: LogFileAtMaxSize -> IO ()
renewLogFileAtMaxSize (LogFileAtMaxSize max_sz fp size_cnt ls) = do
    let renew = do
                flushLogStr ls
                COff fsize <- fileSize <$> getFileStatus fp
                if ( fsize > max_sz )
                    then do
                        cutLogFileThenArchive fp
                        writeIORef size_cnt 0
                        renewLoggerSet ls
                    else
                        writeIORef size_cnt fsize

    renew `catchIOError` annotateRethrowIOError "renewLogFileAtMaxSize" Nothing (Just fp)

-- | create LogFileAtMaxSize
newLogFileAtMaxSize :: Int64 -> BufSize -> FilePath -> IO LogFileAtMaxSize
newLogFileAtMaxSize max_size buf_size fp =
  handle (annotateRethrowIOError "newLogFileAtMaxSize" Nothing (Just fp)) $ do
    logger_set <- newFileLoggerSet buf_size fp
    COff fsize <- fileSize <$> getFileStatus fp

    est_file_sz <- newIORef fsize
    let lf = LogFileAtMaxSize max_size fp est_file_sz logger_set

    when (fsize >= max_size) $ do
        renewLogFileAtMaxSize lf

    return lf

parseSomeLogStoreObj :: Maybe FilePath -> Object -> AT.Parser (IO SomeLogStore)
parseSomeLogStoreObj m_bp o = do
    typ <- o .: "type"
    buf_size <- (o .:? "buf-size"
                    >>= traverse (parseTextByParsec parseByteSizeWithUnit)
                ) .!= defaultBufSize
    case typ of
        "file" -> do
            fp <- fmap (maybe id (</>) m_bp) $ o .: "path"
            m_sz <- o .:? "cut-at-size" >>= traverse (parseTextByParsec parseByteSizeWithUnit)
            case m_sz of
                Nothing -> do
                    return $ do
                        liftM SomeLogStore $
                          newFileLoggerSet buf_size fp
                            `catchIOError` annotateRethrowIOError "newFileLoggerSet" Nothing (Just fp)

                Just sz -> do
                    return $ do
                        liftM SomeLogStore $ newLogFileAtMaxSize sz buf_size fp

        "stdout" -> return $ do
            liftM SomeLogStore $ newStdoutLoggerSet buf_size

        "stderr" -> return $ do
            liftM SomeLogStore $ newStderrLoggerSet buf_size

        _       -> fail $ "unknown handler type: " ++ typ

parseSomeShouldLogPredObj :: Object -> AT.Parser (IO SomeShouldLogPredicator)
parseSomeShouldLogPredObj obj = do
    src_level_map :: HashMap _ _ <- obj .: "src-level" >>= parse_map

    return $ return $ SomeShouldLogPredicator src_level_map

    where
        parse_map = withObject "source-to-level-map" $ \o -> do
                        liftM mapFromList $
                            forM (mapToList o) $ \(k, v) -> do
                                lv <- withText "LogLevel" (return . logLevelFromText) v
                                return (T.strip k, lv)

-- | use this in AppSettings of scaffold site
data LoggerConfig = LoggerConfig
                        (Vector (IO SomeLogStore, IO SomeShouldLogPredicator))
                        (Maybe (IO SomeLogStore, IO SomeShouldLogPredicator))
                            -- ^ default value to use when no others handles the logs

instance Default LoggerConfig where
    def = LoggerConfig mempty Nothing

instance FromJSON LoggerConfig where
    parseJSON = withObject "LoggerConfig" $ \obj -> do
        m_base_path <- obj .:? "base-path"
        LoggerConfig
            <$> (fmap fromList $ obj .: "others" >>= parseSomeObjects "LoggerConfig others" (parse_obj m_base_path))
            <*> (obj .:? "default" >>= traverse (parse_obj m_base_path))
        where
            parse_obj m_bp = \o -> do
                (,) <$> parseSomeLogStoreObj m_bp o
                    <*> parseSomeShouldLogPredObj o

-- | real value for handling all logs
data LogHandlerV = LogHandlerV
                        DateCacheGetter
                        (Vector (SomeLogStore, SomeShouldLogPredicator))
                        (Maybe (SomeLogStore, SomeShouldLogPredicator))

newLogHandlerV :: DateCacheGetter -> LoggerConfig -> IO LogHandlerV
newLogHandlerV getdate (LoggerConfig v m_def) = do
    v2 <- forM v $ uncurry (liftM2 (,))
    m_def2 <- traverse (uncurry (liftM2 (,))) m_def
    return $ LogHandlerV getdate v2 m_def2

-- | use this with runLoggingT
logFuncByHandlerV ::
    LogHandlerV
    -> LoggingFunc
logFuncByHandlerV (LogHandlerV getdate v m_def) loc src level msg = do
    log_str_ioref <- newIORef Nothing

    let get_log_str = do
            m_log_str <- readIORef log_str_ioref
            case m_log_str of
                Nothing -> do
                    log_str <- formatLogMessage getdate loc src level msg
                    writeIORef log_str_ioref (Just log_str)
                    return log_str
                Just x -> return x

    not_done <- liftM (null . filter isJust) $ forM v $
        \(SomeLogStore store, SomeShouldLogPredicator p) -> do
            should_log <- lxShouldLog p src level
            if should_log
                then get_log_str >>= lxPushLogStr store >> return (Just ())
                else return Nothing

    when not_done $ do
        void $ forM m_def $ \(SomeLogStore store, SomeShouldLogPredicator p) -> do
            should_log <- lxShouldLog p src level
            if should_log
                then get_log_str >>= lxPushLogStr store >> return (Just ())
                else return Nothing

logFuncFallbackByHandlerV ::
    LogHandlerV
    -> LoggingFunc
logFuncFallbackByHandlerV (LogHandlerV getdate _v m_def) loc src level msg = do
    void $ forM m_def $ \(SomeLogStore store, SomeShouldLogPredicator p) -> do
        should_log <- lxShouldLog p src level
        when ( should_log ) $ do
            formatLogMessage getdate loc src level msg
                >>= lxPushLogStr store

-- | in scaffold site, makeApplication function:
-- we need a LoggerSet to make log middleware.
-- Hence we need to choose a LoggerSet in the available.
chooseYesodLoggerBySrcLV :: LogHandlerV -> LogSource -> IO (Maybe Logger)
chooseYesodLoggerBySrcLV (LogHandlerV getdate v _def_logger_set) src = do
    stores <-
        forM ([LevelDebug, LevelInfo, LevelWarn, LevelError, LevelOther ""]) $ \level -> do
            liftM catMaybes $ forM (toList v) $
                \(store, SomeShouldLogPredicator p) -> do
                    should_log <- lxShouldLog p src level
                    return $ if should_log
                        then Just store
                        else Nothing

    forM (listToMaybe $ join stores) $ \(SomeLogStore store) -> do
        return $ Logger (lxGetLoggerSet store) getdate

defaultYesodLoggerHandlerV :: LogHandlerV -> Maybe Logger
defaultYesodLoggerHandlerV (LogHandlerV getdate _v m_def) =
    flip fmap m_def $ \(SomeLogStore store, _) ->
        Logger (lxGetLoggerSet store) getdate

defaultShouldLogLV :: LogHandlerV -> LogSource -> LogLevel -> IO Bool
defaultShouldLogLV (LogHandlerV _getdate _v m_def) src level =
    liftM (fromMaybe False) $
        forM m_def $ \(_, SomeShouldLogPredicator p) ->
            lxShouldLog p src level

instance LoggingTRunner LogHandlerV where
    runLoggingTWith v = flip runLoggingT (logFuncByHandlerV v)

withLogFuncInHandlerT ::
    LoggingFunc
    -> HandlerT site m a
    -> HandlerT site m a
withLogFuncInHandlerT log_func (HandlerT f) = HandlerT $ \hd -> do
    let rhe  = handlerEnv hd
    let rhe' = rhe { rheLog = log_func }
        hd'  = hd { handlerEnv = rhe' }
    f hd'

-- | usually, in 'HandlerT site m', log will go to the logger returned by
-- 'makeLogger'. With this function, log will be handled by runLoggingTWith
withSiteLogFuncInHandlerT :: (LoggingTRunner site, Monad m) =>
    HandlerT site m a
    -> HandlerT site m a
withSiteLogFuncInHandlerT h = do
    foundation <- ask
    runLoggingTWith foundation $ LoggingT $ \log_func ->
        withLogFuncInHandlerT log_func h

cutLogFileThenArchive :: FilePath -> IO ()
cutLogFileThenArchive log_path = do
    suf_n <- runResourceT $ sourceDirectory dir_name $$ find_next_n (0 :: Int)
    let suf = '.' : show (suf_n + 1 :: Int)
    renameFile log_path (log_path ++ suf)
    where
        (dir_name, log_file_name) = splitFileName log_path

        find_next_n last_n = do
            mx <- await
            case mx of
                Nothing -> return last_n
                Just fp -> do
                    case stripPrefix (log_file_name ++ ".") (takeFileName fp) of
                        Nothing -> find_next_n last_n
                        Just suf -> do
                            case parse parse_suffix "" suf of
                                Left _  -> find_next_n last_n
                                Right x -> find_next_n $ max x last_n

        parse_suffix = do
            x <- PN.nat
            _ <- eof <|> (Text.Parsec.char '.' >> return ())
            return x

-- | To catch IOError rethrow with better message
annotateRethrowIOError :: String
                       -> Maybe Handle
                       -> Maybe FilePath
                       -> IOError
                       -> IO a
annotateRethrowIOError loc m_handle m_fp ex =
  throwIO $ annotateIOError ex loc m_handle m_fp

-- | XXX: copied from source of yesod-core
formatLogMessage :: DateCacheGetter
                 -> Loc
                 -> LogSource
                 -> LogLevel
                 -> LogStr -- ^ message
                 -> IO LogStr
formatLogMessage getdate loc src level msg = do
    now <- getdate
    return $
        toLogStr now `mappend`
        " [" `mappend`
        (case level of
            LevelOther t -> toLogStr t
            _ -> toLogStr $ drop 5 $ show level) `mappend`
        (if null src
            then mempty
            else "#" `mappend` toLogStr src) `mappend`
        "] " `mappend`
        msg `mappend`
        " @(" `mappend`
        toLogStr (fileLocationToString loc) `mappend`
        ")\n"

-- taken from file-location package
-- turn the TH Loc loaction information into a human readable string
-- leaving out the loc_end parameter
fileLocationToString :: Loc -> String
fileLocationToString loc = (loc_package loc) ++ ':' : (loc_module loc) ++
  ' ' : (loc_filename loc) ++ ':' : (line loc) ++ ':' : (char loc)
  where
    line = show . fst . loc_start
    char = show . snd . loc_start


text:
require 'ebay_trading/types/tax_identifier_attribute'

module EbayTrading # :nodoc:
  module Types # :nodoc:
    # == Attributes
    #  text_node :type, 'Type', :optional => true
def type
  @type
end

    #  text_node :id, 'ID', :optional => true
    #  array_node :attributes, 'Attribute', :class => TaxIdentifierAttribute, :default_value => []
    class TaxIdentifier
      include XML::Mapping
      include Initializer
      root_element_name 'TaxIdentifier'
      text_node :type, 'Type', :optional => true
def type
  @type
end

      text_node :id, 'ID', :optional => true
      array_node :attributes, 'Attribute', :class => TaxIdentifierAttribute, :default_value => []
    end
  end
end

redpajama_set_name: RedPajamaGithub


text:
import Document, {
  Head,
  Main,
  NextDocumentContext,
  NextScript,
} from 'next/document';
import React from 'react';
import { AppRegistry } from 'react-native';

// https://github.com/zeit/next.js/tree/canary/examples/with-react-native-web

// https://github.com/necolas/react-native-web/blob/master/docs/guides/web-recipes.md
// Disable input and textarea outline because blinking caret is good enough.
// Improve font smoothing.
const globalStyles = `
  html,body{height:100%}
  body{overflow:hidden}
  #__next{display:flex;flex-direction:column;height:100%}
  input,textarea{outline:none}
  body{-webkit-font-smoothing:antialiased;-moz-osx-font-smoothing:grayscale}
`;

// eslint-disable-next-line import/no-default-export
export default class MyDocument extends Document {
  static async getInitialProps({ renderPage }: NextDocumentContext) {
    AppRegistry.registerComponent('Main', () => Main);
    // @ts-ignore getApplication is React Native Web addition for SSR.
    const { getStyleElement } = AppRegistry.getApplication('Main');
    const page = renderPage();
    const styles = [
      // eslint-disable-next-line react/no-danger
      <style dangerouslySetInnerHTML={{ __html: globalStyles }} key="styles" />,
      getStyleElement(),
    ];
    return { ...page, styles: React.Children.toArray(styles) };
  }

  render() {
    return (
      <html lang="en">
        <Head>
          <meta charSet="utf-8" />
          <meta name="viewport" content="width=device-width, initial-scale=1" />
          {/* https://favicon.io/favicon-generator/ */}
          {/* Lemonada, #228be6, transparent */}
          <link
            rel="apple-touch-icon"
            sizes="180x180"
            href="/static/apple-touch-icon.png"
          />
          <link
            rel="icon"
            type="image/png"
            sizes="32x32"
            href="/static/favicon-32x32.png"
          />
          <link
            rel="icon"
            type="image/png"
            sizes="16x16"
            href="/static/favicon-16x16.png"
          />
        </Head>
        <body>
          <Main />
          <NextScript />
        </body>
      </html>
    );
  }
}


text:
module Types
  module Snippets
    class TypeEnum < BaseEnum
      value 'personal', value: 'personal'
      value 'project', value: 'project'
    end
  end
end


text:
'use strict'
var npm = require('../npm.js')
var util = require('util')
var nameValidator = require('validate-npm-package-name')

module.exports = errorMessage

function errorMessage (er) {
  var short = []
  var detail = []
  switch (er.code) {
    case 'ECONNREFUSED':
      short.push(['', er])
      detail.push([
        '',
        [
          '\nIf you are behind a proxy, please make sure that the',
          "'proxy' config is set properly.  See: 'npm help config'"
        ].join('\n')
      ])
      break

    case 'EACCES':
    case 'EPERM':
      short.push(['', er])
      detail.push(['', ['\nPlease try running this command again as root/Administrator.'
                ].join('\n')])
      break

    case 'ELIFECYCLE':
      short.push(['', er.message])
      detail.push([
        '',
        [
          '',
          'Failed at the ' + er.pkgid + ' ' + er.stage + ' script.',
          'This is probably not a problem with npm. There is likely additional logging output above.'
        ].join('\n')]
      )
      break

    case 'ENOGIT':
      short.push(['', er.message])
      detail.push([
        '',
        [
          '',
          'Failed using git.',
          'Please check if you have git installed and in your PATH.'
        ].join('\n')
      ])
      break

    case 'EJSONPARSE':
      const path = require('path')
      // Check whether we ran into a conflict in our own package.json
      if (er.file === path.join(npm.prefix, 'package.json')) {
        const isDiff = require('../install/read-shrinkwrap.js')._isDiff
        const txt = require('fs').readFileSync(er.file, 'utf8')
        if (isDiff(txt)) {
          detail.push([
            '',
            [
              'Merge conflict detected in your package.json.',
              '',
              'Please resolve the package.json conflict and retry the command:',
              '',
              `$ ${process.argv.join(' ')}`
            ].join('\n')
          ])
          break
        }
      }
      short.push(['', er.message])
      short.push(['', 'File: ' + er.file])
      detail.push([
        '',
        [
          'Failed to parse package.json data.',
          'package.json must be actual JSON, not just JavaScript.',
          '',
          'Tell the package author to fix their package.json file.'
        ].join('\n'),
        'JSON.parse'
      ])
      break

    case 'EOTP':
    case 'E401':
      // the E401 message checking is a hack till we replace npm-registry-client with something
      // OTP aware.
      if (er.code === 'EOTP' || (er.code === 'E401' && /one-time pass/.test(er.message))) {
        short.push(['', 'This operation requires a one-time password from your authenticator.'])
        detail.push([
          '',
          [
            'You can provide a one-time password by passing --otp=<code> to the command you ran.',
            'If you already provided a one-time password then it is likely that you either typoed',
            'it, or it timed out. Please try again.'
          ].join('\n')
        ])
        break
      } else {
        // npm ERR! code E401
        // npm ERR! Unable to authenticate, need: Basic
        if (er.headers && er.headers['www-authenticate']) {
          const auth = er.headers['www-authenticate'].map((au) => au.split(/,\s*/))[0] || []
          if (auth.indexOf('Bearer') !== -1) {
            short.push(['', 'Unable to authenticate, your authentication token seems to be invalid.'])
            detail.push([
              '',
              [
                'To correct this please trying logging in again with:',
                '    npm login'
              ].join('\n')
            ])
            break
          } else if (auth.indexOf('Basic') !== -1) {
            short.push(['', 'Incorrect or missing password.'])
            detail.push([
              '',
              [
                'If you were trying to login, change your password, create an',
                'authentication token or enable two-factor authentication then',
                'that means you likely typed your password in incorrectly.',
                'Please try again, or recover your password at:',
                '    https://www.npmjs.com/forgot',
                '',
                'If you were doing some other operation then your saved credentials are',
                'probably out of date. To correct this please try logging in again with:',
                '    npm login'
              ].join('\n')
            ])
            break
          }
        }
      }

    case 'E404':
      // There's no need to have 404 in the message as well.
      var msg = er.message.replace(/^404\s+/, '')
      short.push(['404', msg])
      if (er.pkgid && er.pkgid !== '-') {
        detail.push(['404', ''])
        detail.push(['404', '', "'" + er.pkgid + "' is not in the npm registry."])

        var valResult = nameValidator(er.pkgid)

        if (valResult.validForNewPackages) {
          detail.push(['404', 'You should bug the author to publish it (or use the name yourself!)'])
        } else {
          detail.push(['404', 'Your package name is not valid, because', ''])

          var errorsArray = (valResult.errors || []).concat(valResult.warnings || [])
          errorsArray.forEach(function (item, idx) {
            detail.push(['404', ' ' + (idx + 1) + '. ' + item])
          })
        }

        if (er.parent) {
          detail.push(['404', "It was specified as a dependency of '" + er.parent + "'"])
        }
        detail.push(['404', '\nNote that you can also install from a'])
        detail.push(['404', 'tarball, folder, http url, or git url.'])
      }
      break

    case 'EPUBLISHCONFLICT':
      short.push(['publish fail', 'Cannot publish over existing version.'])
      detail.push(['publish fail', "Update the 'version' field in package.json and try again."])
      detail.push(['publish fail', ''])
      detail.push(['publish fail', 'To automatically increment version numbers, see:'])
      detail.push(['publish fail', '    npm help version'])
      break

    case 'EISGIT':
      short.push(['git', er.message])
      short.push(['git', '    ' + er.path])
      detail.push([
        'git',
        [
          'Refusing to remove it. Update manually,',
          'or move it out of the way first.'
        ].join('\n')
      ])
      break

    case 'ECYCLE':
      short.push([
        'cycle',
        [
          er.message,
          'While installing: ' + er.pkgid
        ].join('\n')
      ])
      detail.push([
        'cycle',
        [
          'Found a pathological dependency case that npm cannot solve.',
          'Please report this to the package author.'
        ].join('\n')
      ])
      break

    case 'EBADPLATFORM':
      var validOs = er.os.join ? er.os.join(',') : er.os
      var validArch = er.cpu.join ? er.cpu.join(',') : er.cpu
      var expected = {os: validOs, arch: validArch}
      var actual = {os: process.platform, arch: process.arch}
      short.push([
        'notsup',
        [
          util.format('Unsupported platform for %s: wanted %j (current: %j)', er.pkgid, expected, actual)
        ].join('\n')
      ])
      detail.push([
        'notsup',
        [
          'Valid OS:    ' + validOs,
          'Valid Arch:  ' + validArch,
          'Actual OS:   ' + process.platform,
          'Actual Arch: ' + process.arch
        ].join('\n')
      ])
      break

    case 'EEXIST':
      short.push(['', er.message])
      short.push(['', 'File exists: ' + er.path])
      detail.push(['', 'Move it away, and try again.'])
      break

    case 'ENEEDAUTH':
      short.push(['need auth', er.message])
      detail.push(['need auth', 'You need to authorize this machine using `npm adduser`'])
      break

    case 'ECONNRESET':
    case 'ENOTFOUND':
    case 'ETIMEDOUT':
    case 'EAI_FAIL':
      short.push(['network', er.message])
      detail.push([
        'network',
        [
          'This is a problem related to network connectivity.',
          'In most cases you are behind a proxy or have bad network settings.',
          '\nIf you are behind a proxy, please make sure that the',
          "'proxy' config is set properly.  See: 'npm help config'"
        ].join('\n')
      ])
      break

    case 'ENOPACKAGEJSON':
      short.push(['package.json', er.message])
      detail.push([
        'package.json',
        [
          "npm can't find a package.json file in your current directory."
        ].join('\n')
      ])
      break

    case 'ETARGET':
      short.push(['notarget', er.message])
      msg = [
        'In most cases you or one of your dependencies are requesting',
        "a package version that doesn't exist."
      ]
      if (er.parent) {
        msg.push("\nIt was specified as a dependency of '" + er.parent + "'\n")
      }
      detail.push(['notarget', msg.join('\n')])
      break

    case 'ENOTSUP':
      if (er.required) {
        short.push(['notsup', er.message])
        short.push(['notsup', 'Not compatible with your version of node/npm: ' + er.pkgid])
        detail.push([
          'notsup',
          [
            'Not compatible with your version of node/npm: ' + er.pkgid,
            'Required: ' + JSON.stringify(er.required),
            'Actual:   ' + JSON.stringify({
              npm: npm.version,
              node: npm.config.get('node-version')
            })
          ].join('\n')
        ])
        break
      } // else passthrough
      /*eslint no-fallthrough:0*/

    case 'ENOSPC':
      short.push(['nospc', er.message])
      detail.push([
        'nospc',
        [
          'There appears to be insufficient space on your system to finish.',
          'Clear up some disk space and try again.'
        ].join('\n')
      ])
      break

    case 'EROFS':
      short.push(['rofs', er.message])
      detail.push([
        'rofs',
        [
          'Often virtualized file systems, or other file systems',
          "that don't support symlinks, give this error."
        ].join('\n')
      ])
      break

    case 'ENOENT':
      short.push(['enoent', er.message])
      detail.push([
        'enoent',
        [
          'This is related to npm not being able to find a file.',
          er.file ? "\nCheck if the file '" + er.file + "' is present." : ''
        ].join('\n')
      ])
      break

    case 'EMISSINGARG':
    case 'EUNKNOWNTYPE':
    case 'EINVALIDTYPE':
    case 'ETOOMANYARGS':
      short.push(['typeerror', er.stack])
      detail.push([
        'typeerror',
        [
          'This is an error with npm itself. Please report this error at:',
          '    <https://github.com/npm/npm/issues>'
        ].join('\n')
      ])
      break

    default:
      short.push(['', er.message || er])
      break
  }
  if (er.optional) {
    short.unshift(['optional', er.optional + ' (' + er.location + '):'])
    short.concat(detail).forEach(function (msg) {
      if (!msg[0]) msg[0] = 'optional'
      if (msg[1]) msg[1] = msg[1].toString().replace(/(^|\n)/g, '$1SKIPPING OPTIONAL DEPENDENCY: ')
    })
  }
  return {summary: short, detail: detail}
}


text:
import enum

class FlagEnum(enum.Enum):
    """A derivated enum that enable interraction with flags.
    Enum value should be multiple of the power of 2."""

    @classmethod
    def flag(cls):
        """Return the associated flag class."""
        return None

#---------------------------------------

    def to_int(self):
        return self.value

    def __int__(self):
        return self.to_int()

#---------------------------------------

    def __or__(self, value):
        flag_class = self.flag()
        if flag_class:
            return flag_class(self) | value
        else:
            return super().__or__(value)

    def __neg__(self):
        flag_class = self.flag()
        if flag_class:
            return flag_class(*[st for st in iter(self.__class__)
                                if st is not self])
        else:
            return super().__neg__()

#---------------------------------------

    @classmethod
    def all(cls):
        flag_class = cls.flag()
        if flag_class:
            return flag_class(*tuple(iter(cls.__members__.values())))


text:
package swurg.ui;

import burp.HttpRequestResponse;
import burp.IBurpExtenderCallbacks;
import java.util.Collections;
import java.util.List;
import java.util.stream.IntStream;
import javax.swing.JMenuItem;
import javax.swing.JPopupMenu;
import javax.swing.JSeparator;
import javax.swing.table.DefaultTableModel;

@SuppressWarnings("serial")
class ContextMenu extends JPopupMenu {

  private List<HttpRequestResponse> httpRequestResponses;

  ContextMenu(
      IBurpExtenderCallbacks callbacks, Tab tab
  ) {
    JMenuItem addToSiteMap = new JMenuItem("Add to site map");
    addToSiteMap
        .addActionListener(e -> IntStream.of(tab.getTable().getSelectedRows()).forEach(row -> {
          int index = (int) tab.getTable()
              .getValueAt(row, tab.getTable().getColumn("#").getModelIndex());
          HttpRequestResponse httpRequestResponse = this.httpRequestResponses.get(index);
          callbacks.addToSiteMap(httpRequestResponse);
        }));

    JMenuItem activeScan = new JMenuItem("Do an active scan");
    activeScan
        .addActionListener(e -> IntStream.of(tab.getTable().getSelectedRows()).forEach(row -> {
          int index = (int) tab.getTable()
              .getValueAt(row, tab.getTable().getColumn("#").getModelIndex());
          HttpRequestResponse httpRequestResponse = this.httpRequestResponses.get(index);
          callbacks.doActiveScan(httpRequestResponse.getHttpService().getHost(),
              httpRequestResponse.getHttpService().getPort(), httpRequestResponse.isUseHttps(),
              httpRequestResponse.getRequest()
          );
        }));

    JMenuItem sendToIntruder = new JMenuItem("Send to Intruder");
    sendToIntruder
        .addActionListener(e -> IntStream.of(tab.getTable().getSelectedRows()).forEach(row -> {
          int index = (int) tab.getTable()
              .getValueAt(row, tab.getTable().getColumn("#").getModelIndex());
          HttpRequestResponse httpRequestResponse = this.httpRequestResponses.get(index);
          callbacks.sendToIntruder(httpRequestResponse.getHttpService().getHost(),
              httpRequestResponse.getHttpService().getPort(),
              httpRequestResponse.isUseHttps(), httpRequestResponse.getRequest()
          );
        }));

    JMenuItem sendToRepeater = new JMenuItem("Send to Repeater");
    sendToRepeater
        .addActionListener(e -> IntStream.of(tab.getTable().getSelectedRows()).forEach(row -> {
          int index = (int) tab.getTable()
              .getValueAt(row, tab.getTable().getColumn("#").getModelIndex());
          HttpRequestResponse httpRequestResponse = this.httpRequestResponses.get(index);
          callbacks.sendToRepeater(httpRequestResponse.getHttpService().getHost(),
              httpRequestResponse.getHttpService().getPort(),
              httpRequestResponse.isUseHttps(), httpRequestResponse.getRequest(),
              String.format("%s %s%s", tab.getTable()
                      .getValueAt(row, tab.getTable().getColumn("Method").getModelIndex()),
                  tab.getTable()
                      .getValueAt(row, tab.getTable().getColumn("Base Path").getModelIndex()),
                  tab.getTable()
                      .getValueAt(row, tab.getTable().getColumn("Endpoint").getModelIndex()))
          );
        }));

    JMenuItem sendToComparer = new JMenuItem("Send to Comparer");
    sendToComparer
        .addActionListener(e -> IntStream.of(tab.getTable().getSelectedRows()).forEach(row -> {
          int index = (int) tab.getTable()
              .getValueAt(row, tab.getTable().getColumn("#").getModelIndex());
          HttpRequestResponse httpRequestResponse = this.httpRequestResponses.get(index);
          callbacks.sendToComparer(httpRequestResponse.getRequest());
        }));

    JMenuItem clear = new JMenuItem("Clear item(s)");
    clear.addActionListener(e -> {
      // iterating the indices in decreasing order to not mess up the table shifting
      IntStream.of(tab.getTable().getSelectedRows()).boxed()
          .map(row -> tab.getTable().convertRowIndexToModel(row)).sorted(Collections.reverseOrder())
          .forEach(
              row -> {
                int index = (int) tab.getTable()
                    .getValueAt(row, tab.getTable().getColumn("#").getModelIndex());
                this.httpRequestResponses.remove(index);
                ((DefaultTableModel) tab.getTable().getModel()).removeRow(row);
              }
          );

      // updating the rows' index (reindexing table)
      IntStream.rangeClosed(0, tab.getTable().getRowCount())
          .forEach(row -> tab.getTable().getModel()
              .setValueAt(row, row, tab.getTable().getColumn("#").getModelIndex()));
    });

    JMenuItem clearAll = new JMenuItem("Clear all");
    clearAll.addActionListener(e -> {
      this.httpRequestResponses.clear();
      ((DefaultTableModel) tab.getTable().getModel()).setRowCount(0);
    });

    add(addToSiteMap);
    add(new JSeparator());
    add(activeScan);
    add(sendToIntruder);
    add(sendToRepeater);
    add(sendToComparer);
    add(new JSeparator());
    add(clear);
    add(clearAll);
  }

  void setHttpRequestResponses(List<HttpRequestResponse> httpRequestResponses) {
    this.httpRequestResponses = httpRequestResponses;
  }
}


text:
<?php

namespace Frame\Controller;

/**
 * Class JSON
 * This will output pure json
 * @package Frame\Controller
 */
class JSON extends Base {

    public function _render($out, $args) {
        parent::_render($out, $args);

        $this->response->noCache();

        // Check if method is an object that has a toArray method
        if(method_exists($out, 'toArray')) {
            $out = $out->toArray();
        }

        // Make sure we're not jsoning json.
        if(!$this->isJson($out)) {
            $out = json_encode($out);
        }

        if(isset($args['prefix'])) {
            $prefix = $args['prefix'];

            $this->response->header('Content-Type', 'text/javascript; charset=' . $this->charset);
            $this->response->body("$prefix($out);");
        } else {
            $this->response->header('Content-Type', 'application/json; charset=' . $this->charset);
            $this->response->body($out);
        }

        $this->response->send();
    }

    /**
     * Check if string is JSON
     *
     * @param $string
     *
     * @return bool
     */
    private function isJson($string) {
        if(!is_string($string)) return false;

        json_decode($string);
        return (json_last_error() == JSON_ERROR_NONE);
    }

}


text:
$(document).ready(function(){

	$window = $(window);

	// Testing border radius support
	if (!Modernizr.borderradius) {
		$('#section-contact #links-contact a').attr( "border", "0px" ).removeAttr("border-radius");
	}

	// prettyPhoto
	$("a[class^='prettyPhoto']").prettyPhoto();

	// plugin carousel
	$('.carousel').carousel();

	// jQuery onePageNav
	$('.navbar-nav').onePageNav({
		currentClass: 'active',
		changeHash: false,
		scrollSpeed: 750,
		scrollOffset: 94,
		scrollThreshold: 0.1,
		easing: 'swing',
	});

	// jquery plugin cycle
	$('.list-testimonial').cycle({
		slides: 'li',
		pager: ".testimonial-bullets",
		timeout: 0,
		autoHeight: 0,
		centerHorz: true
	});

	// size testimonial
	$('.list-testimonial').on( 'cycle-update-view', function(e,o,sh,cs) {
		var $this = $(this);

        $this.animate({
          height: $(cs).height()
        }, 500);

        $(window).resize(function() {
          $this.stop().animate({
            height: $(cs).height()
          }, 500);
        });
    });

	// show/hide scroll up button
    $window.scroll(function(){
        if ($(this).scrollTop() > 100) {
            // $('#scrollup').fadeIn();
        } else {
            $('#scrollup').fadeOut();
    	}
    });
    // scroll up action
	$('#scrollup').on('click',function(e){
		e.preventDefault();
		$('html, body').animate({ scrollTop: 0 }, 'slow');
	});

});


text:
// Copyright (c) Microsoft Open Technologies, Inc.  All rights reserved.  Licensed under the Apache License, Version 2.0.  See License.txt in the project root for license information.
using System;
using System.Text;
using System.Collections.Generic;
using System.Linq;
using Xunit;
using DocumentFormat.OpenXml.Wordprocessing;
using DocumentFormat.OpenXml;
using DocumentFormat.OpenXml.Packaging;
using System.IO;
using System.Reflection;

namespace DocumentFormat.OpenXml.Tests
{
    ///
    /// Summary description for CustomXmlElementTest
    ///

    public class CustomXmlElementTest
    {
        ///
        ///Constructor
        ///
        public CustomXmlElementTest()
        {
            //
            // TODO: Add constructor logic here
            //
        }

        private TestContext testContextInstance;

        ///
        ///Gets or sets the test context which provides
        ///information about and functionality for the current test run.
        ///
        public TestContext TestContext
        {
            get
            {
                return testContextInstance;
            }
            set
            {
                testContextInstance = value;
            }
        }

        string uri = "urn:customXmlSample";
        string element = "elementName";

        ///
        ///CustomXmlElementTests.
        ///
        [Fact]
        public void CustomXmlElementTests()
        {

            Type baseType = typeof(CustomXmlElement);
            Assert.True(baseType.GetTypeInfo().IsAbstract);

            // CustomXmlRuby
            CustomXmlRuby cxRuby = new CustomXmlRuby();
            ValidateCustomXmlElement(cxRuby);

            // CustomXmlBlock
            CustomXmlBlock cxBlock = new CustomXmlBlock();
            ValidateCustomXmlElement(cxBlock);

            // CustomXmlRow
            CustomXmlRow cxRow = new CustomXmlRow();
            ValidateCustomXmlElement(cxRow);

            // CustomXmlRun
            CustomXmlRun cxRun = new CustomXmlRun();
            ValidateCustomXmlElement(cxRun);

            // CustomXmlCell
            CustomXmlCell cxCell = new CustomXmlCell();
            ValidateCustomXmlElement(cxCell);

            // Test loading and modification on DOM tree
            using (var doc = WordprocessingDocument.Open(new MemoryStream(TestFileStreams.simpleSdt), false))
            {
                // find customXml
                var customXml = doc.MainDocumentPart.Document.Descendants<CustomXmlRun>().First();
                Assert.Equal("firstName", customXml.Element.Value);
                Assert.Null(customXml.Uri);
                Assert.Equal(typeof(Run), customXml.FirstChild.GetType());
                customXml.Uri = "urn:sampleUri";
                customXml.Append(new Hyperlink());
                Assert.Equal(2, customXml.ChildElements.Count);
            }
        }

        private void ValidateCustomXmlElement(CustomXmlElement e)
        {
            e.Uri = uri;
            e.Element = element;
            Assert.NotNull(e.Uri);
            Assert.Equal(typeof(StringValue), e.Uri.GetType());
            Assert.Equal(uri, e.Uri.Value);
            Assert.NotNull(e.Element);
            Assert.Equal(typeof(StringValue), e.Element.GetType());
            Assert.Equal(element, e.Element.Value);
        }

        ///
        ///SdtBaseClassTest
        ///
        [Fact]
        public void SdtBaseClassTest()
        {
            Type baseType = typeof(SdtElement);
            Assert.True(baseType.GetTypeInfo().IsAbstract);

            // Test loading and modification
            SdtRun sdtRun = new SdtRun();

            using (var doc = WordprocessingDocument.Open(new MemoryStream(TestFileStreams.simpleSdt), false))
            {
                // find sdt
                var sdt = doc.MainDocumentPart.Document.Descendants<SdtBlock>().First();
                // get
                Assert.Equal(2, sdt.ChildElements.Count);
                Assert.Equal(typeof(SdtProperties), sdt.ChildElements[0].GetType());
                Assert.Equal(typeof(SdtContentBlock), sdt.ChildElements[1].GetType());
                Assert.Equal(typeof(SdtAlias), sdt.ChildElements[0].ChildElements[0].GetType());
                Assert.Equal("SDT1", (sdt.ChildElements[0].ChildElements[0] as SdtAlias).Val.Value);
                // set
                SdtContentBlock contentRun = sdt.ChildElements[1] as SdtContentBlock;
                contentRun.Append(new Paragraph());

                Assert.Equal(typeof(Paragraph), contentRun.ChildElements.Last().GetType());
            }
        }
    }
}


text:
// Type definitions for tableau 2.2
// Project: https://onlinehelp.tableau.com/current/api/js_api/en-us/JavaScriptAPI/js_api.htm
// Definitions by: Greg Zapp <https://github.com/protip>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 2.4

declare namespace tableau {
    enum DashboardObjectType {
        BLANK = 'blank',
        WORKSHEET = 'worksheet',
        QUICK_FILTER = 'quickFilter',
        PARAMETER_CONTROL = 'parameterControl',
        PAGE_FILTER = 'pageFilter',
        LEGEND = 'legend',
        TITLE = 'title',
        TEXT = 'text',
        IMAGE = 'image',
        WEB_PAGE = 'webPage',
        ADDIN = 'addIn'
    }

    enum FieldAggregationType {
        SUM,
        AVG,
        MIN,
        MAX,
        STDEV,
        STDEVP,
        VAR,
        VARP,
        COUNT,
        COUNTD,
        MEDIAN,
        ATTR,
        NONE,
        YEAR,
        QTR,
        MONTH,
        DAY,
        HOUR,
        MINUTE,
        SECOND,
        WEEK,
        WEEKDAY,
        MONTHYEAR,
        MDY,
        END,
        TRUNC_YEAR,
        TRUNC_QTR,
        TRUNC_MONTH,
        TRUNC_WEEK,
        TRUNC_DAY,
        TRUNC_HOUR,
        TRUNC_MINUTE,
        TRUNC_SECOND,
        QUART1,
        QUART3,
        SKEWNESS,
        KURTOSIS,
        INOUT,
        USER
    }

    enum FieldRoleType {
        DIMENSION, MEASURE, UKNOWN
    }

    enum SheetType {
        WORKSHEET = 'worksheet',
        DASHBOARD = 'dashboard',
        STORY = 'story',
    }

    enum ParameterAllowableValuesType {
        ALL = 'all',
        LIST = 'list',
        RANGE = 'range',
    }

    enum ParameterDataType {
        FLOAT = 'float',
        INTEGER = 'integer',
        STRING = 'string',
        BOOLEAN = 'boolean',
        DATE = 'date',
        DATETIME = 'datetime'
    }

    //#region Error Classes
    class TableauException extends Error {
        tableauSoftwareErrorCode: ErrorCode;
    }

    enum ErrorCode {
        /** The browser is not capable of supporting the Tableau JavaScript API. */
        BROWSER_NOT_CAPABLE = 'browserNotCapable',
        /** The permissions on a workbook or a view do not allow downloading the workbook. */
        DOWNLOAD_WORKBOOK_NOT_ALLOWED = 'downloadWorkbookNotAllowed',
        /** An error occurred while attempting to perform a filter operation. */
        FILTER_CANNOT_BE_PERFORMED = 'filterCannotBePerformed',
        /** Attempted to switch to a sheet by index that does not exist in the workbook. */
        INDEX_OUT_OF_RANGE = 'indexOutOfRange',
        /** An error occurred within the Tableau JavaScript API. Contact Tableau Support. */
        INTERNAL_ERROR = 'internalError',
        /** An invalid aggregation was specified for the filter, such as setting a range filter to "SUM(Sales)" instead of "Sales". */
        INVALID_AGGREGATION_FIELD_NAME = 'invalidAggregationFieldName',
        /** An operation was attempted on a custom view that does not exist. */
        INVALID_CUSTOM_VIEW_NAME = 'invalidCustomViewName',
        /** An invalid date was specified in a method that required a date parameter. */
        INVALID_DATE_PARAMETER = 'invalidDateParameter',
        /** A filter operation was attempted on a field that does not exist in the data source. */
        INVALID_FILTER_FIELDNAME = 'invalidFilterFieldName',
        /**
         * Either a filter operation was attempted on a field that does not exist in the data source,
         * or the value supplied in the filter operation is the wrong data type or format.
         */
        INVALID_FILTER_FIELDNAME_OR_VALUE = 'invalidFilterFieldNameOrValue',
        /** A filter operation was attempted using a value that is the wrong data type or format. */
        INVALID_FILTER_FIELDVALUE = 'invalidFilterFieldValue',
        /** A parameter is not the correct data type or format. The name of the parameter is specified in the Error.message field. */
        INVALID_PARAMETER = 'invalidParameter',
        /** An invalid date value was specified in a Sheet.selectMarksAsync() call for a date field. */
        INVALID_SELECTION_DATE = 'invalidSelectionDate',
        /** A field was specified in a Sheet.selectMarksAsync() call that does not exist in the data source. */
        INVALID_SELECTION_FIELDNAME = 'invalidSelectionFieldName',
        /** An invalid value was specified in a Sheet.selectMarksAsync() call. */
        INVALID_SELECTION_VALUE = 'invalidSelectionValue',
        /** A negative size was specified or the maxSize value is less than minSize in Sheet.changeSizeAsync(). */
        INVALID_SIZE = 'invalidSize',
        /**
         * A behavior other than SheetSizeBehavior.AUTOMATIC was specified in
         * Sheet.changeSizeAsync() when the sheet is a Worksheet instance.
         */
        INVALID_SIZE_BEHAVIOR_ON_WORKSHEET = 'invalidSizeBehaviorOnWorksheet',
        /** The URL specified in the Viz class constructor is not valid. */
        INVALID_URL = 'invalidUrl',
        /** The maxSize field is missing in Sheet.changeSizeAsync() when specifying SheetSizeBehavior.ATMOST. */
        MISSING_MAX_SIZE = 'missingMaxSize',
        /** The minSize field is missing in Sheet.changeSizeAsync() when specifying SheetSizeBehavior.ATLEAST. */
        MISSING_MIN_SIZE = 'missingMinSize',
        /**
         * Either or both of the minSize or maxSize fields is missing in
         * Sheet.changeSizeAsync() when specifying SheetSizeBehavior.RANGE.
         */
        MISSING_MINMAX_SIZE = 'missingMinMaxSize',
        /** The rangeN field is missing for a relative date filter of type LASTN or NEXTN. */
        MISSING_RANGEN_FOR_RELATIVE_DATE_FILTERS = 'missingRangeNForRelativeDateFilters',
        /** An attempt was made to access Sheet.getUrl() on a hidden sheet. Hidden sheets do not have URLs. */
        NO_URL_FOR_HIDDEN_WORKSHEET = 'noUrlForHiddenWorksheet',
        /** One or both of the parentElement or the URL parameters is not specified in the Viz constructor. */
        NO_URL_OR_PARENT_ELEMENT_NOT_FOUND = 'noUrlOrParentElementNotFound',
        /** An operation was attempted on a sheet that is not active or embedded within the active dashboard. */
        NOT_ACTIVE_SHEET = 'notActiveSheet',
        /** A required parameter was not specified, null, or an empty string/array. */
        NULL_OR_EMPTY_PARAMETER = 'nullOrEmptyParameter',
        /** A general-purpose server error occurred. Details are contained in the Error object. */
        SERVER_ERROR = 'serverError',
        /** An operation was attempted on a sheet that does not exist in the workbook. */
        SHEET_NOT_IN_WORKBOOK = 'sheetNotInWorkbook',
        /** An operation is performed on a CustomView object that is no longer valid (it has been removed). */
        STALE_DATA_REFERENCE = 'staleDataReference',
        /** An unknown event name was specified in the call to Viz.addEventListener or Viz.removeEventListener. */
        UNSUPPORTED_EVENT_NAME = 'unsupportedEventName',
        /** A Viz object has already been created as a child of the parentElement specified in the Viz constructor. */
        VIZ_ALREADY_IN_MANAGER = 'vizAlreadyInManager',
        INVALID_TOOLBAR_BUTTON_NAME = 'invalidToolbarButtonName',
        MAX_VIZ_RESIZE_ATTEMPTS = 'maxVizResizeAttempts',
    }
    //#endregion

    //#region Viz Classes
    class VizManager {
        getVizs(): Viz[];
    }

    type ListenerFunction<T extends TableauEvent> = (event: T) => void;

    class Viz {
        /**
         * Creates a new Tableau Viz inside of the given HTML container, which is typically a <div> element.
         * Each option as well as the options parameter is optional.
         * If there is already a Viz associated with the parentElement, an exception is thrown.
         * Before reusing the parentElement you must first call dispose().
         */
        constructor(node: HTMLElement, url: string, options?: VizCreateOptions);

        /** Indicates whether the tabs are displayed in the UI. It does not actually hide individual tabs. */
        getAreTabsHidden(): boolean;
        /** Indicates whether the toolbar is displayed. */
        getToolbarHidden(): boolean;
        /** Indicates whether the visualization is displayed on the hosting page. */
        getIsHidden(): boolean;
        /** Returns the node that was specified in the constructor. */
        getParentElement(): HTMLElement;
        /** The URL of the visualization, as specified in the constructor */
        getUrl(): string;
        /** One Workbook is supported per visualization. */
        getWorkbook(): Workbook;
        /** Indicates whether automatic updates are currently paused. */
        getAreAutomaticUpdatesPaused(): boolean;

        addEventListener(event: TableauEventName.FILTER_CHANGE, f: ListenerFunction<FilterEvent>): void;
        addEventListener(
            event: TableauEventName.CUSTOM_VIEW_LOAD | TableauEventName.CUSTOM_VIEW_REMOVE | TableauEventName.CUSTOM_VIEW_SAVE | TableauEventName.CUSTOM_VIEW_SET_DEFAULT,
            f: ListenerFunction<CustomViewEvent>): void;
        addEventListener(event: TableauEventName.MARKS_SELECTION, f: ListenerFunction<MarksEvent>): void;
        addEventListener(event: TableauEventName.PARAMETER_VALUE_CHANGE, f: ListenerFunction<ParameterEvent>): void;
        addEventListener(event: TableauEventName.STORY_POINT_SWITCH, f: ListenerFunction<StoryPointSwitchEvent>): void;
        addEventListener(event: TableauEventName.TAB_SWITCH, f: ListenerFunction<TabSwitchEvent>): void;
        addEventListener(event: TableauEventName.TOOLBAR_STATE_CHANGE, f: ListenerFunction<ToolbarStateEvent>): void;
        addEventListener(event: TableauEventName.VIZ_RESIZE, f: ListenerFunction<VizResizeEvent>): void;

        /** Removes an event listener from the specified event. */
        removeEventListener(type: TableauEventName, f: ListenerFunction<TableauEvent>): void;
        /** Shows or hides the iframe element hosting the visualization. */
        show(): void;
        /** Shows or hides the iframe element hosting the visualization. */
        hide(): void;
        /**
         * Cleans up any resources associated with the visualization,
         * removes the visualization from the VizManager instance,
         * and removes any DOM elements from the parentElement object.
         * In effect, this method restores the page to what it was before a Viz object was instantiated.
         */
        dispose(): void;
        /** Pauses or resumes layout updates. This is useful if you are resizing the visualization or performing multiple calls that could affect the layout. */
        pauseAutomaticUpdatesAsync(): void;
        resumeAutomaticUpdatesAsync(): void;
        toggleAutomaticUpdatesAsync(): void;
        /** Equivalent to clicking on the Revert All toolbar button, which restores the workbook to its starting state. */
        revertAllAsync(): Promise<void>;
        /** Equivalent to clicking on the Refresh Data toolbar button. */
        refreshDataAsync(): Promise<void>;
        /** Equivalent to clicking on the Download toolbar button, which downloads a copy of the original workbook. */
        showDownloadWorkbookDialog(): void;
        /** Equivalent to clicking on the Export Image toolbar button, which creates a PNG file of the current visualization. */
        showExportImageDialog(): void;
        /** Equivalent to clicking on the Export PDF toolbar button, which shows a dialog allowing the user to select options for the export. */
        showExportPDFDialog(): void;
        /**
         * Shows the Export Data dialog, which is currently a popup window. The worksheetInDashboard parameter is optional.
         * If not specified, the currently active Worksheet is used.
         */
        showExportDataDialog(worksheetInDashboard: Sheet | SheetInfo | string): void;
        /** Shows the Export CrossTab dialog. The worksheetInDashboard parameter is optional. If not specified, the currently active Worksheet is used. */
        showExportCrossTabDialog(worksheetInDashboard: Sheet | SheetInfo | string): void;
        /**
         * Equivalent to clicking on the Share toolbar button,
         * which displays a dialog allowing the user to share the visualization by email or by embedding its HTML in a web page.
         */
        showShareDialog(): void;
        /**
         * Sets the size of the iframe element, which causes the visualization to expand or
         * collapse to fit the iframe element if the visualization size (current sheet's size) is set to AUTOMATIC.
         */
        setFrameSize(width: number, height: number): void;
        /** Gets the URL of the visualization asynchronously. */
        getCurrentUrlAsync(): Promise<string>;
        /** Redoes last action on a sheet, defaults to a single redo unless optional parameters is specified. */
        redoAsync(): Promise<void>;
        /** Undoes action on sheet, defaults to a single undo unless optional parameters is specified. */
        undoAsync(): Promise<void>;
    }

    interface VizCreateOptions {
        /** Undoes action on sheet, defaults to a single undo unless optional parameters is specified. */
        hideTabs?: boolean;
        /** Indicates whether the toolbar is hidden or shown. */
        hideToolbar?: boolean;
        /**
         * Specifies the ID of an existing instance to make a copy (clone) of.
         * This is useful if the user wants to continue analysis of an existing visualization without losing the state of the original.
         * If the ID does not refer to an existing visualization, the cloned version is derived from the original visualization.
         */
        instanceIdToClone?: string;
        /** Can be any valid CSS size specifier. If not specified, defaults to the published height of the view. */
        height?: string;
        /** Can be any valid CSS size specifier. If not specified, defaults to the published height of the view. */
        width?: string;
        /**
         * Specifies a device layout for a dashboard, if it exists.
         * Values can be desktop, tablet, or phone.
         * If not specified, defaults to loading a layout based on the smallest dimension of the hosting iframe element.
         */
        device?: string;
        /**
         * Callback function that is invoked when the Viz object first becomes interactive.
         * This is only called once, but it's guaranteed to be called.
         * If the Viz object is already interactive, it will be called immediately, but on a separate "thread."
         */
        onFirstInteractive?: (e: TableauEvent) => void;
        /**
         * Callback function that's invoked when the size of the Viz object is known.
         * You can use this callback to perform tasks such as resizing the elements surrounding the Viz object once the object's size has been established.
         */
        onFirstVizSizeKnown?: (e: VizResizeEvent) => void;
        /**
         * Apply a filter that you specify to the view when it is first rendered.
         * For example, if you have an Academic Year filter and only want to display data for 2017,
         * you might enter "Academic Year": "2016". For more information, see Filtering.
         */
        [filter: string]: any;
    }

    enum ToolbarPosition {
        /** Positions the toolbar along the top of the visualization. */
        TOP = 'top',
        /** Positions the toolbar along the bottom of the visualization. */
        BOTTOM = 'bottom',
    }

    class ToolbarState {
        /** Gets the Viz object associated with the toolbar. */
        getViz(): Viz;
        /**
         * Gets a value indicating whether the specified toolbar button is enabled.
         * The supported buttons are defined in the ToobarButtonName enum.
         * Currently, only Undo and Redo are supported.
         * Checking this property with a toolbar button that is not supported causes an InvalidToolbarButtonName error.
         */
        isButtonEnabled(toolbarButtonName: ToolbarButtonName): boolean;
    }

    enum ToolbarButtonName {
        /** Specifies the Undo button in the toolbar. */
        UNDO = 'undo',
        /** Specifies the Redo button in the toolbar. */
        REDO = 'redo',
    }
    //#endregion

    //#region Viz Event Classes
    /**
     * Defines strings passed to the Viz.addEventListener and Viz.removeEventListener methods.
     * The values of the enums are all lowercase strings with no underscores.
     * For example, CUSTOM_VIEW_LOAD is customviewload.
     * Either the fully-qualified enum (tableau.TableauEventName.FILTER_CHANGE) or the raw string (filterchange) is acceptable.
     */
    enum TableauEventName {
        /**
         * Raised when a custom view has finished loading.
         * This event is raised after the callback function for onFirstInteractive (if any) has been called.
         */
        CUSTOM_VIEW_LOAD = 'customviewload',
        /** Raised when the user removes a custom view. */
        CUSTOM_VIEW_REMOVE = 'customviewremove',
        /** Raised when the user saves a new or existing custom view. */
        CUSTOM_VIEW_SAVE = 'customviewsave',
        /** Raised when a custom view has been made the default view for this visualization. */
        CUSTOM_VIEW_SET_DEFAULT = 'customviewsetdefault',
        /** Raised when any filter has changed state. The Viz object may not be interactive yet. */
        FILTER_CHANGE = 'filterchange',
        /** Raised when marks are selected or deselected. */
        MARKS_SELECTION = 'marksselection',
        /** Raised when any parameter has changed state. */
        PARAMETER_VALUE_CHANGE = 'parametervaluechange',
        /** Raised after a story point becomes active. */
        STORY_POINT_SWITCH = 'storypointswitch',
        /** Raised after the tab switched, but the Viz object may not yet be interactive. */
        TAB_SWITCH = 'tabswitch',
        /** Raised when the state of the specified toolbar button changes. See API Reference. */
        TOOLBAR_STATE_CHANGE = 'toolbarstatechange',
        /** Raised every time the frame size is calculated from the available size and the Viz object's published size. */
        VIZ_RESIZE = 'vizresize',
    }

    class TableauEvent {
        /** Gets the Viz object associated with the event. */
        getViz(): Viz;

        /** Gets the name of the event, which is a string, but is also one of the items in the TableauEventName enum. */
        getEventName(): TableauEventName;
    }

    class CustomViewEvent extends TableauEvent {
        /** Gets the CustomView object associated with the event. */
        getCustomViewAsync(): Promise<CustomView>;
    }

    class FilterEvent extends TableauEvent {
        /** Gets the Worksheet object associated with the event. */
        getWorksheet(): Worksheet;

        /** Gets the name of the field. */
        getFieldName(): string;

        /** Gets the Filter object associated with the event. */
        getFilterAsync(): Promise<ConcreteFilter>;
    }

    class MarksEvent extends TableauEvent {
        /** Gets the Worksheet object associated with the event. */
        getWorksheet(): Worksheet;

        /** Gets the selected marks on the Worksheet that triggered the event. */
        getMarksAsync(): Promise<Mark[]>;
    }

    class ParameterEvent extends TableauEvent {
        /** Gets the name of the parameter that changed. */
        getParameterName(): string;
        /** Gets the Parameter object that triggered the event. */
        getParameterAsync(): Promise<Parameter>;
    }

    class StoryPointSwitchEvent extends TableauEvent {
        /**
         * Gets the StoryPointInfo that was active before the story point switch event occurred.
         * The returned object reflects the state of the story point before the switch occurred.
         * The returned object reflects the state of the story point after the switch occured.
         */
        getOldStoryPointInfo(): StoryPointInfo;
        /** Gets the StoryPoint that is currently active. */
        getNewStoryPoint(): StoryPoint;
    }

    class TabSwitchEvent extends TableauEvent {
        /** Gets the name of the sheet that was active before the tab switch event occurred. */
        getOldSheetName(): string;
        /** Gets the name of the sheet that is currently active. */
        getNewSheetName(): string;
    }

    class ToolbarStateEvent extends TableauEvent {
        /** Returns the new ToolbarState. */
        getToolbarState(): ToolbarState;
    }

    class VizResizeEvent extends TableauEvent {
        /** Gets the Viz object associated with the event. */
        getViz(): Viz;
        /** Gets the name of the event, which is a string, but is also one of the items in the TableauEventName enum. */
        getEventName(): TableauEventName;
        /** Gets the sheetSize record for the current sheet. For more information, see SheetSizeOptions Record. */
        getVizSize(): Size;
    }
    //#endregion

    //#region Sheet Classes
    class SheetInfo {
        /** Gets the name of the sheet. */
        getName(): string;
        /** Gets the index of the sheet within the published tabs. Note that hidden tabs are still counted in the ordering, as long as they are published. */
        getIndex(): number;
        /**
         * Gets a value indicating whether the sheet is the currently active sheet.Due to a technical limitation,
         * this will always return false if the object is a Worksheet instance that is part of a Dashboard.
         */
        getIsActive(): boolean;
        /**
         * Gets a value indicating whether the sheet is hidden in the UI. Note that if the entire tab control is hidden,
         * it does not affect the state of this flag. This sheet may still report that it is visible even when the tabs control is hidden.
         */
        getIsHidden(): boolean;
        /** Gets the type of the sheet. SheetType is an enum with the following values: WORKSHEET, DASHBOARD and STORY. */
        getSheetType(): SheetType;
        /** Gets the size information that the author specified when publishing the workbook. */
        getSize(): SheetSizeOptions;
        /** Gets the URL for this sheet. */
        getUrl(): string;
        /** Gets the Workbook to which this Sheet belongs. */
        getWorkbook(): Workbook;
    }

    class Sheet {
        /** Gets the name of the sheet. */
        getName(): string;
        /** Gets the index of the sheet within the published tabs. Note that hidden tabs are still counted in the ordering, as long as they are published. */
        getIndex(): number;
        /** Gets a value indicating whether the sheet is the currently active sheet. */
        getIsActive(): boolean;
        /**
         * Gets a value indicating whether the sheet is hidden in the UI.
         * Note that if the entire tab control is hidden, it does not affect the state of this flag.
         * This sheet may still report that it is visible even when the tabs control is hidden.
         */
        getIsHidden(): boolean;
        /** Gets the type of the sheet. SheetType is an enum with the following values: WORKSHEET , DASHBOARD and STORY. */
        getSheetType(): SheetType;
        /** Gets the size information that the author specified when publishing the workbook. */
        getSize(): SheetSizeOptions;
        /** Gets the URL for this sheet. */
        getUrl(): string;
        /** Gets the Workbook to which this Sheet belongs. */
        getWorkbook(): Workbook;
        /**
         * Sets the size information on a sheet. Note that if the sheet is a Worksheet,
         * only SheetSizeBehavior.AUTOMATIC is allowed since you can't actually set a Worksheet to a fixed size.
         */
        changeSizeAsync(options: SheetSizeOptions): Promise<SheetSizeOptions>;
    }

    enum SheetSizeBehaviour {
        AUTOMATIC = 'automatic',
        EXACTLY = 'exactly',
        RANGE = 'range',
        ATLEAST = 'atleast',
        ATMOST = 'atmost',
    }

    interface SheetSizeOptions {
        /** Contains an enumeration value of one of the following: AUTOMATIC, EXACTLY, RANGE, ATLEAST, and ATMOST. */
        behavior: SheetSizeBehaviour;
        /** This is only defined when behavior is EXACTLY, RANGE or ATMOST. */
        maxSize: number;
        /** This is only defined when behavior is EXACTLY, RANGE, or ATLEAST. */
        minSize: number;
    }

    class DataTable {
        /** Either "Underlying Data Table" or "Summary Data Table". */
        getName(): string;
        /**
         * A two-dimensional array of data without the sheet or column metadata.
         * The first array index is the row index and the second array index is the column index.
         */
        getData(): any[];
        /** The column information, including the name, data type, and index. */
        getColumns(): Column[];
        /** The number of rows in the returned data. */
        getTotalRowCount(): number;
        /** Whether the data is summary data or underlying data. Returns true for summary data. */
        getIsSummaryData(): boolean;
    }

    class Column {
        /** The name of the column. */
        getFieldName(): string;
        /** The data type of the column. Possible values are float, integer, string, boolean, date, and datetime. */
        getDataType(): string;
        /** Whether the column data is referenced in the visualization. */
        getIsReferenced(): boolean;
        /** The number of rows in the returned data. */
        getIndex(): number;
    }

    class Worksheet {
        /** Returns the Dashboard object to which this Worksheet belongs (if it's on a dashboard). Otherwise, it returns null. */
        getParentDashboard(): Dashboard;
        /**
         * Returns the StoryPoint object to which this Worksheet belongs (if it's on a story sheet).
         * Otherwise, it returns null. If the Worksheet instance does not come from a call to StoryPoint.getContainedSheet(), it also returns null.
         */
        getParentStoryPoint(): StoryPoint;
        /**
         * Gets the primary and all of the secondary data sources for this worksheet.
         * Note that by convention the primary data source should always be the first element.
         */
        getDataSourcesAsync(): Promise<DataSource[]>;
        /**
         * Gets aggregated data for the fields used in the currently active sheet and returns it as an object.
         * You can specify options with an optional parameter. This can only be called on sheets of the WORKSHEET type.
         */
        getSummaryDataAsync(options: getSummaryDataOptions): Promise<DataTable>;
        /**
         * Gets data for all fields in the data source used by the currently active sheet and returns it as an object.
         * You can specify options with an optional parameter. This can only be called on sheets of the WORKSHEET type.
         */
        getUnderlyingDataAsync(options: getUnderlyingDataOptions): Promise<DataTable>;
        /** Fetches the collection of filters used on the sheet. */
        getFiltersAsync(): Promise<Filter[]>;
        /**
         * Applies a simple categorical filter (non-date).
         * See the filtering examples for more details on these functions.
         * Returns the fieldName that was filtered.
         */
        applyFilterAsync(fieldName: string, values: object[] | object, updateType: FilterUpdateType, options?: FilterOptions): Promise<string>;
        /**
         * Applies a quantitative filter to a field or to a date.
         * If a range is specified that is outside of the domain min/max values, no error is raised and the command is allowed.
         * Subsequent calls to getFiltersAsync[] will return these values even if they are outside of the bounds of the domain.
         * This is equivalent to the behavior in Tableau Desktop.
         */
        applyRangeFilterAsync(fieldName: string, range: RangeFilterOptions): Promise<string>;
        /** Applies a relative date filter. */
        applyRelativeDateFilterAsync(fieldName: string, options: RelativeDateFilterOptions): Promise<string>;
        /**
         * Applies a hierarchical filter.
         * The values parameter is either a single value, an array of values, or an object { levels: ["1", "2"] }.
         */
        applyHierarchicalFilterAsync(fieldName: string, values: object, options: any): Promise<string>;
        /**
         * Clears the filter, no matter what kind of filter it is.
         * Note that the filter is removed as long as no associated quick filter is showing for the field.
         * If there is a quick filter showing, then the filter is kept, but it's reset to the "All" state (effectually canceling the filter).
         * For relative date filters, however, an error is returned since there is no "All" state for a relative date filter.
         * To clear a relative date filter with a quick filter showing, you can call applyRelativeDateFilter()
         * instead using a range that makes sense for the specific field.
         */
        clearFilterAsync(fieldName: string): Promise<string>;
        /** Clears the selection for this worksheet. */
        clearSelectedMarksAsync(): Promise<void>;
        /** Gets the collection of marks that are currently selected. */
        getSelectedMarksAsync(): Promise<Mark[]>;
        /** Selects the marks and returns them. */
        selectMarksAsync(fieldName: string, value: object | object[], updateType: SelectionUpdateType): Promise<void>;
        /**
         * Allows selection based on this syntax for the first parameter:
         * {
         *   "Field1": value,
         *   "Field2": [1, 2, 3]
         * }
         */
        selectMarksAsync(fieldValuesMap: object | Mark[], updateType: SelectionUpdateType): Promise<void>;
    }

    interface getSummaryDataOptions {
        /** Do not use aliases specified in the data source in Tableau. Default is false. */
        ignoreAliases?: boolean;
        /** Only return data for the currently selected marks. Default is false. */
        ignoreSelection?: boolean;
        /** The number of rows of data that you want to return. Enter 0 to return all rows. */
        maxRows: number;
    }

    interface getUnderlyingDataOptions {
        /** Do not use aliases specified in the data source in Tableau. Default is false. */
        ignoreAliases?: boolean;
        /** Only return data for the currently selected marks. Default is false. */
        ignoreSelection?: boolean;
        /** Return all the columns for the data source. Default is false. */
        ignoreAllColumns?: boolean;
        /** The number of rows of data that you want to return. Enter 0 to return all rows. */
        maxRows: number;
    }

    class Dashboard {
        /** Gets the collection of objects. */
        getObjects(): DashboardObject[];
        /**
         * Gets the collection of worksheets contained in the dashboard.
         * Note that this is a helper method and is equivalent to looping through getObjects() and collecting all of
         * the DashboardObject.Worksheet pointers when DashboardObject.getType() === tableau.DashboardObjectType.WORKSHEET.
         */
        getWorksheets(): Worksheet[];
        /**
         * Returns the StoryPoint object to which this Dashboard belongs (if it's on a story sheet).
         * Otherwise, it returns null.
         * If the Dashboard instance does not come from a call to StoryPoint.getContainedSheet(), it also returns null.
         */
        getParentStoryPoint(): StoryPoint;
    }

    class DashboardObject {
        /**
         * Gets what the object represents, which is an enum with the following values:
         * BLANK, WORKSHEET, QUICK_FILTER, PARAMETER_CONTROL, PAGE_FILTER, LEGEND, TITLE, TEXT, IMAGE, WEB_PAGE.
         */
        getObjectType(): DashboardObjectType;
        /** Gets the Dashboard object that contains this object. */
        getDashboard(): Dashboard;
        /** If getType() returns WORKSHEET, this contains a pointer to the Worksheet object. */
        getWorksheet(): Worksheet;
        /** Gets the coordinates relative to the top-left corner of the dashboard of the object. */
        getPosition(): Point;
        /** Gets the size of the object. */
        getSize(): Size;
    }

    class Story extends Sheet {
        /**
         * Gets an array (not a collection) of StoryPointInfo objects.
         * Note that this is not a collection, since we don't have a unique string key for a story point.
         * We only need ordinal access to the story points (by index).
         */
        getStoryPointsInfo(): StoryPointInfo[];
        /** Gets the currently active story point. */
        getActiveStoryPoint(): StoryPoint;
        /**
         * Activates the story point at the specified index and returns a promise of the activated StoryPoint.
         * Throws a tableau.ErrorCode.INDEX_OUT_OF_RANGE error if the index is less than zero or greater than or equal to the number of story points in the array.
         */
        activateStoryPointAsync(index: number): Promise<StoryPoint>;
        /** Activates the next story point if there is one. If the current story point is the last one, then is stays active. */
        activateNextStoryPointAsync(): Promise<StoryPoint>;
        /** Activates the previous story point if there is one. If the current story point is the first one, then it stays active. */
        activatePreviousStoryPointAsync(): Promise<StoryPoint>;
        /**
         * Reverts the story point at the specified index and returns a promise of the reverted StoryPoint.
         * Throws a tableau.ErrorCode.INDEX_OUT_OF_RANGE error if the index is less than zero or greater than or equal to the number of story points in the array.
         */
        revertStoryPointAsync(index: number): Promise<StoryPoint>;
    }

    class StoryPointInfo {
        /** Gets the zero-based index of this story point within the parent Story sheet. */
        getIndex(): number;
        /** Gets the content of the textual description for this story point. */
        getCaption(): string;
        /** Gets a value indicating whether the story point is the currently active point in the story. */
        getIsActive(): boolean;
        /** Gets a value indicating whether the story point is updated, meaning that there are no changes from the last time the story point was "captured". */
        getIsUpdated(): boolean;
        /** Gets the Story object that contains the story point. */
        getParentStory(): Story;
    }

    class StoryPoint {
        /** Gets the zero-based index of this story point within the parent Story sheet. */
        getIndex(): number;
        /** Gets the content of the textual description for this story point. */
        getCaption(): string;
        /** Gets a value indicating whether the story point is the currently active point in the story. */
        getIsActive(): boolean;
        /** Gets a value indicating whether the story point is updated, meaning that there are no changes from the last time the story point was "captured". */
        getIsUpdated(): boolean;
        /** Gets the sheet that this story point contains. This will be null if the story point does not have a contained sheet. */
        getContainedSheet(): Sheet;
        /** Gets the Story object that contains the story point. */
        getParentStory(): Story;
    }
    //#endregion

    //#region Workbook Classes
    class Workbook {
        /** Gets the Viz object that contains the workbook. */
        getViz(): Viz;
        /** Gets the currently active sheet (the active tab) */
        getActiveSheet(): Sheet;
        /** Gets the currently active custom view, or null if no custom view is active. */
        getActiveCustomView(): CustomView;
        /** Note that this is synchronous, meaning that all of the sheets are expected when loaded. */
        getPublishedSheetsInfo(): SheetInfo[];
        /** Gets the name of the workbook saved to the server. Note that this is not necessarily the file name. */
        getName(): string;
        /** Activates the sheet, either by name or index, and returns a promise of the sheet that was activated. */
        activateSheetAsync(sheetNameOrIndex: string | number): Promise<Sheet>;
        /** Reverts the workbook to its last saved state. */
        revertAllAsync(): Promise<void>;
        /** Fetches the parameters for this workbook. */
        getParametersAsync(): Promise<Parameter[]>;
        /**
         * Changes the value of the parameter with the given name and returns the new Parameter.
         * The value should be the same data type as the parameter and within the allowable range of values.
         * It also needs to be the aliased value and not the raw value.
         * For more information and examples, see changeParameterValueAsync() Additional Information
         */
        changeParameterValueAsync(name: string, value: any): Promise<Parameter>;
        /** Gets the collection of CustomView objects associated with the workbook. */
        getCustomViewsAsync(): Promise<CustomView[]>;
        /** Changes the visualization to show the named saved state. */
        showCustomViewAsync(customViewName: string): Promise<CustomView>;
        /** Removes the named custom view. */
        removeCustomViewAsync(customViewName: string): Promise<CustomView>;
        /** Remembers the current state of the workbook by assigning a custom view name. */
        rememberCustomViewAsync(customViewName: string): Promise<CustomView>;
        /** Sets the active custom view as the default. */
        setActiveCustomViewAsDefaultAsync(): void;
    }

    class DataSource {
        /** The name of the DataSource as seen in the UI. */
        getName(): string;
        /** Indicates whether this DataSource is a primary or a secondary data source. */
        getIsPrimary(): boolean;
        /** Gets an array of Fields associated with the DataSource. */
        getFields(): Field[];
    }

    class Field {
        /** Gets the field name (i.e. caption). */
        getName(): string;
        getAggregation(): FieldAggregationType;
        /** Gets the data source to which this field belongs. */
        getDataSource(): DataSource;
        /** One of the following values: DIMENSION, MEASURE, UKNOWN */
        getRole(): FieldRoleType;
    }

    class CustomView {
        /** User-friendly name for the custom view */
        getName(): string;
        /** User-friendly name for the custom view */
        setName(name: string): string;

        /** Indicates whether the custom view is public or private. */
        getAdvertised(): boolean;
        /** Indicates whether the custom view is public or private. */
        setAdvertised(bool: boolean): boolean;

        /** Gets or sets whether this is the default custom view. */
        getDefault(): boolean;

        /** Gets the user that created the custom view. */
        getOwnerName(): string;

        /** Unique URL to load this view again. */
        getUrl(): string;

        /** Gets the Workbook to which this CustomView belongs. */
        getWorkbook(): Workbook;

        /** After saveAsync() is called, the result of the getUrl method is no longer blank. */
        saveAsync(): Promise<CustomView>;
    }
    //#endregion

    //#region Parameter Classes
    class Parameter {
        /** A unique identifier for the parameter, as specified by the user. */
        getName(): string;
        /** The current value of the parameter. */
        getCurrentValue(): DataValue;
        /** The data type of the parameter can be one of the following: FLOAT, INTEGER, STRING, BOOLEAN, DATE, DATETIME. */
        getDataType(): ParameterDataType;
        /** The type of allowable values that the parameter can accept. It can be one of the following enumeration items: ALL, LIST, RANGE. */
        getAllowableValuesType(): ParameterAllowableValuesType;
        /**
         * If the parameter is restricted to a list of allowable values, this property contains the array of those values.
         * Note that this is not a standard collection, but a JavaScript array.
         */
        getAllowableValues(): DataValue[];
        /** If getAllowableValuesType is RANGE, this defines the minimum allowable value, inclusive. Otherwise it's undefined/null. */
        getMinValue(): DataValue;
        /** If getAllowableValuesType is RANGE, this defines the maximum allowable value, inclusive. Otherwise it's undefined/null. */
        getMaxValue(): DataValue;
        /** If getAllowableValuesType is RANGE, this defines the step size used in the parameter UI control slider. Otherwise it's undefined/null. */
        getStepSize(): number;
        /**
         * If getAllowableValuesType is RANGE and getDataType is DATE or DATETIME,
         * this defines the step date period used in the Parameter UI control slider.
         * Otherwise it's undefined/null.
         */
        getDateStepPeriod(): PeriodType;
    }
    //#endregion

    //#region Filtering
    interface FilterOptions {
        /**
         * Determines whether the filter will apply in exclude mode or include mode.
         * The default is include, which means that you use the fields as part of a filter.
         * Exclude mode means that you include everything else except the specified fields.
         */
        isExcludeMode: boolean;
    }

    interface RangeFilterOptions {
        /** Minimum value for the range (inclusive). Optional. Leave blank if you want a <= filter. */
        min: number | Date;
        /** Maximum value for the range (inclusive). Optional. Leave blank if you want a >= filter. */
        max: number | Date;
        /** The null values to include */
        nullOption: NullOption;
    }

    interface RelativeDateFilterOptions {
        /** The UTC date from which to filter. */
        anchorDate: Date;
        /** Year, quarter, month, etc. */
        periodType: PeriodType;
        /** LAST, LASTN, NEXT, etc. */
        rangeType: DateRangeType;
        /** The number used when the rangeType is LASTN or NEXTN. */
        rangeN: number;
    }

    class Filter {
        /** Gets the parent worksheet */
        getWorksheet(): Worksheet;
        /** Gets the type of the filter. See FilterType Enum for the values in the enum. */
        getFilterType(): FilterType;
        /** Gets the name of the field being filtered. Note that this is the caption as shown in the UI and not the actual database field name. */
        getFieldName(): string;
        /** Gets the field that is currently being filtered. */
        getFieldAsync(): Promise<Field>;
    }

    /** An enumeration that indicates what to do with null values for a given filter or mark selection call. */
    enum NullOption {
        /** Only include null values in the filter. */
        NULL_VALUES = 'nullValues',
        /** Only include non-null values in the filter. */
        NON_NULL_VALUES = 'nonNullValues',
        /** Include null and non-null values in the filter. */
        ALL_VALUES = 'allValues',
    }

    class CategoricalFilter extends Filter {
        /** Gets a value indicating whether the filter is exclude or include (default). */
        getIsExcludeMode(): boolean;
        /**
         * Gets the collection of values that are currently set on the filter.
         * This is a native JavaScript array and not a keyed collection.
         * Note that only the first 200 values are returned.
         */
        getAppliedValues(): DataValue[];
    }

    class QuantitativeFilter extends Filter {
        /** Gets the minimum value as specified in the domain. */
        getDomainMin(): DataValue;
        /** Gets the maximum value as specified in the domain. */
        getDomainMax(): DataValue;
        /** Gets the minimum value, inclusive, applied to the filter. */
        getMin(): DataValue;
        /** Gets the maximum value, inclusive, applied to the filter. */
        getMax(): DataValue;
        /** Indicates whether null values are included in the filter. */
        getIncludeNullValues(): boolean;
    }

    class RelativeDateFilter extends Filter {
        /** The date period of the filter. See PeriodType Enum for the values in the enum. */
        getPeriod(): PeriodType;
        /** The range of the date filter (years, months, etc.). See DateRangeType Enum for the values in the enum. */
        getRange(): DateRangeType;
        /** When getRange returns LASTN or NEXTN, this is the N value (how many years, months, etc.). */
        getRangeN(): number;
    }

    type ConcreteFilter = CategoricalFilter | QuantitativeFilter | RelativeDateFilter;

    class DataValue {
        /** Contains the raw native value as a JavaScript type, which is one of String, Number, Boolean, or Date */
        value: any;
        /** The value formatted according to the locale and the formatting applied to the field or parameter. */
        formattedValue: string;
    }

    enum FilterType {
        /** Categorical filters are used to filter to a set of values within the domain. */
        CATEGORICAL = 'categorical',
        /** Quantitative filters are used to filter to a range of values from a continuous domain. */
        QUANTITATIVE = 'quantitative',
        /** Hierarchical filters are used to filter to a set of values organized into a hierarchy within the domain. */
        HIERARCHICAL = 'hierarchical',
        /** Relative date filters are used to filter a date/time domain to a range of values relative to a fixed point in time. */
        RELATIVE_DATE = 'relativedate',
    }

    enum FilterUpdateType {
        /** Adds all values to the filter. Equivalent to checking the (All) value in a quick filter. */
        ALL = 'all',
        /** Replaces the current filter values with new ones specified in the call */
        REPLACE = 'replace',
        /** Adds the filter values as specified in the call to the current filter values. Equivalent to checking a value in a quick filter. */
        ADD = 'add',
        /** Removes the filter values as specified in the call from the current filter values. Equivalent to unchecking a value in a quick filter. */
        REMOVE = 'remove',
    }

    enum PeriodType {
        YEARS = 'years',
        QUARTERS = 'quarters',
        MONTHS = 'months',
        WEEKS = 'weeks',
        DAYS = 'days',
        HOURS = 'hours',
        MINUTES = 'minutes',
        SECONDS = 'seconds',
    }

    enum DateRangeType {
        LAST = 'last', /** Refers to the last day, week, month, etc. of the date period. */
        LASTN = 'lastn', /** Refers to the last N days, weeks, months, etc. of the date period. */
        NEXT = 'next', /** Refers to the next day, week, month, etc. of the date period. */
        NEXTN = 'nextn', /** Refers to the next N days, weeks, months, etc. of the date period. */
        CURRENT = 'current', /** Refers to the current day, week, month, etc. of the date period. */
        TODATE = 'todate', /** Refers to everything up to and including the current day, week, month, etc. of the date period. */
    }
    //#endregion

    //#region Marks Selection
    /**
     * A mark represents a single data point on the visualization.
     * It is independent of the type of visualization (bar, line, pie, etc.).
     */
    class Mark {
        /** Creates a new Mark with the specified pairs. */
        constructor(pairs: Pair[]);
        /** Gets a collection of field name/value pairs associated with the mark. */
        getPairs(): Pair[];
    }

    class Pair {
        /** The value formatted according to the locale and the formatting applied to the field. */
        formattedValue: string;
        /** The field name to which the value is applied. */
        fieldName: string;
        /** Contains the raw native value for the field as a JavaScript type, which is one of String, Number, Boolean, or Date. */
        value: string | number | boolean | Date;
        /** Creates a new Pair with the specified field name/value pairing */
        constructor(fieldName: string, value: string | number | boolean | Date);
    }

    enum SelectionUpdateType {
        /** Replaces the current marks values with new ones specified in the call. */
        REPLACE = 'replace',
        /** Adds the values as specified in the call to the current selection. Equivalent to control-clicking in desktop. */
        ADD = 'add',
        /** Removes the values as specified in the call from the current selection. Equivalent to control-clicking an already selected mark in desktop. */
        REMOVE = 'remove',
    }
    //#endregion

    //#region Other
    interface Size {
        width: number;
        height: number;
    }

    interface Point {
        x: number;
        y: number;
    }
    //#endregion
}


text:
#import <Foundation/Foundation.h>
#import "EC2InstanceBlockDeviceMapping.h"
#import "EC2ResponseUnmarshaller.h"
#import "../AmazonValueUnmarshaller.h"
#import "../AmazonBoolValueUnmarshaller.h"
#import "EC2EbsInstanceBlockDeviceUnmarshaller.h"

/**
 * Instance Block Device Mapping Unmarshaller
 */
@interface EC2InstanceBlockDeviceMappingUnmarshaller:EC2ResponseUnmarshaller {
    EC2InstanceBlockDeviceMapping *response;
}

@property (nonatomic, readonly) EC2InstanceBlockDeviceMapping *response;

-(void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict;
-(void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName;

@end


text:
using BizHawk.Common;

namespace BizHawk.Emulation.Cores.Nintendo.NES
{
	// Meikyuu Jiin Dababa (FDS Conversion)
	public sealed class Mapper108 : NES.NESBoardBase
	{
		private int prg;

		public override bool Configure(NES.EDetectionOrigin origin)
		{
			switch (Cart.board_type)
			{
				case "MAPPER108":
					break;
				default:
					return false;
			}
			AssertPrg(128);
			AssertChr(0);
			Cart.vram_size = 8;
			AssertWram(0);
			SetMirrorType(Cart.pad_h, Cart.pad_v);

			return true;
		}

		public override void WritePRG(int addr, byte value)
		{
			if (addr < 0xFFF
				|| addr >= 0x7000) // hack ported from FCEUX to support Bubble Bobble (FDS Conversion, Kaiser Hacked) (Unl) [p1][!]
			{
				prg = value & 15;
			}
		}

		public override byte ReadPRG(int addr)
		{
			return ROM[addr | 0x18000];
		}

		public override byte ReadWRAM(int addr)
		{
			return ROM[addr | prg << 13];
		}

		public override void SyncState(Serializer ser)
		{
			base.SyncState(ser);
			ser.Sync(nameof(prg), ref prg);
		}
	}
}


text:
package org.apache.sysml.test.integration.functions.unary.scalar;

import java.util.HashMap;

import org.junit.Test;

import org.apache.sysml.runtime.matrix.data.MatrixValue.CellIndex;
import org.apache.sysml.test.integration.AutomatedTestBase;
import org.apache.sysml.test.integration.TestConfiguration;
import org.apache.sysml.test.utils.TestUtils;

public class RoundTest extends AutomatedTestBase
{

	private final static String TEST_NAME = "RoundTest";
	private final static String TEST_DIR = "functions/unary/scalar/";
	private final static String TEST_CLASS_DIR = TEST_DIR + RoundTest.class.getSimpleName() + "/";

	@Override
	public void setUp() {
		TestUtils.clearAssertionInformation();
		addTestConfiguration("RoundTest", new TestConfiguration(TEST_CLASS_DIR, "RoundTest", new String[] { "scalar" }));
	}

	@Test
	public void testRound() {
		if(shouldSkipTest())
			return;

		getAndLoadTestConfiguration(TEST_NAME);

		double scalar = 10.7;

		/* This is for running the junit test the new way, i.e., construct the arguments directly */
		String HOME = SCRIPT_DIR + TEST_DIR;
		fullDMLScriptName = HOME + TEST_NAME + ".dml";
		programArgs = new String[]{"-args", Double.toString(scalar), output("scalar") };

		double roundScalar = Math.round(scalar);

		writeExpectedScalar("scalar", roundScalar);

		runTest(true, false, null, -1);

		HashMap<CellIndex, Double> map = readDMLScalarFromHDFS("scalar");
		double dmlvalue = map.get(new CellIndex(1,1));

		if ( dmlvalue != roundScalar ) {
			throw new RuntimeException("Values mismatch: DMLvalue " + dmlvalue + " != ExpectedValue " + roundScalar);
		}

		//compareResults();
	}

}


text:
"""
Django settings for whimpy project.

For more information on this file, see
https://docs.djangoproject.com/en/1.6/topics/settings/

For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.6/ref/settings/
"""

# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
import os
from django.conf.global_settings import TEMPLATE_CONTEXT_PROCESSORS
BASE_DIR = os.path.dirname(os.path.dirname(__file__))
# Django settings for a generic project.
# Absolute path to root.
ROOT_PATH = os.path.dirname(__file__)

# fixtures
PROJECT_ROOT = ROOT_PATH
FIXTURE_DIRS = (os.path.join(PROJECT_ROOT, 'fixtures'),)

# Absolute path to the directory static files should be collected to.
# Don't put anything in this directory yourself; store your static files
# in apps' "static/" subdirectories and in STATICFILES_DIRS.
# Example: "/home/media/media.lawrence.com/static/"
STATIC_ROOT = os.path.join(ROOT_PATH, 'static')

# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/1.6/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'ttj-$v1y5(%tm1(y&xc#5an#(v%jd^llk()xm5f@&b)4&h_lh$'

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True

TEMPLATE_DEBUG = True

ALLOWED_HOSTS = []

# Application definition

INSTALLED_APPS = (
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'whimpy',
    'locator',
)

MIDDLEWARE_CLASSES = (
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
    'donottrack.middleware.DoNotTrackMiddleware',
)

TEMPLATE_CONTEXT_PROCESSORS = (
    "django.contrib.auth.context_processors.auth",
    "django.core.context_processors.debug",
    "django.core.context_processors.i18n",
    "django.core.context_processors.media",
    "django.core.context_processors.static",
    "django.core.context_processors.tz",
    "django.contrib.messages.context_processors.messages",
    "donottrack.context_processors.donottrack",
)

ROOT_URLCONF = 'whimpy.urls'

WSGI_APPLICATION = 'whimpy.wsgi.application'

# Database
# https://docs.djangoproject.com/en/1.6/ref/settings/#databases

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
    }
}

# Internationalization
# https://docs.djangoproject.com/en/1.6/topics/i18n/

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'UTC'

USE_I18N = True

USE_L10N = True

USE_TZ = True

# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.6/howto/static-files/

STATIC_URL = '/static/'