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

import rospy
import actionlib

from vigir_synthesis_msgs.msg import *

import ltl_compilation_client
import ltl_synthesis_client
import sm_generate_client

class BehaviorSynthesisActionServer(object):
    '''ROS Action server that handles the following processes:

    * LTL Specification Compilation
    * LTL Synthesis (resulting in an automaton)
    * State Machine Generation/Instantiation

    Depending on the synthesis request's options, all
    or a subset of the above step will be carried out.
    '''

    # Messages that are used to publish feedback/result
    _feedback = BehaviorSynthesisFeedback()
    _result   = BehaviorSynthesisResult()

    def __init__(self, name):
        self._action_name = name
        self._as = actionlib.SimpleActionServer(self._action_name,
                                                BehaviorSynthesisAction,
                                                execute_cb = self.execute_cb,
                                                auto_start = False)
        self._as.start()

    def execute_cb(self, goal):
        '''The code to be executed when a BehaviorSynthesisActionGoal is received.'''

        r = rospy.Rate(1)   # FIX: What should this be?
        success = True      # start optimistically

        # Acknowledge goal reception
        self.set_and_publish_feedback("Received behavior synthesis request.")

        # Examine the goal message
        synthesis_goal = goal.request
        synthesis_options = goal.synthesis_options

        #TODO: receive a callback when a preempt request is received
        if self._as.is_preempt_requested():
            rospy.loginfo('%s: Preempted' % self._action_name)
            self._as.set_preempted()
            success = False

        if success:
            # Request LTL Specification Compilation from the corresponding server
            # and also update and publish the appropriate feedback
            ltl_spec, error_code_value, success = self.handle_ltl_specification_request(synthesis_goal)

        if success:
            # Request LTL Synthesis from the corresponding server
            # and also update and publish the appropriate feedback
            automaton, error_code_value, success = self.handle_ltl_synthesis_request(ltl_spec)

        if success:
            # Request State Machine Generation from the corresponding server
            # and also update and publish the appropriate feedback
            # TODO: how to get the the yaml_config file?
            sm, error_code_value, success = self.handle_sm_generation_request(automaton, synthesis_goal.system)

        if success:
            self._result.error_code = BSErrorCodes(BSErrorCodes.SUCCESS)
            self._result.states = sm
            rospy.loginfo('%s: Succeeded' % self._action_name)
            self._as.set_succeeded(self._result)
        else:
            self._result.error_code = BSErrorCodes(error_code_value)
            rospy.logerr('%s: Failed' % self._action_name)
            self._as.set_aborted(self._result)

    def handle_ltl_specification_request(self, synthesis_goal):
        '''
        Makes a LTL Specification Compilation request
        to the corresponding service and handles the response.

        synthesis_goal: BehaviorSynthesisRequest    A partial specification.
        '''

        system = synthesis_goal.system
        goals = synthesis_goal.goals
        initial_conditions = synthesis_goal.initial_conditions
        custom_ltl = synthesis_goal.ltl_specification #TODO: handle this (currently ignored)

        response = ltl_compilation_client.ltl_compilation_client(system,
                                                                 goals,
                                                                 initial_conditions)

        # Update success and publish feedback based on response
        if response.error_code.value is BSErrorCodes.SUCCESS:
            self.set_and_publish_feedback("Received LTL specification")
            success = True
        else:
            self.set_and_publish_feedback("Did not receive LTL specification")
            success = False

        return response.ltl_specification, response.error_code.value, success

    def handle_ltl_synthesis_request(self, ltl_spec):
        '''
        Makes a LTL Synthesis request
        to the corresponding service and handles the response.

        ltl_spec:   LTLSpecification    A complete LTL specification.
        '''

        response = ltl_synthesis_client.ltl_synthesis_client(ltl_spec)

        if response.synthesizable:
            self.set_and_publish_feedback("The LTL Specification is synthesizable")
            success = True
        else:
            self.set_and_publish_feedback("The LTL Specification is unsynthesizable")
            success = False

        return response.automaton, response.error_code, success

    def handle_sm_generation_request(self, synthesized_automata, system):
        '''
        Generate State Machine definitions for a given
        robotic system based on a synthesized automaton.

        @param synthesized_automata SynthesizedAutomaton    The automaton to instantiate as a SM.
        @param system               string                  System name. e.g. "atlas"
        '''
        response = sm_generate_client.sm_generate_client(synthesized_automata, system)

        # Update success and publish feedback based on response
        if response.error_code.value is BSErrorCodes.SUCCESS:
            self.set_and_publish_feedback("Generated State Machine definitions")
            success = True
        else:
            self.set_and_publish_feedback("Unable to generate State Machine.")
            success = False

        return response.state_definition, response.error_code.value, success

    def set_and_publish_feedback(self, status):
        '''Helper method for updating and publishing feedback.'''

        self._feedback.status = status
        self._as.publish_feedback(self._feedback)

if __name__ == '__main__':
    rospy.init_node('vigir_behavior_synthesis')
    BehaviorSynthesisActionServer(rospy.get_name())
    rospy.spin()
<commit_msg>[vigir_synthesis_manager] Fix action server bug<commit_after>#! /usr/bin/env python

import rospy
import actionlib

from vigir_synthesis_msgs.msg import *

import ltl_compilation_client
import ltl_synthesis_client
import sm_generate_client

class BehaviorSynthesisActionServer(object):
    '''ROS Action server that handles the following processes:

    * LTL Specification Compilation
    * LTL Synthesis (resulting in an automaton)
    * State Machine Generation/Instantiation

    Depending on the synthesis request's options, all
    or a subset of the above step will be carried out.
    '''

    # Messages that are used to publish feedback/result
    _feedback = BehaviorSynthesisFeedback()
    _result   = BehaviorSynthesisResult()

    def __init__(self, name):
        self._action_name = name
        self._as = actionlib.SimpleActionServer(self._action_name,
                                                BehaviorSynthesisAction,
                                                execute_cb = self.execute_cb,
                                                auto_start = False)
        self._as.start()

    def execute_cb(self, goal):
        '''The code to be executed when a BehaviorSynthesisActionGoal is received.'''

        r = rospy.Rate(1)   # FIX: What should this be?
        success = True      # start optimistically

        # Acknowledge goal reception
        self.set_and_publish_feedback("Received behavior synthesis request.")

        # Examine the goal message
        synthesis_goal = goal.request
        synthesis_options = goal.synthesis_options

        #TODO: receive a callback when a preempt request is received
        if self._as.is_preempt_requested():
            rospy.loginfo('%s: Preempted' % self._action_name)
            self._as.set_preempted()
            success = False

        if success:
            # Request LTL Specification Compilation from the corresponding server
            # and also update and publish the appropriate feedback
            ltl_spec, error_code_value, success = self.handle_ltl_specification_request(synthesis_goal)

        if success:
            # Request LTL Synthesis from the corresponding server
            # and also update and publish the appropriate feedback
            automaton, error_code_value, success = self.handle_ltl_synthesis_request(ltl_spec)

        if success:
            # Request State Machine Generation from the corresponding server
            # and also update and publish the appropriate feedback
            # TODO: how to get the the yaml_config file?
            sm, error_code_value, success = self.handle_sm_generation_request(automaton, synthesis_goal.system)

        if success:
            self._result.error_code = BSErrorCodes(BSErrorCodes.SUCCESS)
            self._result.states = sm
            rospy.loginfo('%s: Succeeded' % self._action_name)
            self._as.set_succeeded(self._result)
        else:
            self._result.error_code = BSErrorCodes(error_code_value)
            rospy.logerr('%s: Failed' % self._action_name)
            self._as.set_aborted(self._result)

    def handle_ltl_specification_request(self, synthesis_goal):
        '''
        Makes a LTL Specification Compilation request
        to the corresponding service and handles the response.

        synthesis_goal: BehaviorSynthesisRequest    A partial specification.
        '''

        system = synthesis_goal.system
        goals = synthesis_goal.goals
        initial_conditions = synthesis_goal.initial_conditions
        custom_ltl = synthesis_goal.ltl_specification #TODO: handle this (currently ignored)

        response = ltl_compilation_client.ltl_compilation_client(system,
                                                                 goals,
                                                                 initial_conditions)

        # Update success and publish feedback based on response
        if response.error_code.value is BSErrorCodes.SUCCESS:
            self.set_and_publish_feedback("Received LTL specification")
            success = True
        else:
            self.set_and_publish_feedback("Did not receive LTL specification")
            success = False

        return response.ltl_specification, response.error_code.value, success

    def handle_ltl_synthesis_request(self, ltl_spec):
        '''
        Makes a LTL Synthesis request
        to the corresponding service and handles the response.

        ltl_spec:   LTLSpecification    A complete LTL specification.
        '''

        response = ltl_synthesis_client.ltl_synthesis_client(ltl_spec)

        if response.synthesizable:
            self.set_and_publish_feedback("The LTL Specification is synthesizable")
            success = True
        else:
            self.set_and_publish_feedback("The LTL Specification is unsynthesizable")
            success = False

        return response.automaton, response.error_code.value, success

    def handle_sm_generation_request(self, synthesized_automata, system):
        '''
        Generate State Machine definitions for a given
        robotic system based on a synthesized automaton.

        @param synthesized_automata SynthesizedAutomaton    The automaton to instantiate as a SM.
        @param system               string                  System name. e.g. "atlas"
        '''
        response = sm_generate_client.sm_generate_client(synthesized_automata, system)

        # Update success and publish feedback based on response
        if response.error_code.value is BSErrorCodes.SUCCESS:
            self.set_and_publish_feedback("Generated State Machine definitions")
            success = True
        else:
            self.set_and_publish_feedback("Unable to generate State Machine.")
            success = False

        return response.state_definition, response.error_code.value, success

    def set_and_publish_feedback(self, status):
        '''Helper method for updating and publishing feedback.'''

        self._feedback.status = status
        self._as.publish_feedback(self._feedback)

if __name__ == '__main__':
    rospy.init_node('vigir_behavior_synthesis')
    BehaviorSynthesisActionServer(rospy.get_name())
    rospy.spin()
<|endoftext|>


<commit_before>import logging
from typing import Optional, Tuple

import adjustText
import numpy as np
from PyQt5 import QtWidgets
from matplotlib.axes import Axes
from matplotlib.backend_bases import ResizeEvent, MouseEvent, PickEvent
from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg, NavigationToolbar2QT
from matplotlib.figure import Figure
from matplotlib.patches import Rectangle
from matplotlib.text import Text

from .samplepositionchecker_ui import Ui_Form
from .sampleselectorlist import SampleSelectorModel
from ...core.mixins import ToolWindow
from ....core.services.samples import SampleStore, Sample

logger=logging.getLogger(__name__)
logger.setLevel(logging.INFO)

class SamplePositionChecker(QtWidgets.QWidget, Ui_Form, ToolWindow):

    def __init__(self, *args, **kwargs):
        credo = kwargs.pop('credo')
        QtWidgets.QWidget.__init__(self, *args, **kwargs)
        self._connections = []
        self._canvas_connections = []
        self._picked_index = None
        self._samplepos_cache = None
        self._markers = None
        self._texts = None
        self._snapxline = None
        self._snapyline = None
        self.setupToolWindow(credo)
        self.setupUi(self)

    def setupUi(self, Form):
        Ui_Form.setupUi(self, Form)
        self.model = SampleSelectorModel(self.credo)
        self.treeView.setModel(self.model)
        self.figure = Figure(figsize=(4,4))
        self.axes = self.figure.add_subplot(1, 1, 1)
        self.canvas = FigureCanvasQTAgg(self.figure)
        #self.canvas.setMinimumSize(300, 300)
        self.canvas.setSizePolicy(QtWidgets.QSizePolicy.MinimumExpanding, QtWidgets.QSizePolicy.MinimumExpanding)
        self._canvas_connections=[
            self.canvas.mpl_connect('resize_event', self.onCanvasResize),
            self.canvas.mpl_connect('pick_event', self.onCanvasPick),
            self.canvas.mpl_connect('button_release_event', self.onCanvasButtonRelease),
            self.canvas.mpl_connect('motion_notify_event', self.onCanvasMotionNotify),
                                  ]
        self.navtoolbar = NavigationToolbar2QT(self.canvas, None)
        self.verticalLayout.addWidget(self.canvas, 1)
        self.verticalLayout.addWidget(self.navtoolbar)
        self.showLabelsToolButton.toggled.connect(self.onShowLabels)
        ss = self.credo.services['samplestore']
        assert isinstance(ss, SampleStore)
        self._connections = [ss.connect('list-changed', self.onSampleListChanged)]
        self.model.dataChanged.connect(self.replot)
        self.model.modelReset.connect(self.replot)
        self.labelSizeHorizontalSlider.valueChanged.connect(self.replot)
        self.upsideDownToolButton.toggled.connect(self.replot)
        self.rightToLeftToolButton.toggled.connect(self.replot)
        self.loadPersistence()
        self.replot()

    def savePersistence(self):
        self.credo.savePersistence(
            'samplepositionchecker',
            {'show_labels':self.showLabelsToolButton.isChecked(),
             'rtl':self.rightToLeftToolButton.isChecked(),
             'upsidedown':self.upsideDownToolButton.isChecked(),
             'samples':self.model.getSelected()
             })

    def onCanvasPick(self, event:PickEvent):
        logger.debug('Event.ind is: {}, type: {}'.format(event.ind, type(event.ind)))
        logger.debug('onCanvasPick({})'.format(self.model.getSelected()[event.ind[0]]))
        if not self.enableDragSamplesToolButton.isChecked():
            return
        logger.debug('onCanvasPick({}) continuing'.format(self.model.getSelected()[event.ind[0]]))
        line=event.artist
        self._picked_index = event.ind[0]

    def onCanvasButtonRelease(self, event:MouseEvent):
        logger.debug('onCanvasButtonRelease({}, {}, {})'.format(event.xdata, event.ydata, event.button))
        if not (self.enableDragSamplesToolButton.isChecked() and self._picked_index is not None):
            return
        logger.debug('onCanvasButtonRelease({}, {}, {}) continuing'.format(event.xdata, event.ydata, event.button))
        if event.inaxes is self.axes:
            ss=self.credo.services['samplestore']
            assert isinstance(ss, SampleStore)
            sam=ss.get_sample(self.model.getSelected()[self._picked_index])
            assert isinstance(sam, Sample)
            xsnap, ysnap = self.getSnapCoordinates(event.x, event.y)
            sam.positionx.val=xsnap if xsnap is not None else event.xdata
            sam.positiony.val=ysnap if ysnap is not None else event.ydata
            ss.set_sample(sam.title, sam)

        self._picked_index = None
        self._snapxline = None
        self._snapyline = None
        self.replot()

    def snapRadius(self):
        return 3

    def getSnapCoordinates(self, cursorx:float, cursory:float) -> Tuple[Optional[float],Optional[float]]:
        xdata,ydata=self._markers.get_data()
        xdata=[x for i,x in enumerate(xdata) if i!=self._picked_index]
        ydata=[y for i,y in enumerate(ydata) if i!=self._picked_index]
        cdisp=self.axes.transData.transform(np.vstack((xdata,ydata)).T)
        xsnapindex, xsnapdistance = sorted(enumerate(cdisp[:,0]),key=lambda ix:abs(ix[1]-cursorx))[0]
        ysnapindex, ysnapdistance = sorted(enumerate(cdisp[:,1]),key=lambda iy:abs(iy[1]-cursory))[0]
        xpos=None
        ypos=None
        if self.snapXToolButton.isChecked() and abs(xsnapdistance-cursorx)<self.snapRadius():
            xpos = xdata[xsnapindex]
        if self.snapYToolButton.isChecked() and abs(ysnapdistance-cursory)<self.snapRadius():
            ypos = ydata[ysnapindex]
        return xpos, ypos

    def onCanvasMotionNotify(self, event:MouseEvent):
        if not (self.enableDragSamplesToolButton.isChecked() and self._picked_index is not None):
            return
        if event.inaxes is not self.axes:
            return
        logger.debug('onCanvasMotionNotify({}, {}, {})'.format(event.xdata, event.ydata, event.button))
        if self._snapxline is not None:
            try:
                self._snapxline.remove()
            except ValueError:
                pass
        if self._snapyline is not None:
            try:
                self._snapyline.remove()
            except ValueError:
                pass
        snapx, snapy = self.getSnapCoordinates(event.x, event.y)
        if snapx is not None:
            self._snapxline=self.axes.axvline(snapx, linestyle='--',color='black',linewidth=0.7)
        else:
            snapx = event.xdata
        if snapy is not None:
            self._snapyline=self.axes.axhline(snapy, linestyle='--',color='black',linewidth=0.7)
        else:
            snapy = event.ydata
        xdata,ydata=self._markers.get_data()
        xdata[self._picked_index]=snapx
        ydata[self._picked_index]=snapy
        self._markers.set_data(xdata,ydata)
        if self._texts is not None:
            t=self._texts[self._picked_index]
            assert isinstance(t, Text)
            t.set_position([snapx,snapy])
            adjustText.adjust_text(self._texts)
        self.canvas.draw_idle()

    def loadPersistence(self):
        data=self.credo.loadPersistence('samplepositionchecker')
        if not data:
            return
        try:
            self.showLabelsToolButton.setChecked(data['show_labels'])
        except KeyError:
            pass
        try:
            self.rightToLeftToolButton.setChecked(data['rtl'])
        except KeyError:
            pass
        try:
            self.upsideDownToolButton.setChecked(data['upsidedown'])
        except KeyError:
            pass
        try:
            self.model.setSelected(data['samples'])
        except KeyError:
            pass

    def onCanvasResize(self, event:ResizeEvent):
        logger.debug('onCanvasResize()')
        self.figure.tight_layout()
        adjustText.adjust_text(self.texts)
        self.canvas.draw()

    def cleanup(self):
        for c in self._connections:
            self.credo.services['samplestore'].disconnect(c)
        self._connections = []
        for c in self._canvas_connections:
            self.canvas.mpl_disconnect(c)
        self._canvas_connections = []
        super().cleanup()

    def onSampleListChanged(self, ss: SampleStore):
        self.model.update()
        self.replot()
        return False

    def onShowLabels(self):
        self.replot()

    def replot(self):
        assert isinstance(self.axes, Axes)
        self.axes.clear()
        for c in range(self.treeView.model().columnCount()):
            self.treeView.resizeColumnToContents(c)
        try:
            xmin = self.credo.motors['Sample_X'].get_variable('softleft')
            ymin = self.credo.motors['Sample_Y'].get_variable('softleft')
            xmax = self.credo.motors['Sample_X'].get_variable('softright')
            ymax = self.credo.motors['Sample_Y'].get_variable('softright')
            self.axes.add_patch(Rectangle([xmin, ymin], xmax - xmin, ymax - ymin, fill=True, color='lightgray'))
        except KeyError:
            pass
        self.axes.grid(True, which='both')
        self.axes.axis('equal')
        samples = self.model.getSelected()
        if not samples:
            self.canvas.draw()
            return False
        ss = self.credo.services['samplestore']
        assert isinstance(ss, SampleStore)
        self._samplepos_cache = np.array(
            [[s.positionx.val, s.positiony.val, s.positionx.err, s.positiony.err] for s in ss if s.title in samples])
        self._markers=self.axes.plot(self._samplepos_cache[:, 0], self._samplepos_cache[:, 1], 'bo', picker=5)[0]
        if self.showLabelsToolButton.isChecked():
            self._texts=[]
            for s, x, y in zip(samples, self._samplepos_cache[:, 0], self._samplepos_cache[:, 1]):
                self._texts.append(self.axes.text(x, y, ' ' + s + ' ', ha='left', va='center',
                               fontdict={'size': self.labelSizeHorizontalSlider.value()}))
        else:
            self._texts=None
        xmin, xmax, ymin, ymax = self.axes.axis()
        if self.upsideDownToolButton.isChecked():
            self.axes.axis(ymin=max(ymax, ymin), ymax=min(ymin, ymax))
        else:
            self.axes.axis(ymin=min(ymax, ymin), ymax=max(ymin, ymax))
        if self.rightToLeftToolButton.isChecked():
            self.axes.axis(xmin = max(xmax, xmin), xmax = min(xmax, xmin))
        else:
            self.axes.axis(xmin=min(xmax, xmin), xmax=max(xmin, xmax))
        self.figure.tight_layout()
        self.axes.relim()
        self.axes.autoscale_view()
        adjustText.adjust_text(self._texts)
        self.canvas.draw()
<commit_msg>Fix in sample position checker<commit_after>import logging
from typing import Optional, Tuple

import adjustText
import numpy as np
from PyQt5 import QtWidgets
from matplotlib.axes import Axes
from matplotlib.backend_bases import ResizeEvent, MouseEvent, PickEvent
from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg, NavigationToolbar2QT
from matplotlib.figure import Figure
from matplotlib.patches import Rectangle
from matplotlib.text import Text

from .samplepositionchecker_ui import Ui_Form
from .sampleselectorlist import SampleSelectorModel
from ...core.mixins import ToolWindow
from ....core.services.samples import SampleStore, Sample

logger=logging.getLogger(__name__)
logger.setLevel(logging.INFO)

class SamplePositionChecker(QtWidgets.QWidget, Ui_Form, ToolWindow):

    def __init__(self, *args, **kwargs):
        credo = kwargs.pop('credo')
        QtWidgets.QWidget.__init__(self, *args, **kwargs)
        self._connections = []
        self._canvas_connections = []
        self._picked_index = None
        self._samplepos_cache = None
        self._markers = None
        self._texts = None
        self._snapxline = None
        self._snapyline = None
        self.setupToolWindow(credo)
        self.setupUi(self)

    def setupUi(self, Form):
        Ui_Form.setupUi(self, Form)
        self.model = SampleSelectorModel(self.credo)
        self.treeView.setModel(self.model)
        self.figure = Figure(figsize=(4,4))
        self.axes = self.figure.add_subplot(1, 1, 1)
        self.canvas = FigureCanvasQTAgg(self.figure)
        #self.canvas.setMinimumSize(300, 300)
        self.canvas.setSizePolicy(QtWidgets.QSizePolicy.MinimumExpanding, QtWidgets.QSizePolicy.MinimumExpanding)
        self._canvas_connections=[
            self.canvas.mpl_connect('resize_event', self.onCanvasResize),
            self.canvas.mpl_connect('pick_event', self.onCanvasPick),
            self.canvas.mpl_connect('button_release_event', self.onCanvasButtonRelease),
            self.canvas.mpl_connect('motion_notify_event', self.onCanvasMotionNotify),
                                  ]
        self.navtoolbar = NavigationToolbar2QT(self.canvas, None)
        self.verticalLayout.addWidget(self.canvas, 1)
        self.verticalLayout.addWidget(self.navtoolbar)
        self.showLabelsToolButton.toggled.connect(self.onShowLabels)
        ss = self.credo.services['samplestore']
        assert isinstance(ss, SampleStore)
        self._connections = [ss.connect('list-changed', self.onSampleListChanged)]
        self.model.dataChanged.connect(self.replot)
        self.model.modelReset.connect(self.replot)
        self.labelSizeHorizontalSlider.valueChanged.connect(self.replot)
        self.upsideDownToolButton.toggled.connect(self.replot)
        self.rightToLeftToolButton.toggled.connect(self.replot)
        self.loadPersistence()
        self.replot()

    def savePersistence(self):
        self.credo.savePersistence(
            'samplepositionchecker',
            {'show_labels':self.showLabelsToolButton.isChecked(),
             'rtl':self.rightToLeftToolButton.isChecked(),
             'upsidedown':self.upsideDownToolButton.isChecked(),
             'samples':self.model.getSelected()
             })

    def onCanvasPick(self, event:PickEvent):
        logger.debug('Event.ind is: {}, type: {}'.format(event.ind, type(event.ind)))
        logger.debug('onCanvasPick({})'.format(self.model.getSelected()[event.ind[0]]))
        if not self.enableDragSamplesToolButton.isChecked():
            return
        logger.debug('onCanvasPick({}) continuing'.format(self.model.getSelected()[event.ind[0]]))
        line=event.artist
        self._picked_index = event.ind[0]

    def onCanvasButtonRelease(self, event:MouseEvent):
        logger.debug('onCanvasButtonRelease({}, {}, {})'.format(event.xdata, event.ydata, event.button))
        if not (self.enableDragSamplesToolButton.isChecked() and self._picked_index is not None):
            return
        logger.debug('onCanvasButtonRelease({}, {}, {}) continuing'.format(event.xdata, event.ydata, event.button))
        if event.inaxes is self.axes:
            ss=self.credo.services['samplestore']
            assert isinstance(ss, SampleStore)
            sam=ss.get_sample(self.model.getSelected()[self._picked_index])
            assert isinstance(sam, Sample)
            xsnap, ysnap = self.getSnapCoordinates(event.x, event.y)
            sam.positionx.val=xsnap if xsnap is not None else event.xdata
            sam.positiony.val=ysnap if ysnap is not None else event.ydata
            ss.set_sample(sam.title, sam)

        self._picked_index = None
        self._snapxline = None
        self._snapyline = None
        self.replot()

    def snapRadius(self):
        return 3

    def getSnapCoordinates(self, cursorx:float, cursory:float) -> Tuple[Optional[float],Optional[float]]:
        xdata,ydata=self._markers.get_data()
        xdata=[x for i,x in enumerate(xdata) if i!=self._picked_index]
        ydata=[y for i,y in enumerate(ydata) if i!=self._picked_index]
        cdisp=self.axes.transData.transform(np.vstack((xdata,ydata)).T)
        xsnapindex, xsnapdistance = sorted(enumerate(cdisp[:,0]),key=lambda ix:abs(ix[1]-cursorx))[0]
        ysnapindex, ysnapdistance = sorted(enumerate(cdisp[:,1]),key=lambda iy:abs(iy[1]-cursory))[0]
        xpos=None
        ypos=None
        if self.snapXToolButton.isChecked() and abs(xsnapdistance-cursorx)<self.snapRadius():
            xpos = xdata[xsnapindex]
        if self.snapYToolButton.isChecked() and abs(ysnapdistance-cursory)<self.snapRadius():
            ypos = ydata[ysnapindex]
        return xpos, ypos

    def onCanvasMotionNotify(self, event:MouseEvent):
        if not (self.enableDragSamplesToolButton.isChecked() and self._picked_index is not None):
            return
        if event.inaxes is not self.axes:
            return
        logger.debug('onCanvasMotionNotify({}, {}, {})'.format(event.xdata, event.ydata, event.button))
        if self._snapxline is not None:
            try:
                self._snapxline.remove()
            except ValueError:
                pass
        if self._snapyline is not None:
            try:
                self._snapyline.remove()
            except ValueError:
                pass
        snapx, snapy = self.getSnapCoordinates(event.x, event.y)
        if snapx is not None:
            self._snapxline=self.axes.axvline(snapx, linestyle='--',color='black',linewidth=0.7)
        else:
            snapx = event.xdata
        if snapy is not None:
            self._snapyline=self.axes.axhline(snapy, linestyle='--',color='black',linewidth=0.7)
        else:
            snapy = event.ydata
        xdata,ydata=self._markers.get_data()
        xdata[self._picked_index]=snapx
        ydata[self._picked_index]=snapy
        self._markers.set_data(xdata,ydata)
        if self._texts is not None:
            t=self._texts[self._picked_index]
            assert isinstance(t, Text)
            t.set_position([snapx,snapy])
            adjustText.adjust_text(self._texts)
        self.canvas.draw_idle()

    def loadPersistence(self):
        data=self.credo.loadPersistence('samplepositionchecker')
        if not data:
            return
        try:
            self.showLabelsToolButton.setChecked(data['show_labels'])
        except KeyError:
            pass
        try:
            self.rightToLeftToolButton.setChecked(data['rtl'])
        except KeyError:
            pass
        try:
            self.upsideDownToolButton.setChecked(data['upsidedown'])
        except KeyError:
            pass
        try:
            self.model.setSelected(data['samples'])
        except KeyError:
            pass

    def onCanvasResize(self, event:ResizeEvent):
        logger.debug('onCanvasResize()')
        self.figure.tight_layout()
        adjustText.adjust_text(self._texts)
        self.canvas.draw()

    def cleanup(self):
        for c in self._connections:
            self.credo.services['samplestore'].disconnect(c)
        self._connections = []
        for c in self._canvas_connections:
            self.canvas.mpl_disconnect(c)
        self._canvas_connections = []
        super().cleanup()

    def onSampleListChanged(self, ss: SampleStore):
        self.model.update()
        self.replot()
        return False

    def onShowLabels(self):
        self.replot()

    def replot(self):
        assert isinstance(self.axes, Axes)
        self.axes.clear()
        for c in range(self.treeView.model().columnCount()):
            self.treeView.resizeColumnToContents(c)
        try:
            xmin = self.credo.motors['Sample_X'].get_variable('softleft')
            ymin = self.credo.motors['Sample_Y'].get_variable('softleft')
            xmax = self.credo.motors['Sample_X'].get_variable('softright')
            ymax = self.credo.motors['Sample_Y'].get_variable('softright')
            self.axes.add_patch(Rectangle([xmin, ymin], xmax - xmin, ymax - ymin, fill=True, color='lightgray'))
        except KeyError:
            pass
        self.axes.grid(True, which='both')
        self.axes.axis('equal')
        samples = self.model.getSelected()
        if not samples:
            self.canvas.draw()
            return False
        ss = self.credo.services['samplestore']
        assert isinstance(ss, SampleStore)
        self._samplepos_cache = np.array(
            [[s.positionx.val, s.positiony.val, s.positionx.err, s.positiony.err] for s in ss if s.title in samples])
        self._markers=self.axes.plot(self._samplepos_cache[:, 0], self._samplepos_cache[:, 1], 'bo', picker=5)[0]
        if self.showLabelsToolButton.isChecked():
            self._texts=[]
            for s, x, y in zip(samples, self._samplepos_cache[:, 0], self._samplepos_cache[:, 1]):
                self._texts.append(self.axes.text(x, y, ' ' + s + ' ', ha='left', va='center',
                               fontdict={'size': self.labelSizeHorizontalSlider.value()}))
        else:
            self._texts=None
        xmin, xmax, ymin, ymax = self.axes.axis()
        if self.upsideDownToolButton.isChecked():
            self.axes.axis(ymin=max(ymax, ymin), ymax=min(ymin, ymax))
        else:
            self.axes.axis(ymin=min(ymax, ymin), ymax=max(ymin, ymax))
        if self.rightToLeftToolButton.isChecked():
            self.axes.axis(xmin = max(xmax, xmin), xmax = min(xmax, xmin))
        else:
            self.axes.axis(xmin=min(xmax, xmin), xmax=max(xmin, xmax))
        self.figure.tight_layout()
        self.axes.relim()
        self.axes.autoscale_view()
        adjustText.adjust_text(self._texts)
        self.canvas.draw()
<|endoftext|>


<commit_before>import numpy as np

from chainercv.transforms.image.resize import resize
from chainercv.utils.bbox.bbox_iou import bbox_iou
from chainercv.utils import non_maximum_suppression

def _mask_aggregation(
        bbox, mask_prob, mask_weight,
        size, binary_thresh
):
    assert bbox.shape[0] == len(mask_prob)
    assert bbox.shape[0] == mask_weight.shape[0]

    mask = np.zeros(size, dtype=np.float32)
    for bb, msk_pb, msk_w in zip(bbox, mask_prob, mask_weight):
        bb = np.round(bb).astype(np.int32)
        y_min, x_min, y_max, x_max = bb
        if y_max - y_min > 0 and x_max - x_min > 0:
            msk_pb = resize(
                msk_pb.astype(np.float32)[None],
                (y_max - y_min, x_max - x_min))
            msk_m = (msk_pb >= binary_thresh).astype(np.float32)[0]
            mask[y_min:y_max, x_min:x_max] += msk_m * msk_w

    y_indices, x_indices = np.where(mask >= binary_thresh)
    if len(y_indices) == 0 or len(x_indices) == 0:
        return None, None
    else:
        y_max = y_indices.max() + 1
        y_min = y_indices.min()
        x_max = x_indices.max() + 1
        x_min = x_indices.min()

        c_bbox = np.array(
            [y_min, x_min, y_max, x_max],
            dtype=np.float32)
        c_mask = mask[y_min:y_max, x_min:x_max]
        return c_mask[None], c_bbox[None]

def mask_voting(
        roi_mask_prob, bbox, cls_prob, size,
        score_thresh, nms_thresh,
        mask_merge_thresh, binary_thresh,
        limit=100, bg_label=0
):
    """Refine mask probabilities by merging multiple masks.

    First, this function discard invalid masks with non maximum suppression.
    Then, it merges masks with weight calculated from class probabilities and
    iou.
    This function improves the mask qualities by merging overlapped masks
    predicted as the same object class.

    Here are notations used.
    * :math:`R'` is the total number of RoIs produced across batches.
    * :math:`L` is the number of classes excluding the background.
    * :math:`RH` is the height of pooled image.
    * :math:`RW` is the height of pooled image.

    Args:
        roi_mask_prob (array): A mask probability array whose shape is
            :math:`(R, RH, RW)`.
        bbox (array): A bounding box array whose shape is
            :math:`(R, 4)`.
        cls_prob (array): A class probability array whose shape is
            :math:`(R, L + 1)`.
        size (tuple of int): Original image size.
        score_thresh (float): A threshold value of the class score.
        nms_thresh (float): A threshold value of non maximum suppression.
        mask_merge_thresh (float): A threshold value of the bounding box iou
            for mask merging.
        binary_thresh (float): A threshold value of mask score
            for mask merging.
        limit (int): The maximum number of outputs.
        bg_label (int): The id of the background label.

    Returns:
        array, array, array, array:
        * **v_mask_score**: Merged masks. Its shapes is :math:`(N, RH, RW)`.
        * **v_bbox**: Bounding boxes for the merged masks. Its shape is \
            :math:`(N, 4)`.
        * **v_label**: Class labels for the merged masks. Its shape is \
            :math:`(N, )`.
        * **v_score**: Class probabilities for the merged masks. Its shape \
            is :math:`(N, )`.

    """

    roi_mask_size = roi_mask_prob.shape[1:]
    n_class = cls_prob.shape[1]

    v_mask_prob = []
    v_bbox = []
    v_label = []
    v_cls_prob = []

    cls_score = []
    cls_bbox = []

    for label in range(0, n_class):
        # background
        if label == bg_label:
            continue
        # non maximum suppression
        score_l = cls_prob[:, label]
        keep_indices = non_maximum_suppression(
            bbox, nms_thresh, score_l)
        bbox_l = bbox[keep_indices]
        score_l = score_l[keep_indices]
        cls_bbox.append(bbox_l)
        cls_score.append(score_l)

    sorted_score = np.sort(np.concatenate(cls_score))[::-1]
    n_keep = min(len(sorted_score), limit)
    score_thresh = max(sorted_score[n_keep - 1], score_thresh)

    for label in range(0, n_class):
        # background
        if label == bg_label:
            continue
        bbox_l = cls_bbox[label - 1]
        score_l = cls_score[label - 1]
        keep_indices = np.where(score_l >= score_thresh)
        bbox_l = bbox_l[keep_indices]
        score_l = score_l[keep_indices]

        v_mask_prob_l = []
        v_bbox_l = []
        v_score_l = []

        for i, bb in enumerate(bbox_l):
            iou = bbox_iou(bbox, bb[np.newaxis, :])
            keep_indices = np.where(iou >= mask_merge_thresh)[0]
            mask_weight = cls_prob[keep_indices, label]
            mask_weight = mask_weight / mask_weight.sum()
            mask_prob_i = roi_mask_prob[keep_indices]
            bbox_i = bbox[keep_indices]
            c_mask, c_bbox = _mask_aggregation(
                bbox_i, mask_prob_i, mask_weight, size, binary_thresh)
            if c_mask is not None and c_bbox is not None:
                c_mask = resize(
                    c_mask.astype(np.float32),
                    roi_mask_size)
                v_mask_prob_l.append(c_mask)
                v_bbox_l.append(c_bbox)
                v_score_l.append(score_l[i])

        if len(v_mask_prob_l) > 0:
            v_mask_prob_l = np.concatenate(v_mask_prob_l)
            v_bbox_l = np.concatenate(v_bbox_l)
            v_score_l = np.array(v_score_l)

            v_label_l = np.repeat(label - 1, v_bbox_l.shape[0])
            v_label_l = v_label_l.astype(np.int32)
            v_mask_prob.append(v_mask_prob_l)
            v_bbox.append(v_bbox_l)
            v_label.append(v_label_l)
            v_cls_prob.append(v_score_l)

    if len(v_mask_prob) > 0:
        v_mask_prob = np.concatenate(v_mask_prob)
        v_bbox = np.concatenate(v_bbox)
        v_label = np.concatenate(v_label)
        v_cls_prob = np.concatenate(v_cls_prob)
    else:
        v_mask_prob = np.empty((0, roi_mask_size[0], roi_mask_size[1]))
        v_bbox = np.empty((0, 4))
        v_label = np.empty((0, ))
        v_cls_prob = np.empty((0, ))
    return v_mask_prob, v_bbox, v_label, v_cls_prob
<commit_msg>remove some lines<commit_after>import numpy as np

from chainercv.transforms.image.resize import resize
from chainercv.utils.bbox.bbox_iou import bbox_iou
from chainercv.utils import non_maximum_suppression

def _mask_aggregation(
        bbox, mask_prob, mask_weight,
        size, binary_thresh
):
    assert bbox.shape[0] == len(mask_prob)
    assert bbox.shape[0] == mask_weight.shape[0]

    mask = np.zeros(size, dtype=np.float32)
    for bb, msk_pb, msk_w in zip(bbox, mask_prob, mask_weight):
        bb = np.round(bb).astype(np.int32)
        y_min, x_min, y_max, x_max = bb
        if y_max - y_min > 0 and x_max - x_min > 0:
            msk_pb = resize(
                msk_pb.astype(np.float32)[None],
                (y_max - y_min, x_max - x_min))
            msk_m = (msk_pb >= binary_thresh).astype(np.float32)[0]
            mask[y_min:y_max, x_min:x_max] += msk_m * msk_w

    y_indices, x_indices = np.where(mask >= binary_thresh)
    if len(y_indices) == 0 or len(x_indices) == 0:
        return None, None
    else:
        y_max = y_indices.max() + 1
        y_min = y_indices.min()
        x_max = x_indices.max() + 1
        x_min = x_indices.min()

        c_bbox = np.array(
            [y_min, x_min, y_max, x_max],
            dtype=np.float32)
        c_mask = mask[y_min:y_max, x_min:x_max]
        return c_mask[None], c_bbox[None]

def mask_voting(
        roi_mask_prob, bbox, cls_prob, size,
        score_thresh, nms_thresh,
        mask_merge_thresh, binary_thresh,
        limit=100, bg_label=0
):
    """Refine mask probabilities by merging multiple masks.

    First, this function discard invalid masks with non maximum suppression.
    Then, it merges masks with weight calculated from class probabilities and
    iou.
    This function improves the mask qualities by merging overlapped masks
    predicted as the same object class.

    Here are notations used.
    * :math:`R'` is the total number of RoIs produced across batches.
    * :math:`L` is the number of classes excluding the background.
    * :math:`RH` is the height of pooled image.
    * :math:`RW` is the height of pooled image.

    Args:
        roi_mask_prob (array): A mask probability array whose shape is
            :math:`(R, RH, RW)`.
        bbox (array): A bounding box array whose shape is
            :math:`(R, 4)`.
        cls_prob (array): A class probability array whose shape is
            :math:`(R, L + 1)`.
        size (tuple of int): Original image size.
        score_thresh (float): A threshold value of the class score.
        nms_thresh (float): A threshold value of non maximum suppression.
        mask_merge_thresh (float): A threshold value of the bounding box iou
            for mask merging.
        binary_thresh (float): A threshold value of mask score
            for mask merging.
        limit (int): The maximum number of outputs.
        bg_label (int): The id of the background label.

    Returns:
        array, array, array, array:
        * **v_mask_score**: Merged masks. Its shapes is :math:`(N, RH, RW)`.
        * **v_bbox**: Bounding boxes for the merged masks. Its shape is \
            :math:`(N, 4)`.
        * **v_label**: Class labels for the merged masks. Its shape is \
            :math:`(N, )`.
        * **v_score**: Class probabilities for the merged masks. Its shape \
            is :math:`(N, )`.

    """

    roi_mask_size = roi_mask_prob.shape[1:]
    n_class = cls_prob.shape[1]

    v_mask_prob = []
    v_bbox = []
    v_label = []
    v_cls_prob = []

    cls_score = []
    cls_bbox = []

    for label in range(0, n_class):
        # background
        if label == bg_label:
            continue
        # non maximum suppression
        score_l = cls_prob[:, label]
        keep_indices = non_maximum_suppression(
            bbox, nms_thresh, score_l)
        bbox_l = bbox[keep_indices]
        score_l = score_l[keep_indices]
        cls_bbox.append(bbox_l)
        cls_score.append(score_l)

    sorted_score = np.sort(np.concatenate(cls_score))[::-1]
    n_keep = min(len(sorted_score), limit)
    score_thresh = max(sorted_score[n_keep - 1], score_thresh)

    for label in range(0, n_class):
        # background
        if label == bg_label:
            continue
        bbox_l = cls_bbox[label - 1]
        score_l = cls_score[label - 1]
        keep_indices = np.where(score_l >= score_thresh)
        bbox_l = bbox_l[keep_indices]
        score_l = score_l[keep_indices]

        v_mask_prob_l = []
        v_bbox_l = []
        v_score_l = []

        for i, bb in enumerate(bbox_l):
            iou = bbox_iou(bbox, bb[np.newaxis, :])
            keep_indices = np.where(iou >= mask_merge_thresh)[0]
            mask_weight = cls_prob[keep_indices, label]
            mask_weight = mask_weight / mask_weight.sum()
            mask_prob_i = roi_mask_prob[keep_indices]
            bbox_i = bbox[keep_indices]
            c_mask, c_bbox = _mask_aggregation(
                bbox_i, mask_prob_i, mask_weight, size, binary_thresh)
            if c_mask is not None and c_bbox is not None:
                c_mask = resize(
                    c_mask.astype(np.float32),
                    roi_mask_size)
                v_mask_prob_l.append(c_mask)
                v_bbox_l.append(c_bbox)
                v_score_l.append(score_l[i])

        if len(v_mask_prob_l) > 0:
            v_label_l = np.repeat(
                label - 1, len(v_score_l)).astype(np.int32)

            v_mask_prob += v_mask_prob_l
            v_bbox += v_bbox_l
            v_label.append(v_label_l)
            v_cls_prob.append(v_score_l)

    if len(v_mask_prob) > 0:
        v_mask_prob = np.concatenate(v_mask_prob)
        v_bbox = np.concatenate(v_bbox)
        v_label = np.concatenate(v_label)
        v_cls_prob = np.concatenate(v_cls_prob)
    else:
        v_mask_prob = np.empty((0, roi_mask_size[0], roi_mask_size[1]))
        v_bbox = np.empty((0, 4))
        v_label = np.empty((0, ))
        v_cls_prob = np.empty((0, ))
    return v_mask_prob, v_bbox, v_label, v_cls_prob
<|endoftext|>


<commit_before># coding: utf-8

# my_utils for Intro to Data Science with Python
# Author: Kat Chuang
# Created: Nov 2014

# --------------------------------------
## Stage 2 begin

import csv

# open a file and return a double list
def open_with_CSV(filename, d='\t'):
    uuids = []
    with open(filename) as tsvin:
        tsvin = csv.reader(tsvin, delimiter=d)
        for row in tsvin:
            uuids.append(row)
    return uuids

#2.a size
def number_of_records(data_sample):
    return len(data_sample)

#2.b calculate sum
def calculate_sum(data_sample):
    total = 0
    for row in data_sample[1:]:
        price = float(row[2])
        total += price
    return total

#2.c 1 # Find the average price
def find_average(data_sample, headers=False):
    total = calculate_sum(data_sample)
    size = number_of_records(data_sample)
    if headers:
        total -= 1

    average = total / size
    return average

#2.d. Max, Min
# Find the maximum price
def find_max(theData, col):
    tempList = []

    for row in theData:
        price = float(row[col])
        tempList.append(price)
    return max(tempList)

# Find the minimum price
def find_min(theData, col):
    tempList = []

    for row in theData:
        price = float(row[col])
        tempList.append(price)
    return min(tempList)

# Find the max or min price
def find_max_min(the_data, col, m):
    tempList = [], val = 0

    for row in the_data:
        price = float(row[col])
        tempList.append(price)

        if m == "max":
            val = max(tempList)
        elif m == "min":
            val = min(tempList)
        else: # hopefully we don’t come to this
            pass

    return val

## Stage 2 end

# --------------------------------------

## Stage 3 begin
# Stage 3: Cleaning data

# Filter rows were columns match a string data type
def filter_col_by_string(the_data, field, filter_condition):
    filtered_rows = []

    #find index of field in first row
    col = int(the_data[0].index(field))
    filtered_rows.append(the_data[0])

    for row in the_data[1:]:
        if row[col] == filter_condition:
            filtered_rows.append(row)

    return filtered_rows

# Filter rows were columns match a float data type
def filter_col_by_float(the_data, field, direction, filter_condition):
    filtered_rows = []

    #find index of field in first row
    col = int(the_data[0].index(field))
    cond = float(filter_condition)

    for row in the_data[1:]:
        element = float(row[col])

        if direction == "<":
            if element < cond: filtered_rows.append(row)

        elif direction == "<=":
            if element <= cond: filtered_rows.append(row)

        elif direction == ">":
            if element > cond: filtered_rows.append(row)

        elif  direction == ">=":
            if element >= cond: filtered_rows.append(row)

        elif  direction == "==":
            if element == cond: filtered_rows.append(row)
        else:
            pass

    return filtered_rows

## Stage 3 end

# --------------------------------------

## Stage 4 begin

#4.a csv
def write_to_file(filename, data_sample):
    example = csv.writer(open(filename, 'w', newline=''))
    example.writerows(data_sample)

#4.b more functions
def write_brand_and_price_to_file(filename, data_sample):

    # confirm that the columns only have two columns, otherwise take the two fields
    num_fields = len(data_sample[0])

    brand_field_index = 5 #int(dataSample[0].index("brand"))
    price_field_index = 2 #int(dataSample[0].index("priceLabel"))

    #if numFields > 2:
    new_array = []
    for record in data_sample:
        new_record = [None] * 2
        new_record[0] = record[brand_field_index]
        new_record[1] = record[price_field_index]
        new_array.append(new_record)

    # write the file
    write_to_file(filename, new_array)

#4.c export to excel
from openpyxl import Workbook
from openpyxl.cell import get_column_letter

def save_spreadsheet(filename, data_sample):

    wb = Workbook()
    ws = wb.active

    rowIndex = 1
    for rows in data_sample:
        colIndex = 1
        for field in rows:
            colIndex2 = get_column_letter(colIndex)
            ws.cell('%s%s'%(colIndex2, rowIndex)).value = field
            colIndex +=1
        rowIndex += 1

    wb.save(filename)

## Stage 4 end

# --------------------------------------

## Stage 5 begin

def create_chart(plot, sample, title):
    prices = sorted(map(int, sample))
    xAxisTicks = list( range(len(prices)) )
    width=0.25
    plot.plot(xAxisTicks, prices, 'g', label='price points',linewidth=2)

def prices_of(sampleData):
    tempList = []
    for row in sampleData[1:]:
        priceCol = float(row[2])
        tempList.append(priceCol)
    return tempList

def print_brand_avg_min(name):
    tieSample = filterByString(dataFromCSV, "brandName", name)
    avgPrice = calculateSum(tieSample) / len(tieSample)
    minPrice = findMin(tieSample[1:], 2)
    print("{2} Average: ${0:6.2f}; Min: ${1:.2f}".format(avgPrice, minPrice, name))

## Stage 5 end

# --------------------------------------

## Stage 6 begin

## Stage 6 end

<commit_msg>function for creating line charts<commit_after># coding: utf-8

# my_utils for Intro to Data Science with Python
# Author: Kat Chuang
# Created: Nov 2014

# --------------------------------------
## Stage 2 begin

import csv

# open a file and return a double list
def open_with_CSV(filename, d='\t'):
    uuids = []
    with open(filename) as tsvin:
        tsvin = csv.reader(tsvin, delimiter=d)
        for row in tsvin:
            uuids.append(row)
    return uuids

#2.a size
def number_of_records(data_sample):
    return len(data_sample)

#2.b calculate sum
def calculate_sum(data_sample):
    total = 0
    for row in data_sample[1:]:
        price = float(row[2])
        total += price
    return total

#2.c 1 # Find the average price
def find_average(data_sample, headers=False):
    total = calculate_sum(data_sample)
    size = number_of_records(data_sample)
    if headers:
        total -= 1

    average = total / size
    return average

#2.d. Max, Min
# Find the maximum price
def find_max(theData, col):
    tempList = []

    for row in theData:
        price = float(row[col])
        tempList.append(price)
    return max(tempList)

# Find the minimum price
def find_min(theData, col):
    tempList = []

    for row in theData:
        price = float(row[col])
        tempList.append(price)
    return min(tempList)

# Find the max or min price
def find_max_min(the_data, col, m):
    tempList = [], val = 0

    for row in the_data:
        price = float(row[col])
        tempList.append(price)

        if m == "max":
            val = max(tempList)
        elif m == "min":
            val = min(tempList)
        else: # hopefully we don’t come to this
            pass

    return val

## Stage 2 end

# --------------------------------------

## Stage 3 begin
# Stage 3: Cleaning data

# Filter rows were columns match a string data type
def filter_col_by_string(the_data, field, filter_condition):
    filtered_rows = []

    #find index of field in first row
    col = int(the_data[0].index(field))
    filtered_rows.append(the_data[0])

    for row in the_data[1:]:
        if row[col] == filter_condition:
            filtered_rows.append(row)

    return filtered_rows

# Filter rows were columns match a float data type
def filter_col_by_float(the_data, field, direction, filter_condition):
    filtered_rows = []

    #find index of field in first row
    col = int(the_data[0].index(field))
    cond = float(filter_condition)

    for row in the_data[1:]:
        element = float(row[col])

        if direction == "<":
            if element < cond: filtered_rows.append(row)

        elif direction == "<=":
            if element <= cond: filtered_rows.append(row)

        elif direction == ">":
            if element > cond: filtered_rows.append(row)

        elif  direction == ">=":
            if element >= cond: filtered_rows.append(row)

        elif  direction == "==":
            if element == cond: filtered_rows.append(row)
        else:
            pass

    return filtered_rows

## Stage 3 end

# --------------------------------------

## Stage 4 begin

#4.a csv
def write_to_file(filename, data_sample):
    example = csv.writer(open(filename, 'w', newline=''))
    example.writerows(data_sample)

#4.b more functions
def write_brand_and_price_to_file(filename, data_sample):

    # confirm that the columns only have two columns, otherwise take the two fields
    num_fields = len(data_sample[0])

    brand_field_index = 5 #int(dataSample[0].index("brand"))
    price_field_index = 2 #int(dataSample[0].index("priceLabel"))

    #if numFields > 2:
    new_array = []
    for record in data_sample:
        new_record = [None] * 2
        new_record[0] = record[brand_field_index]
        new_record[1] = record[price_field_index]
        new_array.append(new_record)

    # write the file
    write_to_file(filename, new_array)

#4.c export to excel
from openpyxl import Workbook
from openpyxl.cell import get_column_letter

def save_spreadsheet(filename, data_sample):

    wb = Workbook()
    ws = wb.active

    rowIndex = 1
    for rows in data_sample:
        colIndex = 1
        for field in rows:
            colIndex2 = get_column_letter(colIndex)
            ws.cell('%s%s'%(colIndex2, rowIndex)).value = field
            colIndex +=1
        rowIndex += 1

    wb.save(filename)

## Stage 4 end

# --------------------------------------

## Stage 5 begin
#5.a Line charts
def create_line_chart(sample, title, exported_figure_filename):
    fig = plt.figure()
    ax = fig.add_subplot(1, 1, 1)

    prices = sorted(map(int, sample))
    x_axis_ticks = list( range(len(sample)) )
    ax.plot(x_axis_ticks, prices, label='price points', linewidth=2)
    ax.set_title(title)
    ax.set_xlabel('Tie Price ($)')
    ax.set_ylabel('Number of Ties')
    ax.set_xlim([0,len(sample)])
    fig.savefig(exported_figure_filename)

def print_brand_avg_min(name):
    tieSample = filterByString(dataFromCSV, "brandName", name)
    avgPrice = calculateSum(tieSample) / len(tieSample)
    minPrice = findMin(tieSample[1:], 2)
    print("{2} Average: ${0:6.2f}; Min: ${1:.2f}".format(avgPrice, minPrice, name))

## Stage 5 end

# --------------------------------------

## Stage 6 begin

## Stage 6 end

<|endoftext|>


<commit_before>#!/usr/bin/python
# Copyright (c) 2011 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.

import os
import subprocess
import sys

def Main():
  # TODO(ncbray): figure out why this is failing on windows and enable.
  if (sys.platform in ['win32', 'cygwin'] and
      'xp-nacl-chrome' not in os.environ.get('PWD', '')): return

  script_dir = os.path.dirname(os.path.abspath(__file__))
  test_dir = os.path.dirname(script_dir)
  chrome_dir = os.path.dirname(test_dir)
  src_dir = os.path.dirname(chrome_dir)
  nacl_integration_script = os.path.join(
      src_dir, 'native_client/build/buildbot_chrome_nacl_stage.py')
  cmd = [sys.executable, nacl_integration_script] + sys.argv[1:]
  print cmd
  subprocess.check_call(cmd)

if __name__ == '__main__':
  Main()
<commit_msg>Disabling nacl integration tests on mac, as they fail on some, but not all builders.<commit_after>#!/usr/bin/python
# Copyright (c) 2011 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.

import os
import subprocess
import sys

def Main():
  # TODO(ncbray): figure out why this is failing on windows and enable.
  if (sys.platform in ['win32', 'cygwin'] and
      'xp-nacl-chrome' not in os.environ.get('PWD', '')): return
  # TODO(ncbray): figure out why this is failing on mac and re-enable.
  if (sys.platform == 'darwin' and
      'mac-nacl-chrome' not in os.environ.get('PWD', '')): return

  script_dir = os.path.dirname(os.path.abspath(__file__))
  test_dir = os.path.dirname(script_dir)
  chrome_dir = os.path.dirname(test_dir)
  src_dir = os.path.dirname(chrome_dir)
  nacl_integration_script = os.path.join(
      src_dir, 'native_client/build/buildbot_chrome_nacl_stage.py')
  cmd = [sys.executable, nacl_integration_script] + sys.argv[1:]
  print cmd
  subprocess.check_call(cmd)

if __name__ == '__main__':
  Main()
<|endoftext|>


<commit_before># Use a different solved board to generate different tests.
valid = [[5,3,4,6,7,8,9,1,2],
         [6,7,2,1,9,5,3,4,8],
         [1,9,8,3,4,2,5,6,7],
         [8,5,9,7,6,1,4,2,3],
         [4,2,6,8,5,3,7,9,1],
         [7,1,3,9,2,4,8,5,6],
         [9,6,1,5,3,7,2,8,4],
         [2,8,7,4,1,9,6,3,5],
         [3,4,5,2,8,6,1,7,9]]

# test cases with no solution
no_soln1 = [
[1,2,3,4,5,6,7,8,0],
[0,0,0,0,0,0,0,0,9],
[0,0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0,0]]

no_soln2 = [
[1, 2, 3, 0, 0, 0, 0, 0, 0],
[4, 5, 0, 0, 0, 0, 6, 0, 0],
[0, 0, 0, 6, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0]]
import random, time

squares = [(i,j) for i in range(9) for j in range(9)]
units = dict(((i,j), [[(i,k) for k in range(9)]] +
              [[(k,j) for k in range(9)]] +
              [[(k,l) for k in range(i/3*3, i/3*3+3) for l in range(j/3*3, j/3*3+3)]])
             for (i,j) in squares)
peers = dict((s, set(sum(units[s], [])) - set([s]))
             for s in squares)

def erase(board, i, j, d):
    if d not in board[i][j]:
        return board
    board[i][j] = board[i][j].replace(d, '')
    if len(board[i][j]) == 0:
        return False # contradiction
    elif len(board[i][j]) == 1:
        d2 = board[i][j]
        if not all(erase(board, i1, j1, d2) for (i1, j1) in peers[i,j]):
            return False
    for unit in units[i,j]:
        numplaces = [(i1, j1) for (i1, j1) in unit if d in board[i1][j1]]
        if len(numplaces) == 0:
            return False
        elif len(numplaces) == 1:
            if not assign(board, numplaces[0][0], numplaces[0][1], d):
                return False
    return board

def assign(board, i, j, d):
    if all(erase(board, i, j, d2) for d2 in board[i][j].replace(d, '')):
        return board
    else:
        return False

def random_sudoku(N = 30):
    board = [['123456789' for _ in range(9)] for _ in range(9)]
    cells = [s for s in squares]
    random.shuffle(cells)
    for cell in cells:
        i,j = cell
        if not assign(board, i, j, random.choice(board[i][j])):
            break
        ds = [board[i][j] for i in range(9) for j in range(9) if len(board[i][j]) == 1]
        if len(ds) >= N and len(set(ds)) >= 8:
            return [map(lambda v: int(v) if len(v) == 1 else 0, row) for row in board]
    return random_sudoku(N)

def check_random_solns(solve_sudoku, check_sudoku, mutates, iters):
    random.seed()
    solved = 0
    fraction = 0.9
    for i in range(iters):
        # Generate a valid random board
        board = random_sudoku(mutates)
        bd = ''.join(''.join(map(lambda n: str(n), row)) for row in board)
        # If it's unsolvable the solver screwed up
        start = time.clock()
        soln = solve_sudoku(board)
        if soln is not None and soln is not False:
            solved += 1
        t = time.clock() - start
        if t > 5.0:
            print "board[%d] %s took (%.2f seconds)" % (i, bd, t)
    assert solved > (fraction * iters), "Your solver failed on more than %.1f%% of random boards!" % (100*fraction)
    print "Your solver completed %d / %d random boards! Congrats!" % (solved, iters)
    return True

# Make a copy of a grid so we can modify it without touching the original
def copy (grid):
    return map (lambda x: x[:], grid)

# Assert than a solution remains solvable after mutates-many moves are undone.
# Run iters-many tests of this nature.
def fuzz_solution(soln, mutates, iters, check_sudoku, solve_sudoku):
    """ fuzzes a given *valid* solution """
    random.seed()
    for i in range(iters):
        board = copy(soln)
        # Undo a set of moves. This should leave the board solvable
        for mutate in range(mutates):
            x = random.randrange(0,9)
            y = random.randrange(0,9)
            # Might already be 0 in which case we didn't undo "mutates" moves
            # but still generated a reasonable test case
            board[x][y] = 0
        # If this board is invalid the test harness screwed up
        assert check_sudoku(board), "Input checker failed with input {board}".format(board=board)
        # If it's unsolvable the solver screwed up
        assert solve_sudoku(board), "Solver failed to solve board {board}".format(board=board)
    return True

def check_no_valid_solns(solve_sudoku, tests=None):
    """ runs solver against cases with no solution"""
    tests = tests or [no_soln1, no_soln2]
    for test in tests:
        res = solve_sudoku(test)
        assert res is False, """Solver failed to return False for valid, but unsolveable sudoku.
Returned {res} instead. Input was: {test}""".format(test=test, res=res)
    return True

def fuzz_solver(check_sudoku, solve_sudoku, mutates=10, iters=10, soln=None, tests=None):
    soln = soln or valid
    return check_no_valid_solns(solve_sudoku, tests) and fuzz_solution(valid, mutates, iters, check_sudoku, solve_sudoku) and check_random_solns(solve_sudoku, check_sudoku, mutates, iters)
<commit_msg>fuzz_solver using transpose, reflection, etc<commit_after># Use a different solved board to generate different tests.
valid = [[5,3,4,6,7,8,9,1,2],
         [6,7,2,1,9,5,3,4,8],
         [1,9,8,3,4,2,5,6,7],
         [8,5,9,7,6,1,4,2,3],
         [4,2,6,8,5,3,7,9,1],
         [7,1,3,9,2,4,8,5,6],
         [9,6,1,5,3,7,2,8,4],
         [2,8,7,4,1,9,6,3,5],
         [3,4,5,2,8,6,1,7,9]]

# test cases with no solution
no_soln1 = [
[1,2,3,4,5,6,7,8,0],
[0,0,0,0,0,0,0,0,9],
[0,0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0,0]]

no_soln2 = [
[1, 2, 3, 0, 0, 0, 0, 0, 0],
[4, 5, 0, 0, 0, 0, 6, 0, 0],
[0, 0, 0, 6, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0]]
import random, time

squares = [(i,j) for i in range(9) for j in range(9)]
units = dict(((i,j), [[(i,k) for k in range(9)]] +
              [[(k,j) for k in range(9)]] +
              [[(k,l) for k in range(i/3*3, i/3*3+3) for l in range(j/3*3, j/3*3+3)]])
             for (i,j) in squares)
peers = dict((s, set(sum(units[s], [])) - set([s]))
             for s in squares)

def erase(board, i, j, d):
    if d not in board[i][j]:
        return board
    board[i][j] = board[i][j].replace(d, '')
    if len(board[i][j]) == 0:
        return False # contradiction
    elif len(board[i][j]) == 1:
        d2 = board[i][j]
        if not all(erase(board, i1, j1, d2) for (i1, j1) in peers[i,j]):
            return False
    for unit in units[i,j]:
        numplaces = [(i1, j1) for (i1, j1) in unit if d in board[i1][j1]]
        if len(numplaces) == 0:
            return False
        elif len(numplaces) == 1:
            if not assign(board, numplaces[0][0], numplaces[0][1], d):
                return False
    return board

def assign(board, i, j, d):
    if all(erase(board, i, j, d2) for d2 in board[i][j].replace(d, '')):
        return board
    else:
        return False

def random_sudoku(N = 30):
    board = [['123456789' for _ in range(9)] for _ in range(9)]
    cells = [s for s in squares]
    random.shuffle(cells)
    for cell in cells:
        i,j = cell
        if not assign(board, i, j, random.choice(board[i][j])):
            break
        ds = [board[i][j] for i in range(9) for j in range(9) if len(board[i][j]) == 1]
        if len(ds) >= N and len(set(ds)) >= 8:
            return [map(lambda v: int(v) if len(v) == 1 else 0, row) for row in board]
    return random_sudoku(N)

def check_random_solns(solve_sudoku, check_sudoku, mutates, iters):
    random.seed()
    solved = 0
    fraction = 0.9
    for i in range(iters):
        # Generate a valid random board
        board = random_sudoku(mutates)
        bd = ''.join(''.join(map(lambda n: str(n), row)) for row in board)
        # If it's unsolvable the solver screwed up
        start = time.clock()
        soln = solve_sudoku(board)
        if soln is not None and soln is not False:
            solved += 1
        t = time.clock() - start
        if t > 5.0:
            print "board[%d] %s took (%.2f seconds)" % (i, bd, t)
    assert solved > (fraction * iters), "Your solver failed on more than %.1f%% of random boards!" % (100*fraction)
    print "Your solver completed %d / %d random boards! Congrats!" % (solved, iters)
    return True

# Random strategy 2: Take a valid board and perform transformations
# that do not change validity

# Transposing a grid maintains validity
def transpose(grid):
    return map(list, zip(*grid))

# Permutes the row/column with another row/column in the same range
# (i.e. 6 with 6-8, 0 with 0-2, etc.)
def permute(grid, i, row=True):
    if not row: grid = map(list, zip(*grid))
    j = random.choice(range(i/3*3, i/3*3+3))
    grid[j], grid[i] = grid[i], grid[j]
    return grid if row else transpose(grid)

# Permutes the row/column blocks (i.e. 0-2 with 6-8)
def permute_block(grid, i, row=True):
    if not row: grid = map(list, zip(*grid))
    bi = i*3
    bj = random.choice(range(3))*3
    for offset in range(3):
        grid[bi+offset], grid[bj+offset] = grid[bj+offset], grid[bi+offset]
    return grid if row else transpose(grid)

# Reflects the board along the horizontal or vertical axis
def reflect(grid, horizontal=True):
    if not horizontal: grid = map(list, zip(*grid))
    for i in range(9): grid[i].reverse()
    return grid if horizontal else transpose(grid)

def random_mutation_sudoku(soln, iters=1000):
    # generate a valid grid
    grid = copy(soln)
    choices = [['reflect', horizontal] for horizontal in (True, False)] + [['transpose']] + [['permute', i, row] for row in (True, False) for i in range(9)] + [['permute_block', bi, row] for row in (True, False) for bi in range(3)]
    for i in range(iters):
        choice = random.choice(choices)
        if choice[0] == 'reflect': grid = reflect(grid, *choice[1:])
        if choice[0] == 'transpose': grid = transpose(grid)
        if choice[0] == 'permute': grid = permute(grid, *choice[1:])
        if choice[0] == 'permute_block': grid = permute_block(grid, *choice[1:])
    return grid

# Make a copy of a grid so we can modify it without touching the original
def copy (grid):
    return map (lambda x: x[:], grid)

# Assert than a solution remains solvable after mutates-many moves are undone.
# Run iters-many tests of this nature.
def fuzz_solution(soln, mutates, iters, check_sudoku, solve_sudoku):
    """ fuzzes a given *valid* solution """
    random.seed()
    for i in range(iters):
        board = copy(soln)
        # Undo a set of moves. This should leave the board solvable
        for mutate in range(mutates):
            x = random.randrange(0,9)
            y = random.randrange(0,9)
            # Might already be 0 in which case we didn't undo "mutates" moves
            # but still generated a reasonable test case
            board[x][y] = 0
        # If this board is invalid the test harness screwed up
        assert check_sudoku(board), "Input checker failed with input {board}".format(board=board)
        # If it's unsolvable the solver screwed up
        assert solve_sudoku(board), "Solver failed to solve board {board}".format(board=board)
    return True

def check_no_valid_solns(solve_sudoku, tests=None):
    """ runs solver against cases with no solution"""
    tests = tests or [no_soln1, no_soln2]
    for test in tests:
        res = solve_sudoku(test)
        assert res is False, """Solver failed to return False for valid, but unsolveable sudoku.
Returned {res} instead. Input was: {test}""".format(test=test, res=res)
    return True

def fuzz_solver(check_sudoku, solve_sudoku, mutates=10, iters=10, soln=None, tests=None):
    soln = soln or valid
    success = check_no_valid_solns(solve_sudoku, tests) and fuzz_solution(soln, mutates, iters, check_sudoku, solve_sudoku) and check_random_solns(solve_sudoku, check_sudoku, mutates, iters)
    if success and all(fuzz_solution(random_mutation_sudoku(soln), mutates, 1, check_sudoku, solve_sudoku) for _ in range(iters)):
        print "Your solver completed %d randomly generated boards with %d mutations! Congrats!" % (iters, mutates)
        return True
    else:
        return False
<|endoftext|>


<commit_before>import time
from MeteorClient import MeteorClient
import numpy as np
import scipy as sp
import os
import json

client = MeteorClient('ws://127.0.0.1:3000/websocket')

def callback_function(error, result):
    if error:
        print(error)
        return
    print(result)

def callback_register(error, result):
    if error:
        print(error)
        return

    print('here is the result', result, result.__class__.__name__)
    item = result
    if item['pid'] == os.getpid():
        try:
            client.call('addResult', [item['_id'], str(eval(item['text']))+' (%d)'%(os.getpid())], callback_function)
        except Exception as e:
            client.call('addResult', [item['_id'], '??? (%d)'%(os.getpid())], callback_function)
            print(str(e))

def subscribed(subscription):
    print('* SUBSCRIBED {}'.format(subscription))

def unsubscribed(subscription):
    print('* UNSUBSCRIBED {}'.format(subscription))

def added(collection, id, fields):
    print('* ADDED {} {}'.format(collection, id))
    for key, value in fields.items():
        print('  - FIELD {} {}'.format(key, value))

    # query the data each time something has been added to
    # a collection to see the data `grow`
    all_lists = client.find('items', selector={})
    # print('Lists: {}'.format(all_lists))
    print('Num lists: {}'.format(len(all_lists)))

    if not 'result' in fields:
        pid = os.getpid()
        client.call('reserve', [id, pid], callback_register)
        # print(pid, pid2)
        # if pid2 == pid:
        #     print('%d: this one is for me: %d'%(pid, pid2))
        #     try:
        #         client.call('addResult', [id, str(eval(fields['text']))], callback_function)
        #     except Exception as e:
        #         client.call('addResult', [id, '???'], callback_function)
        #         print(str(e))
        # else:
        #     print('%d: this one is for me: %d'%(pid, pid2))

        # if collection == 'list' you could subscribe to the list here
        # with something like
        # client.subscribe('todos', id)
        # all_todos = client.find('todos', selector={})
        # print 'Todos: {}'.format(all_todos)

def connected():
    print('* CONNECTED')

def subscription_callback(error):
    if error:
        print(error)

client.on('subscribed', subscribed)
client.on('unsubscribed', unsubscribed)
client.on('added', added)
client.on('connected', connected)

client.connect()
client.subscribe('items')

client.call('removeItems', ['Python*'], callback_function)
#client.call('addItem', ['1+1'], callback_function)

# (sort of) hacky way to keep the client alive
# ctrl + c to kill the script
while True:
    try:
        time.sleep(1)
    except KeyboardInterrupt:
        break

client.unsubscribe('items')

client.close()
<commit_msg>cleaning up<commit_after>import time
from MeteorClient import MeteorClient
import numpy as np
import scipy as sp
import os
import json

client = MeteorClient('ws://127.0.0.1:3000/websocket')

def callback_function(error, result):
    if error:
        print(error)
        return
    print(result)

def callback_register(error, result):
    if error:
        print(error)
        return

    print('here is the result', result, result.__class__.__name__)
    item = result
    if item['pid'] == os.getpid():
        try:
            client.call('addResult', [item['_id'], str(eval(item['text']))+' (%d)'%(os.getpid())], callback_function)
        except Exception as e:
            client.call('addResult', [item['_id'], '??? (%d)'%(os.getpid())], callback_function)
            print(str(e))

def subscribed(subscription):
    print('* SUBSCRIBED {}'.format(subscription))

def unsubscribed(subscription):
    print('* UNSUBSCRIBED {}'.format(subscription))

def added(collection, id, fields):
    print('* ADDED {} {}'.format(collection, id))
    for key, value in fields.items():
        print('  - FIELD {} {}'.format(key, value))

    # query the data each time something has been added to
    # a collection to see the data `grow`
    all_lists = client.find('items', selector={})
    # print('Lists: {}'.format(all_lists))
    print('Num lists: {}'.format(len(all_lists)))

    if not 'result' in fields:
        pid = os.getpid()
        client.call('reserve', [id, pid], callback_register)

def connected():
    print('* CONNECTED')

def subscription_callback(error):
    if error:
        print(error)

client.on('subscribed', subscribed)
client.on('unsubscribed', unsubscribed)
client.on('added', added)
client.on('connected', connected)

client.connect()
client.subscribe('items')

client.call('removeItems', ['Python*'], callback_function)
#client.call('addItem', ['1+1'], callback_function)

# (sort of) hacky way to keep the client alive
# ctrl + c to kill the script
while True:
    try:
        time.sleep(1)
    except KeyboardInterrupt:
        break

client.unsubscribe('items')

client.close()
<|endoftext|>


<commit_before>from gadgets.th_gpio import TH_GPIO
import time

class LED():
	def __init__(self,gpio_number=7):
		self.gpio_number = gpio_number
		#A singleton class is treated like a function
		TH_GPIO().enable_pin(gpio_number,mode='out')
		self.status = 0 #0:off,1:on

	def on(self):
		self.status = 1
		TH_GPIO().send(self.gpio_number,self.status)

	def off(self):
		self.status = 0
		TH_GPIO().send(self.gpio_number,self.status)

	def blink(self,numTimes=3,speed=1):
		self.status =  1
		for i in range(0,numTimes):## Run loop numTimes
			TH_GPIO().send(self.gpio_number,1)
			time.sleep(speed)## Wait
			TH_GPIO().send(self.gpio_number,0)
			time.sleep(speed)## Wait
		self.status = 0

	def cleanup(self):
		TH_GPIO().disable_pin(self.gpio_number)
		self.status = 0

class PWM_LED():
	def __init__(self,gpio_number=7,freq=100):
		self.gpio_number = gpio_number
		self.freq = freq
		self.pwm = TH_GPIO().pwm_create(self.gpio_number,freq=self.freq)

	def set_freq(self,freq):
		self.freq = freq
		self.pwm.set_freq(freq)

	def dim(self,start=100,end=0,step=-1,dur=0.1):
		if self.pwm is not None:
			for dc in range(start,end, step):
				self.pwm.change(dc)
				time.sleep(dur)

	def brighten(self,start=0,end=100,step=1,dur=0.1):
		if self.pwm is not None:
			for dc in range(start,end, step):
				self.pwm.change(dc)
				time.sleep(dur)

	def cleanup(self):
		TH_GPIO().disable_pin(self.gpio_number)
<commit_msg>Update led.py<commit_after>from gadgets.th_gpio import TH_GPIO
import time

class LED():
	def __init__(self,gpio_number=7):
		self.gpio_number = gpio_number
		#A singleton class is treated like a function
		TH_GPIO().enable_pin(gpio_number,mode='out')
		self.status = 0 #0:off,1:on

	def on(self):
		self.status = 1
		TH_GPIO().send(self.gpio_number,self.status)

	def off(self):
		self.status = 0
		TH_GPIO().send(self.gpio_number,self.status)

	def blink(self,numTimes=3,speed=1):
		self.status =  1
		for i in range(0,numTimes):## Run loop numTimes
			TH_GPIO().send(self.gpio_number,1)
			time.sleep(speed)## Wait
			TH_GPIO().send(self.gpio_number,0)
			time.sleep(speed)## Wait
		self.status = 0

	def cleanup(self):
		TH_GPIO().disable_pin(self.gpio_number)
		self.status = 0

class PWM_LED():
	def __init__(self,gpio_number=7,freq=100):
		self.gpio_number = gpio_number
		self.freq = freq
		self.pwm = TH_GPIO().pwm_create(self.gpio_number,freq=self.freq)

	def set_freq(self,freq):
		self.freq = freq
		self.pwm.set_freq(freq)

	def dim(self,start=100,end=0,step=-1,dur=0.1):
		if self.pwm is not None:
			for dc in range(start,end, step):
				self.pwm.change(dc)
				time.sleep(dur)

	def brighten(self,start=0,end=100,step=1,dur=0.1):
		if self.pwm is not None:
			for dc in range(start,end, step):
				self.pwm.change(dc)
				time.sleep(dur)

	def cleanup(self):
		TH_GPIO().disable_pin(self.gpio_number)

class ARRAY_LED():
	def __init__(self,gpio_numbers=[]):
		self.leds = {}
		for p in gpio_numbers:
			TH_GPIO().enable_pin(p,mode='out')
			self.leds[p] = 0

	def on(self,leds=[]):
		for p in leds:
			TH_GPIO().send(p,1)
			self.leds[p] = 1

	def off(self,leds=[]):
		for p in leds:
			TH_GPIO().send(p,0)
			self.leds[p] = 0

	def blink(self,leds=[],numTimes=3,dur=1):
		for i in range(0,numTimes):## Run loop numTimes
			self.on(leds)
			time.sleep(dur)## Wait
			self.off(leds)
			time.sleep(dur)## Wait

	def cleanup(self):
		for p in self.leds:
			TH_GPIO().disable_pin(p)
		self.leds.clear()

<|endoftext|>


<commit_before>from random import randint
from enums import Move

class Player:
    def __init__(self, name=None, retarded = False):
        self.name = name + self.get_power_name()
        self.rocks = 1 if not retarded else 0
        self.papers = 1 if not retarded else 0
        self.scissors = 1
        self.points = 0
        self.wins = 0

    def get_power_name(self):
        l = ["the Defiler","the Crusher of Hands","of Doom","the Hand Magician"]
        return " " + l[randint(0, len(l)-1)]

    def lose_move(self, move):
        if (move == Move.ROCK):
            self.rocks -= 1
        elif (move == Move.PAPER):
            self.papers -= 1
        elif (move == Move.SCISSORS):
            self.scissors -= 1

    def gain_move(self,move):
        if (move == Move.ROCK):
            self.rocks += 1
        elif (move == Move.PAPER):
            self.papers += 1
        elif (move == Move.SCISSORS):
            self.scissors += 1
        else:
            NotImplemented

    def won_match(self):
        self.wins += 1

    def gain_points(self, points):
        self.points += points

    def get_moves(self):
        return [self.rocks,self.papers, self.scissors]

    def get_points(self):
        return self.points

    def get_wins(self):
        return self.wins

    def get_name(self):
        return self.name

    def has_moves_left(self):
        return (self.rocks > 0 or self.papers > 0 or self.scissors > 0)

    def can_choose_move(self, move):
        if move == Move.ROCK:
            return self.rocks > 0
        elif move == Move.PAPER:
            return self.papers > 0
        else:
            return self.scissors > 0

    def pack_to_string(self):
        return "{}|{}|{}|{}|{}|{}".format(self.name,
                                          self.rocks,
                                          self.papers,
                                          self.scissors,
                                          self.points,
                                          self.wins)

    def unpack_from_string(self,string):
        self.name,self.rocks,self.papers,self.scissors,self.points,self.wins = string.split('|')

    def __repr__(self):
        return "<player " + self.pack_to_string() +'>'

def test():
    p = Player('p')
    s = p.pack_to_string()
    p2 = Player('p2')
    p2.unpack_from_string(s)
    print('Names are equal after unpack: ',p.get_name() == p2.get_name())

if __name__ == '__main__':
    test()
<commit_msg>gave player the responsibility of getting user input for moves<commit_after>from random import randint
from enums import Move

class Player:
    def __init__(self, name = None, bot = False):
        self.name = name + self.get_power_name()
        self.rocks = 1
        self.papers = 1
        self.scissors = 1
        self.points = 0
        self.wins = 0
        self.bot = bot

    def get_power_name(self):
        l = ["the Defiler","the Crusher of Hands","of Doom","the Hand Magician"]
        return " " + l[randint(0, len(l)-1)]

    def lose_move(self, move):
        if (move == Move.ROCK):
            self.rocks -= 1
        elif (move == Move.PAPER):
            self.papers -= 1
        elif (move == Move.SCISSORS):
            self.scissors -= 1

    def gain_move(self,move):
        if (move == Move.ROCK):
            self.rocks += 1
        elif (move == Move.PAPER):
            self.papers += 1
        elif (move == Move.SCISSORS):
            self.scissors += 1
        else:
            NotImplemented

    def won_match(self):
        self.wins += 1

    def gain_points(self, points):
        self.points += points

    def get_moves(self):
        return [self.rocks,self.papers, self.scissors]

    def get_points(self):
        return self.points

    def get_wins(self):
        return self.wins

    def get_name(self):
        return self.name

    def has_moves_left(self):
        return (self.rocks > 0 or self.papers > 0 or self.scissors > 0)

    def can_choose_move(self, move):
        if move == Move.ROCK:
            return self.rocks > 0
        elif move == Move.PAPER:
            return self.papers > 0
        else:
            return self.scissors > 0

    def get_chosen_move(self):
        choice = -1
        done = False
        if not self.bot:
            while not done:
                choice = input('What is your move?: ')
                if choice in ['q','quit','exit']:
                    done = True
                    choice = -1
                if choice in '123':
                    choice = int(choice)
                    choice -= 1 # minus one since choices do not begin with 0
                    choice = choice % 3
                    if player.can_choose_move(choice):
                        done = True
        else:
            while not done:
                choice = randint(0,2)
                if player.can_choose_move(choice):
                    done = True
        return choice

    def pack_to_string(self):
        return "{}|{}|{}|{}|{}|{}".format(self.name,
                                          self.rocks,
                                          self.papers,
                                          self.scissors,
                                          self.points,
                                          self.wins)

    def unpack_from_string(self,string):
        self.name,self.rocks,self.papers,self.scissors,self.points,self.wins = string.split('|')

    def __repr__(self):
        return "<player " + self.pack_to_string() +'>'

#######
# Tests
def test():
    p = Player('p')
    s = p.pack_to_string()
    p2 = Player('p2')
    p2.unpack_from_string(s)
    print('Names are equal after unpack: ',p.get_name() == p2.get_name())

if __name__ == '__main__':
    test()
<|endoftext|>


<commit_before>"""Views for lutris main app"""

from django.http import HttpResponse
from django.views.generic import list_detail, ListView
from django.shortcuts import render, redirect, get_object_or_404
from django.contrib.auth.decorators import login_required
from games.models import Game, Runner, Genre, Platform, \
                         Company, Installer, News
from games.forms import InstallerForm
#pylint: disable=E1101

class GameList(ListView):
    model = Game
    context_object_name = "games"

class GameListByYear(GameList):
    def get_queryset(self):
        return Game.objects.filter(year=self.args[0])

    def get_context_data(self, **kwargs):
        context = super(GameListByYear, self).get_context_data(**kwargs)
        context['year'] = self.args[0]
        return context

def home(request):
    """Homepage view"""
    print "this is the home"
    featured = Game.objects.exclude(cover__exact="")[:5]
    news = News.objects.all()[:5]
    return render(request, 'home.html',
                  {'featured': featured, 'news': news})

def game_detail(request, slug):
    game = get_object_or_404(Game, slug=slug)
    return render(request, 'games/detail.html', {'game': game})

@login_required
def new_installer(request, slug):
    game = get_object_or_404(Game, slug=slug)
    form = InstallerForm(request.POST or None)
    if request.method == 'POST' and form.is_valid():
        installer = form.save(commit=False)
        installer.game_id = game.id
        installer.user_id = request.user.id
        installer.save()

        return redirect("installer_complete", slug=game.slug)
    return render(request, 'games/new-installer.html',
                  {'form': form, 'game': game})

@login_required
def edit_installer(request, slug):
    installer = get_object_or_404(Installer, slug=slug)
    form = InstallerForm(request.POST or None, instance=installer)
    if request.method == 'POST' and form.is_valid():
        form.save()
        return redirect("installer_complete", slug=installer.game.slug)
    return render(request, 'games/installer-form.html',
                  {'form': form, 'game': installer.game, 'new': False})

def installer_complete(request, slug):
    game = get_object_or_404(Game, slug=slug)
    return render(request, 'games/installer-complete.html', {'game': game})

def serve_installer(request, slug):
    """Serve the content of an installer in yaml format"""
    installer = get_object_or_404(Installer, slug=slug)
    content = installer.content
    return HttpResponse(content, content_type="application/yaml")

def game_list(request):
    """View for all games"""
    games = Game.objects.all()
    return render(request, 'games/game_list.html', {'games': games})

def games_by_runner(request, runner_slug):
    """View for games filtered by runner"""
    runner = get_object_or_404(Runner, slug=runner_slug)
    games = Game.objects.filter(runner__slug=runner.slug)
    return render(request, 'games/game_list.html',
                  {'games': games})

def game_list_by_year(request, year):
    """View for games filtered by year"""
    return list_detail.object_list(
        request,
        queryset=Game.objects.filter(year__gt=2000),
        template_name="games/game_list.html",
        template_object_name="games",
        extra_context={"year": year}
    )

def game_list_by_genre(request, genre_slug):
    """View for games filtered by genre"""
    genre = get_object_or_404(Genre, slug=genre_slug)
    return list_detail.object_list(
        request,
        queryset=Game.objects.filter(genre__slug=genre_slug),
        template_name="games/game_list.html",
        template_object_name="games",
        extra_context={'genre': genre}
    )

def games_by_publisher(request, publisher_slug):
    """View for games filtered by publisher"""
    company = get_object_or_404(Company, slug=publisher_slug)
    return list_detail.object_list(
        request,
        queryset=Game.objects.filter(publisher=company),
        template_name="games/game_list.html",
        template_object_name='games',
        extra_context={'publisher': company}
    )

def games_by_developer(request, developer_slug):
    """View for games filtered by developer"""
    company = get_object_or_404(Company, slug=developer_slug)
    return list_detail.object_list(
        request,
        queryset=Game.objects.filter(developer=company),
        template_name="games/game_list.html",
        template_object_name='games',
        extra_context={'developer': company}
    )

def games_by_platform(request, platform_slug):
    """View for games filtered by platform"""
    platform = get_object_or_404(Platform, slug=platform_slug)
    return list_detail.object_list(
        request,
        queryset=Game.objects.filter(platform=platform),
        template_name="games/game_list.html",
        template_object_name='games',
        extra_context={'platform': platform}
    )

def screenshot_add(request, slug):
    game = get_object_or_404(Game, slug=slug)
    return render(request, 'games/screenshot/add.html')
<commit_msg>Don't remember why I wrote this<commit_after>"""Views for lutris main app"""
# pylint: disable=E1101

from django.http import HttpResponse
from django.views.generic import list_detail, ListView
from django.shortcuts import render, redirect, get_object_or_404
from django.contrib.auth.decorators import login_required
from games.models import Game, Runner, Genre, Platform, \
                         Company, Installer, News
from games.forms import InstallerForm

class GameList(ListView):
    model = Game
    context_object_name = "games"

class GameListByYear(GameList):
    def get_queryset(self):
        return Game.objects.filter(year=self.args[0])

    def get_context_data(self, **kwargs):
        context = super(GameListByYear, self).get_context_data(**kwargs)
        context['year'] = self.args[0]
        return context

def home(request):
    """Homepage view"""
    featured = Game.objects.exclude(cover__exact="")[:5]
    news = News.objects.all()[:5]
    return render(request, 'home.html',
                  {'featured': featured, 'news': news})

def game_detail(request, slug):
    game = get_object_or_404(Game, slug=slug)
    return render(request, 'games/detail.html', {'game': game})

@login_required
def new_installer(request, slug):
    game = get_object_or_404(Game, slug=slug)
    form = InstallerForm(request.POST or None)
    if request.method == 'POST' and form.is_valid():
        installer = form.save(commit=False)
        installer.game_id = game.id
        installer.user_id = request.user.id
        installer.save()

        return redirect("installer_complete", slug=game.slug)
    return render(request, 'games/new-installer.html',
                  {'form': form, 'game': game})

def validate(game, request, form):
    if request.method == 'POST' and form.is_valid():
        installer = form.save(commit=False)
        installer.game_id = game.id
        installer.user_id = request.user.id
        installer.save()

@login_required
def edit_installer(request, slug):
    installer = get_object_or_404(Installer, slug=slug)
    form = InstallerForm(request.POST or None, instance=installer)
    if request.method == 'POST' and form.is_valid():
        form.save()
        return redirect("installer_complete", slug=installer.game.slug)
    return render(request, 'games/installer-form.html',
                  {'form': form, 'game': installer.game, 'new': False})

def installer_complete(request, slug):
    game = get_object_or_404(Game, slug=slug)
    return render(request, 'games/installer-complete.html', {'game': game})

def serve_installer(request, slug):
    """Serve the content of an installer in yaml format"""
    installer = get_object_or_404(Installer, slug=slug)
    content = installer.content
    return HttpResponse(content, content_type="application/yaml")

def game_list(request):
    """View for all games"""
    games = Game.objects.all()
    return render(request, 'games/game_list.html', {'games': games})

def games_by_runner(request, runner_slug):
    """View for games filtered by runner"""
    runner = get_object_or_404(Runner, slug=runner_slug)
    games = Game.objects.filter(runner__slug=runner.slug)
    return render(request, 'games/game_list.html',
                  {'games': games})

def game_list_by_year(request, year):
    """View for games filtered by year"""
    return list_detail.object_list(
        request,
        queryset=Game.objects.filter(year__gt=2000),
        template_name="games/game_list.html",
        template_object_name="games",
        extra_context={"year": year}
    )

def game_list_by_genre(request, genre_slug):
    """View for games filtered by genre"""
    genre = get_object_or_404(Genre, slug=genre_slug)
    return list_detail.object_list(
        request,
        queryset=Game.objects.filter(genre__slug=genre_slug),
        template_name="games/game_list.html",
        template_object_name="games",
        extra_context={'genre': genre}
    )

def games_by_publisher(request, publisher_slug):
    """View for games filtered by publisher"""
    company = get_object_or_404(Company, slug=publisher_slug)
    return list_detail.object_list(
        request,
        queryset=Game.objects.filter(publisher=company),
        template_name="games/game_list.html",
        template_object_name='games',
        extra_context={'publisher': company}
    )

def games_by_developer(request, developer_slug):
    """View for games filtered by developer"""
    company = get_object_or_404(Company, slug=developer_slug)
    return list_detail.object_list(
        request,
        queryset=Game.objects.filter(developer=company),
        template_name="games/game_list.html",
        template_object_name='games',
        extra_context={'developer': company}
    )

def games_by_platform(request, platform_slug):
    """View for games filtered by platform"""
    platform = get_object_or_404(Platform, slug=platform_slug)
    return list_detail.object_list(
        request,
        queryset=Game.objects.filter(platform=platform),
        template_name="games/game_list.html",
        template_object_name='games',
        extra_context={'platform': platform}
    )

def screenshot_add(request, slug):
    game = get_object_or_404(Game, slug=slug)
    return render(request, 'games/screenshot/add.html')
<|endoftext|>