def nextSolution(self, query): if query.client == self: while not query.finished: rospy.wait_for_service(self.prologNextSolutionService) request = rospy.ServiceProxy(self.prologNextSolutionService, PrologNextSolution) try: response = request(id=str(query.id)) except rospy.ServiceException, exception: raise Exception( "PrologNextSolution service request failed: %s" % exception) if response.status == PrologNextSolutionResponse.OK: yield json.loads(response.solution) elif response.status == PrologNextSolutionResponse.NO_SOLUTION: query.client = None return elif response.status == PrologNextSolutionResponse.WRONG_ID: query.client = None raise Exception( "Prolog query id is invalid: " + "Another client may have terminated your query") elif response.status == PrologNextSolutionResponse.QUERY_FAILED: query.client = None raise Exception("Prolog query failed: %s" % response.solution) else: query.client = None raise Exception("Prolog query status unknown: %d", response.status)
def _request(self, route, method, parameters=None): """Make an HTTP request.""" params = parameters if parameters else {} # Form a restful URL uri = self._routes[route].format(params) url = urljoin(self.root, uri) headers = {} if self.token: # set authorization header headers.update({ 'Content-Type': 'application/json', 'Authorization': self.token }) try: r = self.reqsession.request( method, url, data=params if method in ["POST", "PUT"] else None, params=params if method in ["GET", "DELETE"] else None, headers=headers, verify=not self.disable_ssl) except Exception as e: raise e if self.debug: log.debug("Response: {code} {content}".format(code=r.status_code, content=r.content)) # Validate the content type. if "json" in r.headers["content-type"]: try: data = json.loads(r.content.decode("utf8")) except ValueError: raise ex.XTSDataException( "Couldn't parse the JSON response received from the server: {content}" .format(content=r.content)) # api error if data.get("type"): if r.status_code == 400 and data["type"] == "error" and data[ "description"] == "Invalid Token": raise ex.XTSTokenException(data["description"]) if r.status_code == 400 and data["type"] == "error" and data[ "description"] == "Bad Request": message = "Description: " + data[ "description"] + " errors: " + data['result']["errors"] raise ex.XTSInputException(str(message)) return data else: raise ex.XTSDataException( "Unknown Content-Type ({content_type}) with response: ({content})" .format(content_type=r.headers["content-type"], content=r.content))
def operar(columna, simbolo, valor, *args): if len(args): raise err.ArgumentoInvalido("operar") if not hasattr(columna, "__iter__"): raise err.ErrorDeTipo("operar") if isinstance(columna, str): if columna not in d.data.keys(): raise err.ReferenciaInvalida("operar") else: columna = d.data[columna] return list( map(lambda x: interpretar_operacion(simbolo)(x, valor), columna))
def prom(x, *args): if len(args): raise error.ArgumentoInvalido("PROM") elif not hasattr(x, "__iter__"): raise error.ErrorDeTipo("PROM") elif isinstance(x, str): if x not in d.data.keys(): raise error.ReferenciaInvalida("PROM") else: x = d.data[x] if len(x) == 0: raise error.ErrorMatematico("PROM") return sum(x)/len(x)
def unpack(self,A429word): """ return the value given a 32 bit ARINC 429 message value """ if (A429word<0): raise Exception.A429MsgRangeError(self.name,\ 0,\ A429word) elif (A429word>0xFFFFFFFF): raise Exception.A429MsgRangeError(self.name,\ 0xFFFFFFFF,\ A429word) else: return ((A429word& self._mask)>>(self.lsb-1))
def var(x, *args): if len(args): raise error.ArgumentoInvalido("VAR") if not hasattr(x, "__iter__"): raise error.ErrorDeTipo("VAR") if isinstance(x, str): if x not in d.data.keys(): raise error.ReferenciaInvalida("VAR") else: x = d.data[x] if len(x) == 1: raise error.ErrorMatematico("VAR") mean = prom(x) return reduce(lambda z, y: z + y, map(lambda y: (y-mean)**2, x))/(len(x)-1)
def evaluar(funcion, inicio, final, intervalo, *args): if len(args): raise err.ArgumentoInvalido("evaluar") if not isinstance(funcion, type((i for i in range(10)))): raise err.ErrorDeTipo("evaluar") if isinstance(funcion, str): if funcion not in d.data.keys(): raise err.ReferenciaInvalida("evaluar") else: funcion = d.data[funcion] # Retorna los resultados de aplicar la funcion a cada parte largo = int((final - inicio) / intervalo) lista = [inicio + i * intervalo for i in range(largo)] + [final] return [funcion.send(i) for i in lista]
def addField(self,field): ''' Add a field and reorder the message fields by LSB An exception is raised if the field cannot be added (not enough room or same name) ''' if self.canThisFieldBeAdded(field): self._fields.append(field) sorted(self._fields, key=lambda field: field.lsb) # sort list by LBS else: if self.__field_name_already_exist(field): raise Exception.A429MsgStructureError('Field with name {fieldName} already exists\ in message {messageName}'.format(fieldName=field.name, messageName=self.name)) else: raise Exception.A429MsgStructureError('This fields overlap with existing fields in the message')
def interpretar_operacion(simbolo): def division(x, y): if int(y) == 0: raise err.ErrorMatematico("Intepretar operación") else: return x / y def aprox(x, y): if not (isinstance(y, int) or y < 0): raise err.ErrorDeTipo( "Interpretar operacion", "Para aproximar " "debes entregar un " "número mayor o " "igual a 0") return round(x, y) dic = { "+": lambda x, y: x + y, "-": lambda x, y: x - y, "*": lambda x, y: x * y, "/": division, ">=<": aprox } if simbolo not in dic.keys(): raise err.ErrorDeTipo("Interpretar operación") return dic[simbolo]
def __init__(self,lsb,size,name): ''' Constructor ''' self.lsb = lsb if lsb<1: raise Exception.A429MsgStructureError("LSB cannot be lower than 1") self.size = size if (lsb+size)>33: raise Exception.A429MsgStructureError("Field cannot exceed bit 32") self.name = name self._mask=((2**self.size)-1)<<(self.lsb-1)
def normal(u=0.0, s=1.0, *args, **kwargs): if len(args) or len(kwargs): raise err.ArgumentoInvalido("crear funcion") x = 0.0 while True: x = yield (1 / (2 * pi * s)**0.5) * (e**((-1 / 2) * (x - u / s)**2))
def aprox(x, y): if not (isinstance(y, int) or y < 0): raise err.ErrorDeTipo( "Interpretar operacion", "Para aproximar " "debes entregar un " "número mayor o " "igual a 0") return round(x, y)
def setData(self,bitValue): ''' set the bit value This function expect the bit value passed as a boolean ''' if type(bitValue) != type(bool()): raise Exception.A429Exception('Bit are expected as bool') else: self._value = bitValue
def pack(self): ''' Return the 32 bits word corresponding to an A429 message with the bit data (all other bits at zero) ''' if self._value is None: raise Exception.A429NoData(self.name) else: return MessageField.Field.pack(self,int(self._value))
def median(x, *args): if len(args): raise error.ArgumentoInvalido("MEDIAN") if not hasattr(x, "__iter__"): raise error.ErrorDeTipo("MEDIAN") if isinstance(x, str): if x not in d.data.keys(): raise error.ReferenciaInvalida("MEDIAN") else: x = d.data[x] n = len(x) if n == 0: raise error.ErrorDeTipo("MEDIAN") elif n % 2 == 1: return x[n//2] else: return (x[n//2 - 1] + x[n//2])/2
def query(self, query): if isinstance(query, str): query = Query(query=query) if query.finished: rospy.wait_for_service(self.prologQueryService) request = rospy.ServiceProxy(self.prologQueryService, PrologQuery) try: response = request(id=str(query.id), query=str(query)) query.client = self except rospy.ServiceException, exception: raise Exception("PrologQuery service request failed: %s" % exception) if not response.ok: raise Exception("Prolog query failed: %s" % response.message)
def ensureValidIP(self, recursing=False): """ """ host_ip = myPopen('wget http://www.joinge.net/getmyip.php -q -O -') printAction(' Host IP') print(host_ip) vm_ip = device.adbShell( '"wget http://www.joinge.net/getmyip.php -q -O -"') printAction(' Android IP (%s)' % device.active_device) print(vm_ip) # This sanity check doesn't ensure valid IP range but should be sufficient filtered_vm_ip = re.search( '[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}', vm_ip) if not filtered_vm_ip: printAction(' VM IP sanity check...', res=False) print('ERROR: VM IP does not seem to be sane.') if recursing: raise Exception('ERROR: Unable to recover!') else: updateVPN() setVPNFirewall() ensureValidIP(True) else: printAction(' VM IP sanity check...', res=True) if host_ip == vm_ip: printAction(' IPs differ?', res=False) print('ERROR: IPs are identical.') if recursing: raise Exception('ERROR: Unable to recover!') else: updateVPN() setVPNFirewall() ensureValidIP(True) else: printAction(' IPs differ?', res=True)
def setData(self, label): ''' set the label property This function expect label number passed on octal form The number is expected as a string so that we always treat the passed value as an integer. ''' if type(label) != type(str()): raise Exception.A429Exception('Label should be given as strings') try: self._label = int(label, 8) except ValueError: raise Exception.A429MsgRangeError(self.name,\ 0377,\ label) if (self._label < 0): raise Exception.A429MsgRangeError(self.name,\ 0,\ label)
def interpretar_comando(comando, funcion): dic = {"PROM": prom, "VAR": var, "DESV": desv, "MEDIAN": median, "LEN": len} if comando not in dic.keys(): raise error.ErrorDeTipo(funcion) return dic[comando]
def pack(self,value): """ Take an integer value and return a bit array representing the value packed at location corresponding to the message definition Warning: a A429MsgRangeError is raised if the field is not large enough to store the value. """ if(abs(value)>((2**self.size)-1)): raise Exception.A429MsgRangeError(self.name,\ ((2**self.size)-1),\ value) elif value<0: raise Exception.A429MsgRangeError(self.name,\ 0,\ value) else: return value<<(self.lsb-1)
def getFieldValueByName(self,fieldName): ''' Get the field value given its name ''' try: labelField = [field for field in self._fields if field.name == fieldName][0] return labelField.getData() except IndexError: raise Exception.A429MsgStructureError("Message {} has no label field".format(self.name))
def graficar(columna, opcion, *args): if len(args): raise err.ArgumentoInvalido("graficar") if not hasattr(columna, "__iter__"): raise err.ErrorDeTipo("graficar") if isinstance(columna, str): if columna not in d.data.keys(): raise err.ReferenciaInvalida("graficar") else: columna = d.data[columna] if "rango" in opcion: y = list( map(lambda x: float(x), opcion[opcion.find(":") + 1:].split(","))) inicio, final, intervalo = y[0], y[1], y[2] largo = int((final - inicio) / intervalo) y = [inicio + i * intervalo for i in range(largo)] + [final] plt.title(opcion) elif hasattr(opcion, "__iter__") and not isinstance(opcion, str): y = opcion elif opcion == "numerico": variable = list(i for i in range(len(columna))) plt.plot(variable, columna) plt.title("numerico") plt.ylabel("columna") plt.show() return elif opcion == "normalizado": n = sum(columna) y = list(map(lambda x: x / n, (i for i in range(len(columna))))) plt.plot(y, columna) plt.title("normalizado") plt.ylabel("columna") plt.show() return else: raise err.ErrorDeTipo("graficar", "Opcion invalida") if len(y) != len(columna): raise err.ImposibleProcesar("graficar", "largos distintos") else: plt.plot(y, columna) plt.ylabel("columna") plt.show()
def getMap(self): rospy.wait_for_service(self.getSemanticMapService) try: request = rospy.ServiceProxy(self.getSemanticMapService, GetSemanticMap) response = request() except rospy.ServiceException, exception: raise Exception("GetSemanticMap service request failed: %s" % exception)
def pack(self): ''' Return the 32 bits word corresponding to an A429 message with the label data (all other bits at zero) ''' if self._label is None: raise Exception.A429NoData(self.name) else: reverted = int('{:08b}'.format(self._label)[::-1], 2) #let's reverse the bit return MessageField.Field.pack(self, reverted)
def extraer_columna(nombre_archivo, columna, header=False, *args): # Todo es str nombre_archivo es de tipo csv if len(args): raise err.ArgumentoInvalido("extraer columna") if not os.path.exists(nombre_archivo + ".csv"): raise err.ImposibleProcesar("extraer columna", "No existe el archivo") with open(nombre_archivo + ".csv", "r") as f: headers = f.readline().strip().split(";") headers1 = [ headers[i][0:headers[i].find(":")] for i in range(len(headers)) ] if columna not in headers and columna not in headers1: raise err.ImposibleProcesar("Extraer columna", "El archivo no " "tiene esa columna") lugar = int(*[i for i in range(len(headers)) if columna in headers[i]]) archivo = list(map(lambda s: float(s.strip().split(";")[lugar]), f)) if header: archivo = [headers1[lugar]] + archivo return archivo
def changeParityConvention(self,parityConvention): ''' Change the parity convention for the label 'odd' is used by default at the message creation Parity need to be a string of value 'odd' or 'even' ''' try: parityField = [field for field in self._fields if field.name == 'parity'][0] parityField.setConvention(parityConvention) except: raise Exception.A429MsgStructureError("Message {} has no label field".format(self.name))
def getOwl(self): rospy.wait_for_service(self.generateSemanticMapOwlService) try: request = rospy.ServiceProxy(self.generateSemanticMapOwlService, GenerateSemanticMapOWL) response = request(map=self.map) except rospy.ServiceException, exception: raise Exception( "GenerateSemanticMapOWL service request failed: %s" % exception)
def unpack(self,word): ''' Given a 32 bit word, set all the fields values ''' parityField = [field for field in self._fields if field.name == 'parity'][0] if not parityField.isMessageValid(word): raise Exception.A429InvalidMessage(label=self.name) else: for field in self._fields: field.unpack(word)
def interpretar_simbolo(simbolo, funcion): dic = { "<": lambda x, b: x < b, ">": lambda x, b: x > b, "==": lambda x, b: x == b, ">=": lambda x, b: x >= b, "<=": lambda x, b: x <= b, "!=": lambda x, b: x != b } if simbolo not in dic.keys(): raise error.ErrorDeTipo(funcion) return dic[simbolo]
def setConvention(self, parityConvention): ''' set the parity convention If a value is set and the parity convention is changing, revert the parity bit ''' oldConvention = self._parityConvention if type(parityConvention) != type(str()): raise Exception.A429Exception( "Parity Convention {} is not handled".format(parityConvention)) elif parityConvention is not 'odd' and parityConvention is not 'even': raise Exception.A429Exception( "Parity Convention {} is not handled".format(parityConvention)) self._parityConvention = parityConvention if self._value is not None: if self._parityConvention != oldConvention: self._value = (0 if self._value == 1 else 1)