How to use actionName method in fMBT

Best Python code snippet using fMBT_python

subsetting_config.py

Source:subsetting_config.py Github

copy

Full Screen

1def get_subsetting_config():2 subsettingConfig = {3 "config": {4 "FILTER_SETTINGS": {5 "measureColumnFilters": [6 {7 "filterType": "valueRange",8 "lowerBound": 9,9 "colname": "education-num",10 "upperBound": 911 }12 ],13 "dimensionColumnFilters": [14 ],15 "timeDimensionColumnFilters": [16 ]17 },18 "DATA_SOURCE": {19 "datasource_type": "fileUpload",20 "datasource_details": ""21 },22 "COLUMN_SETTINGS": {23 "analysis_type": [24 "metaData"25 ]26 },27 "TRANSFORMATION_SETTINGS": {28 "existingColumns": [29 {30 "slug": "0f37d194687f43e09573aa07326c26b2",31 "name": "age",32 "columnSetting": [33 {34 "status": False,35 "actionName": "unique_identifier",36 "displayName": "Unique Identifier"37 },38 {39 "status": False,40 "actionName": "delete",41 "displayName": "Delete Column"42 },43 {44 "status": False,45 "actionName": "rename",46 "displayName": "Rename Column",47 "newName": None48 },49 {50 "status": False,51 "actionName": "replace",52 "replaceTypeList": [53 {54 "displayName": "Contains",55 "name": "contains"56 },57 {58 "displayName": "Equal To",59 "name": "equals"60 },61 {62 "displayName": "Starts With",63 "name": "startsWith"64 },65 {66 "displayName": "Ends With",67 "name": "endsWith"68 }69 ],70 "displayName": "Replace Values",71 "replacementValues": [72 ]73 },74 {75 "status": False,76 "actionName": "data_type",77 "displayName": "Change Datatype",78 "listOfActions": [79 {80 "status": True,81 "displayName": "Numeric",82 "name": "numeric"83 },84 {85 "status": False,86 "displayName": "Text",87 "name": "text"88 }89 ]90 },91 {92 "status": False,93 "actionName": "set_variable",94 "displayName": "Set Variable as",95 "listOfActions": [96 {97 "status": True,98 "displayName": "General Numeric",99 "name": "general_numeric"100 },101 {102 "status": False,103 "displayName": "Percentage",104 "name": "percentage"105 },106 {107 "status": False,108 "displayName": "Index",109 "name": "index"110 },111 {112 "status": False,113 "displayName": "Average",114 "name": "average"115 }116 ]117 },118 {119 "status": False,120 "actionName": "set_polarity",121 "displayName": "Set Polarity as",122 "listOfActions": [123 {124 "status": True,125 "displayName": "Positive",126 "name": "positive"127 },128 {129 "status": False,130 "displayName": "Negative",131 "name": "negative"132 }133 ]134 },135 {136 "status": False,137 "actionName": "ignore_suggestion",138 "displayName": "Ignore for Analysis",139 "previous_status": False140 }141 ]142 },143 {144 "slug": "26dbb1f77f614106bd1a704c9c0c4bb8",145 "name": "education",146 "columnSetting": [147 {148 "status": False,149 "actionName": "unique_identifier",150 "displayName": "Unique Identifier"151 },152 {153 "status": False,154 "actionName": "delete",155 "displayName": "Delete Column"156 },157 {158 "status": False,159 "actionName": "rename",160 "displayName": "Rename Column",161 "newName": None162 },163 {164 "status": False,165 "actionName": "replace",166 "replaceTypeList": [167 {168 "displayName": "Contains",169 "name": "contains"170 },171 {172 "displayName": "Equal To",173 "name": "equals"174 },175 {176 "displayName": "Starts With",177 "name": "startsWith"178 },179 {180 "displayName": "Ends With",181 "name": "endsWith"182 }183 ],184 "displayName": "Replace Values",185 "replacementValues": [186 ]187 },188 {189 "status": False,190 "actionName": "ignore_suggestion",191 "displayName": "Ignore for Analysis",192 "previous_status": False193 }194 ]195 },196 {197 "slug": "bf209c718c3b406aac15df355030cae3",198 "name": "education-num",199 "columnSetting": [200 {201 "status": False,202 "actionName": "unique_identifier",203 "displayName": "Unique Identifier"204 },205 {206 "status": False,207 "actionName": "delete",208 "displayName": "Delete Column"209 },210 {211 "status": False,212 "actionName": "rename",213 "displayName": "Rename Column",214 "newName": None215 },216 {217 "status": False,218 "actionName": "replace",219 "replaceTypeList": [220 {221 "displayName": "Contains",222 "name": "contains"223 },224 {225 "displayName": "Equal To",226 "name": "equals"227 },228 {229 "displayName": "Starts With",230 "name": "startsWith"231 },232 {233 "displayName": "Ends With",234 "name": "endsWith"235 }236 ],237 "displayName": "Replace Values",238 "replacementValues": [239 ]240 },241 {242 "status": False,243 "actionName": "data_type",244 "displayName": "Change Datatype",245 "listOfActions": [246 {247 "status": True,248 "displayName": "Numeric",249 "name": "numeric"250 },251 {252 "status": False,253 "displayName": "Text",254 "name": "text"255 }256 ]257 },258 {259 "status": False,260 "actionName": "set_variable",261 "displayName": "Set Variable as",262 "listOfActions": [263 {264 "status": True,265 "displayName": "General Numeric",266 "name": "general_numeric"267 },268 {269 "status": False,270 "displayName": "Percentage",271 "name": "percentage"272 },273 {274 "status": False,275 "displayName": "Index",276 "name": "index"277 },278 {279 "status": False,280 "displayName": "Average",281 "name": "average"282 }283 ]284 },285 {286 "status": False,287 "actionName": "set_polarity",288 "displayName": "Set Polarity as",289 "listOfActions": [290 {291 "status": True,292 "displayName": "Positive",293 "name": "positive"294 },295 {296 "status": False,297 "displayName": "Negative",298 "name": "negative"299 }300 ]301 },302 {303 "status": False,304 "actionName": "ignore_suggestion",305 "displayName": "Ignore for Analysis",306 "previous_status": False307 }308 ]309 },310 {311 "slug": "c89d460d3d57463e89ec68743687416a",312 "name": "relationship",313 "columnSetting": [314 {315 "status": False,316 "actionName": "unique_identifier",317 "displayName": "Unique Identifier"318 },319 {320 "status": False,321 "actionName": "delete",322 "displayName": "Delete Column"323 },324 {325 "status": False,326 "actionName": "rename",327 "displayName": "Rename Column",328 "newName": None329 },330 {331 "status": False,332 "actionName": "replace",333 "replaceTypeList": [334 {335 "displayName": "Contains",336 "name": "contains"337 },338 {339 "displayName": "Equal To",340 "name": "equals"341 },342 {343 "displayName": "Starts With",344 "name": "startsWith"345 },346 {347 "displayName": "Ends With",348 "name": "endsWith"349 }350 ],351 "displayName": "Replace Values",352 "replacementValues": [353 ]354 },355 {356 "status": False,357 "actionName": "ignore_suggestion",358 "displayName": "Ignore for Analysis",359 "previous_status": False360 }361 ]362 },363 {364 "slug": "722123903acd4850b83a0b39de91bcc1",365 "name": "race",366 "columnSetting": [367 {368 "status": False,369 "actionName": "unique_identifier",370 "displayName": "Unique Identifier"371 },372 {373 "status": False,374 "actionName": "delete",375 "displayName": "Delete Column"376 },377 {378 "status": False,379 "actionName": "rename",380 "displayName": "Rename Column",381 "newName": None382 },383 {384 "status": False,385 "actionName": "replace",386 "replaceTypeList": [387 {388 "displayName": "Contains",389 "name": "contains"390 },391 {392 "displayName": "Equal To",393 "name": "equals"394 },395 {396 "displayName": "Starts With",397 "name": "startsWith"398 },399 {400 "displayName": "Ends With",401 "name": "endsWith"402 }403 ],404 "displayName": "Replace Values",405 "replacementValues": [406 ]407 },408 {409 "status": False,410 "actionName": "ignore_suggestion",411 "displayName": "Ignore for Analysis",412 "previous_status": False413 }414 ]415 },416 {417 "slug": "e55473c7a15245b5b24af14a160914bb",418 "name": "sex",419 "columnSetting": [420 {421 "status": False,422 "actionName": "unique_identifier",423 "displayName": "Unique Identifier"424 },425 {426 "status": False,427 "actionName": "delete",428 "displayName": "Delete Column"429 },430 {431 "status": False,432 "actionName": "rename",433 "displayName": "Rename Column",434 "newName": None435 },436 {437 "status": False,438 "actionName": "replace",439 "replaceTypeList": [440 {441 "displayName": "Contains",442 "name": "contains"443 },444 {445 "displayName": "Equal To",446 "name": "equals"447 },448 {449 "displayName": "Starts With",450 "name": "startsWith"451 },452 {453 "displayName": "Ends With",454 "name": "endsWith"455 }456 ],457 "displayName": "Replace Values",458 "replacementValues": [459 ]460 },461 {462 "status": False,463 "actionName": "ignore_suggestion",464 "displayName": "Ignore for Analysis",465 "previous_status": False466 }467 ]468 },469 {470 "slug": "b768943ae03f4093ab5f0395325afb19",471 "name": "Capital-gain",472 "columnSetting": [473 {474 "status": False,475 "actionName": "unique_identifier",476 "displayName": "Unique Identifier"477 },478 {479 "status": False,480 "actionName": "delete",481 "displayName": "Delete Column"482 },483 {484 "status": False,485 "actionName": "rename",486 "displayName": "Rename Column",487 "newName": None488 },489 {490 "status": False,491 "actionName": "replace",492 "replaceTypeList": [493 {494 "displayName": "Contains",495 "name": "contains"496 },497 {498 "displayName": "Equal To",499 "name": "equals"500 },501 {502 "displayName": "Starts With",503 "name": "startsWith"504 },505 {506 "displayName": "Ends With",507 "name": "endsWith"508 }509 ],510 "displayName": "Replace Values",511 "replacementValues": [512 ]513 },514 {515 "status": False,516 "actionName": "data_type",517 "displayName": "Change Datatype",518 "listOfActions": [519 {520 "status": True,521 "displayName": "Numeric",522 "name": "numeric"523 },524 {525 "status": False,526 "displayName": "Text",527 "name": "text"528 }529 ]530 },531 {532 "status": False,533 "actionName": "set_variable",534 "displayName": "Set Variable as",535 "listOfActions": [536 {537 "status": True,538 "displayName": "General Numeric",539 "name": "general_numeric"540 },541 {542 "status": False,543 "displayName": "Percentage",544 "name": "percentage"545 },546 {547 "status": False,548 "displayName": "Index",549 "name": "index"550 },551 {552 "status": False,553 "displayName": "Average",554 "name": "average"555 }556 ]557 },558 {559 "status": False,560 "actionName": "set_polarity",561 "displayName": "Set Polarity as",562 "listOfActions": [563 {564 "status": True,565 "displayName": "Positive",566 "name": "positive"567 },568 {569 "status": False,570 "displayName": "Negative",571 "name": "negative"572 }573 ]574 },575 {576 "status": False,577 "actionName": "ignore_suggestion",578 "displayName": "Ignore for Analysis",579 "previous_status": False580 }581 ]582 },583 {584 "slug": "b3a2a40c6ffc403999f5c31312963ffa",585 "name": "class_label",586 "columnSetting": [587 {588 "status": False,589 "actionName": "unique_identifier",590 "displayName": "Unique Identifier"591 },592 {593 "status": False,594 "actionName": "delete",595 "displayName": "Delete Column"596 },597 {598 "status": False,599 "actionName": "rename",600 "displayName": "Rename Column",601 "newName": None602 },603 {604 "status": False,605 "actionName": "replace",606 "replaceTypeList": [607 {608 "displayName": "Contains",609 "name": "contains"610 },611 {612 "displayName": "Equal To",613 "name": "equals"614 },615 {616 "displayName": "Starts With",617 "name": "startsWith"618 },619 {620 "displayName": "Ends With",621 "name": "endsWith"622 }623 ],624 "displayName": "Replace Values",625 "replacementValues": [626 ]627 },628 {629 "status": False,630 "actionName": "ignore_suggestion",631 "displayName": "Ignore for Analysis",632 "previous_status": False633 }634 ]635 }636 ]637 },638 "FILE_SETTINGS": {639 "outputfile": [640 #"gAAAAABaxGdWjSShSd8sbTDAo_7Jj8MvNP8Th9zCneWRxjeZw0GHNTZg2GLs9ebK6zJbC_uGbyqhkrOD0AsfwFgSsRQC8JI2EVIiBOmRXy6iKpLqQYWyrsbKm2Wl9BuTPgIQg7ngO_m6fS73C2ZBiUxiEwkfGSi8bUlCznZBRCI45vgQu0tIvBtrtWAKKQ5rbEplWxpUtjoG"641 "file:///home/gulshan/marlabs/csvout/data"642 ],643 "metadata": {644 "url": "34.196.204.54:9012/api/get_metadata_for_mlscripts/",645 "slug_list": [646 "demography100csv-jhgb0uix28"647 ]648 },649 "inputfile": [650 "file:///home/gulshan/marlabs/datasets/sampleDatasets/demography100.csv"651 ]652 },653 "DATE_SETTINGS": {654 }655 },656 "job_config": {657 "message_url": "http://34.196.204.54:9012/api/messages/Job_subsetting-gul-sub-ayju8x9s4m-rs4kp1im0t_123/",658 "get_config": {659 "action": "get_config",660 "method": "GET"661 },662 "error_reporting_url": "http://34.196.204.54:9012/api/set_job_report/subsetting-gul-sub-ayju8x9s4m-rs4kp1im0t/",663 "set_result": {664 "action": "result",665 "method": "PUT"666 },667 "job_url": "http://34.196.204.54:9012/api/job/subsetting-gul-sub-ayju8x9s4m-rs4kp1im0t/",668 "job_type": "subSetting",669 "job_name": "gul-sub",670 "xml_url": "http://34.196.204.54:9012/api/xml/subsetting-gul-sub-ayju8x9s4m-rs4kp1im0t/",671 "app_id": None672 }673 }...

Full Screen

Full Screen

amazon_ses.py

Source:amazon_ses.py Github

copy

Full Screen

1# http://tagmask.com/vladimir/posts/262#Copyright (c) 2011 Vladimir Pankratiev http://tagmask.com3#4#Permission is hereby granted, free of charge, to any person obtaining a copy5#of this software and associated documentation files (the "Software"), to deal6#in the Software without restriction, including without limitation the rights7#to use, copy, modify, merge, publish, distribute, sublicense, and/or sell8#copies of the Software, and to permit persons to whom the Software is9#furnished to do so, subject to the following conditions:10#11#The above copyright notice and this permission notice shall be included in12#all copies or substantial portions of the Software.13#14#THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR15#IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,16#FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE17#AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER18#LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,19#OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN20#THE SOFTWARE.21import httplib22import urllib23import hashlib24import hmac25import logging26import base6427from datetime import datetime28from xml.etree.ElementTree import XML29from django.conf import settings30log = logging.getLogger(__name__)31class AmazonSES:32 def __init__(self):33 self._accessKeyID = getattr(settings, 'AWS_ACCESS_KEY_ID', None)34 self._secretAccessKey = getattr(settings, 'AWS_SECRET_ACCESS_KEY', None)35 self._responseParser = AmazonResponseParser()36 def _getSignature(self, dateValue):37 h = hmac.new(key=self._secretAccessKey, msg=dateValue, digestmod=hashlib.sha256)38 return base64.b64encode(h.digest()).decode()39 def _getHeaders(self):40 headers = { 'Content-type': 'application/x-www-form-urlencoded' }41 d = datetime.utcnow()42 dateValue = d.strftime('%a, %d %b %Y %H:%M:%S GMT')43 headers['Date'] = dateValue44 signature = self._getSignature(dateValue)45 headers['X-Amzn-Authorization'] = 'AWS3-HTTPS AWSAccessKeyId=%s, Algorithm=HMACSHA256, Signature=%s' % (self._accessKeyID, signature)46 return headers47 def _performAction(self, actionName, params=None):48 if not params:49 params = {}50 params['Action'] = actionName51 #https://email.us-east-1.amazonaws.com/52 conn = httplib.HTTPSConnection('email.us-east-1.amazonaws.com')53 params = urllib.urlencode(params)54 conn.request('POST', '/', params, self._getHeaders())55 response = conn.getresponse()56 responseResult = response.read()57 conn.close()58 return self._responseParser.parse(actionName, response.status, response.reason, responseResult)59 def verifyEmailAddress(self, emailAddress):60 params = { 'EmailAddress': emailAddress }61 return self._performAction('VerifyEmailAddress', params)62 def deleteVerifiedEmailAddress(self, emailAddress):63 params = { 'EmailAddress': emailAddress }64 return self._performAction('DeleteVerifiedEmailAddress', params)65 def getSendQuota(self):66 return self._performAction('GetSendQuota')67 def getSendStatistics(self):68 return self._performAction('GetSendStatistics')69 def listVerifiedEmailAddresses(self):70 return self._performAction('ListVerifiedEmailAddresses')71 def sendEmail(self, source, toAddresses, message, replyToAddresses=None, returnPath=None, ccAddresses=None, bccAddresses=None):72 params = { 'Source': source }73 for objName, addresses in zip(["ToAddresses", "CcAddresses", "BccAddresses"], [toAddresses, ccAddresses, bccAddresses]):74 if addresses:75 if not isinstance(addresses, basestring) and getattr(addresses, '__iter__', False):76 for i, address in enumerate(addresses, 1):77 params['Destination.%s.member.%d' % (objName, i)] = address78 else:79 params['Destination.%s.member.1' % objName] = addresses80 if not returnPath:81 returnPath = source82 params['ReturnPath'] = returnPath83 params['Message.Subject.Charset'] = message.charset84 params['Message.Subject.Data'] = message.subject85 if message.bodyText:86 params['Message.Body.Text.Charset'] = message.charset87 params['Message.Body.Text.Data'] = message.bodyText88 if message.bodyHtml:89 params['Message.Body.Html.Charset'] = message.charset90 params['Message.Body.Html.Data'] = message.bodyHtml91 return self._performAction('SendEmail', params)92class EmailMessage:93 def __init__(self):94 self.charset = 'UTF-8'95 self.subject = None96 self.bodyHtml = None97 self.bodyText = None98class AmazonError(Exception):99 def __init__(self, errorType, code, message):100 self.errorType = errorType101 self.code = code102 self.message = message103class AmazonAPIError(Exception):104 def __init__(self, message):105 self.message = message106class AmazonResult:107 def __init__(self, requestId):108 self.requestId = requestId109class AmazonSendEmailResult(AmazonResult):110 def __init__(self, requestId, messageId):111 self.requestId = requestId112 self.messageId = messageId113class AmazonSendQuota(AmazonResult):114 def __init__(self, requestId, max24HourSend, maxSendRate, sentLast24Hours):115 self.requestId = requestId116 self.max24HourSend = max24HourSend117 self.maxSendRate = maxSendRate118 self.sentLast24Hours = sentLast24Hours119class AmazonSendDataPoint:120 def __init__(self, bounces, complaints, deliveryAttempts, rejects, timestamp):121 self.bounces = bounces122 self.complaints = complaints123 self.deliveryAttempts = deliveryAttempts124 self.rejects = rejects125 self.timestamp = timestamp126class AmazonSendStatistics(AmazonResult):127 def __init__(self, requestId):128 self.requestId = requestId129 self.members = []130class AmazonVerifiedEmails(AmazonSendStatistics):131 pass132class AmazonResponseParser:133 class XmlResponse:134 def __init__(self, str):135 self._rootElement = XML(str)136 self._namespace = self._rootElement.tag[1:].split("}")[0]137 def checkResponseName(self, name):138 if self._rootElement.tag == self._fixTag(self._namespace, name):139 return True140 else:141 raise AmazonAPIError('ErrorResponse is invalid.')142 def checkActionName(self, actionName):143 if self._rootElement.tag == self._fixTag(self._namespace, ('%sResponse' % actionName)):144 return True145 else:146 raise AmazonAPIError('Response of action "%s" is invalid.' % actionName)147 def getChild(self, *itemPath):148 node = self._findNode(self._rootElement, self._namespace, *itemPath)149 if node is not None:150 return node151 else:152 raise AmazonAPIError('Node with the specified path was not found.')153 def getChildText(self, *itemPath):154 node = self.getChild(*itemPath)155 return node.text156 def _fixTag(self, namespace, tag):157 return '{%s}%s' % (namespace, tag)158 def _findNode(self, rootElement, namespace, *args):159 match = '.'160 for s in args:161 match += '/{%s}%s' % (namespace, s)162 return rootElement.find(match)163 def __init__(self):164 self._simpleResultActions = ['DeleteVerifiedEmailAddress', 'VerifyEmailAddress']165 def _parseSimpleResult(self, actionName, xmlResponse):166 if xmlResponse.checkActionName(actionName):167 requestId = xmlResponse.getChildText('ResponseMetadata', 'RequestId')168 return AmazonResult(requestId)169 def _parseSendQuota(self, actionName, xmlResponse):170 if xmlResponse.checkActionName(actionName):171 requestId = xmlResponse.getChildText('ResponseMetadata', 'RequestId')172 value = xmlResponse.getChildText('GetSendQuotaResult', 'Max24HourSend')173 max24HourSend = float(value)174 value = xmlResponse.getChildText('GetSendQuotaResult', 'MaxSendRate')175 maxSendRate = float(value)176 value = xmlResponse.getChildText('GetSendQuotaResult', 'SentLast24Hours')177 sentLast24Hours = float(value)178 return AmazonSendQuota(requestId, max24HourSend, maxSendRate, sentLast24Hours)179 #def _parseSendStatistics(self, actionName, xmlResponse):180 # if xmlResponse.checkActionName(actionName):181 # requestId = xmlResponse.getChildText('ResponseMetadata', 'RequestId')182 def _parseListVerifiedEmails(self, actionName, xmlResponse):183 if xmlResponse.checkActionName(actionName):184 requestId = xmlResponse.getChildText('ResponseMetadata', 'RequestId')185 node = xmlResponse.getChild('ListVerifiedEmailAddressesResult', 'VerifiedEmailAddresses')186 result = AmazonVerifiedEmails(requestId)187 for addr in node:188 result.members.append(addr.text)189 return result190 def _parseSendEmail(self, actionName, xmlResponse):191 if xmlResponse.checkActionName(actionName):192 requestId = xmlResponse.getChildText('ResponseMetadata', 'RequestId')193 messageId = xmlResponse.getChildText('SendEmailResult', 'MessageId')194 return AmazonSendEmailResult(requestId, messageId)195 def _raiseError(self, xmlResponse):196 if xmlResponse.checkResponseName('ErrorResponse'):197 errorType = xmlResponse.getChildText('Error', 'Type')198 code = xmlResponse.getChildText('Error', 'Code')199 message = xmlResponse.getChildText('Error', 'Message')200 raise AmazonError(errorType, code, message)201 def parse(self, actionName, statusCode, reason, responseResult):202 xmlResponse = self.XmlResponse(responseResult)203 log.info('Response status code: %s, reason: %s', statusCode, reason)204 log.debug(responseResult)205 result = None206 if statusCode != 200:207 self._raiseError(xmlResponse)208 else:209 if actionName in self._simpleResultActions:210 result = self._parseSimpleResult(actionName, xmlResponse)211 elif actionName in ['SendEmail']:212 result = self._parseSendEmail(actionName, xmlResponse)213 elif actionName == 'GetSendQuota':214 result = self._parseSendQuota(actionName, xmlResponse)215 #elif actionName == 'GetSendStatistics':216 # result = self._parseSendStatistics(actionName, xmlResponse)217 elif actionName == 'ListVerifiedEmailAddresses':218 result = self._parseListVerifiedEmails(actionName, xmlResponse)219 else:220 #raise AmazonAPIError('Action %s is not supported. Please contact: vladimir@tagmask.com' % (actionName,))221 raise AmazonAPIError('Action %s is not supported.' % (actionName,))...

Full Screen

Full Screen

actionManager.py

Source:actionManager.py Github

copy

Full Screen

1############################################################2#3# BuildingRules Project 4# Politecnico di Milano5# Author: Alessandro A. Nacci6#7# This code is confidential8# Milan, March 20149#10############################################################11import sys12import json13import random14import string15import datetime16import re17from app.backend.commons.errors import *18from app.backend.commons.inputDataChecker import checkData19from app.backend.model.action import Action20from app.backend.model.actions import Actions21class ActionManager:22 def __init__(self):23 pass24 def getInfo(self, actionName):25 checkData(locals())26 27 action = Action(actionName = actionName)28 action.retrive()29 return action.getDict()30 def getActionAndTemplateAndParameterValues(self, ruleConsequent):31 checkData(locals())32 actions = Actions()33 actionList = actions.getAllActions()34 for action in actionList:35 36 # A action.ruleConsequent is represented as set of templates models:37 # Example "template1 | template2 | template2"38 models = action.ruleConsequent.split('|')39 for model in models:40 parameterNumber = model.count("@val")41 originalModel = model.strip()42 model = model.replace("@val","(.+)").strip()43 matchObj = re.match( model, ruleConsequent, re.M|re.I)44 if matchObj:45 parameterValues = {}46 for i in range(0,parameterNumber):47 parameterValues[str(i)] = matchObj.group(i + 1)48 return (action, originalModel, parameterValues)49 raise NotWellFormedRuleError("Impossible to find any action corresponding to the following rule consequent > " + ruleConsequent)50 def getActionAndTemplate(self, ruleConsequent):51 checkData(locals())52 action, template, parameterValues = self.getActionAndTemplateAndParameterValues(ruleConsequent)53 return (action, template)54 def getAction(self, ruleConsequent):55 checkData(locals())56 action, template = self.getActionAndTemplate(ruleConsequent)57 return action58 def __translateParameters(self, actionCategory, parameterValue):59 value = parameterValue60 if actionCategory == "HVAC_TEMP":61 return value.replace("C", "").replace("F", "")62 if actionCategory == "HVAC_HUM":63 return value.replace("%", "")64 if actionCategory == "BLIND":65 return value.replace("%", "")66 return value67 def translateAction(self, ruleConsequent, getDict = False):68 checkData(locals())69 actions = Actions()70 action, originalTemplate, parameterValues = self.getActionAndTemplateAndParameterValues(ruleConsequent)71 translationTemplate = actions.translateTemplate('Z3', originalTemplate)72 translatedParams = {}73 for key,value in parameterValues.iteritems():74 translatedParams[key] = self.__translateParameters(action.category, value)75 translation = translationTemplate76 for i in range(0,len(parameterValues.keys())):77 value = translatedParams[str(i)]78 translation = translation.replace("@val", value, 1)79 if not getDict:80 return translation, action, translatedParams81 else:82 result = {}83 result["translation"] = translation84 result["action"] = action.getDict()85 result["translatedParams"] = translatedParams86 return result87 def getActionCategories(self):88 checkData(locals())89 90 actions = Actions()91 actionList = actions.getAllActions()92 categories = []93 for action in actionList:94 if action.category not in categories:95 categories.append(action.category)96 return categories97 def getActionDriver(self, action, parameters = None):98 checkData(locals())99 from app.backend.drivers.roomHvacActionDriver import RoomHvacActionDriver100 from app.backend.drivers.roomLightActionDriver import RoomLightActionDriver101 from app.backend.drivers.roomApplianceActionDriver import RoomApplianceActionDriver102 from app.backend.drivers.roomSpecialActionDriver import RoomSpecialActionDriver 103 from app.backend.drivers.roomWindowActionDriver import RoomWindowActionDriver 104 from app.backend.drivers.roomFanHoodsActionDriver import RoomFanHoodsActionDriver 105 if not parameters:106 parameters = {}107 if action.actionName == "LIGHT_ON":108 parameters.update({'operation' : 'LIGHT_ON'})109 return RoomLightActionDriver(parameters = parameters)110 if action.actionName == "LIGHT_OFF":111 parameters.update({'operation' : 'LIGHT_OFF'})112 return RoomLightActionDriver(parameters = parameters)113 if action.actionName == "DESKLIGHT_ON":114 parameters.update({'operation' : 'DESKLIGHT_ON'})115 return RoomLightActionDriver(parameters = parameters)116 if action.actionName == "DESKLIGHT_OFF":117 parameters.update({'operation' : 'DESKLIGHT_OFF'})118 return RoomLightActionDriver(parameters = parameters)119 if action.actionName == "HVAC_ON":120 parameters.update({'operation' : 'HVAC_OFF'})121 return RoomHvacActionDriver(parameters = parameters)122 if action.actionName == "HVAC_OFF":123 parameters.update({'operation' : 'HVAC_OFF'})124 return RoomHvacActionDriver(parameters = parameters)125 if action.actionName == "SET_TEMPERATURE":126 parameters.update({'operation' : 'SET_TEMPERATURE'})127 return RoomHvacActionDriver(parameters = parameters)128 if action.actionName == "SET_HUMIDITY":129 parameters.update({'operation' : 'SET_HUMIDITY'})130 return RoomHvacActionDriver(parameters = parameters)131 if action.actionName == "HEATING_ON":132 parameters.update({'operation' : 'HEATING_ON'})133 return RoomHvacActionDriver(parameters = parameters)134 if action.actionName == "HEATING_OFF":135 parameters.update({'operation' : 'HEATING_OFF'})136 return RoomHvacActionDriver(parameters = parameters)137 if action.actionName == "AIR_CONDITIONING_ON":138 parameters.update({'operation' : 'AIR_CONDITIONING_ON'})139 return RoomHvacActionDriver(parameters = parameters)140 if action.actionName == "AIR_CONDITIONING_OFF":141 parameters.update({'operation' : 'AIR_CONDITIONING_OFF'})142 return RoomHvacActionDriver(parameters = parameters)143 if action.actionName == "APP_MICROWAVE_ON":144 parameters.update({'operation' : 'APP_MICROWAVE_ON'})145 return RoomApplianceActionDriver(parameters = parameters)146 if action.actionName == "APP_MICROWAVE_OFF":147 parameters.update({'operation' : 'APP_MICROWAVE_OFF'})148 return RoomApplianceActionDriver(parameters = parameters)149 if action.actionName == "COFFEE_ON":150 parameters.update({'operation' : 'COFFEE_ON'})151 return RoomApplianceActionDriver(parameters = parameters)152 if action.actionName == "COFFEE_OFF":153 parameters.update({'operation' : 'COFFEE_OFF'})154 return RoomApplianceActionDriver(parameters = parameters)155 if action.actionName == "PRINTER_ON":156 parameters.update({'operation' : 'PRINTER_ON'})157 return RoomApplianceActionDriver(parameters = parameters)158 if action.actionName == "PRINTER_OFF":159 parameters.update({'operation' : 'PRINTER_OFF'})160 return RoomApplianceActionDriver(parameters = parameters)161 if action.actionName == "COMPUTER_ON":162 parameters.update({'operation' : 'COMPUTER_ON'})163 return RoomApplianceActionDriver(parameters = parameters)164 if action.actionName == "COMPUTER_OFF":165 parameters.update({'operation' : 'COMPUTER_OFF'})166 return RoomApplianceActionDriver(parameters = parameters)167 if action.actionName == "DISPLAYMONITOR_ON":168 parameters.update({'operation' : 'DISPLAYMONITOR_ON'})169 return RoomApplianceActionDriver(parameters = parameters)170 if action.actionName == "DISPLAYMONITOR_OFF":171 parameters.update({'operation' : 'DISPLAYMONITOR_OFF'})172 return RoomApplianceActionDriver(parameters = parameters)173 if action.actionName == "PROJECTOR_ON":174 parameters.update({'operation' : 'PROJECTOR_ON'})175 return RoomApplianceActionDriver(parameters = parameters)176 if action.actionName == "PROJECTOR_OFF":177 parameters.update({'operation' : 'PROJECTOR_OFF'})178 return RoomApplianceActionDriver(parameters = parameters)179 if action.actionName == "AUDIO_ON":180 parameters.update({'operation' : 'AUDIO_ON'})181 return RoomApplianceActionDriver(parameters = parameters)182 if action.actionName == "AUDIO_OFF":183 parameters.update({'operation' : 'AUDIO_OFF'})184 return RoomApplianceActionDriver(parameters = parameters)185 if action.actionName == "SEND_COMPLAIN":186 parameters.update({'operation' : 'DISPLAYMONITOR_OFF'})187 return RoomSpecialActionDriver(parameters = parameters)188 if action.actionName == "WINDOWS_OPEN":189 parameters.update({'operation' : 'WINDOWS_OPEN'})190 return RoomWindowActionDriver(parameters = parameters)191 if action.actionName == "WINDOWS_CLOSE":192 parameters.update({'operation' : 'WINDOWS_CLOSE'})193 return RoomWindowActionDriver(parameters = parameters)194 if action.actionName == "CURTAINS_OPEN":195 parameters.update({'operation' : 'CURTAINS_OPEN'})196 return RoomWindowActionDriver(parameters = parameters)197 if action.actionName == "CURTAINS_CLOSE":198 parameters.update({'operation' : 'CURTAINS_CLOSE'})199 return RoomWindowActionDriver(parameters = parameters)200 if action.actionName == "SET_BLIND":201 parameters.update({'operation' : 'SET_BLIND'})202 return RoomWindowActionDriver(parameters = parameters)203 if action.actionName == "EXHAUST_FAN_ON":204 parameters.update({'operation' : 'EXHAUST_FAN_ON'})205 return RoomFanHoodsActionDriver(parameters = parameters)206 if action.actionName == "EXHAUST_FAN_OFF":207 parameters.update({'operation' : 'EXHAUST_FAN_OFF'})208 return RoomFanHoodsActionDriver(parameters = parameters)209 if action.actionName == "FUME_HOODS_ON":210 parameters.update({'operation' : 'FUME_HOODS_ON'})211 return RoomFanHoodsActionDriver(parameters = parameters)212 if action.actionName == "FUME_HOODS_OFF":213 parameters.update({'operation' : 'FUME_HOODS_OFF'})214 return RoomFanHoodsActionDriver(parameters = parameters)215 216 raise DriverNotFoundError("Impossibile to find any driver for the action " + str(action))217 def __str__(self):...

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 fMBT 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