text_prompt
stringlengths
157
13.1k
code_prompt
stringlengths
7
19.8k
⌀
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def is_state(self, entity_id, state): """Checks if the entity has the given state"""
return remote.is_state(self.api, entity_id, state)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def etag(self, etag): """ Set the ETag of the resource. :param etag: the ETag """
if not isinstance(etag, bytes): etag = bytes(etag, "utf-8") self._etag.append(etag)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def payload(self, p): """ Set the payload of the resource. :param p: the new payload """
if isinstance(p, tuple): k = p[0] v = p[1] self.actual_content_type = k self._payload[k] = v else: self._payload = {defines.Content_types["text/plain"]: p}
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def content_type(self): """ Get the CoRE Link Format ct attribute of the resource. :return: the CoRE Link Format ct attribute """
value = "" lst = self._attributes.get("ct") if lst is not None and len(lst) > 0: value = "ct=" for v in lst: value += str(v) + " " if len(value) > 0: value = value[:-1] return value
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def content_type(self, lst): """ Set the CoRE Link Format ct attribute of the resource. :param lst: the list of CoRE Link Format ct attribute of the resource """
value = [] if isinstance(lst, str): ct = defines.Content_types[lst] self.add_content_type(ct) elif isinstance(lst, list): for ct in lst: self.add_content_type(ct)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def add_content_type(self, ct): """ Add a CoRE Link Format ct attribute to the resource. :param ct: the CoRE Link Format ct attribute """
lst = self._attributes.get("ct") if lst is None: lst = [] if isinstance(ct, str): ct = defines.Content_types[ct] lst.append(ct) self._attributes["ct"] = lst
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def resource_type(self): """ Get the CoRE Link Format rt attribute of the resource. :return: the CoRE Link Format rt attribute """
value = "rt=" lst = self._attributes.get("rt") if lst is None: value = "" else: value += "\"" + str(lst) + "\"" return value
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def resource_type(self, rt): """ Set the CoRE Link Format rt attribute of the resource. :param rt: the CoRE Link Format rt attribute """
if not isinstance(rt, str): rt = str(rt) self._attributes["rt"] = rt
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def interface_type(self): """ Get the CoRE Link Format if attribute of the resource. :return: the CoRE Link Format if attribute """
value = "if=" lst = self._attributes.get("if") if lst is None: value = "" else: value += "\"" + str(lst) + "\"" return value
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def interface_type(self, ift): """ Set the CoRE Link Format if attribute of the resource. :param ift: the CoRE Link Format if attribute """
if not isinstance(ift, str): ift = str(ift) self._attributes["if"] = ift
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def maximum_size_estimated(self): """ Get the CoRE Link Format sz attribute of the resource. :return: the CoRE Link Format sz attribute """
value = "sz=" lst = self._attributes.get("sz") if lst is None: value = "" else: value += "\"" + str(lst) + "\"" return value
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def maximum_size_estimated(self, sz): """ Set the CoRE Link Format sz attribute of the resource. :param sz: the CoRE Link Format sz attribute """
if not isinstance(sz, str): sz = str(sz) self._attributes["sz"] = sz
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def init_resource(self, request, res): """ Helper function to initialize a new resource. :param request: the request that generate the new resource :param res: t...
res.location_query = request.uri_query res.payload = (request.content_type, request.payload) return res
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def edit_resource(self, request): """ Helper function to edit a resource :param request: the request that edit the resource """
self.location_query = request.uri_query self.payload = (request.content_type, request.payload)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def receive_request(self, transaction): """ Handles the Blocks option in a incoming request. :type transaction: Transaction :param transaction: the transaction t...
if transaction.request.block2 is not None: host, port = transaction.request.source key_token = hash(str(host) + str(port) + str(transaction.request.token)) num, m, size = transaction.request.block2 if key_token in self._block2_receive: self._block...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def send_response(self, transaction): """ Handles the Blocks option in a outgoing response. :type transaction: Transaction :param transaction: the transaction th...
host, port = transaction.request.source key_token = hash(str(host) + str(port) + str(transaction.request.token)) if (key_token in self._block2_receive and transaction.response.payload is not None) or \ (transaction.response.payload is not None and len(transaction.response.payloa...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def send_request(self, request): """ Handles the Blocks option in a outgoing request. :type request: Request :param request: the outgoing request :return: the ed...
assert isinstance(request, Request) if request.block1 or (request.payload is not None and len(request.payload) > defines.MAX_PAYLOAD): host, port = request.destination key_token = hash(str(host) + str(port) + str(request.token)) if request.block1: num...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def incomplete(transaction): """ Notifies incomplete blockwise exchange. :type transaction: Transaction :param transaction: the transaction that owns the respons...
transaction.block_transfer = True transaction.response = Response() transaction.response.destination = transaction.request.source transaction.response.token = transaction.request.token transaction.response.code = defines.Codes.REQUEST_ENTITY_INCOMPLETE.number return tran...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def error(transaction, code): # pragma: no cover """ Notifies generic error on blockwise exchange. :type transaction: Transaction :param transaction: the transac...
transaction.block_transfer = True transaction.response = Response() transaction.response.destination = transaction.request.source transaction.response.type = defines.Types["RST"] transaction.response.token = transaction.request.token transaction.response.code = code ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def send_request(self, request): """ Add itself to the observing list :param request: the request :return: the request unmodified """
if request.observe == 0: # Observe request host, port = request.destination key_token = hash(str(host) + str(port) + str(request.token)) self._relations[key_token] = ObserveItem(time.time(), None, True, None) return request
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def receive_response(self, transaction): """ Sets notification's parameters. :type transaction: Transaction :param transaction: the transaction :rtype : Transact...
host, port = transaction.response.source key_token = hash(str(host) + str(port) + str(transaction.response.token)) if key_token in self._relations and transaction.response.type == defines.Types["CON"]: transaction.notification = True return transaction
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def send_empty(self, message): """ Eventually remove from the observer list in case of a RST message. :type message: Message :param message: the message :return:...
host, port = message.destination key_token = hash(str(host) + str(port) + str(message.token)) if key_token in self._relations and message.type == defines.Types["RST"]: del self._relations[key_token] return message
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def receive_request(self, transaction): """ Manage the observe option in the request end eventually initialize the client for adding to the list of observers or ...
if transaction.request.observe == 0: # Observe request host, port = transaction.request.source key_token = hash(str(host) + str(port) + str(transaction.request.token)) non_counter = 0 if key_token in self._relations: # Renew registrati...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def receive_empty(self, empty, transaction): """ Manage the observe feature to remove a client in case of a RST message receveide in reply to a notification. :ty...
if empty.type == defines.Types["RST"]: host, port = transaction.request.source key_token = hash(str(host) + str(port) + str(transaction.request.token)) logger.info("Remove Subscriber") try: del self._relations[key_token] except KeyErro...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def send_response(self, transaction): """ Finalize to add the client to the list of observer. :type transaction: Transaction :param transaction: the transaction ...
host, port = transaction.request.source key_token = hash(str(host) + str(port) + str(transaction.request.token)) if key_token in self._relations: if transaction.response.code == defines.Codes.CONTENT.number: if transaction.resource is not None and transaction.resourc...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def notify(self, resource, root=None): """ Prepare notification for the resource to all interested observers. :rtype: list :param resource: the resource for whic...
ret = [] if root is not None: resource_list = root.with_prefix_resource(resource.path) else: resource_list = [resource] for key in list(self._relations.keys()): if self._relations[key].transaction.resource in resource_list: if self._re...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def remove_subscriber(self, message): """ Remove a subscriber based on token. :param message: the message """
logger.debug("Remove Subcriber") host, port = message.destination key_token = hash(str(host) + str(port) + str(message.token)) try: self._relations[key_token].transaction.completed = True del self._relations[key_token] except KeyError: logger....
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def purge(self): """ Clean old transactions """
while not self.stopped.isSet(): self.stopped.wait(timeout=defines.EXCHANGE_LIFETIME) self._messageLayer.purge()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def send_datagram(self, message): """ Send a message through the udp socket. :type message: Message :param message: the message to send """
if not self.stopped.isSet(): host, port = message.destination logger.debug("send_datagram - " + str(message)) serializer = Serializer() message = serializer.serialize(message) self._socket.sendto(message, (host, port))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _retransmit(self, transaction, message, future_time, retransmit_count): """ Thread function to retransmit the message in the future :param transaction: the t...
with transaction: while retransmit_count < defines.MAX_RETRANSMIT and (not message.acknowledged and not message.rejected) \ and not self.stopped.isSet(): transaction.retransmit_stop.wait(timeout=future_time) if not message.acknowledged and not mes...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _start_separate_timer(self, transaction): """ Start a thread to handle separate mode. :type transaction: Transaction :param transaction: the transaction that...
t = threading.Timer(defines.ACK_TIMEOUT, self._send_ack, (transaction,)) t.start() return t
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def parse_config(self): """ Parse the xml file with remote servers and discover resources on each found server. """
tree = ElementTree.parse(self.file_xml) root = tree.getroot() for server in root.findall('server'): destination = server.text name = server.get("name") self.discover_remote(destination, name)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def discover_remote(self, destination, name): """ Discover resources on remote servers. :param destination: the remote server (ip, port) :type destination: tuple...
assert (isinstance(destination, str)) if destination.startswith("["): split = destination.split("]", 1) host = split[0][1:] port = int(split[1][1:]) else: split = destination.split(":", 1) host = split[0] port = int(split[1...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def discover_remote_results(self, response, name): """ Create a new remote server resource for each valid discover response. :param response: the response to the...
host, port = response.source if response.code == defines.Codes.CONTENT.number: resource = Resource('server', self, visible=True, observable=False, allow_children=True) self.add_resource(name, resource) self._mapping[name] = (host, port) self.parse_core_l...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def parse_core_link_format(self, link_format, base_path, remote_server): """ Parse discovery results. :param link_format: the payload of the response to the disc...
while len(link_format) > 0: pattern = "<([^>]*)>;" result = re.match(pattern, link_format) path = result.group(1) path = path.split("/") path = path[1:][0] link_format = link_format[result.end(1) + 2:] pattern = "([^<,])*" ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def receive_datagram(self, args): """ Handle messages coming from the udp socket. :param args: (data, client_address) """
data, client_address = args serializer = Serializer() message = serializer.deserialize(data, client_address) if isinstance(message, int): logger.error("receive_datagram - BAD REQUEST") rst = Message() rst.destination = client_address rst...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _wait_response(self, message): """ Private function to get responses from the server. :param message: the received message """
if message is None or message.code != defines.Codes.CONTINUE.number: self.queue.put(message)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _thread_body(self, request, callback): """ Private function. Send a request, wait for response and call the callback function. :param request: the request to...
self.protocol.send_message(request) while not self.protocol.stopped.isSet(): response = self.queue.get(block=True) callback(response)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def cancel_observing(self, response, send_rst): # pragma: no cover """ Delete observing on the remote server. :param response: the last received response :param ...
if send_rst: message = Message() message.destination = self.server message.code = defines.Codes.EMPTY.number message.type = defines.Types["RST"] message.token = response.token message.mid = response.mid self.protocol.send_messa...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def observe(self, path, callback, timeout=None, **kwargs): # pragma: no cover """ Perform a GET with observe on a certain path. :param path: the path :param call...
request = self.mk_request(defines.Codes.GET, path) request.observe = 0 for k, v in kwargs.items(): if hasattr(request, k): setattr(request, k, v) return self.send_request(request, callback, timeout)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def delete(self, path, callback=None, timeout=None, **kwargs): # pragma: no cover """ Perform a DELETE on a certain path. :param path: the path :param callback: ...
request = self.mk_request(defines.Codes.DELETE, path) for k, v in kwargs.items(): if hasattr(request, k): setattr(request, k, v) return self.send_request(request, callback, timeout)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def post(self, path, payload, callback=None, timeout=None, no_response=False, **kwargs): # pragma: no cover """ Perform a POST on a certain path. :param path: th...
request = self.mk_request(defines.Codes.POST, path) request.token = generate_random_token(2) request.payload = payload if no_response: request.add_no_response() request.type = defines.Types["NON"] for k, v in kwargs.items(): if hasattr(reque...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def discover(self, callback=None, timeout=None, **kwargs): # pragma: no cover """ Perform a Discover request on the server. :param callback: the callback functio...
request = self.mk_request(defines.Codes.GET, defines.DISCOVERY_URL) for k, v in kwargs.items(): if hasattr(request, k): setattr(request, k, v) return self.send_request(request, callback, timeout)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def send_request(self, request, callback=None, timeout=None, no_response=False): # pragma: no cover """ Send a request to the remote server. :param request: the ...
if callback is not None: thread = threading.Thread(target=self._thread_body, args=(request, callback)) thread.start() else: self.protocol.send_message(request) if no_response: return try: response = self.queue.g...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def run(self): """ Start the proxy. """
server_address = (self.ip, self.hc_port) hc_proxy = HTTPServer(server_address, HCProxyHandler) logger.info('Starting HTTP-CoAP Proxy...') hc_proxy.serve_forever()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_formatted_path(path): """ Uniform the path string :param path: the path :return: the uniform path """
if path[0] != '/': path = '/' + path if path[-1] != '/': path = '{0}/'.format(path) return path
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_payload(self): """ Return the query string of the uri. :return: the query string as a list """
temp = self.get_uri_as_list() query_string = temp[4] if query_string == "": return None # Bad request error code query_string_as_list = str.split(query_string, "=") return query_string_as_list[1]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def do_initial_operations(self): """ Setup the client for interact with remote server """
if not self.request_hc_path_corresponds(): # the http URI of the request is not the same of the one specified by the admin for the hc proxy, # so I do not answer # For example the admin setup the http proxy URI like: "http://127.0.0.1:8080:/my_hc_path/" and the URI of ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def do_GET(self): """ Perform a GET request """
self.do_initial_operations() coap_response = self.client.get(self.coap_uri.path) self.client.stop() logger.info("Server response: %s", coap_response.pretty_print()) self.set_http_response(coap_response)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def do_HEAD(self): """ Perform a HEAD request """
self.do_initial_operations() # the HEAD method is not present in CoAP, so we treat it # like if it was a GET and then we exclude the body from the response # with send_body=False we say that we do not need the body, because it is a HEAD request coap_response = self.client.get(se...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def do_POST(self): """ Perform a POST request """
# Doesn't do anything with posted data # print "uri: ", self.client_address, self.path self.do_initial_operations() payload = self.coap_uri.get_payload() if payload is None: logger.error("BAD POST REQUEST") self.send_error(BAD_REQUEST) return ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def do_PUT(self): """ Perform a PUT request """
self.do_initial_operations() payload = self.coap_uri.get_payload() if payload is None: logger.error("BAD PUT REQUEST") self.send_error(BAD_REQUEST) return logger.debug(payload) coap_response = self.client.put(self.coap_uri.path, payload) ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def do_DELETE(self): """ Perform a DELETE request """
self.do_initial_operations() coap_response = self.client.delete(self.coap_uri.path) self.client.stop() logger.debug("Server response: %s", coap_response.pretty_print()) self.set_http_response(coap_response)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def request_hc_path_corresponds(self): """ Tells if the hc path of the request corresponds to that specified by the admin :return: a boolean that says if it corr...
uri_path = self.path.split(COAP_PREFACE) request_hc_path = uri_path[0] logger.debug("HCPATH: %s", hc_path) # print HC_PATH logger.debug("URI: %s", request_hc_path) if hc_path != request_hc_path: return False else: return True
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def set_http_header(self, coap_response): """ Sets http headers. :param coap_response: the coap response """
logger.debug( ("Server: %s\n"\ "codice risposta: %s\n"\ "PROXED: %s\n"\ "payload risposta: %s"), coap_response.source, coap_response.code, CoAP_HTTP[Codes.LIST[coap_response.c...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def set_http_body(self, coap_response): """ Set http body. :param coap_response: the coap response """
if coap_response.payload is not None: body = "<html><body><h1>", coap_response.payload, "</h1></body></html>" self.wfile.write("".join(body)) else: self.wfile.write("<html><body><h1>None</h1></body></html>")
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def parse_blockwise(value): """ Parse Blockwise option. :param value: option value :return: num, m, size """
length = byte_len(value) if length == 1: num = value & 0xF0 num >>= 4 m = value & 0x08 m >>= 3 size = value & 0x07 elif length == 2: num = value & 0xFFF0 num >>= 4 m = value & 0x0008 m >>= 3 size = value & 0x0007 else: ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def byte_len(int_type): """ Get the number of byte needed to encode the int passed. :param int_type: the int to be converted :return: the number of bits needed t...
length = 0 while int_type: int_type >>= 1 length += 1 if length > 0: if length % 8 != 0: length = int(length / 8) + 1 else: length = int(length / 8) return length
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def value(self): """ Return the option value. :return: the option value in the correct format depending on the option """
if type(self._value) is None: self._value = bytearray() opt_type = defines.OptionRegistry.LIST[self._number].value_type if opt_type == defines.INTEGER: if byte_len(self._value) > 0: return int(self._value) else: return defines....
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def value(self, value): """ Set the value of the option. :param value: the option value """
opt_type = defines.OptionRegistry.LIST[self._number].value_type if opt_type == defines.INTEGER: if type(value) is not int: value = int(value) if byte_len(value) == 0: value = 0 elif opt_type == defines.STRING: if type(value) is...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def length(self): """ Return the value length :rtype : int """
if isinstance(self._value, int): return byte_len(self._value) if self._value is None: return 0 return len(self._value)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def is_safe(self): """ Check if the option is safe. :rtype : bool :return: True, if option is safe """
if self._number == defines.OptionRegistry.URI_HOST.number \ or self._number == defines.OptionRegistry.URI_PORT.number \ or self._number == defines.OptionRegistry.URI_PATH.number \ or self._number == defines.OptionRegistry.MAX_AGE.number \ or self....
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_option_flags(option_num): """ Get Critical, UnSafe, NoCacheKey flags from the option number as per RFC 7252, section 5.4.6 :param option_num: option numb...
opt_bytes = array.array('B', '\0\0') if option_num < 256: s = struct.Struct("!B") s.pack_into(opt_bytes, 0, option_num) else: s = struct.Struct("H") s.pack_into(opt_bytes, 0, option_num) critical = (opt_bytes[0] & 0x01) > 0 unsafe ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def read_option_value_from_nibble(nibble, pos, values): """ Calculates the value used in the extended option fields. :param nibble: the 4-bit option header value...
if nibble <= 12: return nibble, pos elif nibble == 13: tmp = struct.unpack("!B", values[pos].to_bytes(1, "big"))[0] + 13 pos += 1 return tmp, pos elif nibble == 14: s = struct.Struct("!H") tmp = s.unpack_from(values[pos:].t...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def read_option_value_len_from_byte(byte, pos, values): """ Calculates the value and length used in the extended option fields. :param byte: 1-byte option header...
h_nibble = (byte & 0xF0) >> 4 l_nibble = byte & 0x0F value = 0 length = 0 if h_nibble <= 12: value = h_nibble elif h_nibble == 13: value = struct.unpack("!B", values[pos].to_bytes(1, "big"))[0] + 13 pos += 1 elif h_nibble == 14...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def convert_to_raw(number, value, length): """ Get the value of an option as a ByteArray. :param number: the option number :param value: the option value :param ...
opt_type = defines.OptionRegistry.LIST[number].value_type if length == 0 and opt_type != defines.INTEGER: return bytes() elif length == 0 and opt_type == defines.INTEGER: return 0 elif opt_type == defines.STRING: if isinstance(value, bytes): ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def as_sorted_list(options): """ Returns all options in a list sorted according to their option numbers. :return: the sorted list """
if len(options) > 0: options = sorted(options, key=lambda o: o.number) return options
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def int_to_words(int_val, num_words=4, word_size=32): """ Convert a int value to bytes. :param int_val: an arbitrary length Python integer to be split up. Networ...
max_int = 2 ** (word_size*num_words) - 1 max_word_size = 2 ** word_size - 1 if not 0 <= int_val <= max_int: raise AttributeError('integer %r is out of bounds!' % hex(int_val)) words = [] for _ in range(num_words): word = int_val & max_word_size ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def str_append_hash(*args): """ Convert each argument to a lower case string, appended, then hash """
ret_hash = "" for i in args: ret_hash += str(i).lower() return hash(ret_hash)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def fetch_mid(self): """ Gets the next valid MID. :return: the mid to use """
current_mid = self._current_mid self._current_mid += 1 self._current_mid %= 65535 return current_mid
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def receive_request(self, request): """ Handle duplicates and store received messages. :type request: Request :param request: the incoming request :rtype : Trans...
logger.debug("receive_request - " + str(request)) try: host, port = request.source except AttributeError: return key_mid = str_append_hash(host, port, request.mid) key_token = str_append_hash(host, port, request.token) if key_mid in list(self._tr...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def receive_response(self, response): """ Pair responses with requests. :type response: Response :param response: the received response :rtype : Transaction :ret...
logger.debug("receive_response - " + str(response)) try: host, port = response.source except AttributeError: return key_mid = str_append_hash(host, port, response.mid) key_mid_multicast = str_append_hash(defines.ALL_COAP_NODES, port, response.mid) ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def receive_empty(self, message): """ Pair ACKs with requests. :type message: Message :param message: the received message :rtype : Transaction :return: the tran...
logger.debug("receive_empty - " + str(message)) try: host, port = message.source except AttributeError: return key_mid = str_append_hash(host, port, message.mid) key_mid_multicast = str_append_hash(defines.ALL_COAP_NODES, port, message.mid) key_to...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def send_request(self, request): """ Create the transaction and fill it with the outgoing request. :type request: Request :param request: the request to send :rt...
logger.debug("send_request - " + str(request)) assert isinstance(request, Request) try: host, port = request.destination except AttributeError: return request.timestamp = time.time() transaction = Transaction(request=request, timestamp=request.ti...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def send_response(self, transaction): """ Set the type, the token and eventually the MID for the outgoing response :type transaction: Transaction :param transact...
logger.debug("send_response - " + str(transaction.response)) if transaction.response.type is None: if transaction.request.type == defines.Types["CON"] and not transaction.request.acknowledged: transaction.response.type = defines.Types["ACK"] transaction.respo...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def send_empty(self, transaction, related, message): """ Manage ACK or RST related to a transaction. Sets if the transaction has been acknowledged or rejected. :...
logger.debug("send_empty - " + str(message)) if transaction is None: try: host, port = message.destination except AttributeError: return key_mid = str_append_hash(host, port, message.mid) key_token = str_append_hash(host, p...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def location_path(self): """ Return the Location-Path of the response. :rtype : String :return: the Location-Path option """
value = [] for option in self.options: if option.number == defines.OptionRegistry.LOCATION_PATH.number: value.append(str(option.value)) return "/".join(value)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def location_path(self, path): """ Set the Location-Path of the response. :type path: String :param path: the Location-Path as a string """
path = path.strip("/") tmp = path.split("?") path = tmp[0] paths = path.split("/") for p in paths: option = Option() option.number = defines.OptionRegistry.LOCATION_PATH.number option.value = p self.add_option(option)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def location_query(self): """ Return the Location-Query of the response. :rtype : String :return: the Location-Query option """
value = [] for option in self.options: if option.number == defines.OptionRegistry.LOCATION_QUERY.number: value.append(option.value) return value
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def location_query(self, value): """ Set the Location-Query of the response. :type path: String :param path: the Location-Query as a string """
del self.location_query queries = value.split("&") for q in queries: option = Option() option.number = defines.OptionRegistry.LOCATION_QUERY.number option.value = str(q) self.add_option(option)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def max_age(self): """ Return the MaxAge of the response. :rtype : int :return: the MaxAge option """
value = defines.OptionRegistry.MAX_AGE.default for option in self.options: if option.number == defines.OptionRegistry.MAX_AGE.number: value = int(option.value) return value
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def max_age(self, value): """ Set the MaxAge of the response. :type value: int :param value: the MaxAge option """
option = Option() option.number = defines.OptionRegistry.MAX_AGE.number option.value = int(value) self.del_option_by_number(defines.OptionRegistry.MAX_AGE.number) self.add_option(option)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def receive_request(self, transaction): """ Handle requests coming from the udp socket. :param transaction: the transaction created to manage the request """
with transaction: transaction.separate_timer = self._start_separate_timer(transaction) self._blockLayer.receive_request(transaction) if transaction.block_transfer: self._stop_separate_timer(transaction.separate_timer) self._messageLayer.se...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def add_resource(self, path, resource): """ Helper function to add resources to the resource directory during server initialization. :param path: the path for th...
assert isinstance(resource, Resource) path = path.strip("/") paths = path.split("/") actual_path = "" i = 0 for p in paths: i += 1 actual_path += "/" + p try: res = self.root[actual_path] except KeyError: ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def remove_resource(self, path): """ Helper function to remove resources. :param path: the path for the unwanted resource :rtype : the removed object """
path = path.strip("/") paths = path.split("/") actual_path = "" i = 0 for p in paths: i += 1 actual_path += "/" + p try: res = self.root[actual_path] except KeyError: res = None if res is not None: ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _send_ack(self, transaction): """ Sends an ACK message for the request. :param transaction: the transaction that owns the request """
ack = Message() ack.type = defines.Types['ACK'] # TODO handle mutex on transaction if not transaction.request.acknowledged and transaction.request.type == defines.Types["CON"]: ack = self._messageLayer.send_empty(transaction, transaction.request, ack) self.send_...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def notify(self, resource): """ Notifies the observers of a certain resource. :param resource: the resource """
observers = self._observeLayer.notify(resource) logger.debug("Notify") for transaction in observers: with transaction: transaction.response = None transaction = self._requestLayer.receive_request(transaction) transaction = self._observ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def create_resource(self, path, transaction): """ Render a POST request. :param path: the path of the request :param transaction: the transaction :return: the re...
t = self._parent.root.with_prefix(path) max_len = 0 imax = None for i in t: if i == path: # Resource already present return self.edit_resource(transaction, path) elif len(i) > max_len: imax = i max_l...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def delete_resource(self, transaction, path): """ Render a DELETE request. :param transaction: the transaction :param path: the path :return: the response """
resource = transaction.resource method = getattr(resource, 'render_DELETE', None) try: ret = method(request=transaction.request) except NotImplementedError: try: method = getattr(transaction.resource, "render_DELETE_advanced", None) ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def corelinkformat(resource): """ Return a formatted string representation of the corelinkformat in the tree. :return: the string """
msg = "<" + resource.path + ">;" assert(isinstance(resource, Resource)) keys = sorted(list(resource.attributes.keys())) for k in keys: method = getattr(resource, defines.corelinkformat[k], None) if method is not None and method != "": v = method ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def receive_request(self, transaction): """ Handle request and execute the requested method :type transaction: Transaction :param transaction: the transaction th...
method = transaction.request.code if method == defines.Codes.GET.number: transaction = self._handle_get(transaction) elif method == defines.Codes.POST.number: transaction = self._handle_post(transaction) elif method == defines.Codes.PUT.number: transa...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _handle_delete(self, transaction): """ Handle DELETE requests :type transaction: Transaction :param transaction: the transaction that owns the request :rtype...
path = str("/" + transaction.request.uri_path) transaction.response = Response() transaction.response.destination = transaction.request.source transaction.response.token = transaction.request.token try: resource = self._server.root[path] except KeyError: ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def uri_path(self): """ Return the Uri-Path of a request :rtype : String :return: the Uri-Path """
value = [] for option in self.options: if option.number == defines.OptionRegistry.URI_PATH.number: value.append(str(option.value) + '/') value = "".join(value) value = value[:-1] return value
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def uri_path(self, path): """ Set the Uri-Path of a request. :param path: the Uri-Path """
path = path.strip("/") tmp = path.split("?") path = tmp[0] paths = path.split("/") for p in paths: option = Option() option.number = defines.OptionRegistry.URI_PATH.number option.value = p self.add_option(option) if len(tmp...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def uri_query(self): """ Get the Uri-Query of a request. :return: the Uri-Query :rtype : String :return: the Uri-Query string """
value = [] for option in self.options: if option.number == defines.OptionRegistry.URI_QUERY.number: value.append(str(option.value)) return "&".join(value)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def uri_query(self, value): """ Adds a query. :param value: the query """
del self.uri_query queries = value.split("&") for q in queries: option = Option() option.number = defines.OptionRegistry.URI_QUERY.number option.value = str(q) self.add_option(option)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def accept(self): """ Get the Accept option of a request. :return: the Accept value or None if not specified by the request :rtype : String """
for option in self.options: if option.number == defines.OptionRegistry.ACCEPT.number: return option.value return None
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def accept(self, value): """ Add an Accept option to a request. :param value: the Accept value """
if value in list(defines.Content_types.values()): option = Option() option.number = defines.OptionRegistry.ACCEPT.number option.value = value self.add_option(option)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def if_match(self): """ Get the If-Match option of a request. :return: the If-Match values or [] if not specified by the request :rtype : list """
value = [] for option in self.options: if option.number == defines.OptionRegistry.IF_MATCH.number: value.append(option.value) return value
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def if_match(self, values): """ Set the If-Match option of a request. :param values: the If-Match values :type values : list """
assert isinstance(values, list) for v in values: option = Option() option.number = defines.OptionRegistry.IF_MATCH.number option.value = v self.add_option(option)