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 parse(self, stream, media_type=None, parser_context=None):
""" Parses the incoming bytestream as XML and returns the resulting data. """ |
assert etree, 'XMLParser requires defusedxml to be installed'
parser_context = parser_context or {}
encoding = parser_context.get('encoding', settings.DEFAULT_CHARSET)
parser = etree.DefusedXMLParser(encoding=encoding)
try:
tree = etree.parse(stream, parser=parser, forbid_dtd=True)
except (etree.ParseError, ValueError) as exc:
raise ParseError('XML parse error - %s' % six.text_type(exc))
data = self._xml_convert(tree.getroot())
return 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 _xml_convert(self, element):
""" convert the xml `element` into the corresponding python object """ |
children = list(element)
if len(children) == 0:
return self._type_convert(element.text)
else:
# if the fist child tag is list-item means all children are list-item
if children[0].tag == "list-item":
data = []
for child in children:
data.append(self._xml_convert(child))
else:
data = {}
for child in children:
data[child.tag] = self._xml_convert(child)
return 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 _type_convert(self, value):
""" Converts the value returned by the XMl parse into the equivalent Python type """ |
if value is None:
return value
try:
return datetime.datetime.strptime(value, '%Y-%m-%d %H:%M:%S')
except ValueError:
pass
try:
return int(value)
except ValueError:
pass
try:
return decimal.Decimal(value)
except decimal.InvalidOperation:
pass
return value |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def render(self, data, accepted_media_type=None, renderer_context=None):
""" Renders `data` into serialized XML. """ |
if data is None:
return ''
stream = StringIO()
xml = SimplerXMLGenerator(stream, self.charset)
xml.startDocument()
xml.startElement(self.root_tag_name, {})
self._to_xml(xml, data)
xml.endElement(self.root_tag_name)
xml.endDocument()
return stream.getvalue() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def open(self):
"""Open a connection to the device.""" |
device_type = 'cisco_ios'
if self.transport == 'telnet':
device_type = 'cisco_ios_telnet'
self.device = ConnectHandler(device_type=device_type,
host=self.hostname,
username=self.username,
password=self.password,
**self.netmiko_optional_args)
# ensure in enable mode
self.device.enable() |
<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_tmp_file(config):
"""Write temp file and for use with inline config and SCP.""" |
tmp_dir = tempfile.gettempdir()
rand_fname = py23_compat.text_type(uuid.uuid4())
filename = os.path.join(tmp_dir, rand_fname)
with open(filename, 'wt') as fobj:
fobj.write(config)
return filename |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _load_candidate_wrapper(self, source_file=None, source_config=None, dest_file=None, file_system=None):
""" Transfer file to remote device for either merge or replace operations Returns (return_status, msg) """ |
return_status = False
msg = ''
if source_file and source_config:
raise ValueError("Cannot simultaneously set source_file and source_config")
if source_config:
if self.inline_transfer:
(return_status, msg) = self._inline_tcl_xfer(source_config=source_config,
dest_file=dest_file,
file_system=file_system)
else:
# Use SCP
tmp_file = self._create_tmp_file(source_config)
(return_status, msg) = self._scp_file(source_file=tmp_file, dest_file=dest_file,
file_system=file_system)
if tmp_file and os.path.isfile(tmp_file):
os.remove(tmp_file)
if source_file:
if self.inline_transfer:
(return_status, msg) = self._inline_tcl_xfer(source_file=source_file,
dest_file=dest_file,
file_system=file_system)
else:
(return_status, msg) = self._scp_file(source_file=source_file, dest_file=dest_file,
file_system=file_system)
if not return_status:
if msg == '':
msg = "Transfer to remote device failed"
return (return_status, msg) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def load_replace_candidate(self, filename=None, config=None):
""" SCP file to device filesystem, defaults to candidate_config. Return None or raise exception """ |
self.config_replace = True
return_status, msg = self._load_candidate_wrapper(source_file=filename,
source_config=config,
dest_file=self.candidate_cfg,
file_system=self.dest_file_system)
if not return_status:
raise ReplaceConfigException(msg) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _commit_hostname_handler(self, cmd):
"""Special handler for hostname change on commit operation.""" |
current_prompt = self.device.find_prompt().strip()
terminating_char = current_prompt[-1]
pattern = r"[>#{}]\s*$".format(terminating_char)
# Look exclusively for trailing pattern that includes '#' and '>'
output = self.device.send_command_expect(cmd, expect_string=pattern)
# Reset base prompt in case hostname changed
self.device.set_base_prompt()
return output |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _gen_full_path(self, filename, file_system=None):
"""Generate full file path on remote device.""" |
if file_system is None:
return '{}/{}'.format(self.dest_file_system, filename)
else:
if ":" not in file_system:
raise ValueError("Invalid file_system specified: {}".format(file_system))
return '{}/{}'.format(file_system, filename) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _gen_rollback_cfg(self):
"""Save a configuration that can be used for rollback.""" |
cfg_file = self._gen_full_path(self.rollback_cfg)
cmd = 'copy running-config {}'.format(cfg_file)
self._disable_confirm()
self.device.send_command_expect(cmd)
self._enable_confirm() |
<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_file_exists(self, cfg_file):
""" Check that the file exists on remote device using full path. cfg_file is full path i.e. flash:/file_name For example # dir flash:/candidate_config.txt Directory of flash:/candidate_config.txt 33 -rw- 5592 Dec 18 2015 10:50:22 -08:00 candidate_config.txt return boolean """ |
cmd = 'dir {}'.format(cfg_file)
success_pattern = 'Directory of {}'.format(cfg_file)
output = self.device.send_command_expect(cmd)
if 'Error opening' in output:
return False
elif success_pattern in output:
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 _expand_interface_name(self, interface_brief):
""" Obtain the full interface name from the abbreviated name. Cache mappings in self.interface_map. """ |
if self.interface_map.get(interface_brief):
return self.interface_map.get(interface_brief)
command = 'show int {}'.format(interface_brief)
output = self._send_command(command)
first_line = output.splitlines()[0]
if 'line protocol' in first_line:
full_int_name = first_line.split()[0]
self.interface_map[interface_brief] = full_int_name
return self.interface_map.get(interface_brief)
else:
return interface_brief |
<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_lldp_neighbors_detail(self, interface=''):
""" IOS implementation of get_lldp_neighbors_detail. Calls get_lldp_neighbors. """ |
lldp = {}
lldp_neighbors = self.get_lldp_neighbors()
# Filter to specific interface
if interface:
lldp_data = lldp_neighbors.get(interface)
if lldp_data:
lldp_neighbors = {interface: lldp_data}
else:
lldp_neighbors = {}
for interface in lldp_neighbors:
local_port = interface
lldp_fields = self._lldp_detail_parser(interface)
# Convert any 'not advertised' to 'N/A'
for field in lldp_fields:
for i, value in enumerate(field):
if 'not advertised' in value:
field[i] = 'N/A'
number_entries = len(lldp_fields[0])
# re.findall will return a list. Make sure same number of entries always returned.
for test_list in lldp_fields:
if len(test_list) != number_entries:
raise ValueError("Failure processing show lldp neighbors detail")
# Standardize the fields
port_id, port_description, chassis_id, system_name, system_description, \
system_capabilities, enabled_capabilities, remote_address = lldp_fields
standardized_fields = zip(port_id, port_description, chassis_id, system_name,
system_description, system_capabilities,
enabled_capabilities, remote_address)
lldp.setdefault(local_port, [])
for entry in standardized_fields:
remote_port_id, remote_port_description, remote_chassis_id, remote_system_name, \
remote_system_description, remote_system_capab, remote_enabled_capab, \
remote_mgmt_address = entry
lldp[local_port].append({
'parent_interface': u'N/A',
'remote_port': remote_port_id,
'remote_port_description': remote_port_description,
'remote_chassis_id': remote_chassis_id,
'remote_system_name': remote_system_name,
'remote_system_description': remote_system_description,
'remote_system_capab': remote_system_capab,
'remote_system_enable_capab': remote_enabled_capab})
return lldp |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def bgp_time_conversion(bgp_uptime):
""" Convert string time to seconds. Examples 00:14:23 00:13:40 00:00:21 00:00:13 00:00:49 1d11h 1d17h 1w0d 8w5d 1y28w never """ |
bgp_uptime = bgp_uptime.strip()
uptime_letters = set(['w', 'h', 'd'])
if 'never' in bgp_uptime:
return -1
elif ':' in bgp_uptime:
times = bgp_uptime.split(":")
times = [int(x) for x in times]
hours, minutes, seconds = times
return (hours * 3600) + (minutes * 60) + seconds
# Check if any letters 'w', 'h', 'd' are in the time string
elif uptime_letters & set(bgp_uptime):
form1 = r'(\d+)d(\d+)h' # 1d17h
form2 = r'(\d+)w(\d+)d' # 8w5d
form3 = r'(\d+)y(\d+)w' # 1y28w
match = re.search(form1, bgp_uptime)
if match:
days = int(match.group(1))
hours = int(match.group(2))
return (days * DAY_SECONDS) + (hours * 3600)
match = re.search(form2, bgp_uptime)
if match:
weeks = int(match.group(1))
days = int(match.group(2))
return (weeks * WEEK_SECONDS) + (days * DAY_SECONDS)
match = re.search(form3, bgp_uptime)
if match:
years = int(match.group(1))
weeks = int(match.group(2))
return (years * YEAR_SECONDS) + (weeks * WEEK_SECONDS)
raise ValueError("Unexpected value for BGP uptime string: {}".format(bgp_uptime)) |
<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(self, commands):
""" Execute a list of commands and return the output in a dictionary format using the command as the key. Example input: ['show clock', 'show calendar'] Output example: { 'show calendar': u'22:02:01 UTC Thu Feb 18 2016', 'show clock': u'*22:01:51.165 UTC Thu Feb 18 2016'} """ |
cli_output = dict()
if type(commands) is not list:
raise TypeError('Please enter a valid list of commands!')
for command in commands:
output = self._send_command(command)
if 'Invalid input detected' in output:
raise ValueError('Unable to execute command "{}"'.format(command))
cli_output.setdefault(command, {})
cli_output[command] = output
return cli_output |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_config(self, retrieve='all'):
"""Implementation of get_config for IOS. Returns the startup or/and running configuration as dictionary. The keys of the dictionary represent the type of configuration (startup or running). The candidate is always empty string, since IOS does not support candidate configuration. """ |
configs = {
'startup': '',
'running': '',
'candidate': '',
}
if retrieve in ('startup', 'all'):
command = 'show startup-config'
output = self._send_command(command)
configs['startup'] = output
if retrieve in ('running', 'all'):
command = 'show running-config'
output = self._send_command(command)
configs['running'] = output
return configs |
<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(self):
"""Read the current value of the accelerometer and return it as a tuple of signed 16-bit X, Y, Z axis values. """ |
raw = self._device.readList(ADXL345_REG_DATAX0, 6)
return struct.unpack('<hhh', raw) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def digital_write(pin_num, value, hardware_addr=0):
"""Writes the value to the input pin specified. .. note:: This function is for familiarality with users of other types of IO board. Consider accessing the ``output_pins`` attribute of a PiFaceDigital object: :param pin_num: The pin number to write to. :type pin_num: int :param value: The value to write. :type value: int :param hardware_addr: The board to read from (default: 0) :type hardware_addr: int """ |
_get_pifacedigital(hardware_addr).output_pins[pin_num].value = 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 digital_write_pullup(pin_num, value, hardware_addr=0):
"""Writes the value to the input pullup specified. .. note:: This function is for familiarality with users of other types of IO board. Consider accessing the ``gppub`` attribute of a PiFaceDigital object: 0xff :param pin_num: The pin number to write to. :type pin_num: int :param value: The value to write. :type value: int :param hardware_addr: The board to read from (default: 0) :type hardware_addr: int """ |
_get_pifacedigital(hardware_addr).gppub.bits[pin_num].value = value |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_my_ip():
"""Returns this computers IP address as a string.""" |
ip = subprocess.check_output(GET_IP_CMD, shell=True).decode('utf-8')[:-1]
return ip.strip() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def set_output_port(self, new_value, old_value=0):
"""Sets the output port value to new_value, defaults to old_value.""" |
print("Setting output port to {}.".format(new_value))
port_value = old_value
try:
port_value = int(new_value) # dec
except ValueError:
port_value = int(new_value, 16) # hex
finally:
self.pifacedigital.output_port.value = port_value
return port_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 _request_api(self, **kwargs):
"""Wrap the calls the url, with the given arguments. :param str url: Url to call with the given arguments :param str method: [POST | GET] Method to use on the request :param int status: Expected status code """ |
_url = kwargs.get('url')
_method = kwargs.get('method', 'GET')
_status = kwargs.get('status', 200)
counter = 0
if _method not in ['GET', 'POST']:
raise ValueError('Method is not GET or POST')
while True:
try:
res = REQ[_method](_url, cookies=self._cookie)
if res.status_code == _status:
break
else:
raise BadStatusException(res.content)
except requests.exceptions.BaseHTTPError:
if counter < self._retries:
counter += 1
continue
raise MaxRetryError
self._last_result = res
return res |
<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_infos_with_id(self, uid):
"""Get info about a user based on his id. :return: JSON """ |
_logid = uid
_user_info_url = USER_INFO_URL.format(logid=_logid)
return self._request_api(url=_user_info_url).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 get_current_activities(self, login=None, **kwargs):
"""Get the current activities of user. Either use the `login` param, or the client's login if unset. :return: JSON """ |
_login = kwargs.get(
'login',
login or self._login
)
_activity_url = ACTIVITY_URL.format(login=_login)
return self._request_api(url=_activity_url).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 get_notifications(self, login=None, **kwargs):
"""Get the current notifications of a user. :return: JSON """ |
_login = kwargs.get(
'login',
login or self._login
)
_notif_url = NOTIF_URL.format(login=_login)
return self._request_api(url=_notif_url).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 get_grades(self, login=None, promotion=None, **kwargs):
"""Get a user's grades on a single promotion based on his login. Either use the `login` param, or the client's login if unset. :return: JSON """ |
_login = kwargs.get(
'login',
login or self._login
)
_promotion_id = kwargs.get('promotion', promotion)
_grades_url = GRADES_URL.format(login=_login, promo_id=_promotion_id)
return self._request_api(url=_grades_url).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 get_picture(self, login=None, **kwargs):
"""Get a user's picture. :param str login: Login of the user to check :return: JSON """ |
_login = kwargs.get(
'login',
login or self._login
)
_activities_url = PICTURE_URL.format(login=_login)
return self._request_api(url=_activities_url).content |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_projects(self, **kwargs):
"""Get a user's project. :param str login: User's login (Default: self._login) :return: JSON """ |
_login = kwargs.get('login', self._login)
search_url = SEARCH_URL.format(login=_login)
return self._request_api(url=search_url).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 get_activities_for_project(self, module=None, **kwargs):
"""Get the related activities of a project. :param str module: Stages of a given module :return: JSON """ |
_module_id = kwargs.get('module', module)
_activities_url = ACTIVITIES_URL.format(module_id=_module_id)
return self._request_api(url=_activities_url).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 get_group_for_activity(self, module=None, project=None, **kwargs):
"""Get groups for activity. :param str module: Base module :param str module: Project which contains the group requested :return: JSON """ |
_module_id = kwargs.get('module', module)
_project_id = kwargs.get('project', project)
_url = GROUPS_URL.format(module_id=_module_id, project_id=_project_id)
return self._request_api(url=_url).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 get_students(self, **kwargs):
"""Get users by promotion id. :param int promotion: Promotion ID :return: JSON """ |
_promotion_id = kwargs.get('promotion')
_url = PROMOTION_URL.format(promo_id=_promotion_id)
return self._request_api(url=_url).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 get_log_events(self, login=None, **kwargs):
"""Get a user's log events. :param str login: User's login (Default: self._login) :return: JSON """ |
_login = kwargs.get(
'login',
login
)
log_events_url = GSA_EVENTS_URL.format(login=_login)
return self._request_api(url=log_events_url).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 get_events(self, login=None, start_date=None, end_date=None, **kwargs):
"""Get a user's events. :param str login: User's login (Default: self._login) :param str start_date: Start date :param str end_date: To date :return: JSON """ |
_login = kwargs.get(
'login',
login
)
log_events_url = EVENTS_URL.format(
login=_login,
start_date=start_date,
end_date=end_date,
)
return self._request_api(url=log_events_url).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 get_logs(self, login=None, **kwargs):
"""Get a user's logs. :param str login: User's login (Default: self._login) :return: JSON """ |
_login = kwargs.get(
'login',
login
)
log_events_url = GSA_LOGS_URL.format(login=_login)
return self._request_api(url=log_events_url).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 register(self, collector):
""" Registers a collector""" |
if not isinstance(collector, Collector):
raise TypeError(
"Can't register instance, not a valid type of collector")
if collector.name in self.collectors:
raise ValueError("Collector already exists or name colision")
with mutex:
self.collectors[collector.name] = collector |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def set_value(self, labels, value):
""" Sets a value in the container""" |
if labels:
self._label_names_correct(labels)
with mutex:
self.values[labels] = value |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_all(self):
""" Returns a list populated by tuples of 2 elements, first one is a dict with all the labels and the second elemnt is the value of the metric itself """ |
with mutex:
items = self.values.items()
result = []
for k, v in items:
# Check if is a single value dict (custom empty key)
if not k or k == MetricDict.EMPTY_KEY:
key = None
else:
key = decoder.decode(k)
result.append((key, self.get(k)))
return result |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def add(self, labels, value):
"""Add adds a single observation to the summary.""" |
if type(value) not in (float, int):
raise TypeError("Summary only works with digits (int, float)")
# We have already a lock for data but not for the estimator
with mutex:
try:
e = self.get_value(labels)
except KeyError:
# Initialize quantile estimator
e = quantile.Estimator(*self.__class__.DEFAULT_INVARIANTS)
self.set_value(labels, e)
e.observe(float(value)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get(self, labels):
""" Get gets the data in the form of 0.5, 0.9 and 0.99 percentiles. Also you get sum and count, all in a dict """ |
return_data = {}
# We have already a lock for data but not for the estimator
with mutex:
e = self.get_value(labels)
# Set invariants data (default to 0.50, 0.90 and 0.99)
for i in e._invariants:
q = i._quantile
return_data[q] = e.query(q)
# Set sum and count
return_data[self.__class__.SUM_KEY] = e._sum
return_data[self.__class__.COUNT_KEY] = e._observations
return return_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 get_child(self, name, attribs=None):
""" Returns the first child that matches the given name and attributes. """ |
if name == '.':
if attribs is None or len(attribs) == 0:
return self
if attribs == self.attribs:
return self
return self.child_index.get(nodehash(name, attribs)) |
<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(self, path, data=None):
""" Creates the given node, regardless of whether or not it already exists. Returns the new node. """ |
node = self.current[-1]
path = self._splitpath(path)
n_items = len(path)
for n, item in enumerate(path):
tag, attribs = self._splittag(item)
# The leaf node is always newly created.
if n == n_items-1:
node = node.add(Node(tag, attribs))
break
# Parent nodes are only created if they do not exist yet.
existing = node.get_child(tag, attribs)
if existing is not None:
node = existing
else:
node = node.add(Node(tag, attribs))
if data:
node.text = unquote(data)
return 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 open(self, path):
""" Creates and enters the given node, regardless of whether it already exists. Returns the new node. """ |
self.current.append(self.create(path))
return self.current[-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 enter(self, path):
""" Enters the given node. Creates it if it does not exist. Returns the node. """ |
self.current.append(self.add(path))
return self.current[-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 best_trial_tid(self, rank=0):
"""Get tid of the best trial rank=0 means the best model rank=1 means second best """ |
candidates = [t for t in self.trials
if t['result']['status'] == STATUS_OK]
if len(candidates) == 0:
return None
losses = [float(t['result']['loss']) for t in candidates]
assert not np.any(np.isnan(losses))
lid = np.where(np.argsort(losses).argsort() == rank)[0][0]
return candidates[lid]["tid"] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def plot_history(self, tid, scores=["loss", "f1", "accuracy"], figsize=(15, 3)):
"""Plot the loss curves""" |
history = self.train_history(tid)
import matplotlib.pyplot as plt
fig = plt.figure(figsize=figsize)
for i, score in enumerate(scores):
plt.subplot(1, len(scores), i + 1)
plt.tight_layout()
plt.plot(history[score], label="train")
plt.plot(history['val_' + score], label="validation")
plt.title(score)
plt.ylabel(score)
plt.xlabel('epoch')
plt.legend(loc='best')
return fig |
<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_model(self, tid, custom_objects=None):
"""Load saved keras model of the trial. If tid = None, get the best model Not applicable for trials ran in cross validion (i.e. not applicable for `CompileFN.cv_n_folds is None` """ |
if tid is None:
tid = self.best_trial_tid()
model_path = self.get_trial(tid)["result"]["path"]["model"]
return load_model(model_path, custom_objects=custom_objects) |
<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_ok_results(self, verbose=True):
"""Return a list of results with ok status """ |
if len(self.trials) == 0:
return []
not_ok = np.where(np.array(self.statuses()) != "ok")[0]
if len(not_ok) > 0 and verbose:
print("{0}/{1} trials were not ok.".format(len(not_ok), len(self.trials)))
print("Trials: " + str(not_ok))
print("Statuses: " + str(np.array(self.statuses())[not_ok]))
r = [merge_dicts({"tid": t["tid"]}, t["result"].to_dict())
for t in self.trials if t["result"]["status"] == "ok"]
return 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 resp2flask(resp):
"""Convert an oic.utils.http_util instance to Flask.""" |
if isinstance(resp, Redirect) or isinstance(resp, SeeOther):
code = int(resp.status.split()[0])
raise cherrypy.HTTPRedirect(resp.message, code)
return resp.message, resp.status, resp.headers |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def setup_authentication_methods(authn_config, template_env):
"""Add all authentication methods specified in the configuration.""" |
routing = {}
ac = AuthnBroker()
for authn_method in authn_config:
cls = make_cls_from_name(authn_method["class"])
instance = cls(template_env=template_env, **authn_method["kwargs"])
ac.add(authn_method["acr"], instance)
routing[instance.url_endpoint] = VerifierMiddleware(instance)
return ac, routing |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def setup_endpoints(provider):
"""Setup the OpenID Connect Provider endpoints.""" |
app_routing = {}
endpoints = [
AuthorizationEndpoint(
pyoidcMiddleware(provider.authorization_endpoint)),
TokenEndpoint(
pyoidcMiddleware(provider.token_endpoint)),
UserinfoEndpoint(
pyoidcMiddleware(provider.userinfo_endpoint)),
RegistrationEndpoint(
pyoidcMiddleware(provider.registration_endpoint)),
EndSessionEndpoint(
pyoidcMiddleware(provider.endsession_endpoint))
]
for ep in endpoints:
app_routing["/{}".format(ep.etype)] = ep
return app_routing |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _webfinger(provider, request, **kwargs):
"""Handle webfinger requests.""" |
params = urlparse.parse_qs(request)
if params["rel"][0] == OIC_ISSUER:
wf = WebFinger()
return Response(wf.response(params["resource"][0], provider.baseurl),
headers=[("Content-Type", "application/jrd+json")])
else:
return BadRequest("Incorrect webfinger.") |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def featuresQuery(self, **kwargs):
""" Converts a dictionary of keyword arguments into a tuple of SQL select statements and the list of SQL arguments """ |
# TODO: Optimize by refactoring out string concatenation
sql = ""
sql_rows = "SELECT * FROM FEATURE WHERE id > 1 "
sql_args = ()
if 'name' in kwargs and kwargs['name']:
sql += "AND name = ? "
sql_args += (kwargs.get('name'),)
if 'geneSymbol' in kwargs and kwargs['geneSymbol']:
sql += "AND gene_name = ? "
sql_args += (kwargs.get('geneSymbol'),)
if 'start' in kwargs and kwargs['start'] is not None:
sql += "AND end > ? "
sql_args += (kwargs.get('start'),)
if 'end' in kwargs and kwargs['end'] is not None:
sql += "AND start < ? "
sql_args += (kwargs.get('end'),)
if 'referenceName' in kwargs and kwargs['referenceName']:
sql += "AND reference_name = ?"
sql_args += (kwargs.get('referenceName'),)
if 'parentId' in kwargs and kwargs['parentId']:
sql += "AND parent_id = ? "
sql_args += (kwargs['parentId'],)
if kwargs.get('featureTypes') is not None \
and len(kwargs['featureTypes']) > 0:
sql += "AND type IN ("
sql += ", ".join(["?", ] * len(kwargs.get('featureTypes')))
sql += ") "
sql_args += tuple(kwargs.get('featureTypes'))
sql_rows += sql
sql_rows += " ORDER BY reference_name, start, end ASC "
return sql_rows, sql_args |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def searchFeaturesInDb( self, startIndex=0, maxResults=None, referenceName=None, start=None, end=None, parentId=None, featureTypes=None, name=None, geneSymbol=None):
""" Perform a full features query in database. :param startIndex: int representing first record to return :param maxResults: int representing number of records to return :param referenceName: string representing reference name, ex 'chr1' :param start: int position on reference to start search :param end: int position on reference to end search >= start :param parentId: string restrict search by id of parent node. :param name: match features by name :param geneSymbol: match features by gene symbol :return an array of dictionaries, representing the returned data. """ |
# TODO: Refactor out common bits of this and the above count query.
sql, sql_args = self.featuresQuery(
startIndex=startIndex, maxResults=maxResults,
referenceName=referenceName, start=start, end=end,
parentId=parentId, featureTypes=featureTypes,
name=name, geneSymbol=geneSymbol)
sql += sqlite_backend.limitsSql(startIndex, maxResults)
query = self._dbconn.execute(sql, sql_args)
return sqlite_backend.sqliteRowsToDicts(query.fetchall()) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def getFeatureById(self, featureId):
""" Fetch feature by featureID. :param featureId: the FeatureID as found in GFF3 records :return: dictionary representing a feature object, or None if no match is found. """ |
sql = "SELECT * FROM FEATURE WHERE id = ?"
query = self._dbconn.execute(sql, (featureId,))
ret = query.fetchone()
if ret is None:
return None
return sqlite_backend.sqliteRowToDict(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 toProtocolElement(self):
""" Returns the representation of this FeatureSet as the corresponding ProtocolElement. """ |
gaFeatureSet = protocol.FeatureSet()
gaFeatureSet.id = self.getId()
gaFeatureSet.dataset_id = self.getParentContainer().getId()
gaFeatureSet.reference_set_id = pb.string(self._referenceSet.getId())
gaFeatureSet.name = self._name
gaFeatureSet.source_uri = self._sourceUri
attributes = self.getAttributes()
for key in attributes:
gaFeatureSet.attributes.attr[key] \
.values.extend(protocol.encodeValue(attributes[key]))
return gaFeatureSet |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def getCompoundIdForFeatureId(self, featureId):
""" Returns server-style compound ID for an internal featureId. :param long featureId: id of feature in database :return: string representing ID for the specified GA4GH protocol Feature object in this FeatureSet. """ |
if featureId is not None and featureId != "":
compoundId = datamodel.FeatureCompoundId(
self.getCompoundId(), str(featureId))
else:
compoundId = ""
return str(compoundId) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def getFeature(self, compoundId):
""" Fetches a simulated feature by ID. :param compoundId: any non-null string :return: A simulated feature with id set to the same value as the passed-in compoundId. ":raises: exceptions.ObjectWithIdNotFoundException if None is passed in for the compoundId. """ |
if compoundId is None:
raise exceptions.ObjectWithIdNotFoundException(compoundId)
randomNumberGenerator = random.Random()
randomNumberGenerator.seed(self._randomSeed)
feature = self._generateSimulatedFeature(randomNumberGenerator)
feature.id = str(compoundId)
feature.parent_id = "" # TODO: Test with nonempty parentIDs?
return feature |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def getFeatures(self, referenceName=None, start=None, end=None, startIndex=None, maxResults=None, featureTypes=None, parentId=None, name=None, geneSymbol=None, numFeatures=10):
""" Returns a set number of simulated features. :param referenceName: name of reference to "search" on :param start: start coordinate of query :param end: end coordinate of query :param startIndex: None or int :param maxResults: None or int :param featureTypes: optional list of ontology terms to limit query :param parentId: optional parentId to limit query. :param name: the name of the feature :param geneSymbol: the symbol for the gene the features are on :param numFeatures: number of features to generate in the return. 10 is a reasonable (if arbitrary) default. :return: Yields feature list """ |
randomNumberGenerator = random.Random()
randomNumberGenerator.seed(self._randomSeed)
for featureId in range(numFeatures):
gaFeature = self._generateSimulatedFeature(randomNumberGenerator)
gaFeature.id = self.getCompoundIdForFeatureId(featureId)
match = (
gaFeature.start < end and
gaFeature.end > start and
gaFeature.reference_name == referenceName and (
featureTypes is None or len(featureTypes) == 0 or
gaFeature.feature_type in featureTypes))
if match:
gaFeature.parent_id = "" # TODO: Test nonempty parentIDs?
yield gaFeature |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def addRnaQuantification(self, rnaQuantification):
""" Add an rnaQuantification to this rnaQuantificationSet """ |
id_ = rnaQuantification.getId()
self._rnaQuantificationIdMap[id_] = rnaQuantification
self._rnaQuantificationIds.append(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 populateFromFile(self, dataUrl):
""" Populates the instance variables of this RnaQuantificationSet from the specified data URL. """ |
self._dbFilePath = dataUrl
self._db = SqliteRnaBackend(self._dbFilePath)
self.addRnaQuants() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def populateFromRow(self, quantificationSetRecord):
""" Populates the instance variables of this RnaQuantificationSet from the specified DB row. """ |
self._dbFilePath = quantificationSetRecord.dataurl
self.setAttributesJson(quantificationSetRecord.attributes)
self._db = SqliteRnaBackend(self._dbFilePath)
self.addRnaQuants() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def getExpressionLevels( self, threshold=0.0, names=[], startIndex=0, maxResults=0):
""" Returns the list of ExpressionLevels in this RNA Quantification. """ |
rnaQuantificationId = self.getLocalId()
with self._db as dataSource:
expressionsReturned = dataSource.searchExpressionLevelsInDb(
rnaQuantificationId,
names=names,
threshold=threshold,
startIndex=startIndex,
maxResults=maxResults)
expressionLevels = [
SqliteExpressionLevel(self, expressionEntry) for
expressionEntry in expressionsReturned]
return expressionLevels |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def populateFromRow(self, callSetRecord):
""" Populates this CallSet from the specified DB row. """ |
self._biosampleId = callSetRecord.biosampleid
self.setAttributesJson(callSetRecord.attributes) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def toProtocolElement(self):
""" Returns the representation of this CallSet as the corresponding ProtocolElement. """ |
variantSet = self.getParentContainer()
gaCallSet = protocol.CallSet(
biosample_id=self.getBiosampleId())
if variantSet.getCreationTime():
gaCallSet.created = variantSet.getCreationTime()
if variantSet.getUpdatedTime():
gaCallSet.updated = variantSet.getUpdatedTime()
gaCallSet.id = self.getId()
gaCallSet.name = self.getLocalId()
gaCallSet.variant_set_ids.append(variantSet.getId())
self.serializeAttributes(gaCallSet)
return gaCallSet |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def addVariantAnnotationSet(self, variantAnnotationSet):
""" Adds the specified variantAnnotationSet to this dataset. """ |
id_ = variantAnnotationSet.getId()
self._variantAnnotationSetIdMap[id_] = variantAnnotationSet
self._variantAnnotationSetIds.append(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 getVariantAnnotationSet(self, id_):
""" Returns the AnnotationSet in this dataset with the specified 'id' """ |
if id_ not in self._variantAnnotationSetIdMap:
raise exceptions.AnnotationSetNotFoundException(id_)
return self._variantAnnotationSetIdMap[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 addCallSet(self, callSet):
""" Adds the specfied CallSet to this VariantSet. """ |
callSetId = callSet.getId()
self._callSetIdMap[callSetId] = callSet
self._callSetNameMap[callSet.getLocalId()] = callSet
self._callSetIds.append(callSetId)
self._callSetIdToIndex[callSet.getId()] = len(self._callSetIds) - 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 addCallSetFromName(self, sampleName):
""" Adds a CallSet for the specified sample name. """ |
callSet = CallSet(self, sampleName)
self.addCallSet(callSet) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def getCallSetByName(self, name):
""" Returns a CallSet with the specified name, or raises a CallSetNameNotFoundException if it does not exist. """ |
if name not in self._callSetNameMap:
raise exceptions.CallSetNameNotFoundException(name)
return self._callSetNameMap[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 getCallSet(self, id_):
""" Returns a CallSet with the specified id, or raises a CallSetNotFoundException if it does not exist. """ |
if id_ not in self._callSetIdMap:
raise exceptions.CallSetNotFoundException(id_)
return self._callSetIdMap[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 toProtocolElement(self):
""" Converts this VariantSet into its GA4GH protocol equivalent. """ |
protocolElement = protocol.VariantSet()
protocolElement.id = self.getId()
protocolElement.dataset_id = self.getParentContainer().getId()
protocolElement.reference_set_id = self._referenceSet.getId()
protocolElement.metadata.extend(self.getMetadata())
protocolElement.dataset_id = self.getParentContainer().getId()
protocolElement.reference_set_id = self._referenceSet.getId()
protocolElement.name = self.getLocalId()
self.serializeAttributes(protocolElement)
return protocolElement |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _createGaVariant(self):
""" Convenience method to set the common fields in a GA Variant object from this variant set. """ |
ret = protocol.Variant()
if self._creationTime:
ret.created = self._creationTime
if self._updatedTime:
ret.updated = self._updatedTime
ret.variant_set_id = self.getId()
return 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 getVariantId(self, gaVariant):
""" Returns an ID string suitable for the specified GA Variant object in this variant set. """ |
md5 = self.hashVariant(gaVariant)
compoundId = datamodel.VariantCompoundId(
self.getCompoundId(), gaVariant.reference_name,
str(gaVariant.start), md5)
return str(compoundId) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def getCallSetId(self, sampleName):
""" Returns the callSetId for the specified sampleName in this VariantSet. """ |
compoundId = datamodel.CallSetCompoundId(
self.getCompoundId(), sampleName)
return str(compoundId) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def hashVariant(cls, gaVariant):
""" Produces an MD5 hash of the ga variant object to distinguish it from other variants at the same genomic coordinate. """ |
hash_str = gaVariant.reference_bases + \
str(tuple(gaVariant.alternate_bases))
return hashlib.md5(hash_str).hexdigest() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def generateVariant(self, referenceName, position, randomNumberGenerator):
""" Generate a random variant for the specified position using the specified random number generator. This generator should be seeded with a value that is unique to this position so that the same variant will always be produced regardless of the order it is generated in. """ |
variant = self._createGaVariant()
variant.reference_name = referenceName
variant.start = position
variant.end = position + 1 # SNPs only for now
bases = ["A", "C", "G", "T"]
ref = randomNumberGenerator.choice(bases)
variant.reference_bases = ref
alt = randomNumberGenerator.choice(
[base for base in bases if base != ref])
variant.alternate_bases.append(alt)
randChoice = randomNumberGenerator.randint(0, 2)
if randChoice == 0:
variant.filters_applied = False
elif randChoice == 1:
variant.filters_applied = True
variant.filters_passed = True
else:
variant.filters_applied = True
variant.filters_passed = False
variant.filters_failed.append('q10')
for callSet in self.getCallSets():
call = variant.calls.add()
call.call_set_id = callSet.getId()
# for now, the genotype is either [0,1], [1,1] or [1,0] with equal
# probability; probably will want to do something more
# sophisticated later.
randomChoice = randomNumberGenerator.choice(
[[0, 1], [1, 0], [1, 1]])
call.genotype.extend(randomChoice)
# TODO What is a reasonable model for generating these likelihoods?
# Are these log-scaled? Spec does not say.
call.genotype_likelihood.extend([-100, -100, -100])
variant.id = self.getVariantId(variant)
return variant |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def populateFromRow(self, variantSetRecord):
""" Populates this VariantSet from the specified DB row. """ |
self._created = variantSetRecord.created
self._updated = variantSetRecord.updated
self.setAttributesJson(variantSetRecord.attributes)
self._chromFileMap = {}
# We can't load directly as we want tuples to be stored
# rather than lists.
for key, value in json.loads(variantSetRecord.dataurlindexmap).items():
self._chromFileMap[key] = tuple(value)
self._metadata = []
for jsonDict in json.loads(variantSetRecord.metadata):
metadata = protocol.fromJson(json.dumps(jsonDict),
protocol.VariantSetMetadata)
self._metadata.append(metadata) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def populateFromFile(self, dataUrls, indexFiles):
""" Populates this variant set using the specified lists of data files and indexes. These must be in the same order, such that the jth index file corresponds to the jth data file. """ |
assert len(dataUrls) == len(indexFiles)
for dataUrl, indexFile in zip(dataUrls, indexFiles):
varFile = pysam.VariantFile(dataUrl, index_filename=indexFile)
try:
self._populateFromVariantFile(varFile, dataUrl, indexFile)
finally:
varFile.close() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def populateFromDirectory(self, vcfDirectory):
""" Populates this VariantSet by examing all the VCF files in the specified directory. This is mainly used for as a convenience for testing purposes. """ |
pattern = os.path.join(vcfDirectory, "*.vcf.gz")
dataFiles = []
indexFiles = []
for vcfFile in glob.glob(pattern):
dataFiles.append(vcfFile)
indexFiles.append(vcfFile + ".tbi")
self.populateFromFile(dataFiles, indexFiles) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def checkConsistency(self):
""" Perform consistency check on the variant set """ |
for referenceName, (dataUrl, indexFile) in self._chromFileMap.items():
varFile = pysam.VariantFile(dataUrl, index_filename=indexFile)
try:
for chrom in varFile.index:
chrom, _, _ = self.sanitizeVariantFileFetch(chrom)
if not isEmptyIter(varFile.fetch(chrom)):
self._checkMetadata(varFile)
self._checkCallSetIds(varFile)
finally:
varFile.close() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _populateFromVariantFile(self, varFile, dataUrl, indexFile):
""" Populates the instance variables of this VariantSet from the specified pysam VariantFile object. """ |
if varFile.index is None:
raise exceptions.NotIndexedException(dataUrl)
for chrom in varFile.index:
# Unlike Tabix indices, CSI indices include all contigs defined
# in the BCF header. Thus we must test each one to see if
# records exist or else they are likely to trigger spurious
# overlapping errors.
chrom, _, _ = self.sanitizeVariantFileFetch(chrom)
if not isEmptyIter(varFile.fetch(chrom)):
if chrom in self._chromFileMap:
raise exceptions.OverlappingVcfException(dataUrl, chrom)
self._chromFileMap[chrom] = dataUrl, indexFile
self._updateMetadata(varFile)
self._updateCallSetIds(varFile)
self._updateVariantAnnotationSets(varFile, dataUrl) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _updateVariantAnnotationSets(self, variantFile, dataUrl):
""" Updates the variant annotation set associated with this variant using information in the specified pysam variantFile. """ |
# TODO check the consistency of this between VCF files.
if not self.isAnnotated():
annotationType = None
for record in variantFile.header.records:
if record.type == "GENERIC":
if record.key == "SnpEffVersion":
annotationType = ANNOTATIONS_SNPEFF
elif record.key == "VEP":
version = record.value.split()[0]
# TODO we need _much_ more sophisticated processing
# of VEP versions here. When do they become
# incompatible?
if version == "v82":
annotationType = ANNOTATIONS_VEP_V82
elif version == "v77":
annotationType = ANNOTATIONS_VEP_V77
else:
# TODO raise a proper typed exception there with
# the file name as an argument.
raise ValueError(
"Unsupported VEP version {} in '{}'".format(
version, dataUrl))
if annotationType is None:
infoKeys = variantFile.header.info.keys()
if 'CSQ' in infoKeys or 'ANN' in infoKeys:
# TODO likewise, we want a properly typed exception that
# we can throw back to the repo manager UI and display
# as an import error.
raise ValueError(
"Unsupported annotations in '{}'".format(dataUrl))
if annotationType is not None:
vas = HtslibVariantAnnotationSet(self, self.getLocalId())
vas.populateFromFile(variantFile, annotationType)
self.addVariantAnnotationSet(vas) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _updateMetadata(self, variantFile):
""" Updates the metadata for his variant set based on the specified variant file """ |
metadata = self._getMetadataFromVcf(variantFile)
if self._metadata is None:
self._metadata = metadata |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _checkMetadata(self, variantFile):
""" Checks that metadata is consistent """ |
metadata = self._getMetadataFromVcf(variantFile)
if self._metadata is not None and self._metadata != metadata:
raise exceptions.InconsistentMetaDataException(
variantFile.filename) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _checkCallSetIds(self, variantFile):
""" Checks callSetIds for consistency """ |
if len(self._callSetIdMap) > 0:
callSetIds = set([
self.getCallSetId(sample)
for sample in variantFile.header.samples])
if callSetIds != set(self._callSetIdMap.keys()):
raise exceptions.InconsistentCallSetIdException(
variantFile.filename) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _updateCallSetIds(self, variantFile):
""" Updates the call set IDs based on the specified variant file. """ |
if len(self._callSetIdMap) == 0:
for sample in variantFile.header.samples:
self.addCallSetFromName(sample) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def convertVariant(self, record, callSetIds):
""" Converts the specified pysam variant record into a GA4GH Variant object. Only calls for the specified list of callSetIds will be included. """ |
variant = self._createGaVariant()
variant.reference_name = record.contig
if record.id is not None:
variant.names.extend(record.id.split(';'))
variant.start = record.start # 0-based inclusive
variant.end = record.stop # 0-based exclusive
variant.reference_bases = record.ref
if record.alts is not None:
variant.alternate_bases.extend(list(record.alts))
filterKeys = record.filter.keys()
if len(filterKeys) == 0:
variant.filters_applied = False
else:
variant.filters_applied = True
if len(filterKeys) == 1 and filterKeys[0] == 'PASS':
variant.filters_passed = True
else:
variant.filters_passed = False
variant.filters_failed.extend(filterKeys)
# record.qual is also available, when supported by GAVariant.
for key, value in record.info.iteritems():
if value is None:
continue
if key == 'SVTYPE':
variant.variant_type = value
elif key == 'SVLEN':
variant.svlen = int(value[0])
elif key == 'CIPOS':
variant.cipos.extend(value)
elif key == 'CIEND':
variant.ciend.extend(value)
elif isinstance(value, str):
value = value.split(',')
protocol.setAttribute(
variant.attributes.attr[key].values, value)
for callSetId in callSetIds:
callSet = self.getCallSet(callSetId)
pysamCall = record.samples[str(callSet.getSampleName())]
variant.calls.add().CopyFrom(
self._convertGaCall(callSet, pysamCall))
variant.id = self.getVariantId(variant)
return variant |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def getPysamVariants(self, referenceName, startPosition, endPosition):
""" Returns an iterator over the pysam VCF records corresponding to the specified query. """ |
if referenceName in self._chromFileMap:
varFileName = self._chromFileMap[referenceName]
referenceName, startPosition, endPosition = \
self.sanitizeVariantFileFetch(
referenceName, startPosition, endPosition)
cursor = self.getFileHandle(varFileName).fetch(
referenceName, startPosition, endPosition)
for record in cursor:
yield record |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def getVariants(self, referenceName, startPosition, endPosition, callSetIds=[]):
""" Returns an iterator over the specified variants. The parameters correspond to the attributes of a GASearchVariantsRequest object. """ |
if callSetIds is None:
callSetIds = self._callSetIds
else:
for callSetId in callSetIds:
if callSetId not in self._callSetIds:
raise exceptions.CallSetNotInVariantSetException(
callSetId, self.getId())
for record in self.getPysamVariants(
referenceName, startPosition, endPosition):
yield self.convertVariant(record, callSetIds) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def getMetadataId(self, metadata):
""" Returns the id of a metadata """ |
return str(datamodel.VariantSetMetadataCompoundId(
self.getCompoundId(), 'metadata:' + metadata.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 _createGaVariantAnnotation(self):
""" Convenience method to set the common fields in a GA VariantAnnotation object from this variant set. """ |
ret = protocol.VariantAnnotation()
ret.created = self._creationTime
ret.variant_annotation_set_id = self.getId()
return 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 toProtocolElement(self):
""" Converts this VariantAnnotationSet into its GA4GH protocol equivalent. """ |
protocolElement = protocol.VariantAnnotationSet()
protocolElement.id = self.getId()
protocolElement.variant_set_id = self._variantSet.getId()
protocolElement.name = self.getLocalId()
protocolElement.analysis.CopyFrom(self.getAnalysis())
self.serializeAttributes(protocolElement)
return protocolElement |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def hashVariantAnnotation(cls, gaVariant, gaVariantAnnotation):
""" Produces an MD5 hash of the gaVariant and gaVariantAnnotation objects """ |
treffs = [treff.id for treff in gaVariantAnnotation.transcript_effects]
return hashlib.md5(
"{}\t{}\t{}\t".format(
gaVariant.reference_bases, tuple(gaVariant.alternate_bases),
treffs)
).hexdigest() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def generateVariantAnnotation(self, variant):
""" Generate a random variant annotation based on a given variant. This generator should be seeded with a value that is unique to the variant so that the same annotation will always be produced regardless of the order it is generated in. """ |
# To make this reproducible, make a seed based on this
# specific variant.
seed = self._randomSeed + variant.start + variant.end
randomNumberGenerator = random.Random()
randomNumberGenerator.seed(seed)
ann = protocol.VariantAnnotation()
ann.variant_annotation_set_id = str(self.getCompoundId())
ann.variant_id = variant.id
ann.created = datetime.datetime.now().isoformat() + "Z"
# make a transcript effect for each alternate base element
# multiplied by a random integer (1,5)
for base in variant.alternate_bases:
ann.transcript_effects.add().CopyFrom(
self.generateTranscriptEffect(
variant, ann, base, randomNumberGenerator))
ann.id = self.getVariantAnnotationId(variant, ann)
return ann |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def populateFromRow(self, annotationSetRecord):
""" Populates this VariantAnnotationSet from the specified DB row. """ |
self._annotationType = annotationSetRecord.annotationtype
self._analysis = protocol.fromJson(
annotationSetRecord.analysis, protocol.Analysis)
self._creationTime = annotationSetRecord.created
self._updatedTime = annotationSetRecord.updated
self.setAttributesJson(annotationSetRecord.attributes) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _getAnnotationAnalysis(self, varFile):
""" Assembles metadata within the VCF header into a GA4GH Analysis object. :return: protocol.Analysis """ |
header = varFile.header
analysis = protocol.Analysis()
formats = header.formats.items()
infos = header.info.items()
filters = header.filters.items()
for prefix, content in [("FORMAT", formats), ("INFO", infos),
("FILTER", filters)]:
for contentKey, value in content:
key = "{0}.{1}".format(prefix, value.name)
if key not in analysis.attributes.attr:
analysis.attributes.attr[key].Clear()
if value.description is not None:
analysis.attributes.attr[
key].values.add().string_value = value.description
analysis.created = self._creationTime
analysis.updated = self._updatedTime
for r in header.records:
# Don't add a key to info if there's nothing in the value
if r.value is not None:
if r.key not in analysis.attributes.attr:
analysis.attributes.attr[r.key].Clear()
analysis.attributes.attr[r.key] \
.values.add().string_value = str(r.value)
if r.key == "created" or r.key == "fileDate":
# TODO handle more date formats
try:
if '-' in r.value:
fmtStr = "%Y-%m-%d"
else:
fmtStr = "%Y%m%d"
analysis.created = datetime.datetime.strptime(
r.value, fmtStr).isoformat() + "Z"
except ValueError:
# is there a logger we should tell?
# print("INFO: Could not parse variant annotation time")
pass # analysis.create_date_time remains datetime.now()
if r.key == "software":
analysis.software.append(r.value)
if r.key == "name":
analysis.name = r.value
if r.key == "description":
analysis.description = r.value
analysis.id = str(datamodel.VariantAnnotationSetAnalysisCompoundId(
self._compoundId, "analysis"))
return analysis |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def convertVariantAnnotation(self, record):
""" Converts the specfied pysam variant record into a GA4GH variant annotation object using the specified function to convert the transcripts. """ |
variant = self._variantSet.convertVariant(record, [])
annotation = self._createGaVariantAnnotation()
annotation.variant_id = variant.id
gDots = record.info.get(b'HGVS.g')
# Convert annotations from INFO field into TranscriptEffect
transcriptEffects = []
annotations = record.info.get(b'ANN') or record.info.get(b'CSQ')
for i, ann in enumerate(annotations):
hgvsG = gDots[i % len(variant.alternate_bases)] if gDots else None
transcriptEffects.append(self.convertTranscriptEffect(ann, hgvsG))
annotation.transcript_effects.extend(transcriptEffects)
annotation.id = self.getVariantAnnotationId(variant, annotation)
return variant, annotation |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _attributeStr(self, name):
""" Return name=value for a single attribute """ |
return "{}={}".format(
_encodeAttr(name),
",".join([_encodeAttr(v) for v in self.attributes[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 _attributeStrs(self):
""" Return name=value, semi-colon-separated string for attributes, including url-style quoting """ |
return ";".join([self._attributeStr(name)
for name in self.attributes.iterkeys()]) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.