Example #1
0
 def __init__(self, teh_bot):
     Plugin.__init__(self, teh_bot)
     random.seed()
     self.command_dictionary = {
                           "choice": self.random,
                           "question": self.question,
                           "random": self.random,
                           "scale": self.scale,
                           }
     self.command_info = {
                          "question": [
                                       "  %squestion QUESTION" % self.command_prefix,
                                       "Returns a positive or a negative response to your question",
                                       ],
                          "scale":    [
                                       "  %sscale STATEMENT" % self.command_prefix,
                                       "  %sscale" % self.command_prefix,
                                       "Scales your statment in procent",
                                       "(random number between 1 and 100)",
                                       ],
                          "random":    [
                                        "  %srandom CHOICE1 CHOICE2 CHOICE3" % self.command_prefix,
                                        "  %srandom CHOICE1, CHOICE2, CHOICE3" % self.command_prefix,
                                        "  %srandom CHOICE1 or CHOICE2 or CHOICE3" % self.command_prefix,
                                        "Makes a random choice of the ones provided",
                                        "  %srandom NUMBER1 - NUMBER2" % self.command_prefix,
                                        "  %srandom NUMBER1 to NUMBER2" % self.command_prefix,
                                        "Selects a random number between the two provided",
                                        ],
                          }
Example #2
0
 def __init__(self, options):
     self.options = options
     self.results = []
     self.group_plugin = Plugin.load_plugin(options.group)
     self.flow_plugin = Plugin.load_plugin(options.flow)
     if self.flow_plugin is None:
         self.flow_plugin = FlowPlugin()
    def __init__(self, g_pool, atb_pos=(0, 0)):
        Plugin.__init__(self)
        self.g_pool = g_pool
        self.first_img = None
        self.point = None
        self.count = 0
        self.detected = False
        self.active = False
        self.pos = None
        self.r = 40.0  # radius of circle displayed
        self.ref_list = []
        self.pupil_list = []

        atb_label = "calibrate using natural features"
        self._bar = atb.Bar(
            name=self.__class__.__name__,
            label=atb_label,
            help="ref detection parameters",
            color=(50, 50, 50),
            alpha=100,
            text="light",
            position=atb_pos,
            refresh=0.3,
            size=(300, 100),
        )
        self._bar.add_button("start/stop", self.start_stop, key="c")
    def __init__(self, g_pool,atb_pos=(0,0)):
        Plugin.__init__(self)
        self.active = False
        self.detected = False
        self.g_pool = g_pool
        self.pos = None
        self.smooth_pos = 0.,0.
        self.smooth_vel = 0.
        self.sample_site = (-2,-2)
        self.counter = 0
        self.counter_max = 30
        self.candidate_ellipses = []
        self.show_edges = c_bool(0)
        self.aperture = 7
        self.dist_threshold = c_int(10)
        self.area_threshold = c_int(30)
        self.world_size = None

        self.stop_marker_found = False
        self.auto_stop = 0
        self.auto_stop_max = 30
        atb_label = "calibrate using handheld marker"
        # Creating an ATB Bar is required. Show at least some info about the Ref_Detector
        self._bar = atb.Bar(name = self.__class__.__name__, label=atb_label,
            help="ref detection parameters", color=(50, 50, 50), alpha=100,
            text='light', position=atb_pos,refresh=.3, size=(300, 100))
        self._bar.add_button("start/stop", self.start_stop, key='c')
        self._bar.add_var("show edges",self.show_edges, group="Advanced")
Example #5
0
    def __init__(self, g_pool, atb_pos=(10, 400)):
        Plugin.__init__(self)

        self.context = zmq.Context()
        self.socket = self.context.socket(zmq.PUB)
        self.address = create_string_buffer("tcp://127.0.0.1:5000", 512)
        self.set_server(self.address)

        help_str = "Pupil Message server: Using ZMQ and the *Publish-Subscribe* scheme"

        self._bar = atb.Bar(name=self.__class__.__name__,
                            label='Server',
                            help=help_str,
                            color=(50, 50, 50),
                            alpha=100,
                            text='light',
                            position=atb_pos,
                            refresh=.3,
                            size=(300, 40))
        self._bar.define("valueswidth=170")
        self._bar.add_var("server address",
                          self.address,
                          getter=lambda: self.address,
                          setter=self.set_server)
        self._bar.add_button("close", self.close)

        self.exclude_list = [
            'ellipse', 'pos_in_roi', 'major', 'minor', 'axes', 'angle',
            'center'
        ]
Example #6
0
    def execute(self, data):
        Plugin.init(self, data)
        
        self.target = data.get('in')
        output = '%s.%s' %(self.target, self.suffix)
        data['in'] = output
        
        if self.skip:
            return data
        
        io = open(self.target, 'r')
        oo = open(output, 'w')
        for i, l in enumerate(io):
            ss = l.strip().split(self.mr_delimiter)
            try:
                k = ss[0]
                v = ss[1]
            except:
                continue
            
            oo.write('%s%s%s\n' %(v, self.mr_delimiter, k))

            
        oo.close()
        io.close()



        Plugin.terminate(self, data)
        
        return data
Example #7
0
    def __init__(self,g_pool,atb_pos=(0,0)):
        Plugin.__init__(self)

        self.window_should_open = False
        self.window_should_close = False
        self._window = None
        self.fullscreen = c_bool(0)
        self.realdata = c_bool(False)
        self.x = c_float(0)
        self.y = c_float(0)
        self.blink_time = c_float(1)
        self.should_blink = False
        self.blink_start = None

        atb_label = "android coordinate plugin"
        # Creating an ATB Bar.
        self._bar = atb.Bar(name =self.__class__.__name__, label=atb_label,
            help="ref detection parameters", color=(50, 50, 50), alpha=100,
            text='light', position=atb_pos,refresh=.3, size=(300, 100))
        self._bar.add_var("real data", self.realdata)
        self._bar.add_var("X", self.x)
        self._bar.define("min=0 max=1 step=0.01", "X")
        self._bar.add_var("Y", self.y)
        self._bar.define("min=0 max=1 step=0.01", "Y")
        self._bar.add_var("blink time", self.blink_time, min=0,max=10,step=0.05,help="Simulated blink time")
        # self._bar.define("min=0 max=10000 step=50", "blink time")
        self._bar.add_button("simulate blink", self.schedule_blink)
Example #8
0
    def __init__( self, address="225.1.1.1", port=5200, interface="0.0.0.0" ):
        Plugin.__init__(self, "broadcast")

        self.address   = address
        self.port      = port
        self.interface = interface

        try:
            # Instantiate a UDP socket
            self.sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)

            # Allow address reuse
            self.sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)

            # Set the packets TTL
            self.sock.setsockopt(socket.SOL_IP, socket.IP_MULTICAST_TTL, 1)

            # Do not loop messages back to the local sockets
            self.sock.setsockopt(socket.SOL_IP, socket.IP_MULTICAST_LOOP, 0)

            # Bind to the port
            self.sock.bind(('', self.port))

            # Set the interface to perform the multicast on
            self.sock.setsockopt(socket.SOL_IP, socket.IP_MULTICAST_IF, socket.inet_aton(self.interface))

            # Apply for messages sent to the specified address
            self.sock.setsockopt(socket.SOL_IP,
                                 socket.IP_ADD_MEMBERSHIP,
                                 socket.inet_aton(self.address) + socket.inet_aton(self.interface))

            self._initialized = True

        except socket.error:
            pass
Example #9
0
 def delete(self, key):
     try:
         plugin = Plugin(key)
     except DoesNotExist:
         abort(404)
     plugin.delete(plugin.key)
     return {'result': 'success'}
Example #10
0
 def loadList( self ):
     #Return a list [imdbid, texname]
     data = Plugin.getUrl(self,'http://akas.imdb.com/chart/top')
     #print("Data: " + data)
     bs = BeautifulSoup(data,convertEntities=BeautifulSoup.HTML_ENTITIES)
     if bs is None:
         print("Fail to read imdb toplist")
         return None
         
     tables = bs.findAll('table')
     for table in tables:
         rows = table.findAll('tr')
         if len(rows) < 251:
             continue
         ret = []
         i = iter(rows);
         next(i) #Ignore first row with the names.
         h = HTMLParser.HTMLParser()
         for row in i:
             link = row.find('a',href=True)
             #TODO: I am probably doing something wrong with beautifulsoup
             name = h.unescape(link.getText())
             imdb_id = Plugin.iMDBlink(self, link['href'])
             ret.append([name,imdb_id])
         return ret
     return None
    def __init__(self, global_calibrate,shared_pos,screen_marker_pos,screen_marker_state,atb_pos=(0,0)):
        Plugin.__init__(self)
        self.active = False
        self.detected = False
        self.publish = False
        self.global_calibrate = global_calibrate
        self.global_calibrate.value = False
        self.shared_pos = shared_pos
        self.pos = 0,0 # 0,0 is used to indicate no point detected
        self.smooth_pos = 0.,0.
        self.smooth_vel = 0.
        self.sample_site = (-2,-2)
        self.counter = 0
        self.counter_max = 30
        self.candidate_ellipses = []
        self.show_edges = c_bool(0)
        self.aperture = c_int(7)
        self.dist_threshold = c_int(10)
        self.area_threshold = c_int(30)


        atb_label = "calibrate using handheld marker"
        # Creating an ATB Bar is required. Show at least some info about the Ref_Detector
        self._bar = atb.Bar(name = self.__class__.__name__, label=atb_label,
            help="ref detection parameters", color=(50, 50, 50), alpha=100,
            text='light', position=atb_pos,refresh=.3, size=(300, 100))
        self._bar.add_button("start", self.start, key='c')
Example #12
0
 def delete(self, key):
     try:
         plugin = Plugin(key)
     except DoesNotExist:
         abort(404)
     plugin.delete(plugin.key)
     return {'result': 'success'}
    def __init__(self,g_pool,atb_pos=(0,0)):
        Plugin.__init__(self)
        self.collect_new = False
        self.calculated = False
        self.obj_grid = _gen_pattern_grid((4, 11))
        self.img_points = []
        self.obj_points = []
        self.count = 10
        self.img_shape = None

        self.display_grid = _make_grid()


        self.window_should_open = False
        self.window_should_close = False
        self._window = None
        self.fullscreen = c_bool(0)
        self.monitor_idx = c_int(0)
        self.monitor_handles = glfwGetMonitors()
        self.monitor_names = [glfwGetMonitorName(m) for m in self.monitor_handles]
        monitor_enum = atb.enum("Monitor",dict(((key,val) for val,key in enumerate(self.monitor_names))))
        #primary_monitor = glfwGetPrimaryMonitor()

        atb_label = "estimate camera instrinsics"
        # Creating an ATB Bar is required. Show at least some info about the Ref_Detector
        self._bar = atb.Bar(name =self.__class__.__name__, label=atb_label,
            help="ref detection parameters", color=(50, 50, 50), alpha=100,
            text='light', position=atb_pos,refresh=.3, size=(300, 100))
        self._bar.add_var("monitor",self.monitor_idx, vtype=monitor_enum)
        self._bar.add_var("fullscreen", self.fullscreen)
        self._bar.add_button("  show pattern   ", self.do_open, key='c')
        self._bar.add_button("  Capture Pattern", self.advance, key="SPACE")
        self._bar.add_var("patterns to capture", getter=self.get_count)
Example #14
0
    def __init__(self,
                 answers,
                 APP,
                 dryrun=False,
                 debug=False,
                 stop=False,
                 answers_format=ANSWERS_FILE_SAMPLE_FORMAT,
                 **kwargs):

        self.debug = debug
        self.dryrun = dryrun
        self.stop = stop
        self.kwargs = kwargs

        if "answers_output" in kwargs:
            self.answers_output = kwargs["answers_output"]

        if os.environ and "IMAGE" in os.environ:
            self.app_path = APP
            APP = os.environ["IMAGE"]
            del os.environ["IMAGE"]
        elif "image" in kwargs:
            logger.warning("Setting image to %s" % kwargs["image"])

            self.app_path = APP
            APP = kwargs["image"]
            del kwargs["image"]

        self.kwargs = kwargs

        if APP and os.path.exists(APP):
            self.app_path = APP
        else:
            if not self.app_path:
                self.app_path = os.getcwd()
            install = Install(answers,
                              APP,
                              dryrun=dryrun,
                              target_path=self.app_path,
                              answers_format=answers_format)
            install.install()
            printStatus("Install Successful.")

        self.nulecule_base = Nulecule_Base(target_path=self.app_path,
                                           dryrun=dryrun,
                                           file_format=answers_format)
        if "ask" in kwargs:
            self.nulecule_base.ask = kwargs["ask"]

        workdir = None
        if "workdir" in kwargs:
            workdir = kwargs["workdir"]

        self.utils = Utils(self.app_path, workdir)
        if "workdir" not in kwargs:
            kwargs["workdir"] = self.utils.workdir

        self.answers_file = answers
        self.plugin = Plugin()
        self.plugin.load_plugins()
    def __init__(self,data):
        # call the plugin basic initializations
        Plugin.__init__(self,data)

        # set the name of your plugin
        self.setName("end_optimum_value_kruskal",
        "Make non-parametric over ALL tests.")
Example #16
0
	def __init__(self):
		Plugin.__init__(self)
		self.dispatcher = Dispatcher()
		self.dispatcher.define('learn',  self.cmdDefine, access='member', argc=2)
		self.dispatcher.define('define', self.cmdDefine, access='member', argc=2)
		self.dispatcher.define('forget', self.cmdForget, access='member', argc=1)
		self.dispatcher.define('definfo', self.cmdDefInfo, access='moderator', argc=1)
Example #17
0
    def execute(self, data):
        Plugin.init(self, data)
        
        self.target = data.get('in')
        out = '%s.reduced' %(self.target)

        io = open(self.target, 'r')
        oio = open(out, 'w')

        for i, l in enumerate(io):
            ss = l.strip().split(self.mr_delimiter)
            try:
                k = ss[0]
                v = ss[1]
            except:
                continue

            oio.write('%s%s%s\n' %(v, self.mr_delimiter, k))


        io.close()
        oio.close()
        
        data['in'] = out
        
        Plugin.terminate(self, data)
        return data
Example #18
0
    def __init__(self, g_pool, atb_pos=(10, 400), on_char_fn=None):
        Plugin.__init__(self)
        self.g_pool = g_pool
        self.on_char_fn = on_char_fn
        self.order = .9  #excecute late in the plugin list.
        self.context = zmq.Context()
        self.socket = self.context.socket(zmq.REP)
        self.address = create_string_buffer('', 512)
        self.set_server(create_string_buffer("tcp://*:50020", 512))

        help_str = "Pupil Remote using REQ RREP schema. "

        self._bar = atb.Bar(name=self.__class__.__name__,
                            label='Remote',
                            help=help_str,
                            color=(50, 50, 50),
                            alpha=100,
                            text='light',
                            position=atb_pos,
                            refresh=.3,
                            size=(300, 40))
        self._bar.define("valueswidth=170")
        self._bar.add_var("server address",
                          self.address,
                          getter=lambda: self.address,
                          setter=self.set_server)
        self._bar.add_button("close", self.close)

        self.exclude_list = [
            'ellipse', 'pos_in_roi', 'major', 'minor', 'axes', 'angle',
            'center'
        ]
Example #19
0
 def __init__(self, teh_bot):
     Plugin.__init__(self, teh_bot)
     random.seed()
     self.command_dictionary = {
         "choice": self.random,
         "question": self.question,
         "random": self.random,
         "scale": self.scale,
     }
     self.command_info = {
         "question": [
             "  %squestion QUESTION" % self.command_prefix,
             "Returns a positive or a negative response to your question",
         ],
         "scale": [
             "  %sscale STATEMENT" % self.command_prefix,
             "  %sscale" % self.command_prefix,
             "Scales your statment in procent",
             "(random number between 1 and 100)",
         ],
         "random": [
             "  %srandom CHOICE1 CHOICE2 CHOICE3" % self.command_prefix,
             "  %srandom CHOICE1, CHOICE2, CHOICE3" % self.command_prefix,
             "  %srandom CHOICE1 or CHOICE2 or CHOICE3" %
             self.command_prefix,
             "Makes a random choice of the ones provided",
             "  %srandom NUMBER1 - NUMBER2" % self.command_prefix,
             "  %srandom NUMBER1 to NUMBER2" % self.command_prefix,
             "Selects a random number between the two provided",
         ],
     }
Example #20
0
 def handle(self, client, msg):
   token = msg['body'].split(' ')
   
   try:
     if token[0] == '+':
       Channel.channels[token[1]].plugins.append(token[2])
       
       msg.reply("Plugin {0} in {1} has beend activated".format(token[2], token[1])).send()
   
     elif token[0] == '-':
       Channel.channels[token[1]].plugins.remove(token[2])
       
       msg.reply("Plugin {0} in {1} has beend deactivated".format(token[2], token[1])).send()
     
     elif token[0] == 'reload':
       Plugin.plugins = []
       Plugin.load_all()
       
       msg.reply("Plugins reloaded!").send()
       
     elif token[0] == 'list':
       plugins = []
       
       for p in Plugin.plugins:
         plugins.append(p.name)
       
       msg.reply("Plugins loaded: {0}".format(', '.join(plugins))).send()
       
     elif token[0] == 'active':
       msg.reply("Plugins active in {0}: {1}".format(Channel.channels[token[1]].jid, ', '.join(Channel.channels[token[1]].plugins))).send()
       
   except:
     pass
Example #21
0
    def __init__(self):
        logging.debug('Plugin manager initializing')

        # This will be set later, unable to activate plugins untill set
        self.config = None

        self.plugins = {}
        self.plugin_bases = {}
        for plugin_base in Plugin.__subclasses__():
            plugin_name = plugin_base.__name__
            self.plugin_bases[plugin_name] = plugin_base
            self.plugins[plugin_name] = []

        logging.debug('Searching for plugins')

        plugins_found = self.find_plugins(Plugin.__subclasses__())

        for i, plugin_base in enumerate(Plugin.__subclasses__()):
            plugin_type = plugin_base.__name__

            for plugin in plugins_found[i]:
                self.plugins[plugin_type].append(plugin)

        # list of active plugins
        self.active = {}
        for key in self.plugins:
            self.active[key] = []
Example #22
0
    def execute(self, data):
        Plugin.init(self, data)

        self.target = data.get('in')

        if not self.target:
            return data

        out = '%s.%s' %(self.target, self.suffix)
        data['in'] = out
        
        oio = open(out, 'w')
        io = open(self.target, 'r')
        for i, l in enumerate(io):
            ss = l.strip().split(self.mr_delimiter)
            
            k = ss[0]
            vs = ss[1]
            
            oio.write('%s%s1\n' %(vs, self.mr_delimiter))
            
        io.close()
        
        Plugin.terminate(self, data)
        
        return data
    def __init__(self, g_pool, atb_pos=(0, 0)):
        Plugin.__init__(self)
        self.active = False
        self.detected = False
        self.g_pool = g_pool
        self.pos = None
        self.smooth_pos = 0., 0.
        self.smooth_vel = 0.
        self.sample_site = (-2, -2)
        self.counter = 0
        self.counter_max = 30
        self.candidate_ellipses = []
        self.show_edges = c_bool(0)
        self.aperture = 7
        self.dist_threshold = c_int(10)
        self.area_threshold = c_int(30)
        self.world_size = None

        self.stop_marker_found = False
        self.auto_stop = 0
        self.auto_stop_max = 30
        atb_label = "calibrate using handheld marker"
        # Creating an ATB Bar is required. Show at least some info about the Ref_Detector
        self._bar = atb.Bar(name=self.__class__.__name__,
                            label=atb_label,
                            help="ref detection parameters",
                            color=(50, 50, 50),
                            alpha=100,
                            text='light',
                            position=atb_pos,
                            refresh=.3,
                            size=(300, 100))
        self._bar.add_button("start/stop", self.start_stop, key='c')
        self._bar.add_var("show edges", self.show_edges, group="Advanced")
Example #24
0
def plugin_delete(key):
    message = None
    if request.method == 'POST':
        show_form = False
        try:
            plugin = Plugin(key)
            title = 'Plugin {} version {} deleted'.format(plugin.name, plugin.version)
            plugin.delete(key)
            log("Plugin %s has been deleted" % key)
        except DoesNotExist:
            return render_error('<b>{}</b> does not exists'.format(key))
    else:
        try:
            plugin = Plugin(key)
            title = 'Confirm deletion of Plugin {} version {}?'.format(plugin.name, plugin.version)
            show_form = True
            log("Plugin %s deletion confirmation asked" % key)
        except DoesNotExist:
            return render_error('{} does not exists'.format(key))

    return render_template('delete.html',
                           title=title,
                           plugin=plugin,
                           show_form=show_form,
                           message=message)
Example #25
0
def make_plugin(config):
    smtp_config = SmtpConfig(config)

    p = Plugin()
    p.username = smtp_config.username
    p.sendmail = SmtpSender(smtp_config)
    return p
Example #26
0
	def onLoad(self, bot):
		Plugin.onLoad(self, bot)
		self._users = bot.getDb().table('users')
		self._userData = {}
		for row in self._users.getAll():
			self._userData[row['mask']] = row
		self._loadUsers()
Example #27
0
    def __init__(self, g_pool, atb_pos=(0, 0)):
        Plugin.__init__(self)
        self.g_pool = g_pool
        self.active = False
        self.detected = False
        self.screen_marker_state = 0
        self.screen_marker_max = 70  # maximum bound for state
        self.active_site = 0
        self.sites = []
        self.display_pos = None
        self.on_position = False

        self.candidate_ellipses = []
        self.pos = None

        self.show_edges = c_bool(0)
        self.dist_threshold = c_int(5)
        self.area_threshold = c_int(20)

        self.world_size = None

        self._window = None
        self.window_should_close = False
        self.window_should_open = False
        self.fullscreen = c_bool(1)
        self.monitor_idx = c_int(0)
        monitor_handles = glfwGetMonitors()
        self.monitor_names = [glfwGetMonitorName(m) for m in monitor_handles]
        monitor_enum = atb.enum(
            "Monitor",
            dict(((key, val) for val, key in enumerate(self.monitor_names))))
        #primary_monitor = glfwGetPrimaryMonitor()
        self.frame = None
        self.timebase = 0

        atb_label = "calibrate on screen"
        # Creating an ATB Bar is required. Show at least some info about the Ref_Detector
        self._bar = atb.Bar(name=self.__class__.__name__,
                            label=atb_label,
                            help="ref detection parameters",
                            color=(50, 50, 50),
                            alpha=100,
                            text='light',
                            position=atb_pos,
                            refresh=.3,
                            size=(300, 90))
        self._bar.add_var("monitor", self.monitor_idx, vtype=monitor_enum)
        self._bar.add_var("fullscreen", self.fullscreen)
        self._bar.add_button("  start calibrating  ", self.start, key='c')

        self._bar.add_var("show edges",
                          self.show_edges,
                          group="Detector Variables")
        self._bar.add_var("area threshold",
                          self.area_threshold,
                          group="Detector Variables")
        self._bar.add_var("eccetricity threshold",
                          self.dist_threshold,
                          group="Detector Variables")
Example #28
0
 def __init__(self):
     Plugin.load()
     self.allowed_filetypes = []
     self.allowed_formats = []
     for p, p_class in Plugin.registered.items():
         print("Registered output plugin type %s" % p)
         self.allowed_filetypes.append(p_class.template_file_extension)
         self.allowed_formats.append(p.split('Resume')[0])
Example #29
0
    def testPluginReload(self):
        "Make sure the plugin classes are only loaded once."
        for i in range(1,5):
            self.factory.load_plugins()

        plugin_set = Set(Plugin.__subclasses__())

        self.assertEquals(len(plugin_set), len(Plugin.__subclasses__()))
Example #30
0
 def get_datums(self, datum_filter, datums=None):
     datums_filtered = {}
     if datums is None:
         for plugin_name, plugin in self.plugins.items():
             plugin.datums_filter_get(datums_filtered, datum_filter)
     else:
         Plugin.datums_filter(datums_filtered, datum_filter, datums)
     return datums_filtered
Example #31
0
    def __init__(self, plugin_name, config=None, object_group=None):
        Thread.__init__(self, name=plugin_name)
        Plugin.__init__(self, config=config, object_group=object_group, plugin_name=plugin_name)

        self._run_lock    = Lock()
        self._running     = False
        self.logger       = logging.getLogger('allspark.' + plugin_name)
        self.daemon       = True  # thread dies with program
    def __init__(self,data):
        # call the plugin basic initializations
        Plugin.__init__(self,data)

        # set the name of your plugin
        self.setName("iteration_all_value_quantilebox",
        "For each Test, plot the sequence of iterations (for any run) as a set \
        of quantile boxes. So we have one graphic for each Test.")
Example #33
0
 def __init__ (self):
     Plugin.load()
     self.allowed_filetypes = []
     self.allowed_formats = []
     for p, p_class in Plugin.registered.items():
         print("Registered output plugin type %s" % p)
         self.allowed_filetypes.append(p_class.template_file_extension)
         self.allowed_formats.append(p.split('Resume')[0])
    def __init__(self,data):
        # call the plugin basic initializations
        Plugin.__init__(self,data)

        # set the name of your plugin
        self.setName("end_optimum_value_successrate",
        "Plot the graph of success rates, considering a Test as a success when \
        the given precision of the problem is reached.")
    def __init__(self,data):
        # call the plugin basic initializations
        Plugin.__init__(self,data)

        # set the name of your plugin
        self.setName("iteration_all_value_median_logarithmic",
        "Convergence graph over iterations : plot median error of each run for \
        a given iteration, using logarithmic scale.")
Example #36
0
    def __init__(self, session_str, fps, img_shape, shared_record, eye_tx):
        Plugin.__init__(self)
        self.session_str = session_str
        self.base_path = os.path.join(os.path.abspath(__file__).rsplit('pupil_src', 1)[0], "recordings")
        self.shared_record = shared_record
        self.frame_count = 0
        self.timestamps = []
        self.eye_tx = eye_tx

        self.start_time = time()
        # set up base folder called "recordings"
        try:
            os.mkdir(self.base_path)
        except:
            print "recordings folder already exists, using existing."

        session = os.path.join(self.base_path, self.session_str)
        try:
            os.mkdir(session)
        except:
            print "recordings session folder already exists, using existing."

        # set up self incrementing folder within session folder
        counter = 0
        while True:
            self.path = os.path.join(self.base_path, session, "%03d/" % counter)
            try:
                os.mkdir(self.path)
                break
            except:
                print "We dont want to overwrite data, incrementing counter & trying to make new data folder"
                counter += 1

        self.meta_info_path = os.path.join(self.path, "info.csv")

        with open(self.meta_info_path, 'w') as f:
            f.write("Pupil Recording Name:\t"+self.session_str+ "\n")
            f.write("Start Date: \t"+ strftime("%d.%m.%Y", localtime(self.start_time))+ "\n")
            f.write("Start Time: \t"+ strftime("%H:%M:%S", localtime(self.start_time))+ "\n")



        video_path = os.path.join(self.path, "world.avi")
        self.writer = cv2.VideoWriter(video_path, cv2.cv.CV_FOURCC(*'DIVX'), fps, (img_shape[1], img_shape[0]))
        self.height = img_shape[0]
        self.width = img_shape[1]
        # positions path to eye process
        self.shared_record.value = True
        self.eye_tx.send(self.path)

        atb_pos = (10, 540)
        self._bar = atb.Bar(name = self.__class__.__name__, label='REC: '+session_str,
            help="capture recording control", color=(220, 0, 0), alpha=150,
            text='light', position=atb_pos,refresh=.3, size=(300, 80))
        self._bar.rec_name = create_string_buffer(512)
        self._bar.add_var("rec time",self._bar.rec_name, getter=lambda: create_string_buffer(self.get_rec_time_str(),512), readonly=True)
        self._bar.add_button("stop", self.stop_and_destruct, key="s", help="stop recording")
        self._bar.define("contained=true")
Example #37
0
    def __init__(self, g_pool):
        """ Constructor. """
        Plugin.__init__(self, g_pool)

        # TODO check if this blocks too long for long recordings
        g_pool.odometry_bisector = self.init_bisector(g_pool.rec_dir)
        logger.info("Loaded odometry data")

        self.extrinsics = self.load_extrinsics(g_pool.rec_dir)
Example #38
0
class Main:
    @staticmethod
    def send_data(sock: SCTSock, code: ErrorCodes, data=None):
        sock.send_data({"res": code, "data": data})
        sock.close()

    def __init__(self, threads:int=20, listener_timeout:int=600, request_timeout:int=50):
        self._request_timout = request_timeout

        signal.signal(signal.SIGTERM, self.stop)

        self._pool = multiprocessing.pool.ThreadPool(threads + 1)
        self._lock = multiprocessing.Lock()

        self._plugin = Plugin()
        self._timeout = Timeout(self.stop, listener_timeout)
        self._connections = Connections(threads)
        self._listener = Listener(self.handle_connection)
        self._listener.run()

    def stop(self, signum:int=0, frame=None):
        self._timeout.stop()
        self._listener.close()
        self._connections.apply(lambda con: self.send_data(con, ErrorCodes.listener_timeout))
        self._pool.close()

    def handle_connection(self, sock: SCTSock):
        self._pool.apply_async(self._handle_connection_thread, [sock])

    def _handle_connection_thread(self, sock: SCTSock):
        try:
            with ConnectionsWrapper(sock, self._connections):
                self._timeout.reset()
                with self._lock:
                    version = sock.recv().payload
                    if not self._plugin.checkVersion(version):
                        sock.send_init("init")
                        data = sock.recv().payload
                        self._plugin.setSettings(version, data)
                sock.send_init("data")
                con_pool = multiprocessing.pool.ThreadPool(1)
                data = sock.recv().payload
                result = con_pool.apply_async(self._plugin.exec, [data]).get(
                    self._request_timout
                )
                con_pool.close()
                self.send_data(sock, ErrorCodes.none, result)
        except multiprocessing.TimeoutError:
            self.send_data(sock, ErrorCodes.execution_timeout)
        except TooManyConnectionsError:
            self.send_data(sock, ErrorCodes.too_many_connections)
        except Exception as e:
            traceback = get_traceback(e)
            self.send_data(sock, ErrorCodes.exception, traceback)
            print(traceback)
        finally:
            sock.close()
    def __init__(self,data):
        # call the plugin basic initializations
        Plugin.__init__(self,data)

        # set the name of your plugin
        self.setName("end_optimum_solution_histogram2D","The positions distribution of optimums, in a 2D space. Use PCA if dimensions > 2..")
        
        # eigen vectors weight for the tests
        self.__eigenv = []
    def __init__(self,data):
        # call the plugin basic initializations
        Plugin.__init__(self,data)

        # set the name of your plugin
        self.setName("end_optimum_solution_points","Plot optima and the optimum in their neighborhood plan, PCA used if dimension > 2")
        
        # eigen vectors weight for the tests
        self.__eigenv = []
    def __init__(self,data):
        # call the plugin basic initializations
        Plugin.__init__(self,data)

        # set the name of your plugin
        self.setName("iteration_optimum_value_quantilebox",
        "For each Test, plot the sequence of iterations (for any run) as a set \
        of quantile boxes, instead of showing box for any point of the iteration,\
        we only select the optimum for each run.")
Example #42
0
 def __init__(self):
     #Plugin.load("plugins/")
     script_dir = os.path.dirname(os.path.realpath(sys.argv[0]))
     Plugin.load(os.path.join(script_dir, "plugins"))
     self.allowed_filetypes = []
     self.allowed_formats = []
     for p, p_class in Plugin.registered.items():
         print("Registered output plugin type %s" % p)
         self.allowed_filetypes.append(p_class.template_file_extension)
         self.allowed_formats.append(p.split('Resume')[0])
Example #43
0
 def __init__(self, teh_bot):
     Plugin.__init__(self, teh_bot)
     self.command_dictionary_only_priv_msg_to_bot = {
         "help": self.help,
     }
     self.command_info_only_priv_msg_to_bot = {
         "help": [
             "  %shelp" % self.command_prefix,
             "Shows information about the commands that the bot understands",
         ],
     }
    def __init__(self, parent):
        Plugin.__init__(self)

        self._parent = parent
        self._neighborhood = None
        self._title = _('My Turtle Art session')
        self._bundle_id = "org.laptop.TurtleArt"
        # This could be hashed from the file path (if resuming)
        self._activity_id = "1234567"
        self._nick = ""
        self._setup_has_been_called = False
Example #45
0
    def __init__(self, plugin_name, config=None, object_group=None):
        Thread.__init__(self, name=plugin_name)
        Plugin.__init__(self,
                        config=config,
                        object_group=object_group,
                        plugin_name=plugin_name)

        self._run_lock = Lock()
        self._running = False
        self.logger = logging.getLogger('allspark.' + plugin_name)
        self.daemon = True  # thread dies with program
Example #46
0
 def initConsoleMode(self):
     if self.metaconfig:
         try:
             mode = edfmeta.parse_consolemode(self.metaconfig)
             self.consolemode = util.convert_consolemode(mode)
         except expat.ExpatError:
             # Pass here because we printed something while parsing the
             # invalid file, but we want execution to continue
             pass
     else:
         Plugin.initConsoleMode(self)
Example #47
0
def plugin_download(key, package_name):
    try:
        plugin = Plugin(key)
        plugin.incr_downloads()
        response = make_response(plugin.blob)
        response.headers['Content-Type'] = 'application/zip'
        response.headers['Content-Disposition'] = \
            'inline; filename=%s.zip' % package_name
        log("Plugin %s downloaded" % key)
        return response
    except DoesNotExist:
        return render_error('<b>{}</b> does not exists'.format(key))
Example #48
0
    def __init__(self, threads:int=20, listener_timeout:int=600, request_timeout:int=50):
        self._request_timout = request_timeout

        signal.signal(signal.SIGTERM, self.stop)

        self._pool = multiprocessing.pool.ThreadPool(threads + 1)
        self._lock = multiprocessing.Lock()

        self._plugin = Plugin()
        self._timeout = Timeout(self.stop, listener_timeout)
        self._connections = Connections(threads)
        self._listener = Listener(self.handle_connection)
        self._listener.run()
Example #49
0
def plugin_test():
    plugin = Plugin()
    plugin.import_folder('/home/floeuser/floe/dev/plugins')
    
    for name in plugin.list():
        print(name)
    print(plugin.call('func1'))
    plugin.call('func2', 'pos arg 1', 'pos arg 2', kwarg1='kwarg1', kwarg2='kwarg2', kwarg3='kwarg3')
    print(plugin.call('func3'))
    print(plugin.call('func4'))
Example #50
0
    def testPluginsPresent(self):

        plugins = Plugin.get_plugins('GeoHealthCheck.probe.Probe')
        for plugin in plugins:
            plugin = Factory.create_obj(plugin)
            self.assertIsNotNone(plugin)

            # Must have run_request method
            self.assertIsNotNone(plugin.run_request)

        plugins = Plugin.get_plugins('GeoHealthCheck.check.Check')
        for plugin in plugins:
            plugin = Factory.create_obj(plugin)
            self.assertIsNotNone(plugin)
            # Must have perform method
            self.assertIsNotNone(plugin.perform)

        plugins = Plugin.get_plugins(
            'GeoHealthCheck.resourceauth.ResourceAuth')
        for plugin in plugins:
            plugin = Factory.create_obj(plugin)
            self.assertIsNotNone(plugin)
            # Must have encode method
            self.assertIsNotNone(plugin.encode)

        plugins = Plugin.get_plugins('GeoHealthCheck.probe.Probe',
                                     filters=[('RESOURCE_TYPE', 'OGC:*'),
                                              ('RESOURCE_TYPE', 'OGC:WMS')])

        for plugin in plugins:
            plugin_class = Factory.create_class(plugin)
            self.assertIsNotNone(plugin_class)

            plugin_obj = Factory.create_obj(plugin)
            self.assertIsNotNone(
                plugin_obj, 'Cannot create Plugin from string %s' + plugin)

            parameters = plugin_obj.PARAM_DEFS
            self.assertTrue(
                type(parameters) is dict, 'Plugin Parameters not a dict')

            checks = plugin_obj.CHECKS_AVAIL
            self.assertTrue(type(checks) is dict, 'Plugin checks not a dict')

            # Must have run_request method
            self.assertIsNotNone(plugin_obj.run_request)

            # Must have class var RESOURCE_TYPE='OGC:WMS'
            class_vars = Factory.get_class_vars(plugin)
            self.assertIn(class_vars['RESOURCE_TYPE'], ['OGC:WMS', 'OGC:*'])
Example #51
0
    def down(self, callback, who, arg):
        """down <url> -- checks to see if the site is down."""

        if 'http://' not in arg:
            inp = 'http://' + arg
        else:
            inp = arg

        try:
            p = Plugin('wow', 'such doge')
            p.get_head(url=inp)
            return inp + ' seems to be up.'
        except:
            return inp + ' seems to be down.'
Example #52
0
 def __init__(self, files, io):
     try:
         Plugin.__init__(self, files, io)
         self.metaconfig = files[2]
         self.initTouches()
         self.initRedirection()
         self.initConsoleMode()
     except TrchError:
         # There was an error parsing the plug-in XML
         raise
     except IndexError:
         # We didn't get the right number of files
         raise
     self.procs = []
Example #53
0
 def __init__(self, teh_bot):
     Plugin.__init__(self, teh_bot)
     self.command_dictionary = {
         "stat": self.stat,
     }
     self.command_info = {
         "stat": [
             "  %sstat USER" % self.command_prefix,
             "  %sstat" % self.command_prefix,
             "Shows stats about the user",
         ],
     }
     self.user_data = self.restore_object_from_file("user_data")
     if not self.user_data:
         self.user_data = {}
Example #54
0
def get_probes_avail(resource_type=None, resource=None):
    """
    Get all available Probes with their attributes.
    :param resource_type: optional resource type e.g. OGC:WMS
    :param resource: optional Resource instance
    :return:
    """

    # Assume no resource type
    filters = None
    if resource_type:
        filters = [('RESOURCE_TYPE', resource_type),
                   ('RESOURCE_TYPE', '*:*')]

    probe_classes = Plugin.get_plugins('GeoHealthCheck.probe.Probe', filters)

    result = dict()
    for probe_class in probe_classes:
        probe = Factory.create_obj(probe_class)
        if probe:
            if resource:
                try:
                    probe.expand_params(resource)
                except Exception as err:
                    msg = 'Cannot expand plugin vars for %s err=%s' \
                          % (probe_class, str(err))
                    LOGGER.warning(msg)

            result[probe_class] = probe.get_plugin_vars()

    return result
Example #55
0
def plugin_upload():
    message = None
    if request.method == 'POST':
        # check if the post request has the file part
        if 'file' not in request.files:
            message = 'No file part'
        else:
            file = request.files['file']
            # if user does not select file, browser also
            # submit a empty part without filename
            if file.filename == '':
                message = 'No selected file'
            elif file and '.' in file.filename and \
                    file.filename.rsplit('.', 1)[1] == 'zip':
                file.filename = secure_filename(file.filename)
                # Create plugin
                try:
                    plugin = Plugin.create_from_zip(file, file.filename)
                    message = 'Plugin {} version {} created'.format(
                        plugin.name, plugin.version)
                except ValidationError as e:
                    render_error('<b>{}</b> is not valid {}'.format(key, e))
            else:
                message = 'File does not have a zip extension'
    log("Plugin upload message: %s" % message)
    return render_template('upload.html', message=message)
Example #56
0
 def get_var_names(self):
     var_names = Plugin.get_var_names(self)
     var_names.extend([
         'RESOURCE_TYPE', 'REQUEST_METHOD', 'REQUEST_HEADERS',
         'REQUEST_TEMPLATE', 'CHECKS_AVAIL'
     ])
     return var_names
Example #57
0
    def __init__(self):

        # load config
        self.config = ConfigParser.ConfigParser()

        if not self.config.read("config.ini"):
            print "Error: your config.ini could not be read"
            exit(1)

        # load plugins
        importdir.do("plugins", globals())
        self.plugins = [
            module(config=self.config) for module in Plugin.__subclasses__()
        ]

        # load required config
        self.server = self.config.get('IRC', 'server')
        self.port = int(self.config.get('IRC', 'port'))
        self.nick = self.config.get('IRC', 'nick')
        self.ircchan = self.config.get('IRC', 'ircchan').split(",")
        self.debugchan = self.config.get('IRC', 'debugchan')

        # optional config
        try:
            self.ignore = self.config.get('IRC', 'ignore').split(',')
        except (ConfigParser.NoSectionError, ConfigParser.NoOptionError):
            self.ignore = []

        try:
            self.joindelay = int(self.config.get('IRC', 'joindelay'))
        except (ConfigParser.NoSectionError, ConfigParser.NoOptionError):
            self.joindelay = 0

        self.irc = IRCBot(self.server, self.port, self.nick)
Example #58
0
 def post(self):
     data = StringIO(request.data)
     try:
         plugin = Plugin.create_from_zip(data)
     except ValidationError as e:
         return {'result': 'error', 'message': "%s" % e}
     return {'result': 'success', 'plugin': plugin.metadata}