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

###
# Copyright (c) 2002, Jeremiah Fincher
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
#   * Redistributions of source code must retain the above copyright notice,
#     this list of conditions, and the following disclaimer.
#   * Redistributions in binary form must reproduce the above copyright notice,
#     this list of conditions, and the following disclaimer in the
#     documentation and/or other materials provided with the distribution.
#   * Neither the name of the author of this software nor the name of
#     contributors to this software may be used to endorse or promote products
#     derived from this software without specific prior written consent.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
# ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
###

from fix import *

import gc
import os
import sys
import imp
import linecache

import conf
import debug
import world
import ircdb
import ircmsgs
import drivers
import ircutils
import callbacks

def getChannel(msg, args):
    """Returns the channel the msg came over or the channel given in args.

    If the channel was given in args, args is modified (the channel is
    removed).
    """
    if args and ircutils.isChannel(args[0]):
        return args.pop(0)
    elif ircutils.isChannel(msg.args[0]):
        return msg.args[0]
    else:
        raise callbacks.Error, 'Command must be sent in a channel or ' \
                               'include a channel in its arguments.'

def getArgs(args, needed=1, optional=0):
    """Take the needed arguments from args.

    Always returns a list of size needed + optional, filling it with however
    many empty strings is necessary to fill the tuple to the right size.

    If there aren't enough args even to satisfy needed, raise an error and
    let the caller handle sending the help message.
    """
    if len(args) < needed:
        raise callbacks.ArgumentError
    if len(args) < needed + optional:
        ret = list(args) + ([''] * (needed + optional - len(args)))
    elif len(args) >= needed + optional:
        ret = list(args[:needed + optional - 1])
        ret.append(' '.join(args[needed + optional - 1:]))
    if len(ret) == 1:
        return ret[0]
    else:
        return ret

def getKeywordArgs(irc, msg, d=None):
    if d is None:
        d = {}
    args = []
    tokenizer = callbacks.Tokenizer('=')
    s = callbacks.addressed(irc.nick, msg)
    tokens = tokenizer.tokenize(s) + [None, None]
    counter = 0
    for (left, middle, right) in window(tokens, 3):
        if counter:
            counter -= 1
            continue
        elif middle == '=':
            d[callbacks.canonicalName(left)] = right
            counter = 2
        else:
            args.append(left)
    del args[0] # The command name itself.
    return (args, d)

def checkCapability(f, capability):
    def newf(self, irc, msg, args):
        if ircdb.checkCapability(msg.prefix, capability):
            f(self, irc, msg, args)
        else:
            irc.error(msg, conf.replyNoCapability % capability)
    newf.__doc__ = f.__doc__
    return newf

class CapabilityCheckingPrivmsg(callbacks.Privmsg):
    capability = '' # To satisfy PyChecker
    def callCommand(self, f, irc, msg, args):
        if ircdb.checkCapability(msg.prefix, self.capability):
            callbacks.Privmsg.callCommand(self, f, irc, msg, args)
        else:
            irc.error(msg, conf.replyNoCapability % self.capability)

class OwnerCommands(CapabilityCheckingPrivmsg):
    capability = 'owner'
    def __init__(self):
        callbacks.Privmsg.__init__(self)
        setattr(self.__class__, 'exec', self._exec)

    def eval(self, irc, msg, args):
        """<string to be evaluated by the Python interpreter>"""
        if conf.allowEval:
            s = getArgs(args)
            try:
                irc.reply(msg, repr(eval(s)))
            except Exception, e:
                irc.reply(msg, debug.exnToString(e))
        else:
            irc.error(msg, conf.replyEvalNotAllowed)

    def _exec(self, irc, msg, args):
        """<code to exec>"""
        if conf.allowEval:
            s = getArgs(args)
            try:
                exec s
                irc.reply(msg, conf.replySuccess)
            except Exception, e:
                irc.reply(msg, debug.exnToString(e))
        else:
            irc.error(msg, conf.replyEvalNotAllowed)

    def setdefaultcapability(self, irc, msg, args):
        """<capability>

        Sets the default capability to be allowed for any command.
        """
        capability = getArgs(args)
        conf.defaultCapabilities[capability] = True
        irc.reply(msg, conf.replySuccess)

    def unsetdefaultcapability(self, irc, msg, args):
        """<capability>

        Unsets the default capability for any command.
        """
        capability = getArgs(args)
        del conf.defaultCapabilities[capability]
        irc.reply(msg, conf.replySuccess)

    def settrace(self, irc, msg, args):
        """takes no arguments

        Starts the function-tracing debug mode; beware that this makes *huge*
        logfiles.
        """
        sys.settrace(debug.tracer)
        irc.reply(msg, conf.replySuccess)

    def unsettrace(self, irc, msg, args):
        """takes no arguments

        Stops the function-tracing debug mode."""
        sys.settrace(None)
        irc.reply(msg, conf.replySuccess)

    def ircquote(self, irc, msg, args):
        """<string to be sent to the server>

        Sends the raw string given to the server.
        """
        s = getArgs(args)
        try:
            m = ircmsgs.IrcMsg(s)
            irc.queueMsg(m)
        except Exception:
            debug.recoverableException()
            irc.error(msg, conf.replyError)

    def quit(self, irc, msg, args):
        """[<int return value>]

        Exits the program with the given return value (the default is 0)
        """
        try:
            i = int(args[0])
        except (ValueError, IndexError):
            i = 0
        for driver in drivers._drivers.itervalues():
            driver.die()
        for irc in world.ircs[:]:
            irc.die()
        debug.exit(i)

    def flush(self, irc, msg, args):
        """takes no arguments

        Runs all the periodic flushers in world.flushers.
        """
        world.flush()
        irc.reply(msg, conf.replySuccess)

    def upkeep(self, irc, msg, args):
        """takes no arguments

        Runs the standard upkeep stuff (flushes and gc.collects()).
        """
        world.upkeep()
        irc.reply(msg, conf.replySuccess)

    def set(self, irc, msg, args):
        """<name> <value>

        Sets the runtime variable <name> to <value>.  Currently used variables
        include "noflush" which, if set to true value, will prevent the
        periodic flushing that normally occurs.
        """
        (name, value) = getArgs(args, optional=1)
        world.tempvars[name] = value
        irc.reply(msg, conf.replySuccess)

    def unset(self, irc, msg, args):
        """<name>

        Unsets the value of variables set via the 'set' command.
        """
        name = getArgs(args)
        try:
            del world.tempvars[name]
            irc.reply(msg, conf.replySuccess)
        except KeyError:
            irc.error(msg, 'That variable wasn\'t set.')

    def load(self, irc, msg, args):
        """<plugin>

        Loads the plugin <plugin> from the plugins/ directory.
        """
        name = getArgs(args)
        if name in [cb.name() for cb in irc.callbacks]:
            irc.error(msg, 'That module is already loaded.')
            return
        try:
            moduleInfo = imp.find_module(name)
        except ImportError:
            irc.error(msg, 'No plugin %s exists.' % name)
            return
        module = imp.load_module(name, *moduleInfo)
        linecache.checkcache()
        callback = module.Class()
        if hasattr(callback, 'configure'):
            callback.configure(irc)
        irc.addCallback(callback)
        irc.reply(msg, conf.replySuccess)

    '''
    def superreload(self, irc, msg, args):
        """<module name>

        Reloads a module, hopefully such that all vestiges of the old module
        are gone.
        """
        name = getArgs(args)
        world.superReload(__import__(name))
        irc.reply(msg, conf.replySuccess)
    '''

    def reload(self, irc, msg, args):
        """<callback name>

        Unloads and subsequently reloads the callback by name; use the 'list'
        command to see a list of the currently loaded callbacks.
        """
        name = getArgs(args)
        callbacks = irc.removeCallback(name)
        if callbacks:
            for callback in callbacks:
                callback.die()
                del callback
            gc.collect()
            try:
                moduleInfo = imp.find_module(name)
                module = imp.load_module(name, *moduleInfo)
                linecache.checkcache()
                callback = module.Class()
                if hasattr(callback, 'configure'):
                    callback.configure(irc)
                irc.addCallback(callback)
                irc.reply(msg, conf.replySuccess)
            except ImportError:
                for callback in callbacks:
                    irc.addCallback(callback)
                irc.error(msg, 'No plugin %s exists.' % name)
        else:
            irc.error(msg, 'There was no callback %s.' % name)

    def unload(self, irc, msg, args):
        """<callback name>

        Unloads the callback by name; use the 'list' command to see a list
        of the currently loaded callbacks.
        """
        name = getArgs(args)
        callbacks = irc.removeCallback(name)
        if callbacks:
            for callback in callbacks:
                callback.die()
                del callback
            gc.collect()
            irc.reply(msg, conf.replySuccess)
        else:
            irc.error(msg, 'There was no callback %s' % name)

    def cvsup(self, irc, msg, args):
        """takes no arguments"""
        irc.reply(msg, str(os.system('cvs up')))

    def say(self, irc, msg, args):
        """<channel> <text>"""
        (channel, text) = getArgs(args, needed=2)
        irc.queueMsg(ircmsgs.privmsg(channel, text))

standardPrivmsgModules = [OwnerCommands]

# vim:set shiftwidth=4 tabstop=8 expandtab textwidth=78:
<commit_msg>Made the response of the upkeep command more useful.<commit_after>#!/usr/bin/env python

###
# Copyright (c) 2002, Jeremiah Fincher
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
#   * Redistributions of source code must retain the above copyright notice,
#     this list of conditions, and the following disclaimer.
#   * Redistributions in binary form must reproduce the above copyright notice,
#     this list of conditions, and the following disclaimer in the
#     documentation and/or other materials provided with the distribution.
#   * Neither the name of the author of this software nor the name of
#     contributors to this software may be used to endorse or promote products
#     derived from this software without specific prior written consent.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
# ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
###

from fix import *

import gc
import os
import sys
import imp
import linecache

import conf
import debug
import world
import ircdb
import ircmsgs
import drivers
import ircutils
import callbacks

def getChannel(msg, args):
    """Returns the channel the msg came over or the channel given in args.

    If the channel was given in args, args is modified (the channel is
    removed).
    """
    if args and ircutils.isChannel(args[0]):
        return args.pop(0)
    elif ircutils.isChannel(msg.args[0]):
        return msg.args[0]
    else:
        raise callbacks.Error, 'Command must be sent in a channel or ' \
                               'include a channel in its arguments.'

def getArgs(args, needed=1, optional=0):
    """Take the needed arguments from args.

    Always returns a list of size needed + optional, filling it with however
    many empty strings is necessary to fill the tuple to the right size.

    If there aren't enough args even to satisfy needed, raise an error and
    let the caller handle sending the help message.
    """
    if len(args) < needed:
        raise callbacks.ArgumentError
    if len(args) < needed + optional:
        ret = list(args) + ([''] * (needed + optional - len(args)))
    elif len(args) >= needed + optional:
        ret = list(args[:needed + optional - 1])
        ret.append(' '.join(args[needed + optional - 1:]))
    if len(ret) == 1:
        return ret[0]
    else:
        return ret

def getKeywordArgs(irc, msg, d=None):
    if d is None:
        d = {}
    args = []
    tokenizer = callbacks.Tokenizer('=')
    s = callbacks.addressed(irc.nick, msg)
    tokens = tokenizer.tokenize(s) + [None, None]
    counter = 0
    for (left, middle, right) in window(tokens, 3):
        if counter:
            counter -= 1
            continue
        elif middle == '=':
            d[callbacks.canonicalName(left)] = right
            counter = 2
        else:
            args.append(left)
    del args[0] # The command name itself.
    return (args, d)

def checkCapability(f, capability):
    def newf(self, irc, msg, args):
        if ircdb.checkCapability(msg.prefix, capability):
            f(self, irc, msg, args)
        else:
            irc.error(msg, conf.replyNoCapability % capability)
    newf.__doc__ = f.__doc__
    return newf

class CapabilityCheckingPrivmsg(callbacks.Privmsg):
    capability = '' # To satisfy PyChecker
    def callCommand(self, f, irc, msg, args):
        if ircdb.checkCapability(msg.prefix, self.capability):
            callbacks.Privmsg.callCommand(self, f, irc, msg, args)
        else:
            irc.error(msg, conf.replyNoCapability % self.capability)

class OwnerCommands(CapabilityCheckingPrivmsg):
    capability = 'owner'
    def __init__(self):
        callbacks.Privmsg.__init__(self)
        setattr(self.__class__, 'exec', self._exec)

    def eval(self, irc, msg, args):
        """<string to be evaluated by the Python interpreter>"""
        if conf.allowEval:
            s = getArgs(args)
            try:
                irc.reply(msg, repr(eval(s)))
            except Exception, e:
                irc.reply(msg, debug.exnToString(e))
        else:
            irc.error(msg, conf.replyEvalNotAllowed)

    def _exec(self, irc, msg, args):
        """<code to exec>"""
        if conf.allowEval:
            s = getArgs(args)
            try:
                exec s
                irc.reply(msg, conf.replySuccess)
            except Exception, e:
                irc.reply(msg, debug.exnToString(e))
        else:
            irc.error(msg, conf.replyEvalNotAllowed)

    def setdefaultcapability(self, irc, msg, args):
        """<capability>

        Sets the default capability to be allowed for any command.
        """
        capability = getArgs(args)
        conf.defaultCapabilities[capability] = True
        irc.reply(msg, conf.replySuccess)

    def unsetdefaultcapability(self, irc, msg, args):
        """<capability>

        Unsets the default capability for any command.
        """
        capability = getArgs(args)
        del conf.defaultCapabilities[capability]
        irc.reply(msg, conf.replySuccess)

    def settrace(self, irc, msg, args):
        """takes no arguments

        Starts the function-tracing debug mode; beware that this makes *huge*
        logfiles.
        """
        sys.settrace(debug.tracer)
        irc.reply(msg, conf.replySuccess)

    def unsettrace(self, irc, msg, args):
        """takes no arguments

        Stops the function-tracing debug mode."""
        sys.settrace(None)
        irc.reply(msg, conf.replySuccess)

    def ircquote(self, irc, msg, args):
        """<string to be sent to the server>

        Sends the raw string given to the server.
        """
        s = getArgs(args)
        try:
            m = ircmsgs.IrcMsg(s)
            irc.queueMsg(m)
        except Exception:
            debug.recoverableException()
            irc.error(msg, conf.replyError)

    def quit(self, irc, msg, args):
        """[<int return value>]

        Exits the program with the given return value (the default is 0)
        """
        try:
            i = int(args[0])
        except (ValueError, IndexError):
            i = 0
        for driver in drivers._drivers.itervalues():
            driver.die()
        for irc in world.ircs[:]:
            irc.die()
        debug.exit(i)

    def flush(self, irc, msg, args):
        """takes no arguments

        Runs all the periodic flushers in world.flushers.
        """
        world.flush()
        irc.reply(msg, conf.replySuccess)

    def upkeep(self, irc, msg, args):
        """takes no arguments

        Runs the standard upkeep stuff (flushes and gc.collects()).
        """
        world.upkeep()
        if gc.garbage:
            if len(gc.garbage) < 10:
                irc.reply(msg, 'Garbage!  %r' % gc.garbage)
            else:
                irc.reply(msg, 'Garbage!  %s items.' % len(gc.garbage))
        else:
            irc.reply(msg, conf.replySuccess)

    def set(self, irc, msg, args):
        """<name> <value>

        Sets the runtime variable <name> to <value>.  Currently used variables
        include "noflush" which, if set to true value, will prevent the
        periodic flushing that normally occurs.
        """
        (name, value) = getArgs(args, optional=1)
        world.tempvars[name] = value
        irc.reply(msg, conf.replySuccess)

    def unset(self, irc, msg, args):
        """<name>

        Unsets the value of variables set via the 'set' command.
        """
        name = getArgs(args)
        try:
            del world.tempvars[name]
            irc.reply(msg, conf.replySuccess)
        except KeyError:
            irc.error(msg, 'That variable wasn\'t set.')

    def load(self, irc, msg, args):
        """<plugin>

        Loads the plugin <plugin> from the plugins/ directory.
        """
        name = getArgs(args)
        if name in [cb.name() for cb in irc.callbacks]:
            irc.error(msg, 'That module is already loaded.')
            return
        try:
            moduleInfo = imp.find_module(name)
        except ImportError:
            irc.error(msg, 'No plugin %s exists.' % name)
            return
        module = imp.load_module(name, *moduleInfo)
        linecache.checkcache()
        callback = module.Class()
        if hasattr(callback, 'configure'):
            callback.configure(irc)
        irc.addCallback(callback)
        irc.reply(msg, conf.replySuccess)

    '''
    def superreload(self, irc, msg, args):
        """<module name>

        Reloads a module, hopefully such that all vestiges of the old module
        are gone.
        """
        name = getArgs(args)
        world.superReload(__import__(name))
        irc.reply(msg, conf.replySuccess)
    '''

    def reload(self, irc, msg, args):
        """<callback name>

        Unloads and subsequently reloads the callback by name; use the 'list'
        command to see a list of the currently loaded callbacks.
        """
        name = getArgs(args)
        callbacks = irc.removeCallback(name)
        if callbacks:
            for callback in callbacks:
                callback.die()
                del callback
            gc.collect()
            try:
                moduleInfo = imp.find_module(name)
                module = imp.load_module(name, *moduleInfo)
                linecache.checkcache()
                callback = module.Class()
                if hasattr(callback, 'configure'):
                    callback.configure(irc)
                irc.addCallback(callback)
                irc.reply(msg, conf.replySuccess)
            except ImportError:
                for callback in callbacks:
                    irc.addCallback(callback)
                irc.error(msg, 'No plugin %s exists.' % name)
        else:
            irc.error(msg, 'There was no callback %s.' % name)

    def unload(self, irc, msg, args):
        """<callback name>

        Unloads the callback by name; use the 'list' command to see a list
        of the currently loaded callbacks.
        """
        name = getArgs(args)
        callbacks = irc.removeCallback(name)
        if callbacks:
            for callback in callbacks:
                callback.die()
                del callback
            gc.collect()
            irc.reply(msg, conf.replySuccess)
        else:
            irc.error(msg, 'There was no callback %s' % name)

    def cvsup(self, irc, msg, args):
        """takes no arguments"""
        irc.reply(msg, str(os.system('cvs up')))

    def say(self, irc, msg, args):
        """<channel> <text>"""
        (channel, text) = getArgs(args, needed=2)
        irc.queueMsg(ircmsgs.privmsg(channel, text))

standardPrivmsgModules = [OwnerCommands]

# vim:set shiftwidth=4 tabstop=8 expandtab textwidth=78:
<|endoftext|>


<commit_before>"""
.. topic:: The :mod:`datasets` module provides data sets to test the
    **Spectrum** functionalities.

    .. autosummary::

        data_cosine
        marple_data
        TimeSeries

    .. codeauthor:: Thomas Cokelaer 2011

    :Reference: [Marple]_
"""
import numpy
from numpy import arange, pi, cos, sin
from numpy.random import randn

#example marple app 3.A
A_cholesky = numpy.matrix([[2+0.j, .5-0.5j,-.2+.1j],
                           [.5+.5j,1,.3-0.2j],
                           [-.2-.1j,.3+.2j,.5]], dtype=complex)
a_cholesky = numpy.array([2+0.j, .5-0.5j, 1., -.2+.1j,.3-0.2j,.5],
                         dtype=complex)
B_cholesky = numpy.array([1+3j,2-1j,.5+.8j], dtype=complex)
#should return
sol_cholesky = numpy.array([ 0.95945946+5.25675676j,
                            4.41891892-7.04054054j,
                            -5.13513514+6.35135135j])

#: 64-complex data length from Marple reference [Marple]_
marple_data = [
  1.349839091+  2.011167288j,
 -2.117270231+  0.817693591j,
 -1.786421657-  1.291698933j,
  1.162236333-  1.482598066j,
  1.641072035+  0.372950256j,
  0.072213709+  1.828492761j,
 -1.564284801+  0.824533045j,
 -1.080565453-  1.869776845j,
  0.927129090-  1.743406534j,
  1.891979456+  0.972347319j,
 -0.105391249+  1.602209687j,
 -1.618367076+  0.637513280j,
 -0.945704579-  1.079569221j,
  1.135566235-  1.692269921j,
  1.855816245+  0.986030221j,
 -1.032083511+  1.414613724j,
 -1.571600199+  0.089229003j,
 -0.243143231-  1.444692016j,
  0.838980973-  0.985756695j,
  1.516003132+  0.928058863j,
  0.257979959+  1.170676708j,
 -2.057927608+  0.343388647j,
 -0.578682184-  1.441192508j,
  1.584011555-  1.011150956j,
  0.614114344+  1.508176208j,
 -0.710567117+  1.130144477j,
 -1.100205779-  0.584209621j,
  0.150702029-  1.217450142j,
  0.748856127-  0.804411888j,
  0.795235813+  1.114466429j,
 -0.071512341+  1.017092347j,
 -1.732939839-  0.283070654j,
  0.404945314-  0.781708360j,
  1.293794155-  0.352723092j,
 -0.119905084+  0.905150294j,
 -0.522588372+  0.437393665j,
 -0.974838495-  0.670074046j,
  0.275279552-  0.509659231j,
  0.854210198-  0.008278057j,
  0.289598197+  0.506233990j,
 -0.283553183+  0.250371397j,
 -0.359602571-  0.135261074j,
  0.102775671-  0.466086507j,
 -0.009722650+  0.030377999j,
  0.185930878+  0.808869600j,
 -0.243692726-  0.200126961j,
 -0.270986766-  0.460243553j,
  0.399368525+  0.249096692j,
 -0.250714004-  0.362990230j,
  0.419116348-  0.389185309j,
 -0.050458215+  0.702862442j,
 -0.395043731+  0.140808776j,
  0.746575892-  0.126762003j,
 -0.559076190+  0.523169816j,
 -0.344389260-  0.913451135j,
  0.733228028-  0.006237417j,
 -0.480273813+  0.509469569j,
  0.033316225+  0.087501869j,
 -0.321229130-  0.254548967j,
 -0.063007891-  0.499800682j,
  1.239739418-  0.013479125j,
  0.083303742+  0.673984587j,
 -0.762731433+  0.408971250j,
 -0.895898521-  0.364855707j]

def data_cosine(N=1024, A=0.1, sampling=1024., freq=200):
    r"""Return a noisy cosine at a given frequency.

    :param N:           the final data size
    :param A:           the strength of the noise
    :param float sampling: sampling frequency of the input :attr:`data`.
    :param float freq:  the frequency :math:`f_0` of the cosine.

    .. math:: x[t] = cos(2\pi t * f_0) + A w[t]

    where w[t] is a white noise of variance 1.

    .. doctest::

        >>> from spectrum import data_cosine
        >>> a = data_cosine(N=1024, sampling=1024, A=0.5, freq=100)

    """
    t = arange(0, float(N)/sampling, 1./sampling)
    x = cos(2.*pi*t*freq) + A * randn(t.size)
    return x

def data_two_freqs(N=200):
    """A simple test example with two close frequencies

    """
    nn = arange(N)
    xx = cos(0.257*pi*nn) + sin(0.2*pi*nn) + 0.01*randn(nn.size)
    return xx

class TimeSeries():
    """A simple Base Class for various data sets.

    .. doctest::

        >>> from spectrum import TimeSeries
        >>> data = [1, 2, 3, 4, 3, 2, 1, 0 ]
        >>> ts = TimeSeries(data, sampling=1)
        >>> ts.plot()
        >>> ts.dt
        1.0

    """
    def __init__(self, data, sampling=1):
        """

        :param array data: input data (list or numpy.array)
        :param sampling: the sampling frequency of the data (default 1Hz)

        """
        self.data = data
        self.N = len(data)
        self.sampling = sampling
        self.dt = 1./sampling

    def plot(self, **kargs):
        """Plot the data set, using the sampling information to set the x-axis
        correctly."""
        from pylab import plot, linspace, xlabel, ylabel, grid
        time = linspace(1*self.dt, self.N*self.dt, self.N)
        plot(time, self.data, **kargs)
        xlabel('Time')
        ylabel('Amplitude')
        grid(True)
<commit_msg>add object in class parent<commit_after>"""
.. topic:: The :mod:`datasets` module provides data sets to test the
    **Spectrum** functionalities.

    .. autosummary::

        data_cosine
        marple_data
        TimeSeries

    .. codeauthor:: Thomas Cokelaer 2011

    :Reference: [Marple]_
"""
import numpy
from numpy import arange, pi, cos, sin
from numpy.random import randn

#example marple app 3.A
A_cholesky = numpy.matrix([[2+0.j, .5-0.5j,-.2+.1j],
                           [.5+.5j,1,.3-0.2j],
                           [-.2-.1j,.3+.2j,.5]], dtype=complex)
a_cholesky = numpy.array([2+0.j, .5-0.5j, 1., -.2+.1j,.3-0.2j,.5],
                         dtype=complex)
B_cholesky = numpy.array([1+3j,2-1j,.5+.8j], dtype=complex)
#should return
sol_cholesky = numpy.array([ 0.95945946+5.25675676j,
                            4.41891892-7.04054054j,
                            -5.13513514+6.35135135j])

#: 64-complex data length from Marple reference [Marple]_
marple_data = [
  1.349839091+  2.011167288j,
 -2.117270231+  0.817693591j,
 -1.786421657-  1.291698933j,
  1.162236333-  1.482598066j,
  1.641072035+  0.372950256j,
  0.072213709+  1.828492761j,
 -1.564284801+  0.824533045j,
 -1.080565453-  1.869776845j,
  0.927129090-  1.743406534j,
  1.891979456+  0.972347319j,
 -0.105391249+  1.602209687j,
 -1.618367076+  0.637513280j,
 -0.945704579-  1.079569221j,
  1.135566235-  1.692269921j,
  1.855816245+  0.986030221j,
 -1.032083511+  1.414613724j,
 -1.571600199+  0.089229003j,
 -0.243143231-  1.444692016j,
  0.838980973-  0.985756695j,
  1.516003132+  0.928058863j,
  0.257979959+  1.170676708j,
 -2.057927608+  0.343388647j,
 -0.578682184-  1.441192508j,
  1.584011555-  1.011150956j,
  0.614114344+  1.508176208j,
 -0.710567117+  1.130144477j,
 -1.100205779-  0.584209621j,
  0.150702029-  1.217450142j,
  0.748856127-  0.804411888j,
  0.795235813+  1.114466429j,
 -0.071512341+  1.017092347j,
 -1.732939839-  0.283070654j,
  0.404945314-  0.781708360j,
  1.293794155-  0.352723092j,
 -0.119905084+  0.905150294j,
 -0.522588372+  0.437393665j,
 -0.974838495-  0.670074046j,
  0.275279552-  0.509659231j,
  0.854210198-  0.008278057j,
  0.289598197+  0.506233990j,
 -0.283553183+  0.250371397j,
 -0.359602571-  0.135261074j,
  0.102775671-  0.466086507j,
 -0.009722650+  0.030377999j,
  0.185930878+  0.808869600j,
 -0.243692726-  0.200126961j,
 -0.270986766-  0.460243553j,
  0.399368525+  0.249096692j,
 -0.250714004-  0.362990230j,
  0.419116348-  0.389185309j,
 -0.050458215+  0.702862442j,
 -0.395043731+  0.140808776j,
  0.746575892-  0.126762003j,
 -0.559076190+  0.523169816j,
 -0.344389260-  0.913451135j,
  0.733228028-  0.006237417j,
 -0.480273813+  0.509469569j,
  0.033316225+  0.087501869j,
 -0.321229130-  0.254548967j,
 -0.063007891-  0.499800682j,
  1.239739418-  0.013479125j,
  0.083303742+  0.673984587j,
 -0.762731433+  0.408971250j,
 -0.895898521-  0.364855707j]

def data_cosine(N=1024, A=0.1, sampling=1024., freq=200):
    r"""Return a noisy cosine at a given frequency.

    :param N:           the final data size
    :param A:           the strength of the noise
    :param float sampling: sampling frequency of the input :attr:`data`.
    :param float freq:  the frequency :math:`f_0` of the cosine.

    .. math:: x[t] = cos(2\pi t * f_0) + A w[t]

    where w[t] is a white noise of variance 1.

    .. doctest::

        >>> from spectrum import data_cosine
        >>> a = data_cosine(N=1024, sampling=1024, A=0.5, freq=100)

    """
    t = arange(0, float(N)/sampling, 1./sampling)
    x = cos(2.*pi*t*freq) + A * randn(t.size)
    return x

def data_two_freqs(N=200):
    """A simple test example with two close frequencies

    """
    nn = arange(N)
    xx = cos(0.257*pi*nn) + sin(0.2*pi*nn) + 0.01*randn(nn.size)
    return xx

class TimeSeries(object):
    """A simple Base Class for various data sets.

    .. doctest::

        >>> from spectrum import TimeSeries
        >>> data = [1, 2, 3, 4, 3, 2, 1, 0 ]
        >>> ts = TimeSeries(data, sampling=1)
        >>> ts.plot()
        >>> ts.dt
        1.0

    """
    def __init__(self, data, sampling=1):
        """

        :param array data: input data (list or numpy.array)
        :param sampling: the sampling frequency of the data (default 1Hz)

        """
        self.data = data
        self.N = len(data)
        self.sampling = sampling
        self.dt = 1./sampling

    def plot(self, **kargs):
        """Plot the data set, using the sampling information to set the x-axis
        correctly."""
        from pylab import plot, linspace, xlabel, ylabel, grid
        time = linspace(1*self.dt, self.N*self.dt, self.N)
        plot(time, self.data, **kargs)
        xlabel('Time')
        ylabel('Amplitude')
        grid(True)
<|endoftext|>


<commit_before><commit_msg>Fixed python sqlparse module importing issue.<commit_after><|endoftext|>


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

import os
import re
import sys
import yaml
import signal
import socket
import pycassa
import tempfile
import subprocess
from glob import glob
from time import sleep
from shutil import copyfile, copytree, rmtree

__all__ = ['Cassandra', 'skipIfNotInstalled', 'skipIfNotFound']

SEARCH_PATHS = ['/usr/local/cassandra', '/usr/local/apache-cassandra']
DEFAULT_SETTINGS = dict(auto_start=2,
                        base_dir=None,
                        cassandra_home=None,
                        pid=None,
                        copy_data_from=None)

class Cassandra(object):
    def __init__(self, **kwargs):
        self.settings = dict(DEFAULT_SETTINGS)
        self.settings.update(kwargs)
        self.pid = None
        self._owner_pid = os.getpid()
        self._use_tmpdir = False

        if self.base_dir:
            if self.base_dir[0] != '/':
                self.settings['base_dir'] = os.path.join(os.getcwd(), self.base_dir)
        else:
            self.settings['base_dir'] = tempfile.mkdtemp()
            self._use_tmpdir = True

        if self.cassandra_home is None:
            self.settings['cassandra_home'] = find_cassandra_home()

        self.settings.setdefault('cassandra_bin', os.path.join(self.cassandra_home, 'bin', 'cassandra'))

        user_config = self.settings.get('cassandra_yaml')
        with open(os.path.join(self.cassandra_home, 'conf', 'cassandra.yaml')) as fd:
            self.settings['cassandra_yaml'] = yaml.load(fd.read())
            self.settings['cassandra_yaml']['commitlog_directory'] = os.path.join(self.base_dir, 'commitlog')
            self.settings['cassandra_yaml']['data_file_directories'] = [os.path.join(self.base_dir, 'data')]
            self.settings['cassandra_yaml']['saved_caches_directory'] = os.path.join(self.base_dir, 'saved_caches')

            if user_config:
                for key, value in user_config.items():
                    self.settings['cassandra_yaml'][key] = value

        if self.auto_start:
            if os.path.exists(self.pid_file):
                raise RuntimeError('cassandra is already running (%s)' % self.pid_file)

            if self.auto_start >= 2:
                self.setup()

            self.start()

    def __del__(self):
        self.stop()

    def __enter__(self):
        return self

    def __exit__(self, *args):
        self.stop()

    def __getattr__(self, name):
        if name in self.settings:
            return self.settings[name]
        else:
            raise AttributeError("'Cassandra' object has no attribute '%s'" % name)

    @property
    def pid_file(self):
        return os.path.join(self.base_dir, 'tmp', 'cassandra.pid')

    def server_list(self):
        hostname = '127.0.0.1:%d' % self.cassandra_yaml['rpc_port']
        return [hostname]

    def setup(self):
        # copy data files
        if self.copy_data_from:
            try:
                datadir = os.path.join(self.base_dir, 'data')
                copytree(self.copy_data_from, datadir)
            except Exception as exc:
                raise RuntimeError("could not copytree %s to %s: %r" %
                                   (self.copy_data_from, datadir, exc))

        # (re)create directory structure
        for subdir in ['conf', 'commitlog', 'data', 'saved_caches', 'tmp']:
            try:
                path = os.path.join(self.base_dir, subdir)
                os.makedirs(path)
            except:
                pass

        # conf directory
        orig_dir = os.path.join(self.cassandra_home, 'conf')
        conf_dir = os.path.join(self.base_dir, 'conf')
        for filename in os.listdir(os.path.join(orig_dir)):
            srcpath = os.path.join(orig_dir, filename)
            destpath = os.path.join(conf_dir, filename)
            if not os.path.exists(destpath):
                if filename == 'log4j-server.properties':
                    logpath = os.path.join(self.base_dir, 'tmp', 'system.log')
                    with open(srcpath) as src:
                        with open(destpath, 'w') as dest:
                            property = re.sub('log4j.appender.R.File=.*',
                                              'log4j.appender.R.File=%s' % logpath,
                                              src.read())
                            dest.write(property)
                elif os.path.isdir(srcpath):
                    copytree(srcpath, destpath)
                else:
                    copyfile(srcpath, destpath)

    def prestart(self):
        # assign ports to cassandra
        ports = self.get_unused_ports(5)
        jmx_port = ports.pop()
        config_keys = ['rpc_port', 'storage_port', 'ssl_storage_port', 'native_transport_port']
        for key in config_keys:
            if key in self.settings['cassandra_yaml']:
                self.settings['cassandra_yaml'][key] = ports.pop()

        # replace cassandra-env.sh
        with open(os.path.join(self.base_dir, 'conf', 'cassandra-env.sh'), 'rt+') as fd:
            script = re.sub('JMX_PORT="7199"', 'JMX_PORT="%d"' % jmx_port, fd.read())
            fd.seek(0)
            fd.write(script)

        # generate cassandra.yaml
        with open(os.path.join(self.base_dir, 'conf', 'cassandra.yaml'), 'wt') as fd:
            fd.write(yaml.dump(self.cassandra_yaml))

    def start(self):
        if self.pid:
            return  # already started

        self.prestart()

        logger = open(os.path.join(self.base_dir, 'tmp', 'cassandra.log'), 'wt')
        pid = os.fork()
        if pid == 0:
            os.dup2(logger.fileno(), sys.__stdout__.fileno())
            os.dup2(logger.fileno(), sys.__stderr__.fileno())

            try:
                with open(self.pid_file, 'wt') as fd:
                    fd.write(str(pid))

                os.environ['CASSANDRA_CONF'] = os.path.join(self.base_dir, 'conf')
                os.execl(self.cassandra_bin, self.cassandra_bin, '-f')
            except Exception as exc:
                raise RuntimeError('failed to launch cassandra: %r' % exc)
        else:
            logger.close()

            while True:
                try:
                    sock = socket.create_connection(('127.0.0.1', self.cassandra_yaml['rpc_port']), 1.0)
                    sock.shutdown(socket.SHUT_RDWR)
                    sock.close()
                    break
                except Exception:
                    pass

                if os.waitpid(pid, os.WNOHANG) != (0, 0):
                    raise RuntimeError("*** failed to launch cassandra ***\n" + self.read_log())

                sleep(1)

            self.pid = pid

            # create test keyspace
            conn = pycassa.system_manager.SystemManager(self.server_list()[0])
            try:
                conn.create_keyspace('test', pycassa.SIMPLE_STRATEGY, {'replication_factor': '1'})
            except pycassa.InvalidRequestException:
                pass
            conn.close()

    def stop(self, _signal=signal.SIGTERM):
        if self._owner_pid == os.getpid():
            self.terminate(_signal)
            self.cleanup()

    def terminate(self, _signal=signal.SIGTERM):
        if self.pid is None:
            return  # not started

        if self._owner_pid != os.getpid():
            return  # could not stop in child process

        try:
            os.kill(self.pid, _signal)
            while (os.waitpid(self.pid, 0)):
                pass
        except:
            pass

        self.pid = None

        try:
            os.unlink(self.pid_file)
        except:
            pass

    def cleanup(self):
        if self.pid is not None:
            return

        if self._use_tmpdir and os.path.exists(self.base_dir):
            rmtree(self.base_dir)

    def read_log(self):
        try:
            with open(os.path.join(self.base_dir, 'tmp', 'cassandra.log')) as log:
                return log.read()
        except Exception as exc:
            raise RuntimeError("failed to open file:tmp/cassandra.log: %r" % exc)

    def get_unused_ports(self, count=1):
        ports = []
        sockets = []
        for _ in range(count):
            sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
            sock.bind(('127.0.0.1', 0))
            _, port = sock.getsockname()

            ports.append(port)
            sockets.append(sock)

        for sock in sockets:
            sock.close()

        return ports

def skipIfNotInstalled(arg=None):
    if sys.version_info < (2, 7):
        from unittest2 import skipIf
    else:
        from unittest import skipIf

    def decorator(fn, path=arg):
        if path:
            cond = not os.path.exists(path)
        else:
            try:
                find_cassandra_home()  # raise exception if not found
                cond = False
            except:
                cond = True  # not found

        return skipIf(cond, "Cassandra does not found")(fn)

    if callable(arg):  # execute as simple decorator
        return decorator(arg, None)
    else:  # execute with path argument
        return decorator

skipIfNotFound = skipIfNotInstalled

def find_cassandra_home():
    for dir in SEARCH_PATHS:
        if os.path.exists(os.path.join(dir, 'bin', 'cassandra')):
            return dir

    def strip_version(dir):
        m = re.search('(\d+)\.(\d+)\.(\d+)', dir)
        if m is None:
            return None
        else:
            return [int(ver) for ver in m.groups()]

    # search newest cassandra-x.x.x directory
    cassandra_dirs = [dir for dir in glob("/usr/local/*cassandra*") if os.path.isdir(dir)]
    if cassandra_dirs:
        return sorted(cassandra_dirs, key=strip_version)[-1]

    raise RuntimeError("could not find CASSANDRA_HOME")

def get_path_of(name):
    path = subprocess.Popen(['which', name], stdout=subprocess.PIPE, stderr=subprocess.PIPE).communicate()[0]
    if path:
        return path.rstrip().decode('utf-8')
    else:
        return None
<commit_msg>Fix failed on cleanup()<commit_after># -*- coding: utf-8 -*-
#  Copyright 2013 Takeshi KOMIYA
#
#  Licensed under the Apache License, Version 2.0 (the "License");
#  you may not use this file except in compliance with the License.
#  You may obtain a copy of the License at
#
#      http://www.apache.org/licenses/LICENSE-2.0
#
#  Unless required by applicable law or agreed to in writing, software
#  distributed under the License is distributed on an "AS IS" BASIS,
#  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
#  See the License for the specific language governing permissions and
#  limitations under the License.

import os
import re
import sys
import yaml
import signal
import socket
import pycassa
import tempfile
import subprocess
from glob import glob
from time import sleep
from shutil import copyfile, copytree, rmtree

__all__ = ['Cassandra', 'skipIfNotInstalled', 'skipIfNotFound']

SEARCH_PATHS = ['/usr/local/cassandra', '/usr/local/apache-cassandra']
DEFAULT_SETTINGS = dict(auto_start=2,
                        base_dir=None,
                        cassandra_home=None,
                        pid=None,
                        copy_data_from=None)

class Cassandra(object):
    def __init__(self, **kwargs):
        self.settings = dict(DEFAULT_SETTINGS)
        self.settings.update(kwargs)
        self.pid = None
        self._owner_pid = os.getpid()
        self._use_tmpdir = False

        if self.base_dir:
            if self.base_dir[0] != '/':
                self.settings['base_dir'] = os.path.join(os.getcwd(), self.base_dir)
        else:
            self.settings['base_dir'] = tempfile.mkdtemp()
            self._use_tmpdir = True

        if self.cassandra_home is None:
            self.settings['cassandra_home'] = find_cassandra_home()

        self.settings.setdefault('cassandra_bin', os.path.join(self.cassandra_home, 'bin', 'cassandra'))

        user_config = self.settings.get('cassandra_yaml')
        with open(os.path.join(self.cassandra_home, 'conf', 'cassandra.yaml')) as fd:
            self.settings['cassandra_yaml'] = yaml.load(fd.read())
            self.settings['cassandra_yaml']['commitlog_directory'] = os.path.join(self.base_dir, 'commitlog')
            self.settings['cassandra_yaml']['data_file_directories'] = [os.path.join(self.base_dir, 'data')]
            self.settings['cassandra_yaml']['saved_caches_directory'] = os.path.join(self.base_dir, 'saved_caches')

            if user_config:
                for key, value in user_config.items():
                    self.settings['cassandra_yaml'][key] = value

        if self.auto_start:
            if os.path.exists(self.pid_file):
                raise RuntimeError('cassandra is already running (%s)' % self.pid_file)

            if self.auto_start >= 2:
                self.setup()

            self.start()

    def __del__(self):
        self.stop()

    def __enter__(self):
        return self

    def __exit__(self, *args):
        self.stop()

    def __getattr__(self, name):
        if name in self.settings:
            return self.settings[name]
        else:
            raise AttributeError("'Cassandra' object has no attribute '%s'" % name)

    @property
    def pid_file(self):
        return os.path.join(self.base_dir, 'tmp', 'cassandra.pid')

    def server_list(self):
        hostname = '127.0.0.1:%d' % self.cassandra_yaml['rpc_port']
        return [hostname]

    def setup(self):
        # copy data files
        if self.copy_data_from:
            try:
                datadir = os.path.join(self.base_dir, 'data')
                copytree(self.copy_data_from, datadir)
            except Exception as exc:
                raise RuntimeError("could not copytree %s to %s: %r" %
                                   (self.copy_data_from, datadir, exc))

        # (re)create directory structure
        for subdir in ['conf', 'commitlog', 'data', 'saved_caches', 'tmp']:
            try:
                path = os.path.join(self.base_dir, subdir)
                os.makedirs(path)
            except:
                pass

        # conf directory
        orig_dir = os.path.join(self.cassandra_home, 'conf')
        conf_dir = os.path.join(self.base_dir, 'conf')
        for filename in os.listdir(os.path.join(orig_dir)):
            srcpath = os.path.join(orig_dir, filename)
            destpath = os.path.join(conf_dir, filename)
            if not os.path.exists(destpath):
                if filename == 'log4j-server.properties':
                    logpath = os.path.join(self.base_dir, 'tmp', 'system.log')
                    with open(srcpath) as src:
                        with open(destpath, 'w') as dest:
                            property = re.sub('log4j.appender.R.File=.*',
                                              'log4j.appender.R.File=%s' % logpath,
                                              src.read())
                            dest.write(property)
                elif os.path.isdir(srcpath):
                    copytree(srcpath, destpath)
                else:
                    copyfile(srcpath, destpath)

    def prestart(self):
        # assign ports to cassandra
        ports = self.get_unused_ports(5)
        jmx_port = ports.pop()
        config_keys = ['rpc_port', 'storage_port', 'ssl_storage_port', 'native_transport_port']
        for key in config_keys:
            if key in self.settings['cassandra_yaml']:
                self.settings['cassandra_yaml'][key] = ports.pop()

        # replace cassandra-env.sh
        with open(os.path.join(self.base_dir, 'conf', 'cassandra-env.sh'), 'rt+') as fd:
            script = re.sub('JMX_PORT="7199"', 'JMX_PORT="%d"' % jmx_port, fd.read())
            fd.seek(0)
            fd.write(script)

        # generate cassandra.yaml
        with open(os.path.join(self.base_dir, 'conf', 'cassandra.yaml'), 'wt') as fd:
            fd.write(yaml.dump(self.cassandra_yaml))

    def start(self):
        if self.pid:
            return  # already started

        self.prestart()

        logger = open(os.path.join(self.base_dir, 'tmp', 'cassandra.log'), 'wt')
        pid = os.fork()
        if pid == 0:
            os.dup2(logger.fileno(), sys.__stdout__.fileno())
            os.dup2(logger.fileno(), sys.__stderr__.fileno())

            try:
                with open(self.pid_file, 'wt') as fd:
                    fd.write(str(pid))

                os.environ['CASSANDRA_CONF'] = os.path.join(self.base_dir, 'conf')
                os.execl(self.cassandra_bin, self.cassandra_bin, '-f')
            except Exception as exc:
                raise RuntimeError('failed to launch cassandra: %r' % exc)
        else:
            logger.close()

            while True:
                try:
                    sock = socket.create_connection(('127.0.0.1', self.cassandra_yaml['rpc_port']), 1.0)
                    sock.shutdown(socket.SHUT_RDWR)
                    sock.close()
                    break
                except Exception:
                    pass

                if os.waitpid(pid, os.WNOHANG) != (0, 0):
                    raise RuntimeError("*** failed to launch cassandra ***\n" + self.read_log())

                sleep(1)

            self.pid = pid

            # create test keyspace
            conn = pycassa.system_manager.SystemManager(self.server_list()[0])
            try:
                conn.create_keyspace('test', pycassa.SIMPLE_STRATEGY, {'replication_factor': '1'})
            except pycassa.InvalidRequestException:
                pass
            conn.close()

    def stop(self, _signal=signal.SIGTERM):
        if self._owner_pid == os.getpid():
            self.terminate(_signal)
            self.cleanup()

    def terminate(self, _signal=signal.SIGTERM):
        if self.pid is None:
            return  # not started

        if self._owner_pid != os.getpid():
            return  # could not stop in child process

        try:
            os.kill(self.pid, _signal)
            while (os.waitpid(self.pid, 0)):
                pass
        except:
            pass

        self.pid = None

        try:
            os.unlink(self.pid_file)
        except:
            pass

    def cleanup(self):
        if self.pid is not None:
            return

        if self._use_tmpdir and os.path.exists(self.base_dir):
            rmtree(self.base_dir, ignore_errors=True)

    def read_log(self):
        try:
            with open(os.path.join(self.base_dir, 'tmp', 'cassandra.log')) as log:
                return log.read()
        except Exception as exc:
            raise RuntimeError("failed to open file:tmp/cassandra.log: %r" % exc)

    def get_unused_ports(self, count=1):
        ports = []
        sockets = []
        for _ in range(count):
            sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
            sock.bind(('127.0.0.1', 0))
            _, port = sock.getsockname()

            ports.append(port)
            sockets.append(sock)

        for sock in sockets:
            sock.close()

        return ports

def skipIfNotInstalled(arg=None):
    if sys.version_info < (2, 7):
        from unittest2 import skipIf
    else:
        from unittest import skipIf

    def decorator(fn, path=arg):
        if path:
            cond = not os.path.exists(path)
        else:
            try:
                find_cassandra_home()  # raise exception if not found
                cond = False
            except:
                cond = True  # not found

        return skipIf(cond, "Cassandra does not found")(fn)

    if callable(arg):  # execute as simple decorator
        return decorator(arg, None)
    else:  # execute with path argument
        return decorator

skipIfNotFound = skipIfNotInstalled

def find_cassandra_home():
    for dir in SEARCH_PATHS:
        if os.path.exists(os.path.join(dir, 'bin', 'cassandra')):
            return dir

    def strip_version(dir):
        m = re.search('(\d+)\.(\d+)\.(\d+)', dir)
        if m is None:
            return None
        else:
            return [int(ver) for ver in m.groups()]

    # search newest cassandra-x.x.x directory
    cassandra_dirs = [dir for dir in glob("/usr/local/*cassandra*") if os.path.isdir(dir)]
    if cassandra_dirs:
        return sorted(cassandra_dirs, key=strip_version)[-1]

    raise RuntimeError("could not find CASSANDRA_HOME")

def get_path_of(name):
    path = subprocess.Popen(['which', name], stdout=subprocess.PIPE, stderr=subprocess.PIPE).communicate()[0]
    if path:
        return path.rstrip().decode('utf-8')
    else:
        return None
<|endoftext|>


<commit_before>import sys
import wx
import time
import threading
sys.path.insert(0, "../settings/")
import settings
sys.path.insert(0, "../control/")
import motorControl
sys.path.insert(0, "../traj/")
import trajectoryController
sys.path.insert(0, "../arduino/")
import python2arduino

class MyFrame(wx.Frame):
    def __init__(self, parent, id, title):
        wx.Frame.__init__(self, parent, id, title, wx.DefaultPosition, (800, 600))
        #panel = wx.Panel(self, -1, style=wx.SIMPLE_BORDER)

        vbox = wx.BoxSizer(wx.VERTICAL)
        hboxcontrols = wx.BoxSizer(wx.HORIZONTAL)
        hboxlist = wx.BoxSizer(wx.HORIZONTAL)

        vbox.Add(hboxcontrols)
        vbox.Add(hboxlist, 1, wx.EXPAND)

        #load motor
        motorSettings = settings.MotorSettings().get()
        self.motorController = motorControl.MotorControl(motorSettings)
        self.motorController.setAllSpeed(100)
        #parse motor setting to get min and max angle, store result in hash motors
        motors = {}
        motorsConfig=motorSettings["motorConfig"]
        for motor in motorsConfig:
            motors[motor[3]] = [motor[1], motor[2]]

        #load led
        self.ledController = python2arduino.Arduino()

        #visual element

        #bowl button
        pnlBowl = wx.Panel(self, -1, size=(10,-1), style=wx.SIMPLE_BORDER)
        hboxcontrols.Add(pnlBowl, 1, wx.ALL |wx.EXPAND, 1)
        self.sldBowl = wx.Slider(pnlBowl, -1, motors["bowl"][0], motors["bowl"][0], motors["bowl"][1], wx.DefaultPosition, (-1, -1), wx.SL_VERTICAL | wx.SL_LABELS)
        textBowl = wx.StaticText(pnlBowl, -1, 'Bowl')
        vboxBowl = wx.BoxSizer(wx.VERTICAL)
        vboxBowl.Add(self.sldBowl, 1, wx.CENTER, 0)
        vboxBowl.Add(textBowl, 1, wx.CENTER)
        pnlBowl.SetSizer(vboxBowl)

        #bottom button
        pnlBottom = wx.Panel(self, -1, style=wx.SIMPLE_BORDER)
        hboxcontrols.Add(pnlBottom, 1, wx.ALL | wx.EXPAND, 1)
        self.sldBottom = wx.Slider(pnlBottom, -1, motors["bottom"][1], motors["bottom"][0], motors["bottom"][1], wx.DefaultPosition, (-1, -1), wx.SL_VERTICAL | wx.SL_LABELS)
        textBottom = wx.StaticText(pnlBottom, -1, 'Bottom')
        vboxBottom = wx.BoxSizer(wx.VERTICAL)
        vboxBottom.Add(self.sldBottom, 1, wx.CENTER)
        vboxBottom.Add(textBottom, 1, wx.CENTER)
        pnlBottom.SetSizer(vboxBottom)

        #middle button
        pnlMiddle = wx.Panel(self, -1, style=wx.SIMPLE_BORDER)
        hboxcontrols.Add(pnlMiddle, 1, wx.ALL | wx.EXPAND, 1)
        self.sldMiddle = wx.Slider(pnlMiddle, -1, motors["mid"][0], motors["mid"][0], motors["mid"][1], wx.DefaultPosition, (-1, -1), wx.SL_VERTICAL | wx.SL_LABELS)
        textMiddle = wx.StaticText(pnlMiddle, -1, 'Middle')
        vboxMiddle= wx.BoxSizer(wx.VERTICAL)
        vboxMiddle.Add(self.sldMiddle, 1, wx.CENTER)
        vboxMiddle.Add(textMiddle, 1, wx.CENTER)
        pnlMiddle.SetSizer(vboxMiddle)

        #top button
        pnlTop = wx.Panel(self, -1, style=wx.SIMPLE_BORDER)
        hboxcontrols.Add(pnlTop, 1, wx.ALL | wx.EXPAND, 1)
        self.sldTop = wx.Slider(pnlTop, -1, motors["top"][0], motors["top"][0], motors["top"][1], wx.DefaultPosition, (-1, -1), wx.SL_VERTICAL | wx.SL_LABELS)
        textTop = wx.StaticText(pnlTop, -1, 'Top')
        vboxTop = wx.BoxSizer(wx.VERTICAL)
        vboxTop.Add(self.sldTop, 1, wx.CENTER)
        vboxTop.Add(textTop, 1, wx.CENTER)
        pnlTop.SetSizer(vboxTop)

        #head button
        pnlHead = wx.Panel(self, -1, style=wx.SIMPLE_BORDER)
        hboxcontrols.Add(pnlHead, 1, wx.ALL | wx.EXPAND, 1)
        self.sldHead = wx.Slider(pnlHead, -1, motors["head"][0], motors["head"][0], motors["head"][1], wx.DefaultPosition, (-1, -1), wx.SL_VERTICAL | wx.SL_LABELS)
        textHead = wx.StaticText(pnlHead, -1, 'Head')
        vboxHead = wx.BoxSizer(wx.VERTICAL)
        vboxHead.Add(self.sldHead, 1, wx.CENTER)
        vboxHead.Add(textHead, 1, wx.CENTER)
        pnlHead.SetSizer(vboxHead)

        #red button
        pnlRed = wx.Panel(self, -1, style=wx.SIMPLE_BORDER)
        hboxcontrols.Add(pnlRed, 1, wx.ALL | wx.EXPAND, 1)
        self.sldRed = wx.Slider(pnlRed, -1, 0, 0, 255, wx.DefaultPosition, (-1, -1), wx.SL_VERTICAL | wx.SL_LABELS)
        textRed = wx.StaticText(pnlRed, -1, 'Red')
        vboxRed = wx.BoxSizer(wx.VERTICAL)
        vboxRed.Add(self.sldRed, 1, wx.CENTER)
        vboxRed.Add(textRed, 1, wx.CENTER)
        pnlRed.SetSizer(vboxRed)

        #green button
        pnlGreen = wx.Panel(self, -1, style=wx.SIMPLE_BORDER)
        hboxcontrols.Add(pnlGreen, 1, wx.ALL | wx.EXPAND, 1)
        self.sldGreen = wx.Slider(pnlGreen, -1, 0, 0, 255, wx.DefaultPosition, (-1, -1), wx.SL_VERTICAL | wx.SL_LABELS)
        textGreen = wx.StaticText(pnlGreen, -1, 'Green')
        vboxGreen = wx.BoxSizer(wx.VERTICAL)
        vboxGreen.Add(self.sldGreen, 1, wx.CENTER)
        vboxGreen.Add(textGreen, 1, wx.CENTER)
        pnlGreen.SetSizer(vboxGreen)

        #blue button
        pnlBlue = wx.Panel(self, -1, style=wx.SIMPLE_BORDER)
        hboxcontrols.Add(pnlBlue, 1, wx.ALL | wx.EXPAND, 1)
        self.sldBlue = wx.Slider(pnlBlue, -1, 0, 0, 255, wx.DefaultPosition, (-1, -1), wx.SL_VERTICAL | wx.SL_LABELS)
        textBlue = wx.StaticText(pnlBlue, -1, 'Blue')
        vboxBlue = wx.BoxSizer(wx.VERTICAL)
        vboxBlue.Add(self.sldBlue, 1, wx.CENTER)
        vboxBlue.Add(textBlue, 1, wx.CENTER)
        pnlBlue.SetSizer(vboxBlue)

        #buttons
        pnlButtons = wx.Panel(self, -1, style=wx.SIMPLE_BORDER)
        hboxcontrols.Add(pnlButtons, 1, wx.EXPAND | wx.ALL, 1)
        vboxButton = wx.BoxSizer(wx.VERTICAL)

        gotoButton = wx.Button(pnlButtons, 7, 'Go To')
        vboxButton.Add(gotoButton, 1, wx.ALIGN_CENTER | wx.TOP, 15)
        wx.EVT_BUTTON(self, 7, self.OnGoto)

        savePositionButton = wx.Button(pnlButtons, 8, 'Save position to list')
        vboxButton.Add(savePositionButton, 1, wx.ALIGN_CENTER | wx.TOP, 15)
        wx.EVT_BUTTON(self, 8, self.OnSavePosition)

        deletePositionButton = wx.Button(pnlButtons, 9, 'delete position from list')
        vboxButton.Add(deletePositionButton, 1, wx.ALIGN_CENTER | wx.TOP, 15)
        wx.EVT_BUTTON(self, 9, self.OnDeletePosition)

        playButton = wx.Button(pnlButtons, 10, 'Play')
        vboxButton.Add(playButton, 1, wx.ALIGN_CENTER | wx.TOP, 15)
        wx.EVT_BUTTON(self, 10, self.OnPlay)

        stopButton = wx.Button(pnlButtons, 11, 'Stop')
        vboxButton.Add(stopButton, 1, wx.ALIGN_CENTER | wx.TOP | wx.BOTTOM, 15)
        wx.EVT_BUTTON(self, 11, self.OnStop)

        pnlButtons.SetSizer(vboxButton)

        #list of position
        self.positionList = wx.ListCtrl(self, -1, style=wx.LC_REPORT)
        self.positionList.InsertColumn(0, 'bowl')
        self.positionList.InsertColumn(1, 'bottom')
        self.positionList.InsertColumn(2, 'middle')
        self.positionList.InsertColumn(3, 'top')
        self.positionList.InsertColumn(4, 'head')
        self.positionList.InsertColumn(5, 'red')
        self.positionList.InsertColumn(6, 'green')
        self.positionList.InsertColumn(7, 'blue')
        hboxlist.Add(self.positionList, 1, wx.EXPAND)

        #panel.SetSizer(vbox)
        self.SetSizer(vbox)

    def OnPlay(self, event):
        count = self.positionList.GetItemCount()
        listMove = []
        listLed = []
        for row in range(count):
            tmpListMove = []
            value = int(self.positionList.GetItem(row, 0).GetText())
            tmpListMove.append(["bowl", value])
            value = int(self.positionList.GetItem(row, 1).GetText())
            tmpListMove.append(["bottom", value])
            value = int(self.positionList.GetItem(row, 2).GetText())
            tmpListMove.append(["mid", value])
            value = int(self.positionList.GetItem(row, 3).GetText())
            tmpListMove.append(["top", value])
            value = int(self.positionList.GetItem(row, 4).GetText())
            tmpListMove.append(["head", value])
            listMove.append(tmpListMove)

            tmpListLed = []
            value = int(self.positionList.GetItem(row, 5).GetText())
            tmpListLed.append(value)
            value = int(self.positionList.GetItem(row, 6).GetText())
            tmpListLed.append(value)
            value = int(self.positionList.GetItem(row, 7).GetText())
            tmpListLed.append(value)
            listLed.append(tmpListLed)

        #thread for sequence of movement
        self.play = PlayMove(self.motorController, self.ledController)
        self.play.listMove(listMove)
        self.play.listLed(listLed)
        self.play.start()

    def OnStop(self, event):
        #print "caramel"
        self.play.stop()

    def OnGoto(self, event):

        red = self.sldRed.GetValue()
        green = self.sldGreen.GetValue()
        blue = self.sldBlue.GetValue()
        self.ledController.lightLed(red, green, blue)

        listMove = []
        listMove.append(["bowl", self.sldBowl.GetValue()])
        listMove.append(["bottom", self.sldBottom.GetValue()])
        listMove.append(["mid", self.sldMiddle.GetValue()])
        listMove.append(["top", self.sldTop.GetValue()])
        listMove.append(["head", self.sldHead.GetValue()])
        self.motorController.setAllSpeed(100)
        self.motorController.setMotorsByName(listMove)

    def OnSavePosition(self, event):
        num_positions = self.positionList.GetItemCount()
        self.positionList.InsertStringItem(num_positions, str(self.sldBowl.GetValue()))
        self.positionList.SetStringItem(num_positions, 1, str(self.sldBottom.GetValue()))
        self.positionList.SetStringItem(num_positions, 2, str(self.sldMiddle.GetValue()))
        self.positionList.SetStringItem(num_positions, 3, str(self.sldTop.GetValue()))
        self.positionList.SetStringItem(num_positions, 4, str(self.sldHead.GetValue()))
        self.positionList.SetStringItem(num_positions, 5, str(self.sldRed.GetValue()))
        self.positionList.SetStringItem(num_positions, 6, str(self.sldGreen.GetValue()))
        self.positionList.SetStringItem(num_positions, 7, str(self.sldBlue.GetValue()))

    def OnDeletePosition(self, event):
        while self.positionList.GetSelectedItemCount() != 0 :
            index = self.positionList.GetFirstSelected()
            self.positionList.DeleteItem(index)

class MyApp(wx.App):
    def OnInit(self):
        frame = MyFrame(None, -1, 'Pinokio alpha 0.1')
        frame.Show(True)
        frame.Centre()
        return True

def getValueList(l):
  res = []
  for move in l:
    res.append(move[1])
  return res

#this class handle moves sequence, in a thread. So that GUI is not block when moves sequence is launched
class PlayMove(threading.Thread):
    def __init__(self, motorController, ledController):
        threading.Thread.__init__(self)
        #init stop flog to false
        self.play = False
        self.stoplock = threading.Lock()

        #initialize motor and led controller
        self.motorController = motorController
        self.ledController = ledController

    def run(self):
        #set the stop flag to true
        self.play = True
        index = 0

        #Go to initial position
        print self.moves[0]
        self.motorController.setMotorsByName(self.moves[0])

        #set led color to initial color
        currentLedColor=self.led[0]
        self.ledController.lightLed(int(currentLedColor[0]), int(currentLedColor[1]), int(currentLedColor[2]))

        #wait for the end of the move
        time.sleep(3)

        if len(self.moves) > 1 :
          traj = trajectoryController.TrajectoryController(100,40,len(self.moves[0]))
          traj.set(getValueList(self.moves[0]),getValueList(self.moves[1]))
          #while stop button have not been pressed
          while self.play :
            #if motors haven't reach the position
            if not traj.update():
              self.motorController.setAllSpeed(int(traj.speed))
              values = [["bowl",traj.position[0]],
                        ["bottom",traj.position[1]],
                        ["mid",traj.position[2]],
                        ["top",traj.position[3]],
                        ["head",traj.position[4]]]
              self.motorController.setMotorsByName(values)
            #if motors are in final position
            else :
                #increment index but keep it in list length
                index = (index + 1) % len(self.moves)
                #set a new trajectory between the current position and the next position
                traj.set(getValueList(self.moves[index]), getValueList(self.moves[(index + 1) % len(self.moves)]))
                #change led color
                currentLedColor = self.led[index]
                self.ledController.lightLed(currentLedColor[0], currentLedColor[1], currentLedColor[2])

    def stop(self):
        with self.stoplock:
            #set stop flag to false
            #moves sequence's stop and the thread can be deleted
            self.play = False

    def listMove(self, list):
        with self.stoplock:
            #update list of moves
            self.moves = list

    def listLed(self, list):
        with self.stoplock:
            #update list of colors
            self.led = list

<commit_msg>GUI that correctly fit the windows under linux<commit_after>import sys
import wx
import time
import threading
sys.path.insert(0, "../settings/")
import settings
sys.path.insert(0, "../control/")
import motorControl
sys.path.insert(0, "../traj/")
import trajectoryController
sys.path.insert(0, "../arduino/")
import python2arduino

class MyFrame(wx.Frame):
    def __init__(self, parent, id, title):
        wx.Frame.__init__(self, parent, id, title, wx.DefaultPosition, (800, 600))

        hbox= wx.BoxSizer(wx.HORIZONTAL)
        vbox = wx.BoxSizer(wx.VERTICAL)
        hboxcontrols = wx.BoxSizer(wx.HORIZONTAL)
        hboxlist = wx.BoxSizer(wx.HORIZONTAL)

        vbox.Add(hboxcontrols, 1, wx.EXPAND)
        vbox.Add(hboxlist, 1, wx.EXPAND)

        #comment load motor and load led when working on gui
        #load motor
        motorSettings = settings.MotorSettings().get()
        self.motorController = motorControl.MotorControl(motorSettings)
        self.motorController.setAllSpeed(100)
        #parse motor setting to get min and max angle, store result in hash motors
        motors = {}
        motorsConfig=motorSettings["motorConfig"]
        for motor in motorsConfig:
            motors[motor[3]] = [motor[1], motor[2]]

        #uncomment when working on gui
        #motors = {"bowl": [0, 150], "bottom": [0, 150], "mid": [0, 150], "top": [0, 150], "head": [0, 150]}

        #visual element

        #bowl button
        pnlBowl = wx.Panel(self, -1, style=wx.SIMPLE_BORDER)
        hboxcontrols.Add(pnlBowl, 1, wx.ALL |wx.EXPAND, 1)
        self.sldBowl = wx.Slider(pnlBowl, -1, motors["bowl"][0], motors["bowl"][0], motors["bowl"][1], wx.DefaultPosition, (-1, -1), wx.SL_VERTICAL | wx.SL_LABELS)
        textBowl = wx.StaticText(pnlBowl, -1, 'Bowl')
        vboxBowl = wx.BoxSizer(wx.VERTICAL)
        vboxBowl.Add(self.sldBowl, 1, wx.CENTER, 0)
        vboxBowl.Add(textBowl, 1, wx.CENTER)
        pnlBowl.SetSizer(vboxBowl)

        #bottom button
        pnlBottom = wx.Panel(self, -1, style=wx.SIMPLE_BORDER)
        hboxcontrols.Add(pnlBottom, 1, wx.ALL | wx.EXPAND, 1)
        self.sldBottom = wx.Slider(pnlBottom, -1, motors["bottom"][1], motors["bottom"][0], motors["bottom"][1], wx.DefaultPosition, (-1, -1), wx.SL_VERTICAL | wx.SL_LABELS)
        textBottom = wx.StaticText(pnlBottom, -1, 'Bottom')
        vboxBottom = wx.BoxSizer(wx.VERTICAL)
        vboxBottom.Add(self.sldBottom, 1, wx.CENTER)
        vboxBottom.Add(textBottom, 1, wx.CENTER)
        pnlBottom.SetSizer(vboxBottom)

        #middle button
        pnlMiddle = wx.Panel(self, -1, style=wx.SIMPLE_BORDER)
        hboxcontrols.Add(pnlMiddle, 1, wx.ALL | wx.EXPAND, 1)
        self.sldMiddle = wx.Slider(pnlMiddle, -1, motors["mid"][0], motors["mid"][0], motors["mid"][1], wx.DefaultPosition, (-1, -1), wx.SL_VERTICAL | wx.SL_LABELS)
        textMiddle = wx.StaticText(pnlMiddle, -1, 'Middle')
        vboxMiddle= wx.BoxSizer(wx.VERTICAL)
        vboxMiddle.Add(self.sldMiddle, 1, wx.CENTER)
        vboxMiddle.Add(textMiddle, 1, wx.CENTER)
        pnlMiddle.SetSizer(vboxMiddle)

        #top button
        pnlTop = wx.Panel(self, -1, style=wx.SIMPLE_BORDER)
        hboxcontrols.Add(pnlTop, 1, wx.ALL | wx.EXPAND, 1)
        self.sldTop = wx.Slider(pnlTop, -1, motors["top"][0], motors["top"][0], motors["top"][1], wx.DefaultPosition, (-1, -1), wx.SL_VERTICAL | wx.SL_LABELS)
        textTop = wx.StaticText(pnlTop, -1, 'Top')
        vboxTop = wx.BoxSizer(wx.VERTICAL)
        vboxTop.Add(self.sldTop, 1, wx.CENTER)
        vboxTop.Add(textTop, 1, wx.CENTER)
        pnlTop.SetSizer(vboxTop)

        #head button
        pnlHead = wx.Panel(self, -1, style=wx.SIMPLE_BORDER)
        hboxcontrols.Add(pnlHead, 1, wx.ALL | wx.EXPAND, 1)
        self.sldHead = wx.Slider(pnlHead, -1, motors["head"][0], motors["head"][0], motors["head"][1], wx.DefaultPosition, (-1, -1), wx.SL_VERTICAL | wx.SL_LABELS)
        textHead = wx.StaticText(pnlHead, -1, 'Head')
        vboxHead = wx.BoxSizer(wx.VERTICAL)
        vboxHead.Add(self.sldHead, 1, wx.CENTER)
        vboxHead.Add(textHead, 1, wx.CENTER)
        pnlHead.SetSizer(vboxHead)

        #red button
        pnlRed = wx.Panel(self, -1, style=wx.SIMPLE_BORDER)
        hboxcontrols.Add(pnlRed, 1, wx.ALL | wx.EXPAND, 1)
        self.sldRed = wx.Slider(pnlRed, -1, 0, 0, 255, wx.DefaultPosition, (-1, -1), wx.SL_VERTICAL | wx.SL_LABELS)
        textRed = wx.StaticText(pnlRed, -1, 'Red')
        vboxRed = wx.BoxSizer(wx.VERTICAL)
        vboxRed.Add(self.sldRed, 1, wx.CENTER)
        vboxRed.Add(textRed, 1, wx.CENTER)
        pnlRed.SetSizer(vboxRed)

        #green button
        pnlGreen = wx.Panel(self, -1, style=wx.SIMPLE_BORDER)
        hboxcontrols.Add(pnlGreen, 1, wx.ALL | wx.EXPAND, 1)
        self.sldGreen = wx.Slider(pnlGreen, -1, 0, 0, 255, wx.DefaultPosition, (-1, -1), wx.SL_VERTICAL | wx.SL_LABELS)
        textGreen = wx.StaticText(pnlGreen, -1, 'Green')
        vboxGreen = wx.BoxSizer(wx.VERTICAL)
        vboxGreen.Add(self.sldGreen, 1, wx.CENTER)
        vboxGreen.Add(textGreen, 1, wx.CENTER)
        pnlGreen.SetSizer(vboxGreen)

        #blue button
        pnlBlue = wx.Panel(self, -1, style=wx.SIMPLE_BORDER)
        hboxcontrols.Add(pnlBlue, 1, wx.ALL | wx.EXPAND, 1)
        self.sldBlue = wx.Slider(pnlBlue, -1, 0, 0, 255, wx.DefaultPosition, (-1, -1), wx.SL_VERTICAL | wx.SL_LABELS)
        textBlue = wx.StaticText(pnlBlue, -1, 'Blue')
        vboxBlue = wx.BoxSizer(wx.VERTICAL)
        vboxBlue.Add(self.sldBlue, 1, wx.CENTER)
        vboxBlue.Add(textBlue, 1, wx.CENTER)
        pnlBlue.SetSizer(vboxBlue)

        #buttons
        pnlButtons = wx.Panel(self, -1, style=wx.SIMPLE_BORDER)
        vboxButton = wx.BoxSizer(wx.VERTICAL)

        gotoButton = wx.Button(pnlButtons, 7, 'Go To')
        vboxButton.Add(gotoButton, 1, wx.ALIGN_CENTER | wx.TOP, 15)
        wx.EVT_BUTTON(self, 7, self.OnGoto)

        savePositionButton = wx.Button(pnlButtons, 8, 'Save to list')
        vboxButton.Add(savePositionButton, 1, wx.ALIGN_CENTER | wx.TOP, 15)
        wx.EVT_BUTTON(self, 8, self.OnSavePosition)

        deletePositionButton = wx.Button(pnlButtons, 9, 'Delete from list')
        vboxButton.Add(deletePositionButton, 1, wx.ALIGN_CENTER | wx.TOP, 15)
        wx.EVT_BUTTON(self, 9, self.OnDeletePosition)

        playButton = wx.Button(pnlButtons, 10, 'Play')
        vboxButton.Add(playButton, 1, wx.ALIGN_CENTER | wx.TOP, 15)
        wx.EVT_BUTTON(self, 10, self.OnPlay)

        stopButton = wx.Button(pnlButtons, 11, 'Stop')
        vboxButton.Add(stopButton, 1, wx.ALIGN_CENTER | wx.TOP | wx.BOTTOM, 15)
        wx.EVT_BUTTON(self, 11, self.OnStop)

        pnlButtons.SetSizer(vboxButton)

        #list of position
        self.positionList = wx.ListCtrl(self, -1, style=wx.LC_REPORT)
        self.positionList.InsertColumn(0, 'bowl')
        self.positionList.InsertColumn(1, 'bottom')
        self.positionList.InsertColumn(2, 'middle')
        self.positionList.InsertColumn(3, 'top')
        self.positionList.InsertColumn(4, 'head')
        self.positionList.InsertColumn(5, 'red')
        self.positionList.InsertColumn(6, 'green')
        self.positionList.InsertColumn(7, 'blue')
        hboxlist.Add(self.positionList, 1, wx.EXPAND)

        hbox.Add(vbox, 5, wx.EXPAND | wx.ALL, 1)
        hbox.Add(pnlButtons, 1, wx.EXPAND | wx.ALL, 1)
        self.SetSize((800, 600))
        self.SetSizer(hbox)
        self.Centre()

    def OnPlay(self, event):
        count = self.positionList.GetItemCount()
        listMove = []
        listLed = []
        for row in range(count):
            tmpListMove = []
            value = int(self.positionList.GetItem(row, 0).GetText())
            tmpListMove.append(["bowl", value])
            value = int(self.positionList.GetItem(row, 1).GetText())
            tmpListMove.append(["bottom", value])
            value = int(self.positionList.GetItem(row, 2).GetText())
            tmpListMove.append(["mid", value])
            value = int(self.positionList.GetItem(row, 3).GetText())
            tmpListMove.append(["top", value])
            value = int(self.positionList.GetItem(row, 4).GetText())
            tmpListMove.append(["head", value])
            listMove.append(tmpListMove)

            tmpListLed = []
            value = int(self.positionList.GetItem(row, 5).GetText())
            tmpListLed.append(value)
            value = int(self.positionList.GetItem(row, 6).GetText())
            tmpListLed.append(value)
            value = int(self.positionList.GetItem(row, 7).GetText())
            tmpListLed.append(value)
            listLed.append(tmpListLed)

        #thread for sequence of movement
        self.play = PlayMove(self.motorController, self.ledController)
        self.play.listMove(listMove)
        self.play.listLed(listLed)
        self.play.start()

    def OnStop(self, event):
        #print "caramel"
        self.play.stop()

    def OnGoto(self, event):

        red = self.sldRed.GetValue()
        green = self.sldGreen.GetValue()
        blue = self.sldBlue.GetValue()
        self.ledController.lightLed(red, green, blue)

        listMove = []
        listMove.append(["bowl", self.sldBowl.GetValue()])
        listMove.append(["bottom", self.sldBottom.GetValue()])
        listMove.append(["mid", self.sldMiddle.GetValue()])
        listMove.append(["top", self.sldTop.GetValue()])
        listMove.append(["head", self.sldHead.GetValue()])
        self.motorController.setAllSpeed(100)
        self.motorController.setMotorsByName(listMove)

    def OnSavePosition(self, event):
        num_positions = self.positionList.GetItemCount()
        self.positionList.InsertStringItem(num_positions, str(self.sldBowl.GetValue()))
        self.positionList.SetStringItem(num_positions, 1, str(self.sldBottom.GetValue()))
        self.positionList.SetStringItem(num_positions, 2, str(self.sldMiddle.GetValue()))
        self.positionList.SetStringItem(num_positions, 3, str(self.sldTop.GetValue()))
        self.positionList.SetStringItem(num_positions, 4, str(self.sldHead.GetValue()))
        self.positionList.SetStringItem(num_positions, 5, str(self.sldRed.GetValue()))
        self.positionList.SetStringItem(num_positions, 6, str(self.sldGreen.GetValue()))
        self.positionList.SetStringItem(num_positions, 7, str(self.sldBlue.GetValue()))

    def OnDeletePosition(self, event):
        while self.positionList.GetSelectedItemCount() != 0 :
            index = self.positionList.GetFirstSelected()
            self.positionList.DeleteItem(index)

class MyApp(wx.App):
    def OnInit(self):
        frame = MyFrame(None, -1, 'Pinokio alpha 0.1')
        frame.Show(True)
        frame.Centre()
        return True

def getValueList(l):
  res = []
  for move in l:
    res.append(move[1])
  return res

#this class handle moves sequence, in a thread. So that GUI is not block when moves sequence is launched
class PlayMove(threading.Thread):
    def __init__(self, motorController, ledController):
        threading.Thread.__init__(self)
        #init stop flog to false
        self.play = False
        self.stoplock = threading.Lock()

        #initialize motor and led controller
        self.motorController = motorController
        self.ledController = ledController

    def run(self):
        #set the stop flag to true
        self.play = True
        index = 0

        #Go to initial position
        #print self.moves[0]
        self.motorController.setMotorsByName(self.moves[0])

        #set led color to initial color
        currentLedColor=self.led[0]
        self.ledController.lightLed(int(currentLedColor[0]), int(currentLedColor[1]), int(currentLedColor[2]))

        #wait for the end of the move
        time.sleep(3)

        if len(self.moves) > 1 :
          traj = trajectoryController.TrajectoryController(100,40,len(self.moves[0]))
          traj.set(getValueList(self.moves[0]),getValueList(self.moves[1]))
          #while stop button have not been pressed
          while self.play :
            #if motors haven't reach the position
            if not traj.update():
              self.motorController.setAllSpeed(int(traj.speed))
              values = [["bowl",traj.position[0]],
                        ["bottom",traj.position[1]],
                        ["mid",traj.position[2]],
                        ["top",traj.position[3]],
                        ["head",traj.position[4]]]
              self.motorController.setMotorsByName(values)
            #if motors are in final position
            else :
                #increment index but keep it in list length
                index = (index + 1) % len(self.moves)
                #set a new trajectory between the current position and the next position
                traj.set(getValueList(self.moves[index]), getValueList(self.moves[(index + 1) % len(self.moves)]))
                #change led color
                currentLedColor = self.led[index]
                self.ledController.lightLed(currentLedColor[0], currentLedColor[1], currentLedColor[2])

    def stop(self):
        with self.stoplock:
            #set stop flag to false
            #moves sequence's stop and the thread can be deleted
            self.play = False

    def listMove(self, list):
        with self.stoplock:
            #update list of moves
            self.moves = list

    def listLed(self, list):
        with self.stoplock:
            #update list of colors
            self.led = list

<|endoftext|>