<commit_before># Copyright 2013-2021 Lawrence Livermore National Security, LLC and other
# Spack Project Developers. See the top-level COPYRIGHT file for details.
#
# SPDX-License-Identifier: (Apache-2.0 OR MIT)

from spack import *

class Amrex(CMakePackage, CudaPackage):
    """AMReX is a publicly available software framework designed
    for building massively parallel block- structured adaptive
    mesh refinement (AMR) applications."""

    homepage = "https://amrex-codes.github.io/amrex/"
    url      = "https://github.com/AMReX-Codes/amrex/releases/download/20.05/amrex-20.05.tar.gz"
    git      = "https://github.com/AMReX-Codes/amrex.git"

    maintainers = ['mic84', 'asalmgren']

    version('develop', branch='development')
    version('21.01', sha256='59de3ed429347ee6a7ad4f09c0c431248f2e081f59c301db37cacb36993622f4')
    version('20.12', sha256='a8ba1d605780250da77619939582ce44b33cd286f2dbcc0dfd5cdbaf209140a5')
    version('20.11', sha256='b86f4f2ebf414cec050e562d4ab81545944bda581b496d69767b4bf6a3060855')
    version('20.10', sha256='92def480d1f0bcb5bcb9dfae2ddc8997060414386a1d71ccbfdad785fa2e46fa')
    version('20.09', sha256='3ae203f18656117d8201da16e899a6144ec217817a2a5d9b7649e2eef9cacdf9')
    version('20.08', sha256='a202430cd8dbef2de29b20fe9b5881cc58ee762326556ec3c0ad9c3f85ddfc2f')
    version('20.07', sha256='c386f566f4c57ee56b5630f79ce2c6117d5a612a4aab69b7b26e48d577251165')
    version('20.06', sha256='be2f2a5107111fcb8b3928b76024b370c7cb01a9e5dd79484cf7fcf59d0b4858')
    version('20.05', sha256='97d753bb75e845a0a959ec1a044a48e6adb86dd008b5e29ce7a01d49ed276338')
    version('20.04', sha256='a7ece54d5d89cc00fd555551902a0d4d0fb50db15d2600f441353eed0dddd83b')
    version('20.03', sha256='9728f20c0d7297c935fe5cbc63c1ee60f983b833a735c797340ee2765d626165')
    version('20.02', sha256='2eda858b43e7455718ccb96c18f678da1778ec61031e90effdcb9c3e7e6f9bb5')
    version('20.01', sha256='957e7a7fe90a0a9f4ae10bf9e46dba68d72448d0bec69a4a4e66a544930caca3')
    version('19.10', sha256='9f30a2b3ec13711dfc6a1b59af59bd7df78449b5846ac6457b5dbbdecb20c576')
    version('19.08', sha256='94b1e9a9dcfb8c5b52aef91a2ed373aef504d766dd7d0aba6731ceb94e48e940')
    version('18.10.1', sha256='e648465c9c3b7ff4c696dfa8b6d079b4f61c80d96c51e27af210951c9367c201')
    version('18.10', sha256='298eba03ef03d617c346079433af1089d38076d6fab2c34476c687740c1f4234')
    version('18.09.1', sha256='a065ee4d1d98324b6c492ae20ea63ba12a4a4e23432bf5b3fe9788d44aa4398e')

    # Config options
    variant('dimensions', default='3',
            description='Dimensionality', values=('2', '3'))
    variant('shared',  default=False,
            description='Build shared library')
    variant('mpi',          default=True,
            description='Build with MPI support')
    variant('openmp',       default=False,
            description='Build with OpenMP support')
    variant('precision',  default='double',
            description='Real precision (double/single)',
            values=('single', 'double'))
    variant('eb',  default=False,
            description='Build Embedded Boundary classes')
    variant('fortran',  default=False,
            description='Build Fortran API')
    variant('linear_solvers', default=True,
            description='Build linear solvers')
    variant('amrdata',    default=False,
            description='Build data services')
    variant('particles',  default=False,
            description='Build particle classes')
    variant('build_type', default='Release',
            description='The build type to build',
            values=('Debug', 'Release'))
    variant('sundials', default=False,
            description='Build AMReX with SUNDIALS support')
    variant('hdf5',  default=False,
            description='Enable HDF5-based I/O')
    variant('hypre', default=False,
            description='Enable Hypre interfaces')
    variant('petsc', default=False,
            description='Enable PETSc interfaces')

    # Build dependencies
    depends_on('mpi', when='+mpi')
    depends_on('sundials@4.0.0:4.1.0 +ARKODE +CVODE', when='@19.08: +sundials')
    depends_on('cuda@9.0.0:', when='+cuda')
    depends_on('python@2.7:', type='build', when='@:20.04')
    depends_on('cmake@3.5:',  type='build', when='@:18.10.99')
    depends_on('cmake@3.13:', type='build', when='@18.11:')
    depends_on('cmake@3.14:', type='build', when='@19.04:')
    # cmake @3.17: is necessary to handle cuda @11: correctly
    depends_on('cmake@3.17:', type='build', when='^cuda @11:')
    conflicts('%apple-clang')
    conflicts('%clang')

    # Check options compatibility
    conflicts('+sundials', when='~fortran',
              msg='AMReX SUNDIALS support needs AMReX Fortran API (+fortran)')
    conflicts('+sundials', when='@20.12:',
              msg='AMReX >= 20.12 no longer supports SUNDIALS interfaces')
    conflicts('+hdf5', when='@:20.06',
              msg='AMReX HDF5 support needs AMReX newer than version 20.06')
    conflicts('+hypre', when='@:20.06',
              msg='AMReX Hypre support needs AMReX newer than version 20.06')
    conflicts('+hypre', when='~fortran',
              msg='AMReX Hypre support needs AMReX Fortran API (+fortran)')
    conflicts('+hypre', when='~linear_solvers',
              msg='AMReX Hypre support needs variant +linear_solvers')
    conflicts('+petsc', when='@:20.06',
              msg='AMReX PETSc support needs AMReX newer than version 20.06')
    conflicts('+petsc', when='~fortran',
              msg='AMReX PETSc support needs AMReX Fortran API (+fortran)')
    conflicts('+petsc', when='~linear_solvers',
              msg='AMReX PETSc support needs variant +linear_solvers')
    conflicts('+cuda', when='@:19.08',
              msg='AMReX CUDA support needs AMReX newer than version 19.08')
    conflicts('cuda_arch=10', when='+cuda', msg='AMReX only supports compute capabilities >= 3.5')
    conflicts('cuda_arch=11', when='+cuda', msg='AMReX only supports compute capabilities >= 3.5')
    conflicts('cuda_arch=12', when='+cuda', msg='AMReX only supports compute capabilities >= 3.5')
    conflicts('cuda_arch=13', when='+cuda', msg='AMReX only supports compute capabilities >= 3.5')
    conflicts('cuda_arch=20', when='+cuda', msg='AMReX only supports compute capabilities >= 3.5')
    conflicts('cuda_arch=21', when='+cuda', msg='AMReX only supports compute capabilities >= 3.5')
    conflicts('cuda_arch=30', when='+cuda', msg='AMReX only supports compute capabilities >= 3.5')
    conflicts('cuda_arch=32', when='+cuda', msg='AMReX only supports compute capabilities >= 3.5')

    def url_for_version(self, version):
        if version >= Version('20.05'):
            url = "https://github.com/AMReX-Codes/amrex/releases/download/{0}/amrex-{0}.tar.gz"
        else:
            url = "https://github.com/AMReX-Codes/amrex/archive/{0}.tar.gz"
        return url.format(version.dotted)

    def get_cuda_arch_string(self, values):
        if 'none' in values:
            return 'Auto'
        else:
            # Use format x.y instead of CudaPackage xy format
            vf = tuple(float(x) / 10.0 for x in values)
            return ';'.join(str(x) for x in vf)

    #
    # For versions <= 20.11
    #
    @when('@:20.11')
    def cmake_args(self):
        args = [
            '-DUSE_XSDK_DEFAULTS=ON',
            self.define_from_variant('DIM', 'dimensions'),
            self.define_from_variant('BUILD_SHARED_LIBS', 'shared'),
            self.define_from_variant('ENABLE_MPI', 'mpi'),
            self.define_from_variant('ENABLE_OMP', 'openmp'),
            '-DXSDK_PRECISION:STRING=%s' %
            self.spec.variants['precision'].value.upper(),
            self.define_from_variant('XSDK_ENABLE_Fortran', 'fortran'),
            self.define_from_variant('ENABLE_FORTRAN_INTERFACES', 'fortran'),
            self.define_from_variant('ENABLE_EB', 'eb'),
            self.define_from_variant('ENABLE_LINEAR_SOLVERS',
                                     'linear_solvers'),
            self.define_from_variant('ENABLE_AMRDATA', 'amrdata'),
            self.define_from_variant('ENABLE_PARTICLES', 'particles'),
            self.define_from_variant('ENABLE_SUNDIALS', 'sundials'),
            self.define_from_variant('ENABLE_HDF5', 'hdf5'),
            self.define_from_variant('ENABLE_HYPRE', 'hypre'),
            self.define_from_variant('ENABLE_PETSC', 'petsc'),
            self.define_from_variant('ENABLE_CUDA', 'cuda'),
        ]

        if self.spec.satisfies('%fj'):
            args.append('-DCMAKE_Fortran_MODDIR_FLAG=-M')

        if '+cuda' in self.spec:
            cuda_arch = self.spec.variants['cuda_arch'].value
            args.append('-DCUDA_ARCH=' + self.get_cuda_arch_string(cuda_arch))

        return args

    #
    # For versions > 20.11
    #
    @when('@20.12:')
    def cmake_args(self):
        args = [
            '-DUSE_XSDK_DEFAULTS=ON',
            self.define_from_variant('AMReX_SPACEDIM', 'dimensions'),
            self.define_from_variant('BUILD_SHARED_LIBS', 'shared'),
            self.define_from_variant('AMReX_MPI', 'mpi'),
            self.define_from_variant('AMReX_OMP', 'openmp'),
            '-DXSDK_PRECISION:STRING=%s' %
            self.spec.variants['precision'].value.upper(),
            self.define_from_variant('XSDK_ENABLE_Fortran', 'fortran'),
            self.define_from_variant('AMReX_FORTRAN_INTERFACES', 'fortran'),
            self.define_from_variant('AMReX_EB', 'eb'),
            self.define_from_variant('AMReX_LINEAR_SOLVERS',
                                     'linear_solvers'),
            self.define_from_variant('AMReX_AMRDATA', 'amrdata'),
            self.define_from_variant('AMReX_PARTICLES', 'particles'),
            self.define_from_variant('AMReX_HDF5', 'hdf5'),
            self.define_from_variant('AMReX_HYPRE', 'hypre'),
            self.define_from_variant('AMReX_PETSC', 'petsc'),
        ]

        if self.spec.satisfies('%fj'):
            args.append('-DCMAKE_Fortran_MODDIR_FLAG=-M')

        if '+cuda' in self.spec:
            args.append('-DAMReX_GPU_BACKEND=CUDA')
            args.append('-DAMReX_CUDA_ERROR_CAPTURE_THIS=ON')
            args.append('-DAMReX_CUDA_ERROR_CROSS_EXECUTION_SPACE_CALL=ON')
            cuda_arch = self.spec.variants['cuda_arch'].value
            args.append('-DCUDA_ARCH=' + self.get_cuda_arch_string(cuda_arch))

        return args
<commit_msg>amrex: add ROCm support (#20809)<commit_after># Copyright 2013-2021 Lawrence Livermore National Security, LLC and other
# Spack Project Developers. See the top-level COPYRIGHT file for details.
#
# SPDX-License-Identifier: (Apache-2.0 OR MIT)

from spack import *

class Amrex(CMakePackage, CudaPackage, ROCmPackage):
    """AMReX is a publicly available software framework designed
    for building massively parallel block- structured adaptive
    mesh refinement (AMR) applications."""

    homepage = "https://amrex-codes.github.io/amrex/"
    url      = "https://github.com/AMReX-Codes/amrex/releases/download/20.05/amrex-20.05.tar.gz"
    git      = "https://github.com/AMReX-Codes/amrex.git"

    maintainers = ['mic84', 'asalmgren']

    version('develop', branch='development')
    version('21.01', sha256='59de3ed429347ee6a7ad4f09c0c431248f2e081f59c301db37cacb36993622f4')
    version('20.12', sha256='a8ba1d605780250da77619939582ce44b33cd286f2dbcc0dfd5cdbaf209140a5')
    version('20.11', sha256='b86f4f2ebf414cec050e562d4ab81545944bda581b496d69767b4bf6a3060855')
    version('20.10', sha256='92def480d1f0bcb5bcb9dfae2ddc8997060414386a1d71ccbfdad785fa2e46fa')
    version('20.09', sha256='3ae203f18656117d8201da16e899a6144ec217817a2a5d9b7649e2eef9cacdf9')
    version('20.08', sha256='a202430cd8dbef2de29b20fe9b5881cc58ee762326556ec3c0ad9c3f85ddfc2f')
    version('20.07', sha256='c386f566f4c57ee56b5630f79ce2c6117d5a612a4aab69b7b26e48d577251165')
    version('20.06', sha256='be2f2a5107111fcb8b3928b76024b370c7cb01a9e5dd79484cf7fcf59d0b4858')
    version('20.05', sha256='97d753bb75e845a0a959ec1a044a48e6adb86dd008b5e29ce7a01d49ed276338')
    version('20.04', sha256='a7ece54d5d89cc00fd555551902a0d4d0fb50db15d2600f441353eed0dddd83b')
    version('20.03', sha256='9728f20c0d7297c935fe5cbc63c1ee60f983b833a735c797340ee2765d626165')
    version('20.02', sha256='2eda858b43e7455718ccb96c18f678da1778ec61031e90effdcb9c3e7e6f9bb5')
    version('20.01', sha256='957e7a7fe90a0a9f4ae10bf9e46dba68d72448d0bec69a4a4e66a544930caca3')
    version('19.10', sha256='9f30a2b3ec13711dfc6a1b59af59bd7df78449b5846ac6457b5dbbdecb20c576')
    version('19.08', sha256='94b1e9a9dcfb8c5b52aef91a2ed373aef504d766dd7d0aba6731ceb94e48e940')
    version('18.10.1', sha256='e648465c9c3b7ff4c696dfa8b6d079b4f61c80d96c51e27af210951c9367c201')
    version('18.10', sha256='298eba03ef03d617c346079433af1089d38076d6fab2c34476c687740c1f4234')
    version('18.09.1', sha256='a065ee4d1d98324b6c492ae20ea63ba12a4a4e23432bf5b3fe9788d44aa4398e')

    # Config options
    variant('dimensions', default='3',
            description='Dimensionality', values=('2', '3'))
    variant('shared',  default=False,
            description='Build shared library')
    variant('mpi',          default=True,
            description='Build with MPI support')
    variant('openmp',       default=False,
            description='Build with OpenMP support')
    variant('precision',  default='double',
            description='Real precision (double/single)',
            values=('single', 'double'))
    variant('eb',  default=False,
            description='Build Embedded Boundary classes')
    variant('fortran',  default=False,
            description='Build Fortran API')
    variant('linear_solvers', default=True,
            description='Build linear solvers')
    variant('amrdata',    default=False,
            description='Build data services')
    variant('particles',  default=False,
            description='Build particle classes')
    variant('build_type', default='Release',
            description='The build type to build',
            values=('Debug', 'Release'))
    variant('sundials', default=False,
            description='Build AMReX with SUNDIALS support')
    variant('hdf5',  default=False,
            description='Enable HDF5-based I/O')
    variant('hypre', default=False,
            description='Enable Hypre interfaces')
    variant('petsc', default=False,
            description='Enable PETSc interfaces')

    # Build dependencies
    depends_on('mpi', when='+mpi')
    depends_on('sundials@4.0.0:4.1.0 +ARKODE +CVODE', when='@19.08: +sundials')
    depends_on('cuda@9.0.0:', when='+cuda')
    depends_on('python@2.7:', type='build', when='@:20.04')
    depends_on('cmake@3.5:',  type='build', when='@:18.10.99')
    depends_on('cmake@3.13:', type='build', when='@18.11:')
    depends_on('cmake@3.14:', type='build', when='@19.04:')
    # cmake @3.17: is necessary to handle cuda @11: correctly
    depends_on('cmake@3.17:', type='build', when='^cuda @11:')
    depends_on('rocrand', type='build', when='+rocm')
    conflicts('%apple-clang')
    conflicts('%clang')

    # Check options compatibility
    conflicts('+sundials', when='~fortran',
              msg='AMReX SUNDIALS support needs AMReX Fortran API (+fortran)')
    conflicts('+sundials', when='@20.12:',
              msg='AMReX >= 20.12 no longer supports SUNDIALS interfaces')
    conflicts('+hdf5', when='@:20.06',
              msg='AMReX HDF5 support needs AMReX newer than version 20.06')
    conflicts('+hypre', when='@:20.06',
              msg='AMReX Hypre support needs AMReX newer than version 20.06')
    conflicts('+hypre', when='~fortran',
              msg='AMReX Hypre support needs AMReX Fortran API (+fortran)')
    conflicts('+hypre', when='~linear_solvers',
              msg='AMReX Hypre support needs variant +linear_solvers')
    conflicts('+petsc', when='@:20.06',
              msg='AMReX PETSc support needs AMReX newer than version 20.06')
    conflicts('+petsc', when='~fortran',
              msg='AMReX PETSc support needs AMReX Fortran API (+fortran)')
    conflicts('+petsc', when='~linear_solvers',
              msg='AMReX PETSc support needs variant +linear_solvers')
    conflicts('+cuda', when='@:19.08',
              msg='AMReX CUDA support needs AMReX newer than version 19.08')
    conflicts('cuda_arch=10', when='+cuda', msg='AMReX only supports compute capabilities >= 3.5')
    conflicts('cuda_arch=11', when='+cuda', msg='AMReX only supports compute capabilities >= 3.5')
    conflicts('cuda_arch=12', when='+cuda', msg='AMReX only supports compute capabilities >= 3.5')
    conflicts('cuda_arch=13', when='+cuda', msg='AMReX only supports compute capabilities >= 3.5')
    conflicts('cuda_arch=20', when='+cuda', msg='AMReX only supports compute capabilities >= 3.5')
    conflicts('cuda_arch=21', when='+cuda', msg='AMReX only supports compute capabilities >= 3.5')
    conflicts('cuda_arch=30', when='+cuda', msg='AMReX only supports compute capabilities >= 3.5')
    conflicts('cuda_arch=32', when='+cuda', msg='AMReX only supports compute capabilities >= 3.5')
    conflicts('+rocm', when='@:20.11', msg='AMReX HIP support needs AMReX newer than version 20.11')
    conflicts('+cuda', when='+rocm', msg='CUDA and HIP support are exclusive')

    def url_for_version(self, version):
        if version >= Version('20.05'):
            url = "https://github.com/AMReX-Codes/amrex/releases/download/{0}/amrex-{0}.tar.gz"
        else:
            url = "https://github.com/AMReX-Codes/amrex/archive/{0}.tar.gz"
        return url.format(version.dotted)

    def get_cuda_arch_string(self, values):
        if 'none' in values:
            return 'Auto'
        else:
            # Use format x.y instead of CudaPackage xy format
            vf = tuple(float(x) / 10.0 for x in values)
            return ';'.join(str(x) for x in vf)

    #
    # For versions <= 20.11
    #
    @when('@:20.11')
    def cmake_args(self):
        args = [
            '-DUSE_XSDK_DEFAULTS=ON',
            self.define_from_variant('DIM', 'dimensions'),
            self.define_from_variant('BUILD_SHARED_LIBS', 'shared'),
            self.define_from_variant('ENABLE_MPI', 'mpi'),
            self.define_from_variant('ENABLE_OMP', 'openmp'),
            '-DXSDK_PRECISION:STRING=%s' %
            self.spec.variants['precision'].value.upper(),
            self.define_from_variant('XSDK_ENABLE_Fortran', 'fortran'),
            self.define_from_variant('ENABLE_FORTRAN_INTERFACES', 'fortran'),
            self.define_from_variant('ENABLE_EB', 'eb'),
            self.define_from_variant('ENABLE_LINEAR_SOLVERS',
                                     'linear_solvers'),
            self.define_from_variant('ENABLE_AMRDATA', 'amrdata'),
            self.define_from_variant('ENABLE_PARTICLES', 'particles'),
            self.define_from_variant('ENABLE_SUNDIALS', 'sundials'),
            self.define_from_variant('ENABLE_HDF5', 'hdf5'),
            self.define_from_variant('ENABLE_HYPRE', 'hypre'),
            self.define_from_variant('ENABLE_PETSC', 'petsc'),
            self.define_from_variant('ENABLE_CUDA', 'cuda'),
        ]

        if self.spec.satisfies('%fj'):
            args.append('-DCMAKE_Fortran_MODDIR_FLAG=-M')

        if '+cuda' in self.spec:
            cuda_arch = self.spec.variants['cuda_arch'].value
            args.append('-DCUDA_ARCH=' + self.get_cuda_arch_string(cuda_arch))

        return args

    #
    # For versions > 20.11
    #
    @when('@20.12:')
    def cmake_args(self):
        args = [
            '-DUSE_XSDK_DEFAULTS=ON',
            self.define_from_variant('AMReX_SPACEDIM', 'dimensions'),
            self.define_from_variant('BUILD_SHARED_LIBS', 'shared'),
            self.define_from_variant('AMReX_MPI', 'mpi'),
            self.define_from_variant('AMReX_OMP', 'openmp'),
            '-DXSDK_PRECISION:STRING=%s' %
            self.spec.variants['precision'].value.upper(),
            self.define_from_variant('XSDK_ENABLE_Fortran', 'fortran'),
            self.define_from_variant('AMReX_FORTRAN_INTERFACES', 'fortran'),
            self.define_from_variant('AMReX_EB', 'eb'),
            self.define_from_variant('AMReX_LINEAR_SOLVERS',
                                     'linear_solvers'),
            self.define_from_variant('AMReX_AMRDATA', 'amrdata'),
            self.define_from_variant('AMReX_PARTICLES', 'particles'),
            self.define_from_variant('AMReX_HDF5', 'hdf5'),
            self.define_from_variant('AMReX_HYPRE', 'hypre'),
            self.define_from_variant('AMReX_PETSC', 'petsc'),
        ]

        if self.spec.satisfies('%fj'):
            args.append('-DCMAKE_Fortran_MODDIR_FLAG=-M')

        if '+cuda' in self.spec:
            args.append('-DAMReX_GPU_BACKEND=CUDA')
            args.append('-DAMReX_CUDA_ERROR_CAPTURE_THIS=ON')
            args.append('-DAMReX_CUDA_ERROR_CROSS_EXECUTION_SPACE_CALL=ON')
            cuda_arch = self.spec.variants['cuda_arch'].value
            args.append('-DCUDA_ARCH=' + self.get_cuda_arch_string(cuda_arch))

        if '+rocm' in self.spec:
            args.append('-DCMAKE_CXX_COMPILER={0}'.format(self.spec['hip'].hipcc))
            args.append('-DAMReX_GPU_BACKEND=HIP')
            targets = self.spec.variants['amdgpu_target'].value
            args.append('-DAMReX_AMD_ARCH=' + ';'.join(str(x) for x in targets))

        return args
<|endoftext|>


<commit_before>#!/usr/bin/env python

'''
'''

__docformat__ = 'restructuredtext'
__version__ = '$Id: $'

import sys
import time

from pyglet.gl import *
from pyglet import clock
from pyglet import font
from pyglet import media
from pyglet import window
from pyglet.window import key

class MediaPlayWindow(window.Window):
    instance = None
    sound = None
    video = None

    def __init__(self, filename, *args, **kwargs):
        super(MediaPlayWindow, self).__init__(*args, **kwargs)

        # Load the medium, determine if it's video and/or audio
        medium = media.load(filename, streaming=True)
        if medium.has_video:
            self.instance = self.video = medium.get_video()
            self.sound = self.instance.sound
            self.width = self.video.width
            self.height = self.video.height
        elif medium.has_audio:
            self.sound = self.instance = medium.get_sound()

        if not self.sound and not self.video:
            raise Exception("Media file doesn't contain sound or video")

        self.instance.play()

        # Decorative labels

        self.y = self.height
        self.labels = []
        def add_label(text):
            l = font.Label(font.load('Arial', 12), text, color=(1, 1, 1, 1))
            l.x = 10
            l.y = self.y - l.height
            self.y -= l.height
            self.labels.append(l)
            return l

        add_label(filename)
        self.time_label = add_label('')
        add_label('')
        self.playing_label = add_label('Playing; press space to pause')
        self.volume_label = add_label('Volume 1.0; adjust with +,-')
        self.pitch_label = add_label('Pitch 1.0: adjust with [,]')
        self.position_label = add_label('Position 0,0,0: adjust with W,A,S,D')
        self.velocity_label = add_label('Velocity 0,0,0: adjust with I,J,K,L')

    def draw(self):
        glClearColor(0, 0, 0, 1)
        glClear(GL_COLOR_BUFFER_BIT)
        if self.video:
            self.video.texture.blit(0, 0, 0)
        for label in self.labels:
            label.draw()
        self.flip()

    def add_volume(self, v):
        self.sound.volume += v
        self.volume_label.text = \
            'Volume %f; adjust with +/-' % self.sound.volume

    def add_position(self, dx, dy, dz):
        x, y, z = self.sound.position
        self.sound.position = x + dx, y + dy, z + dz
        self.position_label.text = \
            'Position %.2f, %.2f, %.2f; adjust with W,A,S,D' % \
                self.sound.position

    def add_velocity(self, dx, dy, dz):
        x, y, z = self.sound.velocity
        self.sound.velocity = x + dx, y + dy, z + dz
        self.velocity_label.text = \
            'Velocity %.2f, %.2f, %.2f; adjust with W,A,S,D' % \
                self.sound.velocity

    def add_pitch(self, pitch):
        self.sound.pitch += pitch
        self.pitch_label.text = \
            'Pitch %.2f; adjust with [,]' % self.sound.pitch

    def on_key_press(self, symbol, modifiers):
        if symbol == key.SPACE:
            if self.instance.playing:
                self.instance.pause()
                self.playing_label.text = 'Paused; press space to resume'
            else:
                self.instance.play()
                self.playing_label.text = 'Playing; press space to pause'
        elif symbol in (key.EQUAL, key.NUM_ADD):
            self.add_volume(.1)
        elif symbol in (key.MINUS, key.NUM_SUBTRACT):
            self.add_volume(-.1)
        elif symbol == key.A:
            self.add_position(-.1, 0, 0)
        elif symbol == key.S:
            self.add_position(0, 0, .1)
        elif symbol == key.D:
            self.add_position(.1, 0, 0)
        elif symbol == key.W:
            self.add_position(0, 0, -.1)
        elif symbol == key.J:
            self.add_velocity(-.1, 0, 0)
        elif symbol == key.K:
            self.add_velocity(0, 0, .1)
        elif symbol == key.L:
            self.add_velocity(.1, 0, 0)
        elif symbol == key.I:
            self.add_velocity(0, 0, -.1)
        elif symbol == key.BRACKETLEFT:
            self.add_pitch(-0.1)
        elif symbol == key.BRACKETRIGHT:
            self.add_pitch(0.1)
        else:
            return super(MediaPlayWindow, self).on_key_press(symbol, modifiers)
        return event.EVENT_HANDLED

    def run(self):
        clock.set_fps_limit(30)
        while not self.instance.finished and not self.has_exit:
            clock.tick()
            self.dispatch_events()
            media.dispatch_events()

            t = self.instance.time
            self.time_label.text = '%d:%05.2f' % \
                (int(t / 60), t - 60 * int(t / 60))

            self.draw()

if __name__ == '__main__':
    filename = sys.argv[1]

    try:
        win = MediaPlayWindow(filename, width=400, height=150, resizable=True)
        win.run()
    finally:
        media.cleanup()
<commit_msg>include FPS display<commit_after>#!/usr/bin/env python

'''
'''

__docformat__ = 'restructuredtext'
__version__ = '$Id: $'

import sys
import time

from pyglet.gl import *
from pyglet import clock
from pyglet import font
from pyglet import media
from pyglet import window
from pyglet.window import key

class MediaPlayWindow(window.Window):
    instance = None
    sound = None
    video = None

    def __init__(self, filename, *args, **kwargs):
        super(MediaPlayWindow, self).__init__(*args, **kwargs)

        # Load the medium, determine if it's video and/or audio
        medium = media.load(filename, streaming=True)
        if medium.has_video:
            self.instance = self.video = medium.get_video()
            self.sound = self.instance.sound
            self.width = self.video.width
            self.height = self.video.height
        elif medium.has_audio:
            self.sound = self.instance = medium.get_sound()

        if not self.sound and not self.video:
            raise Exception("Media file doesn't contain sound or video")

        self.instance.play()

        # Decorative labels

        self.y = self.height
        self.labels = []
        def add_label(text):
            l = font.Label(font.load('Arial', 12), text, color=(1, 1, 1, 1))
            l.x = 10
            l.y = self.y - l.height
            self.y -= l.height
            self.labels.append(l)
            return l

        add_label(filename)
        self.time_label = add_label('')
        self.fps_label = add_label('')
        add_label('')
        self.playing_label = add_label('Playing; press space to pause')
        self.volume_label = add_label('Volume 1.0; adjust with +,-')
        self.pitch_label = add_label('Pitch 1.0: adjust with [,]')
        self.position_label = add_label('Position 0,0,0: adjust with W,A,S,D')
        self.velocity_label = add_label('Velocity 0,0,0: adjust with I,J,K,L')

    def draw(self):
        glClearColor(0, 0, 0, 1)
        glClear(GL_COLOR_BUFFER_BIT)
        if self.video:
            self.video.texture.blit(0, 0, 0)
        for label in self.labels:
            label.draw()
        self.flip()

    def add_volume(self, v):
        self.sound.volume += v
        self.volume_label.text = \
            'Volume %f; adjust with +/-' % self.sound.volume

    def add_position(self, dx, dy, dz):
        x, y, z = self.sound.position
        self.sound.position = x + dx, y + dy, z + dz
        self.position_label.text = \
            'Position %.2f, %.2f, %.2f; adjust with W,A,S,D' % \
                self.sound.position

    def add_velocity(self, dx, dy, dz):
        x, y, z = self.sound.velocity
        self.sound.velocity = x + dx, y + dy, z + dz
        self.velocity_label.text = \
            'Velocity %.2f, %.2f, %.2f; adjust with W,A,S,D' % \
                self.sound.velocity

    def add_pitch(self, pitch):
        self.sound.pitch += pitch
        self.pitch_label.text = \
            'Pitch %.2f; adjust with [,]' % self.sound.pitch

    def on_key_press(self, symbol, modifiers):
        if symbol == key.SPACE:
            if self.instance.playing:
                self.instance.pause()
                self.playing_label.text = 'Paused; press space to resume'
            else:
                self.instance.play()
                self.playing_label.text = 'Playing; press space to pause'
        elif symbol in (key.EQUAL, key.NUM_ADD):
            self.add_volume(.1)
        elif symbol in (key.MINUS, key.NUM_SUBTRACT):
            self.add_volume(-.1)
        elif symbol == key.A:
            self.add_position(-.1, 0, 0)
        elif symbol == key.S:
            self.add_position(0, 0, .1)
        elif symbol == key.D:
            self.add_position(.1, 0, 0)
        elif symbol == key.W:
            self.add_position(0, 0, -.1)
        elif symbol == key.J:
            self.add_velocity(-.1, 0, 0)
        elif symbol == key.K:
            self.add_velocity(0, 0, .1)
        elif symbol == key.L:
            self.add_velocity(.1, 0, 0)
        elif symbol == key.I:
            self.add_velocity(0, 0, -.1)
        elif symbol == key.BRACKETLEFT:
            self.add_pitch(-0.1)
        elif symbol == key.BRACKETRIGHT:
            self.add_pitch(0.1)
        else:
            return super(MediaPlayWindow, self).on_key_press(symbol, modifiers)
        return event.EVENT_HANDLED

    def run(self):
        clock.set_fps_limit(30)
        while not self.instance.finished and not self.has_exit:
            clock.tick()
            self.dispatch_events()
            media.dispatch_events()

            t = self.instance.time
            self.time_label.text = '%d:%05.2f' % \
                (int(t / 60), t - 60 * int(t / 60))
            self.fps_label.text = 'FPS: %.2f'%clock.get_fps()

            self.draw()

if __name__ == '__main__':
    filename = sys.argv[1]

    try:
        win = MediaPlayWindow(filename, width=400, height=150, resizable=True)
        win.run()
    finally:
        media.cleanup()
<|endoftext|>


<commit_before># Copyright 2013-2019 Lawrence Livermore National Security, LLC and other
# Spack Project Developers. See the top-level COPYRIGHT file for details.
#
# SPDX-License-Identifier: (Apache-2.0 OR MIT)

from spack import *
import sys

class Hwloc(AutotoolsPackage):
    """The Hardware Locality (hwloc) software project.

    The Portable Hardware Locality (hwloc) software package
    provides a portable abstraction (across OS, versions,
    architectures, ...) of the hierarchical topology of modern
    architectures, including NUMA memory nodes, sockets, shared
    caches, cores and simultaneous multithreading. It also gathers
    various system attributes such as cache and memory information
    as well as the locality of I/O devices such as network
    interfaces, InfiniBand HCAs or GPUs. It primarily aims at
    helping applications with gathering information about modern
    computing hardware so as to exploit it accordingly and
    efficiently.
    """

    homepage = "http://www.open-mpi.org/projects/hwloc/"
    url      = "https://download.open-mpi.org/release/hwloc/v2.0/hwloc-2.0.2.tar.gz"
    list_url = "http://www.open-mpi.org/software/hwloc/"
    list_depth = 2

    version('2.0.2',  sha256='27dcfe42e3fb3422b72ce48b48bf601c0a3e46e850ee72d9bdd17b5863b6e42c')
    version('2.0.1',  sha256='f1156df22fc2365a31a3dc5f752c53aad49e34a5e22d75ed231cd97eaa437f9d')
    version('2.0.0',  sha256='a0d425a0fc7c7e3f2c92a272ffaffbd913005556b4443e1887d2e1718d902887')
    version('1.11.11', sha256='74329da3be1b25de8e98a712adb28b14e561889244bf3a8138afe91ab18e0b3a')
    version('1.11.10', sha256='0a2530b739d9ebf60c4c1e86adb5451a20d9e78f7798cf78d0147cc6df328aac')
    version('1.11.9', sha256='85b978995b67db0b1a12dd1a73b09ef3d39f8e3cb09f8b9c60cf04633acce46c')
    version('1.11.8', sha256='8af89b1164a330e36d18210360ea9bb305e19f9773d1c882855d261a13054ea8')
    version('1.11.7', sha256='ac16bed9cdd3c63bca1fe1ac3de522a1376b1487c4fc85b7b19592e28fd98e26')
    version('1.11.6', sha256='67963f15197e6b551539c4ed95a4f8882be9a16cf336300902004361cf89bdee')
    version('1.11.5', sha256='da2c780fce9b5440a1a7d1caf78f637feff9181a9d1ca090278cae4bea71b3df')
    version('1.11.4', sha256='1b6a58049c31ce36aff162cf4332998fd468486bd08fdfe0249a47437311512d')
    version('1.11.3', sha256='03a1cc63f23fed7e17e4d4369a75dc77d5c145111b8578b70e0964a12712dea0')
    version('1.11.2', sha256='d11f091ed54c56c325ffca1083113a405fcd8a25d5888af64f5cd6cf587b7b0a')
    version('1.11.1', sha256='b41f877d79b6026640943d57ef25311299378450f2995d507a5e633da711be61')
    version('1.9',    sha256='9fb572daef35a1c8608d1a6232a4a9f56846bab2854c50562dfb9a7be294f4e8')

    variant('nvml', default=False, description="Support NVML device discovery")
    variant('gl', default=False, description="Support GL device discovery")
    variant('cuda', default=False, description="Support CUDA devices")
    variant('libxml2', default=True, description="Build with libxml2")
    variant('pci', default=(sys.platform != 'darwin'),
            description="Support analyzing devices on PCI bus")
    variant('shared', default=True, description="Build shared libraries")
    variant(
        'cairo',
        default=False,
        description='Enable the Cairo back-end of hwloc\'s lstopo command'
    )

    depends_on('pkgconfig', type='build')

    depends_on('cuda', when='+nvml')
    depends_on('cuda', when='+cuda')
    depends_on('gl', when='+gl')
    depends_on('libpciaccess', when='+pci')
    depends_on('libxml2', when='+libxml2')
    depends_on('cairo', when='+cairo')
    depends_on('numactl', when='@:1.11.11 platform=linux')

    def url_for_version(self, version):
        return "http://www.open-mpi.org/software/hwloc/v%s/downloads/hwloc-%s.tar.gz" % (version.up_to(2), version)

    def configure_args(self):
        args = [
            # Disable OpenCL, since hwloc might pick up an OpenCL
            # library at build time that is then not found at run time
            # (Alternatively, we could require OpenCL as dependency.)
            "--disable-opencl",
        ]
        if '@2.0.0:' in self.spec:
            args.append('--enable-netloc')

        args.extend(self.enable_or_disable('cairo'))
        args.extend(self.enable_or_disable('nvml'))
        args.extend(self.enable_or_disable('gl'))
        args.extend(self.enable_or_disable('cuda'))
        args.extend(self.enable_or_disable('libxml2'))
        args.extend(self.enable_or_disable('pci'))
        args.extend(self.enable_or_disable('shared'))

        return args
<commit_msg>hwloc: added 'master' version pointing at the HEAD of the master branch (#13734)<commit_after># Copyright 2013-2019 Lawrence Livermore National Security, LLC and other
# Spack Project Developers. See the top-level COPYRIGHT file for details.
#
# SPDX-License-Identifier: (Apache-2.0 OR MIT)
import sys

class Hwloc(AutotoolsPackage):
    """The Hardware Locality (hwloc) software project.

    The Portable Hardware Locality (hwloc) software package
    provides a portable abstraction (across OS, versions,
    architectures, ...) of the hierarchical topology of modern
    architectures, including NUMA memory nodes, sockets, shared
    caches, cores and simultaneous multithreading. It also gathers
    various system attributes such as cache and memory information
    as well as the locality of I/O devices such as network
    interfaces, InfiniBand HCAs or GPUs. It primarily aims at
    helping applications with gathering information about modern
    computing hardware so as to exploit it accordingly and
    efficiently.
    """

    homepage = "http://www.open-mpi.org/projects/hwloc/"
    url      = "https://download.open-mpi.org/release/hwloc/v2.0/hwloc-2.0.2.tar.gz"
    list_url = "http://www.open-mpi.org/software/hwloc/"
    list_depth = 2
    git = 'https://github.com/open-mpi/hwloc.git'

    version('master', branch='master')
    version('2.0.2',  sha256='27dcfe42e3fb3422b72ce48b48bf601c0a3e46e850ee72d9bdd17b5863b6e42c')
    version('2.0.1',  sha256='f1156df22fc2365a31a3dc5f752c53aad49e34a5e22d75ed231cd97eaa437f9d')
    version('2.0.0',  sha256='a0d425a0fc7c7e3f2c92a272ffaffbd913005556b4443e1887d2e1718d902887')
    version('1.11.11', sha256='74329da3be1b25de8e98a712adb28b14e561889244bf3a8138afe91ab18e0b3a')
    version('1.11.10', sha256='0a2530b739d9ebf60c4c1e86adb5451a20d9e78f7798cf78d0147cc6df328aac')
    version('1.11.9', sha256='85b978995b67db0b1a12dd1a73b09ef3d39f8e3cb09f8b9c60cf04633acce46c')
    version('1.11.8', sha256='8af89b1164a330e36d18210360ea9bb305e19f9773d1c882855d261a13054ea8')
    version('1.11.7', sha256='ac16bed9cdd3c63bca1fe1ac3de522a1376b1487c4fc85b7b19592e28fd98e26')
    version('1.11.6', sha256='67963f15197e6b551539c4ed95a4f8882be9a16cf336300902004361cf89bdee')
    version('1.11.5', sha256='da2c780fce9b5440a1a7d1caf78f637feff9181a9d1ca090278cae4bea71b3df')
    version('1.11.4', sha256='1b6a58049c31ce36aff162cf4332998fd468486bd08fdfe0249a47437311512d')
    version('1.11.3', sha256='03a1cc63f23fed7e17e4d4369a75dc77d5c145111b8578b70e0964a12712dea0')
    version('1.11.2', sha256='d11f091ed54c56c325ffca1083113a405fcd8a25d5888af64f5cd6cf587b7b0a')
    version('1.11.1', sha256='b41f877d79b6026640943d57ef25311299378450f2995d507a5e633da711be61')
    version('1.9',    sha256='9fb572daef35a1c8608d1a6232a4a9f56846bab2854c50562dfb9a7be294f4e8')

    variant('nvml', default=False, description="Support NVML device discovery")
    variant('gl', default=False, description="Support GL device discovery")
    variant('cuda', default=False, description="Support CUDA devices")
    variant('libxml2', default=True, description="Build with libxml2")
    variant('pci', default=(sys.platform != 'darwin'),
            description="Support analyzing devices on PCI bus")
    variant('shared', default=True, description="Build shared libraries")
    variant(
        'cairo',
        default=False,
        description='Enable the Cairo back-end of hwloc\'s lstopo command'
    )

    depends_on('pkgconfig', type='build')
    depends_on('m4', type='build', when='@master')
    depends_on('autoconf', type='build', when='@master')
    depends_on('automake', type='build', when='@master')
    depends_on('libtool', type='build', when='@master')
    depends_on('cuda', when='+nvml')
    depends_on('cuda', when='+cuda')
    depends_on('gl', when='+gl')
    depends_on('libpciaccess', when='+pci')
    depends_on('libxml2', when='+libxml2')
    depends_on('cairo', when='+cairo')
    depends_on('numactl', when='@:1.11.11 platform=linux')

    def url_for_version(self, version):
        return "http://www.open-mpi.org/software/hwloc/v%s/downloads/hwloc-%s.tar.gz" % (version.up_to(2), version)

    def configure_args(self):
        args = [
            # Disable OpenCL, since hwloc might pick up an OpenCL
            # library at build time that is then not found at run time
            # (Alternatively, we could require OpenCL as dependency.)
            "--disable-opencl",
        ]
        if '@2.0.0:' in self.spec:
            args.append('--enable-netloc')

        args.extend(self.enable_or_disable('cairo'))
        args.extend(self.enable_or_disable('nvml'))
        args.extend(self.enable_or_disable('gl'))
        args.extend(self.enable_or_disable('cuda'))
        args.extend(self.enable_or_disable('libxml2'))
        args.extend(self.enable_or_disable('pci'))
        args.extend(self.enable_or_disable('shared'))

        return args
<|endoftext|>


<commit_before># Copyright 2013-2019 Lawrence Livermore National Security, LLC and other
# Spack Project Developers. See the top-level COPYRIGHT file for details.
#
# SPDX-License-Identifier: (Apache-2.0 OR MIT)

from spack import *
import sys

class Hwloc(AutotoolsPackage):
    """The Hardware Locality (hwloc) software project.

    The Portable Hardware Locality (hwloc) software package
    provides a portable abstraction (across OS, versions,
    architectures, ...) of the hierarchical topology of modern
    architectures, including NUMA memory nodes, sockets, shared
    caches, cores and simultaneous multithreading. It also gathers
    various system attributes such as cache and memory information
    as well as the locality of I/O devices such as network
    interfaces, InfiniBand HCAs or GPUs. It primarily aims at
    helping applications with gathering information about modern
    computing hardware so as to exploit it accordingly and
    efficiently.
    """

    homepage = "http://www.open-mpi.org/projects/hwloc/"
    url      = "https://download.open-mpi.org/release/hwloc/v2.0/hwloc-2.0.2.tar.gz"
    list_url = "http://www.open-mpi.org/software/hwloc/"
    list_depth = 2

    version('2.0.2',  sha256='27dcfe42e3fb3422b72ce48b48bf601c0a3e46e850ee72d9bdd17b5863b6e42c')
    version('2.0.1',  sha256='f1156df22fc2365a31a3dc5f752c53aad49e34a5e22d75ed231cd97eaa437f9d')
    version('2.0.0',  sha256='a0d425a0fc7c7e3f2c92a272ffaffbd913005556b4443e1887d2e1718d902887')
    version('1.11.11', sha256='74329da3be1b25de8e98a712adb28b14e561889244bf3a8138afe91ab18e0b3a')
    version('1.11.10', sha256='0a2530b739d9ebf60c4c1e86adb5451a20d9e78f7798cf78d0147cc6df328aac')
    version('1.11.9', sha256='85b978995b67db0b1a12dd1a73b09ef3d39f8e3cb09f8b9c60cf04633acce46c')
    version('1.11.8', sha256='8af89b1164a330e36d18210360ea9bb305e19f9773d1c882855d261a13054ea8')
    version('1.11.7', sha256='ac16bed9cdd3c63bca1fe1ac3de522a1376b1487c4fc85b7b19592e28fd98e26')
    version('1.11.6', sha256='67963f15197e6b551539c4ed95a4f8882be9a16cf336300902004361cf89bdee')
    version('1.11.5', sha256='da2c780fce9b5440a1a7d1caf78f637feff9181a9d1ca090278cae4bea71b3df')
    version('1.11.4', sha256='1b6a58049c31ce36aff162cf4332998fd468486bd08fdfe0249a47437311512d')
    version('1.11.3', sha256='03a1cc63f23fed7e17e4d4369a75dc77d5c145111b8578b70e0964a12712dea0')
    version('1.11.2', sha256='d11f091ed54c56c325ffca1083113a405fcd8a25d5888af64f5cd6cf587b7b0a')
    version('1.11.1', sha256='b41f877d79b6026640943d57ef25311299378450f2995d507a5e633da711be61')
    version('1.9',    sha256='9fb572daef35a1c8608d1a6232a4a9f56846bab2854c50562dfb9a7be294f4e8')

    variant('nvml', default=False, description="Support NVML device discovery")
    variant('gl', default=False, description="Support GL device discovery")
    variant('cuda', default=False, description="Support CUDA devices")
    variant('libxml2', default=True, description="Build with libxml2")
    variant('pci', default=(sys.platform != 'darwin'),
            description="Support analyzing devices on PCI bus")
    variant('shared', default=True, description="Build shared libraries")
    variant(
        'cairo',
        default=False,
        description='Enable the Cairo back-end of hwloc\'s lstopo command'
    )

    depends_on('pkgconfig', type='build')

    depends_on('cuda', when='+nvml')
    depends_on('cuda', when='+cuda')
    depends_on('gl', when='+gl')
    depends_on('libpciaccess', when='+pci')
    depends_on('libxml2', when='+libxml2')
    depends_on('cairo', when='+cairo')
    depends_on('numactl', when='@:1.11.11 platform=linux')

    def url_for_version(self, version):
        return "http://www.open-mpi.org/software/hwloc/v%s/downloads/hwloc-%s.tar.gz" % (version.up_to(2), version)

    def configure_args(self):
        args = [
            # Disable OpenCL, since hwloc might pick up an OpenCL
            # library at build time that is then not found at run time
            # (Alternatively, we could require OpenCL as dependency.)
            "--disable-opencl",
        ]
        if '@2.0.0:' in self.spec:
            args.append('--enable-netloc')

        args.extend(self.enable_or_disable('cairo'))
        args.extend(self.enable_or_disable('nvml'))
        args.extend(self.enable_or_disable('gl'))
        args.extend(self.enable_or_disable('cuda'))
        args.extend(self.enable_or_disable('libxml2'))
        args.extend(self.enable_or_disable('pci'))
        args.extend(self.enable_or_disable('shared'))

        return args
<commit_msg>hwloc: added 'master' version pointing at the HEAD of the master branch (#13731)<commit_after># Copyright 2013-2019 Lawrence Livermore National Security, LLC and other
# Spack Project Developers. See the top-level COPYRIGHT file for details.
#
# SPDX-License-Identifier: (Apache-2.0 OR MIT)
import sys

class Hwloc(AutotoolsPackage):
    """The Hardware Locality (hwloc) software project.

    The Portable Hardware Locality (hwloc) software package
    provides a portable abstraction (across OS, versions,
    architectures, ...) of the hierarchical topology of modern
    architectures, including NUMA memory nodes, sockets, shared
    caches, cores and simultaneous multithreading. It also gathers
    various system attributes such as cache and memory information
    as well as the locality of I/O devices such as network
    interfaces, InfiniBand HCAs or GPUs. It primarily aims at
    helping applications with gathering information about modern
    computing hardware so as to exploit it accordingly and
    efficiently.
    """

    homepage = "http://www.open-mpi.org/projects/hwloc/"
    url      = "https://download.open-mpi.org/release/hwloc/v2.0/hwloc-2.0.2.tar.gz"
    list_url = "http://www.open-mpi.org/software/hwloc/"
    list_depth = 2
    git = 'https://github.com/open-mpi/hwloc.git'

    version('master', branch='master')
    version('2.0.2',  sha256='27dcfe42e3fb3422b72ce48b48bf601c0a3e46e850ee72d9bdd17b5863b6e42c')
    version('2.0.1',  sha256='f1156df22fc2365a31a3dc5f752c53aad49e34a5e22d75ed231cd97eaa437f9d')
    version('2.0.0',  sha256='a0d425a0fc7c7e3f2c92a272ffaffbd913005556b4443e1887d2e1718d902887')
    version('1.11.11', sha256='74329da3be1b25de8e98a712adb28b14e561889244bf3a8138afe91ab18e0b3a')
    version('1.11.10', sha256='0a2530b739d9ebf60c4c1e86adb5451a20d9e78f7798cf78d0147cc6df328aac')
    version('1.11.9', sha256='85b978995b67db0b1a12dd1a73b09ef3d39f8e3cb09f8b9c60cf04633acce46c')
    version('1.11.8', sha256='8af89b1164a330e36d18210360ea9bb305e19f9773d1c882855d261a13054ea8')
    version('1.11.7', sha256='ac16bed9cdd3c63bca1fe1ac3de522a1376b1487c4fc85b7b19592e28fd98e26')
    version('1.11.6', sha256='67963f15197e6b551539c4ed95a4f8882be9a16cf336300902004361cf89bdee')
    version('1.11.5', sha256='da2c780fce9b5440a1a7d1caf78f637feff9181a9d1ca090278cae4bea71b3df')
    version('1.11.4', sha256='1b6a58049c31ce36aff162cf4332998fd468486bd08fdfe0249a47437311512d')
    version('1.11.3', sha256='03a1cc63f23fed7e17e4d4369a75dc77d5c145111b8578b70e0964a12712dea0')
    version('1.11.2', sha256='d11f091ed54c56c325ffca1083113a405fcd8a25d5888af64f5cd6cf587b7b0a')
    version('1.11.1', sha256='b41f877d79b6026640943d57ef25311299378450f2995d507a5e633da711be61')
    version('1.9',    sha256='9fb572daef35a1c8608d1a6232a4a9f56846bab2854c50562dfb9a7be294f4e8')

    variant('nvml', default=False, description="Support NVML device discovery")
    variant('gl', default=False, description="Support GL device discovery")
    variant('cuda', default=False, description="Support CUDA devices")
    variant('libxml2', default=True, description="Build with libxml2")
    variant('pci', default=(sys.platform != 'darwin'),
            description="Support analyzing devices on PCI bus")
    variant('shared', default=True, description="Build shared libraries")
    variant(
        'cairo',
        default=False,
        description='Enable the Cairo back-end of hwloc\'s lstopo command'
    )

    depends_on('pkgconfig', type='build')
    depends_on('m4', type='build', when='@master')
    depends_on('autoconf', type='build', when='@master')
    depends_on('automake', type='build', when='@master')
    depends_on('libtool', type='build', when='@master')
    depends_on('cuda', when='+nvml')
    depends_on('cuda', when='+cuda')
    depends_on('gl', when='+gl')
    depends_on('libpciaccess', when='+pci')
    depends_on('libxml2', when='+libxml2')
    depends_on('cairo', when='+cairo')
    depends_on('numactl', when='@:1.11.11 platform=linux')

    def url_for_version(self, version):
        return "http://www.open-mpi.org/software/hwloc/v%s/downloads/hwloc-%s.tar.gz" % (version.up_to(2), version)

    def configure_args(self):
        args = [
            # Disable OpenCL, since hwloc might pick up an OpenCL
            # library at build time that is then not found at run time
            # (Alternatively, we could require OpenCL as dependency.)
            "--disable-opencl",
        ]
        if '@2.0.0:' in self.spec:
            args.append('--enable-netloc')

        args.extend(self.enable_or_disable('cairo'))
        args.extend(self.enable_or_disable('nvml'))
        args.extend(self.enable_or_disable('gl'))
        args.extend(self.enable_or_disable('cuda'))
        args.extend(self.enable_or_disable('libxml2'))
        args.extend(self.enable_or_disable('pci'))
        args.extend(self.enable_or_disable('shared'))

        return args
<|endoftext|>


<commit_before>##############################################################################
# Copyright (c) 2013-2018, Lawrence Livermore National Security, LLC.
# Produced at the Lawrence Livermore National Laboratory.
#
# This file is part of Spack.
# Created by Todd Gamblin, tgamblin@llnl.gov, All rights reserved.
# LLNL-CODE-647188
#
# For details, see https://github.com/spack/spack
# Please also see the NOTICE and LICENSE files for our notice and the LGPL.
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License (as
# published by the Free Software Foundation) version 2.1, February 1999.
#
# This program is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the IMPLIED WARRANTY OF
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the terms and
# conditions of the GNU Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
##############################################################################
from spack import *
import os
import sys

class Hypre(Package):
    """Hypre is a library of high performance preconditioners that
       features parallel multigrid methods for both structured and
       unstructured grid problems."""

    homepage = "http://computation.llnl.gov/project/linear_solvers/software.php"
    url      = "https://github.com/LLNL/hypre/archive/v2.14.0.tar.gz"
    git      = "https://github.com/LLNL/hypre.git"

    version('develop', branch='master')
    version('2.14.0', 'ecde5cc807ec45bfb647e9f28d2eaea1')
    version('2.13.0', '4b688a5c15b6b5e3de5e045ae081b89b')
    version('2.12.1', 'c6fcb6d7e57cec1c7ce4a44da885068c')
    version('2.11.2', 'd507943a1a3ce5681c3308e2f3a6dd34')
    version('2.11.1', '3f02ef8fd679239a6723f60b7f796519')
    version('2.10.1', 'dc048c4cabb3cd549af72591474ad674')
    version('2.10.0b', '768be38793a35bb5d055905b271f5b8e')
    version('xsdk-0.2.0', tag='xsdk-0.2.0')

    # Versions 2.13.0 and later can be patched to build shared
    # libraries on Darwin; the patch for this capability does not
    # apply to version 2.12.1 and earlier due to changes in the build system
    # between versions 2.12.1 and 2.13.0.
    variant('shared', default=(sys.platform != 'darwin'),
            description="Build shared library (disables static library)")
    # SuperluDist have conflicting headers with those in Hypre
    variant('internal-superlu', default=True,
            description="Use internal Superlu routines")
    variant('int64', default=False,
            description="Use 64bit integers")
    variant('mpi', default=True, description='Enable MPI support')
    variant('debug', default=False,
            description='Build debug instead of optimized version')

    # Patch to add ppc64le in config.guess
    patch('ibm-ppc64le.patch', when='@:2.11.1')

    # Patch to build shared libraries on Darwin
    patch('darwin-shared-libs-for-hypre-2.13.0.patch', when='+shared@2.13.0 platform=darwin')
    patch('darwin-shared-libs-for-hypre-2.14.0.patch', when='+shared@2.14.0: platform=darwin')

    depends_on("mpi", when='+mpi')
    depends_on("blas")
    depends_on("lapack")

    # Patch to build shared libraries on Darwin does not apply to
    # versions before 2.13.0
    conflicts("+shared@:2.12.99 platform=darwin")

    def url_for_version(self, version):
        if version >= Version('2.12.0'):
            url = 'https://github.com/LLNL/hypre/archive/v{0}.tar.gz'
        else:
            url = 'http://computation.llnl.gov/project/linear_solvers/download/hypre-{0}.tar.gz'

        return url.format(version)

    def install(self, spec, prefix):
        # Note: --with-(lapack|blas)_libs= needs space separated list of names
        lapack = spec['lapack'].libs
        blas = spec['blas'].libs

        configure_args = [
            '--prefix=%s' % prefix,
            '--with-lapack-libs=%s' % ' '.join(lapack.names),
            '--with-lapack-lib-dirs=%s' % ' '.join(lapack.directories),
            '--with-blas-libs=%s' % ' '.join(blas.names),
            '--with-blas-lib-dirs=%s' % ' '.join(blas.directories)
        ]

        if '+mpi' in self.spec:
            os.environ['CC'] = spec['mpi'].mpicc
            os.environ['CXX'] = spec['mpi'].mpicxx
            os.environ['F77'] = spec['mpi'].mpif77
            configure_args.append('--with-MPI')
        else:
            configure_args.append('--without-MPI')

        if '+int64' in self.spec:
            configure_args.append('--enable-bigint')

        if '+shared' in self.spec:
            configure_args.append("--enable-shared")

        if '~internal-superlu' in self.spec:
            configure_args.append("--without-superlu")
            # MLI and FEI do not build without superlu on Linux
            configure_args.append("--without-mli")
            configure_args.append("--without-fei")

        if '+debug' in self.spec:
            configure_args.append("--enable-debug")
        else:
            configure_args.append("--disable-debug")

        # Hypre's source is staged under ./src so we'll have to manually
        # cd into it.
        with working_dir("src"):
            configure(*configure_args)

            make()
            if self.run_tests:
                make("check")
                make("test")
                Executable(join_path('test', 'ij'))()
                sstruct = Executable(join_path('test', 'struct'))
                sstruct()
                sstruct('-in', 'test/sstruct.in.default', '-solver', '40',
                        '-rhsone')
            make("install")

    @property
    def headers(self):
        """Export the main hypre header, HYPRE.h; all other headers can be found
        in the same directory.
        Sample usage: spec['hypre'].headers.cpp_flags
        """
        hdrs = find_headers('HYPRE', self.prefix.include, recursive=False)
        return hdrs or None

    @property
    def libs(self):
        """Export the hypre library.
        Sample usage: spec['hypre'].libs.ld_flags
        """
        search_paths = [[self.prefix.lib, False], [self.prefix.lib64, False],
                        [self.prefix, True]]
        is_shared = '+shared' in self.spec
        for path, recursive in search_paths:
            libs = find_libraries('libHYPRE', root=path,
                                  shared=is_shared, recursive=recursive)
            if libs:
                return libs
        return None
<commit_msg>Update HYPRE with version 2.15.0. (#9443)<commit_after>##############################################################################
# Copyright (c) 2013-2018, Lawrence Livermore National Security, LLC.
# Produced at the Lawrence Livermore National Laboratory.
#
# This file is part of Spack.
# Created by Todd Gamblin, tgamblin@llnl.gov, All rights reserved.
# LLNL-CODE-647188
#
# For details, see https://github.com/spack/spack
# Please also see the NOTICE and LICENSE files for our notice and the LGPL.
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License (as
# published by the Free Software Foundation) version 2.1, February 1999.
#
# This program is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the IMPLIED WARRANTY OF
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the terms and
# conditions of the GNU Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
##############################################################################
from spack import *
import os
import sys

class Hypre(Package):
    """Hypre is a library of high performance preconditioners that
       features parallel multigrid methods for both structured and
       unstructured grid problems."""

    homepage = "http://computation.llnl.gov/project/linear_solvers/software.php"
    url      = "https://github.com/LLNL/hypre/archive/v2.14.0.tar.gz"
    git      = "https://github.com/LLNL/hypre.git"

    version('develop', branch='master')
    version('2.15.0', '4645acc49141069cae1d53de96107a08')
    version('2.14.0', 'ecde5cc807ec45bfb647e9f28d2eaea1')
    version('2.13.0', '4b688a5c15b6b5e3de5e045ae081b89b')
    version('2.12.1', 'c6fcb6d7e57cec1c7ce4a44da885068c')
    version('2.11.2', 'd507943a1a3ce5681c3308e2f3a6dd34')
    version('2.11.1', '3f02ef8fd679239a6723f60b7f796519')
    version('2.10.1', 'dc048c4cabb3cd549af72591474ad674')
    version('2.10.0b', '768be38793a35bb5d055905b271f5b8e')
    version('xsdk-0.2.0', tag='xsdk-0.2.0')

    # Versions 2.13.0 and later can be patched to build shared
    # libraries on Darwin; the patch for this capability does not
    # apply to version 2.12.1 and earlier due to changes in the build system
    # between versions 2.12.1 and 2.13.0.
    variant('shared', default=(sys.platform != 'darwin'),
            description="Build shared library (disables static library)")
    # SuperluDist have conflicting headers with those in Hypre
    variant('internal-superlu', default=True,
            description="Use internal Superlu routines")
    variant('int64', default=False,
            description="Use 64bit integers")
    variant('mpi', default=True, description='Enable MPI support')
    variant('debug', default=False,
            description='Build debug instead of optimized version')

    # Patch to add ppc64le in config.guess
    patch('ibm-ppc64le.patch', when='@:2.11.1')

    # Patch to build shared libraries on Darwin
    patch('darwin-shared-libs-for-hypre-2.13.0.patch', when='+shared@2.13.0 platform=darwin')
    patch('darwin-shared-libs-for-hypre-2.14.0.patch', when='+shared@2.14.0: platform=darwin')

    depends_on("mpi", when='+mpi')
    depends_on("blas")
    depends_on("lapack")

    # Patch to build shared libraries on Darwin does not apply to
    # versions before 2.13.0
    conflicts("+shared@:2.12.99 platform=darwin")

    def url_for_version(self, version):
        if version >= Version('2.12.0'):
            url = 'https://github.com/LLNL/hypre/archive/v{0}.tar.gz'
        else:
            url = 'http://computation.llnl.gov/project/linear_solvers/download/hypre-{0}.tar.gz'

        return url.format(version)

    def install(self, spec, prefix):
        # Note: --with-(lapack|blas)_libs= needs space separated list of names
        lapack = spec['lapack'].libs
        blas = spec['blas'].libs

        configure_args = [
            '--prefix=%s' % prefix,
            '--with-lapack-libs=%s' % ' '.join(lapack.names),
            '--with-lapack-lib-dirs=%s' % ' '.join(lapack.directories),
            '--with-blas-libs=%s' % ' '.join(blas.names),
            '--with-blas-lib-dirs=%s' % ' '.join(blas.directories)
        ]

        if '+mpi' in self.spec:
            os.environ['CC'] = spec['mpi'].mpicc
            os.environ['CXX'] = spec['mpi'].mpicxx
            os.environ['F77'] = spec['mpi'].mpif77
            configure_args.append('--with-MPI')
        else:
            configure_args.append('--without-MPI')

        if '+int64' in self.spec:
            configure_args.append('--enable-bigint')

        if '+shared' in self.spec:
            configure_args.append("--enable-shared")

        if '~internal-superlu' in self.spec:
            configure_args.append("--without-superlu")
            # MLI and FEI do not build without superlu on Linux
            configure_args.append("--without-mli")
            configure_args.append("--without-fei")

        if '+debug' in self.spec:
            configure_args.append("--enable-debug")
        else:
            configure_args.append("--disable-debug")

        # Hypre's source is staged under ./src so we'll have to manually
        # cd into it.
        with working_dir("src"):
            configure(*configure_args)

            make()
            if self.run_tests:
                make("check")
                make("test")
                Executable(join_path('test', 'ij'))()
                sstruct = Executable(join_path('test', 'struct'))
                sstruct()
                sstruct('-in', 'test/sstruct.in.default', '-solver', '40',
                        '-rhsone')
            make("install")

    @property
    def headers(self):
        """Export the main hypre header, HYPRE.h; all other headers can be found
        in the same directory.
        Sample usage: spec['hypre'].headers.cpp_flags
        """
        hdrs = find_headers('HYPRE', self.prefix.include, recursive=False)
        return hdrs or None

    @property
    def libs(self):
        """Export the hypre library.
        Sample usage: spec['hypre'].libs.ld_flags
        """
        search_paths = [[self.prefix.lib, False], [self.prefix.lib64, False],
                        [self.prefix, True]]
        is_shared = '+shared' in self.spec
        for path, recursive in search_paths:
            libs = find_libraries('libHYPRE', root=path,
                                  shared=is_shared, recursive=recursive)
            if libs:
                return libs
        return None
<|endoftext|>


<commit_before>import logging
import datetime
import urllib.parse
from html.parser import HTMLParser
from typing import Dict, Any, List, Union, Callable, Set, TypeVar, Type

import discord
import timeago
from discord import Message, Member, Embed
from discord.utils import maybe_coroutine

log = logging.getLogger(__name__)

class MLStripper(HTMLParser):
    def __init__(self):
        super().__init__()
        self.reset()
        self.strict = False
        self.convert_charrefs = True
        self.fed = []

    def handle_data(self, d):
        self.fed.append(d)

    def get_data(self):
        return ''.join(self.fed)

def user_format(format_string: str, parameters: Dict[Any, Any]) -> str:
    """Like .format, but for user input."""
    result = format_string

    for key, value in parameters.items():
        result = result.replace('{' + key + '}', str(value))

    return result

R = TypeVar('T')
ResultContainerType = Union[List, Set]

async def history_reducer(ctx, reducer: Callable[[Message], R], *,
                          ignore_duplicates=False, result_container_type: Type=list, **kwargs) -> ResultContainerType[R]:
    """
    Iterates through message history, and outputs a list of items populated by a function that receives each
    message.

    Parameters
    ----------
    ctx
        The command context.
    reducer
        The callable reducer. Results that aren't falsy are added to the result container.
    ignore_duplicates
        Specifies whether duplicates should be ignored.
    result_container_type
        Specifies the type of result container. Should be either ``list`` or ``set``.
    kwargs
        The kwargs to pass to the ``ctx.history`` class.

    Returns
    -------
        The list of items.
    """
    if 'limit' not in kwargs:
        raise TypeError('limit required')

    history: List[Message] = await ctx.history(limit=kwargs['limit']).flatten()
    results: Union[List, Set] = result_container_type()

    for message in history:
        result = await maybe_coroutine(reducer, message)

        if result:
            if ignore_duplicates and result in results:
                continue

            if isinstance(results, list):
                results.append(result)
            elif isinstance(results, set):
                results.add(results)

    return results

def format_dict(d: Dict[Any, Any], *, style='equals') -> str:
    """
    Formats a ``dict`` to appear in key-value style.

    Parameters
    ----------
    d
        The ``dict`` to format.
    style
        The style to format the dict.

    Returns
    -------
    str
        The formatted ``dict``, as a ``str``.
    """
    code_block = '```{}\n'.format('ini' if style == 'ini' else '')

    # calculate the longest key
    padding = len(max(d.keys(), key=len))

    for name, value in d.items():
        if style == 'equals':
            code_block += '{name: <{width}} = {value}\n'.format(name=name, width=padding, value=value)
        elif style == 'ini':
            code_block += '{name: <{width}} {value}\n'.format(name=f'[{name}]', width=padding + 2, value=value)

    return code_block + '```'

def prevent_codeblock_breakout(text: str) -> str:
    """
    Formats text to prevent "breaking out" of a codeblock.

    Parameters
    ----------
    text
        The text to format.

    Returns
    -------
    str
        The formatted text.
    """
    return text.replace('`', '\u200b`\u200b')

def make_profile_embed(member: Member) -> Embed:
    """
    Creates an embed with the author containing the :class:`discord.Member`'s username and discriminator, along
    with their icon.

    Parameters
    ----------
    member
        The member to use in the :class:`discord.Embed`

    Returns
    -------
    :class:`discord.Embed`
        The resulting embed.
    """
    return Embed().set_author(name=str(member), icon_url=member.avatar_url)

def codeblock(text: str, *, lang: str='') -> str:
    """
    Formats a codeblock.

    Parameters
    ----------
    text
        The text to be inside of the codeblock.
    lang
        The language to use.

    Returns
    -------
    str
        The formatted message.
    """
    return f'```{lang}\n{text}\n```'

def strip_tags(text: str) -> str:
    """
    Strips HTML tags from text.

    Parameters
    ----------
    text
        The text to strip.

    Returns
    -------
    str
        The stripped text.
    """
    s = MLStripper()
    s.feed(text)
    return s.get_data()

def urlescape(text: str) -> str:
    """
    Quotes text using urllib to be included in URIs.

    Parameters
    ----------
    text
        The text to quote.

    Returns
    -------
    str
        The quoted text.
    """
    return urllib.parse.quote_plus(text)

def standard_datetime(dt: datetime.datetime):
    """
    Returns a string representing a :class:`datetime.datetime` formatted a nice way: ::

        YEAR-MONTH-DAY HOUR:MINUTE:SECOND

    Parameters
    ----------
    dt
        The :class:`datetime.datetime` to format.
    """
    return dt.strftime('%Y-%m-%d %H:%M:%S')

def format_list(lst: List[Any]) -> str:
    """
    Returns a string representing a list as an ordered list. List numerals are padded to ensure that there are at
    least 3 digits.

    Parameters
    ----------
    lst
        The list to format.

    Returns
    -------
    str
        The formatted string.
    """
    return '\n'.join('`{:03d}`: {}'.format(index + 1, value) for index, value in enumerate(lst))

def now() -> str:
    """
    Returns a string representing the current time, formatted with :func:`standard_datetime`.
    """
    """ Returns an Semistandard-formatted datetime with a "UTC" suffix. """
    return standard_datetime(datetime.datetime.utcnow()) + ' UTC'

def ago(dt: datetime.datetime) -> str:
    """
    Returns a string representing the amount of time since a datetime.

    Parameters
    ----------
    dt
        The datetime to process.
    """
    return timeago.format(dt, datetime.datetime.utcnow())

def truncate(text: str, desired_length: int):
    """
    Truncates text to a desired length.

    If the text is truncated, the last three characters are overwritten with ``...``

    Parameters
    ----------
    text
        The text to truncate.
    desired_length
        The desired length.

    Returns
    -------
    str
        The truncated string.
    """
    if len(text) > desired_length:
        return text[:desired_length - 3] + '...'
    return text

def commas(number: Union[int, float]) -> str:
    """
    Adds American-style commas to an number, then returns it as a str.
    """
    return '{:,d}'.format(number)

def filesize(byte_size: int) -> str:
    """
    Converts an byte size to a human-readable filesize.

    At this time, it only supports MB and KB.

    Parameters
    ----------
    byte_size
        The amount of bytes.

    Returns
    -------
    str
        The human-readable filesize.
    """
    if bytes > 10 ** 5 * 5:  # 0.5 MB
        return f'{round(byte_size / 10 ** 6, 2)} MB'
    else:
        return f'{round(byte_size / 1000, 2)} KB'

def describe(thing: Any, *, mention=False, before='', created=False, joined=False, quote=False):
    """
    Returns a string representing an project. Usually consists of the object in string form,
    then the object's ID in parentheses after.

    Parameters
    ----------
    thing
        The thing to describe. Usually a superclass of :class:`discord.Object`.
    mention
        Specifies whether to mention the thing instead of using its string representation.
    before
        Specifies text to insert after name and ID.
    created
        Specifies whether to append the ``created_at`` attribute, post-processed with :func:`ago`.
    joined
        Specifies whether to append the ``joined_at`` attribute, post-processed with :func:`ago`.
    quote
        Specifies whether to quote the name of the thing.
    """

    # get name, might be mention
    name = str(thing) if not mention else thing.mention

    # handle emoji specially
    if isinstance(thing, discord.Emoji):
        name = f'`{":" + thing.name + ":" if thing.require_colons else thing.name}`'

    if quote:
        name = '"' + name + '"'

    # name + id
    message = f'{name} (`{thing.id}`)'

    # objects have id only
    if isinstance(thing, discord.Object):
        message = f'`{thing.id}`'

    if before:
        message += ' ' + before
    if created:
        message += f', created {ago(thing.created_at)}'
    if joined and isinstance(thing, discord.Member):
        message += f', joined {ago(thing.joined_at)}'
    return message
<commit_msg>fix broken typehints in formatting<commit_after>import logging
import datetime
import urllib.parse
from html.parser import HTMLParser
from typing import Dict, Any, List, Union, Callable, Set, TypeVar, Type

import discord
import timeago
from discord import Message, Member, Embed
from discord.utils import maybe_coroutine

log = logging.getLogger(__name__)

class MLStripper(HTMLParser):
    def __init__(self):
        super().__init__()
        self.reset()
        self.strict = False
        self.convert_charrefs = True
        self.fed = []

    def handle_data(self, d):
        self.fed.append(d)

    def get_data(self):
        return ''.join(self.fed)

def user_format(format_string: str, parameters: Dict[Any, Any]) -> str:
    """Like .format, but for user input."""
    result = format_string

    for key, value in parameters.items():
        result = result.replace('{' + key + '}', str(value))

    return result

async def history_reducer(ctx, reducer: Callable[[Message], Any], *,
                          ignore_duplicates=False, result_container_type: Type=list, **kwargs) -> Union[List, Set]:
    """
    Iterates through message history, and outputs a list of items populated by a function that receives each
    message.

    Parameters
    ----------
    ctx
        The command context.
    reducer
        The callable reducer. Results that aren't falsy are added to the result container.
    ignore_duplicates
        Specifies whether duplicates should be ignored.
    result_container_type
        Specifies the type of result container. Should be either ``list`` or ``set``.
    kwargs
        The kwargs to pass to the ``ctx.history`` class.

    Returns
    -------
        The list of items.
    """
    if 'limit' not in kwargs:
        raise TypeError('limit required')

    history: List[Message] = await ctx.history(limit=kwargs['limit']).flatten()
    results: Union[List, Set] = result_container_type()

    for message in history:
        result = await maybe_coroutine(reducer, message)

        if result:
            if ignore_duplicates and result in results:
                continue

            if isinstance(results, list):
                results.append(result)
            elif isinstance(results, set):
                results.add(results)

    return results

def format_dict(d: Dict[Any, Any], *, style='equals') -> str:
    """
    Formats a ``dict`` to appear in key-value style.

    Parameters
    ----------
    d
        The ``dict`` to format.
    style
        The style to format the dict.

    Returns
    -------
    str
        The formatted ``dict``, as a ``str``.
    """
    code_block = '```{}\n'.format('ini' if style == 'ini' else '')

    # calculate the longest key
    padding = len(max(d.keys(), key=len))

    for name, value in d.items():
        if style == 'equals':
            code_block += '{name: <{width}} = {value}\n'.format(name=name, width=padding, value=value)
        elif style == 'ini':
            code_block += '{name: <{width}} {value}\n'.format(name=f'[{name}]', width=padding + 2, value=value)

    return code_block + '```'

def prevent_codeblock_breakout(text: str) -> str:
    """
    Formats text to prevent "breaking out" of a codeblock.

    Parameters
    ----------
    text
        The text to format.

    Returns
    -------
    str
        The formatted text.
    """
    return text.replace('`', '\u200b`\u200b')

def make_profile_embed(member: Member) -> Embed:
    """
    Creates an embed with the author containing the :class:`discord.Member`'s username and discriminator, along
    with their icon.

    Parameters
    ----------
    member
        The member to use in the :class:`discord.Embed`

    Returns
    -------
    :class:`discord.Embed`
        The resulting embed.
    """
    return Embed().set_author(name=str(member), icon_url=member.avatar_url)

def codeblock(text: str, *, lang: str='') -> str:
    """
    Formats a codeblock.

    Parameters
    ----------
    text
        The text to be inside of the codeblock.
    lang
        The language to use.

    Returns
    -------
    str
        The formatted message.
    """
    return f'```{lang}\n{text}\n```'

def strip_tags(text: str) -> str:
    """
    Strips HTML tags from text.

    Parameters
    ----------
    text
        The text to strip.

    Returns
    -------
    str
        The stripped text.
    """
    s = MLStripper()
    s.feed(text)
    return s.get_data()

def urlescape(text: str) -> str:
    """
    Quotes text using urllib to be included in URIs.

    Parameters
    ----------
    text
        The text to quote.

    Returns
    -------
    str
        The quoted text.
    """
    return urllib.parse.quote_plus(text)

def standard_datetime(dt: datetime.datetime):
    """
    Returns a string representing a :class:`datetime.datetime` formatted a nice way: ::

        YEAR-MONTH-DAY HOUR:MINUTE:SECOND

    Parameters
    ----------
    dt
        The :class:`datetime.datetime` to format.
    """
    return dt.strftime('%Y-%m-%d %H:%M:%S')

def format_list(lst: List[Any]) -> str:
    """
    Returns a string representing a list as an ordered list. List numerals are padded to ensure that there are at
    least 3 digits.

    Parameters
    ----------
    lst
        The list to format.

    Returns
    -------
    str
        The formatted string.
    """
    return '\n'.join('`{:03d}`: {}'.format(index + 1, value) for index, value in enumerate(lst))

def now() -> str:
    """
    Returns a string representing the current time, formatted with :func:`standard_datetime`.
    """
    """ Returns an Semistandard-formatted datetime with a "UTC" suffix. """
    return standard_datetime(datetime.datetime.utcnow()) + ' UTC'

def ago(dt: datetime.datetime) -> str:
    """
    Returns a string representing the amount of time since a datetime.

    Parameters
    ----------
    dt
        The datetime to process.
    """
    return timeago.format(dt, datetime.datetime.utcnow())

def truncate(text: str, desired_length: int):
    """
    Truncates text to a desired length.

    If the text is truncated, the last three characters are overwritten with ``...``

    Parameters
    ----------
    text
        The text to truncate.
    desired_length
        The desired length.

    Returns
    -------
    str
        The truncated string.
    """
    if len(text) > desired_length:
        return text[:desired_length - 3] + '...'
    return text

def commas(number: Union[int, float]) -> str:
    """
    Adds American-style commas to an number, then returns it as a str.
    """
    return '{:,d}'.format(number)

def filesize(byte_size: int) -> str:
    """
    Converts an byte size to a human-readable filesize.

    At this time, it only supports MB and KB.

    Parameters
    ----------
    byte_size
        The amount of bytes.

    Returns
    -------
    str
        The human-readable filesize.
    """
    if bytes > 10 ** 5 * 5:  # 0.5 MB
        return f'{round(byte_size / 10 ** 6, 2)} MB'
    else:
        return f'{round(byte_size / 1000, 2)} KB'

def describe(thing: Any, *, mention=False, before='', created=False, joined=False, quote=False):
    """
    Returns a string representing an project. Usually consists of the object in string form,
    then the object's ID in parentheses after.

    Parameters
    ----------
    thing
        The thing to describe. Usually a superclass of :class:`discord.Object`.
    mention
        Specifies whether to mention the thing instead of using its string representation.
    before
        Specifies text to insert after name and ID.
    created
        Specifies whether to append the ``created_at`` attribute, post-processed with :func:`ago`.
    joined
        Specifies whether to append the ``joined_at`` attribute, post-processed with :func:`ago`.
    quote
        Specifies whether to quote the name of the thing.
    """

    # get name, might be mention
    name = str(thing) if not mention else thing.mention

    # handle emoji specially
    if isinstance(thing, discord.Emoji):
        name = f'`{":" + thing.name + ":" if thing.require_colons else thing.name}`'

    if quote:
        name = '"' + name + '"'

    # name + id
    message = f'{name} (`{thing.id}`)'

    # objects have id only
    if isinstance(thing, discord.Object):
        message = f'`{thing.id}`'

    if before:
        message += ' ' + before
    if created:
        message += f', created {ago(thing.created_at)}'
    if joined and isinstance(thing, discord.Member):
        message += f', joined {ago(thing.joined_at)}'
    return message
<|endoftext|>