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 _as_json_dumps(self, indent: str=' ', **kwargs) -> str: """ Convert to a stringified json object. This is the same as _as_json with the exception that it isn't :param indent: indent argument to dumps :param kwargs: other arguments for dumps :return: JSON formatted string """
return json.dumps(self, default=self._default, indent=indent, **kwargs)
<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_list(value: List[JsonObjTypes]) -> List[JsonTypes]: """ Return a json array as a list :param value: array :return: array with JsonObj instances removed """
return [e._as_dict if isinstance(e, JsonObj) else e for e in 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 _as_dict(self) -> Dict[str, JsonTypes]: """ Convert a JsonObj into a straight dictionary :return: dictionary that cooresponds to the json object """
return {k: v._as_dict if isinstance(v, JsonObj) else self.__as_list(v) if isinstance(v, list) else v for k, v in self.__dict__.items()}
<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_entries(self): """ Removes the maximum entry limit """
self._debug_log.info('Removing maximum entries restriction') self._log_entries(deque(self._log_entries))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def main(dimension, iterations): """ Main function to execute gbest GC PSO algorithm. """
objective_function = minimize(functions.sphere) stopping_condition = max_iterations(iterations) (solution, metrics) = optimize(objective_function=objective_function, domain=Domain(-5.12, 5.12, dimension), stopping_condition=stopping_condition, parameters={'seed': 3758117674, 'rho': 1.0, 'e_s': 15, 'e_f': 5}, velocity_update=gc_velocity_update, parameter_update=update_rho, measurements=[fitness_measurement]) return solution
<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_chunks(self): """Read chunks from the HTTP client"""
if self.reading_chunks and self.got_chunk: # we got on the fast-path and directly read from the buffer. # if we continue to recurse, this is going to blow up the stack. # so instead return # # NOTE: This actually is unnecessary as long as tornado guarantees that # ioloop.add_callback always gets dispatched via the main io loop # and they don't introduce a fast-path similar to read_XY logger.debug("Fast-Path detected, returning...") return while not self.got_request: self.reading_chunks = True self.got_chunk = False # chunk starts with length, so read it. This will then subsequently also read the chunk self.httpstream.read_until("\r\n", self._chunk_length) self.reading_chunks = False if self.got_chunk: # the previous read hit the fast path and read from the buffer # instead of going through the main polling loop. This means we # should iteratively issue the next request logger.debug("Fast-Path detected, iterating...") continue else: break # if we arrive here, we read the complete request or # the ioloop has scheduled another call to read_chunks 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 _chunk_length(self, data): """Received the chunk length"""
assert data[-2:] == "\r\n", "CRLF" length = data[:-2].split(';')[0] # cut off optional length paramters length = int(length.strip(), 16) # length is in hex if length: logger.debug('Got chunk length: %d', length) self.httpstream.read_bytes(length + 2, self._chunk_data) else: logger.debug('Got last chunk (size 0)') self.got_request = True # enable input write event so the handler can finish things up # when it has written all pending data self.ioloop.update_handler(self.fd_stdin, self.ioloop.WRITE | self.ioloop.ERROR)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _chunk_data(self, data): """Received chunk data"""
assert data[-2:] == "\r\n", "CRLF" if self.gzip_decompressor: if not self.gzip_header_seen: assert data[:2] == '\x1f\x8b', "gzip header" self.gzip_header_seen = True self.process_input_buffer += self.gzip_decompressor.decompress(data[:-2]) else: self.process_input_buffer += data[:-2] self.got_chunk = True if self.process_input_buffer: # since we now have data in the buffer, enable write events again logger.debug('Got data in buffer, interested in writing to process again') self.ioloop.update_handler(self.fd_stdin, self.ioloop.WRITE | self.ioloop.ERROR) # do NOT call read_chunks directly. This is to give git a chance to consume input. # we don't want to grow the buffer unnecessarily. # Additionally, this should mitigate the stack explosion mentioned in read_chunks self.ioloop.add_callback(self.read_chunks)
<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_stdin_event(self, fd, events): """Eventhandler for stdin"""
assert fd == self.fd_stdin if events & self.ioloop.ERROR: # An error at the end is expected since tornado maps HUP to ERROR logger.debug('Error on stdin') # ensure pipe is closed if not self.process.stdin.closed: self.process.stdin.close() # remove handler self.ioloop.remove_handler(self.fd_stdin) # if all fds are closed, we can finish return self._graceful_finish() # got data ready logger.debug('stdin ready for write') if self.process_input_buffer: count = os.write(fd, self.process_input_buffer) logger.debug('Wrote first %d bytes of %d total', count, len(self.process_input_buffer)) self.process_input_buffer = self.process_input_buffer[count:] if not self.process_input_buffer: # consumed everything in the buffer if self.got_request: # we got the request and wrote everything to the process # this means we can close stdin and stop handling events # for it logger.debug('Got complete request, closing stdin') self.process.stdin.close() self.ioloop.remove_handler(fd) else: # There is more data bound to come from the client # so just disable write events for the moment until # we got more to write logger.debug('Not interested in write events on stdin anymore') self.ioloop.update_handler(fd, self.ioloop.ERROR)
<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_stdout_event(self, fd, events): """Eventhandler for stdout"""
assert fd == self.fd_stdout if events & self.ioloop.READ: # got data ready to read data = '' # Now basically we have two cases: either the client supports # HTTP/1.1 in which case we can stream the answer in chunked mode # in HTTP/1.0 we need to send a content-length and thus buffer the complete output if self.request.supports_http_1_1(): if not self.headers_sent: self.sent_chunks = True self.headers.update({'Date': get_date_header(), 'Transfer-Encoding': 'chunked'}) data = 'HTTP/1.1 200 OK\r\n' + '\r\n'.join([ k + ': ' + v for k, v in self.headers.items()]) + '\r\n\r\n' if self.output_prelude: data += hex(len(self.output_prelude))[2:] + "\r\n" # cut off 0x data += self.output_prelude + "\r\n" self.headers_sent = True payload = os.read(fd, 8192) if events & self.ioloop.ERROR: # there might be data remaining in the buffer if we got HUP, get it all remainder = True while remainder != '': # until EOF remainder = os.read(fd, 8192) payload += remainder data += hex(len(payload))[2:] + "\r\n" # cut off 0x data += payload + "\r\n" else: if not self.headers_sent: # Use the over-eager blocking read that will get everything until we hit EOF # this might actually be somewhat dangerous as noted in the subprocess documentation # and lead to a deadlock. This is only a legacy mode for HTTP/1.0 clients anyway, # so we might want to remove it entirely anyways payload = self.process.stdout.read() self.headers.update({'Date': get_date_header(), 'Content-Length': str(len(payload))}) data = 'HTTP/1.0 200 OK\r\n' + '\r\n'.join([ k + ': ' + v for k, v in self.headers.items()]) + '\r\n\r\n' self.headers_sent = True data += self.output_prelude + payload else: # this is actually somewhat illegal as it messes with content-length but # it shouldn't happen anyways, as the read above should have read anything # python docs say this can happen on ttys... logger.error("This should not happen") data = self.process.stdout.read() if len(data) == 8200: self.number_of_8k_chunks_sent += 1 else: if self.number_of_8k_chunks_sent > 0: logger.debug('Sent %d * 8192 bytes', self.number_of_8k_chunks_sent) self.number_of_8k_chunks_sent = 0 logger.debug('Sending stdout to client %d bytes: %r', len(data), data[:20]) self.request.write(data) # now we can also have an error. This is because tornado maps HUP onto error # therefore, no elif here! if events & self.ioloop.ERROR: logger.debug('Error on stdout') # ensure file is closed if not self.process.stdout.closed: self.process.stdout.close() # remove handler self.ioloop.remove_handler(self.fd_stdout) # if all fds are closed, we can finish return self._graceful_finish()
<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_stderr_event(self, fd, events): """Eventhandler for stderr"""
assert fd == self.fd_stderr if events & self.ioloop.READ: # got data ready if not self.headers_sent: payload = self.process.stderr.read() data = 'HTTP/1.1 500 Internal Server Error\r\nDate: %s\r\nContent-Length: %d\r\n\r\n' % (get_date_header(), len(payload)) self.headers_sent = True data += payload else: # see stdout logger.error("This should not happen (stderr)") data = self.process.stderr.read() logger.debug('Sending stderr to client: %r', data) self.request.write(data) if events & self.ioloop.ERROR: logger.debug('Error on stderr') # ensure file is closed if not self.process.stderr.closed: self.process.stderr.close() # remove handler self.ioloop.remove_handler(self.fd_stderr) # if all fds are closed, we can finish return self._graceful_finish()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _graceful_finish(self): """Detect if process has closed pipes and we can finish"""
if not self.process.stdout.closed or not self.process.stderr.closed: return # stdout/stderr still open if not self.process.stdin.closed: self.process.stdin.close() if self.number_of_8k_chunks_sent > 0: logger.debug('Sent %d * 8k chunks', self.number_of_8k_chunks_sent) logger.debug("Finishing up. Process poll: %r", self.process.poll()) if not self.headers_sent: retval = self.process.poll() if retval != 0: logger.warning("Empty response. Git return value: " + str(retval)) payload = "Did not produce any data. Errorcode: " + str(retval) data = 'HTTP/1.1 500 Internal Server Error\r\nDate: %s\r\nContent-Length: %d\r\n\r\n' % (get_date_header(), len(payload)) self.headers_sent = True data += payload self.request.write(data) else: data = 'HTTP/1.1 200 Ok\r\nDate: %s\r\nContent-Length: 0\r\n\r\n' % get_date_header() self.headers_sent = True self.request.write(data) # if we are in chunked mode, send end chunk with length 0 elif self.sent_chunks: logger.debug("End chunk") self.request.write("0\r\n") #we could now send some more headers resp. trailers self.request.write("\r\n") self.request.finish()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _genTimeoutList(self, const): """ Generates a dict of the valid timeout values for the given `const`. The `const` value may change for different versions or types of Pololu boards. """
result = {} for v in range(128): x = v & 0x0F y = (v >> 4) & 0x07 if not y or (y and x > 7): result[const * x * 2**y] = v self._log and self._log.debug("Timeout list: %s", result) return result
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def findConnectedDevices(self): """ Find all the devices on the serial buss and store the results in a class member object. """
tmpTimeout = self._serial.timeout self._serial.timeout = 0.01 for dev in range(128): device = self._getDeviceID(dev) if device is not None and int(device) not in self._deviceConfig: config = self._deviceConfig.setdefault(int(device), {}) self._deviceCallback(device, config) self._log and self._log.info( "Found device '%s' with configuration: %s", device, config) self._serial.timeout = tmpTimeout
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def setCompactProtocol(self): """ Set the compact protocol. """
self._compact = True self._serial.write(bytes(self._BAUD_DETECT)) self._log and self._log.debug("Compact protocol has been set.")
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def setPololuProtocol(self): """ Set the pololu protocol. """
self._compact = False self._log and self._log.debug("Pololu protocol has been set.")
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _writeData(self, command, device, params=()): """ Write the data to the device. :Parameters: command : `int` The command to write to the device. device : `int` The device is the integer number of the hardware devices ID and is only used with the Pololu Protocol. params : `tuple` Sequence of bytes to write. :Exceptions: * `SerialTimeoutException` If the low level serial package times out. * `SerialException` IO error when the port is not open. """
sequence = [] if self._compact: sequence.append(command | 0x80) else: sequence.append(self._BAUD_DETECT) sequence.append(device) sequence.append(command) for param in params: sequence.append(param) if self._crc: sequence.append(crc7(sequence)) self._serial.write(bytearray(sequence)) self._log and self._log.debug("Wrote byte sequence: %s", [hex(num) for num in sequence])
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _getFirmwareVersion(self, device): """ Get the firmware version. :Parameters: device : `int` The device is the integer number of the hardware devices ID and is only used with the Pololu Protocol. :Returns: An integer indicating the version number. """
cmd = self._COMMAND.get('get-fw-version') self._writeData(cmd, device) try: result = self._serial.read(size=1) result = int(result) except serial.SerialException as e: self._log and self._log.error("Error: %s", e, exc_info=True) raise e except ValueError as e: result = None return result
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _getError(self, device, message): """ Get the error message or value stored in the Qik hardware. :Parameters: device : `int` The device is the integer number of the hardware devices ID and is only used with the Pololu Protocol. message : `bool` If set to `True` a text message will be returned, if set to `False` the integer stored in the Qik will be returned. :Returns: A list of text messages, integers, or and empty list. See the `message` parameter above. """
cmd = self._COMMAND.get('get-error') self._writeData(cmd, device) result = [] bits = [] try: num = self._serial.read(size=1) num = ord(num) except serial.SerialException as e: self._log and self._log.error("Error: %s", e, exc_info=True) raise e except TypeError as e: num = 0 for i in range(7, -1, -1): bit = num & (1 << i) if bit: if message: result.append(self._ERRORS.get(bit)) else: result.append(bit) return result
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _getConfig(self, num, device): """ Low level method used for all get config commands. :Parameters: num : `int` Number that indicates the config option to get from the hardware. device : `int` The device is the integer number of the hardware devices ID and is only used with the Pololu Protocol. :Returns: An integer representing the value stored in the hardware device. """
cmd = self._COMMAND.get('get-config') self._writeData(cmd, device, params=(num,)) try: result = self._serial.read(size=1) result = ord(result) except serial.SerialException as e: self._log and self._log.error("Error: %s", e, exc_info=True) raise e except TypeError as e: result = None return result
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _getPWMFrequency(self, device, message): """ Get the PWM frequency stored on the hardware device. :Parameters: device : `int` The device is the integer number of the hardware devices ID and is only used with the Pololu Protocol. message : `bool` If set to `True` a text message will be returned, if set to `False` the integer stored in the Qik will be returned. :Returns: A text message or an int. See the `message` parameter above. """
result = self._getConfig(self.PWM_PARAM, device) freq, msg = self._CONFIG_PWM.get(result, (result, 'Invalid Frequency')) if message: result = msg else: result = freq return result
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _getSerialTimeout(self, device): """ Get the serial timeout stored on the hardware device. Caution, more that one value returned from the Qik can have the same actual timeout value according the the formula below. I have verified this as an idiosyncrasy of the Qik itself. There are only a total of 72 unique values that the Qik can logically use the remaining 56 values are repeats of the 72. :Parameters: device : `int` The device is the integer number of the hardware devices ID and is only used with the Pololu Protocol. :Returns: The timeout value in seconds. """
num = self._getConfig(self.SERIAL_TIMEOUT, device) if isinstance(num, int): x = num & 0x0F y = (num >> 4) & 0x07 result = self.DEFAULT_SERIAL_TIMEOUT * x * pow(2, y) else: result = num return result
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _setConfig(self, num, value, device, message): """ Low level method used for all set config commands. :Parameters: num : `int` Number that indicates the config option to get from the hardware. value : `int` The value to set in the hardware device. device : `int` The device is the integer number of the hardware devices ID and is only used with the Pololu Protocol. message : `bool` If set to `True` a text message will be returned, if set to `False` the integer stored in the Qik will be returned. :Returns: A text message or an int. See the `message` parameter above. :Exceptions: * `SerialException` IO error indicating there was a problem reading from the serial connection. """
cmd = self._COMMAND.get('set-config') self._writeData(cmd, device, params=(num, value, 0x55, 0x2A)) try: result = self._serial.read(size=1) result = ord(result) except serial.SerialException as e: self._log and self._log.error("Error: %s", e, exc_info=True) raise e except TypeError as e: result = None if result is not None and message: result = self._CONFIG_RETURN.get( result, 'Unknown return value: {}'.format(result)) return result
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _setSpeed(self, speed, motor, device): """ Set motor speed. This method takes into consideration the PWM frequency that the hardware is currently running at and limits the values passed to the hardware accordingly. :Parameters: speed : `int` Motor speed as an integer. Negative numbers indicate reverse speeds. motor : `str` A string value indicating the motor to set the speed on. device : `int` The device is the integer number of the hardware devices ID and is only used with the Pololu Protocol. """
reverse = False if speed < 0: speed = -speed reverse = True # 0 and 2 for Qik 2s9v1, 0, 2, and 4 for 2s12v10 if self._deviceConfig[device]['pwm'] in (0, 2, 4,) and speed > 127: speed = 127 if speed > 127: if speed > 255: speed = 255 if reverse: cmd = self._COMMAND.get('{}-reverse-8bit'.format(motor)) else: cmd = self._COMMAND.get('{}-forward-8bit'.format(motor)) speed -= 128 else: if reverse: cmd = self._COMMAND.get('{}-reverse-7bit'.format(motor)) else: cmd = self._COMMAND.get('{}-forward-7bit'.format(motor)) if not cmd: msg = "Invalid motor specified: {}".format(motor) self._log and self._log.error(msg) raise ValueError(msg) self._writeData(cmd, device, params=(speed,))
<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_key_names(self): """ Gets keys of all elements stored in this map. :return: a list with all map keys. """
names = [] for (k, _) in self.items(): names.append(k) return names
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def append(self, map): """ Appends new elements to this map. :param map: a map with elements to be added. """
if isinstance(map, dict): for (k, v) in map.items(): key = StringConverter.to_string(k) value = v self.put(key, 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 set_as_object(self, value): """ Sets a new value to map element :param value: a new element or map value. """
self.clear() map = MapConverter.to_map(value) self.append(map)
<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_as_nullable_string(self, key): """ Converts map element into a string or returns None if conversion is not possible. :param key: an index of element to get. :return: string value of the element or None if conversion is not supported. """
value = self.get(key) return StringConverter.to_nullable_string(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 get_as_string(self, key): """ Converts map element into a string or returns "" if conversion is not possible. :param key: an index of element to get. :return: string value ot the element or "" if conversion is not supported. """
value = self.get(key) return StringConverter.to_string(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 get_as_string_with_default(self, key, default_value): """ Converts map element into a string or returns default value if conversion is not possible. :param key: an index of element to get. :param default_value: the default value :return: string value ot the element or default value if conversion is not supported. """
value = self.get(key) return StringConverter.to_string_with_default(value, default_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 get_as_nullable_boolean(self, key): """ Converts map element into a boolean or returns None if conversion is not possible :param key: an index of element to get. :return: boolean value of the element or None if conversion is not supported. """
value = self.get(key) return BooleanConverter.to_nullable_boolean(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 get_as_boolean(self, key): """ Converts map element into a boolean or returns false if conversion is not possible. :param key: an index of element to get. :return: boolean value ot the element or false if conversion is not supported. """
value = self.get(key) return BooleanConverter.to_boolean(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 get_as_boolean_with_default(self, key, default_value): """ Converts map element into a boolean or returns default value if conversion is not possible. :param key: an index of element to get. :param default_value: the default value :return: boolean value ot the element or default value if conversion is not supported. """
value = self.get(key) return BooleanConverter.to_boolean_with_default(value, default_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 get_as_nullable_integer(self, key): """ Converts map element into an integer or returns None if conversion is not possible. :param key: an index of element to get. :return: integer value of the element or None if conversion is not supported. """
value = self.get(key) return IntegerConverter.to_nullable_integer(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 get_as_integer(self, key): """ Converts map element into an integer or returns 0 if conversion is not possible. :param key: an index of element to get. :return: integer value ot the element or 0 if conversion is not supported. """
value = self.get(key) return IntegerConverter.to_integer(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 get_as_integer_with_default(self, key, default_value): """ Converts map element into an integer or returns default value if conversion is not possible. :param key: an index of element to get. :param default_value: the default value :return: integer value ot the element or default value if conversion is not supported. """
value = self.get(key) return IntegerConverter.to_integer_with_default(value, default_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 get_as_nullable_float(self, key): """ Converts map element into a float or returns None if conversion is not possible. :param key: an index of element to get. :return: float value of the element or None if conversion is not supported. """
value = self.get(key) return FloatConverter.to_nullable_float(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 get_as_float(self, key): """ Converts map element into a float or returns 0 if conversion is not possible. :param key: an index of element to get. :return: float value ot the element or 0 if conversion is not supported. """
value = self.get(key) return FloatConverter.to_float(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 get_as_float_with_default(self, key, default_value): """ Converts map element into a float or returns default value if conversion is not possible. :param key: an index of element to get. :param default_value: the default value :return: float value ot the element or default value if conversion is not supported. """
value = self.get(key) return FloatConverter.to_float_with_default(value, default_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 get_as_nullable_datetime(self, key): """ Converts map element into a Date or returns None if conversion is not possible. :param key: an index of element to get. :return: Date value of the element or None if conversion is not supported. """
value = self.get(key) return DateTimeConverter.to_nullable_datetime(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 get_as_datetime(self, key): """ Converts map element into a Date or returns the current date if conversion is not possible. :param key: an index of element to get. :return: Date value ot the element or the current date if conversion is not supported. """
value = self.get(key) return DateTimeConverter.to_datetime(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 get_as_datetime_with_default(self, key, default_value): """ Converts map element into a Date or returns default value if conversion is not possible. :param key: an index of element to get. :param default_value: the default value :return: Date value ot the element or default value if conversion is not supported. """
value = self.get(key) return DateTimeConverter.to_datetime_with_default(value, default_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 get_as_nullable_type(self, key, value_type): """ Converts map element into a value defined by specied typecode. If conversion is not possible it returns None. :param key: an index of element to get. :param value_type: the TypeCode that defined the type of the result :return: element value defined by the typecode or None if conversion is not supported. """
value = self.get(key) return TypeConverter.to_nullable_type(value_type, 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 get_as_type(self, key, value_type): """ Converts map element into a value defined by specied typecode. If conversion is not possible it returns default value for the specified type. :param key: an index of element to get. :param value_type: the TypeCode that defined the type of the result :return: element value defined by the typecode or default if conversion is not supported. """
value = self.get(key) return TypeConverter.to_type(value_type, 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 get_as_type_with_default(self, key, value_type, default_value): """ Converts map element into a value defined by specied typecode. If conversion is not possible it returns default value. :param key: an index of element to get. :param value_type: the TypeCode that defined the type of the result :param default_value: the default value :return: element value defined by the typecode or default value if conversion is not supported. """
value = self.get(key) return TypeConverter.to_type_with_default(value_type, value, default_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 get_as_nullable_map(self, key): """ Converts map element into an AnyValueMap or returns None if conversion is not possible. :param key: a key of element to get. :return: AnyValueMap value of the element or None if conversion is not supported. """
value = self.get_as_object(key) return AnyValueMap.from_value(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 get_as_map_with_default(self, key, default_value): """ Converts map element into an AnyValueMap or returns default value if conversion is not possible. :param key: a key of element to get. :param default_value: the default value :return: AnyValueMap value of the element or default value if conversion is not supported. """
value = self.get_as_nullable_map(key) return MapConverter.to_map_with_default(value, default_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 open(url): """ Launches browser depending on os """
if sys.platform == 'win32': os.startfile(url) elif sys.platform == 'darwin': subprocess.Popen(['open', url]) else: try: subprocess.Popen(['xdg-open', url]) except OSError: import webbrowser webbrowser.open(url)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def print_arguments(): """ Decorator that provides the wrapped function with an attribute 'print_arguments' containing just those keyword arguments actually passed in to the function. To use the decorator for debugging, preface the function into whose calls you are interested with '@print_arguments()' """
def decorator(function): def inner(*args, **kwargs): if args: print "Passed arguments:" for i in args: pp.pprint(i) print "Passed keyword arguments:" pp.pprint(kwargs) return function(*args, **kwargs) return inner return decorator
<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_subservice(self, obj): """Add a sub-service object. :param obj: stackinabox.services.StackInABoxService instance :raises: RouteAlreadyRegisteredError if the route is already registered :returns: n/a """
# ensure there is not already a sub-service if self.obj is not None: raise RouteAlreadyRegisteredError( 'Service Router ({0} - {1}): Route {2} already has a ' 'sub-service handler' .format(id(self), self.service_name, self.uri)) # warn if any methods are already registered if len(self.methods): logger.debug( 'WARNING: Service Router ({0} - {1}): Methods detected ' 'on Route {2}. Sub-Service {3} may be hidden.' .format(id(self), self.service_name, self.uri, obj.name)) # Ensure we do not have any circular references assert(obj != self.parent_obj) # if no errors, save the object and update the URI self.obj = obj self.obj.base_url = '{0}/{1}'.format(self.uri, self.service_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 update_uris(self, new_uri): """Update all URIS. :param new_uri: URI to switch to and update the matching :returns: n/a Note: This overwrites any existing URI """
self.uri = new_uri # if there is a sub-service, update it too if self.obj: self.obj.base_url = '{0}/{1}'.format(self.uri, self.service_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 register_method(self, method, fn): """Register an HTTP method and handler function. :param method: string, HTTP verb :param fn: python function handling the request :raises: RouteAlreadyRegisteredError if the route is already registered :returns: n/a """
# ensure the HTTP verb is not already registered if method not in self.methods.keys(): logger.debug('Service Router ({0} - {1}): Adding method {2} on ' 'route {3}' .format(id(self), self.service_name, method, self.uri)) self.methods[method] = fn else: raise RouteAlreadyRegisteredError( 'Service Router ({0} - {1}): Method {2} already registered ' 'on Route {3}' .format(id(self), self.service_name, method, self.uri))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def validate_regex(regex, sub_service): """Is the regex valid for StackInABox routing? :param regex: Python regex object to match the URI :param sub_service: boolean for whether or not the regex is for a sub-service :raises: InvalidRouteRegexError if the regex does not meet the requirements. """
# The regex generated by stackinabox starts with ^ # and ends with $. Enforce that the provided regex does the same. if regex.pattern.startswith('^') is False: logger.debug('StackInABoxService: Pattern must start with ^') raise InvalidRouteRegexError('Pattern must start with ^') # Note: pattern may end with $ even if sub_service is True if regex.pattern.endswith('$') is False and sub_service is False: logger.debug('StackInABoxService: Pattern must end with $') raise InvalidRouteRegexError('Pattern must end with $') # Enforce that if the pattern does not end with $ that it is a service if regex.pattern.endswith('$') is True and sub_service is True: logger.debug( 'StackInABoxService: Sub-Service RegEx Pattern must not ' 'end with $') raise InvalidRouteRegexError('Pattern must end with $')
<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_service_regex(base_url, service_url, sub_service): """Get the regex for a given service. :param base_url: string - Base URI :param service_url: string - Service URI under the Base URI :param sub_service: boolean - is the Service URI for a sub-service? :returns: Python Regex object containing the regex for the Service """
# if the specified service_url is already a regex # then just use. Otherwise create what we need if StackInABoxService.is_regex(service_url): logger.debug('StackInABoxService: Received regex {0} for use...' .format(service_url.pattern)) # Validate the regex against StackInABoxService requirement StackInABoxService.validate_regex(service_url, sub_service) return service_url else: regex = '^{0}{1}$'.format('', service_url) logger.debug('StackInABoxService: {0} + {1} -> {2}' .format(base_url, service_url, regex)) return re.compile(regex)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def base_url(self, value): """Set the Base URI value. :param value: the new URI to use for the Base URI """
logger.debug('StackInABoxService ({0}:{1}) Updating Base URL ' 'from {2} to {3}' .format(self.__id, self.name, self.__base_url, value)) self.__base_url = value for k, v in six.iteritems(self.routes): v['regex'] = StackInABoxService.get_service_regex( value, v['uri'], v['handlers'].is_subservice)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def reset(self): """Reset the service to its' initial state."""
logger.debug('StackInABoxService ({0}): Reset' .format(self.__id, self.name)) self.base_url = '/{0}'.format(self.name) logger.debug('StackInABoxService ({0}): Hosting Service {1}' .format(self.__id, self.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 try_handle_route(self, route_uri, method, request, uri, headers): """Try to handle the supplied request on the specified routing URI. :param route_uri: string - URI of the request :param method: string - HTTP Verb :param request: request object describing the HTTP request :param uri: URI of the reuqest :param headers: case-insensitive headers dict :returns: tuple - (int, dict, string) containing: int - the http response status code dict - the headers for the http response string - http string response """
uri_path = route_uri if '?' in uri: logger.debug('StackInABoxService ({0}:{1}): Found query string ' 'removing for match operation.' .format(self.__id, self.name)) uri_path, uri_qs = uri.split('?') logger.debug('StackInABoxService ({0}:{1}): uri = "{2}", ' 'query = "{3}"' .format(self.__id, self.name, uri_path, uri_qs)) for k, v in six.iteritems(self.routes): logger.debug('StackInABoxService ({0}:{1}): Checking if ' 'route {2} handles...' .format(self.__id, self.name, v['uri'])) logger.debug('StackInABoxService ({0}:{1}): ...using regex ' 'pattern {2} against {3}' .format(self.__id, self.name, v['regex'].pattern, uri_path)) if v['regex'].match(uri_path): logger.debug('StackInABoxService ({0}:{1}): Checking if ' 'route {2} handles method {2}...' .format(self.__id, self.name, v['uri'], method)) return v['handlers'](method, request, uri, headers) return (595, headers, 'Route ({0}) Not Handled'.format(uri))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def sub_request(self, method, request, uri, headers): """Handle the supplied sub-service request on the specified routing URI. :param method: string - HTTP Verb :param request: request object describing the HTTP request :param uri: URI of the reuqest :param headers: case-insensitive headers dict :returns: tuple - (int, dict, string) containing: int - the http response status code dict - the headers for the http response string - http string response """
logger.debug('StackInABoxService ({0}:{1}): Sub-Request Received ' '{2} - {3}' .format(self.__id, self.name, method, uri)) return self.request(method, request, uri, headers)
<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_route(self, uri, sub_service): """Create the route for the URI. :param uri: string - URI to be routed :param sub_service: boolean - is the URI for a sub-service :returns: n/a """
if uri not in self.routes.keys(): logger.debug('Service ({0}): Creating routes' .format(self.name)) self.routes[uri] = { 'regex': StackInABoxService.get_service_regex(self.base_url, uri, sub_service), 'uri': uri, 'handlers': StackInABoxServiceRouter(self.name, uri, None, 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 register(self, method, uri, call_back): """Register a class instance function to handle a request. :param method: string - HTTP Verb :param uri: string - URI for the request :param call_back: class instance function that handles the request :returns: n/a """
found = False self.create_route(uri, False) self.routes[uri]['handlers'].register_method(method, call_back)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def register_subservice(self, uri, service): """Register a class instance to handle a URI. :param uri: string - URI for the request :param service: StackInABoxService object instance that handles the request :returns: n/a """
found = False self.create_route(uri, True) self.routes[uri]['handlers'].set_subservice(service)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def pullup(self, pin, enabled): """Turn on the pull-up resistor for the specified pin if enabled is True, otherwise turn off the pull-up resistor. """
self._validate_channel(pin) if enabled: self.gppu[int(pin/8)] |= 1 << (int(pin%8)) else: self.gppu[int(pin/8)] &= ~(1 << (int(pin%8))) self._write_gppu()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _write_gpio(self, gpio=None): """Write the specified byte value to the GPIO registor. If no value specified the current buffered value will be written. """
if gpio is not None: self.gpio = gpio self.i2c.write_list(self.GPIO, self.gpio)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _write_iodir(self, iodir=None): """Write the specified byte value to the IODIR registor. If no value specified the current buffered value will be written. """
if iodir is not None: self.iodir = iodir self.i2c.write_list(self.IODIR, self.iodir)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _write_gppu(self, gppu=None): """Write the specified byte value to the GPPU registor. If no value specified the current buffered value will be written. """
if gppu is not None: self.gppu = gppu self.i2c.write_list(self.GPPU, self.gppu)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def getJson(url): """Download json and return simplejson object"""
site = urllib2.urlopen(url, timeout=300) return json.load(site)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def getWeb(url, isFeed): """Download url and parse it with lxml. If "isFeed" is True returns lxml.etree else, returns lxml.html """
socket.setdefaulttimeout(300) loadedWeb = urllib2.build_opener() loadedWeb.addheaders = getHeaders() if isFeed: web = etree.parse(loadedWeb.open(url)) else: web = html.parse(loadedWeb.open(url)) return web
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def rmSelf(f): """f -> function. Decorator, removes first argument from f parameters. """
def new_f(*args, **kwargs): newArgs = args[1:] result = f(*newArgs, **kwargs) return result return new_f
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def __builder_connect_pending_signals(self): """Called internally to actually make the internal Gtk.Builder instance connect all signals found in controllers controlling self."""
class _MultiHandlersProxy (object): def __init__(self, funcs): self.funcs = funcs def __call__(self, *args, **kwargs): # according to gtk documentation, the return value of # a signal is the return value of the last executed # handler for func in self.funcs: res = func(*args, **kwargs) return res final_dict = {n: (v.pop() if len(v) == 1 else _MultiHandlersProxy(v)) for n, v in self.builder_pending_callbacks.items()} self._builder.connect_signals(final_dict) self.builder_connected = True self.builder_pending_callbacks = {}
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _builder_connect_signals(self, _dict): """Called by controllers which want to autoconnect their handlers with signals declared in internal Gtk.Builder. This method accumulates handlers, and books signal autoconnection later on the idle of the next occurring gtk loop. After the autoconnection is done, this method cannot be called anymore."""
assert not self.builder_connected, "Gtk.Builder not already connected" if _dict and not self.builder_pending_callbacks: # this is the first call, book the builder connection for # later gtk loop GLib.idle_add(self.__builder_connect_pending_signals) for n, v in _dict.items(): if n not in self.builder_pending_callbacks: _set = set() self.builder_pending_callbacks[n] = _set else: _set = self.builder_pending_callbacks[n] _set.add(v)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def __extract_autoWidgets(self): """Extract autoWidgets map if needed, out of the glade specifications and gtk builder"""
if self.__autoWidgets_calculated: return if self._builder is not None: for wid in self._builder.get_objects(): # General workaround for issue # https://bugzilla.gnome.org/show_bug.cgi?id=607492 try: name = Gtk.Buildable.get_name(wid) except TypeError: continue if name in self.autoWidgets and self.autoWidgets[name] != wid: raise ViewError("Widget '%s' in builder also found in " "glade specification" % name) self.autoWidgets[name] = wid self.__autowidgets_calculated = 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 clef_error_check(func_to_decorate): """Return JSON decoded response from API call. Handle errors when bad response encountered."""
def wrapper(*args, **kwargs): try: response = func_to_decorate(*args, **kwargs) except requests.exceptions.RequestException: raise ConnectionError( 'Clef encountered a network connectivity problem. Are you sure you are connected to the Internet?' ) else: raise_right_error(response) return response.json() # decode json return wrapper
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def raise_right_error(response): """Raise appropriate error when bad response received."""
if response.status_code == 200: return if response.status_code == 500: raise ServerError('Clef servers are down.') if response.status_code == 403: message = response.json().get('error') error_class = MESSAGE_TO_ERROR_MAP[message] if error_class == InvalidOAuthTokenError: message = 'Something went wrong at Clef. Unable to retrieve user information with this token.' raise error_class(message) if response.status_code == 400: message = response.json().get('error') error_class = MESSAGE_TO_ERROR_MAP[message] if error_class: raise error_class(message) else: raise InvalidLogoutTokenError(message) if response.status_code == 404: raise NotFoundError('Unable to retrieve the page. Are you sure the Clef API endpoint is configured right?') raise APIError
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _call(self, method, url, params): """Return response from Clef API call."""
request_params = {} if method == 'GET': request_params['params'] = params elif method == 'POST': request_params['data'] = params response = requests.request(method, url, **request_params) return 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 get_login_information(self, code=None): """Return Clef user info after exchanging code for OAuth token."""
# do the handshake to get token access_token = self._get_access_token(code) # make request with token to get user details return self._get_user_info(access_token)
<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_user_info(self, access_token): """Return Clef user info."""
info_response = self._call('GET', self.info_url, params={'access_token': access_token}) user_info = info_response.get('info') return user_info
<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_logout_information(self, logout_token): """Return Clef user info after exchanging logout token."""
data = dict(logout_token=logout_token, app_id=self.app_id, app_secret=self.app_secret) logout_response = self._call('POST', self.logout_url, params=data) clef_user_id = logout_response.get('clef_id') return clef_user_id
<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_observing_method(self, prop_names, method): """ Remove dynamic notifications. *method* a callable that was registered with :meth:`observe`. *prop_names* a sequence of strings. This need not correspond to any one `observe` call. .. note:: This can revert even the effects of decorator `observe` at runtime. Don't. """
for prop_name in prop_names: if prop_name in self.__PROP_TO_METHS: # exact match self.__PROP_TO_METHS[prop_name].remove(method) del self.__PAT_METH_TO_KWARGS[(prop_name, method)] elif method in self.__METH_TO_PAT: # found a pattern matching pat = self.__METH_TO_PAT[method] if fnmatch.fnmatch(prop_name, pat): del self.__METH_TO_PAT[method] self.__PAT_TO_METHS[pat].remove(method) del self.__PAT_METH_TO_KWARGS[(pat, 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 is_observing_method(self, prop_name, method): """ Returns `True` if the given method was previously added as an observing method, either dynamically or via decorator. """
if (prop_name, method) in self.__PAT_METH_TO_KWARGS: return True if method in self.__METH_TO_PAT: pat = self.__METH_TO_PAT[method] if fnmatch.fnmatch(prop_name, pat): return True return False
<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_data(self, column, value, role): """Set the data for the given column to value The default implementation returns False :param column: the column to set :type column: int :param value: the value to set :param role: the role, usually EditRole :type role: :class:`QtCore.Qt.ItemDataRole` :returns: True, if editing was successfull :rtype: :class:`bool` :raises: None """
if role == QtCore.Qt.EditRole or role == QtCore.Qt.DisplayRole: self._list[column] = value return True else: return False
<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_model(self, model): """Set the model the item belongs to A TreeItem can only belong to one model. :param model: the model the item belongs to :type model: :class:`Treemodel` :returns: None :rtype: None :raises: None """
self._model = model for c in self.childItems: c.set_model(model)
<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_child(self, child): """Add child to children of this TreeItem :param child: the child TreeItem :type child: :class:`TreeItem` :returns: None :rtype: None :raises: None """
child.set_model(self._model) if self._model: row = len(self.childItems) parentindex = self._model.index_of_item(self) self._model.insertRow(row, child, parentindex) else: self.childItems.append(child)
<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_child(self, child): """Remove the child from this TreeItem :param child: the child TreeItem :type child: :class:`TreeItem` :returns: None :rtype: None :raises: ValueError """
child.set_model(None) if self._model: row = self.childItems.index(child) parentindex = self._model.index_of_item(self) self._model.removeRow(row, parentindex) else: self.childItems.remove(child)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def column_count(self, ): """Return the number of columns that the children have If there are no children, return the column count of its own data. :returns: the column count of the children data :rtype: int :raises: None """
if self.child_count(): return self.childItems[0]._data.column_count() else: return self._data.column_count() if self._data else 0
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def data(self, column, role): """Return the data for the column and role :param column: the data column :type column: int :param role: the data role :type role: QtCore.Qt.ItemDataRole :returns: data depending on the role :rtype: :raises: None """
if self._data is not None and (column >= 0 or column < self._data.column_count()): return self._data.data(column, role)
<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_data(self, column, value, role): """Set the data of column to value :param column: the column to set :type column: int :param value: the value to set :param role: the role, usually EditRole :type role: :class:`QtCore.Qt.ItemDataRole` :returns: True, if data successfully changed :rtype: :class:`bool` :raises: None """
if not self._data or column >= self._data.column_count(): return False return self._data.set_data(column, value, role)
<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_parent(self, parent): """Set the parent of the treeitem :param parent: parent treeitem :type parent: :class:`TreeItem` | None :returns: None :rtype: None :raises: None """
if self._parent == parent: return if self._parent: self._parent.remove_child(self) self._parent = parent if parent: parent.add_child(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 rowCount(self, parent): """Return the number of rows under the given parent. When the parent is valid return rowCount the number of children of parent. :param parent: the parent index :type parent: :class:`QtCore.QModelIndex`: :returns: the row count :rtype: int :raises: None """
if parent.column() > 0: return 0 if not parent.isValid(): parentItem = self._root else: parentItem = parent.internalPointer() return parentItem.child_count()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def columnCount(self, parent): """Return the number of columns for the children of the given parent. :param parent: the parent index :type parent: :class:`QtCore.QModelIndex`: :returns: the column count :rtype: int :raises: None """
if parent.isValid(): return parent.internalPointer().column_count() else: return self._root.column_count()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def setData(self, index, value, role=QtCore.Qt.EditRole): """Set the data of the given index to value :param index: the index to set :type index: :class:`QtCore.QModelIndex` :param value: the value to set :param role: the role, usually edit role :type role: :data:`QtCore.Qt.ItemDataRole` :returns: True, if successfull, False if unsuccessfull :rtype: :class:`bool` :raises: None """
if not index.isValid(): return False item = index.internalPointer() r = item.set_data(index.column(), value, role) if r: self.dataChanged.emit(index, index) return r
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def headerData(self, section, orientation, role): """Return the header data Will call :meth:`TreeItem.data` of the root :class:`TreeItem` with the given section (column) and role for horizontal orientations. Vertical orientations are numbered. :param section: the section in the header view :type section: int :param orientation: vertical or horizontal orientation :type orientation: :data:`QtCore.Qt.Vertical` | :data:`QtCore.Qt.Horizontal` :param role: the data role. :type role: :data:`QtCore.Qt.ItemDataRole` :returns: data for the header :raises: None """
if orientation == QtCore.Qt.Horizontal: d = self._root.data(section, role) if d is None and role == QtCore.Qt.DisplayRole: return str(section+1) return d if orientation == QtCore.Qt.Vertical and role == QtCore.Qt.DisplayRole: return str(section+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 insertRow(self, row, item, parent): """Insert a single item before the given row in the child items of the parent specified. :param row: the index where the rows get inserted :type row: int :param item: the item to insert. When creating the item, make sure it's parent is None. If not it will defeat the purpose of this function. :type item: :class:`TreeItem` :param parent: the parent :type parent: :class:`QtCore.QModelIndex` :returns: Returns true if the row is inserted; otherwise returns false. :rtype: bool :raises: None """
item.set_model(self) if parent.isValid(): parentitem = parent.internalPointer() else: parentitem = self._root self.beginInsertRows(parent, row, row) item._parent = parentitem if parentitem: parentitem.childItems.insert(row, item) self.endInsertRows() 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 removeRow(self, row, parent): """Remove row from parent :param row: the row index :type row: int :param parent: the parent index :type parent: :class:`QtCore.QModelIndex` :returns: True if row is inserted; otherwise returns false. :rtype: bool :raises: None """
if parent.isValid(): parentitem = parent.internalPointer() else: parentitem = self._root self.beginRemoveRows(parent, row, row) item = parentitem.childItems[row] item.set_model(None) item._parent = None del parentitem.childItems[row] self.endRemoveRows() 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 flags(self, index): """Return the flags for the given index This will call :meth:`TreeItem.flags` for valid ones. :param index: the index to query :type index: :class:`QtCore.QModelIndex` :returns: None :rtype: None :raises: None """
if index.isValid(): item = index.internalPointer() return item.flags(index) else: super(TreeModel, self).flags(index)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def index_of_item(self, item): """Get the index for the given TreeItem :param item: the treeitem to query :type item: :class:`TreeItem` :returns: the index of the item :rtype: :class:`QtCore.QModelIndex` :raises: ValueError """
# root has an invalid index if item == self._root: return QtCore.QModelIndex() # find all parents to get their index parents = [item] i = item while True: parent = i.parent() # break if parent is root because we got all parents we need if parent == self._root: break if parent is None: # No new parent but last parent wasn't root! # This means that the item was not in the model! return QtCore.QModelIndex() # a new parent was found and we are still not at root # search further until we get to root i = parent parents.append(parent) # get the parent indexes until index = QtCore.QModelIndex() for treeitem in reversed(parents): parent = treeitem.parent() row = parent.childItems.index(treeitem) index = self.index(row, 0, index) return index
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def dict(self, var, default=NOTSET, cast=None, force=True): """Convenience method for casting to a dict Note: Casting """
return self._get(var, default=default, cast={str: cast}, force=force)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def decimal(self, var, default=NOTSET, force=True): """Convenience method for casting to a decimal.Decimal Note: Casting """
return self._get(var, default=default, cast=Decimal, force=force)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def json(self, var, default=NOTSET, force=True): """Get environment variable, parsed as a json string"""
return self._get(var, default=default, cast=json.loads, force=force)
<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_selection(self): """Call selection changed in the beginning, so signals get emitted once Emit shot_taskfile_sel_changed signal and asset_taskfile_sel_changed. :returns: None :raises: None """
si = self.shotverbrws.selected_indexes(0) if si: self.shot_ver_sel_changed(si[0]) else: self.shot_ver_sel_changed(QtCore.QModelIndex()) ai = self.assetverbrws.selected_indexes(0) if ai: self.asset_ver_sel_changed(ai[0]) else: self.asset_ver_sel_changed(QtCore.QModelIndex())
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def setup_releasetype_buttons(self, ): """Create a radio button for every releasetype :returns: None :rtype: None :raises: None """
# we insert the radiobuttons instead of adding them # because there is already a spacer in the layout to # keep the buttons to the left. To maintain the original order # we insert them all to position 0 but in reversed order for rt in reversed(self._releasetypes): rb = QtGui.QRadioButton(rt) self.releasetype_hbox.insertWidget(0, rb) self._releasetype_button_mapping[rt] = rb # set first radiobutton checked if self._releasetypes: rt = self._releasetypes[0] rb = self._releasetype_button_mapping[rt] rb.setChecked(True) # if there is only one releasetype hide the buttons if len(self._releasetypes) == 1: self.releasetype_widget.setVisible(False)