text:
{-# LANGUAGE CPP #-}
-----------------------------------------------------------------------------
-- |
-- Module      :  Distribution.Simple.GHC
-- Copyright   :  Isaac Jones 2003-2007
-- License     :  BSD3
--
-- Maintainer  :  cabal-devel@haskell.org
-- Portability :  portable
--
-- This is a fairly large module. It contains most of the GHC-specific code for
-- configuring, building and installing packages. It also exports a function
-- for finding out what packages are already installed. Configuring involves
-- finding the @ghc@ and @ghc-pkg@ programs, finding what language extensions
-- this version of ghc supports and returning a 'Compiler' value.
--
-- 'getInstalledPackages' involves calling the @ghc-pkg@ program to find out
-- what packages are installed.
--
-- Building is somewhat complex as there is quite a bit of information to take
-- into account. We have to build libs and programs, possibly for profiling and
-- shared libs. We have to support building libraries that will be usable by
-- GHCi and also ghc's @-split-objs@ feature. We have to compile any C files
-- using ghc. Linking, especially for @split-objs@ is remarkably complex,
-- partly because there tend to be 1,000's of @.o@ files and this can often be
-- more than we can pass to the @ld@ or @ar@ programs in one go.
--
-- Installing for libs and exes involves finding the right files and copying
-- them to the right places. One of the more tricky things about this module is
-- remembering the layout of files in the build directory (which is not
-- explicitly documented) and thus what search dirs are used for various kinds
-- of files.

module Distribution.Simple.GHC (
        getGhcInfo,
        configure, getInstalledPackages, getPackageDBContents,
        buildLib, buildExe,
        replLib, replExe,
        startInterpreter,
        installLib, installExe,
        libAbiHash,
        hcPkgInfo,
        registerPackage,
        componentGhcOptions,
        componentCcGhcOptions,
        getLibDir,
        isDynamic,
        getGlobalPackageDB,
        pkgRoot
 ) where

import qualified Distribution.Simple.GHC.IPI641 as IPI641
import qualified Distribution.Simple.GHC.IPI642 as IPI642
import qualified Distribution.Simple.GHC.Internal as Internal
import Distribution.Simple.GHC.ImplInfo
import Distribution.PackageDescription as PD
         ( PackageDescription(..), BuildInfo(..), Executable(..), Library(..)
         , allExtensions, libModules, exeModules
         , hcOptions, hcSharedOptions, hcProfOptions )
import Distribution.InstalledPackageInfo
         ( InstalledPackageInfo )
import qualified Distribution.InstalledPackageInfo as InstalledPackageInfo
                                ( InstalledPackageInfo(..) )
import Distribution.Simple.PackageIndex (InstalledPackageIndex)
import qualified Distribution.Simple.PackageIndex as PackageIndex
import Distribution.Simple.LocalBuildInfo
         ( LocalBuildInfo(..), ComponentLocalBuildInfo(..)
         , absoluteInstallDirs, depLibraryPaths )
import qualified Distribution.Simple.Hpc as Hpc
import Distribution.Simple.InstallDirs hiding ( absoluteInstallDirs )
import Distribution.Simple.BuildPaths
import Distribution.Simple.Utils
import Distribution.Package
         ( PackageName(..) )
import qualified Distribution.ModuleName as ModuleName
import Distribution.Simple.Program
         ( Program(..), ConfiguredProgram(..), ProgramConfiguration
         , ProgramSearchPath
         , rawSystemProgramStdout, rawSystemProgramStdoutConf
         , getProgramInvocationOutput, requireProgramVersion, requireProgram
         , userMaybeSpecifyPath, programPath, lookupProgram, addKnownProgram
         , ghcProgram, ghcPkgProgram, haddockProgram, hsc2hsProgram, ldProgram )
import qualified Distribution.Simple.Program.HcPkg as HcPkg
import qualified Distribution.Simple.Program.Ar    as Ar
import qualified Distribution.Simple.Program.Ld    as Ld
import qualified Distribution.Simple.Program.Strip as Strip
import Distribution.Simple.Program.GHC
import Distribution.Simple.Setup
         ( toFlag, fromFlag, fromFlagOrDefault, configCoverage, configDistPref )
import qualified Distribution.Simple.Setup as Cabal
        ( Flag(..) )
import Distribution.Simple.Compiler
         ( CompilerFlavor(..), CompilerId(..), Compiler(..), compilerVersion
         , PackageDB(..), PackageDBStack, AbiTag(..) )
import Distribution.Version
         ( Version(..), anyVersion, orLaterVersion )
import Distribution.System
         ( Platform(..), OS(..) )
import Distribution.Verbosity
import Distribution.Text
         ( display )
import Distribution.Utils.NubList
         ( NubListR, overNubListR, toNubListR )
import Language.Haskell.Extension (Extension(..), KnownExtension(..))

import Control.Monad            ( unless, when )
import Data.Char                ( isDigit, isSpace )
import Data.List
import qualified Data.Map as M  ( fromList )
import Data.Maybe               ( catMaybes )
#if __GLASGOW_HASKELL__ < 710
import Data.Monoid              ( Monoid(..) )
#endif
import Data.Version             ( showVersion )
import System.Directory
         ( doesFileExist, getAppUserDataDirectory, createDirectoryIfMissing )
import System.FilePath          ( (</>), (<.>), takeExtension,
                                  takeDirectory, replaceExtension,
                                  splitExtension, isRelative )
import qualified System.Info

-- -----------------------------------------------------------------------------
-- Configuring

configure :: Verbosity -> Maybe FilePath -> Maybe FilePath
          -> ProgramConfiguration
          -> IO (Compiler, Maybe Platform, ProgramConfiguration)
configure verbosity hcPath hcPkgPath conf0 = do

  (ghcProg, ghcVersion, conf1) <-
    requireProgramVersion verbosity ghcProgram
      (orLaterVersion (Version [6,4] []))
      (userMaybeSpecifyPath "ghc" hcPath conf0)
  let implInfo = ghcVersionImplInfo ghcVersion

  -- This is slightly tricky, we have to configure ghc first, then we use the
  -- location of ghc to help find ghc-pkg in the case that the user did not
  -- specify the location of ghc-pkg directly:
  (ghcPkgProg, ghcPkgVersion, conf2) <-
    requireProgramVersion verbosity ghcPkgProgram {
      programFindLocation = guessGhcPkgFromGhcPath ghcProg
    }
    anyVersion (userMaybeSpecifyPath "ghc-pkg" hcPkgPath conf1)

  when (ghcVersion /= ghcPkgVersion) $ die $
       "Version mismatch between ghc and ghc-pkg: "
    ++ programPath ghcProg ++ " is version " ++ display ghcVersion ++ " "
    ++ programPath ghcPkgProg ++ " is version " ++ display ghcPkgVersion

  -- Likewise we try to find the matching hsc2hs and haddock programs.
  let hsc2hsProgram' = hsc2hsProgram {
                           programFindLocation = guessHsc2hsFromGhcPath ghcProg
                       }
      haddockProgram' = haddockProgram {
                           programFindLocation = guessHaddockFromGhcPath ghcProg
                       }
      conf3 = addKnownProgram haddockProgram' $
              addKnownProgram hsc2hsProgram' conf2

  languages  <- Internal.getLanguages verbosity implInfo ghcProg
  extensions <- Internal.getExtensions verbosity implInfo ghcProg

  ghcInfo <- Internal.getGhcInfo verbosity implInfo ghcProg
  let ghcInfoMap = M.fromList ghcInfo

  let comp = Compiler {
        compilerId         = CompilerId GHC ghcVersion,
        compilerAbiTag     = NoAbiTag,
        compilerCompat     = [],
        compilerLanguages  = languages,
        compilerExtensions = extensions,
        compilerProperties = ghcInfoMap
      }
      compPlatform = Internal.targetPlatform ghcInfo
      -- configure gcc and ld
      conf4 = Internal.configureToolchain implInfo ghcProg ghcInfoMap conf3
  return (comp, compPlatform, conf4)

-- | Given something like /usr/local/bin/ghc-6.6.1(.exe) we try and find
-- the corresponding tool; e.g. if the tool is ghc-pkg, we try looking
-- for a versioned or unversioned ghc-pkg in the same dir, that is:
--
-- > /usr/local/bin/ghc-pkg-ghc-6.6.1(.exe)
-- > /usr/local/bin/ghc-pkg-6.6.1(.exe)
-- > /usr/local/bin/ghc-pkg(.exe)
--
guessToolFromGhcPath :: Program -> ConfiguredProgram
                     -> Verbosity -> ProgramSearchPath
                     -> IO (Maybe FilePath)
guessToolFromGhcPath tool ghcProg verbosity searchpath
  = do let toolname          = programName tool
           path              = programPath ghcProg
           dir               = takeDirectory path
           versionSuffix     = takeVersionSuffix (dropExeExtension path)
           guessNormal       = dir </> toolname <.> exeExtension
           guessGhcVersioned = dir </> (toolname ++ "-ghc" ++ versionSuffix)
                               <.> exeExtension
           guessVersioned    = dir </> (toolname ++ versionSuffix)
                               <.> exeExtension
           guesses | null versionSuffix = [guessNormal]
                   | otherwise          = [guessGhcVersioned,
                                           guessVersioned,
                                           guessNormal]
       info verbosity $ "looking for tool " ++ toolname
         ++ " near compiler in " ++ dir
       exists <- mapM doesFileExist guesses
       case [ file | (file, True) <- zip guesses exists ] of
                   -- If we can't find it near ghc, fall back to the usual
                   -- method.
         []     -> programFindLocation tool verbosity searchpath
         (fp:_) -> do info verbosity $ "found " ++ toolname ++ " in " ++ fp
                      return (Just fp)

  where takeVersionSuffix :: FilePath -> String
        takeVersionSuffix = takeWhileEndLE isSuffixChar

        isSuffixChar :: Char -> Bool
        isSuffixChar c = isDigit c || c == '.' || c == '-'

        dropExeExtension :: FilePath -> FilePath
        dropExeExtension filepath =
          case splitExtension filepath of
            (filepath', extension) | extension == exeExtension -> filepath'
                                   | otherwise                 -> filepath

-- | Given something like /usr/local/bin/ghc-6.6.1(.exe) we try and find a
-- corresponding ghc-pkg, we try looking for both a versioned and unversioned
-- ghc-pkg in the same dir, that is:
--
-- > /usr/local/bin/ghc-pkg-ghc-6.6.1(.exe)
-- > /usr/local/bin/ghc-pkg-6.6.1(.exe)
-- > /usr/local/bin/ghc-pkg(.exe)
--
guessGhcPkgFromGhcPath :: ConfiguredProgram
                       -> Verbosity -> ProgramSearchPath -> IO (Maybe FilePath)
guessGhcPkgFromGhcPath = guessToolFromGhcPath ghcPkgProgram

-- | Given something like /usr/local/bin/ghc-6.6.1(.exe) we try and find a
-- corresponding hsc2hs, we try looking for both a versioned and unversioned
-- hsc2hs in the same dir, that is:
--
-- > /usr/local/bin/hsc2hs-ghc-6.6.1(.exe)
-- > /usr/local/bin/hsc2hs-6.6.1(.exe)
-- > /usr/local/bin/hsc2hs(.exe)
--
guessHsc2hsFromGhcPath :: ConfiguredProgram
                       -> Verbosity -> ProgramSearchPath -> IO (Maybe FilePath)
guessHsc2hsFromGhcPath = guessToolFromGhcPath hsc2hsProgram

-- | Given something like /usr/local/bin/ghc-6.6.1(.exe) we try and find a
-- corresponding haddock, we try looking for both a versioned and unversioned
-- haddock in the same dir, that is:
--
-- > /usr/local/bin/haddock-ghc-6.6.1(.exe)
-- > /usr/local/bin/haddock-6.6.1(.exe)
-- > /usr/local/bin/haddock(.exe)
--
guessHaddockFromGhcPath :: ConfiguredProgram
                       -> Verbosity -> ProgramSearchPath -> IO (Maybe FilePath)
guessHaddockFromGhcPath = guessToolFromGhcPath haddockProgram

getGhcInfo :: Verbosity -> ConfiguredProgram -> IO [(String, String)]
getGhcInfo verbosity ghcProg = Internal.getGhcInfo verbosity implInfo ghcProg
  where
    Just version = programVersion ghcProg
    implInfo = ghcVersionImplInfo version

-- | Given a single package DB, return all installed packages.
getPackageDBContents :: Verbosity -> PackageDB -> ProgramConfiguration
                        -> IO InstalledPackageIndex
getPackageDBContents verbosity packagedb conf = do
  pkgss <- getInstalledPackages' verbosity [packagedb] conf
  toPackageIndex verbosity pkgss conf

-- | Given a package DB stack, return all installed packages.
getInstalledPackages :: Verbosity -> Compiler -> PackageDBStack -> ProgramConfiguration
                     -> IO InstalledPackageIndex
getInstalledPackages verbosity comp packagedbs conf = do
  checkPackageDbEnvVar
  checkPackageDbStack comp packagedbs
  pkgss <- getInstalledPackages' verbosity packagedbs conf
  index <- toPackageIndex verbosity pkgss conf
  return $! hackRtsPackage index

  where
    hackRtsPackage index =
      case PackageIndex.lookupPackageName index (PackageName "rts") of
        [(_,[rts])]
           -> PackageIndex.insert (removeMingwIncludeDir rts) index
        _  -> index -- No (or multiple) ghc rts package is registered!!
                    -- Feh, whatever, the ghc test suite does some crazy stuff.

-- | Given a list of @(PackageDB, InstalledPackageInfo)@ pairs, produce a
-- @PackageIndex@. Helper function used by 'getPackageDBContents' and
-- 'getInstalledPackages'.
toPackageIndex :: Verbosity
               -> [(PackageDB, [InstalledPackageInfo])]
               -> ProgramConfiguration
               -> IO InstalledPackageIndex
toPackageIndex verbosity pkgss conf = do
  -- On Windows, various fields have $topdir/foo rather than full
  -- paths. We need to substitute the right value in so that when
  -- we, for example, call gcc, we have proper paths to give it.
  topDir <- getLibDir' verbosity ghcProg
  let indices = [ PackageIndex.fromList (map (Internal.substTopDir topDir) pkgs)
                | (_, pkgs) <- pkgss ]
  return $! (mconcat indices)

  where
    Just ghcProg = lookupProgram ghcProgram conf

getLibDir :: Verbosity -> LocalBuildInfo -> IO FilePath
getLibDir verbosity lbi =
    dropWhileEndLE isSpace `fmap`
     rawSystemProgramStdoutConf verbosity ghcProgram
     (withPrograms lbi) ["--print-libdir"]

getLibDir' :: Verbosity -> ConfiguredProgram -> IO FilePath
getLibDir' verbosity ghcProg =
    dropWhileEndLE isSpace `fmap`
     rawSystemProgramStdout verbosity ghcProg ["--print-libdir"]

-- | Return the 'FilePath' to the global GHC package database.
getGlobalPackageDB :: Verbosity -> ConfiguredProgram -> IO FilePath
getGlobalPackageDB verbosity ghcProg =
    dropWhileEndLE isSpace `fmap`
     rawSystemProgramStdout verbosity ghcProg ["--print-global-package-db"]

checkPackageDbEnvVar :: IO ()
checkPackageDbEnvVar =
    Internal.checkPackageDbEnvVar "GHC" "GHC_PACKAGE_PATH"

checkPackageDbStack :: Compiler -> PackageDBStack -> IO ()
checkPackageDbStack comp = if flagPackageConf implInfo
                              then checkPackageDbStackPre76
                              else checkPackageDbStackPost76
  where implInfo = ghcVersionImplInfo (compilerVersion comp)

checkPackageDbStackPost76 :: PackageDBStack -> IO ()
checkPackageDbStackPost76 (GlobalPackageDB:rest)
  | GlobalPackageDB `notElem` rest = return ()
checkPackageDbStackPost76 rest
  | GlobalPackageDB `elem` rest =
  die $ "If the global package db is specified, it must be "
     ++ "specified first and cannot be specified multiple times"
checkPackageDbStackPost76 _ = return ()

checkPackageDbStackPre76 :: PackageDBStack -> IO ()
checkPackageDbStackPre76 (GlobalPackageDB:rest)
  | GlobalPackageDB `notElem` rest = return ()
checkPackageDbStackPre76 rest
  | GlobalPackageDB `notElem` rest =
  die $ "With current ghc versions the global package db is always used "
     ++ "and must be listed first. This ghc limitation is lifted in GHC 7.6,"
     ++ "see http://hackage.haskell.org/trac/ghc/ticket/5977"
checkPackageDbStackPre76 _ =
  die $ "If the global package db is specified, it must be "
     ++ "specified first and cannot be specified multiple times"

-- GHC < 6.10 put "$topdir/include/mingw" in rts's installDirs. This
-- breaks when you want to use a different gcc, so we need to filter
-- it out.
removeMingwIncludeDir :: InstalledPackageInfo -> InstalledPackageInfo
removeMingwIncludeDir pkg =
    let ids = InstalledPackageInfo.includeDirs pkg
        ids' = filter (not . ("mingw" `isSuffixOf`)) ids
    in pkg { InstalledPackageInfo.includeDirs = ids' }

-- | Get the packages from specific PackageDBs, not cumulative.
--
getInstalledPackages' :: Verbosity -> [PackageDB] -> ProgramConfiguration
                     -> IO [(PackageDB, [InstalledPackageInfo])]
getInstalledPackages' verbosity packagedbs conf
  | ghcVersion >= Version [6,9] [] =
  sequence
    [ do pkgs <- HcPkg.dump (hcPkgInfo conf) verbosity packagedb
         return (packagedb, pkgs)
    | packagedb <- packagedbs ]

  where
    Just ghcProg    = lookupProgram ghcProgram conf
    Just ghcVersion = programVersion ghcProg

getInstalledPackages' verbosity packagedbs conf = do
    str <- rawSystemProgramStdoutConf verbosity ghcPkgProgram conf ["list"]
    let pkgFiles = [ init line | line <- lines str, last line == ':' ]
        dbFile packagedb = case (packagedb, pkgFiles) of
          (GlobalPackageDB, global:_)      -> return $ Just global
          (UserPackageDB,  _global:user:_) -> return $ Just user
          (UserPackageDB,  _global:_)      -> return $ Nothing
          (SpecificPackageDB specific, _)  -> return $ Just specific
          _ -> die "cannot read ghc-pkg package listing"
    pkgFiles' <- mapM dbFile packagedbs
    sequence [ withFileContents file $ \content -> do
                  pkgs <- readPackages file content
                  return (db, pkgs)
             | (db , Just file) <- zip packagedbs pkgFiles' ]
  where
    -- Depending on the version of ghc we use a different type's Read
    -- instance to parse the package file and then convert.
    -- It's a bit yuck. But that's what we get for using Read/Show.
    readPackages
      | ghcVersion >= Version [6,4,2] []
      = \file content -> case reads content of
          [(pkgs, _)] -> return (map IPI642.toCurrent pkgs)
          _           -> failToRead file
      | otherwise
      = \file content -> case reads content of
          [(pkgs, _)] -> return (map IPI641.toCurrent pkgs)
          _           -> failToRead file
    Just ghcProg = lookupProgram ghcProgram conf
    Just ghcVersion = programVersion ghcProg
    failToRead file = die $ "cannot read ghc package database " ++ file

-- -----------------------------------------------------------------------------
-- Building

-- | Build a library with GHC.
--
buildLib, replLib :: Verbosity          -> Cabal.Flag (Maybe Int)
                  -> PackageDescription -> LocalBuildInfo
                  -> Library            -> ComponentLocalBuildInfo -> IO ()
buildLib = buildOrReplLib False
replLib  = buildOrReplLib True

buildOrReplLib :: Bool -> Verbosity  -> Cabal.Flag (Maybe Int)
               -> PackageDescription -> LocalBuildInfo
               -> Library            -> ComponentLocalBuildInfo -> IO ()
buildOrReplLib forRepl verbosity numJobs pkg_descr lbi lib clbi = do
  let libName = componentId clbi
      libTargetDir = buildDir lbi
      whenVanillaLib forceVanilla =
        when (forceVanilla || withVanillaLib lbi)
      whenProfLib = when (withProfLib lbi)
      whenSharedLib forceShared =
        when (forceShared || withSharedLib lbi)
      whenGHCiLib = when (withGHCiLib lbi && withVanillaLib lbi)
      ifReplLib = when forRepl
      comp = compiler lbi
      ghcVersion = compilerVersion comp
      implInfo  = getImplInfo comp
      (Platform _hostArch hostOS) = hostPlatform lbi

  (ghcProg, _) <- requireProgram verbosity ghcProgram (withPrograms lbi)
  let runGhcProg = runGHC verbosity ghcProg comp

  libBi <- hackThreadedFlag verbosity
             comp (withProfLib lbi) (libBuildInfo lib)

  let isGhcDynamic        = isDynamic comp
      dynamicTooSupported = supportsDynamicToo comp
      doingTH = EnableExtension TemplateHaskell `elem` allExtensions libBi
      forceVanillaLib = doingTH && not isGhcDynamic
      forceSharedLib  = doingTH &&     isGhcDynamic
      -- TH always needs default libs, even when building for profiling

  -- Determine if program coverage should be enabled and if so, what
  -- '-hpcdir' should be.
  let isCoverageEnabled = fromFlag $ configCoverage $ configFlags lbi
      -- Component name. Not 'libName' because that has the "HS" prefix
      -- that GHC gives Haskell libraries.
      cname = display $ PD.package $ localPkgDescr lbi
      distPref = fromFlag $ configDistPref $ configFlags lbi
      hpcdir way
        | forRepl = mempty  -- HPC is not supported in ghci
        | isCoverageEnabled = toFlag $ Hpc.mixDir distPref way cname
        | otherwise = mempty

  createDirectoryIfMissingVerbose verbosity True libTargetDir
  -- TODO: do we need to put hs-boot files into place for mutually recursive
  -- modules?
  let cObjs       = map (`replaceExtension` objExtension) (cSources libBi)
      baseOpts    = componentGhcOptions verbosity lbi libBi clbi libTargetDir
      vanillaOpts = baseOpts `mappend` mempty {
                      ghcOptMode         = toFlag GhcModeMake,
                      ghcOptNumJobs      = numJobs,
                      ghcOptInputModules = toNubListR $ libModules lib,
                      ghcOptHPCDir       = hpcdir Hpc.Vanilla
                    }

      profOpts    = vanillaOpts `mappend` mempty {
                      ghcOptProfilingMode = toFlag True,
                      ghcOptProfilingAuto = Internal.profDetailLevelFlag True
                                              (withProfLibDetail lbi),
                      ghcOptHiSuffix      = toFlag "p_hi",
                      ghcOptObjSuffix     = toFlag "p_o",
                      ghcOptExtra         = toNubListR $ hcProfOptions GHC libBi,
                      ghcOptHPCDir        = hpcdir Hpc.Prof
                    }

      sharedOpts  = vanillaOpts `mappend` mempty {
                      ghcOptDynLinkMode = toFlag GhcDynamicOnly,
                      ghcOptFPic        = toFlag True,
                      ghcOptHiSuffix    = toFlag "dyn_hi",
                      ghcOptObjSuffix   = toFlag "dyn_o",
                      ghcOptExtra       = toNubListR $ hcSharedOptions GHC libBi,
                      ghcOptHPCDir      = hpcdir Hpc.Dyn
                    }
      linkerOpts = mempty {
                      ghcOptLinkOptions    = toNubListR $ PD.ldOptions libBi,
                      ghcOptLinkLibs       = toNubListR $ extraLibs libBi,
                      ghcOptLinkLibPath    = toNubListR $ extraLibDirs libBi,
                      ghcOptLinkFrameworks = toNubListR $ PD.frameworks libBi,
                      ghcOptInputFiles     = toNubListR
                                             [libTargetDir </> x | x <- cObjs]
                   }
      replOpts    = vanillaOpts {
                      ghcOptExtra        = overNubListR
                                           Internal.filterGhciFlags $
                                           (ghcOptExtra vanillaOpts),
                      ghcOptNumJobs      = mempty
                    }
                    `mappend` linkerOpts
                    `mappend` mempty {
                      ghcOptMode         = toFlag GhcModeInteractive,
                      ghcOptOptimisation = toFlag GhcNoOptimisation
                    }

      vanillaSharedOpts = vanillaOpts `mappend` mempty {
                      ghcOptDynLinkMode  = toFlag GhcStaticAndDynamic,
                      ghcOptDynHiSuffix  = toFlag "dyn_hi",
                      ghcOptDynObjSuffix = toFlag "dyn_o",
                      ghcOptHPCDir       = hpcdir Hpc.Dyn
                    }

  unless (forRepl || null (libModules lib)) $
    do let vanilla = whenVanillaLib forceVanillaLib (runGhcProg vanillaOpts)
           shared  = whenSharedLib  forceSharedLib  (runGhcProg sharedOpts)
           useDynToo = dynamicTooSupported &&
                       (forceVanillaLib || withVanillaLib lbi) &&
                       (forceSharedLib  || withSharedLib  lbi) &&
                       null (hcSharedOptions GHC libBi)
       if useDynToo
          then do
              runGhcProg vanillaSharedOpts
              case (hpcdir Hpc.Dyn, hpcdir Hpc.Vanilla) of
                (Cabal.Flag dynDir, Cabal.Flag vanillaDir) -> do
                    -- When the vanilla and shared library builds are done
                    -- in one pass, only one set of HPC module interfaces
                    -- are generated. This set should suffice for both
                    -- static and dynamically linked executables. We copy
                    -- the modules interfaces so they are available under
                    -- both ways.
                    copyDirectoryRecursive verbosity dynDir vanillaDir
                _ -> return ()
          else if isGhcDynamic
            then do shared;  vanilla
            else do vanilla; shared
       whenProfLib (runGhcProg profOpts)

  -- build any C sources
  unless (null (cSources libBi)) $ do
    info verbosity "Building C Sources..."
    sequence_
      [ do let baseCcOpts    = Internal.componentCcGhcOptions verbosity implInfo
                               lbi libBi clbi libTargetDir filename
               vanillaCcOpts = if isGhcDynamic
                               -- Dynamic GHC requires C sources to be built
                               -- with -fPIC for REPL to work. See #2207.
                               then baseCcOpts { ghcOptFPic = toFlag True }
                               else baseCcOpts
               profCcOpts    = vanillaCcOpts `mappend` mempty {
                                 ghcOptProfilingMode = toFlag True,
                                 ghcOptObjSuffix     = toFlag "p_o"
                               }
               sharedCcOpts  = vanillaCcOpts `mappend` mempty {
                                 ghcOptFPic        = toFlag True,
                                 ghcOptDynLinkMode = toFlag GhcDynamicOnly,
                                 ghcOptObjSuffix   = toFlag "dyn_o"
                               }
               odir          = fromFlag (ghcOptObjDir vanillaCcOpts)
           createDirectoryIfMissingVerbose verbosity True odir
           needsRecomp <- checkNeedsRecompilation filename vanillaCcOpts
           when needsRecomp $ do
               runGhcProg vanillaCcOpts
               unless forRepl $
                 whenSharedLib forceSharedLib (runGhcProg sharedCcOpts)
               unless forRepl $ whenProfLib (runGhcProg profCcOpts)
      | filename <- cSources libBi]

  -- TODO: problem here is we need the .c files built first, so we can load them
  -- with ghci, but .c files can depend on .h files generated by ghc by ffi
  -- exports.

  ifReplLib $ do
    when (null (libModules lib)) $ warn verbosity "No exposed modules"
    ifReplLib (runGhcProg replOpts)

  -- link:
  unless forRepl $ do
    info verbosity "Linking..."
    let cProfObjs   = map (`replaceExtension` ("p_" ++ objExtension))
                      (cSources libBi)
        cSharedObjs = map (`replaceExtension` ("dyn_" ++ objExtension))
                      (cSources libBi)
        cid = compilerId (compiler lbi)
        vanillaLibFilePath = libTargetDir </> mkLibName           libName
        profileLibFilePath = libTargetDir </> mkProfLibName       libName
        sharedLibFilePath  = libTargetDir </> mkSharedLibName cid libName
        ghciLibFilePath    = libTargetDir </> Internal.mkGHCiLibName libName
        libInstallPath = libdir $ absoluteInstallDirs pkg_descr lbi NoCopyDest
        sharedLibInstallPath = libInstallPath </> mkSharedLibName cid libName

    stubObjs <- fmap catMaybes $ sequence
      [ findFileWithExtension [objExtension] [libTargetDir]
          (ModuleName.toFilePath x ++"_stub")
      | ghcVersion < Version [7,2] [] -- ghc-7.2+ does not make _stub.o files
      , x <- libModules lib ]
    stubProfObjs <- fmap catMaybes $ sequence
      [ findFileWithExtension ["p_" ++ objExtension] [libTargetDir]
          (ModuleName.toFilePath x ++"_stub")
      | ghcVersion < Version [7,2] [] -- ghc-7.2+ does not make _stub.o files
      , x <- libModules lib ]
    stubSharedObjs <- fmap catMaybes $ sequence
      [ findFileWithExtension ["dyn_" ++ objExtension] [libTargetDir]
          (ModuleName.toFilePath x ++"_stub")
      | ghcVersion < Version [7,2] [] -- ghc-7.2+ does not make _stub.o files
      , x <- libModules lib ]

    hObjs     <- Internal.getHaskellObjects implInfo lib lbi
                      libTargetDir objExtension True
    hProfObjs <-
      if (withProfLib lbi)
              then Internal.getHaskellObjects implInfo lib lbi
                      libTargetDir ("p_" ++ objExtension) True
              else return []
    hSharedObjs <-
      if (withSharedLib lbi)
              then Internal.getHaskellObjects implInfo lib lbi
                      libTargetDir ("dyn_" ++ objExtension) False
              else return []

    unless (null hObjs && null cObjs && null stubObjs) $ do
      rpaths <- getRPaths lbi clbi

      let staticObjectFiles =
                 hObjs
              ++ map (libTargetDir </>) cObjs
              ++ stubObjs
          profObjectFiles =
                 hProfObjs
              ++ map (libTargetDir </>) cProfObjs
              ++ stubProfObjs
          ghciObjFiles =
                 hObjs
              ++ map (libTargetDir </>) cObjs
              ++ stubObjs
          dynamicObjectFiles =
                 hSharedObjs
              ++ map (libTargetDir </>) cSharedObjs
              ++ stubSharedObjs
          -- After the relocation lib is created we invoke ghc -shared
          -- with the dependencies spelled out as -package arguments
          -- and ghc invokes the linker with the proper library paths
          ghcSharedLinkArgs =
              mempty {
                ghcOptShared             = toFlag True,
                ghcOptDynLinkMode        = toFlag GhcDynamicOnly,
                ghcOptInputFiles         = toNubListR dynamicObjectFiles,
                ghcOptOutputFile         = toFlag sharedLibFilePath,
                -- For dynamic libs, Mac OS/X needs to know the install location
                -- at build time. This only applies to GHC < 7.8 - see the
                -- discussion in #1660.
                ghcOptDylibName          = if (hostOS == OSX
                                               && ghcVersion < Version [7,8] [])
                                            then toFlag sharedLibInstallPath
                                            else mempty,
                ghcOptNoAutoLinkPackages = toFlag True,
                ghcOptPackageDBs         = withPackageDB lbi,
                ghcOptPackages           = toNubListR $
                                           Internal.mkGhcOptPackages clbi ,
                ghcOptLinkLibs           = toNubListR $ extraLibs libBi,
                ghcOptLinkLibPath        = toNubListR $ extraLibDirs libBi,
                ghcOptLinkFrameworks     = toNubListR $ PD.frameworks libBi,
                ghcOptRPaths             = rpaths
              }

      info verbosity (show (ghcOptPackages ghcSharedLinkArgs))

      whenVanillaLib False $ do
        Ar.createArLibArchive verbosity lbi vanillaLibFilePath staticObjectFiles

      whenProfLib $ do
        Ar.createArLibArchive verbosity lbi profileLibFilePath profObjectFiles

      whenGHCiLib $ do
        (ldProg, _) <- requireProgram verbosity ldProgram (withPrograms lbi)
        Ld.combineObjectFiles verbosity ldProg
          ghciLibFilePath ghciObjFiles

      whenSharedLib False $
        runGhcProg ghcSharedLinkArgs

-- | Start a REPL without loading any source files.
startInterpreter :: Verbosity -> ProgramConfiguration -> Compiler
                 -> PackageDBStack -> IO ()
startInterpreter verbosity conf comp packageDBs = do
  let replOpts = mempty {
        ghcOptMode       = toFlag GhcModeInteractive,
        ghcOptPackageDBs = packageDBs
        }
  checkPackageDbStack comp packageDBs
  (ghcProg, _) <- requireProgram verbosity ghcProgram conf
  runGHC verbosity ghcProg comp replOpts

-- | Build an executable with GHC.
--
buildExe, replExe :: Verbosity          -> Cabal.Flag (Maybe Int)
                  -> PackageDescription -> LocalBuildInfo
                  -> Executable         -> ComponentLocalBuildInfo -> IO ()
buildExe = buildOrReplExe False
replExe  = buildOrReplExe True

buildOrReplExe :: Bool -> Verbosity  -> Cabal.Flag (Maybe Int)
               -> PackageDescription -> LocalBuildInfo
               -> Executable         -> ComponentLocalBuildInfo -> IO ()
buildOrReplExe forRepl verbosity numJobs _pkg_descr lbi
  exe@Executable { exeName = exeName', modulePath = modPath } clbi = do

  (ghcProg, _) <- requireProgram verbosity ghcProgram (withPrograms lbi)
  let comp       = compiler lbi
      implInfo   = getImplInfo comp
      runGhcProg = runGHC verbosity ghcProg comp

  exeBi <- hackThreadedFlag verbosity
             comp (withProfExe lbi) (buildInfo exe)

  -- exeNameReal, the name that GHC really uses (with .exe on Windows)
  let exeNameReal = exeName' <.>
                    (if takeExtension exeName' /= ('.':exeExtension)
                       then exeExtension
                       else "")

  let targetDir = (buildDir lbi) </> exeName'
  let exeDir    = targetDir </> (exeName' ++ "-tmp")
  createDirectoryIfMissingVerbose verbosity True targetDir
  createDirectoryIfMissingVerbose verbosity True exeDir
  -- TODO: do we need to put hs-boot files into place for mutually recursive
  -- modules?  FIX: what about exeName.hi-boot?

  -- Determine if program coverage should be enabled and if so, what
  -- '-hpcdir' should be.
  let isCoverageEnabled = fromFlag $ configCoverage $ configFlags lbi
      distPref = fromFlag $ configDistPref $ configFlags lbi
      hpcdir way
        | forRepl = mempty  -- HPC is not supported in ghci
        | isCoverageEnabled = toFlag $ Hpc.mixDir distPref way exeName'
        | otherwise = mempty

  -- build executables

  srcMainFile         <- findFile (exeDir : hsSourceDirs exeBi) modPath
  rpaths              <- getRPaths lbi clbi

  let isGhcDynamic        = isDynamic comp
      dynamicTooSupported = supportsDynamicToo comp
      isHaskellMain = elem (takeExtension srcMainFile) [".hs", ".lhs"]
      cSrcs         = cSources exeBi ++ [srcMainFile | not isHaskellMain]
      cObjs         = map (`replaceExtension` objExtension) cSrcs
      baseOpts   = (componentGhcOptions verbosity lbi exeBi clbi exeDir)
                    `mappend` mempty {
                      ghcOptMode         = toFlag GhcModeMake,
                      ghcOptInputFiles   = toNubListR
                        [ srcMainFile | isHaskellMain],
                      ghcOptInputModules = toNubListR
                        [ m | not isHaskellMain, m <- exeModules exe]
                    }
      staticOpts = baseOpts `mappend` mempty {
                      ghcOptDynLinkMode    = toFlag GhcStaticOnly,
                      ghcOptHPCDir         = hpcdir Hpc.Vanilla
                   }
      profOpts   = baseOpts `mappend` mempty {
                      ghcOptProfilingMode  = toFlag True,
                      ghcOptProfilingAuto  = Internal.profDetailLevelFlag False
                                               (withProfExeDetail lbi),
                      ghcOptHiSuffix       = toFlag "p_hi",
                      ghcOptObjSuffix      = toFlag "p_o",
                      ghcOptExtra          = toNubListR (hcProfOptions GHC exeBi),
                      ghcOptHPCDir         = hpcdir Hpc.Prof
                    }
      dynOpts    = baseOpts `mappend` mempty {
                      ghcOptDynLinkMode    = toFlag GhcDynamicOnly,
                      ghcOptHiSuffix       = toFlag "dyn_hi",
                      ghcOptObjSuffix      = toFlag "dyn_o",
                      ghcOptExtra          = toNubListR $
                                             hcSharedOptions GHC exeBi,
                      ghcOptHPCDir         = hpcdir Hpc.Dyn
                    }
      dynTooOpts = staticOpts `mappend` mempty {
                      ghcOptDynLinkMode    = toFlag GhcStaticAndDynamic,
                      ghcOptDynHiSuffix    = toFlag "dyn_hi",
                      ghcOptDynObjSuffix   = toFlag "dyn_o",
                      ghcOptHPCDir         = hpcdir Hpc.Dyn
                    }
      linkerOpts = mempty {
                      ghcOptLinkOptions    = toNubListR $ PD.ldOptions exeBi,
                      ghcOptLinkLibs       = toNubListR $ extraLibs exeBi,
                      ghcOptLinkLibPath    = toNubListR $ extraLibDirs exeBi,
                      ghcOptLinkFrameworks = toNubListR $ PD.frameworks exeBi,
                      ghcOptInputFiles     = toNubListR
                                             [exeDir </> x | x <- cObjs]
                    }
      dynLinkerOpts = mempty {
                      ghcOptRPaths         = rpaths
                   }
      replOpts   = baseOpts {
                      ghcOptExtra          = overNubListR
                                             Internal.filterGhciFlags
                                             (ghcOptExtra baseOpts)
                   }
                   -- For a normal compile we do separate invocations of ghc for
                   -- compiling as for linking. But for repl we have to do just
                   -- the one invocation, so that one has to include all the
                   -- linker stuff too, like -l flags and any .o files from C
                   -- files etc.
                   `mappend` linkerOpts
                   `mappend` mempty {
                      ghcOptMode           = toFlag GhcModeInteractive,
                      ghcOptOptimisation   = toFlag GhcNoOptimisation
                   }
      commonOpts  | withProfExe lbi = profOpts
                  | withDynExe  lbi = dynOpts
                  | otherwise       = staticOpts
      compileOpts | useDynToo = dynTooOpts
                  | otherwise = commonOpts
      withStaticExe = (not $ withProfExe lbi) && (not $ withDynExe lbi)

      -- For building exe's that use TH with -prof or -dynamic we actually have
      -- to build twice, once without -prof/-dynamic and then again with
      -- -prof/-dynamic. This is because the code that TH needs to run at
      -- compile time needs to be the vanilla ABI so it can be loaded up and run
      -- by the compiler.
      -- With dynamic-by-default GHC the TH object files loaded at compile-time
      -- need to be .dyn_o instead of .o.
      doingTH = EnableExtension TemplateHaskell `elem` allExtensions exeBi
      -- Should we use -dynamic-too instead of compiling twice?
      useDynToo = dynamicTooSupported && isGhcDynamic
                  && doingTH && withStaticExe
                  && null (hcSharedOptions GHC exeBi)
      compileTHOpts | isGhcDynamic = dynOpts
                    | otherwise    = staticOpts
      compileForTH
        | forRepl      = False
        | useDynToo    = False
        | isGhcDynamic = doingTH && (withProfExe lbi || withStaticExe)
        | otherwise    = doingTH && (withProfExe lbi || withDynExe lbi)

      linkOpts = commonOpts `mappend`
                 linkerOpts `mappend`
                 mempty { ghcOptLinkNoHsMain   = toFlag (not isHaskellMain) } `mappend`
                 (if withDynExe lbi then dynLinkerOpts else mempty)

  -- Build static/dynamic object files for TH, if needed.
  when compileForTH $
    runGhcProg compileTHOpts { ghcOptNoLink  = toFlag True
                             , ghcOptNumJobs = numJobs }

  unless forRepl $
    runGhcProg compileOpts { ghcOptNoLink  = toFlag True
                           , ghcOptNumJobs = numJobs }

  -- build any C sources
  unless (null cSrcs) $ do
   info verbosity "Building C Sources..."
   sequence_
     [ do let opts = (Internal.componentCcGhcOptions verbosity implInfo lbi exeBi
                         clbi exeDir filename) `mappend` mempty {
                       ghcOptDynLinkMode   = toFlag (if withDynExe lbi
                                                       then GhcDynamicOnly
                                                       else GhcStaticOnly),
                       ghcOptProfilingMode = toFlag (withProfExe lbi)
                     }
              odir  = fromFlag (ghcOptObjDir opts)
          createDirectoryIfMissingVerbose verbosity True odir
          needsRecomp <- checkNeedsRecompilation filename opts
          when needsRecomp $
            runGhcProg opts
     | filename <- cSrcs ]

  -- TODO: problem here is we need the .c files built first, so we can load them
  -- with ghci, but .c files can depend on .h files generated by ghc by ffi
  -- exports.
  when forRepl $ runGhcProg replOpts

  -- link:
  unless forRepl $ do
    info verbosity "Linking..."
    runGhcProg linkOpts { ghcOptOutputFile = toFlag (targetDir </> exeNameReal) }

-- | Returns True if the modification date of the given source file is newer than
-- the object file we last compiled for it, or if no object file exists yet.
checkNeedsRecompilation :: FilePath -> GhcOptions -> IO Bool
checkNeedsRecompilation filename opts = filename `moreRecentFile` oname
    where oname = getObjectFileName filename opts

-- | Finds the object file name of the given source file
getObjectFileName :: FilePath -> GhcOptions -> FilePath
getObjectFileName filename opts = oname
    where odir  = fromFlag (ghcOptObjDir opts)
          oext  = fromFlagOrDefault "o" (ghcOptObjSuffix opts)
          oname = odir </> replaceExtension filename oext

-- | Calculate the RPATHs for the component we are building.
--
-- Calculates relative RPATHs when 'relocatable' is set.
getRPaths :: LocalBuildInfo
          -> ComponentLocalBuildInfo -- ^ Component we are building
          -> IO (NubListR FilePath)
getRPaths lbi clbi | supportRPaths hostOS = do
    libraryPaths <- depLibraryPaths False (relocatable lbi) lbi clbi
    let hostPref = case hostOS of
                     OSX -> "@loader_path"
                     _   -> "$ORIGIN"
        relPath p = if isRelative p then hostPref </> p else p
        rpaths    = toNubListR (map relPath libraryPaths)
    return rpaths
  where
    (Platform _ hostOS) = hostPlatform lbi

    -- The list of RPath-supported operating systems below reflects the
    -- platforms on which Cabal's RPATH handling is tested. It does _NOT_
    -- reflect whether the OS supports RPATH.

    -- E.g. when this comment was written, the *BSD operating systems were
    -- untested with regards to Cabal RPATH handling, and were hence set to
    -- 'False', while those operating systems themselves do support RPATH.
    supportRPaths Linux       = True
    supportRPaths Windows     = False
    supportRPaths OSX         = True
    supportRPaths FreeBSD     = False
    supportRPaths OpenBSD     = False
    supportRPaths NetBSD      = False
    supportRPaths DragonFly   = False
    supportRPaths Solaris     = False
    supportRPaths AIX         = False
    supportRPaths HPUX        = False
    supportRPaths IRIX        = False
    supportRPaths HaLVM       = False
    supportRPaths IOS         = False
    supportRPaths Android     = False
    supportRPaths Ghcjs       = False
    supportRPaths Hurd        = False
    supportRPaths (OtherOS _) = False
    -- Do _not_ add a default case so that we get a warning here when a new OS
    -- is added.

getRPaths _ _ = return mempty

-- | Filter the "-threaded" flag when profiling as it does not
--   work with ghc-6.8 and older.
hackThreadedFlag :: Verbosity -> Compiler -> Bool -> BuildInfo -> IO BuildInfo
hackThreadedFlag verbosity comp prof bi
  | not mustFilterThreaded = return bi
  | otherwise              = do
    warn verbosity $ "The ghc flag '-threaded' is not compatible with "
                  ++ "profiling in ghc-6.8 and older. It will be disabled."
    return bi { options = filterHcOptions (/= "-threaded") (options bi) }
  where
    mustFilterThreaded = prof && compilerVersion comp < Version [6, 10] []
                      && "-threaded" `elem` hcOptions GHC bi
    filterHcOptions p hcoptss =
      [ (hc, if hc == GHC then filter p opts else opts)
      | (hc, opts) <- hcoptss ]

-- | Extracts a String representing a hash of the ABI of a built
-- library.  It can fail if the library has not yet been built.
--
libAbiHash :: Verbosity -> PackageDescription -> LocalBuildInfo
           -> Library -> ComponentLocalBuildInfo -> IO String
libAbiHash verbosity _pkg_descr lbi lib clbi = do
  libBi <- hackThreadedFlag verbosity
             (compiler lbi) (withProfLib lbi) (libBuildInfo lib)
  let
      comp        = compiler lbi
      vanillaArgs =
        (componentGhcOptions verbosity lbi libBi clbi (buildDir lbi))
        `mappend` mempty {
          ghcOptMode         = toFlag GhcModeAbiHash,
          ghcOptInputModules = toNubListR $ exposedModules lib
        }
      sharedArgs = vanillaArgs `mappend` mempty {
                       ghcOptDynLinkMode = toFlag GhcDynamicOnly,
                       ghcOptFPic        = toFlag True,
                       ghcOptHiSuffix    = toFlag "dyn_hi",
                       ghcOptObjSuffix   = toFlag "dyn_o",
                       ghcOptExtra       = toNubListR $ hcSharedOptions GHC libBi
                   }
      profArgs   = vanillaArgs `mappend` mempty {
                     ghcOptProfilingMode = toFlag True,
                     ghcOptProfilingAuto = Internal.profDetailLevelFlag True
                                             (withProfLibDetail lbi),
                     ghcOptHiSuffix      = toFlag "p_hi",
                     ghcOptObjSuffix     = toFlag "p_o",
                     ghcOptExtra         = toNubListR $ hcProfOptions GHC libBi
                   }
      ghcArgs = if withVanillaLib lbi then vanillaArgs
           else if withSharedLib  lbi then sharedArgs
           else if withProfLib    lbi then profArgs
           else error "libAbiHash: Can't find an enabled library way"
  --
  (ghcProg, _) <- requireProgram verbosity ghcProgram (withPrograms lbi)
  hash <- getProgramInvocationOutput verbosity
          (ghcInvocation ghcProg comp ghcArgs)
  return (takeWhile (not . isSpace) hash)

componentGhcOptions :: Verbosity -> LocalBuildInfo
                    -> BuildInfo -> ComponentLocalBuildInfo -> FilePath
                    -> GhcOptions
componentGhcOptions = Internal.componentGhcOptions

componentCcGhcOptions :: Verbosity -> LocalBuildInfo
                      -> BuildInfo -> ComponentLocalBuildInfo
                      -> FilePath -> FilePath
                      -> GhcOptions
componentCcGhcOptions verbosity lbi =
    Internal.componentCcGhcOptions verbosity implInfo lbi
  where
    comp     = compiler lbi
    implInfo = getImplInfo comp

-- -----------------------------------------------------------------------------
-- Installing

-- |Install executables for GHC.
installExe :: Verbosity
           -> LocalBuildInfo
           -> InstallDirs FilePath -- ^Where to copy the files to
           -> FilePath  -- ^Build location
           -> (FilePath, FilePath)  -- ^Executable (prefix,suffix)
           -> PackageDescription
           -> Executable
           -> IO ()
installExe verbosity lbi installDirs buildPref
  (progprefix, progsuffix) _pkg exe = do
  let binDir = bindir installDirs
  createDirectoryIfMissingVerbose verbosity True binDir
  let exeFileName = exeName exe <.> exeExtension
      fixedExeBaseName = progprefix ++ exeName exe ++ progsuffix
      installBinary dest = do
          installExecutableFile verbosity
            (buildPref </> exeName exe </> exeFileName)
            (dest <.> exeExtension)
          when (stripExes lbi) $
            Strip.stripExe verbosity (hostPlatform lbi) (withPrograms lbi)
                           (dest <.> exeExtension)
  installBinary (binDir </> fixedExeBaseName)

-- |Install for ghc, .hi, .a and, if --with-ghci given, .o
installLib    :: Verbosity
              -> LocalBuildInfo
              -> FilePath  -- ^install location
              -> FilePath  -- ^install location for dynamic libraries
              -> FilePath  -- ^Build location
              -> PackageDescription
              -> Library
              -> ComponentLocalBuildInfo
              -> IO ()
installLib verbosity lbi targetDir dynlibTargetDir builtDir _pkg lib clbi = do
  -- copy .hi files over:
  whenVanilla $ copyModuleFiles "hi"
  whenProf    $ copyModuleFiles "p_hi"
  whenShared  $ copyModuleFiles "dyn_hi"

  -- copy the built library files over:
  whenVanilla $ installOrdinary builtDir targetDir       vanillaLibName
  whenProf    $ installOrdinary builtDir targetDir       profileLibName
  whenGHCi    $ installOrdinary builtDir targetDir       ghciLibName
  whenShared  $ installShared   builtDir dynlibTargetDir sharedLibName

  where
    install isShared srcDir dstDir name = do
      let src = srcDir </> name
          dst = dstDir </> name
      createDirectoryIfMissingVerbose verbosity True dstDir

      if isShared
        then installExecutableFile verbosity src dst
        else installOrdinaryFile   verbosity src dst

      when (stripLibs lbi) $ Strip.stripLib verbosity
                             (hostPlatform lbi) (withPrograms lbi) dst

    installOrdinary = install False
    installShared   = install True

    copyModuleFiles ext =
      findModuleFiles [builtDir] [ext] (libModules lib)
      >>= installOrdinaryFiles verbosity targetDir

    cid = compilerId (compiler lbi)
    libName = componentId clbi
    vanillaLibName = mkLibName              libName
    profileLibName = mkProfLibName          libName
    ghciLibName    = Internal.mkGHCiLibName libName
    sharedLibName  = (mkSharedLibName cid)  libName

    hasLib    = not $ null (libModules lib)
                   && null (cSources (libBuildInfo lib))
    whenVanilla = when (hasLib && withVanillaLib lbi)
    whenProf    = when (hasLib && withProfLib    lbi)
    whenGHCi    = when (hasLib && withGHCiLib    lbi)
    whenShared  = when (hasLib && withSharedLib  lbi)

-- -----------------------------------------------------------------------------
-- Registering

hcPkgInfo :: ProgramConfiguration -> HcPkg.HcPkgInfo
hcPkgInfo conf = HcPkg.HcPkgInfo { HcPkg.hcPkgProgram    = ghcPkgProg
                                 , HcPkg.noPkgDbStack    = v < [6,9]
                                 , HcPkg.noVerboseFlag   = v < [6,11]
                                 , HcPkg.flagPackageConf = v < [7,5]
                                 , HcPkg.useSingleFileDb = v < [7,9]
                                 }
  where
    v               = versionBranch ver
    Just ghcPkgProg = lookupProgram ghcPkgProgram conf
    Just ver        = programVersion ghcPkgProg

registerPackage
  :: Verbosity
  -> InstalledPackageInfo
  -> PackageDescription
  -> LocalBuildInfo
  -> Bool
  -> PackageDBStack
  -> IO ()
registerPackage verbosity installedPkgInfo _pkg lbi _inplace packageDbs =
  HcPkg.reregister (hcPkgInfo $ withPrograms lbi) verbosity
    packageDbs (Right installedPkgInfo)

pkgRoot :: Verbosity -> LocalBuildInfo -> PackageDB -> IO FilePath
pkgRoot verbosity lbi = pkgRoot'
   where
    pkgRoot' GlobalPackageDB =
      let Just ghcProg = lookupProgram ghcProgram (withPrograms lbi)
      in  fmap takeDirectory (getGlobalPackageDB verbosity ghcProg)
    pkgRoot' UserPackageDB = do
      appDir <- getAppUserDataDirectory "ghc"
      let ver      = compilerVersion (compiler lbi)
          subdir   = System.Info.arch ++ '-':System.Info.os
                     ++ '-':showVersion ver
          rootDir  = appDir </> subdir
      -- We must create the root directory for the user package database if it
      -- does not yet exists. Otherwise '${pkgroot}' will resolve to a
      -- directory at the time of 'ghc-pkg register', and registration will
      -- fail.
      createDirectoryIfMissing True rootDir
      return rootDir
    pkgRoot' (SpecificPackageDB fp) = return (takeDirectory fp)

-- -----------------------------------------------------------------------------
-- Utils

isDynamic :: Compiler -> Bool
isDynamic = Internal.ghcLookupProperty "GHC Dynamic"

supportsDynamicToo :: Compiler -> Bool
supportsDynamicToo = Internal.ghcLookupProperty "Support dynamic-too"


[197 U.S. 178, 179] Messrs. Charles A. Douglass, Dupont Guerry, and Homer Guerry for appellant.
Messrs. Olin J. Wimberly and John I. Hall for appellee.
This is a bill in equity, brought in the circuit court by the appellee, the trust company, as mortgagee of the Dawson Waterworks Company, to restrain the city of Dawson from taking measures to build a new set of waterworks, and to compel it specifically to perform a contract made with the waterworks company in 1890, to pay that company or its mortgagee a certain sum for the use of its water for twenty years. The trust company is a Pennsylvania corporation, and the only ground of jurisdiction for the bill as originally filed was diversity of citizenship. The bill, after stating the contract, set up a formal repudiation of the same by the city on June 27, 1894, refusals to pay for the water from that time, and attempts to collect taxes which, by the contract, were to be satisfied by the furnishing of water, but alleged a continued use of the water by the city. It further stated the calling of an election for December 12, 1894, to see if the city should issue bonds to erect or buy waterworks or electric lights, a vote in favor of the issue, an issue of $10,000 for the erection of an electric-light plant, and a present intent to sell the residue for the purpose of erecting new waterworks. It also alleged that the waterworks company, recognizing the plaintiff's right to be paid the rentals for the water, in the events which had happened, which had made the waterworks [197 U.S. 178, 180] company unable to pay the interest on the mortgage, had yielded to the plaintiff's demand that it should collect the rentals, and that the plaintiff had notified the city, and had made demand, but that the city refused to pay. Other details are immaterial. The waterworks company was made a party defendant, and was served with process. An answer was served, although not filed, by the defendants other than the waterworks company, setting up among other things, that the waterworks company was the real plaintiff, and was made defendant solely to avoid the effect of a decision by the supreme court of the state in a suit by the waterworks company against the city, to the effect that the contract relied on was void. 106 Ga. 696, 32 S. E. 907. The answer, on this ground, denied the jurisdiction of the court. After service of this answer the bill was amended so as to allege that the acts of the city impaired the obligation of its contract, and deprived the plaintiff of its property without due process of law, contrary to the Constitution of the United States. A prayer was added, also, that the waterworks company be decreed to perform its contract with the city, that thereby the rights of bondholders might be saved. The further proceedings do not need mention. They ended in a decree in accordance with the prayer, and the city appealed to this court. Davis & F. Mfg. Co. v. Los Angeles, 189 U.S. 207, 216 , 47 S. L. ed. 778, 780, 23 Sup. Ct. Rep. 498.
We are of opinion that the bill should have been dismissed for want of jurisdiction. The waterworks company is admitted to have been a necessary party, and it, like the defendant city, was a Georgia corporation. It was made a defendant, but the court will look beyond the pleadings, and arrange the parties according to their sides in the dispute. When that is done, it is obvious that the waterworks company is on the plaintiff's side, and was made a defendant solely for the purpose of reopening, in the United States court, a controversy which had been decided against it in the courts of the state. There was a pretense of saking relief against it, as we have stated, but no foundation for the prayer was laid in the allegations [197 U.S. 178, 181] of the bill. On the contrary, it appears from those allegations that the waterworks company insisted on its contract with the city, and did everything in its power to carry the contract out. It also recognized the plaintiff's right to receive the rentals, and yielded to its demand. No difference or collision of interest or action is alleged or even suggested. If we assume that the plaintiff is more than an assignee of the city's contract to pay (which we do not intimate), still, when the arrangement of the parties is merely a contrivance between friends for the purpose of founding a jurisdiction which otherwise would not exist, the device cannot be allowed to succeed. See Removal Cases (Meyer v. Delaware R. Constr. Co. ), 100 U.S. 457, 469 , 25 S. L. ed. 593, 598; Hawes v. Oakland (Hawes v. Contra Costa Water Co.), 104 U.S. 450, 453 , 26 S. L. ed. 827, 829; Detroit v. Dean, 106 U.S. 537, 541 , 27 S. L. ed. 300, 302, 1 Sup. Ct. Rep. 560; Doctor v. Harrington, 196 U.S. 579 , ante, p. 355, 25 Sup. Ct. Rep. p. 355. Act March 3, 1875 (18 Stat. at L. 472, chap. 137, 5, U. S. Comp. Stat. 1901, p. 508).
The attempt, by an afterthought, to give jurisdiction by setting up constitutional rights, must fail also. The bill presents a naked case of breach of contract. The first step of the city was to repudiate the contract and to refuse to pay. Whatever it may have done subsequently, its wrong, if contrary to the decision of the supreme court of the state, there was a wrong, was complete then. The repudiation and refusal were kept up until the bill was filed, and the other acts were subsequent, subordinate to, and in aid of, them. The mere fact that the city was a municipal corporation does not give to its refusal the character of a law impairing the obligation of contracts, or deprive a citizen of property without due process of law. That point was decided in St. Paul Gaslight Co. v. St. Paul, 181 U.S. 142, 150 , 45 S. L. ed. 788, 792, 21 Sup. Ct. Rep. 575.
Undoubtedly the decisions on the two sides of the lines are very near to each other. But the case at bar is governed by the one which we have cited, and not by Walla Walla v. Walla Walla Water Co. 172 U.S. 1 , 43 L. ed. 341, 19 Sup. Ct. Rep. 77, which is cited and distinguished in St. Paul Gaslight Co. v. St. Paul. In Vicksburg Waterworks Co. v. Vicksburg, 185 U.S. 65 , 46 L. ed. 808, 22 Sup. Ct. Rep. 585, the city had made a contract with the waterworks company, and afterwards a [197 U.S. 178, 182] law was passed authorizing the city to build new works. The city, acting under this law, denied liability, and took steps to build the works, whereupon the waterworks company filed its bill, alleging the law to be unconstitutional. The bill was held to present a case under the Constitution. In the case before us there was no legislation subsequent to the contract, and it is not even shown that there is color of previous legislation for the city's acts. Those acts are alleged to be unlawful, and the allegation would be maintained by showing that they were not warranted by the laws of the state. See Hamilton Gaslight & Coke Co. v. Hamilton, 146 U.S. 258, 266 , 36 S. L. ed. 963, 967, 13 Sup. Ct. Rep. 90; Lehigh Water Co. v. Easton, 121 U.S. 388, 392 , 30 S. L. ed. 1059, 1060, 7 Sup. Ct. Rep. 916. We repeat that something more than a mere refusal of a municipal corporation to perform its contract is necessary to make a law impairing the obligation of contracts, or otherwise to give rise to a suit under the Constitution of the United States. The decree of the circuit court must be reversed, and the cause remanded with instructions to dismiss the bill. Newburyport Water Co. v. Newburyport, 193 U.S. 561, 576 , 48 S. L. ed. 795, 799, 24 Sup. Ct. Rep. 553.
Mr. Justice White, not having been present at the argument, took no part in the decision.


text:
package org.openalto.alto.client.wrapper;

import javax.ws.rs.client.Client;

import org.openalto.alto.common.resource.ResourceEntry;
import org.openalto.alto.common.resource.ResourceType;

import org.openalto.alto.client.ALTORequest;
import org.openalto.alto.client.ALTORequestBuilder;
import org.openalto.alto.client.ALTOResponseParser;

public class IRDRequestBuilder extends ALTORequestBuilder {

    public IRDRequestBuilder(Client client, ALTOResponseParser parser) {
        super(client, parser);
    }

    @Override
    public boolean canRequest(ResourceEntry entry) {
        if ((entry == null) || (entry.getType() == null))
            return false;
        return (entry.getType().equals(ResourceType.DIRECTORY_TYPE));
    }

    @Override
    public ALTORequest request(ResourceEntry resource, Object params) {
        return _request(resource, params, null);
    }
}

redpajama_set_name: RedPajamaGithub


This past Wednesday, SOJA released their latest single "Morning". This track was originally performed at the Arlington, Virginia based band's 2016 hometown show at Wolf Trap National Park for the Performing Arts, of which it's Live in Virginia album was nominated for a Grammy.
SOJA is a band that has always been known to ask all those questions that many don't dare ask while challenging political norms in the process. "Morning" with its lighthearted take on such topics, relates to those first thoughts when one wakes up, before the "busy-ness" of your day-to-day routine takes over.
As a long-time fan, I am pleased that this track made it to the studio with its throwback style to the band's beginnings. With their strong Brazilian fan base and their contribution to Puerto Rico, especially during its two devastating hurricanes, this song is on my list of favorites and another reason why they hold a special place in my heart.
Make sure to catch SOJA live as they perform this track and their many hits on their "Sing to Me" Spring and Summer Tour!
Omayra is a Florida girl, mother of three, and visual artist sharing all things art, fun and the beautiful things in life. She firmly believes that one creates their own reality and applies that to her own life by marching to the beat of a different drum, using her camera as a tool for that purpose. Omayra is a jack of all trades and masters them all. When she's not behind of the camera, she's in front of it. Her experience as a model, helped her develop her eye as a photographer.


Seattle, Wash.— Day three of the NTCA 2018 Fall Conference jumped right into Legal Seminar and telco and director track sessions.
NTCA CEO Shirley Bloomfield fielded questions and shared her insight with attendees on the high-cost Universal Service Fund, bringing broadband to rural America, leveraging the strengths of the communities telcos serve and bridging the gap between electric co-ops and telcos.
Curtis Strole, executive director, customer relations, NeoNova, showed us gadgets of the future. Gadgets already in development include clothes that detect medical issues and robotics for the assisted living. He stressed that through technological devices, we can work together to improve everyone's quality of life.
A panel of telecom experts, including Roger Goldblatt, FCC deputy bureau chief, Consumer and Governmental Affairs Bureau, advised that the best defense against robocalls is to use common sense. Simple tactics include not providing personal information to unknown callers, searching unknown phone numbers and encouraging carriers to be more vigilant.
Megan Brown, Attorney, Wiley Rein LLP, shared tips and strategies on managing cybersecurity issues and reporting obligations, as well as what to do when an attorney becomes the victim of hacking.
Day three concluded with the Networking Reception and Vendor Showcase.
Share your stories and experiences with us on social media by using hashtag #ntcafallconf.


"oh, look, i have only one coin..."
but they are very ballsy here!
"there are no small roles, only small actors"
"even the mail boy keeps the whole office working"
i keep thinking i see dead dogs.
it~s amazing what we can get used to.


Write down your goals in your goal section to refer back to.
Try to complete the core goals first before trying more advanced poses.
Poses are your goals, the shapes and lines that you want to achieve. Static stretches are pose preps, poses are basically more intense static stretches. Accordingly you can list static stretches as your goals.
Focus on these core goals first, than you can work on some of the more advanced poses.
4 sets of 30 seconds, about 10 deep breaths.
Alongside static stretches are techniques to help increase the effectiveness of a stretch. You may have heard of isometrics, PNF, passive, and/or resistance training, these are all helpful techniques to learn and apply. See more below.
To keep it simple here is what I do in a static stretch. Breath integrated with muscle contraction and relaxation.
Once proper form is achieved begin; Inhale and contract all of your muscles.
Exhale, relax muscles, and gently sink into the stretch.
Inhale, slightly come back out of the stretch, straighten or elongate necessary muscles and contract.
Exhale, relax muscles and gently sink into the stretch.
Repeat until you reach 10.
The main focus is to breath deep; the next major focus is form. No matter how flexible or inflexible you are it is important to work on form, which normally consists of elongating every limb, squaring hips, or slightly turning, twisting arms, and legs; all depending on the stretch.
When you achieve good form, squeezing or contracting all the muscles will build muscle memory, so when you are up in the air without gravity's assistance you will remember what good form feels like and which muscles need to be activated.
If you study the shapes you're imitating and then watch the shapes you are making, you will start to see the adjustments you need to make, this is also the invaluable part of having a coach or instructor.
Most of the static stretches are tutorials that you can click through to.
Pick 5-10 poses to focus on.
Hold each pose for 4 sets of 30 seconds, about 10 deep breaths.
Apply a technique to each pose hold.
Click on the link at the bottom of the picture, to go to the video tutorial or source page.
Click anywhere on the picture to view the image larger.
The pose guide is a place where we can all contribute our unique pose names and display them in the photo caption. Some of the photos have basic names to describe them.
These photos are fed from pinterest boards. To add your pose name simply visit the pinterest boards below and add a comment to the pose you'd like to add a name to.
Scorpion! I am a contortionist and my favourite move is the scorpion! I sit in this position to paint my nails! It is where you lay on your tummy and then roll your body over so that your feet are on top of your head! Look at a scorpion 🦂 picture. In that position, the scorpions tail is replaced by your legs only further forward.


text:
Q: mysql range query performance I have a simple MySQL table with 40000 rows:
id CHAR(36) (i am using UUIDs as primary keys)
number_from (INT)
number_to (INT)

with 3 indexes:
primary(id)
number_from(number_from)
number_to(number_to)

it looks like simple query like following takes fairly large
amount of time (like 30 seconds or more):
SELECT * FROM numbers WHERE (number_from >= 703911711 AND number_to <= 703911800)

it there anything i can do to optimize performance?

A: Having the indexes separated will force MySQL to scan them separately. If you index both number_from and number_to together, MySQL could perform the entire where clause on a single index:
CREATE INDEX number_from_number_to_ind
ON numbers (number_from, number_to)

Adding the id to the index will actually allow MySQL to perform the entire query without accessing the table, but at the expense of making the index significantly larger. You'd have to benchmark and see if this actually improves the query's performance or not:
CREATE INDEX all_columns_ind
ON numbers (number_from, number_to, id)

A: You have two problems that are not easily solved.

*

*UUIDs are terribly 'random',

*The optimizer dos not understand that the from-to ranges do not overlap

But first, let's make sure you have the cache settings right.  If you are using MyISAM, key_buffer_size should be about 20% of available RAM.  Or for InnoDB, innodb_buffer_pool_size should be about 70% of available RAM.  If you had small settings, this change would only move the problem from being I/O to being CPU.  And it will not scale past when you cannot cache most of the table and its indexes in RAM.  Reference
My blog explains why UUIDs are terrible for large indexes.  That also provides a Stored Function to make the UUID smaller (BINARY(16)), hence more cacheable; this will help with the I/O.
If you have "type-1" UUIDs (such as generated by MySQL), the blog also explains why, with the help of the Function, use of UUIDs can be scaled.  But if it is some other flavor of UUID, and you must have at least one BTree (INDEX or PRIMARY KEY) with the UUID in it, your task is not scalable.  Can you turn it into an AUTO_INCREMENT?  That would allow INSERTs to be clumped at the 'end' of the table rather than randomly scattered around the table, thereby blowing out cache?
As for the ranges, you need to revamp the table to put only one of from/to in each row.  This involves extra rows for the 'unowned' ranges.  Then write a stored routine to use LIMIT 1 to prevent what you are seeing -- namely failure to effectively use any index.  Another blog goes into the details, together with schema design and reference code for IPv4 (which might be what you are doing) and IPv6.  My code is very scalable and eliminates the indexing problem you posed.

A: Conventional indexes don't work when the bounds of your range are stored in different attributes. As lots of people have discovered and documented, the solution is to use geospatial indexing. This was the first hit in google.
Since mysql geospatial indexing works in 2 dimensions, the trick is to map the range to one dimension and use a fixed scale in the other dimension.

A: Old post, I know, but I like to keep StackOverflow a bit up-to-date if possible.
So, if you need a RANGE(from,to) kind of function, please note that nowadays MariaDB has an ENGINE called SEQUENCE that will do this for you:
SELECT `seq` FROM `seq_0_to_100`

as long as the from and to numbers are within the limits of BIGINT(20) UNSIGNED

redpajama_set_name: RedPajamaStackExchange


text:
Lawyers Getting $1.9 million from Michigan in Gay Marriage Case
by admin | Oct 16, 2015 | LGBT, News
Lesbian moms April DeBoer and Jayne Rowse, from suburban Detroit, announced their challenge to Michigan's constitutional ban on same-sex marriage with their three children at a news conference. Photo: LGBTWeekly.
The state of Michigan has agreed to pay $1.9 million to the lawyers who have won a landmark gay marriage case at the US Supreme Court. The Michigan case was one that led to the legalization of marriage equality for every state in the United States.
The lawyers were fighting for a Hazel Park couple Jayne Rowse and April DeBoer who went on to challenge Michigan's own ban on gay marriage and it's restrictions on joint adoption.
The state has also agreed to pay an additional $96,000 to the lawyer it hired to defend the ban, along with an additional $148,000 to the economist and social scientists who testified in support of the ban.
One of the four main lawyers defending the couple, Carole Stanyar said, "The fee (law) was enacted to empower and encourage the vindication of civil rights. I do feel empowered and very encouraged so I guess the law is working as Congress intended. If our case motivates young lawyers to stand up for people and do the right thing, that would be great."
The couple was legally married in August after winning their lawsuit in June when the US Supreme Court legalized same-sex marriage in the US, which was a result of the couple's lawsuit as well as others in Ohio, Kentucky and Tennessee. The same judge who struck down Michigan's marriage ban in 2014, Federal Judge Bernard Friedman, performed the ceremony.
For the past two centuries, Americans have fought for equal rights; we have fought to have rights no matter our race, our gender, our nationality, or our religion. Today we must continue that fight for equal rights, no matter who we love, what gender we are, where we are from, or what we believe.
Here at One Equal World, we want to continue and strengthen the conversation around human rights; we want to contribute to the cause through news, articles, discussion, and support. With a focus on LGBT and women's rights, we're striving to make a difference in the world.
We are still a growing community, but we are proud, we are here, and we're not going anywhere. We believe in one equal world, and we will fight for it.
Follow @1EqualWorld
© 2019 One Equal World. All Rights Reserved. Sitemap

redpajama_set_name: RedPajamaCommonCrawl


Welcome to Area 84. This area is in the central Mississauga around Square one Area and Burnhamthorpe Road and Hurontario Street Intersection.
Area 84 has 6 EEE clubs - Engaging, Enthusiastic, Entertaining clubs : Trillium Toastmasters, Axis Communications, ActionMasters, Knowledge First Financial, IIBA Mississauga Toastmasters Club, Desjardins Toastmasters.
Hello Mississauga Residents and Corporates. We are the Area 84 Toastmasters and welcome you to the World of Toastmasters. Our Area Clubs are fun, entertaining, engaging and rewarding place and we are here to promote, engage and enrich our member experience and create value.
We are an enthusiastic team and we are have a great year ahead of us. Look forward to collaborate and contribute to our clubs and help our members. Come join us on this exciting journey in 2018-2019.
Below here you will find regular updates about the events and programs that we have in store in our Area this year. Stay tuned ! More Information to follow soon.
This year for the very first time, in place of the Humorous speech contest and Table Topics Contest, District 86 will be hosting a MARKETING EXPO from the District. The venue, date and details are below. Please register and come out to explore the opportunities that Toastmasters has for you.
We will also be organizing a Division D Marketing Expo sometime on Nov 10, 2018. Details to follow soon.
Please see below for some important dates and events that are coming up in our Area and District. Come join us.
Contest dates are subjected to change.


For 2011, the compact Toyota Tacoma pickup gets new TX and TX Pro packages, which add a combination of official Toyota Racing Development (TRD) off-road and appearance accessories to the Tacoma's Off-Road Package. All Tacoma models get a slightly new look to the grille, and air conditioning is now standard on all models. Also, Toyota has cut several unpopular models out of the line and added five 4-cylinder models, including PreRunner and 4x4 models, as well as Access Cab and Double Cab styles.
Two different engines are available on the 2011 Toyota Tacoma line: a 159-horsepower, 2.7L 4-cylinder and a 236-hp, 4.0L V6. Both engines have variable valve timing to help provide both strong low-end torque as well as higher-rev passing power. A 6-speed manual transmission is available with the V6 as is a 5-speed manual, which comes with the 4-cylinder. For automatic transmissions, a 5-speed can be optioned with the V6 and a 5-speed is available with the 4-cylinder models.
Just as most other pickup models, the Tacoma is available in several different configurations so as to suit a wide range of uses. Regular Cab models come with two doors, with the Access Cab including a small backseat as well as rear doors that open 80 degrees for easy access; 4-door Double Cab models include 60/40-split rear seats that are comfortable enough for adults. Access Cab models also have fold-up rear seats, but add under-seat storage. All Tacoma models now come with electronic stability control, anti-lock brakes, brake assist and an automatic limited-slip differential. With the available Off-Road Package, there's also Hill-start Assist Control and Downhill Assist Control, which help keep traction on steep slippery slopes or moderate speed and traction on steep downhills. Seat-mounted side airbags, roll-sensing side airbags and active front headrests are also included.
The Toyota Tacoma X-Runner model is the highest-performance version of this truck line and carries over with a number of serious performance mods as well as appearance upgrades. The suspension is specially tuned for road performance, while there's a full body kit, hood scoop, and special fog lamps. With the V6, it's claimed to accelerate to 60 mph in less than seven seconds, but there's even more performance potential on tap with an available supercharger kit, bringing output up to 304 hp and 334 lb-feet of torque.
Base Tacoma models are quite simply equipped and don't even include power windows or locks. They do come with air conditioning and a 4-speaker CD sound system. Access Cab and Double Cab models include power windows and locks, while Double Cab models also get a lumbar-adjustable driver's seat.
Options on Access and Double Cab models include upgraded audio, steering-wheel controls, and a backup monitor system.
The new TX and TX Pro packages this year give the Tacoma PreRunner and 4x4 models a more aggressive, more off-road-capable look with special accessories and performance enhancements. The TX package brings the menacing look, with BF Goodrich Rugged Trail tires on 16-inch black alloy bead-lock wheels, special tube-side steps, a stainless steel exhaust tip, and exterior graphics, while the TX Pro gets a special cat-back performance exhaust system. Both include what's otherwise offered as the TRD Off-Road Package, with progressive-rate front springs, an electric-locking front differential, Bilstein shocks, a larger stabilizer bar, and fog lamps, plus a 400-watt, 115-volt powerpoint, sport seats and an overhead console.
There aren't as many compact truck models on the market as there used to be, but Toyota has done a great job keeping the Tacoma competitive, up-to-date and finding recreation and performance appeal. Toyota boasts that it has more model variations than any other truck manufacturer in this class. Also with expanded standard features, such as air conditioning, included even on base models for 2011, the Tacoma is an even better value--especially when considering the model's reputation for reliability and resale value. And for those who don't have to tow much more than a small boat or trailer, the Tacoma might provide all the hauling ability you need yet feel more maneuverable for daily driving.
Get up-to-date information on the 2011 Toyota Tacoma. Read in depth about this model's features, specs, performance, and much more. Let Bestride.com be your guide to finding your next car.


I´ve captured some AAC LATM streams that are being broadcasted (DVB-T) here in Brazil and tried to transcode them using FFmpeg. The stereo streams work fine but the 5.1 streams are generating some error messages during transcode.
Besides that, the resulting file is always a little smaller in duration than the original (when there´s music, you can more easily notice that the resulting audio seems to be playing "faster", due to missed samples I guess).
I´ve found some old tickets related to AAC streams (ticket:1694 and ticket:2335) with similar error messages, and testing the samples provided there also got me the same behaviour.
I have uploaded the problem_transcoding_5dot1_aac_latm_audio.aac file to the "incoming" folder of the FTP. I´ve also uploaded the complete report generated by FFmpeg under the name problem_transcoding_5dot1_aac_latm_audio.log.
Reading option '-i' ... matched as input file with argument 'problem_transcoding_5dot1_aac_latm_audio.aac'.
Parsing a group of options: input file problem_transcoding_5dot1_aac_latm_audio.aac.
Opening an input file: problem_transcoding_5dot1_aac_latm_audio.aac.
problem_transcoding_5dot1_aac_latm_audio.aac (1.6 MB) - added by chq.contact 4 years ago.
problem_transcoding_5dot1_aac_latm_audio.log (393.3 KB) - added by chq.contact 4 years ago.
Hi, I would like to add that other players like VLC and Windows Media Player can play this file without any noticeable problem. There are no glitches or changes in the audio duration that indicate dropped samples.
The vlc output is around 10 percent longer, both with and without --codec=ffmpeg (the FFmpeg decoder works fine for the given sample in vlc).
[aac_latm @ 0x7fe396001c00] SSR is not implemented. Update your FFmpeg version to the newest one from Git. If the problem still occurs, it means that your file has a feature which has not been implemented.
The code for LTP and SSR is still in the Summer of Code repository for anyone who is interested in working on either of those features in the future.
So the existing atrac and atrac3 decoders might be useful as well.
artifacts that seem to be related to EIGHT_SHORT_SEQUENCE windows.
It seems mostly complete, though it will definitely take some work to port the changes over to master.
There is no mention of SSR. Sorry for hijacking this ticket.


text:
Elliot Irwin McLoughry
Origin: Grey County
Nominated by: Ontario Agricultural Representatives Branch Association
Specialty: Conservation, Livestock - Swine
Devoted to improving agricultural products, the mark of Elliot McLoughry, raised on a farm in Grey County, can be seen in every facet of the industry. His expertise was in translating the scientific advancements of the classroom and laboratory to practical applications on the farm. During the 1920's he introduced the first agricultural "short courses", and in 1925 organized bacon hog fairs which led to rail grading and the establishment of the first advance registry for the swine testing station at New Hamburg. In 1942 he was actively involved in the first commercial program for artificial insemination of cattle and in 1947 organized a comprehensive soil testing program in Waterloo County.
McLoughry's interest in soil conservation led to his appointment as first secretary of the Grand River Conservation Authority and he participated in meetings which led to the passing of the Conservation Authorities Act in 1946. His farm financial expertise was recognized when he was appointed as a director of the Junior Farmer Establishment Loan Board and eventually became board chairman. A prime mover in the Extension Branch of the Ministry of Agriculture, he organized the agricultural engineering service to assist farmers in drainage, buildings, farm machinery and materials handling.
Elliot McLoughry also served his community throughout his career by being an active member of the Galt Kiwanis Club and the Masonic Lodge.


text:
Q: BroadCastReceiver. What's wrong in my code? Code of Receiver:
public class OnBootReceiver extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {

          try {
                BufferedReader in=new BufferedReader(
                        new FileReader(MainNote.log));

                String AlarmString;
                int i = 0;

                while ((AlarmString = in.readLine())!=null)
                {
                    Long AlarmTime = Long.parseLong(AlarmString.substring(0, AlarmString.indexOf(" ")));
                    if (AlarmTime < System.currentTimeMillis()) i++;
                    else {
                        String AlarmArray[] = AlarmString.split("\\s");
                        Intent AlarmIntent = new Intent(context, AlarmReceiver.class);
                        if (AlarmArray[1].equals("null")) AlarmIntent.putExtra("alarm_message", "");
                        else AlarmIntent.putExtra("alarm_message", AlarmArray[1]);
                        if (AlarmArray[2].equals("true"))
                        AlarmIntent.putExtra("Vibration", true);
                        else AlarmIntent.putExtra("Vibration", false);
                        if (AlarmArray[3].equals("true"))
                        AlarmIntent.putExtra("Sound", true);
                        else AlarmIntent.putExtra("Sound", false);

                         final int _ID = (int) System.currentTimeMillis();
                         PendingIntent sender = PendingIntent.getBroadcast(context , _ID, AlarmIntent, PendingIntent.FLAG_UPDATE_CURRENT);
                         AlarmManager am = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
                         am.set(AlarmManager.RTC_WAKEUP, AlarmTime, sender);
                    }
                }

Code of AlarmReceiver.class
public class AlarmReceiver extends BroadcastReceiver {

 @Override
 public void onReceive(Context context, Intent intent) {
     Bundle bundle = intent.getExtras();
     String message = bundle.getString("alarm_message");
     boolean Vibration = bundle.getBoolean("Vibration");
     boolean Sound = bundle.getBoolean("Sound");
     if (message.equals(null))
     NotifierHelper.sendNotification(context, MainNote.class, context.getResources().getString(R.string.NotTitle), context.getResources().getString(R.string.Nodiscr), 1, Sound, true, Vibration);
     else
     NotifierHelper.sendNotification(context, MainNote.class, context.getResources().getString(R.string.NotTitle), message, 1, Sound, true, Vibration);
 }
}

Manifest:
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
      android:versionCode="1"
      android:versionName="1.0">
    <uses-sdk android:minSdkVersion="4" />
    <uses-permission android:name="android.permission.VIBRATE" />
    <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.WAKE_LOCK" />

    <application android:icon="@drawable/icon" android:label="@string/app_name">
        <activity android:label="@string/app_name" android:name=".MainNote">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

        <activity android:name=".FingerPaint"></activity>
    <receiver  android:process=":remote" android:name=".AlarmReceiver"></receiver>

        <receiver android:name=".OnBootReceiver">
            <intent-filter>
                <action
android:name="android.intent.action.BOOT_COMPLETED"/>
            </intent-filter>
        </receiver>
    </application>
</manifest>

MainNote.log can costist for example
1304094118826 text true true

After reboot I see that my process is started, but then I dont have Notifacation. Whats wrong here? And how to debug code in OnBootReciever?
I replace my code in OnBootReciever on
Intent AlarmIntent = new Intent(context, AlarmReceiver.class);
        AlarmIntent.putExtra("alarm_message", "blabla");
        AlarmIntent.putExtra("Vibration", true);
        AlarmIntent.putExtra("Sound", true);

         final int _ID = (int) System.currentTimeMillis();
         PendingIntent sender = PendingIntent.getBroadcast(context , _ID, AlarmIntent, PendingIntent.FLAG_UPDATE_CURRENT);
         AlarmManager am = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
         am.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis()+6000, sender);

And its work. So problem in part where I read information from file.
One problem was in MainNote.log. Log its static varible so I cant contact with this here. But now I have very strange problem -
java.io.FileNotFoundException: /mnt/sdcard/AlarmsFromDrawNote.alm (Permission denied)
com.notedraw.bos.app.OnBootReceiver1.onReceive(OnBootReceiver1.java:30)

30th line is -
BufferedReader in=new BufferedReader(new FileReader(log));

WTF? (see manifest)

A: Your AlarmReceiver needs to be a static BroadcastReceiver like your OnBootReceiver is in order for it to act on the alarm that you set. Unfortunately, I don't think you can have more than one static receiver per application (I tried before and it did not work for me). You could try putting two intent filters on your OnBootReceiver and have it deal with both broadcasts.
In your onRecieve, simply check intent.getAction() to see which broadcast it is receiving (the boot up one or the alarm), and deal with it appropriately.

A: You need to create a new broadcast receiver inside the class where the broadcast will be received.  Put this at the top of your class outside any methods.
AlarmReceiver intentReceiver = new AlarmReceiver ();

And you need:
@Override
protected void onPause() {
    // TODO Mark time user logged out
    unregisterReceiver(intentReceiver);
    super.onPause();
}`

And:
@Override
protected void onResume() {

    IntentFilter filter = new IntentFilter(CustomAction.MY_INTENT);
    filter.addAction(CustomAction.MY_INTENT);
    registerReceiver(intentReceiver, filter);
    super.onResume();
}


text:
Q: IOError: closed stream in Ruby SFTP The following code tries to list the entries of a remote directory via SFTP and Net::SFTP, but it causes an "closed stream" IOError if the directory contains a large number of files (~ 6000 files):
require 'net/ssh'
require 'net/sftp'
Net::SFTP.start('hostname', 'username', :password => 'password') do |sftp|
  # list the entries in a directory
  sftp.dir.foreach("/") do |entry|
    puts entry.longname
  end
end

What is the best way to avoid it? Versions are net-sftp Gem: 2.0.5 and net-ssh Gem: 2.2.1, Ruby: 1.8.7. The full error message reads:
IOError: closed stream
from ~/.rvm/gems/ruby-1.8.7-p330/gems/net-ssh-2.2.1/lib/net/ssh/ruby_compat.rb:33:in `select'
from ~/.rvm/gems/ruby-1.8.7-p330/gems/net-ssh-2.2.1/lib/net/ssh/ruby_compat.rb:33:in `io_select'
from ~/.rvm/gems/ruby-1.8.7-p330/gems/net-ssh-2.2.1/lib/net/ssh/ruby_compat.rb:32:in `synchronize'
from ~/.rvm/gems/ruby-1.8.7-p330/gems/net-ssh-2.2.1/lib/net/ssh/ruby_compat.rb:32:in `io_select'
from ~/.rvm/gems/ruby-1.8.7-p330/gems/net-ssh-2.2.1/lib/net/ssh/transport/packet_stream.rb:73:in `available_for_read?'
from ~/.rvm/gems/ruby-1.8.7-p330/gems/net-ssh-2.2.1/lib/net/ssh/transport/packet_stream.rb:85:in `next_packet'
from ~/.rvm/gems/ruby-1.8.7-p330/gems/net-ssh-2.2.1/lib/net/ssh/transport/session.rb:170:in `poll_message'
from ~/.rvm/gems/ruby-1.8.7-p330/gems/net-ssh-2.2.1/lib/net/ssh/transport/session.rb:165:in `loop'
from ~/.rvm/gems/ruby-1.8.7-p330/gems/net-ssh-2.2.1/lib/net/ssh/transport/session.rb:165:in `poll_message'
from ~/.rvm/gems/ruby-1.8.7-p330/gems/net-ssh-2.2.1/lib/net/ssh/connection/session.rb:451:in `dispatch_incoming_packets'
from ~/.rvm/gems/ruby-1.8.7-p330/gems/net-ssh-2.2.1/lib/net/ssh/connection/session.rb:213:in `preprocess'
from ~/.rvm/gems/ruby-1.8.7-p330/gems/net-ssh-2.2.1/lib/net/ssh/connection/session.rb:197:in `process'
from ~/.rvm/gems/ruby-1.8.7-p330/gems/net-ssh-2.2.1/lib/net/ssh/connection/session.rb:161:in `loop'
from ~/.rvm/gems/ruby-1.8.7-p330/gems/net-ssh-2.2.1/lib/net/ssh/connection/session.rb:161:in `loop_forever'
from ~/.rvm/gems/ruby-1.8.7-p330/gems/net-ssh-2.2.1/lib/net/ssh/connection/session.rb:161:in `loop'
from ~/.rvm/gems/ruby-1.8.7-p330/gems/net-ssh-2.2.1/lib/net/ssh/connection/session.rb:110:in `close'
from ~/.rvm/gems/ruby-1.8.7-p330/gems/net-sftp-2.0.5/lib/net/sftp.rb:36:in `start'

A: The behavior could be deliberate, if we take a look at the dir source code in net-sftp/lib/net/sftp/operations/dir.rb, we see a close operation:
def foreach(path)
  ..
ensure
  sftp.close!(handle) if handle
end

It is possible that this close operation causes the closed stream error. If it does not indicate a bug, it is possible the catch the IOError exception. It also seems to help to run the SSH event loop occasionally:
begin
  ..
  sftp.dir.foreach("/") do |entry|
    puts entry.longname
    # ...
    sftp.loop # Runs the SSH event loop
  end
rescue IOError => Ex
  puts "*** We are done: "+Ex.message
end


"The world Islah means 'to make better, to improve,' he says. "I titled my album Islah because it's my first album which is named after my first baby so it's metaphor because my first album is my first baby; and it's the scariest thing in the world when you're having a first album or a first baby."
Watch above for more with the rapper about his frustrations with the traditional album process and more about Islah.


Note: This series of posts is based on my 1999 trip to Turkey and Israel. I have introduced a new character (Ariel) to help me discuss some topics that I think are pertinent to the purpose of this blog.
I awoke wondering where I was, and then remembered - I was in Jerusalem! We arrived at night and so I wanted to see what the view was like from our 10 story room. I walked to the window and pulled back the curtain which caused my roommate Joe to let out a groan. I immediately saw that we were up on a hill with other hills around us. The hill in front of me had a series of 3-4 story buildings that lined descending shaded streets. Some of the streets had only one building separating them from the next street. There was some greenery with an occasional palm tree, but the overall color impression was various shades of sandstone.
I had read on a map that the Shalom Jerusalem hotel was a 10 minute drive from the center of Jerusalem and close to the Yad Vashem Holocaust Memorial. That must be in the opposite direction because I didn't see anything like that in front of me. After showering and putting on my casual clothes for the day, I headed to the elevator. I remembered the shiny floor of the lobby and the complimentary glass of orange juice that was given to each of us upon our late night arrival; a nice gesture that made me think positively of the hotel. The breakfast spread continued the trend I'd seen in Tel Aviv and Tiberius; lots of fruit, healthy cereals, and yogurt - but no meat, lest we break the rabbinic restriction of mixing meat and dairy. All of this was still new and almost exotic when I would see Hebrew letters on packaging or signs.
Tomorrow was now today; I got up to discard my trash and selected a pastry from a tray.
And then, near the elevators, I saw Ariel talking with our team leader Dave. They stopped and exchanged words until I could see them nod in agreement; at that point they walked over towards me. Dave said, "Morning Dennis, how's the breakfast?" "I like breakfast in Israel; there's always something healthy and good," as I self consciously held the pastry. "Please join us; we have something we'd like to talk to you about," said Dave. I waited until they got some food and let them choose the table. When they did, Dave said he'd pray the blessing. With our heads bowed, he thanked the Lord for the food.


text:
Site Filter — Worldwide / All Aircraft
What is this site filter?
Europe Middle East Africa Asia Pacific North America South America Worldwide
All Aircraft Long Range All Fixed Wing Rotorcraft
All Fixed Wing
Two global leaders, one superior experience
View advert
For fuel and everything else
A reflection of excellence
Straight In & Straight Out
The best tug loads automatically
Stobart Jet Centre is now open
Quality pre-owned aircraft.
You have control
The monthly news publication for aviation professionals.
Request your printed copy
See more information from the Business Air News Handbook...
Piaggio Aerospace
P180 Avanti
Read our latest feature: Special report: Recruitment and training
US Avanti owner signs up for EVO
Mid-South Services has acquired several Piaggio Avanti aircraft over the years, and has now placed a further order for a new EVO. The supplementary fuel tank makes longer trips a breeze.
Mid-South is a keen admirer of the Avanti EVO.
Read this story in our September 2020 printed issue.
While the process of finding a new owner for the company is proceeding according to plan, a new order has arrived for Piaggio Aerospace from the US. A sales agreement for one new production P.180 Avanti EVO has been signed with Mid-South Services, a company with headquarters in Clearwater, Florida.
Scheduled for delivery in the first half of next year the aircraft, intended for private and commercial use, will feature a seven-seat corporate interior and an extended range supplemental fuel tank.
"The unbeatable speed, cabin comfort and eco-friendly fuel efficiency of the aircraft make the Avanti EVO my preferred choice over all other products in this category, while the supplemental fuel tank allows us to complete our longer trips without a stop," says Dean Fuller, president of Mid-South Services and buyer of several Piaggio Avanti aircraft in previous years.
"The contract signed today, which comes from a customer operating in the most important and dynamic market in the world, confirms once more the global interest in the Avanti EVO and its unique performances," adds Vincenzo Nicastro, extraordinary commissioner of Piaggio Aerospace. "The company, with integrated functions of customer service and sales, is demonstrating an excellent vitality and significant capability to operate in international markets."
With this new order, the company has 11 new Avanti EVOs in production and is proceeding with the upgrading of the onboard systems of an additional 19 P.180 aircraft operated by the Italian Armed Forces. The total amount of the order portfolio, including the activity of its engine business unit, has a value of approximately 640 million euros ($750 million USD). Additional orders with a value of 260 million euros ($300 million USD) are under negotiation.
In February of this year commissioner Nicastro, appointed by the Italian Government in December 2018, issued an international call for tenders for the sale of the business complexes of the company, receiving 19 responses. From these, 11 companies have been granted access to the data room, which will remain open until the end of September. The target of the commissioner remains the signature of the sale document this year.
Get the latest news in your inbox!
Piaggio selects Honeywell's cabin pressure system
The fourth-generation version of Honeywell's CPCMS system is all-electric and has built-in test capability to detect and report any failures or issues, including for the back-up manual portion of the system.
Piaggio has a million reasons to celebrate the Avanti
The Avanti, which in its third variant assumed the name Avanti EVO, was designed in the early 1980s by a team of engineers led by designer Alessandro Mazzoni. The global fleet has notched up a million hours.
Tecnam brings electric propulsion P-Volt to market
All of the electric motors, avionics, heating, air conditioning and de-ice systems in the Tecnam P-Volt are designed to provide fully sustainable and pollution-free transportation. It will be electrified directly by Tecnam.
© Copyright of Stansted News Limited 2021
Terms & Conditions | Privacy & Cookies Policy


No matter how hot things get, the Tradewind Performance Tee will keep you looking and feeling cool during any sport training. This tee proves that you don't have to sacrifice style or comfort for technical performance. This piece is perfect for running, training, hot yoga, and cross-fit sessions.