How to use getdict method in tox

Best Python code snippet using tox_python

database.py

Source:database.py Github

copy

Full Screen

1'''2Database Service3'''4from flask_pymongo import PyMongo5from models.room import Room6from models.user import User7from models.sensor import Sensor8from models.actuator import Actuator9from models.roommap import Roommap10import utilities.util as util11import threading12import time13import numpy as np14import datetime15class DB():16 def __init__(self, app):17 app.config['MONGO_URI'] = "mongodb://localhost:27017/smaroomansDatabase"18 self.mongo = PyMongo(app)19 print('init DB')20 self.sensorlock = threading.Lock()21 self.roomlock = threading.Lock()22 self.userlock = threading.Lock()23 self.dayoffset = 024 def getAllRooms(self):25 """26 returns all Rooms27 Returns28 -------29 list30 list with all Rooms as model dict31 """32 rooms = []33 for room in self.mongo.db.room.find():34 try:35 room['active'] = self.getRoomState(36 room['key'], datetime.datetime.now().strftime('%Y-%m-%d'))37 room['users'] = self.getRoomUsers(38 room['key'], datetime.datetime.now().strftime('%Y-%m-%d'))39 rooms.append(Room(**room).getDict())40 except Exception as e:41 print(e)42 return rooms43 def getAllSensors(self):44 """45 returns all Sensors46 Returns47 -------48 moongodb.cursor49 iterator with all sensors50 """51 return self.mongo.db.sensor.find()52 def getAllActuators(self):53 """54 returns all Actuators55 Returns56 -------57 moongodb.cursor58 iterator with all actuators59 """60 return self.mongo.db.actuator.find()61 def getAllUsers(self):62 """63 returns all Users64 Returns65 -------66 moongodb.cursor67 iterator with all Users68 """69 return self.mongo.db.user.find()70 def setUserPlan(self, user, workplan):71 """72 update user workplan73 Parameters74 -------75 user: str76 user key as string77 workplan: list78 user workplan as list79 """80 self.mongo.db.user.update_one(81 {'key': user}, {'$set': {'workplan': workplan}}, upsert=True)82 def appendNotification(self, room, notification):83 """84 append Notifications to room85 Parameters86 -------87 room: str88 room key as string89 notification: list90 notifications for room as list91 """92 roomNotifications = self.mongo.db.room.find_one({'key': room})[93 'notifications']94 roomNotifications.append(notification)95 try:96 self.mongo.db.room.update_one(97 {'key': room}, {'$set': {'notifications': roomNotifications}}, upsert=False)98 except Exception as e:99 print(e)100 def clearAllNotifications(self):101 """102 deletes all room Notifications103 """104 try:105 for room in self.getAllRooms():106 self.mongo.db.room.update_one(107 {'key': room['key']}, {'$set': {'notifications': []}}, upsert=False)108 except Exception as e:109 print(e)110 def updateSensorData(self, key, data):111 """112 update sensor data information113 Parameters114 -------115 key: str116 sensor key as string117 data: dict118 sensor data as key value pair119 """120 key = str(key).replace(" ", "_")121 self.mongo.db.sensor.update_one(122 {'key': key}, {'$set': {'data': data}}, upsert=True)123 def getSensorTopic(self, key):124 """125 returns Sensor topic information126 Parameters127 -------128 key: str129 sensor key as string130 Returns131 -------132 string133 topic as string134 """135 key = str(key).replace(" ", "_")136 sensor = self.mongo.db.sensor.find_one({'key': key})137 if sensor is not None:138 topic = 'sensor'+'/'+str(key)139 return topic140 else:141 return None142 def getSensorData(self, key):143 """144 returns Sensor data information145 Parameters146 -------147 key: str148 sensor key as string149 Returns150 -------151 dict152 key value pair with sensor data153 """154 key = str(key).replace(" ", "_")155 sensor = self.mongo.db.sensor.find_one({'key': key})156 #if key in self.sensorCache : sensor['data'] = self.sensorCache[key]157 return sensor['data'] if sensor is not None else None158 def getSensor(self, key):159 """160 returns Sensor model as dict161 Parameters162 -------163 key: str164 sensor key as string165 Returns166 -------167 dict168 complete sensor information as dict169 """170 key = str(key).replace(" ", "_")171 sensor = self.mongo.db.sensor.find_one({'key': key})172 #if key in self.sensorCache : sensor['data'] = self.sensorCache[key]173 return sensor if sensor is not None else None174 def getRoomSensors(self, room):175 # TODO maybe just return key?176 """177 returns Sensor models as dict of room 178 Parameters179 -------180 room: str181 room key as string182 Returns183 -------184 list185 dicts with sensor informations186 """187 sensordata = []188 sensors = self.mongo.db.room.find_one({'key': room})['sensors']189 for sensor in sensors:190 sensordata.append({'key': sensor,191 'sensortopic': self.getSensorTopic(sensor),192 'data': self.getSensorData(sensor)})193 return sensordata194 def getRoomActuatorTopicAndData(self, room, actuatorType):195 """196 returns actuator topic and topicdata197 Parameters198 -------199 room: str200 room key as string201 actuatortype: str202 actuator type203 Returns204 -------205 string206 actuatortopic207 string208 actuatordata209 """210 roomActuators = self.mongo.db.room.find_one({'key': room})['actuators']211 actuators = []212 for actuator in roomActuators:213 actuators.append(214 self.mongo.db.actuator.find_one({'key': actuator}))215 actuatorTopic = None216 actuatorData = None217 for actuator in actuators:218 if actuator['actuatortype'] == actuatorType:219 actuatorTopic = actuator['topic']220 actuatorData = actuator['topicdata']221 return actuatorTopic, actuatorData222 def getRoomTemperature(self, room):223 """224 returns room temperature225 Parameters226 -------227 room: str228 room key as string229 Returns230 -------231 int232 temperature233 """234 roomSensors = self.mongo.db.room.find_one({'key': room})['sensors']235 for roomSensor in roomSensors:236 sensor = self.mongo.db.sensor.find_one({'key': roomSensor})237 if sensor['sensortype'] == 'temperature':238 return sensor['data']['Temperature']239 def getRoomWindowStatus(self, room):240 """241 returns window status of room242 Parameters243 -------244 room: str245 room key as string246 Returns247 -------248 int249 0: closed250 1: open251 """252 roomSensors = self.mongo.db.room.find_one({'key': room})['sensors']253 for roomSensor in roomSensors:254 sensor = self.mongo.db.sensor.find_one({'key': roomSensor})255 if sensor['sensortype'] == 'window':256 return sensor['data']['window']257 def getRoomLuminance(self, room):258 """259 returns luminance of room260 Parameters261 -------262 room: str263 room key as string264 Returns265 -------266 int267 luminance268 """269 roomSensors = self.mongo.db.room.find_one({'key': room})['sensors']270 for roomSensor in roomSensors:271 sensor = self.mongo.db.sensor.find_one({'key': roomSensor})272 if sensor['sensortype'] == 'luminance':273 return sensor['data']['Luminance']274 def getRoomLightState(self, room):275 """276 returns light state of room277 Parameters278 -------279 room: str280 room key as string281 Returns282 -------283 string284 'on'/'off'285 """286 roomSensors = self.mongo.db.room.find_one({'key': room})['sensors']287 for roomSensor in roomSensors:288 sensor = self.mongo.db.sensor.find_one({'key': roomSensor})289 if sensor['sensortype'] == 'lightswitch':290 return sensor['data']['switch']291 def getRoomFanState(self, room):292 """293 returns fan state of room294 Parameters295 -------296 room: str297 room key as string298 Returns299 -------300 string301 'on'/'off302 """303 roomSensors = self.mongo.db.room.find_one({'key': room})['sensors']304 for roomSensor in roomSensors:305 sensor = self.mongo.db.sensor.find_one({'key': roomSensor})306 if sensor['sensortype'] == 'fanswitch':307 return sensor['data']['switch']308 def getRoomState(self, room, date):309 """310 returns current room state of room311 Parameters312 -------313 room: str314 room key as string315 Returns316 -------317 bool318 True: room is active319 False: room is in stanbymode320 """321 try:322 date = (datetime.datetime.strptime(date, "%Y-%m-%d") +323 datetime.timedelta(days=self.dayoffset)).strftime('%Y-%m-%d')324 roommap = self.mongo.db.roommanager.find_one(325 {'datum': util.datumToSeconds(date), 'room': room})326 if roommap is not None:327 return roommap['active']328 else:329 return True330 except Exception as e:331 print(e)332 return False333 def getRoomUsers(self, room, date):334 """335 returns all mapped user for the room at specific date336 Parameters337 -------338 room: str339 room key as string340 date: str341 date string in format %Y-%m-%d342 Returns343 -------344 list345 userkeys346 """347 try:348 date = (datetime.datetime.strptime(date, "%Y-%m-%d") +349 datetime.timedelta(days=self.dayoffset)).strftime('%Y-%m-%d')350 roommap = self.mongo.db.roommanager.find_one(351 {'datum': util.datumToSeconds(date), 'room': room})352 if roommap is not None:353 return roommap['users']354 else:355 return []356 except Exception as e:357 print(e)358 return []359 def getRoomMapsByDatum(self, timebegin, timeend):360 """361 returns all roommaps in timerange362 Parameters363 -------364 timebegin: str365 date string for first date in format %Y-%m-%d366 timeend: str367 date string for last date in format %Y-%m-%d368 Returns369 -------370 mongodb.cursors371 iterator with all roommaps372 """373 datumbegin = util.datumToSeconds(timebegin)374 datumend = util.datumToSeconds(timeend)375 roommaps = self.mongo.db.roommanager.find(376 {'datum': {"$gte": datumbegin, "$lte": datumend}})377 return roommaps378 def updateRoomMap(self, roommap):379 """380 update roommap entry in roommanager db381 Parameters382 -------383 roommap:dict384 roommap model as dict385 """386 self.mongo.db.roommanager.update_one({'datum': util.datumToSeconds(roommap['datum']), 'room': roommap['room']},387 {'$set': {'users': roommap['users'], 'active': roommap['active']}}, upsert=True)388 def updateDate(self, date):389 """390 update date offset391 Parameters392 -------393 date:string394 datestring395 """396 self.dayoffset = (datetime.datetime.strptime(date, "%Y-%m-%d") - datetime.datetime.strptime(397 datetime.datetime.now().strftime("%Y-%m-%d"), "%Y-%m-%d")).days398 ###### Initialization #####399 def _setSensorRooms(self):400 '''401 set room information in sensor entry 402 '''403 for sensor in self.getAllSensors():404 print('sensor:', sensor)405 for room in self.getAllRooms():406 if sensor['key'] in room['sensors']:407 print('update:', sensor['key'], room['key'])408 self.mongo.db.sensor.update_one({'key': sensor['key']}, {409 '$set': {'room': room['key']}}, upsert=True)410 def _setActuatorRooms(self):411 '''412 set room information in actuator entry413 '''414 for actuator in self.getAllActuators():415 for room in self.getAllRooms():416 if actuator['key'] in room['actuators']:417 self.mongo.db.actuator.update_one({'key': actuator['key']}, {418 '$set': {'room': room['key']}}, upsert=True)419 def _initialisation(self):420 '''421 Database initialisation422 '''423 # delete all tables424 self.mongo.db.sensor.drop()425 self.mongo.db.user.drop()426 self.mongo.db.room.drop()427 self.mongo.db.actuator.drop()428 self.mongo.db.roommanager.drop()429 # insert sensors430 self.mongo.db.sensor.insert(Sensor(431 key='multisensor_Relative_Humidity', sensortype='humidity', data={'Humidity': 0}).getDict())432 self.mongo.db.sensor.insert(Sensor(433 key='multisensor_Temperature', sensortype='temperature', data={'Temperature': 0}).getDict())434 self.mongo.db.sensor.insert(435 Sensor(key='multisensor_Ultraviolet', sensortype='ultraviolet').getDict())436 self.mongo.db.sensor.insert(437 Sensor(key='multisensor_Group_1_Interval', sensortype='interval').getDict())438 self.mongo.db.sensor.insert(Sensor(439 key='multisensor_Luminance', sensortype='luminance', data={'Luminance': 30}).getDict())440 self.mongo.db.sensor.insert(441 Sensor(key='plugwise1_type', sensortype='plugtype').getDict())442 self.mongo.db.sensor.insert(443 Sensor(key='plugwise1_typ', sensortype='plugtyp').getDict())444 self.mongo.db.sensor.insert(445 Sensor(key='plugwise1_ts', sensortype='plugts').getDict())446 self.mongo.db.sensor.insert(447 Sensor(key='plugwise1_mac', sensortype='plugmac').getDict())448 self.mongo.db.sensor.insert(449 Sensor(key='plugwise1_power', sensortype='lightpower').getDict())450 self.mongo.db.sensor.insert(451 Sensor(key='plugwise1_switch', sensortype='lightswitch').getDict())452 self.mongo.db.sensor.insert(453 Sensor(key='plugwise1_energy', sensortype='lightenergy').getDict())454 self.mongo.db.sensor.insert(455 Sensor(key='plugwise1_cum_energy', sensortype='lightcumenergy').getDict())456 self.mongo.db.sensor.insert(Sensor(key='plugwise1_pwenergy').getDict())457 self.mongo.db.sensor.insert(Sensor(key='plugwise1_power82').getDict())458 self.mongo.db.sensor.insert(Sensor(key='plugwise1_powerts').getDict())459 self.mongo.db.sensor.insert(Sensor(key='plugwise1_name').getDict())460 self.mongo.db.sensor.insert(Sensor(key='plugwise1_schedule').getDict())461 self.mongo.db.sensor.insert(Sensor(key='plugwise1_requid').getDict())462 self.mongo.db.sensor.insert(Sensor(key='plugwise1_power1s').getDict())463 self.mongo.db.sensor.insert(Sensor(key='plugwise1_switcheq').getDict())464 self.mongo.db.sensor.insert(Sensor(key='plugwise1_readonly').getDict())465 self.mongo.db.sensor.insert(466 Sensor(key='plugwise1_interval', sensortype='lightinterval').getDict())467 self.mongo.db.sensor.insert(Sensor(key='plugwise2_type').getDict())468 self.mongo.db.sensor.insert(Sensor(key='plugwise2_typ').getDict())469 self.mongo.db.sensor.insert(Sensor(key='plugwise2_ts').getDict())470 self.mongo.db.sensor.insert(Sensor(key='plugwise2_mac').getDict())471 self.mongo.db.sensor.insert(472 Sensor(key='plugwise2_power', sensortype='fanpower').getDict())473 self.mongo.db.sensor.insert(474 Sensor(key='plugwise2_switch', sensortype='fanswitch').getDict())475 self.mongo.db.sensor.insert(476 Sensor(key='plugwise2_energy', sensortype='fanenergy').getDict())477 self.mongo.db.sensor.insert(478 Sensor(key='plugwise2_cum_energy', sensortype='fancumenergy').getDict())479 self.mongo.db.sensor.insert(Sensor(key='plugwise2_pwenergy').getDict())480 self.mongo.db.sensor.insert(Sensor(key='plugwise2_power82').getDict())481 self.mongo.db.sensor.insert(Sensor(key='plugwise2_powerts').getDict())482 self.mongo.db.sensor.insert(Sensor(key='plugwise2_name').getDict())483 self.mongo.db.sensor.insert(Sensor(key='plugwise2_schedule').getDict())484 self.mongo.db.sensor.insert(Sensor(key='plugwise2_requid').getDict())485 self.mongo.db.sensor.insert(Sensor(key='plugwise2_power1s').getDict())486 self.mongo.db.sensor.insert(Sensor(key='plugwise2_switcheq').getDict())487 self.mongo.db.sensor.insert(Sensor(key='plugwise2_readonly').getDict())488 self.mongo.db.sensor.insert(489 Sensor(key='plugwise2_interval', sensortype='faninterval').getDict())490 self.mongo.db.sensor.insert(Sensor(491 key='gpiosensor_window', sensortype='window', data={'window': 0}).getDict())492 for i in range(19):493 self.mongo.db.sensor.insert(494 Sensor(key='sensor' + str(i)).getDict())495 # insers actuators496 self.mongo.db.actuator.insert(Actuator(497 key='stateled1', actuatortype='stateled', topicdata={'data': 0}).getDict())498 self.mongo.db.actuator.insert(Actuator(499 key='stateled2', actuatortype='stateled', topicdata={'data': 0}).getDict())500 self.mongo.db.actuator.insert(Actuator(501 key='stateled3', actuatortype='stateled', topicdata={'data': 0}).getDict())502 self.mongo.db.actuator.insert(Actuator(503 key='stateled4', actuatortype='stateled', topicdata={'data': 0}).getDict())504 self.mongo.db.actuator.insert(Actuator(505 key='stateled5', actuatortype='stateled', topicdata={'data': 0}).getDict())506 self.mongo.db.actuator.insert(Actuator(507 key='stateled6', actuatortype='stateled', topicdata={'data': 0}).getDict())508 self.mongo.db.actuator.insert(Actuator(509 key='stateled7', actuatortype='stateled', topicdata={'data': 0}).getDict())510 self.mongo.db.actuator.insert(Actuator(511 key='stateled8', actuatortype='stateled', topicdata={'data': 0}).getDict())512 self.mongo.db.actuator.insert(Actuator(513 key='stateled9', actuatortype='stateled', topicdata={'data': 0}).getDict())514 self.mongo.db.actuator.insert(Actuator(515 key='stateled10', actuatortype='stateled', topicdata={'data': 0}).getDict())516 self.mongo.db.actuator.insert(Actuator(517 key='notificationrgbled1', actuatortype='notificationrgbled', topicdata={'state': [0, 0, 0]}).getDict())518 self.mongo.db.actuator.insert(Actuator(key='light1', actuatortype='light',519 topic='plugwise2py/cmd/switch/000D6F0004B1E6C4', topicdata={'mac': "", "cmd": "switch", "val": "off"}).getDict())520 self.mongo.db.actuator.insert(Actuator(key='fan1', actuatortype='fan', topic='plugwise2py/cmd/switch/000D6F0005692B55',521 topicdata={'mac': "", "cmd": "switch", "val": "off"}).getDict())522 # insert Rooms523 self.mongo.db.room.insert(Room(key='room1', maxStaff=5, sensors=['multisensor_Relative_Humidity',524 'multisensor_Temperature',525 'multisensor_Ultraviolet',526 'multisensor_Luminance',527 'multisensor_Group_1_Interval',528 'gpiosensor_window',529 'plugwise1_power',530 'plugwise1_switch',531 'plugwise1_energy',532 'plugwise1_cum_energy',533 'plugwise1_interval',534 'plugwise2_power',535 'plugwise2_switch',536 'plugwise2_energy',537 'plugwise2_cum_energy',538 'plugwise2_interval'], actuators=['stateled1', 'notificationrgbled1', 'light1', 'fan1'], users=['staff1', 'staff2']).getDict())539 self.mongo.db.room.insert(Room(key='room2', maxStaff=3, sensors=[540 'sensor1', 'sensor2'], actuators=['stateled2']).getDict())541 self.mongo.db.room.insert(Room(key='room3', maxStaff=3, sensors=[542 'sensor3', 'sensor4'], actuators=['stateled3']).getDict())543 self.mongo.db.room.insert(Room(key='room4', maxStaff=3, sensors=[544 'sensor5', 'sensor6'], actuators=['stateled4']).getDict())545 self.mongo.db.room.insert(Room(key='room5', maxStaff=3, sensors=[546 'sensor7', 'sensor8'], actuators=['stateled5']).getDict())547 self.mongo.db.room.insert(Room(key='room6', maxStaff=3, sensors=[548 'sensor9', 'sensor10'], actuators=['stateled6']).getDict())549 self.mongo.db.room.insert(Room(key='room7', maxStaff=3, sensors=[550 'sensor11', 'sensor12'], actuators=['stateled7']).getDict())551 self.mongo.db.room.insert(Room(key='room8', maxStaff=3, sensors=[552 'sensor13', 'sensor14'], actuators=['stateled8']).getDict())553 self.mongo.db.room.insert(Room(key='room9', maxStaff=3, sensors=[554 'sensor15', 'sensor16'], actuators=['stateled9']).getDict())555 self.mongo.db.room.insert(Room(key='room10', maxStaff=3, sensors=[556 'sensor17', 'sensor18'], actuators=['stateled10']).getDict())557 # insert User558 for i in range(32):559 self.mongo.db.user.insert(User(key='staff' + str(i)).getDict())560 # insert roommaps561 self.mongo.db.roommanager.insert(Roommap(util.datumToSeconds(562 "2019-07-15"), 'room1', users=['staff1', 'staff2']).getDict())563 self.mongo.db.roommanager.insert(Roommap(util.datumToSeconds(564 "2019-07-15"), 'room3', users=['staff10', 'staff12']).getDict())565 self.mongo.db.roommanager.insert(Roommap(util.datumToSeconds(566 "2019-07-15"), 'room7', users=['staff20', 'staff21']).getDict())567 self.mongo.db.roommanager.insert(568 Roommap(util.datumToSeconds("2019-07-16"), 'room1', users=[]).getDict())569 # add relations into database570 self._setSensorRooms()...

Full Screen

Full Screen

tools_shelf_actions.py

Source:tools_shelf_actions.py Github

copy

Full Screen

1# Copyright 2001-2016 Crytek GmbH / Crytek Group. All rights reserved.2import time, re, os, sys, itertools, ast 3import general4global ctrlFile5ctrlFile = 'setState.txt'6global logfile7logfile = 'Editor.log'8def getLogList(logfile):9 logList = [x for x in open(logfile, 'r')]10 return logList11def getCheckList(ctrlFile): 12 try:13 with open(ctrlFile):14 stateList = open(ctrlFile, 'r')15 except:16 open(ctrlFile, 'w').close()17 stateList = open(ctrlFile, 'r')18 checkList = [x for x in stateList]19 return checkList20 21#toggle CVars--------------------------------------------------------------------# 22def toggleCvarsRestartCheck(log, state, mode, cVars, onValue, offValue, ctrlFile):23 if log in state:24 toggleCvarsV(mode, cVars, onValue, offValue, ctrlFile)25 else:26 stateList = open(ctrlFile, 'w')27 stateList.write(log)28 stateList = open(ctrlFile, 'r') 29 toggleCvarsV(mode, cVars, onValue, offValue, ctrlFile)30 31def toggleCvarsV(mode, cVars, onValue, offValue, ctrlFile):32 stateList = open(ctrlFile, 'r') 33 setState = [x for x in enumerate(stateList)] 34 blankCheck = [x for x in setState]35 getList = [x for x in stateList]36 37 if blankCheck == []:38 stateList = open(ctrlFile, 'w')39 stateList.write(''.join(str("%s,{'%s': %s}" % (mode, cVars, offValue))+'\n'))40 general.set_cvar(cVars, offValue)41 else:42 stateList = open(ctrlFile, 'r')43 checkFor = str([x for x in stateList])44 if mode not in str(checkFor):45 stateList = open(ctrlFile, 'r')46 getList = [x for x in stateList] 47 getList.insert(1, str("%s,{'%s': %s}\n" % (mode, cVars , offValue)))48 print str("{'%s': %s}\n" % (cVars , offValue))49 stateList = open(ctrlFile, 'w')50 stateList.write(''.join(getList)) 51 general.set_cvar(cVars, offValue)52 53 else:54 stateList = open(ctrlFile, 'r')55 for d in enumerate(stateList):56 values = d[1].split(',')57 stateList = open(ctrlFile, 'r')58 getList = [x for x in stateList] 59 60 if mode in values[0]:61 getDict = ast.literal_eval(values[1])62 getState = getDict.get(cVars)63 64 if getState == offValue:65 getDict[cVars] = onValue66 joinStr = [mode,",",str(getDict), '\n']67 newLine = ''.join(joinStr)68 print getDict69 getList[d[0]] = newLine70 stateList = open(ctrlFile, 'w')71 stateList.write(''.join(str(''.join(getList))))72 general.set_cvar(cVars, onValue)73 else: 74 getDict[cVars] = offValue75 joinStr = [mode,",",str(getDict), '\n']76 newLine = ''.join(joinStr)77 print getDict78 getList[d[0]] = newLine79 stateList = open(ctrlFile, 'w')80 stateList.write(''.join(str(''.join(getList))))81 general.set_cvar(cVars, offValue)82def toggleCvarsValue(mode, cVars, onValue, offValue):83 logList = getLogList(logfile)84 checkList = getCheckList(ctrlFile)85 toggleCvarsRestartCheck(logList[1], checkList, mode, cVars, onValue, offValue, ctrlFile) 86 87#toggleConsol--------------------------------------------------------------------# 88 89def toggleConsolRestartCheck(log,state, mode, onValue, offValue, ctrlFile): 90 if log in state:91 toggleConsolV(mode, onValue, offValue, ctrlFile)92 else:93 stateList = open(ctrlFile, 'w')94 stateList.write(log)95 stateList = open(ctrlFile, 'r') 96 toggleConsolV(mode, onValue, offValue, ctrlFile)97 98def toggleConsolV(mode, onValue, offValue):99 stateList = open(ctrlFile, 'r') 100 setState = [x for x in enumerate(stateList)] 101 blankCheck = [x for x in setState]102 getList = [x for x in stateList]103 onOffList = [onValue, offValue]104 105 if blankCheck == []:106 stateList = open(ctrlFile, 'w')107 stateList.write(''.join(str("%s,'%s'" % (mode, offValue))+'\n'))108 general.run_console(offValue)109 else:110 stateList = open(ctrlFile, 'r')111 checkFor = str([x for x in stateList])112 113 if mode not in str(checkFor):114 stateList = open(ctrlFile, 'r')115 getList = [x for x in stateList] 116 getList.insert(1, str("%s,'%s'\n" % (mode, offValue)))117 print str("{'%s': %s}\n" % (cVars , offValue))118 stateList = open(ctrlFile, 'w')119 stateList.write(''.join(getList)) 120 general.run_console(onValue)121 122 else:123 stateList = open(ctrlFile, 'r')124 for d in enumerate(stateList):125 126 values = d[1].split(',')127 128 stateList = open(ctrlFile, 'r')129 getList = [x for x in stateList] 130 131 if mode in values[0]:132 getDict = values[1]133 off = ["'",str(offValue),"'", '\n']134 joinoff = ''.join(off)135 if values[1] == joinoff:136 getDict = onValue137 joinStr = [mode,",","'",getDict,"'", '\n']138 newLine = ''.join(joinStr)139 print getDict140 getList[d[0]] = str(newLine) 141 stateList = open(ctrlFile, 'w')142 stateList.write(''.join(str(''.join(getList))))143 general.run_console(onValue)144 else: 145 getDict = offValue146 joinStr = [mode,",","'",getDict,"'", '\n']147 newLine = ''.join(joinStr)148 print getDict149 getList[d[0]] = str(newLine) 150 stateList = open(ctrlFile, 'w')151 stateList.write(''.join(str(''.join(getList))))152 general.run_console(offValue) 153def toggleConsolValue(log, state, mode, onValue, offValue):154 logList = getLogList(logfile)155 checkList = getCheckList(ctrlFile)156 toggleConsolRestartCheck(logList[1],checkList, mode, onValue, offValue, ctrlFile)157 158#cycleCvars----------------------------------------------------------------------#159 160def cycleCvarsRestartCheck(log, state, mode, cVars, cycleList, ctrlFile): 161 if log in state:162 cycleCvarsV(mode, cVars, cycleList, ctrlFile)163 else:164 stateList = open(ctrlFile, 'w')165 stateList.write(log)166 stateList = open(ctrlFile, 'r') 167 cycleCvarsV(mode, cVars, cycleList, ctrlFile)168 169def cycleCvarsV(mode, cVars, cycleList, ctrlFile):170 stateList = open(ctrlFile, 'r') 171 setState = [x for x in enumerate(stateList)] 172 blankCheck = [x for x in setState]173 getList = [x for x in stateList]174 if blankCheck == []:175 stateList = open(ctrlFile, 'w')176 stateList.write(''.join(str("%s,{'%s': %s}" % (mode, cVars, cycleList[1]))+'\n'))177 general.set_cvar(cVars, cycleList[1])178 else:179 stateList = open(ctrlFile, 'r')180 checkFor = str([x for x in stateList])181 182 if mode not in str(checkFor):183 stateList = open(ctrlFile, 'r')184 getList = [x for x in stateList] 185 getList.insert(1, str("%s,{'%s': %s}\n" % (mode, cVars , cycleList[1])))186 #print '%s' % cycleList[1]187 stateList = open(ctrlFile, 'w')188 stateList.write(''.join(getList)) 189 general.set_cvar(cVars, cycleList[1])190 else:191 stateList = open(ctrlFile, 'r')192 193 for d in enumerate(stateList):194 stateList = open(ctrlFile, 'r')195 getList = [x for x in stateList] 196 values = d[1].split(',')197 198 if mode in values[0]:199 getDict = ast.literal_eval(values[1])200 getState = getDict.get(cVars)201 cycleL = [x for x in enumerate(cycleList)]202 for x in cycleL:203 if getState == x[1]:204 number = [n[1] for n in cycleL] 205 getMax = max(number)206 nextNum = x[0]+1207 208 if nextNum > getMax:209 getDict[cVars] = cycleList[0]210 joinStr = [mode,",",str(getDict), '\n']211 newLine = ''.join(joinStr)212 getList[d[0]] = newLine213 print getDict214 stateList = open(ctrlFile, 'w')215 stateList.write(''.join(str(''.join(getList))))216 general.set_cvar(cVars, cycleList[0])217 else:218 getDict[cVars] = cycleList[x[0]+1]219 joinStr = [mode,",",str(getDict), '\n']220 newLine = ''.join(joinStr)221 getList[d[0]] = newLine222 print getDict223 stateList = open(ctrlFile, 'w')224 stateList.write(''.join(str(''.join(getList))))225 general.set_cvar(cVars, cycleList[x[0]+1])226def cycleCvarsValue(log, state, mode, cVars, cycleList):227 logList = getLogList(logfile)228 checkList = getCheckList(ctrlFile)229 cycleCvarsRestartCheck(logList[1],checkList, mode, cVars, cycleList, ctrlFile) 230 231#cycleConsol----------------------------------------------------------------------# 232 233def cycleConsolRestartCheck(log, state, mode, cycleList, ctrlFile): 234 if log in state:235 cycleConsolV(mode, cycleList, ctrlFile)236 else:237 stateList = open(ctrlFile, 'w')238 stateList.write(log)239 stateList = open(ctrlFile, 'r') 240 cycleConsolV(mode, cycleList, ctrlFile)241 242def cycleConsolV(mode, cycleList, ctrlFile):243 stateList = open(ctrlFile, 'r') 244 setState = [x for x in enumerate(stateList)] 245 blankCheck = [x for x in setState]246 getList = [x for x in stateList]247 248 if blankCheck == []:249 stateList = open(ctrlFile, 'w')250 stateList.write(''.join(str("%s,'%s'" % (mode, cycleList[0]))+'\n'))251 general.run_console(cycleList[0])252 else:253 stateList = open(ctrlFile, 'r')254 checkFor = str([x for x in stateList])255 256 if mode not in str(checkFor):257 stateList = open(ctrlFile, 'r')258 getList = [x for x in stateList] 259 getList.insert(1, str("%s,'%s'\n" % (mode, cycleList[0])))260 #print '%s' % cycleList[0]261 stateList = open(ctrlFile, 'w')262 stateList.write(''.join(getList)) 263 general.run_console(cycleList[0])264 265 else:266 stateList = open(ctrlFile, 'r')267 for d in enumerate(stateList):268 stateList = open(ctrlFile, 'r')269 getList = [x for x in stateList] 270 values = d[1].split(',')271 if mode in values[0]:272 newValue = ''.join(values[1].split('\n'))273 cycleL = [e for e in enumerate(cycleList)]274 getDict = ''.join(values[1].split('\n'))275 276 for x in cycleL:277 if newValue in "'%s'" % x[1]:278 number = [n[0] for n in cycleL] 279 getMax = max(number)280 nextNum = x[0]+1281 282 if nextNum > getMax:283 getDict = '%s' % cycleList[0]284 joinStr = [mode,",","'",getDict,"'", '\n']285 newLine = ''.join(joinStr)286 getList[d[0]] = newLine287 print getDict288 stateList = open(ctrlFile, 'w')289 stateList.write(''.join(str(''.join(getList))))290 general.run_console(getDict)291 else:292 getDict = '%s' % cycleList[x[0]+1]293 joinStr = [mode,",","'",getDict,"'", '\n']294 newLine = ''.join(joinStr)295 getList[d[0]] = newLine296 print getDict297 stateList = open(ctrlFile, 'w')298 stateList.write(''.join(str(''.join(getList))))299 general.run_console(getDict)300 301def cycleConsolValue(mode, cycleList):302 logList = getLogList(logfile)303 checkList = getCheckList(ctrlFile)304 cycleConsolRestartCheck(logList[1],checkList, mode, cycleList, ctrlFile)305 306def toggleHideMaskValues(type):307 if (general.get_hidemask(type)):308 general.set_hidemask(type, 0)309 else:310 general.set_hidemask(type, 1)311 312#toggleHide------------------------------------------------------------------------#313 314def toggleHideRestartCheck(log, state, mode, type, onValue, offValue, ctrlFile):315 if log in state:316 toggleHideByT(mode, type, onValue, offValue, ctrlFile)317 else:318 stateList = open(ctrlFile, 'w')319 stateList.write(log)320 stateList = open(ctrlFile, 'r') 321 toggleHideByT(mode, type, onValue, offValue, ctrlFile)322def toggleHideByType(mode, type, onValue, offValue):323 logList = getLogList(logfile)324 checkList = getCheckList(ctrlFile)325 toggleHideRestartCheck(logList[1],checkList, mode, type, onValue, offValue, ctrlFile)326 327def toggleHideByT(mode, type, onValue, offValue, ctrlFile):328 stateList = open(ctrlFile, 'r') 329 setState = [x for x in enumerate(stateList)] 330 blankCheck = [x for x in setState]331 getList = [x for x in stateList]332 333 if blankCheck == []:334 stateList = open(ctrlFile, 'w')335 stateList.write(''.join(str("%s,{'%s': %s}" % (mode, type, offValue))+'\n'))336 337 hideByType(type)338 else:339 stateList = open(ctrlFile, 'r')340 checkFor = str([x for x in stateList])341 342 if mode not in str(checkFor):343 stateList = open(ctrlFile, 'r')344 getList = [x for x in stateList] 345 getList.insert(1, str("%s,{'%s': %s}\n" % (mode, type , offValue)))346 print str("{'%s': %s}\n" % (type , offValue))347 stateList = open(ctrlFile, 'w')348 stateList.write(''.join(getList)) 349 hideByType(type)350 else:351 stateList = open(ctrlFile, 'r')352 for d in enumerate(stateList):353 values = d[1].split(',')354 stateList = open(ctrlFile, 'r')355 getList = [x for x in stateList] 356 357 if mode in values[0]:358 getDict = ast.literal_eval(values[1])359 getState = getDict.get(type)360 361 if getState == offValue:362 getDict[type] = onValue363 joinStr = [mode,",",str(getDict), '\n']364 newLine = ''.join(joinStr)365 print getDict366 getList[d[0]] = newLine367 stateList = open(ctrlFile, 'w')368 stateList.write(''.join(str(''.join(getList))))369 unHideByType(type)370 else: 371 getDict[type] = offValue372 joinStr = [mode,",",str(getDict), '\n']373 newLine = ''.join(joinStr)374 print getDict375 getList[d[0]] = newLine376 stateList = open(ctrlFile, 'w')377 stateList.write(''.join(str(''.join(getList))))378 hideByType(type)379def hideByType(type): 380 typeList = general.get_all_objects(str(type), "")381 #print typeList382 #general.select_objects(typeList)383 for x in typeList:384 general.hide_object(x)385 386def unHideByType(type): 387 typeList = general.get_all_objects(str(type), "")388 #print typeList389 #general.select_objects(typeList)390 for x in typeList:...

Full Screen

Full Screen

test_minimal_logic.py

Source:test_minimal_logic.py Github

copy

Full Screen

1import unittest2from data_generation.minimal_proplogic import *3class Test(unittest.TestCase):4 def test_getdict_list(self):5 self.assertEqual(getdict_list("01", ["Symbol_1", "Symbol_2"]), {"Symbol_1": False, "Symbol_2": True})6 self.assertEqual(getdict_list("10", ["Symbol_10", "Symbol_100"]), {"Symbol_10": True, "Symbol_100": False})7 def test_evaluate(self):8 self.assertTrue(evaluate_sentence("1"))9 self.assertTrue(evaluate_sentence("(1&1)"))10 self.assertTrue(evaluate_sentence("(1|1)"))11 self.assertTrue(evaluate_sentence("(0|1)"))12 self.assertTrue(evaluate_sentence("(1|0)"))13 self.assertTrue(evaluate_sentence("~(0|0)"))14 self.assertTrue(evaluate_sentence("~(0)"))15 self.assertTrue(evaluate_sentence("((1&1)|0)"))16 self.assertTrue(evaluate_sentence("((1&0)|1)"))17 self.assertFalse(evaluate_sentence("0"))18 self.assertFalse(evaluate_sentence("(0&1)"))19 self.assertFalse(evaluate_sentence("(1&0)"))20 self.assertFalse(evaluate_sentence("~(1)"))21 self.assertFalse(evaluate_sentence("~(1&1)"))22 self.assertFalse(evaluate_sentence("~(1|0)"))23 self.assertFalse(evaluate_sentence("~(0|1)"))24 def test_eval_assignment_in_world(self):25 sentence0 = "~ ( Symbol_1 & Symbol_2 )"26 sentence0_true_dict = getdict_list("01", ["Symbol_1", "Symbol_2"])27 sentence0_false_dict = getdict_list("11", ["Symbol_1", "Symbol_2"])28 self.assertTrue(eval_assignment_in_world(sentence0, sentence0_true_dict))29 self.assertFalse(eval_assignment_in_world(sentence0, sentence0_false_dict))30 sentence1 = "~ ( Symbol_3 | Symbol_4 )"31 sentence1_true_dict = getdict_list("00", ["Symbol_4", "Symbol_3"])32 sentence1_false_dict = getdict_list("10", ["Symbol_4", "Symbol_3"])33 self.assertTrue(eval_assignment_in_world(sentence1, sentence1_true_dict))34 self.assertFalse(eval_assignment_in_world(sentence1, sentence1_false_dict))35 sentence2 = "( Symbol_10 & ~ ( Symbol_1010 | Symbol_1010 ) )"36 sentence2_true_dict = getdict_list("01", ["Symbol_1010", "Symbol_10"])37 sentence2_false_dict = getdict_list("10", ["Symbol_1010", "Symbol_10"])38 self.assertTrue(eval_assignment_in_world(sentence2, sentence2_true_dict))39 self.assertFalse(eval_assignment_in_world(sentence2, sentence2_false_dict))40 sentence3 = "( ~ ( Symbol_9 ) | ( Symbol_99 & Symbol_999 ) )"41 sentence3_true_dict = getdict_list("111", ["Symbol_99", "Symbol_999", "Symbol_9"])42 sentence3_false_dict = getdict_list("001", ["Symbol_99", "Symbol_999", "Symbol_9"])43 self.assertTrue(eval_assignment_in_world(sentence3, sentence3_true_dict))44 self.assertFalse(eval_assignment_in_world(sentence3, sentence3_false_dict))45 sentence4 = "( Symbol_3021 )"46 sentence4_true_dict = getdict_list("1", ["Symbol_3021"])47 sentence4_false_dict = getdict_list("0", ["Symbol_3021"])48 self.assertTrue(eval_assignment_in_world(sentence4, sentence4_true_dict))49 self.assertFalse(eval_assignment_in_world(sentence4, sentence4_false_dict))50if __name__ == "__main__":...

Full Screen

Full Screen

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run tox automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful