_id stringlengths 2 7 | title stringlengths 1 88 | partition stringclasses 3
values | text stringlengths 75 19.8k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q233400 | get_result_xml | train | def get_result_xml(result):
""" Formats a scan result to XML format.
Arguments:
result (dict): Dictionary with a scan result.
Return:
Result as xml element object.
"""
result_xml = Element('result')
for name, value in [('name', result['name']),
('type', ... | python | {
"resource": ""
} |
q233401 | simple_response_str | train | def simple_response_str(command, status, status_text, content=""):
""" Creates an OSP response XML string.
Arguments:
command (str): OSP Command to respond to.
status (int): Status of the response.
status_text (str): Status text of the response.
content (str): Text part of the r... | python | {
"resource": ""
} |
q233402 | close_client_stream | train | def close_client_stream(client_stream, unix_path):
""" Closes provided client stream """
try:
client_stream.shutdown(socket.SHUT_RDWR)
if unix_path:
logger.debug('%s: Connection closed', unix_path)
else:
peer = client_stream.getpeername()
logger.debug(... | python | {
"resource": ""
} |
q233403 | OSPDaemon.set_command_attributes | train | def set_command_attributes(self, name, attributes):
""" Sets the xml attributes of a specified command. """
if self.command_exists(name):
command = self.commands.get(name)
command['attributes'] = attributes | python | {
"resource": ""
} |
q233404 | OSPDaemon.add_scanner_param | train | def add_scanner_param(self, name, scanner_param):
""" Add a scanner parameter. """
assert name
assert scanner_param
self.scanner_params[name] = scanner_param
command = self.commands.get('start_scan')
command['elements'] = {
'scanner_params':
{... | python | {
"resource": ""
} |
q233405 | OSPDaemon.add_vt | train | def add_vt(self, vt_id, name=None, vt_params=None, vt_refs=None,
custom=None, vt_creation_time=None, vt_modification_time=None,
vt_dependencies=None, summary=None, impact=None, affected=None,
insight=None, solution=None, solution_t=None, detection=None,
qod_t=... | python | {
"resource": ""
} |
q233406 | OSPDaemon._preprocess_scan_params | train | def _preprocess_scan_params(self, xml_params):
""" Processes the scan parameters. """
params = {}
for param in xml_params:
params[param.tag] = param.text or ''
# Set default values.
for key in self.scanner_params:
if key not in params:
para... | python | {
"resource": ""
} |
q233407 | OSPDaemon.process_vts_params | train | def process_vts_params(self, scanner_vts):
""" Receive an XML object with the Vulnerability Tests an their
parameters to be use in a scan and return a dictionary.
@param: XML element with vt subelements. Each vt has an
id attribute. Optional parameters can be included
... | python | {
"resource": ""
} |
q233408 | OSPDaemon.process_credentials_elements | train | def process_credentials_elements(cred_tree):
""" Receive an XML object with the credentials to run
a scan against a given target.
@param:
<credentials>
<credential type="up" service="ssh" port="22">
<username>scanuser</username>
<password>mypass</passwo... | python | {
"resource": ""
} |
q233409 | OSPDaemon.process_targets_element | train | def process_targets_element(cls, scanner_target):
""" Receive an XML object with the target, ports and credentials to run
a scan against.
@param: XML element with target subelements. Each target has <hosts>
and <ports> subelements. Hosts can be a single host, a host range,
a com... | python | {
"resource": ""
} |
q233410 | OSPDaemon.finish_scan | train | def finish_scan(self, scan_id):
""" Sets a scan as finished. """
self.set_scan_progress(scan_id, 100)
self.set_scan_status(scan_id, ScanStatus.FINISHED)
logger.info("%s: Scan finished.", scan_id) | python | {
"resource": ""
} |
q233411 | OSPDaemon.get_scanner_param_type | train | def get_scanner_param_type(self, param):
""" Returns type of a scanner parameter. """
assert isinstance(param, str)
entry = self.scanner_params.get(param)
if not entry:
return None
return entry.get('type') | python | {
"resource": ""
} |
q233412 | OSPDaemon.get_scanner_param_mandatory | train | def get_scanner_param_mandatory(self, param):
""" Returns if a scanner parameter is mandatory. """
assert isinstance(param, str)
entry = self.scanner_params.get(param)
if not entry:
return False
return entry.get('mandatory') | python | {
"resource": ""
} |
q233413 | OSPDaemon.get_scanner_param_default | train | def get_scanner_param_default(self, param):
""" Returns default value of a scanner parameter. """
assert isinstance(param, str)
entry = self.scanner_params.get(param)
if not entry:
return None
return entry.get('default') | python | {
"resource": ""
} |
q233414 | OSPDaemon.get_scanner_params_xml | train | def get_scanner_params_xml(self):
""" Returns the OSP Daemon's scanner params in xml format. """
scanner_params = Element('scanner_params')
for param_id, param in self.scanner_params.items():
param_xml = SubElement(scanner_params, 'scanner_param')
for name, value in [('id... | python | {
"resource": ""
} |
q233415 | OSPDaemon.new_client_stream | train | def new_client_stream(self, sock):
""" Returns a new ssl client stream from bind_socket. """
assert sock
newsocket, fromaddr = sock.accept()
logger.debug("New connection from"
" %s:%s", fromaddr[0], fromaddr[1])
# NB: Despite the name, ssl.PROTOCOL_SSLv23 se... | python | {
"resource": ""
} |
q233416 | OSPDaemon.write_to_stream | train | def write_to_stream(stream, response, block_len=1024):
"""
Send the response in blocks of the given len using the
passed method dependending on the socket type.
"""
try:
i_start = 0
i_end = block_len
while True:
if i_end > len(r... | python | {
"resource": ""
} |
q233417 | OSPDaemon.handle_client_stream | train | def handle_client_stream(self, stream, is_unix=False):
""" Handles stream of data received from client. """
assert stream
data = []
stream.settimeout(2)
while True:
try:
if is_unix:
buf = stream.recv(1024)
else:
... | python | {
"resource": ""
} |
q233418 | OSPDaemon.parallel_scan | train | def parallel_scan(self, scan_id, target):
""" Starts the scan with scan_id. """
try:
ret = self.exec_scan(scan_id, target)
if ret == 0:
self.add_scan_host_detail(scan_id, name='host_status',
host=target, value='0')
... | python | {
"resource": ""
} |
q233419 | OSPDaemon.calculate_progress | train | def calculate_progress(self, scan_id):
""" Calculate the total scan progress from the
partial target progress. """
t_prog = dict()
for target in self.get_scan_target(scan_id):
t_prog[target] = self.get_scan_target_progress(scan_id, target)
return sum(t_prog.values())... | python | {
"resource": ""
} |
q233420 | OSPDaemon.start_scan | train | def start_scan(self, scan_id, targets, parallel=1):
""" Handle N parallel scans if 'parallel' is greater than 1. """
os.setsid()
multiscan_proc = []
logger.info("%s: Scan started.", scan_id)
target_list = targets
if target_list is None or not target_list:
rai... | python | {
"resource": ""
} |
q233421 | OSPDaemon.dry_run_scan | train | def dry_run_scan(self, scan_id, targets):
""" Dry runs a scan. """
os.setsid()
for _, target in enumerate(targets):
host = resolve_hostname(target[0])
if host is None:
logger.info("Couldn't resolve %s.", target[0])
continue
por... | python | {
"resource": ""
} |
q233422 | OSPDaemon.handle_timeout | train | def handle_timeout(self, scan_id, host):
""" Handles scanner reaching timeout error. """
self.add_scan_error(scan_id, host=host, name="Timeout",
value="{0} exec timeout."
.format(self.get_scanner_name())) | python | {
"resource": ""
} |
q233423 | OSPDaemon.set_scan_target_progress | train | def set_scan_target_progress(
self, scan_id, target, host, progress):
""" Sets host's progress which is part of target. """
self.scan_collection.set_target_progress(
scan_id, target, host, progress) | python | {
"resource": ""
} |
q233424 | OSPDaemon.get_help_text | train | def get_help_text(self):
""" Returns the help output in plain text format."""
txt = str('\n')
for name, info in self.commands.items():
command_txt = "\t{0: <22} {1}\n".format(name, info['description'])
if info['attributes']:
command_txt = ''.join([command... | python | {
"resource": ""
} |
q233425 | OSPDaemon.elements_as_text | train | def elements_as_text(self, elems, indent=2):
""" Returns the elems dictionary as formatted plain text. """
assert elems
text = ""
for elename, eledesc in elems.items():
if isinstance(eledesc, dict):
desc_txt = self.elements_as_text(eledesc, indent + 2)
... | python | {
"resource": ""
} |
q233426 | OSPDaemon.delete_scan | train | def delete_scan(self, scan_id):
""" Deletes scan_id scan from collection.
@return: 1 if scan deleted, 0 otherwise.
"""
if self.get_scan_status(scan_id) == ScanStatus.RUNNING:
return 0
try:
del self.scan_processes[scan_id]
except KeyError:
... | python | {
"resource": ""
} |
q233427 | OSPDaemon.get_scan_results_xml | train | def get_scan_results_xml(self, scan_id, pop_res):
""" Gets scan_id scan's results in XML format.
@return: String of scan results in xml.
"""
results = Element('results')
for result in self.scan_collection.results_iterator(scan_id, pop_res):
results.append(get_result_... | python | {
"resource": ""
} |
q233428 | OSPDaemon.get_xml_str | train | def get_xml_str(self, data):
""" Creates a string in XML Format using the provided data structure.
@param: Dictionary of xml tags and their elements.
@return: String of data in xml format.
"""
responses = []
for tag, value in data.items():
elem = Element(ta... | python | {
"resource": ""
} |
q233429 | OSPDaemon.get_scan_xml | train | def get_scan_xml(self, scan_id, detailed=True, pop_res=False):
""" Gets scan in XML format.
@return: String of scan in XML format.
"""
if not scan_id:
return Element('scan')
target = ','.join(self.get_scan_target(scan_id))
progress = self.get_scan_progress(s... | python | {
"resource": ""
} |
q233430 | OSPDaemon.get_vts_xml | train | def get_vts_xml(self, vt_id=None, filtered_vts=None):
""" Gets collection of vulnerability test information in XML format.
If vt_id is specified, the collection will contain only this vt, if
found.
If no vt_id is specified, the collection will contain all vts or those
passed in f... | python | {
"resource": ""
} |
q233431 | OSPDaemon.handle_command | train | def handle_command(self, command):
""" Handles an osp command in a string.
@return: OSP Response to command.
"""
try:
tree = secET.fromstring(command)
except secET.ParseError:
logger.debug("Erroneous client input: %s", command)
raise OSPDError... | python | {
"resource": ""
} |
q233432 | OSPDaemon.run | train | def run(self, address, port, unix_path):
""" Starts the Daemon, handling commands until interrupted.
@return False if error. Runs indefinitely otherwise.
"""
assert address or unix_path
if unix_path:
sock = bind_unix_socket(unix_path)
else:
sock =... | python | {
"resource": ""
} |
q233433 | OSPDaemon.create_scan | train | def create_scan(self, scan_id, targets, options, vts):
""" Creates a new scan.
@target: Target to scan.
@options: Miscellaneous scan options.
@return: New scan's ID.
"""
if self.scan_exists(scan_id):
logger.info("Scan %s exists. Resuming scan.", scan_id)
... | python | {
"resource": ""
} |
q233434 | OSPDaemon.set_scan_option | train | def set_scan_option(self, scan_id, name, value):
""" Sets a scan's option to a provided value. """
return self.scan_collection.set_option(scan_id, name, value) | python | {
"resource": ""
} |
q233435 | OSPDaemon.check_scan_process | train | def check_scan_process(self, scan_id):
""" Check the scan's process, and terminate the scan if not alive. """
scan_process = self.scan_processes[scan_id]
progress = self.get_scan_progress(scan_id)
if progress < 100 and not scan_process.is_alive():
self.set_scan_status(scan_id... | python | {
"resource": ""
} |
q233436 | OSPDaemon.add_scan_log | train | def add_scan_log(self, scan_id, host='', name='', value='', port='',
test_id='', qod=''):
""" Adds a log result to scan_id scan. """
self.scan_collection.add_result(scan_id, ResultType.LOG, host, name,
value, port, test_id, 0.0, qod) | python | {
"resource": ""
} |
q233437 | OSPDaemon.add_scan_error | train | def add_scan_error(self, scan_id, host='', name='', value='', port=''):
""" Adds an error result to scan_id scan. """
self.scan_collection.add_result(scan_id, ResultType.ERROR, host, name,
value, port) | python | {
"resource": ""
} |
q233438 | OSPDaemon.add_scan_host_detail | train | def add_scan_host_detail(self, scan_id, host='', name='', value=''):
""" Adds a host detail result to scan_id scan. """
self.scan_collection.add_result(scan_id, ResultType.HOST_DETAIL, host,
name, value) | python | {
"resource": ""
} |
q233439 | OSPDaemon.add_scan_alarm | train | def add_scan_alarm(self, scan_id, host='', name='', value='', port='',
test_id='', severity='', qod=''):
""" Adds an alarm result to scan_id scan. """
self.scan_collection.add_result(scan_id, ResultType.ALARM, host, name,
value, port, test_i... | python | {
"resource": ""
} |
q233440 | VtsFilter.parse_filters | train | def parse_filters(self, vt_filter):
""" Parse a string containing one or more filters
and return a list of filters
Arguments:
vt_filter (string): String containing filters separated with
semicolon.
Return:
List with filters. Each filters is a list... | python | {
"resource": ""
} |
q233441 | VtsFilter.format_filter_value | train | def format_filter_value(self, element, value):
""" Calls the specific function to format value,
depending on the given element.
Arguments:
element (string): The element of the VT to be formatted.
value (dictionary): The element value.
Returns:
Return... | python | {
"resource": ""
} |
q233442 | VtsFilter.get_filtered_vts_list | train | def get_filtered_vts_list(self, vts, vt_filter):
""" Gets a collection of vulnerability test from the vts dictionary,
which match the filter.
Arguments:
vt_filter (string): Filter to apply to the vts collection.
vts (dictionary): The complete vts collection.
Ret... | python | {
"resource": ""
} |
q233443 | inet_pton | train | def inet_pton(address_family, ip_string):
""" A platform independent version of inet_pton """
global __inet_pton
if __inet_pton is None:
if hasattr(socket, 'inet_pton'):
__inet_pton = socket.inet_pton
else:
from ospd import win_socket
__inet_pton = win_soc... | python | {
"resource": ""
} |
q233444 | inet_ntop | train | def inet_ntop(address_family, packed_ip):
""" A platform independent version of inet_ntop """
global __inet_ntop
if __inet_ntop is None:
if hasattr(socket, 'inet_ntop'):
__inet_ntop = socket.inet_ntop
else:
from ospd import win_socket
__inet_ntop = win_soc... | python | {
"resource": ""
} |
q233445 | ipv4_range_to_list | train | def ipv4_range_to_list(start_packed, end_packed):
""" Return a list of IPv4 entries from start_packed to end_packed. """
new_list = list()
start = struct.unpack('!L', start_packed)[0]
end = struct.unpack('!L', end_packed)[0]
for value in range(start, end + 1):
new_ip = socket.inet_ntoa(stru... | python | {
"resource": ""
} |
q233446 | target_to_ipv4_short | train | def target_to_ipv4_short(target):
""" Attempt to return a IPv4 short range list from a target string. """
splitted = target.split('-')
if len(splitted) != 2:
return None
try:
start_packed = inet_pton(socket.AF_INET, splitted[0])
end_value = int(splitted[1])
except (socket.er... | python | {
"resource": ""
} |
q233447 | target_to_ipv4_cidr | train | def target_to_ipv4_cidr(target):
""" Attempt to return a IPv4 CIDR list from a target string. """
splitted = target.split('/')
if len(splitted) != 2:
return None
try:
start_packed = inet_pton(socket.AF_INET, splitted[0])
block = int(splitted[1])
except (socket.error, ValueEr... | python | {
"resource": ""
} |
q233448 | target_to_ipv6_cidr | train | def target_to_ipv6_cidr(target):
""" Attempt to return a IPv6 CIDR list from a target string. """
splitted = target.split('/')
if len(splitted) != 2:
return None
try:
start_packed = inet_pton(socket.AF_INET6, splitted[0])
block = int(splitted[1])
except (socket.error, ValueE... | python | {
"resource": ""
} |
q233449 | target_to_ipv4_long | train | def target_to_ipv4_long(target):
""" Attempt to return a IPv4 long-range list from a target string. """
splitted = target.split('-')
if len(splitted) != 2:
return None
try:
start_packed = inet_pton(socket.AF_INET, splitted[0])
end_packed = inet_pton(socket.AF_INET, splitted[1])
... | python | {
"resource": ""
} |
q233450 | ipv6_range_to_list | train | def ipv6_range_to_list(start_packed, end_packed):
""" Return a list of IPv6 entries from start_packed to end_packed. """
new_list = list()
start = int(binascii.hexlify(start_packed), 16)
end = int(binascii.hexlify(end_packed), 16)
for value in range(start, end + 1):
high = value >> 64
... | python | {
"resource": ""
} |
q233451 | target_to_ipv6_short | train | def target_to_ipv6_short(target):
""" Attempt to return a IPv6 short-range list from a target string. """
splitted = target.split('-')
if len(splitted) != 2:
return None
try:
start_packed = inet_pton(socket.AF_INET6, splitted[0])
end_value = int(splitted[1], 16)
except (sock... | python | {
"resource": ""
} |
q233452 | target_to_ipv6_long | train | def target_to_ipv6_long(target):
""" Attempt to return a IPv6 long-range list from a target string. """
splitted = target.split('-')
if len(splitted) != 2:
return None
try:
start_packed = inet_pton(socket.AF_INET6, splitted[0])
end_packed = inet_pton(socket.AF_INET6, splitted[1]... | python | {
"resource": ""
} |
q233453 | target_to_hostname | train | def target_to_hostname(target):
""" Attempt to return a single hostname list from a target string. """
if len(target) == 0 or len(target) > 255:
return None
if not re.match(r'^[\w.-]+$', target):
return None
return [target] | python | {
"resource": ""
} |
q233454 | target_to_list | train | def target_to_list(target):
""" Attempt to return a list of single hosts from a target string. """
# Is it an IPv4 address ?
new_list = target_to_ipv4(target)
# Is it an IPv6 address ?
if not new_list:
new_list = target_to_ipv6(target)
# Is it an IPv4 CIDR ?
if not new_list:
... | python | {
"resource": ""
} |
q233455 | target_str_to_list | train | def target_str_to_list(target_str):
""" Parses a targets string into a list of individual targets. """
new_list = list()
for target in target_str.split(','):
target = target.strip()
target_list = target_to_list(target)
if target_list:
new_list.extend(target_list)
... | python | {
"resource": ""
} |
q233456 | port_range_expand | train | def port_range_expand(portrange):
"""
Receive a port range and expands it in individual ports.
@input Port range.
e.g. "4-8"
@return List of integers.
e.g. [4, 5, 6, 7, 8]
"""
if not portrange or '-' not in portrange:
LOGGER.info("Invalid port range format")
return None... | python | {
"resource": ""
} |
q233457 | ports_str_check_failed | train | def ports_str_check_failed(port_str):
"""
Check if the port string is well formed.
Return True if fail, False other case.
"""
pattern = r'[^TU:0-9, \-]'
if (
re.search(pattern, port_str)
or port_str.count('T') > 1
or port_str.count('U') > 1
or port_str.count(':')... | python | {
"resource": ""
} |
q233458 | ports_as_list | train | def ports_as_list(port_str):
"""
Parses a ports string into two list of individual tcp and udp ports.
@input string containing a port list
e.g. T:1,2,3,5-8 U:22,80,600-1024
@return two list of sorted integers, for tcp and udp ports respectively.
"""
if not port_str:
LOGGER.info("In... | python | {
"resource": ""
} |
q233459 | port_list_compress | train | def port_list_compress(port_list):
""" Compress a port list and return a string. """
if not port_list or len(port_list) == 0:
LOGGER.info("Invalid or empty port list.")
return ''
port_list = sorted(set(port_list))
compressed_list = []
for key, group in itertools.groupby(enumerate(p... | python | {
"resource": ""
} |
q233460 | valid_uuid | train | def valid_uuid(value):
""" Check if value is a valid UUID. """
try:
uuid.UUID(value, version=4)
return True
except (TypeError, ValueError, AttributeError):
return False | python | {
"resource": ""
} |
q233461 | create_args_parser | train | def create_args_parser(description):
""" Create a command-line arguments parser for OSPD. """
parser = argparse.ArgumentParser(description=description)
def network_port(string):
""" Check if provided string is a valid network port. """
value = int(string)
if not 0 < value <= 65535... | python | {
"resource": ""
} |
q233462 | go_to_background | train | def go_to_background():
""" Daemonize the running process. """
try:
if os.fork():
sys.exit()
except OSError as errmsg:
LOGGER.error('Fork failed: {0}'.format(errmsg))
sys.exit('Fork failed') | python | {
"resource": ""
} |
q233463 | get_common_args | train | def get_common_args(parser, args=None):
""" Return list of OSPD common command-line arguments from parser, after
validating provided values or setting default ones.
"""
options = parser.parse_args(args)
# TCP Port to listen on.
port = options.port
# Network address to bind listener to
... | python | {
"resource": ""
} |
q233464 | print_version | train | def print_version(wrapper):
""" Prints the server version and license information."""
scanner_name = wrapper.get_scanner_name()
server_version = wrapper.get_server_version()
print("OSP Server for {0} version {1}".format(scanner_name, server_version))
protocol_version = wrapper.get_protocol_version(... | python | {
"resource": ""
} |
q233465 | main | train | def main(name, klass):
""" OSPD Main function. """
# Common args parser.
parser = create_args_parser(name)
# Common args
cargs = get_common_args(parser)
logging.getLogger().setLevel(cargs['log_level'])
wrapper = klass(certfile=cargs['certfile'], keyfile=cargs['keyfile'],
... | python | {
"resource": ""
} |
q233466 | ScanCollection.add_result | train | def add_result(self, scan_id, result_type, host='', name='', value='',
port='', test_id='', severity='', qod=''):
""" Add a result to a scan in the table. """
assert scan_id
assert len(name) or len(value)
result = dict()
result['type'] = result_type
re... | python | {
"resource": ""
} |
q233467 | ScanCollection.get_hosts_unfinished | train | def get_hosts_unfinished(self, scan_id):
""" Get a list of finished hosts."""
unfinished_hosts = list()
for target in self.scans_table[scan_id]['finished_hosts']:
unfinished_hosts.extend(target_str_to_list(target))
for target in self.scans_table[scan_id]['finished_hosts']:
... | python | {
"resource": ""
} |
q233468 | ScanCollection.results_iterator | train | def results_iterator(self, scan_id, pop_res):
""" Returns an iterator over scan_id scan's results. If pop_res is True,
it removed the fetched results from the list.
"""
if pop_res:
result_aux = self.scans_table[scan_id]['results']
self.scans_table[scan_id]['result... | python | {
"resource": ""
} |
q233469 | ScanCollection.del_results_for_stopped_hosts | train | def del_results_for_stopped_hosts(self, scan_id):
""" Remove results from the result table for those host
"""
unfinished_hosts = self.get_hosts_unfinished(scan_id)
for result in self.results_iterator(scan_id, False):
if result['host'] in unfinished_hosts:
self... | python | {
"resource": ""
} |
q233470 | ScanCollection.create_scan | train | def create_scan(self, scan_id='', targets='', options=None, vts=''):
""" Creates a new scan with provided scan information. """
if self.data_manager is None:
self.data_manager = multiprocessing.Manager()
# Check if it is possible to resume task. To avoid to resume, the
# sc... | python | {
"resource": ""
} |
q233471 | ScanCollection.set_option | train | def set_option(self, scan_id, name, value):
""" Set a scan_id scan's name option to value. """
self.scans_table[scan_id]['options'][name] = value | python | {
"resource": ""
} |
q233472 | ScanCollection.get_target_progress | train | def get_target_progress(self, scan_id, target):
""" Get a target's current progress value.
The value is calculated with the progress of each single host
in the target."""
total_hosts = len(target_str_to_list(target))
host_progresses = self.scans_table[scan_id]['target_progress']... | python | {
"resource": ""
} |
q233473 | ScanCollection.get_target_list | train | def get_target_list(self, scan_id):
""" Get a scan's target list. """
target_list = []
for target, _, _ in self.scans_table[scan_id]['targets']:
target_list.append(target)
return target_list | python | {
"resource": ""
} |
q233474 | ScanCollection.get_ports | train | def get_ports(self, scan_id, target):
""" Get a scan's ports list. If a target is specified
it will return the corresponding port for it. If not,
it returns the port item of the first nested list in
the target's list.
"""
if target:
for item in self.scans_tabl... | python | {
"resource": ""
} |
q233475 | ScanCollection.get_credentials | train | def get_credentials(self, scan_id, target):
""" Get a scan's credential list. It return dictionary with
the corresponding credential for a given target.
"""
if target:
for item in self.scans_table[scan_id]['targets']:
if target == item[0]:
... | python | {
"resource": ""
} |
q233476 | ScanCollection.delete_scan | train | def delete_scan(self, scan_id):
""" Delete a scan if fully finished. """
if self.get_status(scan_id) == ScanStatus.RUNNING:
return False
self.scans_table.pop(scan_id)
if len(self.scans_table) == 0:
del self.data_manager
self.data_manager = None
... | python | {
"resource": ""
} |
q233477 | is_timestamp | train | def is_timestamp(obj):
"""
Yaml either have automatically converted it to a datetime object
or it is a string that will be validated later.
"""
return isinstance(obj, datetime.datetime) or is_string(obj) or is_int(obj) or is_float(obj) | python | {
"resource": ""
} |
q233478 | init_logging | train | def init_logging(log_level):
"""
Init logging settings with default set to INFO
"""
log_level = log_level_to_string_map[min(log_level, 5)]
msg = "%(levelname)s - %(name)s:%(lineno)s - %(message)s" if log_level in os.environ else "%(levelname)s - %(message)s"
logging_conf = {
"version":... | python | {
"resource": ""
} |
q233479 | Rule.keywords | train | def keywords(self):
"""
Returns a list of all keywords that this rule object has defined.
A keyword is considered defined if the value it returns != None.
"""
defined_keywords = [
('allowempty_map', 'allowempty_map'),
('assertion', 'assertion'),
... | python | {
"resource": ""
} |
q233480 | Core._load_extensions | train | def _load_extensions(self):
"""
Load all extension files into the namespace pykwalify.ext
"""
log.debug(u"loading all extensions : %s", self.extensions)
self.loaded_extensions = []
for f in self.extensions:
if not os.path.isabs(f):
f = os.pat... | python | {
"resource": ""
} |
q233481 | Core._handle_func | train | def _handle_func(self, value, rule, path, done=None):
"""
Helper function that should check if func is specified for this rule and
then handle it for all cases in a generic way.
"""
func = rule.func
# func keyword is not defined so nothing to do
if not func:
... | python | {
"resource": ""
} |
q233482 | Core._validate_range | train | def _validate_range(self, max_, min_, max_ex, min_ex, value, path, prefix):
"""
Validate that value is within range values.
"""
if not isinstance(value, int) and not isinstance(value, float):
raise CoreError("Value must be a integer type")
log.debug(
u"Va... | python | {
"resource": ""
} |
q233483 | run | train | def run(cli_args):
"""
Split the functionality into 2 methods.
One for parsing the cli and one that runs the application.
"""
from .core import Core
c = Core(
source_file=cli_args["--data-file"],
schema_files=cli_args["--schema-file"],
extensions=cli_args['--extension']... | python | {
"resource": ""
} |
q233484 | to_bedtool | train | def to_bedtool(iterator):
"""
Convert any iterator into a pybedtools.BedTool object.
Note that the supplied iterator is not consumed by this function. To save
to a temp file or to a known location, use the `.saveas()` method of the
returned BedTool object.
"""
def gen():
for i in it... | python | {
"resource": ""
} |
q233485 | tsses | train | def tsses(db, merge_overlapping=False, attrs=None, attrs_sep=":",
merge_kwargs=None, as_bed6=False, bedtools_227_or_later=True):
"""
Create 1-bp transcription start sites for all transcripts in the database
and return as a sorted pybedtools.BedTool object pointing to a temporary
file.
To ... | python | {
"resource": ""
} |
q233486 | GFFWriter.close | train | def close(self):
"""
Close the stream. Assumes stream has 'close' method.
"""
self.out_stream.close()
# If we're asked to write in place, substitute the named
# temporary file for the current file
if self.in_place:
shutil.move(self.temp_file.name, self... | python | {
"resource": ""
} |
q233487 | to_seqfeature | train | def to_seqfeature(feature):
"""
Converts a gffutils.Feature object to a Bio.SeqFeature object.
The GFF fields `source`, `score`, `seqid`, and `frame` are stored as
qualifiers. GFF `attributes` are also stored as qualifiers.
Parameters
----------
feature : Feature object, or string
... | python | {
"resource": ""
} |
q233488 | from_seqfeature | train | def from_seqfeature(s, **kwargs):
"""
Converts a Bio.SeqFeature object to a gffutils.Feature object.
The GFF fields `source`, `score`, `seqid`, and `frame` are assumed to be
stored as qualifiers. Any other qualifiers will be assumed to be GFF
attributes.
"""
source = s.qualifiers.get('sour... | python | {
"resource": ""
} |
q233489 | FeatureDB.set_pragmas | train | def set_pragmas(self, pragmas):
"""
Set pragmas for the current database connection.
Parameters
----------
pragmas : dict
Dictionary of pragmas; see constants.default_pragmas for a template
and http://www.sqlite.org/pragma.html for a full list.
""... | python | {
"resource": ""
} |
q233490 | FeatureDB._feature_returner | train | def _feature_returner(self, **kwargs):
"""
Returns a feature, adding additional database-specific defaults
"""
kwargs.setdefault('dialect', self.dialect)
kwargs.setdefault('keep_order', self.keep_order)
kwargs.setdefault('sort_attribute_values', self.sort_attribute_values... | python | {
"resource": ""
} |
q233491 | FeatureDB.schema | train | def schema(self):
"""
Returns the database schema as a string.
"""
c = self.conn.cursor()
c.execute(
'''
SELECT sql FROM sqlite_master
''')
results = []
for i, in c:
if i is not None:
results.append(i... | python | {
"resource": ""
} |
q233492 | FeatureDB.featuretypes | train | def featuretypes(self):
"""
Iterate over feature types found in the database.
Returns
-------
A generator object that yields featuretypes (as strings)
"""
c = self.conn.cursor()
c.execute(
'''
SELECT DISTINCT featuretype from featu... | python | {
"resource": ""
} |
q233493 | FeatureDB.execute | train | def execute(self, query):
"""
Execute arbitrary queries on the db.
.. seealso::
:class:`FeatureDB.schema` may be helpful when writing your own
queries.
Parameters
----------
query : str
Query to execute -- trailing ";" opti... | python | {
"resource": ""
} |
q233494 | FeatureDB.interfeatures | train | def interfeatures(self, features, new_featuretype=None,
merge_attributes=True, dialect=None,
attribute_func=None, update_attributes=None):
"""
Construct new features representing the space between features.
For example, if `features` is a list of exon... | python | {
"resource": ""
} |
q233495 | FeatureDB.update | train | def update(self, data, make_backup=True, **kwargs):
"""
Update database with features in `data`.
data : str, iterable, FeatureDB instance
If FeatureDB, all data will be used. If string, assume it's
a filename of a GFF or GTF file. Otherwise, assume it's an
i... | python | {
"resource": ""
} |
q233496 | FeatureDB.create_introns | train | def create_introns(self, exon_featuretype='exon',
grandparent_featuretype='gene', parent_featuretype=None,
new_featuretype='intron', merge_attributes=True):
"""
Create introns from existing annotations.
Parameters
----------
exon_fe... | python | {
"resource": ""
} |
q233497 | FeatureDB.merge | train | def merge(self, features, ignore_strand=False):
"""
Merge overlapping features together.
Parameters
----------
features : iterator of Feature instances
ignore_strand : bool
If True, features on multiple strands will be merged, and the final
stra... | python | {
"resource": ""
} |
q233498 | FeatureDB.children_bp | train | def children_bp(self, feature, child_featuretype='exon', merge=False,
ignore_strand=False):
"""
Total bp of all children of a featuretype.
Useful for getting the exonic bp of an mRNA.
Parameters
----------
feature : str or Feature instance
... | python | {
"resource": ""
} |
q233499 | FeatureDB.bed12 | train | def bed12(self, feature, block_featuretype=['exon'],
thick_featuretype=['CDS'], thin_featuretype=None,
name_field='ID', color=None):
"""
Converts `feature` into a BED12 format.
GFF and GTF files do not necessarily define genes consistently, so this
method pro... | python | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.