Code
stringlengths
103
85.9k
Summary
listlengths
0
94
Please provide a description of the function:def pdu_to_function_code_or_raise_error(resp_pdu): function_code = struct.unpack('>B', resp_pdu[0:1])[0] if function_code not in function_code_to_function_map.keys(): error_code = struct.unpack('>B', resp_pdu[1:2])[0] raise error_code_to_excepti...
[ " Parse response PDU and return of :class:`ModbusFunction` or\n raise error.\n\n :param resp_pdu: PDU of response.\n :return: Subclass of :class:`ModbusFunction` matching the response.\n :raises ModbusError: When response contains error code.\n " ]
Please provide a description of the function:def create_function_from_response_pdu(resp_pdu, req_pdu=None): function_code = pdu_to_function_code_or_raise_error(resp_pdu) function = function_code_to_function_map[function_code] if req_pdu is not None and \ 'req_pdu' in inspect.getargspec(functio...
[ " Parse response PDU and return instance of :class:`ModbusFunction` or\n raise error.\n\n :param resp_pdu: PDU of response.\n :param req_pdu: Request PDU, some functions require more info than in\n response PDU in order to create instance. Default is None.\n :return: Number or list with response...
Please provide a description of the function:def create_function_from_request_pdu(pdu): function_code = get_function_code_from_request_pdu(pdu) try: function_class = function_code_to_function_map[function_code] except KeyError: raise IllegalFunctionError(function_code) return funct...
[ " Return function instance, based on request PDU.\n\n :param pdu: Array of bytes.\n :return: Instance of a function.\n " ]
Please provide a description of the function:def request_pdu(self): if None in [self.starting_address, self.quantity]: # TODO Raise proper exception. raise Exception return struct.pack('>BHH', self.function_code, self.starting_address, self.qu...
[ " Build request PDU to read coils.\n\n :return: Byte array of 5 bytes with PDU.\n " ]
Please provide a description of the function:def create_response_pdu(self, data): log.debug('Create single bit response pdu {0}.'.format(data)) bytes_ = [data[i:i + 8] for i in range(0, len(data), 8)] # Reduce each all bits per byte to a number. Byte # [0, 0, 0, 0, 0, 1, 1, 1] ...
[ " Create response pdu.\n\n :param data: A list with 0's and/or 1's.\n :return: Byte array of at least 3 bytes.\n " ]
Please provide a description of the function:def create_from_response_pdu(resp_pdu, req_pdu): read_coils = ReadCoils() read_coils.quantity = struct.unpack('>H', req_pdu[-2:])[0] byte_count = struct.unpack('>B', resp_pdu[1:2])[0] fmt = '>' + ('B' * byte_count) bytes_ = s...
[ " Create instance from response PDU.\n\n Response PDU is required together with the quantity of coils read.\n\n :param resp_pdu: Byte array with request PDU.\n :param quantity: Number of coils read.\n :return: Instance of :class:`ReadCoils`.\n " ]
Please provide a description of the function:def execute(self, slave_id, route_map): try: values = [] for address in range(self.starting_address, self.starting_address + self.quantity): endpoint = route_map.match(slave_id, self.f...
[ " Execute the Modbus function registered for a route.\n\n :param slave_id: Slave id.\n :param eindpoint: Instance of modbus.route.Map.\n :return: Result of call to endpoint.\n " ]
Please provide a description of the function:def create_from_request_pdu(pdu): _, starting_address, quantity = struct.unpack('>BHH', pdu) instance = ReadHoldingRegisters() instance.starting_address = starting_address instance.quantity = quantity return instance
[ " Create instance from request PDU.\n :param pdu: A request PDU.\n :return: Instance of this class.\n " ]
Please provide a description of the function:def create_response_pdu(self, data): log.debug('Create multi bit response pdu {0}.'.format(data)) fmt = '>BB' + conf.TYPE_CHAR * len(data) return struct.pack(fmt, self.function_code, len(data) * 2, *data)
[ " Create response pdu.\n\n :param data: A list with values.\n :return: Byte array of at least 4 bytes.\n " ]
Please provide a description of the function:def create_from_response_pdu(resp_pdu, req_pdu): read_holding_registers = ReadHoldingRegisters() read_holding_registers.quantity = struct.unpack('>H', req_pdu[-2:])[0] read_holding_registers.byte_count = \ struct.unpack('>B', resp...
[ " Create instance from response PDU.\n\n Response PDU is required together with the number of registers read.\n\n :param resp_pdu: Byte array with request PDU.\n :param quantity: Number of coils read.\n :return: Instance of :class:`ReadCoils`.\n " ]
Please provide a description of the function:def create_from_response_pdu(resp_pdu, req_pdu): read_input_registers = ReadInputRegisters() read_input_registers.quantity = struct.unpack('>H', req_pdu[-2:])[0] fmt = '>' + (conf.TYPE_CHAR * read_input_registers.quantity) read_input...
[ " Create instance from response PDU.\n\n Response PDU is required together with the number of registers read.\n\n :param resp_pdu: Byte array with request PDU.\n :param quantity: Number of coils read.\n :return: Instance of :class:`ReadCoils`.\n " ]
Please provide a description of the function:def request_pdu(self): if None in [self.address, self.value]: # TODO Raise proper exception. raise Exception return struct.pack('>BHH', self.function_code, self.address, self._value)
[ " Build request PDU to write single coil.\n\n :return: Byte array of 5 bytes with PDU.\n " ]
Please provide a description of the function:def create_from_request_pdu(pdu): _, address, value = struct.unpack('>BHH', pdu) value = 1 if value == 0xFF00 else value instance = WriteSingleCoil() instance.address = address instance.value = value return instance
[ " Create instance from request PDU.\n\n :param pdu: A response PDU.\n " ]
Please provide a description of the function:def create_response_pdu(self): fmt = '>BHH' return struct.pack(fmt, self.function_code, self.address, self._value)
[ " Create response pdu.\n\n :param data: A list with values.\n :return: Byte array of at least 4 bytes.\n " ]
Please provide a description of the function:def create_from_response_pdu(resp_pdu): write_single_coil = WriteSingleCoil() address, value = struct.unpack('>HH', resp_pdu[1:5]) value = 1 if value == 0xFF00 else value write_single_coil.address = address write_single_coil...
[ " Create instance from response PDU.\n\n :param resp_pdu: Byte array with request PDU.\n :return: Instance of :class:`WriteSingleCoil`.\n " ]
Please provide a description of the function:def execute(self, slave_id, route_map): endpoint = route_map.match(slave_id, self.function_code, self.address) try: endpoint(slave_id=slave_id, address=self.address, value=self.value, function_code=self.function_code)...
[ " Execute the Modbus function registered for a route.\n\n :param slave_id: Slave id.\n :param eindpoint: Instance of modbus.route.Map.\n " ]
Please provide a description of the function:def value(self, value): try: struct.pack('>' + conf.TYPE_CHAR, value) except struct.error: raise IllegalDataValueError self._value = value
[ " Value to be written on register.\n\n :param value: An integer.\n :raises: IllegalDataValueError when value isn't in range.\n " ]
Please provide a description of the function:def request_pdu(self): if None in [self.address, self.value]: # TODO Raise proper exception. raise Exception return struct.pack('>BH' + conf.TYPE_CHAR, self.function_code, self.address, self.value)
[ " Build request PDU to write single register.\n\n :return: Byte array of 5 bytes with PDU.\n " ]
Please provide a description of the function:def create_from_request_pdu(pdu): _, address, value = \ struct.unpack('>BH' + conf.MULTI_BIT_VALUE_FORMAT_CHARACTER, pdu) instance = WriteSingleRegister() instance.address = address instance.value = value return ...
[ " Create instance from request PDU.\n\n :param pdu: A response PDU.\n " ]
Please provide a description of the function:def create_from_response_pdu(resp_pdu): write_single_register = WriteSingleRegister() address, value = struct.unpack('>H' + conf.TYPE_CHAR, resp_pdu[1:5]) write_single_register.address = address write_single_register.data = value ...
[ " Create instance from response PDU.\n\n :param resp_pdu: Byte array with request PDU.\n :return: Instance of :class:`WriteSingleRegister`.\n " ]
Please provide a description of the function:def create_from_request_pdu(pdu): _, starting_address, quantity, byte_count = \ struct.unpack('>BHHB', pdu[:6]) fmt = '>' + (conf.SINGLE_BIT_VALUE_FORMAT_CHARACTER * byte_count) values = struct.unpack(fmt, pdu[6:]) res =...
[ " Create instance from request PDU.\n\n This method requires some clarification regarding the unpacking of\n the status that are being passed to the callbacks.\n\n A coil status can be 0 or 1. The request PDU contains at least 1 byte,\n representing the status for 1 to 8 coils.\n\n ...
Please provide a description of the function:def create_response_pdu(self): return struct.pack('>BHH', self.function_code, self.starting_address, len(self.values))
[ " Create response pdu.\n\n :param data: A list with values.\n :return: Byte array 5 bytes.\n " ]
Please provide a description of the function:def execute(self, slave_id, route_map): for index, value in enumerate(self.values): address = self.starting_address + index endpoint = route_map.match(slave_id, self.function_code, address) try: endpoint(s...
[ " Execute the Modbus function registered for a route.\n\n :param slave_id: Slave id.\n :param eindpoint: Instance of modbus.route.Map.\n " ]
Please provide a description of the function:def create_from_request_pdu(pdu): _, starting_address, quantity, byte_count = \ struct.unpack('>BHHB', pdu[:6]) # Values are 16 bit, so each value takes up 2 bytes. fmt = '>' + (conf.MULTI_BIT_VALUE_FORMAT_CHARACTER * ...
[ " Create instance from request PDU.\n\n :param pdu: A request PDU.\n :return: Instance of this class.\n " ]
Please provide a description of the function:def get_server(server_class, serial_port): s = server_class() s.serial_port = serial_port s.route_map = Map() s.route = MethodType(route, s) return s
[ " Return instance of :param:`server_class` with :param:`request_handler`\n bound to it.\n This method also binds a :func:`route` method to the server instance.\n >>> server = get_server(TcpServer, ('localhost', 502), RequestHandler)\n >>> server.serve_forever()\n :param server_class: (sub)Cla...
Please provide a description of the function:def serve_forever(self, poll_interval=0.5): self.serial_port.timeout = poll_interval while not self._shutdown_request: try: self.serve_once() except (CRCError, struct.error) as e: log.error('Ca...
[ " Wait for incomming requests. " ]
Please provide a description of the function:def process(self, request_adu): meta_data = self.get_meta_data(request_adu) request_pdu = self.get_request_pdu(request_adu) response_pdu = self.execute_route(meta_data, request_pdu) response_adu = self.create_response_adu(meta_data, ...
[ " Process request ADU and return response.\n\n :param request_adu: A bytearray containing the ADU request.\n :return: A bytearray containing the response of the ADU request.\n " ]
Please provide a description of the function:def execute_route(self, meta_data, request_pdu): try: function = create_function_from_request_pdu(request_pdu) results =\ function.execute(meta_data['unit_id'], self.route_map) try: # ReadF...
[ " Execute configured route based on requests meta data and request\n PDU.\n\n :param meta_data: A dict with meta data. It must at least contain\n key 'unit_id'.\n :param request_pdu: A bytearray containing request PDU.\n :return: A bytearry containing reponse PDU.\n " ]
Please provide a description of the function:def respond(self, response_adu): log.debug('--> {0}'.format(hexlify(response_adu))) self.serial_port.write(response_adu)
[ " Send response ADU back to client.\n\n :param response_adu: A bytearray containing the response of an ADU.\n " ]
Please provide a description of the function:def serial_port(self, serial_port): char_size = get_char_size(serial_port.baudrate) # See docstring of get_char_size() for meaning of constants below. serial_port.inter_byte_timeout = 1.5 * char_size serial_port.timeout = 3.5 * char_...
[ " Set timeouts on serial port based on baudrate to detect frames. " ]
Please provide a description of the function:def serve_once(self): # 256 is the maximum size of a Modbus RTU frame. request_adu = self.serial_port.read(256) log.debug('<-- {0}'.format(hexlify(request_adu))) if len(request_adu) == 0: raise ValueError respons...
[ " Listen and handle 1 request. " ]
Please provide a description of the function:def process(self, request_adu): validate_crc(request_adu) return super(RTUServer, self).process(request_adu)
[ " Process request ADU and return response.\n\n :param request_adu: A bytearray containing the ADU request.\n :return: A bytearray containing the response of the ADU request.\n " ]
Please provide a description of the function:def create_response_adu(self, meta_data, response_pdu): first_part_adu = struct.pack('>B', meta_data['unit_id']) + response_pdu return first_part_adu + get_crc(first_part_adu)
[ " Build response ADU from meta data and response PDU and return it.\n\n :param meta_data: A dict with meta data.\n :param request_pdu: A bytearray containing request PDU.\n :return: A bytearray containing request ADU.\n " ]
Please provide a description of the function:def generate_look_up_table(): poly = 0xA001 table = [] for index in range(256): data = index << 1 crc = 0 for _ in range(8, 0, -1): data >>= 1 if (data ^ crc) & 0x0001: crc = (crc >> 1) ^ poly...
[ " Generate look up table.\n\n :return: List\n " ]
Please provide a description of the function:def get_crc(msg): register = 0xFFFF for byte_ in msg: try: val = struct.unpack('<B', byte_)[0] # Iterating over a bit-like objects in Python 3 gets you ints. # Because fuck logic. except TypeError: val = b...
[ " Return CRC of 2 byte for message.\n\n >>> assert get_crc(b'\\x02\\x07') == struct.unpack('<H', b'\\x41\\x12')\n\n :param msg: A byte array.\n :return: Byte array of 2 bytes.\n " ]
Please provide a description of the function:def validate_crc(msg): if not struct.unpack('<H', get_crc(msg[:-2])) ==\ struct.unpack('<H', msg[-2:]): raise CRCError('CRC validation failed.')
[ " Validate CRC of message.\n\n :param msg: Byte array with message with CRC.\n :raise: CRCError.\n " ]
Please provide a description of the function:def _create_request_adu(slave_id, req_pdu): first_part_adu = struct.pack('>B', slave_id) + req_pdu return first_part_adu + get_crc(first_part_adu)
[ " Return request ADU for Modbus RTU.\n\n :param slave_id: Slave id.\n :param req_pdu: Byte array with PDU.\n :return: Byte array with ADU.\n " ]
Please provide a description of the function:def read_coils(slave_id, starting_address, quantity): function = ReadCoils() function.starting_address = starting_address function.quantity = quantity return _create_request_adu(slave_id, function.request_pdu)
[ " Return ADU for Modbus function code 01: Read Coils.\n\n :param slave_id: Number of slave.\n :return: Byte array with ADU.\n " ]
Please provide a description of the function:def read_discrete_inputs(slave_id, starting_address, quantity): function = ReadDiscreteInputs() function.starting_address = starting_address function.quantity = quantity return _create_request_adu(slave_id, function.request_pdu)
[ " Return ADU for Modbus function code 02: Read Discrete Inputs.\n\n :param slave_id: Number of slave.\n :return: Byte array with ADU.\n " ]
Please provide a description of the function:def read_holding_registers(slave_id, starting_address, quantity): function = ReadHoldingRegisters() function.starting_address = starting_address function.quantity = quantity return _create_request_adu(slave_id, function.request_pdu)
[ " Return ADU for Modbus function code 03: Read Holding Registers.\n\n :param slave_id: Number of slave.\n :return: Byte array with ADU.\n " ]
Please provide a description of the function:def read_input_registers(slave_id, starting_address, quantity): function = ReadInputRegisters() function.starting_address = starting_address function.quantity = quantity return _create_request_adu(slave_id, function.request_pdu)
[ " Return ADU for Modbus function code 04: Read Input Registers.\n\n :param slave_id: Number of slave.\n :return: Byte array with ADU.\n " ]
Please provide a description of the function:def write_single_coil(slave_id, address, value): function = WriteSingleCoil() function.address = address function.value = value return _create_request_adu(slave_id, function.request_pdu)
[ " Return ADU for Modbus function code 05: Write Single Coil.\n\n :param slave_id: Number of slave.\n :return: Byte array with ADU.\n " ]
Please provide a description of the function:def write_single_register(slave_id, address, value): function = WriteSingleRegister() function.address = address function.value = value return _create_request_adu(slave_id, function.request_pdu)
[ " Return ADU for Modbus function code 06: Write Single Register.\n\n :param slave_id: Number of slave.\n :return: Byte array with ADU.\n " ]
Please provide a description of the function:def write_multiple_coils(slave_id, starting_address, values): function = WriteMultipleCoils() function.starting_address = starting_address function.values = values return _create_request_adu(slave_id, function.request_pdu)
[ " Return ADU for Modbus function code 15: Write Multiple Coils.\n\n :param slave_id: Number of slave.\n :return: Byte array with ADU.\n " ]
Please provide a description of the function:def write_multiple_registers(slave_id, starting_address, values): function = WriteMultipleRegisters() function.starting_address = starting_address function.values = values return _create_request_adu(slave_id, function.request_pdu)
[ " Return ADU for Modbus function code 16: Write Multiple Registers.\n\n :param slave_id: Number of slave.\n :return: Byte array with ADU.\n " ]
Please provide a description of the function:def parse_response_adu(resp_adu, req_adu=None): resp_pdu = resp_adu[1:-2] validate_crc(resp_adu) req_pdu = None if req_adu is not None: req_pdu = req_adu[1:-2] function = create_function_from_response_pdu(resp_pdu, req_pdu) return fun...
[ " Parse response ADU and return response data. Some functions require\n request ADU to fully understand request ADU.\n\n :param resp_adu: Resonse ADU.\n :param req_adu: Request ADU, default None.\n :return: Response data.\n " ]
Please provide a description of the function:def send_message(adu, serial_port): serial_port.write(adu) serial_port.flush() # Check exception ADU (which is shorter than all other responses) first. exception_adu_size = 5 response_error_adu = recv_exactly(serial_port.read, exception_adu_size) ...
[ " Send ADU over serial to to server and return parsed response.\n\n :param adu: Request ADU.\n :param sock: Serial port instance.\n :return: Parsed response from server.\n " ]
Please provide a description of the function:def route(self, slave_ids=None, function_codes=None, addresses=None): def inner(f): self.route_map.add_rule(f, slave_ids, function_codes, addresses) return f return inner
[ " A decorator that is used to register an endpoint for a given\n rule::\n\n @server.route(slave_ids=[1], function_codes=[1, 2], addresses=list(range(100, 200))) # NOQA\n def read_single_bit_values(slave_id, address):\n return random.choise([0, 1])\n\n :param slave_ids: A list or set ...
Please provide a description of the function:def respond(self, response_adu): log.info('--> {0} - {1}.'.format(self.client_address[0], hexlify(response_adu))) self.request.sendall(response_adu)
[ " Send response ADU back to client.\n\n :param response_adu: A bytearray containing the response of an ADU.\n " ]
Please provide a description of the function:def get_server(server_class, server_address, request_handler_class): s = server_class(server_address, request_handler_class) s.route_map = Map() s.route = MethodType(route, s) return s
[ " Return instance of :param:`server_class` with :param:`request_handler`\n bound to it.\n This method also binds a :func:`route` method to the server instance.\n >>> server = get_server(TcpServer, ('localhost', 502), RequestHandler)\n >>> server.serve_forever()\n :param server_class: (sub)Cla...
Please provide a description of the function:def get_meta_data(self, request_adu): try: transaction_id, protocol_id, length, unit_id = \ unpack_mbap(request_adu[:7]) except struct.error: raise ServerDeviceFailureError() return { 'tran...
[ "\" Extract MBAP header from request adu and return it. The dict has\n 4 keys: transaction_id, protocol_id, length and unit_id.\n\n :param request_adu: A bytearray containing request ADU.\n :return: Dict with meta data of request.\n " ]
Please provide a description of the function:def create_response_adu(self, meta_data, response_pdu): response_mbap = pack_mbap( transaction_id=meta_data['transaction_id'], protocol_id=meta_data['protocol_id'], length=len(response_pdu) + 1, unit_id=meta_da...
[ " Build response ADU from meta data and response PDU and return it.\n\n :param meta_data: A dict with meta data.\n :param request_pdu: A bytearray containing request PDU.\n :return: A bytearray containing request ADU.\n " ]
Please provide a description of the function:def log_to_stream(stream=sys.stderr, level=logging.NOTSET, fmt=logging.BASIC_FORMAT): fmt = Formatter(fmt) handler = StreamHandler() handler.setFormatter(fmt) handler.setLevel(level) log.addHandler(handler)
[ " Add :class:`logging.StreamHandler` to logger which logs to a stream.\n\n :param stream. Stream to log to, default STDERR.\n :param level: Log level, default NOTSET.\n :param fmt: String with log format, default is BASIC_FORMAT.\n " ]
Please provide a description of the function:def pack_mbap(transaction_id, protocol_id, length, unit_id): return struct.pack('>HHHB', transaction_id, protocol_id, length, unit_id)
[ " Create and return response MBAP.\n\n :param transaction_id: Transaction id.\n :param protocol_id: Protocol id.\n :param length: Length of following bytes in ADU.\n :param unit_id: Unit id.\n :return: Byte array of 7 bytes.\n " ]
Please provide a description of the function:def memoize(f): cache = {} @wraps(f) def inner(arg): if arg not in cache: cache[arg] = f(arg) return cache[arg] return inner
[ " Decorator which caches function's return value each it is called.\n If called later with same arguments, the cached value is returned.\n " ]
Please provide a description of the function:def recv_exactly(recv_fn, size): recv_bytes = 0 chunks = [] while recv_bytes < size: chunk = recv_fn(size - recv_bytes) if len(chunk) == 0: # when closed or empty break recv_bytes += len(chunk) chunks.append(chunk...
[ " Use the function to read and return exactly number of bytes desired.\n\n https://docs.python.org/3/howto/sockets.html#socket-programming-howto for\n more information about why this is necessary.\n\n :param recv_fn: Function that can return up to given bytes\n (i.e. socket.recv, file.read)\n :pa...
Please provide a description of the function:def _create_mbap_header(slave_id, pdu): # 65535 = (2**16)-1 aka maximum number that fits in 2 bytes. transaction_id = randint(0, 65535) length = len(pdu) + 1 return struct.pack('>HHHB', transaction_id, 0, length, slave_id)
[ " Return byte array with MBAP header for PDU.\n\n :param slave_id: Number of slave.\n :param pdu: Byte array with PDU.\n :return: Byte array of 7 bytes with MBAP header.\n " ]
Please provide a description of the function:def parse_response_adu(resp_adu, req_adu=None): resp_pdu = resp_adu[7:] function = create_function_from_response_pdu(resp_pdu, req_adu) return function.data
[ " Parse response ADU and return response data. Some functions require\n request ADU to fully understand request ADU.\n\n :param resp_adu: Resonse ADU.\n :param req_adu: Request ADU, default None.\n :return: Response data.\n " ]
Please provide a description of the function:def send_message(adu, sock): sock.sendall(adu) # Check exception ADU (which is shorter than all other responses) first. exception_adu_size = 9 response_error_adu = recv_exactly(sock.recv, exception_adu_size) raise_for_exception_adu(response_error_ad...
[ " Send ADU over socket to to server and return parsed response.\n\n :param adu: Request ADU.\n :param sock: Socket instance.\n :return: Parsed response from server.\n " ]
Please provide a description of the function:def get_serial_port(): port = Serial(port='/dev/ttyS1', baudrate=9600, parity=PARITY_NONE, stopbits=1, bytesize=8, timeout=1) fh = port.fileno() # A struct with configuration for serial port. serial_rs485 = struct.pack('hhhhhhhh', 1, ...
[ " Return serial.Serial instance, ready to use for RS485." ]
Please provide a description of the function:def _set_multi_bit_value_format_character(self): self.MULTI_BIT_VALUE_FORMAT_CHARACTER = \ self.MULTI_BIT_VALUE_FORMAT_CHARACTER.upper() if self.SIGNED_VALUES: self.MULTI_BIT_VALUE_FORMAT_CHARACTER = \ self.MU...
[ " Set format character for multibit values.\n\n The format character depends on size of the value and whether values\n are signed or unsigned.\n\n " ]
Please provide a description of the function:def png(contents, kvs): outfile = os.path.join(IMAGEDIR, sha(contents + str(kvs['staffsize']))) src = outfile + '.png' if not os.path.isfile(src): try: os.mkdir(IMAGEDIR) stderr.write('Created directory ' + IMAGEDIR + '\n') ...
[ "Creates a png if needed." ]
Please provide a description of the function:def get_filename4code(module, content, ext=None): imagedir = module + "-images" fn = hashlib.sha1(content.encode(sys.getfilesystemencoding())).hexdigest() try: os.mkdir(imagedir) sys.stderr.write('Created directory ' + imagedir + '\n') ex...
[ "Generate filename based on content\n\n The function ensures that the (temporary) directory exists, so that the\n file can be written.\n\n Example:\n filename = get_filename4code(\"myfilter\", code)\n " ]
Please provide a description of the function:def get_value(kv, key, value = None): res = [] for k, v in kv: if k == key: value = v else: res.append([k, v]) return value, res
[ "get value from the keyvalues (options)" ]
Please provide a description of the function:def get_caption(kv): caption = [] typef = "" value, res = get_value(kv, u"caption") if value is not None: caption = [Str(value)] typef = "fig:" return caption, typef, res
[ "get caption from the keyvalues (options)\n\n Example:\n if key == 'CodeBlock':\n [[ident, classes, keyvals], code] = value\n caption, typef, keyvals = get_caption(keyvals)\n ...\n return Para([Image([ident, [], keyvals], caption, [filename, typef])])\n " ]
Please provide a description of the function:def walk(x, action, format, meta): if isinstance(x, list): array = [] for item in x: if isinstance(item, dict) and 't' in item: res = action(item['t'], item['c'] if 'c' in item else None, forma...
[ "Walk a tree, applying an action to every object.\n Returns a modified tree. An action is a function of the form\n `action(key, value, format, meta)`, where:\n\n * `key` is the type of the pandoc object (e.g. 'Str', 'Para') `value` is\n * the contents of the object (e.g. a string for 'Str', a list of\n...
Please provide a description of the function:def toJSONFilters(actions): try: input_stream = io.TextIOWrapper(sys.stdin.buffer, encoding='utf-8') except AttributeError: # Python 2 does not have sys.stdin.buffer. # REF: https://stackoverflow.com/questions/2467928/python-unicodeencode...
[ "Generate a JSON-to-JSON filter from stdin to stdout\n\n The filter:\n\n * reads a JSON-formatted pandoc document from stdin\n * transforms it by walking the tree and performing the actions\n * returns a new JSON-formatted pandoc document to stdout\n\n The argument `actions` is a list of functions of...
Please provide a description of the function:def applyJSONFilters(actions, source, format=""): doc = json.loads(source) if 'meta' in doc: meta = doc['meta'] elif doc[0]: # old API meta = doc[0]['unMeta'] else: meta = {} altered = doc for action in actions: ...
[ "Walk through JSON structure and apply filters\n\n This:\n\n * reads a JSON-formatted pandoc document from a source string\n * transforms it by walking the tree and performing the actions\n * returns a new JSON-formatted pandoc document as a string\n\n The `actions` argument is a list of functions (s...
Please provide a description of the function:def stringify(x): result = [] def go(key, val, format, meta): if key in ['Str', 'MetaString']: result.append(val) elif key == 'Code': result.append(val[1]) elif key == 'Math': result.append(val[1]) ...
[ "Walks the tree x and returns concatenated string content,\n leaving out all formatting.\n " ]
Please provide a description of the function:def attributes(attrs): attrs = attrs or {} ident = attrs.get("id", "") classes = attrs.get("classes", []) keyvals = [[x, attrs[x]] for x in attrs if (x != "classes" and x != "id")] return [ident, classes, keyvals]
[ "Returns an attribute list, constructed from the\n dictionary attrs.\n " ]
Please provide a description of the function:def latexsnippet(code, kvs, staffsize=17, initiallines=1): snippet = '' staffsize = int(kvs['staffsize']) if 'staffsize' in kvs \ else staffsize initiallines = int(kvs['initiallines']) if 'initiallines' in kvs \ else initiallines annotati...
[ "Take in account key/values" ]
Please provide a description of the function:def latex2png(snippet, outfile): pngimage = os.path.join(IMAGEDIR, outfile + '.png') texdocument = os.path.join(IMAGEDIR, 'tmp.tex') with open(texdocument, 'w') as doc: doc.write(LATEX_DOC % (snippet)) environment = os.environ environment['sh...
[ "Compiles a LaTeX snippet to png" ]
Please provide a description of the function:def png(contents, latex_command): outfile = sha(contents + latex_command) src = os.path.join(IMAGEDIR, outfile + '.png') if not os.path.isfile(src): try: os.mkdir(IMAGEDIR) stderr.write('Created directory ' + IMAGEDIR + '\n') ...
[ "Creates a png if needed." ]
Please provide a description of the function:def to_latlon(easting, northing, zone_number, zone_letter=None, northern=None, strict=True): if not zone_letter and northern is None: raise ValueError('either zone_letter or northern needs to be set') elif zone_letter and northern is not None: r...
[ "This function convert an UTM coordinate into Latitude and Longitude\n\n Parameters\n ----------\n easting: int\n Easting value of UTM coordinate\n\n northing: int\n Northing value of UTM coordinate\n\n zone number: int\n Zone Number is represented...
Please provide a description of the function:def from_latlon(latitude, longitude, force_zone_number=None, force_zone_letter=None): if not in_bounds(latitude, -80.0, 84.0): raise OutOfRangeError('latitude out of range (must be between 80 deg S and 84 deg N)') if not in_bounds(longitude, -180.0, 180....
[ "This function convert Latitude and Longitude to UTM coordinate\n\n Parameters\n ----------\n latitude: float\n Latitude between 80 deg S and 84 deg N, e.g. (-80.0 to 84.0)\n\n longitude: float\n Longitude between 180 deg W and 180 deg E, e.g. (-180.0 to 180.0).\n\n...
Please provide a description of the function:def get_jokes(language='en', category='neutral'): if language not in all_jokes: raise LanguageNotFoundError('No such language %s' % language) jokes = all_jokes[language] if category not in jokes: raise CategoryNotFoundError('No such catego...
[ "\n Parameters\n ----------\n category: str\n Choices: 'neutral', 'chuck', 'all', 'twister'\n lang: str\n Choices: 'en', 'de', 'es', 'gl', 'eu', 'it'\n\n Returns\n -------\n jokes: list\n " ]
Please provide a description of the function:def get_joke(language='en', category='neutral'): jokes = get_jokes(language, category) return random.choice(jokes)
[ "\n Parameters\n ----------\n category: str\n Choices: 'neutral', 'chuck', 'all', 'twister'\n lang: str\n Choices: 'en', 'de', 'es', 'gl', 'eu', 'it'\n\n Returns\n -------\n joke: str\n " ]
Please provide a description of the function:def _capture_original_object(self): try: self._doubles_target = getattr(self.target, self._name) except AttributeError: raise VerifyingDoubleError(self.target, self._name)
[ "Capture the original python object." ]
Please provide a description of the function:def set_value(self, value): self._value = value setattr(self.target, self._name, value)
[ "Set the value of the target.\n\n :param obj value: The value to set.\n " ]
Please provide a description of the function:def patch_class(input_class): class Instantiator(object): @classmethod def _doubles__new__(self, *args, **kwargs): pass new_class = type(input_class.__name__, (input_class, Instantiator), {}) return new_class
[ "Create a new class based on the input_class.\n\n :param class input_class: The class to patch.\n :rtype class:\n " ]
Please provide a description of the function:def clear(*objects_to_clear): if not hasattr(_thread_local_data, 'current_space'): return space = current_space() for obj in objects_to_clear: space.clear(obj)
[ "Clears allowances/expectations on objects\n\n :param object objects_to_clear: The objects to remove allowances and\n expectations from.\n " ]
Please provide a description of the function:def satisfy_any_args_match(self): is_match = super(Expectation, self).satisfy_any_args_match() if is_match: self._satisfy() return is_match
[ "\n Returns a boolean indicating whether or not the mock will accept arbitrary arguments.\n This will be true unless the user has specified otherwise using ``with_args`` or\n ``with_no_args``.\n\n :return: Whether or not the mock accepts arbitrary arguments.\n :rtype: bool\n ...
Please provide a description of the function:def satisfy_exact_match(self, args, kwargs): is_match = super(Expectation, self).satisfy_exact_match(args, kwargs) if is_match: self._satisfy() return is_match
[ "\n Returns a boolean indicating whether or not the mock will accept the provided arguments.\n\n :return: Whether or not the mock accepts the provided arguments.\n :rtype: bool\n " ]
Please provide a description of the function:def satisfy_custom_matcher(self, args, kwargs): is_match = super(Expectation, self).satisfy_custom_matcher(args, kwargs) if is_match: self._satisfy() return is_match
[ "Returns a boolean indicating whether or not the mock will accept the provided arguments.\n\n :param tuple args: A tuple of position args\n :param dict kwargs: A dictionary of keyword args\n :return: Whether or not the mock accepts the provided arguments.\n :rtype: bool\n " ]
Please provide a description of the function:def is_satisfied(self): return self._call_counter.has_correct_call_count() and ( self._call_counter.never() or self._is_satisfied)
[ "\n Returns a boolean indicating whether or not the double has been satisfied. Stubs are\n always satisfied, but mocks are only satisfied if they've been called as was declared,\n or if call is expected not to happen.\n\n :return: Whether or not the double is satisfied.\n :rtype: ...
Please provide a description of the function:def has_too_many_calls(self): if self.has_exact and self._call_count > self._exact: return True if self.has_maximum and self._call_count > self._maximum: return True return False
[ "Test if there have been too many calls\n\n :rtype boolean\n " ]
Please provide a description of the function:def has_too_few_calls(self): if self.has_exact and self._call_count < self._exact: return True if self.has_minimum and self._call_count < self._minimum: return True return False
[ "Test if there have not been enough calls\n\n :rtype boolean\n " ]
Please provide a description of the function:def _restriction_string(self): if self.has_minimum: string = 'at least ' value = self._minimum elif self.has_maximum: string = 'at most ' value = self._maximum elif self.has_exact: ...
[ "Get a string explaining the expectation currently set\n\n e.g `at least 5 times`, `at most 1 time`, or `2 times`\n\n :rtype string\n " ]
Please provide a description of the function:def error_string(self): if self.has_correct_call_count(): return '' return '{} instead of {} {} '.format( self._restriction_string(), self.count, pluralize('time', self.count) )
[ "Returns a well formed error message\n\n e.g at least 5 times but was called 4 times\n\n :rtype string\n " ]
Please provide a description of the function:def patch_for(self, path): if path not in self._patches: self._patches[path] = Patch(path) return self._patches[path]
[ "Returns the ``Patch`` for the target path, creating it if necessary.\n\n :param str path: The absolute module path to the target.\n :return: The mapped ``Patch``.\n :rtype: Patch\n " ]
Please provide a description of the function:def proxy_for(self, obj): obj_id = id(obj) if obj_id not in self._proxies: self._proxies[obj_id] = Proxy(obj) return self._proxies[obj_id]
[ "Returns the ``Proxy`` for the target object, creating it if necessary.\n\n :param object obj: The object that will be doubled.\n :return: The mapped ``Proxy``.\n :rtype: Proxy\n " ]
Please provide a description of the function:def teardown(self): for proxy in self._proxies.values(): proxy.restore_original_object() for patch in self._patches.values(): patch.restore_original_object()
[ "Restores all doubled objects to their original state." ]
Please provide a description of the function:def clear(self, obj): self.proxy_for(obj).restore_original_object() del self._proxies[id(obj)]
[ "Clear allowances/expectations set on an object.\n\n :param object obj: The object to clear.\n " ]
Please provide a description of the function:def verify(self): if self._is_verified: return for proxy in self._proxies.values(): proxy.verify() self._is_verified = True
[ "Verifies expectations on all doubled objects.\n\n :raise: ``MockExpectationError`` on the first expectation that is not satisfied, if any.\n " ]
Please provide a description of the function:def restore_original_method(self): if self._target.is_class_or_module(): setattr(self._target.obj, self._method_name, self._original_method) if self._method_name == '__new__' and sys.version_info >= (3, 0): _restore__...
[ "Replaces the proxy method on the target object with its original value." ]
Please provide a description of the function:def _hijack_target(self): if self._target.is_class_or_module(): setattr(self._target.obj, self._method_name, self) elif self._attr.kind == 'property': proxy_property = ProxyProperty( double_name(self._method_n...
[ "Replaces the target method on the target object with the proxy method." ]
Please provide a description of the function:def _raise_exception(self, args, kwargs): error_message = ( "Received unexpected call to '{}' on {!r}. The supplied arguments " "{} do not match any available allowances." ) raise UnallowedMethodCallError( ...
[ " Raises an ``UnallowedMethodCallError`` with a useful message.\n\n :raise: ``UnallowedMethodCallError``\n " ]
Please provide a description of the function:def method_double_for(self, method_name): if method_name not in self._method_doubles: self._method_doubles[method_name] = MethodDouble(method_name, self._target) return self._method_doubles[method_name]
[ "Returns the method double for the provided method name, creating one if necessary.\n\n :param str method_name: The name of the method to retrieve a method double for.\n :return: The mapped ``MethodDouble``.\n :rtype: MethodDouble\n " ]
Please provide a description of the function:def _get_doubles_target(module, class_name, path): try: doubles_target = getattr(module, class_name) if isinstance(doubles_target, ObjectDouble): return doubles_target._doubles_target if not isclass(doubles_target): ...
[ "Validate and return the class to be doubled.\n\n :param module module: The module that contains the class that will be doubled.\n :param str class_name: The name of the class that will be doubled.\n :param str path: The full path to the class that will be doubled.\n :return: The class that will be doub...
Please provide a description of the function:def and_raise(self, exception, *args, **kwargs): def proxy_exception(*proxy_args, **proxy_kwargs): raise exception self._return_value = proxy_exception return self
[ "Causes the double to raise the provided exception when called.\n\n If provided, additional arguments (positional and keyword) passed to\n `and_raise` are used in the exception instantiation.\n\n :param Exception exception: The exception to raise.\n " ]