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 reverse_search_history(self, e): # (C-r) u'''Search backward starting at the current line and moving up through the history as necessary. This is an incremental search.''' log("rev_search_history") self._init_incremental_search(self._history.reverse_search_history, e) self.finalize()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def forward_search_history(self, e): # (C-s) u'''Search forward starting at the current line and moving down through the the history as necessary. This is an incremental search.''' log("fwd_search_history") self._init_incremental_search(self._history.forward_search_history, e) self.finalize()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def tab_insert(self, e): # (M-TAB) u'''Insert a tab character. ''' cursor = min(self.l_buffer.point, len(self.l_buffer.line_buffer)) ws = ' ' * (self.tabstop - (cursor % self.tabstop)) self.insert_text(ws) self.finalize()
<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(filename, task, alias): """Creates a gptool help xml file."""
metadata = ET.Element('metadata', {'xml:lang': 'en'}) tool = ET.SubElement(metadata, 'tool', name=task.name, displayname=task.display_name, toolboxalias=alias) summary = ET.SubElement(tool, 'summary') summary.text = ''.join((HTML_BEGIN, task.description, HTML_END)) parameters = ET.SubElement(tool, 'parameters') for task_param in task.parameters: param = ET.SubElement(parameters, 'param', name=task_param['name'], displayname=task_param['display_name'] ) dialog_ref = ET.SubElement(param, 'dialogReference') dialog_ref.text = ''.join((HTML_BEGIN, task_param['description'], HTML_END)) python_ref = ET.SubElement(param, 'pythonReference') python_ref.text = ''.join((HTML_BEGIN, task_param['description'], HTML_END)) dataIdInfo = ET.SubElement(metadata, 'dataIdInfo') searchKeys = ET.SubElement(dataIdInfo, 'searchKeys') keyword1 = ET.SubElement(searchKeys, 'keyword') keyword1.text = 'ENVI' keyword2 = ET.SubElement(searchKeys, 'keyword') keyword2.text = task.name idCitation = ET.SubElement(dataIdInfo, 'idCitation') resTitle = ET.SubElement(idCitation, 'resTitle') resTitle.text = task.name idAbs = ET.SubElement(dataIdInfo, 'idAbs') idAbs.text = ''.join((HTML_BEGIN, task.description, HTML_END)) idCredit = ET.SubElement(dataIdInfo, 'idCredit') idCredit.text = '(c) 2017 Exelis Visual Information Solutions, Inc.' resTitle.text = task.name tree = ET.ElementTree(metadata) tree.write(filename)
<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_params(self, params): """ Parsing params, params is a dict and the dict value can be a string or an iterable, namely a list, we need to process those iterables """
for (key, value) in params.items(): if not isinstance(value, str): string_params = self.to_string(value) params[key] = string_params return params
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def to_string(self, obj): """ Picks up an object and transforms it into a string, by coercing each element in an iterable to a string and then joining them, or by trying to coerce the object directly """
try: converted = [str(element) for element in obj] string = ','.join(converted) except TypeError: # for now this is ok for booleans string = str(obj) return string
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def filter(self, endpoint, params): """ Makes a get request by construction the path from an endpoint and a dict with filter query params e.g. params = {'category__in': [1,2]} response = self.client.filter('/experiences/', params) """
params = self.parse_params(params) params = urlencode(params) path = '{0}?{1}'.format(endpoint, params) return self.get(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 is_domain_class_member_attribute(ent, attr_name): """ Checks if the given attribute name is a entity attribute of the given registered resource. """
attr = get_domain_class_attribute(ent, attr_name) return attr.kind == RESOURCE_ATTRIBUTE_KINDS.MEMBER
<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_domain_class_collection_attribute(ent, attr_name): """ Checks if the given attribute name is a aggregate attribute of the given registered resource. """
attr = get_domain_class_attribute(ent, attr_name) return attr.kind == RESOURCE_ATTRIBUTE_KINDS.COLLECTION
<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_password(self, password): """ Set user password with hash """
self.password = Security.hash(password) self.save()
<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_password_reset(cls, email, valid_for=3600) -> str: """ Create a password reset request in the user_password_resets database table. Hashed code gets stored in the database. Returns unhashed reset code """
user = cls.where_email(email) if user is None: return None PasswordResetModel.delete_where_user_id(user.id) token = JWT().create_token({ 'code': Security.random_string(5), # make unique 'user_id': user.id}, token_valid_for=valid_for) code = Security.generate_uuid(1) + "-" + Security.random_string(5) password_reset_model = PasswordResetModel() password_reset_model.token = token password_reset_model.code = code password_reset_model.user_id = user.id password_reset_model.save() return 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 validate_password_reset(cls, code, new_password): """ Validates an unhashed code against a hashed code. Once the code has been validated and confirmed new_password will replace the old users password """
password_reset_model = \ PasswordResetModel.where_code(code) if password_reset_model is None: return None jwt = JWT() if jwt.verify_token(password_reset_model.token): user = cls.where_id(jwt.data['data']['user_id']) if user is not None: user.set_password(new_password) PasswordResetModel.delete_where_user_id(user.id) return user password_reset_model.delete() # delete expired/invalid token 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 by_current_session(cls): """ Returns current user session """
session = Session.current_session() if session is None: return None return cls.where_id(session.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 AdvancedJsonify(data, status_code): """ Advanced Jsonify Response Maker :param data: Data :param status_code: Status_code :return: Response """
response = jsonify(data) response.status_code = status_code 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 response(self, callback=None): """ View representation of the object :param callback: Function to represent the error in view. Default : flask.jsonify :type callback: function :return: View """
if not callback: callback = type(self).AdvancedJsonify resp = { "status": "error", "message": self.message } if self.step: resp["step"] = self.step self.LOGGER.error(self.message, extra={"step": self.step, "context": self.context}) return callback(resp, status_code=self.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 __json(self): """ Using the exclude lists, convert fields to a string. """
if self.exclude_list is None: self.exclude_list = [] fields = {} for key, item in vars(self).items(): if hasattr(self, '_sa_instance_state'): # load only deferred objects if len(orm.attributes.instance_state(self).unloaded) > 0: mapper = inspect(self) for column in mapper.attrs: column.key column.value if str(key).startswith('_') or key in self.exclude_list: continue fields[key] = item obj = Json.safe_object(fields) return str(obj)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def manage(cls, entity, unit_of_work): """ Manages the given entity under the given Unit Of Work. If `entity` is already managed by the given Unit Of Work, nothing is done. :raises ValueError: If the given entity is already under management by a different Unit Of Work. """
if hasattr(entity, '__everest__'): if not unit_of_work is entity.__everest__.unit_of_work: raise ValueError('Trying to register an entity that has been ' 'registered with another session!') else: entity.__everest__ = cls(entity, unit_of_work)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def release(cls, entity, unit_of_work): """ Releases the given entity from management under the given Unit Of Work. :raises ValueError: If `entity` is not managed at all or is not managed by the given Unit Of Work. """
if not hasattr(entity, '__everest__'): raise ValueError('Trying to unregister an entity that has not ' 'been registered yet!') elif not unit_of_work is entity.__everest__.unit_of_work: raise ValueError('Trying to unregister an entity that has been ' 'registered with another session!') delattr(entity, '__everest__')
<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_state_data(cls, entity): """ Returns the state data for the given entity. This also works for unmanaged entities. """
attrs = get_domain_class_attribute_iterator(type(entity)) return dict([(attr, get_nested_attribute(entity, attr.entity_attr)) for attr in attrs if not attr.entity_attr is 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 set_state_data(cls, entity, data): """ Sets the state data for the given entity to the given data. This also works for unmanaged entities. """
attr_names = get_domain_class_attribute_names(type(entity)) nested_items = [] for attr, new_attr_value in iteritems_(data): if not attr.entity_attr in attr_names: raise ValueError('Can not set attribute "%s" for entity ' '"%s".' % (attr.entity_attr, entity)) if '.' in attr.entity_attr: nested_items.append((attr, new_attr_value)) continue else: setattr(entity, attr.entity_attr, new_attr_value) for attr, new_attr_value in nested_items: try: set_nested_attribute(entity, attr.entity_attr, new_attr_value) except AttributeError as exc: if not new_attr_value is None: raise exc
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def transfer_state_data(cls, source_entity, target_entity): """ Transfers instance state data from the given source entity to the given target entity. """
state_data = cls.get_state_data(source_entity) cls.set_state_data(target_entity, state_data)
<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, data): """ Sets the given state data on the given entity of the given class. :param data: State data to set. :type data: Dictionary mapping attributes to attribute values. :param entity: Entity to receive the state data. """
ent = self.__entity_ref() self.set_state_data(ent, data)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def pretty_print(self, carrot=True): """Print the previous and current line with line numbers and a carret under the current character position. Will also print a message if one is given to this exception. """
output = ['\n'] output.extend([line.pretty_print() for line in self.partpyobj.get_surrounding_lines(1, 0)]) if carrot: output.append('\n' + (' ' * (self.partpyobj.col + 5)) + '^' + '\n') if self.partpymsg: output.append(self.partpymsg) return ''.join(output)
<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_event(self, num): """Extract event from dataset."""
if num < 0 or num >= self.params["events_num"]: raise IndexError("Index out of range [0:%s]" % (self.params["events_num"])) ch_num = self.params['channel_number'] ev_size = self.params['b_size'] event = {} self.file.seek(7168 + num * (96 + 2 * ch_num * ev_size)) event["text_hdr"] = self.file.read(64) event["ev_num"] = struct.unpack('I', self.file.read(4))[0] self.file.read(4) start_time = struct.unpack('Q', self.file.read(8))[0] event["start_time"] = datetime.fromtimestamp(start_time) ns_since_epoch = struct.unpack('Q', self.file.read(8))[0] if ns_since_epoch: event['ns_since_epoch'] = ns_since_epoch self.file.read(8) event_data = self.file.read(2 * ev_size * ch_num) event["data"] = np.fromstring(event_data, np.short) return event
<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_event_data(self, num, data): """Update event data in dataset."""
if num < 0 or num >= self.params["events_num"]: raise IndexError("Index out of range [0:%s]" % (self.params["events_num"])) if isinstance(data, np.ndarray): raise TypeError("data should be np.ndarray") if data.dtype != np.short: raise TypeError("data array dtype should be dtype('int16')") ch_num = self.params['channel_number'] ev_size = self.params['b_size'] if data.shape != (ch_num * ev_size,): raise Exception("data should contain same number of elements " "(%s)" % (ch_num * ev_size)) self.file.seek(7168 + num * (96 + 2 * ch_num * ev_size) + 96) self.file.write(data.tostring()) self.file.flush()
<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_to_pool(upstream): """ Given a string containing an nginx upstream section, return the pool name and list of nodes. """
name = re.search('upstream +(.*?) +{', upstream).group(1) nodes = re.findall('server +(.*?);', upstream) return name, nodes
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def calculate_vss(self, method=None): """ Calculate the vertical swimming speed of this behavior. Takes into account the vertical swimming speed and the variance. Parameters: method: "gaussian" (default) or "random" "random" (vss - variance) < X < (vss + variance) """
if self.variance == float(0): return self.vss else: # Calculate gausian distribution and return if method == "gaussian" or method is None: return gauss(self.vss, self.variance) elif method == "random": return uniform(self.vss - self.variance, self.vss + self.variance) else: raise ValueError("Method of vss calculation not recognized, please use 'gaussian' or 'random'")
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _check_experiment(self, name): """Check the signal type of the experiment Returns ------- True, if the signal type is supported, False otherwise Raises ------ Warning if the signal type is not supported """
with h5py.File(name=self.path, mode="r") as h5: sigpath = "/Experiments/{}/metadata/Signal".format(name) signal_type = h5[sigpath].attrs["signal_type"] if signal_type != "hologram": msg = "Signal type '{}' not supported: {}[{}]".format(signal_type, self.path, name) warnings.warn(msg, WrongSignalTypeWarnging) return signal_type == "hologram"
<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_experiments(self): """Get all experiments from the hdf5 file"""
explist = [] with h5py.File(name=self.path, mode="r") as h5: if "Experiments" not in h5: msg = "Group 'Experiments' not found in {}.".format(self.path) raise HyperSpyNoDataFoundError(msg) for name in h5["Experiments"]: # check experiment if self._check_experiment(name): explist.append(name) explist.sort() if not explist: # if this error is raised, the signal_type is probably not # set to "hologram". msg = "No supported data found: {}".format(self.path) raise HyperSpyNoDataFoundError(msg) return explist
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def verify(path): """Verify that `path` has the HyperSpy file format"""
valid = False try: h5 = h5py.File(path, mode="r") except (OSError, IsADirectoryError): pass else: if ("file_format" in h5.attrs and h5.attrs["file_format"].lower() == "hyperspy" and "Experiments" in h5): valid = True return valid
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def transform(self, df): """ Transforms a DataFrame in place. Computes all outputs of the DataFrame. Args: df (pandas.DataFrame): DataFrame to transform. """
for name, function in self.outputs: df[name] = function(df)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def pop(self): """ Removes the last traversal path node from this traversal path. """
node = self.nodes.pop() self.__keys.remove(node.key)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def parent(self): """ Returns the proxy from the last node visited on the path, or `None`, if no node has been visited yet. """
if len(self.nodes) > 0: parent = self.nodes[-1].proxy else: parent = None return parent
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def relation_operation(self): """ Returns the relation operation from the last node visited on the path, or `None`, if no node has been visited yet. """
if len(self.nodes) > 0: rel_op = self.nodes[-1].relation_operation else: rel_op = None return rel_op
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def ensure_unicode(text): u"""helper to ensure that text passed to WriteConsoleW is unicode"""
if isinstance(text, str): try: return text.decode(pyreadline_codepage, u"replace") except (LookupError, TypeError): return text.decode(u"ascii", u"replace") return text
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def ensure_str(text): u"""Convert unicode to str using pyreadline_codepage"""
if isinstance(text, unicode): try: return text.encode(pyreadline_codepage, u"replace") except (LookupError, TypeError): return text.encode(u"ascii", u"replace") return text
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def unwrap_raw(content): """ unwraps the callback and returns the raw content """
starting_symbol = get_start_symbol(content) ending_symbol = ']' if starting_symbol == '[' else '}' start = content.find(starting_symbol, 0) end = content.rfind(ending_symbol) return content[start:end+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 combine_word_list(word_list): """ Combine word list into a bag-of-words. Input: - word_list: This is a python list of strings. Output: - bag_of_words: This is the corresponding multi-set or bag-of-words, in the form of a python dictionary. """
bag_of_words = collections.defaultdict(int) for word in word_list: bag_of_words[word] += 1 return bag_of_words
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def reduce_list_of_bags_of_words(list_of_keyword_sets): """ Reduces a number of keyword sets to a bag-of-words. Input: - list_of_keyword_sets: This is a python list of sets of strings. Output: - bag_of_words: This is the corresponding multi-set or bag-of-words, in the form of a python dictionary. """
bag_of_words = dict() get_bag_of_words_keys = bag_of_words.keys for keyword_set in list_of_keyword_sets: for keyword in keyword_set: if keyword in get_bag_of_words_keys(): bag_of_words[keyword] += 1 else: bag_of_words[keyword] = 1 return bag_of_words
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def query_list_of_words(target_word, list_of_words, edit_distance=1): """ Checks whether a target word is within editing distance of any one in a set of keywords. Inputs: - target_word: A string containing the word we want to search in a list. - list_of_words: A python list of words. - edit_distance: For larger words, we also check for similar words based on edit_distance. Outputs: - new_list_of_words: This is the input list of words minus any found keywords. - found_list_of_words: This is the list of words that are within edit distance of the target word. """
# Initialize lists new_list_of_words = list() found_list_of_words = list() append_left_keyword = new_list_of_words.append append_found_keyword = found_list_of_words.append # Iterate over the list of words for word in list_of_words: if len(word) > 6: effective_edit_distance = edit_distance else: effective_edit_distance = 0 # No edit distance for small words. if abs(len(word)-len(target_word)) <= effective_edit_distance: if nltk.edit_distance(word, target_word) <= effective_edit_distance: append_found_keyword(word) else: append_left_keyword(word) else: append_left_keyword(word) return new_list_of_words, found_list_of_words
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def fixup_instance(sender, **kwargs): """ Cache JSONAttributes data on instance and vice versa for convenience. """
instance = kwargs['instance'] for model_field in instance._meta.fields: if not isinstance(model_field, JSONAttributeField): continue if hasattr(instance, '_attr_field'): raise FieldError('multiple JSONAttributeField fields: ' 'only one is allowed per model!') field_name = model_field.name attrs = getattr(instance, field_name) # ensure JSONAttributeField's data is of JSONAttributes type if not isinstance(attrs, JSONAttributes): setattr(instance, field_name, JSONAttributes(attrs)) attrs = getattr(instance, field_name) # Cache model instance on JSONAttributes instance and vice-versa attrs._instance = instance attrs._get_from_instance = functools.partial( getattr, instance, field_name) instance._attr_field = attrs if not hasattr(instance, '_attr_field'): raise FieldError('missing JSONAttributeField field in ' 'fixup_instance 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 size(self): """ Recursively find size of a tree. Slow. """
if self is NULL: return 0 return 1 + self.left.size() + self.right.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 find_prekeyed(self, value, key): """ Find a value in a node, using a key function. The value is already a key. """
while self is not NULL: direction = cmp(value, key(self.value)) if direction < 0: self = self.left elif direction > 0: self = self.right elif direction == 0: return 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 rotate_left(self): """ Rotate the node to the left. """
right = self.right new = self._replace(right=self.right.left, red=True) top = right._replace(left=new, red=self.red) return top
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def flip(self): """ Flip colors of a node and its children. """
left = self.left._replace(red=not self.left.red) right = self.right._replace(red=not self.right.red) top = self._replace(left=left, right=right, red=not self.red) return top
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def balance(self): """ Balance a node. The balance is inductive and relies on all subtrees being balanced recursively or by construction. If the subtrees are not balanced, then this will not fix them. """
# Always lean left with red nodes. if self.right.red: self = self.rotate_left() # Never permit red nodes to have red children. Note that if the left-hand # node is NULL, it will short-circuit and fail this test, so we don't have # to worry about a dereference here. if self.left.red and self.left.left.red: self = self.rotate_right() # Finally, move red children on both sides up to the next level, reducing # the total redness. if self.left.red and self.right.red: self = self.flip() return 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 insert(self, value, key): """ Insert a value into a tree rooted at the given node, and return whether this was an insertion or update. Balances the tree during insertion. An update is performed instead of an insertion if a value in the tree compares equal to the new value. """
# Base case: Insertion into the empty tree is just creating a new node # with no children. if self is NULL: return Node(value, NULL, NULL, True), True # Recursive case: Insertion into a non-empty tree is insertion into # whichever of the two sides is correctly compared. direction = cmp(key(value), key(self.value)) if direction < 0: left, insertion = self.left.insert(value, key) self = self._replace(left=left) elif direction > 0: right, insertion = self.right.insert(value, key) self = self._replace(right=right) elif direction == 0: # Exact hit on an existing node (this node, in fact). In this # case, perform an update. self = self._replace(value=value) insertion = False # And balance on the way back up. return self.balance(), insertion
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def move_red_left(self): """ Shuffle red to the left of a tree. """
self = self.flip() if self.right is not NULL and self.right.left.red: self = self._replace(right=self.right.rotate_right()) self = self.rotate_left().flip() return 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 move_red_right(self): """ Shuffle red to the right of a tree. """
self = self.flip() if self.left is not NULL and self.left.left.red: self = self.rotate_right().flip() return 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 delete_min(self): """ Delete the left-most value from a tree. """
# Base case: If there are no nodes lesser than this node, then this is the # node to delete. if self.left is NULL: return NULL, self.value # Acquire more reds if necessary to continue the traversal. The # double-deep check is fine because NULL is red. if not self.left.red and not self.left.left.red: self = self.move_red_left() # Recursive case: Delete the minimum node of all nodes lesser than this # node. left, value = self.left.delete_min() self = self._replace(left=left) return self.balance(), 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 delete_max(self): """ Delete the right-most value from a tree. """
# Attempt to rotate left-leaning reds to the right. if self.left.red: self = self.rotate_right() # Base case: If there are no selfs greater than this self, then this is # the self to delete. if self.right is NULL: return NULL, self.value # Acquire more reds if necessary to continue the traversal. NULL is # red so this check doesn't need to check for NULL. if not self.right.red and not self.right.left.red: self = self.move_red_right() # Recursive case: Delete the maximum self of all selfs greater than this # self. right, value = self.right.delete_max() self = self._replace(right=right) return self.balance(), 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 delete(self, value, key): """ Delete a value from a tree. """
# Base case: The empty tree cannot possibly have the desired value. if self is NULL: raise KeyError(value) direction = cmp(key(value), key(self.value)) # Because we lean to the left, the left case stands alone. if direction < 0: if (not self.left.red and self.left is not NULL and not self.left.left.red): self = self.move_red_left() # Delete towards the left. left = self.left.delete(value, key) self = self._replace(left=left) else: # If we currently lean to the left, lean to the right for now. if self.left.red: self = self.rotate_right() # Best case: The node on our right (which we just rotated there) is a # red link and also we were just holding the node to delete. In that # case, we just rotated NULL into our current node, and the node to # the right is the lone matching node to delete. if direction == 0 and self.right is NULL: return NULL # No? Okay. Move more reds to the right so that we can continue to # traverse in that direction. At *this* spot, we do have to confirm # that node.right is not NULL... if (not self.right.red and self.right is not NULL and not self.right.left.red): self = self.move_red_right() if direction > 0: # Delete towards the right. right = self.right.delete(value, key) self = self._replace(right=right) else: # Annoying case: The current node was the node to delete all # along! Use a right-handed minimum deletion. First find the # replacement value to rebuild the current node with, then delete # the replacement value from the right-side tree. Finally, create # the new node with the old value replaced and the replaced value # deleted. rnode = self.right while rnode is not NULL: rnode = rnode.left right, replacement = self.right.delete_min() self = self._replace(value=replacement, right=right) return self.balance()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def pop_max(self): """ Remove the maximum value and return it. """
if self.root is NULL: raise KeyError("pop from an empty blackjack") self.root, value = self.root.delete_max() self._len -= 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 pop_min(self): """ Remove the minimum value and return it. """
if self.root is NULL: raise KeyError("pop from an empty blackjack") self.root, value = self.root.delete_min() self._len -= 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 install_readline(hook): '''Set up things for the interpreter to call our function like GNU readline.''' global readline_hook, readline_ref # save the hook so the wrapper can call it readline_hook = hook # get the address of PyOS_ReadlineFunctionPointer so we can update it PyOS_RFP = c_void_p.from_address(Console.GetProcAddress(sys.dllhandle, "PyOS_ReadlineFunctionPointer")) # save a reference to the generated C-callable so it doesn't go away if sys.version < '2.3': readline_ref = HOOKFUNC22(hook_wrapper) else: readline_ref = HOOKFUNC23(hook_wrapper_23) # get the address of the function func_start = c_void_p.from_address(addressof(readline_ref)).value # write the function address into PyOS_ReadlineFunctionPointer PyOS_RFP.value = func_start
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def fixcoord(self, x, y): u'''Return a long with x and y packed inside, also handle negative x and y.''' if x < 0 or y < 0: info = CONSOLE_SCREEN_BUFFER_INFO() self.GetConsoleScreenBufferInfo(self.hout, byref(info)) if x < 0: x = info.srWindow.Right - x y = info.srWindow.Bottom + y # this is a hack! ctypes won't pass structures but COORD is # just like a long, so this works. return c_int(y << 16 | x)
<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_scrolling(self, text, attr=None): u'''write text at current cursor position while watching for scrolling. If the window scrolls because you are at the bottom of the screen buffer, all positions that you are storing will be shifted by the scroll amount. For example, I remember the cursor position of the prompt so that I can redraw the line but if the window scrolls, the remembered position is off. This variant of write tries to keep track of the cursor position so that it will know when the screen buffer is scrolled. It returns the number of lines that the buffer scrolled. ''' x, y = self.pos() w, h = self.size() scroll = 0 # the result # split the string into ordinary characters and funny characters chunks = self.motion_char_re.split(text) for chunk in chunks: n = self.write_color(chunk, attr) if len(chunk) == 1: # the funny characters will be alone if chunk[0] == u'\n': # newline x = 0 y += 1 elif chunk[0] == u'\r': # carriage return x = 0 elif chunk[0] == u'\t': # tab x = 8 * (int(x / 8) + 1) if x > w: # newline x -= w y += 1 elif chunk[0] == u'\007': # bell pass elif chunk[0] == u'\010': x -= 1 if x < 0: y -= 1 # backed up 1 line else: # ordinary character x += 1 if x == w: # wrap x = 0 y += 1 if y == h: # scroll scroll += 1 y = h - 1 else: # chunk of ordinary characters x += n l = int(x / w) # lines we advanced x = x % w # new x value y += l if y >= h: # scroll scroll += y - h + 1 y = h - 1 return scroll
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def page(self, attr=None, fill=u' '): u'''Fill the entire screen.''' if attr is None: attr = self.attr if len(fill) != 1: raise ValueError info = CONSOLE_SCREEN_BUFFER_INFO() self.GetConsoleScreenBufferInfo(self.hout, byref(info)) if info.dwCursorPosition.X != 0 or info.dwCursorPosition.Y != 0: self.SetConsoleCursorPosition(self.hout, self.fixcoord(0, 0)) w = info.dwSize.X n = DWORD(0) for y in range(info.dwSize.Y): self.FillConsoleOutputAttribute(self.hout, attr, w, self.fixcoord(0, y), byref(n)) self.FillConsoleOutputCharacterW(self.hout, ord(fill[0]), w, self.fixcoord(0, y), byref(n)) self.attr = attr
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def scroll(self, rect, dx, dy, attr=None, fill=' '): u'''Scroll a rectangle.''' if attr is None: attr = self.attr x0, y0, x1, y1 = rect source = SMALL_RECT(x0, y0, x1 - 1, y1 - 1) dest = self.fixcoord(x0 + dx, y0 + dy) style = CHAR_INFO() style.Char.AsciiChar = ensure_str(fill[0]) style.Attributes = attr return self.ScrollConsoleScreenBufferW(self.hout, byref(source), byref(source), dest, byref(style))
<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(self): u'''Get next event from queue.''' inputHookFunc = c_void_p.from_address(self.inputHookPtr).value Cevent = INPUT_RECORD() count = DWORD(0) while 1: if inputHookFunc: call_function(inputHookFunc, ()) status = self.ReadConsoleInputW(self.hin, byref(Cevent), 1, byref(count)) if status and count.value == 1: e = event(self, Cevent) return e
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def getchar(self): u'''Get next character from queue.''' Cevent = INPUT_RECORD() count = DWORD(0) while 1: status = self.ReadConsoleInputW(self.hin, byref(Cevent), 1, byref(count)) if (status and (count.value == 1) and (Cevent.EventType == 1) and Cevent.Event.KeyEvent.bKeyDown): sym = keysym(Cevent.Event.KeyEvent.wVirtualKeyCode) if len(sym) == 0: sym = Cevent.Event.KeyEvent.uChar.AsciiChar return sym
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def peek(self): u'''Check event queue.''' Cevent = INPUT_RECORD() count = DWORD(0) status = self.PeekConsoleInputW(self.hin, byref(Cevent), 1, byref(count)) if status and count == 1: return event(self, Cevent)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def cursor(self, visible=None, size=None): u'''Set cursor on or off.''' info = CONSOLE_CURSOR_INFO() if self.GetConsoleCursorInfo(self.hout, byref(info)): if visible is not None: info.bVisible = visible if size is not None: info.dwSize = size self.SetConsoleCursorInfo(self.hout, byref(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 inherit_docstrings(cls): """Class decorator for inheriting docstrings. Automatically inherits base class doc-strings if not present in the derived class. """
@functools.wraps(cls) def _inherit_docstrings(cls): if not isinstance(cls, (type, colorise.compat.ClassType)): raise RuntimeError("Type is not a class") for name, value in colorise.compat.iteritems(vars(cls)): if isinstance(getattr(cls, name), types.MethodType): if not getattr(value, '__doc__', None): for base in cls.__bases__: basemethod = getattr(base, name, None) if basemethod and getattr(base, '__doc__', None): value.__doc__ = basemethod.__doc__ return cls return _inherit_docstrings(cls)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def upload(config): """Upload the build documentation site to LSST the Docs. Parameters config : `lander.config.Configuration` Site configuration, which includes upload information and credentials. """
token = get_keeper_token(config['keeper_url'], config['keeper_user'], config['keeper_password']) build_resource = register_build(config, token) ltdconveyor.upload_dir( build_resource['bucket_name'], build_resource['bucket_root_dir'], config['build_dir'], aws_access_key_id=config['aws_id'], aws_secret_access_key=config['aws_secret'], surrogate_key=build_resource['surrogate_key'], cache_control='max-age=31536000', surrogate_control=None, upload_dir_redirect_objects=True) confirm_build(config, token, build_resource)
<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_keeper_token(base_url, username, password): """Get a temporary auth token from LTD Keeper."""
token_endpoint = base_url + '/token' r = requests.get(token_endpoint, auth=(username, password)) if r.status_code != 200: raise RuntimeError('Could not authenticate to {0}: error {1:d}\n{2}'. format(base_url, r.status_code, r.json())) return r.json()['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 install( board_id='atmega88', mcu='atmega88', f_cpu=20000000, upload='usbasp', core='arduino', replace_existing=True, ): """install atmega88 board."""
board = AutoBunch() board.name = TEMPL.format(mcu=mcu, f_cpu=f_cpu, upload=upload) board.upload.using = upload board.upload.maximum_size = 8 * 1024 board.build.mcu = mcu board.build.f_cpu = str(f_cpu) + 'L' board.build.core = core # for 1.0 board.build.variant = 'standard' install_board(board_id, board, replace_existing=replace_existing)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _compute_bgid(self, bg=None): """Return a unique identifier for the background data"""
if bg is None: bg = self._bgdata if isinstance(bg, qpimage.QPImage): # Single QPImage if "identifier" in bg: return bg["identifier"] else: data = [bg.amp, bg.pha] for key in sorted(list(bg.meta.keys())): val = bg.meta[key] data.append("{}={}".format(key, val)) return hash_obj(data) elif (isinstance(bg, list) and isinstance(bg[0], qpimage.QPImage)): # List of QPImage data = [] for bgii in bg: data.append(self._compute_bgid(bgii)) return hash_obj(data) elif (isinstance(bg, SeriesData) and (len(bg) == 1 or len(bg) == len(self))): # DataSet return bg.identifier else: raise ValueError("Unknown background data type: {}".format(bg))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def identifier(self): """Return a unique identifier for the given data set"""
if self.background_identifier is None: idsum = self._identifier_data() else: idsum = hash_obj([self._identifier_data(), self.background_identifier]) return idsum
<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_time(self, idx): """Return time of data at index `idx` Returns nan if the time is not defined"""
# raw data qpi = self.get_qpimage_raw(idx) if "time" in qpi.meta: thetime = qpi.meta["time"] else: thetime = np.nan return thetime
<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_bg(self, dataset): """Set background data Parameters dataset: `DataSet`, `qpimage.QPImage`, or int If the ``len(dataset)`` matches ``len(self)``, then background correction is performed element-wise. Otherwise, ``len(dataset)`` must be one and is used for all data of ``self``. See Also -------- get_qpimage: obtain the background corrected QPImage """
if isinstance(dataset, qpimage.QPImage): # Single QPImage self._bgdata = [dataset] elif (isinstance(dataset, list) and len(dataset) == len(self) and isinstance(dataset[0], qpimage.QPImage)): # List of QPImage self._bgdata = dataset elif (isinstance(dataset, SeriesData) and (len(dataset) == 1 or len(dataset) == len(self))): # DataSet self._bgdata = dataset else: raise ValueError("Bad length or type for bg: {}".format(dataset)) self.background_identifier = self._compute_bgid()
<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_time(self, idx=0): """Time of the data Returns nan if the time is not defined """
thetime = super(SingleData, self).get_time(idx=0) return thetime
<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(self, fn, message=None, *args, **kwargs): """Add a 'do' action to the steps. This is a function to execute :param fn: A function :param message: Message indicating what this function does (used for debugging if assertions fail) """
self.items.put(ChainItem(fn, self.do, message, *args, **kwargs)) return 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 expect(self, value, message='Failed: "{actual} {operator} {expected}" after step "{step}"', operator='=='): """Add an 'assertion' action to the steps. This will evaluate the return value of the last 'do' step and compare it to the value passed here using the specified operator. Checks that the first function will return 2 This will check that your function does not return None :param value: The expected value :param message: The error message to raise if the assertion fails. You can access the variables: {actual} -- The actual value {expected} -- The expected value {step} -- The step just performed, which did not meet the expectation {operator} -- The operator used to make the comparison """
if operator not in self.valid_operators: raise ValueError('Illegal operator specified for ') self.items.put(ChainItem(value, self.expect, message, operator=operator)) return 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 perform(self): """Runs through all of the steps in the chain and runs each of them in sequence. :return: The value from the lat "do" step performed """
last_value = None last_step = None while self.items.qsize(): item = self.items.get() if item.flag == self.do: last_value = item.item(*item.args, **item.kwargs) last_step = item.message elif item.flag == self.expect: message = item.message local = {'value': last_value, 'expectation': item.item} expression = 'value {operator} expectation'.format(operator=item.operator) result = eval(expression, local) # Format the error message format_vars = { 'actual': last_value, 'expected': item.item, 'step': last_step, 'operator': item.operator } for var, val in format_vars.iteritems(): message = message.replace('{' + str(var) + '}', str(val)) assert result, message return last_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_volumes(self): """ Return a list of all Volumes in this Storage Pool """
vols = [self.find_volume(name) for name in self.virsp.listVolumes()] return vols
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def install(replace_existing=False): """install dapa programmer."""
bunch = AutoBunch() bunch.name = 'DAPA' bunch.protocol = 'dapa' bunch.force = 'true' # bunch.delay=200 install_programmer('dapa', bunch, replace_existing=replace_existing)
<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_terminal_converted(self, attr): """ Returns the value of the specified attribute converted to a representation value. :param attr: Attribute to retrieve. :type attr: :class:`everest.representers.attributes.MappedAttribute` :returns: Representation string. """
value = self.data.get(attr.repr_name) return self.converter_registry.convert_to_representation( value, attr.value_type)
<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_terminal_converted(self, attr, repr_value): """ Converts the given representation value and sets the specified attribute value to the converted value. :param attr: Attribute to set. :param str repr_value: String value of the attribute to set. """
value = self.converter_registry.convert_from_representation( repr_value, attr.value_type) self.data[attr.repr_name] = 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 load(self, filename, offset): """Will eventually load information for Apple_Boot volume. \ Not yet implemented"""
try: self.offset = offset # self.fd = open(filename, 'rb') # self.fd.close() except IOError: self.logger.error('Unable to load EfiSystem volume')
<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(self, filenames=None): """Sends the file to the remote host and archives the sent file locally. """
try: with self.ssh_client.connect() as ssh_conn: with self.sftp_client.connect(ssh_conn) as sftp_conn: for filename in filenames: sftp_conn.copy(filename=filename) self.archive(filename=filename) if self.update_history_model: self.update_history(filename=filename) except SSHClientError as e: raise TransactionFileSenderError(e) from e except SFTPClientError as e: raise TransactionFileSenderError(e) from e return filenames
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def compile(self, name, folder=None, data=None): """ renders template_name + self.extension file with data using jinja """
template_name = name.replace(os.sep, "") if folder is None: folder = "" full_name = os.path.join( folder.strip(os.sep), template_name) if data is None: data = {} try: self.templates[template_name] = \ self.jinja.get_template(full_name).render(data) except TemplateNotFound as template_error: if current_app.config['DEBUG']: raise template_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 create_token(self, data, token_valid_for=180) -> str: """ Create encrypted JWT """
jwt_token = jwt.encode({ 'data': data, 'exp': datetime.utcnow() + timedelta(seconds=token_valid_for)}, self.app_secret) return Security.encrypt(jwt_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 verify_token(self, token) -> bool: """ Verify encrypted JWT """
try: self.data = jwt.decode(Security.decrypt(token), self.app_secret) return True except (Exception, BaseException) as error: self.errors.append(error) return False 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 verify_http_auth_token(self) -> bool: """ Use request information to validate JWT """
authorization_token = self.get_http_token() if authorization_token is not None: if self.verify_token(authorization_token): if self.data is not None: self.data = self.data['data'] return True return False else: return False 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 create_token_with_refresh_token(self, data, token_valid_for=180, refresh_token_valid_for=86400): """ Create an encrypted JWT with a refresh_token """
refresh_token = None refresh_token = jwt.encode({ 'exp': datetime.utcnow() + timedelta(seconds=refresh_token_valid_for)}, self.app_secret).decode("utf-8") jwt_token = jwt.encode({ 'data': data, 'refresh_token': refresh_token, 'exp': datetime.utcnow() + timedelta(seconds=token_valid_for)}, self.app_secret) return Security.encrypt(jwt_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 verify_refresh_token(self, expired_token) -> bool: """ Use request information to validate refresh JWT """
try: decoded_token = jwt.decode( Security.decrypt(expired_token), self.app_secret, options={'verify_exp': False}) if 'refresh_token' in decoded_token and \ decoded_token['refresh_token'] is not None: try: jwt.decode(decoded_token['refresh_token'], self.app_secret) self.data = decoded_token return True except (Exception, BaseException) as error: self.errors.append(error) return False except (Exception, BaseException) as error: self.errors.append(error) return False 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 verify_http_auth_refresh_token(self) -> bool: """ Use expired token to check refresh token information """
authorization_token = self.get_http_token() if authorization_token is not None: if self.verify_refresh_token(authorization_token): if self.data is not None: self.data = self.data['data'] return True return False else: return False 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 status(self, status_code=None): """ Set status or Get Status """
if status_code is not None: self.response_model.status = status_code # return string for response support return str(self.response_model.status)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def message(self, message=None): """ Set response message """
if message is not None: self.response_model.message = message return self.response_model.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 data(self, data=None): """ Set response data """
if data is not None: self.response_model.data = data return self.response_model.data
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def quick_response(self, status_code): """ Quickly construct response using a status code """
translator = Translator(environ=self.environ) if status_code == 404: self.status(404) self.message(translator.trans('http_messages.404')) elif status_code == 401: self.status(401) self.message(translator.trans('http_messages.401')) elif status_code == 400: self.status(400) self.message(translator.trans('http_messages.400')) elif status_code == 200: self.status(200) self.message(translator.trans('http_messages.200'))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def memoize(func): """Cache forever."""
cache = {} def memoizer(): if 0 not in cache: cache[0] = func() return cache[0] return functools.wraps(func)(memoizer)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def getinputencoding(stream=None): """Return preferred encoding for reading from ``stream``. ``stream`` defaults to sys.stdin. """
if stream is None: stream = sys.stdin encoding = stream.encoding if not encoding: encoding = getpreferredencoding() return encoding
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def getoutputencoding(stream=None): """Return preferred encoding for writing to ``stream``. ``stream`` defaults to sys.stdout. """
if stream is None: stream = sys.stdout encoding = stream.encoding if not encoding: encoding = getpreferredencoding() return encoding
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def decode(string, encoding=None, errors=None): """Decode from specified encoding. ``encoding`` defaults to the preferred encoding. ``errors`` defaults to the preferred error handler. """
if encoding is None: encoding = getpreferredencoding() if errors is None: errors = getpreferrederrors() return string.decode(encoding, errors)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def encode(string, encoding=None, errors=None): """Encode to specified encoding. ``encoding`` defaults to the preferred encoding. ``errors`` defaults to the preferred error handler. """
if encoding is None: encoding = getpreferredencoding() if errors is None: errors = getpreferrederrors() return string.encode(encoding, errors)
<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_response_mime_type(self): """ Returns the reponse MIME type for this view. :raises: :class:`pyramid.httpexceptions.HTTPNotAcceptable` if the MIME content type(s) the client specified can not be handled by the view. """
view_name = self.request.view_name if view_name != '': mime_type = get_registered_mime_type_for_name(view_name) else: mime_type = None acc = None for acc in self.request.accept: if acc == '*/*': # The client does not care; use the default. mime_type = self.__get_default_response_mime_type() break try: mime_type = \ get_registered_mime_type_for_string(acc.lower()) except KeyError: pass else: break if mime_type is None: if not acc is None: # The client specified a MIME type we can not handle; this # is a 406 exception. We supply allowed MIME content # types in the body of the response. headers = \ [('Location', self.request.path_url), ('Content-Type', TextPlainMime.mime_type_string), ] mime_strings = get_registered_mime_strings() exc = HTTPNotAcceptable('Requested MIME content type(s) ' 'not acceptable.', body=','.join(mime_strings), headers=headers) raise exc mime_type = self.__get_default_response_mime_type() return mime_type
<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_result(self, resource): """ Converts the given resource to a result to be returned from the view. Unless a custom renderer is employed, this will involve creating a representer and using it to convert the resource to a string. :param resource: Resource to convert. :type resource: Object implementing :class:`evererst.interfaces.IResource`. :returns: :class:`pyramid.reposnse.Response` object or a dictionary with a single key "context" mapped to the given resource (to be passed on to a custom renderer). """
if self._convert_response: self._update_response_body(resource) result = self.request.response else: result = dict(context=resource) 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 _update_response_body(self, resource): """ Creates a representer and updates the response body with the byte representation created for the given resource. """
rpr = self._get_response_representer(resource) # Set content type and body of the response. self.request.response.content_type = \ rpr.content_type.mime_type_string rpr_body = rpr.to_bytes(resource) self.request.response.body = rpr_body