<commit_before># -*- coding: utf-8 -*-

# Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements.  See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You 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.

from collections import defaultdict
import logging
from multiprocessing import Manager, Lock, Process, Queue
import time

class Machine(object):
    """
    Implements a state machine

    The life cycle of a machine can be described as follows::

    1. A machine instance is created and configured::

           >>>bot = ShellBot(...)
           >>>machine = Machine(bot=bot)

           >>>machine.set(states=states, transitions=transitions, ...

    2. The machine is switched on::

           >>>machine.start()

    3. Machine can process more events than ticks::

           >>>machine.execute('hello world')

    4. When a machine is expecting data from the chat space, it listens
       from the ``fan`` queue used by the shell::

           >>>bot.fan.put('special command')

    4. When the machine is coming end of life, resources can be disposed::

           >>>machine.stop()

    credit: Alex Bertsch <abertsch@dropbox.com>   securitybot/state_machine.py
    """

    TICK_DURATION = 0.2  # time to wait between ticks

    def __init__(self,
                 bot=None,
                 states=None,
                 transitions=None,
                 initial=None,
                 during=None,
                 on_enter=None,
                 on_exit=None,
                 **kwargs):
        """
        Implements a state machine

        :param bot: the overarching bot
        :type bot: ShellBot

        :param states: All states supported by this machine
        :type states: list of str

        :param transitions: Transitions between states.
            Each transition is a dictionary. Each dictionary must feature
            following keys:
                source (str): The source state of the transition
                target (str): The target state of the transition
            Each dictionary may contain following keys:
                condition (function): A condition that must be true for the
                    transition to occur. If no condition is provided then
                    the state machine will transition on a step.
                action (function): A function to be executed while the
                    transition occurs.
        :type transitions: list of dict

        :param initial: The initial state
        :type initial: str

        :param during: A mapping of states to functions to execute while in
            that state. Each key should map to a callable function.
        :type during: dict

        :param on_enter: A mapping of states to functions to execute when
            entering that state. Each key should map to a callable function.
        :type on_enter: dict

        :param on_exit: A mapping of states to functions to execute when
            exiting that state. Each key should map to a callable function.
        :type on_exit: dict

        Example::

            machine = Machine(bot=bot)

        """
        self.bot = bot

        self.lock = Lock()
        self.mutables = Manager().dict()
        self.mixer = Queue()

        self.on_init(**kwargs)

        if states is not None:
            self.build(states, transitions, initial, during, on_enter, on_exit)

    def on_init(self, prefix='machine', **kwargs):
        """
        Handles extended initialisation parameters

        :param prefix: the main keyword for configuration of this machine
        :type prefix: str

        This function should be expanded in sub-class, where necessary.

        Example::

            def on_init(self, prefix='my.machine', **kwargs):
                ...

        """
        assert prefix not in (None, '')
        self.prefix = prefix

    def get(self, key, default=None):
        """
        Retrieves the value of one key
        """

        self.lock.acquire()
        value = None
        try:
            value = self.mutables.get(key, default)

            if value is None:
                value = default
        finally:
            self.lock.release()
            return value

    def set(self, key, value):
        """
        Remembers the value of one key
        """

        self.lock.acquire()
        try:
            self.mutables[key] = value
        finally:
            self.lock.release()

    def build(self,
            states,
            transitions,
            initial,
            during=None,
            on_enter=None,
            on_exit=None):
        """
        Builds a complete state machine

        :param states: All states supported by this machine
        :type states: list of str

        :param transitions: Transitions between states.
            Each transition is a dictionary. Each dictionary must feature
            following keys:
                source (str): The source state of the transition
                target (str): The target state of the transition
            Each dictionary may contain following keys:
                condition (function): A condition that must be true for the
                    transition to occur. If no condition is provided then
                    the state machine will transition on a step.
                action (function): A function to be executed while the
                    transition occurs.
        :type transitions: list of dict

        :param initial: The initial state
        :type initial: str

        :param during: A mapping of states to functions to execute while in
            that state. Each key should map to a callable function.
        :type during: dict

        :param on_enter: A mapping of states to functions to execute when
            entering that state. Each key should map to a callable function.
        :type on_enter: dict

        :param on_exit: A mapping of states to functions to execute when
            exiting that state. Each key should map to a callable function.
        :type on_exit: dict

        """
        if during is None:
            during = {}
        if on_enter is None:
            on_enter = {}
        if on_exit is None:
            on_exit = {}

        states = sorted(list(set(states)))

        self._states = dict()
        for state in states:
            self._states[state] = State(state,
                                        during.get(state, None),
                                        on_enter.get(state, None),
                                        on_exit.get(state, None))

        try:
            self.mutables['state'] = self._states[initial].name
        except KeyError:
            raise ValueError(u'Invalid initial state {}'.format(initial))

        self._transitions = defaultdict(list)
        for transition in transitions:
            try:
                source_state = self._states[transition['source']]
            except KeyError:
                if 'source' not in transition:
                    raise ValueError(u'Missing source state')
                else:
                    raise ValueError(u'Invalid source state {}'.format(
                        transition['source']))

            try:
                target_state = self._states[transition['target']]
            except KeyError:
                if 'target' not in transition:
                    raise ValueError(u'Missing target state')
                else:
                    raise ValueError(u'Invalid target state {}'.format(
                        transition['target']))

            item = Transition(source_state,
                              target_state,
                              transition.get('condition', None),
                              transition.get('action', None))

            self._transitions[transition['source']].append(item)

    def state(self, name):
        """
        Provides a state by name

        :param name: The label of the target state
        :type name: str

        :return: State
        """
        return self._states[name]

    @property
    def current_state(self):
        """
        Provides current state

        :return: State

        This function raises AttributeError if it is called before ``build()``.
        """
        try:
            name = self.mutables['state']
        except KeyError:
            raise AttributeError('Machine has not been built')

        return self._states[name]

    def step(self, **kwargs):
        """
        Brings some life to the state machine

        This machine should report on progress by sending
        messages with one or multiple ``self.bot.say("Whatever message")``.

        """
        self.current_state.during(**kwargs)

        for transition in self._transitions[self.current_state.name]:
            if transition.condition(**kwargs):
                logging.debug('Transitioning: {0}'.format(transition))
                transition.action()
                self.current_state.on_exit()
                self.mutables['state'] = transition.target.name
                self.current_state.on_enter()
                break

    def start(self, tick=None):
        """
        Starts the machine

        :param tick: The duration set for each tick
        :type tick: float

        :return: either the process that has been started, or None

        This function starts a separate thread to tick the machine
        in the background.
        """
        if tick:
            self.TICK_DURATION = tick

        p = Process(target=self.tick)
#        p.daemon = True
        p.start()
        return p

    def stop(self):
        """
        Stops the machine
        """
        if self.mixer is not None:
            self.mixer.put(None)

    def tick(self):
        """
        Continuously ticks the machine

        This function is looping in the background, and calls the function
        ``step()`` at regular intervals.

        The recommended way for stopping the process is to call the function
        ``stop()``. For example::

            machine.stop()

        The loop is also stopped when the parameter ``general.switch``
        is changed in the context. For example::

            bot.context.set('general.switch', 'off')

        """
        logging.info(u"Starting machine")
        self.set('is_running', True)

        try:
            while self.bot.context.get('general.switch', 'on') == 'on':

                try:
                    if self.mixer.empty():
#                        logging.debug(u"Clocking the machine")
                        self.step(event='tick')
                        time.sleep(self.TICK_DURATION)
                        continue

                    item = self.mixer.get(True, self.TICK_DURATION)
                    if item is None:
                        break

                    logging.debug('Processing item')
                    self.execute(arguments=item)

                except Exception as feedback:
                    logging.exception(feedback)
                    break

        except KeyboardInterrupt:
            pass

        logging.info(u"Machine has been stopped")
        self.set('is_running', False)

    def execute(self, arguments):
        """
        Processes data received from the chat

        This function can be used to feed the machine asynchronously
        """
        self.step(event='input', arguments=arguments)

    @property
    def is_running(self):
        """
        Determines if this machine is runnning

        :return: True or False
        """
        return self.get('is_running', False)

class State(object):
    """
    Represents a state in the machine

    Each state has a function to perform while it's active, when it's entered
    into, and when it's exited. These functions may be None.
    """
    def __init__(self,
                 name,
                 during=None,
                 on_enter=None,
                 on_exit=None):
        """
        Represents a state in the machine

        :param name: name of the state
        :type name: str

        ;param during: A function to call while this state is active.
        :type during: function

        :param on_enter: A function to call when transitioning into this state.
        :type on_enter: function

        :param on_exit: Function to call when transitioning out of this state.
        :type on_exit: function

        """
        self.name = name
        self._during = during
        self._on_enter = on_enter
        self._on_exit = on_exit

    def __repr__(self):
        """
        Provides a representation of this state

        :rtype: str

        """
        return u"State({0}, {1}, {2}, {3})".format(self.name,
                                                   self._during,
                                                   self._on_enter,
                                                   self._on_exit
                                                   )

    def __str__(self):
        """
        Provides a string handle to this state

        :rtype: str
        """
        return self.name

    def during(self, **kwargs):
        """
        Does some stuff while in this state
        """
        if self._during is not None:
            self._during(**kwargs)

    def on_enter(self):
        """
        Does some stuf while transitioning into this state
        """
        if self._on_enter is not None:
            self._on_enter()

    def on_exit(self):
        """
        Does some stuf while transitioning out of this state
        """
        if self._on_exit is not None:
            self._on_exit()

class Transition(object):
    """
    Represents a transition between two states

    Each transition object holds
    a reference to its source and destination states, as well as the condition
    function it requires for transitioning and the action to perform upon
    transitioning.
    """

    def __init__(self,
                 source,
                 target,
                 condition=None,
                 action=None):
        """
        Represents a transition between two states

        Args:
            source (State): The source State for this transition.
            target (State): The destination State for this transition.
            condition (function): The transitioning condition callback.
            action (function): An action to perform upon transitioning.
        """
        self.source = source
        self.target = target
        self._condition = condition
        self._action = action

    def __repr__(self):
        """
        Provides a representation of this transition

        :rtype: str

        """
        return u"Transition({0}, {1}, {2}, {3})".format(repr(self.source),
                                                        repr(self.target),
                                                        self._condition,
                                                        self._action
                                                        )

    def __str__(self):
        """
        Provides a string handle to this transition

        :rtype: str
        """
        return "{0} => {1}".format(self.source, self.target)

    def condition(self, **kwargs):
        """
        Checks if transition can be triggered

        :return: True or False

        Condition default to True if none is provided
        """
        return True if self._condition is None else self._condition(**kwargs)

    def action(self):
        """
        Does some stuff while transitioning
        """
        if self._action is not None:
            self._action()

<commit_msg>make base state machine more pythonic<commit_after># -*- coding: utf-8 -*-

# Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements.  See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You 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.

from collections import defaultdict
import logging
from multiprocessing import Manager, Lock, Process, Queue
import time

class Machine(object):
    """
    Implements a state machine

    The life cycle of a machine can be described as follows::

    1. A machine instance is created and configured::

           >>>bot = ShellBot(...)
           >>>machine = Machine(bot=bot)

           >>>machine.set(states=states, transitions=transitions, ...

    2. The machine is switched on::

           >>>machine.start()

    3. Machine can process more events than ticks::

           >>>machine.execute('hello world')

    4. When a machine is expecting data from the chat space, it listens
       from the ``fan`` queue used by the shell::

           >>>bot.fan.put('special command')

    4. When the machine is coming end of life, resources can be disposed::

           >>>machine.stop()

    credit: Alex Bertsch <abertsch@dropbox.com>   securitybot/state_machine.py
    """

    TICK_DURATION = 0.2  # time to wait between ticks

    def __init__(self,
                 bot=None,
                 states=None,
                 transitions=None,
                 initial=None,
                 during=None,
                 on_enter=None,
                 on_exit=None,
                 **kwargs):
        """
        Implements a state machine

        :param bot: the overarching bot
        :type bot: ShellBot

        :param states: All states supported by this machine
        :type states: list of str

        :param transitions: Transitions between states.
            Each transition is a dictionary. Each dictionary must feature
            following keys:
                source (str): The source state of the transition
                target (str): The target state of the transition
            Each dictionary may contain following keys:
                condition (function): A condition that must be true for the
                    transition to occur. If no condition is provided then
                    the state machine will transition on a step.
                action (function): A function to be executed while the
                    transition occurs.
        :type transitions: list of dict

        :param initial: The initial state
        :type initial: str

        :param during: A mapping of states to functions to execute while in
            that state. Each key should map to a callable function.
        :type during: dict

        :param on_enter: A mapping of states to functions to execute when
            entering that state. Each key should map to a callable function.
        :type on_enter: dict

        :param on_exit: A mapping of states to functions to execute when
            exiting that state. Each key should map to a callable function.
        :type on_exit: dict

        Example::

            machine = Machine(bot=bot)

        """
        self.bot = bot

        self.lock = Lock()

        # prevent Manager() process to be interrupted
        handler = signal.signal(signal.SIGINT, signal.SIG_IGN)

        self.mutables = Manager().dict()

        # restore current handler for the rest of the program
        signal.signal(signal.SIGINT, handler)

        self.mixer = Queue()

        self.on_init(**kwargs)

        if states is not None:
            self.build(states, transitions, initial, during, on_enter, on_exit)

    def on_init(self, prefix='machine', **kwargs):
        """
        Handles extended initialisation parameters

        :param prefix: the main keyword for configuration of this machine
        :type prefix: str

        This function should be expanded in sub-class, where necessary.

        Example::

            def on_init(self, prefix='my.machine', **kwargs):
                ...

        """
        assert prefix not in (None, '')
        self.prefix = prefix

    def get(self, key, default=None):
        """
        Retrieves the value of one key
        """

        with self.lock:

            value = self.mutables.get(key, default)

            if value is not None:
                return value

            return default

    def set(self, key, value):
        """
        Remembers the value of one key
        """

        with self.lock:

            self.mutables[key] = value

    def build(self,
            states,
            transitions,
            initial,
            during=None,
            on_enter=None,
            on_exit=None):
        """
        Builds a complete state machine

        :param states: All states supported by this machine
        :type states: list of str

        :param transitions: Transitions between states.
            Each transition is a dictionary. Each dictionary must feature
            following keys:
                source (str): The source state of the transition
                target (str): The target state of the transition
            Each dictionary may contain following keys:
                condition (function): A condition that must be true for the
                    transition to occur. If no condition is provided then
                    the state machine will transition on a step.
                action (function): A function to be executed while the
                    transition occurs.
        :type transitions: list of dict

        :param initial: The initial state
        :type initial: str

        :param during: A mapping of states to functions to execute while in
            that state. Each key should map to a callable function.
        :type during: dict

        :param on_enter: A mapping of states to functions to execute when
            entering that state. Each key should map to a callable function.
        :type on_enter: dict

        :param on_exit: A mapping of states to functions to execute when
            exiting that state. Each key should map to a callable function.
        :type on_exit: dict

        """
        if during is None:
            during = {}
        if on_enter is None:
            on_enter = {}
        if on_exit is None:
            on_exit = {}

        states = sorted(list(set(states)))

        self._states = dict()
        for state in states:
            self._states[state] = State(state,
                                        during.get(state, None),
                                        on_enter.get(state, None),
                                        on_exit.get(state, None))

        try:
            self.mutables['state'] = self._states[initial].name
        except KeyError:
            raise ValueError(u'Invalid initial state {}'.format(initial))

        self._transitions = defaultdict(list)
        for transition in transitions:
            try:
                source_state = self._states[transition['source']]
            except KeyError:
                if 'source' not in transition:
                    raise ValueError(u'Missing source state')
                else:
                    raise ValueError(u'Invalid source state {}'.format(
                        transition['source']))

            try:
                target_state = self._states[transition['target']]
            except KeyError:
                if 'target' not in transition:
                    raise ValueError(u'Missing target state')
                else:
                    raise ValueError(u'Invalid target state {}'.format(
                        transition['target']))

            item = Transition(source_state,
                              target_state,
                              transition.get('condition', None),
                              transition.get('action', None))

            self._transitions[transition['source']].append(item)

    def state(self, name):
        """
        Provides a state by name

        :param name: The label of the target state
        :type name: str

        :return: State
        """
        return self._states[name]

    @property
    def current_state(self):
        """
        Provides current state

        :return: State

        This function raises AttributeError if it is called before ``build()``.
        """
        try:
            name = self.mutables['state']
        except KeyError:
            raise AttributeError('Machine has not been built')

        return self._states[name]

    def step(self, **kwargs):
        """
        Brings some life to the state machine

        This machine should report on progress by sending
        messages with one or multiple ``self.bot.say("Whatever message")``.

        """
        self.current_state.during(**kwargs)

        for transition in self._transitions[self.current_state.name]:
            if transition.condition(**kwargs):
                logging.debug('Transitioning: {0}'.format(transition))
                transition.action()
                self.current_state.on_exit()
                self.mutables['state'] = transition.target.name
                self.current_state.on_enter()
                break

    def start(self, tick=None):
        """
        Starts the machine

        :param tick: The duration set for each tick
        :type tick: float

        :return: either the process that has been started, or None

        This function starts a separate thread to tick the machine
        in the background.
        """
        if tick:
            self.TICK_DURATION = tick

        p = Process(target=self.tick)
#        p.daemon = True
        p.start()
        return p

    def stop(self):
        """
        Stops the machine
        """
        if self.mixer is not None:
            self.mixer.put(None)

    def tick(self):
        """
        Continuously ticks the machine

        This function is looping in the background, and calls the function
        ``step()`` at regular intervals.

        The recommended way for stopping the process is to call the function
        ``stop()``. For example::

            machine.stop()

        The loop is also stopped when the parameter ``general.switch``
        is changed in the context. For example::

            bot.context.set('general.switch', 'off')

        """
        logging.info(u"Starting machine")
        self.set('is_running', True)

        try:
            while self.bot.context.get('general.switch', 'on') == 'on':

                try:
                    if self.mixer.empty():
#                        logging.debug(u"Clocking the machine")
                        self.step(event='tick')
                        time.sleep(self.TICK_DURATION)
                        continue

                    item = self.mixer.get(True, self.TICK_DURATION)
                    if item is None:
                        break

                    logging.debug('Processing item')
                    self.execute(arguments=item)

                except Exception as feedback:
                    logging.exception(feedback)
                    break

        except KeyboardInterrupt:
            pass

        logging.info(u"Machine has been stopped")
        self.set('is_running', False)

    def execute(self, arguments):
        """
        Processes data received from the chat

        This function can be used to feed the machine asynchronously
        """
        self.step(event='input', arguments=arguments)

    @property
    def is_running(self):
        """
        Determines if this machine is runnning

        :return: True or False
        """
        return self.get('is_running', False)

class State(object):
    """
    Represents a state in the machine

    Each state has a function to perform while it's active, when it's entered
    into, and when it's exited. These functions may be None.
    """
    def __init__(self,
                 name,
                 during=None,
                 on_enter=None,
                 on_exit=None):
        """
        Represents a state in the machine

        :param name: name of the state
        :type name: str

        ;param during: A function to call while this state is active.
        :type during: function

        :param on_enter: A function to call when transitioning into this state.
        :type on_enter: function

        :param on_exit: Function to call when transitioning out of this state.
        :type on_exit: function

        """
        self.name = name
        self._during = during
        self._on_enter = on_enter
        self._on_exit = on_exit

    def __repr__(self):
        """
        Provides a representation of this state

        :rtype: str

        """
        return u"State({0}, {1}, {2}, {3})".format(self.name,
                                                   self._during,
                                                   self._on_enter,
                                                   self._on_exit
                                                   )

    def __str__(self):
        """
        Provides a string handle to this state

        :rtype: str
        """
        return self.name

    def during(self, **kwargs):
        """
        Does some stuff while in this state
        """
        if self._during is not None:
            self._during(**kwargs)

    def on_enter(self):
        """
        Does some stuf while transitioning into this state
        """
        if self._on_enter is not None:
            self._on_enter()

    def on_exit(self):
        """
        Does some stuf while transitioning out of this state
        """
        if self._on_exit is not None:
            self._on_exit()

class Transition(object):
    """
    Represents a transition between two states

    Each transition object holds
    a reference to its source and destination states, as well as the condition
    function it requires for transitioning and the action to perform upon
    transitioning.
    """

    def __init__(self,
                 source,
                 target,
                 condition=None,
                 action=None):
        """
        Represents a transition between two states

        Args:
            source (State): The source State for this transition.
            target (State): The destination State for this transition.
            condition (function): The transitioning condition callback.
            action (function): An action to perform upon transitioning.
        """
        self.source = source
        self.target = target
        self._condition = condition
        self._action = action

    def __repr__(self):
        """
        Provides a representation of this transition

        :rtype: str

        """
        return u"Transition({0}, {1}, {2}, {3})".format(repr(self.source),
                                                        repr(self.target),
                                                        self._condition,
                                                        self._action
                                                        )

    def __str__(self):
        """
        Provides a string handle to this transition

        :rtype: str
        """
        return "{0} => {1}".format(self.source, self.target)

    def condition(self, **kwargs):
        """
        Checks if transition can be triggered

        :return: True or False

        Condition default to True if none is provided
        """
        return True if self._condition is None else self._condition(**kwargs)

    def action(self):
        """
        Does some stuff while transitioning
        """
        if self._action is not None:
            self._action()

<|endoftext|>


<commit_before>import xmpp
import threading
import Agent
import Envelope
import FIPAMessage
import AID
import Behaviour

class SpadePlatform(Agent.PlatformAgent):
	class RouteBehaviour(Behaviour.Behaviour):
		def __init__(self):
			Behaviour.Behaviour.__init__(self)
		def process(self):
			msg = self.blockingReceive()
			if (msg != None):
				to_list = msg.getReceivers()
				d = {}
				for to in to_list:
					if not to.getAddresses()[0] in d: d[to.getAddresses()[0]]=list()
					d[to.getAddresses()[0]].append(to)
				for k,v in d.items():
					newmsg = msg
					newmsg.to = v
					if k != self.myAgent.getSpadePlatformJID():
						self.myAgent.sendTo(newmsg, k)
					else:
						for recv in v:
							self.myAgent.sendTo(newmsg, recv.getName())
					# Reenviamos el msg a todos los destinatarios
					# Deberiamos de comprobar si el destinatario estaen otro servidor y reenviarselo a la plataforma en vez de a el.
					# Tambien deberiamos comprobar el protocolo y usar una pasarela en el caso de que sea necesario.
					#print "Message to", to.getName(), "... Posting!"
			else:
				print "ACC::dying... it shouldn't happen"

	def __init__(self, node, password, server, port):
		Agent.PlatformAgent.__init__(self, node, password, server, port)

	def setup(self):
		self.setDefaultBehaviour(self.RouteBehaviour())

"""
class FipperPlatform(threading.Thread):
    def __init__(self, params=dict()):
        threading.Thread.__init__(self)
        self.__params = params
        self.__mts = MTS(params)

        try:
            mtp_list = params["mtps"]
            for mtp in mtp_list:
                self.__mts.addMTP(mtp)
        except KeyError:
            pass

    def getMTS(self):
        return self.__mts

    def run(self):
        pass

class MTS:

    def __init__(self, params=dict()):
        self.__platformagents = dict()

    def addAgent(self, agent):
        aid = agent.getAID()
        self.__platformagents[aid] = agent

    def addMTP(self, mtp):
        pass

    def dispatch(self, msg):
        print "Dispatching msg..."
        envelope = msg.getEnvelope()
        to_list = envelope.getTo()
        #for to in to_list:
	#	print to

        for to in to_list:
            if to in self.__platformagents:
                print "Agend finded! Posting..."
                self.__platformagents[to].postMessage(msg)

class MTP:
    def getName(self):
        raise NotImplemented

    def getSupportedProtocols(self):
        raise NotImplemented

    def activate(self, dispatcher, params):
        raise NotImplemented

    def deactivate(self):
        raise NotImplemented

    def deliver(self, addr, envelope, payload):
        raise NotImplemented

"""

<commit_msg>packaging<commit_after>import xmpp
import threading
import Agent
import Envelope
import FIPAMessage
import AID
import Behaviour

class SpadePlatform(Agent.PlatformAgent):
	class RouteBehaviour(Behaviour.Behaviour):
		def __init__(self):
			Behaviour.Behaviour.__init__(self)
		def process(self):
			msg = self.blockingReceive()
			if (msg != None):
				to_list = msg.getReceivers()
				d = {}
				for to in to_list:
					if not to.getAddresses()[0] in d: d[to.getAddresses()[0]]=list()
					d[to.getAddresses()[0]].append(to)
				for k,v in d.items():
					newmsg = msg
					newmsg.to = v
					print "############# k != plat?"
					print " k>>"+k + "    plat>>"+self.myAgent.getSpadePlatformJID()
					if k != self.myAgent.getSpadePlatformJID():
						self.myAgent.sendTo(newmsg, k[7:])
					else:
						for recv in v:
							self.myAgent.sendTo(newmsg, recv.getName())
					# Reenviamos el msg a todos los destinatarios
					# Deberiamos de comprobar si el destinatario estaen otro servidor y reenviarselo a la plataforma en vez de a el.
					# Tambien deberiamos comprobar el protocolo y usar una pasarela en el caso de que sea necesario.
					#print "Message to", to.getName(), "... Posting!"
			else:
				print "ACC::dying... it shouldn't happen"

	def __init__(self, node, password, server, port):
		Agent.PlatformAgent.__init__(self, node, password, server, port)

	def setup(self):
		self.setDefaultBehaviour(self.RouteBehaviour())

"""
class FipperPlatform(threading.Thread):
    def __init__(self, params=dict()):
        threading.Thread.__init__(self)
        self.__params = params
        self.__mts = MTS(params)

        try:
            mtp_list = params["mtps"]
            for mtp in mtp_list:
                self.__mts.addMTP(mtp)
        except KeyError:
            pass

    def getMTS(self):
        return self.__mts

    def run(self):
        pass

class MTS:

    def __init__(self, params=dict()):
        self.__platformagents = dict()

    def addAgent(self, agent):
        aid = agent.getAID()
        self.__platformagents[aid] = agent

    def addMTP(self, mtp):
        pass

    def dispatch(self, msg):
        print "Dispatching msg..."
        envelope = msg.getEnvelope()
        to_list = envelope.getTo()
        #for to in to_list:
	#	print to

        for to in to_list:
            if to in self.__platformagents:
                print "Agend finded! Posting..."
                self.__platformagents[to].postMessage(msg)

class MTP:
    def getName(self):
        raise NotImplemented

    def getSupportedProtocols(self):
        raise NotImplemented

    def activate(self, dispatcher, params):
        raise NotImplemented

    def deactivate(self):
        raise NotImplemented

    def deliver(self, addr, envelope, payload):
        raise NotImplemented

"""

<|endoftext|>


<commit_before>import json

from django.http import HttpResponse
from django.http import HttpResponseBadRequest
from django.views.generic import View

from .models import Webhook
from .utils import verify_webhook
from notification.models import ProductNotification
from product.models import Product
from product.models import Transaction

class ValidateMixin(object):
    def post(self, request, *args, **kwargs):
        # Validate provided UUID
        uuid = self.kwargs.get('uuid')
        try:
            Webhook.objects.get(id=uuid)
        except Webhook.DoesNotExist:
            return HttpResponseBadRequest()

        # Validate received data
        hmac_sha256 = request.META.get('HTTP_X_SHOPIFY_HMAC_SHA256', None)
        if not verify_webhook(request.body, hmac_sha256):
            return HttpResponseBadRequest()

        super(ValidateMixin, self).post(request, *args, **kwargs)

class OrdersPaidView(ValidateMixin, View):
    def post(self, request, *args, **kwargs):
        data = json.loads(request.body)
        for item in data['line_items']:
            ProductNotification.objects.notify_users(item, data)
            Transaction.objects.add_transaction(item['product_id'],
                                                item['price'],
                                                item['quantity'],
                                                order_id=data['id'],
                                                order_name=data['name'],
                                                item_id=item['id'])
        return HttpResponse()

class ProductsCreateView(ValidateMixin, View):
    def post(self, request, *args, **kwargs):
        data = json.loads(request.body)
        Product.objects.create(product_id=data['id'],
                               product_type=data['product_type'],
                               description=data['title'])
        return HttpResponse()

class ProductsUpdateView(ValidateMixin, View):
    def post(self, request, *args, **kwargs):
        data = json.loads(request.body)
        Product.objects.filter(product_id=data['id']).update(product_type=data['product_type'],
                                                             description=data['title'])
        return HttpResponse()

class RefundsCreateView(ValidateMixin, View):
    def post(self, request, *args, **kwargs):
        data = json.loads(request.body)
        for refund in data['refund_line_items']:
            item = refund['line_item']
            Transaction.objects.add_transaction(item['product_id'],
                                                item['price'],
                                                item['quantity'],
                                                credit=False,
                                                order_id=data['order_id'])
        return HttpResponse()
<commit_msg>Include item ID when creating a refund transaction<commit_after>import json

from django.http import HttpResponse
from django.http import HttpResponseBadRequest
from django.views.generic import View

from .models import Webhook
from .utils import verify_webhook
from notification.models import ProductNotification
from product.models import Product
from product.models import Transaction

class ValidateMixin(object):
    def post(self, request, *args, **kwargs):
        # Validate provided UUID
        uuid = self.kwargs.get('uuid')
        try:
            Webhook.objects.get(id=uuid)
        except Webhook.DoesNotExist:
            return HttpResponseBadRequest()

        # Validate received data
        hmac_sha256 = request.META.get('HTTP_X_SHOPIFY_HMAC_SHA256', None)
        if not verify_webhook(request.body, hmac_sha256):
            return HttpResponseBadRequest()

        super(ValidateMixin, self).post(request, *args, **kwargs)

class OrdersPaidView(ValidateMixin, View):
    def post(self, request, *args, **kwargs):
        data = json.loads(request.body)
        for item in data['line_items']:
            ProductNotification.objects.notify_users(item, data)
            Transaction.objects.add_transaction(item['product_id'],
                                                item['price'],
                                                item['quantity'],
                                                order_id=data['id'],
                                                order_name=data['name'],
                                                item_id=item['id'])
        return HttpResponse()

class ProductsCreateView(ValidateMixin, View):
    def post(self, request, *args, **kwargs):
        data = json.loads(request.body)
        Product.objects.create(product_id=data['id'],
                               product_type=data['product_type'],
                               description=data['title'])
        return HttpResponse()

class ProductsUpdateView(ValidateMixin, View):
    def post(self, request, *args, **kwargs):
        data = json.loads(request.body)
        Product.objects.filter(product_id=data['id']).update(product_type=data['product_type'],
                                                             description=data['title'])
        return HttpResponse()

class RefundsCreateView(ValidateMixin, View):
    def post(self, request, *args, **kwargs):
        data = json.loads(request.body)
        for refund in data['refund_line_items']:
            item = refund['line_item']
            Transaction.objects.add_transaction(item['product_id'],
                                                item['price'],
                                                item['quantity'],
                                                credit=False,
                                                order_id=data['order_id'],
                                                item_id=item['id'])
        return HttpResponse()
<|endoftext|>


<commit_before>import ACLMessage
import Behaviour
import Envelope
import MessageReceiver
import SL0Parser
import XMLCodec
import ACLParser
import AID
import BasicFipaDateTime
import DF
import FIPAMessage
import Platform
import Agent
import AMS
import spade_backend
import SpadeConfigParser

<commit_msg>packaging<commit_after>import ACLMessage
import Behaviour
import Envelope
import MessageReceiver
import SL0Parser
import XMLCodec
import ACLParser
import AID
import BasicFipaDateTime
import DF
import FIPAMessage
import Platform
import Agent
import AMS
import spade_backend
import SpadeConfigParser
import stanza_queue
<|endoftext|>


<commit_before>from collections import OrderedDict
import operator
from libpysal import cg
import numpy as np

def compute_length(v0, v1):
    """
    Compute the euclidean distance between two points.

    Parameters
    ----------
    v0:         sequence in the form x, y

    vq:         sequence in the form x, y

    Returns
    --------
    Euclidean distance
    """

    return np.sqrt((v0[0] - v1[0])**2 + (v0[1] - v1[1])**2)

def get_neighbor_distances(ntw, v0, l):
    edges = ntw.enum_links_node(v0)
    neighbors = {}
    for e in edges:
        if e[0] != v0:
            neighbors[e[0]] = l[e]
        else:
            neighbors[e[1]] = l[e]
    return neighbors

def generatetree(pred):
    tree = {}
    for i, p in enumerate(pred):
        if p == -1:
            #root node
            tree[i] = [i]
            continue
        idx = p
        path = [idx]
        while idx >= 0:
            nextnode = pred[idx]
            idx = nextnode
            if idx >= 0:
                path.append(nextnode)
        tree[i] = path
    return tree

def dijkstra(ntw, cost, node, n=float('inf')):
    """
    Compute the shortest path between a start node and all other nodes in the web.

    Parameters
    ----------
    ntw:        object
                PySAL network object

    cost:       dict
                key:    tuple
                        (start node, end node)
                value:  float
                        Cost per edge to travel, e.g. distance

    node:       int
                Start node ID

    n:          float('inf')
                integer break point to stop iteration and return n neighbors

    Returns
    -------
    distance:   list
                List of distances from node to all other nodes.

    pred:       list
                List of preceeding nodes for traversal route.
    """

    v0 = node
    distance = [float('inf') for x in ntw.node_list]
    idx = ntw.node_list.index(v0)
    distance[ntw.node_list.index(v0)] = 0
    pred = [-1 for x in ntw.node_list]
    a = set()
    a.add(v0)
    while len(a) > 0:
        # Get node with the lowest value from distance.
        dist = float('inf')
        for node in a:
            if distance[node] < dist:
                dist = distance[node]
                v = node
        # Remove that node from the set.
        a.remove(v)
        last = v
        #4. Get the neighbors to the current node.
        neighbors = get_neighbor_distances(ntw, v, cost)
        for v1, indiv_cost in neighbors.items():
            if distance[v1] > distance[v] + indiv_cost:
                distance[v1] = distance[v] + indiv_cost
                pred[v1] = v
                a.add(v1)
    return distance, np.array(pred, dtype=np.int)

def dijkstra_mp(ntw_cost_node):
    """
    Compute the shortest path between a start node and all other nodes in the web
    utilizing multiple cores upon request.

    Parameters
    ----------
    ntw_cost_node   tuple
                    tuple of arguments to pass into dijkstra
                        ntw:    object
                                PySAL network object
                        cost:   dict
                                key:    tuple
                                        (start node, end node)
                                value:  float
                                        Cost per edge to travel, e.g. distance
                        node:   int
                                Start node ID
    Returns
    -------
    distance:   list
                List of distances from node to all other nodes.
    pred:       list
                List of preceeding nodes for traversal route.
    """
    ntw, cost, node = ntw_cost_node
    return dijkstra(ntw, cost, node)

def squaredDistancePointSegment(point, segment):
    """Find the squared distance between a point and a segment

    Parameters
    ---------
    point:      tuple
                (x,y)

    segment:    list
                List of 2 tuples [(x0,y0), (x1,y1)]

    Returns
    -------
    tuple:      2 elements:
                    1. distance squared between point and segment
                    2. array(xb, yb): the nearest point on the segment
    """
    p0,p1 = [np.array(p) for p in segment]
    v = p1 - p0
    p = np.array(point)
    w = p - p0
    c1 = np.dot(w,v)
    if c1 <= 0.:
        # Print 'before p0'
        return np.dot(w.T,w), p0
    c2 = np.dot(v,v)
    if c2 <= c1:
        dp1 = p - p1
        # Print 'after p1'
        return np.dot(dp1.T,dp1), p1

    b = c1 / c2
    bv = np.dot(b,v)
    pb = p0 + bv
    d2 = p - pb

    return np.dot(d2,d2), pb

def snapPointsOnSegments(points, segments):
    """Place points onto closet segment in a set of segments

    Arguments
    ---------
    points:     dict
                Point id as key and (x,y) coordinate as value

    segments:   list
                Elements are of type pysal.cg.shapes.Chain
                ** Note **
                        each element is a segment represented as a chain with
                        *one head and one tail node*, in other words one link only.

    Returns
    -------
    p2s:        dict
                key:    point id (see points in arguments)

                value:  a 2-tuple: ((head, tail), point)
                        where (head, tail) is the target segment, and point is the snapped
                        location on the segment
    """

    # Put segments in an Rtree.
    rt = cg.Rtree()
    SMALL = 0.01
    node2segs = {}

    for segment in segments:
        head,tail = segment.vertices
        x0,y0 = head
        x1,y1 = tail
        if (x0,y0) not in node2segs:
            node2segs[(x0,y0)] = []
        if (x1,y1) not in node2segs:
            node2segs[(x1,y1)] = []
        node2segs[(x0,y0)].append(segment)
        node2segs[(x1,y1)].append(segment)
        x0,y0,x1,y1 =  segment.bounding_box
        x0 -= SMALL
        y0 -= SMALL
        x1 += SMALL
        y1 += SMALL
        r = cg.Rect(x0,y0,x1,y1)
        rt.insert(segment, r)

    # Build a KDtree on segment nodes.
    kt = cg.KDTree(list(node2segs.keys()))
    p2s = {}

    for ptIdx, point in points.items():
        # First, find nearest neighbor segment node for the point.
        dmin, node = kt.query(point, k=1)
        node = tuple(kt.data[node])
        closest = node2segs[node][0].vertices

        # Use this segment as the candidate closest segment:  closest
        # Use the distance as the distance to beat:           dmin
        p2s[ptIdx] = (closest, node) # sna
        x0 = point[0] - dmin
        y0 = point[1] - dmin
        x1 = point[0] + dmin
        y1 = point[1] + dmin

        # Find all segments with bounding boxes that intersect
        # a query rectangle centered on the point with sides of length 2*dmin.
        candidates = [ cand for cand in rt.intersection([x0,y0,x1,y1])]
        dmin += SMALL
        dmin2 = dmin * dmin

        # Of the candidate segments, find the nearest to the query point.
        for candidate in candidates:
            dnc, p2b = squaredDistancePointSegment(point, candidate.vertices)
            if dnc <= dmin2:
                closest = candidate.vertices
                dmin2 = dnc
                p2s[ptIdx] = (closest, p2b)

    return p2s
<commit_msg>updated util.py with autopep8<commit_after>from collections import OrderedDict
import operator
from libpysal import cg
import numpy as np

def compute_length(v0, v1):
    """
    Compute the euclidean distance between two points.

    Parameters
    ----------
    v0:         sequence in the form x, y

    vq:         sequence in the form x, y

    Returns
    --------
    Euclidean distance
    """
    return np.sqrt((v0[0] - v1[0])**2 + (v0[1] - v1[1])**2)

def get_neighbor_distances(ntw, v0, l):
    """
    """
    edges = ntw.enum_links_node(v0)
    neighbors = {}
    for e in edges:
        if e[0] != v0:
            neighbors[e[0]] = l[e]
        else:
            neighbors[e[1]] = l[e]
    return neighbors

def generatetree(pred):
    """
    """
    tree = {}
    for i, p in enumerate(pred):
        if p == -1:
            # root node
            tree[i] = [i]
            continue
        idx = p
        path = [idx]
        while idx >= 0:
            nextnode = pred[idx]
            idx = nextnode
            if idx >= 0:
                path.append(nextnode)
        tree[i] = path
    return tree

def dijkstra(ntw, cost, node, n=float('inf')):
    """
    Compute the shortest path between a start
    node and all other nodes in the web.

    Parameters
    ----------
    ntw:        object
                PySAL network object

    cost:       dict
                key:    tuple
                        (start node, end node)
                value:  float
                        Cost per edge to travel, e.g. distance

    node:       int
                Start node ID

    n:          float('inf')
                integer break point to stop iteration and return n neighbors

    Returns
    -------
    distance:   list
                List of distances from node to all other nodes.

    pred:       list
                List of preceeding nodes for traversal route.
    """

    v0 = node
    distance = [float('inf') for x in ntw.node_list]
    idx = ntw.node_list.index(v0)
    distance[ntw.node_list.index(v0)] = 0
    pred = [-1 for x in ntw.node_list]
    a = set()
    a.add(v0)
    while len(a) > 0:
        # Get node with the lowest value from distance.
        dist = float('inf')
        for node in a:
            if distance[node] < dist:
                dist = distance[node]
                v = node
        # Remove that node from the set.
        a.remove(v)
        last = v
        # 4. Get the neighbors to the current node.
        neighbors = get_neighbor_distances(ntw, v, cost)
        for v1, indiv_cost in neighbors.items():
            if distance[v1] > distance[v] + indiv_cost:
                distance[v1] = distance[v] + indiv_cost
                pred[v1] = v
                a.add(v1)
    return distance, np.array(pred, dtype=np.int)

def dijkstra_mp(ntw_cost_node):
    """
    Compute the shortest path between a start node and all other
    nodes in the web utilizing multiple cores upon request.

    Parameters
    ----------
    ntw_cost_node   tuple
                    tuple of arguments to pass into dijkstra
                        ntw:    object
                                PySAL network object
                        cost:   dict
                                key:    tuple
                                        (start node, end node)
                                value:  float
                                        Cost per edge to travel, e.g. distance
                        node:   int
                                Start node ID
    Returns
    -------
    distance:   list
                List of distances from node to all other nodes.
    pred:       list
                List of preceeding nodes for traversal route.
    """
    ntw, cost, node = ntw_cost_node
    return dijkstra(ntw, cost, node)

def squaredDistancePointSegment(point, segment):
    """Find the squared distance between a point and a segment

    Parameters
    ---------
    point:      tuple
                (x,y)

    segment:    list
                List of 2 tuples [(x0,y0), (x1,y1)]

    Returns
    -------
    tuple:      2 elements:
                    1. distance squared between point and segment
                    2. array(xb, yb): the nearest point on the segment
    """
    p0, p1 = [np.array(p) for p in segment]
    v = p1 - p0
    p = np.array(point)
    w = p - p0
    c1 = np.dot(w, v)
    if c1 <= 0.:
        # Print 'before p0'
        return np.dot(w.T, w), p0
    c2 = np.dot(v, v)
    if c2 <= c1:
        dp1 = p - p1
        # Print 'after p1'
        return np.dot(dp1.T, dp1), p1

    b = c1 / c2
    bv = np.dot(b, v)
    pb = p0 + bv
    d2 = p - pb

    return np.dot(d2, d2), pb

def snapPointsOnSegments(points, segments):
    """Place points onto closet segment in a set of segments

    Arguments
    ---------
    points:     dict
                Point id as key and (x,y) coordinate as value

    segments:   list
                Elements are of type pysal.cg.shapes.Chain
                ** Note **
                        each element is a segment represented as a chain with
                        *one head and one tail node*
                        in other words one link only.

    Returns
    -------
    p2s:        dict
                key:    point id (see points in arguments)

                value:  a 2-tuple: ((head, tail), point)
                        where (head, tail) is the target segment,
                        and point is the snapped location on the segment
    """

    # Put segments in an Rtree.
    rt = cg.Rtree()
    SMALL = 0.01
    node2segs = {}

    for segment in segments:
        head, tail = segment.vertices
        x0, y0 = head
        x1, y1 = tail
        if (x0, y0) not in node2segs:
            node2segs[(x0, y0)] = []
        if (x1, y1) not in node2segs:
            node2segs[(x1, y1)] = []
        node2segs[(x0, y0)].append(segment)
        node2segs[(x1, y1)].append(segment)
        x0, y0, x1, y1 = segment.bounding_box
        x0 -= SMALL
        y0 -= SMALL
        x1 += SMALL
        y1 += SMALL
        r = cg.Rect(x0, y0, x1, y1)
        rt.insert(segment, r)

    # Build a KDtree on segment nodes.
    kt = cg.KDTree(list(node2segs.keys()))
    p2s = {}

    for ptIdx, point in points.items():
        # First, find nearest neighbor segment node for the point.
        dmin, node = kt.query(point, k=1)
        node = tuple(kt.data[node])
        closest = node2segs[node][0].vertices

        # Use this segment as the candidate closest segment:  closest
        # Use the distance as the distance to beat:           dmin
        p2s[ptIdx] = (closest, node)  # sna
        x0 = point[0] - dmin
        y0 = point[1] - dmin
        x1 = point[0] + dmin
        y1 = point[1] + dmin

        # Find all segments with bounding boxes that intersect
        # a query rectangle centered on the point with sides of length 2*dmin.
        candidates = [cand for cand in rt.intersection([x0, y0, x1, y1])]
        dmin += SMALL
        dmin2 = dmin * dmin

        # Of the candidate segments, find the nearest to the query point.
        for candidate in candidates:
            dnc, p2b = squaredDistancePointSegment(point, candidate.vertices)
            if dnc <= dmin2:
                closest = candidate.vertices
                dmin2 = dnc
                p2s[ptIdx] = (closest, p2b)

    return p2s
<|endoftext|>


<commit_before># Copyright (C) 2004 Anthony Baxter

# A special audio device. It merely echoes back what you send it.

from converters import MediaLayer

opened = None

class EchoAudioDevice:

    def __init__(self):
        self._data = ''

    def _push_up_some_data(self):
        sample, self._data = self._data[-320:], ''
        if self.encoder and self._data:
            self.encoder.handle_audio(self._data)

    def write(self, bytes):
        self._data += bytes

    def _close(self):
        self._data = ''
        try:
            self.LC.stop()
        except AttributeError:
            # workaround for twisted bug
            pass

    def openDev(self):
        from twisted.internet.task import LoopingCall
        self.LC = LoopingCall(self._push_up_some_data)
        self.LC.start(0.020)
        self._data = ''

Device = EchoAudioDevice
<commit_msg>woops. echoaudio didn't inherit from baseaudio.AudioDevice (caught by: Stefan Alfredsson)<commit_after># Copyright (C) 2004 Anthony Baxter

# A special audio device. It merely echoes back what you send it.

from converters import MediaLayer
import baseaudio

opened = None

class EchoAudioDevice(baseaudio.AudioDevice):

    def __init__(self):
        self._data = ''

    def _push_up_some_data(self):
        sample, self._data = self._data[-320:], ''
        if self.encoder and self._data:
            self.encoder.handle_audio(self._data)

    def write(self, bytes):
        self._data += bytes

    def _close(self):
        self._data = ''
        try:
            self.LC.stop()
        except AttributeError:
            # workaround for twisted bug
            pass

    def openDev(self):
        from twisted.internet.task import LoopingCall
        self.LC = LoopingCall(self._push_up_some_data)
        self.LC.start(0.020)
        self._data = ''

Device = EchoAudioDevice
<|endoftext|>


<commit_before>import uuid
import random
import collections

import numpy
from numpy.testing import assert_equal

from simphony.core.keywords import KEYWORDS
from simphony.core.data_container import DataContainer
from simphony.core.cuba import CUBA
from simphony.cuds.particles import Particle, Bond
from simphony.cuds.mesh import Point, Edge, Face, Cell

def compare_particles_datasets(particles, reference, msg=None, testcase=None):
    self = testcase
    self.assertEqual(particles.name, reference.name)
    for b, r in zip(particles.iter_bonds(), reference.iter_bonds()):
        compare_bonds(b, r, testcase=self)
    for p, r in zip(particles.iter_particles(), reference.iter_particles()):
        compare_particles(p, r, testcase=self)
    compare_data_containers(particles.data, reference.data, testcase=self)

def compare_mesh_datasets(mesh, reference, msg=None, testcase=None):
    self = testcase
    self.assertEqual(mesh.name, reference.name)
    for p, r in zip(mesh.iter_points(), reference.iter_points()):
        compare_points(p, r, testcase=self)
    for e, r in zip(mesh.iter_edges(), reference.iter_edges()):
        compare_elements(e, r, testcase=self)
    for f, r in zip(mesh.iter_faces(), reference.iter_faces()):
        compare_elements(f, r, testcase=self)
    for c, r in zip(mesh.iter_cells(), reference.iter_cells()):
        compare_elements(c, r, testcase=self)
    compare_data_containers(mesh.data, reference.data, testcase=self)

def compare_lattice_datasets(lattice, reference, msg=None, testcase=None):
    self = testcase
    self.assertEqual(lattice.name, reference.name)
    for l, r in zip(lattice.iter_nodes(), reference.iter_nodes()):
        compare_lattice_nodes(l, r, testcase=self)
    compare_data_containers(lattice.data, reference.data, testcase=self)
    self.assertEqual(lattice.type, reference.type)
    numpy.testing.assert_array_equal(lattice.base_vect, reference.base_vect)
    self.assertEqual(lattice.size, reference.size)
    numpy.testing.assert_array_equal(lattice.origin, reference.origin)

def compare_bonds(bond, reference, msg=None, testcase=None):
    self = testcase
    self.assertEqual(bond.uid, reference.uid)
    self.assertEqual(bond.particles, reference.particles)
    compare_data_containers(bond.data, reference.data, testcase=self)

def compare_particles(particle, reference, msg=None, testcase=None):
    self = testcase
    self.assertEqual(particle.uid, reference.uid)
    self.assertEqual(particle.coordinates, reference.coordinates)
    compare_data_containers(particle.data, reference.data, testcase=self)

def compare_points(point, reference, msg=None, testcase=None):
    self = testcase
    self.assertEqual(point.uid, reference.uid)
    self.assertEqual(point.coordinates, reference.coordinates)
    compare_data_containers(point.data, reference.data, testcase=self)

def compare_elements(element, reference, msg=None, testcase=None):
    self = testcase
    self.assertEqual(element.uid, reference.uid)
    points = collections.deque(reference.points)
    for _ in range(len(points)):
        points.rotate(1)
        try:
            self.assertSequenceEqual(element.points, points)
        except AssertionError:
            continue
        else:
            break
    else:
        message = 'Point uid sequences are not equivalent: {} !~ {}'
        raise AssertionError(message.format(element.points, reference.points))

    compare_data_containers(element.data, reference.data, testcase=self)

def compare_lattice_nodes(node, reference, msg=None, testcase=None):
    self = testcase
    self.assertEqual(node.index, reference.index)
    compare_data_containers(node.data, reference.data, testcase=self)

def compare_data_containers(data, reference, msg=None, testcase=None):
    self = testcase
    self.assertEqual(set(data), set(reference))
    for key in data:
        self.assertIn(key, reference)
        self.assertIsInstance(key, CUBA)
        message = "Values for {} are not equal\n ACTUAL: {}\n DESIRED: {}"
        assert_equal(
            data[key], reference[key],
            err_msg=message.format(key.name, data[key], reference[key]),
            verbose=False)

def create_particles(n=10, restrict=None):
    particle_list = []
    for i in xrange(n):
        data = create_data_container(restrict=restrict, constant=i)
        particle_list.append(
            Particle([i, i*10, i*100], data=data))
    return particle_list

def create_particles_with_id(n=10, restrict=None):
    particle_list = []
    for i in xrange(n):
        data = create_data_container(restrict=restrict)
        uid = uuid.uuid4()
        particle_list.append(
            Particle(uid=uid,
                     coordinates=[i, i*10, i*100],
                     data=data))
    return particle_list

def create_points(n=10, restrict=None):
    point_list = []
    for i in xrange(n):
        data = create_data_container(restrict=restrict, constant=i)
        point_list.append(
            Point(uid=None,
                  coordinates=[i, i*10, i*100],
                  data=data))
    return point_list

def create_points_with_id(n=10, restrict=None):
    point_list = []
    for i in xrange(n):
        data = create_data_container(restrict=restrict)
        uid = uuid.uuid4()
        point_list.append(
            Point(uid=uid,
                  coordinates=[i, i*10, i*100],
                  data=data))
    return point_list

def create_bonds(n=5, restrict=None, particles=None):
    bond_list = []
    for i in xrange(n):
        data = create_data_container(restrict=restrict, constant=i)
        if particles is None:
            ids = [uuid.uuid4() for x in xrange(n)]
        else:
            uids = [particle.uid for particle in particles]
            ids = random.sample(uids, n)
        bond_list.append(Bond(particles=ids, data=data))
    return bond_list

def create_bonds_with_id(n=5, restrict=None, particles=None):
    bond_list = []
    for i in xrange(n):
        data = create_data_container(restrict=restrict)
        uid = uuid.uuid4()
        if particles is None:
            ids = [uuid.uuid4() for x in xrange(n)]
        else:
            uids = [particle.uid for particle in particles]
            ids = random.sample(uids, n)
        bond_list.append(Bond(uid=uid, particles=ids, data=data))
    return bond_list

def create_edges(n=5, restrict=None, points=None):
    edge_list = []
    for i in xrange(n):
        data = create_data_container(restrict=restrict, constant=i)
        if points is None:
            ids = [uuid.uuid4() for x in xrange(2)]
        else:
            uids = [point.uid for point in points]
            ids = random.sample(uids, 2)
        edge_list.append(
            Edge(uid=None,
                 points=ids,
                 data=data))
    return edge_list

def create_edges_with_id(n=5, restrict=None, points=None):
    edge_list = []
    for i in xrange(n):
        data = create_data_container(restrict=restrict, constant=i)
        uid = uuid.uuid4()
        if points is None:
            ids = [uuid.uuid4() for x in xrange(2)]
        else:
            uids = [point.uid for point in points]
            ids = random.sample(uids, 2)
        edge_list.append(
            Edge(uid=uid,
                 points=ids,
                 data=data))
    return edge_list

def create_faces(n=5, restrict=None, points=None):
    face_list = []
    for i in xrange(n):
        data = create_data_container(restrict=restrict, constant=i)
        if points is None:
            ids = [uuid.uuid4() for x in xrange(3)]
        else:
            uids = [point.uid for point in points]
            ids = random.sample(uids, 3)
        face_list.append(
            Face(uid=None,
                 points=ids,
                 data=data))
    return face_list

def create_faces_with_id(n=5, restrict=None, points=None):
    face_list = []
    for i in xrange(n):
        data = create_data_container(restrict=restrict, constant=i)
        uid = uuid.uuid4()
        if points is None:
            ids = [uuid.uuid4() for x in xrange(3)]
        else:
            uids = [point.uid for point in points]
            ids = random.sample(uids, 3)
        face_list.append(
            Face(uid=uid,
                 points=ids,
                 data=data))
    return face_list

def create_cells(n=5, restrict=None, points=None):
    cell_list = []
    for i in xrange(n):
        data = create_data_container(restrict=restrict, constant=i)
        if points is None:
            ids = [uuid.uuid4() for x in xrange(4)]
        else:
            uids = [point.uid for point in points]
            ids = random.sample(uids, 4)
        cell_list.append(
            Cell(uid=None,
                 points=ids,
                 data=data))
    return cell_list

def create_cells_with_id(n=5, restrict=None, points=None):
    cell_list = []
    for i in xrange(n):
        data = create_data_container(restrict=restrict, constant=i)
        uid = uuid.uuid4()
        if points is None:
            ids = [uuid.uuid4() for x in xrange(4)]
        else:
            uids = [point.uid for point in points]
            ids = random.sample(uids, 4)
        cell_list.append(
            Cell(uid=uid,
                 points=ids,
                 data=data))
    return cell_list

def create_data_container(restrict=None, constant=None):
    """ Create a dummy data container while respecting the expected data types.

    This is a utility function to be used for testing and prototyping.

    Parameters
    ----------
    restrict : list
        The list of CUBA keys to restrict the value population. Default is to
        use all CUBA keys.

    constant : int
        A numerical constant to create the dummy value. Default is None.

    Returns
    -------
    data : DataContainer

    """
    if restrict is None:
        restrict = CUBA
    data = {cuba: dummy_cuba_value(cuba, constant) for cuba in restrict}
    return DataContainer(data)

def dummy_cuba_value(cuba, constant=None):
    """ Create a dummy value for the CUBA keyword.

    Parameters
    ----------
    cuba : CUBA
        The cuba key to get a dummy value back

    constant : int
        A numerical constant to create the dummy value. Default is 3.

    Returns
    -------
    value :
        A dummy value following the dtype description of the CUBA keyword.

    """
    if constant is None:
        constant = 3
    keyword = KEYWORDS[CUBA(cuba).name]
    if numpy.issubdtype(keyword.dtype, str):
        return keyword.name + str(constant)
    else:
        shape = keyword.shape
        if shape == [1]:
            if numpy.issubdtype(keyword.dtype, 'float'):
                return float(cuba + constant)
            if numpy.issubdtype(keyword.dtype, 'int'):
                return int(cuba + constant)
        else:
            data = numpy.arange(numpy.prod(shape)) * (cuba + constant)
            data = numpy.reshape(data, shape)
            if numpy.issubdtype(keyword.dtype, 'float'):
                return numpy.ones(shape=shape, dtype=numpy.float64) * data
            if numpy.issubdtype(keyword.dtype, 'int'):
                return numpy.ones(shape=shape, dtype=numpy.int32) * data

    raise RuntimeError(
        'cannot create value for {}'.format(keyword.dtype))

def grouper(iterable, n):
    """ Collect data into fixed-length chunks or blocks

    .. note::

       If the iterable is exhausted before a valid chuck is collected
       then the last chuck is ignored and the iteration ends.

    """
    iterator = iter(iterable)
    while True:
        yield [next(iterator) for _ in range(n)]
<commit_msg>Removed msg from compare_dataset functions<commit_after>import uuid
import random
import collections

import numpy
from numpy.testing import assert_equal

from simphony.core.keywords import KEYWORDS
from simphony.core.data_container import DataContainer
from simphony.core.cuba import CUBA
from simphony.cuds.particles import Particle, Bond
from simphony.cuds.mesh import Point, Edge, Face, Cell

def compare_particles_datasets(particles, reference, testcase=None):
    self = testcase
    self.assertEqual(particles.name, reference.name)
    for b, r in zip(particles.iter_bonds(), reference.iter_bonds()):
        compare_bonds(b, r, testcase=self)
    for p, r in zip(particles.iter_particles(), reference.iter_particles()):
        compare_particles(p, r, testcase=self)
    compare_data_containers(particles.data, reference.data, testcase=self)

def compare_mesh_datasets(mesh, reference, testcase=None):
    self = testcase
    self.assertEqual(mesh.name, reference.name)
    for p, r in zip(mesh.iter_points(), reference.iter_points()):
        compare_points(p, r, testcase=self)
    for e, r in zip(mesh.iter_edges(), reference.iter_edges()):
        compare_elements(e, r, testcase=self)
    for f, r in zip(mesh.iter_faces(), reference.iter_faces()):
        compare_elements(f, r, testcase=self)
    for c, r in zip(mesh.iter_cells(), reference.iter_cells()):
        compare_elements(c, r, testcase=self)
    compare_data_containers(mesh.data, reference.data, testcase=self)

def compare_lattice_datasets(lattice, reference, testcase=None):
    self = testcase
    self.assertEqual(lattice.name, reference.name)
    for l, r in zip(lattice.iter_nodes(), reference.iter_nodes()):
        compare_lattice_nodes(l, r, testcase=self)
    compare_data_containers(lattice.data, reference.data, testcase=self)
    self.assertEqual(lattice.type, reference.type)
    numpy.testing.assert_array_equal(lattice.base_vect, reference.base_vect)
    self.assertEqual(lattice.size, reference.size)
    numpy.testing.assert_array_equal(lattice.origin, reference.origin)

def compare_bonds(bond, reference, msg=None, testcase=None):
    self = testcase
    self.assertEqual(bond.uid, reference.uid)
    self.assertEqual(bond.particles, reference.particles)
    compare_data_containers(bond.data, reference.data, testcase=self)

def compare_particles(particle, reference, msg=None, testcase=None):
    self = testcase
    self.assertEqual(particle.uid, reference.uid)
    self.assertEqual(particle.coordinates, reference.coordinates)
    compare_data_containers(particle.data, reference.data, testcase=self)

def compare_points(point, reference, msg=None, testcase=None):
    self = testcase
    self.assertEqual(point.uid, reference.uid)
    self.assertEqual(point.coordinates, reference.coordinates)
    compare_data_containers(point.data, reference.data, testcase=self)

def compare_elements(element, reference, msg=None, testcase=None):
    self = testcase
    self.assertEqual(element.uid, reference.uid)
    points = collections.deque(reference.points)
    for _ in range(len(points)):
        points.rotate(1)
        try:
            self.assertSequenceEqual(element.points, points)
        except AssertionError:
            continue
        else:
            break
    else:
        message = 'Point uid sequences are not equivalent: {} !~ {}'
        raise AssertionError(message.format(element.points, reference.points))

    compare_data_containers(element.data, reference.data, testcase=self)

def compare_lattice_nodes(node, reference, msg=None, testcase=None):
    self = testcase
    self.assertEqual(node.index, reference.index)
    compare_data_containers(node.data, reference.data, testcase=self)

def compare_data_containers(data, reference, msg=None, testcase=None):
    self = testcase
    self.assertEqual(set(data), set(reference))
    for key in data:
        self.assertIn(key, reference)
        self.assertIsInstance(key, CUBA)
        message = "Values for {} are not equal\n ACTUAL: {}\n DESIRED: {}"
        assert_equal(
            data[key], reference[key],
            err_msg=message.format(key.name, data[key], reference[key]),
            verbose=False)

def create_particles(n=10, restrict=None):
    particle_list = []
    for i in xrange(n):
        data = create_data_container(restrict=restrict, constant=i)
        particle_list.append(
            Particle([i, i*10, i*100], data=data))
    return particle_list

def create_particles_with_id(n=10, restrict=None):
    particle_list = []
    for i in xrange(n):
        data = create_data_container(restrict=restrict)
        uid = uuid.uuid4()
        particle_list.append(
            Particle(uid=uid,
                     coordinates=[i, i*10, i*100],
                     data=data))
    return particle_list

def create_points(n=10, restrict=None):
    point_list = []
    for i in xrange(n):
        data = create_data_container(restrict=restrict, constant=i)
        point_list.append(
            Point(uid=None,
                  coordinates=[i, i*10, i*100],
                  data=data))
    return point_list

def create_points_with_id(n=10, restrict=None):
    point_list = []
    for i in xrange(n):
        data = create_data_container(restrict=restrict)
        uid = uuid.uuid4()
        point_list.append(
            Point(uid=uid,
                  coordinates=[i, i*10, i*100],
                  data=data))
    return point_list

def create_bonds(n=5, restrict=None, particles=None):
    bond_list = []
    for i in xrange(n):
        data = create_data_container(restrict=restrict, constant=i)
        if particles is None:
            ids = [uuid.uuid4() for x in xrange(n)]
        else:
            uids = [particle.uid for particle in particles]
            ids = random.sample(uids, n)
        bond_list.append(Bond(particles=ids, data=data))
    return bond_list

def create_bonds_with_id(n=5, restrict=None, particles=None):
    bond_list = []
    for i in xrange(n):
        data = create_data_container(restrict=restrict)
        uid = uuid.uuid4()
        if particles is None:
            ids = [uuid.uuid4() for x in xrange(n)]
        else:
            uids = [particle.uid for particle in particles]
            ids = random.sample(uids, n)
        bond_list.append(Bond(uid=uid, particles=ids, data=data))
    return bond_list

def create_edges(n=5, restrict=None, points=None):
    edge_list = []
    for i in xrange(n):
        data = create_data_container(restrict=restrict, constant=i)
        if points is None:
            ids = [uuid.uuid4() for x in xrange(2)]
        else:
            uids = [point.uid for point in points]
            ids = random.sample(uids, 2)
        edge_list.append(
            Edge(uid=None,
                 points=ids,
                 data=data))
    return edge_list

def create_edges_with_id(n=5, restrict=None, points=None):
    edge_list = []
    for i in xrange(n):
        data = create_data_container(restrict=restrict, constant=i)
        uid = uuid.uuid4()
        if points is None:
            ids = [uuid.uuid4() for x in xrange(2)]
        else:
            uids = [point.uid for point in points]
            ids = random.sample(uids, 2)
        edge_list.append(
            Edge(uid=uid,
                 points=ids,
                 data=data))
    return edge_list

def create_faces(n=5, restrict=None, points=None):
    face_list = []
    for i in xrange(n):
        data = create_data_container(restrict=restrict, constant=i)
        if points is None:
            ids = [uuid.uuid4() for x in xrange(3)]
        else:
            uids = [point.uid for point in points]
            ids = random.sample(uids, 3)
        face_list.append(
            Face(uid=None,
                 points=ids,
                 data=data))
    return face_list

def create_faces_with_id(n=5, restrict=None, points=None):
    face_list = []
    for i in xrange(n):
        data = create_data_container(restrict=restrict, constant=i)
        uid = uuid.uuid4()
        if points is None:
            ids = [uuid.uuid4() for x in xrange(3)]
        else:
            uids = [point.uid for point in points]
            ids = random.sample(uids, 3)
        face_list.append(
            Face(uid=uid,
                 points=ids,
                 data=data))
    return face_list

def create_cells(n=5, restrict=None, points=None):
    cell_list = []
    for i in xrange(n):
        data = create_data_container(restrict=restrict, constant=i)
        if points is None:
            ids = [uuid.uuid4() for x in xrange(4)]
        else:
            uids = [point.uid for point in points]
            ids = random.sample(uids, 4)
        cell_list.append(
            Cell(uid=None,
                 points=ids,
                 data=data))
    return cell_list

def create_cells_with_id(n=5, restrict=None, points=None):
    cell_list = []
    for i in xrange(n):
        data = create_data_container(restrict=restrict, constant=i)
        uid = uuid.uuid4()
        if points is None:
            ids = [uuid.uuid4() for x in xrange(4)]
        else:
            uids = [point.uid for point in points]
            ids = random.sample(uids, 4)
        cell_list.append(
            Cell(uid=uid,
                 points=ids,
                 data=data))
    return cell_list

def create_data_container(restrict=None, constant=None):
    """ Create a dummy data container while respecting the expected data types.

    This is a utility function to be used for testing and prototyping.

    Parameters
    ----------
    restrict : list
        The list of CUBA keys to restrict the value population. Default is to
        use all CUBA keys.

    constant : int
        A numerical constant to create the dummy value. Default is None.

    Returns
    -------
    data : DataContainer

    """
    if restrict is None:
        restrict = CUBA
    data = {cuba: dummy_cuba_value(cuba, constant) for cuba in restrict}
    return DataContainer(data)

def dummy_cuba_value(cuba, constant=None):
    """ Create a dummy value for the CUBA keyword.

    Parameters
    ----------
    cuba : CUBA
        The cuba key to get a dummy value back

    constant : int
        A numerical constant to create the dummy value. Default is 3.

    Returns
    -------
    value :
        A dummy value following the dtype description of the CUBA keyword.

    """
    if constant is None:
        constant = 3
    keyword = KEYWORDS[CUBA(cuba).name]
    if numpy.issubdtype(keyword.dtype, str):
        return keyword.name + str(constant)
    else:
        shape = keyword.shape
        if shape == [1]:
            if numpy.issubdtype(keyword.dtype, 'float'):
                return float(cuba + constant)
            if numpy.issubdtype(keyword.dtype, 'int'):
                return int(cuba + constant)
        else:
            data = numpy.arange(numpy.prod(shape)) * (cuba + constant)
            data = numpy.reshape(data, shape)
            if numpy.issubdtype(keyword.dtype, 'float'):
                return numpy.ones(shape=shape, dtype=numpy.float64) * data
            if numpy.issubdtype(keyword.dtype, 'int'):
                return numpy.ones(shape=shape, dtype=numpy.int32) * data

    raise RuntimeError(
        'cannot create value for {}'.format(keyword.dtype))

def grouper(iterable, n):
    """ Collect data into fixed-length chunks or blocks

    .. note::

       If the iterable is exhausted before a valid chuck is collected
       then the last chuck is ignored and the iteration ends.

    """
    iterator = iter(iterable)
    while True:
        yield [next(iterator) for _ in range(n)]
<|endoftext|>