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 special chars mentioned in RFC 4515 are escaped. If 1 all NON-ASCII chars are escaped. If 2 all chars are escaped. """ |
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:
if c == ord('\\') or c == ord('*') \
or c == ord('(') or c == ord(')') \
or c == ord('\x00'):
do_escape = True
elif escape_mode == 1:
if c < '0' or c > 'z' or c in "\\*()":
do_escape = True
elif escape_mode == 2:
do_escape = True
else:
raise ValueError('escape_mode must be 0, 1 or 2.')
if do_escape:
s.append(b"\\%02x" % c)
else:
b = None
if str != bytes: # Python 3
b = bytes([c])
else: # Python 2
b = chr(c)
s.append(b)
return b''.join(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 filter_format(filter_template, assertion_values):
""" filter_template String containing %s as placeholder for assertion values. assertion_values List or tuple of assertion values. Length must match count of %s in filter_template. """ |
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. :param arguments: list of command arguments. :return: command output. """ |
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 = [env_j["id"] for env_j in self.json() if env_j["isDefault"]]
if len(def_envs) > 1:
log.warning('Found more than one default environment. Picking last.')
return self[def_envs[-1]]
elif len(def_envs) == 1:
return self[def_envs[0]]
raise exceptions.NotFoundError('Unable to get default environment') |
<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"):
_, _, package_path = uri.partition("#")
else:
uri = (
pathlib.Path("..")
/ pathlib.Path(current_filename).parent
/ pathlib.Path(uri)
)
uri = str(uri).replace(os.path.sep, "/")
urls[package_path] = uri
# Same document
elif child.get("refid") is not None:
urls[child["reftitle"]] = (
"../" + current_filename + "#" + child.get("refid")
)
return urls |
<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.executable)
logger.debug(cobald.__file__)
logger.info('Using configuration %s', configuration)
with load(configuration):
logger.info('Starting daemon services...')
runtime.accept() |
<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 nodes. Returns: List of all act nodes found. """ |
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)]
token = node.first_token # type: ignore
# Check if line marked with '# act'
if token.line.strip().endswith('# act'):
return [cls(node, ActNodeType.marked_act)]
# Recurse (downwards) if it's a context manager
if isinstance(node, ast.With):
return cls.build_body(node.body)
return [] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def 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):
""" Launches instance in application and returns Instance object. """ |
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:
q_filter['showDestroyed'] = 'false'
else:
q_filter['showDestroyed'] = 'true'
q_filter['showRunning'] = 'false'
q_filter['showError'] = 'false'
q_filter['showLaunching'] = 'false'
if application:
q_filter["applicationFilterId"] = application.applicationId
resp_json = self._router.get_instances(org_id=self.organizationId, params=q_filter).json()
if type(resp_json) == dict:
instances = [instance for g in resp_json['groups'] for instance in g['records']]
else: # TODO: This is compatibility fix for platform < 37.1
instances = resp_json
return instances |
<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._router.post_init_custom_cloud_account(org_id=self.organizationId, data=json.dumps(ca_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 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: name of the report :param tags: tags identifying the specific report :param fields: measurements of the report :param timestamp: when the measurement was taken, in **seconds** since the epoch """ |
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:
# line protocol requires nanosecond precision, python uses seconds
output_str += ' %d' % (timestamp * 1E9)
return output_str + '\n' |
<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 category. """ |
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:
base_url = reverse('block_admin:{}_{}_add'.format(
block._meta.app_label, block._meta.model_name,
), kwargs={
'version_id': self.glitter_page.version.id,
})
block_qs = {
'column': self.name,
'top': top,
}
block_url = '{}?{}'.format(base_url, urlencode(block_qs))
block_text = capfirst(force_text(block._meta.verbose_name))
category_choices.append((block_url, block_text))
category_choices = sorted(category_choices, key=lambda x: x[1])
block_choices.append((category, category_choices))
return block_choices |
<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).group(2))
if re.match(VIMEO_URL_RE, self.url):
embed_url = vimeo_embed_url.format(re.match(VIMEO_URL_RE, self.url).group(3))
return embed_url |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def 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=subprocess.PIPE)
galaxy_ip = p3.stdout.read()
log.debug('Host IP determined to be %s', galaxy_ip)
return galaxy_ip |
<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 node that wraps the act node. """ |
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_node], LineType.act) |
<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 Act block start. """ |
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 filtering is *still* running off the line number of the Act node, when instead it should be using the last line of the Act block. """ |
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:
scripting_groups.append(scripting_group)
entry = (scripting_group, instance.alias)
if (scripting_group,) in aliases:
message = "alias conflict between scripting group"
message += " {!r} and {}"
message = message.format(
scripting_group, aliases[(scripting_group,)].__name__
)
raise Exception(message)
if entry in aliases:
message = "alias conflict between {} and {}"
message = message.format(
aliases[entry].__name__, cli_class.__name__
)
raise Exception(message)
aliases[entry] = cli_class
else:
entry = (instance.alias,)
if entry in scripting_groups:
message = "alias conflict between {}"
message += " and scripting group {!r}"
message = message.format(cli_class.__name__, instance.alias)
raise Exception(message)
if entry in aliases:
message = "alias conflict be {} and {}"
message = message.format(cli_class.__name__, aliases[entry])
raise Exception(message)
aliases[(instance.alias,)] = cli_class
else:
if instance.program_name in scripting_groups:
message = "Alias conflict between {}"
message += " and scripting group {!r}"
message = message.format(cli_class.__name__, instance.program_name)
raise Exception(message)
aliases[(instance.program_name,)] = cli_class
alias_map = {}
for key, value in aliases.items():
if len(key) == 1:
alias_map[key[0]] = value
else:
if key[0] not in alias_map:
alias_map[key[0]] = {}
alias_map[key[0]][key[1]] = value
return alias_map |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def 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 == term_id]
if len(found_terms) != 1:
raise ValueError('{} term(s) found with id {}'.format(len(found_terms), term_id))
term = found_terms[0]
if term.image.url:
# Creating a term with an image requires an "image identifier", which you get by uploading
# an image via https://quizlet.com/api/2.0/docs/images , which can only be used by Quizlet
# PLUS members.
raise NotImplementedError('"{}" has an image and is thus not supported'.format(term))
print('Deleting "{}"...'.format(term))
delete_term(set_id, term_id, access_token)
print('Re-creating "{}"...'.format(term))
add_term(set_id, term, access_token)
print('Done') |
<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 attributes:The payload of the host creation @param printer: - False for no creation progression message - True to get creation progression printed on STDOUT - Printer class containig a status method for enhanced print. def printer.status(status, msg, eol=eol) @return RETURN: The API result """ |
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')
self.api.create('hosts', attributes, async=self.async)
self[key]['interfaces'].append(ipmi)
# Wait for puppet catalog to be applied
# self.waitPuppetCatalogToBeApplied(key)
self.reload()
self[key]['build'] = 'true'
self[key]['boot'] = 'pxe'
self[key]['power'] = 'cycle'
return self[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 waitPuppetCatalogToBeApplied(self, key, sleepTime=5):
""" Function waitPuppetCatalogToBeApplied Wait for puppet catalog to be applied @param key: The host name or ID @return RETURN: None """ |
# 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: provisioning OK')
loop_stop = True
elif status == 'Error':
self.__printProgression__(False,
key + ' creation: Error - '
'Error during provisioning')
loop_stop = True
return False
else:
self.__printProgression__('In progress',
key + ' creation: provisioning ({})'
.format(status),
eol='\r')
time.sleep(sleepTime) |
<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 create the element in foreman, the ask to start before the result of the creation. To do so, we make async calls to the API and check the results @param key: The host name or ID @param attributes:The payload of the host creation @param printer: - False for no creation progression message - True to get creation progression printed on STDOUT - Printer class containig a status method for enhanced print. def printer.status(status, msg, eol=eol) @return RETURN: The API result """ |
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 = self.api.create('hosts', attributes, async=self.async)
# Wait before asking to power on the VM
# sleep = 5
# for i in range(0, sleep):
# time.sleep(1)
# self.__printProgression__('In progress',
# key + ' creation: start in {0}s'
# .format(sleep - i),
# eol='\r')
# Power on the VM
self.__printProgression__('In progress',
key + ' creation: starting', eol='\r')
powerOn = self[key].powerOn()
# Show Power on result
if powerOn['power']:
self.__printProgression__('In progress',
key + ' creation: wait for end of boot',
eol='\r')
else:
self.__printProgression__(False,
key + ' creation: Error - ' +
str(powerOn))
return False
# Show creation result
# NOTA: with 1.8 it will return 422 'Failed to login via SSH'
# if asyncCreation.result().status_code is 200:
# self.__printProgression__('In progress',
# key + ' creation: created',
# eol='\r')
# else:
# self.__printProgression__(False,
# key + ' creation: Error - ' +
# str(asyncCreation.result()
# .status_code) + ' - ' +
# str(asyncCreation.result().text))
# return False
# Wait for puppet catalog to be applied
self.waitPuppetCatalogToBeApplied(key)
return self[key]['id'] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def construct(self, mapping: dict, **kwargs):
""" Construct an object from a mapping :param mapping: the constructor definition, with ``__type__`` name and keyword arguments :param kwargs: additional keyword arguments to pass to the constructor """ |
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 component in path[1:]:
try:
obj = getattr(obj, component)
except AttributeError as err:
raise ConfigurationError(what='no such object %r: %s' % (absolute_name, err))
return obj
else: # ImportError is not raised if ``absolute_name`` points to a valid module
return sys.modules[absolute_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 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 set to True, will raise an error if the line has something remaining. """ |
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(self.line)
if m:
self.line = self.line[m.end():]
handler = getattr(self, 'convert_%s' % key)
token = handler(m)
break
else:
raise TomlDecodeError(self.parser.lineno,
'Parsing error: %r' % self.line)
if is_end and not BLANK_RE.match(self.line):
raise TomlDecodeError(self.parser.lineno,
'Something is remained: %r' % self.line)
return 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 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_name: when inside a table array, it is the table name """ |
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):
continue
if TABLE_RE.match(line):
next_table = self.split_string(
TABLE_RE.match(line).group(1), '.', False)
if table_name and not contains_list(next_table, table_name):
self._store_table(sub_table, temp, is_array, data=data)
break
table = cut_list(next_table, table_name)
if sub_table == table:
raise TomlDecodeError(self.lineno, 'Duplicate table name'
'in origin: %r' % sub_table)
else: # different table name
self._store_table(sub_table, temp, is_array, data=data)
sub_table = table
is_array = False
elif TABLE_ARRAY_RE.match(line):
next_table = self.split_string(
TABLE_ARRAY_RE.match(line).group(1), '.', False)
if table_name and not contains_list(next_table, table_name):
# Out of current loop
# write current data dict to table dict
self._store_table(sub_table, temp, is_array, data=data)
break
table = cut_list(next_table, table_name)
if sub_table == table and not is_array:
raise TomlDecodeError(self.lineno, 'Duplicate name of '
'table and array of table: %r'
% sub_table)
else: # Begin a nested loop
# Write any temp data to table dict
self._store_table(sub_table, temp, is_array, data=data)
sub_table = table
is_array = True
self.parse(temp, next_table)
elif KEY_RE.match(line):
m = KEY_RE.match(line)
keys = self.split_string(m.group(1), '.')
value = self.converter.convert(line[m.end():])
if value is None:
raise TomlDecodeError(self.lineno, 'Value is missing')
self._store_table(keys[:-1], {keys[-1]: value}, data=temp)
else:
raise TomlDecodeError(self.lineno,
'Pattern is not recognized: %r' % line)
# Rollback to the last line for next parse
# This will do nothing if EOF is hit
self.instream.seek(self.instream.tell() - len(line))
self.lineno -= 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 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 (published and have a current version - checked with `is_published`), pages with a glitter app associated don't need any page versions. """ |
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 = package_path.split(".")
if not self.document_private_modules and any(
part.startswith("_") for part in parts
):
continue
# Find parent node.
parent_node = root
if len(parts) > 1:
parent_package_path = ".".join(parts[:-1])
try:
parent_node = root[parent_package_path]
except KeyError:
parent_node = root
try:
if parent_node is root:
# Backfill missing parent node.
grandparent_node = root
if len(parts) > 2:
grandparent_node = root[
parent_package_path.rpartition(".")[0]
]
parent_node = PackageNode(name=parent_package_path)
grandparent_node.append(parent_node)
grandparent_node[:] = sorted(
grandparent_node, key=lambda x: x.package_path
)
except KeyError:
parent_node = root
# Create or update child node.
node_class = ModuleNode
if source_path.name == "__init__.py":
node_class = PackageNode
try:
# If the child exists, it was previously backfilled.
child_node = root[package_path]
child_node.source_path = source_path
except KeyError:
# Otherwise it needs to be created and appended to the parent.
child_node = node_class(name=package_path, source_path=source_path)
parent_node.append(child_node)
parent_node[:] = sorted(parent_node, key=lambda x: x.package_path)
# Build documenters, bottom-up.
# This allows parent documenters to easily aggregate their children.
for node in root.depth_first(top_down=False):
kwargs = dict(
document_private_members=self.document_private_members,
member_documenter_classes=self.member_documenter_classes,
)
if isinstance(node, ModuleNode):
node.documenter = self.module_documenter_class(
node.package_path, **kwargs
)
else:
# Collect references to child modules and packages.
node.documenter = self.module_documenter_class(
node.package_path,
module_documenters=[
child.documenter
for child in node
if child.documenter is not None
],
**kwargs,
)
if (
not self.document_empty_modules
and not node.documenter.module_documenters
and not node.documenter.member_documenters
):
node.parent.remove(node)
return root |
<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:
# Happens when raw_data is None, i.e. when a term has no image:
pass
return Image(url, width, 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 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:
raise ValueError('Unexpected term 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 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
body = ['Release %s from agiletoolkit' % name]
data = dict(
tag_name=name,
target_commitish=branch,
name=name,
body='\n\n'.join(body),
draft=False,
prerelease=False
)
if yes:
data = api.releases.create(data=data)
m.message('Successfully created a new Github release')
click.echo(niceJson(data))
else:
click.echo('skipped') |
<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)
extension_class = getattr(module, class_name)
extension_class.setup_sphinx(app)
app.uqbar_book_extensions.append(extension_class) |
<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 for {}: {}".format(path, 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(class_):
emphasis = nodes.emphasis("abstract ", "abstract ", classes=["property"])
signature_node.insert(0, emphasis) |
<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 the scripting session :param ip: rest server IP :param port: rest server TCP port :return: Xena object :rtype: XenaApp """ |
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: chassis port number :param password: chassis password :return: newly created chassis :rtype: xenamanager.xena_app.XenaChassis """ |
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):
XenaPort(parent=self, index='{}/{}'.format(self.index, p_index)).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 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_loop()
loop.run_forever()
dispose() |
<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)}
self.message_user(request, msg, messages.SUCCESS)
# We redirect to the save and continue page, which updates the
# parent window in javascript and redirects back to the edit page
# in javascript.
return HttpResponseRedirect(reverse(
'admin:%s_%s_continue' % opts,
args=(pk_value,),
current_app=self.admin_site.name
))
# Update column and close popup - don't bother with a message as they won't see it
return self.response_rerender(request, obj, 'admin/glitter/update_column.html') |
<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 search operation %s" % operation) |
<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 possible. """ |
# 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 = []
for child in q.children:
# if this child is a node, then descend into it
if isinstance(child, tldap.Q):
search.append(get_filter(child, fields, pk))
else:
# otherwise get the values in this node
name, value = child
# split the name if possible
name, _, operation = name.rpartition("__")
if name == "":
name, operation = operation, None
# replace pk with the real attribute
if name == "pk":
name = pk
# DN is a special case
if name == "dn":
dn_name = "entryDN:"
if isinstance(value, list):
s = []
for v in value:
assert isinstance(v, str)
v = v.encode('utf_8')
s.append(get_filter_item(dn_name, operation, v))
search.append("(&".join(search) + ")")
# or process just the single value
else:
assert isinstance(value, str)
v = value.encode('utf_8')
search.append(get_filter_item(dn_name, operation, v))
continue
# try to find field associated with name
field = fields[name]
if isinstance(value, list) and len(value) == 1:
value = value[0]
assert isinstance(value, str)
# process as list
if isinstance(value, list):
s = []
for v in value:
v = field.value_to_filter(v)
s.append(get_filter_item(name, operation, v))
search.append(b"(&".join(search) + b")")
# or process just the single value
else:
value = field.value_to_filter(value)
search.append(get_filter_item(name, operation, value))
# output the results
if len(search) == 1 and not q.negated:
# just one non-negative term, return it
return search[0]
else:
# multiple terms
return b"(" + op + b"".join(search) + 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 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/1286705 """ |
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 - i.e. start of function is line 0. """ |
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 docstrings or ``pass``. """ |
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 be ignored when searching for blank lines. """ |
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: ValidationError: A non-recoverable linting error is found. """ |
# 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)
act_block_first_line_no, act_block_last_line_no = self.act_block.get_span(0)
# ARRANGE
self.arrange_block = Block.build_arrange(self.node.body, act_block_first_line_no)
# ASSERT
assert self.act_node
self.assert_block = Block.build_assert(self.node.body, act_block_last_line_no)
# SPACING
for block in ['arrange', 'act', 'assert']:
self_block = getattr(self, '{}_block'.format(block))
try:
span = self_block.get_span(self.first_line_no)
except EmptyBlock:
continue
self.line_markers.update(span, self_block.line_type)
yield from self.line_markers.check_arrange_act_spacing()
yield from self.line_markers.check_act_assert_spacing()
yield from self.line_markers.check_blank_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 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 with no stringy parent node. """ |
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_number] = LineType.blank_line
return counter |
<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: the hostgroup item linked to this host @param default: default value @return RETURN: the value """ |
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:
return default |
<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 userdata script for metadata server from Foreman API @param domain: the domain item linked to this host @param hostgroup: the hostgroup item linked to this host @param defaultPwd: the default password if no password is specified in the host>hostgroup>domain params @param defaultSshKey: the default ssh key if no password is specified in the host>hostgroup>domain params @param proxyHostname: hostname of the smartproxy @param tplFolder: the templates folder @return RETURN: the user data """ |
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', defaultPwd)
sshauthkeys = self.getParamFromEnv('global_sshkey', defaultSshKey)
with open(tplFolder+'puppet.conf', 'r') as puppet_file:
p = MyTemplate(puppet_file.read())
content = p.substitute(foremanHostname=proxyHostname)
enc_puppet_file = base64.b64encode(bytes(content, 'utf-8'))
with open(tplFolder+'cloud-init.tpl', 'r') as content_file:
s = MyTemplate(content_file.read())
if sshauthkeys:
sshauthkeys = ' - '+sshauthkeys
self.userdata = s.substitute(
password=password,
fqdn=self['name'],
sshauthkeys=sshauthkeys,
foremanurlbuilt="http://{}/unattended/built"
.format(proxyHostname),
puppet_conf_content=enc_puppet_file.decode('utf-8'))
return self.userdata |
<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():
if runner is not thread_runner:
thread_runner.register_payload(runner.run)
if threading.current_thread() == threading.main_thread():
asyncio_main_run(root_runner=thread_runner)
else:
thread_runner.run()
except Exception as err:
self._logger.exception('runner terminated: %s', err)
raise RuntimeError from err
finally:
self._stop_runners()
self._logger.info('stopped all runners')
self.running.clear() |
<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, they're passed to the form Field's constructor. """ |
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,
)
return formfield |
<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 lists DO NOT keep order (and Python lists do), so this must be taken into account during comparison. Note this wont check all configurations, only first one that seems to match, which can lead to wrong results. :param one: First schema to compare. :param two: Second schema to compare. :rtype: `bool` """ |
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
elif one is None:
return one is two
else:
raise RuntimeError('Not allowed type "{type}"'.format(
type=type(one).__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 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('/'):
return True
return False |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def 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 returned unchanged. :param string value: ECMA regex. :return: 2-tuple with `regex` and `flags` :rtype: namedtuple """ |
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[1:]), 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 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. :param string value: Python regex. :param list flags: List of flags (allowed flags: `re.I`, `re.M`) :return: ECMA 262 regex :rtype: str """ |
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:
field.__set__(self, values.pop(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_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 is name under which value is seen in structure and schema (in primitives) and only there. """ |
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() |
Subsets and Splits