Exemplo n.º 1
0
 def __get__(self, obj, t = None):
   if t is None:
     raise NotImplementedError # I don't know what to do here
   if obj is None:
     return new.instancemethod(self.__func__, t, type(t))
   else:
     return new.instancemethod(self.__func__, obj, t)
Exemplo n.º 2
0
def shlaunchBackground(cmd, desc = None, progressFunc = None, endFunc = None):
    """
    Follow backup process

    The progressFunc in param can follow processus via stdin and stdout.
        - progressFunc is called each time datas are emmited on stdout
        - shlaunchBackground drop process after 60 seconds on inactivity

    @param cmd: the shell command to launch
    @type cmd: str
    @param desc: description in "background action" (optional)
    @type desc: str
    @param progressFunc: callback function to follow processus evolution.
        @see: progressBackup for an example
    @type progressFunc: function
    """
    logger = logging.getLogger()
    logger.info("support.mmctools.shlaunchBackground(\""+str(cmd)+"\")")
    shProcess = shSharedProcessProtocol(cmd)
    if desc == None:
        shProcess.desc = cmd
    else:
        shProcess.desc = desc

    ProcessScheduler().addProcess(shProcess.desc, shProcess)

    if progressFunc:
        shProcess.progressCalc = instancemethod(progressFunc, shProcess, shSharedProcessProtocol)

    if endFunc:
        shProcess.processEnded = instancemethod(endFunc, shProcess, shSharedProcessProtocol)
    reactor.spawnProcess(shProcess, "/bin/sh", ['/bin/sh','-c',cmd],env=os.environ)
Exemplo n.º 3
0
def CommandLinePlugin(_name, _holderProject = None):
    """ Create a command line plugin project. """
    _sourceRootFolder = csnUtility.NormalizePath(os.path.dirname(csnProject.FindFilename(1)))
    
    # command line lib
    projectLibName = "%sLib" % _name
    projectLib = csnProject.Project(projectLibName, "dll", _sourceRootFolder)
    #project = CilabModuleProject(projectName, "dll", _sourceRootFolder)
    projectLib.AddDefinitions(["-Dmain=ModuleEntryPoint"], _private = 1 ) 
    projectLib.installSubFolder = "commandLinePlugins"
    projectLib.CMakeInsertBeforeTarget = new.instancemethod(CreateCMakeCLPPre, projectLib)
    projectLib.CMakeInsertAfterTarget = new.instancemethod(CreateCMakeCLPPost, projectLib)
    
    # command line executable
    projectAppName = _name
    projectApp = csnBuild.Project(projectAppName, "executable", _sourceRootFolder)
    projectApp.AddProjects( [projectLib] )
    projectApp.installSubFolder = "commandLinePlugins"
    # wrapper for shared libraries
    wrapperSourceFile = None
    for thirdParty in csnProject.globalCurrentContext.GetThirdPartyFolders():
        currentWrapperSourceFile = u'%s/SLICER/Slicer3/Applications/CLI/Templates/CommandLineSharedLibraryWrapper.cxx' % thirdParty
        if os.path.isfile(currentWrapperSourceFile):
            wrapperSourceFile = currentWrapperSourceFile
    if wrapperSourceFile is None:
        raise Exception("Could not find Slicer template in your thirdParty folders.")
    projectApp.AddSources( [wrapperSourceFile]  )

    # force the creation of the application project
    projectLib.AddProjects([projectApp], _dependency = 0)
    
    if not (_holderProject is None):
        _holderProject.AddProjects( [projectLib] )
    
    return projectLib
Exemplo n.º 4
0
def AddMethod(object, function, name = None):
    """
    Adds either a bound method to an instance or an unbound method to
    a class. If name is ommited the name of the specified function
    is used by default.
    Example:
      a = A()
      def f(self, x, y):
        self.z = x + y
      AddMethod(f, A, "add")
      a.add(2, 4)
      print a.z
      AddMethod(lambda self, i: self.l[i], a, "listIndex")
      print a.listIndex(5)
    """
    import new

    if name is None:
        name = function.func_name
    else:
        function = RenameFunction(function, name)

    try:
        klass = object.__class__
    except AttributeError:
        # "object" is really a class, so it gets an unbound method.
        object.__dict__[name] = new.instancemethod(function, None, object)
    else:
        # "object" is really an instance, so it gets a bound method.
        object.__dict__[name] = new.instancemethod(function, object, klass)
Exemplo n.º 5
0
    def test_0020_static_file_url(self):
        with Transaction().start(DB_NAME, USER, CONTEXT):
            self.setup_defaults()

            file_buffer = buffer('test-content')
            file = self.create_static_file(file_buffer)
            self.assertFalse(file.url)

            app = self.get_app()
            static_file_obj = self.static_file_obj
            with app.test_client() as c:
                # Patch the home page method
                def home_func(self, file_id):
                    return render_template(
                        'home.jinja',
                        static_file_obj=static_file_obj,
                        static_file_id=file_id,
                    )
                home_func = functools.partial(home_func, file_id=file.id)
                c.application.view_functions[
                    'nereid.website.home'] = new.instancemethod(
                    home_func, self.nereid_website_obj
                )
                self.nereid_website_obj.home = new.instancemethod(
                    home_func, self.nereid_website_obj
                )
                rv = c.get('/en_US/')
                self.assertTrue('/en_US/static-file/test/test.png' in rv.data)
                self.assertEqual(rv.status_code, 200)
Exemplo n.º 6
0
    def setUp(self):
        class Model(object):
            _row_data = None
            _addition_rows = None
            _removal_rows = None

            def _get_row_data(self):
                return self._row_data

            def _set_row_data(self, _row_data, addition_rows=None, removal_rows=None):
                self._row_data = _row_data
                self._addition_rows = addition_rows
                self._removal_rows = removal_rows

            _sort_order = QtCore.Qt.SortOrder.AscendingOrder
            _sort_column1 = 0
            _sort_column2 = 0

            def _sort_list(self, _row_data):
                qtui.CustomItemModel._sort_list.im_func(self, _row_data)

        class DisassemblyModule(object):
            _next_uncertain_references = None

            def get_uncertain_references_by_address(self, program_data, address):
                result = self._next_uncertain_references
                self._next_uncertain_references = None
                return result

        class DisassemblyData(object):
            pass

        self.fake_disassembly_module = fake_disassembly_module = DisassemblyModule()
        self.disassembly_data = disassembly_data = DisassemblyData()

        if False:
            class EditorState(object):
                def get_uncertain_references_by_address(self, address):
                    return fake_disassembly_module.get_uncertain_references_by_address(disassembly_data, address)

        class EditorClient(object):
            def reset_state(self):
                pass

        self.editor_client = EditorClient()
        self.editor_state = editor_state.EditorState()
        self.editor_state.register_client(self.editor_client)
        self.editor_state.get_uncertain_references_by_address.func_globals["disassembly"] = self.fake_disassembly_module

        self.uncertain_code_references_model = Model()
        self.uncertain_data_references_model = Model()

        self.code_rows = [ [1], [2], [5], [9], [10] ]
        self.uncertain_code_references_model._row_data = self.code_rows[:]
        self.data_rows = [ [3], [7], [8], [11] ]
        self.uncertain_data_references_model._row_data = self.data_rows[:]

        self.on_uncertain_reference_modification = qtui.MainWindow.on_uncertain_reference_modification.im_func
        self._remove_address_range_from_model = new.instancemethod(qtui.MainWindow._remove_address_range_from_model.im_func, self, self.__class__)
        self._add_rows_to_model = new.instancemethod(qtui.MainWindow._add_rows_to_model.im_func, self, self.__class__)
def unpickleMethod(im_name,
                    im_self,
                    im_class):
    'support function for copy_reg to unpickle method refs'
    try:
        unbound = getattr(im_class,im_name)
        if im_self is None:
            return unbound
        bound=instancemethod(unbound.im_func,
                                 im_self,
                                 im_class)
        return bound
    except AttributeError:
        log.error("Method" + im_name + "not on class" + im_class)
        assert im_self is not None,"No recourse: no instance to guess from."
        # Attempt a common fix before bailing -- if classes have
        # changed around since we pickled this method, we may still be
        # able to get it by looking on the instance's current class.
        unbound = getattr(im_self.__class__,im_name)
        log.error("Attempting fixup with" + unbound)
        if im_self is None:
            return unbound
        bound=instancemethod(unbound.im_func,
                                 im_self,
                                 im_self.__class__)
        return bound
Exemplo n.º 8
0
def make_simpleai(stage, node, timeout=1.0):
    """A stupid AI for enemies.

    Just moving around randomly.
    
    @type stage: stagescene.StageScene

    """
    node.ai_timecount=timeout * random()
    node.ai_old_pos = (node.x, node.y)
    node.is_ai_stopped = False

    def on_tick(self, interval):
        if self.is_ai_stopped:
            return

        self.ai_timecount += interval
        # XXX
        #if (self.ai_timecount < timeout
        #        and self.ai_old_pos != (self.x, self.y)):
        if (self.ai_timecount < timeout):
            return
        
        self.ai_timecount = 0.0
        self.ai_old_pos = (node.x, node.y)
        dir = ['up', 'down', 'left', 'right'][int(random() * 4)]
        self.stop()
        self.move(dir)

    def stop_ai(self):
        self.is_ai_stopped = True

    node.on_tick = instancemethod(on_tick, node)
    node.stop_ai = instancemethod(stop_ai, node)
    return node
Exemplo n.º 9
0
    def __init__(self, app, gladefile, windowname) :
        self.appmanager = app
        self.imageDatabase = app.imageDatabase
        self.appmanager.register_window(self)
        
        self.widgets=gtk.glade.XML (gladefile,windowname)
        callbacks = {}
        #find and store methods as bound callbacks

        for c in self.__class__.__bases__ :
            class_methods = c.__dict__
            for method_name in class_methods.keys():
                method = class_methods[method_name]
                if type(method) == types.FunctionType:
                    callbacks[method_name] = new.instancemethod(
                        method, self, self.__class__)
        
        class_methods = self.__class__.__dict__
        for method_name in class_methods.keys():
            method = class_methods[method_name]
            if type(method) == types.FunctionType:
                callbacks[method_name] = new.instancemethod(
                                         method, self, self.__class__)
        self.widgets.signal_autoconnect(callbacks)
        self.window = self.widgets.get_widget(windowname)
        self.window.connect('delete-event', self.on_window_delete_event);
        self.window.connect('destroy-event', self.on_window_destroy_event);
Exemplo n.º 10
0
    def __getattr__(self, attr):
        # Allow the underlying interface to provide a better implementation if desired.
        if attr in _special_getattr_names:
            raise AttributeError, attr

        ret = getattr(self.__dict__['_comobj_'], attr, None)
        if ret is not None:
            return ret
        # Do the function thing first.
        unbound_method = self.__dict__['_methods_'].get(attr, None)
        if unbound_method is not None:
            return new.instancemethod(unbound_method, self, self.__class__)

        getters = self.__dict__['_property_getters_']
        info = getters.get(attr)
        if info is not None:
            method_index, param_infos = info
            if len(param_infos)!=1: # Only expecting a retval
                raise RuntimeError, "Can't get properties with this many args!"
            args = ( param_infos, () )
            return XPTC_InvokeByIndex(self._comobj_, method_index, args)

        # See if we have a method info waiting to be turned into a method.
        # Do this last as it is a one-off hit.
        method_info = self.__dict__['_method_infos_'].get(attr, None)
        if method_info is not None:
            unbound_method = BuildMethod(method_info, self._iid_)
            # Cache it locally
            self.__dict__['_methods_'][attr] = unbound_method
            return new.instancemethod(unbound_method, self, self.__class__)

        raise AttributeError, "XPCOM component '%s' has no attribute '%s'" % (self._object_name_, attr)
Exemplo n.º 11
0
    def _configFeature(self, ftr, obj):
        global loadedFeatures

        if type(ftr) == str:
            modName, ftrName = ftr.split('.')

            ftrClsName = "%s_Feature" % ftrName

            mod = __import__('indico.tests.python.unit.%s' % modName,
                             globals(), locals(), [ftrClsName])
            ftr = mod.__dict__[ftrClsName]
        else:
            pass

        for name, func in ftr.__dict__.iteritems():
            if name.startswith('_action_'):
                setattr(obj, name[7:], new.instancemethod(func, obj, obj.__class__))

            elif name.startswith('_context_'):
                setattr(obj, name, new.instancemethod(func, obj, obj.__class__))

        ftrObj = ftr()

        if ftr not in loadedFeatures:
            ftrObj.start(obj)
            loadedFeatures.append(ftr)

        return ftrObj
Exemplo n.º 12
0
    def test_request_exception_signal(self):
        with Transaction().start(DB_NAME, USER, CONTEXT):
            self.setup_defaults()
            app = self.get_app()
            app.config['DEBUG'] = False
            recorded = []

            # Patch the home page method
            def home_func(self):
                1 // 0

            app.view_functions['nereid.website.home'] = \
                new.instancemethod(
                    home_func, self.nereid_website_obj
            )
            self.nereid_website_obj.home = new.instancemethod(
                home_func, self.nereid_website_obj
            )

            def record(sender, exception):
                recorded.append(exception)

            flask.got_request_exception.connect(record, app)
            try:
                self.assertEqual(
                    app.test_client().get('/').status_code, 500
                )
                self.assertEqual(len(recorded), 1)
                assert isinstance(recorded[0], ZeroDivisionError)
            finally:
                flask.got_request_exception.disconnect(record, app)
Exemplo n.º 13
0
    def test_template_rendered(self):

        with Transaction().start(DB_NAME, USER, CONTEXT):
            self.setup_defaults()
            app = self.get_app()

            # Patch the home page method
            def home_func(self):
                return nereid.render_template(
                    'home.jinja', whiskey=42
                )
            app.view_functions['nereid.website.home'] = \
                new.instancemethod(
                    home_func, self.nereid_website_obj
            )
            self.nereid_website_obj.home = new.instancemethod(
                home_func, self.nereid_website_obj
            )

            recorded = []

            def record(sender, template, context):
                recorded.append((template, context))

            flask.template_rendered.connect(record, app)
            try:
                app.test_client().get('/')
                self.assertEqual(len(recorded), 1)
                template, context = recorded[0]
                self.assertEqual(template.name, 'home.jinja')
                self.assertEqual(context['whiskey'], 42)
            finally:
                flask.template_rendered.disconnect(record, app)
Exemplo n.º 14
0
    def test_0020_static_file_url(self):
        with Transaction().start(testing_proxy.db_name, 1, None) as txn:
            file_id, = self.static_file_obj.search([], limit=1)
            file = self.static_file_obj.browse(file_id)
            self.assertFalse(file.url)

        app = self.get_app()
        with app.test_client() as c:
            # Patch the home page method
            def home_func(self, file_id):
                static_file_obj = Pool().get('nereid.static.file')
                return render_template(
                    'home.jinja', 
                    static_file_obj=static_file_obj,
                    static_file_id=file_id,
                )
            home_func = functools.partial(home_func, file_id=file_id)
            c.application.view_functions[
                'nereid.website.home'] = new.instancemethod(
                    home_func, self.website_obj
            )
            self.website_obj.home = new.instancemethod(
                home_func, self.website_obj
            )
            rv = c.get('/en_US/')
            self.assertTrue('/en_US/static-file/test/test.png' in rv.data)
            self.assertEqual(rv.status_code, 200)
Exemplo n.º 15
0
    def __init__(cls, name, bases, cls_dict):
        cls.use_metaclass = 1

        def fake_method(self):
            pass

        new.instancemethod(fake_method, None, cls)
Exemplo n.º 16
0
def override_replace(target, name, func, combiner=replacement, reverse=False):
    obj = target
    cls = target.__class__

    is_derived = False
    # The function is defined in the superclass (which we don't override)
    if not name in cls.__dict__:
        is_derived = True
        # Bind the call to the superclass function
        orig_func = new.instancemethod(lambda self, *args, **named: getattr(super(cls, self), name).__call__(*args,**named), obj, cls)
    else:
        orig_func = getattr(obj, name)
    if not hasattr(orig_func, "stacked"):
        stacked_func = stacked_function(orig_func, combiner=combiner, reverse=reverse)
        setattr(target, name, stacked_func)
    else: stacked_func = orig_func
    # Add the replacement effect along with the card name (in case of multiple effects)
    new_func = [new.instancemethod(func, obj, cls), name, False] #card.name, False]
    stacked_func.add_func(new_func)
    def restore(stacked_func=stacked_func):
        stacked_func.remove_func(new_func)
        if not stacked_func.stacking():
            setattr(target, name, stacked_func.funcs[0])
            del stacked_func
    func.expire = restore
    return restore
Exemplo n.º 17
0
def seek_gzip_factory(f):
    """Use this factory to produce the class so that we can do a lazy
    import on gzip.

    """
    import gzip, new

    def seek(self, offset, whence=0):
        # figure out new position (we can only seek forwards)
        if whence == 1:
            offset = self.offset + offset

        if whence not in [0, 1]:
            raise IOError, "Illegal argument"

        if offset < self.offset:
            # for negative seek, rewind and do positive seek
            self.rewind()
            count = offset - self.offset
            for i in range(count // 1024):
                self.read(1024)
            self.read(count % 1024)

    def tell(self):
        return self.offset

    if isinstance(f, str):
        f = gzip.GzipFile(f)

    f.seek = new.instancemethod(seek, f)
    f.tell = new.instancemethod(tell, f)

    return f
Exemplo n.º 18
0
def enable_router_hints():
    import new
    from django.db import DEFAULT_DB_ALIAS, router
    from landlord.conf import settings

    def _router_func(action):
        def _route_db(self, model, **hints):
            from landlord import landlord

            hints.update({settings.LANDLORD_DEFAULT_NAMESPACE_KEY: landlord.get_current_namespace()})

            chosen_db = None
            for router in self.routers:
                try:
                    method = getattr(router, action)
                except AttributeError:
                    # If the router doesn't have a method, skip to the next one.
                    pass
                else:
                    chosen_db = method(model, **hints)
                    if chosen_db:
                        return chosen_db
            try:
                return hints["instance"]._state.db or DEFAULT_DB_ALIAS
            except KeyError:
                return DEFAULT_DB_ALIAS

        return _route_db

    router.db_for_read = new.instancemethod(_router_func("db_for_read"), router, None)
    router.db_for_write = new.instancemethod(_router_func("db_for_write"), router, None)
Exemplo n.º 19
0
 def decorator(orig):
     if isinstance(orig, (new.classobj, type)):
         cls2 = orig
         class Before(object): pass
         b = Before()
         setattr(cls, "Before" + cls2.__name__, b)
         setattr(cls2, "super", b)
         for k, v in cls2.__dict__.items():
             if isinstance(v, new.function):
                 f = decorator(v)
                 setattr(b, f.func_name, f.__original__)
                 v.__original__ = f.__original__
         return cls2
     else:
         f = orig
         func_name = f.func_name
         replacement_method = new.instancemethod(f, None, cls)
         def monkeypatch(*a, **k):
             return replacement_method(*a, **k)
         f = monkeypatch
         f.func_name = func_name
         method = getattr(cls, func_name, None)
         f.__original__ = method
         setattr(cls, func_name,
                 new.instancemethod(f, None, cls))
         return f
Exemplo n.º 20
0
 def __init__(self, link, flash_type):
   self.stopped = False
   self.status = ''
   self.link = link
   self.flash_type = flash_type
   self._waiting_for_callback = False
   self._read_callback_data = []
   self.link.add_callback(ids.FLASH_DONE, self._done_callback)
   self.link.add_callback(ids.FLASH_READ, self._read_callback)
   self.ihx_elapsed_ops = 0 # N operations finished in self.write_ihx
   self.ihx_total_ops = None # Total operations in self.write_ihx call
   if self.flash_type == "STM":
     self.flash_type_byte = 0
     self.addr_sector_map = stm_addr_sector_map
     # Add STM-specific functions.
     self.__dict__['lock_sector'] = \
         new.instancemethod(_stm_lock_sector, self, Flash)
     self.__dict__['unlock_sector'] = \
         new.instancemethod(_stm_unlock_sector, self, Flash)
     self.n_sectors = STM_N_SECTORS
     self.restricted_sectors = STM_RESTRICTED_SECTORS
   elif self.flash_type == "M25":
     self.flash_type_byte = 1
     self.addr_sector_map = m25_addr_sector_map
     # Add M25-specific functions.
     self.__dict__['write_status'] = \
         new.instancemethod(_m25_write_status, self, Flash)
     self.n_sectors = M25_N_SECTORS
     self.restricted_sectors = M25_RESTRICTED_SECTORS
   else:
     raise ValueError("flash_type must be \"STM\" or \"M25\"")
Exemplo n.º 21
0
    def setup (self):
        logging.getLogger('').handlers = []

        logging.addLevelName(TRACE, 'TRACE')
        logging.addLevelName(MOREINFO, 'MOREINFO')

        if self.enabled == True:

            # setup root logger
            self.root_logger = logging.getLogger('')
            if self.file is not None:
                formatter = logging.Formatter(self.format, self.datefmt)
                handler = MyFileHandler(self.file, 'a')
                handler.setFormatter(formatter)
                self.root_logger.addHandler(handler)
            else:
                self.root_logger.addHandler(DevnullHandler())
            self.root_logger.setLevel(logging._levelNames[self.level])

            self.root_logger.trace = new.instancemethod(trace_method, self.root_logger, self.root_logger.__class__)
            self.root_logger.moreinfo = new.instancemethod(moreinfo_method, self.root_logger, self.root_logger.__class__)
            self.root_logger.__repr__ = new.instancemethod(repr_method, self.root_logger, self.root_logger.__class__)

            # setup a console logger, if enabled
            if self.console == True:
                console_fmtr = logging.Formatter(self.console_format, self.console_datefmt)
                console_hdlr = logging.StreamHandler()
                console_hdlr.setFormatter(console_fmtr)
                console_hdlr.setLevel(logging._levelNames[self.console_level])
                self.root_logger.addHandler(console_hdlr)

        self.is_setup = True
Exemplo n.º 22
0
	def __init__(self, category_algorithm, rank_by, frequency_bins = None):
		if category_algorithm == "frequency-ifos-oninstruments":
			self.category_func = lambda self, on_instruments, participating_instruments, frequency: (on_instruments, participating_instruments, self.frequency_bins[frequency])
		elif category_algorithm == "oninstruments":
			self.category_func = lambda self, on_instruments, participating_instruments, frequency: on_instruments
		else:
			raise ValueError, category_algorithm
		self.category_func = instancemethod(self.category_func, self, self.__class__)

		if rank_by == "snr":
			self.reputation_func = lambda self, snr, uncombined_ifar, likelihood: snr
		elif rank_by == "uncombined-ifar":
			# cast to float so this does the right thing when
			# we get "inf" as a string
			self.reputation_func = lambda self, snr, uncombined_ifar, likelihood: float(uncombined_ifar)
		elif rank_by == "likelihood":
			self.reputation_func = lambda self, snr, uncombined_ifar, likelihood: likelihood
		else:
			raise ValueError, rank_by
		self.rank_by = rank_by
		self.reputation_func = instancemethod(self.reputation_func, self, self.__class__)

		self.frequency_bins = frequency_bins
		self.reputations = {}
		self.cached_livetime = {}
		self.extrapolate = False
		self.extrapolation_coeffs = {}
		self.categories = []
Exemplo n.º 23
0
def setup_logging(increase_padding=False):
    """
    Setup overall logging engine and add 2 more levels of logging lower than
    DEBUG, TRACE and GARBAGE.
    """
    import logging

    if increase_padding and logging.getLoggerClass() is not Logging:
        logging.setLoggerClass(Logging)

    if not hasattr(LoggingLoggerClass, 'trace'):
        def trace(cls, msg, *args, **kwargs):
            return cls.log(5, msg, *args, **kwargs)

        logging.addLevelName(5, 'TRACE')
        LoggingLoggerClass.trace = new.instancemethod(
            trace, None, LoggingLoggerClass
        )

    if not hasattr(LoggingLoggerClass, 'garbage'):
        def garbage(cls, msg, *args, **kwargs):
            return cls.log(1, msg, *args, **kwargs)

        logging.addLevelName(1, 'GARBAGE')
        LoggingLoggerClass.garbage = new.instancemethod(
            garbage, None, LoggingLoggerClass
        )

    # Set the root logger at the lowest level possible
    logging.getLogger().setLevel(1)
Exemplo n.º 24
0
 def __init__(self, filename=None, mirror=False):
     if filename:
         self.load(filename)
     self.mirror = mirror
     self.plot_stretch = new.instancemethod(_make_plotting_func(self.stretch_density, "Stretching"), self)
     self.plot_bend = new.instancemethod(_make_plotting_func(self.bend_density, "Bending"), self)
     self.plot_height = new.instancemethod(_make_plotting_func(lambda: self.f_z, "Height"), self)
Exemplo n.º 25
0
    def __init__(self, link, flash_type, sbp_version, max_queued_ops=1):
        """
        Object representing either of the two flashes (STM/M25) on the Piksi,
        including methods to erase, program, and read.

        Parameters
        ----------
        link : sbp.client.handler.Handler
          Handler to send messages to Piksi over and register callbacks with.
        flash_type : string
          Which Piksi flash to interact with ("M25" or "STM").
        sbp_version : (int, int)
          SBP protocol version, used to select messages to send.
        max_queued_ops : int
          Maximum number of Flash read/program operations to queue in device flash.
          (0.5 * ADDRS_PER_OP + SBP packet overhead) * max_queued_ops is how much
          of the device UART RX buffer will be filled by the program/read callback
          messages. A higher value will significantly speed up flashing, but can
          result in RX buffer overflows in other UARTs if the device is receiving
          data on other UARTs.

        Returns
        -------
        out : Flash instance
        """
        self._n_queued_ops = 0
        self.max_queued_ops = max_queued_ops
        self.nqo_lock = Lock()
        self.stopped = False
        self.status = ''
        self.link = link
        self.flash_type = flash_type
        self.sbp_version = sbp_version
        # IntelHex object to store read flash data in that was read from device.
        self._read_callback_ihx = IntelHex()
        self.link.add_callback(self._done_callback, SBP_MSG_FLASH_DONE)
        self.link.add_callback(self._read_callback, SBP_MSG_FLASH_READ_RESP)
        self.ihx_elapsed_ops = 0  # N operations finished in self.write_ihx
        if self.flash_type == "STM":
            self.flash_type_byte = 0
            self.addr_sector_map = stm_addr_sector_map
            # Add STM-specific functions.
            self.__dict__['lock_sector'] = \
                new.instancemethod(_stm_lock_sector, self, Flash)
            self.__dict__['unlock_sector'] = \
                new.instancemethod(_stm_unlock_sector, self, Flash)
            self.n_sectors = STM_N_SECTORS
            self.restricted_sectors = STM_RESTRICTED_SECTORS
        elif self.flash_type == "M25":
            self.flash_type_byte = 1
            self.addr_sector_map = m25_addr_sector_map
            # Add M25-specific functions.
            self.__dict__['write_status'] = \
                new.instancemethod(_m25_write_status, self, Flash)
            self.n_sectors = M25_N_SECTORS
            self.restricted_sectors = M25_RESTRICTED_SECTORS
        else:
            raise ValueError(
                "flash_type must be \"STM\" or \"M25\", got \"%s\"" %
                flash_type)
Exemplo n.º 26
0
	def __call__( cls, *args, **kwargs ):
		instance = cls.__new__( cls )
		instance.__init__( *args, **kwargs )

		setUpMethods    = []
		tearDownMethods = []

		for _cls in reversed( cls.__mro__ ):
			setUp    = getattr( _cls, 'setUp', None )
			tearDown = getattr( _cls, 'tearDown', None )

			if setUp:
				if not len( setUpMethods ) or setUp != setUpMethods[-1]:
					setUpMethods.append( setUp )

			if tearDown:
				if not len( tearDownMethods ) or tearDown != tearDownMethods[0]:
					tearDownMethods.insert( 0, tearDown )

		def chain( methods ):
			def fun( self ):
				for method in methods:
					method( self )
			return fun

		instance.setUp    = new.instancemethod( chain( setUpMethods ), instance, cls )
		instance.tearDown = new.instancemethod( chain( tearDownMethods ), instance, cls )

		return instance 
Exemplo n.º 27
0
    def setup_wiki_handlers(self):
        """
            Have the MoinMoin formatter handle markup when it makes sense. These
            are portions of the document that do not contain reST specific
            markup. This allows these portions of the document to look
            consistent with other wiki pages.

            Setup dispatch routines to handle basic document markup. The
            hanlders dict is the html4css1 handler name followed by the wiki
            handler name.
        """
        handlers = {
            # Text Markup
            'emphasis': 'emphasis',
            'strong': 'strong',
            'literal': 'code',
            # Blocks
            'literal_block': 'preformatted',
            # Simple Lists
            # bullet-lists are handled completely by docutils because it uses
            # the node context to decide when to make a compact list
            # (no <p> tags).
            'list_item': 'listitem',
            # Definition List
            'definition_list': 'definition_list',
        }
        for rest_func, moin_func in handlers.items():
            visit_func, depart_func = self.create_wiki_functor(moin_func)
            visit_func = new.instancemethod(visit_func, self, MoinTranslator)
            depart_func = new.instancemethod(depart_func, self, MoinTranslator)
            setattr(self, 'visit_%s' % (rest_func), visit_func)
            setattr(self, 'depart_%s' % (rest_func), depart_func)
Exemplo n.º 28
0
    def __init__(self, api_token, endpoint="https://shreddr.captricity.com/api/backbone/schema", version=None):
        """
        endpoint must be the full url to the API schema document, like `http://127.0.0.1:8000/api/backbone/schema'
        api_token is the unique string associated with your account's profile which allows API access
        """
        self.api_token = api_token
        self.endpoint = endpoint
        self.parsed_endpoint = urlparse.urlparse(self.endpoint)
        self.api_version = version 
        schema_url = self.parsed_endpoint.path
        if version: schema_url = schema_url + '?version=' + version
        self.schema = self._get_data(schema_url)
        self.api_version = self.schema['version']

        for resource in self.schema['resources']:
            if "GET" in resource['allowed_request_methods']:
                read_callable = _generate_read_callable(resource['name'], resource['display_name'], resource['arguments'], resource['regex'], resource['doc'], resource['supported'])
                setattr(self, read_callable.__name__, new.instancemethod(read_callable, self, self.__class__))
            if "PUT" in resource['allowed_request_methods']:
                update_callable = _generate_update_callable(resource['name'], resource['display_name'], resource['arguments'], resource['regex'], resource['doc'], resource['supported'], resource['put_syntaxes'])
                setattr(self, update_callable.__name__, new.instancemethod(update_callable, self, self.__class__))
            if "POST" in resource['allowed_request_methods']:
                create_callable = _generate_create_callable(resource['name'], resource['display_name'], resource['arguments'], resource['regex'], resource['doc'], resource['supported'], resource['post_syntaxes'], resource['is_action'])
                setattr(self, create_callable.__name__, new.instancemethod(create_callable, self, self.__class__))
            if "DELETE" in resource['allowed_request_methods']:
                delete_callable = _generate_delete_callable(resource['name'], resource['display_name'], resource['arguments'], resource['regex'], resource['doc'], resource['supported'])
                setattr(self, delete_callable.__name__, new.instancemethod(delete_callable, self, self.__class__))
Exemplo n.º 29
0
    def __init__(self, hardware_obj):
        QObject.__init__(self)

        self.setIn = new.instancemethod(lambda self: None, self)
        self.setOut = self.setIn
        self.getState = new.instancemethod(lambda self: "unknown", self)

        self.dev = hardware_obj

        try:
            sClass = str(self.dev.__class__)
            i, j = re.search("'.*'", sClass).span()
        except BaseException:
            dev_class = sClass
        else:
            dev_class = sClass[i + 1 : j - 1]
        self.devClass = dev_class.split(".")[-1]

        # print "Type is",self.devClass
        if self.devClass == "Device":
            self.devClass = "Procedure"

        if not self.devClass in (
            "WagoPneu",
            "Shutter",
            "SpecMotorWSpecPositions",
            "Procedure",
        ):
            self.devClass = "WagoPneu"

        initFunc = getattr(self, "init%s" % self.devClass)
        initFunc()
        self.setIn = getattr(self, "setIn%s" % self.devClass)
        self.setOut = getattr(self, "setOut%s" % self.devClass)
        self.getState = getattr(self, "getState%s" % self.devClass)
Exemplo n.º 30
0
def add_filters():
    """Add filters for every choice in ItemToPush.STATUS.

    This filters are mostly useless except if you do a lot of management from
    command line"""
    constants = [c for c in dir(models.ITEM_TO_PUSH_STATUS) if c.isupper() and c not in NOT_CONSTANTS]
    for current_constant in constants:
        method_name = current_constant.lower()
        def get_filter_function(constant):
            def filter_by_status(self):
                value = getattr(models.ITEM_TO_PUSH_STATUS, constant)
                return self.filter(status=value)
            return filter_by_status
        filter_by_status = get_filter_function(current_constant)
        filter_by_status_method = instancemethod(filter_by_status, None, BaseQuerySet)
        setattr(BaseQuerySet, method_name, filter_by_status_method)

        def get_query_function(name):
            def query_by_status(self):
                method = getattr(self.get_query_set(), name)
                return method()
            return query_by_status
        query_by_status = get_query_function(method_name)
        query_by_status_method = instancemethod(query_by_status, None, BaseManager)
        setattr(BaseManager, method_name, query_by_status_method)
Exemplo n.º 31
0
def get_parser(document=None,
               namespaces=0,
               validate=0,
               external_ges=1,
               logfile=None,
               doc_factory=POM.new_document):
    import xml
    if hasattr(xml, "use_pyxml"):
        xml.use_pyxml()
    import xml.sax.sax2exts
    import xml.sax.handler
    import new
    handler = ContentHandler(document,
                             doc_factory=doc_factory,
                             logfile=logfile)
    errorhandler = ErrorHandler(logfile)
    # create parser
    parser = xml.sax.sax2exts.XMLParserFactory.make_parser()
    parser.setFeature(xml.sax.handler.feature_namespaces, namespaces)
    parser.setFeature(xml.sax.handler.feature_validation, validate)
    parser.setFeature(xml.sax.handler.feature_external_ges, external_ges)
    parser.setFeature(xml.sax.handler.feature_external_pes, 0)
    parser.setFeature(xml.sax.handler.feature_string_interning, 1)
    # set handlers
    parser.setContentHandler(handler)
    parser.setDTDHandler(handler)
    parser.setEntityResolver(handler)
    parser.setErrorHandler(errorhandler)
    # since the xml API provides some generic parser I can't just
    # subclass I have to "patch" the object in-place with this trick.
    # This is to a) make the API compatible with the HTMLParser, and b)
    # allow specifing the encoding and other headers in the request.
    parser.parse_orig = parser.parse

    def parse(self,
              url,
              data=None,
              encoding=POM.DEFAULT_ENCODING,
              useragent=None,
              accept=None):
        from pycopia.WWW import urllibplus
        fo = urllibplus.urlopen(url,
                                data,
                                encoding,
                                useragent=useragent,
                                accept=accept)
        if logfile:
            from pycopia import UserFile
            fo = UserFile.FileWrapper(fo, logfile=logfile)
        return self.parse_orig(fo)

    parser.parse = new.instancemethod(parse, parser, parser.__class__)
    return parser
Exemplo n.º 32
0
    def init_app(self):
        # TODO: ideally, this should be done by hooking body with an "onLoad".

        from __pyjamas__ import pygwt_processMetas, set_main_frame
        from __pyjamas__ import set_gtk_module
        set_gtk_module(gtk)

        main_frame = self._browser.getMainFrame()
        main_frame._callbacks = []
        main_frame.gobject_wrap = webkit.gobject_wrap
        main_frame.platform = 'webkit'
        main_frame.addEventListener = addEventListener
        main_frame.getUri = self.getUri
        main_frame.getDomDocument = new.instancemethod(getDomDocument,
                                                       main_frame)
        main_frame._addXMLHttpRequestEventListener = addXMLHttpRequestEventListener
        main_frame._addWindowEventListener = new.instancemethod(
            addWindowEventListener, main_frame)
        main_frame._alert = new.instancemethod(_alert, main_frame)
        main_frame.mash_attrib = mash_attrib
        set_main_frame(main_frame)
Exemplo n.º 33
0
    def __init__(self, parent_scope_ref):
        self._scope = parent_scope_ref

        def generatePrimitive(type_, self, text, **kwargs):
            return type_(self._scope(), text, **kwargs)

        # generate all the type factories
        import new
        for fname, type_ in self.types.iteritems():
            func = functools.partial(generatePrimitive, type_)
            setattr(self, fname, new.instancemethod(func, self,
                PrimitiveFactory))
Exemplo n.º 34
0
 def as(self, pName):
    """ obtain a representation of self with respect to some personality """
    cls = self.__class__
    err = 'illegal personality for '+str(cls) + ': ' + pName
    assert pName in cls.personalities, err
    out   = cls.personalities[pName]
    P = proxy()
    for funcname in out:
          func = out[funcname]
          func = new.instancemethod(func,self,cls)
          setattr(P, funcname, func)
    return P
    def install(self, methodIdentifier):
        """Install myself on my instance in place of this method.
        """
        oldMethod = getattr(self.instance, methodIdentifier, None)

        # XXX: this conditional probably isn't effective.
        if oldMethod is not self:
            # avoid triggering __setattr__
            self.instance.__dict__[methodIdentifier] = (
                new.instancemethod(self, self.instance,
                                   self.instance.__class__))
            self.oldMethod = (methodIdentifier, oldMethod)
Exemplo n.º 36
0
    def build_model(self):
        self.model = get_model(**self.model_args)
        ln.info("Using RMSprop with %s" %
                dict(lr=float(self.config["learning_rate"]),
                     rho=0.9,
                     epsilon=1e-08,
                     decay=0.0))
        optimizer = RMSprop(lr=float(self.config["learning_rate"]),
                            rho=0.9,
                            epsilon=1e-08,
                            decay=0.0)

        self.model.compile(optimizer=optimizer,
                           loss='categorical_crossentropy',
                           metrics=["accuracy"])
        self.model.summary()

        # hot-patch saving and loading TODO remove once this is fixed in seq2seq
        def save_weights(_self, fname, overwrite=True):
            if not overwrite and os.path.isfile(fname):
                proceed = ask_to_proceed_with_overwrite(fname)
                if not proceed:
                    return
            outf = h5py.File(fname, 'w')
            weight = _self.get_weights()
            for i in range(len(weight)):
                outf.create_dataset('weight' + str(i), data=weight[i])
            outf.close()

        def load_weights(_self, fname):
            infile = h5py.File(fname, 'r')
            weight = []
            for i in range(len(infile.keys())):
                weight.append(infile['weight' + str(i)][:])
            _self.set_weights(weight)

        self.model.save_weights = new.instancemethod(save_weights, self.model,
                                                     None)
        self.model.load_weights = new.instancemethod(load_weights, self.model,
                                                     None)
Exemplo n.º 37
0
def CommandLinePlugin(_name, _holderProject=None):
    """ Create a command line plugin project. """
    _sourceRootFolder = csnUtility.NormalizePath(
        os.path.dirname(csnProject.FindFilename(1)))

    # command line lib
    projectLibName = "%sLib" % _name
    projectLib = csnProject.Project(projectLibName, "dll", _sourceRootFolder)
    #project = CilabModuleProject(projectName, "dll", _sourceRootFolder)
    projectLib.AddDefinitions(["-Dmain=ModuleEntryPoint"], _private=1)
    projectLib.installSubFolder = "commandLinePlugins"
    projectLib.CMakeInsertBeforeTarget = new.instancemethod(
        CreateCMakeCLPPre, projectLib)
    projectLib.CMakeInsertAfterTarget = new.instancemethod(
        CreateCMakeCLPPost, projectLib)

    # command line executable
    projectAppName = _name
    projectApp = csnBuild.Project(projectAppName, "executable",
                                  _sourceRootFolder)
    projectApp.AddProjects([projectLib])
    projectApp.installSubFolder = "commandLinePlugins"
    # wrapper for shared libraries
    wrapperSourceFile = None
    for thirdParty in csnProject.globalCurrentContext.GetThirdPartyFolders():
        currentWrapperSourceFile = u'%s/SLICER/Slicer3/Applications/CLI/Templates/CommandLineSharedLibraryWrapper.cxx' % thirdParty
        if os.path.isfile(currentWrapperSourceFile):
            wrapperSourceFile = currentWrapperSourceFile
    if wrapperSourceFile is None:
        raise Exception(
            "Could not find Slicer template in your thirdParty folders.")
    projectApp.AddSources([wrapperSourceFile])

    # force the creation of the application project
    projectLib.AddProjects([projectApp], _dependency=0)

    if not (_holderProject is None):
        _holderProject.AddProjects([projectLib])

    return projectLib
    def patch_b3_admin_plugin(self):
        """
        Monkey patches the admin plugin
        """
        def new_cmd_kick(this, data, client=None, cmd=None):
            """
            <name> [<reason>] - kick a player
            <fullexactname> [<reason>] - kick an incompletely authed player
            """
            m = this.parseUserCmd(data)
            if not m:
                client.message('^7Invalid parameters')
                return False

            cid, keyword = m
            reason = this.getReason(keyword)

            if not reason and client.maxLevel < this._noreason_level:
                client.message('^1ERROR: ^7You must supply a reason')
                return False

            sclient = this.findClientPrompt(cid, client)
            if sclient:
                if sclient.cid == client.cid:
                    this.console.say(
                        self.getMessage('kick_self', client.exactName))
                    return True
                elif sclient.maxLevel >= client.maxLevel:
                    if sclient.maskGroup:
                        client.message(
                            '^7%s ^7is a masked higher level player, can\'t kick'
                            % sclient.exactName)
                    else:
                        message = this.getMessage('kick_denied',
                                                  sclient.exactName,
                                                  client.exactName,
                                                  sclient.exactName)
                        this.console.say(message)
                    return True
                else:
                    sclient.kick(reason, keyword, client)
                    return True
            elif re.match('^[0-9]+$', cid):
                # failsafe, do a manual client id kick
                this.console.kick(cid, reason, client)
            else:
                this.console.kickbyfullname(cid, reason, client)

        admin_plugin = self.getPlugin('admin')
        command = admin_plugin._commands['kick']
        command.func = new.instancemethod(new_cmd_kick, admin_plugin)
        command.help = new_cmd_kick.__doc__.strip()
Exemplo n.º 39
0
    def __getattr__(self, name):
        if name in self._symbols:
            raise AttributeError(name)

        if name in ('__members__', '__methods__'):
            raise AttributeError(name)

        if name == 'constructor':
            return PyV8.JSClassConstructor(self.__class__)

        if name == 'prototype':
            return PyV8.JSClassPrototype(self.__class__)

        prop = self.__dict__.setdefault('__properties__', {}).get(name, None)

        if prop and isinstance(prop[0], collections.Callable):
            return prop[0]()

        context = self.__class__.__dict__['context'].__get__(self, Window)

        try:
            self._symbols.add(name)
            symbol = context.eval(name)
        except:
            raise AttributeError(name)
        finally:
            self._symbols.discard(name)

        if isinstance(symbol, PyV8.JSFunction):
            _method = None

            if symbol in self._methods:
                _method = symbol.clone()

            if _method is None:
                _method = new.instancemethod(symbol, self, Window)
                #_method = symbol.__get__(self, Window)

            setattr(self, name, _method)
            context.locals[name] = _method
            return _method

        if isinstance(symbol, (thug_string,
                               bool,
                               numbers.Number,
                               datetime.datetime,
                               PyV8.JSObject)):
            setattr(self, name, symbol)
            context.locals[name] = symbol
            return symbol

        raise AttributeError(name)
Exemplo n.º 40
0
    def __call__(self, *args, **kwargs):  # @DontTrace
        '''
        Calls every registered function with the given args and kwargs.
        '''
        callbacks = self._callbacks
        if not callbacks:
            return

        # Note: There's a copy of this code in the _calculate_to_call method below. It's a copy
        # because we don't want to had a function call overhead here.
        to_call = []

        for key, info in compat.items(callbacks):  # iterate in a copy

            func_obj = info[0]
            if func_obj is not None:
                # Ok, we have a self.
                func_obj = func_obj()
                if func_obj is None:
                    # self is dead
                    del callbacks[key]
                else:
                    func_func = info[1]
                    if func_func is None:
                        to_call.append(func_obj)
                    else:
                        if compat.PY2:
                            to_call.append(
                                new.instancemethod(func_func, func_obj,
                                                   info[2]))
                        else:
                            to_call.append(new.MethodType(func_func, func_obj))

            else:
                func_func = info[1]

                # No self: either classmethod or just callable
                to_call.append(func_func)

        # let's keep the 'if' outside of the iteration...
        if not is_in_main_thread():
            for func in to_call:
                if not getattr(func, '__call_out_of_main_thread__', False):
                    raise AssertionError(
                        'Call: %s out of the main thread (and it is not marked as @not_main_thread_callback)!'
                        % (func, ))

        for func in to_call:
            try:
                func(*args, **kwargs)
            except Exception:  # Show it but don't propagate.
                sys.excepthook(*sys.exc_info())
    def replaceMethod(self, oldMethod, newFunction):
        foundIt = 0
        import new
        for cdc in self.number2cdc.values():
            for cdu in cdc.allCDU:
                method = cdu.func
                if method and method.im_func == oldMethod:
                    newMethod = new.instancemethod(newFunction, method.im_self,
                                                   method.im_class)
                    cdu.func = newMethod
                    foundIt = 1

        return foundIt
Exemplo n.º 42
0
 def loadepg(self, result, retval, extra_args):
     if retval is 0:
         epgcache = new.instancemethod(_enigma.eEPGCache_load, None,
                                       eEPGCache)
         epgcache = eEPGCache.getInstance().load()
         self.mbox = self.session.open(MessageBox, (_("EPG downloaded")),
                                       MessageBox.TYPE_INFO,
                                       timeout=4)
     else:
         self.mbox = self.session.open(MessageBox,
                                       (_("Sorry, the EPG download error")),
                                       MessageBox.TYPE_INFO,
                                       timeout=4)
Exemplo n.º 43
0
 def boundNewCommand(self, cmdName):
     """
     At construction, all existing commands are bound directly in the class.
     This method enables to bound new commands dynamically. These new bounds
     are not made with the class, but directly with the object instance.
     """
     if (cmdName in self.__dict__) | (cmdName in self.__class__.__dict__):
         print("Warning: command ", cmdName,
               " will overwrite an object attribute.")
     docstring = wrap.entity_get_command_docstring(self.obj, cmdName)
     cmd = Entity.createCommandBind(cmdName, docstring)
     # Limitation (todo): does not handle for path attribute name (see setattrpath).
     setattr(self, cmdName, new.instancemethod(cmd, self, self.__class__))
Exemplo n.º 44
0
 def create_merger(self):
     if isinstance(self.merge_strategy, type):
         merge_strategy = object.__new__(self.merge_strategy)
         merge_strategy.__init__()
     else:
         merge_strategy = self.merge_strategy
     merger = merge_strategy.create_merger()
     merger.log = self.log
     wrapped_merge_func = self.create_handle_module_func(
         merger.handle_module)
     setattr(merger, 'handle_module',
             new.instancemethod(wrapped_merge_func, merger, None))
     return merger
 def _test(self, tocheck):
     if INFO_TEST_RGX.match(self.module):
         self.linter.enable_message_category('I')
     else:
         self.linter.disable_message_category('I')
     try:
         self.linter.check(tocheck)
     except Exception, ex:
         # need finalization to restore a correct state
         self.linter.reporter.finalize()
         ex.file = tocheck
         ex.__str__ = new.instancemethod(exception_str, ex, None)
         raise
Exemplo n.º 46
0
    def new(uri):
        """
        constructor
        """
        uri = quote(URIRef(uri))
        name = getLocalName(uri)

        cls = OWLDatatypeProperty(name, (), {'uri': uri, 'name': name})

        #add the appropriate class method
        cls.getURI = instancemethod(getURI, cls)

        return cls
Exemplo n.º 47
0
def _enable_autopx(self):
    """Enable %autopx mode by saving the original runsource and installing 
    pxrunsource.
    """
    try:
        activeController = __IPYTHON__.activeController
    except AttributeError:
        print "No active RemoteController found, use RemoteController.activate()."
    else:
        self._original_runsource = self.runsource
        self.runsource = new.instancemethod(pxrunsource, self, self.__class__)
        self.autopx = True
        print "Auto Parallel Enabled\nType %autopx to disable"
Exemplo n.º 48
0
def _monkeypatchWCS(wcsObj, naxis, wcsFields):
    """monkeypatches pywcs instances for DaCHS' purposes.
	"""
    wcsObj._dachs_header = wcsFields
    wcsObj.longAxis = naxis[0]
    if len(naxis) > 1:
        wcsObj.latAxis = naxis[1]
    wcsObj._monkey_naxis_lengths = [
        wcsFields.get("NAXIS%d" % i) for i in naxis
    ]
    wcsObj.origCalcFootprint = wcsObj.calcFootprint
    wcsObj.calcFootprint = new.instancemethod(_calcFootprintMonkeypatch,
                                              wcsObj, wcsObj.__class__)
Exemplo n.º 49
0
    def __call__(self, *args, **kwArgs):

        s = self.instance()
        if s is None:
            if "fallbackResult" in self.__kw:
                return self.__kw["fallbackResult"]
            else:
                raise ReferenceError(
                    "Instance referenced by WeakMethod %s.%s() no longer exists"
                    % (self.__method.__module__, self.__method.__name__))

        m = new.instancemethod(self.__method, s, s.__class__)
        return m(*args, **kwArgs)
Exemplo n.º 50
0
 def setup_admonitions_handlers(self):
     """
         Admonitions are handled here... We basically surround admonitions
         in a div with class admonition_{name of the admonition}.
     """
     handled_admonitions = [
         'attention',
         'caution',
         'danger',
         'error',
         'hint',
         'important',
         'note',
         'tip',
         'warning',
     ]
     for adm in handled_admonitions:
         visit_func, depart_func = self.create_admonition_functor(adm)
         visit_func = new.instancemethod(visit_func, self, MoinTranslator)
         depart_func = new.instancemethod(depart_func, self, MoinTranslator)
         setattr(self, 'visit_%s' % (adm), visit_func)
         setattr(self, 'depart_%s' % (adm), depart_func)
Exemplo n.º 51
0
 def __getattr__(self, aname):
     if self.debug:
         print "Waiting on future"
     self.event.wait()
     if self.exception is not None:
         raise FutureException, self.exception[0], self.exception[1]
     target = self.target
     f = getattr(target, aname)
     if isinstance(f, MethodType):
         # Rebind the method to the target.
         return new.instancemethod(f.im_func, self, target.__class__)
     else:
         return f
Exemplo n.º 52
0
 def __call__(self):
     '''Return a new bound-method like the original, or the
     original function if it was just a function or unbound
     method.
     Returns None if the original object doesn't exist.
     '''
     if self.is_dead():
         return None
     if self._obj is not None:
         return new.instancemethod(self._func, self._obj(), self._class)
     else:
         # we don't have an instance: return just the function
         return self._func
Exemplo n.º 53
0
 def setup_overrides(self, f_name, f_class):
     if not f_name in f_class.__dict__:
         # If the function is defined in a parent, bind a call to function in the superclass
         self.original = new.instancemethod(
             lambda self, *args, **named: getattr(super(
                 f_class, self), f_name).__call__(*args, **named), None,
             f_class)
         self.is_derived = True
     else:
         self.original = getattr(f_class, f_name)
         self.is_derived = False
     # Install the stacked function
     setattr(f_class, f_name, self)
Exemplo n.º 54
0
 def _utc(self):
     UTC = FixedOffsetTimezone(0, 'UTC')
     def fake_localize(self, dt, is_dst=False):
         raise NotImplementedError()
     try:
         import new
         UTC.localize = new.instancemethod(fake_localize, UTC, UTC.__class__)
     except ImportError:
         import functools
         UTC.localize = functools.partial(fake_localize, UTC)
     # This is important to trigger the actual bug (#257)
     self.assertEqual(False, hasattr(UTC, 'normalize'))
     return UTC
Exemplo n.º 55
0
    def _add_unpickler(self, klass, module, name):
        """ Modifies the specified class so that our 'modify_state' method
            is called when its next instance is unpickled.
        """
        logger.debug('Adding unpickler hook to [%s]', klass)

        # Replace the existing setstate method with ours.
        self._backup_setstate(klass)
        m = new.instancemethod(__replacement_setstate__, None, klass)
        setattr(klass, _SETSTATE_NAME, m)

        # Add the information necessary to allow this unpickler to run
        setattr(klass, _UNPICKLER_DATA, (self, module, name))
Exemplo n.º 56
0
 def _makeOrder(self):
     #emsg, asFix = IntegrityTester._makeOrder(self)
     msg = makeOrder(fix)
     import new
     # Slot in a new compile method for one invocation
     oldCompiler = self.initiatorSession.compile_message
     self.initiatorSession.compile_message = new.instancemethod(
         compileMessageOmitSequenceNumber, self.initiatorSession)
     strMsg = self.initiatorSession.compile_message(msg,
                                                    disableValidation=True)
     # Return to original state
     self.initiatorSession.compile_message = oldCompiler
     return msg, strMsg
Exemplo n.º 57
0
def __fill_callbacks(handlers, kind, callbacks):
    members = kind.__dict__
    for name in members:
        if name.startswith('on_') and not name in callbacks:
            value = members[name]
            import types
            if type(value) == types.FunctionType:
                import new
                callbacks[name] = new.instancemethod(value, handlers,
                                                     handlers.__class__)

    for base in kind.__bases__:
        __fill_callbacks(handlers, base, callbacks)
Exemplo n.º 58
0
    def go_continue(self, ret):

        try:
            if os.path.exists('/usr/bin/enigma2.sh'):
                content = open('/usr/bin/enigma2.sh', 'r').read()
                m = re.search('epg.dat', content)
                if not m:
                    os.system(
                        "cp /usr/bin/enigma2.sh /usr/bin/enigma2.sh.xmltvbak")
                    line_number = 2
                    with open('/usr/bin/enigma2.sh') as f:
                        lines = f.readlines()
                    lines.insert(
                        line_number,
                        '[ -f /media/hdd/epg_new.dat ] && cp /media/hdd/epg_new.dat /media/hdd/epg.dat\n'
                    )
                    with open('/usr/bin/enigma2.sh', 'w') as f:
                        f.writelines(lines)
            lang = self["menu"].l.getCurrentSelection()[1]
            ret = os.system(
                "wget -q http://linux-sat.tv/epg/epg_%s.dat.gz -O /hdd/epg_new.dat.gz"
                % (lang))
            if ret:
                self.mbox = self.session.open(MessageBox, (_(
                    "Sorry, the EPG download error. Try again later or check your internet connection"
                )),
                                              MessageBox.TYPE_INFO,
                                              timeout=6)
                return
            os.system("gzip -df /hdd/epg_new.dat.gz")
            os.system("cp -f /hdd/epg_new.dat /hdd/epg.dat")
            os.system("rm -f epg_new.dat.gz")
            self.mbox = self.session.open(MessageBox,
                                          (_("the EPG download is complete")),
                                          MessageBox.TYPE_INFO,
                                          timeout=4)
        except:
            self.mbox = self.session.open(MessageBox, (_("Error")),
                                          MessageBox.TYPE_INFO,
                                          timeout=4)
        try:
            epgcache = new.instancemethod(_enigma.eEPGCache_load, None,
                                          eEPGCache)
            epgcache = eEPGCache.getInstance().load()
            self.close()
        except:
            restartbox = self.session.openWithCallback(self.restartGUI,
                                                       MessageBox,
                                                       _("Restart GUI now?"),
                                                       MessageBox.TYPE_YESNO)
            restartbox.setTitle(_("Restart GUI now?"))
Exemplo n.º 59
0
 def save(self):
     config.misc.epgcache_filename.value = '%sepg.dat' % config.misc.epgcachepath.value
     config.misc.epgcache_filename.save()
     config.misc.epgcachepath.save()
     epgcache = new.instancemethod(_enigma.eEPGCache_save, None, eEPGCache)
     epgcache = eEPGCache.getInstance().save()
     config.plugins.ldteam.epgmhw2wait.save()
     config.epg.save()
     config.epg.maxdays.save()
     configfile.save()
     self.mbox = self.session.open(MessageBox,
                                   _('configuration is saved'),
                                   MessageBox.TYPE_INFO,
                                   timeout=4)
Exemplo n.º 60
0
    def watchObject(self, object, identifier, callback):
        """Watch the given object.

        Whenever I think the object might have changed, I'll send an
        ObjectLink of it to the callback.

        The identifier argument is used to generate identifiers for
        objects which are members of this one.
        """
        if type(object) is not types.InstanceType:
            raise TypeError, "Sorry, can only place a watch on Instances."

        # uninstallers = []

        dct = {}
        reflect.addMethodNamesToDict(object.__class__, dct, '')
        for k in object.__dict__.keys():
            dct[k] = 1

        members = dct.keys()

        clazzNS = {}
        clazz = new.classobj(
            'Watching%s%X' % (object.__class__.__name__, id(object)), (
                _MonkeysSetattrMixin,
                object.__class__,
            ), clazzNS)

        clazzNS['_watchEmitChanged'] = new.instancemethod(
            lambda slf, i=identifier, b=self, cb=callback: cb(
                b.browseObject(slf, i)),
            None,
            clazz)

        # orig_class = object.__class__
        object.__class__ = clazz

        for name in members:
            m = getattr(object, name)
            # Only hook bound methods.
            if ((type(m) is types.MethodType) and (m.im_self is not None)):
                # What's the use of putting watch monkeys on methods
                # in addition to __setattr__?  Well, um, uh, if the
                # methods modify their attributes (i.e. add a key to
                # a dictionary) instead of [re]setting them, then
                # we wouldn't know about it unless we did this.
                # (Is that convincing?)

                monkey = _WatchMonkey(object)
                monkey.install(name)