Example #1
0
    def __new__(cls, clsname, clsbases, clsdict):
        members = clsdict.get("__tcl_members__", list())
        command = clsdict.get("__tcl_command__", None)
        for (n, m) in enumerate(members):
            if not isinstance(m, TclMember):
                raise RuntimeError("Element #%d of __tcl_members__ is not a " "TclMember" % (n + 1,))

            def fget(self, cmd=command, m=m):
                self._ix_get(m)
                val = self._api.call("%s cget -%s" % (cmd, m.name))[0]
                return m.type(val)

            def fset(self, value, cmd=command, m=m):
                val = self._api.call("%s config -%s %s" % (cmd, m.name, value))
                self._ix_set(m)

            attrname = m.attrname
            if m.attrname is None:
                attrname = translate_ix_member_name(m.name)

            if m.doc is not None:
                fget.__doc__ = m.doc

            fget.__name__ = "_get_%s" % attrname
            clsdict[fget.__name__] = fget
            if not m.flags & FLAG_RDONLY:
                fset.__name__ = "_set_%s" % attrname
                clsdict[fset.__name__] = fset
                p = property(fget=fget, fset=fset)
            else:
                p = property(fget=fget)

            clsdict[attrname] = p
        t = type.__new__(cls, clsname, clsbases, clsdict)
        return t
Example #2
0
def _create_property(field_name, docstring,
                      read_only=False, closed_only=False):
    """Helper for creating properties to read/write to files.
    """
    def getter(self):
        if closed_only and not self._closed:
            raise AttributeError("can only get %r on a closed file" %
                                 field_name)
        # Protect against PHP-237
        if field_name == 'length':
            return self._file.get(field_name, 0)
        return self._file.get(field_name, None)

    def setter(self, value):
        if self._closed:
            self._coll.files.update({"_id": self._file["_id"]},
                                    {"$set": {field_name: value}}, safe=True)
        self._file[field_name] = value

    if read_only:
        docstring = docstring + "\n\nThis attribute is read-only."
    elif closed_only:
        docstring = "%s\n\n%s" % (docstring, "This attribute is read-only and "
                                  "can only be read after :meth:`close` "
                                  "has been called.")

    if not read_only and not closed_only:
        return property(getter, setter, doc=docstring)
    return property(getter, doc=docstring)
Example #3
0
def register(cls, admin_cls):
    cls.add_to_class('_content_title', models.TextField(_('content title'), blank=True,
        help_text=_('The first line is the main title, the following lines are subtitles.')))
    cls.add_to_class('_page_title', models.CharField(_('page title'), max_length=100, blank=True,
        help_text=_('Page title for browser window. Same as title by default.')))

    def _page_title(self):
        """
        Use this for the browser window (<title>-tag in the <head> of the HTML document)
        """

        if self._page_title:
            return self._page_title
        return self.content_title

    cls.page_title = property(_page_title)

    def _content_title(self):
        """
        This should be used f.e. for the <h1>-tag
        """

        if not self._content_title:
            return self.title

        return self._content_title.splitlines()[0]

    cls.content_title = property(_content_title)

    def _content_subtitle(self):
        return u'\n'.join(self._content_title.splitlines()[1:])

    cls.content_subtitle = property(_content_subtitle)
    def __new__(cls, nm, parents, attrs):
        super_new = super(CamelCasedClass, cls).__new__

        tmp_dct = dict()
        for name, value in attrs.items():
            if not name.startswith('__') and not name.endswith('__'):
                tmp_dct[name] = value
        attrs.update(tmp_dct)

        # Create property for each key in `description_map` dict.
        # Besides, if `descriptor_type` is data descriptor, a `getxxx` and
        # a `setxxx` method also will be added to `cls`, if `descriptor_type`
        # is non data descriptor, only a `getxxx` method added.
        if 'descriptor_map' in attrs:
            for attr in attrs['descriptor_map']:
                # Definition of getter and setter method for properties.
                def get_attr(attr, self):
                    return self.getproperty(attr)
                def set_attr(attr, self, value):
                    self.setproperty(attr, value)

                property_name = attr
                getter = partial(get_attr, attr)
                setter = partial(set_attr, attr)
                # Add property to class.
                if attrs['descriptor_type'] == 'data descriptor':
                    # data descriptor.
                    attrs[property_name] = property(getter, setter, None, attr)
                else:
                    # non data descriptor.
                    attrs[property_name] = property(getter, None, None, attr)
        return super_new(cls, nm, parents, attrs)
Example #5
0
File: qt.py Project: infinit/drake
 def unclosure(prop, library):
   def library_getter(self, static):
     name = '_Qt__%s_%s' % (prop, 'static' if static else 'dynamic')
     if getattr(self, name) is None:
       lib = self._Qt__find_lib(library,
                                self._Qt__cxx_toolkit,
                                static = static)
       setattr(self, name, lib)
     return getattr(self, name)
   setattr(Qt, '%s_dynamic' % prop,
           property(lambda self: library_getter(self, False)))
   setattr(Qt, '%s_static' % prop,
           property(lambda self: library_getter(self, True)))
   def config_getter(self, static = None, link = True):
     if static is None:
       static = not self._Qt__prefer_shared
     name = '_Qt__config_%s_%s' % \
            (prop, 'static' if static else 'dynamic')
     if getattr(self, name) is None:
       lib = library_getter(self, static)
       c = Config()
       macro = prop.upper()
       macro += static and '_STATIC' or '_DYN'
       c.define('Qt_%s_LINK' % macro, 1)
       c.add_system_include_path(
         Qt._Qt__include_dir / Qt._Qt__libraries[prop])
       setattr(self, name + '_header', Config(c))
       c.library_add(lib)
       setattr(self, name, Config(c))
     return getattr(self, name + ('_header' if not link else ''))
   setattr(Qt, 'config_%s' % prop, config_getter)
    def mk_property(fieldname):
        """use a clousre to build out the getter & setter for the given field
        """
        if mutable:
            def field_setter(self, value):
                """Validate and set the given field
                """
                if isinstance(value, six.string_types):
                    raise TypeError("Cannot set integer field to a string")
                value = int(value)
                vals = []
                for fname, fspec in self._field_mapping.items():
                    if fname != fieldname:
                        vals.append(getattr(self, fname))
                    else:
                        vals.append(value)
                # Rebuilding the whole string is a little kludgy, but it's
                # good for a proof of concept iteration
                self._bitstring = self._build_from_vals(vals)

        def field_getter(self):
            """Return the value for the given field
            """
            field_spec = self._field_mapping[fieldname]
            return (self._bitstring & field_spec.mask) >> field_spec.offset

        if mutable:
            return property(field_getter, field_setter)
        else:
            return property(field_getter)
Example #7
0
    def __init__(cls, name, base, namespace):
        # store the Property definitions on the class as a dictionary
        # mapping the Property name to the Property instance
        cls._properties = {}

        # loop through the class namespace looking for Property instances
        for key, value in namespace.items():
            #print key,value
            if isinstance(value, Property):
                if value.name is None:
                    # name will be none unless set via kwd param
                    value.name = key
                cls._properties[key] = value
                # now that the property reference is stored away, 
                # initialize its vars to None, the default vale (TODO), or the fget
                if value.default:
                    #TODO: Make this work for scalars too
                    fget = getattr(cls,value.default)
                    value = property(fget)
                elif value.fget:
                    # wrapped fset and fdel in str() to make the default None work with getattr
                    fget = getattr(cls,value.fget)
                    fset = getattr(cls,str(value.fset),None)
                    fdel = getattr(cls,str(value.fdel),None)
                    value = property(fget,fset,fdel)
                else:
                    value = None
                setattr(cls,key,value)
    def _set_components(cls, components, classdict):
        """

        """
        def mkfnc_plural(klass):
            """
            Create closure to avoid changing value of component_class
            """
            return lambda self: self.get_instances(klass)

        def mkfnc_singular(klass):
            """
            Singular version of mkfnc_plural
            """
            return lambda self: self.get_instance(klass)

        classdict["components"] = components

        for component_class in components:
            # Loop through components for this class. Normalize each component name,
            # and create plural and singular versions.
            name = re.sub("component$", "", component_class.__name__.lower())
            plural_name = name+"s"
            singular_name = name

            # Then, if not already defined, assign each name as a property. If defined, raise a warning.
            if plural_name not in classdict:
                classdict[plural_name] = property(mkfnc_plural(component_class))
            if singular_name not in classdict:
                classdict[singular_name] = property(mkfnc_singular(component_class))
def _create_property(field_name, docstring,
                      read_only=False, closed_only=False):
    """Helper for creating properties to read/write to files.
    """
    def getter(self):
        if closed_only and not self._closed:
            raise AttributeError("can only get %r on a closed file" %
                                 field_name)
        return self._file.get(field_name, None)

    def setter(self, value):
        if self._closed:
            raise AttributeError("cannot set %r on a closed file" %
                                 field_name)
        self._file[field_name] = value

    if read_only:
        docstring = docstring + "\n\nThis attribute is read-only."
    elif not closed_only:
        docstring = "%s\n\n%s" % (docstring, "This attribute can only be "
                                  "set before :meth:`close` has been called.")
    else:
        docstring = "%s\n\n%s" % (docstring, "This attribute is read-only and "
                                  "can only be read after :meth:`close` "
                                  "has been called.")

    if not read_only and not closed_only:
        return property(getter, setter, doc=docstring)
    return property(getter, doc=docstring)
Example #10
0
def _create_property(field_name, docstring, read_only=False, from_meta=False):
    """Helper for creating properties to IO objects to files.
    """

    def getter(self):
        if from_meta:
            if 'Meta' not in self:
                return None
            return self['Meta'].get(field_name, None)
        return self.get(field_name, None)

    def setter(self, value):
        if from_meta:
            if 'Meta' not in self:
                self['Meta'] = {}
            self['Meta'][field_name] = value
        else:
            self[field_name] = value

    def deleter(self):
        if from_meta:
            del self['Meta'][field_name]
        else:
            del self[field_name]

    if read_only:
        docstring = docstring + "\n\nThis attribute is read-only."

    if not read_only:
        return property(getter, setter, deleter, doc=docstring)
    return property(getter, doc=docstring)
Example #11
0
 def __getattr__(self, attr):
     # Using an anonymous class
     direction = self.direction
     return type("", (object, ), {
         'direction': property(lambda self: direction),
         'type': property(lambda self: attr),
     })()
Example #12
0
 def info_volume(volume_id):
     """
     Info volume mockup
     """
     return type('Info', (), {'object_type': property(lambda s: 'BASE'),
                              'metadata_backend_config': property(lambda s: MockStorageRouterClient.metadata_backend_config.get(volume_id)),
                              'vrouter_id': property(lambda s: MockStorageRouterClient.vrouter_id.get(volume_id))})()
Example #13
0
 def empty_info():
     """
     Returns an empty info object
     """
     return type('Info', (), {'object_type': property(lambda s: 'BASE'),
                              'metadata_backend_config': property(lambda s: None),
                              'vrouter_id': property(lambda s: None)})()
Example #14
0
def attrib_property(name, validator=None, delete=False,
        default=None, doc=None, converter=None):
    '''XML attribute property helper'''
    # pylint: disable=W0212,C0111
    def propget(myself):
        att = get_attrib(myself._xml, name)
        if att is None and default is not None:
            att = default
        if converter is not None and att is not None:
            return converter.from_xml(att)
        return att

    propget.xml_property = 'attrib'
    propget.xml_name = name

    def propset(myself, value):
        if converter is not None:
            sval = converter.to_xml(value)
        elif validator is not None:
            validator(value)
            sval = value
        if default is not None and default == sval:
            del myself._xml[name]
        else:
            myself._xml.attrib[name] = sval

    if delete:
        def propdel(myself):
            del_attrib(myself._xml, name)
        prop = property(propget, propset, propdel, doc=doc)
    else:
        prop = property(propget, propset, doc=doc)

    return prop
Example #15
0
    def get_property(self):
        """Returns the property in which the relation will be referenced."""
        def _ws_inner(method_self):
            """Inner function to return the property for the relation."""
            _klass = self.to_class()
            self.__plural_name = _klass.__class__.plural_name
            self.__get_all_cmd = _klass.data_source.get_all_cmd
            if self.plural_name is not None:
                plural_name = self.plural_name
            else:
                plural_name = method_self.plural_name
            if not self.ws_call:
                _klass.data_source.get_all_cmd = self.ws_call
                ret = _klass.one(getattr(method_self, self.attr_fk))
            else:
                _klass.__class__.plural_name = "/".join(
                    (plural_name, getattr(method_self, self.attr_fk)))
                _klass.data_source.get_all_cmd = self.ws_call
                ret = _klass.many()
            _klass.__class__.plural_name = self.__plural_name
            _klass.data_source.get_all_cmd = self.__get_all_cmd
            return ret

        def _inner(method_self):
            """Inner function to return the property for the relation."""
            fk = getattr(method_self, self.attr_fk)
            return self.to_class.one(fk)

        if self.ws_call is not None:
            ret = property(_ws_inner)
        else:
            ret = property(_inner)
        return ret
Example #16
0
def funding( startup ):
	if startup.get( "last_round" ) is None:
		al_data = startup[ 'al_data' ]
		al_id = property( al_data, 'id' )
		al_funding = bot_utils.load_json( "https://api.angel.co/1/startups/%s/funding?access_token=%s" % (al_id, access_token) )
		if al_funding is not None:
			funding_info = al_funding.get( "funding" )
			total_raised = 0
			last_round = None

			for funding in funding_info:
				amount = property( funding, "amount" )

				if amount is not None:					
					closed = property( funding, "closed_at" )
				
					total_raised = total_raised + amount
					if last_round is None or closed > last_round.get( "closed_at" ):
						last_round = funding

			if last_round is not None:
				bot_utils.set_if_empty( startup, "last_round", last_round.get( "amount" ) )
				bot_utils.set_if_empty( startup, "last_round_type", last_round.get( "round_type" ) )
				bot_utils.set_if_empty( startup, "last_round_url", last_round.get( "source_url" ) )
				bot_utils.set_if_empty( startup, "total_funding", total_raised )
Example #17
0
def bool_attrib_property(name, delete=False, default=None, doc=None):
    '''XML boolean attribute property helper'''
    # pylint: disable=W0212,C0111
    def propget(myself):
        att = get_attrib(myself._xml, name)
        if att is not None:
            return boolstr(att)
        else:
            return default
    propget.xml_property = 'attrib'
    propget.xml_name = name

    def propset(myself, value):
        if not type(value) == bool:
            raise ValueError('Value has to be of the type bool')
        if default is not None and default == value:
            del_attrib(myself._xml, name)
        else:
            myself._xml.text = 'yes' if value == True else 'no'

    if delete:
        def propdel(myself):
            del_attrib(myself._xml, name)
        prop = property(propget, propset, propdel, doc=doc)
    else:
        prop = property(propget, propset, doc=doc)

    return prop
Example #18
0
    def callback(frame, name, func, old_locals):

        def __new__(cls, *args, **kw):
            result = func(*args, **kw)
            if type(result) is tuple:
                return tuple.__new__(cls, (cls,)+result)
            else:
                return result

        def __repr__(self):
            return name+tuple.__repr__(self[1:])

        import inspect
        args, star, dstar, defaults = inspect.getargspec(func)

        d = dict(
            __new__ = __new__, __repr__ = __repr__, __doc__=func.__doc__,
            __module__ = func.__module__, __args__ = args, __star__ = star,
            __slots__ = [],
        )

        for p,a in enumerate(args):
            if isinstance(a,str):
                d[a] = property(lambda self, p=p+1: self[p])

        if star:
            d[star] = property(lambda self, p=len(args)+1: self[p:])

        d.update(kw)
        return type(name, mixins+(tuple,), d)
Example #19
0
    def _set_attr(self, name, doc=None, preload=False):
        "Initially sets up an attribute."

        if doc is None:
            doc = 'The {name} attribute.'.format(name=name)

        if not hasattr(self._attr_func_, name):
            attr_prop = property(
                functools.partial(self._setable_get_, name),
                functools.partial(self._setable_set_, name),
                doc=doc
            )

        elif preload:
            func = getattr(self._attr_func_, name)
            setattr(self._attr_data_, name, func())
            delattr(self._attr_func_, name)
            attr_prop = property(
                functools.partial(self._simple_get_, name),
                doc=doc
            )

        else:
            attr_prop = property(
                functools.partial(self._loadable_get_, name),
                doc=doc
            )

        setattr(type(self), name, attr_prop)
	def __get_flavor(self):

        return self.__flavor

	source=property(fget=__get_src)
	    platform=property(fget=__get_platform)
	    flavor=property(fget=__get_flavor)
Example #21
0
    def __init__(self, rw_ops, lregs, loc_pfx, stk_pfx, frm_pfx):
        self.__nibbles = 0
        self.__nr = 0
        self.__read, self.__write = rw_ops[1]
        self.__list = []
        self.__dico = {}
        for regs in lregs:
            sz = regs[0]
            nm = regs[1]
            for n in nm:
                r = Register(self.__nr, n, sz, rw_ops[0])

                fget = lambda me, who = self.__nr: me.__read_reg(who)
                fset = lambda me, v, who = self.__nr: me.__write_reg(who,v)

                if n.find(loc_pfx) != -1:
                    setattr(self.__class__, "pc", property(fget, fset))
                    self.__dico.update({"pc":self.__nr})
                elif n.find(stk_pfx) != -1:
                    setattr(self.__class__, "stack", property(fget, fset))
                    self.__dico.update({"stack":self.__nr})
                elif n.find(frm_pfx) != -1:
                    setattr(self.__class__, "frame", property(fget, fset))
                    self.__dico.update({"frame":self.__nr})

                setattr(self.__class__, n, property(fget, fset))
                self.__dico.update({n:self.__nr})
                self.__list.append(r)

                self.__nibbles += sz*2
                self.__nr += 1
Example #22
0
def init(table, reload=False):
    if 'density' in table.properties and not reload: return
    table.properties.append('density')
    Isotope.density = property(density, "density using inter-atomic spacing from naturally occurring form")
    Element.density = property(density, "density using inter-atomic spacing from naturally occurring form")
    Element.density_units = "g/cm^3"

    Element.interatomic_distance \
        = property(interatomic_distance,
                   "interatomic distance estimated from density")
    Element.interatomic_distance_units = "angstrom"
    Element.number_density \
        = property(number_density,
                   "number density estimated from mass and density")
    Element.number_density_units = "1/cm^3"

    for k,v in element_densities.items():
        el = getattr(table,k)
        if isinstance(v,tuple):
            el._density = v[0]
            el.density_caveat = v[1]
        elif v is None:
            el._density = None
            el.density_caveat = "unavailable"
        else:
            el._density = v
            el.density_caveat = ""
Example #23
0
def _bounded_property(base_name, allowed_units, default_units, doc=""):
    
    def getter(self):
        return pq.Quantity(*split_unit_str(
            self._query("{}?".format(base_name)),
            default_units
        ))
    
    def min_getter(self):
        return pq.Quantity(*split_unit_str(self._query("{}:MIN?".format(base_name))))
    
    def max_getter(self):
        return pq.Quantity(*split_unit_str(self._query("{}:MAX?".format(base_name))))
    
    def setter(self, newval):
        newval = assume_units(newval, default_units)
        
        if newval > max_getter(self) or newval < min_getter(self):
            raise ValueError("Value outside allowed bounds for this channel.")
        
        if newval.units not in allowed_units:
            newval = newval.rescale(default_units)
            
        self._sendcmd("{}:{}".format(base_name, newval))
        
    return property(getter, setter, doc=doc), property(min_getter), property(max_getter)
Example #24
0
def enum_type(*args):
    """
    Create an enumeration from string arguments
    """
    # Test args
    for arg in args:
        if not isinstance(arg, basestring):
            msg = "{} is not a string".format(arg)
            raise TypeError(msg)

    # Format strings
    values = [arg.strip() for arg in args]

    # Create MetaEnum
    values_property = property(lambda cls: values)
    MetaEnum = type("MetaEnum", (type,), {"values": values_property})

    # __new__ method
    def __new__(cls, value):
        if value not in cls.values:
            msg = "'{}' not in {}".format(value, cls.values)
            raise AttributeError(msg)
        return BaseEnum.__new__(cls, value)

    # __repr__ method
    def __repr__(self):
        return u"Element '{}' of Enum({})".format(unicode(self), self.values)

    # method dictionnary
    method_dict = {"__new__": __new__,
                   "__repr__": __repr__,
                   "values": property(lambda self: self.__class__.values)}

    # Create EnumType
    return MetaEnum("EnumType", (BaseEnum,), method_dict)
Example #25
0
def resolved_tool_contract_runner(rtc):
    opts = rtc.task.options
    # XXX to handle chunking I am simply re-using the old i/N arguments, but
    # embedded in the input pickle instead of passed on the command line
    final_pickle_fn = rtc.task.input_files[2]
    _tmp = cPickle.load(open(final_pickle_fn, 'rb'))
    i_chunk = 0
    n_chunks = 1
    if "__chunk_i" in _tmp:
        i_chunk = _tmp['__chunk_i']
        n_chunks = _tmp['__chunk_n']
        final_pickle_fn = _tmp['pickle_file']
    output_dir = os.path.dirname(final_pickle_fn)
    IceFiles.final_consensus_fa = property(
        lambda self: rtc.task.input_files[1])
    IceFiles.final_pickle_fn = property(lambda self: final_pickle_fn)
    IceFiles.nfl_all_pickle_fn = property(lambda self: rtc.task.input_files[3])
    iceq = IceQuiverRTC(
        root_dir=output_dir,
        subread_set=rtc.task.input_files[0],
        nproc=rtc.task.nproc)
    iceq.validate_inputs()
    iceq.process_chunk_i(i=i_chunk, num_chunks=n_chunks)
    with open(rtc.task.output_files[0], 'w') as f:
        report = Report.from_simple_dict(
            report_id="isoseq_ice_quiver",
            raw_d={'n_chunks': 1},
            namespace="ice_quiver")
        f.write(report.to_json())
    return 0
Example #26
0
File: _cri.py Project: behnam/cgkit
def loadRI(libName):
    """Load a RenderMan library and return a module-like handle to it.
    
    libName is the name of a shared library that implements the RenderMan
    interface. The name can either be an absolute file name or just the
    name of the library (without suffix or "lib" prefix) in which case 
    the function tries to find the library file itself.
    The return value is the library handle as returned by the ctypes 
    LoadLibrary() function. This handle has already been prepared so that
    it can be used like a module that contains the RenderMan interface.
    """
    
    # Try to figure out the location of the lib if the name is not an absolute path...
    libName = rmanlibutil.resolveRManLib(libName)
        
    # Load the library...
    ri = cdll.LoadLibrary(libName)
    
    _createRiTypes(ri)
    _createRiTokens(ri)
    _createRiConstants(ri)
    _createRiFunctions(ri)

    # Create an alias for every Ri function and RI_ constant that has the prefix removed...
    for name in dir(ri):
        if name.startswith("Ri"):
            setattr(ri, name[2:], getattr(ri, name))
        elif name.startswith("RI_"):
            setattr(ri, name[3:], getattr(ri, name))

    ri.__class__.RiLastError = property(_getLastError, _setLastError)
    ri.__class__.LastError = property(_getLastError, _setLastError)

    return ri
Example #27
0
    def register():
        for i in range(len(models)):
            model = models[i]
            if '_decl_class_registry' in model.__dict__:
                continue
            _as_declarative(model, model.__name__, model.__dict__)

            #for auto-update timestamps
            event.listen(model, 'before_insert', ModelExtension.before_insert_listener)
            event.listen(model, 'before_update', ModelExtension.before_update_listener)

            # for ref grandchildren
            for j in range(i):
                if not models[j] in model.__bases__:
                    continue
                parent = models[j]
                for grandparent in parent._many_to_models:
                    setattr(grandparent, model._readable_names,
                        (lambda parent, model: property(lambda self: getattr(self, parent._readable_names)
                        .filter_by(real_type = model._readable_name)))(parent, model))

                for grandparent in parent._one_to_models:
                    setattr(grandparent, model._readable_name,
                        (lambda parent, model: property(lambda self: getattr(self, parent._readable_name)
                            if getattr(self, parent._readable_name).real_type == model._readable_name else None))(parent, model))
        models[:] = []
Example #28
0
    def interface(cls, name, uselist=True):

        mapper = class_mapper(cls)
        table = mapper.local_table
        mapper.add_property(attr_name, 
                            relationship(GenericAssoc, 
                                    backref='_backref_%s' % table.name)
                            )

        if uselist:
            # list based property decorator
            def get(self):
                if getattr(self, attr_name) is None:
                    setattr(self, attr_name, GenericAssoc(table.name))
                return getattr(self, attr_name).targets
            setattr(cls, name, property(get))
        else:
            # scalar based property decorator
            def get(self):
                return getattr(self, attr_name).targets[0]
            def set(self, value):
                if getattr(self, attr_name) is None:
                    setattr(self, attr_name, GenericAssoc(table.name))
                getattr(self, attr_name).targets = [value]
            setattr(cls, name, property(get, set))
Example #29
0
def style_metaclass(name, bases, attrs):

    for k in expansions:
        def setter_a(self, v,  k=k):
            self.setattr(k, v)

        def deleter_a(self, k=k):
            self.delattr(k)

        def getter_a(self, k=k):
            return self.getattr(k)

        attrs[k] = property(getter_a, setter_a, deleter_a)


    for k, number in property_number.iteritems():
        def getter_b(self, number=number):
            return self.cache[self.offset + number]

        def setter_b(self, v,  k=k):
            self.setattr(k, v)

        def deleter_b(self, k=k):
            self.delattr(k)

        attrs[k] = property(getter_b, setter_b, deleter_b)

    return type(name, bases, attrs)
Example #30
0
    def __init__(self, zero=False, freq=100, dev_name='Dev1'):
        self._daq  = ni.NIDAQ(dev_name)
        self._freq = {}
            
        for chan in self._daq.get_AI_channels():
            setattr(NIDAQ,chan,property(fget=eval('lambda self: self.get_chan(\'%s\')' %chan))) # set up property for input channels NIDAQ.ai#(0-31)
        
        for chan in self._daq.get_AO_channels():
            setattr(self, '_%s' %chan, None)# privately store value
            # The following line works with instrumental modified to add read function to AnalogOut
            setattr(NIDAQ,chan,property(fset=eval('lambda self, value: self.set_chan(\'%s\',value)' %chan), fget=eval('lambda self: self.get_chan(\'%s\')' %chan)))
            # This works with instrumental after names of input channels added manually
            # setattr(NIDAQ,chan,property(fset=eval('lambda self, value: self.set_chan(\'%s\',value)' %chan), fget=eval('lambda self: self.get_chan(\'_%s_vs_aognd\')' %chan)))
            # This works with the current code, since I couldn't figure out internal channels with instrumental:
            # setattr(NIDAQ,chan,property(fset=eval('lambda self, value: self.set_chan(\'%s\',value)' %chan), fget=eval('lambda self: self.get_internal_chan(\'%s\')' %chan))) #property for output channels NIDAQ.ao# (0-3); monitor using internal channels
            self._freq[chan] = freq

            # DEBUG
        # for chan in ['ao0_vs_aognd', 'ao1_vs_aognd']:
            # setattr(self._daq, chan, ni.AnalogIn(self._daq, '%s'%chan))
            # setattr(NIDAQ,chan,property(fget=eval('lambda self: self.get_chan(\'%s\')' %chan)))
            # print(chan)
         
        self.inputs_to_monitor = ['ai23']# at least monitor one input
        
        if zero:
            self.zero()
Example #31
0
class QXmlSchemaValidator():  # skipped bases: <class 'sip.simplewrapper'>
    """
    QXmlSchemaValidator()
    QXmlSchemaValidator(QXmlSchema)
    """
    def messageHandler(self):  # real signature unknown; restored from __doc__
        """ QXmlSchemaValidator.messageHandler() -> QAbstractMessageHandler """
        return QAbstractMessageHandler

    def namePool(self):  # real signature unknown; restored from __doc__
        """ QXmlSchemaValidator.namePool() -> QXmlNamePool """
        return QXmlNamePool

    def networkAccessManager(
            self):  # real signature unknown; restored from __doc__
        """ QXmlSchemaValidator.networkAccessManager() -> QNetworkAccessManager """
        pass

    def schema(self):  # real signature unknown; restored from __doc__
        """ QXmlSchemaValidator.schema() -> QXmlSchema """
        return QXmlSchema

    def setMessageHandler(self, QAbstractMessageHandler
                          ):  # real signature unknown; restored from __doc__
        """ QXmlSchemaValidator.setMessageHandler(QAbstractMessageHandler) """
        pass

    def setNetworkAccessManager(
        self, QNetworkAccessManager
    ):  # real signature unknown; restored from __doc__
        """ QXmlSchemaValidator.setNetworkAccessManager(QNetworkAccessManager) """
        pass

    def setSchema(self,
                  QXmlSchema):  # real signature unknown; restored from __doc__
        """ QXmlSchemaValidator.setSchema(QXmlSchema) """
        pass

    def setUriResolver(self, QAbstractUriResolver
                       ):  # real signature unknown; restored from __doc__
        """ QXmlSchemaValidator.setUriResolver(QAbstractUriResolver) """
        pass

    def uriResolver(self):  # real signature unknown; restored from __doc__
        """ QXmlSchemaValidator.uriResolver() -> QAbstractUriResolver """
        return QAbstractUriResolver

    def validate(
        self, *__args
    ):  # real signature unknown; restored from __doc__ with multiple overloads
        """
        QXmlSchemaValidator.validate(QUrl) -> bool
        QXmlSchemaValidator.validate(QIODevice, QUrl documentUri=QUrl()) -> bool
        QXmlSchemaValidator.validate(QByteArray, QUrl documentUri=QUrl()) -> bool
        """
        return False

    def __init__(
        self,
        QXmlSchema=None
    ):  # real signature unknown; restored from __doc__ with multiple overloads
        pass

    __weakref__ = property(lambda self: object(), lambda self, v: None,
                           lambda self: None)  # default
    """list of weak references to the object (if defined)"""
Example #32
0
class User(db.Model):
    __tablename__ = 'users'
    __bind_key__ = "user"
    query_class = UserQuery

    ADMIN = 1
    OP = 2
    uid = db.Column(db.Integer, primary_key=True, autoincrement=True)
    username = db.Column(db.String(32), unique=True)
    nickname = db.Column(db.String(20), nullable=True)
    department = db.Column(db.String(20))
    catalog = db.Column(db.String(64))
    email = db.Column(db.String(100), unique=True, nullable=False)
    mobile = db.Column(db.String(14), unique=True)
    _password = db.Column("password", db.String(80))
    key = db.Column(db.String(32), nullable=False)
    secret = db.Column(db.String(32), nullable=False)
    date_joined = db.Column(db.DateTime, default=datetime.utcnow)
    last_login = db.Column(db.DateTime, default=datetime.utcnow)
    block = db.Column(db.Boolean, default=False)
    has_logined = db.Column(db.Boolean, default=False)

    class Permissions(object):
        def __init__(self, obj):
            self.obj = obj

        # @cached_property
        # def is_admin(self):
        #     return Permission(UserNeed(self.obj.id)) & admin

    def __init__(self, *args, **kwargs):
        super(User, self).__init__(*args, **kwargs)

    def __str__(self):
        return self.username

    #def __repr__(self):
    #    return "<%s>" % self

    @cached_property
    def permissions(self):
        return self.Permissions(self)

    def _get_password(self):
        return self._password

    def _set_password(self, password):
        self._password = hashlib.md5(password).hexdigest()

    password = db.synonym("_password",
                          descriptor=property(_get_password,
                                              _set_password))

    def check_password(self, password):
        if self.password is None:
            return False
        return self.password == hashlib.md5(password).hexdigest()

    @cached_property
    def provides(self):
        needs = [RoleNeed('authenticated'),
                 UserNeed(self.uid)]
        for r in self.rolenames:
            needs.append(RoleNeed(r))
        if self.is_admin:
            needs.append(RoleNeed('admin'))
        return needs

    @property
    def roles(self):
        urs = db.session.query(UserRole.rid).filter(
            UserRole.uid == self.uid).all()
        return [x.rid for x in urs]

    @property
    def rolenames(self):
        roles = list()
        for rid in self.roles:
            role = db.session.query(Role).filter(Role.rid == rid).first()
            roles.append(role.role_name)
        return roles

    @property
    def is_admin(self):
        return self.ADMIN in self.roles

    @property
    def is_sam_admin(self):
        return 'sam_admin' in self.rolenames

    @property
    def is_op(self):
        return (self.OP in self.roles) or (self.ADMIN in self.roles)
Example #33
0
class QXmlNodeModelIndex():  # skipped bases: <class 'sip.simplewrapper'>
    """
    QXmlNodeModelIndex()
    QXmlNodeModelIndex(QXmlNodeModelIndex)
    """
    def additionalData(self):  # real signature unknown; restored from __doc__
        """ QXmlNodeModelIndex.additionalData() -> int """
        return 0

    def data(self):  # real signature unknown; restored from __doc__
        """ QXmlNodeModelIndex.data() -> int """
        return 0

    def internalPointer(self):  # real signature unknown; restored from __doc__
        """ QXmlNodeModelIndex.internalPointer() -> object """
        return object()

    def isNull(self):  # real signature unknown; restored from __doc__
        """ QXmlNodeModelIndex.isNull() -> bool """
        return False

    def model(self):  # real signature unknown; restored from __doc__
        """ QXmlNodeModelIndex.model() -> QAbstractXmlNodeModel """
        return QAbstractXmlNodeModel

    def __eq__(self, *args, **kwargs):  # real signature unknown
        """ Return self==value. """
        pass

    def __ge__(self, *args, **kwargs):  # real signature unknown
        """ Return self>=value. """
        pass

    def __gt__(self, *args, **kwargs):  # real signature unknown
        """ Return self>value. """
        pass

    def __hash__(self, *args, **kwargs):  # real signature unknown
        """ Return hash(self). """
        pass

    def __init__(
        self,
        QXmlNodeModelIndex=None
    ):  # real signature unknown; restored from __doc__ with multiple overloads
        pass

    def __le__(self, *args, **kwargs):  # real signature unknown
        """ Return self<=value. """
        pass

    def __lt__(self, *args, **kwargs):  # real signature unknown
        """ Return self<value. """
        pass

    def __ne__(self, *args, **kwargs):  # real signature unknown
        """ Return self!=value. """
        pass

    __weakref__ = property(lambda self: object(), lambda self, v: None,
                           lambda self: None)  # default
    """list of weak references to the object (if defined)"""

    Attribute = 1
    Comment = 2
    Document = 4
    DocumentOrder = None  # (!) real value is ''
    Element = 8
    Follows = 1
    Is = 0
    Namespace = 16
    NodeKind = None  # (!) real value is ''
    Precedes = -1
    ProcessingInstruction = 32
    Text = 64
Example #34
0
class QAbstractXmlNodeModel():  # skipped bases: <class 'sip.simplewrapper'>
    """ QAbstractXmlNodeModel() """
    def attributes(self, QXmlNodeModelIndex
                   ):  # real signature unknown; restored from __doc__
        """ QAbstractXmlNodeModel.attributes(QXmlNodeModelIndex) -> list-of-QXmlNodeModelIndex """
        pass

    def baseUri(self, QXmlNodeModelIndex
                ):  # real signature unknown; restored from __doc__
        """ QAbstractXmlNodeModel.baseUri(QXmlNodeModelIndex) -> QUrl """
        pass

    def compareOrder(self, QXmlNodeModelIndex, QXmlNodeModelIndex_1
                     ):  # real signature unknown; restored from __doc__
        """ QAbstractXmlNodeModel.compareOrder(QXmlNodeModelIndex, QXmlNodeModelIndex) -> QXmlNodeModelIndex.DocumentOrder """
        pass

    def createIndex(
        self, *__args
    ):  # real signature unknown; restored from __doc__ with multiple overloads
        """
        QAbstractXmlNodeModel.createIndex(int) -> QXmlNodeModelIndex
        QAbstractXmlNodeModel.createIndex(int, int) -> QXmlNodeModelIndex
        QAbstractXmlNodeModel.createIndex(object, int additionalData=0) -> QXmlNodeModelIndex
        """
        return QXmlNodeModelIndex

    def documentUri(self, QXmlNodeModelIndex
                    ):  # real signature unknown; restored from __doc__
        """ QAbstractXmlNodeModel.documentUri(QXmlNodeModelIndex) -> QUrl """
        pass

    def elementById(self,
                    QXmlName):  # real signature unknown; restored from __doc__
        """ QAbstractXmlNodeModel.elementById(QXmlName) -> QXmlNodeModelIndex """
        return QXmlNodeModelIndex

    def kind(self, QXmlNodeModelIndex
             ):  # real signature unknown; restored from __doc__
        """ QAbstractXmlNodeModel.kind(QXmlNodeModelIndex) -> QXmlNodeModelIndex.NodeKind """
        pass

    def name(self, QXmlNodeModelIndex
             ):  # real signature unknown; restored from __doc__
        """ QAbstractXmlNodeModel.name(QXmlNodeModelIndex) -> QXmlName """
        return QXmlName

    def namespaceBindings(self, QXmlNodeModelIndex
                          ):  # real signature unknown; restored from __doc__
        """ QAbstractXmlNodeModel.namespaceBindings(QXmlNodeModelIndex) -> list-of-QXmlName """
        pass

    def nextFromSimpleAxis(self, QAbstractXmlNodeModel_SimpleAxis,
                           QXmlNodeModelIndex
                           ):  # real signature unknown; restored from __doc__
        """ QAbstractXmlNodeModel.nextFromSimpleAxis(QAbstractXmlNodeModel.SimpleAxis, QXmlNodeModelIndex) -> QXmlNodeModelIndex """
        return QXmlNodeModelIndex

    def nodesByIdref(
            self, QXmlName):  # real signature unknown; restored from __doc__
        """ QAbstractXmlNodeModel.nodesByIdref(QXmlName) -> list-of-QXmlNodeModelIndex """
        pass

    def root(self, QXmlNodeModelIndex
             ):  # real signature unknown; restored from __doc__
        """ QAbstractXmlNodeModel.root(QXmlNodeModelIndex) -> QXmlNodeModelIndex """
        return QXmlNodeModelIndex

    def sourceLocation(self, QXmlNodeModelIndex
                       ):  # real signature unknown; restored from __doc__
        """ QAbstractXmlNodeModel.sourceLocation(QXmlNodeModelIndex) -> QSourceLocation """
        return QSourceLocation

    def stringValue(self, QXmlNodeModelIndex
                    ):  # real signature unknown; restored from __doc__
        """ QAbstractXmlNodeModel.stringValue(QXmlNodeModelIndex) -> str """
        return ""

    def typedValue(self, QXmlNodeModelIndex
                   ):  # real signature unknown; restored from __doc__
        """ QAbstractXmlNodeModel.typedValue(QXmlNodeModelIndex) -> object """
        return object()

    def __init__(self):  # real signature unknown; restored from __doc__
        pass

    __weakref__ = property(lambda self: object(), lambda self, v: None,
                           lambda self: None)  # default
    """list of weak references to the object (if defined)"""

    FirstChild = 1
    NextSibling = 3
    Parent = 0
    PreviousSibling = 2
    SimpleAxis = None  # (!) real value is ''
Example #35
0
class QXmlQuery():  # skipped bases: <class 'sip.simplewrapper'>
    """
    QXmlQuery()
    QXmlQuery(QXmlQuery)
    QXmlQuery(QXmlNamePool)
    QXmlQuery(QXmlQuery.QueryLanguage, QXmlNamePool pool=QXmlNamePool())
    """
    def bindVariable(
        self, *__args
    ):  # real signature unknown; restored from __doc__ with multiple overloads
        """
        QXmlQuery.bindVariable(QXmlName, QXmlItem)
        QXmlQuery.bindVariable(QXmlName, QIODevice)
        QXmlQuery.bindVariable(QXmlName, QXmlQuery)
        QXmlQuery.bindVariable(str, QXmlItem)
        QXmlQuery.bindVariable(str, QIODevice)
        QXmlQuery.bindVariable(str, QXmlQuery)
        """
        pass

    def evaluateTo(
        self, *__args
    ):  # real signature unknown; restored from __doc__ with multiple overloads
        """
        QXmlQuery.evaluateTo(QXmlResultItems)
        QXmlQuery.evaluateTo(QAbstractXmlReceiver) -> bool
        QXmlQuery.evaluateTo(QIODevice) -> bool
        """
        return False

    def evaluateToString(
            self):  # real signature unknown; restored from __doc__
        """ QXmlQuery.evaluateToString() -> str """
        return ""

    def evaluateToStringList(
            self):  # real signature unknown; restored from __doc__
        """ QXmlQuery.evaluateToStringList() -> list-of-str """
        pass

    def initialTemplateName(
            self):  # real signature unknown; restored from __doc__
        """ QXmlQuery.initialTemplateName() -> QXmlName """
        return QXmlName

    def isValid(self):  # real signature unknown; restored from __doc__
        """ QXmlQuery.isValid() -> bool """
        return False

    def messageHandler(self):  # real signature unknown; restored from __doc__
        """ QXmlQuery.messageHandler() -> QAbstractMessageHandler """
        return QAbstractMessageHandler

    def namePool(self):  # real signature unknown; restored from __doc__
        """ QXmlQuery.namePool() -> QXmlNamePool """
        return QXmlNamePool

    def networkAccessManager(
            self):  # real signature unknown; restored from __doc__
        """ QXmlQuery.networkAccessManager() -> QNetworkAccessManager """
        pass

    def queryLanguage(self):  # real signature unknown; restored from __doc__
        """ QXmlQuery.queryLanguage() -> QXmlQuery.QueryLanguage """
        pass

    def setFocus(
        self, *__args
    ):  # real signature unknown; restored from __doc__ with multiple overloads
        """
        QXmlQuery.setFocus(QXmlItem)
        QXmlQuery.setFocus(QUrl) -> bool
        QXmlQuery.setFocus(QIODevice) -> bool
        QXmlQuery.setFocus(str) -> bool
        """
        return False

    def setInitialTemplateName(
        self, *__args
    ):  # real signature unknown; restored from __doc__ with multiple overloads
        """
        QXmlQuery.setInitialTemplateName(QXmlName)
        QXmlQuery.setInitialTemplateName(str)
        """
        pass

    def setMessageHandler(self, QAbstractMessageHandler
                          ):  # real signature unknown; restored from __doc__
        """ QXmlQuery.setMessageHandler(QAbstractMessageHandler) """
        pass

    def setNetworkAccessManager(
        self, QNetworkAccessManager
    ):  # real signature unknown; restored from __doc__
        """ QXmlQuery.setNetworkAccessManager(QNetworkAccessManager) """
        pass

    def setQuery(
        self, *__args
    ):  # real signature unknown; restored from __doc__ with multiple overloads
        """
        QXmlQuery.setQuery(str, QUrl documentUri=QUrl())
        QXmlQuery.setQuery(QIODevice, QUrl documentUri=QUrl())
        QXmlQuery.setQuery(QUrl, QUrl baseUri=QUrl())
        """
        pass

    def setUriResolver(self, QAbstractUriResolver
                       ):  # real signature unknown; restored from __doc__
        """ QXmlQuery.setUriResolver(QAbstractUriResolver) """
        pass

    def uriResolver(self):  # real signature unknown; restored from __doc__
        """ QXmlQuery.uriResolver() -> QAbstractUriResolver """
        return QAbstractUriResolver

    def __init__(
        self, *__args
    ):  # real signature unknown; restored from __doc__ with multiple overloads
        pass

    __weakref__ = property(lambda self: object(), lambda self, v: None,
                           lambda self: None)  # default
    """list of weak references to the object (if defined)"""

    QueryLanguage = None  # (!) real value is ''
    XQuery10 = 1
    XSLT20 = 2
Example #36
0
class QAbstractXmlReceiver():  # skipped bases: <class 'sip.simplewrapper'>
    """ QAbstractXmlReceiver() """
    def atomicValue(self,
                    p_object):  # real signature unknown; restored from __doc__
        """ QAbstractXmlReceiver.atomicValue(object) """
        pass

    def attribute(self, QXmlName,
                  QStringRef):  # real signature unknown; restored from __doc__
        """ QAbstractXmlReceiver.attribute(QXmlName, QStringRef) """
        pass

    def characters(
            self, QStringRef):  # real signature unknown; restored from __doc__
        """ QAbstractXmlReceiver.characters(QStringRef) """
        pass

    def comment(self, p_str):  # real signature unknown; restored from __doc__
        """ QAbstractXmlReceiver.comment(str) """
        pass

    def endDocument(self):  # real signature unknown; restored from __doc__
        """ QAbstractXmlReceiver.endDocument() """
        pass

    def endElement(self):  # real signature unknown; restored from __doc__
        """ QAbstractXmlReceiver.endElement() """
        pass

    def endOfSequence(self):  # real signature unknown; restored from __doc__
        """ QAbstractXmlReceiver.endOfSequence() """
        pass

    def namespaceBinding(
            self, QXmlName):  # real signature unknown; restored from __doc__
        """ QAbstractXmlReceiver.namespaceBinding(QXmlName) """
        pass

    def processingInstruction(
            self, QXmlName,
            p_str):  # real signature unknown; restored from __doc__
        """ QAbstractXmlReceiver.processingInstruction(QXmlName, str) """
        pass

    def startDocument(self):  # real signature unknown; restored from __doc__
        """ QAbstractXmlReceiver.startDocument() """
        pass

    def startElement(
            self, QXmlName):  # real signature unknown; restored from __doc__
        """ QAbstractXmlReceiver.startElement(QXmlName) """
        pass

    def startOfSequence(self):  # real signature unknown; restored from __doc__
        """ QAbstractXmlReceiver.startOfSequence() """
        pass

    def __init__(self):  # real signature unknown; restored from __doc__
        pass

    __weakref__ = property(lambda self: object(), lambda self, v: None,
                           lambda self: None)  # default
    """list of weak references to the object (if defined)"""
Example #37
0
class QXmlName():  # skipped bases: <class 'sip.simplewrapper'>
    """
    QXmlName()
    QXmlName(QXmlNamePool, str, str namespaceUri='', str prefix='')
    QXmlName(QXmlName)
    """
    def fromClarkName(
            self, p_str,
            QXmlNamePool):  # real signature unknown; restored from __doc__
        """ QXmlName.fromClarkName(str, QXmlNamePool) -> QXmlName """
        return QXmlName

    def isNCName(self, p_str):  # real signature unknown; restored from __doc__
        """ QXmlName.isNCName(str) -> bool """
        return False

    def isNull(self):  # real signature unknown; restored from __doc__
        """ QXmlName.isNull() -> bool """
        return False

    def localName(
            self,
            QXmlNamePool):  # real signature unknown; restored from __doc__
        """ QXmlName.localName(QXmlNamePool) -> str """
        return ""

    def namespaceUri(
            self,
            QXmlNamePool):  # real signature unknown; restored from __doc__
        """ QXmlName.namespaceUri(QXmlNamePool) -> str """
        return ""

    def prefix(self,
               QXmlNamePool):  # real signature unknown; restored from __doc__
        """ QXmlName.prefix(QXmlNamePool) -> str """
        return ""

    def toClarkName(
            self,
            QXmlNamePool):  # real signature unknown; restored from __doc__
        """ QXmlName.toClarkName(QXmlNamePool) -> str """
        return ""

    def __eq__(self, *args, **kwargs):  # real signature unknown
        """ Return self==value. """
        pass

    def __ge__(self, *args, **kwargs):  # real signature unknown
        """ Return self>=value. """
        pass

    def __gt__(self, *args, **kwargs):  # real signature unknown
        """ Return self>value. """
        pass

    def __hash__(self, *args, **kwargs):  # real signature unknown
        """ Return hash(self). """
        pass

    def __init__(
        self, *__args
    ):  # real signature unknown; restored from __doc__ with multiple overloads
        pass

    def __le__(self, *args, **kwargs):  # real signature unknown
        """ Return self<=value. """
        pass

    def __lt__(self, *args, **kwargs):  # real signature unknown
        """ Return self<value. """
        pass

    def __ne__(self, *args, **kwargs):  # real signature unknown
        """ Return self!=value. """
        pass

    __weakref__ = property(lambda self: object(), lambda self, v: None,
                           lambda self: None)  # default
    """list of weak references to the object (if defined)"""
Example #38
0
class TimeFromEpoch(TimeFormat):
    """
    Base class for times that represent the interval from a particular
    epoch as a floating point multiple of a unit time interval (e.g. seconds
    or days).
    """

    def __init__(self, val1, val2, scale, precision,
                 in_subfmt, out_subfmt, from_jd=False):
        self.scale = scale
        # Initialize the reference epoch (a single time defined in subclasses)
        epoch = Time(self.epoch_val, self.epoch_val2, scale=self.epoch_scale,
                     format=self.epoch_format)
        self.epoch = epoch

        # Now create the TimeFormat object as normal
        super().__init__(val1, val2, scale, precision, in_subfmt, out_subfmt,
                         from_jd)

    def set_jds(self, val1, val2):
        """
        Initialize the internal jd1 and jd2 attributes given val1 and val2.
        For an TimeFromEpoch subclass like TimeUnix these will be floats giving
        the effective seconds since an epoch time (e.g. 1970-01-01 00:00:00).
        """
        # Form new JDs based on epoch time + time from epoch (converted to JD).
        # One subtlety that might not be obvious is that 1.000 Julian days in
        # UTC can be 86400 or 86401 seconds.  For the TimeUnix format the
        # assumption is that every day is exactly 86400 seconds, so this is, in
        # principle, doing the math incorrectly, *except* that it matches the
        # definition of Unix time which does not include leap seconds.

        # note: use divisor=1./self.unit, since this is either 1 or 1/86400,
        # and 1/86400 is not exactly representable as a float64, so multiplying
        # by that will cause rounding errors. (But inverting it as a float64
        # recovers the exact number)
        day, frac = day_frac(val1, val2, divisor=1. / self.unit)

        jd1 = self.epoch.jd1 + day
        jd2 = self.epoch.jd2 + frac

        # Create a temporary Time object corresponding to the new (jd1, jd2) in
        # the epoch scale (e.g. UTC for TimeUnix) then convert that to the
        # desired time scale for this object.
        #
        # A known limitation is that the transform from self.epoch_scale to
        # self.scale cannot involve any metadata like lat or lon.
        try:
            tm = getattr(Time(jd1, jd2, scale=self.epoch_scale,
                              format='jd'), self.scale)
        except Exception as err:
            raise ScaleValueError("Cannot convert from '{0}' epoch scale '{1}'"
                                  "to specified scale '{2}', got error:\n{3}"
                                  .format(self.name, self.epoch_scale,
                                          self.scale, err))

        self.jd1, self.jd2 = day_frac(tm._time.jd1, tm._time.jd2)

    def to_value(self, parent=None):
        # Make sure that scale is the same as epoch scale so we can just
        # subtract the epoch and convert
        if self.scale != self.epoch_scale:
            if parent is None:
                raise ValueError('cannot compute value without parent Time object')
            tm = getattr(parent, self.epoch_scale)
            jd1, jd2 = tm._time.jd1, tm._time.jd2
        else:
            jd1, jd2 = self.jd1, self.jd2

        time_from_epoch = ((jd1 - self.epoch.jd1) +
                           (jd2 - self.epoch.jd2)) / self.unit

        return self.mask_if_needed(time_from_epoch)

    value = property(to_value)
Example #39
0
class QSourceLocation():  # skipped bases: <class 'sip.simplewrapper'>
    """
    QSourceLocation()
    QSourceLocation(QSourceLocation)
    QSourceLocation(QUrl, int line=-1, int column=-1)
    """
    def column(self):  # real signature unknown; restored from __doc__
        """ QSourceLocation.column() -> int """
        return 0

    def isNull(self):  # real signature unknown; restored from __doc__
        """ QSourceLocation.isNull() -> bool """
        return False

    def line(self):  # real signature unknown; restored from __doc__
        """ QSourceLocation.line() -> int """
        return 0

    def setColumn(self,
                  p_int):  # real signature unknown; restored from __doc__
        """ QSourceLocation.setColumn(int) """
        pass

    def setLine(self, p_int):  # real signature unknown; restored from __doc__
        """ QSourceLocation.setLine(int) """
        pass

    def setUri(self, QUrl):  # real signature unknown; restored from __doc__
        """ QSourceLocation.setUri(QUrl) """
        pass

    def uri(self):  # real signature unknown; restored from __doc__
        """ QSourceLocation.uri() -> QUrl """
        pass

    def __eq__(self, *args, **kwargs):  # real signature unknown
        """ Return self==value. """
        pass

    def __ge__(self, *args, **kwargs):  # real signature unknown
        """ Return self>=value. """
        pass

    def __gt__(self, *args, **kwargs):  # real signature unknown
        """ Return self>value. """
        pass

    def __hash__(self, *args, **kwargs):  # real signature unknown
        """ Return hash(self). """
        pass

    def __init__(
        self, *__args
    ):  # real signature unknown; restored from __doc__ with multiple overloads
        pass

    def __le__(self, *args, **kwargs):  # real signature unknown
        """ Return self<=value. """
        pass

    def __lt__(self, *args, **kwargs):  # real signature unknown
        """ Return self<value. """
        pass

    def __ne__(self, *args, **kwargs):  # real signature unknown
        """ Return self!=value. """
        pass

    __weakref__ = property(lambda self: object(), lambda self, v: None,
                           lambda self: None)  # default
    """list of weak references to the object (if defined)"""
Example #40
0
class Unpickler(object):
    """
    This takes a binary file for reading a pickle data stream.
    
    The protocol version of the pickle is detected automatically, so no
    protocol argument is needed.  Bytes past the pickled object's
    representation are ignored.
    
    The argument *file* must have two methods, a read() method that takes
    an integer argument, and a readline() method that requires no
    arguments.  Both methods should return bytes.  Thus *file* can be a
    binary file object opened for reading, an io.BytesIO object, or any
    other custom object that meets this interface.
    
    Optional keyword arguments are *fix_imports*, *encoding* and *errors*,
    which are used to control compatibility support for pickle stream
    generated by Python 2.  If *fix_imports* is True, pickle will try to
    map the old Python 2 names to the new names used in Python 3.  The
    *encoding* and *errors* tell pickle how to decode 8-bit string
    instances pickled by Python 2; these default to 'ASCII' and 'strict',
    respectively.  The *encoding* can be 'bytes' to read these 8-bit
    string instances as bytes objects.
    """
    def find_class(self, *args, **kwargs):  # real signature unknown
        """
        Return an object from a specified module.
        
        If necessary, the module will be imported. Subclasses may override
        this method (e.g. to restrict unpickling of arbitrary classes and
        functions).
        
        This method is called whenever a class or a function object is
        needed.  Both arguments passed are str objects.
        """
        pass

    def load(self, *args, **kwargs):  # real signature unknown
        """
        Load a pickle.
        
        Read a pickled object representation from the open file object given
        in the constructor, and return the reconstituted object hierarchy
        specified therein.
        """
        pass

    def __init__(self, *args, **kwargs):  # real signature unknown
        pass

    @staticmethod  # known case of __new__
    def __new__(*args, **kwargs):  # real signature unknown
        """ Create and return a new object.  See help(type) for accurate signature. """
        pass

    def __sizeof__(self, *args, **kwargs):  # real signature unknown
        """ Returns size in memory, in bytes. """
        pass

    memo = property(lambda self: object(), lambda self, v: None,
                    lambda self: None)  # default

    persistent_load = property(lambda self: object(), lambda self, v: None,
                               lambda self: None)  # default
Example #41
0
class TimeDatetime(TimeUnique):
    """
    Represent date as Python standard library `~datetime.datetime` object

    Example::

      >>> from astropy.time import Time
      >>> from datetime import datetime
      >>> t = Time(datetime(2000, 1, 2, 12, 0, 0), scale='utc')
      >>> t.iso
      '2000-01-02 12:00:00.000'
      >>> t.tt.datetime
      datetime.datetime(2000, 1, 2, 12, 1, 4, 184000)
    """
    name = 'datetime'

    def _check_val_type(self, val1, val2):
        # Note: don't care about val2 for this class
        if not all(isinstance(val, datetime.datetime) for val in val1.flat):
            raise TypeError('Input values for {0} class must be '
                            'datetime objects'.format(self.name))
        return val1, None

    def set_jds(self, val1, val2):
        """Convert datetime object contained in val1 to jd1, jd2"""
        # Iterate through the datetime objects, getting year, month, etc.
        iterator = np.nditer([val1, None, None, None, None, None, None],
                             flags=['refs_ok'],
                             op_dtypes=[object] + 5*[np.intc] + [np.double])
        for val, iy, im, id, ihr, imin, dsec in iterator:
            dt = val.item()

            if dt.tzinfo is not None:
                dt = (dt - dt.utcoffset()).replace(tzinfo=None)

            iy[...] = dt.year
            im[...] = dt.month
            id[...] = dt.day
            ihr[...] = dt.hour
            imin[...] = dt.minute
            dsec[...] = dt.second + dt.microsecond / 1e6

        jd1, jd2 = erfa.dtf2d(self.scale.upper().encode('ascii'),
                              *iterator.operands[1:])
        self.jd1, self.jd2 = day_frac(jd1, jd2)

    def to_value(self, timezone=None, parent=None):
        """
        Convert to (potentially timezone-aware) `~datetime.datetime` object.

        If ``timezone`` is not ``None``, return a timezone-aware datetime
        object.

        Parameters
        ----------
        timezone : {`~datetime.tzinfo`, None} (optional)
            If not `None`, return timezone-aware datetime.

        Returns
        -------
        `~datetime.datetime`
            If ``timezone`` is not ``None``, output will be timezone-aware.
        """
        if timezone is not None:
            if self._scale != 'utc':
                raise ScaleValueError("scale is {}, must be 'utc' when timezone "
                                      "is supplied.".format(self._scale))

        # Rather than define a value property directly, we have a function,
        # since we want to be able to pass in timezone information.
        scale = self.scale.upper().encode('ascii')
        iys, ims, ids, ihmsfs = erfa.d2dtf(scale, 6,  # 6 for microsec
                                           self.jd1, self.jd2_filled)
        ihrs = ihmsfs[..., 0]
        imins = ihmsfs[..., 1]
        isecs = ihmsfs[..., 2]
        ifracs = ihmsfs[..., 3]
        iterator = np.nditer([iys, ims, ids, ihrs, imins, isecs, ifracs, None],
                             flags=['refs_ok'],
                             op_dtypes=7*[iys.dtype] + [object])

        for iy, im, id, ihr, imin, isec, ifracsec, out in iterator:
            if isec >= 60:
                raise ValueError('Time {} is within a leap second but datetime '
                                 'does not support leap seconds'
                                 .format((iy, im, id, ihr, imin, isec, ifracsec)))
            if timezone is not None:
                out[...] = datetime.datetime(iy, im, id, ihr, imin, isec, ifracsec,
                                             tzinfo=TimezoneInfo()).astimezone(timezone)
            else:
                out[...] = datetime.datetime(iy, im, id, ihr, imin, isec, ifracsec)

        return self.mask_if_needed(iterator.operands[-1])

    value = property(to_value)
Example #42
0
class ApiDocWriter(object):
    ''' Class for automatic detection and parsing of API docs
    to Sphinx-parsable reST format'''

    # only separating first two levels
    rst_section_levels = ['*', '=', '-', '~', '^']

    def __init__(self,
                 package_name,
                 rst_extension='.rst',
                 package_skip_patterns=None,
                 module_skip_patterns=None,
                 ):
        ''' Initialize package for parsing

        Parameters
        ----------
        package_name : string
            Name of the top-level package.  *package_name* must be the
            name of an importable package
        rst_extension : string, optional
            Extension for reST files, default '.rst'
        package_skip_patterns : None or sequence of {strings, regexps}
            Sequence of strings giving URIs of packages to be excluded
            Operates on the package path, starting at (including) the
            first dot in the package path, after *package_name* - so,
            if *package_name* is ``sphinx``, then ``sphinx.util`` will
            result in ``.util`` being passed for earching by these
            regexps.  If is None, gives default. Default is:
            ['\.tests$']
        module_skip_patterns : None or sequence
            Sequence of strings giving URIs of modules to be excluded
            Operates on the module name including preceding URI path,
            back to the first dot after *package_name*.  For example
            ``sphinx.util.console`` results in the string to search of
            ``.util.console``
            If is None, gives default. Default is:
            ['\.setup$', '\._']
        '''
        if package_skip_patterns is None:
            package_skip_patterns = ['\\.tests$']
        if module_skip_patterns is None:
            module_skip_patterns = ['\\.setup$', '\\._']
        self.package_name = package_name
        self.rst_extension = rst_extension
        self.package_skip_patterns = package_skip_patterns
        self.module_skip_patterns = module_skip_patterns

    def get_package_name(self):
        return self._package_name

    def set_package_name(self, package_name):
        ''' Set package_name

        >>> docwriter = ApiDocWriter('sphinx')
        >>> import sphinx
        >>> docwriter.root_path == sphinx.__path__[0]
        True
        >>> docwriter.package_name = 'docutils'
        >>> import docutils
        >>> docwriter.root_path == docutils.__path__[0]
        True
        '''
        # It's also possible to imagine caching the module parsing here
        self._package_name = package_name
        root_module = self._import(package_name)
        self.root_path = root_module.__path__[-1]
        self.written_modules = None

    package_name = property(get_package_name, set_package_name, None,
                            'get/set package_name')

    def _import(self, name):
        ''' Import namespace package '''
        mod = __import__(name)
        components = name.split('.')
        for comp in components[1:]:
            mod = getattr(mod, comp)
        return mod

    def _get_object_name(self, line):
        ''' Get second token in line
        >>> docwriter = ApiDocWriter('sphinx')
        >>> docwriter._get_object_name("  def func():  ")
        'func'
        >>> docwriter._get_object_name("  class Klass(object):  ")
        'Klass'
        >>> docwriter._get_object_name("  class Klass:  ")
        'Klass'
        '''
        name = line.split()[1].split('(')[0].strip()
        # in case we have classes which are not derived from object
        # ie. old style classes
        return name.rstrip(':')

    def _uri2path(self, uri):
        ''' Convert uri to absolute filepath

        Parameters
        ----------
        uri : string
            URI of python module to return path for

        Returns
        -------
        path : None or string
            Returns None if there is no valid path for this URI
            Otherwise returns absolute file system path for URI

        Examples
        --------
        >>> docwriter = ApiDocWriter('sphinx')
        >>> import sphinx
        >>> modpath = sphinx.__path__[0]
        >>> res = docwriter._uri2path('sphinx.builder')
        >>> res == os.path.join(modpath, 'builder.py')
        True
        >>> res = docwriter._uri2path('sphinx')
        >>> res == os.path.join(modpath, '__init__.py')
        True
        >>> docwriter._uri2path('sphinx.does_not_exist')

        '''
        if uri == self.package_name:
            return os.path.join(self.root_path, '__init__.py')
        path = uri.replace(self.package_name + '.', '')
        path = path.replace('.', os.path.sep)
        path = os.path.join(self.root_path, path)
        # XXX maybe check for extensions as well?
        if os.path.exists(path + '.py'): # file
            path += '.py'
        elif os.path.exists(os.path.join(path, '__init__.py')):
            path = os.path.join(path, '__init__.py')
        else:
            return None
        return path

    def _path2uri(self, dirpath):
        ''' Convert directory path to uri '''
        package_dir = self.package_name.replace('.', os.path.sep)
        relpath = dirpath.replace(self.root_path, package_dir)
        if relpath.startswith(os.path.sep):
            relpath = relpath[1:]
        return relpath.replace(os.path.sep, '.')

    def _parse_module(self, uri):
        ''' Parse module defined in *uri* '''
        filename = self._uri2path(uri)
        if filename is None:
            print(filename, 'erk')
            # nothing that we could handle here.
            return ([],[])
        f = open(filename, 'rt')
        functions, classes = self._parse_lines(f)
        f.close()
        return functions, classes

    def _parse_module_with_import(self, uri):
        """Look for functions and classes in an importable module.

        Parameters
        ----------
        uri : str
            The name of the module to be parsed. This module needs to be
            importable.

        Returns
        -------
        functions : list of str
            A list of (public) function names in the module.
        classes : list of str
            A list of (public) class names in the module.
        submodules : list of str
            A list of (public) submodule names in the module.
        """
        mod = __import__(uri, fromlist=[uri.split('.')[-1]])
        # find all public objects in the module.
        obj_strs = getattr(mod, '__all__',
                           [obj for obj in dir(mod) if not obj.startswith('_')])
        functions = []
        classes = []
        submodules = []
        for obj_str in obj_strs:
            # find the actual object from its string representation
            if obj_str not in mod.__dict__:
                continue
            obj = mod.__dict__[obj_str]

            # figure out if obj is a function or class
            if isinstance(obj, (FunctionType, BuiltinFunctionType)):
                functions.append(obj_str)
            elif isinstance(obj, ModuleType) and 'skimage' in mod.__name__:
                submodules.append(obj_str)
            else:
                try:
                    issubclass(obj, object)
                    classes.append(obj_str)
                except TypeError:
                    # not a function or class
                    pass
        return functions, classes, submodules

    def _parse_lines(self, linesource):
        ''' Parse lines of text for functions and classes '''
        functions = []
        classes = []
        for line in linesource:
            if line.startswith('def ') and line.count('('):
                # exclude private stuff
                name = self._get_object_name(line)
                if not name.startswith('_'):
                    functions.append(name)
            elif line.startswith('class '):
                # exclude private stuff
                name = self._get_object_name(line)
                if not name.startswith('_'):
                    classes.append(name)
            else:
                pass
        functions.sort()
        classes.sort()
        return functions, classes

    def generate_api_doc(self, uri):
        '''Make autodoc documentation template string for a module

        Parameters
        ----------
        uri : string
            python location of module - e.g 'sphinx.builder'

        Returns
        -------
        S : string
            Contents of API doc
        '''
        # get the names of all classes and functions
        functions, classes, submodules = self._parse_module_with_import(uri)
        if not (len(functions) or len(classes) or len(submodules)) and DEBUG:
            print('WARNING: Empty -', uri)
            return ''
        functions = sorted(functions)
        classes = sorted(classes)
        submodules = sorted(submodules)

        # Make a shorter version of the uri that omits the package name for
        # titles
        uri_short = re.sub(r'^%s\.' % self.package_name,'',uri)

        ad = '.. AUTO-GENERATED FILE -- DO NOT EDIT!\n\n'

        # Set the chapter title to read 'module' for all modules except for the
        # main packages
        if '.' in uri:
            title = 'Module: :mod:`' + uri_short + '`'
        else:
            title = ':mod:`' + uri_short + '`'
        ad += title + '\n' + self.rst_section_levels[1] * len(title)

        ad += '\n.. automodule:: ' + uri + '\n'
        ad += '\n.. currentmodule:: ' + uri + '\n'
        ad += '.. autosummary::\n\n'
        for f in functions:
            ad += '   ' + uri + '.' + f + '\n'
        ad += '\n'
        for c in classes:
            ad += '   ' + uri + '.' + c + '\n'
        ad += '\n'
        for m in submodules:
            ad += '    ' + uri + '.' + m + '\n'
        ad += '\n'

        for f in functions:
            # must NOT exclude from index to keep cross-refs working
            full_f = uri + '.' + f
            ad += f + '\n'
            ad += self.rst_section_levels[2] * len(f) + '\n'
            ad += '\n.. autofunction:: ' + full_f + '\n\n'
            ad += '\n.. include:: ' + full_f + '.examples\n\n'
        for c in classes:
            ad += '\n:class:`' + c + '`\n' \
                  + self.rst_section_levels[2] * \
                  (len(c)+9) + '\n\n'
            ad += '\n.. autoclass:: ' + c + '\n'
            # must NOT exclude from index to keep cross-refs working
            ad += '  :members:\n' \
                  '  :undoc-members:\n' \
                  '  :show-inheritance:\n' \
                  '\n' \
                  '  .. automethod:: __init__\n'
            full_c = uri + '.' + c
            ad += '\n.. include:: ' + full_c + '.examples\n\n'
        return ad

    def _survives_exclude(self, matchstr, match_type):
        ''' Returns True if *matchstr* does not match patterns

        ``self.package_name`` removed from front of string if present

        Examples
        --------
        >>> dw = ApiDocWriter('sphinx')
        >>> dw._survives_exclude('sphinx.okpkg', 'package')
        True
        >>> dw.package_skip_patterns.append('^\\.badpkg$')
        >>> dw._survives_exclude('sphinx.badpkg', 'package')
        False
        >>> dw._survives_exclude('sphinx.badpkg', 'module')
        True
        >>> dw._survives_exclude('sphinx.badmod', 'module')
        True
        >>> dw.module_skip_patterns.append('^\\.badmod$')
        >>> dw._survives_exclude('sphinx.badmod', 'module')
        False
        '''
        if match_type == 'module':
            patterns = self.module_skip_patterns
        elif match_type == 'package':
            patterns = self.package_skip_patterns
        else:
            raise ValueError('Cannot interpret match type "%s"'
                             % match_type)
        # Match to URI without package name
        L = len(self.package_name)
        if matchstr[:L] == self.package_name:
            matchstr = matchstr[L:]
        for pat in patterns:
            try:
                pat.search
            except AttributeError:
                pat = re.compile(pat)
            if pat.search(matchstr):
                return False
        return True

    def discover_modules(self):
        ''' Return module sequence discovered from ``self.package_name``


        Parameters
        ----------
        None

        Returns
        -------
        mods : sequence
            Sequence of module names within ``self.package_name``

        Examples
        --------
        >>> dw = ApiDocWriter('sphinx')
        >>> mods = dw.discover_modules()
        >>> 'sphinx.util' in mods
        True
        >>> dw.package_skip_patterns.append('\.util$')
        >>> 'sphinx.util' in dw.discover_modules()
        False
        >>>
        '''
        modules = [self.package_name]
        # raw directory parsing
        for dirpath, dirnames, filenames in os.walk(self.root_path):
            # Check directory names for packages
            root_uri = self._path2uri(os.path.join(self.root_path,
                                                   dirpath))
            for dirname in dirnames[:]: # copy list - we modify inplace
                package_uri = '.'.join((root_uri, dirname))
                if (self._uri2path(package_uri) and
                    self._survives_exclude(package_uri, 'package')):
                    modules.append(package_uri)
                else:
                    dirnames.remove(dirname)
        return sorted(modules)

    def write_modules_api(self, modules, outdir):
        # write the list
        written_modules = []
        public_modules = [m for m in modules
                          if not m.split('.')[-1].startswith('_')]
        for m in public_modules:
            api_str = self.generate_api_doc(m)
            if not api_str:
                continue
            # write out to file
            outfile = os.path.join(outdir,
                                   m + self.rst_extension)
            fileobj = open(outfile, 'wt')
            fileobj.write(api_str)
            fileobj.close()
            written_modules.append(m)
        self.written_modules = written_modules

    def write_api_docs(self, outdir):
        """Generate API reST files.

        Parameters
        ----------
        outdir : string
            Directory name in which to store files
            We create automatic filenames for each module

        Returns
        -------
        None

        Notes
        -----
        Sets self.written_modules to list of written modules
        """
        if not os.path.exists(outdir):
            os.mkdir(outdir)
        # compose list of modules
        modules = self.discover_modules()
        self.write_modules_api(modules, outdir)

    def write_index(self, outdir, froot='gen', relative_to=None):
        """Make a reST API index file from written files

        Parameters
        ----------
        path : string
            Filename to write index to
        outdir : string
            Directory to which to write generated index file
        froot : string, optional
            root (filename without extension) of filename to write to
            Defaults to 'gen'.  We add ``self.rst_extension``.
        relative_to : string
            path to which written filenames are relative.  This
            component of the written file path will be removed from
            outdir, in the generated index.  Default is None, meaning,
            leave path as it is.
        """
        if self.written_modules is None:
            raise ValueError('No modules written')
        # Get full filename path
        path = os.path.join(outdir, froot+self.rst_extension)
        # Path written into index is relative to rootpath
        if relative_to is not None:
            relpath = (outdir + os.path.sep).replace(relative_to + os.path.sep, '')
        else:
            relpath = outdir
        print("outdir: ", relpath)
        idx = open(path,'wt')
        w = idx.write
        w('.. AUTO-GENERATED FILE -- DO NOT EDIT!\n\n')

        # We look at the module name.  If it is `skimage`, display, if `skimage.submodule`, only show `submodule`,
        # if it is `skimage.submodule.subsubmodule`, ignore.

        title = "API Reference for skimage |version|"
        w(title + "\n")
        w("=" * len(title) + "\n\n")

        subtitle = "Submodules"
        w(subtitle + "\n")
        w("-" * len(subtitle) + "\n\n")

        for f in self.written_modules:
            module_name = f.split('.')
            if len(module_name) > 2:
                continue
            elif len(module_name) == 1:
                module_name = module_name[0]
                prefix = "-"
            elif len(module_name) == 2:
                module_name = module_name[1]
                prefix = "\n  -"
            w('{0} `{1} <{2}.html>`__\n'.format(prefix, module_name, os.path.join(f)))
        w('\n')

        subtitle = "Submodule Contents"
        w(subtitle + "\n")
        w("-" * len(subtitle) + "\n\n")

        w('.. toctree::\n')
        w('   :maxdepth: 2\n\n')
        for f in self.written_modules:
            w('   %s\n' % os.path.join(relpath,f))
        idx.close()
Example #43
0
class __loader__(object):
    """
    Meta path import for built-in modules.
    
        All methods are either class or static methods to avoid the need to
        instantiate the class.
    """
    @classmethod
    def create_module(cls, *args, **kwargs):  # real signature unknown
        """ Create a built-in module """
        pass

    @classmethod
    def exec_module(cls, *args, **kwargs):  # real signature unknown
        """ Exec a built-in module """
        pass

    @classmethod
    def find_module(cls, *args, **kwargs):  # real signature unknown
        """
        Find the built-in module.
        
                If 'path' is ever specified then the search is considered a failure.
        
                This method is deprecated.  Use find_spec() instead.
        """
        pass

    @classmethod
    def find_spec(cls, *args, **kwargs):  # real signature unknown
        pass

    @classmethod
    def get_code(cls, *args, **kwargs):  # real signature unknown
        """ Return None as built-in modules do not have code objects. """
        pass

    @classmethod
    def get_source(cls, *args, **kwargs):  # real signature unknown
        """ Return None as built-in modules do not have source code. """
        pass

    @classmethod
    def is_package(cls, *args, **kwargs):  # real signature unknown
        """ Return False as built-in modules are never packages. """
        pass

    @classmethod
    def load_module(cls, *args, **kwargs):  # real signature unknown
        """
        Load the specified module into sys.modules and return it.
        
            This method is deprecated.  Use loader.exec_module instead.
        """
        pass

    def module_repr(module):  # reliably restored by inspect
        """
        Return repr for the module.
        
                The method is deprecated.  The import machinery does the job itself.
        """
        pass

    def __init__(self, *args, **kwargs):  # real signature unknown
        pass

    __weakref__ = property(lambda self: object(), lambda self, v: None,
                           lambda self: None)  # default
    """list of weak references to the object (if defined)"""

    __dict__ = None  # (!) real value is ''
Example #44
0
class CameraInfo(object, IDisposable):
    """ An object holding information about the projection mapping of a 3D view. """

    def Dispose(self):
        """ Dispose(self: CameraInfo) """
        pass

    def ReleaseUnmanagedResources(self, *args):
        """ ReleaseUnmanagedResources(self: CameraInfo,disposing: bool) """
        pass

    def __enter__(self, *args):
        """ __enter__(self: IDisposable) -> object """
        pass

    def __exit__(self, *args):
        """ __exit__(self: IDisposable,exc_type: object,exc_value: object,exc_back: object) """
        pass

    def __init__(self, *args):
        """ x.__init__(...) initializes x; see x.__class__.__doc__ for signaturex.__init__(...) initializes x; see x.__class__.__doc__ for signaturex.__init__(...) initializes x; see x.__class__.__doc__ for signature """
        pass

    def __repr__(self, *args):
        """ __repr__(self: object) -> str """
        pass

    FarDistance = property(
        lambda self: object(), lambda self, v: None, lambda self: None
    )
    """Distance from eye point to far plane of view frustum along the view direction.



Get: FarDistance(self: CameraInfo) -> float



"""

    HorizontalExtent = property(
        lambda self: object(), lambda self, v: None, lambda self: None
    )
    """Distance between left and right planes on the target plane.



Get: HorizontalExtent(self: CameraInfo) -> float



"""

    IsPerspective = property(
        lambda self: object(), lambda self, v: None, lambda self: None
    )
    """Identifies whether the projection is orthographic or perspective



Get: IsPerspective(self: CameraInfo) -> bool



"""

    IsPespective = property(
        lambda self: object(), lambda self, v: None, lambda self: None
    )
    """Identifies whether the projection is orthographic or perspective



Get: IsPespective(self: CameraInfo) -> bool



"""

    IsValidObject = property(
        lambda self: object(), lambda self, v: None, lambda self: None
    )
    """Specifies whether the .NET object represents a valid Revit entity.



Get: IsValidObject(self: CameraInfo) -> bool



"""

    NearDistance = property(
        lambda self: object(), lambda self, v: None, lambda self: None
    )
    """Distance from eye point to near plane of view frustum along the view direction.



Get: NearDistance(self: CameraInfo) -> float



"""

    RightOffset = property(
        lambda self: object(), lambda self, v: None, lambda self: None
    )
    """Distance that the target plane is offset towards the right

   where right is normal to both Up direction and View direction.

   This offset shifts both left and right planes.



Get: RightOffset(self: CameraInfo) -> float



"""

    TargetDistance = property(
        lambda self: object(), lambda self, v: None, lambda self: None
    )
    """Distance from eye point along view direction to target plane.



Get: TargetDistance(self: CameraInfo) -> float



"""

    UpOffset = property(lambda self: object(), lambda self, v: None, lambda self: None)
    """Distance that the target plane is offset in the direction of

   the Up direction. This offset shifts both top and bottom planes.



Get: UpOffset(self: CameraInfo) -> float



"""

    VerticalExtent = property(
        lambda self: object(), lambda self, v: None, lambda self: None
    )
    """Distance between top and bottom planes on the target plane.
Example #45
0
class Pickler(object):
    """
    This takes a binary file for writing a pickle data stream.
    
    The optional *protocol* argument tells the pickler to use the given
    protocol; supported protocols are 0, 1, 2, 3 and 4.  The default
    protocol is 3; a backward-incompatible protocol designed for Python 3.
    
    Specifying a negative protocol version selects the highest protocol
    version supported.  The higher the protocol used, the more recent the
    version of Python needed to read the pickle produced.
    
    The *file* argument must have a write() method that accepts a single
    bytes argument. It can thus be a file object opened for binary
    writing, an io.BytesIO instance, or any other custom object that meets
    this interface.
    
    If *fix_imports* is True and protocol is less than 3, pickle will try
    to map the new Python 3 names to the old module names used in Python
    2, so that the pickle data stream is readable with Python 2.
    """
    def clear_memo(self, *args, **kwargs):  # real signature unknown
        """
        Clears the pickler's "memo".
        
        The memo is the data structure that remembers which objects the
        pickler has already seen, so that shared or recursive objects are
        pickled by reference and not by value.  This method is useful when
        re-using picklers.
        """
        pass

    def dump(self, *args, **kwargs):  # real signature unknown
        """ Write a pickled representation of the given object to the open file. """
        pass

    def __init__(self, *args, **kwargs):  # real signature unknown
        pass

    @staticmethod  # known case of __new__
    def __new__(*args, **kwargs):  # real signature unknown
        """ Create and return a new object.  See help(type) for accurate signature. """
        pass

    def __sizeof__(self, *args, **kwargs):  # real signature unknown
        """ Returns size in memory, in bytes. """
        pass

    bin = property(lambda self: object(), lambda self, v: None,
                   lambda self: None)  # default

    dispatch_table = property(lambda self: object(), lambda self, v: None,
                              lambda self: None)  # default

    fast = property(lambda self: object(), lambda self, v: None,
                    lambda self: None)  # default

    memo = property(lambda self: object(), lambda self, v: None,
                    lambda self: None)  # default

    persistent_id = property(lambda self: object(), lambda self, v: None,
                             lambda self: None)  # default
Example #46
0
class ConnectivityNode(IdentifiedObject):
    """Connectivity nodes are points where terminals of conducting equipment are connected together with zero impedance.
    """

    def __init__(self, ConnectivityNodeContainer=None, Terminals=None, *args, **kw_args):
        """Initialises a new 'ConnectivityNode' instance.

        @param ConnectivityNodeContainer: Container of this connectivity node.
        @param Terminals: Terminals interconnect with zero impedance at a node.  Measurements on a node apply to all of its terminals.
        """
        self._ConnectivityNodeContainer = None
        self.ConnectivityNodeContainer = ConnectivityNodeContainer

        self._Terminals = []
        self.Terminals = [] if Terminals is None else Terminals

        super(ConnectivityNode, self).__init__(*args, **kw_args)

    _attrs = []
    _attr_types = {}
    _defaults = {}
    _enums = {}
    _refs = ["ConnectivityNodeContainer", "Terminals"]
    _many_refs = ["Terminals"]

    def getConnectivityNodeContainer(self):
        """Container of this connectivity node.
        """
        return self._ConnectivityNodeContainer

    def setConnectivityNodeContainer(self, value):
        if self._ConnectivityNodeContainer is not None:
            filtered = [x for x in self.ConnectivityNodeContainer.ConnectivityNodes if x != self]
            self._ConnectivityNodeContainer._ConnectivityNodes = filtered

        self._ConnectivityNodeContainer = value
        if self._ConnectivityNodeContainer is not None:
            if self not in self._ConnectivityNodeContainer._ConnectivityNodes:
                self._ConnectivityNodeContainer._ConnectivityNodes.append(self)

    ConnectivityNodeContainer = property(getConnectivityNodeContainer, setConnectivityNodeContainer)

    def getTerminals(self):
        """Terminals interconnect with zero impedance at a node.  Measurements on a node apply to all of its terminals.
        """
        return self._Terminals

    def setTerminals(self, value):
        for x in self._Terminals:
            x.ConnectivityNode = None
        for y in value:
            y._ConnectivityNode = self
        self._Terminals = value

    Terminals = property(getTerminals, setTerminals)

    def addTerminals(self, *Terminals):
        for obj in Terminals:
            obj.ConnectivityNode = self

    def removeTerminals(self, *Terminals):
        for obj in Terminals:
            obj.ConnectivityNode = None
Example #47
0
class ObjectWrapper(metaclass=MetaObjectWrapper):
    """
    This class provides a same common interface for all (FBX-wise) object-like elements:
    * Blender Object
    * Blender Bone and PoseBone
    * Blender DupliObject
    Note since a same Blender object might be 'mapped' to several FBX models (esp. with duplis),
    we need to use a key to identify each.
    """
    __slots__ = (
        'name', 'key', 'bdata', 'parented_to_armature',
        '_tag', '_ref', '_dupli_matrix'
    )

    @classmethod
    def cache_clear(cls):
        if hasattr(cls, "_cache"):
            del cls._cache

    @staticmethod
    def _get_dup_num_id(bdata):
        return ".".join(str(i) for i in bdata.persistent_id if i != 2147483647)

    def __init__(self, bdata, armature=None):
        """
        bdata might be an Object, DupliObject, Bone or PoseBone.
        If Bone or PoseBone, armature Object must be provided.
        """
        if isinstance(bdata, Object):
            self._tag = 'OB'
            self.name = get_blenderID_name(bdata)
            self.bdata = bdata
            self._ref = None
        elif isinstance(bdata, DupliObject):
            self._tag = 'DP'
            self.name = "|".join((get_blenderID_name((bdata.id_data, bdata.object)),
                                  "Dupli", self._get_dup_num_id(bdata)))
            self.bdata = bdata.object
            self._ref = bdata.id_data
        else:  # isinstance(bdata, (Bone, PoseBone)):
            if isinstance(bdata, PoseBone):
                bdata = armature.data.bones[bdata.name]
            self._tag = 'BO'
            self.name = get_blenderID_name(bdata)
            self.bdata = bdata
            self._ref = armature
        self.parented_to_armature = False

    def __eq__(self, other):
        return isinstance(other, self.__class__) and self.key == other.key

    def __hash__(self):
        return hash(self.key)

    # #### Common to all _tag values.
    def get_fbx_uuid(self):
        return get_fbx_uuid_from_key(self.key)
    fbx_uuid = property(get_fbx_uuid)

    def get_hide(self):
        return self.bdata.hide
    hide = property(get_hide)

    def get_parent(self):
        if self._tag == 'OB':
            if (self.bdata.parent and self.bdata.parent.type == 'ARMATURE' and
                self.bdata.parent_type == 'BONE' and self.bdata.parent_bone):
                # Try to parent to a bone.
                bo_par = self.bdata.parent.pose.bones.get(self.bdata.parent_bone, None)
                if (bo_par):
                    return ObjectWrapper(bo_par, self.bdata.parent)
                else:  # Fallback to mere object parenting.
                    return ObjectWrapper(self.bdata.parent)
            else:
                # Mere object parenting.
                return ObjectWrapper(self.bdata.parent)
        elif self._tag == 'DP':
            return ObjectWrapper(self.bdata.parent or self._ref)
        else:  # self._tag == 'BO'
            return ObjectWrapper(self.bdata.parent, self._ref) or ObjectWrapper(self._ref)
    parent = property(get_parent)

    def get_matrix_local(self):
        if self._tag == 'OB':
            return self.bdata.matrix_local.copy()
        elif self._tag == 'DP':
            return self._ref.matrix_world.inverted_safe() * self._dupli_matrix
        else:  # 'BO', current pose
            # PoseBone.matrix is in armature space, bring in back in real local one!
            par = self.bdata.parent
            par_mat_inv = self._ref.pose.bones[par.name].matrix.inverted_safe() if par else Matrix()
            return par_mat_inv * self._ref.pose.bones[self.bdata.name].matrix
    matrix_local = property(get_matrix_local)

    def get_matrix_global(self):
        if self._tag == 'OB':
            return self.bdata.matrix_world.copy()
        elif self._tag == 'DP':
            return self._dupli_matrix
        else:  # 'BO', current pose
            return self._ref.matrix_world * self._ref.pose.bones[self.bdata.name].matrix
    matrix_global = property(get_matrix_global)

    def get_matrix_rest_local(self):
        if self._tag == 'BO':
            # Bone.matrix_local is in armature space, bring in back in real local one!
            par = self.bdata.parent
            par_mat_inv = par.matrix_local.inverted_safe() if par else Matrix()
            return par_mat_inv * self.bdata.matrix_local
        else:
            return self.matrix_local.copy()
    matrix_rest_local = property(get_matrix_rest_local)

    def get_matrix_rest_global(self):
        if self._tag == 'BO':
            return self._ref.matrix_world * self.bdata.matrix_local
        else:
            return self.matrix_global.copy()
    matrix_rest_global = property(get_matrix_rest_global)

    # #### Transform and helpers
    def has_valid_parent(self, objects):
        par = self.parent
        if par in objects:
            if self._tag == 'OB':
                par_type = self.bdata.parent_type
                if par_type in {'OBJECT', 'BONE'}:
                    return True
                else:
                    print("Sorry, “{}” parenting type is not supported".format(par_type))
                    return False
            return True
        return False

    def use_bake_space_transform(self, scene_data):
        # NOTE: Only applies to object types supporting this!!! Currently, only meshes and the like...
        # TODO: Check whether this can work for bones too...
        return (scene_data.settings.bake_space_transform and self._tag in {'OB', 'DP'} and
                self.bdata.type in BLENDER_OBJECT_TYPES_MESHLIKE | {'EMPTY'})

    def fbx_object_matrix(self, scene_data, rest=False, local_space=False, global_space=False):
        """
        Generate object transform matrix (*always* in matching *FBX* space!).
        If local_space is True, returned matrix is *always* in local space.
        Else if global_space is True, returned matrix is always in world space.
        If both local_space and global_space are False, returned matrix is in parent space if parent is valid,
        else in world space.
        Note local_space has precedence over global_space.
        If rest is True and object is a Bone, returns matching rest pose transform instead of current pose one.
        Applies specific rotation to bones, lamps and cameras (conversion Blender -> FBX).
        """
        # Objects which are not bones and do not have any parent are *always* in global space
        # (unless local_space is True!).
        is_global = (not local_space and
                     (global_space or not (self._tag in {'DP', 'BO'} or self.has_valid_parent(scene_data.objects))))

        # Objects (meshes!) parented to armature are not parented to anything in FBX, hence we need them
        # in global space, which is their 'virtual' local space...
        is_global = is_global or self.parented_to_armature

        # Since we have to apply corrections to some types of object, we always need local Blender space here...
        matrix = self.matrix_rest_local if rest else self.matrix_local
        parent = self.parent

        # Bones, lamps and cameras need to be rotated (in local space!).
        if self._tag == 'BO':
            # If we have a bone parent we need to undo the parent correction.
            if not is_global and scene_data.settings.bone_correction_matrix_inv and parent and parent.is_bone:
                matrix = scene_data.settings.bone_correction_matrix_inv * matrix
            # Apply the bone correction.
            if scene_data.settings.bone_correction_matrix:
                matrix = matrix * scene_data.settings.bone_correction_matrix
        elif self.bdata.type == 'LAMP':
            matrix = matrix * MAT_CONVERT_LAMP
        elif self.bdata.type == 'CAMERA':
            matrix = matrix * MAT_CONVERT_CAMERA

        if self._tag in {'DP', 'OB'} and parent:
            if parent._tag == 'BO':
                # In bone parent case, we get transformation in **bone tip** space (sigh).
                # Have to bring it back into bone root, which is FBX expected value.
                matrix = Matrix.Translation((0, (parent.bdata.tail - parent.bdata.head).length, 0)) * matrix

        # Our matrix is in local space, time to bring it in its final desired space.
        if parent:
            if is_global:
                # Move matrix to global Blender space.
                matrix = (parent.matrix_rest_global if rest else parent.matrix_global) * matrix
            elif parent.use_bake_space_transform(scene_data):
                # Blender's and FBX's local space of parent may differ if we use bake_space_transform...
                # Apply parent's *Blender* local space...
                matrix = (parent.matrix_rest_local if rest else parent.matrix_local) * matrix
                # ...and move it back into parent's *FBX* local space.
                par_mat = parent.fbx_object_matrix(scene_data, rest=rest, local_space=True)
                matrix = par_mat.inverted_safe() * matrix

        if self.use_bake_space_transform(scene_data):
            # If we bake the transforms we need to post-multiply inverse global transform.
            # This means that the global transform will not apply to children of this transform.
            matrix = matrix * scene_data.settings.global_matrix_inv
        if is_global:
            # In any case, pre-multiply the global matrix to get it in FBX global space!
            matrix = scene_data.settings.global_matrix * matrix

        return matrix

    def fbx_object_tx(self, scene_data, rest=False, rot_euler_compat=None):
        """
        Generate object transform data (always in local space when possible).
        """
        matrix = self.fbx_object_matrix(scene_data, rest=rest)
        loc, rot, scale = matrix.decompose()
        matrix_rot = rot.to_matrix()
        # quat -> euler, we always use 'XYZ' order, use ref rotation if given.
        if rot_euler_compat is not None:
            rot = rot.to_euler('XYZ', rot_euler_compat)
        else:
            rot = rot.to_euler('XYZ')
        return loc, rot, scale, matrix, matrix_rot

    # #### _tag dependent...
    def get_is_object(self):
        return self._tag == 'OB'
    is_object = property(get_is_object)

    def get_is_dupli(self):
        return self._tag == 'DP'
    is_dupli = property(get_is_dupli)

    def get_is_bone(self):
        return self._tag == 'BO'
    is_bone = property(get_is_bone)

    def get_type(self):
        if self._tag in {'OB', 'DP'}:
            return self.bdata.type
        return ...
    type = property(get_type)

    def get_armature(self):
        if self._tag == 'BO':
            return ObjectWrapper(self._ref)
        return None
    armature = property(get_armature)

    def get_bones(self):
        if self._tag == 'OB' and self.bdata.type == 'ARMATURE':
            return (ObjectWrapper(bo, self.bdata) for bo in self.bdata.data.bones)
        return ()
    bones = property(get_bones)

    def get_material_slots(self):
        if self._tag in {'OB', 'DP'}:
            return self.bdata.material_slots
        return ()
    material_slots = property(get_material_slots)

    def is_deformed_by_armature(self, arm_obj):
        if not (self.is_object and self.type == 'MESH'):
            return False
        if self.parent == arm_obj and self.bdata.parent_type == 'ARMATURE':
            return True
        for mod in self.bdata.modifiers:
            if mod.type == 'ARMATURE' and mod.object in {arm_obj.bdata, arm_obj.bdata.proxy}:
                return True

    # #### Duplis...
    def dupli_list_create(self, scene, settings='PREVIEW'):
        if self._tag == 'OB' and self.bdata.is_duplicator:
            self.bdata.dupli_list_create(scene, settings)

    def dupli_list_clear(self):
        if self._tag == 'OB'and self.bdata.is_duplicator:
            self.bdata.dupli_list_clear()

    def get_dupli_list(self):
        if self._tag == 'OB'and self.bdata.is_duplicator:
            return (ObjectWrapper(dup) for dup in self.bdata.dupli_list)
        return ()
    dupli_list = property(get_dupli_list)
Example #48
0
class RemoteControl(Source):
	# Flags
	FLAG_MAKE = 0
	FLAG_BREAK = 1
	FLAG_REPEAT = 2
	FLAG_LONG = 3
	FLAG_ASCII = 4
	
	#Device Types
	TYPE_STANDARD = "dreambox remote control (native)"
	TYPE_ADVANCED = "dreambox advanced remote control (native)"
	TYPE_KEYBOARD = "dreambox ir keyboard"
		
	def __init__(self, session):
		self.cmd = None
		self.session = session
		Source.__init__(self)
		self.res = ( False, "Missing or wrong argument" )
		self.eam = eActionMap.getInstance()
		
		#Advanced remote or standard?
		
		if config.misc.rcused.value == 0:
			self.remotetype = self.TYPE_ADVANCED
		else:
			self.remotetype = self.TYPE_STANDARD
			
		print "[RemoteControl.__init__] Configured RCU-Type is '%s'" %(self.remotetype)										

	def handleCommand(self, cmd):
		self.cmd = cmd
		self.res = self.sendEvent()

	def sendEvent(self):
		if not self.cmd:
			print "[RemoteControl.sendEvent] cmd is empty or None"
			return self.res
		
		key = self.cmd.get("command", None)
		if key is None:
			print "[RemoteControl.sendEvent] Obligatory parameter 'command' is missing!"
			return ( False, "Obligatory parameter 'command' is missing!" )

		key = int(key)

		if key <= 0:			
			print "[RemoteControl.sendEvent] command <= 0 (%s)" % key
			return ( False, "the command was not > 0" )

		#type can be "long" or "ascii", everything else will result in FLAG_MAKE
		type = self.cmd.get('type', '')
		flag = self.FLAG_MAKE
		if type == "long":
			#Doesn't work yet (WHY?)
			#TODO Fix long key press
			flag = self.FLAG_LONG
		elif type == "ascii":
			flag = self.FLAG_ASCII
			
		remotetype = self.cmd.get("rcu", None)

		if remotetype == "standard":
			remotetype = self.TYPE_STANDARD
		elif remotetype == "advanced":
			remotetype = self.TYPE_ADVANCED
		elif remotetype == "keyboard":
			remotetype == self.TYPE_KEYBOARD
		else:
			remotetype = self.remotetype
		
		#If type=="long" we need to press send FLAG_MAKE first 
		if(flag == self.FLAG_LONG):			
			self.eam.keyPressed(remotetype, key, self.FLAG_MAKE)
		
		#press the key with the desired flag
		self.eam.keyPressed(remotetype, key, flag)
		#Release the key		
		self.eam.keyPressed(remotetype, key, self.FLAG_BREAK)
			
		print "[RemoteControl.sendEvent] command was was sent (key: %s, flag: %s)" %(key, flag)
		return ( True, "RC command '" + str(key) + "' has been issued" ) 

	result = property(lambda self: self.res)
Example #49
0
 def state(self):
     return synonym('_state', descriptor=property(self.get_state, self.set_state))
class ListBox(QWidget):
    def __init__(self, parent):
        QWidget.__init__(self, parent)
        while not isinstance(parent, QDialog):
            parent = parent.parent()
        self.setObjectName("ListBox" + str(len(parent.findChildren(ListBox))))


        self.hLayoutBoxPanel = QHBoxLayout(self)
        self.hLayoutBoxPanel.setSpacing(0)
        self.hLayoutBoxPanel.setContentsMargins(3,3,3,3)
        self.hLayoutBoxPanel.setObjectName(("hLayoutBoxPanel"))
        self.frameBoxPanel = QFrame(self)
        sizePolicy = QSizePolicy(QSizePolicy.Preferred, QSizePolicy.Fixed)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(self.frameBoxPanel.sizePolicy().hasHeightForWidth())
        self.frameBoxPanel.setSizePolicy(sizePolicy)
        self.frameBoxPanel.setFrameShape(QFrame.NoFrame)
        self.frameBoxPanel.setFrameShadow(QFrame.Raised)
        self.frameBoxPanel.setObjectName(("frameBoxPanel"))
        self.hLayoutframeBoxPanel = QHBoxLayout(self.frameBoxPanel)
        self.hLayoutframeBoxPanel.setSpacing(0)
        self.hLayoutframeBoxPanel.setMargin(0)
        self.hLayoutframeBoxPanel.setObjectName(("hLayoutframeBoxPanel"))
        self.captionLabel = QLabel(self.frameBoxPanel)
        sizePolicy = QSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(self.captionLabel.sizePolicy().hasHeightForWidth())
        self.captionLabel.setSizePolicy(sizePolicy)
        self.captionLabel.setMinimumSize(QSize(200, 0))
        self.captionLabel.setMaximumSize(QSize(200, 16777215))
        font = QFont()
        font.setBold(False)
        font.setWeight(50)
        self.captionLabel.setFont(font)
        self.captionLabel.setObjectName(("captionLabel"))
        self.hLayoutframeBoxPanel.addWidget(self.captionLabel)

        self.listBox = QListWidget(self.frameBoxPanel)
        self.listBox.setEnabled(True)
        font = QFont()
        font.setBold(False)
        font.setWeight(50)
        self.listBox.setFont(font)
        self.listBox.setObjectName(("listBox"))
        # self.listBox.setText("0.0")
        self.hLayoutframeBoxPanel.addWidget(self.listBox)

        self.imageButton = QToolButton(self.frameBoxPanel)
        self.imageButton.setText((""))
        icon = QIcon()
        icon.addPixmap(QPixmap(("Resource/convex_hull.png")), QIcon.Normal, QIcon.Off)
        self.imageButton.setIcon(icon)
        self.imageButton.setObjectName(("imageButton"))
        self.imageButton.setVisible(False)
        self.hLayoutframeBoxPanel.addWidget(self.imageButton)

        self.hLayoutBoxPanel.addWidget(self.frameBoxPanel)

        self.listBox.currentRowChanged.connect(self.listBoxChanged)
        self.imageButton.clicked.connect(self.imageButtonClicked)

        

        self.captionUnits = ""

        self.hasObject = False

        self.objectList = []
        self.captionLabel.setVisible(False)
    def get_Count(self):
        return self.listBox.count()
    Count = property(get_Count, None, None, None)
    def method_3(self, string_0):
        return self.listBox.row(self.listBox.findItems(string_0)[0]);

    def method_11(self, string_0):
        if (self.IsEmpty):
            return "%s%s\t"%(string_0, self.Caption);
        return "%s%s\t%s %s"%(string_0, self.Caption, self.Value, self.CaptionUnits);

    def listBoxChanged(self, index):
        i = index
        self.emit(SIGNAL("Event_0"), self)
    def IndexOf(self, item):
        if isinstance(item, str):
            return self.listBox.row(self.listBox.findItems(item)[0]);
        else:
            return self.listBox.row(self.listBox.findItems(item.ToString())[0]);

    def Contains(self, item):
        compStr = None
        if isinstance(item, str):
            compStr = item
        elif isinstance(item, float) or isinstance(item, int):
            compStr = str(item)
        else:
            compStr = item.ToString()
        for i in range(self.listBox.count()):
            comboItemstr = self.listBox.item(i).text()
            if compStr == comboItemstr:
                return True
        return False


    def Clear(self):
        self.listBox.clear()
        self.objectList = []
        self.hasObject = False
    def Add(self, item):
        if not isinstance(item, str) and not isinstance(item, QString):
            self.listBox.addItem(item.ToString())
            self.objectList.append(item)
            self.hasObject = True
            return
        self.listBox.addItem(item)
        self.hasObject = False
        return self.listBox.count() - 1
    def Insert(self, index, item):
        if not isinstance(item, str):
            self.listBox.insertItem(index, item.ToString())
            self.objectList.insert(index, item)
            self.hasObject = True
            return
        self.listBox.insertItem(index, item)
        self.hasObject = False
    def imageButtonClicked(self):
        self.emit(SIGNAL("Event_3"), self)
    def get_Caption(self):
        caption = self.captionLabel.text()
        findIndex = caption.indexOf("(")
        if findIndex > 0:
            val = caption.left(findIndex)
            return val
        return caption
    def set_Caption(self, captionStr):
        if captionStr == "":
            self.captionLabel.setText("")
            self.LabelWidth = 0
            return
        if self.CaptionUnits != "" and self.CaptionUnits != None:
            self.captionLabel.setText(captionStr + "(" + str(self.CaptionUnits) + ")" + ":")
        else:
            self.captionLabel.setText(captionStr + ":")
    Caption = property(get_Caption, set_Caption, None, None)

    def get_CaptionUnits(self):
        return self.captionUnits
    def set_CaptionUnits(self, captionUnits):
        self.captionUnits = captionUnits
    CaptionUnits = property(get_CaptionUnits, set_CaptionUnits, None, None)

    def set_ButtonVisible(self, bool):
        self.imageButton.setVisible(bool)
    ButtonVisible = property(None, set_ButtonVisible, None, None)

    # def get_Value(self):
    #     return self.listBox.currentIndex()
    #
    # def set_Value(self, value):
    #     try:
    #         self.listBox.setCurrentIndex(value)
    #     except:
    #         self.textBox.setText("")
    # Value = property(get_Value, set_Value, None, None)

    # def get_IsEmpty(self):
    #     return self.listBox.currentText() == "" or self.listBox.currentIndex() == -1
    # IsEmpty = property(get_IsEmpty, None, None, None)

    # def get_ReadOnly(self):
    #     return self.listBox.isReadOnly()
    # # def set_ReadOnly(self, bool):
    # #     self.listBox.setR.setReadOnly(bool)
    # # ReadOnly = property(get_ReadOnly, set_ReadOnly, None, None)

    def set_LabelWidth(self, width):
        self.captionLabel.setMinimumSize(QSize(width, 0))
        self.captionLabel.setMaximumSize(QSize(width, 16777215))
    LabelWidth = property(None, set_LabelWidth, None, None)

    def set_Width(self, width):
        self.listBox.setMinimumSize(QSize(width, 0))
        self.listBox.setMaximumSize(QSize(width, 16777215))
    Width = property(None, set_Width, None, None)

    def set_Button(self, imageName):
        if imageName == None or imageName == "":
            self.imageButton.setVisible(False)
            return
        icon = QIcon()
        icon.addPixmap(QPixmap(("Resource/" + imageName)), QIcon.Normal, QIcon.Off)
        self.imageButton.setIcon(icon)
        self.imageButton.setVisible(True)
    Button = property(None, set_Button, None, None)

    def get_SelectedIndex(self):
        try:
            return self.listBox.currentRow()
        except:
            return 0
    def set_SelectedIndex(self, index):
        if self.listBox.count() == 0:
            return
        if index > self.listBox.count() - 1:
            self.listBox.setCurrentRow(0)
        else:
            self.listBox.setCurrentRow(index)
    SelectedIndex = property(get_SelectedIndex, set_SelectedIndex, None, None)

    # def get_Value(self):
    #     return self.listBox.currentIndex()
    # def set_Value(self, valueStr):
    #     if self.listBox.count() == 0:
    #         return
    #     self.listBox.setCurrentIndex(self.listBox.findText(valueStr))
    # Value = property(get_Value, set_Value, None, None)

    def get_Items(self):
        if self.hasObject:
            return self.objectList
        itemList = []
        if self.listBox.count() > 0:
            for i in range(self.listBox.count()):
                itemList.append(self.listBox.item(i).text())
        return itemList
    def set_AddItems(self, strList):
        if len(strList) != 0 and not isinstance(strList[0], str) and not isinstance(strList[0], QString):
            for obj in strList:
                self.listBox.addItem(obj.ToString())
                self.objectList.append(obj)
            self.hasObject = True
            return
        self.listBox.addItems(strList)
    Items = property(get_Items, set_AddItems, None, None)

    def get_Enabled(self):
        return self.listBox.isEnabled()
    def set_Enabled(self, bool):
        self.listBox.setEnabled(bool)
    Enabled = property(get_Enabled, set_Enabled, None, None)

    def get_Visible(self):
        return self.isVisible()
    def set_Visible(self, bool):
        self.setVisible(bool)
    Visible = property(get_Visible, set_Visible, None, None)

    def get_SelectedItem(self):
        if self.listBox.count() == 0:
            return None
        if self.hasObject:
            return self.objectList[self.SelectedIndex]
        return self.listBox.currentItem().text()
    # def set_SelectedItem(self, val):
    #     index = self.listBox.findText(val)
    #     self.listBox.setCurrentIndex(index)
    SelectedItem = property(get_SelectedItem, None, None, None)
Example #51
0
class Pluto_T6Parser(b3.parsers.pluto_iw5.Pluto_Iw5Parser):

    gameName = 'PlutoT6'
    _botGuid = "0"
    _guidLength = 1
    _line_length = 72
    _commands = {
        'message': 'tell %(cid)s "%(message)s"',
        'say': 'say "%(message)s"',
        'set': 'set %(name)s "%(value)s"',
        'kick': 'clientkick_for_reason %(cid)s "%(reason)s"',
        'ban': 'clientkick_for_reason %(cid)s "%(reason)s"',
        'unban': 'unban "%(name)s"',
        'tempban': 'clientkick_for_reason %(cid)s "%(reason)s"'
    }

    _reCvar = re.compile(
        r'^((?P<cvar>[a-z][a-z0-9_]*)).*?(is).*?(\")(?P<value>.*)(\")',
        re.IGNORECASE)
    _regPlayer = re.compile(
        r'^\s*?(?P<slot>[0-9]+)\s+?(?P<score>[0-9-]+).+?(?P<bot>\d+)\s+?(?P<ping>\d+|)\s+?(?P<guid>\S+)\s+?\^7(?P<name>[\S\s]+?)\s+?(?P<last>\d+)\s+?(?P<ip>[0-9.]+|localhost)[:]*(?P<port>[0-9-]+|)\s+?(?P<qport>[0-9-]+).+?(?P<rate>\d+)',
        re.IGNORECASE)

    ####################################################################################################################
    #                                                                                                                  #
    #   PARSER INITIALIZATION                                                                                          #
    #                                                                                                                  #
    ####################################################################################################################

    def startup(self):
        """
        Called after the parser is created before run().
        """
        b3.parsers.pluto_iw5.Pluto_Iw5Parser.startup(self)
        #Add our own expressions to the line formats.
        #Kill + Damage
        self._lineFormats = (re.compile(
            r'(?P<action>[A-Z]);(?P<data>(?P<guid>[^;]+);(?P<cid>[0-9]{1,2});(?P<team>[a-z]*);(?P<name>[^;]+);(?P<aguid>[^;]+);(?P<acid>[0-9-]{1,2});(?P<ateam>[a-z]*);(?P<aname>[^;]+);(?P<aweap>[a-z0-9_+-]+);(?P<damage>[0-9.]+);(?P<dtype>[A-Z_]+);(?P<dlocation>[a-z_]+))$',
            re.IGNORECASE), ) + self._lineFormats

    ####################################################################################################################
    #                                                                                                                  #
    #   EVENT HANDLERS                                                                                                 #
    #                                                                                                                  #
    ####################################################################################################################

    #Remove the guid from bots.
    def OnJ(self, action, data, match=None):
        codguid = match.group('guid')
        cid = match.group('cid')
        name = match.group('name')
        self.verbose2('Client Joining: %s: %s [%s]' % (name, codguid, cid))
        if len(codguid) < self._guidLength:
            # invalid guid
            self.verbose2('Invalid GUID: %s. GUID length set to %s' %
                          (codguid, self._guidLength))
            codguid = None

        if codguid != None and codguid == self._botGuid:
            # We have a bot
            self.info('Changed GUID to NONE for %s.' % name)
            codguid = None
        client = self.getClient(match)

        if client:
            self.verbose2('Client object already exists')
            if codguid != client.guid:
                self.debug(
                    'This is not the correct client (%s <> %s): disconnecting...'
                    % (codguid, client.guid))
                client.disconnect()
                return None
            else:
                self.verbose2('client.guid in sync: %s == %s' %
                              (codguid, client.guid))

            client.state = b3.STATE_ALIVE
            client.name = name
            # join-event for mapcount reasons and so forth
            return self.getEvent('EVT_CLIENT_JOIN', client=client)
        else:
            if self._counter.get(
                    cid) and self._counter.get(cid) != 'Disconnected':
                self.verbose(
                    'cid: %s already in authentication queue: aborting join' %
                    cid)
                return None

            self._counter[cid] = 1
            t = Timer(2, self.newPlayer, (cid, codguid, name))
            t.start()
            self.debug('%s connected: waiting for authentication...' % name)
            self.debug('Our authentication queue: %s' % self._counter)

    ####################################################################################################################
    #                                                                                                                  #
    #   B3 PARSER INTERFACE IMPLEMENTATION                                                                             #
    #                                                                                                                  #
    ####################################################################################################################

    def getCvar(self, cvar_name):
        """
        Return a CVAR from the server.
        :param cvar_name: The CVAR name.
        """
        if self._reCvarName.match(cvar_name):
            val = self.write("get " + cvar_name).replace("\"^7", "\"")
            self.debug('Get cvar %s = [%s]', cvar_name, val)

            m = re.match(self._reCvar, val)

            if m:
                if m.group('cvar').lower() == cvar_name.lower():
                    try:
                        default_value = m.group('default')
                    except IndexError:
                        default_value = None
                    return b3.cvar.Cvar(m.group('cvar'),
                                        value=m.group('value'),
                                        default=default_value)
            else:
                return None

    def cod9ClientGuidSetter(self, guid):
        if self.console != None:
            self.console.verbose2('Custom setter works. :ok:')
        if guid and len(guid) > 0:
            if self._guid and self._guid != guid:
                if self.console != None:
                    self.console.error(
                        'Client has guid but its not the same %s <> %s',
                        self._guid, guid)
                self.authed = False
            elif not self._guid:
                if self.console != None:
                    self.console.verbose2('Set guid from %s to %s', self._guid,
                                          guid)
                self._guid = guid
        else:
            self.authed = False
            self._guid = ''

    b3.clients.Client.guid = property(b3.clients.Client._get_guid,
                                      cod9ClientGuidSetter)