<commit_before># -*- coding: utf-8 -*-
import operator
import functools
import copy
import numpy as np
from bohrium_api import _bh_api
from . import _dtype_util

class BhBase(object):
    def __init__(self, dtype, nelem):
        self.dtype = _dtype_util.type_to_dtype(dtype)
        self._bh_dtype_enum = _dtype_util.np2bh_enum(self.dtype)
        self.nelem = nelem
        self.itemsize = _dtype_util.size_of(self.dtype)
        self.nbytes = nelem * self.itemsize
        if self.nelem == 0:
            self._bhc_handle = None
        else:
            self._bhc_handle = _bh_api.new(self._bh_dtype_enum, self.nelem)

    def __del__(self):
        if hasattr(self, '_bhc_handle') and self._bhc_handle is not None:
            _bh_api.destroy(self._bh_dtype_enum, self._bhc_handle)

    def __str__(self):
        return str(self.copy2numpy())

class BhArray(object):
    def __init__(self, shape, dtype, stride=None, offset=0, base=None):
        if np.isscalar(shape):
            shape = (shape,)
        self.dtype = _dtype_util.type_to_dtype(dtype)
        self._bh_dtype_enum = _dtype_util.np2bh_enum(self.dtype)
        if len(shape) == 0:
            self.nelem = 0
        else:
            self.nelem = functools.reduce(operator.mul, shape)
        if base is None:
            base = BhBase(self.dtype, self.nelem)
        assert (self.dtype == base.dtype)
        if stride is None:
            stride = [0] * len(shape)
            s = 1
            for i in range(len(shape)):
                stride[len(shape) - i - 1] = s
                s *= shape[i]
        self.base = base
        self.shape = tuple(shape)
        self.stride = tuple(stride)
        self.offset = offset
        if self.nelem == 0:
            self._bhc_handle = None
        else:
            self._bhc_handle = _bh_api.view(self._bh_dtype_enum, base._bhc_handle, len(shape),
                                            int(offset), list(shape), list(stride))

    @classmethod
    def fromNumpy(cls, numpy_array):
        numpy_array = np.require(numpy_array, requirements=['C_CONTIGUOUS', 'ALIGNED', 'OWNDATA'])
        ret = cls(numpy_array.shape, numpy_array.dtype, stride=[s // numpy_array.itemsize for s in numpy_array.strides])
        _bh_api.copy_from_memory_view(ret._bh_dtype_enum, ret._bhc_handle, memoryview(numpy_array))
        return ret

    def __del__(self):
        if hasattr(self, '_bhc_handle') and self._bhc_handle is not None:
            _bh_api.destroy(self.base._bh_dtype_enum, self._bhc_handle)

    def __str__(self):
        return str(self.asnumpy())

    def view(self):
        return copy.deepcopy(self)

    def asnumpy(self, flush=True):
        if self.nelem == 0:
            raise RuntimeError("The size of the zero!")
        if flush:
            _bh_api.flush()
        data = _bh_api.data_get(self._bh_dtype_enum, self._bhc_handle, True, True, False, self.base.nbytes)
        ret = np.frombuffer(data, dtype=self.dtype, offset=self.offset * self.base.itemsize)
        return np.lib.stride_tricks.as_strided(ret, self.shape, [s * self.base.itemsize for s in self.stride])

    def copy2numpy(self, flush=True):
        if self.nelem == 0:
            return np.array([], self.dtype)
        else:
            return self.asnumpy(flush).copy()

    def fill(self, value):
        """Fill the array with a scalar value.

            Parameters
            ----------
            value : scalar
                All elements of `a` will be assigned this value.

            Examples
            --------
            >>> a = bh.array([1, 2])
            >>> a.fill(0)
            >>> a
            array([0, 0])
            >>> a = bh.empty(2)
            >>> a.fill(1)
            >>> a
            array([ 1.,  1.])
            """
        from .ufuncs import assign
        assign(value, self)

    def astype(self, dtype, always_copy=True):
        from .ufuncs import assign
        if not always_copy and self.dtype == dtype:
            return self
        ret = BhArray(self.shape, dtype)
        assign(self, ret)
        return ret

    # Binary Operators
    def __add__(self, other):
        from .ufuncs import ufunc_dict
        return ufunc_dict['add'](self, other)

    def __iadd__(self, other):
        from .ufuncs import ufunc_dict
        return ufunc_dict['add'](self, other, self)

    def __sub__(self, other):
        from .ufuncs import ufunc_dict
        return ufunc_dict['subtract'](self, other)

    def __isub__(self, other):
        from .ufuncs import ufunc_dict
        return ufunc_dict['subtract'](self, other, self)

    def __mul__(self, other):
        from .ufuncs import ufunc_dict
        return ufunc_dict['multiply'](self, other)

    def __imul__(self, other):
        from .ufuncs import ufunc_dict
        return ufunc_dict['multiply'](self, other, self)

    def __floordiv__(self, other):
        from .ufuncs import ufunc_dict
        return ufunc_dict['floor_divide'](self, other)

    def __ifloordiv__(self, other):
        from .ufuncs import ufunc_dict
        return ufunc_dict['floor_divide'](self, other, self)

    def __div__(self, other):
        from .ufuncs import ufunc_dict
        return ufunc_dict['true_divide'](self, other)

    def __idiv__(self, other):
        from .ufuncs import ufunc_dict
        return ufunc_dict['true_divide'](self, other, self)

    def __mod__(self, other):
        from .ufuncs import ufunc_dict
        return ufunc_dict['mod'](self, other)

    def __imod__(self, other):
        from .ufuncs import ufunc_dict
        return ufunc_dict['mod'](self, other, self)

    def __pow__(self, other):
        from .ufuncs import ufunc_dict
        return ufunc_dict['power'](self, other)

    def __ipow__(self, other):
        from .ufuncs import ufunc_dict
        return ufunc_dict['power'](self, other, self)

    def __and__(self, other):
        from .ufuncs import ufunc_dict
        return ufunc_dict['bitwise_and'](self, other)

    def __iand__(self, other):
        from .ufuncs import ufunc_dict
        return ufunc_dict['bitwise_and'](self, other, self)

    def __xor__(self, other):
        from .ufuncs import ufunc_dict
        return ufunc_dict['bitwise_xor'](self, other)

    def __ixor__(self, other):
        from .ufuncs import ufunc_dict
        return ufunc_dict['bitwise_xor'](self, other, self)

    def __or__(self, other):
        from .ufuncs import ufunc_dict
        return ufunc_dict['bitwise_or'](self, other)

    def __ior__(self, other):
        from .ufuncs import ufunc_dict
        return ufunc_dict['bitwise_or'](self, other, self)

    # Unary Operators
    def __neg__(self, other):
        from .ufuncs import ufunc_dict
        return ufunc_dict['negative'](self, other)

    def __abs__(self, other):
        from .ufuncs import ufunc_dict
        return ufunc_dict['absolute'](self, other)

    def __invert__(self, other):
        from .ufuncs import ufunc_dict
        return ufunc_dict['invert'](self, other)
<commit_msg>bh107: implemented iscontiguous() and reshape()<commit_after># -*- coding: utf-8 -*-
import operator
import functools
import copy
import numpy as np
from bohrium_api import _bh_api
from . import _dtype_util

class BhBase(object):
    def __init__(self, dtype, nelem):
        self.dtype = _dtype_util.type_to_dtype(dtype)
        self._bh_dtype_enum = _dtype_util.np2bh_enum(self.dtype)
        self.nelem = nelem
        self.itemsize = _dtype_util.size_of(self.dtype)
        self.nbytes = nelem * self.itemsize
        if self.nelem == 0:
            self._bhc_handle = None
        else:
            self._bhc_handle = _bh_api.new(self._bh_dtype_enum, self.nelem)

    def __del__(self):
        if hasattr(self, '_bhc_handle') and self._bhc_handle is not None:
            _bh_api.destroy(self._bh_dtype_enum, self._bhc_handle)

    def __str__(self):
        return str(self.copy2numpy())

class BhArray(object):
    def __init__(self, shape, dtype, stride=None, offset=0, base=None):
        if np.isscalar(shape):
            shape = (shape,)
        self.dtype = _dtype_util.type_to_dtype(dtype)
        self._bh_dtype_enum = _dtype_util.np2bh_enum(self.dtype)
        if len(shape) == 0:
            self.nelem = 0
        else:
            self.nelem = functools.reduce(operator.mul, shape)
        if base is None:
            base = BhBase(self.dtype, self.nelem)
        assert (self.dtype == base.dtype)
        if stride is None:
            stride = [0] * len(shape)
            s = 1
            for i in range(len(shape)):
                stride[len(shape) - i - 1] = s
                s *= shape[i]
        self.base = base
        self.shape = tuple(shape)
        self.stride = tuple(stride)
        self.offset = offset
        if self.nelem == 0:
            self._bhc_handle = None
        else:
            self._bhc_handle = _bh_api.view(self._bh_dtype_enum, base._bhc_handle, len(shape),
                                            int(offset), list(shape), list(stride))

    @classmethod
    def fromNumpy(cls, numpy_array):
        numpy_array = np.require(numpy_array, requirements=['C_CONTIGUOUS', 'ALIGNED', 'OWNDATA'])
        ret = cls(numpy_array.shape, numpy_array.dtype, stride=[s // numpy_array.itemsize for s in numpy_array.strides])
        _bh_api.copy_from_memory_view(ret._bh_dtype_enum, ret._bhc_handle, memoryview(numpy_array))
        return ret

    def __del__(self):
        if hasattr(self, '_bhc_handle') and self._bhc_handle is not None:
            _bh_api.destroy(self.base._bh_dtype_enum, self._bhc_handle)

    def __str__(self):
        return str(self.asnumpy())

    def view(self):
        return copy.deepcopy(self)

    def asnumpy(self, flush=True):
        if self.nelem == 0:
            raise RuntimeError("The size of the zero!")
        if flush:
            _bh_api.flush()
        data = _bh_api.data_get(self._bh_dtype_enum, self._bhc_handle, True, True, False, self.base.nbytes)
        ret = np.frombuffer(data, dtype=self.dtype, offset=self.offset * self.base.itemsize)
        return np.lib.stride_tricks.as_strided(ret, self.shape, [s * self.base.itemsize for s in self.stride])

    def copy2numpy(self, flush=True):
        if self.nelem == 0:
            return np.array([], self.dtype)
        else:
            return self.asnumpy(flush).copy()

    def fill(self, value):
        """Fill the array with a scalar value.

            Parameters
            ----------
            value : scalar
                All elements of `a` will be assigned this value.

            Examples
            --------
            >>> a = bh.array([1, 2])
            >>> a.fill(0)
            >>> a
            array([0, 0])
            >>> a = bh.empty(2)
            >>> a.fill(1)
            >>> a
            array([ 1.,  1.])
            """
        from .ufuncs import assign
        assign(value, self)

    def astype(self, dtype, always_copy=True):
        from .ufuncs import assign
        if not always_copy and self.dtype == dtype:
            return self
        ret = BhArray(self.shape, dtype)
        assign(self, ret)
        return ret

    def iscontiguous(self):
        acc = 1
        for shape, stride in zip(self.shape, self.stride):
            if shape > 1 and stride != acc:
                return False
            else:
                acc *= shape
        return True

    def reshape(self, shape):
        from .ufuncs import assign
        length = self.nelem = functools.reduce(operator.mul, shape)
        if length != self.nelem:
            raise RuntimeError("Total size cannot change when reshaping")

        if self.iscontiguous():
            return BhArray(shape, self.dtype, offset=self.offset, base=self.base)
        else:
            ret = BhArray(shape, self.dtype)
            assign(self, ret)
            return ret

    # Binary Operators
    def __add__(self, other):
        from .ufuncs import ufunc_dict
        return ufunc_dict['add'](self, other)

    def __iadd__(self, other):
        from .ufuncs import ufunc_dict
        return ufunc_dict['add'](self, other, self)

    def __sub__(self, other):
        from .ufuncs import ufunc_dict
        return ufunc_dict['subtract'](self, other)

    def __isub__(self, other):
        from .ufuncs import ufunc_dict
        return ufunc_dict['subtract'](self, other, self)

    def __mul__(self, other):
        from .ufuncs import ufunc_dict
        return ufunc_dict['multiply'](self, other)

    def __imul__(self, other):
        from .ufuncs import ufunc_dict
        return ufunc_dict['multiply'](self, other, self)

    def __floordiv__(self, other):
        from .ufuncs import ufunc_dict
        return ufunc_dict['floor_divide'](self, other)

    def __ifloordiv__(self, other):
        from .ufuncs import ufunc_dict
        return ufunc_dict['floor_divide'](self, other, self)

    def __div__(self, other):
        from .ufuncs import ufunc_dict
        return ufunc_dict['true_divide'](self, other)

    def __idiv__(self, other):
        from .ufuncs import ufunc_dict
        return ufunc_dict['true_divide'](self, other, self)

    def __mod__(self, other):
        from .ufuncs import ufunc_dict
        return ufunc_dict['mod'](self, other)

    def __imod__(self, other):
        from .ufuncs import ufunc_dict
        return ufunc_dict['mod'](self, other, self)

    def __pow__(self, other):
        from .ufuncs import ufunc_dict
        return ufunc_dict['power'](self, other)

    def __ipow__(self, other):
        from .ufuncs import ufunc_dict
        return ufunc_dict['power'](self, other, self)

    def __and__(self, other):
        from .ufuncs import ufunc_dict
        return ufunc_dict['bitwise_and'](self, other)

    def __iand__(self, other):
        from .ufuncs import ufunc_dict
        return ufunc_dict['bitwise_and'](self, other, self)

    def __xor__(self, other):
        from .ufuncs import ufunc_dict
        return ufunc_dict['bitwise_xor'](self, other)

    def __ixor__(self, other):
        from .ufuncs import ufunc_dict
        return ufunc_dict['bitwise_xor'](self, other, self)

    def __or__(self, other):
        from .ufuncs import ufunc_dict
        return ufunc_dict['bitwise_or'](self, other)

    def __ior__(self, other):
        from .ufuncs import ufunc_dict
        return ufunc_dict['bitwise_or'](self, other, self)

    # Unary Operators
    def __neg__(self, other):
        from .ufuncs import ufunc_dict
        return ufunc_dict['negative'](self, other)

    def __abs__(self, other):
        from .ufuncs import ufunc_dict
        return ufunc_dict['absolute'](self, other)

    def __invert__(self, other):
        from .ufuncs import ufunc_dict
        return ufunc_dict['invert'](self, other)
<|endoftext|>


<commit_before># coding: utf-8

""" Evolution of frequencies for an ensemble of orbits. """

from __future__ import division, print_function

__author__ = "adrn <adrn@astro.columbia.edu>"

# Standard library
import os
import sys

# Third-party
from astropy import log as logger
import astropy.units as u
import matplotlib as mpl
import matplotlib.pyplot as plt
import numpy as np
import gary.dynamics as gd
import gary.integrate as gi
import gary.potential as gp
from gary.util import rolling_window, get_pool

# Project
from streammorphology import project_path
from streammorphology.freqmap import estimate_dt_nsteps
from streammorphology.ensemble import create_ball

# integration
nsteps_per_period = 512
nperiods = 100

# ensemble properties
nensemble = 100
m_scale = 1E4

# windowing properties
window_width = 50 * nsteps_per_period
window_stride = 1 * nsteps_per_period

def worker(task):
    dt = task['dt']
    nsteps = task['nsteps']
    w0 = task['w0']
    potential = task['potential']

    t,w = potential.integrate_orbit(w0, dt=dt, nsteps=nsteps,
                                    Integrator=gi.DOPRI853Integrator)

    freqs = []
    for (i1,i2),ww in rolling_window(w, window_size=window_width,
                                     stride=window_stride, return_idx=True):
        if i2 >= nsteps:
            break

        fs = [(ww[:,0,i]+1j*ww[:,0,i+3]) for i in range(3)]
        naff = gd.NAFF(t[i1:i2], p=4)
        try:
            f,d,ixes = naff.find_fundamental_frequencies(fs, nintvec=5)
        except:
            f = np.ones(3)*np.nan
        freqs.append(f)

    return freqs

def main(name, mpi=False, threads=None, plot=False):
    outpath = os.path.join(project_path, "output/tests/ensemble_evolution")
    if not os.path.exists(outpath):
        os.makedirs(outpath)

    # load potential
    potential = gp.load(os.path.join(project_path,"potentials/triaxial-NFW.yml"))

    if name == 'regular':
        w0 = np.array([27.300000000000008, 0.0, 1.1000000000000003, 0.0, 0.1877759468430073, 0.0]) # regular
    elif name == 'chaotic':
        w0 = np.array([27.300000000000008, 0.0, 21.900000000000006, 0.0, 0.11374625738916841, 0.0]) # chaotic
    elif name == 'mildly_chaotic':
        w0 = np.array([27.300000000000008, 0.0, 20.300000000000004, 0.0, 0.12395598334095129, 0.0]) # mild chaos
    elif name == 'pal5':
        potential = gp.load(os.path.join(project_path,"potentials/lm10.yml")) # pal5 fanning
        w0 = np.array([8.312877511, 0.242593717, 16.811943627, -0.053619865077559205, -0.09889356946871429, -0.008341373370759497])
    else:
        raise ValueError()

    filename = os.path.join(outpath, '{0}_window_freqs.npy'.format(name))
    if not os.path.exists(filename):

        # get a pool object for multiprocessing / MPI
        pool = get_pool(mpi=mpi, threads=threads)

        # get integration parameters
        dt,nsteps,T = estimate_dt_nsteps(potential, w0,
                                         nperiods=nperiods,
                                         nsteps_per_period=nsteps_per_period,
                                         return_periods=True)

        # create an ensemble around the parent orbit
        ball_w0 = create_ball(w0, potential, N=nensemble, m_scale=m_scale)
        ball_w0[:,3:] = w0[None,3:]

        tasks = []
        for n,w0 in enumerate(ball_w0):
            task = dict()
            task['dt'] = dt
            task['nsteps'] = nsteps
            task['w0'] = w0
            task['potential'] = potential
            tasks.append(task)

        results = pool.map(worker, tasks)
        pool.close()

        all_freqs = np.array(results)
        np.save(filename, all_freqs)

    else:
        all_freqs = np.load(filename)

    if plot:
        plt.figure(figsize=(10,8))
        plt.plot(all_freqs.T[0]*1000., c='k', alpha=0.4)

        plt.figure(figsize=(10,8))

        ff = np.median(all_freqs[:,0], axis=0)
        root_var = np.sqrt(np.sum(np.var(all_freqs, axis=1)/ff**2, axis=-1))
        plt.plot(root_var, c='k', alpha=1.)
        plt.ylim(0.1,1)
        plt.ylabel(r'$\sigma_\Omega/\Omega$')

        plt.figure(figsize=(10,10))
        r1 = all_freqs[...,0] / all_freqs[...,2]
        r2 = all_freqs[...,1] / all_freqs[...,2]
        plt.plot(r1, r2, linestyle='none', marker='.', c='k', alpha=0.5)
        plt.plot(r1[:,0], r2[:,0], linestyle='none', marker='o', c='g', alpha=0.5)
        plt.plot(r1[:,-1], r2[:,-1], linestyle='none', marker='o', c='r', alpha=0.5)
        plt.xlabel(r'$\Omega_1/\Omega_3$')
        plt.ylabel(r'$\Omega_2/\Omega_3$')

        plt.figure(figsize=(10,10))
        r1 = all_freqs[...,0]*1000
        r2 = all_freqs[...,1]*1000
        plt.plot(r1, r2, linestyle='none', marker='.', c='k', alpha=0.5)
        plt.plot(r1[:,0], r2[:,0], linestyle='none', marker='o', c='g', alpha=0.5)
        plt.plot(r1[:,-1], r2[:,-1], linestyle='none', marker='o', c='r', alpha=0.5)
        plt.xlabel(r'$\Omega_1$ [Gyr$^{-1}$]')
        plt.ylabel(r'$\Omega_2$ [Gyr$^{-1}$]')

        plt.figure(figsize=(10,10))
        r1 = all_freqs[...,0]*1000
        r2 = all_freqs[...,2]*1000
        plt.plot(r1, r2, linestyle='none', marker='.', c='k', alpha=0.5)
        plt.plot(r1[:,0], r2[:,0], linestyle='none', marker='o', c='g', alpha=0.5)
        plt.plot(r1[:,-1], r2[:,-1], linestyle='none', marker='o', c='r', alpha=0.5)
        plt.xlabel(r'$\Omega_1$ [Gyr$^{-1}$]')
        plt.ylabel(r'$\Omega_3$ [Gyr$^{-1}$]')

        plt.show()

if __name__ == "__main__":
    from argparse import ArgumentParser

    parser = ArgumentParser(description="")

    # threading
    parser.add_argument("--name", dest="name", required=True, type=str,
                        help="Name: regular or chaotic")
    parser.add_argument("--mpi", dest="mpi", default=False, action="store_true",
                        help="Run with MPI.")
    parser.add_argument("--threads", dest="threads", default=None, type=int,
                        help="Number of multiprocessing threads to run on.")

    parser.add_argument("--plot", dest="plot", default=False, action="store_true",
                        help="Show dem plots.")
    args = parser.parse_args()

    main(args.name, mpi=args.mpi, threads=args.threads, plot=args.plot)
<commit_msg>change window width<commit_after># coding: utf-8

""" Evolution of frequencies for an ensemble of orbits. """

from __future__ import division, print_function

__author__ = "adrn <adrn@astro.columbia.edu>"

# Standard library
import os
import sys

# Third-party
from astropy import log as logger
import astropy.units as u
import matplotlib as mpl
import matplotlib.pyplot as plt
import numpy as np
import gary.dynamics as gd
import gary.integrate as gi
import gary.potential as gp
from gary.util import rolling_window, get_pool

# Project
from streammorphology import project_path
from streammorphology.freqmap import estimate_dt_nsteps
from streammorphology.ensemble import create_ball

# integration
nsteps_per_period = 512
nperiods = 100

# ensemble properties
nensemble = 100
m_scale = 1E4

# windowing properties
window_width = 25 * nsteps_per_period
window_stride = 0.5 * nsteps_per_period

def worker(task):
    dt = task['dt']
    nsteps = task['nsteps']
    w0 = task['w0']
    potential = task['potential']

    t,w = potential.integrate_orbit(w0, dt=dt, nsteps=nsteps,
                                    Integrator=gi.DOPRI853Integrator)

    freqs = []
    for (i1,i2),ww in rolling_window(w, window_size=window_width,
                                     stride=window_stride, return_idx=True):
        if i2 >= nsteps:
            break

        fs = [(ww[:,0,i]+1j*ww[:,0,i+3]) for i in range(3)]
        naff = gd.NAFF(t[i1:i2], p=4)
        try:
            f,d,ixes = naff.find_fundamental_frequencies(fs, nintvec=5)
        except:
            f = np.ones(3)*np.nan
        freqs.append(f)

    return freqs

def main(name, mpi=False, threads=None, plot=False):
    outpath = os.path.join(project_path, "output/tests/ensemble_evolution")
    if not os.path.exists(outpath):
        os.makedirs(outpath)

    # load potential
    potential = gp.load(os.path.join(project_path,"potentials/triaxial-NFW.yml"))

    if name == 'regular':
        w0 = np.array([27.300000000000008, 0.0, 1.1000000000000003, 0.0, 0.1877759468430073, 0.0]) # regular
    elif name == 'chaotic':
        w0 = np.array([27.300000000000008, 0.0, 21.900000000000006, 0.0, 0.11374625738916841, 0.0]) # chaotic
    elif name == 'mildly_chaotic':
        w0 = np.array([27.300000000000008, 0.0, 20.300000000000004, 0.0, 0.12395598334095129, 0.0]) # mild chaos
    elif name == 'pal5':
        potential = gp.load(os.path.join(project_path,"potentials/lm10.yml")) # pal5 fanning
        w0 = np.array([8.312877511, 0.242593717, 16.811943627, -0.053619865077559205, -0.09889356946871429, -0.008341373370759497])
    else:
        raise ValueError()

    filename = os.path.join(outpath, '{0}_window_freqs.npy'.format(name))
    if not os.path.exists(filename):

        # get a pool object for multiprocessing / MPI
        pool = get_pool(mpi=mpi, threads=threads)

        # get integration parameters
        dt,nsteps,T = estimate_dt_nsteps(potential, w0,
                                         nperiods=nperiods,
                                         nsteps_per_period=nsteps_per_period,
                                         return_periods=True)

        # create an ensemble around the parent orbit
        ball_w0 = create_ball(w0, potential, N=nensemble, m_scale=m_scale)
        ball_w0[:,3:] = w0[None,3:]

        tasks = []
        for n,w0 in enumerate(ball_w0):
            task = dict()
            task['dt'] = dt
            task['nsteps'] = nsteps
            task['w0'] = w0
            task['potential'] = potential
            tasks.append(task)

        results = pool.map(worker, tasks)
        pool.close()

        all_freqs = np.array(results)
        np.save(filename, all_freqs)

    else:
        all_freqs = np.load(filename)

    if plot:
        plt.figure(figsize=(10,8))
        plt.plot(all_freqs.T[0]*1000., c='k', alpha=0.4)

        plt.figure(figsize=(10,8))

        ff = np.median(all_freqs[:,0], axis=0)
        root_var = np.sqrt(np.sum(np.var(all_freqs, axis=1)/ff**2, axis=-1))
        plt.plot(root_var, c='k', alpha=1.)
        plt.ylim(0.1,1)
        plt.ylabel(r'$\sigma_\Omega/\Omega$')

        plt.figure(figsize=(10,10))
        r1 = all_freqs[...,0] / all_freqs[...,2]
        r2 = all_freqs[...,1] / all_freqs[...,2]
        plt.plot(r1, r2, linestyle='none', marker='.', c='k', alpha=0.5)
        plt.plot(r1[:,0], r2[:,0], linestyle='none', marker='o', c='g', alpha=0.5)
        plt.plot(r1[:,-1], r2[:,-1], linestyle='none', marker='o', c='r', alpha=0.5)
        plt.xlabel(r'$\Omega_1/\Omega_3$')
        plt.ylabel(r'$\Omega_2/\Omega_3$')

        plt.figure(figsize=(10,10))
        r1 = all_freqs[...,0]*1000
        r2 = all_freqs[...,1]*1000
        plt.plot(r1, r2, linestyle='none', marker='.', c='k', alpha=0.5)
        plt.plot(r1[:,0], r2[:,0], linestyle='none', marker='o', c='g', alpha=0.5)
        plt.plot(r1[:,-1], r2[:,-1], linestyle='none', marker='o', c='r', alpha=0.5)
        plt.xlabel(r'$\Omega_1$ [Gyr$^{-1}$]')
        plt.ylabel(r'$\Omega_2$ [Gyr$^{-1}$]')

        plt.figure(figsize=(10,10))
        r1 = all_freqs[...,0]*1000
        r2 = all_freqs[...,2]*1000
        plt.plot(r1, r2, linestyle='none', marker='.', c='k', alpha=0.5)
        plt.plot(r1[:,0], r2[:,0], linestyle='none', marker='o', c='g', alpha=0.5)
        plt.plot(r1[:,-1], r2[:,-1], linestyle='none', marker='o', c='r', alpha=0.5)
        plt.xlabel(r'$\Omega_1$ [Gyr$^{-1}$]')
        plt.ylabel(r'$\Omega_3$ [Gyr$^{-1}$]')

        plt.show()

if __name__ == "__main__":
    from argparse import ArgumentParser

    parser = ArgumentParser(description="")

    # threading
    parser.add_argument("--name", dest="name", required=True, type=str,
                        help="Name: regular or chaotic")
    parser.add_argument("--mpi", dest="mpi", default=False, action="store_true",
                        help="Run with MPI.")
    parser.add_argument("--threads", dest="threads", default=None, type=int,
                        help="Number of multiprocessing threads to run on.")

    parser.add_argument("--plot", dest="plot", default=False, action="store_true",
                        help="Show dem plots.")
    args = parser.parse_args()

    main(args.name, mpi=args.mpi, threads=args.threads, plot=args.plot)
<|endoftext|>


<commit_before>"""
Tests for the usage of the mock.
"""

import base64
import datetime
import io
import socket
import string
import uuid

import pytest
import requests
from hypothesis import given
from hypothesis.strategies import text
from requests import codes
from requests_mock.exceptions import NoMockAddress

from common.constants import TargetStatuses
from mock_vws import MockVWS
from tests.mock_vws.utils import (
    add_target_to_vws,
    database_summary,
    get_vws_target,
)
from tests.utils import VuforiaDatabaseKeys
from vws._request_utils import rfc_1123_date

def request_unmocked_address() -> None:
    """
    Make a request, using `requests` to an unmocked, free local address.

    Raises:
        requests.exceptions.ConnectionError: This is expected as there is
            nothing to connect to.
        requests_mock.exceptions.NoMockAddress: This request is being made in
            the context of a `requests_mock` mock which does not mock local
            addresses.
    """
    sock = socket.socket()
    sock.bind(('', 0))
    port = sock.getsockname()[1]
    sock.close()
    address = 'http://localhost:{free_port}'.format(free_port=port)
    requests.get(address)

def request_mocked_address() -> None:
    """
    Make a request, using `requests` to an address that is mocked by `MockVWS`.
    """
    requests.get(
        url='https://vws.vuforia.com/summary',
        headers={
            'Date': rfc_1123_date(),
            'Authorization': 'bad_auth_token',
        },
        data=b'',
    )

def assert_valid_server_credentials(
    server_access_key: str,
    server_secret_key: str,
) -> None:
    """
    Given server credentials, assert that they can authenticate with a Vuforia
    database.

    Raises:
        AssertionError: The given credentials fail to authenticate with a
            Vuforia database.
    """
    credentials = VuforiaDatabaseKeys(
        database_name=uuid.uuid4().hex,
        server_access_key=server_access_key,
        server_secret_key=server_secret_key,
        client_access_key=uuid.uuid4().hex,
        client_secret_key=uuid.uuid4().hex,
    )

    response = get_vws_target(
        vuforia_database_keys=credentials,
        target_id=uuid.uuid4().hex,
    )

    # This shows that the response does not include an authentication
    # error which is what would happen if the keys were incorrect.
    assert response.status_code == codes.NOT_FOUND

class TestRealHTTP:
    """
    Tests for making requestsd to mocked and unmocked addresses.
    """

    def test_default(self) -> None:
        """
        By default, the mock stops any requests made with `requests` to
        non-Vuforia addresses, but not to mocked Vuforia endpoints.
        """
        with MockVWS():
            with pytest.raises(NoMockAddress):
                request_unmocked_address()

            # No exception is raised when making a request to a mocked
            # endpoint.
            request_mocked_address()

        # The mocking stops when the context manager stops.
        with pytest.raises(requests.exceptions.ConnectionError):
            request_unmocked_address()

    def test_real_http(self) -> None:
        """
        When the `real_http` parameter given to the context manager is set to
        `True`, requests made to unmocked addresses are not stopped.
        """
        with MockVWS(real_http=True):
            with pytest.raises(requests.exceptions.ConnectionError):
                request_unmocked_address()

class TestProcessingTime:
    """
    XXX
    """

    def test_default(self, png_rgb: io.BytesIO) -> None:
        """
        XXX
        """
        image_data = png_rgb.read()
        image_data_encoded = base64.b64encode(image_data).decode('ascii')

        data = {
            'name': 'example',
            'width': 1,
            'image': image_data_encoded,
        }

        with MockVWS() as mock:
            vuforia_database_keys = VuforiaDatabaseKeys(
                database_name=uuid.uuid4().hex,
                server_access_key=mock.server_access_key,
                server_secret_key=mock.server_secret_key,
                client_access_key=uuid.uuid4().hex,
                client_secret_key=uuid.uuid4().hex,
            )

            response = add_target_to_vws(
                vuforia_database_keys=vuforia_database_keys,
                data=data,
            )

            target_id = response.json()['target_id']

            start_time = datetime.datetime.now()

            while True:
                response = get_vws_target(
                    vuforia_database_keys=vuforia_database_keys,
                    target_id=target_id,
                )

                status = response.json()['status']
                if status != TargetStatuses.PROCESSING.value:
                    elapsed_time = datetime.datetime.now() - start_time
                    assert elapsed_time < datetime.timedelta(seconds=0.51)
                    assert elapsed_time > datetime.timedelta(seconds=0.49)
                    return

    def test_custom(self, png_rgb: io.BytesIO) -> None:
        """
        XXX
        """
        image_data = png_rgb.read()
        image_data_encoded = base64.b64encode(image_data).decode('ascii')

        data = {
            'name': 'example',
            'width': 1,
            'image': image_data_encoded,
        }

        with MockVWS(processing_time_seconds=0.1) as mock:
            vuforia_database_keys = VuforiaDatabaseKeys(
                database_name=uuid.uuid4().hex,
                server_access_key=mock.server_access_key,
                server_secret_key=mock.server_secret_key,
                client_access_key=uuid.uuid4().hex,
                client_secret_key=uuid.uuid4().hex,
            )

            response = add_target_to_vws(
                vuforia_database_keys=vuforia_database_keys,
                data=data,
            )

            target_id = response.json()['target_id']

            start_time = datetime.datetime.now()

            while True:
                response = get_vws_target(
                    vuforia_database_keys=vuforia_database_keys,
                    target_id=target_id,
                )

                status = response.json()['status']
                if status != TargetStatuses.PROCESSING.value:
                    elapsed_time = datetime.datetime.now() - start_time
                    assert elapsed_time < datetime.timedelta(seconds=0.11)
                    assert elapsed_time > datetime.timedelta(seconds=0.09)
                    return

class TestDatabaseName:
    """
    Tests for the database name.
    """

    def test_default(self) -> None:
        """
        By default, the database has a random name.
        """
        with MockVWS() as mock:
            vuforia_database_keys = VuforiaDatabaseKeys(
                database_name=uuid.uuid4().hex,
                server_access_key=mock.server_access_key,
                server_secret_key=mock.server_secret_key,
                client_access_key=uuid.uuid4().hex,
                client_secret_key=uuid.uuid4().hex,
            )

            response = database_summary(
                vuforia_database_keys=vuforia_database_keys,
            )
            first_database_name = response.json()['name']

        with MockVWS() as mock:
            vuforia_database_keys = VuforiaDatabaseKeys(
                database_name=uuid.uuid4().hex,
                server_access_key=mock.server_access_key,
                server_secret_key=mock.server_secret_key,
                client_access_key=uuid.uuid4().hex,
                client_secret_key=uuid.uuid4().hex,
            )
            response = database_summary(
                vuforia_database_keys=vuforia_database_keys,
            )
            second_database_name = response.json()['name']

        assert first_database_name != second_database_name

    @given(database_name=text())
    def test_custom_name(
        self,
        database_name: str,
    ) -> None:
        """
        It is possible to set a custom database name.
        """
        with MockVWS(database_name=database_name) as mock:
            vuforia_database_keys = VuforiaDatabaseKeys(
                database_name=database_name,
                server_access_key=mock.server_access_key,
                server_secret_key=mock.server_secret_key,
                client_access_key=uuid.uuid4().hex,
                client_secret_key=uuid.uuid4().hex,
            )
            response = database_summary(
                vuforia_database_keys=vuforia_database_keys,
            )
            assert response.json()['name'] == database_name

class TestPersistence:
    """
    Tests for isolation between instances of the mock.
    """

    def test_context_manager(
        self,
        png_rgb: io.BytesIO,
    ) -> None:
        """
        When the context manager is used, targets are not persisted between
        invocations.
        """
        image_data = png_rgb.read()
        image_data_encoded = base64.b64encode(image_data).decode('ascii')

        data = {
            'name': 'example',
            'width': 1,
            'image': image_data_encoded,
        }

        with MockVWS() as mock:
            vuforia_database_keys = VuforiaDatabaseKeys(
                database_name=uuid.uuid4().hex,
                server_access_key=mock.server_access_key,
                server_secret_key=mock.server_secret_key,
                client_access_key=uuid.uuid4().hex,
                client_secret_key=uuid.uuid4().hex,
            )

            response = add_target_to_vws(
                vuforia_database_keys=vuforia_database_keys,
                data=data,
            )

            target_id = response.json()['target_id']

            response = get_vws_target(
                vuforia_database_keys=vuforia_database_keys,
                target_id=target_id,
            )

            assert response.status_code == codes.OK

        with MockVWS() as mock:
            vuforia_database_keys = VuforiaDatabaseKeys(
                database_name=uuid.uuid4().hex,
                server_access_key=mock.server_access_key,
                server_secret_key=mock.server_secret_key,
                client_access_key=uuid.uuid4().hex,
                client_secret_key=uuid.uuid4().hex,
            )

            response = get_vws_target(
                vuforia_database_keys=vuforia_database_keys,
                target_id=target_id,
            )

            assert response.status_code == codes.NOT_FOUND

class TestCredentials:
    """
    Tests for setting credentials for the mock.
    """

    def test_default(self) -> None:
        """
        By default the mock uses a random access key and secret key.
        """
        with MockVWS() as first_mock:
            with MockVWS() as second_mock:
                assert (
                    first_mock.server_access_key !=
                    second_mock.server_access_key
                )
                assert (
                    first_mock.server_secret_key !=
                    second_mock.server_secret_key
                )
                assert first_mock.database_name != second_mock.database_name

    # We limit this to ASCII letters because some characters are not allowed
    # in request headers (e.g. a leading space).
    @given(
        server_access_key=text(alphabet=string.ascii_letters),
        server_secret_key=text(alphabet=string.ascii_letters)
    )
    def test_custom_credentials(
        self,
        server_access_key: str,
        server_secret_key: str,
    ) -> None:
        """
        It is possible to set custom credentials.
        """
        with MockVWS(
            server_access_key=server_access_key,
            server_secret_key=server_secret_key,
        ) as mock:
            assert mock.server_access_key == server_access_key
            assert mock.server_secret_key == server_secret_key

            assert_valid_server_credentials(
                server_access_key=server_access_key,
                server_secret_key=server_secret_key,
            )
<commit_msg>Docstrings<commit_after>"""
Tests for the usage of the mock.
"""

import base64
import datetime
import io
import socket
import string
import uuid

import pytest
import requests
from hypothesis import given
from hypothesis.strategies import text
from requests import codes
from requests_mock.exceptions import NoMockAddress

from common.constants import TargetStatuses
from mock_vws import MockVWS
from tests.mock_vws.utils import (
    add_target_to_vws,
    database_summary,
    get_vws_target,
)
from tests.utils import VuforiaDatabaseKeys
from vws._request_utils import rfc_1123_date

def request_unmocked_address() -> None:
    """
    Make a request, using `requests` to an unmocked, free local address.

    Raises:
        requests.exceptions.ConnectionError: This is expected as there is
            nothing to connect to.
        requests_mock.exceptions.NoMockAddress: This request is being made in
            the context of a `requests_mock` mock which does not mock local
            addresses.
    """
    sock = socket.socket()
    sock.bind(('', 0))
    port = sock.getsockname()[1]
    sock.close()
    address = 'http://localhost:{free_port}'.format(free_port=port)
    requests.get(address)

def request_mocked_address() -> None:
    """
    Make a request, using `requests` to an address that is mocked by `MockVWS`.
    """
    requests.get(
        url='https://vws.vuforia.com/summary',
        headers={
            'Date': rfc_1123_date(),
            'Authorization': 'bad_auth_token',
        },
        data=b'',
    )

def assert_valid_server_credentials(
    server_access_key: str,
    server_secret_key: str,
) -> None:
    """
    Given server credentials, assert that they can authenticate with a Vuforia
    database.

    Raises:
        AssertionError: The given credentials fail to authenticate with a
            Vuforia database.
    """
    credentials = VuforiaDatabaseKeys(
        database_name=uuid.uuid4().hex,
        server_access_key=server_access_key,
        server_secret_key=server_secret_key,
        client_access_key=uuid.uuid4().hex,
        client_secret_key=uuid.uuid4().hex,
    )

    response = get_vws_target(
        vuforia_database_keys=credentials,
        target_id=uuid.uuid4().hex,
    )

    # This shows that the response does not include an authentication
    # error which is what would happen if the keys were incorrect.
    assert response.status_code == codes.NOT_FOUND

class TestRealHTTP:
    """
    Tests for making requestsd to mocked and unmocked addresses.
    """

    def test_default(self) -> None:
        """
        By default, the mock stops any requests made with `requests` to
        non-Vuforia addresses, but not to mocked Vuforia endpoints.
        """
        with MockVWS():
            with pytest.raises(NoMockAddress):
                request_unmocked_address()

            # No exception is raised when making a request to a mocked
            # endpoint.
            request_mocked_address()

        # The mocking stops when the context manager stops.
        with pytest.raises(requests.exceptions.ConnectionError):
            request_unmocked_address()

    def test_real_http(self) -> None:
        """
        When the `real_http` parameter given to the context manager is set to
        `True`, requests made to unmocked addresses are not stopped.
        """
        with MockVWS(real_http=True):
            with pytest.raises(requests.exceptions.ConnectionError):
                request_unmocked_address()

class TestProcessingTime:
    """
    Tests for the time taken to process targets in the mock.
    """

    def test_default(self, png_rgb: io.BytesIO) -> None:
        """
        By default, targets in the mock take 0.5 seconds to be processed.
        """
        image_data = png_rgb.read()
        image_data_encoded = base64.b64encode(image_data).decode('ascii')

        data = {
            'name': 'example',
            'width': 1,
            'image': image_data_encoded,
        }

        with MockVWS() as mock:
            vuforia_database_keys = VuforiaDatabaseKeys(
                database_name=uuid.uuid4().hex,
                server_access_key=mock.server_access_key,
                server_secret_key=mock.server_secret_key,
                client_access_key=uuid.uuid4().hex,
                client_secret_key=uuid.uuid4().hex,
            )

            response = add_target_to_vws(
                vuforia_database_keys=vuforia_database_keys,
                data=data,
            )

            target_id = response.json()['target_id']

            start_time = datetime.datetime.now()

            while True:
                response = get_vws_target(
                    vuforia_database_keys=vuforia_database_keys,
                    target_id=target_id,
                )

                status = response.json()['status']
                if status != TargetStatuses.PROCESSING.value:
                    elapsed_time = datetime.datetime.now() - start_time
                    assert elapsed_time < datetime.timedelta(seconds=0.51)
                    assert elapsed_time > datetime.timedelta(seconds=0.49)
                    return

    def test_custom(self, png_rgb: io.BytesIO) -> None:
        """
        It is possible to set a custom processing time.
        """
        image_data = png_rgb.read()
        image_data_encoded = base64.b64encode(image_data).decode('ascii')

        data = {
            'name': 'example',
            'width': 1,
            'image': image_data_encoded,
        }

        with MockVWS(processing_time_seconds=0.1) as mock:
            vuforia_database_keys = VuforiaDatabaseKeys(
                database_name=uuid.uuid4().hex,
                server_access_key=mock.server_access_key,
                server_secret_key=mock.server_secret_key,
                client_access_key=uuid.uuid4().hex,
                client_secret_key=uuid.uuid4().hex,
            )

            response = add_target_to_vws(
                vuforia_database_keys=vuforia_database_keys,
                data=data,
            )

            target_id = response.json()['target_id']

            start_time = datetime.datetime.now()

            while True:
                response = get_vws_target(
                    vuforia_database_keys=vuforia_database_keys,
                    target_id=target_id,
                )

                status = response.json()['status']
                if status != TargetStatuses.PROCESSING.value:
                    elapsed_time = datetime.datetime.now() - start_time
                    assert elapsed_time < datetime.timedelta(seconds=0.11)
                    assert elapsed_time > datetime.timedelta(seconds=0.09)
                    return

class TestDatabaseName:
    """
    Tests for the database name.
    """

    def test_default(self) -> None:
        """
        By default, the database has a random name.
        """
        with MockVWS() as mock:
            vuforia_database_keys = VuforiaDatabaseKeys(
                database_name=uuid.uuid4().hex,
                server_access_key=mock.server_access_key,
                server_secret_key=mock.server_secret_key,
                client_access_key=uuid.uuid4().hex,
                client_secret_key=uuid.uuid4().hex,
            )

            response = database_summary(
                vuforia_database_keys=vuforia_database_keys,
            )
            first_database_name = response.json()['name']

        with MockVWS() as mock:
            vuforia_database_keys = VuforiaDatabaseKeys(
                database_name=uuid.uuid4().hex,
                server_access_key=mock.server_access_key,
                server_secret_key=mock.server_secret_key,
                client_access_key=uuid.uuid4().hex,
                client_secret_key=uuid.uuid4().hex,
            )
            response = database_summary(
                vuforia_database_keys=vuforia_database_keys,
            )
            second_database_name = response.json()['name']

        assert first_database_name != second_database_name

    @given(database_name=text())
    def test_custom_name(
        self,
        database_name: str,
    ) -> None:
        """
        It is possible to set a custom database name.
        """
        with MockVWS(database_name=database_name) as mock:
            vuforia_database_keys = VuforiaDatabaseKeys(
                database_name=database_name,
                server_access_key=mock.server_access_key,
                server_secret_key=mock.server_secret_key,
                client_access_key=uuid.uuid4().hex,
                client_secret_key=uuid.uuid4().hex,
            )
            response = database_summary(
                vuforia_database_keys=vuforia_database_keys,
            )
            assert response.json()['name'] == database_name

class TestPersistence:
    """
    Tests for isolation between instances of the mock.
    """

    def test_context_manager(
        self,
        png_rgb: io.BytesIO,
    ) -> None:
        """
        When the context manager is used, targets are not persisted between
        invocations.
        """
        image_data = png_rgb.read()
        image_data_encoded = base64.b64encode(image_data).decode('ascii')

        data = {
            'name': 'example',
            'width': 1,
            'image': image_data_encoded,
        }

        with MockVWS() as mock:
            vuforia_database_keys = VuforiaDatabaseKeys(
                database_name=uuid.uuid4().hex,
                server_access_key=mock.server_access_key,
                server_secret_key=mock.server_secret_key,
                client_access_key=uuid.uuid4().hex,
                client_secret_key=uuid.uuid4().hex,
            )

            response = add_target_to_vws(
                vuforia_database_keys=vuforia_database_keys,
                data=data,
            )

            target_id = response.json()['target_id']

            response = get_vws_target(
                vuforia_database_keys=vuforia_database_keys,
                target_id=target_id,
            )

            assert response.status_code == codes.OK

        with MockVWS() as mock:
            vuforia_database_keys = VuforiaDatabaseKeys(
                database_name=uuid.uuid4().hex,
                server_access_key=mock.server_access_key,
                server_secret_key=mock.server_secret_key,
                client_access_key=uuid.uuid4().hex,
                client_secret_key=uuid.uuid4().hex,
            )

            response = get_vws_target(
                vuforia_database_keys=vuforia_database_keys,
                target_id=target_id,
            )

            assert response.status_code == codes.NOT_FOUND

class TestCredentials:
    """
    Tests for setting credentials for the mock.
    """

    def test_default(self) -> None:
        """
        By default the mock uses a random access key and secret key.
        """
        with MockVWS() as first_mock:
            with MockVWS() as second_mock:
                assert (
                    first_mock.server_access_key !=
                    second_mock.server_access_key
                )
                assert (
                    first_mock.server_secret_key !=
                    second_mock.server_secret_key
                )
                assert first_mock.database_name != second_mock.database_name

    # We limit this to ASCII letters because some characters are not allowed
    # in request headers (e.g. a leading space).
    @given(
        server_access_key=text(alphabet=string.ascii_letters),
        server_secret_key=text(alphabet=string.ascii_letters)
    )
    def test_custom_credentials(
        self,
        server_access_key: str,
        server_secret_key: str,
    ) -> None:
        """
        It is possible to set custom credentials.
        """
        with MockVWS(
            server_access_key=server_access_key,
            server_secret_key=server_secret_key,
        ) as mock:
            assert mock.server_access_key == server_access_key
            assert mock.server_secret_key == server_secret_key

            assert_valid_server_credentials(
                server_access_key=server_access_key,
                server_secret_key=server_secret_key,
            )
<|endoftext|>


<commit_before>import discord
from discord.ext import commands
from sys import argv

class Rules:
    """
    Read da rules.
    """
    def __init__(self, bot):
        self.bot = bot
        print('Addon "{}" loaded'.format(self.__class__.__name__))

    async def simple_embed(self, text, title="", color=discord.Color.default()):
        embed = discord.Embed(title=title, color=color)
        embed.description = text
        await self.bot.say("", embed=embed)

    @commands.command()
    async def consoleban(self):
        """States some stuff about no assistance with bans"""
        await self.bot.say("Please refrain from asking for or giving assistance with unbanning consoles which have been banned from online services.\nReminder: sharing files that allow other users to evade Nintendo issued bans is a bannable offense.")

    @commands.command()
    async def pirate(self):
        """Hey! You can't steal another trainer's Pokémon!"""
        await self.bot.say("Please refrain from asking for or giving assistance with installing or using illegitimately obtained software.")

    @commands.command(hidden=True)
    async def nick(self):
        """Displays the Nickname and Avatar Policy."""
        await self.bot.say("🏷 ___Username/Nickname and Avatar policy___\n"
                           "Usernames are to be kept primarily alphanumeric, to keep them easy to tag and read. Excessively long usernames are not acceptable. Usernames and avatars that are annoying, offensive, inappropriate (\"nsfw\"), and/or disruptive to others are also not allowed.\n"
                           "Usernames that go against these rules will be assigned a nickname. Users can request a specific nickname that follows these.\n"
                           "Users with avatars against these rules will be asked to change them or be kicked from the server.")

    @commands.command()
    async def rules(self):
        """Links to rules website."""
        await self.bot.say("Please check {} or <http://ninty.cf/w/> for a full list of rules".format(self.bot.welcome_channel.mention))

    @commands.command(hidden=True)
    async def r1(self):
        """Displays rule 1."""
        await self.simple_embed("Be nice to each other. It's fine to disagree, it's not fine to insult or attack other people.", title="Rule 1")

    @commands.command(hidden=True)
    async def r2(self):
        """Displays rule 2."""
        await self.simple_embed("This is an English-speaking server, so please speak English to keep communication simple.", title="Rule 2")

    @commands.command(hidden=True)
    async def r3(self):
        """Displays rule 3."""
        await self.simple_embed("Keep 3DS and Wii U support questions to the assistance channels.\n"
                                    "• Don't ask how to bypass network restrictions in place by Nintendo or game developers. This includes bypassing console bans.", title="Rule 3")

    @commands.command(hidden=True)
    async def r4(self):
        """Displays rule 4."""
        await self.simple_embed("Don't ask to ask, just ask. Just post your question instead of asking if you can and you will get an answer faster.\n"
                                    " • Add details when asking. \"x doesn't work\" will slow down help.", title="Rule 4")

    @commands.command(hidden=True)
    async def r5(self):
        """Displays rule 5."""
        await self.simple_embed("Don't spam. Don't post your question twice unless you fully believe you were not intentionally ignored.\n"
                                    " • For excessively long text, use a service like https://hastebin.com.", title="Rule 5")

    @commands.command(hidden=True)
    async def r6(self):
        """Displays rule 6."""
        await self.simple_embed("Remain mindful and polite when asking or answering questions in the assistance channels. Derailing support or otherwise causing issues will get your access removed.", title="Rule 6")

    @commands.command(hidden=True)
    async def r7(self):
        """Displays rule 7."""
        await self.simple_embed("Don't brigade, raid, or otherwise attack other people or communities. Don't discuss participation in these attacks. This may warrant an immediate permanent ban.", title="Rule 7")

    @commands.command(hidden=True)
    async def r8(self):
        """Displays rule 8."""
        await self.simple_embed("One account per user. Bots/fully automated clients run by users are not allowed. Alternate accounts will have access removed. If you are switching accounts, please remove your original from the server.", title="Rule 8")

    @commands.command(hidden=True)
    async def r9(self):
        """Displays rule 9."""
        await self.simple_embed("User-side scripts are fine if they are only accessible by you and are not annoying. Community-accessible triggers on a user account are a violation of the Discord Terms of Service.", title="Rule 9")

    @commands.command(hidden=True)
    async def r10(self):
        """Displays rule 10."""
        await self.simple_embed("Not-safe-for-work content (including gore and other \"shock\" content) is prohibited.", title="Rule 10")

    @commands.command(hidden=True)
    async def r11(self):
        """Displays rule 11."""
        await self.simple_embed("The Piracy rule: Don't...\n"
                                    " • ask how to pirate games\n"
                                    " • share full game data\n"
                                    " • mention piracy sites and tools by name\n"
                                    " • share game tickets and titlekeys\n"
                                    " • ask to share direct messages to help with piracy\n"
                                    " • discuss piracy in the assistance channels\n"
                                    " • in general commit copyright violations\n\n"

                                    "If you simply need to tell someone to not ask about piracy, consider `.pirate` instead.", title="Rule 11")

    @commands.command(hidden=True)
    async def r12(self):
        """Displays rule 12."""
        await self.simple_embed("Don't post other people's personal information, including social media accounts with this. This may warrant an immediate ban.", title="Rule 12")

    @commands.command(hidden=True)
    async def r13(self):
        """Displays rule 13."""
        await self.simple_embed("Ask a staff member before posting invite links to things like servers on Discord, Skype groups, etc.", title="Rule 13")

    @commands.command(hidden=True)
    async def r14(self):
        """Displays rule 14."""
        await self.simple_embed("Off-topic content goes to <#277529766972620800>. Keep low-quality content like memes out. There is a channel for that, use \".togglechannel elsewhere\" to get access.", title="Rule 14")

    @commands.command(hidden=True)
    async def r15(self):
        """Displays rule 15."""
        await self.simple_embed("Voice and music commands and other random/contextless command usage belong in <#239564960781434880> and <#261581918653513729> respectively.", title="Rule 15")

    @commands.command(hidden=True)
    async def r16(self):
        """Displays rule 16."""
        await self.simple_embed("Trying to evade, look for loopholes, or stay borderline within the rules will be treated as breaking them.", title="Rule 16")

def setup(bot):
    bot.add_cog(Rules(bot))
<commit_msg>remove elsewhere commadn from r14<commit_after>import discord
from discord.ext import commands
from sys import argv

class Rules:
    """
    Read da rules.
    """
    def __init__(self, bot):
        self.bot = bot
        print('Addon "{}" loaded'.format(self.__class__.__name__))

    async def simple_embed(self, text, title="", color=discord.Color.default()):
        embed = discord.Embed(title=title, color=color)
        embed.description = text
        await self.bot.say("", embed=embed)

    @commands.command()
    async def consoleban(self):
        """States some stuff about no assistance with bans"""
        await self.bot.say("Please refrain from asking for or giving assistance with unbanning consoles which have been banned from online services.\nReminder: sharing files that allow other users to evade Nintendo issued bans is a bannable offense.")

    @commands.command()
    async def pirate(self):
        """Hey! You can't steal another trainer's Pokémon!"""
        await self.bot.say("Please refrain from asking for or giving assistance with installing or using illegitimately obtained software.")

    @commands.command(hidden=True)
    async def nick(self):
        """Displays the Nickname and Avatar Policy."""
        await self.bot.say("🏷 ___Username/Nickname and Avatar policy___\n"
                           "Usernames are to be kept primarily alphanumeric, to keep them easy to tag and read. Excessively long usernames are not acceptable. Usernames and avatars that are annoying, offensive, inappropriate (\"nsfw\"), and/or disruptive to others are also not allowed.\n"
                           "Usernames that go against these rules will be assigned a nickname. Users can request a specific nickname that follows these.\n"
                           "Users with avatars against these rules will be asked to change them or be kicked from the server.")

    @commands.command()
    async def rules(self):
        """Links to rules website."""
        await self.bot.say("Please check {} or <http://ninty.cf/w/> for a full list of rules".format(self.bot.welcome_channel.mention))

    @commands.command(hidden=True)
    async def r1(self):
        """Displays rule 1."""
        await self.simple_embed("Be nice to each other. It's fine to disagree, it's not fine to insult or attack other people.", title="Rule 1")

    @commands.command(hidden=True)
    async def r2(self):
        """Displays rule 2."""
        await self.simple_embed("This is an English-speaking server, so please speak English to keep communication simple.", title="Rule 2")

    @commands.command(hidden=True)
    async def r3(self):
        """Displays rule 3."""
        await self.simple_embed("Keep 3DS and Wii U support questions to the assistance channels.\n"
                                    "• Don't ask how to bypass network restrictions in place by Nintendo or game developers. This includes bypassing console bans.", title="Rule 3")

    @commands.command(hidden=True)
    async def r4(self):
        """Displays rule 4."""
        await self.simple_embed("Don't ask to ask, just ask. Just post your question instead of asking if you can and you will get an answer faster.\n"
                                    " • Add details when asking. \"x doesn't work\" will slow down help.", title="Rule 4")

    @commands.command(hidden=True)
    async def r5(self):
        """Displays rule 5."""
        await self.simple_embed("Don't spam. Don't post your question twice unless you fully believe you were not intentionally ignored.\n"
                                    " • For excessively long text, use a service like https://hastebin.com.", title="Rule 5")

    @commands.command(hidden=True)
    async def r6(self):
        """Displays rule 6."""
        await self.simple_embed("Remain mindful and polite when asking or answering questions in the assistance channels. Derailing support or otherwise causing issues will get your access removed.", title="Rule 6")

    @commands.command(hidden=True)
    async def r7(self):
        """Displays rule 7."""
        await self.simple_embed("Don't brigade, raid, or otherwise attack other people or communities. Don't discuss participation in these attacks. This may warrant an immediate permanent ban.", title="Rule 7")

    @commands.command(hidden=True)
    async def r8(self):
        """Displays rule 8."""
        await self.simple_embed("One account per user. Bots/fully automated clients run by users are not allowed. Alternate accounts will have access removed. If you are switching accounts, please remove your original from the server.", title="Rule 8")

    @commands.command(hidden=True)
    async def r9(self):
        """Displays rule 9."""
        await self.simple_embed("User-side scripts are fine if they are only accessible by you and are not annoying. Community-accessible triggers on a user account are a violation of the Discord Terms of Service.", title="Rule 9")

    @commands.command(hidden=True)
    async def r10(self):
        """Displays rule 10."""
        await self.simple_embed("Not-safe-for-work content (including gore and other \"shock\" content) is prohibited.", title="Rule 10")

    @commands.command(hidden=True)
    async def r11(self):
        """Displays rule 11."""
        await self.simple_embed("The Piracy rule: Don't...\n"
                                    " • ask how to pirate games\n"
                                    " • share full game data\n"
                                    " • mention piracy sites and tools by name\n"
                                    " • share game tickets and titlekeys\n"
                                    " • ask to share direct messages to help with piracy\n"
                                    " • discuss piracy in the assistance channels\n"
                                    " • in general commit copyright violations\n\n"

                                    "If you simply need to tell someone to not ask about piracy, consider `.pirate` instead.", title="Rule 11")

    @commands.command(hidden=True)
    async def r12(self):
        """Displays rule 12."""
        await self.simple_embed("Don't post other people's personal information, including social media accounts with this. This may warrant an immediate ban.", title="Rule 12")

    @commands.command(hidden=True)
    async def r13(self):
        """Displays rule 13."""
        await self.simple_embed("Ask a staff member before posting invite links to things like servers on Discord, Skype groups, etc.", title="Rule 13")

    @commands.command(hidden=True)
    async def r14(self):
        """Displays rule 14."""
        await self.simple_embed("Off-topic content goes to <#277529766972620800>. Keep low-quality content like memes out. There is a channel for that, read <#196618637950451712> to find it.", title="Rule 14")

    @commands.command(hidden=True)
    async def r15(self):
        """Displays rule 15."""
        await self.simple_embed("Voice and music commands and other random/contextless command usage belong in <#239564960781434880> and <#261581918653513729> respectively.", title="Rule 15")

    @commands.command(hidden=True)
    async def r16(self):
        """Displays rule 16."""
        await self.simple_embed("Trying to evade, look for loopholes, or stay borderline within the rules will be treated as breaking them.", title="Rule 16")

def setup(bot):
    bot.add_cog(Rules(bot))
<|endoftext|>


<commit_before>import pytest
from plenum.common.eventually import eventually
from sovrin_node.test.upgrade.test_pool_upgrade \
    import validUpgradeSent, upgradeScheduled

whitelist = ['Failed to upgrade node', 'Failed to send update request!']

def testTimeoutWorks(nodeSet, looper, validUpgradeSent, upgradeScheduled):
    """
    Checks that after some timeout upgrade is marked as failed if
    it not started
    """

    import asyncio
    completionFuture = asyncio.Future()

    def callback(oldCallback, completionFuture):
        def f():
            completionFuture.set_result(True)
            oldCallback()
        return f

    for node in nodeSet:
        oldCallback = node.upgrader._upgradeFailedCallback
        node.upgrader._upgradeFailedCallback = \
            callback(oldCallback, completionFuture)
        print(node.upgrader.scheduledUpgrade)
    print("ZZZZZZZ")

    looper.run(eventually(lambda x: completionFuture.result(),
                          nodeSet,
                          retryWait=20,
                          timeout=60))
<commit_msg>fixing a broken test<commit_after>import pytest
from plenum.common.eventually import eventually
from sovrin_node.test.upgrade.test_pool_upgrade \
    import validUpgradeSent, upgradeScheduled

whitelist = ['Failed to upgrade node', 'Failed to send update request!']

@pytest.fixture(scope="module")
def dontClearNode(nodeSet):
    for node in nodeSet:
        node.cleanupOnStopping = False

def testTimeoutWorks(nodeSet, looper, dontClearNode, validUpgradeSent,
                     upgradeScheduled):
    """
    Checks that after some timeout upgrade is marked as failed if
    it not started
    """

    pending = {node.name for node in nodeSet}

    def chk():
        nonlocal pending
        assert len(pending) == 0

    def callback(oldCallback, nodeName):
        def f():
            print("_upgradeFailedCallback called of {}'s upgrader".format(nodeName))
            oldCallback()
            nonlocal pending
            pending.remove(nodeName)
        return f

    for node in nodeSet:
        oldCallback = node.upgrader._upgradeFailedCallback
        node.upgrader._upgradeFailedCallback = \
            callback(oldCallback, node.name)
        print(node.upgrader.scheduledUpgrade)

    looper.run(eventually(chk,
                          retryWait=10,
                          timeout=90))
<|endoftext|>


<commit_before>import logging
import sys
import time
from .utils import dbop
from .utils import get_references
from .utils import get_storage
from .utils import QUEUE_TABLE_NAME
from .utils import TARGET_TABLE_NAME
import psycopg2

EMTPY_DELAY = 1

log = logging.getLogger("worker")
log.setLevel(logging.WARNING)

def _get_and_lock_next_zoid(cursor):
    stmt = """
    LOCK TABLE %(qtable)s IN SHARE ROW EXCLUSIVE MODE;
    UPDATE %(qtable)s
    SET taken=TRUE,
        timestamp=now()
    FROM (
        SELECT zoid FROM %(qtable)s
        WHERE taken IS FALSE AND finished IS FALSE
        LIMIT 1
    ) AS subquery
    WHERE %(qtable)s.zoid = subquery.zoid
    RETURNING subquery.zoid AS zoid;
    """ % {'qtable': QUEUE_TABLE_NAME}
    try:
        cursor.execute(stmt)
    except (psycopg2.ProgrammingError, psycopg2.InternalError):
        return False
    zoid = None
    for cvalue in cursor:
        zoid = cvalue[0]
    if zoid is None:
        cursor.execute('ABORT;')
        return False  # queue empty
    cursor.execute('COMMIT;')
    log.debug("selected and locked zoid=%s" % zoid)
    return zoid

def _finish_zoid(cursor, zoid):
    stmt = """
    UPDATE %s SET finished=TRUE WHERE zoid=%s;
    COMMIT;
    """ % (QUEUE_TABLE_NAME, zoid)
    try:
        cursor.execute(stmt)
    except psycopg2.InternalError:
        log.warning("hard aborted zoid=%s" % zoid)
    log.debug("finished zoid=%s" % zoid)

def _copy_zoid(cursor, zoid):
    stmt = """
    INSERT INTO %(table)s
        SELECT zoid, tid, state_size, state
        FROM object_state
        WHERE zoid=%(zoid)s
        AND NOT EXISTS (
            SELECT zoid FROM %(table)s
            WHERE zoid = %(zoid)s
        )
    """ % {'table': TARGET_TABLE_NAME, 'zoid': zoid}
    try:
        cursor.execute(stmt)
    except:
        log.debug("Statement failed: \n%s" % stmt)
        raise
    log.debug("copied zoid=%s" % zoid)

def _handle_references(cursor, zoid):
    stmt = """
    SELECT state
    FROM object_state
    WHERE zoid=%s;
    """ % (zoid)
    cursor.execute(stmt)
    row = cursor.next()
    if not row:
        log.debug('Can not load state for zoid-%s!' % zoid)
        return
    refs = get_references(row[0])
    log.info("handle %s references for zoid=%s" % (len(refs), zoid))
    stmt = ""
    for ref_zoid in set(refs):
        stmt = """
        INSERT INTO %(qtable)s (zoid)
        SELECT %(zoid)s
        WHERE NOT EXISTS (
            SELECT zoid FROM %(qtable)s
            WHERE zoid = %(zoid)s
        );
        """ % {'qtable': QUEUE_TABLE_NAME,
               'ttable': TARGET_TABLE_NAME,
               'zoid': ref_zoid
        }
        try:
            cursor.execute(stmt)
        except:
            log.warning('-> zoid=%s can not be added twice to queue' %
                            ref_zoid)
            raise

def process_queue(cursor):
    """process worker queue
    - fetch an item from queue.
    - for each reference put it in queue.
    - copy item over to new table
    - delete from queue

    return True if item was processed, else False
    """
    start = time.time()
    try:
        zoid = _get_and_lock_next_zoid(cursor)
    except KeyboardInterrupt:
        # conflict - unlock
        cursor.execute('ABORT;')
        log.info(80 * '-' + '\nStopped by human interaction.')
        exit(0)
    except:
        raise
        log.warning(80 * '-' + '\nProblem fetching zoid, wait some millis.')
        time.sleep(0.1)
        return True
    if zoid is False:
        return False
    log.info('time: %.2fms get and lock' % ((time.time() - start) * 1000.0))
    cursor.execute('BEGIN;')
    try:
        middle = time.time()
        _copy_zoid(cursor, zoid)
        log.info('time: %.2fms copy' % ((time.time() - middle) * 1000.0))
        middle = time.time()
        _handle_references(cursor, zoid)
        log.info('time: %.2fms references' % ((time.time() - middle) * 1000.0))
        middle = time.time()
        _finish_zoid(cursor, zoid)
        log.info('time: %.2fms finish' % ((time.time() - middle) * 1000.0))
    except KeyboardInterrupt:
        # conflict - unlock
        cursor.execute('ABORT;')
        log.info(80 * '-' + '\nStopped by human interaction.')
        exit(0)
    except:
        # conflict - unlock
        cursor.execute('ABORT;')
        log.warning(80 * '-' + '\nAbort for unknown reason, wait some millis.')
        time.sleep(0.1)
        return True
    log.info('processed item %s in %.2fms\n--------------------------' %
              (zoid, (time.time() - start) * 1000.0))
    return True

def run(argv=sys.argv):
    log.info("Packing worker started")
    storage = get_storage(argv, __doc__, False)
    try:
        while True:
            state = dbop(storage, process_queue)
            if not state:
                log.info("Nothing to do, check again in %ss" % EMTPY_DELAY)
                time.sleep(EMTPY_DELAY)
    finally:
        log.info("Closing storage")
        storage.close()
        log.info("Packing worker stopped")
<commit_msg>lower log level<commit_after>import logging
import sys
import time
from .utils import dbop
from .utils import get_references
from .utils import get_storage
from .utils import QUEUE_TABLE_NAME
from .utils import TARGET_TABLE_NAME
import psycopg2

EMTPY_DELAY = 1

log = logging.getLogger("worker")
log.setLevel(logging.INFO)

def _get_and_lock_next_zoid(cursor):
    stmt = """
    LOCK TABLE %(qtable)s IN SHARE ROW EXCLUSIVE MODE;
    UPDATE %(qtable)s
    SET taken=TRUE,
        timestamp=now()
    FROM (
        SELECT zoid FROM %(qtable)s
        WHERE taken IS FALSE AND finished IS FALSE
        LIMIT 1
    ) AS subquery
    WHERE %(qtable)s.zoid = subquery.zoid
    RETURNING subquery.zoid AS zoid;
    """ % {'qtable': QUEUE_TABLE_NAME}
    try:
        cursor.execute(stmt)
    except (psycopg2.ProgrammingError, psycopg2.InternalError):
        return False
    zoid = None
    for cvalue in cursor:
        zoid = cvalue[0]
    if zoid is None:
        cursor.execute('ABORT;')
        return False  # queue empty
    cursor.execute('COMMIT;')
    log.debug("selected and locked zoid=%s" % zoid)
    return zoid

def _finish_zoid(cursor, zoid):
    stmt = """
    UPDATE %s SET finished=TRUE WHERE zoid=%s;
    COMMIT;
    """ % (QUEUE_TABLE_NAME, zoid)
    try:
        cursor.execute(stmt)
    except psycopg2.InternalError:
        log.warning("hard aborted zoid=%s" % zoid)
    log.debug("finished zoid=%s" % zoid)

def _copy_zoid(cursor, zoid):
    stmt = """
    INSERT INTO %(table)s
        SELECT zoid, tid, state_size, state
        FROM object_state
        WHERE zoid=%(zoid)s
        AND NOT EXISTS (
            SELECT zoid FROM %(table)s
            WHERE zoid = %(zoid)s
        )
    """ % {'table': TARGET_TABLE_NAME, 'zoid': zoid}
    try:
        cursor.execute(stmt)
    except:
        log.debug("Statement failed: \n%s" % stmt)
        raise
    log.debug("copied zoid=%s" % zoid)

def _handle_references(cursor, zoid):
    stmt = """
    SELECT state
    FROM object_state
    WHERE zoid=%s;
    """ % (zoid)
    cursor.execute(stmt)
    row = cursor.next()
    if not row:
        log.debug('Can not load state for zoid-%s!' % zoid)
        return
    refs = get_references(row[0])
    log.info("handle %s references for zoid=%s" % (len(refs), zoid))
    stmt = ""
    for ref_zoid in set(refs):
        stmt = """
        INSERT INTO %(qtable)s (zoid)
        SELECT %(zoid)s
        WHERE NOT EXISTS (
            SELECT zoid FROM %(qtable)s
            WHERE zoid = %(zoid)s
        );
        """ % {'qtable': QUEUE_TABLE_NAME,
               'ttable': TARGET_TABLE_NAME,
               'zoid': ref_zoid
        }
        try:
            cursor.execute(stmt)
        except:
            log.warning('-> zoid=%s can not be added twice to queue' %
                            ref_zoid)
            raise

def process_queue(cursor):
    """process worker queue
    - fetch an item from queue.
    - for each reference put it in queue.
    - copy item over to new table
    - delete from queue

    return True if item was processed, else False
    """
    start = time.time()
    try:
        zoid = _get_and_lock_next_zoid(cursor)
    except KeyboardInterrupt:
        # conflict - unlock
        cursor.execute('ABORT;')
        log.info(80 * '-' + '\nStopped by human interaction.')
        exit(0)
    except:
        raise
        log.warning(80 * '-' + '\nProblem fetching zoid, wait some millis.')
        time.sleep(0.1)
        return True
    if zoid is False:
        return False
    log.info('time: %.2fms get and lock' % ((time.time() - start) * 1000.0))
    cursor.execute('BEGIN;')
    try:
        middle = time.time()
        _copy_zoid(cursor, zoid)
        log.info('time: %.2fms copy' % ((time.time() - middle) * 1000.0))
        middle = time.time()
        _handle_references(cursor, zoid)
        log.info('time: %.2fms references' % ((time.time() - middle) * 1000.0))
        middle = time.time()
        _finish_zoid(cursor, zoid)
        log.info('time: %.2fms finish' % ((time.time() - middle) * 1000.0))
    except KeyboardInterrupt:
        # conflict - unlock
        cursor.execute('ABORT;')
        log.info(80 * '-' + '\nStopped by human interaction.')
        exit(0)
    except:
        # conflict - unlock
        cursor.execute('ABORT;')
        log.warning(80 * '-' + '\nAbort for unknown reason, wait some millis.')
        time.sleep(0.1)
        return True
    log.info('processed item %s in %.2fms\n--------------------------' %
              (zoid, (time.time() - start) * 1000.0))
    return True

def run(argv=sys.argv):
    log.info("Packing worker started")
    storage = get_storage(argv, __doc__, False)
    try:
        while True:
            state = dbop(storage, process_queue)
            if not state:
                log.info("Nothing to do, check again in %ss" % EMTPY_DELAY)
                time.sleep(EMTPY_DELAY)
    finally:
        log.info("Closing storage")
        storage.close()
        log.info("Packing worker stopped")
<|endoftext|>


<commit_before># ERPNext - web based ERP (http://erpnext.com)
# Copyright (C) 2012 Web Notes Technologies Pvt Ltd
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# 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
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.

from __future__ import unicode_literals
patch_list = [
	"patches.mar_2012.so_rv_mapper_fix",
	"patches.mar_2012.clean_property_setter",
	"patches.april_2012.naming_series_patch",
	"patches.mar_2012.cleanup_control_panel",
	"patches.mar_2012.doctype_get_refactor",
	"patches.mar_2012.delete_docformat",
	"patches.mar_2012.usertags",
	"patches.april_2012.reload_c_form",
	"patches.april_2012.after_sync_cleanup",
	"patches.april_2012.remove_default_from_rv_detail",
	"patches.april_2012.update_role_in_address",
	"patches.april_2012.update_permlevel_in_address",
	"patches.april_2012.update_appraisal_permission",
	"patches.april_2012.serial_no_fixes",
	"patches.april_2012.repost_stock_for_posting_time",
	"patches.may_2012.cleanup_property_setter",
	"patches.may_2012.rename_prev_doctype",
	"patches.may_2012.cleanup_notification_control",
	"patches.may_2012.renamedt_in_custom_search_criteria",
	"patches.may_2012.stock_reco_patch",
	"patches.may_2012.reload_reports",
	"patches.may_2012.page_role_series_fix",
	"patches.may_2012.reload_sales_invoice_pf",
	"patches.may_2012.std_pf_readonly",
	"patches.may_2012.reload_so_pending_items",
	"patches.may_2012.customize_form_cleanup",
	"patches.may_2012.cs_server_readonly",
	"patches.may_2012.clear_session_cache",
	"patches.may_2012.same_purchase_rate_patch",
	"patches.may_2012.create_report_manager_role",
	"patches.may_2012.reload_customer_address_contact",
	"patches.may_2012.profile_perm_patch",
	"patches.may_2012.remove_euro_currency",
	"patches.may_2012.remove_communication_log",
	"patches.june_2012.barcode_in_feature_setup",
	"patches.june_2012.copy_uom_for_pur_inv_item",
	"patches.june_2012.fetch_organization_from_lead",
	"patches.june_2012.reports_list_permission",
	"patches.june_2012.support_ticket_autoreply",
	"patches.june_2012.series_unique_patch",
	"patches.june_2012.set_recurring_type",
	"patches.june_2012.alter_tabsessions",
	"patches.june_2012.delete_old_parent_entries",
	"patches.april_2012.delete_about_contact",
	"patches.july_2012.reload_pr_po_mapper",
	"patches.july_2012.address_contact_perms",
	"patches.july_2012.packing_list_cleanup_and_serial_no",
	"patches.july_2012.deprecate_import_data_control",
	"patches.july_2012.default_freeze_account",
	"patches.july_2012.update_purchase_tax",
	"patches.june_2012.cms2",
	"patches.july_2012.auth_table",
	"patches.july_2012.remove_event_role_owner_match",
	"patches.july_2012.deprecate_bulk_rename",
	"patches.july_2012.blog_guest_permission",
	"patches.july_2012.bin_permission",
	"patches.july_2012.project_patch_repeat",
	"patches.july_2012.repost_stock_due_to_wrong_packing_list",
	"patches.july_2012.supplier_quotation",
	"patches.august_2012.report_supplier_quotations",
	"patches.august_2012.task_allocated_to_assigned",
	"patches.august_2012.change_profile_permission",
	"patches.august_2012.changed_blog_date_format",
	"patches.august_2012.repost_billed_amt",
	"patches.august_2012.remove_cash_flow_statement",
	"patches.september_2012.stock_report_permissions_for_accounts",
	"patches.september_2012.communication_delete_permission",
	"patches.september_2012.all_permissions_patch",
	"patches.september_2012.customer_permission_patch",
	"patches.september_2012.add_stock_ledger_entry_index",
	"patches.september_2012.plot_patch",
	"patches.september_2012.event_permission",
	"patches.september_2012.repost_stock",
	"patches.september_2012.reload_gross_profit",
	"patches.september_2012.rebuild_trees",
	"patches.september_2012.deprecate_account_balance",
	"patches.september_2012.profile_delete_permission",
	"patches.october_2012.update_permission",
	"patches.october_2012.reload_gl_mapper",
	"patches.october_2012.fix_wrong_vouchers",
	"patches.october_2012.remove_old_customer_contact_address",
	"patches.october_2012.company_fiscal_year_docstatus_patch",
	"patches.october_2012.update_account_property",
	"patches.october_2012.remove_old_trial_bal",
	"patches.october_2012.fix_cancelled_gl_entries",
	"patches.october_2012.custom_script_delete_permission",
	"patches.november_2012.custom_field_insert_after",
	"patches.november_2012.delete_item_sales_register1",
	"patches.november_2012.rename_employee_leave_balance_report",
	"patches.november_2012.report_permissions",
	"patches.november_2012.customer_issue_allocated_to_assigned",
	"patches.november_2012.reset_appraisal_permissions",
	"patches.november_2012.disable_cancelled_profiles",
	"patches.november_2012.remove_old_unbilled_items_report",
	"patches.november_2012.support_ticket_response_to_communication",
	"patches.november_2012.cancelled_bom_patch",
	"patches.november_2012.communication_sender_and_recipient",
	"patches.november_2012.update_delivered_billed_percentage_for_pos",
	"patches.november_2012.add_theme_to_profile",
	"patches.november_2012.add_employee_field_in_employee",
	"patches.november_2012.leave_application_cleanup",
	"patches.november_2012.production_order_patch",
	"patches.november_2012.gle_floating_point_issue",
	"patches.december_2012.deprecate_tds",
	"patches.december_2012.expense_leave_reload",
	"patches.december_2012.repost_ordered_qty",
	"patches.december_2012.repost_projected_qty",
	"patches.december_2012.reload_debtors_creditors_ledger",
	"patches.december_2012.website_cache_refactor",
	"patches.december_2012.production_cleanup",
	"patches.december_2012.fix_default_print_format",
	"patches.december_2012.file_list_rename",
	"patches.december_2012.replace_createlocal",
	"patches.december_2012.clear_web_cache",
	"patches.december_2012.remove_quotation_next_contact",
	"patches.december_2012.stock_entry_cleanup",
	"patches.december_2012.production_order_naming_series",
	"patches.december_2012.rebuild_item_group_tree",
	"patches.december_2012.address_title",
	"patches.december_2012.delete_form16_print_format",
	"patches.december_2012.remove_project_mapper",
	"patches.december_2012.update_print_width",
	"patches.january_2013.remove_bad_permissions",
	"patches.january_2013.deprecate_stock_search_criteria",
	"patches.january_2013.remove_support_search_criteria",
	"patches.january_2013.holiday_list_patch",
	"patches.january_2013.stock_reconciliation_patch",
	"patches.january_2013.report_permission",
	"patches.january_2013.give_report_permission_on_read",
	"patches.january_2013.update_closed_on",
	"patches.january_2013.change_patch_structure",
	"patches.january_2013.update_country_info",
	"patches.january_2013.remove_tds_entry_from_gl_mapper",
	"patches.january_2013.update_number_format",
	"patches.january_2013.purchase_price_list",
	"execute:webnotes.reload_doc('accounts','Print Format','Payment Receipt Voucher')",
	"patches.january_2013.update_fraction_for_usd",
	"patches.january_2013.enable_currencies",
	"patches.january_2013.remove_unwanted_permission",
	"patches.january_2013.remove_landed_cost_master",
	"patches.january_2013.reload_print_format",
	"patches.january_2013.rebuild_tree",
	"execute:webnotes.reload_doc('core','doctype','docfield') #2013-01-28",
	"patches.january_2013.tabsessions_to_myisam",
	"patches.february_2013.remove_gl_mapper",
	"patches.february_2013.reload_bom_replace_tool_permission",
	"patches.february_2013.payment_reconciliation_reset_values",
	"patches.february_2013.remove_sales_order_pending_items",
	"patches.february_2013.account_negative_balance",
	"patches.february_2013.remove_account_utils_folder",
	"patches.february_2013.update_company_in_leave_application",
	"execute:webnotes.conn.sql_ddl('alter table tabSeries change `name` `name` varchar(100)')",
	"execute:webnotes.conn.sql('update tabUserRole set parentfield=\"user_roles\" where parentfield=\"userroles\"')",
	"patches.february_2013.fix_outstanding",
	"patches.february_2013.p01_event",
	"execute:webnotes.delete_doc('Page', 'Calendar')",
	"execute:webnotes.conn.sql('update `tabEmail Digest` set calendar_events=1, todo_list=1 where enabled=1')"
]<commit_msg>email digest patch<commit_after># ERPNext - web based ERP (http://erpnext.com)
# Copyright (C) 2012 Web Notes Technologies Pvt Ltd
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# 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
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.

from __future__ import unicode_literals
patch_list = [
	"patches.mar_2012.so_rv_mapper_fix",
	"patches.mar_2012.clean_property_setter",
	"patches.april_2012.naming_series_patch",
	"patches.mar_2012.cleanup_control_panel",
	"patches.mar_2012.doctype_get_refactor",
	"patches.mar_2012.delete_docformat",
	"patches.mar_2012.usertags",
	"patches.april_2012.reload_c_form",
	"patches.april_2012.after_sync_cleanup",
	"patches.april_2012.remove_default_from_rv_detail",
	"patches.april_2012.update_role_in_address",
	"patches.april_2012.update_permlevel_in_address",
	"patches.april_2012.update_appraisal_permission",
	"patches.april_2012.serial_no_fixes",
	"patches.april_2012.repost_stock_for_posting_time",
	"patches.may_2012.cleanup_property_setter",
	"patches.may_2012.rename_prev_doctype",
	"patches.may_2012.cleanup_notification_control",
	"patches.may_2012.renamedt_in_custom_search_criteria",
	"patches.may_2012.stock_reco_patch",
	"patches.may_2012.reload_reports",
	"patches.may_2012.page_role_series_fix",
	"patches.may_2012.reload_sales_invoice_pf",
	"patches.may_2012.std_pf_readonly",
	"patches.may_2012.reload_so_pending_items",
	"patches.may_2012.customize_form_cleanup",
	"patches.may_2012.cs_server_readonly",
	"patches.may_2012.clear_session_cache",
	"patches.may_2012.same_purchase_rate_patch",
	"patches.may_2012.create_report_manager_role",
	"patches.may_2012.reload_customer_address_contact",
	"patches.may_2012.profile_perm_patch",
	"patches.may_2012.remove_euro_currency",
	"patches.may_2012.remove_communication_log",
	"patches.june_2012.barcode_in_feature_setup",
	"patches.june_2012.copy_uom_for_pur_inv_item",
	"patches.june_2012.fetch_organization_from_lead",
	"patches.june_2012.reports_list_permission",
	"patches.june_2012.support_ticket_autoreply",
	"patches.june_2012.series_unique_patch",
	"patches.june_2012.set_recurring_type",
	"patches.june_2012.alter_tabsessions",
	"patches.june_2012.delete_old_parent_entries",
	"patches.april_2012.delete_about_contact",
	"patches.july_2012.reload_pr_po_mapper",
	"patches.july_2012.address_contact_perms",
	"patches.july_2012.packing_list_cleanup_and_serial_no",
	"patches.july_2012.deprecate_import_data_control",
	"patches.july_2012.default_freeze_account",
	"patches.july_2012.update_purchase_tax",
	"patches.june_2012.cms2",
	"patches.july_2012.auth_table",
	"patches.july_2012.remove_event_role_owner_match",
	"patches.july_2012.deprecate_bulk_rename",
	"patches.july_2012.blog_guest_permission",
	"patches.july_2012.bin_permission",
	"patches.july_2012.project_patch_repeat",
	"patches.july_2012.repost_stock_due_to_wrong_packing_list",
	"patches.july_2012.supplier_quotation",
	"patches.august_2012.report_supplier_quotations",
	"patches.august_2012.task_allocated_to_assigned",
	"patches.august_2012.change_profile_permission",
	"patches.august_2012.changed_blog_date_format",
	"patches.august_2012.repost_billed_amt",
	"patches.august_2012.remove_cash_flow_statement",
	"patches.september_2012.stock_report_permissions_for_accounts",
	"patches.september_2012.communication_delete_permission",
	"patches.september_2012.all_permissions_patch",
	"patches.september_2012.customer_permission_patch",
	"patches.september_2012.add_stock_ledger_entry_index",
	"patches.september_2012.plot_patch",
	"patches.september_2012.event_permission",
	"patches.september_2012.repost_stock",
	"patches.september_2012.reload_gross_profit",
	"patches.september_2012.rebuild_trees",
	"patches.september_2012.deprecate_account_balance",
	"patches.september_2012.profile_delete_permission",
	"patches.october_2012.update_permission",
	"patches.october_2012.reload_gl_mapper",
	"patches.october_2012.fix_wrong_vouchers",
	"patches.october_2012.remove_old_customer_contact_address",
	"patches.october_2012.company_fiscal_year_docstatus_patch",
	"patches.october_2012.update_account_property",
	"patches.october_2012.remove_old_trial_bal",
	"patches.october_2012.fix_cancelled_gl_entries",
	"patches.october_2012.custom_script_delete_permission",
	"patches.november_2012.custom_field_insert_after",
	"patches.november_2012.delete_item_sales_register1",
	"patches.november_2012.rename_employee_leave_balance_report",
	"patches.november_2012.report_permissions",
	"patches.november_2012.customer_issue_allocated_to_assigned",
	"patches.november_2012.reset_appraisal_permissions",
	"patches.november_2012.disable_cancelled_profiles",
	"patches.november_2012.remove_old_unbilled_items_report",
	"patches.november_2012.support_ticket_response_to_communication",
	"patches.november_2012.cancelled_bom_patch",
	"patches.november_2012.communication_sender_and_recipient",
	"patches.november_2012.update_delivered_billed_percentage_for_pos",
	"patches.november_2012.add_theme_to_profile",
	"patches.november_2012.add_employee_field_in_employee",
	"patches.november_2012.leave_application_cleanup",
	"patches.november_2012.production_order_patch",
	"patches.november_2012.gle_floating_point_issue",
	"patches.december_2012.deprecate_tds",
	"patches.december_2012.expense_leave_reload",
	"patches.december_2012.repost_ordered_qty",
	"patches.december_2012.repost_projected_qty",
	"patches.december_2012.reload_debtors_creditors_ledger",
	"patches.december_2012.website_cache_refactor",
	"patches.december_2012.production_cleanup",
	"patches.december_2012.fix_default_print_format",
	"patches.december_2012.file_list_rename",
	"patches.december_2012.replace_createlocal",
	"patches.december_2012.clear_web_cache",
	"patches.december_2012.remove_quotation_next_contact",
	"patches.december_2012.stock_entry_cleanup",
	"patches.december_2012.production_order_naming_series",
	"patches.december_2012.rebuild_item_group_tree",
	"patches.december_2012.address_title",
	"patches.december_2012.delete_form16_print_format",
	"patches.december_2012.remove_project_mapper",
	"patches.december_2012.update_print_width",
	"patches.january_2013.remove_bad_permissions",
	"patches.january_2013.deprecate_stock_search_criteria",
	"patches.january_2013.remove_support_search_criteria",
	"patches.january_2013.holiday_list_patch",
	"patches.january_2013.stock_reconciliation_patch",
	"patches.january_2013.report_permission",
	"patches.january_2013.give_report_permission_on_read",
	"patches.january_2013.update_closed_on",
	"patches.january_2013.change_patch_structure",
	"patches.january_2013.update_country_info",
	"patches.january_2013.remove_tds_entry_from_gl_mapper",
	"patches.january_2013.update_number_format",
	"patches.january_2013.purchase_price_list",
	"execute:webnotes.reload_doc('accounts','Print Format','Payment Receipt Voucher')",
	"patches.january_2013.update_fraction_for_usd",
	"patches.january_2013.enable_currencies",
	"patches.january_2013.remove_unwanted_permission",
	"patches.january_2013.remove_landed_cost_master",
	"patches.january_2013.reload_print_format",
	"patches.january_2013.rebuild_tree",
	"execute:webnotes.reload_doc('core','doctype','docfield') #2013-01-28",
	"patches.january_2013.tabsessions_to_myisam",
	"patches.february_2013.remove_gl_mapper",
	"patches.february_2013.reload_bom_replace_tool_permission",
	"patches.february_2013.payment_reconciliation_reset_values",
	"patches.february_2013.remove_sales_order_pending_items",
	"patches.february_2013.account_negative_balance",
	"patches.february_2013.remove_account_utils_folder",
	"patches.february_2013.update_company_in_leave_application",
	"execute:webnotes.conn.sql_ddl('alter table tabSeries change `name` `name` varchar(100)')",
	"execute:webnotes.conn.sql('update tabUserRole set parentfield=\"user_roles\" where parentfield=\"userroles\"')",
	"patches.february_2013.fix_outstanding",
	"patches.february_2013.p01_event",
	"execute:webnotes.delete_doc('Page', 'Calendar')",
	"patches.february_2013.p02_email_digest",
]<|endoftext|>