module Idris.Elab.Implementation

import Core.Binary
import Core.Context
import Core.Core
import Core.Env
import Core.Metadata
import Core.TT
import Core.Unify

import Idris.Resugar
import Idris.Syntax

import TTImp.BindImplicits
import TTImp.Elab
import TTImp.Elab.Check
import TTImp.ProcessDecls
import TTImp.TTImp
import TTImp.Unelab
import TTImp.Utils

import Control.Monad.State
import Data.ANameMap
import Data.NameMap

%default covering

mkImpl : FC -> Name -> List RawImp -> Name
mkImpl fc n ps
    = DN (show n ++ " implementation at " ++ show fc)
         (UN ("__Impl_" ++ show n ++ "_" ++
          showSep "_" (map show ps)))

bindConstraints : FC -> PiInfo RawImp ->
                  List (Maybe Name, RawImp) -> RawImp -> RawImp
bindConstraints fc p [] ty = ty
bindConstraints fc p ((n, ty) :: rest) sc
    = IPi fc top p n ty (bindConstraints fc p rest sc)

bindImpls : FC -> List (Name, RigCount, RawImp) -> RawImp -> RawImp
bindImpls fc [] ty = ty
bindImpls fc ((n, r, ty) :: rest) sc
    = IPi fc r Implicit (Just n) ty (bindImpls fc rest sc)

addDefaults : FC -> Name -> List Name -> List (Name, List ImpClause) ->
              List ImpDecl ->
              (List ImpDecl, List Name) -- Updated body, list of missing methods
addDefaults fc impName allms defs body
    = let missing = dropGot allms body in
          extendBody [] missing body
  where
    -- Given the list of missing names, if any are among the default definitions,
    -- add them to the body
    extendBody : List Name -> List Name -> List ImpDecl ->
                 (List ImpDecl, List Name)
    extendBody ms [] body = (body, ms)
    extendBody ms (n :: ns) body
        = case lookup n defs of
               Nothing => extendBody (n :: ms) ns body
               Just cs =>
                    -- If any method names appear in the clauses, they should
                    -- be applied to the constraint name __con because they
                    -- are going to be referring to the present implementation.
                    -- That is, default method implementations could depend on
                    -- other methods.
                    -- (See test idris2/interface014 for an example!)
                    let mupdates
                            = map (\n => (n, IImplicitApp fc (IVar fc n)
                                                          (Just (UN "__con"))
                                                          (IVar fc impName))) allms
                        cs' = map (substNamesClause [] mupdates) cs in
                        extendBody ms ns
                             (IDef fc n (map (substLocClause fc) cs') :: body)

    -- Find which names are missing from the body
    dropGot : List Name -> List ImpDecl -> List Name
    dropGot ms [] = ms
    dropGot ms (IDef _ n _ :: ds)
        = dropGot (filter (/= n) ms) ds
    dropGot ms (_ :: ds) = dropGot ms ds

getMethImps : {auto c : Ref Ctxt Defs} ->
              Env Term vars -> Term vars ->
              Core (List (Name, RigCount, RawImp))
getMethImps env (Bind fc x (Pi c Implicit ty) sc)
    = do rty <- unelabNoSugar env ty
         ts <- getMethImps (Pi c Implicit ty :: env) sc
         pure ((x, c, rty) :: ts)
getMethImps env tm = pure []

export
elabImplementation : {auto c : Ref Ctxt Defs} ->
                     {auto u : Ref UST UState} ->
                     {auto s : Ref Syn SyntaxInfo} ->
                     {auto m : Ref MD Metadata} ->
                     FC -> Visibility -> List FnOpt -> Pass ->
                     Env Term vars -> NestedNames vars ->
                     (implicits : List (Name, RigCount, RawImp)) ->
                     (constraints : List (Maybe Name, RawImp)) ->
                     Name ->
                     (ps : List RawImp) ->
                     (implName : Maybe Name) ->
                     (nusing : List Name) ->
                     Maybe (List ImpDecl) ->
                     Core ()
-- TODO: Refactor all these steps into separate functions
elabImplementation {vars} fc vis opts_in pass env nest is cons iname ps impln nusing mbody
    = do let impName_in = maybe (mkImpl fc iname ps) id impln
         impName <- inCurrentNS impName_in
         syn <- get Syn
         let [cndata] = lookupName iname (ifaces syn)
             | [] => throw (UndefinedName fc iname)
             | ns => throw (AmbiguousName fc (map fst ns))
         let cn : Name = fst cndata
         let cdata : IFaceInfo = snd cndata
         defs <- get Ctxt

         Just ity <- lookupTyExact cn (gamma defs)
              | Nothing => throw (UndefinedName fc cn)
         Just conty <- lookupTyExact (iconstructor cdata) (gamma defs)
              | Nothing => throw (UndefinedName fc (iconstructor cdata))

         let impsp = nub (concatMap findIBinds ps ++
                          concatMap findIBinds (map snd cons))

         logTerm 3 ("Found interface " ++ show cn) ity
         log 3 $ " with params: " ++ show (params cdata)
                 ++ " and parents: " ++ show (parents cdata)
                 ++ " using implicits: " ++ show impsp
                 ++ " and methods: " ++ show (methods cdata) ++ "\n"
                 ++ "Constructor: " ++ show (iconstructor cdata) ++ "\n"
         logTerm 3 "Constructor type: " conty
         log 5 $ "Making implementation " ++ show impName

         -- 1. Build the type for the implementation
         -- Make the constraints auto implicit arguments, which can be explicitly
         -- given when using named implementations
         --    (cs : Constraints) -> Impl params
         -- Don't make it a hint if it's a named implementation
         let opts = maybe ([Inline, Hint True])
                          (const ([Inline])) impln

         let initTy = bindImpls fc is $ bindConstraints fc AutoImplicit cons
                         (apply (IVar fc iname) ps)
         let paramBinds = if !isUnboundImplicits
                          then findBindableNames True vars [] initTy
                          else []
         let impTy = doBind paramBinds initTy

         let impTyDecl = IClaim fc top vis opts (MkImpTy fc impName impTy)
         log 5 $ "Implementation type: " ++ show impTy

         when (typePass pass) $ processDecl [] nest env impTyDecl

         -- If the body is empty, we're done for now (just declaring that
         -- the implementation exists and define it later)
         when (defPass pass) $ maybe (pure ())
           (\body_in => do
               defs <- get Ctxt
               Just impTyc <- lookupTyExact impName (gamma defs)
                    | Nothing => throw (InternalError ("Can't happen, can't find type of " ++ show impName))
               methImps <- getMethImps [] impTyc
               log 3 $ "Bind implicits to each method: " ++ show methImps

               -- 1.5. Lookup default definitions and add them to to body
               let (body, missing)
                     = addDefaults fc impName (map (dropNS . fst) (methods cdata))
                                      (defaults cdata) body_in

               log 5 $ "Added defaults: body is " ++ show body
               log 5 $ "Missing methods: " ++ show missing

               -- Add the 'using' hints
               defs <- get Ctxt
               let hs = openHints defs -- snapshot open hint state
               log 10 $ "Open hints: " ++ (show (impName :: nusing))
               traverse_ (\n => do n' <- checkUnambig fc n
                                   addOpenHint n') nusing

               -- 2. Elaborate top level function types for this interface
               defs <- get Ctxt
               fns <- topMethTypes [] impName methImps impsp (params cdata)
                                      (map fst (methods cdata))
                                      (methods cdata)
               traverse (processDecl [] nest env) (map mkTopMethDecl fns)

               -- 3. Build the record for the implementation
               let mtops = map (Basics.fst . snd) fns
               let con = iconstructor cdata
               let ilhs = impsApply (IVar fc impName)
                                    (map (\x => (x, IBindVar fc (show x)))
                                              (map fst methImps))
               -- RHS is the constructor applied to a search for the necessary
               -- parent constraints, then the method implementations
               defs <- get Ctxt
               let fldTys = getFieldArgs !(normaliseHoles defs [] conty)
               log 5 $ "Field types " ++ show fldTys
               let irhs = apply (IVar fc con)
                                (map (const (ISearch fc 500)) (parents cdata)
                                 ++ map (mkMethField methImps fldTys) fns)
               let impFn = IDef fc impName [PatClause fc ilhs irhs]
               log 5 $ "Implementation record: " ++ show impFn

               -- If it's a named implementation, add it as a global hint while
               -- elaborating the record and bodies
               maybe (pure ()) (\x => addOpenHint impName) impln

               -- Make sure we don't use this name to solve parent constraints
               -- when elaborating the record, or we'll end up in a cycle!
               setFlag fc impName BlockedHint
               traverse (processDecl [] nest env) [impFn]
               unsetFlag fc impName BlockedHint

               setFlag fc impName TCInline

               -- 4. (TODO: Order method bodies to be in declaration order, in
               --    case of dependencies)

               -- 5. Elaborate the method bodies
               let upds = map methNameUpdate fns
               body' <- traverse (updateBody upds) body
               log 10 $ "Implementation body: " ++ show body'
               traverse (processDecl [] nest env) body'

               -- 6. Add transnformation rules for top level methods
               traverse (addTransform impName upds) (methods cdata)

               -- Reset the open hints (remove the named implementation)
               setOpenHints hs
               pure ()) mbody
  where
    -- For the method fields in the record, get the arguments we need to abstract
    -- over
    getFieldArgs : Term vs -> List (Name, List (Name, RigCount, PiInfo RawImp))
    getFieldArgs (Bind _ x (Pi c p ty) sc)
        = (x, getArgs ty) :: getFieldArgs sc
      where
        getArgs : Term vs' -> List (Name, RigCount, PiInfo RawImp)
        getArgs (Bind _ x (Pi c p _) sc)
            = (x, c, forgetDef p) :: getArgs sc
        getArgs _ = []
    getFieldArgs _ = []

    impsApply : RawImp -> List (Name, RawImp) -> RawImp
    impsApply fn [] = fn
    impsApply fn ((n, arg) :: ns)
        = impsApply (IImplicitApp fc fn (Just n) arg) ns

    mkLam : List (Name, RigCount, PiInfo RawImp) -> RawImp -> RawImp
    mkLam [] tm = tm
    mkLam ((x, c, p) :: xs) tm
        = ILam fc c p (Just x) (Implicit fc False) (mkLam xs tm)

    applyTo : FC -> RawImp -> List (Name, RigCount, PiInfo RawImp) -> RawImp
    applyTo fc tm [] = tm
    applyTo fc tm ((x, c, Explicit) :: xs)
        = applyTo fc (IApp fc tm (IVar fc x)) xs
    applyTo fc tm ((x, c, AutoImplicit) :: xs)
        = applyTo fc (IImplicitApp fc tm (Just x) (IVar fc x)) xs
    applyTo fc tm ((x, c, Implicit) :: xs)
        = applyTo fc (IImplicitApp fc tm (Just x) (IVar fc x)) xs
    applyTo fc tm ((x, c, DefImplicit _) :: xs)
        = applyTo fc (IImplicitApp fc tm (Just x) (IVar fc x)) xs

    -- When applying the method in the field for the record, eta expand
    -- the expected arguments based on the field type, so that implicits get
    -- inserted in the right place
    mkMethField : List (Name, RigCount, RawImp) ->
                  List (Name, List (Name, RigCount, PiInfo RawImp)) ->
                  (Name, Name, List (String, String), RigCount, RawImp) -> RawImp
    mkMethField methImps fldTys (topn, n, upds, c, ty)
        = let argns = map applyUpdate (maybe [] id (lookup (dropNS topn) fldTys))
              imps = map fst methImps in
              -- Pass through implicit arguments to the function which are also
              -- implicit arguments to the declaration
              mkLam argns
                    (impsApply
                         (applyTo fc (IVar fc n) argns)
                         (map (\n => (n, IVar fc (UN (show n)))) imps))
      where
        applyUpdate : (Name, RigCount, PiInfo RawImp) ->
                      (Name, RigCount, PiInfo RawImp)
        applyUpdate (UN n, c, p)
            = maybe (UN n, c, p) (\n' => (UN n', c, p)) (lookup n upds)
        applyUpdate t = t

    methName : Name -> Name
    methName (NS _ n) = methName n
    methName n
        = DN (show n)
             (UN (show n ++ "_" ++ show iname ++ "_" ++
                     maybe "" show impln ++ "_" ++
                     showSep "_" (map show ps)))

    applyCon : Name -> Name -> Core (Name, RawImp)
    applyCon impl n
        = do mn <- inCurrentNS (methName n)
             pure (dropNS n, IVar fc mn)

    bindImps : List (Name, RigCount, RawImp) -> RawImp -> RawImp
    bindImps [] ty = ty
    bindImps ((n, c, t) :: ts) ty
        = IPi fc c Implicit (Just n) t (bindImps ts ty)

    -- Return method name, specialised method name, implicit name updates,
    -- and method type. Also return how the method name should be updated
    -- in later method types (specifically, putting implicits in)
    topMethType : List (Name, RawImp) ->
                  Name -> List (Name, RigCount, RawImp) ->
                  List String -> List Name -> List Name ->
                  (Name, RigCount, (Bool, RawImp)) ->
                  Core ((Name, Name, List (String, String), RigCount, RawImp),
                           List (Name, RawImp))
    topMethType methupds impName methImps impsp pnames allmeths (mn, c, (d, mty_in))
        = do -- Get the specialised type by applying the method to the
             -- parameters
             n <- inCurrentNS (methName mn)

             -- Avoid any name clashes between parameters and method types by
             -- renaming IBindVars in the method types which appear in the
             -- parameters
             let upds' = !(traverse (applyCon impName) allmeths)
             let mty_in = substNames vars upds' mty_in
             let (mty_in, upds) = runState (renameIBinds impsp (findImplicits mty_in) mty_in) []
             -- Finally update the method type so that implicits from the
             -- parameters are passed through to any earlier methods which
             -- appear in the type
             let mty_in = substNames vars methupds mty_in
             let mbase = bindImps methImps $
                         bindConstraints fc AutoImplicit cons $
                         substNames vars (zip pnames ps) mty_in
             let ibound = findImplicits mbase

             mty <- bindTypeNamesUsed ibound vars mbase

             log 3 $ "Method " ++ show mn ++ " ==> " ++
                     show n ++ " : " ++ show mty
             log 3 $ "    (initially " ++ show mty_in ++ ")"
             log 5 $ "Updates " ++ show methupds
             log 5 $ "From " ++ show mbase
             log 3 $ "Name updates " ++ show upds
             log 3 $ "Param names: " ++ show pnames
             log 10 $ "Used names " ++ show ibound
             let ibinds = map fst methImps
             let methupds' = if isNil ibinds then []
                             else [(n, impsApply (IVar fc n)
                                     (map (\x => (x, IBindVar fc (show x))) ibinds))]
             pure ((mn, n, upds, c, mty), methupds')

    topMethTypes : List (Name, RawImp) ->
                   Name -> List (Name, RigCount, RawImp) ->
                   List String -> List Name -> List Name ->
                   List (Name, RigCount, (Bool, RawImp)) ->
                   Core (List (Name, Name, List (String, String), RigCount, RawImp))
    topMethTypes upds impName methImps impsp pnames allmeths [] = pure []
    topMethTypes upds impName methImps impsp pnames allmeths (m :: ms)
        = do (m', newupds) <- topMethType upds impName methImps impsp pnames allmeths m
             ms' <- topMethTypes (newupds ++ upds) impName methImps impsp pnames allmeths ms
             pure (m' :: ms')

    mkTopMethDecl : (Name, Name, List (String, String), RigCount, RawImp) -> ImpDecl
    mkTopMethDecl (mn, n, upds, c, mty)
        = IClaim fc c vis opts_in (MkImpTy fc n mty)

    -- Given the method type (result of topMethType) return the mapping from
    -- top level method name to current implementation's method name
    methNameUpdate : (Name, Name, t) -> (Name, Name)
    methNameUpdate (mn, fn, _) = (UN (nameRoot mn), fn)

    findMethName : List (Name, Name) -> FC -> Name -> Core Name
    findMethName ns fc n
        = case lookup n ns of
               Nothing => throw (GenericMsg fc
                                (show n ++ " is not a method of " ++
                                 show iname))
               Just n' => pure n'

    updateApp : List (Name, Name) -> RawImp -> Core RawImp
    updateApp ns (IVar fc n)
        = do n' <- findMethName ns fc n
             pure (IVar fc n')
    updateApp ns (IApp fc f arg)
        = do f' <- updateApp ns f
             pure (IApp fc f' arg)
    updateApp ns (IImplicitApp fc f x arg)
        = do f' <- updateApp ns f
             pure (IImplicitApp fc f' x arg)
    updateApp ns tm
        = throw (GenericMsg (getFC tm) "Invalid method definition")

    updateClause : List (Name, Name) -> ImpClause ->
                   Core ImpClause
    updateClause ns (PatClause fc lhs rhs)
        = do lhs' <- updateApp ns lhs
             pure (PatClause fc lhs' rhs)
    updateClause ns (WithClause fc lhs wval cs)
        = do lhs' <- updateApp ns lhs
             cs' <- traverse (updateClause ns) cs
             pure (WithClause fc lhs' wval cs')
    updateClause ns (ImpossibleClause fc lhs)
        = do lhs' <- updateApp ns lhs
             pure (ImpossibleClause fc lhs')

    updateBody : List (Name, Name) -> ImpDecl -> Core ImpDecl
    updateBody ns (IDef fc n cs)
        = do cs' <- traverse (updateClause ns) cs
             n' <- findMethName ns fc n
             pure (IDef fc n' cs')
    updateBody ns _
        = throw (GenericMsg fc
                   "Implementation body can only contain definitions")

    addTransform : Name -> List (Name, Name) ->
                   (Name, RigCount, Bool, RawImp) ->
                   Core ()
    addTransform iname ns (top, _, _, ty)
        = do log 3 $ "Adding transform for " ++ show top ++ " : " ++ show ty ++
                     "\n\tfor " ++ show iname ++ " in " ++ show ns
             let lhs = IImplicitApp fc (IVar fc top)
                                       (Just (UN "__con"))
                                       (IVar fc iname)
             let Just mname = lookup (dropNS top) ns
                 | Nothing => pure ()
             let rhs = IVar fc mname
             log 5 $ show lhs ++ " ==> " ++ show rhs
             handleUnify
                 (processDecl [] nest env
                     (ITransform fc (UN (show top ++ " " ++ show iname)) lhs rhs))
                 (\err =>
                     log 5 $ "Can't add transform " ++
                                show lhs ++ " ==> " ++ show rhs ++
                             "\n\t" ++ show err)

{'repo_name': 'edwinb/Idris2-boot', 'stars': '946', 'repo_language': 'Idris', 'file_name': 'ci-base.dockerfile', 'mime_type': 'text/plain', 'hash': 802650828450857621, 'source_dataset': 'data'}


'use strict'

const BB = require('bluebird')

const cacache = require('cacache')
const cacheKey = require('./util/cache-key')
const fetchFromManifest = require('./fetch').fromManifest
const finished = require('./util/finished')
const minimatch = require('minimatch')
const normalize = require('normalize-package-data')
const optCheck = require('./util/opt-check')
const path = require('path')
const pipe = BB.promisify(require('mississippi').pipe)
const ssri = require('ssri')
const tar = require('tar')
const readJson = require('./util/read-json')
const normalizePackageBin = require('npm-normalize-package-bin')

// `finalizeManifest` takes as input the various kinds of manifests that
// manifest handlers ('lib/fetchers/*.js#manifest()') return, and makes sure
// they are:
//
// * filled out with any required data that the handler couldn't fill in
// * formatted consistently
// * cached so we don't have to repeat this work more than necessary
//
// The biggest thing this package might do is do a full tarball extraction in
// order to find missing bits of metadata required by the npm installer. For
// example, it will fill in `_shrinkwrap`, `_integrity`, and other details that
// the plain manifest handlers would require a tarball to fill out. If a
// handler returns everything necessary, this process is skipped.
//
// If we get to the tarball phase, the corresponding tarball handler for the
// requested type will be invoked and the entire tarball will be read from the
// stream.
//
module.exports = finalizeManifest
function finalizeManifest (pkg, spec, opts) {
  const key = finalKey(pkg, spec)
  opts = optCheck(opts)

  const cachedManifest = (opts.cache && key && !opts.preferOnline && !opts.fullMetadata && !opts.enjoyBy)
    ? cacache.get.info(opts.cache, key, opts)
    : BB.resolve(null)

  return cachedManifest.then(cached => {
    if (cached && cached.metadata && cached.metadata.manifest) {
      return new Manifest(cached.metadata.manifest)
    } else {
      return tarballedProps(pkg, spec, opts).then(props => {
        return pkg && pkg.name
          ? new Manifest(pkg, props, opts.fullMetadata)
          : new Manifest(props, null, opts.fullMetadata)
      }).then(manifest => {
        const cacheKey = key || finalKey(manifest, spec)
        if (!opts.cache || !cacheKey) {
          return manifest
        } else {
          return cacache.put(
            opts.cache, cacheKey, '.', {
              metadata: {
                id: manifest._id,
                manifest,
                type: 'finalized-manifest'
              }
            }
          ).then(() => manifest)
        }
      })
    }
  })
}

module.exports.Manifest = Manifest
function Manifest (pkg, fromTarball, fullMetadata) {
  fromTarball = fromTarball || {}
  if (fullMetadata) {
    Object.assign(this, pkg)
  }
  this.name = pkg.name
  this.version = pkg.version
  this.engines = pkg.engines || fromTarball.engines
  this.cpu = pkg.cpu || fromTarball.cpu
  this.os = pkg.os || fromTarball.os
  this.dependencies = pkg.dependencies || {}
  this.optionalDependencies = pkg.optionalDependencies || {}
  this.peerDependenciesMeta = pkg.peerDependenciesMeta || {}
  this.devDependencies = pkg.devDependencies || {}
  const bundled = (
    pkg.bundledDependencies ||
    pkg.bundleDependencies ||
    false
  )
  this.bundleDependencies = bundled
  this.peerDependencies = pkg.peerDependencies || {}
  this.deprecated = pkg.deprecated || false

  // These depend entirely on each handler
  this._resolved = pkg._resolved

  // Not all handlers (or registries) provide these out of the box,
  // and if they don't, we need to extract and read the tarball ourselves.
  // These are details required by the installer.
  this._integrity = pkg._integrity || fromTarball._integrity || null
  this._shasum = pkg._shasum || fromTarball._shasum || null
  this._shrinkwrap = pkg._shrinkwrap || fromTarball._shrinkwrap || null
  this.bin = pkg.bin || fromTarball.bin || null

  // turn arrays and strings into a legit object, strip out bad stuff
  normalizePackageBin(this)

  this._id = null

  // TODO - freezing and inextensibility pending npm changes. See test suite.
  // Object.preventExtensions(this)
  normalize(this)

  // I don't want this why did you give it to me. Go away. 🔥🔥🔥🔥
  delete this.readme

  // Object.freeze(this)
}

// Some things aren't filled in by standard manifest fetching.
// If this function needs to do its work, it will grab the
// package tarball, extract it, and take whatever it needs
// from the stream.
function tarballedProps (pkg, spec, opts) {
  const needsShrinkwrap = (!pkg || (
    pkg._hasShrinkwrap !== false &&
    !pkg._shrinkwrap
  ))
  const needsBin = !!(!pkg || (
    !pkg.bin &&
    pkg.directories &&
    pkg.directories.bin
  ))
  const needsIntegrity = !pkg || (!pkg._integrity && pkg._integrity !== false)
  const needsShasum = !pkg || (!pkg._shasum && pkg._shasum !== false)
  const needsHash = needsIntegrity || needsShasum
  const needsManifest = !pkg || !pkg.name
  const needsExtract = needsShrinkwrap || needsBin || needsManifest
  if (!needsShrinkwrap && !needsBin && !needsHash && !needsManifest) {
    return BB.resolve({})
  } else {
    opts = optCheck(opts)
    const tarStream = fetchFromManifest(pkg, spec, opts)
    const extracted = needsExtract && new tar.Parse()
    return BB.join(
      needsShrinkwrap && jsonFromStream('npm-shrinkwrap.json', extracted),
      needsManifest && jsonFromStream('package.json', extracted),
      needsBin && getPaths(extracted),
      needsHash && ssri.fromStream(tarStream, { algorithms: ['sha1', 'sha512'] }),
      needsExtract && pipe(tarStream, extracted),
      (sr, mani, paths, hash) => {
        if (needsManifest && !mani) {
          const err = new Error(`Non-registry package missing package.json: ${spec}.`)
          err.code = 'ENOPACKAGEJSON'
          throw err
        }
        const extraProps = mani || {}
        delete extraProps._resolved
        // drain out the rest of the tarball
        tarStream.resume()
        // if we have directories.bin, we need to collect any matching files
        // to add to bin
        if (paths && paths.length) {
          const dirBin = mani
            ? (mani && mani.directories && mani.directories.bin)
            : (pkg && pkg.directories && pkg.directories.bin)
          if (dirBin) {
            extraProps.bin = {}
            paths.forEach(filePath => {
              if (minimatch(filePath, dirBin + '/**')) {
                const relative = path.relative(dirBin, filePath)
                if (relative && relative[0] !== '.') {
                  extraProps.bin[path.basename(relative)] = path.join(dirBin, relative)
                }
              }
            })
          }
        }
        return Object.assign(extraProps, {
          _shrinkwrap: sr,
          _resolved: (mani && mani._resolved) ||
          (pkg && pkg._resolved) ||
          spec.fetchSpec,
          _integrity: needsIntegrity && hash && hash.sha512 && hash.sha512[0].toString(),
          _shasum: needsShasum && hash && hash.sha1 && hash.sha1[0].hexDigest()
        })
      }
    )
  }
}

function jsonFromStream (filename, dataStream) {
  return BB.fromNode(cb => {
    dataStream.on('error', cb)
    dataStream.on('close', cb)
    dataStream.on('entry', entry => {
      const filePath = entry.header.path.replace(/[^/]+\//, '')
      if (filePath !== filename) {
        entry.resume()
      } else {
        let data = ''
        entry.on('error', cb)
        finished(entry).then(() => {
          try {
            cb(null, readJson(data))
          } catch (err) {
            cb(err)
          }
        }, err => {
          cb(err)
        })
        entry.on('data', d => { data += d })
      }
    })
  })
}

function getPaths (dataStream) {
  return BB.fromNode(cb => {
    let paths = []
    dataStream.on('error', cb)
    dataStream.on('close', () => cb(null, paths))
    dataStream.on('entry', function handler (entry) {
      const filePath = entry.header.path.replace(/[^/]+\//, '')
      entry.resume()
      paths.push(filePath)
    })
  })
}

function finalKey (pkg, spec) {
  if (pkg && pkg._uniqueResolved) {
    // git packages have a unique, identifiable id, but no tar sha
    return cacheKey(`${spec.type}-manifest`, pkg._uniqueResolved)
  } else {
    return (
      pkg && pkg._integrity &&
      cacheKey(
        `${spec.type}-manifest`,
        `${pkg._resolved}:${ssri.stringify(pkg._integrity)}`
      )
    )
  }
}

{'repo_name': 'nodejs/node', 'stars': '71611', 'repo_language': 'JavaScript', 'file_name': 'rc4-586.s', 'mime_type': 'text/x-asm', 'hash': 7521408533321145211, 'source_dataset': 'data'}


/**
 * This code was generated by
 * \ / _    _  _|   _  _
 *  | (_)\/(_)(_|\/| |(/_  v1.0.0
 *       /       /
 */

package com.twilio.rest.autopilot.v1.assistant;

import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.twilio.base.Resource;
import com.twilio.converter.Converter;
import com.twilio.exception.ApiConnectionException;
import com.twilio.exception.ApiException;
import com.twilio.exception.RestException;
import com.twilio.http.HttpMethod;
import com.twilio.http.Request;
import com.twilio.http.Response;
import com.twilio.http.TwilioRestClient;
import com.twilio.rest.Domains;
import lombok.ToString;

import java.io.IOException;
import java.io.InputStream;
import java.net.URI;
import java.util.Map;
import java.util.Objects;

/**
 * PLEASE NOTE that this class contains preview products that are subject to
 * change. Use them with caution. If you currently do not have developer preview
 * access, please contact help@twilio.com.
 */
@JsonIgnoreProperties(ignoreUnknown = true)
@ToString
public class Defaults extends Resource {
    private static final long serialVersionUID = 3179724176697L;

    /**
     * Create a DefaultsFetcher to execute fetch.
     *
     * @param pathAssistantSid The SID of the Assistant that is the parent of the
     *                         resource to fetch
     * @return DefaultsFetcher capable of executing the fetch
     */
    public static DefaultsFetcher fetcher(final String pathAssistantSid) {
        return new DefaultsFetcher(pathAssistantSid);
    }

    /**
     * Create a DefaultsUpdater to execute update.
     *
     * @param pathAssistantSid The SID of the Assistant that is the parent of the
     *                         resource to update
     * @return DefaultsUpdater capable of executing the update
     */
    public static DefaultsUpdater updater(final String pathAssistantSid) {
        return new DefaultsUpdater(pathAssistantSid);
    }

    /**
     * Converts a JSON String into a Defaults object using the provided
     * ObjectMapper.
     *
     * @param json Raw JSON String
     * @param objectMapper Jackson ObjectMapper
     * @return Defaults object represented by the provided JSON
     */
    public static Defaults fromJson(final String json, final ObjectMapper objectMapper) {
        // Convert all checked exceptions to Runtime
        try {
            return objectMapper.readValue(json, Defaults.class);
        } catch (final JsonMappingException | JsonParseException e) {
            throw new ApiException(e.getMessage(), e);
        } catch (final IOException e) {
            throw new ApiConnectionException(e.getMessage(), e);
        }
    }

    /**
     * Converts a JSON InputStream into a Defaults object using the provided
     * ObjectMapper.
     *
     * @param json Raw JSON InputStream
     * @param objectMapper Jackson ObjectMapper
     * @return Defaults object represented by the provided JSON
     */
    public static Defaults fromJson(final InputStream json, final ObjectMapper objectMapper) {
        // Convert all checked exceptions to Runtime
        try {
            return objectMapper.readValue(json, Defaults.class);
        } catch (final JsonMappingException | JsonParseException e) {
            throw new ApiException(e.getMessage(), e);
        } catch (final IOException e) {
            throw new ApiConnectionException(e.getMessage(), e);
        }
    }

    private final String accountSid;
    private final String assistantSid;
    private final URI url;
    private final Map<String, Object> data;

    @JsonCreator
    private Defaults(@JsonProperty("account_sid")
                     final String accountSid,
                     @JsonProperty("assistant_sid")
                     final String assistantSid,
                     @JsonProperty("url")
                     final URI url,
                     @JsonProperty("data")
                     final Map<String, Object> data) {
        this.accountSid = accountSid;
        this.assistantSid = assistantSid;
        this.url = url;
        this.data = data;
    }

    /**
     * Returns The SID of the Account that created the resource.
     *
     * @return The SID of the Account that created the resource
     */
    public final String getAccountSid() {
        return this.accountSid;
    }

    /**
     * Returns The SID of the Assistant that is the parent of the resource.
     *
     * @return The SID of the Assistant that is the parent of the resource
     */
    public final String getAssistantSid() {
        return this.assistantSid;
    }

    /**
     * Returns The absolute URL of the Defaults resource.
     *
     * @return The absolute URL of the Defaults resource
     */
    public final URI getUrl() {
        return this.url;
    }

    /**
     * Returns The JSON string that describes the default task links.
     *
     * @return The JSON string that describes the default task links
     */
    public final Map<String, Object> getData() {
        return this.data;
    }

    @Override
    public boolean equals(final Object o) {
        if (this == o) {
            return true;
        }

        if (o == null || getClass() != o.getClass()) {
            return false;
        }

        Defaults other = (Defaults) o;

        return Objects.equals(accountSid, other.accountSid) &&
               Objects.equals(assistantSid, other.assistantSid) &&
               Objects.equals(url, other.url) &&
               Objects.equals(data, other.data);
    }

    @Override
    public int hashCode() {
        return Objects.hash(accountSid,
                            assistantSid,
                            url,
                            data);
    }
}

{'repo_name': 'twilio/twilio-java', 'stars': '357', 'repo_language': 'Java', 'file_name': 'PhoneNumberCapabilitiesTest.java', 'mime_type': 'text/x-java', 'hash': 7460367334787399258, 'source_dataset': 'data'}


/*
Copyright (c) 2017 VMware, Inc. All Rights Reserved.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

package toolbox

import "testing"

var _ Channel = new(backdoorChannel)

func TestBackdoorChannel(t *testing.T) {
	in := NewBackdoorChannelIn()
	out := NewBackdoorChannelOut()

	funcs := []func() error{
		in.Start,
		out.Start,
		in.Stop,
		out.Stop,
	}

	for _, f := range funcs {
		err := f()

		if err != nil {
			if err == ErrNotVirtualWorld {
				t.SkipNow()
			}
			t.Fatal(err)
		}
	}

	// expect an error if we don't specify the protocol
	err := new(backdoorChannel).Start()
	if err == nil {
		t.Error("expected error")
	}
}

{'repo_name': 'vmware/govmomi', 'stars': '1383', 'repo_language': 'Go', 'file_name': 'assignment_manager.go', 'mime_type': 'text/plain', 'hash': 6338273571717230129, 'source_dataset': 'data'}


import React from 'react'

import uncontrollableInput from 'uncontrollable-input'
import Combobox from '../combobox'
import Component from '../base-component'
import getEventValue from '../get-event-value'

import { PrimitiveInputWrapper } from './helpers'

// ===================================================================

@uncontrollableInput()
export default class IntegerInput extends Component {
  _onChange = event => {
    const value = getEventValue(event)
    this.props.onChange(value ? +value : undefined)
  }

  render() {
    const { required, schema } = this.props
    const {
      disabled,
      onChange, // eslint-disable-line no-unused-vars
      placeholder = schema.default,
      value,
      ...props
    } = this.props

    return (
      <PrimitiveInputWrapper {...props}>
        <Combobox
          value={value === undefined ? '' : String(value)}
          disabled={disabled}
          max={schema.max}
          min={schema.min}
          onChange={this._onChange}
          options={schema.defaults}
          placeholder={placeholder}
          required={required}
          step={1}
          type='number'
        />
      </PrimitiveInputWrapper>
    )
  }
}

{'repo_name': 'vatesfr/xen-orchestra', 'stars': '301', 'repo_language': 'JavaScript', 'file_name': 'USAGE.md', 'mime_type': 'text/plain', 'hash': -2099539955368160313, 'source_dataset': 'data'}


<?php
namespace GuzzleHttp\Promise;

/**
 * A promise that has been rejected.
 *
 * Thenning off of this promise will invoke the onRejected callback
 * immediately and ignore other callbacks.
 */
class RejectedPromise implements PromiseInterface
{
    private $reason;

    public function __construct($reason)
    {
        if (method_exists($reason, 'then')) {
            throw new \InvalidArgumentException(
                'You cannot create a RejectedPromise with a promise.');
        }

        $this->reason = $reason;
    }

    public function then(
        callable $onFulfilled = null,
        callable $onRejected = null
    ) {
        // If there's no onRejected callback then just return self.
        if (!$onRejected) {
            return $this;
        }

        $queue = queue();
        $reason = $this->reason;
        $p = new Promise([$queue, 'run']);
        $queue->add(static function () use ($p, $reason, $onRejected) {
            if ($p->getState() === self::PENDING) {
                try {
                    // Return a resolved promise if onRejected does not throw.
                    $p->resolve($onRejected($reason));
                } catch (\Throwable $e) {
                    // onRejected threw, so return a rejected promise.
                    $p->reject($e);
                } catch (\Exception $e) {
                    // onRejected threw, so return a rejected promise.
                    $p->reject($e);
                }
            }
        });

        return $p;
    }

    public function otherwise(callable $onRejected)
    {
        return $this->then(null, $onRejected);
    }

    public function wait($unwrap = true, $defaultDelivery = null)
    {
        if ($unwrap) {
            throw exception_for($this->reason);
        }
    }

    public function getState()
    {
        return self::REJECTED;
    }

    public function resolve($value)
    {
        throw new \LogicException("Cannot resolve a rejected promise");
    }

    public function reject($reason)
    {
        if ($reason !== $this->reason) {
            throw new \LogicException("Cannot reject a rejected promise");
        }
    }

    public function cancel()
    {
        // pass
    }
}

{'repo_name': 'spotweb/spotweb', 'stars': '296', 'repo_language': 'PHP', 'file_name': 'jquery.mobile-1.4.5.js', 'mime_type': 'text/plain', 'hash': 3268179092011168100, 'source_dataset': 'data'}


1457 1566839602946 httpcache-v1
Method: POST
URL: https://www.notion.so/api/v3/getRecordValues
Body:+110
{
  "requests": [
    {
      "id": "0afb75e2-b6d4-4d59-a89d-0f26da878ce7",
      "table": "block"
    }
  ]
}
Response:+1257
{
  "results": [
    {
      "role": "comment_only",
      "value": {
        "alive": true,
        "content": [
          "a8cdf0f6-61ce-4879-ba5b-e105697af2a2",
          "50928ea9-bbcd-4a68-ab8b-33b250f57a30",
          "8e10f245-8f5e-47c7-98a5-e0b844b6a433",
          "a776d0d6-ae96-4003-bc1d-b5ef61c1e8d3",
          "7e767802-4050-45e4-ac35-78d91e3d8179",
          "da747466-0629-4dba-9d5c-70562fc9a161",
          "d00fa2c8-10bc-4ad0-95dd-318d0354dc42",
          "2194935d-c4c1-47aa-b236-c65f331fd837",
          "8722ff52-0598-4daa-b010-5d55f92af0e4"
        ],
        "created_by": "bb760e2d-d679-4b64-b2a9-03005b21870a",
        "created_time": 1552021129346,
        "format": {
          "page_full_width": true,
          "page_small_text": true
        },
        "id": "0afb75e2-b6d4-4d59-a89d-0f26da878ce7",
        "ignore_block_count": true,
        "last_edited_by": "bb760e2d-d679-4b64-b2a9-03005b21870a",
        "last_edited_time": 1552021129346,
        "parent_id": "fb4c1ee4-492d-40da-a681-cea667f64cab",
        "parent_table": "block",
        "properties": {
          "title": [
            [
              "NSDictionary"
            ]
          ]
        },
        "type": "page",
        "version": 3
      }
    }
  ]
}
16428 1566839602947 httpcache-v1
Method: POST
URL: https://www.notion.so/api/v3/loadPageChunk
Body:+152
{
  "chunkNumber": 0,
  "cursor": {
    "stack": []
  },
  "limit": 50,
  "pageId": "0afb75e2-b6d4-4d59-a89d-0f26da878ce7",
  "verticalColumns": false
}
Response:+16187
{
  "cursor": {
    "stack": []
  },
  "recordMap": {
    "block": {
      "0afb75e2-b6d4-4d59-a89d-0f26da878ce7": {
        "role": "comment_only",
        "value": {
          "alive": true,
          "content": [
            "a8cdf0f6-61ce-4879-ba5b-e105697af2a2",
            "50928ea9-bbcd-4a68-ab8b-33b250f57a30",
            "8e10f245-8f5e-47c7-98a5-e0b844b6a433",
            "a776d0d6-ae96-4003-bc1d-b5ef61c1e8d3",
            "7e767802-4050-45e4-ac35-78d91e3d8179",
            "da747466-0629-4dba-9d5c-70562fc9a161",
            "d00fa2c8-10bc-4ad0-95dd-318d0354dc42",
            "2194935d-c4c1-47aa-b236-c65f331fd837",
            "8722ff52-0598-4daa-b010-5d55f92af0e4"
          ],
          "created_by": "bb760e2d-d679-4b64-b2a9-03005b21870a",
          "created_time": 1552021129346,
          "format": {
            "page_full_width": true,
            "page_small_text": true
          },
          "id": "0afb75e2-b6d4-4d59-a89d-0f26da878ce7",
          "ignore_block_count": true,
          "last_edited_by": "bb760e2d-d679-4b64-b2a9-03005b21870a",
          "last_edited_time": 1552021129346,
          "parent_id": "fb4c1ee4-492d-40da-a681-cea667f64cab",
          "parent_table": "block",
          "properties": {
            "title": [
              [
                "NSDictionary"
              ]
            ]
          },
          "type": "page",
          "version": 3
        }
      },
      "2194935d-c4c1-47aa-b236-c65f331fd837": {
        "role": "comment_only",
        "value": {
          "alive": true,
          "created_by": "bb760e2d-d679-4b64-b2a9-03005b21870a",
          "created_time": 1552021129346,
          "id": "2194935d-c4c1-47aa-b236-c65f331fd837",
          "ignore_block_count": true,
          "last_edited_by": "bb760e2d-d679-4b64-b2a9-03005b21870a",
          "last_edited_time": 1552021129346,
          "parent_id": "0afb75e2-b6d4-4d59-a89d-0f26da878ce7",
          "parent_table": "block",
          "properties": {
            "title": [
              [
                "A key-value pair within a dictionary is called an entry. Each entry consists of one object that represents the key and a second object that is that key’s value. Within a dictionary, the keys are unique. That is, no two keys in a single dictionary are equal (as determined by isEqual:). In general, a key can be any object (provided that it conforms to the NSCopying protocol—see below), but note that when using key-value coding the key must be a string (see Key-Value Coding Fundamentals). Neither a key nor a value can be nil; if you need to represent a null value in a dictionary, you should use NSNull."
              ]
            ]
          },
          "type": "text",
          "version": 1
        }
      },
      "50928ea9-bbcd-4a68-ab8b-33b250f57a30": {
        "role": "comment_only",
        "value": {
          "alive": true,
          "created_by": "bb760e2d-d679-4b64-b2a9-03005b21870a",
          "created_time": 1552021129344,
          "id": "50928ea9-bbcd-4a68-ab8b-33b250f57a30",
          "ignore_block_count": true,
          "last_edited_by": "bb760e2d-d679-4b64-b2a9-03005b21870a",
          "last_edited_time": 1552021129344,
          "parent_id": "0afb75e2-b6d4-4d59-a89d-0f26da878ce7",
          "parent_table": "block",
          "properties": {
            "title": [
              [
                "@{ key: value, … }"
              ]
            ]
          },
          "type": "bulleted_list",
          "version": 1
        }
      },
      "7e767802-4050-45e4-ac35-78d91e3d8179": {
        "role": "comment_only",
        "value": {
          "alive": true,
          "created_by": "bb760e2d-d679-4b64-b2a9-03005b21870a",
          "created_time": 1552021129345,
          "id": "7e767802-4050-45e4-ac35-78d91e3d8179",
          "ignore_block_count": true,
          "last_edited_by": "bb760e2d-d679-4b64-b2a9-03005b21870a",
          "last_edited_time": 1552021129345,
          "parent_id": "0afb75e2-b6d4-4d59-a89d-0f26da878ce7",
          "parent_table": "block",
          "properties": {
            "title": [
              [
                "id "
              ],
              [
                "value",
                [
                  [
                    "i"
                  ]
                ]
              ],
              [
                " = dict["
              ],
              [
                "key",
                [
                  [
                    "i"
                  ]
                ]
              ],
              [
                "];"
              ]
            ]
          },
          "type": "bulleted_list",
          "version": 1
        }
      },
      "8722ff52-0598-4daa-b010-5d55f92af0e4": {
        "role": "comment_only",
        "value": {
          "alive": true,
          "created_by": "bb760e2d-d679-4b64-b2a9-03005b21870a",
          "created_time": 1552021129346,
          "id": "8722ff52-0598-4daa-b010-5d55f92af0e4",
          "ignore_block_count": true,
          "last_edited_by": "bb760e2d-d679-4b64-b2a9-03005b21870a",
          "last_edited_time": 1552021129346,
          "parent_id": "0afb75e2-b6d4-4d59-a89d-0f26da878ce7",
          "parent_table": "block",
          "properties": {
            "title": [
              [
                "NSDictionary is “toll-free bridged” with its Core Foundation counterpart, CFDictionaryRef. See Toll-Free Bridging for more information on toll-free bridging."
              ]
            ]
          },
          "type": "text",
          "version": 1
        }
      },
      "8e10f245-8f5e-47c7-98a5-e0b844b6a433": {
        "role": "comment_only",
        "value": {
          "alive": true,
          "created_by": "bb760e2d-d679-4b64-b2a9-03005b21870a",
          "created_time": 1552021129345,
          "id": "8e10f245-8f5e-47c7-98a5-e0b844b6a433",
          "ignore_block_count": true,
          "last_edited_by": "bb760e2d-d679-4b64-b2a9-03005b21870a",
          "last_edited_time": 1552021129345,
          "parent_id": "0afb75e2-b6d4-4d59-a89d-0f26da878ce7",
          "parent_table": "block",
          "properties": {
            "title": [
              [
                "[NSDictionary dictionaryWithObjectsAndKeys: value, key, …, nil];"
              ]
            ]
          },
          "type": "bulleted_list",
          "version": 1
        }
      },
      "a776d0d6-ae96-4003-bc1d-b5ef61c1e8d3": {
        "role": "comment_only",
        "value": {
          "alive": true,
          "created_by": "bb760e2d-d679-4b64-b2a9-03005b21870a",
          "created_time": 1552021129345,
          "id": "a776d0d6-ae96-4003-bc1d-b5ef61c1e8d3",
          "ignore_block_count": true,
          "last_edited_by": "bb760e2d-d679-4b64-b2a9-03005b21870a",
          "last_edited_time": 1552021129345,
          "parent_id": "0afb75e2-b6d4-4d59-a89d-0f26da878ce7",
          "parent_table": "block",
          "properties": {
            "title": [
              [
                "dict["
              ],
              [
                "key",
                [
                  [
                    "i"
                  ]
                ]
              ],
              [
                "] = "
              ],
              [
                "value",
                [
                  [
                    "i"
                  ]
                ]
              ],
              [
                ";"
              ]
            ]
          },
          "type": "bulleted_list",
          "version": 1
        }
      },
      "a8cdf0f6-61ce-4879-ba5b-e105697af2a2": {
        "role": "comment_only",
        "value": {
          "alive": true,
          "created_by": "bb760e2d-d679-4b64-b2a9-03005b21870a",
          "created_time": 1552021129341,
          "id": "a8cdf0f6-61ce-4879-ba5b-e105697af2a2",
          "ignore_block_count": true,
          "last_edited_by": "bb760e2d-d679-4b64-b2a9-03005b21870a",
          "last_edited_time": 1552021129341,
          "parent_id": "0afb75e2-b6d4-4d59-a89d-0f26da878ce7",
          "parent_table": "block",
          "properties": {
            "title": [
              [
                "Syntax"
              ]
            ]
          },
          "type": "sub_header",
          "version": 1
        }
      },
      "d00fa2c8-10bc-4ad0-95dd-318d0354dc42": {
        "role": "comment_only",
        "value": {
          "alive": true,
          "created_by": "bb760e2d-d679-4b64-b2a9-03005b21870a",
          "created_time": 1552021129346,
          "id": "d00fa2c8-10bc-4ad0-95dd-318d0354dc42",
          "ignore_block_count": true,
          "last_edited_by": "bb760e2d-d679-4b64-b2a9-03005b21870a",
          "last_edited_time": 1552021129346,
          "parent_id": "0afb75e2-b6d4-4d59-a89d-0f26da878ce7",
          "parent_table": "block",
          "properties": {
            "title": [
              [
                "The NSDictionary class declares the programmatic interface to objects that manage immutable associations of keys and values. Use this class or its subclass NSMutableDictionary when you need a convenient and efficient way to retrieve data associated with an arbitrary key. NSDictionary creates static dictionaries, and NSMutableDictionary creates dynamic dictionaries. (For convenience, the term dictionary refers to any instance of one of these classes without specifying its exact class membership.)"
              ]
            ]
          },
          "type": "text",
          "version": 1
        }
      },
      "d16f98c8-a3d6-41cd-88a6-5fb67e6b0081": {
        "role": "comment_only",
        "value": {
          "alive": true,
          "content": [
            "6ebb8a71-c184-4331-921a-a77677384f58",
            "9c8eea30-4419-48d9-9acc-2af85e13f691",
            "659988d9-31bd-43a9-aa8a-348d98106bf0",
            "ff4ae9d1-4b98-4f1b-8814-7d60938bb23f",
            "305ad731-6870-4315-8bd7-cb7cd68c8d5a",
            "1a2fc903-c419-477e-bc9c-634980a5b747",
            "71be0d2e-f5d6-49fc-8196-d4c08c802f89",
            "f8482d7d-a938-4531-a1d5-3a2dea595618",
            "b1a21291-9e7c-4ffa-8e64-d67c8ab753f2",
            "e8e7dac1-8fbf-4c7a-8987-a252df50ecfc",
            "3bba93bb-22fb-4816-a8ec-5d32c6243cfb",
            "fb4c1ee4-492d-40da-a681-cea667f64cab",
            "73591b7d-ab8a-48a4-8c0c-08a8eb95bd4e",
            "b653a6b7-956c-4993-8016-e838958e7ddc",
            "aefd8c4b-8e31-4127-9a8b-1d53f29839fd",
            "8ec8ae67-95b2-4065-adb2-6ff87458c670",
            "6122b855-f4c4-40d2-8cd2-fed4622d6e60",
            "705af5a2-3877-4339-99bf-d2b1f18377ff",
            "38d6d725-9d1b-46dd-90eb-5553450bfd05",
            "e7bba57b-0017-4678-b23c-37fd58d4bb80",
            "1e25a23e-d9da-4b30-9aa1-85fc78588266",
            "03bd7682-492e-408b-a8ae-d2189af7bbf5",
            "a41e68d2-e582-4c84-a9f7-71a1875df769",
            "734553f3-51e7-4bf8-8797-b50a5168b0df",
            "92ce0718-865c-4b6c-ac25-14bd8ea869e3",
            "4ac15f4d-fa60-4b5b-b714-d3549a0d967e",
            "3732f308-d12a-4cbd-8512-6e4f9d34a917",
            "1ba93139-aa14-4c2f-8bc2-51d74d0a5004",
            "2efdb963-ab02-4ea2-b2ba-e9381c8d216b",
            "82d08f77-0a1c-41a8-b1d0-a6c4522aba79",
            "e7d2fa0b-2d3f-4e9f-96af-721c1e741921",
            "b1516cc0-3f41-437a-8a95-18c88c0a41a3",
            "c5c180ed-aa1c-4002-b026-b35629fa1a84",
            "1780f62b-a545-4fe9-a767-8218a6496c42",
            "9d23f8a0-4809-4661-b686-63a0b911686b",
            "9ab4b6b8-bf3c-4fb8-b76e-f1e7486d2519",
            "fa9e7153-af6b-44c3-a386-3a9bf09a29ee",
            "03168880-1fe9-41c0-baca-65baf138fad0",
            "cb761839-f116-465c-a454-57011164d2e6",
            "fa5a9568-291b-4191-9be1-aa8b1b3c2f54",
            "c504c87a-07be-45df-ad76-8d0af4c59938",
            "3a2c46a4-1ba7-45a0-a365-0faa59123e73",
            "be4edf80-ba6f-4efc-87a3-342ba9d898ec",
            "dfeb304a-24c5-4f8c-9bad-d655832a9e39",
            "15cab868-dec0-4d95-81ce-8373d1a0315d",
            "b272f154-2728-4de5-b4f5-34ebc1506cb0",
            "5bafcfca-f7e1-4638-8f2f-937ebf46de74",
            "c1b3d150-9074-4c8f-8273-3a9b2fcb2ef5",
            "7beccec4-73a8-4e2c-8e50-2f52f2d456fc",
            "18b57704-b3ac-4132-9848-35ce57454675",
            "02183709-7d63-4c9d-8176-03979c40287f",
            "0836f366-8217-47c4-9d26-b81c0a937842",
            "783bc93a-4764-48cf-84f2-8ae9024a2700",
            "54fea9a9-8cc2-452a-b846-79af09af8bdd"
          ],
          "created_by": "bb760e2d-d679-4b64-b2a9-03005b21870a",
          "created_time": 1552021024411,
          "format": {
            "page_full_width": true,
            "page_small_text": true
          },
          "id": "d16f98c8-a3d6-41cd-88a6-5fb67e6b0081",
          "last_edited_by": "bb760e2d-d679-4b64-b2a9-03005b21870a",
          "last_edited_time": 1553726040000,
          "parent_id": "85cbbaf3-24b7-40ad-ae47-345fc76db9bb",
          "parent_table": "block",
          "permissions": [
            {
              "allow_search_engine_indexing": false,
              "role": "comment_only",
              "type": "public_permission"
            }
          ],
          "properties": {
            "title": [
              [
                "Essential Objective-C"
              ]
            ]
          },
          "type": "page",
          "version": 94
        }
      },
      "da747466-0629-4dba-9d5c-70562fc9a161": {
        "role": "comment_only",
        "value": {
          "alive": true,
          "created_by": "bb760e2d-d679-4b64-b2a9-03005b21870a",
          "created_time": 1552021129345,
          "id": "da747466-0629-4dba-9d5c-70562fc9a161",
          "ignore_block_count": true,
          "last_edited_by": "bb760e2d-d679-4b64-b2a9-03005b21870a",
          "last_edited_time": 1552021129345,
          "parent_id": "0afb75e2-b6d4-4d59-a89d-0f26da878ce7",
          "parent_table": "block",
          "properties": {
            "title": [
              [
                "Remarks"
              ]
            ]
          },
          "type": "sub_header",
          "version": 1
        }
      },
      "fb4c1ee4-492d-40da-a681-cea667f64cab": {
        "role": "comment_only",
        "value": {
          "alive": true,
          "content": [
            "0afb75e2-b6d4-4d59-a89d-0f26da878ce7",
            "019274bc-9de9-494f-999b-53f562464bea",
            "dc0f8e04-3b11-4212-a198-6dcd73906ebc",
            "f0580299-e54f-4e34-a54b-2f7326046d78",
            "600de1cc-77eb-41b7-9057-56693d8e69d0",
            "d39c7912-dd39-4236-8381-4684cf48c9c2",
            "6036c8fc-1d58-4f1b-ba6a-a81afd67b7cd"
          ],
          "created_by": "bb760e2d-d679-4b64-b2a9-03005b21870a",
          "created_time": 1552021080000,
          "format": {
            "page_full_width": true,
            "page_small_text": true
          },
          "id": "fb4c1ee4-492d-40da-a681-cea667f64cab",
          "last_edited_by": "bb760e2d-d679-4b64-b2a9-03005b21870a",
          "last_edited_time": 1552021380000,
          "parent_id": "d16f98c8-a3d6-41cd-88a6-5fb67e6b0081",
          "parent_table": "block",
          "permissions": [
            {
              "role": "editor",
              "type": "user_permission",
              "user_id": "bb760e2d-d679-4b64-b2a9-03005b21870a"
            }
          ],
          "properties": {
            "title": [
              [
                "NSDictionary"
              ]
            ]
          },
          "type": "page",
          "version": 29
        }
      }
    },
    "notion_user": {
      "bb760e2d-d679-4b64-b2a9-03005b21870a": {
        "role": "reader",
        "value": {
          "clipper_onboarding_completed": true,
          "email": "kkowalczyk@gmail.com",
          "family_name": "Kowalczyk",
          "given_name": "Krzysztof",
          "id": "bb760e2d-d679-4b64-b2a9-03005b21870a",
          "mobile_onboarding_completed": true,
          "onboarding_completed": true,
          "profile_photo": "https://s3-us-west-2.amazonaws.com/public.notion-static.com/2dcaa66c-7674-4ff6-9924-601785b63561/head-bw-640x960.png",
          "version": 182
        }
      }
    },
    "space": {}
  }
}

{'repo_name': 'essentialbooks/books', 'stars': '405', 'repo_language': 'Go', 'file_name': 'cd15d428bae84880a76e1f4a06c84838.txt', 'mime_type': 'text/plain', 'hash': 2000685400648256808, 'source_dataset': 'data'}


<?php
/*
 * Copyright 2016 Google Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
 * use this file except in compliance with the License. You may obtain a copy of
 * the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations under
 * the License.
 */

/**
 * The "activities" collection of methods.
 * Typical usage is:
 *  <code>
 *   $youtubeService = new Google_Service_YouTube(...);
 *   $activities = $youtubeService->activities;
 *  </code>
 */
class Google_Service_YouTube_Resource_Activities extends Google_Service_Resource
{
  /**
   * Posts a bulletin for a specific channel. (The user submitting the request
   * must be authorized to act on the channel's behalf.)
   *
   * Note: Even though an activity resource can contain information about actions
   * like a user rating a video or marking a video as a favorite, you need to use
   * other API methods to generate those activity resources. For example, you
   * would use the API's videos.rate() method to rate a video and the
   * playlistItems.insert() method to mark a video as a favorite.
   * (activities.insert)
   *
   * @param string $part The part parameter serves two purposes in this operation.
   * It identifies the properties that the write operation will set as well as the
   * properties that the API response will include.
   * @param Google_Service_YouTube_Activity $postBody
   * @param array $optParams Optional parameters.
   * @return Google_Service_YouTube_Activity
   */
  public function insert($part, Google_Service_YouTube_Activity $postBody, $optParams = array())
  {
    $params = array('part' => $part, 'postBody' => $postBody);
    $params = array_merge($params, $optParams);
    return $this->call('insert', array($params), "Google_Service_YouTube_Activity");
  }
  /**
   * Returns a list of channel activity events that match the request criteria.
   * For example, you can retrieve events associated with a particular channel,
   * events associated with the user's subscriptions and Google+ friends, or the
   * YouTube home page feed, which is customized for each user.
   * (activities.listActivities)
   *
   * @param string $part The part parameter specifies a comma-separated list of
   * one or more activity resource properties that the API response will include.
   *
   * If the parameter identifies a property that contains child properties, the
   * child properties will be included in the response. For example, in an
   * activity resource, the snippet property contains other properties that
   * identify the type of activity, a display title for the activity, and so
   * forth. If you set part=snippet, the API response will also contain all of
   * those nested properties.
   * @param array $optParams Optional parameters.
   *
   * @opt_param string channelId The channelId parameter specifies a unique
   * YouTube channel ID. The API will then return a list of that channel's
   * activities.
   * @opt_param bool home Set this parameter's value to true to retrieve the
   * activity feed that displays on the YouTube home page for the currently
   * authenticated user.
   * @opt_param string maxResults The maxResults parameter specifies the maximum
   * number of items that should be returned in the result set.
   * @opt_param bool mine Set this parameter's value to true to retrieve a feed of
   * the authenticated user's activities.
   * @opt_param string pageToken The pageToken parameter identifies a specific
   * page in the result set that should be returned. In an API response, the
   * nextPageToken and prevPageToken properties identify other pages that could be
   * retrieved.
   * @opt_param string publishedAfter The publishedAfter parameter specifies the
   * earliest date and time that an activity could have occurred for that activity
   * to be included in the API response. If the parameter value specifies a day,
   * but not a time, then any activities that occurred that day will be included
   * in the result set. The value is specified in ISO 8601 (YYYY-MM-
   * DDThh:mm:ss.sZ) format.
   * @opt_param string publishedBefore The publishedBefore parameter specifies the
   * date and time before which an activity must have occurred for that activity
   * to be included in the API response. If the parameter value specifies a day,
   * but not a time, then any activities that occurred that day will be excluded
   * from the result set. The value is specified in ISO 8601 (YYYY-MM-
   * DDThh:mm:ss.sZ) format.
   * @opt_param string regionCode The regionCode parameter instructs the API to
   * return results for the specified country. The parameter value is an ISO
   * 3166-1 alpha-2 country code. YouTube uses this value when the authorized
   * user's previous activity on YouTube does not provide enough information to
   * generate the activity feed.
   * @return Google_Service_YouTube_ActivityListResponse
   */
  public function listActivities($part, $optParams = array())
  {
    $params = array('part' => $part);
    $params = array_merge($params, $optParams);
    return $this->call('list', array($params), "Google_Service_YouTube_ActivityListResponse");
  }
}

{'repo_name': 'cashmusic/platform', 'stars': '1005', 'repo_language': 'PHP', 'file_name': 'SeedBase.php', 'mime_type': 'text/x-php', 'hash': -6489938779675108878, 'source_dataset': 'data'}


package mezz.jei.api.gui.ingredient;

import javax.annotation.Nullable;

import net.minecraft.item.ItemStack;

import mezz.jei.api.gui.IRecipeLayout;

/**
 * IGuiItemStackGroup displays ItemStacks in a gui.
 *
 * If multiple ItemStacks are set, they will be displayed in rotation.
 *
 * Get an instance from {@link IRecipeLayout#getItemStacks()}.
 */
public interface IGuiItemStackGroup extends IGuiIngredientGroup<ItemStack> {

	/**
	 * Initialize the itemStack at slotIndex.
	 *
	 * @param slotIndex the slot index of this itemStack
	 * @param input     whether this slot is an input. Used for the recipe-fill feature.
	 * @param xPosition x position of the slot relative to the recipe background
	 * @param yPosition y position of the slot relative to the recipe background
	 */
	@Override
	void init(int slotIndex, boolean input, int xPosition, int yPosition);

	@Override
	void set(int slotIndex, @Nullable ItemStack itemStack);

	@Override
	void addTooltipCallback(ITooltipCallback<ItemStack> tooltipCallback);
}

{'repo_name': 'mezz/JustEnoughItems', 'stars': '334', 'repo_language': 'Java', 'file_name': 'gradle-wrapper.properties', 'mime_type': 'text/plain', 'hash': 363783921365431805, 'source_dataset': 'data'}


/* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com)
 * All rights reserved.
 *
 * This package is an SSL implementation written
 * by Eric Young (eay@cryptsoft.com).
 * The implementation was written so as to conform with Netscapes SSL.
 *
 * This library is free for commercial and non-commercial use as long as
 * the following conditions are aheared to.  The following conditions
 * apply to all code found in this distribution, be it the RC4, RSA,
 * lhash, DES, etc., code; not just the SSL code.  The SSL documentation
 * included with this distribution is covered by the same copyright terms
 * except that the holder is Tim Hudson (tjh@cryptsoft.com).
 *
 * Copyright remains Eric Young's, and as such any Copyright notices in
 * the code are not to be removed.
 * If this package is used in a product, Eric Young should be given attribution
 * as the author of the parts of the library used.
 * This can be in the form of a textual message at program startup or
 * in documentation (online or textual) provided with the package.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 * 3. All advertising materials mentioning features or use of this software
 *    must display the following acknowledgement:
 *    "This product includes cryptographic software written by
 *     Eric Young (eay@cryptsoft.com)"
 *    The word 'cryptographic' can be left out if the rouines from the library
 *    being used are not cryptographic related :-).
 * 4. If you include any Windows specific code (or a derivative thereof) from
 *    the apps directory (application code) you must include an acknowledgement:
 *    "This product includes software written by Tim Hudson (tjh@cryptsoft.com)"
 *
 * THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 *
 * The licence and distribution terms for any publically available version or
 * derivative of this code cannot be changed.  i.e. this code cannot simply be
 * copied and put under another distribution licence
 * [including the GNU Public Licence.] */

#ifndef OPENSSL_HEADER_HMAC_H
#define OPENSSL_HEADER_HMAC_H

#include <openssl/base.h>

#include <openssl/digest.h>

#if defined(__cplusplus)
extern "C" {
#endif

// HMAC contains functions for constructing PRFs from Merkle–Damgård hash
// functions using HMAC.

// One-shot operation.

// HMAC calculates the HMAC of |data_len| bytes of |data|, using the given key
// and hash function, and writes the result to |out|. On entry, |out| must
// contain at least |EVP_MD_size| bytes of space. The actual length of the
// result is written to |*out_len|. An output size of |EVP_MAX_MD_SIZE| will
// always be large enough. It returns |out| or NULL on error.
OPENSSL_EXPORT uint8_t *HMAC(const EVP_MD *evp_md, const void *key,
                             size_t key_len, const uint8_t *data,
                             size_t data_len, uint8_t *out,
                             unsigned int *out_len);

// Incremental operation.

// HMAC_CTX_init initialises |ctx| for use in an HMAC operation. It's assumed
// that HMAC_CTX objects will be allocated on the stack thus no allocation
// function is provided.
OPENSSL_EXPORT void HMAC_CTX_init(HMAC_CTX *ctx);

// HMAC_CTX_new allocates and initialises a new |HMAC_CTX| and returns it, or
// NULL on allocation failure. The caller must use |HMAC_CTX_free| to release
// the resulting object.
OPENSSL_EXPORT HMAC_CTX *HMAC_CTX_new(void);

// HMAC_CTX_cleanup frees data owned by |ctx|. It does not free |ctx| itself.
OPENSSL_EXPORT void HMAC_CTX_cleanup(HMAC_CTX *ctx);

// HMAC_CTX_free calls |HMAC_CTX_cleanup| and then frees |ctx| itself.
OPENSSL_EXPORT void HMAC_CTX_free(HMAC_CTX *ctx);

// HMAC_Init_ex sets up an initialised |HMAC_CTX| to use |md| as the hash
// function and |key| as the key. For a non-initial call, |md| may be NULL, in
// which case the previous hash function will be used. If the hash function has
// not changed and |key| is NULL, |ctx| reuses the previous key. It returns one
// on success or zero otherwise.
//
// WARNING: NULL and empty keys are ambiguous on non-initial calls. Passing NULL
// |key| but repeating the previous |md| reuses the previous key rather than the
// empty key.
OPENSSL_EXPORT int HMAC_Init_ex(HMAC_CTX *ctx, const void *key, size_t key_len,
                                const EVP_MD *md, ENGINE *impl);

// HMAC_Update hashes |data_len| bytes from |data| into the current HMAC
// operation in |ctx|. It returns one.
OPENSSL_EXPORT int HMAC_Update(HMAC_CTX *ctx, const uint8_t *data,
                               size_t data_len);

// HMAC_Final completes the HMAC operation in |ctx| and writes the result to
// |out| and the sets |*out_len| to the length of the result. On entry, |out|
// must contain at least |HMAC_size| bytes of space. An output size of
// |EVP_MAX_MD_SIZE| will always be large enough. It returns one on success or
// zero on error.
OPENSSL_EXPORT int HMAC_Final(HMAC_CTX *ctx, uint8_t *out,
                              unsigned int *out_len);

// Utility functions.

// HMAC_size returns the size, in bytes, of the HMAC that will be produced by
// |ctx|. On entry, |ctx| must have been setup with |HMAC_Init_ex|.
OPENSSL_EXPORT size_t HMAC_size(const HMAC_CTX *ctx);

// HMAC_CTX_copy_ex sets |dest| equal to |src|. On entry, |dest| must have been
// initialised by calling |HMAC_CTX_init|. It returns one on success and zero
// on error.
OPENSSL_EXPORT int HMAC_CTX_copy_ex(HMAC_CTX *dest, const HMAC_CTX *src);

// HMAC_CTX_reset calls |HMAC_CTX_cleanup| followed by |HMAC_CTX_init|.
OPENSSL_EXPORT void HMAC_CTX_reset(HMAC_CTX *ctx);

// Deprecated functions.

OPENSSL_EXPORT int HMAC_Init(HMAC_CTX *ctx, const void *key, int key_len,
                             const EVP_MD *md);

// HMAC_CTX_copy calls |HMAC_CTX_init| on |dest| and then sets it equal to
// |src|. On entry, |dest| must /not/ be initialised for an operation with
// |HMAC_Init_ex|. It returns one on success and zero on error.
OPENSSL_EXPORT int HMAC_CTX_copy(HMAC_CTX *dest, const HMAC_CTX *src);

// Private functions

struct hmac_ctx_st {
  const EVP_MD *md;
  EVP_MD_CTX md_ctx;
  EVP_MD_CTX i_ctx;
  EVP_MD_CTX o_ctx;
} /* HMAC_CTX */;

#if defined(__cplusplus)
}  // extern C

#if !defined(BORINGSSL_NO_CXX)
extern "C++" {

namespace bssl {

BORINGSSL_MAKE_DELETER(HMAC_CTX, HMAC_CTX_free)

using ScopedHMAC_CTX =
    internal::StackAllocated<HMAC_CTX, void, HMAC_CTX_init, HMAC_CTX_cleanup>;

}  // namespace bssl

}  // extern C++
#endif

#endif

#endif  // OPENSSL_HEADER_HMAC_H

{'repo_name': 'LN-Zap/zap-iOS', 'stars': '137', 'repo_language': 'Swift', 'file_name': 'LNURL.swift', 'mime_type': 'text/plain', 'hash': 105684991413467176, 'source_dataset': 'data'}


/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* ***** BEGIN LICENSE BLOCK *****
 * Version: MPL 1.1/GPL 2.0/LGPL 2.1
 *
 * The contents of this file are subject to the Mozilla Public License Version
 * 1.1 (the "License"); you may not use this file except in compliance with
 * the License. You may obtain a copy of the License at
 * http://www.mozilla.org/MPL/
 *
 * Software distributed under the License is distributed on an "AS IS" basis,
 * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
 * for the specific language governing rights and limitations under the
 * License.
 *
 * The Original Code is the Netscape Portable Runtime (NSPR).
 *
 * The Initial Developer of the Original Code is
 * Netscape Communications Corporation.
 * Portions created by the Initial Developer are Copyright (C) 1998-2000
 * the Initial Developer. All Rights Reserved.
 *
 * Contributor(s):
 *
 * Alternatively, the contents of this file may be used under the terms of
 * either the GNU General Public License Version 2 or later (the "GPL"), or
 * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
 * in which case the provisions of the GPL or the LGPL are applicable instead
 * of those above. If you wish to allow use of your version of this file only
 * under the terms of either the GPL or the LGPL, and not to allow others to
 * use your version of this file under the terms of the MPL, indicate your
 * decision by deleting the provisions above and replace them with the notice
 * and other provisions required by the GPL or the LGPL. If you do not delete
 * the provisions above, a recipient may use your version of this file under
 * the terms of any one of the MPL, the GPL or the LGPL.
 *
 * ***** END LICENSE BLOCK ***** */

#if defined(_PRMWAIT_H)
#else
#define _PRMWAIT_H

#include "prio.h"
#include "prtypes.h"
#include "prclist.h"

#ifdef VBOX_WITH_XPCOM_NAMESPACE_CLEANUP
#define PR_AddWaitFileDesc VBoxNsprPR_AddWaitFileDesc
#define PR_CancelWaitFileDesc VBoxNsprPR_CancelWaitFileDesc
#define PR_CancelWaitGroup VBoxNsprPR_CancelWaitGroup
#define PR_CreateWaitGroup VBoxNsprPR_CreateWaitGroup
#define PR_CreateMWaitEnumerator VBoxNsprPR_CreateMWaitEnumerator
#define PR_DestroyWaitGroup VBoxNsprPR_DestroyWaitGroup
#define PR_DestroyMWaitEnumerator VBoxNsprPR_DestroyMWaitEnumerator
#define PR_EnumerateWaitGroup VBoxNsprPR_EnumerateWaitGroup
#define PR_WaitRecvReady VBoxNsprPR_WaitRecvReady
#endif /* VBOX_WITH_XPCOM_NAMESPACE_CLEANUP */

PR_BEGIN_EXTERN_C

/********************************************************************************/
/********************************************************************************/
/********************************************************************************/
/******************************       WARNING        ****************************/
/********************************************************************************/
/**************************** This is work in progress. *************************/
/************************** Do not make any assumptions *************************/
/************************** about the stability of this *************************/
/************************** API or the underlying imple- ************************/
/************************** mentation.                   ************************/
/********************************************************************************/
/********************************************************************************/

/*
** STRUCTURE:   PRWaitGroup
** DESCRIPTION:
**      The client may define several wait groups in order to semantically
**      tie a collection of file descriptors for a single purpose. This allows
**      easier dispatching of threads that returned with active file descriptors
**      from the wait function.
*/
typedef struct PRWaitGroup PRWaitGroup;

/*
** ENUMERATION: PRMWStatus
** DESCRIPTION:
**      This enumeration is used to indicate the completion status of
**      a receive wait object. Generally stated, a positive value indicates
**      that the operation is not yet complete. A zero value indicates
**      success (similar to PR_SUCCESS) and any negative value is an
**      indication of failure. The reason for the failure can be retrieved
**      by calling PR_GetError().
**
**  PR_MW_PENDING       The operation is still pending. None of the other
**                      fields of the object are currently valid.
**  PR_MW_SUCCESS       The operation is complete and it was successful.
**  PR_MW_FAILURE       The operation failed. The reason for the failure
**                      can be retrieved by calling PR_GetError().
**  PR_MW_TIMEOUT       The amount of time allowed for by the object's
**                      'timeout' field has expired w/o the operation
**                      otherwise coming to closure.
**  PR_MW_INTERRUPT     The operation was cancelled, either by the client
**                      calling PR_CancelWaitFileDesc() or destroying the
**                      entire wait group (PR_DestroyWaitGroup()).
*/
typedef enum PRMWStatus
{
    PR_MW_PENDING = 1,
    PR_MW_SUCCESS = 0,
    PR_MW_FAILURE = -1,
    PR_MW_TIMEOUT = -2,
    PR_MW_INTERRUPT = -3
} PRMWStatus;

/*
** STRUCTURE:   PRMemoryDescriptor
** DESCRIPTION:
**      THis is a descriptor for an interval of memory. It contains a
**      pointer to the first byte of that memory and the length (in
**      bytes) of the interval.
*/
typedef struct PRMemoryDescriptor
{
    void *start;                /* pointer to first byte of memory */
    PRSize length;              /* length (in bytes) of memory interval */
} PRMemoryDescriptor;

/*
** STRUCTURE:   PRMWaitClientData
** DESCRIPTION:
**      An opague stucture for which a client MAY give provide a concrete
**      definition and associate with a receive descriptor. The NSPR runtime
**      does not manage this field. It is completely up to the client.
*/
typedef struct PRMWaitClientData PRMWaitClientData;

/*
** STRUCTURE:   PRRecvWait
** DESCRIPTION:
**      A receive wait object contains the file descriptor that is subject
**      to the wait and the amount of time (beginning epoch established
**      when the object is presented to the runtime) the the channel should
**      block before abandoning the process.
**
**      The success of the wait operation will be noted in the object's
**      'outcome' field. The fields are not valid when the NSPR runtime
**      is in possession of the object.
**
**      The memory descriptor describes an interval of writable memory
**      in the caller's address space where data from an initial read
**      can be placed. The description may indicate a null interval.
*/
typedef struct PRRecvWait
{
    PRCList internal;           /* internal runtime linkages */

    PRFileDesc *fd;             /* file descriptor associated w/ object */
    PRMWStatus outcome;         /* outcome of the current/last operation */
    PRIntervalTime timeout;     /* time allowed for entire operation */

    PRInt32 bytesRecv;          /* number of bytes transferred into buffer */
    PRMemoryDescriptor buffer;  /* where to store first segment of input data */
    PRMWaitClientData *client;  /* pointer to arbitrary client defined data */
} PRRecvWait;

/*
** STRUCTURE:   PRMWaitEnumerator
** DESCRIPTION:
**      An enumeration object is used to store the state of an existing
**      enumeration over a wait group. The opaque object must be allocated
**      by the client and the reference presented on each call to the
**      pseudo-stateless enumerator. The enumeration objects are sharable
**      only in serial fashion.
*/
typedef struct PRMWaitEnumerator PRMWaitEnumerator;

/*
** FUNCTION:    PR_AddWaitFileDesc
** DESCRIPTION:
**      This function will effectively add a file descriptor to the
**      list of those waiting for network receive. The new descriptor
**      will be semantically tied to the wait group specified.
**
**      The ownership for the storage pointed to by 'desc' is temporarily
**      passed over the the NSPR runtime. It will be handed back by the
**      function PR_WaitRecvReady().
**
**  INPUTS
**      group       A reference to a PRWaitGroup or NULL. Wait groups are
**                  created by calling PR_CreateWaitGroup() and are used
**                  to semantically group various file descriptors by the
**                  client's application.
**      desc        A reference to a valid PRRecvWait. The object of the
**                  reference must be preserved and not be modified
**                  until its ownership is returned to the client.
**  RETURN
**      PRStatus    An indication of success. If equal to PR_FAILUE details
**                  of the failure are avaiable via PR_GetError().
**
**  ERRORS
**      PR_INVALID_ARGUMENT_ERROR
**                  Invalid 'group' identifier or duplicate 'desc' object.
**      PR_OUT_OF_MEMORY_ERROR
**                  Insuffient memory for internal data structures.
**      PR_INVALID_STATE_ERROR
**                  The group is being destroyed.
*/
NSPR_API(PRStatus) PR_AddWaitFileDesc(PRWaitGroup *group, PRRecvWait *desc);

/*
** FUNCTION:    PR_WaitRecvReady
** DESCRIPTION:
**      PR_WaitRecvReady will block the calling thread until one of the
**      file descriptors that have been added via PR_AddWaitFileDesc is
**      available for input I/O.
**  INPUT
**      group       A pointer to a valid PRWaitGroup or NULL (the null
**                  group. The function will block the caller until a
**                  channel from the wait group becomes ready for receive
**                  or there is some sort of error.
**  RETURN
**      PRReciveWait
**                  When the caller is resumed it is either returned a
**                  valid pointer to a previously added receive wait or
**                  a NULL. If the latter, the function has terminated
**                  for a reason that can be determined by calling
**                  PR_GetError().
**                  If a valid pointer is returned, the reference is to the
**                  file descriptor contained in the receive wait object.
**                  The outcome of the wait operation may still fail, and
**                  if it has, that fact will be noted in the object's
**                  outcome field. Details can be retrieved from PR_GetError().
**
**  ERRORS
**      PR_INVALID_ARGUMENT_ERROR
**                  The 'group' is not known by the runtime.
**      PR_PENDING_INTERRUPT_ERROR
                    The thread was interrupted.
**      PR_INVALID_STATE_ERROR
**                  The group is being destroyed.
*/
NSPR_API(PRRecvWait*) PR_WaitRecvReady(PRWaitGroup *group);

/*
** FUNCTION:    PR_CancelWaitFileDesc
** DESCRIPTION:
**      PR_CancelWaitFileDesc is provided as a means for cancelling operations
**      on objects previously submitted by use of PR_AddWaitFileDesc(). If
**      the runtime knows of the object, it will be marked as having failed
**      because it was interrupted (similar to PR_Interrupt()). The first
**      available thread waiting on the group will be made to return the
**      PRRecvWait object with the outcome noted.
**
**  INPUTS
**      group       The wait group under which the wait receive object was
**                  added.
**      desc        A pointer to the wait receive object that is to be
**                  cancelled.
**  RETURN
**      PRStatus    If the wait receive object was located and associated
**                  with the specified wait group, the status returned will
**                  be PR_SUCCESS. There is still a race condition that would
**                  permit the offected object to complete normally, but it
**                  is assured that it will complete in the near future.
**                  If the receive object or wait group are invalid, the
**                  function will return with a status of PR_FAILURE.
**
**  ERRORS
**      PR_INVALID_ARGUMENT_ERROR
**                  The 'group' argument is not recognized as a valid group.
**      PR_COLLECTION_EMPTY_ERROR
**                  There are no more receive wait objects in the group's
**                  collection.
**      PR_INVALID_STATE_ERROR
**                  The group is being destroyed.
*/
NSPR_API(PRStatus) PR_CancelWaitFileDesc(PRWaitGroup *group, PRRecvWait *desc);

/*
** FUNCTION:    PR_CancelWaitGroup
** DESCRIPTION:
**      PR_CancelWaitGroup is provided as a means for cancelling operations
**      on objects previously submitted by use of PR_AddWaitFileDesc(). Each
**      successive call will return a pointer to a PRRecvWait object that
**      was previously registered via PR_AddWaitFileDesc(). If no wait
**      objects are associated with the wait group, a NULL will be returned.
**      This function should be called in a loop until a NULL is returned
**      to reclaim all the wait objects prior to calling PR_DestroyWaitGroup().
**
**  INPUTS
**      group       The wait group under which the wait receive object was
**                  added.
**  RETURN
**      PRRecvWait* If the wait group is valid and at least one receive wait
**                  object is present in the group, that object will be
**                  marked as PR_MW_INTERRUPT'd and removed from the group's
**                  queues. Otherwise a NULL will be returned and the reason
**                  for the NULL may be retrieved by calling PR_GetError().
**
**  ERRORS
**      PR_INVALID_ARGUMENT_ERROR
**      PR_GROUP_EMPTY_ERROR
*/
NSPR_API(PRRecvWait*) PR_CancelWaitGroup(PRWaitGroup *group);

/*
** FUNCTION:    PR_CreateWaitGroup
** DESCRIPTION:
**      A wait group is an opaque object that a client may create in order
**      to semantically group various wait requests. Each wait group is
**      unique, including the default wait group (NULL). A wait request
**      that was added under a wait group will only be serviced by a caller
**      that specified the same wait group.
**
**  INPUT
**      size        The size of the hash table to be used to contain the
**                  receive wait objects. This is just the initial size.
**                  It will grow as it needs to, but to avoid that hassle
**                  one can suggest a suitable size initially. It should
**                  be ~30% larger than the maximum number of receive wait
**                  objects expected.
**  RETURN
**      PRWaitGroup If successful, the function will return a pointer to an
**                  object that was allocated by and owned by the runtime.
**                  The reference remains valid until it is explicitly destroyed
**                  by calling PR_DestroyWaitGroup().
**
**  ERRORS
**      PR_OUT_OF_MEMORY_ERROR
*/
NSPR_API(PRWaitGroup*) PR_CreateWaitGroup(PRInt32 size);

/*
** FUNCTION:    PR_DestroyWaitGroup
** DESCRIPTION:
**      Undo the effects of PR_CreateWaitGroup(). Any receive wait operations
**      on the group will be treated as if the each had been the target of a
**      PR_CancelWaitFileDesc().
**
**  INPUT
**      group       Reference to a wait group previously allocated using
**                  PR_CreateWaitGroup().
**  RETURN
**      PRStatus    Will be PR_SUCCESS if the wait group was valid and there
**                  are no receive wait objects in that group. Otherwise
**                  will indicate PR_FAILURE.
**
**  ERRORS
**      PR_INVALID_ARGUMENT_ERROR
**                  The 'group' argument does not reference a known object.
**      PR_INVALID_STATE_ERROR
**                  The group still contains receive wait objects.
*/
NSPR_API(PRStatus) PR_DestroyWaitGroup(PRWaitGroup *group);

/*
** FUNCTION:    PR_CreateMWaitEnumerator
** DESCRIPTION:
**      The PR_CreateMWaitEnumerator() function returns a reference to an
**      opaque PRMWaitEnumerator object. The enumerator object is required
**      as an argument for each successive call in the stateless enumeration
**      of the indicated wait group.
**
**      group       The wait group that the enumeration is intended to
**                  process. It may be be the default wait group (NULL).
** RETURN
**      PRMWaitEnumerator* group
**                  A reference to an object that will be used to store
**                  intermediate state of enumerations.
** ERRORS
**      Errors are indicated by the function returning a NULL.
**      PR_INVALID_ARGUMENT_ERROR
**                  The 'group' argument does not reference a known object.
**      PR_OUT_OF_MEMORY_ERROR
*/
NSPR_API(PRMWaitEnumerator*) PR_CreateMWaitEnumerator(PRWaitGroup *group);

/*
** FUNCTION:    PR_DestroyMWaitEnumerator
** DESCRIPTION:
**      Destroys the object created by PR_CreateMWaitEnumerator(). The reference
**      used as an argument becomes invalid.
**
** INPUT
**      PRMWaitEnumerator* enumerator
**          The PRMWaitEnumerator object to destroy.
** RETURN
**      PRStatus
**          PR_SUCCESS if successful, PR_FAILURE otherwise.
** ERRORS
**      PR_INVALID_ARGUMENT_ERROR
**                  The enumerator is invalid.
*/
NSPR_API(PRStatus) PR_DestroyMWaitEnumerator(PRMWaitEnumerator* enumerator);

/*
** FUNCTION:    PR_EnumerateWaitGroup
** DESCRIPTION:
**      PR_EnumerateWaitGroup is a thread safe enumerator over a wait group.
**      Each call to the enumerator must present a valid PRMWaitEnumerator
**      rererence and a pointer to the "previous" element returned from the
**      enumeration process or a NULL.
**
**      An enumeration is started by passing a NULL as the "previous" value.
**      Subsequent calls to the enumerator must pass in the result of the
**      previous call. The enumeration end is signaled by the runtime returning
**      a NULL as the result.
**
**      Modifications to the content of the wait group are allowed during
**      an enumeration. The effect is that the enumeration may have to be
**      "reset" and that may result in duplicates being returned from the
**      enumeration.
**
**      An enumeration may be abandoned at any time. The runtime is not
**      keeping any state, so there are no issues in that regard.
*/
NSPR_API(PRRecvWait*) PR_EnumerateWaitGroup(
    PRMWaitEnumerator *enumerator, const PRRecvWait *previous);

PR_END_EXTERN_C

#endif /* defined(_PRMWAIT_H) */

/* prmwait.h */

{'repo_name': 'VirtualMonitor/VirtualMonitor', 'stars': '152', 'repo_language': 'C', 'file_name': 'lintian-override.in', 'mime_type': 'text/plain', 'hash': -8716218903371722535, 'source_dataset': 'data'}


Copyright (c) Microsoft Corporation. All rights reserved.

Licensed under the Source EULA. See License.txt in the project root for license information.

Do not edit this file. It is machine generated.

Alerta de condição de desempenho do SQL Server

{'repo_name': 'microsoft/azuredatastudio', 'stars': '5815', 'repo_language': 'TypeScript', 'file_name': 'apps', 'mime_type': 'text/plain', 'hash': 6024305839951732528, 'source_dataset': 'data'}


using System;
using System.Collections.Generic;
using System.Linq;
using UnityEngine;

namespace UnityEditor.ProBuilder
{
	/// <remarks>
	/// https://www.dotnetperls.com/levenshtein
	/// </remarks>
	static class LevenshteinDistance
	{
		/// <summary>
		/// Compute the distance between two strings.
		/// </summary>
		public static int Compute(string s, string t)
		{
			int n = s.Length;
			int m = t.Length;
			int[,] d = new int[n + 1, m + 1];

			// Step 1
			if (n == 0)
			{
				return m;
			}

			if (m == 0)
			{
				return n;
			}

			// Step 2
			for (int i = 0; i <= n; d[i, 0] = i++)
			{
			}

			for (int j = 0; j <= m; d[0, j] = j++)
			{
			}

			// Step 3
			for (int i = 1; i <= n; i++)
			{
				//Step 4
				for (int j = 1; j <= m; j++)
				{
					// Step 5
					int cost = (t[j - 1] == s[i - 1]) ? 0 : 1;

					// Step 6
					d[i, j] = System.Math.Min(
						System.Math.Min(d[i - 1, j] + 1, d[i, j - 1] + 1),
						d[i - 1, j - 1] + cost);
				}
			}
			// Step 7
			return d[n, m];
		}
	}

	static class DiceCoefficientExtensions
	{
		/// <summary>
		/// Dice Coefficient based on bigrams. <br />
		/// A good value would be 0.33 or above, a value under 0.2 is not a good match, from 0.2 to 0.33 is iffy.
		/// </summary>
		/// <param name="input"></param>
		/// <param name="comparedTo"></param>
		/// <returns></returns>
		public static double DiceCoefficient(this string input, string comparedTo)
		{
			var ngrams = input.ToBiGrams();
			var compareToNgrams = comparedTo.ToBiGrams();
			return ngrams.DiceCoefficient(compareToNgrams);
		}

		/// <summary>
		/// Dice Coefficient used to compare nGrams arrays produced in advance.
		/// </summary>
		/// <param name="nGrams"></param>
		/// <param name="compareToNGrams"></param>
		/// <returns></returns>
		public static double DiceCoefficient(this string[] nGrams, string[] compareToNGrams)
		{
			int matches = 0;
			foreach (var nGram in nGrams)
			{
				if (compareToNGrams.Any(x => x == nGram)) matches++;
			}
			if (matches == 0) return 0.0d;
			double totalBigrams = nGrams.Length + compareToNGrams.Length;
			return (2 * matches) / totalBigrams;
		}

		public static string[] ToBiGrams(this string input)
		{
			// nLength == 2
			//   from Jackson, return %j ja ac ck ks so on n#
			//   from Main, return #m ma ai in n#
			input = SinglePercent + input + SinglePound;
			return ToNGrams(input, 2);
		}

		public static string[] ToTriGrams(this string input)
		{
			// nLength == 3
			//   from Jackson, return %%j %ja jac ack cks kso son on# n##
			//   from Main, return ##m #ma mai ain in# n##
			input = DoublePercent + input + DoublePount;
			return ToNGrams(input, 3);
		}

		private static string[] ToNGrams(string input, int nLength)
		{
			int itemsCount = input.Length - 1;
			string[] ngrams = new string[input.Length - 1];
			for (int i = 0; i < itemsCount; i++) ngrams[i] = input.Substring(i, nLength);
			return ngrams;
		}

		private const string SinglePercent = "%";
		private const string SinglePound = "#";
		private const string DoublePercent = "&&";
		private const string DoublePount = "##";
	}

	struct MenuActionAndFuzzyScore: IComparable<MenuActionAndFuzzyScore>
	{
		public MenuAction action;
		int m_Levenshtein;
		float m_DiceCoefficient;

		public float distance
		{
			get { return m_Levenshtein; }// * m_DiceCoefficient; }
		}

		public MenuActionAndFuzzyScore(MenuAction input, string compare)
		{
			var inp = input.menuTitle.ToLower();
			var cmp = compare.ToLower();
			m_Levenshtein = LevenshteinDistance.Compute(inp, cmp);
			m_DiceCoefficient = (float) DiceCoefficientExtensions.DiceCoefficient(inp, cmp);
			action = input;
		}

		public int CompareTo(MenuActionAndFuzzyScore other)
		{
			return distance.CompareTo(other.distance);
		}

		public bool ScoreIsAboveThreshold()
		{
			return m_Levenshtein < 20 && m_DiceCoefficient > .15f;
		}

		public override string ToString()
		{
#if DEBUG_FUZZY_SEARCH
			return m_Levenshtein + " (" + m_DiceCoefficient + ")  " + action.menuTitle;
#else
			return action.menuTitle;
#endif
		}
	}

	sealed class CommandPalette : EditorWindow
	{
		string m_SearchContent;
		List<MenuActionAndFuzzyScore> m_Results = new List<MenuActionAndFuzzyScore>();
		int m_SelectedIndex;
		const string k_SearchFieldControlName = "fuzzySearchField";
		bool m_FocusInitialized;
		Vector2 m_Scroll;
		static readonly Color k_SelectedColor = new Color(64/255f, 134/255f, 181/255f, .99f);

		static class Styles
		{
			static bool s_Initialized;
			public static GUIStyle selected;

			public static void Init()
			{
				if (s_Initialized)
					return;
				s_Initialized = true;
				selected = new GUIStyle(GUI.skin.label)
				{
					stretchWidth = true,
					normal = new GUIStyleState()
					{
						background = EditorGUIUtility.whiteTexture
					}
				};
			}
		}

		[MenuItem("Window/Command Palette %#o")]
		static void OpenCommandPalette()
		{
			GetWindow<CommandPalette>(true);
		}

		void OnEnable()
		{
			wantsMouseMove = true;
		}

		void OnGUI()
		{
			Styles.Init();

			var evt = Event.current;

			switch (evt.type)
			{
				case EventType.KeyUp:
					HandleKeyUp(evt);
					break;
			}

			EditorGUI.BeginChangeCheck();
			GUI.SetNextControlName(k_SearchFieldControlName);
			m_SearchContent = EditorGUILayout.TextField(m_SearchContent);
			if (EditorGUI.EndChangeCheck())
				UpdateSearchResults();

			m_Scroll = EditorGUILayout.BeginScrollView(m_Scroll);

			for (int i = 0, c = m_Results.Count; i < c; i++)
			{
				if (m_SelectedIndex == i)
				{
					GUI.backgroundColor = k_SelectedColor;
					GUILayout.Label(m_Results[i].ToString(), Styles.selected);
					GUI.backgroundColor = Color.white;
				}
				else
				{
					GUILayout.Label(m_Results[i].ToString());
				}

				if (evt.isMouse)
				{
					if (GUILayoutUtility.GetLastRect().Contains(evt.mousePosition))
					{
						if (evt.type == EventType.MouseUp)
						{
							m_SelectedIndex = i;
							DoSelectedAction();
						}
						else if (evt.type == EventType.MouseMove)
						{
							m_SelectedIndex = i;
						}
					}

					Repaint();
				}
			}

			EditorGUILayout.EndScrollView();

			if (!m_FocusInitialized)
			{
				m_FocusInitialized = true;
				EditorGUI.FocusTextInControl(k_SearchFieldControlName);
			}
		}

		void UpdateSearchResults()
		{
			var results = EditorToolbarLoader.GetActions().Select(x => new MenuActionAndFuzzyScore(x, m_SearchContent));
			m_Results = results.Where(x => x.ScoreIsAboveThreshold()).ToList();
			m_Results.Sort();
		}

		void DoSelectedAction()
		{
			if (m_SelectedIndex > -1 && m_SelectedIndex < m_Results.Count)
			{
				var action = m_Results[m_SelectedIndex].action;
				EditorUtility.ShowNotification(action.DoAction().notification);
			}

			Close();
		}

		void HandleKeyUp(Event evt)
		{
			if (evt.keyCode == KeyCode.Escape)
				Close();
			if (evt.keyCode == KeyCode.Return || evt.keyCode == KeyCode.KeypadEnter)
				DoSelectedAction();

			if (evt.keyCode == KeyCode.UpArrow)
			{
				if (m_SelectedIndex < 0 || m_SelectedIndex > m_Results.Count - 1)
					m_SelectedIndex = m_Results.Count - 1;
				else
					m_SelectedIndex = Math.Max(0, m_SelectedIndex - 1);
			}

			if (evt.keyCode == KeyCode.DownArrow)
			{
				if (m_SelectedIndex < 0 || m_SelectedIndex > m_Results.Count - 1)
					m_SelectedIndex = 0;
				else
					m_SelectedIndex = Math.Min(m_SelectedIndex + 1, m_Results.Count - 1);
			}

			Repaint();
		}
	}
}

{'repo_name': 'Unity-Technologies/com.unity.probuilder', 'stars': '101', 'repo_language': 'C#', 'file_name': 'Blue.mat.meta', 'mime_type': 'text/plain', 'hash': -1508649779464049713, 'source_dataset': 'data'}