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)
s... |
<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,... |
<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.descripti... |
<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 i... |
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 b... |
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 = {'categor... |
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 ... |
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_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 validate_password_reset(cls, code, new_password):
"""
Validates an unhashed code against a hashed code.
Once the code has been validated and confirmed
ne... |
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 ... |
<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 ... |
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}... |
<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:
... |
<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, nothi... |
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, u... |
<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 manage... |
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 '
... |
<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".' % (at... |
<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 ... |
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 ... |
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.... |
<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 * (... |
<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:
... |
<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... |
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.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 _check_experiment(self, name):
"""Check the signal type of the experiment Returns ------- True, if the signal type is supported, False otherwise Raises -----... |
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,
... |
<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 expe... |
<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):
... |
<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 i... |
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 l... |
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 ... |
<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... |
# 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_dist... |
<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 a... |
<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... |
# 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.... |
<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 duri... |
# 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 comp... |
<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 no... |
<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
# Acqu... |
<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 a... |
<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_RF... |
<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.s... |
<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 reme... |
<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.d... |
<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... |
<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.Rea... |
<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
... |
<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.dwSi... |
<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):
... |
<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... |
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']... |
<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'
... |
<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())):
... |
<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 ba... |
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 = dat... |
<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 i... |
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 w... |
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:
... |
<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.... |
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. :p... |
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)
... |
<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... |
<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
... |
<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_tok... |
<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:
... |
<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
... |
<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'))
... |
<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 pr... |
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 pref... |
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 conten... |
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 doe... |
<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 involv... |
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 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.