def __init__(self, ledPin): Thing.__init__(self, 'urn:dev:ops:blue-led-1234', 'Blue LED', ['OnOffSwitch', 'Light'], 'Blue LED on SparkFun ESP32 Thing') self.pinLed = machine.Pin(ledPin, machine.Pin.OUT) self.pwmLed = machine.PWM(self.pinLed) self.ledBrightness = 50 self.on = False self.updateLed() self.add_property( Property(self, 'on', Value(self.on, self.setOnOff), metadata={ '@type': 'OnOffProperty', 'title': 'On/Off', 'type': 'boolean', 'description': 'Whether the LED is turned on', })) self.add_property( Property(self, 'brightness', Value(self.ledBrightness, self.setBrightness), metadata={ '@type': 'BrightnessProperty', 'title': 'Brightness', 'type': 'number', 'minimum': 0, 'maximum': 100, 'unit': 'percent', 'description': 'The brightness of the LED', }))
def __init__(self): Thing.__init__(self, 'My Humidity Sensor', 'multiLevelSensor', 'A web connected humidity sensor') self.add_property( Property(self, 'on', Value(True), metadata={ 'type': 'boolean', 'description': 'Whether the sensor is on', })) self.level = Value(0.0) self.add_property( Property(self, 'level', self.level, metadata={ 'type': 'number', 'description': 'The current humidity in %', 'unit': '%', })) log.debug('starting the sensor update looping task')
def setProperty(self, name, value=None, priority=u"", normalize=True): """(DOM) Set a property value and priority within this declaration block. :param name: of the CSS property to set (in W3C DOM the parameter is called "propertyName"), always lowercase (even if not normalized) If a property with this `name` is present it will be reset. cssutils also allowed `name` to be a :class:`~cssutils.css.Property` object, all other parameter are ignored in this case :param value: the new value of the property, ignored if `name` is a Property. :param priority: the optional priority of the property (e.g. "important"), ignored if `name` is a Property. :param normalize: if True (DEFAULT) `name` will be normalized (lowercase, no simple escapes) so "color", "COLOR" or "C\olor" will all be equivalent :exceptions: - :exc:`~xml.dom.SyntaxErr`: Raised if the specified value has a syntax error and is unparsable. - :exc:`~xml.dom.NoModificationAllowedErr`: Raised if this declaration is readonly or the property is readonly. """ self._checkReadonly() if isinstance(name, Property): newp = name name = newp.literalname elif not value: # empty string or None effectively removed property return self.removeProperty(name) else: newp = Property(name, value, priority) if not newp.wellformed: self._log.warn(u"Invalid Property: %s: %s %s" % (name, value, priority)) else: nname = self._normalize(name) properties = self.getProperties(name, all=(not normalize)) for property in reversed(properties): if normalize and property.name == nname: property.cssValue = newp.cssValue.cssText property.priority = newp.priority break elif property.literalname == name: property.cssValue = newp.cssValue.cssText property.priority = newp.priority break else: newp.parent = self self.seq._readonly = False self.seq.append(newp, "Property") self.seq._readonly = True
def createPlot(self, streetAddress, city, state, zipcode, alias): """ Creates the analysis plot based on given address, city, state, zipcode, and alias. :param streetAddress: street address as string :param city: city as string :param state: state as two letter string ex. "CO" :param zipcode: zipcode as an int :param alias: prop alias as string :return: Nothing """ self.propObj = Property() # property object self.propObj.setInfo( streetAddress.text(), city.text(), state.text(), zipcode.text(), alias.text()) # manually set info instead of getting from db try: self.propObj.initZillowInfo( "X1-ZWz17njsl1wx6z_3mmvk") # replace with key in env self.prop = propertyBox(self.propObj) self.prop.createBox() self.mainLayout.addWidget(self.prop) self.resubmitform = QPushButton("Change Property") self.resubmitform.clicked.connect(self.changeProperty) self.prop.vbox.addWidget(self.resubmitform) self.form.hide() except Exception as e: print(e) # create a popup window with the error and keep form as is QMessageBox.about( self, "Error", "Sorry! API cannot get full analytics. Check if address is valid." )
def __init__(self, identifier: str = 'solid', latex: Optional[str] = None, comment: Optional[str] = None) -> None: """ Args: identifier: Identifier of matter latex: Latex-version of identifier. If None, latex identical with identifier comment: Comment on matter Note: Do NOT define a self.__call__() method in this class """ super().__init__(identifier=identifier, latex=latex, comment=comment) self.R_p02 = Property('Rp0.2', 'Pa', latex='$R_{p,0.2}$', comment='yield strength') self.R_m = Property('R_m', 'Pa', latex='$R_{m}$', comment='tensile strength') self.R_compr = Property('R_compr', 'Pa', latex='$R_{compr}$', comment='compressive strength') self.T_recryst = 0.
def setProperty(self, name, value=None, priority=u'', normalize=True): """(DOM) Set a property value and priority within this declaration block. :param name: of the CSS property to set (in W3C DOM the parameter is called "propertyName"), always lowercase (even if not normalized) If a property with this `name` is present it will be reset. cssutils also allowed `name` to be a :class:`~cssutils.css.Property` object, all other parameter are ignored in this case :param value: the new value of the property, ignored if `name` is a Property. :param priority: the optional priority of the property (e.g. "important"), ignored if `name` is a Property. :param normalize: if True (DEFAULT) `name` will be normalized (lowercase, no simple escapes) so "color", "COLOR" or "C\olor" will all be equivalent :exceptions: - :exc:`~xml.dom.SyntaxErr`: Raised if the specified value has a syntax error and is unparsable. - :exc:`~xml.dom.NoModificationAllowedErr`: Raised if this declaration is readonly or the property is readonly. """ self._checkReadonly() if isinstance(name, Property): newp = name name = newp.literalname else: newp = Property(name, value, priority) if not newp.wellformed: self._log.warn(u'Invalid Property: %s: %s %s' % (name, value, priority)) else: nname = self._normalize(name) properties = self.getProperties(name, all=(not normalize)) for property in reversed(properties): if normalize and property.name == nname: property.cssValue = newp.cssValue.cssText property.priority = newp.priority break elif property.literalname == name: property.cssValue = newp.cssValue.cssText property.priority = newp.priority break else: newp.parent = self self.seq._readonly = False self.seq.append(newp, 'Property') self.seq._readonly = True
def make_thing(): thing = Thing('My Lamp', 'dimmableLight', 'A web connected lamp') def noop(_): pass thing.add_property( Property(thing, 'on', Value(True, noop), metadata={ 'type': 'boolean', 'description': 'Whether the lamp is turned on', })) thing.add_property( Property(thing, 'level', Value(50, noop), metadata={ 'type': 'number', 'description': 'The level of light from 0-100', 'minimum': 0, 'maximum': 100, })) thing.add_available_action( 'fade', { 'description': 'Fade the lamp to a given level', 'input': { 'type': 'object', 'required': [ 'level', 'duration', ], 'properties': { 'level': { 'type': 'number', 'minimum': 0, 'maximum': 100, }, 'duration': { 'type': 'number', 'unit': 'milliseconds', }, }, } }, FadeAction) thing.add_available_event( 'overheated', { 'description': 'The lamp has exceeded its safe operating temperature', 'type': 'number', 'unit': 'celsius' }) return thing
class Task: properties = ( Property('ID', 'int primary key'), Property('initDate', 'date'), Property('name', 'text'), Property('detail', 'text'), Property('person_ID', 'int'), ) schema = ', '.join(['{0} {1}'.format(p.name, p.typ) for p in properties])
class Table: """ テーブルです。 データ構造を保持して、データの生成を行います。 """ def __init__(self, _table_name, **properties): self.name = _table_name self.properties = Property(properties) def __call__(self, name): return self.properties.get(name) def create(self, count): records = [self._assemble(index=index) for index in range(count)] self.records = records return self def to_sql(self): if self.records is None: print("please run create method") else: sqls = list() for record in self.records: sql = (f"INSERT INTO {self.name}" + "(" + ", ".join([str(k) for k in record.keys()]) + ") VALUES (" + ", ".join([self._str(v) for v in record.values()]) + ");") sqls.append(sql) return sqls def show_sql(self): if self.records is None: print('data is not exist') else: for query in self.to_sql(): print(query) def _assemble(self, index): record = dict() for name, seed in self.properties.items(): record[name] = seed.get(index=index) return record def _str(self, val): if type(val) is str: return f"'{val}'" elif type(val) is int: return str(val) elif type(val) is datetime.date: return f"'{val}'" elif type(val) is datetime.datetime: return f"'{val}'" else: return str(val)
def __init__(self): Thing.__init__(self, 'urn:dev:ops:my-pycom-pysense', 'My Pycom', ['RGBLed', 'memory'], 'A web connected Pycom') self.color = 0 #0 is no light, 20 is very light blue #0xff00 #green self.updateLeds() self.mempycom = Value(0.0) self.seconds = 0 self.__alarm = Timer.Alarm(self._seconds_handler, s=10, periodic=True) #self._alarm = Timer.Alarm(updateMemPycom, 1, arg=None, periodic=True) self.add_property( Property(self, 'mempycom', self.mempycom, metadata={ '@type': 'SystemParameter', 'title': 'Memory', 'type': 'number', 'description': 'The free RAM of the system', })) self.add_property( Property(self, 'color', Value(self.color, self.setcolor), metadata={ '@type': 'ColorProperty', 'title': 'Color', 'type': 'integar', 'description': 'The color of the LED', })) self.add_available_action( 'setrgbcolor', { 'title': 'Change Color', 'description': 'Change the color of LED', 'input': { 'type': 'object', 'required': [ 'color', ], 'properties': { 'color': { 'type': 'integer', 'minimum': 0, 'maximum': 0xFFFFFF, #'unit': 'percent', }, }, }, }, SetRGBColor)
class linux(objects.GetObject): timeout = 3 retries = 0 properties = { 'name': Property(oid=('SNMPv2-MIB', 'sysName', 0)), 'uptime': Property(oid=('SNMPv2-MIB', 'sysUpTime', 0)), # 'or_id': Property(oid=('SNMPv2-MIB', 'sysORID'), method='walk'), 'or_descr': Property(oid=('SNMPv2-MIB', 'sysORDescr'), method='walk'), # 'or_uptime': Property(oid=('SNMPv2-MIB', 'sysORUpTime'), method='walk'), }
def __init__(self, identifier: str = 'matter', latex: Optional[str] = None, comment: Optional[str] = None) -> None: """ Args: identifier: Identifier of matter latex: Latex-version of identifier. If None, latex is identical with identifier comment: Comment on matter Note: Do NOT define a self.__call__() method in this class """ super().__init__(identifier=identifier, latex=latex, comment=comment) self.a = Property('a', 'm$^2$/s', comment='thermal diffusity', calc = self._a) self.beta = Property('beta', '1/K', latex=r'$\beta_{th}$', comment='volumetric thermal expansion') self.c_p = Property('c_p', 'J/kg/K', comment='specific heat capacity') self.c_sound = Property('c_sound', 'm/s', latex='$c_{sound}$') self.c_sound.calc = lambda T, p, x: None self.composition: Dict[str, float] = OrderedDict() self.compressible: bool = False self.E = Property('E', 'Pa', comment="Young's (elastic) modulus") self.h_melt: float = None self.h_vap: float = None self.k = Property('k', 'W/m/K', latex='$k$', comment='thermal conductivity') self.M = Property('M', 'kmol/kg', comment='molar mass') self.M.calc = lambda T=0, p=0, x=0: None self.nu_mech: float = None self.rho = Property('rho', 'kg/m$^3$', latex=r'$\varrho$', ref=1., comment='density') self.rho.T.ref = C2K(20.) self.rho.p.ref = atm() self.rho_el = Property('rho_el', r'$\Omega$', latex=r'$\varrho_{el}$', comment='electric resistance') self.T_boil: float = 0. self.T_flash_point: float = 0. self.T_liq: float = 0. self.T_melt: float = 0. self.T_sol: float = 0. if self.E() is None or np.abs(self.E()) < 1e-20: self.rho.calc = lambda T, p, x: self.rho.ref \ / (1. + (T - self.rho.T.ref) * self.beta()) else: self.rho.calc = lambda T, p, x: self.rho.ref \ / (1. + (T - self.rho.T.ref) * self.beta()) \ / (1. - (p - self.rho.p.ref) / self.E())
def __init__(self, fname): Launcher.__init__(self, fname) Property.__init__(self, fname) self.qeConfig = QEConfig(self.pwscfInput) self.qeConfig.parse() self.structure = QEStructure(self.pwscfInput) self.dispersion = dispersion.Dispersion(self) # self._kpts = self.getkPoints() self._ekincutoff = self.getEkincutoff()
def __init__(self, userID, DBconnect): self.userID = userID self.DBconnect = DBconnect self.firstname = self.DBconnect.getFirstName(self.userID) self.lastname = self.DBconnect.getLastName(self.userID) self.listOfPropertyDicts = self.DBconnect.getPropertyListofDict( self.userID) self.properties = [] for propInfoDict in self.listOfPropertyDicts: prop = Property() prop.initPropInfo(propInfoDict) # prop.getAPIinfo(DBconnect) # prop.initZillowInfo("X1-ZWz17njsl1wx6z_3mmvk") self.properties.append(prop)
def ident(expected, seq, token, tokenizer=None): # a property tokens = self._tokensupto2(tokenizer, starttoken=token, semicolon=True) if self._tokenvalue(tokens[-1]) == u";": tokens.pop() property = Property(parent=self) property.cssText = tokens if property.wellformed: seq.append(property, "Property") else: self._log.error(u"CSSStyleDeclaration: Syntax Error in " u"Property: %s" % self._valuestr(tokens)) # does not matter in this case return expected
def write_csv(area_uris): for area in area_uris: uris = area_uris[area] csv_file = CsvHelper(f"{area}_properties") try: index = 0 for uri in uris: property = Property(uri[index]) csv_file.write(property.to_h()) print(f"({index}/{len(uris)})") index += 1 finally: csv_file.file.close()
def run(numOfConsumer, conCoeffA, conCoeffB, numOfPro, proCoeffAList, proCoeffBList, maxSlot): consumerList = [] for i in range(numOfConsumer): valueDict = {} valueDict[1] = randint(10,60) valueDict[2] = valueDict[1] + randint(10,60) valueDict[3] = valueDict[2] + randint(10,60) valueDict[4] = valueDict[3] + randint(10,60) valueDict[5] = valueDict[4] + randint(10,60) #print(valueDict) consumer = Consumer(i, valueDict) consumer.set_bidList(conCoeffA, conCoeffB) consumerList.append(consumer) propertyDict = {1:[], 2:[], 3:[], 4:[], 5:[]} numOfPro = 20 for n in range(numOfPro): star = randint(1,5) if star == 1: cost = randint(10,40) elif star == 2: cost = randint(30,100) elif star == 3: cost = randint(50,160) elif star == 4: cost = randint(70, 220) elif star == 5: cost = randint(90,280) #print(cost) pro = Property(n, star, cost, randint(1,5)) pro.set_priceList(proCoeffAList, proCoeffBList, maxSlot) propertyDict[star].append(pro) priceline = NYOP() priceline.compute(consumerList, propertyDict) #print("priceline's profit", priceline.profit) aveConU = sum(c.utility for c in consumerList)/numOfConsumer #print("average consumer utility", aveConU) sumProProfit = 0 for k in propertyDict.keys(): sumProProfit += sum(p.profit for p in propertyDict[k]) aveProProfit = sumProProfit/numOfPro #print("average property profit", aveProProfit) return (priceline.profit, aveConU, aveProProfit)
def __init__(self, identifier: str = 'gas', latex: Optional[str] = None, comment: Optional[str] = None) -> None: """ Args: identifier: Identifier of matter latex: Latex-version of identifier. If None, identical with identifier comment: Comment on matter Note: Do NOT define a self.__call__() method in this class """ super().__init__(identifier=identifier, latex=latex, comment=comment) # self.a.calc = self._a self.D_in_air = Property('D_in_air', 'm2/s', calc=lambda T, p=atm(), x=0.: None) self.T.ref = C2K(15.)
def __init__(self): Thing.__init__( self, 'urn:dev:ops:my-humidity-sensor-1234', 'My Humidity Sensor', ['MultiLevelSensor'], 'A web connected humidity sensor' ) self.level = Value(0.0) self.add_property( Property(self, 'level', self.level, metadata={ '@type': 'LevelProperty', 'title': 'Humidity', 'type': 'number', 'description': 'The current humidity in %', 'minimum': 0, 'maximum': 100, 'unit': 'percent', 'readOnly': True, })) log.debug('starting the sensor update looping task')
def __init__(self, rPin, gPin, bPin): Thing.__init__( self, "urn:dev:ops:esp32-rgb-led-1234", "ESP32-RGB-LED", ["OnOffSwitch", "Light", "ColorControl"], "RGB LED on ESP-Wrover-Kit", ) self.pinRed = machine.Pin(rPin, machine.Pin.OUT) self.pinGreen = machine.Pin(gPin, machine.Pin.OUT) self.pinBlue = machine.Pin(bPin, machine.Pin.OUT) self.pwmRed = machine.PWM(self.pinRed) self.pwmGreen = machine.PWM(self.pinGreen) self.pwmBlue = machine.PWM(self.pinBlue) self.redLevel = 50 self.greenLevel = 50 self.blueLevel = 50 self.on = False self.updateLeds() self.add_property( Property( self, "on", Value(True, self.setOnOff), metadata={ "@type": "OnOffProperty", "title": "On/Off", "type": "boolean", "description": "Whether the LED is turned on", }, ) ) self.add_property( Property( self, "color", Value("#808080", self.setRGBColor), metadata={ "@type": "ColorProperty", "title": "Color", "type": "string", "description": "The color of the LED", }, ) )
def get_on_property(self): return Property(self, 'on', Value(True, lambda v: print('On-State is now', v)), metadata={ 'type': 'boolean', 'description': 'Whether the lamp is turned on', })
def ident(expected, seq, token, tokenizer=None): # a property tokens = self._tokensupto2(tokenizer, starttoken=token, semicolon=True) if self._tokenvalue(tokens[-1]) == u';': tokens.pop() property = Property(parent=self) property.cssText = tokens if property.wellformed: seq.append(property, 'Property') else: self._log.error(u'CSSStyleDeclaration: Syntax Error in ' u'Property: %s' % self._valuestr(tokens)) # does not matter in this case return expected
def main(): annual_rent = input("Property Annual Rent: ") property_tax_rate = input("Property Tax Rate: ") property_tax_rate /= 100.0 myProperty = Property(annual_rent=annual_rent, tax_rate=property_tax_rate) equity = input("Equity: ") closing_costs = input("Closing Costs: ") debt_amount = input("Debt Amount: ") interest_rate = input("Interest Rate: ") interest_rate /= 100.0 term = input("Term: ") myPurchase = Purchase(equity=equity, closing_cost=closing_costs, debt_amount=debt_amount, interest_rate=interest_rate, term=term) duration = input("Duration: ") rental_rate_increase_percent = input("Rental rate increase %: ") rental_rate_increase_percent /= 100.0 rental_rate_occupancy = input("Rental rate occupancy: ") rental_rate_occupancy /= 100.0 tax_rate_increase_percent = input("Tax Rate increase %: ") tax_rate_increase_percent /= 100.0 home_appreciation_annual_percent = input("Home Appreciation Annual %: ") home_appreciation_annual_percent /= 100.0 maintainance_cost_annual_percent = input("Maintainance Cost Annual %: ") maintainance_cost_annual_percent /= 100.0 insurance_cost_percent = input("Insurance Cost %: ") insurance_cost_percent /= 100.0 exit_closing_costs = input("Exit Closing Cost: ") myPropertyPerformace = PropertyPerformance( duration, rental_rate_increase_percent, rental_rate_occupancy, tax_rate_increase_percent, home_appreciation_annual_percent, maintainance_cost_annual_percent, insurance_cost_percent, exit_closing_costs) print "Upfront Costs: ", myPurchase.upfront_costs() print "Total Rental Revenue: ", total_rental_revenue( myProperty, myPropertyPerformace) print "Home Exit value: ", home_exit_value(myPurchase, myPropertyPerformace) print "Total Taxes Paid: ", total_taxes_paid(myProperty, myPurchase, myPropertyPerformace) print "Total Mainatainance: ", total_maintainance_spend( myPurchase, myPropertyPerformace) print "Total Insurance: ", total_insurance_costs(myPurchase, myPropertyPerformace)
def prompt_init(): parent_init = Property.prompt_init() laundry = get_valid_input( "What laundry facilities does " "the property have? ", Apartment.valid_laundries) balcony = get_valid_input("Does the property have a balcony? ", Apartment.valid_balconies) parent_init.update({"laundry": laundry, "balcony": balcony}) return parent_init
def get_level_property(self): return Property(self, 'level', Value(50, lambda l: print('New light level is', l)), metadata={ 'type': 'number', 'description': 'The level of light from 0-100', 'minimum': 0, 'maximum': 100, })
def recurseSearch(parentNode, principal, comparables, limit, comparableCount): ''' Recursively creates a network of comparable real estate. Height of the tree = limit. Number of leaf nodes = comparableCount ** (limit - 1) ''' print("Height Level: {}".format(limit)) if limit == 1: return True else: for comp in comparables: compObj = Property(comp['zpid'], comp['links'], comp['address'], comp['zestimate'], comp['localRealEstate'], principal=principal) tempParent = Node(compObj.zpid, parent=parentNode) tempPrinciple, tempComparables = compObj.searchComparables( comparableCount) recurseSearch(tempParent, tempPrinciple, tempComparables, limit - 1, comparableCount)
def prompt_init(self): parent_init = Property.prompt_init() laundry = '' while laundry.lower() not in Apartment.valid_laundries: laundry = input("What laundry facilities does the property have ? ({})".format(','.join(Apartment.valid_laundaries))) while balcony.lower() not in Apartment.valid_balconies: balcony = input("Does the property have a balcony ? ({})".format(','.join(Apartment.valid_balconies))) parent_init.update({"laundry": laundry, "balcony": balcony}) return parent_init
def __init__(self, userID, DBconnect): self.userID = userID self.DBconnect = DBconnect self.firstname = self.DBconnect.getFirstName(self.userID) self.lastname = self.DBconnect.getLastName(self.userID) self.listOfPropertyDicts = self.DBconnect.getPropertyListofDict( self.userID) self.properties = [] for propInfoDict in self.listOfPropertyDicts: prop = Property(propInfoDict, self.DBconnect) self.properties.append(prop)
def get_property(post, existing_urls): title = PostScrapper.get_title(post) url = post.find(class_='ann-box-title')['href'] time_in_market = PostScrapper.get_time_in_market(post) prop = Property(title, time_in_market, url) property_page_scrapper = PropertyPageScrapper(url) prop = property_page_scrapper.complete_property(prop) return prop
def prompt_init(): parent_init = Property.prompt_init() laundry = get_valid_custom_input(PROMPT_MESSAGE["laundry_input"], Apartment.valid_laundries) or '' balcony = get_valid_custom_input(PROMPT_MESSAGE["balcony_input"], Apartment.valid_balconies) or '' parent_init.update({"laundry": laundry, "balcony": balcony}) #print(parent_init, '-->') return parent_init
def ident(expected, seq, token, tokenizer=None): # a property if new['char']: # maybe an IE hack? token = (token[0], u'%s%s' % (new['char'], token[1]), token[2], token[3]) tokens = self._tokensupto2(tokenizer, starttoken=token, semicolon=True) if self._tokenvalue(tokens[-1]) == u';': tokens.pop() property = Property() property.cssText = tokens if property.wellformed: seq.append(property) else: self._log.error(u'CSSStyleDeclaration: Syntax Error in Property: %s' % self._valuestr(tokens)) new['char'] = None return expected
def prompt_init(): parent_init = Property.prompt_init() fenced = get_valid_input("Is the yard fenced? ", House.valid_fenced) garage = get_valid_input("Is there a garage? ", House.valid_garage) num_stories = input("How many stories? ") parent_init.update({ "fenced": fenced, "garage": garage, "num_stories": num_stories }) return parent_init
def __init__(self, rPin, gPin, bPin): Thing.__init__( self, 'urn:dev:ops:esp32-rgb-led-1234', 'ESP32-RGB-LED', ['OnOffSwitch', 'Light', 'ColorControl'], 'RGB LED on ESP-Wrover-Kit' ) self.pinRed = machine.Pin(rPin, machine.Pin.OUT) self.pinGreen = machine.Pin(gPin, machine.Pin.OUT) self.pinBlue = machine.Pin(bPin, machine.Pin.OUT) self.pwmRed = machine.PWM(self.pinRed) self.pwmGreen = machine.PWM(self.pinGreen) self.pwmBlue = machine.PWM(self.pinBlue) self.redLevel = 50 self.greenLevel = 50 self.blueLevel = 50 self.on = False self.updateLeds() self.add_property( Property(self, 'on', Value(True, self.setOnOff), metadata={ '@type': 'OnOffProperty', 'title': 'On/Off', 'type': 'boolean', 'description': 'Whether the LED is turned on', })) self.add_property( Property(self, 'color', Value('#808080', self.setRGBColor), metadata={ '@type': 'ColorProperty', 'title': 'Color', 'type': 'string', 'description': 'The color of the LED', }))
def __init__(self): Thing.__init__(self, 'urn:dev:ops:my-pysense', 'My PySense', [ 'Temperature', 'Humidity', 'Pressure', 'Luminance', 'Accelerometer' ], 'A Sensor Shield') self.seconds = 0 self.temperature = Value(0.0) self.humidity = Value(0.0) self.light = lt.light()[0] self.accelaration_0 = li.acceleration()[0] self.accelaration_1 = li.acceleration()[1] self.accelaration_2 = li.acceleration()[2] self.roll = li.roll() self.pitch = li.pitch() self.__alarm = Timer.Alarm(self._seconds_handler, s=10, periodic=True) #self._alarm = Timer.Alarm(updateMemPycom, 1, arg=None, periodic=True) self.add_property( Property( self, 'temperature', self.temperature, #, self.updateTemperature), metadata={ '@type': 'Temperature', 'title': 'Temperature', 'type': 'number', 'description': 'The temperature sensor value', })) self.add_property( Property(self, 'humidity', self.humidity, metadata={ '@type': 'Humidity', 'title': 'Humidity', 'type': 'number', 'description': 'The humidity sensor value', }))
def setProperty(self, name, value=None, priority=u'', normalize=True, replace=True): """(DOM) Set a property value and priority within this declaration block. :param name: of the CSS property to set (in W3C DOM the parameter is called "propertyName"), always lowercase (even if not normalized) If a property with this `name` is present it will be reset. cssutils also allowed `name` to be a :class:`~cssutils.css.Property` object, all other parameter are ignored in this case :param value: the new value of the property, ignored if `name` is a Property. :param priority: the optional priority of the property (e.g. "important"), ignored if `name` is a Property. :param normalize: if True (DEFAULT) `name` will be normalized (lowercase, no simple escapes) so "color", "COLOR" or "C\olor" will all be equivalent :param replace: if True (DEFAULT) the given property will replace a present property. If False a new property will be added always. The difference to `normalize` is that two or more properties with the same name may be set, useful for e.g. stuff like:: background: red; background: rgba(255, 0, 0, 0.5); which defines the same property but only capable UAs use the last property value, older ones use the first value. :exceptions: - :exc:`~xml.dom.SyntaxErr`: Raised if the specified value has a syntax error and is unparsable. - :exc:`~xml.dom.NoModificationAllowedErr`: Raised if this declaration is readonly or the property is readonly. """ self._checkReadonly() if isinstance(name, Property): newp = name name = newp.literalname elif not value: # empty string or None effectively removed property return self.removeProperty(name) else: newp = Property(name, value, priority, parent=self) if newp.wellformed: if replace: # check if update nname = self._normalize(name) properties = self.getProperties(name, all=(not normalize)) for property in reversed(properties): if normalize and property.name == nname: property.propertyValue = newp.propertyValue.cssText property.priority = newp.priority return elif property.literalname == name: property.propertyValue = newp.propertyValue.cssText property.priority = newp.priority return # not yet set or forced omit replace newp.parent = self self.seq._readonly = False self.seq.append(newp, 'Property') self.seq._readonly = True else: self._log.warn(u'Invalid Property: %s: %s %s' % (name, value, priority))