Best Python code snippet using lisa_python
entity.py
Source:entity.py
1from zmq import Context, DONTWAIT, Poller, POLLIN, DEALER2from threading import Thread3from pickle import dumps, loads4from logging import getLogger5from soda.helpers import support_arguments6from soda.distributed_environment.behavior import ActionNode, IfNode7from subprocess import run, PIPE8from shlex import split9from copy import deepcopy10_logger = getLogger(__name__)11class Entity(Thread):12 def __init__(_self, _id, _ip, _in_port, _state, _term_states, _states_behaviors, _neighbours):13 Thread.__init__(_self)14 _self._id = _id15 _self._ip = _ip16 _self._in_port = _in_port17 _self._state = _state18 _self._term_states = _term_states19 _self._states_behaviors = _states_behaviors20 _self._neighbours = _neighbours21 _self._impulse = False22 _self._read_lock = False23 _self._count_sent_messages = 024 _context = Context()25 _self._in_socket = _context.socket(DEALER)26 _self._in_socket.bind("tcp://*:%s" % _self._in_port)27 _poller = Poller()28 _poller.register(_self._in_socket, POLLIN)29 _self.i_ID = int(_id)30 _self.i_NEIGHBOURS = [_n for _n in _neighbours]31 _self.__dict__['deepcopy'] = deepcopy32 _self.__dict__['LEN'] = len33 def read():34 # V nekoneÄnom cykle sledujeme, Äi na soket priÅ¡la správa.35 while True:36 _socks = dict(_poller.poll())37 # Ak priÅ¡la správa.38 if _socks.get(_self._in_socket) == POLLIN:39 # Správu preÄÃtame a následne extrahujeme obsah správy a odosieľatela.40 _pickled_received_message = _self._in_socket.recv(flags=DONTWAIT)41 _received_message, _sender_entity_id = loads(_pickled_received_message)42 _logger.info("Entity: {0} | Action: RECEIVED | Message : {1} | From entity : {2} ".format(_self._id,43 _received_message,44 _sender_entity_id))45 # Porovnámme prijatú správu so vÅ¡etkými vzormi READ konÅ¡trukcià pre46 # aktuálny stav.47 for _pattern in list(filter(lambda _p: _p != 'IMPULSE', _self._states_behaviors[_self._state])):48 _result = []49 # Porovnáme správu so vzorom. Ak je na rovnakej pozÃcii vo vzore a50 # prijatej správe tá istá hodnota a vo vzore nieje na poziÃcii premenná51 # uložÃme si do premennej _result hodnotu True. Ak sa hodnoty nezhodujú52 # a vo vzore nie je na pozÃcii premenná úložÃme hodnotu False. Pre pozÃcie53 # kde je vo vzore premenná si uložÃme hodnotu None.54 if len(_pattern[1]) == len(_received_message):55 for _i, _j in zip(_pattern[1], _received_message):56 if _i == _j and type(_i) is not tuple:57 _result.append(True)58 elif _i != _j and type(_i) is not tuple:59 _result.append(False)60 else:61 _result.append(None)62 # Ak v v poli _result nie je hodnota False znamená to, že prijatá správa63 # sa zhoduje so vzorom.64 if False not in _result:65 # Pre pozÃcie kde je vo vzore premenná uložÃme hodnotu z prÃsluÅ¡nej66 # pozÃcie v správe do tejto premennej.67 for _i, _j in zip(_pattern[1], _received_message):68 if type(_i) is tuple:69 _identifier, _ = _i70 if type(_j) is str:71 _j = "'" + _j + "'"72 _expression = "%s = %s" % (_identifier, _j)73 # Využijeme akciu entity pre priradenie.74 _self._actions["ASSIGN"]((_expression, ))75 # UložÃme odosieľatela do použitelnej premennej.76 _self.i_SENDER = _sender_entity_id77 _logger.info("Entity: {0} | Action: READ | Message : {1} | From entity : {2} ".format(_self._id, _received_message, _sender_entity_id))78 # Nakoniec vrátime vzor, ktorý sa zhodoval so správou, ktorú sme79 # prijali aby sme mohli následne v metóde run() identifikovaÅ¥80 # správanie prÃsluÅ¡né tomuto vzoru.81 return _pattern82 @support_arguments83 def send(_message, _recipients):84 # Vykonáme evaluáciu správy a prijÃmateľov aby sme naprÃklad v prÃpade85 # argumentov, ktoré sú premennými dostali konkrétne hodnity.86 _message = _self._actions["EVALUATE"](str(_message))87 _recipients = _self._actions["EVALUATE"](str(_recipients))88 if type(_message) is not tuple:89 _message = (_message, )90 # Ak je prijÃmateľ iba jeden pretypujeme ho na pole.91 if type(_recipients) is int:92 _recipients = [_recipients] * 193 # Pre každého prijÃmateľa vytvorÃme nový soket typu DEALER [18]. Následne94 # odoÅ¡leme správu spolu s identifikátorom odosieľatela a zvýšÃme poÄet95 # odoslaných správ pre entitu o 1.96 for _n in _recipients:97 try:98 _out_socket = _context.socket(DEALER)99 _out_socket.connect("tcp://localhost:%s" % _self._neighbours[_n]["in_port"])100 _message_content = (_message, _self._id)101 _pickled_message = dumps(_message_content)102 _out_socket.send(_pickled_message, flags=DONTWAIT)103 # Zalogovanie úspeÅ¡ného poslania správy. Zaznamenaný je identifikátor104 # odosielateľa, prijÃmateľa a samotná správa.105 _logger.info("Entity: {0} | Action: SEND | Message : {1} | To entity : {2} ".format(_self._id, _message, _n))106 _self._count_sent_messages += 1107 except KeyError:108 # Zalogovanie neúspeÅ¡ného odoslania správy.109 _logger.info("Entity: {0} | Action: SEND | Trying to send message to non existing neighbour! -> {1} ".format(_self._id, _n))110 @support_arguments111 def become(_new_state):112 _logger.info("Entity: {0} | Action: BECOME | Old state : {1} | New state : {2} ".format(_self._id, _self._state, _new_state))113 # Entita zmenà svoj stav na nový.114 _self._state = _new_state115 # Ak je tento nový stav terminujúci tak ukonÄÃme správanie.116 if _self._state in _self._term_states:117 exit()118 @support_arguments119 def assign(_expression):120 # Pre uskutoÄnenie priradenia do nejakej premennej využÃvame funkciu exec(),121 # ktorá je jednou zo vstavaných funkcià jazyka Python. Exec() dokáže vykonaÅ¥122 # akýkolvek valÃdny Python prÃkaz. PrÃkaz, ktorý ma exec vykonaÅ¥ je definovaný123 # reÅ¥azcom _expression. Aby mala funkcia exec() prÃstup ku vÅ¡etkým lokálnym124 # premenným entity, ktoré použÃvateľ opÃsal v algoritme je nutné predaÅ¥ funkcii125 # exec() prostrednÃctvom tretieho argumenty atribút objektu __dict__, v ktorom126 # sú uchované vÅ¡etky aktuálne referencie premenných a ich hodnôt.127 try:128 exec(_expression, {}, _self.__dict__)129 _logger.info("Entity: {0} | Action: ASSIGN | Expression : {1} ".format(_self._id, _expression))130 except NameError as _Name:131 _logger.info("Entity: {0} | Action: ASSIGN | Undefined identifier! -> {1} -> {2} ".format(_self._id, _Name, _expression))132 exit()133 except AttributeError as _Attribute:134 _logger.info("Entity: {0} | Action: ASSIGN | Wrong type of identifier! -> {1} -> {2} ".format(_self._id, _Attribute, _expression))135 exit()136 except TypeError as _Type:137 _logger.info("Entity: {0} | Action: ASSIGN | Wrong type of identifier! -> {1} -> {2} ".format(_self._id, _Type, _expression))138 exit()139 @support_arguments140 def log(_expression):141 print("SODA: " + _self._actions["EVALUATE"](_expression))142 def evaluate(_expression):143 result = None144 try:145 result = eval(_expression, {}, _self.__dict__)146 except NameError as _Name:147 _logger.info("Entity: {0} | Action: EVALUATE | Undefined identifier! -> {1} -> {2} ".format(_self._id, _Name, _expression))148 exit()149 except AttributeError as _Attribute:150 _logger.info("Entity: {0} | Action: EVALUATE | Wrong type of identifier! -> {1} -> {2} ".format(_self._id, _Attribute, _expression))151 exit()152 except ValueError as _Value:153 _logger.info("Entity: {0} | Action: EVALUATE | Wrong value! -> {1} -> {2} ".format(_self._id, _Value,_expression))154 exit()155 return result156 @support_arguments157 def execute(_command, _output_type, _output, _input):158 _command = split(_command)159 _input = _self._actions["EVALUATE"](str(_input))160 _process_output= None161 _completed_process = run(_command, input=str(_input), stdout=PIPE, universal_newlines=True, shell=True)162 # cast to correct output type163 if _output_type == 'string':164 _process_output = "'" + _completed_process.stdout + "'"165 elif _output_type == 'int':166 try:167 _process_output = int(_completed_process.stdout)168 except ValueError as _Value:169 _logger.info(170 "Entity: {0} | Action: EXEC | Wrong value for output cast to int! -> {1} -> {2} ".format(_self._id, _Value,171 _completed_process.stdout))172 exit()173 elif _output_type == 'float':174 try:175 _process_output = float(_completed_process.stdout)176 except ValueError as _Value:177 _logger.info(178 "Entity: {0} | Action: EXEC | Wrong value for output cast to float! -> {1} -> {2} ".format(_self._id, _Value,179 _completed_process.stdout))180 exit()181 _expression = "%s = %s" % (_output, _process_output)182 _self._actions["ASSIGN"]((_expression,))183 @support_arguments184 def add(_array, _value):185 _expression = "%s.append(%s)" % (_array, _value)186 _self._actions["EVALUATE"](str(_expression))187 @support_arguments188 def remove(_array, _value):189 _expression = "%s.remove(%s)" % (_array, _value)190 _self._actions["EVALUATE"](str(_expression))191 @support_arguments192 def pop(_array, _output):193 _expression = "%s = %s.pop()" % (_output, _array)194 _self._actions["ASSIGN"]((_expression,))195 _self._actions = {196 "READ": read,197 "SEND": send,198 "BECOME": become,199 "ASSIGN": assign,200 "LOG": log,201 "EVALUATE": evaluate,202 "EXEC": execute,203 "ADD": add,204 "REMOVE": remove,205 "POP": pop206 }207 def run(_self):208 # Entita vykonáva správanie pokiaľ sa nedostane do terminujúceho stavu.209 while _self._state not in _self._term_states:210 _current_state = _self._state211 # Entita sa spustà impulzom alebo zaÄne ÄÃtaÅ¥ prijaté správy.212 if _self._impulse:213 _self._impulse = False214 _behavior = 'IMPULSE'215 _logger.info("Entity: {0} | Action: Started by IMPULSE ".format(_self._id))216 else:217 _self._read_lock = True218 _behavior = _self._actions["READ"]()219 _self._read_lock = False220 # NastavÃme _n na prvý uzol správania prÃsluÅ¡ného pre aktuálny stav.221 _n = _self._states_behaviors[_current_state][_behavior].head222 _next_node = None223 # Iterujeme cez správanie.224 while _n is not None:225 # Vykonáme logiku uzlu. Logika uzlov je opÃsaná226 # v podkapitole 4.2.3 Správanie.227 if type(_n) is ActionNode:228 _next_node = _n.execute(_self)229 elif type(_n) is IfNode:230 _next_node = _n.execute(_self)231 if _next_node == "BECOME":232 break...
reporting.py
Source:reporting.py
...8 JsonLinkClient.__init__(self, max_reconnect_delay)9 self._received_message = recv_msg_callback10 self._connection_made = conn_made_callback11 def receivedMessage(self, protocol, msg):12 return self._received_message(msg)13 def connectionMade(self, protocol):14 JsonLinkClient.connectionMade(self, protocol)15 # Delegate to the callback16 self._connection_made(protocol)17class JsonReporter(object):18 def __init__(self, host, port,19 max_queue_len=2048,20 max_active_queue_len=100,21 retry_after_s=5,22 start_suspended=False):23 self._link = ReporterJsonLinkClient(self._connection_made_int,24 self._received_message)25 self._queue = DeliveryQueue(self._link.sendMessage,26 drop_callback=self.on_drop,27 max_queue_len=max_queue_len,28 max_active_queue_len=max_active_queue_len,29 retry_after_s=retry_after_s,30 start_suspended=start_suspended)31 self._connector = reactor.connectTCP(host, port, self._link)32 def redirect(self, host, port):33 self._connector.stopConnecting()34 self._connector.disconnect()35 self._connector = reactor.connectTCP(host, port, self._link)36 def _callback(self, result):37 return True38 def _errorback(self, failure):39 return False40 def _received_message(self, msg):41 return True42 def _connection_made_int(self, protocol):43 try:44 protocol.transport.setTcpNoDelay(True)45 protocol.transport.setTcpKeepAlive(True)46 # Seconds before sending keepalive probes47 protocol.transport.socket.setsockopt(socket.SOL_TCP, socket.TCP_KEEPIDLE, 120)48 # Interval in seconds between keepalive probes49 protocol.transport.socket.setsockopt(socket.SOL_TCP, socket.TCP_KEEPINTVL, 1)50 # Failed keepalive probles before declaring other end dead51 protocol.transport.socket.setsockopt(socket.SOL_TCP, socket.TCP_KEEPCNT, 5)52 except:53 pass54 self._connection_made()...
UsbHidBaseProtocol.py
Source:UsbHidBaseProtocol.py
1#!/usr/bin/env python32from abc import ABC, abstractmethod3import asyncio4from pi_usb_gadget_controller.gadget_device import GadgetDevice5class UsbHidBaseProtocol(ABC, asyncio.Protocol):6 def __init__(self, device, logger, delimiter='\n', heartbeat=''):7 self._logger = logger8 self._delimiter = ord(delimiter)9 self._heartbeat = heartbeat10 self._gadget_device = device11 self._transport = None12 self._received_message = ""13 def connection_made(self, transport):14 try:15 peername = transport.get_extra_info('peername')16 self._logger.info('Connection from {}'.format(peername))17 self._transport = transport18 self._gadget_device.open()19 except Exception as e:20 self._logger.error(e)21 def data_received(self, data):22 self._logger.debug(f"Packet received: {data}")23 message = data.decode()24 self._logger.debug(f"Decoded Packet: {message}")25 for letter in message:26 if ord(letter) != self._delimiter:27 self._received_message += letter28 else:29 self._process_packet_for_heartbeat(self._received_message)30 self._received_message = ''31 def _process_packet_for_heartbeat(self, packet):32 if packet == self._heartbeat:33 self._logger.debug("HEARTBEAT")34 # This is used for heartbeats so do nothing but also no need to log35 pass36 else:37 self._process_packet(packet)38 @abstractmethod39 def _process_packet(self, packet):40 pass41 def connection_lost(self, exc):42 self._logger.warning('Connection Lost')43 self._transport.close()...
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.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!