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 _es_text(settings, text_formating = {}): """ Extract text formating related subset of widget settings. """
s = {k: settings[k] for k in (ConsoleWidget.SETTING_FLAG_PLAIN,)} s.update(text_formating) return 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 _es_margin(settings): """ Extract margin formating related subset of widget settings. """
return {k: settings[k] for k in (ConsoleWidget.SETTING_MARGIN, ConsoleWidget.SETTING_MARGIN_LEFT, ConsoleWidget.SETTING_MARGIN_RIGHT, ConsoleWidget.SETTING_MARGIN_CHAR)}
<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_width_widget(width, margin = None, margin_left = None, margin_right = None): """ Calculate actual widget width based on given margins. """
if margin_left is None: margin_left = margin if margin_right is None: margin_right = margin if margin_left is not None: width -= int(margin_left) if margin_right is not None: width -= int(margin_right) return width if width > 0 else 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 fmt_data(text, data_formating = None, data_type = None): """ Format given text according to given data formating pattern or data type. """
if data_type: return DATA_TYPES[data_type](text) elif data_formating: return str(data_formating).format(text) return str(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 fmt_content(text, width = 0, align = '<', padding = None, padding_left = None, padding_right = None, padding_char = ' '): """ Pad given text with given padding characters, inflate it to given width and perform horizontal aligning. """
if padding_left is None: padding_left = padding if padding_right is None: padding_right = padding if padding_left is not None: text = '{}{}'.format(str(padding_char)[0] * int(padding_left), text) if padding_right is not None: text = '{}{}'.format(text, str(padding_char)[0] * int(padding_right)) if width: strptrn = '{:' + ('{}{}{}'.format(str(padding_char)[0], str(TEXT_ALIGNMENT[align]), str(width))) + 's}' text = strptrn.format(text) 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 fmt_text(text, bg = None, fg = None, attr = None, plain = False): """ Apply given console formating around given text. """
if not plain: if fg is not None: text = TEXT_FORMATING['fg'][fg] + text if bg is not None: text = TEXT_FORMATING['bg'][bg] + text if attr is not None: text = TEXT_FORMATING['attr'][attr] + text if (fg is not None) or (bg is not None) or (attr is not None): text += TEXT_FORMATING['rst'] 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 fmt_margin(text, margin = None, margin_left = None, margin_right = None, margin_char = ' '): """ Surround given text with given margin characters. """
if margin_left is None: margin_left = margin if margin_right is None: margin_right = margin if margin_left is not None: text = '{}{}'.format(str(margin_char)[0] * int(margin_left), text) if margin_right is not None: text = '{}{}'.format(text, str(margin_char)[0] * int(margin_right)) 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 bchar(posh, posv, border_style): """ Retrieve table border style for particular box border piece. """
index = '{}{}'.format(posv, posh).lower() return BORDER_STYLES[border_style][index]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _render_item(self, depth, key, value = None, **settings): """ Format single list item. """
strptrn = self.INDENT * depth lchar = self.lchar(settings[self.SETTING_LIST_STYLE]) s = self._es_text(settings, settings[self.SETTING_LIST_FORMATING]) lchar = self.fmt_text(lchar, **s) strptrn = "{}" if value is not None: strptrn += ": {}" s = self._es_text(settings, settings[self.SETTING_TEXT_FORMATING]) strptrn = self.fmt_text(strptrn.format(key, value), **s) return '{} {} {}'.format(self.INDENT * depth, lchar, strptrn)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def tchar(tree_style, cur_level, level, item, size): """ Retrieve tree character for particular tree node. """
if (cur_level == level): i1 = '1' if level == 0 else 'x' i2 = '1' if item == 0 else 'x' i3 = 'x' if size == 1: i3 = '1' elif item == (size - 1): i3 = 'l' index = '{}{}{}'.format(i1, i2, i3) else: index = 'non' if item == (size - 1) else 'ver' return TREE_STYLES[tree_style][index]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _render_item(self, dstack, key, value = None, **settings): """ Format single tree line. """
cur_depth = len(dstack) - 1 treeptrn = '' s = self._es_text(settings, settings[self.SETTING_TREE_FORMATING]) for ds in dstack: treeptrn += ' ' + self.fmt_text(self.tchar(settings[self.SETTING_TREE_STYLE], cur_depth, *ds), **s) + '' strptrn = "{}" if value is not None: strptrn += ": {}" s = self._es_text(settings, settings[self.SETTING_TEXT_FORMATING]) strptrn = self.fmt_text(strptrn.format(key, value), **s) return '{} {}'.format(treeptrn, strptrn)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _render_content_list(self, content, depth, dstack, **settings): """ Render the list. """
result = [] i = 0 size = len(content) for value in content: ds = [(depth, i, size)] ds = dstack + ds if isinstance(value, dict): result.append(self._render_item(ds, "[{}]".format(i), **settings)) result += self._render_content_dict(value, depth + 1, ds, **settings) elif isinstance(value, list): result.append(self._render_item(ds, "[{}]".format(i), **settings)) result += self._render_content_list(value, depth + 1, ds, **settings) else: result.append(self._render_item(ds, value, **settings)) i += 1 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 _render_content_dict(self, content, depth, dstack, **settings): """ Render the dict. """
result = [] i = 0 size = len(content) for key in sorted(content): ds = [(depth, i, size)] ds = dstack + ds if isinstance(content[key], dict): result.append(self._render_item(ds, key, **settings)) result += self._render_content_dict(content[key], depth + 1, ds, **settings) elif isinstance(content[key], list): result.append(self._render_item(ds, key, **settings)) result += self._render_content_list(content[key], depth + 1, ds, **settings) else: result.append(self._render_item(ds, key, content[key], **settings)) i += 1 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 _render_content(self, content, **settings): """ Render the tree widget. """
if isinstance(content, dict): return self._render_content_dict(content, 0, [], **settings) elif isinstance(content, list): return self._render_content_list(content, 0, [], **settings) else: raise Exception("Received invalid data tree for rendering.")
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def fmt_border(self, width, t = 'm', border_style = 'utf8.a', border_formating = {}): """ Format box separator line. """
border = self.bchar('l', t, border_style) + (self.bchar('h', t, border_style) * (width-2)) + self.bchar('r', t, border_style) return self.fmt_text(border, **border_formating)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _wrap_content(content, width): """ Wrap given content into lines of given width. """
data = [] if isinstance(content, list): data += content else: data.append(content) lines = [] for d in data: l = textwrap.wrap(d, width) lines += l return lines
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _render_border_line(self, t, settings): """ Render box border line. """
s = self._es(settings, self.SETTING_WIDTH, self.SETTING_MARGIN, self.SETTING_MARGIN_LEFT, self.SETTING_MARGIN_RIGHT) w = self.calculate_width_widget(**s) s = self._es(settings, self.SETTING_BORDER_STYLE, self.SETTING_BORDER_FORMATING) border_line = self.fmt_border(w, t, **s) s = self._es(settings, self.SETTING_MARGIN, self.SETTING_MARGIN_LEFT, self.SETTING_MARGIN_RIGHT, self.SETTING_MARGIN_CHAR) border_line = self.fmt_margin(border_line, **s) return border_line
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _render_line(self, line, settings): """ Render single box line. """
s = self._es(settings, self.SETTING_WIDTH, self.SETTING_FLAG_BORDER, self.SETTING_MARGIN, self.SETTING_MARGIN_LEFT, self.SETTING_MARGIN_RIGHT) width_content = self.calculate_width_widget_int(**s) s = self._es_content(settings) s[self.SETTING_WIDTH] = width_content line = self.fmt_content(line, **s) s = self._es_text(settings, settings[self.SETTING_TEXT_FORMATING]) line = self.fmt_text(line, **s) s = self._es(settings, self.SETTING_BORDER_STYLE) bchar = self.bchar('v', 'm', **s) s = self._es_text(settings, settings[self.SETTING_BORDER_FORMATING]) bchar = self.fmt_text(bchar, **s) line = '{}{}{}'.format(bchar, line, bchar) s = self._es_margin(settings) line = self.fmt_margin(line, **s) return line
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def fmt_border(self, dimensions, t = 'm', border_style = 'utf8.a', border_formating = {}): """ Format table separator line. """
cells = [] for column in dimensions: cells.append(self.bchar('h', t, border_style) * (dimensions[column] + 2)) border = '{}{}{}'.format(self.bchar('l', t, border_style), self.bchar('m', t, border_style).join(cells), self.bchar('r', t, border_style)) return self.fmt_text(border, **border_formating)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def fmt_cell(self, value, width, cell_formating, **text_formating): """ Format sigle table cell. """
strptrn = " {:" + '{:s}{:d}'.format(cell_formating.get('align', '<'), width) + "s} " strptrn = self.fmt_text(strptrn, **text_formating) return strptrn.format(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 fmt_row(self, columns, dimensions, row, **settings): """ Format single table row. """
cells = [] i = 0 for column in columns: cells.append(self.fmt_cell( row[i], dimensions[i], column, **settings[self.SETTING_TEXT_FORMATING] ) ) i += 1 return self.bchar('v', 'm', settings[self.SETTING_BORDER_STYLE], **settings[self.SETTING_BORDER_FORMATING]) + \ self.bchar('v', 'm', settings[self.SETTING_BORDER_STYLE], **settings[self.SETTING_BORDER_FORMATING]).join(cells) + \ self.bchar('v', 'm', settings[self.SETTING_BORDER_STYLE], **settings[self.SETTING_BORDER_FORMATING])
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def fmt_row_header(self, columns, dimensions, **settings): """ Format table header row. """
row = list(map(lambda x: x['label'], columns)) return self.fmt_row(columns, dimensions, row, **settings)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _render_bar(self, bar, value, max_value, label_width, bar_width, **settings): """ Render single chart bar. """
percent = value / max_value barstr = "" barstr += str(settings[self.SETTING_BAR_CHAR]) * int(bar_width * percent) s = {k: settings[k] for k in (self.SETTING_FLAG_PLAIN,)} s.update(settings[self.SETTING_BAR_FORMATING]) barstr = self.fmt_text(barstr, **s) barstr += ' ' * int(bar_width - int(bar_width * percent)) strptrn = "{:"+str(label_width)+"s} [{:s}]" return strptrn.format(bar.get('label'), barstr)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def build_select(query_obj): """ Given a Query obj, return the corresponding sql """
return build_select_query(query_obj.source, query_obj.fields, query_obj.filter, skip=query_obj.skip, \ limit=query_obj.limit, sort=query_obj.sort, distinct=query_obj.distinct)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def build_insert(table_name, attributes): """ Given the table_name and the data, return the sql to insert the data """
sql = "INSERT INTO %s" %(table_name) column_str = u"" value_str = u"" for index, (key, value) in enumerate(attributes.items()): if index > 0: column_str += u"," value_str += u"," column_str += key value_str += value_to_sql_str(value) sql = sql + u"(%s) VALUES(%s)" %(column_str, value_str) return sql
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def make_gatherer(cls, cell, source_tiers, gatherby): """ Produce a single source tier that gathers from a set of tiers when the key function returns a unique result for each tier. """
pending = collections.defaultdict(dict) tier_hashes = [hash(x) for x in source_tiers] @asyncio.coroutine def organize(route, *args): srchash = hash(route.source) key = gatherby(*args) group = pending[key] assert srchash not in group group[srchash] = args if len(group) == len(tier_hashes): del pending[key] yield from route.emit(*[group[x] for x in tier_hashes]) return cls(cell, organize)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def enqueue_task(self, source, *args): """ Enqueue a task execution. It will run in the background as soon as the coordinator clears it to do so. """
yield from self.cell.coord.enqueue(self) route = Route(source, self.cell, self.spec, self.emit) self.cell.loop.create_task(self.coord_wrap(route, *args)) # To guarantee that the event loop works fluidly, we manually yield # once. The coordinator enqueue coroutine is not required to yield so # this ensures we avoid various forms of event starvation regardless. yield
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def coord_wrap(self, *args): """ Wrap the coroutine with coordination throttles. """
yield from self.cell.coord.start(self) yield from self.coro(*args) yield from self.cell.coord.finish(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 flush(self): """ Flush the buffer of buffered tiers to our destination tiers. """
if self.buffer is None: return data = self.buffer self.buffer = [] for x in self.dests: yield from x.enqueue_task(self, *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 add_source(self, tier): """ Schedule this tier to be called when another tier emits. """
tier.add_dest(self) self.sources.append(tier)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def close(self): """ Free any potential cycles. """
self.cell = None self.coro = None self.buffer = None del self.dests[:] del self.sources[:]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def add_arguments(parser): '''Add command-line arguments for yakonfig proper. This is part of the :class:`~yakonfig.Configurable` interface, and is usually run by including :mod:`yakonfig` in the :func:`parse_args()` module list. :param argparse.ArgumentParser parser: command-line argument parser ''' parser.add_argument('--config', '-c', metavar='FILE', help='read configuration from FILE') parser.add_argument('--dump-config', metavar='WHAT', nargs='?', help='dump out configuration then stop ' '(default, effective, full)')
<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_args(parser, modules, args=None): """Set up global configuration for command-line tools. `modules` is an iterable of :class:`yakonfig.Configurable` objects, or anything equivalently typed. This function iterates through those objects and calls :meth:`~yakonfig.Configurable.add_arguments` on each to build up a complete list of command-line arguments, then calls :meth:`argparse.ArgumentParser.parse_args` to actually process the command line. This produces a configuration that is a combination of all default values declared by all modules; configuration specified in ``--config`` arguments; and overriding configuration values specified in command-line arguments. This returns the :class:`argparse.Namespace` object, in case the application has defined its own command-line parameters and needs to process them. The new global configuration can be obtained via :func:`yakonfig.get_global_config`. :param argparse.ArgumentParser parser: application-provided argument parser :param modules: modules or Configurable instances to use :type modules: iterable of :class:`~yakonfig.Configurable` :param args: command-line options, or `None` to use `sys.argv` :return: the new global configuration """
collect_add_argparse(parser, modules) namespace = parser.parse_args(args) try: do_dump_config = getattr(namespace, 'dump_config', None) set_default_config(modules, params=vars(namespace), validate=not do_dump_config) if do_dump_config: if namespace.dump_config == 'full': to_dump = get_global_config() elif namespace.dump_config == 'default': to_dump = assemble_default_config(modules) else: # 'effective' to_dump = diff_config(assemble_default_config(modules), get_global_config()) yaml_mod.dump(to_dump, sys.stdout) parser.exit() except ConfigurationError as e: parser.error(e) return namespace
<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_default_config(modules, params=None, yaml=None, filename=None, config=None, validate=True): """Set up global configuration for tests and noninteractive tools. `modules` is an iterable of :class:`yakonfig.Configurable` objects, or anything equivalently typed. This function iterates through those objects to produce a default configuration, reads `yaml` as though it were the configuration file, and fills in any values from `params` as though they were command-line arguments. The resulting configuration is set as the global configuration. :param modules: modules or Configurable instances to use :type modules: iterable of :class:`~yakonfig.Configurable` :param dict params: dictionary of command-line argument key to values :param str yaml: global configuration file :param str filename: location of global configuration file :param dict config: global configuration object :param bool validate: check configuration after creating :return: the new global configuration :returntype: dict """
if params is None: params = {} # Get the configuration from the file, or from params['config'] file_config = {} if yaml is None and filename is None and config is None: if 'config' in params and params['config'] is not None: filename = params['config'] if yaml is not None or filename is not None or config is not None: if yaml is not None: file_config = yaml_mod.load(StringIO(yaml)) elif filename is not None: with open(filename, 'r') as f: file_config = yaml_mod.load(f) elif config is not None: file_config = config # First pass: set up to call replace_config() # Assemble the configuration from defaults + file + arguments base_config = copy.deepcopy(file_config) create_config_tree(base_config, modules) fill_in_arguments(base_config, modules, params) default_config = assemble_default_config(modules) base_config = overlay_config(default_config, base_config) # Replace the modules list (accommodate external modules) def replace_module(config, m): name = getattr(m, 'config_name') c = config.get(name, {}) if hasattr(m, 'replace_config'): return getattr(m, 'replace_config')(c, name) return m modules = [replace_module(base_config, m) for m in modules] # Reassemble the configuration again, this time reaching out to # the environment base_config = file_config create_config_tree(base_config, modules) fill_in_arguments(base_config, modules, params) do_config_discovery(base_config, modules) default_config = assemble_default_config(modules) base_config = overlay_config(default_config, file_config) fill_in_arguments(base_config, modules, params) # Validate the configuration if validate and len(modules) > 0: mod = modules[-1] checker = getattr(mod, 'check_config', None) if checker is not None: with _temporary_config(): set_global_config(base_config) checker(base_config[mod.config_name], mod.config_name) # All done, normalize and set the global configuration normalize_config(base_config, modules) set_global_config(base_config) return base_config
<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_toplevel_config(what, who): """Verify that some dependent configuration is present and correct. This will generally be called from a :meth:`~yakonfig.Configurable.check_config` implementation. `what` is a :class:`~yakonfig.Configurable`-like object. If the corresponding configuration isn't present in the global configuration, raise a :exc:`yakonfig.ConfigurationError` explaining that `who` required it. Otherwise call that module's :meth:`~yakonfig.Configurable.check_config` (if any). :param yakonfig.Configurable what: top-level module to require :param str who: name of the requiring module :raise yakonfig.ConfigurationError: if configuration for `what` is missing or incorrect """
config_name = what.config_name config = get_global_config() if config_name not in config: raise ConfigurationError( '{0} requires top-level configuration for {1}' .format(who, config_name)) checker = getattr(what, 'check_config', None) if checker: checker(config[config_name], config_name)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def _recurse_config(parent_config, modules, f, prefix=''): '''Walk through the module tree. This is a helper function for :func:`create_config_tree` and :func:`_walk_config`. It calls `f` once for each module in the configuration tree with parameters `parent_config`, `config_name`, `prefix`, and `module`. `parent_config[config_name]` may or may not exist (but could be populated, as :func:`create_config_tree`). If even the parent configuration doesn't exist, `parent_config` could be :const:`None`. :param dict parent_config: configuration dictionary holding configuration for `modules`, or maybe :const:`None` :param modules: modules or Configurable instances to use :type modules: iterable of :class:`~yakonfig.configurable.Configurable` :param f: callable to call on each module :param str prefix: prefix name of `parent_config` :return: `parent_config` ''' for module in modules: config_name = getattr(module, 'config_name', None) if config_name is None: raise ProgrammerError('{0!r} must provide a config_name' .format(module)) new_name = prefix + config_name f(parent_config, config_name, new_name, module) try: _recurse_config((parent_config or {}).get(config_name, None), getattr(module, 'sub_modules', []), f, new_name + '.') except: # achieve a sort of stack trace on the way out logger.error('exception in _recurse_config of %s', module) raise return parent_config
<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_config_tree(config, modules, prefix=''): '''Cause every possible configuration sub-dictionary to exist. This is intended to be called very early in the configuration sequence. For each module, it checks that the corresponding configuration item exists in `config` and creates it as an empty dictionary if required, and then recurses into child configs/modules. :param dict config: configuration to populate :param modules: modules or Configurable instances to use :type modules: iterable of :class:`~yakonfig.configurable.Configurable` :param str prefix: prefix name of the config :return: `config` :raises yakonfig.ConfigurationError: if an expected name is present in the provided config, but that name is not a dictionary ''' def work_in(parent_config, config_name, prefix, module): if config_name not in parent_config: # this is the usual, expected case parent_config[config_name] = {} elif not isinstance(parent_config[config_name], collections.Mapping): raise ConfigurationError( '{0} must be an object configuration'.format(prefix)) else: # config_name is a pre-existing dictionary in parent_config pass _recurse_config(config, modules, work_in)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _walk_config(config, modules, f, prefix=''): """Recursively walk through a module list. For every module, calls ``f(config, module, name)`` where `config` is the configuration scoped to that module, `module` is the Configurable-like object, and `name` is the complete path (ending in the module name). :param dict config: configuration to walk and possibly update :param modules: modules or Configurable instances to use :type modules: iterable of :class:`~yakonfig.configurable.Configurable` :param f: callback function for each module :param str prefix: prefix name of the config :return: config """
def work_in(parent_config, config_name, prefix, module): # create_config_tree() needs to have been called by now # and you should never hit either of these asserts if config_name not in parent_config: raise ProgrammerError('{0} not present in configuration' .format(prefix)) if not isinstance(parent_config[config_name], collections.Mapping): raise ConfigurationError( '{0} must be an object configuration'.format(prefix)) # do the work! f(parent_config[config_name], module, prefix) return _recurse_config(config, modules, work_in)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def collect_add_argparse(parser, modules): """Add all command-line options. `modules` is an iterable of :class:`yakonfig.configurable.Configurable` objects, or anything equivalently typed. This calls :meth:`~yakonfig.configurable.Configurable.add_arguments` (if present) on all of them to set the global command-line arguments. :param argparse.ArgumentParser parser: argparse parser :param modules: modules or Configurable instances to use :type modules: iterable of :class:`~yakonfig.configurable.Configurable` """
def work_in(parent_config, config_name, prefix, module): f = getattr(module, 'add_arguments', None) if f is not None: f(parser) _recurse_config(dict(), modules, work_in) return parser
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def assemble_default_config(modules): """Build the default configuration from a set of modules. `modules` is an iterable of :class:`yakonfig.configurable.Configurable` objects, or anything equivalently typed. This produces the default configuration from that list of modules. :param modules: modules or Configurable instances to use :type modules: iterable of :class:`~yakonfig.configurable.Configurable` :return: configuration dictionary """
def work_in(parent_config, config_name, prefix, module): my_config = dict(getattr(module, 'default_config', {})) if config_name in parent_config: extra_config = parent_config[config_name] raise ProgrammerError( 'config for {0} already present when about to fetch {3}.default_config (had {1!r} would have set {2!r})'.format( prefix, extra_config, my_config, module)) parent_config[config_name] = my_config return _recurse_config(dict(), modules, work_in)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def fill_in_arguments(config, modules, args): """Fill in configuration fields from command-line arguments. `config` is a dictionary holding the initial configuration, probably the result of :func:`assemble_default_config`. It reads through `modules`, and for each, fills in any configuration values that are provided in `args`. `config` is modified in place. `args` may be either a dictionary or an object (as the result of :mod:`argparse`). :param dict config: configuration tree to update :param modules: modules or Configurable instances to use :type modules: iterable of :class:`~yakonfig.configurable.Configurable` :param args: command-line objects :paramtype args: dict or object :return: config """
def work_in(config, module, name): rkeys = getattr(module, 'runtime_keys', {}) for (attr, cname) in iteritems(rkeys): v = args.get(attr, None) if v is not None: config[cname] = v if not isinstance(args, collections.Mapping): args = vars(args) return _walk_config(config, modules, work_in)
<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_config_discovery(config, modules): '''Let modules detect additional configuration values. `config` is the initial dictionary with command-line and file-derived values, but nothing else, filled in. This calls :meth:`yakonfig.configurable.Configurable.discover_config` on every configuration module. It is expect that this method will modify the passed-in configuration dictionaries in place. :param dict config: configuration tree to update :param modules: modules or Configurable instances to use :type modules: iterable of :class:`~yakonfig.configurable.Configurable` :return: `config` ''' def work_in(config, module, name): f = getattr(module, 'discover_config', None) if f: f(config, name) return _walk_config(config, modules, work_in)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def main(arguments=None, config=None): """ Parse arguments for ``idid`` command. Pass optional parameter ``arguments`` as either command line string or list of options. This is mainly useful for testing. ``config`` can be passed in as a path or string to access user defined values for important variables manually. YAML only. Returns the saved logg string. """
# Parse options, initialize gathered stats options = LoggOptions(arguments=arguments).parse() # FIXME: pass in only config; set config.journal = options.journal if not config: config = options.config_file logg = Logg(config, options.journal) return logg.logg_record(options.logg, options.date)
<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(self, opts, args): """ Perform additional check for ``idid`` command arguments """
k_args = len(args) _dt = opts.date = None logg = opts.logg = None journal = opts.journal = None default_journal = self.config.get('default_journal') _journals = self.config.get('journals') or {} log.debug(' ... got {0} args [{1}]'.format(k_args, args)) if k_args == 0 and default_journal: # launch the editor to save a message into 'default' branch # FIXME: 'unsorted' should be configurable as 'default branch' log.warn('Target branch not set, using "{0}"'.format( default_journal)) journal, logg = default_journal, '--' elif k_args == 1: # NOTE: two different usage patterns can be expected here # 1) idid journal # launch EDITOR for logg in target journal # 2) idid 'logg record' # save under default branch 'unsorted' # if we have a value that's got more than one word in it, we # assume it's a logg (B), otherwise (A) arg = args.pop() k_words = len(arg.split()) # variant A); user wants to launch the editor # variany B); user wants to save record to 'master' branch # default to an unspecified, unsorted target journal since # journal not specified if k_words == 1: journal, logg = (arg, '--') elif default_journal: journal, logg = (default_journal, arg) else: raise RuntimeError('UNKNOWN ERROR') elif k_args == 2: # variants: # 1) idid [datetime] 'logg message' # 2) idid [datetime] journal # launch editor # 3) idid journal 'logg message' # 4) idid unquoted logg message _one = args[0].strip() _two = args[1].strip() # try to parse a date from the value _dt = self._parse_date(_one, DT_ISO_FMT) if _dt: if _two in _journals: # scenario 2) journal, logg = (_two, '--') else: # scenario 1) journal, logg = (_two, _one) elif _one in _journals: # senario 3) journal, logg = (_one, _two) elif default_journal: # senario 4) journal, logg = (default_journal, _two) else: raise RuntimeError("No journal specified.") elif k_args >= 3: # variants: # 1) idid [datetime] journal 'message' # 2) idid [datetime] unquoted logg # 3) idid journal unquoted logg _one = args[0] _two = args[1] _three = ' '.join(args[2:]) # try to parse a date from the value _dt = self._parse_date(_one, DT_ISO_FMT) if _dt: if _two in _journals: # scenario 1) journal, logg = (_two, _three) elif default_journal: # scenario 2) journal, logg = (_two, ' '.join(args[1:])) else: raise RuntimeError("No journal specified.") elif _one in _journals: # senario 3) journal, logg = (_one, ' '.join(args[1:])) elif default_journal: # senario 4) journal, logg = (default_journal, ' '.join(args[:])) else: raise RuntimeError("No journal specified.") else: raise RuntimeError("Ambiguous command line arguments!") opts.date = _dt or utils.Date('today', fmt=DT_ISO_FMT) opts.journal = journal opts.logg = logg log.debug(' Found Date: {0}'.format(_dt)) log.debug(' Found Target: {0}'.format(journal)) log.debug(' Found Logg: {0}'.format(logg)) return opts
<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_root_tex_document(base_dir="."): """Find the tex article in the current directory that can be considered a root. We do this by searching contents for ``'\documentclass'``. Parameters base_dir : str Directory to search for LaTeX documents, relative to the current working directory. Returns ------- tex_path : str Path to the root tex document relative to the current working directory. """
log = logging.getLogger(__name__) for tex_path in iter_tex_documents(base_dir=base_dir): with codecs.open(tex_path, 'r', encoding='utf-8') as f: text = f.read() if len(docclass_pattern.findall(text)) > 0: log.debug("Found root tex {0}".format(tex_path)) return tex_path log.warning("Could not find a root .tex file") raise RootNotFound
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def iter_tex_documents(base_dir="."): """Iterate through all .tex documents in the current directory."""
for path, dirlist, filelist in os.walk(base_dir): for name in fnmatch.filter(filelist, "*.tex"): yield os.path.join(path, name)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def inline(root_text, base_dir="", replacer=None, ifexists_replacer=None): """Inline all input latex files. The inlining is accomplished recursively. All files are opened as UTF-8 unicode files. Parameters root_txt : unicode Text to process (and include in-lined files). base_dir : str Base directory of file containing ``root_text``. Defaults to the current working directory. replacer : function Function called by :func:`re.sub` to replace ``\input`` expressions with a latex document. Changeable only for testing purposes. ifexists_replacer : function Function called by :func:`re.sub` to replace ``\InputIfExists`` expressions with a latex document. Changeable only for testing purposes. Returns ------- txt : unicode Text with referenced files included. """
def _sub_line(match): """Function to be used with re.sub to inline files for each match.""" fname = match.group(1) if not fname.endswith('.tex'): full_fname = ".".join((fname, 'tex')) else: full_fname = fname full_path = os.path.abspath(os.path.join(base_dir, full_fname)) try: with codecs.open(full_path, 'r', encoding='utf-8') as f: included_text = f.read() except IOError: # TODO actually do logging here print("Cannot open {0} for in-lining".format(full_path)) return u"" else: # Recursively inline files included_text = inline(included_text, base_dir=base_dir) return included_text def _sub_line_ifexists(match): """Function to be used with re.sub for the input_ifexists_pattern.""" fname = match.group(1) if not fname.endswith('.tex'): full_fname = ".".join((fname, 'tex')) else: full_fname = fname full_path = os.path.abspath(os.path.join(base_dir, full_fname)) if os.path.exists(full_path): with codecs.open(full_path, 'r', encoding='utf-8') as f: included_text = f.read() # Append extra info after input included_text = "\n".join((included_text, match.group(2))) else: # Use the fall-back clause in InputIfExists included_text = match.group(3) # Recursively inline files included_text = inline(included_text, base_dir=base_dir) return included_text # Text processing pipline result = remove_comments(root_text) result = input_pattern.sub(_sub_line, result) result = include_pattern.sub(_sub_line, result) result = input_ifexists_pattern.sub(_sub_line_ifexists, result) return result
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def inline_blob(commit_ref, root_text, base_dir='.', repo_dir=""): """Inline all input latex files that exist as git blobs in a tree object. The inlining is accomplished recursively. All files are opened as UTF-8 unicode files. Parameters commit_ref : str String identifying a git commit/tag. root_text : unicode Text of tex document where referenced files will be inlined. base_dir : str Directory of the master tex document, relative to the repo_dir. repo_dir : str Directory of the containing git repository. Returns ------- txt : unicode Text with referenced files included. """
def _sub_blob(match): """Function to be used with re.sub to inline files for each match.""" fname = match.group(1) if not fname.endswith('.tex'): full_fname = ".".join((fname, 'tex')) else: full_fname = fname git_rel_path = os.path.relpath(full_fname, base_dir) included_text = read_git_blob(commit_ref, git_rel_path, repo_dir=repo_dir) if included_text is None: # perhaps file is not in VC # FIXME need to deal with possibility # it does not exist there either with codecs.open(full_fname, 'r', encoding='utf-8') as f: included_text = f.read() # Recursively inline files included_text = inline_blob(commit_ref, included_text, base_dir=base_dir, repo_dir=repo_dir) return included_text def _sub_blob_ifexists(match): """Function to be used with re.sub for the input_ifexists_pattern.""" fname = match.group(1) if not fname.endswith('.tex'): full_fname = ".".join((fname, 'tex')) else: full_fname = fname # full_fname is relative to the root_path # Make path relative to git repo root git_rel_path = os.path.relpath( os.path.join(repo_dir, base_dir, full_fname), repo_dir) included_text = read_git_blob(commit_ref, git_rel_path, repo_dir=repo_dir) if included_text is not None: # Append extra info after input included_text = "\n".join((included_text, match.group(2))) if included_text is None: # Use the fall-back clause in InputIfExists included_text = match.group(3) # Recursively inline files included_text = inline_blob(commit_ref, included_text, base_dir=base_dir, repo_dir=repo_dir) return included_text # Text processing pipline result = remove_comments(root_text) result = input_pattern.sub(_sub_blob, result) result = include_pattern.sub(_sub_blob, result) result = input_ifexists_pattern.sub(_sub_blob_ifexists, result) return result
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _get(self, uri, options): """ Quick and dirty wrapper around the requests object to do some simple data catching :params uri: a string, the uri you want to request :params options: a dict, the list of parameters you want to use """
url = "http://%s/%s" % (self.host, uri) r = requests.get(url, params=options) if r.status_code == 200: data = r.json() return data['results'] else: # Throws anything not 200 error r.raise_for_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 setWindowTitle(self, newTitle=''): """Prepend Rampage to all window titles."""
title = 'Rampage - ' + newTitle super(MainWindow, self).setWindowTitle(title)
<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(jwks): """Parse a JWKSet and return a dictionary that maps key IDs on keys."""
sign_keys = {} verify_keys = {} try: keyset = json.loads(jwks) for key in keyset['keys']: for op in key['key_ops']: if op == 'sign': k = sign_keys elif op == 'verify': k = verify_keys else: raise JWKError("Unsupported key operation: {}".format(op)) if key['kty'] == 'oct': k[key['kid']] = _Key(alg=key['alg'], key=base64.urlsafe_b64decode(key['k'])) elif key['kty'] == 'EC': alg, ec_key = _load_ecdsa(key, op == 'verify') k[key['kid']] = _Key(alg=alg, key=ec_key) else: raise JWKError("Unsupported key type: {}".format(key['kty'])) except (KeyError, json.JSONDecodeError) as e: raise JWKError() from e keys = _KeySet(signers=MappingProxyType(sign_keys), verifiers=MappingProxyType(verify_keys)) return 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 version(): """ Get the local package version. """
path = join("lib", _CONFIG["name"], "__version__.py") with open(path) as stream: exec(stream.read()) return __version__
<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_config_path(self): """ Reads config path from environment variable CLOEEPY_CONFIG_PATH and sets as instance attr """
self._path = os.getenv("CLOEEPY_CONFIG_PATH") if self._path is None: msg = "CLOEEPY_CONFIG_PATH is not set. Exiting..." sys.exit(msg)
<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_config(self): """ Loads the YAML configuration file and sets python dictionary and raw contents as instance attrs. """
if not os.path.exists(self._path): sys.exit("Config path %s does not exist" % self._path) # create empty config object self._config_dict = {} # read file and marshal yaml with open(self._path, 'r') as f: self._raw = f.read() self._config_dict = yaml.load(self._raw)
<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_attributes(self): """ Recursively transforms config dictionaries into instance attrs to make for easy dot attribute access instead of dictionary access. """
# turn config dict into nested objects config = obj(self._config_dict) # set the attributes onto instance for k, v in self._config_dict.items(): setattr(self, k, getattr(config, k))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def highlight(__text: str, *, lexer: str = 'diff', formatter: str = 'terminal') -> str: """Highlight text highlighted using ``pygments``. Returns text untouched if colour output is not enabled. See also: :pypi:`Pygments` Args: __text: Text to highlight lexer: Jinja lexer to use formatter: Jinja formatter to use Returns: Syntax highlighted output, when possible """
if sys.stdout.isatty(): lexer = get_lexer_by_name(lexer) formatter = get_formatter_by_name(formatter) __text = pyg_highlight(__text, lexer, formatter) 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 html2text(__html: str, *, width: int = 80, ascii_replacements: bool = False) -> str: """HTML to plain text renderer. See also: :pypi:`html2text` Args: __html: Text to process width: Paragraph width ascii_replacements: Use pseudo-ASCII replacements for Unicode Returns: Rendered text """
html2.BODY_WIDTH = width html2.UNICODE_SNOB = ascii_replacements return html2.html2text(__html).strip()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def regexp(__string: str, __pattern: str, __repl: Union[Callable, str], *, count: int = 0, flags: int = 0) -> str: """Jinja filter for regexp replacements. See :func:`re.sub` for documentation. Returns: Text with substitutions applied """
return re.sub(__pattern, __repl, __string, count, flags)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def setup(__pkg: str) -> jinja2.Environment: """Configure a new Jinja environment with our filters. Args: __pkg: Package name to use as base for templates searches Returns: Configured Jinja environment """
dirs = [path.join(d, 'templates') for d in xdg_basedir.get_data_dirs(__pkg)] env = jinja2.Environment( autoescape=jinja2.select_autoescape(['html', 'xml']), loader=jinja2.ChoiceLoader([jinja2.FileSystemLoader(s) for s in dirs])) env.loader.loaders.append(jinja2.PackageLoader(__pkg, 'templates')) env.filters.update(FILTERS) return env
<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_intercom_user(obj_id): """Creates or updates single user account on intercom"""
UserModel = get_user_model() intercom_user = False instance = UserModel.objects.get(pk=obj_id) data = instance.get_intercom_data() if not getattr(settings, "SKIP_INTERCOM", False): try: intercom_user = intercom.users.create(**data) except errors.ServiceUnavailableError: pass if intercom_user: UserModel.objects.filter(pk=obj_id).update( intercom_last_api_response=intercom_user.to_dict(), intercom_api_response_timestamp=make_aware(datetime.now(), pytz.UTC) )
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def LoadExclusions(self, snps): """ Load locus exclusions. :param snps: Can either be a list of rsids or a file containing rsids. :return: None If snps is a file, the file must only contain RSIDs separated by whitespace (tabs, spaces and return characters). """
snp_names = [] if len(snps) == 1 and os.path.isfile(snps[0]): snp_names = open(snps).read().strip().split() else: snp_names = snps for snp in snp_names: if len(snp.strip()) > 0: self.ignored_rs.append(snp)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def getserialnum(flist): """ This function assumes the serial number of the camera is in a particular place in the filename. Yes, this is a little lame, but it's how the original 2011 image-writing program worked, and I've carried over the scheme rather than appending bits to dozens of TB of files. """
sn = [] for f in flist: tmp = search(r'(?<=CamSer)\d{3,6}', f) if tmp: ser = int(tmp.group()) else: ser = None sn.append(ser) return sn
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def getDMCparam(fn: Path, xyPix, xyBin, FrameIndReq=None, ut1req=None, kineticsec=None, startUTC=None, nHeadBytes=4, verbose=0): """ nHeadBytes=4 for 2013-2016 data nHeadBytes=0 for 2011 data """
Nmetadata = nHeadBytes // 2 # FIXME for DMCdata version 1 only if not fn.is_file(): # leave this here, getsize() doesn't fail on directory raise ValueError(f'{fn} is not a file!') print(f'reading {fn}') # int() in case we are fed a float or int SuperX = int(xyPix[0] // xyBin[0]) SuperY = int(xyPix[1] // xyBin[1]) PixelsPerImage, BytesPerImage, BytesPerFrame = howbig( SuperX, SuperY, nHeadBytes) (firstRawInd, lastRawInd) = getRawInd( fn, BytesPerImage, nHeadBytes, Nmetadata) FrameIndRel = whichframes(fn, FrameIndReq, kineticsec, ut1req, startUTC, firstRawInd, lastRawInd, BytesPerImage, BytesPerFrame, verbose) return {'superx': SuperX, 'supery': SuperY, 'nmetadata': Nmetadata, 'bytesperframe': BytesPerFrame, 'pixelsperimage': PixelsPerImage, 'nframeextract': FrameIndRel.size, 'frameindrel': FrameIndRel}
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def whichframes(fn, FrameIndReq, kineticsec, ut1req, startUTC, firstRawInd, lastRawInd, BytesPerImage, BytesPerFrame, verbose): ext = Path(fn).suffix # %% get file size fileSizeBytes = fn.stat().st_size if fileSizeBytes < BytesPerImage: raise ValueError( f'File size {fileSizeBytes} is smaller than a single image frame!') if ext == '.DMCdata' and fileSizeBytes % BytesPerFrame: logging.error( f"Looks like I am not reading this file correctly, with BPF: {BytesPerFrame:d}") if ext == '.DMCdata': nFrame = fileSizeBytes // BytesPerFrame print(f'{nFrame} frames, Bytes: {fileSizeBytes} in file {fn}') nFrameRaw = (lastRawInd - firstRawInd + 1) if nFrameRaw != nFrame: logging.warning( f'there may be missed frames: nFrameRaw {nFrameRaw} nFrame {nFrame}') else: nFrame = lastRawInd - firstRawInd + 1 allrawframe = arange(firstRawInd, lastRawInd + 1, 1, dtype=int64) print(f"first / last raw frame #'s: {firstRawInd} / {lastRawInd} ") # %% absolute time estimate ut1_unix_all = frame2ut1(startUTC, kineticsec, allrawframe) # %% setup frame indices """ if no requested frames were specified, read all frames. Otherwise, just return the requested frames Assignments have to be "int64", not just python "int". Windows python 2.7 64-bit on files >2.1GB, the bytes will wrap """
FrameIndRel = ut12frame(ut1req, arange(0, nFrame, 1, dtype=int64), ut1_unix_all) # NOTE: no ut1req or problems with ut1req, canNOT use else, need to test len() in case index is [0] validly if FrameIndRel is None or len(FrameIndRel) == 0: FrameIndRel = req2frame(FrameIndReq, nFrame) badReqInd = (FrameIndRel > nFrame) | (FrameIndRel < 0) # check if we requested frames beyond what the BigFN contains if badReqInd.any(): # don't include frames in case of None raise ValueError(f'frames requested outside the times covered in {fn}') nFrameExtract = FrameIndRel.size # to preallocate properly nBytesExtract = nFrameExtract * BytesPerFrame print( f'Extracted {nFrameExtract} frames from {fn} totaling {nBytesExtract/1e9:.2f} GB.') if nBytesExtract > 4e9: print(f'This will require {nBytesExtract/1e9:.2f} GB of RAM.') return FrameIndRel
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def getDMCframe(f, iFrm: int, finf: dict, verbose: bool=False): """ f is open file handle """
# on windows, "int" is int32 and overflows at 2.1GB! We need np.int64 currByte = iFrm * finf['bytesperframe'] # %% advance to start of frame in bytes if verbose: print(f'seeking to byte {currByte}') assert isinstance(iFrm, (int, int64)), 'int32 will fail on files > 2GB' try: f.seek(currByte, 0) except IOError as e: raise IOError(f'I couldnt seek to byte {currByte:d}. try using a 64-bit integer for iFrm \n' 'is {f.name} a DMCdata file? {e}') # %% read data ***LABVIEW USES ROW-MAJOR C ORDERING!! try: currFrame = fromfile(f, uint16, finf['pixelsperimage']).reshape((finf['supery'], finf['superx']), order='C') except ValueError as e: raise ValueError(f'read past end of file? {e}') rawFrameInd = meta2rawInd(f, finf['nmetadata']) if rawFrameInd is None: # 2011 no metadata file rawFrameInd = iFrm + 1 # fallback return currFrame, rawFrameInd
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _fixSize(self): """Fix the menu size. Commonly called when the font is changed"""
self.height = 0 for o in self.options: text = o['label'] font = o['font'] ren = font.render(text, 1, (0, 0, 0)) if ren.get_width() > self.width: self.width = ren.get_width() self.height += font.get_height()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def draw(self, surface): """Blit the menu to a surface."""
offset = 0 i = 0 ol, ot = self.screen_topleft_offset first = self.options and self.options[0] last = self.options and self.options[-1] for o in self.options: indent = o.get('padding_col', 0) # padding above the line if o != first and o.get('padding_line', 0): offset += o['padding_line'] font = o.get('font', self._font) if i == self.option and self.focus_color: clr = self.focus_color else: clr = self.color text = o['label'] ren = font.render(text, 1, clr) if ren.get_width() > self.width: self.width = ren.get_width() o['label_rect'] = pygame.Rect( (ol + self.x + indent, ot + self.y + offset), (ren.get_width(), ren.get_height()), ) surface.blit(ren, (self.x + indent, self.y + offset)) offset += font.get_height() # padding below the line if o != last and o.get('padding_line', 0): offset += o['padding_line'] i += 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 update(self, events, time_passed=None): """Update the menu and get input for the menu. @events: the pygame catched events @time_passed: delta time since the last call """
for e in events: if e.type == pygame.QUIT: raise SystemExit if e.type == pygame.KEYDOWN: if e.key == pygame.K_ESCAPE: raise SystemExit if e.key == pygame.K_DOWN: self.option += 1 if e.key == pygame.K_UP: self.option -= 1 if e.key == pygame.K_RETURN or e.key == pygame.K_SPACE: self.options[self.option]['callable']() # Mouse controls elif e.type == pygame.MOUSEBUTTONDOWN: lb, cb, rb = pygame.mouse.get_pressed() if lb: self.options[self.option]['callable']() # Menu limits if self.option > len(self.options) - 1: self.option = len(self.options) - 1 elif self.option < 0: self.option = 0 # Check for mouse position if self.mouse_enabled: self._checkMousePositionForFocus() if time_passed: self._updateEffects(time_passed)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _checkMousePositionForFocus(self): """Check the mouse position to know if move focus on a option"""
i = 0 cur_pos = pygame.mouse.get_pos() ml, mt = self.position for o in self.options: rect = o.get('label_rect') if rect: if rect.collidepoint(cur_pos) and self.mouse_pos != cur_pos: self.option = i self.mouse_pos = cur_pos break i += 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 center_at(self, x, y): """Center the menu at x, y"""
self.x = x - (self.width / 2) self.y = y - (self.height / 2)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def run_bots(bots): """ Run many bots in parallel. :param bots: IRC bots to run. :type bots: list """
greenlets = [spawn(bot.run) for bot in bots] try: joinall(greenlets) except KeyboardInterrupt: for bot in bots: bot.disconnect() finally: killall(greenlets)
<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(cls, data): """ Extracts message informations from `data`. :param data: received line. :type data: unicode :return: extracted informations (source, destination, command, args). :rtype: tuple(Source, str, str, list) :raise: :class:`fatbotslim.irc.NullMessage` if `data` is empty. """
src = u'' dst = None if data[0] == u':': src, data = data[1:].split(u' ', 1) if u' :' in data: data, trailing = data.split(u' :', 1) args = data.split() args.extend(trailing.split()) else: args = data.split() command = args.pop(0) if command in (PRIVMSG, NOTICE): dst = args.pop(0) if ctcp_re.match(args[0]): args = args[0].strip(u'\x01').split() command = u'CTCP_' + args.pop(0) return Source(src), dst, command, args
<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(cls, prefix): """ Extracts informations from `prefix`. :param prefix: prefix with format ``<servername>|<nick>['!'<user>]['@'<host>]``. :type prefix: unicode :return: extracted informations (nickname or host, mode, username, host). :rtype: tuple(str, str, str, str) """
try: nick, rest = prefix.split(u'!') except ValueError: return prefix, None, None, None try: mode, rest = rest.split(u'=') except ValueError: mode, rest = None, rest try: user, host = rest.split(u'@') except ValueError: return nick, mode, rest, None return nick, mode, user, host
<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_connection(self): """ Creates a transport channel. :return: transport channel instance :rtype: :class:`fatbotslim.irc.tcp.TCP` or :class:`fatbotslim.irc.tcp.SSL` """
transport = SSL if self.ssl else TCP return transport(self.server, self.port)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _connect(self): """ Connects the bot to the server and identifies itself. """
self.conn = self._create_connection() spawn(self.conn.connect) self.set_nick(self.nick) self.cmd(u'USER', u'{0} 3 * {1}'.format(self.nick, self.realname))
<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, command): """ Sends a raw line to the server. :param command: line to send. :type command: unicode """
command = command.encode('utf-8') log.debug('>> ' + command) self.conn.oqueue.put(command)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _handle(self, msg): """ Pass a received message to the registered handlers. :param msg: received message :type msg: :class:`fatbotslim.irc.Message` """
def handler_yielder(): for handler in self.handlers: yield handler def handler_callback(_): if msg.propagate: try: h = hyielder.next() g = self._pool.spawn(handler_runner, h) g.link(handler_callback) except StopIteration: pass def handler_runner(h): for command in h.commands: if command == msg.command: method = getattr(h, h.commands[command]) method(msg) hyielder = handler_yielder() try: next_handler = hyielder.next() g = self._pool.spawn(handler_runner, next_handler) g.link(handler_callback) except StopIteration: pass
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def randomize_nick(cls, base, suffix_length=3): """ Generates a pseudo-random nickname. :param base: prefix to use for the generated nickname. :type base: unicode :param suffix_length: amount of digits to append to `base` :type suffix_length: int :return: generated nickname. :rtype: unicode """
suffix = u''.join(choice(u'0123456789') for _ in range(suffix_length)) return u'{0}{1}'.format(base, suffix)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def add_handler(self, handler, args=None, kwargs=None): """ Registers a new handler. :param handler: handler to register. :type handler: :class:`fatbotslim.handlers.BaseHandler` :param args: positional arguments to pass to the handler's constructor. :type args: list :param kwargs: keyword arguments to pass to the handler's constructor. :type kwargs: dict """
args = [] if args is None else args kwargs = {} if kwargs is None else kwargs handler_instance = handler(self, *args, **kwargs) if isinstance(handler_instance, RightsHandler): self.rights = handler_instance if handler_instance not in self.handlers: self.handlers.append(handler_instance)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def cmd(self, command, args, prefix=None): """ Sends a command to the server. :param command: IRC code to send. :type command: unicode :param args: arguments to pass with the command. :type args: basestring :param prefix: optional prefix to prepend to the command. :type prefix: str or None """
if prefix is None: prefix = u'' raw_cmd = u'{0} {1} {2}'.format(prefix, command, args).strip() self._send(raw_cmd)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def ctcp_reply(self, command, dst, message=None): """ Sends a reply to a CTCP request. :param command: CTCP command to use. :type command: str :param dst: sender of the initial request. :type dst: str :param message: data to attach to the reply. :type message: str """
if message is None: raw_cmd = u'\x01{0}\x01'.format(command) else: raw_cmd = u'\x01{0} {1}\x01'.format(command, message) self.notice(dst, raw_cmd)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def msg(self, target, msg): """ Sends a message to an user or channel. :param target: user or channel to send to. :type target: str :param msg: message to send. :type msg: str """
self.cmd(u'PRIVMSG', u'{0} :{1}'.format(target, msg))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def notice(self, target, msg): """ Sends a NOTICE to an user or channel. :param target: user or channel to send to. :type target: str :param msg: message to send. :type msg: basestring """
self.cmd(u'NOTICE', u'{0} :{1}'.format(target, msg))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def siget(fullname=""): """Returns a softimage object given its fullname."""
fullname = str(fullname) if not len(fullname): return None return sidict.GetObject(fullname, 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 cmd_wrapper(cmd_name, **kwds): """Wrap and execute a softimage command accepting named arguments"""
cmd = si.Commands(cmd_name) if not cmd: raise Exception(cmd_name + " doesnt found!") for arg in cmd.Arguments: value = kwds.get(arg.Name) if value: arg.Value = value return cmd.Execute()
<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_logger(middleware_settings): """ Creates a logger using the given settings. """
if django_settings.DEBUG: level = logging.DEBUG formatter = logging.Formatter( middleware_settings['LOGGER_FORMAT_DEBUG']) else: level = middleware_settings['LOGGER_LEVEL'] formatter = logging.Formatter(middleware_settings['LOGGER_FORMAT']) handler = logging.StreamHandler(sys.stderr) handler.setLevel(level) handler.setFormatter(formatter) logger = logging.getLogger(middleware_settings['LOGGER_NAME']) # If in some strange way this logger already exists we make sure to delete # its existing handlers del logger.handlers[:] logger.addHandler(handler) # Disable propagation by default logger.propagate = False return logger
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def press(*keys): """ Simulates a key-press for all the keys passed to the function :param keys: list of keys to be pressed :return: None """
for key in keys: win32api.keybd_event(codes[key], 0, 0, 0) release(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 hold(*keys, hold_time = 0, hold_while = None): """ Simulates the holding of all the keys passed to the function These keys are held down for a default period of 0 seconds before release :param keys: list of keys to be held :param hold_time: length of time to hold keys :param hold_while: hold keys while hold_while returns True :return: None """
for key in keys: win32api.keybd_event(codes[key], 0, 0, 0) if callable(hold_while): while hold_while(): pass else: time.sleep(hold_time) release(*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 release(*keys): """ Simulates the release of all the keys passed to this function :param keys: list of keys to be released :return: None """
for key in keys: win32api.keybd_event(codes[key], 0, win32con.KEYEVENTF_KEYUP, 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 normalize_input_value(value): """ Returns an input value normalized for RightScale API 2.0. This typically means adjusting the *input type* prefix to be one of the valid values:: blank ignore inherit text: env: cred: key: array: This list comes from the table published here: http://reference.rightscale.com/api1.5/resources/ResourceInputs.html#multi_update If unspecified, value is assumed to be a of type ``text``. """
if value in ('blank', 'ignore', 'inherit'): return value # assume any unspecified or unknown types are text tokens = value.split(':') if (len(tokens) < 2 or tokens[0] not in ('text', 'env', 'cred', 'key', 'array')): return 'text:%s' % value return value
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def create_stack(self, name): """ Creates stack if necessary. """
deployment = find_exact(self.api.deployments, name=name) if not deployment: try: # TODO: replace when python-rightscale handles non-json self.api.client.post( '/api/deployments', data={'deployment[name]': name}, ) except HTTPError as e: log.error( 'Failed to create stack %s. ' 'RightScale returned %d:\n%s' % (name, e.response.status_code, e.response.content) )
<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_features_types_from_dataframe(self, data_frame): """ Sets the features types from the given data_frame. All the calls except the first one are ignored. """
if self.__feature_types_set: return self.__feature_types_set = True dtypes = data_frame.dtypes for feature in self.__iter__(): name = feature.get_name() type_name = data_type_to_type_name(dtypes[name]) feature.set_type_name(type_name)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def handle_api_error(resp): """Stolen straight from the Stripe Python source."""
content = yield resp.json() headers = HeaderWrapper(resp.headers) try: err = content['error'] except (KeyError, TypeError): raise error.APIError( "Invalid response object from API: %r (HTTP response code " "was %d)" % (content, resp.code), resp, resp.code, content, headers) if resp.code in [400, 404]: raise error.InvalidRequestError( err.get('message'), err.get('param'), resp, resp.code, content, headers) elif resp.code == 401: raise error.AuthenticationError( err.get('message'), resp, resp.code, content, headers) elif resp.code == 402: raise error.CardError( err.get('message'), err.get('param'), err.get('code'), content, resp.code, resp, headers) else: raise error.APIError( err.get('message'), content, resp.code, resp, headers)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def vectors_between_pts(pts=[]): '''Return vectors between points on N dimensions. Last vector is the path between the first and last point, creating a loop. ''' assert isinstance(pts, list) and len(pts) > 0 l_pts = len(pts) l_pt_prev = None for pt in pts: assert isinstance(pt, tuple) l_pt = len(pt) assert l_pt > 1 for i in pt: assert isinstance(i, float) if l_pt_prev is not None: assert l_pt == l_pt_prev l_pt_prev = l_pt return [tuple([pts[(i+1) % l_pts][j] - pts[i][j] for j in range(l_pt)]) \ for i in range(l_pts)]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def pt_between_pts(a=(0.0, 0.0), b=(0.0, 0.0), t=0.5): '''Return the point between two points on N dimensions. ''' assert isinstance(a, tuple) assert isinstance(b, tuple) l_pt = len(a) assert l_pt > 1 assert l_pt == len(b) for i in a: assert isinstance(i, float) for i in b: assert isinstance(i, float) assert isinstance(t, float) assert 0 <= t <= 1 return tuple([ ((b[i] - a[i]) * t) + a[i] for i in range(l_pt) ])
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def pt_rotate(pt=(0.0, 0.0), angle=[0.0], center=(0.0, 0.0)): '''Return given point rotated around a center point in N dimensions. Angle is list of rotation in radians for each pair of axis. ''' assert isinstance(pt, tuple) l_pt = len(pt) assert l_pt > 1 for i in pt: assert isinstance(i, float) assert isinstance(angle, list) l_angle = len(angle) assert l_angle == l_pt-1 for i in angle: assert isinstance(i, float) assert abs(i) <= 2*pi assert isinstance(center, tuple) assert len(center) == l_pt for i in center: assert isinstance(i, float) # Get vector from center to point and use to get relative polar coordinate. v_cart = [pt[i] - center[i] for i in range(l_pt)] # Length of vector needs to stay constant for new point. v_pol_l = [sqrt(v_cart[i]**2 + v_cart[i+1]**2) for i in range(l_angle)] v_pol_a = [(atan(v_cart[i+1] / v_cart[i]) if v_cart[i] != 0.0 else pi/2) + pi*int(pt[i] < center[i]) \ for i in range(l_angle)] # Add rotation angle then convert back to cartesian vector. n_pol_a = [v_pol_a[i] + angle[i] for i in range(l_angle)] n_cart = [v_pol_l[0] * cos(n_pol_a[0])] + [v_pol_l[i] * sin(n_pol_a[i])\ for i in range(l_angle)] # Add in the centre offset to get original offset from c. r = [n_cart[i] + center[i] for i in range(l_pt)] return tuple(r)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def pts_rotate(pts=[], angle=[0.0], center=(0.0, 0.0)): '''Return given points rotated around a center point in N dimensions. Angle is list of rotation in radians for each pair of axis. ''' assert isinstance(pts, list) and len(pts) > 0 l_pt_prev = None for pt in pts: assert isinstance(pt, tuple) l_pt = len(pt) assert l_pt > 1 for i in pt: assert isinstance(i, float) if l_pt_prev is not None: assert l_pt == l_pt_prev l_pt_prev = l_pt assert isinstance(angle, list) l_angle = len(angle) assert l_angle == l_pt-1 for i in angle: assert isinstance(i, float) assert abs(i) <= 2*pi assert isinstance(center, tuple) assert len(center) == l_pt for i in center: assert isinstance(i, float) return [pt_rotate(pt, angle, center) for pt in pts]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def pt_shift(pt=(0.0, 0.0), shift=[0.0, 0.0]): '''Return given point shifted in N dimensions. ''' assert isinstance(pt, tuple) l_pt = len(pt) assert l_pt > 1 for i in pt: assert isinstance(i, float) assert isinstance(shift, list) l_sh = len(shift) assert l_sh == l_pt for i in shift: assert isinstance(i, float) return tuple([pt[i] + shift[i] for i in range(l_pt)])
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def pts_shift(pts=[], shift=[0.0, 0.0]): '''Return given points shifted in N dimensions. ''' assert isinstance(pts, list) and len(pts) > 0 l_pt_prev = None for pt in pts: assert isinstance(pt, tuple) l_pt = len(pt) assert l_pt > 1 for i in pt: assert isinstance(i, float) if l_pt_prev is not None: assert l_pt == l_pt_prev l_pt_prev = l_pt assert isinstance(shift, list) l_sh = len(shift) assert l_sh == l_pt for i in shift: assert isinstance(i, float) return [pt_shift(pt, shift) for pt in pts]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def pt_scale(pt=(0.0, 0.0), f=1.0): '''Return given point scaled by factor f from origin. ''' assert isinstance(pt, tuple) l_pt = len(pt) assert l_pt > 1 for i in pt: assert isinstance(i, float) assert isinstance(f, float) return tuple([pt[i]*f for i in range(l_pt)])