def manager(self,rule, ruledef):
     from MatchManager import Matching
     from SearchManager import SearchManager
     from Trigger import Trigger
     from FileManager import FileManager
        
     Matching = Matching(rule, ruledef)
     Trigger = Trigger()
     FileManager = FileManager()
        
     log_location = self.log_check(rule)
     log = FileManager.read_logfile(log_location)
     logfile = log
     endPoint = len(logfile)
     
     while True:
         if endPoint > self.startAt:     
             Searching = SearchManager(Matching.matchlist, rule, logfile)
             Trigger.perform_action(Searching.action, rule)
         
         print 'start at begin: ' ,  self.startAt
         self.startAt = endPoint
         print 'startat = ', self.startAt
         print 'endpoint = ', endPoint
         interval = self.interval_check(rule)
         print 'Sleeping for ' + str(interval) + ' seconds'
         time.sleep(interval)
         print 'Searching in the new rule file'
         
         log_location = self.log_check(rule)
         log = FileManager.read_logfile(log_location)
         del logfile[:]
         for line in range (self.startAt, len(log)):
             logfile.append(log[line])
         endPoint = len(log)
Example #2
0
 def setupTrigger(name: str,
                  num: int,
                  led_name: str,
                  on_what: str = "event"):
     trg = Trigger(name, arduino)
     trg.add_listener(on_what, to_main(num, led_name, trg))
     return trg
Example #3
0
    def manager(self, rule, ruledef):
        from MatchManager import Matching
        from SearchManager import SearchManager
        from Trigger import Trigger
        from FileManager import FileManager

        Matching = Matching(rule, ruledef)
        Trigger = Trigger()
        FileManager = FileManager()

        log_location = self.log_check(rule)
        log = FileManager.read_logfile(log_location)
        logfile = log
        endPoint = len(logfile)

        while True:
            if endPoint > self.startAt:
                Searching = SearchManager(Matching.matchlist, rule, logfile)
                Trigger.perform_action(Searching.action, rule)

            print 'start at begin: ', self.startAt
            self.startAt = endPoint
            print 'startat = ', self.startAt
            print 'endpoint = ', endPoint
            interval = self.interval_check(rule)
            print 'Sleeping for ' + str(interval) + ' seconds'
            time.sleep(interval)
            print 'Searching in the new rule file'

            log_location = self.log_check(rule)
            log = FileManager.read_logfile(log_location)
            del logfile[:]
            for line in range(self.startAt, len(log)):
                logfile.append(log[line])
            endPoint = len(log)
Example #4
0
 def __init__(self, effects, zone="battlefield", txt='', keyword=''):
     super(CardStaticAbility, self).__init__(effects,
                                             zone=zone,
                                             txt=txt,
                                             keyword=keyword)
     # XXX The zone is not quite right, for attached static abilities that can
     # attach to something out of the battlefield
     self.control_changed = Trigger(
         ControllerChanged(),
         sender="source")  # card with ability changed controller
Example #5
0
class Gun:
    """docstring for Gun"""

    YAW_CHANNEL = 0
    PITCH_CHANNEL = 1
    TRIGGER_CHANNEL = 2

    MAX_SPEED = 0
    MAX_ACCEL = 0

    def __init__(self):
        self.controller = maestro.Controller('COM3')
        self.yaw_motor = Motor(self.controller,
                               self.YAW_CHANNEL,
                               name='yaw',
                               offset_angle=10)
        self.pitch_motor = Motor(self.controller,
                                 self.PITCH_CHANNEL,
                                 name='pitch',
                                 max_angle=20,
                                 offset_angle=0)
        self.trigger = Trigger(self.controller,
                               self.TRIGGER_CHANNEL,
                               name='trigger',
                               neutral_pulse=1880 * 4,
                               pulse_travel=2080 * 4)

    def get_angles(self):
        yaw = self.yaw_motor.get_angle()
        pitch = self.yaw_motor.get_angle()
        return (yaw, pitch)

    def is_moving(self):
        return not self.controller.getMovingState()

    def set_yaw(self, yaw, speed=MAX_SPEED, accel=MAX_ACCEL):
        self.yaw_motor.set_target(yaw, speed, accel)

    def set_pitch(self, pitch, speed=MAX_SPEED, accel=MAX_ACCEL):
        self.pitch_motor.set_target(pitch, speed, accel)

    def set_target(self, yaw, pitch, speed=MAX_SPEED, accel=MAX_ACCEL):
        self.set_yaw(yaw, speed, accel)
        self.set_pitch(pitch, speed, accel)
        print('%s, %s' % (yaw, pitch))

    def fire(self):
        self.trigger.set_on()

    def stop_fire(self):
        self.trigger.set_off()

    def go_to_zero(self, speed=MAX_SPEED, accel=MAX_ACCEL):
        self.stop_fire()
        self.set_target(0, 0, speed, accel)
Example #6
0
    def processTrainingSet(self, basedir="sounds/train/", signalword="oknavsa", savedir="data/"):

        clips = [clip for clip in os.listdir(basedir) if clip.endswith(".wav")]

        try:
            with open("sounds/train/thresh.dat","r") as fh:
                lines = [line.strip() for line in fh.readlines() if len(line)>1]
                bestThresh = {line.split(",")[0]:int(line.split(",")[1]) for line in lines}
        except:
            bestThresh = {}

        tr = Trigger()

        self.YXtot = []
        fnames = []
        durations = []
        self.keywordDurations = []

        with warnings.catch_warnings():
            warnings.filterwarnings("ignore",category=Warning)

            for clip in clips:

                if clip in bestThresh: tr.setParams({"THRESHOLD": bestThresh[clip]})
                else: tr.setParams({"THRESHOLD": 600})

                if clip.lower().startswith(signalword): isSignal = True
                elif clip.lower().startswith("random"): isSignal = False
                elif clip.lower().startswith("background"): isSignal = False
                else: continue

                tr.readWav(basedir+clip)
                subsamples = tr.getSubsamples()
                framerate = tr.getFramerate()

                if self.verbosity > 1: print "Loading clip %s (isSignal: %i) ==> %i subsamples" % (clip, isSignal, len(subsamples))

                for ss in subsamples:
                    duration = self.getSampleDuration(ss, framerate) 
                    if isSignal: self.keywordDurations.append(duration)

                    self.YXtot.append( self.getFeatures(ss,framerate,isSignal) )
                    fnames.append(clip)
                    durations.append(duration)

        self.YXtot = np.array(self.YXtot)

        self.keywordDurations = np.array(self.keywordDurations)

        outputname = "%simagedata_%i_%i.npy" % (savedir,self.Nfreq,self.Ntime)
        outputname_meta = "%smetadata_%i_%i.npy" % (savedir,self.Nfreq,self.Ntime)
        np.save(outputname, self.YXtot)
        np.save(outputname_meta, self.keywordDurations)
        if self.verbosity > 1: print "made %s and %s" % (outputname, outputname_meta)

        idx_test, YXtest = self.trainAndTest()

        return np.array(fnames)[idx_test], np.array(durations)[idx_test], YXtest
def Preprocess(data):
               
    if (args.events_number != -1): data = data.head(args.events_number)
       
    print('Data successfully acquired!')
    print('Total hits acquired: ' + str(data.shape[0]))

    # Triggers avaiable: 139 (mean-time), 0 (triggerless)
    events = Trigger(args.trigger).Get_Final_Dataframe(data)

    if args.events_file: 
        print('Creating csv output file...')
        events.to_csv('events_dataframe_' + args.events_file + '.csv')
        print('Creating events output file (txt)...')
        Write_Events_tofile(events,args.events_file + '.txt')
Example #8
0
 def create_trigger(cls, name):
     trigger = Trigger()
     cls.__triggers.append(trigger)
     id = len(cls.__triggers) - 1
     if name != None:
         cls.__trigger_name_dict[name] = id
     return id
Example #9
0
 def buildTriggers(self, level, triggerNPs):
     for np in triggerNPs:
         callbackName = np.getTag("callback")
         onlyOnce = np.getTag("onlyOnce") == "True"
         active = np.getTag("active") == "True"
         trigger = Trigger(callbackName, np, onlyOnce, active)
         self.triggers.append(trigger)
Example #10
0
 def __init__(self):
     self.controller = maestro.Controller('COM3')
     self.yaw_motor = Motor(self.controller,
                            self.YAW_CHANNEL,
                            name='yaw',
                            offset_angle=10)
     self.pitch_motor = Motor(self.controller,
                              self.PITCH_CHANNEL,
                              name='pitch',
                              max_angle=20,
                              offset_angle=0)
     self.trigger = Trigger(self.controller,
                            self.TRIGGER_CHANNEL,
                            name='trigger',
                            neutral_pulse=1880 * 4,
                            pulse_travel=2080 * 4)
Example #11
0
def bushido(value):
    if isinstance(value, int): txt = "Bushido %d" % value
    else: txt = "Bushido X"

    def effects(controller, source):
        yield NoTarget()
        value = int(value)
        until_end_of_turn(source.augment_power_toughness(value, value))
        yield

    ability = TriggeredAbility([
        Trigger(BlockerDeclaredEvent(), sender_match),
        Trigger(AttackerBlockedEvent(), sender_match)
    ],
                               effects,
                               txt=txt,
                               keyword='bushido')
    ability.bushido_value = value
    return ability
Example #12
0
class CardStaticAbility(StaticAbility):
    def __init__(self, effects, zone="battlefield", txt='', keyword=''):
        super(CardStaticAbility, self).__init__(effects,
                                                zone=zone,
                                                txt=txt,
                                                keyword=keyword)
        # XXX The zone is not quite right, for attached static abilities that can
        # attach to something out of the battlefield
        self.control_changed = Trigger(
            ControllerChanged(),
            sender="source")  # card with ability changed controller

    def _enable(self):
        super(CardStaticAbility, self)._enable()
        self.control_changed.setup_trigger(self.source,
                                           self.new_controller,
                                           priority=CONTINUOUS_PRIORITY)
        self.effect_tracking = [
            combine(*removal_func)
            if isinstance(removal_func, tuple) else removal_func
            for removal_func in self.effect_generator(self.source)
        ]

    def _disable(self):
        super(CardStaticAbility, self)._disable()
        self.control_changed.clear_trigger()
        for remove in self.effect_tracking:
            remove()
        self.effect_tracking = []

    def leaving(self, card):
        # XXX Don't remove the effect since it's part of LKI
        self.effect_tracking = []

    def new_controller(self, original):
        for remove in self.effect_tracking:
            remove()
        self.effect_tracking = [
            combine(*removal_func)
            if isinstance(removal_func, tuple) else removal_func
            for removal_func in self.effect_generator(self.source)
        ]
Example #13
0
 def create_trigger(self,
                    name,
                    accelerator="",
                    description="",
                    category="",
                    error=True,
                    removable=True):
     from Trigger import Trigger
     trigger = Trigger(self, name, accelerator, description, category,
                       error, removable)
     return trigger
 def __init__(self):
     self.get_apk_from_manager()
     self.trigger = Trigger.get_trigger_for(self.get_filter_tag(), self.get_package_name(), self.get_description())
     self.reporter = Reporter.get_reporter_for(self.get_filter_tag(), self.get_package_name(),
         self.get_description())
     self.analyzer = Analyzer.get_analyzer_for(self.get_filter_tag(), self.get_package_name(),
         self.get_description())
     self.emulator = Emulator.get_emulator_for(self.get_filter_tag(), self.get_package_name(),
         self.get_description())
     self.error_queue = multiprocessing.Queue()
     self.setup_device()
Example #15
0
class CardStaticAbility(StaticAbility):
    def __init__(self, effects, zone="battlefield", txt='', keyword=''):
        super(CardStaticAbility, self).__init__(effects, zone=zone, txt=txt, keyword=keyword)
        # XXX The zone is not quite right, for attached static abilities that can 
        # attach to something out of the battlefield
        self.control_changed = Trigger(ControllerChanged(), sender="source")  # card with ability changed controller
    def _enable(self):
        super(CardStaticAbility, self)._enable()
        self.control_changed.setup_trigger(self.source, self.new_controller, priority=CONTINUOUS_PRIORITY)
        self.effect_tracking = [combine(*removal_func) if isinstance(removal_func, tuple) else removal_func for removal_func in self.effect_generator(self.source)]
    def _disable(self):
        super(CardStaticAbility, self)._disable()
        self.control_changed.clear_trigger()
        for remove in self.effect_tracking: remove()
        self.effect_tracking = []
    def leaving(self, card):
        # XXX Don't remove the effect since it's part of LKI
        self.effect_tracking = []
    def new_controller(self, original):
        for remove in self.effect_tracking: remove()
        self.effect_tracking = [combine(*removal_func) if isinstance(removal_func, tuple) else removal_func for removal_func in self.effect_generator(self.source)]
Example #16
0
 def __init__(self, effects, condition, events = [], tracking="battlefield", zone="battlefield", txt=''):
     super(CardTrackingAbility, self).__init__(effects, zone, txt)
     self.enter_trigger = EnterTrigger(tracking, condition, player="any")
     self.leave_trigger = LeaveTrigger(tracking, player="any")
     self.control_changed = Trigger(ControllerChanged(), sender="source")  # card with ability changed controller
     if isinstance(events, tuple): events = list(events)
     elif not isinstance(events, list): events = [events]
     self.other_triggers = [Trigger(event) for event in [ControllerChanged()] + events] # triggers for tracked cards
     if not condition: condition = all_match
     self.condition = condition
     self.tracking = tracking
     self.events = events
Example #17
0
def main():
    while True:
        #retrieve data

        Trigger(db)

        # The alarm class, basically it checks in the database if the alarm is true or false,
        # based on that it either turns on or off the leds/buzzing
        Alarm(db)

        # makes it so it runs every second
        time.sleep(1)
Example #18
0
 def process(self, time_passed):
     GameEntity.process(self, time_passed)
     # reduce the food (1 people consume 0.1 food per second)
     self.food -= 0.1 * len(self.people_list) * time_passed / 1000
     if self.food < 0:
         self.food = 0
     # People Add
     Trigger.strike_add_people_event(self, self.world)
     # People Die
     Trigger.strike_hungry_people_event(self, self.world)
     # Remove redundant farmland
     Trigger.strike_remove_farmland_event(self, self.world)
     # Random Generate Wolf
     Trigger.strike_generate_wolf_event(self, self.world)
Example #19
0
 def __init__(self,
              effects,
              condition,
              events=[],
              tracking="battlefield",
              zone="battlefield",
              txt=''):
     super(CardTrackingAbility, self).__init__(effects, zone, txt)
     self.enter_trigger = EnterTrigger(tracking, condition, player="any")
     self.leave_trigger = LeaveTrigger(tracking, player="any")
     self.control_changed = Trigger(
         ControllerChanged(),
         sender="source")  # card with ability changed controller
     if isinstance(events, tuple): events = list(events)
     elif not isinstance(events, list): events = [events]
     self.other_triggers = [
         Trigger(event) for event in [ControllerChanged()] + events
     ]  # triggers for tracked cards
     if not condition: condition = all_match
     self.condition = condition
     self.tracking = tracking
     self.events = events
Example #20
0
def exalted():
    def condition(source, sender, attackers):
        return sender.active_player == source.controller and len(
            attackers) == 1

    def effects(controller, source, attackers):
        yield NoTarget()
        until_end_of_turn(attackers[0].augment_power_toughness(1, 1))
        yield

    return TriggeredAbility(Trigger(DeclareAttackersEvent(), condition),
                            effects,
                            zone="battlefield",
                            keyword='exalted')
Example #21
0
 def __init__(self):
     self.get_apk_from_manager()
     self.trigger = Trigger.get_trigger_for(self.get_filter_tag(),
                                            self.get_package_name(),
                                            self.get_description())
     self.reporter = Reporter.get_reporter_for(self.get_filter_tag(),
                                               self.get_package_name(),
                                               self.get_description())
     self.analyzer = Analyzer.get_analyzer_for(self.get_filter_tag(),
                                               self.get_package_name(),
                                               self.get_description())
     self.emulator = Emulator.get_emulator_for(self.get_filter_tag(),
                                               self.get_package_name(),
                                               self.get_description())
     self.error_queue = multiprocessing.Queue()
     self.setup_device()
Example #22
0
    def change_setup(self, setup):

        # Reset run configuration to its default values
        self.set_default_config()

        # Read new setup
        self.setup = setup
        if (self.read_setup() == "error"): return "error"

        # Create new set of ADC board processes (DAQ and ZSUP) handlers
        self.daq_nodes_id_list = []
        for b in self.boardid_list:
            print "Run - Configuring ADC board %d" % b
            adcboard = ADCBoard(b)
            self.configure_adcboard(adcboard)
            self.adcboard_list.append(adcboard)
            self.daq_nodes_id_list.append(adcboard.node_id)

        # Get unique list of DAQ nodes (needed to create start/stop files)
        self.daq_nodes_id_list = list(set(self.daq_nodes_id_list))

        # Store ip addresses of DAQ nodes in a dictionary
        self.daq_nodes_ip_list = {}
        for node_id in self.daq_nodes_id_list:
            self.daq_nodes_ip_list[node_id] = self.db.get_node_daq_ip(node_id)

        # Create new Trigger process handler
        self.trigger = Trigger()
        self.configure_trigger(self.trigger)

        # Create new Merger process handler
        self.merger = Merger()
        self.configure_merger(self.merger)

        # Create new set of Level1 process handlers
        for l in range(self.level1_nproc):
            print "Run - Configuring Level1 process %d" % l
            lvl1_proc = Level1(l)
            self.configure_level1(lvl1_proc)
            self.level1_list.append(lvl1_proc)

        return setup
 def __init__(self):
     logging.basicConfig(filename="/tmp/VMClient.log", level=logging.DEBUG)
     self.get_apk_from_manager()
     self.trigger = Trigger.get_trigger_for(self.get_filter_tag(),
                                            self.get_package_name(),
                                            self.get_description())
     self.reporter = Reporter.get_reporter_for(self.get_filter_tag(),
                                               self.get_package_name(),
                                               self.get_description())
     self.analyzer = Analyzer.get_analyzer_for(self.get_filter_tag(),
                                               self.get_package_name(),
                                               self.get_description())
     self.emulator = Emulator.get_emulator_for(self.get_filter_tag(),
                                               self.get_package_name(),
                                               self.get_description())
     self.error_queue = multiprocessing.Queue()
     self.setup_device()
     logging.debug("Init successful")
     logging.debug("Trigger: " + repr(self.trigger))
     logging.debug("Reporter: " + repr(self.reporter))
     logging.debug("Analyzer: " + repr(self.analyzer))
     logging.debug("Emulator: " + repr(self.emulator))
 def __init__(self, filter_id, package_name, description):
     Trigger.__init__(self, filter_id, package_name, description)
     self.throttle = 1000
     self.event_per_test = 100
Example #25
0
class CardTrackingAbility(StaticAbility):
    def __init__(self,
                 effects,
                 condition,
                 events=[],
                 tracking="battlefield",
                 zone="battlefield",
                 txt=''):
        super(CardTrackingAbility, self).__init__(effects, zone, txt)
        self.enter_trigger = EnterTrigger(tracking, condition, player="any")
        self.leave_trigger = LeaveTrigger(tracking, player="any")
        self.control_changed = Trigger(
            ControllerChanged(),
            sender="source")  # card with ability changed controller
        if isinstance(events, tuple): events = list(events)
        elif not isinstance(events, list): events = [events]
        self.other_triggers = [
            Trigger(event) for event in [ControllerChanged()] + events
        ]  # triggers for tracked cards
        if not condition: condition = all_match
        self.condition = condition
        self.tracking = tracking
        self.events = events

    def get_current(self):
        controller = self.source.controller
        zone_condition = partial(self.condition, self.source)
        if self.tracking == "battlefield":
            cards = controller.battlefield.get(zone_condition, all=True)
        else:
            zone = getattr(controller, self.tracking)
            cards = zone.get(zone_condition)
            for opponent in controller.opponents:
                opp_zone = getattr(opponent, self.tracking)
                cards.extend(opp_zone.get(zone_condition))
        return cards

    def _enable(self):
        super(CardTrackingAbility, self)._enable()
        self.effect_tracking = {}
        # Get all cards in the tracked zone
        for card in self.get_current():
            self.add_effects(card)

        self.enter_trigger.setup_trigger(self.source,
                                         self.entering,
                                         priority=CONTINUOUS_PRIORITY)
        self.leave_trigger.setup_trigger(self.source,
                                         self.leaving,
                                         priority=CONTINUOUS_PRIORITY)
        self.control_changed.setup_trigger(self.source,
                                           self.new_controller,
                                           priority=CONTINUOUS_PRIORITY)
        for trigger in self.other_triggers:
            trigger.setup_trigger(self.source,
                                  self.card_changed,
                                  priority=CONTINUOUS_PRIORITY)

    def _disable(self):
        super(CardTrackingAbility, self)._disable()
        self.enter_trigger.clear_trigger()
        self.leave_trigger.clear_trigger()
        self.control_changed.clear_trigger()
        for trigger in self.other_triggers:
            trigger.clear_trigger()

        for card in self.effect_tracking.keys():
            self.remove_effects(card)
        self.effect_tracking.clear()

    def new_controller(self, original):
        # Check all current cards, to see if they should be added or removed from the current set
        new_cards, old_cards = set(self.get_current()), set(
            self.effect_tracking)
        for card in new_cards - old_cards:
            self.add_effects(card)
        for card in old_cards - new_cards:
            self.remove_effects(card)

    def entering(self, card):
        # This is called everytime a card that matches condition enters the tracking zone
        if not card in self.effect_tracking: self.add_effects(card)

    def leaving(self, card):
        # This is called everytime a card that matches condition leaves the tracking zone
        # The card might already be removed if the tracked card is removed and this card leaves the battlefield
        # XXX Don't remove the effect since it's part of LKI
        #if card in self.effect_tracking: self.remove_effects(card)
        if card in self.effect_tracking: del self.effect_tracking[card]

    def add_effects(self, card):
        self.effect_tracking[
            card] = True  # this is to prevent recursion when the effect is called
        self.effect_tracking[card] = [
            combine(*removal_func)
            if isinstance(removal_func, tuple) else removal_func
            for removal_func in self.effect_generator(self.source, card)
        ]

    def remove_effects(self, card):
        for remove in self.effect_tracking[card]:
            remove()
        del self.effect_tracking[card]  # necessary to prevent recursion

    def card_changed(self, sender):
        tracking = sender in self.effect_tracking
        pass_condition = self.condition(self.source, sender)
        # If card is already tracked, but doesn't pass the condition, remove it
        # XXX Note the condition can't rely on any trigger data
        if not tracking and pass_condition: self.add_effects(sender)
        elif tracking and not pass_condition and not self.effect_tracking[
                sender] == True:
            self.remove_effects(sender)

    def copy(self):
        return self.__class__(self.effect_generator, self.condition,
                              self.events, self.tracking, self.zone, self.txt)
Example #26
0
class CardTrackingAbility(StaticAbility):
    def __init__(self, effects, condition, events = [], tracking="battlefield", zone="battlefield", txt=''):
        super(CardTrackingAbility, self).__init__(effects, zone, txt)
        self.enter_trigger = EnterTrigger(tracking, condition, player="any")
        self.leave_trigger = LeaveTrigger(tracking, player="any")
        self.control_changed = Trigger(ControllerChanged(), sender="source")  # card with ability changed controller
        if isinstance(events, tuple): events = list(events)
        elif not isinstance(events, list): events = [events]
        self.other_triggers = [Trigger(event) for event in [ControllerChanged()] + events] # triggers for tracked cards
        if not condition: condition = all_match
        self.condition = condition
        self.tracking = tracking
        self.events = events
    def get_current(self):
        controller = self.source.controller
        zone_condition = partial(self.condition, self.source)
        if self.tracking == "battlefield":
            cards = controller.battlefield.get(zone_condition, all=True)
        else:
            zone = getattr(controller, self.tracking)
            cards = zone.get(zone_condition)
            for opponent in controller.opponents:
                opp_zone = getattr(opponent, self.tracking)
                cards.extend(opp_zone.get(zone_condition))
        return cards
    def _enable(self):
        super(CardTrackingAbility, self)._enable()
        self.effect_tracking = {}
        # Get all cards in the tracked zone
        for card in self.get_current(): self.add_effects(card)

        self.enter_trigger.setup_trigger(self.source, self.entering, priority=CONTINUOUS_PRIORITY)
        self.leave_trigger.setup_trigger(self.source, self.leaving, priority=CONTINUOUS_PRIORITY)
        self.control_changed.setup_trigger(self.source, self.new_controller, priority=CONTINUOUS_PRIORITY)
        for trigger in self.other_triggers: trigger.setup_trigger(self.source, self.card_changed, priority=CONTINUOUS_PRIORITY)
    def _disable(self):
        super(CardTrackingAbility, self)._disable()
        self.enter_trigger.clear_trigger()
        self.leave_trigger.clear_trigger()
        self.control_changed.clear_trigger()
        for trigger in self.other_triggers: trigger.clear_trigger()

        for card in self.effect_tracking.keys(): self.remove_effects(card)
        self.effect_tracking.clear()
    def new_controller(self, original):
        # Check all current cards, to see if they should be added or removed from the current set
        new_cards, old_cards = set(self.get_current()), set(self.effect_tracking)
        for card in new_cards-old_cards:
            self.add_effects(card)
        for card in old_cards-new_cards:
            self.remove_effects(card)
    def entering(self, card):
        # This is called everytime a card that matches condition enters the tracking zone
        if not card in self.effect_tracking: self.add_effects(card)
    def leaving(self, card):
        # This is called everytime a card that matches condition leaves the tracking zone
        # The card might already be removed if the tracked card is removed and this card leaves the battlefield
        # XXX Don't remove the effect since it's part of LKI
        #if card in self.effect_tracking: self.remove_effects(card)
        if card in self.effect_tracking: del self.effect_tracking[card]
    def add_effects(self, card):
        self.effect_tracking[card] = True  # this is to prevent recursion when the effect is called
        self.effect_tracking[card] = [combine(*removal_func) if isinstance(removal_func, tuple) 
                else removal_func for removal_func in self.effect_generator(self.source, card)]
    def remove_effects(self, card):
        for remove in self.effect_tracking[card]: remove()
        del self.effect_tracking[card]   # necessary to prevent recursion
    def card_changed(self, sender):
        tracking = sender in self.effect_tracking
        pass_condition = self.condition(self.source, sender)
        # If card is already tracked, but doesn't pass the condition, remove it
        # XXX Note the condition can't rely on any trigger data
        if not tracking and pass_condition: self.add_effects(sender)
        elif tracking and not pass_condition and not self.effect_tracking[sender] == True: self.remove_effects(sender)
    def copy(self):
        return self.__class__(self.effect_generator, self.condition, self.events, self.tracking, self.zone, self.txt)
Example #27
0
def make_test_data():
    #### ADDING USER AND TRIGGERS FOR EoD
    Users.add_user('hari')
    # create a symbol
    reliance = Symbol(name='Reliance',
                      y_symbol='RELIANCE.BO',
                      g_symbol='NSE:RELIANCE')
    # create a trigger
    trigger_list = []
    trigger_list.append(
        Trigger(
            # s_symbol='RELIANCE.BO',
            symbol_obj=reliance,
            s_attribute='RSI_period_1_param_10',
            s_value='10',
            s_bias='+',
        ))
    trigger_list.append(
        Trigger(
            symbol_obj=reliance,
            s_attribute='RSI_period_1_param_20',
            s_value='10',
            s_bias='+',
        ))
    trigger_list.append(
        Trigger(
            symbol_obj=reliance,
            s_attribute='Price_',
            s_value='10',
            s_bias='+',
        ))
    # useing trigger, create a reminder
    reminder = Reminder(trigger_list)
    Users.get_by_name('hari').add_reminder(reminder)

    #### ADDING USER AND TRIGGERS FOR intraday
    Users.add_user('hari_intraday')
    # create a symbol
    asianpaint = Symbol(name='Asianpaint',
                        y_symbol='ASIANPAINT.BO',
                        g_symbol='NSE:ASIANPAINT')
    # create a trigger
    trigger_list = []
    trigger_list.append(
        Trigger(
            symbol_obj=asianpaint,
            s_attribute='RSI_period_1_param_10_symbolmode_intraday',
            s_value='10',
            s_bias='+',
        ))
    trigger_list.append(
        Trigger(
            symbol_obj=asianpaint,
            s_attribute='RSI_period_1_param_20_symbolmode_intraday',
            s_value='10',
            s_bias='+',
        ))
    trigger_list.append(
        Trigger(
            symbol_obj=asianpaint,
            s_attribute='Price_symbolmode_intraday',
            s_value='10',
            s_bias='+',
        ))
    # useing trigger, create a reminder
    reminder = Reminder(trigger_list)
    Users.get_by_name('hari_intraday').add_reminder(reminder)
Example #28
0
File: do.py Project: Amarang/navsa
import signal

import Utils as u
from Process import Processor
from Trigger import Trigger
from Parse import Parser
import config

haveLeds = config.device == "mypi"
proc = Processor()
parser = Parser()
if haveLeds:
    from Lights import Lights
    led = Lights()
    led.stop()
    tr = Trigger(verbose=True, led=led, AMBIENT_MULT = 1.9)
else:
    tr = Trigger(verbose=True)

# proc.processTrainingSet(basedir="sounds/train/", signalword="oknavsa", savedir="data/")
# proc.processTrainingSet(basedir="16khz/", signalword="oknavsa", savedir="data/")
proc.loadTrainData("data/imagedata_15_15.npy")

#if not in this range, we want to not fingerprint it to save time and trouble
lower,upper = proc.getKeywordDurationRange()
tr.setParams({"MIN_WORD_TIME": lower, "MAX_WORD_TIME": upper})

tr.setParams({"THRESHOLD": 150})
# tr.getAmbientLevels(duration=0.7)

 def __init__(self, filter_id, package_name, description):
     Trigger.__init__(self, filter_id, package_name, description)
     self.throttle = 1000
     self.event_per_test = 100
Example #30
0
 def __init__(self, effects, zone="battlefield", txt='', keyword=''):
     super(CardStaticAbility, self).__init__(effects, zone=zone, txt=txt, keyword=keyword)
     # XXX The zone is not quite right, for attached static abilities that can 
     # attach to something out of the battlefield
     self.control_changed = Trigger(ControllerChanged(), sender="source")  # card with ability changed controller