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 escape_filter_chars(assertion_value, escape_mode=0): """ Replace all special characters found in assertion_value by quoted notation. escape_mode If 0 only sp...
if isinstance(assertion_value, six.text_type): assertion_value = assertion_value.encode("utf_8") s = [] for c in assertion_value: do_escape = False if str != bytes: # Python 3 pass else: # Python 2 c = ord(c) if escape_mode == 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 filter_format(filter_template, assertion_values): """ filter_template String containing %s as placeholder for assertion values. assertion_values List or tupl...
assert isinstance(filter_template, bytes) return filter_template % ( tuple(map(escape_filter_chars, assertion_values)))
<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_command_return(self, obj, command, *arguments): """ Send command with single line output. :param obj: requested object. :param command: command to send....
return self._perform_command('{}/{}'.format(self.session_url, obj.ref), command, OperReturnType.line_output, *arguments).json()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def default(self): """ Returns environment marked as default. When Zone is set marked default makes no sense, special env with proper Zone is returned. """
if ZONE_NAME: log.info("Getting or creating default environment for zone with name '{0}'".format(DEFAULT_ENV_NAME())) zone_id = self.organization.zones[ZONE_NAME].id return self.organization.get_or_create_environment(name=DEFAULT_ENV_NAME(), zone=zone_id) def_envs =...
<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_urls(self: NodeVisitor, node: inheritance_diagram) -> Mapping[str, str]: """ Builds a mapping of class paths to URLs. """
current_filename = self.builder.current_docname + self.builder.out_suffix urls = {} for child in node: # Another document if child.get("refuri") is not None: uri = child.get("refuri") package_path = child["reftitle"] if uri.startswith("http"): ...
<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(configuration: str, level: str, target: str, short_format: bool): """Run the daemon and all its services"""
initialise_logging(level=level, target=target, short_format=short_format) logger = logging.getLogger(__package__) logger.info('COBalD %s', cobald.__about__.__version__) logger.info(cobald.__about__.__url__) logger.info('%s %s (%s)', platform.python_implementation(), platform.python_version(), sys.e...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def cli_run(): """Run the daemon from a command line interface"""
options = CLI.parse_args() run(options.CONFIGURATION, options.log_level, options.log_target, options.log_journal)
<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(cls: Type[AN], node: ast.stmt) -> List[AN]: """ Starting at this ``node``, check if it's an act node. If it's a context manager, recurse into child node...
if node_is_result_assignment(node): return [cls(node, ActNodeType.result_assignment)] if node_is_pytest_raises(node): return [cls(node, ActNodeType.pytest_raises)] if node_is_unittest_raises(node): return [cls(node, ActNodeType.unittest_raises)] toke...
<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_application(self, name=None, manifest=None): """ Creates application and returns Application object. """
if not manifest: raise exceptions.NotEnoughParams('Manifest not set') if not name: name = 'auto-generated-name' from qubell.api.private.application import Application return Application.new(self, name, manifest, self._router)
<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_application(self, id=None, name=None): """ Get application object by name or id. """
log.info("Picking application: %s (%s)" % (name, id)) return self.applications[id or 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 create_instance(self, application, revision=None, environment=None, name=None, parameters=None, submodules=None, destroyInterval=None, manifestVersion=None): ...
from qubell.api.private.instance import Instance return Instance.new(self._router, application, revision, environment, name, parameters, submodules, destroyInterval, manifestVersion=manifestVersion)
<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_instance(self, id=None, name=None): """ Get instance object by name or id. If application set, search within the application. """
log.info("Picking instance: %s (%s)" % (name, id)) if id: # submodule instances are invisible for lists return Instance(id=id, organization=self).init_router(self._router) return Instance.get(self._router, self, name)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def list_instances_json(self, application=None, show_only_destroyed=False): """ Get list of instances in json format converted to list"""
# todo: application should not be parameter here. Application should do its own list, just in sake of code reuse q_filter = {'sortBy': 'byCreation', 'descending': 'true', 'mode': 'short', 'from': '0', 'to': '10000'} if not show_only_destroyed: ...
<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_environment(self, name, default=False, zone=None): """ Creates environment and returns Environment object. """
from qubell.api.private.environment import Environment return Environment.new(organization=self, name=name, zone_id=zone, default=default, router=self._router)
<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_environment(self, id=None, name=None): """ Get environment object by name or id. """
log.info("Picking environment: %s (%s)" % (name, id)) return self.environments[id or 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 get_zone(self, id=None, name=None): """ Get zone object by name or id. """
log.info("Picking zone: %s (%s)" % (name, id)) return self.zones[id or 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 get_role(self, id=None, name=None): """ Get role object by name or id. """
log.info("Picking role: %s (%s)" % (name, id)) return self.roles[id or 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 get_user(self, id=None, name=None, email=None): """ Get user object by email or id. """
log.info("Picking user: %s (%s) (%s)" % (name, email, id)) from qubell.api.private.user import User if email: user = User.get(self._router, organization=self, email=email) else: user = self.users[id or name] return user
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def init(self, access_key=None, secret_key=None): """ Mimics wizard's environment preparation """
if not access_key and not secret_key: self._router.post_init(org_id=self.organizationId, data='{"initCloudAccount": true}') else: self._router.post_init(org_id=self.organizationId, data='{}') ca_data = dict(accessKey=access_key, secretKey=secret_key) 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 process_response(self, request, response): """Commits and leaves transaction management."""
if tldap.transaction.is_managed(): tldap.transaction.commit() tldap.transaction.leave_transaction_management() 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 line_protocol(name, tags: dict = None, fields: dict = None, timestamp: float = None) -> str: """ Format a report as per InfluxDB line protocol :param name: na...
output_str = name if tags: output_str += ',' output_str += ','.join('%s=%s' % (key, value) for key, value in sorted(tags.items())) output_str += ' ' output_str += ','.join(('%s=%r' % (key, value)).replace("'", '"') for key, value in sorted(fields.items())) if timestamp 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 block_type(self): """ This gets display on the block header. """
return capfirst(force_text( self.content_block.content_type.model_class()._meta.verbose_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 add_block_widget(self, top=False): """ Return a select widget for blocks which can be added to this column. """
widget = AddBlockSelect(attrs={ 'class': 'glitter-add-block-select', }, choices=self.add_block_options(top=top)) return widget.render(name='', value=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 add_block_options(self, top): """ Return a list of URLs and titles for blocks which can be added to this column. All available blocks are grouped by block ca...
from .blockadmin import blocks block_choices = [] # Group all block by category for category in sorted(blocks.site.block_list): category_blocks = blocks.site.block_list[category] category_choices = [] for block in category_blocks: b...
<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_embed_url(self): """ Get correct embed url for Youtube or Vimeo. """
embed_url = None youtube_embed_url = 'https://www.youtube.com/embed/{}' vimeo_embed_url = 'https://player.vimeo.com/video/{}' # Get video ID from url. if re.match(YOUTUBE_URL_RE, self.url): embed_url = youtube_embed_url.format(re.match(YOUTUBE_URL_RE, self.url).grou...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def save(self, force_insert=False, force_update=False, using=None, update_fields=None): """ Set html field with correct iframe. """
if self.url: iframe_html = '<iframe src="{}" frameborder="0" title="{}" allowfullscreen></iframe>' self.html = iframe_html.format( self.get_embed_url(), self.title ) return super().save(force_insert, force_update, using, update_fields)
<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_ip(): """Get IP address for the docker host """
cmd_netstat = ['netstat', '-nr'] p1 = subprocess.Popen(cmd_netstat, stdout=subprocess.PIPE) cmd_grep = ['grep', '^0\.0\.0\.0'] p2 = subprocess.Popen(cmd_grep, stdin=p1.stdout, stdout=subprocess.PIPE) cmd_awk = ['awk', '{ print $2 }'] p3 = subprocess.Popen(cmd_awk, stdin=p2.stdout, stdout=subpro...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_user_history (history_id=None): """ Get all visible dataset infos of user history. Return a list of dict of each dataset. """
history_id = history_id or os.environ['HISTORY_ID'] gi = get_galaxy_connection(history_id=history_id, obj=False) hc = HistoryClient(gi) history = hc.show_history(history_id, visible=True, contents=True) return 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 build_act(cls: Type[_Block], node: ast.stmt, test_func_node: ast.FunctionDef) -> _Block: """ Act block is a single node - either the act node itself, or the n...
add_node_parents(test_func_node) # Walk up the parent nodes of the parent node to find test's definition. act_block_node = node while act_block_node.parent != test_func_node: # type: ignore act_block_node = act_block_node.parent # type: ignore return cls([act_block...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def build_arrange(cls: Type[_Block], nodes: List[ast.stmt], max_line_number: int) -> _Block: """ Arrange block is all non-pass and non-docstring nodes before the ...
return cls(filter_arrange_nodes(nodes, max_line_number), LineType.arrange)
<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_assert(cls: Type[_Block], nodes: List[ast.stmt], min_line_number: int) -> _Block: """ Assert block is all nodes that are after the Act node. Note: The f...
return cls(filter_assert_nodes(nodes, min_line_number), LineType._assert)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def cli_aliases(self): r"""Developer script aliases. """
scripting_groups = [] aliases = {} for cli_class in self.cli_classes: instance = cli_class() if getattr(instance, "alias", None): scripting_group = getattr(instance, "scripting_group", None) if scripting_group: scriptin...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def cli_program_names(self): r"""Developer script program names. """
program_names = {} for cli_class in self.cli_classes: instance = cli_class() program_names[instance.program_name] = cli_class return program_names
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def read_stats(self): """ Read current ports statistics from chassis. :return: dictionary {port name {group name, {stat name: stat value}}} """
self.statistics = TgnObjectsDict() for port in self.session.ports.values(): self.statistics[port] = port.read_port_stats() return self.statistics
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_user_sets(client_id, user_id): """Find all user sets."""
data = api_call('get', 'users/{}/sets'.format(user_id), client_id=client_id) return [WordSet.from_dict(wordset) for wordset in 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 delete_term(set_id, term_id, access_token): """Delete the given term."""
api_call('delete', 'sets/{}/terms/{}'.format(set_id, term_id), access_token=access_token)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def reset_term_stats(set_id, term_id, client_id, user_id, access_token): """Reset the stats of a term by deleting and re-creating it."""
found_sets = [user_set for user_set in get_user_sets(client_id, user_id) if user_set.set_id == set_id] if len(found_sets) != 1: raise ValueError('{} set(s) found with id {}'.format(len(found_sets), set_id)) found_terms = [term for term in found_sets[0].terms if term.term_id == ter...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def createController(self, key, attributes, ipmi, printer=False): """ Function createController Create a controller node @param key: The host name or ID @param a...
if key not in self: self.printer = printer self.async = False # Create the VM in foreman self.__printProgression__('In progress', key + ' creation: push in Foreman', eol='\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 waitPuppetCatalogToBeApplied(self, key, sleepTime=5): """ Function waitPuppetCatalogToBeApplied Wait for puppet catalog to be applied @param key: The host na...
# Wait for puppet catalog to be applied loop_stop = False while not loop_stop: status = self[key].getStatus() if status == 'No Changes' or status == 'Active': self.__printProgression__(True, key + ' creation: prov...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def createVM(self, key, attributes, printer=False): """ Function createVM Create a Virtual Machine The creation of a VM with libVirt is a bit complexe. We first ...
self.printer = printer self.async = False # Create the VM in foreman # NOTA: with 1.8 it will return 422 'Failed to login via SSH' self.__printProgression__('In progress', key + ' creation: push in Foreman', eol='\r') asyncCreation = se...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def construct(self, mapping: dict, **kwargs): """ Construct an object from a mapping :param mapping: the constructor definition, with ``__type__`` name and keywo...
assert '__type__' not in kwargs and '__args__' not in kwargs mapping = {**mapping, **kwargs} factory_fqdn = mapping.pop('__type__') factory = self.load_name(factory_fqdn) args = mapping.pop('__args__', []) return factory(*args, **mapping)
<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_name(absolute_name: str): """Load an object based on an absolute, dotted name"""
path = absolute_name.split('.') try: __import__(absolute_name) except ImportError: try: obj = sys.modules[path[0]] except KeyError: raise ModuleNotFoundError('No module named %r' % path[0]) else: for...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def contains_list(longer, shorter): """Check if longer list starts with shorter list"""
if len(longer) <= len(shorter): return False for a, b in zip(shorter, longer): if a != b: return False return True
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def load(f, dict_=dict): """Load and parse toml from a file object An additional argument `dict_` is used to specify the output type """
if not f.read: raise ValueError('The first parameter needs to be a file object, ', '%r is passed' % type(f)) return loads(f.read(), dict_)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def loads(content, dict_=dict): """Parse a toml string An additional argument `dict_` is used to specify the output type """
if not isinstance(content, basestring): raise ValueError('The first parameter needs to be a string object, ', '%r is passed' % type(content)) decoder = Decoder(content, dict_) decoder.parse() return decoder.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 convert(self, line=None, is_end=True): """Read the line content and return the converted value :param line: the line to feed to converter :param is_end: if s...
if line is not None: self.line = line if not self.line: raise TomlDecodeError(self.parser.lineno, 'EOF is hit!') token = None self.line = self.line.lstrip() for key, pattern in self.patterns: m = pattern.match...
<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, data=None, table_name=None): """Parse the lines from index i :param data: optional, store the parsed result to it when specified :param table_nam...
temp = self.dict_() sub_table = None is_array = False line = '' while True: line = self._readline() if not line: self._store_table(sub_table, temp, is_array, data=data) break # EOF if BLANK_RE.match(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 is_visible(self): """ Return a boolean if the page is visible in navigation. Pages must have show in navigation set. Regular pages must be published (publish...
if self.glitter_app_name: visible = self.show_in_navigation else: visible = self.show_in_navigation and self.is_published return visible
<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_node_tree(self, source_paths): """ Build a node tree. """
import uqbar.apis root = PackageNode() # Build node tree, top-down for source_path in sorted( source_paths, key=lambda x: uqbar.apis.source_path_to_package_path(x) ): package_path = uqbar.apis.source_path_to_package_path(source_path) parts = ...
<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_unique(self): """ Add this method because django doesn't validate correctly because required fields are excluded. """
unique_checks, date_checks = self.instance._get_unique_checks(exclude=[]) errors = self.instance._perform_unique_checks(unique_checks) if errors: self.add_error(None, 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 from_dict(raw_data): """Create Image from raw dictionary data."""
url = None width = None height = None try: url = raw_data['url'] width = raw_data['width'] height = raw_data['height'] except KeyError: raise ValueError('Unexpected image json structure') except TypeError: # Hap...
<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_dict(self): """Convert Image into raw dictionary data."""
if not self.url: return None return { 'url': self.url, 'width': self.width, 'height': self.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 from_dict(raw_data): """Create Term from raw dictionary data."""
try: definition = raw_data['definition'] term_id = raw_data['id'] image = Image.from_dict(raw_data['image']) rank = raw_data['rank'] term = raw_data['term'] return Term(definition, term_id, image, rank, term) except KeyError: ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def to_dict(self): """Convert Term into raw dictionary data."""
return { 'definition': self.definition, 'id': self.term_id, 'image': self.image.to_dict(), 'rank': self.rank, 'term': self.term }
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def has_common(self, other): """Return set of common words between two word sets."""
if not isinstance(other, WordSet): raise ValueError('Can compare only WordSets') return self.term_set & other.term_set
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def from_dict(raw_data): """Create WordSet from raw dictionary data."""
try: set_id = raw_data['id'] title = raw_data['title'] terms = [Term.from_dict(term) for term in raw_data['terms']] return WordSet(set_id, title, terms) except KeyError: raise ValueError('Unexpected set json structure')
<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_dict(self): """Convert WordSet into raw dictionary data."""
return { 'id': self.set_id, 'title': self.title, 'terms': [term.to_dict() for term in self.terms] }
<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(ctx, yes, latest): """Create a new release in github """
m = RepoManager(ctx.obj['agile']) api = m.github_repo() if latest: latest = api.releases.latest() if latest: click.echo(latest['tag_name']) elif m.can_release('sandbox'): branch = m.info['branch'] version = m.validate_version() name = 'v%s' % 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 on_config_inited(app, config): """ Hooks into Sphinx's ``config-inited`` event. """
extension_paths = config["uqbar_book_extensions"] or [ "uqbar.book.extensions.GraphExtension" ] app.uqbar_book_extensions = [] for extension_path in extension_paths: module_name, _, class_name = extension_path.rpartition(".") module = importlib.import_module(module_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 on_build_finished(app, exception): """ Hooks into Sphinx's ``build-finished`` event. """
if not app.config["uqbar_book_use_cache"]: return logger.info("") for row in app.connection.execute("SELECT path, hits FROM cache ORDER BY path"): path, hits = row if not hits: continue logger.info(bold("[uqbar-book]"), nonl=True) logger.info(" Cache hits...
<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_class(signature_node, module, object_name, cache): """ Styles ``autoclass`` entries. Adds ``abstract`` prefix to abstract classes. """
class_ = getattr(module, object_name, None) if class_ is None: return if class_ not in cache: cache[class_] = {} attributes = inspect.classify_class_attrs(class_) for attribute in attributes: cache[class_][attribute.name] = attribute if inspect.isabstract(cla...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def init_xena(api, logger, owner, ip=None, port=57911): """ Create XenaManager object. :param api: cli/rest :param logger: python logger :param owner: owner of t...
if api == ApiType.socket: api_wrapper = XenaCliWrapper(logger) elif api == ApiType.rest: api_wrapper = XenaRestWrapper(logger, ip, port) return XenaApp(logger, owner, api_wrapper)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def add_chassis(self, chassis, port=22611, password='xena'): """ Add chassis. XenaManager-2G -> Add Chassis. :param chassis: chassis IP address :param port: chas...
if chassis not in self.chassis_list: try: XenaChassis(self, chassis, port, password) except Exception as error: self.objects.pop('{}/{}'.format(self.owner, chassis)) raise error return self.chassis_list[chassis]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def inventory(self): """ Get inventory for all chassis. """
for chassis in self.chassis_list.values(): chassis.inventory(modules_inventory=True)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def stop_traffic(self, *ports): """ Stop traffic on list of ports. :param ports: list of ports to stop traffic on. Default - all session ports. """
for chassis, chassis_ports in self._per_chassis_ports(*self._get_operation_ports(*ports)).items(): chassis.stop_traffic(*chassis_ports)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def inventory(self, modules_inventory=False): """ Get chassis inventory. :param modules_inventory: True - read modules inventory, false - don't read. """
self.c_info = self.get_attributes() for m_index, m_portcounts in enumerate(self.c_info['c_portcounts'].split()): if int(m_portcounts): module = XenaModule(parent=self, index=m_index) if modules_inventory: module.inventory()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def inventory(self): """ Get module inventory. """
self.m_info = self.get_attributes() if 'NOTCFP' in self.m_info['m_cfptype']: a = self.get_attribute('m_portcount') m_portcount = int(a) else: m_portcount = int(self.get_attribute('m_cfpconfig').split()[0]) for p_index in range(m_portcount): ...
<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(entry_point, drivers, loop = None): ''' This is a runner wrapping the cyclotron "run" implementation. It takes an additional parameter to provide a custom asyncio mainloop. ''' program = setup(entry_point, drivers) dispose = program.run() if loop == None: loop = asyncio.get_event...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def register(model, admin=None, category=None): """ Decorator to registering you Admin class. """
def _model_admin_wrapper(admin_class): site.register(model, admin_class=admin_class) if category: site.register_block(model, category) return admin_class return _model_admin_wrapper
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def response_change(self, request, obj): """Determine the HttpResponse for the change_view stage."""
opts = self.opts.app_label, self.opts.model_name pk_value = obj._get_pk_val() if '_continue' in request.POST: msg = _( 'The %(name)s block was changed successfully. You may edit it again below.' ) % {'name': force_text(self.opts.verbose_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 get_filter_item(name: str, operation: bytes, value: bytes) -> bytes: """ A field could be found for this term, try to get filter string for it. """
assert isinstance(name, str) assert isinstance(value, bytes) if operation is None: return filter_format(b"(%s=%s)", [name, value]) elif operation == "contains": assert value != "" return filter_format(b"(%s=*%s*)", [name, value]) else: raise ValueError("Unknown searc...
<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_filter(q: tldap.Q, fields: Dict[str, tldap.fields.Field], pk: str): """ Translate the Q tree into a filter string to search for, or None if no results po...
# check the details are valid if q.negated and len(q.children) == 1: op = b"!" elif q.connector == tldap.Q.AND: op = b"&" elif q.connector == tldap.Q.OR: op = b"|" else: raise ValueError("Invalid value of op found") # scan through every child search = [] ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def program_name(self): r"""The name of the script, callable from the command line. """
name = "-".join( word.lower() for word in uqbar.strings.delimit_words(type(self).__name__) ) return 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 node_is_noop(node: ast.AST) -> bool: """ Node does nothing. """
return isinstance(node.value, ast.Str) if isinstance(node, ast.Expr) else isinstance(node, ast.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 function_is_noop(function_node: ast.FunctionDef) -> bool: """ Function does nothing - is just ``pass`` or docstring. """
return all(node_is_noop(n) for n in function_node.body)
<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_node_parents(root: ast.AST) -> None: """ Adds "parent" attribute to all child nodes of passed node. Code taken from https://stackoverflow.com/a/43311383/1...
for node in ast.walk(root): for child in ast.iter_child_nodes(node): child.parent = node
<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_footprint(node: ast.AST, first_line_no: int) -> Set[int]: """ Generates a list of lines that the passed node covers, relative to the marked lines list -...
return set( range( get_first_token(node).start[0] - first_line_no, get_last_token(node).end[0] - first_line_no + 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 filter_arrange_nodes(nodes: List[ast.stmt], max_line_number: int) -> List[ast.stmt]: """ Finds all nodes that are before the ``max_line_number`` and are not d...
return [ node for node in nodes if node.lineno < max_line_number and not isinstance(node, ast.Pass) and not (isinstance(node, ast.Expr) and isinstance(node.value, ast.Str)) ]
<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_assert_nodes(nodes: List[ast.stmt], min_line_number: int) -> List[ast.stmt]: """ Finds all nodes that are after the ``min_line_number`` """
return [node for node in nodes if node.lineno > min_line_number]
<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_stringy_lines(tree: ast.AST, first_line_no: int) -> Set[int]: """ Finds all lines that contain a string in a tree, usually a function. These lines will b...
str_footprints = set() for node in ast.walk(tree): if isinstance(node, ast.Str): str_footprints.update(build_footprint(node, first_line_no)) return str_footprints
<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_all(self) -> Generator[AAAError, None, None]: """ Run everything required for checking this function. Returns: A generator of errors. Raises: Validation...
# Function def if function_is_noop(self.node): return self.mark_bl() self.mark_def() # ACT # Load act block and kick out when none is found self.act_node = self.load_act_node() self.act_block = Block.build_act(self.act_node.node, self.node) ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def mark_bl(self) -> int: """ Mark unprocessed lines that have no content and no string nodes covering them as blank line BL. Returns: Number of blank lines found...
counter = 0 stringy_lines = find_stringy_lines(self.node, self.first_line_no) for relative_line_number, line in enumerate(self.lines): if relative_line_number not in stringy_lines and line.strip() == '': counter += 1 self.line_markers[relative_line_nu...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def getParamFromEnv(self, var, default=''): """ Function getParamFromEnv Search a parameter in the host environment @param var: the var name @param hostgroup: th...
if self.getParam(var): return self.getParam(var) if self.hostgroup: if self.hostgroup.getParam(var): return self.hostgroup.getParam(var) if self.domain.getParam('password'): return self.domain.getParam('password') else: ret...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def getUserData(self, hostgroup, domain, defaultPwd='', defaultSshKey='', proxyHostname='', tplFolder='metadata/templates/'): """ Function getUserData Generate a...
if 'user-data' in self.keys(): return self['user-data'] else: self.hostgroup = hostgroup self.domain = domain if proxyHostname == '': proxyHostname = 'foreman.' + domain['name'] password = self.getParamFromEnv('password', defau...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def register_payload(self, *payloads, flavour: ModuleType): """Queue one or more payload for execution after its runner is started"""
for payload in payloads: self._logger.debug('registering payload %s (%s)', NameRepr(payload), NameRepr(flavour)) self.runners[flavour].register_payload(payload)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def run_payload(self, payload, *, flavour: ModuleType): """Execute one payload after its runner is started and return its output"""
return self.runners[flavour].run_payload(payload)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def run(self): """Run all runners, blocking until completion or error"""
self._logger.info('starting all runners') try: with self._lock: assert not self.running.set(), 'cannot re-run: %s' % self self.running.set() thread_runner = self.runners[threading] for runner in self.runners.values(): i...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def formfield_for_dbfield(self, db_field, **kwargs): """ Hook for specifying the form Field instance for a given database Field instance. If kwargs are given, th...
formfield = super().formfield_for_dbfield(db_field, **kwargs) if db_field.name == 'image': formfield.widget = ImageRelatedFieldWidgetWrapper( ImageSelect(), db_field.rel, self.admin_site, can_add_related=True, can_change_related=True, ) re...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def compare_schemas(one, two): """Compare two structures that represents JSON schemas. For comparison you can't use normal comparison, because in JSON schema lis...
one = _normalize_string_type(one) two = _normalize_string_type(two) _assert_same_types(one, two) if isinstance(one, list): return _compare_lists(one, two) elif isinstance(one, dict): return _compare_dicts(one, two) elif isinstance(one, SCALAR_TYPES): return one == two ...
<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_ecma_regex(regex): """Check if given regex is of type ECMA 262 or not. :rtype: bool """
parts = regex.split('/') if len(parts) == 1: return False if len(parts) < 3: raise ValueError('Given regex isn\'t ECMA regex nor Python regex.') parts.pop() parts.append('') raw_regex = '/'.join(parts) if raw_regex.startswith('/') and raw_regex.endswith('/'): retu...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def convert_ecma_regex_to_python(value): """Convert ECMA 262 regex to Python tuple with regex and flags. If given value is already Python regex it will be return...
if not is_ecma_regex(value): return PythonRegex(value, []) parts = value.split('/') flags = parts.pop() try: result_flags = [ECMA_TO_PYTHON_FLAGS[f] for f in flags] except KeyError: raise ValueError('Wrong flags "{}".'.format(flags)) return PythonRegex('/'.join(parts[...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def convert_python_regex_to_ecma(value, flags=[]): """Convert Python regex to ECMA 262 regex. If given value is already ECMA regex it will be returned unchanged....
if is_ecma_regex(value): return value result_flags = [PYTHON_TO_ECMA_FLAGS[f] for f in flags] result_flags = ''.join(result_flags) return '/{value}/{flags}'.format(value=value, flags=result_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 populate(self, **values): """Populate values to fields. Skip non-existing."""
values = values.copy() fields = list(self.iterate_with_name()) for _, structure_name, field in fields: if structure_name in values: field.__set__(self, values.pop(structure_name)) for name, _, field in fields: if name in values: fi...
<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_field(self, field_name): """Get field associated with given attribute."""
for attr_name, field in self: if field_name == attr_name: return field raise errors.FieldNotFound('Field not found', field_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 validate(self): """Explicitly validate all the fields."""
for name, field in self: try: field.validate_for_object(self) except ValidationError as error: raise ValidationError( "Error for field '{name}'.".format(name=name), error, )
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def iterate_with_name(cls): """Iterate over fields, but also give `structure_name`. Format is `(attribute_name, structue_name, field_instance)`. Structure name i...
for attr_name, field in cls.iterate_over_fields(): structure_name = field.structue_name(attr_name) yield attr_name, structure_name, field
<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_value(self, value): """Cast value to `bool`."""
parsed = super(BoolField, self).parse_value(value) return bool(parsed) if parsed is not None 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 parse_value(self, values): """Cast value to proper collection."""
result = self.get_default_value() if not values: return result if not isinstance(values, list): return values return [self._cast_value(value) for value in values]
<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_value(self, value): """Parse value to proper model type."""
if not isinstance(value, dict): return value embed_type = self._get_embed_type() return embed_type(**value)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def to_struct(self, value): """Cast `time` object to string."""
if self.str_format: return value.strftime(self.str_format) return value.isoformat()