repo stringlengths 7 55 | path stringlengths 4 127 | func_name stringlengths 1 88 | original_string stringlengths 75 19.8k | language stringclasses 1
value | code stringlengths 75 19.8k | code_tokens listlengths 20 707 | docstring stringlengths 3 17.3k | docstring_tokens listlengths 3 222 | sha stringlengths 40 40 | url stringlengths 87 242 | partition stringclasses 1
value | idx int64 0 252k |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
ns1/ns1-python | ns1/ipam.py | Network.new_address | def new_address(self, prefix, type, callback=None, errback=None, **kwargs):
"""
Create a new address space in this Network
:param str prefix: The CIDR prefix of the address to add
:param str type: planned, assignment, host
:return: The newly created Address object
"""
if not self.data:
raise NetworkException('Network not loaded')
return Address(self.config, prefix, type, self).create(**kwargs) | python | def new_address(self, prefix, type, callback=None, errback=None, **kwargs):
"""
Create a new address space in this Network
:param str prefix: The CIDR prefix of the address to add
:param str type: planned, assignment, host
:return: The newly created Address object
"""
if not self.data:
raise NetworkException('Network not loaded')
return Address(self.config, prefix, type, self).create(**kwargs) | [
"def",
"new_address",
"(",
"self",
",",
"prefix",
",",
"type",
",",
"callback",
"=",
"None",
",",
"errback",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"not",
"self",
".",
"data",
":",
"raise",
"NetworkException",
"(",
"'Network not loaded'",
... | Create a new address space in this Network
:param str prefix: The CIDR prefix of the address to add
:param str type: planned, assignment, host
:return: The newly created Address object | [
"Create",
"a",
"new",
"address",
"space",
"in",
"this",
"Network"
] | f3e1d90a3b76a1bd18f855f2c622a8a49d4b585e | https://github.com/ns1/ns1-python/blob/f3e1d90a3b76a1bd18f855f2c622a8a49d4b585e/ns1/ipam.py#L130-L141 | train | 211,000 |
ns1/ns1-python | ns1/ipam.py | Address.load | def load(self, callback=None, errback=None, reload=False):
"""
Load address data from the API.
"""
if not reload and self.data:
raise AddressException('Address already loaded')
def success(result, *args):
self.data = result
self.id = result['id']
self.prefix = result['prefix']
self.type = result['type']
self.network = Network(self.config, id=result['network_id'])
# self.scope_group = Scopegroup(config=self.config, id=result['scope_group_id']) NYI
if self.type != 'host':
self.report = self._rest.report(self.id)
children = self._rest.retrieve_children(self.id)
self.children = [Address(self.config, id=child['id']) for child in
children if len(children) > 0]
try:
parent = self._rest.retrieve_parent(self.id)
self.parent = Address(self.config, id=parent['id'])
except ResourceException:
pass
if callback:
return callback(self)
else:
return self
if self.id is None:
if self.prefix is None or self.type is None or self.network is None:
raise AddressException('Must at least specify an id or prefix, type and network')
else:
network_id = self.network.id
try:
self.id = [address for address in self._rest.list() if address['prefix'] == self.prefix and address[
'type'] == self.type and address['network_id'] == network_id][0]['id']
except IndexError:
raise AddressException("Could not find address by prefix. It may not exist, or is a child address. "
"Use the topmost parent prefix or specify ID")
return self._rest.retrieve(self.id, callback=success,
errback=errback) | python | def load(self, callback=None, errback=None, reload=False):
"""
Load address data from the API.
"""
if not reload and self.data:
raise AddressException('Address already loaded')
def success(result, *args):
self.data = result
self.id = result['id']
self.prefix = result['prefix']
self.type = result['type']
self.network = Network(self.config, id=result['network_id'])
# self.scope_group = Scopegroup(config=self.config, id=result['scope_group_id']) NYI
if self.type != 'host':
self.report = self._rest.report(self.id)
children = self._rest.retrieve_children(self.id)
self.children = [Address(self.config, id=child['id']) for child in
children if len(children) > 0]
try:
parent = self._rest.retrieve_parent(self.id)
self.parent = Address(self.config, id=parent['id'])
except ResourceException:
pass
if callback:
return callback(self)
else:
return self
if self.id is None:
if self.prefix is None or self.type is None or self.network is None:
raise AddressException('Must at least specify an id or prefix, type and network')
else:
network_id = self.network.id
try:
self.id = [address for address in self._rest.list() if address['prefix'] == self.prefix and address[
'type'] == self.type and address['network_id'] == network_id][0]['id']
except IndexError:
raise AddressException("Could not find address by prefix. It may not exist, or is a child address. "
"Use the topmost parent prefix or specify ID")
return self._rest.retrieve(self.id, callback=success,
errback=errback) | [
"def",
"load",
"(",
"self",
",",
"callback",
"=",
"None",
",",
"errback",
"=",
"None",
",",
"reload",
"=",
"False",
")",
":",
"if",
"not",
"reload",
"and",
"self",
".",
"data",
":",
"raise",
"AddressException",
"(",
"'Address already loaded'",
")",
"def"... | Load address data from the API. | [
"Load",
"address",
"data",
"from",
"the",
"API",
"."
] | f3e1d90a3b76a1bd18f855f2c622a8a49d4b585e | https://github.com/ns1/ns1-python/blob/f3e1d90a3b76a1bd18f855f2c622a8a49d4b585e/ns1/ipam.py#L179-L221 | train | 211,001 |
ns1/ns1-python | ns1/ipam.py | Scopegroup.load | def load(self, callback=None, errback=None, reload=False):
"""
Load Scopegroup data from the API.
"""
if not reload and self.data:
raise ScopegroupException('Scope Group already loaded')
def success(result, *args):
self.data = result
self.id = result['id']
self.dhcp4 = result['dhcp4']
self.dhcp6 = result['dhcp6']
self.name = result['name']
self.service_group_id = result['service_group_id']
if callback:
return callback(self)
else:
return self
if self.id is None:
if self.dhcp4 is None or self.dhcp6 is None or self.name is None or self.service_group_id is None:
raise AddressException('Must at least specify an id or name and service_group_id')
else:
try:
self.id = [scope_group for scope_group in self._rest.list() if scope_group['name'] == self.name and
scope_group['service_group_id'] == self.service_group_id][0]['id']
except IndexError:
raise AddressException("Could not find Scope Group by name and service_group_id. It may not exist")
return self._rest.retrieve(self.id, callback=success,
errback=errback) | python | def load(self, callback=None, errback=None, reload=False):
"""
Load Scopegroup data from the API.
"""
if not reload and self.data:
raise ScopegroupException('Scope Group already loaded')
def success(result, *args):
self.data = result
self.id = result['id']
self.dhcp4 = result['dhcp4']
self.dhcp6 = result['dhcp6']
self.name = result['name']
self.service_group_id = result['service_group_id']
if callback:
return callback(self)
else:
return self
if self.id is None:
if self.dhcp4 is None or self.dhcp6 is None or self.name is None or self.service_group_id is None:
raise AddressException('Must at least specify an id or name and service_group_id')
else:
try:
self.id = [scope_group for scope_group in self._rest.list() if scope_group['name'] == self.name and
scope_group['service_group_id'] == self.service_group_id][0]['id']
except IndexError:
raise AddressException("Could not find Scope Group by name and service_group_id. It may not exist")
return self._rest.retrieve(self.id, callback=success,
errback=errback) | [
"def",
"load",
"(",
"self",
",",
"callback",
"=",
"None",
",",
"errback",
"=",
"None",
",",
"reload",
"=",
"False",
")",
":",
"if",
"not",
"reload",
"and",
"self",
".",
"data",
":",
"raise",
"ScopegroupException",
"(",
"'Scope Group already loaded'",
")",
... | Load Scopegroup data from the API. | [
"Load",
"Scopegroup",
"data",
"from",
"the",
"API",
"."
] | f3e1d90a3b76a1bd18f855f2c622a8a49d4b585e | https://github.com/ns1/ns1-python/blob/f3e1d90a3b76a1bd18f855f2c622a8a49d4b585e/ns1/ipam.py#L331-L361 | train | 211,002 |
ns1/ns1-python | ns1/zones.py | Zone.search | def search(self, q=None, has_geo=False, callback=None, errback=None):
"""
Search within a zone for specific metadata. Zone must already be loaded.
"""
if not self.data:
raise ZoneException('zone not loaded')
return self._rest.search(self.zone, q, has_geo, callback, errback) | python | def search(self, q=None, has_geo=False, callback=None, errback=None):
"""
Search within a zone for specific metadata. Zone must already be loaded.
"""
if not self.data:
raise ZoneException('zone not loaded')
return self._rest.search(self.zone, q, has_geo, callback, errback) | [
"def",
"search",
"(",
"self",
",",
"q",
"=",
"None",
",",
"has_geo",
"=",
"False",
",",
"callback",
"=",
"None",
",",
"errback",
"=",
"None",
")",
":",
"if",
"not",
"self",
".",
"data",
":",
"raise",
"ZoneException",
"(",
"'zone not loaded'",
")",
"r... | Search within a zone for specific metadata. Zone must already be loaded. | [
"Search",
"within",
"a",
"zone",
"for",
"specific",
"metadata",
".",
"Zone",
"must",
"already",
"be",
"loaded",
"."
] | f3e1d90a3b76a1bd18f855f2c622a8a49d4b585e | https://github.com/ns1/ns1-python/blob/f3e1d90a3b76a1bd18f855f2c622a8a49d4b585e/ns1/zones.py#L67-L74 | train | 211,003 |
ns1/ns1-python | ns1/zones.py | Zone.delete | def delete(self, callback=None, errback=None):
"""
Delete the zone and ALL records it contains.
"""
return self._rest.delete(self.zone, callback=callback, errback=errback) | python | def delete(self, callback=None, errback=None):
"""
Delete the zone and ALL records it contains.
"""
return self._rest.delete(self.zone, callback=callback, errback=errback) | [
"def",
"delete",
"(",
"self",
",",
"callback",
"=",
"None",
",",
"errback",
"=",
"None",
")",
":",
"return",
"self",
".",
"_rest",
".",
"delete",
"(",
"self",
".",
"zone",
",",
"callback",
"=",
"callback",
",",
"errback",
"=",
"errback",
")"
] | Delete the zone and ALL records it contains. | [
"Delete",
"the",
"zone",
"and",
"ALL",
"records",
"it",
"contains",
"."
] | f3e1d90a3b76a1bd18f855f2c622a8a49d4b585e | https://github.com/ns1/ns1-python/blob/f3e1d90a3b76a1bd18f855f2c622a8a49d4b585e/ns1/zones.py#L76-L80 | train | 211,004 |
ns1/ns1-python | ns1/zones.py | Zone.createLinkToSelf | def createLinkToSelf(self, new_zone, callback=None, errback=None,
**kwargs):
"""
Create a new linked zone, linking to ourselves. All records in this
zone will then be available as "linked records" in the new zone.
:param str new_zone: the new zone name to link to this one
:return: new Zone
"""
zone = Zone(self.config, new_zone)
kwargs['link'] = self.data['zone']
return zone.create(callback=callback, errback=errback, **kwargs) | python | def createLinkToSelf(self, new_zone, callback=None, errback=None,
**kwargs):
"""
Create a new linked zone, linking to ourselves. All records in this
zone will then be available as "linked records" in the new zone.
:param str new_zone: the new zone name to link to this one
:return: new Zone
"""
zone = Zone(self.config, new_zone)
kwargs['link'] = self.data['zone']
return zone.create(callback=callback, errback=errback, **kwargs) | [
"def",
"createLinkToSelf",
"(",
"self",
",",
"new_zone",
",",
"callback",
"=",
"None",
",",
"errback",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"zone",
"=",
"Zone",
"(",
"self",
".",
"config",
",",
"new_zone",
")",
"kwargs",
"[",
"'link'",
"]"... | Create a new linked zone, linking to ourselves. All records in this
zone will then be available as "linked records" in the new zone.
:param str new_zone: the new zone name to link to this one
:return: new Zone | [
"Create",
"a",
"new",
"linked",
"zone",
"linking",
"to",
"ourselves",
".",
"All",
"records",
"in",
"this",
"zone",
"will",
"then",
"be",
"available",
"as",
"linked",
"records",
"in",
"the",
"new",
"zone",
"."
] | f3e1d90a3b76a1bd18f855f2c622a8a49d4b585e | https://github.com/ns1/ns1-python/blob/f3e1d90a3b76a1bd18f855f2c622a8a49d4b585e/ns1/zones.py#L143-L154 | train | 211,005 |
ns1/ns1-python | ns1/zones.py | Zone.cloneRecord | def cloneRecord(self, existing_domain, new_domain, rtype,
zone=None, callback=None, errback=None):
"""
Clone the given record to a new record such that their configs are
identical.
:param str existing_domain: The existing record to clone
:param str new_domain: The name of the new cloned record
:param str rtype: DNS record type
:param str zone: Optional zone name, if the new record should exist in\
a different zone than the original record.
:rtype: ns1.records.Record
:return: new Record
"""
if zone is None:
zone = self.zone
if not new_domain.endswith(zone):
new_domain = new_domain + '.' + zone
def onSaveNewRecord(new_data):
if zone != self.zone:
pZone = Zone(self.config, zone)
else:
pZone = self
new_rec = Record(pZone, new_domain, rtype)
new_rec._parseModel(new_data)
if callback:
return callback(new_rec)
else:
return new_rec
def onLoadRecord(old_rec):
data = old_rec.data
data['zone'] = zone
data['domain'] = new_domain
restapi = Records(self.config)
return restapi.create_raw(zone, new_domain, rtype, data,
callback=onSaveNewRecord,
errback=errback)
return self.loadRecord(existing_domain, rtype,
callback=onLoadRecord,
errback=errback) | python | def cloneRecord(self, existing_domain, new_domain, rtype,
zone=None, callback=None, errback=None):
"""
Clone the given record to a new record such that their configs are
identical.
:param str existing_domain: The existing record to clone
:param str new_domain: The name of the new cloned record
:param str rtype: DNS record type
:param str zone: Optional zone name, if the new record should exist in\
a different zone than the original record.
:rtype: ns1.records.Record
:return: new Record
"""
if zone is None:
zone = self.zone
if not new_domain.endswith(zone):
new_domain = new_domain + '.' + zone
def onSaveNewRecord(new_data):
if zone != self.zone:
pZone = Zone(self.config, zone)
else:
pZone = self
new_rec = Record(pZone, new_domain, rtype)
new_rec._parseModel(new_data)
if callback:
return callback(new_rec)
else:
return new_rec
def onLoadRecord(old_rec):
data = old_rec.data
data['zone'] = zone
data['domain'] = new_domain
restapi = Records(self.config)
return restapi.create_raw(zone, new_domain, rtype, data,
callback=onSaveNewRecord,
errback=errback)
return self.loadRecord(existing_domain, rtype,
callback=onLoadRecord,
errback=errback) | [
"def",
"cloneRecord",
"(",
"self",
",",
"existing_domain",
",",
"new_domain",
",",
"rtype",
",",
"zone",
"=",
"None",
",",
"callback",
"=",
"None",
",",
"errback",
"=",
"None",
")",
":",
"if",
"zone",
"is",
"None",
":",
"zone",
"=",
"self",
".",
"zon... | Clone the given record to a new record such that their configs are
identical.
:param str existing_domain: The existing record to clone
:param str new_domain: The name of the new cloned record
:param str rtype: DNS record type
:param str zone: Optional zone name, if the new record should exist in\
a different zone than the original record.
:rtype: ns1.records.Record
:return: new Record | [
"Clone",
"the",
"given",
"record",
"to",
"a",
"new",
"record",
"such",
"that",
"their",
"configs",
"are",
"identical",
"."
] | f3e1d90a3b76a1bd18f855f2c622a8a49d4b585e | https://github.com/ns1/ns1-python/blob/f3e1d90a3b76a1bd18f855f2c622a8a49d4b585e/ns1/zones.py#L183-L226 | train | 211,006 |
ns1/ns1-python | ns1/zones.py | Zone.loadRecord | def loadRecord(self, domain, rtype, callback=None, errback=None):
"""
Load a high level Record object from a domain within this Zone.
:param str domain: The name of the record to load
:param str rtype: The DNS record type
:rtype: ns1.records.Record
:return: new Record
"""
rec = Record(self, domain, rtype)
return rec.load(callback=callback, errback=errback) | python | def loadRecord(self, domain, rtype, callback=None, errback=None):
"""
Load a high level Record object from a domain within this Zone.
:param str domain: The name of the record to load
:param str rtype: The DNS record type
:rtype: ns1.records.Record
:return: new Record
"""
rec = Record(self, domain, rtype)
return rec.load(callback=callback, errback=errback) | [
"def",
"loadRecord",
"(",
"self",
",",
"domain",
",",
"rtype",
",",
"callback",
"=",
"None",
",",
"errback",
"=",
"None",
")",
":",
"rec",
"=",
"Record",
"(",
"self",
",",
"domain",
",",
"rtype",
")",
"return",
"rec",
".",
"load",
"(",
"callback",
... | Load a high level Record object from a domain within this Zone.
:param str domain: The name of the record to load
:param str rtype: The DNS record type
:rtype: ns1.records.Record
:return: new Record | [
"Load",
"a",
"high",
"level",
"Record",
"object",
"from",
"a",
"domain",
"within",
"this",
"Zone",
"."
] | f3e1d90a3b76a1bd18f855f2c622a8a49d4b585e | https://github.com/ns1/ns1-python/blob/f3e1d90a3b76a1bd18f855f2c622a8a49d4b585e/ns1/zones.py#L228-L238 | train | 211,007 |
ns1/ns1-python | ns1/zones.py | Zone.qps | def qps(self, callback=None, errback=None):
"""
Return the current QPS for this zone
:rtype: dict
:return: QPS information
"""
stats = Stats(self.config)
return stats.qps(zone=self.zone, callback=callback, errback=errback) | python | def qps(self, callback=None, errback=None):
"""
Return the current QPS for this zone
:rtype: dict
:return: QPS information
"""
stats = Stats(self.config)
return stats.qps(zone=self.zone, callback=callback, errback=errback) | [
"def",
"qps",
"(",
"self",
",",
"callback",
"=",
"None",
",",
"errback",
"=",
"None",
")",
":",
"stats",
"=",
"Stats",
"(",
"self",
".",
"config",
")",
"return",
"stats",
".",
"qps",
"(",
"zone",
"=",
"self",
".",
"zone",
",",
"callback",
"=",
"c... | Return the current QPS for this zone
:rtype: dict
:return: QPS information | [
"Return",
"the",
"current",
"QPS",
"for",
"this",
"zone"
] | f3e1d90a3b76a1bd18f855f2c622a8a49d4b585e | https://github.com/ns1/ns1-python/blob/f3e1d90a3b76a1bd18f855f2c622a8a49d4b585e/ns1/zones.py#L240-L248 | train | 211,008 |
ns1/ns1-python | ns1/zones.py | Zone.usage | def usage(self, callback=None, errback=None, **kwargs):
"""
Return the current usage information for this zone
:rtype: dict
:return: usage information
"""
stats = Stats(self.config)
return stats.usage(zone=self.zone, callback=callback, errback=errback,
**kwargs) | python | def usage(self, callback=None, errback=None, **kwargs):
"""
Return the current usage information for this zone
:rtype: dict
:return: usage information
"""
stats = Stats(self.config)
return stats.usage(zone=self.zone, callback=callback, errback=errback,
**kwargs) | [
"def",
"usage",
"(",
"self",
",",
"callback",
"=",
"None",
",",
"errback",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"stats",
"=",
"Stats",
"(",
"self",
".",
"config",
")",
"return",
"stats",
".",
"usage",
"(",
"zone",
"=",
"self",
".",
"zo... | Return the current usage information for this zone
:rtype: dict
:return: usage information | [
"Return",
"the",
"current",
"usage",
"information",
"for",
"this",
"zone"
] | f3e1d90a3b76a1bd18f855f2c622a8a49d4b585e | https://github.com/ns1/ns1-python/blob/f3e1d90a3b76a1bd18f855f2c622a8a49d4b585e/ns1/zones.py#L250-L259 | train | 211,009 |
ns1/ns1-python | ns1/monitoring.py | Monitor.load | def load(self, callback=None, errback=None, reload=False):
"""
Load monitor data from the API.
"""
if not reload and self.data:
raise MonitorException('monitor already loaded')
def success(result, *args):
self.data = result
if callback:
return callback(self)
else:
return self
return self._rest.retrieve(self.data['id'], callback=success,
errback=errback) | python | def load(self, callback=None, errback=None, reload=False):
"""
Load monitor data from the API.
"""
if not reload and self.data:
raise MonitorException('monitor already loaded')
def success(result, *args):
self.data = result
if callback:
return callback(self)
else:
return self
return self._rest.retrieve(self.data['id'], callback=success,
errback=errback) | [
"def",
"load",
"(",
"self",
",",
"callback",
"=",
"None",
",",
"errback",
"=",
"None",
",",
"reload",
"=",
"False",
")",
":",
"if",
"not",
"reload",
"and",
"self",
".",
"data",
":",
"raise",
"MonitorException",
"(",
"'monitor already loaded'",
")",
"def"... | Load monitor data from the API. | [
"Load",
"monitor",
"data",
"from",
"the",
"API",
"."
] | f3e1d90a3b76a1bd18f855f2c622a8a49d4b585e | https://github.com/ns1/ns1-python/blob/f3e1d90a3b76a1bd18f855f2c622a8a49d4b585e/ns1/monitoring.py#L45-L60 | train | 211,010 |
ns1/ns1-python | ns1/monitoring.py | Monitor.delete | def delete(self, callback=None, errback=None):
"""
Delete the monitor
"""
return self._rest.delete(self.data['id'], callback=callback, errback=errback) | python | def delete(self, callback=None, errback=None):
"""
Delete the monitor
"""
return self._rest.delete(self.data['id'], callback=callback, errback=errback) | [
"def",
"delete",
"(",
"self",
",",
"callback",
"=",
"None",
",",
"errback",
"=",
"None",
")",
":",
"return",
"self",
".",
"_rest",
".",
"delete",
"(",
"self",
".",
"data",
"[",
"'id'",
"]",
",",
"callback",
"=",
"callback",
",",
"errback",
"=",
"er... | Delete the monitor | [
"Delete",
"the",
"monitor"
] | f3e1d90a3b76a1bd18f855f2c622a8a49d4b585e | https://github.com/ns1/ns1-python/blob/f3e1d90a3b76a1bd18f855f2c622a8a49d4b585e/ns1/monitoring.py#L62-L66 | train | 211,011 |
ns1/ns1-python | ns1/monitoring.py | Monitor.update | def update(self, callback=None, errback=None, **kwargs):
"""
Update monitor configuration. Pass a list of keywords and their values to
update.
"""
if not self.data:
raise MonitorException('monitor not loaded')
def success(result, *args):
self.data = result
if callback:
return callback(self)
else:
return self
return self._rest.update(self.data['id'], {}, callback=success, errback=errback, **kwargs) | python | def update(self, callback=None, errback=None, **kwargs):
"""
Update monitor configuration. Pass a list of keywords and their values to
update.
"""
if not self.data:
raise MonitorException('monitor not loaded')
def success(result, *args):
self.data = result
if callback:
return callback(self)
else:
return self
return self._rest.update(self.data['id'], {}, callback=success, errback=errback, **kwargs) | [
"def",
"update",
"(",
"self",
",",
"callback",
"=",
"None",
",",
"errback",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"not",
"self",
".",
"data",
":",
"raise",
"MonitorException",
"(",
"'monitor not loaded'",
")",
"def",
"success",
"(",
"re... | Update monitor configuration. Pass a list of keywords and their values to
update. | [
"Update",
"monitor",
"configuration",
".",
"Pass",
"a",
"list",
"of",
"keywords",
"and",
"their",
"values",
"to",
"update",
"."
] | f3e1d90a3b76a1bd18f855f2c622a8a49d4b585e | https://github.com/ns1/ns1-python/blob/f3e1d90a3b76a1bd18f855f2c622a8a49d4b585e/ns1/monitoring.py#L68-L83 | train | 211,012 |
ns1/ns1-python | ns1/__init__.py | NS1.zones | def zones(self):
"""
Return a new raw REST interface to zone resources
:rtype: :py:class:`ns1.rest.zones.Zones`
"""
import ns1.rest.zones
return ns1.rest.zones.Zones(self.config) | python | def zones(self):
"""
Return a new raw REST interface to zone resources
:rtype: :py:class:`ns1.rest.zones.Zones`
"""
import ns1.rest.zones
return ns1.rest.zones.Zones(self.config) | [
"def",
"zones",
"(",
"self",
")",
":",
"import",
"ns1",
".",
"rest",
".",
"zones",
"return",
"ns1",
".",
"rest",
".",
"zones",
".",
"Zones",
"(",
"self",
".",
"config",
")"
] | Return a new raw REST interface to zone resources
:rtype: :py:class:`ns1.rest.zones.Zones` | [
"Return",
"a",
"new",
"raw",
"REST",
"interface",
"to",
"zone",
"resources"
] | f3e1d90a3b76a1bd18f855f2c622a8a49d4b585e | https://github.com/ns1/ns1-python/blob/f3e1d90a3b76a1bd18f855f2c622a8a49d4b585e/ns1/__init__.py#L44-L51 | train | 211,013 |
ns1/ns1-python | ns1/__init__.py | NS1.records | def records(self):
"""
Return a new raw REST interface to record resources
:rtype: :py:class:`ns1.rest.records.Records`
"""
import ns1.rest.records
return ns1.rest.records.Records(self.config) | python | def records(self):
"""
Return a new raw REST interface to record resources
:rtype: :py:class:`ns1.rest.records.Records`
"""
import ns1.rest.records
return ns1.rest.records.Records(self.config) | [
"def",
"records",
"(",
"self",
")",
":",
"import",
"ns1",
".",
"rest",
".",
"records",
"return",
"ns1",
".",
"rest",
".",
"records",
".",
"Records",
"(",
"self",
".",
"config",
")"
] | Return a new raw REST interface to record resources
:rtype: :py:class:`ns1.rest.records.Records` | [
"Return",
"a",
"new",
"raw",
"REST",
"interface",
"to",
"record",
"resources"
] | f3e1d90a3b76a1bd18f855f2c622a8a49d4b585e | https://github.com/ns1/ns1-python/blob/f3e1d90a3b76a1bd18f855f2c622a8a49d4b585e/ns1/__init__.py#L53-L60 | train | 211,014 |
ns1/ns1-python | ns1/__init__.py | NS1.addresses | def addresses(self):
"""
Return a new raw REST interface to address resources
:rtype: :py:class:`ns1.rest.ipam.Adresses`
"""
import ns1.rest.ipam
return ns1.rest.ipam.Addresses(self.config) | python | def addresses(self):
"""
Return a new raw REST interface to address resources
:rtype: :py:class:`ns1.rest.ipam.Adresses`
"""
import ns1.rest.ipam
return ns1.rest.ipam.Addresses(self.config) | [
"def",
"addresses",
"(",
"self",
")",
":",
"import",
"ns1",
".",
"rest",
".",
"ipam",
"return",
"ns1",
".",
"rest",
".",
"ipam",
".",
"Addresses",
"(",
"self",
".",
"config",
")"
] | Return a new raw REST interface to address resources
:rtype: :py:class:`ns1.rest.ipam.Adresses` | [
"Return",
"a",
"new",
"raw",
"REST",
"interface",
"to",
"address",
"resources"
] | f3e1d90a3b76a1bd18f855f2c622a8a49d4b585e | https://github.com/ns1/ns1-python/blob/f3e1d90a3b76a1bd18f855f2c622a8a49d4b585e/ns1/__init__.py#L62-L69 | train | 211,015 |
ns1/ns1-python | ns1/__init__.py | NS1.networks | def networks(self):
"""
Return a new raw REST interface to network resources
:rtype: :py:class:`ns1.rest.ipam.Networks`
"""
import ns1.rest.ipam
return ns1.rest.ipam.Networks(self.config) | python | def networks(self):
"""
Return a new raw REST interface to network resources
:rtype: :py:class:`ns1.rest.ipam.Networks`
"""
import ns1.rest.ipam
return ns1.rest.ipam.Networks(self.config) | [
"def",
"networks",
"(",
"self",
")",
":",
"import",
"ns1",
".",
"rest",
".",
"ipam",
"return",
"ns1",
".",
"rest",
".",
"ipam",
".",
"Networks",
"(",
"self",
".",
"config",
")"
] | Return a new raw REST interface to network resources
:rtype: :py:class:`ns1.rest.ipam.Networks` | [
"Return",
"a",
"new",
"raw",
"REST",
"interface",
"to",
"network",
"resources"
] | f3e1d90a3b76a1bd18f855f2c622a8a49d4b585e | https://github.com/ns1/ns1-python/blob/f3e1d90a3b76a1bd18f855f2c622a8a49d4b585e/ns1/__init__.py#L71-L78 | train | 211,016 |
ns1/ns1-python | ns1/__init__.py | NS1.scope_groups | def scope_groups(self):
"""
Return a new raw REST interface to scope_group resources
:rtype: :py:class:`ns1.rest.ipam.Scopegroups`
"""
import ns1.rest.ipam
return ns1.rest.ipam.Scopegroups(self.config) | python | def scope_groups(self):
"""
Return a new raw REST interface to scope_group resources
:rtype: :py:class:`ns1.rest.ipam.Scopegroups`
"""
import ns1.rest.ipam
return ns1.rest.ipam.Scopegroups(self.config) | [
"def",
"scope_groups",
"(",
"self",
")",
":",
"import",
"ns1",
".",
"rest",
".",
"ipam",
"return",
"ns1",
".",
"rest",
".",
"ipam",
".",
"Scopegroups",
"(",
"self",
".",
"config",
")"
] | Return a new raw REST interface to scope_group resources
:rtype: :py:class:`ns1.rest.ipam.Scopegroups` | [
"Return",
"a",
"new",
"raw",
"REST",
"interface",
"to",
"scope_group",
"resources"
] | f3e1d90a3b76a1bd18f855f2c622a8a49d4b585e | https://github.com/ns1/ns1-python/blob/f3e1d90a3b76a1bd18f855f2c622a8a49d4b585e/ns1/__init__.py#L80-L87 | train | 211,017 |
ns1/ns1-python | ns1/__init__.py | NS1.stats | def stats(self):
"""
Return a new raw REST interface to stats resources
:rtype: :py:class:`ns1.rest.stats.Stats`
"""
import ns1.rest.stats
return ns1.rest.stats.Stats(self.config) | python | def stats(self):
"""
Return a new raw REST interface to stats resources
:rtype: :py:class:`ns1.rest.stats.Stats`
"""
import ns1.rest.stats
return ns1.rest.stats.Stats(self.config) | [
"def",
"stats",
"(",
"self",
")",
":",
"import",
"ns1",
".",
"rest",
".",
"stats",
"return",
"ns1",
".",
"rest",
".",
"stats",
".",
"Stats",
"(",
"self",
".",
"config",
")"
] | Return a new raw REST interface to stats resources
:rtype: :py:class:`ns1.rest.stats.Stats` | [
"Return",
"a",
"new",
"raw",
"REST",
"interface",
"to",
"stats",
"resources"
] | f3e1d90a3b76a1bd18f855f2c622a8a49d4b585e | https://github.com/ns1/ns1-python/blob/f3e1d90a3b76a1bd18f855f2c622a8a49d4b585e/ns1/__init__.py#L89-L96 | train | 211,018 |
ns1/ns1-python | ns1/__init__.py | NS1.datasource | def datasource(self):
"""
Return a new raw REST interface to datasource resources
:rtype: :py:class:`ns1.rest.data.Source`
"""
import ns1.rest.data
return ns1.rest.data.Source(self.config) | python | def datasource(self):
"""
Return a new raw REST interface to datasource resources
:rtype: :py:class:`ns1.rest.data.Source`
"""
import ns1.rest.data
return ns1.rest.data.Source(self.config) | [
"def",
"datasource",
"(",
"self",
")",
":",
"import",
"ns1",
".",
"rest",
".",
"data",
"return",
"ns1",
".",
"rest",
".",
"data",
".",
"Source",
"(",
"self",
".",
"config",
")"
] | Return a new raw REST interface to datasource resources
:rtype: :py:class:`ns1.rest.data.Source` | [
"Return",
"a",
"new",
"raw",
"REST",
"interface",
"to",
"datasource",
"resources"
] | f3e1d90a3b76a1bd18f855f2c622a8a49d4b585e | https://github.com/ns1/ns1-python/blob/f3e1d90a3b76a1bd18f855f2c622a8a49d4b585e/ns1/__init__.py#L98-L105 | train | 211,019 |
ns1/ns1-python | ns1/__init__.py | NS1.datafeed | def datafeed(self):
"""
Return a new raw REST interface to feed resources
:rtype: :py:class:`ns1.rest.data.Feed`
"""
import ns1.rest.data
return ns1.rest.data.Feed(self.config) | python | def datafeed(self):
"""
Return a new raw REST interface to feed resources
:rtype: :py:class:`ns1.rest.data.Feed`
"""
import ns1.rest.data
return ns1.rest.data.Feed(self.config) | [
"def",
"datafeed",
"(",
"self",
")",
":",
"import",
"ns1",
".",
"rest",
".",
"data",
"return",
"ns1",
".",
"rest",
".",
"data",
".",
"Feed",
"(",
"self",
".",
"config",
")"
] | Return a new raw REST interface to feed resources
:rtype: :py:class:`ns1.rest.data.Feed` | [
"Return",
"a",
"new",
"raw",
"REST",
"interface",
"to",
"feed",
"resources"
] | f3e1d90a3b76a1bd18f855f2c622a8a49d4b585e | https://github.com/ns1/ns1-python/blob/f3e1d90a3b76a1bd18f855f2c622a8a49d4b585e/ns1/__init__.py#L107-L114 | train | 211,020 |
ns1/ns1-python | ns1/__init__.py | NS1.monitors | def monitors(self):
"""
Return a new raw REST interface to monitors resources
:rtype: :py:class:`ns1.rest.monitoring.Monitors`
"""
import ns1.rest.monitoring
return ns1.rest.monitoring.Monitors(self.config) | python | def monitors(self):
"""
Return a new raw REST interface to monitors resources
:rtype: :py:class:`ns1.rest.monitoring.Monitors`
"""
import ns1.rest.monitoring
return ns1.rest.monitoring.Monitors(self.config) | [
"def",
"monitors",
"(",
"self",
")",
":",
"import",
"ns1",
".",
"rest",
".",
"monitoring",
"return",
"ns1",
".",
"rest",
".",
"monitoring",
".",
"Monitors",
"(",
"self",
".",
"config",
")"
] | Return a new raw REST interface to monitors resources
:rtype: :py:class:`ns1.rest.monitoring.Monitors` | [
"Return",
"a",
"new",
"raw",
"REST",
"interface",
"to",
"monitors",
"resources"
] | f3e1d90a3b76a1bd18f855f2c622a8a49d4b585e | https://github.com/ns1/ns1-python/blob/f3e1d90a3b76a1bd18f855f2c622a8a49d4b585e/ns1/__init__.py#L116-L123 | train | 211,021 |
ns1/ns1-python | ns1/__init__.py | NS1.notifylists | def notifylists(self):
"""
Return a new raw REST interface to notify list resources
:rtype: :py:class:`ns1.rest.monitoring.NotifyLists`
"""
import ns1.rest.monitoring
return ns1.rest.monitoring.NotifyLists(self.config) | python | def notifylists(self):
"""
Return a new raw REST interface to notify list resources
:rtype: :py:class:`ns1.rest.monitoring.NotifyLists`
"""
import ns1.rest.monitoring
return ns1.rest.monitoring.NotifyLists(self.config) | [
"def",
"notifylists",
"(",
"self",
")",
":",
"import",
"ns1",
".",
"rest",
".",
"monitoring",
"return",
"ns1",
".",
"rest",
".",
"monitoring",
".",
"NotifyLists",
"(",
"self",
".",
"config",
")"
] | Return a new raw REST interface to notify list resources
:rtype: :py:class:`ns1.rest.monitoring.NotifyLists` | [
"Return",
"a",
"new",
"raw",
"REST",
"interface",
"to",
"notify",
"list",
"resources"
] | f3e1d90a3b76a1bd18f855f2c622a8a49d4b585e | https://github.com/ns1/ns1-python/blob/f3e1d90a3b76a1bd18f855f2c622a8a49d4b585e/ns1/__init__.py#L125-L132 | train | 211,022 |
ns1/ns1-python | ns1/__init__.py | NS1.plan | def plan(self):
"""
Return a new raw REST interface to account plan
:rtype: :py:class:`ns1.rest.account.Plan`
"""
import ns1.rest.account
return ns1.rest.account.Plan(self.config) | python | def plan(self):
"""
Return a new raw REST interface to account plan
:rtype: :py:class:`ns1.rest.account.Plan`
"""
import ns1.rest.account
return ns1.rest.account.Plan(self.config) | [
"def",
"plan",
"(",
"self",
")",
":",
"import",
"ns1",
".",
"rest",
".",
"account",
"return",
"ns1",
".",
"rest",
".",
"account",
".",
"Plan",
"(",
"self",
".",
"config",
")"
] | Return a new raw REST interface to account plan
:rtype: :py:class:`ns1.rest.account.Plan` | [
"Return",
"a",
"new",
"raw",
"REST",
"interface",
"to",
"account",
"plan"
] | f3e1d90a3b76a1bd18f855f2c622a8a49d4b585e | https://github.com/ns1/ns1-python/blob/f3e1d90a3b76a1bd18f855f2c622a8a49d4b585e/ns1/__init__.py#L134-L141 | train | 211,023 |
ns1/ns1-python | ns1/__init__.py | NS1.loadZone | def loadZone(self, zone, callback=None, errback=None):
"""
Load an existing zone into a high level Zone object.
:param str zone: zone name, like 'example.com'
:rtype: :py:class:`ns1.zones.Zone`
"""
import ns1.zones
zone = ns1.zones.Zone(self.config, zone)
return zone.load(callback=callback, errback=errback) | python | def loadZone(self, zone, callback=None, errback=None):
"""
Load an existing zone into a high level Zone object.
:param str zone: zone name, like 'example.com'
:rtype: :py:class:`ns1.zones.Zone`
"""
import ns1.zones
zone = ns1.zones.Zone(self.config, zone)
return zone.load(callback=callback, errback=errback) | [
"def",
"loadZone",
"(",
"self",
",",
"zone",
",",
"callback",
"=",
"None",
",",
"errback",
"=",
"None",
")",
":",
"import",
"ns1",
".",
"zones",
"zone",
"=",
"ns1",
".",
"zones",
".",
"Zone",
"(",
"self",
".",
"config",
",",
"zone",
")",
"return",
... | Load an existing zone into a high level Zone object.
:param str zone: zone name, like 'example.com'
:rtype: :py:class:`ns1.zones.Zone` | [
"Load",
"an",
"existing",
"zone",
"into",
"a",
"high",
"level",
"Zone",
"object",
"."
] | f3e1d90a3b76a1bd18f855f2c622a8a49d4b585e | https://github.com/ns1/ns1-python/blob/f3e1d90a3b76a1bd18f855f2c622a8a49d4b585e/ns1/__init__.py#L144-L153 | train | 211,024 |
ns1/ns1-python | ns1/__init__.py | NS1.createZone | def createZone(self, zone, zoneFile=None, callback=None, errback=None,
**kwargs):
"""
Create a new zone, and return an associated high level Zone object.
Several optional keyword arguments are available to configure the SOA
record.
If zoneFile is specified, upload the specific zone definition file
to populate the zone with.
:param str zone: zone name, like 'example.com'
:param str zoneFile: absolute path of a zone file
:keyword int retry: retry time
:keyword int refresh: refresh ttl
:keyword int expiry: expiry ttl
:keyword int nx_ttl: nxdomain TTL
:rtype: :py:class:`ns1.zones.Zone`
"""
import ns1.zones
zone = ns1.zones.Zone(self.config, zone)
return zone.create(zoneFile=zoneFile, callback=callback,
errback=errback, **kwargs) | python | def createZone(self, zone, zoneFile=None, callback=None, errback=None,
**kwargs):
"""
Create a new zone, and return an associated high level Zone object.
Several optional keyword arguments are available to configure the SOA
record.
If zoneFile is specified, upload the specific zone definition file
to populate the zone with.
:param str zone: zone name, like 'example.com'
:param str zoneFile: absolute path of a zone file
:keyword int retry: retry time
:keyword int refresh: refresh ttl
:keyword int expiry: expiry ttl
:keyword int nx_ttl: nxdomain TTL
:rtype: :py:class:`ns1.zones.Zone`
"""
import ns1.zones
zone = ns1.zones.Zone(self.config, zone)
return zone.create(zoneFile=zoneFile, callback=callback,
errback=errback, **kwargs) | [
"def",
"createZone",
"(",
"self",
",",
"zone",
",",
"zoneFile",
"=",
"None",
",",
"callback",
"=",
"None",
",",
"errback",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"import",
"ns1",
".",
"zones",
"zone",
"=",
"ns1",
".",
"zones",
".",
"Zone",... | Create a new zone, and return an associated high level Zone object.
Several optional keyword arguments are available to configure the SOA
record.
If zoneFile is specified, upload the specific zone definition file
to populate the zone with.
:param str zone: zone name, like 'example.com'
:param str zoneFile: absolute path of a zone file
:keyword int retry: retry time
:keyword int refresh: refresh ttl
:keyword int expiry: expiry ttl
:keyword int nx_ttl: nxdomain TTL
:rtype: :py:class:`ns1.zones.Zone` | [
"Create",
"a",
"new",
"zone",
"and",
"return",
"an",
"associated",
"high",
"level",
"Zone",
"object",
".",
"Several",
"optional",
"keyword",
"arguments",
"are",
"available",
"to",
"configure",
"the",
"SOA",
"record",
"."
] | f3e1d90a3b76a1bd18f855f2c622a8a49d4b585e | https://github.com/ns1/ns1-python/blob/f3e1d90a3b76a1bd18f855f2c622a8a49d4b585e/ns1/__init__.py#L165-L187 | train | 211,025 |
ns1/ns1-python | ns1/__init__.py | NS1.loadRecord | def loadRecord(self, domain, type, zone=None, callback=None,
errback=None, **kwargs):
"""
Load an existing record into a high level Record object.
:param str domain: domain name of the record in the zone, for example \
'myrecord'. You may leave off the zone, since it must be \
specified in the zone parameter
:param str type: record type, such as 'A', 'MX', 'AAAA', etc.
:param str zone: zone name, like 'example.com'
:rtype: :py:class:`ns1.records`
"""
import ns1.zones
if zone is None:
# extract from record string
parts = domain.split('.')
if len(parts) <= 2:
zone = '.'.join(parts)
else:
zone = '.'.join(parts[1:])
z = ns1.zones.Zone(self.config, zone)
return z.loadRecord(domain, type, callback=callback, errback=errback,
**kwargs) | python | def loadRecord(self, domain, type, zone=None, callback=None,
errback=None, **kwargs):
"""
Load an existing record into a high level Record object.
:param str domain: domain name of the record in the zone, for example \
'myrecord'. You may leave off the zone, since it must be \
specified in the zone parameter
:param str type: record type, such as 'A', 'MX', 'AAAA', etc.
:param str zone: zone name, like 'example.com'
:rtype: :py:class:`ns1.records`
"""
import ns1.zones
if zone is None:
# extract from record string
parts = domain.split('.')
if len(parts) <= 2:
zone = '.'.join(parts)
else:
zone = '.'.join(parts[1:])
z = ns1.zones.Zone(self.config, zone)
return z.loadRecord(domain, type, callback=callback, errback=errback,
**kwargs) | [
"def",
"loadRecord",
"(",
"self",
",",
"domain",
",",
"type",
",",
"zone",
"=",
"None",
",",
"callback",
"=",
"None",
",",
"errback",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"import",
"ns1",
".",
"zones",
"if",
"zone",
"is",
"None",
":",
... | Load an existing record into a high level Record object.
:param str domain: domain name of the record in the zone, for example \
'myrecord'. You may leave off the zone, since it must be \
specified in the zone parameter
:param str type: record type, such as 'A', 'MX', 'AAAA', etc.
:param str zone: zone name, like 'example.com'
:rtype: :py:class:`ns1.records` | [
"Load",
"an",
"existing",
"record",
"into",
"a",
"high",
"level",
"Record",
"object",
"."
] | f3e1d90a3b76a1bd18f855f2c622a8a49d4b585e | https://github.com/ns1/ns1-python/blob/f3e1d90a3b76a1bd18f855f2c622a8a49d4b585e/ns1/__init__.py#L189-L211 | train | 211,026 |
ns1/ns1-python | ns1/__init__.py | NS1.loadMonitors | def loadMonitors(self, callback=None, errback=None, **kwargs):
"""
Load all monitors
"""
import ns1.monitoring
monitors_list = self.monitors().list(callback, errback)
return [ns1.monitoring.Monitor(self.config, m) for m in monitors_list] | python | def loadMonitors(self, callback=None, errback=None, **kwargs):
"""
Load all monitors
"""
import ns1.monitoring
monitors_list = self.monitors().list(callback, errback)
return [ns1.monitoring.Monitor(self.config, m) for m in monitors_list] | [
"def",
"loadMonitors",
"(",
"self",
",",
"callback",
"=",
"None",
",",
"errback",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"import",
"ns1",
".",
"monitoring",
"monitors_list",
"=",
"self",
".",
"monitors",
"(",
")",
".",
"list",
"(",
"callback",... | Load all monitors | [
"Load",
"all",
"monitors"
] | f3e1d90a3b76a1bd18f855f2c622a8a49d4b585e | https://github.com/ns1/ns1-python/blob/f3e1d90a3b76a1bd18f855f2c622a8a49d4b585e/ns1/__init__.py#L213-L220 | train | 211,027 |
ns1/ns1-python | ns1/__init__.py | NS1.createMonitor | def createMonitor(self, callback=None, errback=None, **kwargs):
"""
Create a monitor
"""
import ns1.monitoring
monitor = ns1.monitoring.Monitor(self.config)
return monitor.create(callback=callback, errback=errback, **kwargs) | python | def createMonitor(self, callback=None, errback=None, **kwargs):
"""
Create a monitor
"""
import ns1.monitoring
monitor = ns1.monitoring.Monitor(self.config)
return monitor.create(callback=callback, errback=errback, **kwargs) | [
"def",
"createMonitor",
"(",
"self",
",",
"callback",
"=",
"None",
",",
"errback",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"import",
"ns1",
".",
"monitoring",
"monitor",
"=",
"ns1",
".",
"monitoring",
".",
"Monitor",
"(",
"self",
".",
"config",... | Create a monitor | [
"Create",
"a",
"monitor"
] | f3e1d90a3b76a1bd18f855f2c622a8a49d4b585e | https://github.com/ns1/ns1-python/blob/f3e1d90a3b76a1bd18f855f2c622a8a49d4b585e/ns1/__init__.py#L222-L228 | train | 211,028 |
ns1/ns1-python | ns1/__init__.py | NS1.loadNetworkbyID | def loadNetworkbyID(self, id, callback=None, errback=None):
"""
Load an existing Network by ID into a high level Network object
:param int id: id of an existing Network
"""
import ns1.ipam
network = ns1.ipam.Network(self.config, id=id)
return network.load(callback=callback, errback=errback) | python | def loadNetworkbyID(self, id, callback=None, errback=None):
"""
Load an existing Network by ID into a high level Network object
:param int id: id of an existing Network
"""
import ns1.ipam
network = ns1.ipam.Network(self.config, id=id)
return network.load(callback=callback, errback=errback) | [
"def",
"loadNetworkbyID",
"(",
"self",
",",
"id",
",",
"callback",
"=",
"None",
",",
"errback",
"=",
"None",
")",
":",
"import",
"ns1",
".",
"ipam",
"network",
"=",
"ns1",
".",
"ipam",
".",
"Network",
"(",
"self",
".",
"config",
",",
"id",
"=",
"id... | Load an existing Network by ID into a high level Network object
:param int id: id of an existing Network | [
"Load",
"an",
"existing",
"Network",
"by",
"ID",
"into",
"a",
"high",
"level",
"Network",
"object"
] | f3e1d90a3b76a1bd18f855f2c622a8a49d4b585e | https://github.com/ns1/ns1-python/blob/f3e1d90a3b76a1bd18f855f2c622a8a49d4b585e/ns1/__init__.py#L230-L238 | train | 211,029 |
ns1/ns1-python | ns1/__init__.py | NS1.loadNetworkbyName | def loadNetworkbyName(self, name, callback=None, errback=None):
"""
Load an existing Network by name into a high level Network object
:param str name: Name of an existing Network
"""
import ns1.ipam
network = ns1.ipam.Network(self.config, name=name)
return network.load(callback=callback, errback=errback) | python | def loadNetworkbyName(self, name, callback=None, errback=None):
"""
Load an existing Network by name into a high level Network object
:param str name: Name of an existing Network
"""
import ns1.ipam
network = ns1.ipam.Network(self.config, name=name)
return network.load(callback=callback, errback=errback) | [
"def",
"loadNetworkbyName",
"(",
"self",
",",
"name",
",",
"callback",
"=",
"None",
",",
"errback",
"=",
"None",
")",
":",
"import",
"ns1",
".",
"ipam",
"network",
"=",
"ns1",
".",
"ipam",
".",
"Network",
"(",
"self",
".",
"config",
",",
"name",
"=",... | Load an existing Network by name into a high level Network object
:param str name: Name of an existing Network | [
"Load",
"an",
"existing",
"Network",
"by",
"name",
"into",
"a",
"high",
"level",
"Network",
"object"
] | f3e1d90a3b76a1bd18f855f2c622a8a49d4b585e | https://github.com/ns1/ns1-python/blob/f3e1d90a3b76a1bd18f855f2c622a8a49d4b585e/ns1/__init__.py#L240-L248 | train | 211,030 |
ns1/ns1-python | ns1/__init__.py | NS1.loadAddressbyID | def loadAddressbyID(self, id, callback=None, errback=None):
"""
Load an existing address by ID into a high level Address object
:param int id: id of an existing Address
"""
import ns1.ipam
address = ns1.ipam.Address(self.config, id=id)
return address.load(callback=callback, errback=errback) | python | def loadAddressbyID(self, id, callback=None, errback=None):
"""
Load an existing address by ID into a high level Address object
:param int id: id of an existing Address
"""
import ns1.ipam
address = ns1.ipam.Address(self.config, id=id)
return address.load(callback=callback, errback=errback) | [
"def",
"loadAddressbyID",
"(",
"self",
",",
"id",
",",
"callback",
"=",
"None",
",",
"errback",
"=",
"None",
")",
":",
"import",
"ns1",
".",
"ipam",
"address",
"=",
"ns1",
".",
"ipam",
".",
"Address",
"(",
"self",
".",
"config",
",",
"id",
"=",
"id... | Load an existing address by ID into a high level Address object
:param int id: id of an existing Address | [
"Load",
"an",
"existing",
"address",
"by",
"ID",
"into",
"a",
"high",
"level",
"Address",
"object"
] | f3e1d90a3b76a1bd18f855f2c622a8a49d4b585e | https://github.com/ns1/ns1-python/blob/f3e1d90a3b76a1bd18f855f2c622a8a49d4b585e/ns1/__init__.py#L265-L273 | train | 211,031 |
ns1/ns1-python | ns1/__init__.py | NS1.loadAddressbyPrefix | def loadAddressbyPrefix(self, prefix, type, network_id, callback=None, errback=None):
"""
Load an existing address by prefix, type and network into a high level Address object
:param str prefix: CIDR prefix of an existing Address
:param str type: Type of address assignement (planned, assignment or host)
:param int network_id: network_id associated with the address
"""
import ns1.ipam
network = ns1.ipam.Network(self.config, id=network_id).load()
address = ns1.ipam.Address(self.config, prefix=prefix, type=type, network=network)
return address.load(callback=callback, errback=errback) | python | def loadAddressbyPrefix(self, prefix, type, network_id, callback=None, errback=None):
"""
Load an existing address by prefix, type and network into a high level Address object
:param str prefix: CIDR prefix of an existing Address
:param str type: Type of address assignement (planned, assignment or host)
:param int network_id: network_id associated with the address
"""
import ns1.ipam
network = ns1.ipam.Network(self.config, id=network_id).load()
address = ns1.ipam.Address(self.config, prefix=prefix, type=type, network=network)
return address.load(callback=callback, errback=errback) | [
"def",
"loadAddressbyPrefix",
"(",
"self",
",",
"prefix",
",",
"type",
",",
"network_id",
",",
"callback",
"=",
"None",
",",
"errback",
"=",
"None",
")",
":",
"import",
"ns1",
".",
"ipam",
"network",
"=",
"ns1",
".",
"ipam",
".",
"Network",
"(",
"self"... | Load an existing address by prefix, type and network into a high level Address object
:param str prefix: CIDR prefix of an existing Address
:param str type: Type of address assignement (planned, assignment or host)
:param int network_id: network_id associated with the address | [
"Load",
"an",
"existing",
"address",
"by",
"prefix",
"type",
"and",
"network",
"into",
"a",
"high",
"level",
"Address",
"object"
] | f3e1d90a3b76a1bd18f855f2c622a8a49d4b585e | https://github.com/ns1/ns1-python/blob/f3e1d90a3b76a1bd18f855f2c622a8a49d4b585e/ns1/__init__.py#L275-L286 | train | 211,032 |
ns1/ns1-python | ns1/__init__.py | NS1.loadScopeGroupbyID | def loadScopeGroupbyID(self, id, callback=None, errback=None):
"""
Load an existing Scope Group by ID into a high level Scope Group object
:param int id: id of an existing ScopeGroup
"""
import ns1.ipam
scope_group = ns1.ipam.Scopegroup(self.config, id=id)
return scope_group.load(callback=callback, errback=errback) | python | def loadScopeGroupbyID(self, id, callback=None, errback=None):
"""
Load an existing Scope Group by ID into a high level Scope Group object
:param int id: id of an existing ScopeGroup
"""
import ns1.ipam
scope_group = ns1.ipam.Scopegroup(self.config, id=id)
return scope_group.load(callback=callback, errback=errback) | [
"def",
"loadScopeGroupbyID",
"(",
"self",
",",
"id",
",",
"callback",
"=",
"None",
",",
"errback",
"=",
"None",
")",
":",
"import",
"ns1",
".",
"ipam",
"scope_group",
"=",
"ns1",
".",
"ipam",
".",
"Scopegroup",
"(",
"self",
".",
"config",
",",
"id",
... | Load an existing Scope Group by ID into a high level Scope Group object
:param int id: id of an existing ScopeGroup | [
"Load",
"an",
"existing",
"Scope",
"Group",
"by",
"ID",
"into",
"a",
"high",
"level",
"Scope",
"Group",
"object"
] | f3e1d90a3b76a1bd18f855f2c622a8a49d4b585e | https://github.com/ns1/ns1-python/blob/f3e1d90a3b76a1bd18f855f2c622a8a49d4b585e/ns1/__init__.py#L302-L310 | train | 211,033 |
ns1/ns1-python | ns1/__init__.py | NS1.loadScopeGroupbyName | def loadScopeGroupbyName(self, name, service_group_id, callback=None, errback=None):
"""
Load an existing Scope Group by name and service group id into a high level Scope Group object
:param str name: Name of an existing Scope Group
:param int service_group_id: id of the service group the Scope group is associated with
"""
import ns1.ipam
scope_group = ns1.ipam.Scopegroup(self.config, name=name, service_group_id=service_group_id)
return scope_group.load(callback=callback, errback=errback) | python | def loadScopeGroupbyName(self, name, service_group_id, callback=None, errback=None):
"""
Load an existing Scope Group by name and service group id into a high level Scope Group object
:param str name: Name of an existing Scope Group
:param int service_group_id: id of the service group the Scope group is associated with
"""
import ns1.ipam
scope_group = ns1.ipam.Scopegroup(self.config, name=name, service_group_id=service_group_id)
return scope_group.load(callback=callback, errback=errback) | [
"def",
"loadScopeGroupbyName",
"(",
"self",
",",
"name",
",",
"service_group_id",
",",
"callback",
"=",
"None",
",",
"errback",
"=",
"None",
")",
":",
"import",
"ns1",
".",
"ipam",
"scope_group",
"=",
"ns1",
".",
"ipam",
".",
"Scopegroup",
"(",
"self",
"... | Load an existing Scope Group by name and service group id into a high level Scope Group object
:param str name: Name of an existing Scope Group
:param int service_group_id: id of the service group the Scope group is associated with | [
"Load",
"an",
"existing",
"Scope",
"Group",
"by",
"name",
"and",
"service",
"group",
"id",
"into",
"a",
"high",
"level",
"Scope",
"Group",
"object"
] | f3e1d90a3b76a1bd18f855f2c622a8a49d4b585e | https://github.com/ns1/ns1-python/blob/f3e1d90a3b76a1bd18f855f2c622a8a49d4b585e/ns1/__init__.py#L312-L321 | train | 211,034 |
ns1/ns1-python | ns1/__init__.py | NS1.generateDHCPOptionsTemplate | def generateDHCPOptionsTemplate(self, address_family):
"""
Generate boilerplate dictionary to hold dhcp options
:param str address_family: dhcpv4 or dhcpv6
:return: dict containing valid option set for address family
"""
from ns1.ipam import DHCPOptions
options = {}
for option in DHCPOptions.OPTIONS[address_family]:
options[option] = ""
return options | python | def generateDHCPOptionsTemplate(self, address_family):
"""
Generate boilerplate dictionary to hold dhcp options
:param str address_family: dhcpv4 or dhcpv6
:return: dict containing valid option set for address family
"""
from ns1.ipam import DHCPOptions
options = {}
for option in DHCPOptions.OPTIONS[address_family]:
options[option] = ""
return options | [
"def",
"generateDHCPOptionsTemplate",
"(",
"self",
",",
"address_family",
")",
":",
"from",
"ns1",
".",
"ipam",
"import",
"DHCPOptions",
"options",
"=",
"{",
"}",
"for",
"option",
"in",
"DHCPOptions",
".",
"OPTIONS",
"[",
"address_family",
"]",
":",
"options",... | Generate boilerplate dictionary to hold dhcp options
:param str address_family: dhcpv4 or dhcpv6
:return: dict containing valid option set for address family | [
"Generate",
"boilerplate",
"dictionary",
"to",
"hold",
"dhcp",
"options"
] | f3e1d90a3b76a1bd18f855f2c622a8a49d4b585e | https://github.com/ns1/ns1-python/blob/f3e1d90a3b76a1bd18f855f2c622a8a49d4b585e/ns1/__init__.py#L337-L348 | train | 211,035 |
ns1/ns1-python | ns1/__init__.py | NS1.loadDHCPOptions | def loadDHCPOptions(self, address_family, options):
"""
Create a high level DHCPOptions object
:param str address_family: Address family of the options. Can be either dhcpv4 or dhcpv6
:param dict options: Dictionary containing the option set to apply for this address family. Note: only those specified will be applied. Allowed options can be found in :attr:`ns1.ipam.DHCPOptions.OPTIONS`
"""
import ns1.ipam
return ns1.ipam.DHCPOptions(address_family, options) | python | def loadDHCPOptions(self, address_family, options):
"""
Create a high level DHCPOptions object
:param str address_family: Address family of the options. Can be either dhcpv4 or dhcpv6
:param dict options: Dictionary containing the option set to apply for this address family. Note: only those specified will be applied. Allowed options can be found in :attr:`ns1.ipam.DHCPOptions.OPTIONS`
"""
import ns1.ipam
return ns1.ipam.DHCPOptions(address_family, options) | [
"def",
"loadDHCPOptions",
"(",
"self",
",",
"address_family",
",",
"options",
")",
":",
"import",
"ns1",
".",
"ipam",
"return",
"ns1",
".",
"ipam",
".",
"DHCPOptions",
"(",
"address_family",
",",
"options",
")"
] | Create a high level DHCPOptions object
:param str address_family: Address family of the options. Can be either dhcpv4 or dhcpv6
:param dict options: Dictionary containing the option set to apply for this address family. Note: only those specified will be applied. Allowed options can be found in :attr:`ns1.ipam.DHCPOptions.OPTIONS` | [
"Create",
"a",
"high",
"level",
"DHCPOptions",
"object"
] | f3e1d90a3b76a1bd18f855f2c622a8a49d4b585e | https://github.com/ns1/ns1-python/blob/f3e1d90a3b76a1bd18f855f2c622a8a49d4b585e/ns1/__init__.py#L350-L358 | train | 211,036 |
HonzaKral/django-threadedcomments | threadedcomments/util.py | fill_tree | def fill_tree(comments):
"""
Insert extra comments in the comments list, so that the root path of the first comment is always visible.
Use this in comments' pagination to fill in the tree information.
The inserted comments have an ``added_path`` attribute.
"""
if not comments:
return
it = iter(comments)
first = next(it)
extra_path_items = imap(_mark_as_root_path, first.root_path)
return chain(extra_path_items, [first], it) | python | def fill_tree(comments):
"""
Insert extra comments in the comments list, so that the root path of the first comment is always visible.
Use this in comments' pagination to fill in the tree information.
The inserted comments have an ``added_path`` attribute.
"""
if not comments:
return
it = iter(comments)
first = next(it)
extra_path_items = imap(_mark_as_root_path, first.root_path)
return chain(extra_path_items, [first], it) | [
"def",
"fill_tree",
"(",
"comments",
")",
":",
"if",
"not",
"comments",
":",
"return",
"it",
"=",
"iter",
"(",
"comments",
")",
"first",
"=",
"next",
"(",
"it",
")",
"extra_path_items",
"=",
"imap",
"(",
"_mark_as_root_path",
",",
"first",
".",
"root_pat... | Insert extra comments in the comments list, so that the root path of the first comment is always visible.
Use this in comments' pagination to fill in the tree information.
The inserted comments have an ``added_path`` attribute. | [
"Insert",
"extra",
"comments",
"in",
"the",
"comments",
"list",
"so",
"that",
"the",
"root",
"path",
"of",
"the",
"first",
"comment",
"is",
"always",
"visible",
".",
"Use",
"this",
"in",
"comments",
"pagination",
"to",
"fill",
"in",
"the",
"tree",
"informa... | 7b36d9e0813fcbb634052990d1cf01bba8ef220f | https://github.com/HonzaKral/django-threadedcomments/blob/7b36d9e0813fcbb634052990d1cf01bba8ef220f/threadedcomments/util.py#L21-L34 | train | 211,037 |
HonzaKral/django-threadedcomments | threadedcomments/util.py | annotate_tree_properties | def annotate_tree_properties(comments):
"""
iterate through nodes and adds some magic properties to each of them
representing opening list of children and closing it
"""
if not comments:
return
it = iter(comments)
# get the first item, this will fail if no items !
old = next(it)
# first item starts a new thread
old.open = True
last = set()
for c in it:
# if this comment has a parent, store its last child for future reference
if old.last_child_id:
last.add(old.last_child_id)
# this is the last child, mark it
if c.pk in last:
c.last = True
# increase the depth
if c.depth > old.depth:
c.open = True
else: # c.depth <= old.depth
# close some depths
old.close = list(range(old.depth - c.depth))
# new thread
if old.root_id != c.root_id:
# close even the top depth
old.close.append(len(old.close))
# and start a new thread
c.open = True
# empty the last set
last = set()
# iterate
yield old
old = c
old.close = range(old.depth)
yield old | python | def annotate_tree_properties(comments):
"""
iterate through nodes and adds some magic properties to each of them
representing opening list of children and closing it
"""
if not comments:
return
it = iter(comments)
# get the first item, this will fail if no items !
old = next(it)
# first item starts a new thread
old.open = True
last = set()
for c in it:
# if this comment has a parent, store its last child for future reference
if old.last_child_id:
last.add(old.last_child_id)
# this is the last child, mark it
if c.pk in last:
c.last = True
# increase the depth
if c.depth > old.depth:
c.open = True
else: # c.depth <= old.depth
# close some depths
old.close = list(range(old.depth - c.depth))
# new thread
if old.root_id != c.root_id:
# close even the top depth
old.close.append(len(old.close))
# and start a new thread
c.open = True
# empty the last set
last = set()
# iterate
yield old
old = c
old.close = range(old.depth)
yield old | [
"def",
"annotate_tree_properties",
"(",
"comments",
")",
":",
"if",
"not",
"comments",
":",
"return",
"it",
"=",
"iter",
"(",
"comments",
")",
"# get the first item, this will fail if no items !",
"old",
"=",
"next",
"(",
"it",
")",
"# first item starts a new thread",... | iterate through nodes and adds some magic properties to each of them
representing opening list of children and closing it | [
"iterate",
"through",
"nodes",
"and",
"adds",
"some",
"magic",
"properties",
"to",
"each",
"of",
"them",
"representing",
"opening",
"list",
"of",
"children",
"and",
"closing",
"it"
] | 7b36d9e0813fcbb634052990d1cf01bba8ef220f | https://github.com/HonzaKral/django-threadedcomments/blob/7b36d9e0813fcbb634052990d1cf01bba8ef220f/threadedcomments/util.py#L37-L83 | train | 211,038 |
sanger-pathogens/circlator | circlator/assemble.py | Assembler.run_spades | def run_spades(self, stop_at_first_success=False):
'''Runs spades on all kmers. Each a separate run because SPAdes dies if any kmer does
not work. Chooses the 'best' assembly to be the one with the biggest N50'''
n50 = {}
kmer_to_dir = {}
for k in self.spades_kmers:
tmpdir = tempfile.mkdtemp(prefix=self.outdir + '.tmp.spades.' + str(k) + '.', dir=os.getcwd())
kmer_to_dir[k] = tmpdir
ok, errs = self.run_spades_once(k, tmpdir)
if ok:
contigs_fasta = os.path.join(tmpdir, 'contigs.fasta')
contigs_fai = contigs_fasta + '.fai'
common.syscall(self.samtools.exe() + ' faidx ' + contigs_fasta, verbose=self.verbose)
stats = pyfastaq.tasks.stats_from_fai(contigs_fai)
if stats['N50'] != 0:
n50[k] = stats['N50']
if stop_at_first_success:
break
if len(n50) > 0:
if self.verbose:
print('[assemble]\tkmer\tN50')
for k in sorted(n50):
print('[assemble]', k, n50[k], sep='\t')
best_k = None
for k in sorted(n50):
if best_k is None or n50[k] >= n50[best_k]:
best_k = k
assert best_k is not None
for k, directory in kmer_to_dir.items():
if k == best_k:
if self.verbose:
print('[assemble] using assembly with kmer', k)
os.rename(directory, self.outdir)
else:
shutil.rmtree(directory)
else:
raise Error('Error running SPAdes. Output directories are:\n ' + '\n '.join(kmer_to_dir.values()) + '\nThe reason why should be in the spades.log file in each directory.') | python | def run_spades(self, stop_at_first_success=False):
'''Runs spades on all kmers. Each a separate run because SPAdes dies if any kmer does
not work. Chooses the 'best' assembly to be the one with the biggest N50'''
n50 = {}
kmer_to_dir = {}
for k in self.spades_kmers:
tmpdir = tempfile.mkdtemp(prefix=self.outdir + '.tmp.spades.' + str(k) + '.', dir=os.getcwd())
kmer_to_dir[k] = tmpdir
ok, errs = self.run_spades_once(k, tmpdir)
if ok:
contigs_fasta = os.path.join(tmpdir, 'contigs.fasta')
contigs_fai = contigs_fasta + '.fai'
common.syscall(self.samtools.exe() + ' faidx ' + contigs_fasta, verbose=self.verbose)
stats = pyfastaq.tasks.stats_from_fai(contigs_fai)
if stats['N50'] != 0:
n50[k] = stats['N50']
if stop_at_first_success:
break
if len(n50) > 0:
if self.verbose:
print('[assemble]\tkmer\tN50')
for k in sorted(n50):
print('[assemble]', k, n50[k], sep='\t')
best_k = None
for k in sorted(n50):
if best_k is None or n50[k] >= n50[best_k]:
best_k = k
assert best_k is not None
for k, directory in kmer_to_dir.items():
if k == best_k:
if self.verbose:
print('[assemble] using assembly with kmer', k)
os.rename(directory, self.outdir)
else:
shutil.rmtree(directory)
else:
raise Error('Error running SPAdes. Output directories are:\n ' + '\n '.join(kmer_to_dir.values()) + '\nThe reason why should be in the spades.log file in each directory.') | [
"def",
"run_spades",
"(",
"self",
",",
"stop_at_first_success",
"=",
"False",
")",
":",
"n50",
"=",
"{",
"}",
"kmer_to_dir",
"=",
"{",
"}",
"for",
"k",
"in",
"self",
".",
"spades_kmers",
":",
"tmpdir",
"=",
"tempfile",
".",
"mkdtemp",
"(",
"prefix",
"=... | Runs spades on all kmers. Each a separate run because SPAdes dies if any kmer does
not work. Chooses the 'best' assembly to be the one with the biggest N50 | [
"Runs",
"spades",
"on",
"all",
"kmers",
".",
"Each",
"a",
"separate",
"run",
"because",
"SPAdes",
"dies",
"if",
"any",
"kmer",
"does",
"not",
"work",
".",
"Chooses",
"the",
"best",
"assembly",
"to",
"be",
"the",
"one",
"with",
"the",
"biggest",
"N50"
] | a4befb8c9dbbcd4b3ad1899a95aa3e689d58b638 | https://github.com/sanger-pathogens/circlator/blob/a4befb8c9dbbcd4b3ad1899a95aa3e689d58b638/circlator/assemble.py#L102-L145 | train | 211,039 |
sanger-pathogens/circlator | circlator/assemble.py | Assembler.run_canu | def run_canu(self):
'''Runs canu instead of spades'''
cmd = self._make_canu_command(self.outdir,'canu')
ok, errs = common.syscall(cmd, verbose=self.verbose, allow_fail=False)
if not ok:
raise Error('Error running Canu.')
original_contigs = os.path.join(self.outdir, 'canu.contigs.fasta')
renamed_contigs = os.path.join(self.outdir, 'contigs.fasta')
Assembler._rename_canu_contigs(original_contigs, renamed_contigs)
original_gfa = os.path.join(self.outdir, 'canu.contigs.gfa')
renamed_gfa = os.path.join(self.outdir, 'contigs.gfa')
os.rename(original_gfa, renamed_gfa) | python | def run_canu(self):
'''Runs canu instead of spades'''
cmd = self._make_canu_command(self.outdir,'canu')
ok, errs = common.syscall(cmd, verbose=self.verbose, allow_fail=False)
if not ok:
raise Error('Error running Canu.')
original_contigs = os.path.join(self.outdir, 'canu.contigs.fasta')
renamed_contigs = os.path.join(self.outdir, 'contigs.fasta')
Assembler._rename_canu_contigs(original_contigs, renamed_contigs)
original_gfa = os.path.join(self.outdir, 'canu.contigs.gfa')
renamed_gfa = os.path.join(self.outdir, 'contigs.gfa')
os.rename(original_gfa, renamed_gfa) | [
"def",
"run_canu",
"(",
"self",
")",
":",
"cmd",
"=",
"self",
".",
"_make_canu_command",
"(",
"self",
".",
"outdir",
",",
"'canu'",
")",
"ok",
",",
"errs",
"=",
"common",
".",
"syscall",
"(",
"cmd",
",",
"verbose",
"=",
"self",
".",
"verbose",
",",
... | Runs canu instead of spades | [
"Runs",
"canu",
"instead",
"of",
"spades"
] | a4befb8c9dbbcd4b3ad1899a95aa3e689d58b638 | https://github.com/sanger-pathogens/circlator/blob/a4befb8c9dbbcd4b3ad1899a95aa3e689d58b638/circlator/assemble.py#L159-L171 | train | 211,040 |
sanger-pathogens/circlator | circlator/mapping.py | aligned_read_to_read | def aligned_read_to_read(read, revcomp=True, qual=None, ignore_quality=False):
'''Returns Fasta or Fastq sequence from pysam aligned read'''
if read.qual is None or ignore_quality:
if qual is None or ignore_quality:
seq = pyfastaq.sequences.Fasta(read.qname, common.decode(read.seq))
else:
seq = pyfastaq.sequences.Fastq(read.qname, common.decode(read.seq), qual * read.query_length)
else:
if qual is None:
seq = pyfastaq.sequences.Fastq(read.qname, common.decode(read.seq), common.decode(read.qual))
else:
seq = pyfastaq.sequences.Fastq(read.qname, common.decode(read.seq), qual * read.query_length)
if read.is_reverse and revcomp:
seq.revcomp()
return seq | python | def aligned_read_to_read(read, revcomp=True, qual=None, ignore_quality=False):
'''Returns Fasta or Fastq sequence from pysam aligned read'''
if read.qual is None or ignore_quality:
if qual is None or ignore_quality:
seq = pyfastaq.sequences.Fasta(read.qname, common.decode(read.seq))
else:
seq = pyfastaq.sequences.Fastq(read.qname, common.decode(read.seq), qual * read.query_length)
else:
if qual is None:
seq = pyfastaq.sequences.Fastq(read.qname, common.decode(read.seq), common.decode(read.qual))
else:
seq = pyfastaq.sequences.Fastq(read.qname, common.decode(read.seq), qual * read.query_length)
if read.is_reverse and revcomp:
seq.revcomp()
return seq | [
"def",
"aligned_read_to_read",
"(",
"read",
",",
"revcomp",
"=",
"True",
",",
"qual",
"=",
"None",
",",
"ignore_quality",
"=",
"False",
")",
":",
"if",
"read",
".",
"qual",
"is",
"None",
"or",
"ignore_quality",
":",
"if",
"qual",
"is",
"None",
"or",
"i... | Returns Fasta or Fastq sequence from pysam aligned read | [
"Returns",
"Fasta",
"or",
"Fastq",
"sequence",
"from",
"pysam",
"aligned",
"read"
] | a4befb8c9dbbcd4b3ad1899a95aa3e689d58b638 | https://github.com/sanger-pathogens/circlator/blob/a4befb8c9dbbcd4b3ad1899a95aa3e689d58b638/circlator/mapping.py#L109-L125 | train | 211,041 |
sanger-pathogens/circlator | circlator/bamfilter.py | BamFilter._get_ref_lengths | def _get_ref_lengths(self):
'''Gets the length of each reference sequence from the header of the bam. Returns dict name => length'''
sam_reader = pysam.Samfile(self.bam, "rb")
return dict(zip(sam_reader.references, sam_reader.lengths)) | python | def _get_ref_lengths(self):
'''Gets the length of each reference sequence from the header of the bam. Returns dict name => length'''
sam_reader = pysam.Samfile(self.bam, "rb")
return dict(zip(sam_reader.references, sam_reader.lengths)) | [
"def",
"_get_ref_lengths",
"(",
"self",
")",
":",
"sam_reader",
"=",
"pysam",
".",
"Samfile",
"(",
"self",
".",
"bam",
",",
"\"rb\"",
")",
"return",
"dict",
"(",
"zip",
"(",
"sam_reader",
".",
"references",
",",
"sam_reader",
".",
"lengths",
")",
")"
] | Gets the length of each reference sequence from the header of the bam. Returns dict name => length | [
"Gets",
"the",
"length",
"of",
"each",
"reference",
"sequence",
"from",
"the",
"header",
"of",
"the",
"bam",
".",
"Returns",
"dict",
"name",
"=",
">",
"length"
] | a4befb8c9dbbcd4b3ad1899a95aa3e689d58b638 | https://github.com/sanger-pathogens/circlator/blob/a4befb8c9dbbcd4b3ad1899a95aa3e689d58b638/circlator/bamfilter.py#L40-L43 | train | 211,042 |
sanger-pathogens/circlator | circlator/bamfilter.py | BamFilter._get_contigs_to_use | def _get_contigs_to_use(self, contigs_to_use):
'''If contigs_to_use is a set, returns that set. If it's None, returns an empty set.
Otherwise, assumes it's a file name, and gets names from the file'''
if type(contigs_to_use) == set:
return contigs_to_use
elif contigs_to_use is None:
return set()
else:
f = pyfastaq.utils.open_file_read(contigs_to_use)
contigs_to_use = set([line.rstrip() for line in f])
pyfastaq.utils.close(f)
return contigs_to_use | python | def _get_contigs_to_use(self, contigs_to_use):
'''If contigs_to_use is a set, returns that set. If it's None, returns an empty set.
Otherwise, assumes it's a file name, and gets names from the file'''
if type(contigs_to_use) == set:
return contigs_to_use
elif contigs_to_use is None:
return set()
else:
f = pyfastaq.utils.open_file_read(contigs_to_use)
contigs_to_use = set([line.rstrip() for line in f])
pyfastaq.utils.close(f)
return contigs_to_use | [
"def",
"_get_contigs_to_use",
"(",
"self",
",",
"contigs_to_use",
")",
":",
"if",
"type",
"(",
"contigs_to_use",
")",
"==",
"set",
":",
"return",
"contigs_to_use",
"elif",
"contigs_to_use",
"is",
"None",
":",
"return",
"set",
"(",
")",
"else",
":",
"f",
"=... | If contigs_to_use is a set, returns that set. If it's None, returns an empty set.
Otherwise, assumes it's a file name, and gets names from the file | [
"If",
"contigs_to_use",
"is",
"a",
"set",
"returns",
"that",
"set",
".",
"If",
"it",
"s",
"None",
"returns",
"an",
"empty",
"set",
".",
"Otherwise",
"assumes",
"it",
"s",
"a",
"file",
"name",
"and",
"gets",
"names",
"from",
"the",
"file"
] | a4befb8c9dbbcd4b3ad1899a95aa3e689d58b638 | https://github.com/sanger-pathogens/circlator/blob/a4befb8c9dbbcd4b3ad1899a95aa3e689d58b638/circlator/bamfilter.py#L46-L57 | train | 211,043 |
sanger-pathogens/circlator | circlator/bamfilter.py | BamFilter._all_reads_from_contig | def _all_reads_from_contig(self, contig, fout):
'''Gets all reads from contig called "contig" and writes to fout'''
sam_reader = pysam.Samfile(self.bam, "rb")
for read in sam_reader.fetch(contig):
print(mapping.aligned_read_to_read(read, ignore_quality=not self.fastq_out), file=fout) | python | def _all_reads_from_contig(self, contig, fout):
'''Gets all reads from contig called "contig" and writes to fout'''
sam_reader = pysam.Samfile(self.bam, "rb")
for read in sam_reader.fetch(contig):
print(mapping.aligned_read_to_read(read, ignore_quality=not self.fastq_out), file=fout) | [
"def",
"_all_reads_from_contig",
"(",
"self",
",",
"contig",
",",
"fout",
")",
":",
"sam_reader",
"=",
"pysam",
".",
"Samfile",
"(",
"self",
".",
"bam",
",",
"\"rb\"",
")",
"for",
"read",
"in",
"sam_reader",
".",
"fetch",
"(",
"contig",
")",
":",
"prin... | Gets all reads from contig called "contig" and writes to fout | [
"Gets",
"all",
"reads",
"from",
"contig",
"called",
"contig",
"and",
"writes",
"to",
"fout"
] | a4befb8c9dbbcd4b3ad1899a95aa3e689d58b638 | https://github.com/sanger-pathogens/circlator/blob/a4befb8c9dbbcd4b3ad1899a95aa3e689d58b638/circlator/bamfilter.py#L73-L77 | train | 211,044 |
sanger-pathogens/circlator | circlator/bamfilter.py | BamFilter._get_all_unmapped_reads | def _get_all_unmapped_reads(self, fout):
'''Writes all unmapped reads to fout'''
sam_reader = pysam.Samfile(self.bam, "rb")
for read in sam_reader.fetch(until_eof=True):
if read.is_unmapped:
print(mapping.aligned_read_to_read(read, ignore_quality=not self.fastq_out), file=fout) | python | def _get_all_unmapped_reads(self, fout):
'''Writes all unmapped reads to fout'''
sam_reader = pysam.Samfile(self.bam, "rb")
for read in sam_reader.fetch(until_eof=True):
if read.is_unmapped:
print(mapping.aligned_read_to_read(read, ignore_quality=not self.fastq_out), file=fout) | [
"def",
"_get_all_unmapped_reads",
"(",
"self",
",",
"fout",
")",
":",
"sam_reader",
"=",
"pysam",
".",
"Samfile",
"(",
"self",
".",
"bam",
",",
"\"rb\"",
")",
"for",
"read",
"in",
"sam_reader",
".",
"fetch",
"(",
"until_eof",
"=",
"True",
")",
":",
"if... | Writes all unmapped reads to fout | [
"Writes",
"all",
"unmapped",
"reads",
"to",
"fout"
] | a4befb8c9dbbcd4b3ad1899a95aa3e689d58b638 | https://github.com/sanger-pathogens/circlator/blob/a4befb8c9dbbcd4b3ad1899a95aa3e689d58b638/circlator/bamfilter.py#L80-L85 | train | 211,045 |
sanger-pathogens/circlator | circlator/bamfilter.py | BamFilter._exclude_region | def _exclude_region(self, contig, start, end, fout):
'''Writes reads not mapping to the given region of contig, start and end as per python convention'''
sam_reader = pysam.Samfile(self.bam, "rb")
exclude_interval = pyfastaq.intervals.Interval(start, end - 1)
for read in sam_reader.fetch(contig):
read_interval = pyfastaq.intervals.Interval(read.pos, read.reference_end - 1)
if not read_interval.intersects(exclude_interval):
print(mapping.aligned_read_to_read(read, ignore_quality=not self.fastq_out), file=fout) | python | def _exclude_region(self, contig, start, end, fout):
'''Writes reads not mapping to the given region of contig, start and end as per python convention'''
sam_reader = pysam.Samfile(self.bam, "rb")
exclude_interval = pyfastaq.intervals.Interval(start, end - 1)
for read in sam_reader.fetch(contig):
read_interval = pyfastaq.intervals.Interval(read.pos, read.reference_end - 1)
if not read_interval.intersects(exclude_interval):
print(mapping.aligned_read_to_read(read, ignore_quality=not self.fastq_out), file=fout) | [
"def",
"_exclude_region",
"(",
"self",
",",
"contig",
",",
"start",
",",
"end",
",",
"fout",
")",
":",
"sam_reader",
"=",
"pysam",
".",
"Samfile",
"(",
"self",
".",
"bam",
",",
"\"rb\"",
")",
"exclude_interval",
"=",
"pyfastaq",
".",
"intervals",
".",
... | Writes reads not mapping to the given region of contig, start and end as per python convention | [
"Writes",
"reads",
"not",
"mapping",
"to",
"the",
"given",
"region",
"of",
"contig",
"start",
"and",
"end",
"as",
"per",
"python",
"convention"
] | a4befb8c9dbbcd4b3ad1899a95aa3e689d58b638 | https://github.com/sanger-pathogens/circlator/blob/a4befb8c9dbbcd4b3ad1899a95aa3e689d58b638/circlator/bamfilter.py#L112-L119 | train | 211,046 |
sanger-pathogens/circlator | circlator/bamfilter.py | BamFilter._get_region | def _get_region(self, contig, start, end, fout, min_length=250):
'''Writes reads mapping to given region of contig, trimming part of read not in the region'''
sam_reader = pysam.Samfile(self.bam, "rb")
trimming_end = (start == 0)
for read in sam_reader.fetch(contig, start, end):
read_interval = pyfastaq.intervals.Interval(read.pos, read.reference_end - 1)
seq = mapping.aligned_read_to_read(read, ignore_quality=not self.fastq_out, revcomp=False)
if trimming_end:
bases_off_start = 0
bases_off_end = max(0, read.reference_end - 1 - end)
#seq.seq = seq.seq[:read.query_alignment_end - bases_off_end]
seq = seq.subseq(0, read.query_alignment_end - bases_off_end)
else:
bases_off_start = max(0, start - read.pos + 1)
#seq.seq = seq.seq[bases_off_start + read.query_alignment_start:]
seq = seq.subseq(bases_off_start + read.query_alignment_start, len(seq))
if read.is_reverse:
seq.revcomp()
if len(seq) >= min_length:
print(seq, file=fout) | python | def _get_region(self, contig, start, end, fout, min_length=250):
'''Writes reads mapping to given region of contig, trimming part of read not in the region'''
sam_reader = pysam.Samfile(self.bam, "rb")
trimming_end = (start == 0)
for read in sam_reader.fetch(contig, start, end):
read_interval = pyfastaq.intervals.Interval(read.pos, read.reference_end - 1)
seq = mapping.aligned_read_to_read(read, ignore_quality=not self.fastq_out, revcomp=False)
if trimming_end:
bases_off_start = 0
bases_off_end = max(0, read.reference_end - 1 - end)
#seq.seq = seq.seq[:read.query_alignment_end - bases_off_end]
seq = seq.subseq(0, read.query_alignment_end - bases_off_end)
else:
bases_off_start = max(0, start - read.pos + 1)
#seq.seq = seq.seq[bases_off_start + read.query_alignment_start:]
seq = seq.subseq(bases_off_start + read.query_alignment_start, len(seq))
if read.is_reverse:
seq.revcomp()
if len(seq) >= min_length:
print(seq, file=fout) | [
"def",
"_get_region",
"(",
"self",
",",
"contig",
",",
"start",
",",
"end",
",",
"fout",
",",
"min_length",
"=",
"250",
")",
":",
"sam_reader",
"=",
"pysam",
".",
"Samfile",
"(",
"self",
".",
"bam",
",",
"\"rb\"",
")",
"trimming_end",
"=",
"(",
"star... | Writes reads mapping to given region of contig, trimming part of read not in the region | [
"Writes",
"reads",
"mapping",
"to",
"given",
"region",
"of",
"contig",
"trimming",
"part",
"of",
"read",
"not",
"in",
"the",
"region"
] | a4befb8c9dbbcd4b3ad1899a95aa3e689d58b638 | https://github.com/sanger-pathogens/circlator/blob/a4befb8c9dbbcd4b3ad1899a95aa3e689d58b638/circlator/bamfilter.py#L122-L144 | train | 211,047 |
sanger-pathogens/circlator | circlator/clean.py | Cleaner._get_contigs_to_keep | def _get_contigs_to_keep(self, filename):
'''Returns a set of names from file called filename. If filename is None, returns an empty set'''
if filename is None:
return set()
with open(filename) as f:
return {line.rstrip() for line in f} | python | def _get_contigs_to_keep(self, filename):
'''Returns a set of names from file called filename. If filename is None, returns an empty set'''
if filename is None:
return set()
with open(filename) as f:
return {line.rstrip() for line in f} | [
"def",
"_get_contigs_to_keep",
"(",
"self",
",",
"filename",
")",
":",
"if",
"filename",
"is",
"None",
":",
"return",
"set",
"(",
")",
"with",
"open",
"(",
"filename",
")",
"as",
"f",
":",
"return",
"{",
"line",
".",
"rstrip",
"(",
")",
"for",
"line"... | Returns a set of names from file called filename. If filename is None, returns an empty set | [
"Returns",
"a",
"set",
"of",
"names",
"from",
"file",
"called",
"filename",
".",
"If",
"filename",
"is",
"None",
"returns",
"an",
"empty",
"set"
] | a4befb8c9dbbcd4b3ad1899a95aa3e689d58b638 | https://github.com/sanger-pathogens/circlator/blob/a4befb8c9dbbcd4b3ad1899a95aa3e689d58b638/circlator/clean.py#L34-L40 | train | 211,048 |
sanger-pathogens/circlator | circlator/clean.py | Cleaner._remove_small_contigs | def _remove_small_contigs(self, infile, outfile, keep=None):
'''Writes a new file with small contigs removed.
Returns lists of all names and names of removed contigs'''
removed = set()
all_names = set()
if keep is None:
keep = set()
file_reader = pyfastaq.sequences.file_reader(infile)
fout = pyfastaq.utils.open_file_write(outfile)
for seq in file_reader:
all_names.add(seq.id)
if len(seq) >= self.min_contig_length or seq.id in keep:
print(seq, file=fout)
else:
removed.add(seq.id)
pyfastaq.utils.close(fout)
return all_names, removed | python | def _remove_small_contigs(self, infile, outfile, keep=None):
'''Writes a new file with small contigs removed.
Returns lists of all names and names of removed contigs'''
removed = set()
all_names = set()
if keep is None:
keep = set()
file_reader = pyfastaq.sequences.file_reader(infile)
fout = pyfastaq.utils.open_file_write(outfile)
for seq in file_reader:
all_names.add(seq.id)
if len(seq) >= self.min_contig_length or seq.id in keep:
print(seq, file=fout)
else:
removed.add(seq.id)
pyfastaq.utils.close(fout)
return all_names, removed | [
"def",
"_remove_small_contigs",
"(",
"self",
",",
"infile",
",",
"outfile",
",",
"keep",
"=",
"None",
")",
":",
"removed",
"=",
"set",
"(",
")",
"all_names",
"=",
"set",
"(",
")",
"if",
"keep",
"is",
"None",
":",
"keep",
"=",
"set",
"(",
")",
"file... | Writes a new file with small contigs removed.
Returns lists of all names and names of removed contigs | [
"Writes",
"a",
"new",
"file",
"with",
"small",
"contigs",
"removed",
".",
"Returns",
"lists",
"of",
"all",
"names",
"and",
"names",
"of",
"removed",
"contigs"
] | a4befb8c9dbbcd4b3ad1899a95aa3e689d58b638 | https://github.com/sanger-pathogens/circlator/blob/a4befb8c9dbbcd4b3ad1899a95aa3e689d58b638/circlator/clean.py#L43-L62 | train | 211,049 |
sanger-pathogens/circlator | circlator/clean.py | Cleaner._containing_contigs | def _containing_contigs(self, hits):
'''Given a list of hits, all with same query,
returns a set of the contigs containing that query'''
return {hit.ref_name for hit in hits if self._contains(hit)} | python | def _containing_contigs(self, hits):
'''Given a list of hits, all with same query,
returns a set of the contigs containing that query'''
return {hit.ref_name for hit in hits if self._contains(hit)} | [
"def",
"_containing_contigs",
"(",
"self",
",",
"hits",
")",
":",
"return",
"{",
"hit",
".",
"ref_name",
"for",
"hit",
"in",
"hits",
"if",
"self",
".",
"_contains",
"(",
"hit",
")",
"}"
] | Given a list of hits, all with same query,
returns a set of the contigs containing that query | [
"Given",
"a",
"list",
"of",
"hits",
"all",
"with",
"same",
"query",
"returns",
"a",
"set",
"of",
"the",
"contigs",
"containing",
"that",
"query"
] | a4befb8c9dbbcd4b3ad1899a95aa3e689d58b638 | https://github.com/sanger-pathogens/circlator/blob/a4befb8c9dbbcd4b3ad1899a95aa3e689d58b638/circlator/clean.py#L112-L115 | train | 211,050 |
sanger-pathogens/circlator | circlator/clean.py | Cleaner._expand_containing_using_transitivity | def _expand_containing_using_transitivity(self, containing_contigs):
'''This uses a contined in b, and b contained in c to force a contained in c.
Just in case a contained in c wasn't already found by nucmer'''
for name in containing_contigs:
containing_contigs[name] = self._get_all_containing(containing_contigs, name)
return containing_contigs | python | def _expand_containing_using_transitivity(self, containing_contigs):
'''This uses a contined in b, and b contained in c to force a contained in c.
Just in case a contained in c wasn't already found by nucmer'''
for name in containing_contigs:
containing_contigs[name] = self._get_all_containing(containing_contigs, name)
return containing_contigs | [
"def",
"_expand_containing_using_transitivity",
"(",
"self",
",",
"containing_contigs",
")",
":",
"for",
"name",
"in",
"containing_contigs",
":",
"containing_contigs",
"[",
"name",
"]",
"=",
"self",
".",
"_get_all_containing",
"(",
"containing_contigs",
",",
"name",
... | This uses a contined in b, and b contained in c to force a contained in c.
Just in case a contained in c wasn't already found by nucmer | [
"This",
"uses",
"a",
"contined",
"in",
"b",
"and",
"b",
"contained",
"in",
"c",
"to",
"force",
"a",
"contained",
"in",
"c",
".",
"Just",
"in",
"case",
"a",
"contained",
"in",
"c",
"wasn",
"t",
"already",
"found",
"by",
"nucmer"
] | a4befb8c9dbbcd4b3ad1899a95aa3e689d58b638 | https://github.com/sanger-pathogens/circlator/blob/a4befb8c9dbbcd4b3ad1899a95aa3e689d58b638/circlator/clean.py#L153-L158 | train | 211,051 |
sanger-pathogens/circlator | circlator/clean.py | Cleaner._collapse_list_of_sets | def _collapse_list_of_sets(self, sets):
'''Input is a list of sets. Merges any intersecting sets in the list'''
found = True
while found:
found = False
to_intersect = None
for i in range(len(sets)):
for j in range(len(sets)):
if i == j:
continue
elif sets[i].intersection(sets[j]):
to_intersect = i, j
break
if to_intersect is not None:
break
if to_intersect is not None:
found = True
sets[i].update(sets[j])
sets.pop(j)
return sets | python | def _collapse_list_of_sets(self, sets):
'''Input is a list of sets. Merges any intersecting sets in the list'''
found = True
while found:
found = False
to_intersect = None
for i in range(len(sets)):
for j in range(len(sets)):
if i == j:
continue
elif sets[i].intersection(sets[j]):
to_intersect = i, j
break
if to_intersect is not None:
break
if to_intersect is not None:
found = True
sets[i].update(sets[j])
sets.pop(j)
return sets | [
"def",
"_collapse_list_of_sets",
"(",
"self",
",",
"sets",
")",
":",
"found",
"=",
"True",
"while",
"found",
":",
"found",
"=",
"False",
"to_intersect",
"=",
"None",
"for",
"i",
"in",
"range",
"(",
"len",
"(",
"sets",
")",
")",
":",
"for",
"j",
"in",... | Input is a list of sets. Merges any intersecting sets in the list | [
"Input",
"is",
"a",
"list",
"of",
"sets",
".",
"Merges",
"any",
"intersecting",
"sets",
"in",
"the",
"list"
] | a4befb8c9dbbcd4b3ad1899a95aa3e689d58b638 | https://github.com/sanger-pathogens/circlator/blob/a4befb8c9dbbcd4b3ad1899a95aa3e689d58b638/circlator/clean.py#L161-L183 | train | 211,052 |
sanger-pathogens/circlator | circlator/clean.py | Cleaner._longest_contig | def _longest_contig(self, contig_set, contig_lengths):
'''Returns the name of the longest contig, from the set of names contig_set. contig_lengths
is expected to be a dictionary of contig name => length.'''
longest_name = None
max_length = -1
for name in contig_set:
if contig_lengths[name] > max_length:
longest_name = name
max_length = contig_lengths[name]
assert max_length != -1
assert longest_name is not None
return longest_name | python | def _longest_contig(self, contig_set, contig_lengths):
'''Returns the name of the longest contig, from the set of names contig_set. contig_lengths
is expected to be a dictionary of contig name => length.'''
longest_name = None
max_length = -1
for name in contig_set:
if contig_lengths[name] > max_length:
longest_name = name
max_length = contig_lengths[name]
assert max_length != -1
assert longest_name is not None
return longest_name | [
"def",
"_longest_contig",
"(",
"self",
",",
"contig_set",
",",
"contig_lengths",
")",
":",
"longest_name",
"=",
"None",
"max_length",
"=",
"-",
"1",
"for",
"name",
"in",
"contig_set",
":",
"if",
"contig_lengths",
"[",
"name",
"]",
">",
"max_length",
":",
"... | Returns the name of the longest contig, from the set of names contig_set. contig_lengths
is expected to be a dictionary of contig name => length. | [
"Returns",
"the",
"name",
"of",
"the",
"longest",
"contig",
"from",
"the",
"set",
"of",
"names",
"contig_set",
".",
"contig_lengths",
"is",
"expected",
"to",
"be",
"a",
"dictionary",
"of",
"contig",
"name",
"=",
">",
"length",
"."
] | a4befb8c9dbbcd4b3ad1899a95aa3e689d58b638 | https://github.com/sanger-pathogens/circlator/blob/a4befb8c9dbbcd4b3ad1899a95aa3e689d58b638/circlator/clean.py#L206-L217 | train | 211,053 |
sanger-pathogens/circlator | circlator/common.py | check_files_exist | def check_files_exist(filenames):
'''Dies if any files in the list of filenames does not exist'''
files_not_found = [x for x in filenames if not os.path.exists(x)]
if len(files_not_found):
for filename in files_not_found:
print('File not found: "', filename, '"', sep='', file=sys.stderr)
raise Error('File(s) not found. Cannot continue') | python | def check_files_exist(filenames):
'''Dies if any files in the list of filenames does not exist'''
files_not_found = [x for x in filenames if not os.path.exists(x)]
if len(files_not_found):
for filename in files_not_found:
print('File not found: "', filename, '"', sep='', file=sys.stderr)
raise Error('File(s) not found. Cannot continue') | [
"def",
"check_files_exist",
"(",
"filenames",
")",
":",
"files_not_found",
"=",
"[",
"x",
"for",
"x",
"in",
"filenames",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"x",
")",
"]",
"if",
"len",
"(",
"files_not_found",
")",
":",
"for",
"filename"... | Dies if any files in the list of filenames does not exist | [
"Dies",
"if",
"any",
"files",
"in",
"the",
"list",
"of",
"filenames",
"does",
"not",
"exist"
] | a4befb8c9dbbcd4b3ad1899a95aa3e689d58b638 | https://github.com/sanger-pathogens/circlator/blob/a4befb8c9dbbcd4b3ad1899a95aa3e689d58b638/circlator/common.py#L45-L51 | train | 211,054 |
sanger-pathogens/circlator | circlator/assembly.py | Assembly.get_contigs | def get_contigs(self):
'''Returns a dictionary of contig_name -> pyfastaq.Sequences.Fasta object'''
contigs = {}
pyfastaq.tasks.file_to_dict(self.contigs_fasta, contigs)
return contigs | python | def get_contigs(self):
'''Returns a dictionary of contig_name -> pyfastaq.Sequences.Fasta object'''
contigs = {}
pyfastaq.tasks.file_to_dict(self.contigs_fasta, contigs)
return contigs | [
"def",
"get_contigs",
"(",
"self",
")",
":",
"contigs",
"=",
"{",
"}",
"pyfastaq",
".",
"tasks",
".",
"file_to_dict",
"(",
"self",
".",
"contigs_fasta",
",",
"contigs",
")",
"return",
"contigs"
] | Returns a dictionary of contig_name -> pyfastaq.Sequences.Fasta object | [
"Returns",
"a",
"dictionary",
"of",
"contig_name",
"-",
">",
"pyfastaq",
".",
"Sequences",
".",
"Fasta",
"object"
] | a4befb8c9dbbcd4b3ad1899a95aa3e689d58b638 | https://github.com/sanger-pathogens/circlator/blob/a4befb8c9dbbcd4b3ad1899a95aa3e689d58b638/circlator/assembly.py#L71-L75 | train | 211,055 |
sanger-pathogens/circlator | circlator/assembly.py | Assembly.circular_contigs | def circular_contigs(self):
'''Returns a set of the contig names that are circular'''
if self.assembler == 'spades':
if self.contigs_fastg is not None:
return self._circular_contigs_from_spades_before_3_6_1(self.contigs_fastg)
elif None not in [self.contigs_paths, self.assembly_graph_fastg]:
return self._circular_contigs_from_spades_after_3_6_1(self.assembly_graph_fastg, self.contigs_paths)
else:
return set()
elif self.assembler == 'canu':
return self._circular_contigs_from_canu_gfa(self.contigs_gfa)
else:
return set() | python | def circular_contigs(self):
'''Returns a set of the contig names that are circular'''
if self.assembler == 'spades':
if self.contigs_fastg is not None:
return self._circular_contigs_from_spades_before_3_6_1(self.contigs_fastg)
elif None not in [self.contigs_paths, self.assembly_graph_fastg]:
return self._circular_contigs_from_spades_after_3_6_1(self.assembly_graph_fastg, self.contigs_paths)
else:
return set()
elif self.assembler == 'canu':
return self._circular_contigs_from_canu_gfa(self.contigs_gfa)
else:
return set() | [
"def",
"circular_contigs",
"(",
"self",
")",
":",
"if",
"self",
".",
"assembler",
"==",
"'spades'",
":",
"if",
"self",
".",
"contigs_fastg",
"is",
"not",
"None",
":",
"return",
"self",
".",
"_circular_contigs_from_spades_before_3_6_1",
"(",
"self",
".",
"conti... | Returns a set of the contig names that are circular | [
"Returns",
"a",
"set",
"of",
"the",
"contig",
"names",
"that",
"are",
"circular"
] | a4befb8c9dbbcd4b3ad1899a95aa3e689d58b638 | https://github.com/sanger-pathogens/circlator/blob/a4befb8c9dbbcd4b3ad1899a95aa3e689d58b638/circlator/assembly.py#L177-L189 | train | 211,056 |
sanger-pathogens/circlator | circlator/merge.py | Merger._run_nucmer | def _run_nucmer(self, ref, qry, outfile):
'''Run nucmer of new assembly vs original assembly'''
n = pymummer.nucmer.Runner(
ref,
qry,
outfile,
min_id=self.nucmer_min_id,
min_length=self.nucmer_min_length,
diagdiff=self.nucmer_diagdiff,
maxmatch=True,
breaklen=self.nucmer_breaklen,
simplify=True,
verbose=self.verbose
)
n.run() | python | def _run_nucmer(self, ref, qry, outfile):
'''Run nucmer of new assembly vs original assembly'''
n = pymummer.nucmer.Runner(
ref,
qry,
outfile,
min_id=self.nucmer_min_id,
min_length=self.nucmer_min_length,
diagdiff=self.nucmer_diagdiff,
maxmatch=True,
breaklen=self.nucmer_breaklen,
simplify=True,
verbose=self.verbose
)
n.run() | [
"def",
"_run_nucmer",
"(",
"self",
",",
"ref",
",",
"qry",
",",
"outfile",
")",
":",
"n",
"=",
"pymummer",
".",
"nucmer",
".",
"Runner",
"(",
"ref",
",",
"qry",
",",
"outfile",
",",
"min_id",
"=",
"self",
".",
"nucmer_min_id",
",",
"min_length",
"=",... | Run nucmer of new assembly vs original assembly | [
"Run",
"nucmer",
"of",
"new",
"assembly",
"vs",
"original",
"assembly"
] | a4befb8c9dbbcd4b3ad1899a95aa3e689d58b638 | https://github.com/sanger-pathogens/circlator/blob/a4befb8c9dbbcd4b3ad1899a95aa3e689d58b638/circlator/merge.py#L71-L85 | train | 211,057 |
sanger-pathogens/circlator | circlator/merge.py | Merger._load_nucmer_hits | def _load_nucmer_hits(self, infile):
'''Returns dict ref name => list of nucmer hits from infile'''
hits = {}
file_reader = pymummer.coords_file.reader(infile)
for al in file_reader:
if al.ref_name not in hits:
hits[al.ref_name] = []
hits[al.ref_name].append(al)
return hits | python | def _load_nucmer_hits(self, infile):
'''Returns dict ref name => list of nucmer hits from infile'''
hits = {}
file_reader = pymummer.coords_file.reader(infile)
for al in file_reader:
if al.ref_name not in hits:
hits[al.ref_name] = []
hits[al.ref_name].append(al)
return hits | [
"def",
"_load_nucmer_hits",
"(",
"self",
",",
"infile",
")",
":",
"hits",
"=",
"{",
"}",
"file_reader",
"=",
"pymummer",
".",
"coords_file",
".",
"reader",
"(",
"infile",
")",
"for",
"al",
"in",
"file_reader",
":",
"if",
"al",
".",
"ref_name",
"not",
"... | Returns dict ref name => list of nucmer hits from infile | [
"Returns",
"dict",
"ref",
"name",
"=",
">",
"list",
"of",
"nucmer",
"hits",
"from",
"infile"
] | a4befb8c9dbbcd4b3ad1899a95aa3e689d58b638 | https://github.com/sanger-pathogens/circlator/blob/a4befb8c9dbbcd4b3ad1899a95aa3e689d58b638/circlator/merge.py#L88-L96 | train | 211,058 |
sanger-pathogens/circlator | circlator/merge.py | Merger._is_at_ref_start | def _is_at_ref_start(self, nucmer_hit):
'''Returns True iff the hit is "close enough" to the start of the reference sequence'''
hit_coords = nucmer_hit.ref_coords()
return hit_coords.start < self.ref_end_tolerance | python | def _is_at_ref_start(self, nucmer_hit):
'''Returns True iff the hit is "close enough" to the start of the reference sequence'''
hit_coords = nucmer_hit.ref_coords()
return hit_coords.start < self.ref_end_tolerance | [
"def",
"_is_at_ref_start",
"(",
"self",
",",
"nucmer_hit",
")",
":",
"hit_coords",
"=",
"nucmer_hit",
".",
"ref_coords",
"(",
")",
"return",
"hit_coords",
".",
"start",
"<",
"self",
".",
"ref_end_tolerance"
] | Returns True iff the hit is "close enough" to the start of the reference sequence | [
"Returns",
"True",
"iff",
"the",
"hit",
"is",
"close",
"enough",
"to",
"the",
"start",
"of",
"the",
"reference",
"sequence"
] | a4befb8c9dbbcd4b3ad1899a95aa3e689d58b638 | https://github.com/sanger-pathogens/circlator/blob/a4befb8c9dbbcd4b3ad1899a95aa3e689d58b638/circlator/merge.py#L125-L128 | train | 211,059 |
sanger-pathogens/circlator | circlator/merge.py | Merger._is_at_ref_end | def _is_at_ref_end(self, nucmer_hit):
'''Returns True iff the hit is "close enough" to the end of the reference sequence'''
hit_coords = nucmer_hit.ref_coords()
return hit_coords.end >= nucmer_hit.ref_length - self.ref_end_tolerance | python | def _is_at_ref_end(self, nucmer_hit):
'''Returns True iff the hit is "close enough" to the end of the reference sequence'''
hit_coords = nucmer_hit.ref_coords()
return hit_coords.end >= nucmer_hit.ref_length - self.ref_end_tolerance | [
"def",
"_is_at_ref_end",
"(",
"self",
",",
"nucmer_hit",
")",
":",
"hit_coords",
"=",
"nucmer_hit",
".",
"ref_coords",
"(",
")",
"return",
"hit_coords",
".",
"end",
">=",
"nucmer_hit",
".",
"ref_length",
"-",
"self",
".",
"ref_end_tolerance"
] | Returns True iff the hit is "close enough" to the end of the reference sequence | [
"Returns",
"True",
"iff",
"the",
"hit",
"is",
"close",
"enough",
"to",
"the",
"end",
"of",
"the",
"reference",
"sequence"
] | a4befb8c9dbbcd4b3ad1899a95aa3e689d58b638 | https://github.com/sanger-pathogens/circlator/blob/a4befb8c9dbbcd4b3ad1899a95aa3e689d58b638/circlator/merge.py#L131-L134 | train | 211,060 |
sanger-pathogens/circlator | circlator/merge.py | Merger._is_at_qry_start | def _is_at_qry_start(self, nucmer_hit):
'''Returns True iff the hit is "close enough" to the start of the query sequence'''
hit_coords = nucmer_hit.qry_coords()
return hit_coords.start < self.qry_end_tolerance | python | def _is_at_qry_start(self, nucmer_hit):
'''Returns True iff the hit is "close enough" to the start of the query sequence'''
hit_coords = nucmer_hit.qry_coords()
return hit_coords.start < self.qry_end_tolerance | [
"def",
"_is_at_qry_start",
"(",
"self",
",",
"nucmer_hit",
")",
":",
"hit_coords",
"=",
"nucmer_hit",
".",
"qry_coords",
"(",
")",
"return",
"hit_coords",
".",
"start",
"<",
"self",
".",
"qry_end_tolerance"
] | Returns True iff the hit is "close enough" to the start of the query sequence | [
"Returns",
"True",
"iff",
"the",
"hit",
"is",
"close",
"enough",
"to",
"the",
"start",
"of",
"the",
"query",
"sequence"
] | a4befb8c9dbbcd4b3ad1899a95aa3e689d58b638 | https://github.com/sanger-pathogens/circlator/blob/a4befb8c9dbbcd4b3ad1899a95aa3e689d58b638/circlator/merge.py#L137-L140 | train | 211,061 |
sanger-pathogens/circlator | circlator/merge.py | Merger._is_at_qry_end | def _is_at_qry_end(self, nucmer_hit):
'''Returns True iff the hit is "close enough" to the end of the query sequence'''
hit_coords = nucmer_hit.qry_coords()
return hit_coords.end >= nucmer_hit.qry_length - self.qry_end_tolerance | python | def _is_at_qry_end(self, nucmer_hit):
'''Returns True iff the hit is "close enough" to the end of the query sequence'''
hit_coords = nucmer_hit.qry_coords()
return hit_coords.end >= nucmer_hit.qry_length - self.qry_end_tolerance | [
"def",
"_is_at_qry_end",
"(",
"self",
",",
"nucmer_hit",
")",
":",
"hit_coords",
"=",
"nucmer_hit",
".",
"qry_coords",
"(",
")",
"return",
"hit_coords",
".",
"end",
">=",
"nucmer_hit",
".",
"qry_length",
"-",
"self",
".",
"qry_end_tolerance"
] | Returns True iff the hit is "close enough" to the end of the query sequence | [
"Returns",
"True",
"iff",
"the",
"hit",
"is",
"close",
"enough",
"to",
"the",
"end",
"of",
"the",
"query",
"sequence"
] | a4befb8c9dbbcd4b3ad1899a95aa3e689d58b638 | https://github.com/sanger-pathogens/circlator/blob/a4befb8c9dbbcd4b3ad1899a95aa3e689d58b638/circlator/merge.py#L143-L146 | train | 211,062 |
sanger-pathogens/circlator | circlator/merge.py | Merger._get_hit_nearest_ref_start | def _get_hit_nearest_ref_start(self, hits):
'''Returns the hit nearest to the start of the ref sequence from the input list of hits'''
nearest_to_start = hits[0]
for hit in hits[1:]:
if hit.ref_coords().start < nearest_to_start.ref_coords().start:
nearest_to_start = hit
return nearest_to_start | python | def _get_hit_nearest_ref_start(self, hits):
'''Returns the hit nearest to the start of the ref sequence from the input list of hits'''
nearest_to_start = hits[0]
for hit in hits[1:]:
if hit.ref_coords().start < nearest_to_start.ref_coords().start:
nearest_to_start = hit
return nearest_to_start | [
"def",
"_get_hit_nearest_ref_start",
"(",
"self",
",",
"hits",
")",
":",
"nearest_to_start",
"=",
"hits",
"[",
"0",
"]",
"for",
"hit",
"in",
"hits",
"[",
"1",
":",
"]",
":",
"if",
"hit",
".",
"ref_coords",
"(",
")",
".",
"start",
"<",
"nearest_to_start... | Returns the hit nearest to the start of the ref sequence from the input list of hits | [
"Returns",
"the",
"hit",
"nearest",
"to",
"the",
"start",
"of",
"the",
"ref",
"sequence",
"from",
"the",
"input",
"list",
"of",
"hits"
] | a4befb8c9dbbcd4b3ad1899a95aa3e689d58b638 | https://github.com/sanger-pathogens/circlator/blob/a4befb8c9dbbcd4b3ad1899a95aa3e689d58b638/circlator/merge.py#L149-L155 | train | 211,063 |
sanger-pathogens/circlator | circlator/merge.py | Merger._get_hit_nearest_ref_end | def _get_hit_nearest_ref_end(self, hits):
'''Returns the hit nearest to the end of the ref sequence from the input list of hits'''
nearest_to_end = hits[0]
for hit in hits[1:]:
if hit.ref_coords().end > nearest_to_end.ref_coords().end:
nearest_to_end = hit
return nearest_to_end | python | def _get_hit_nearest_ref_end(self, hits):
'''Returns the hit nearest to the end of the ref sequence from the input list of hits'''
nearest_to_end = hits[0]
for hit in hits[1:]:
if hit.ref_coords().end > nearest_to_end.ref_coords().end:
nearest_to_end = hit
return nearest_to_end | [
"def",
"_get_hit_nearest_ref_end",
"(",
"self",
",",
"hits",
")",
":",
"nearest_to_end",
"=",
"hits",
"[",
"0",
"]",
"for",
"hit",
"in",
"hits",
"[",
"1",
":",
"]",
":",
"if",
"hit",
".",
"ref_coords",
"(",
")",
".",
"end",
">",
"nearest_to_end",
"."... | Returns the hit nearest to the end of the ref sequence from the input list of hits | [
"Returns",
"the",
"hit",
"nearest",
"to",
"the",
"end",
"of",
"the",
"ref",
"sequence",
"from",
"the",
"input",
"list",
"of",
"hits"
] | a4befb8c9dbbcd4b3ad1899a95aa3e689d58b638 | https://github.com/sanger-pathogens/circlator/blob/a4befb8c9dbbcd4b3ad1899a95aa3e689d58b638/circlator/merge.py#L158-L164 | train | 211,064 |
sanger-pathogens/circlator | circlator/merge.py | Merger._has_qry_hit_longer_than | def _has_qry_hit_longer_than(self, nucmer_hits, min_length, hits_to_exclude=None):
'''Returns True iff list of nucmer_hits has a hit longer than min_length, not counting the hits in hits_to_exclude'''
if hits_to_exclude is None:
to_exclude = set()
else:
to_exclude = hits_to_exclude
long_hits = [hit.hit_length_qry for hit in nucmer_hits if hit not in to_exclude and hit.hit_length_qry > min_length]
return len(long_hits) > 0 | python | def _has_qry_hit_longer_than(self, nucmer_hits, min_length, hits_to_exclude=None):
'''Returns True iff list of nucmer_hits has a hit longer than min_length, not counting the hits in hits_to_exclude'''
if hits_to_exclude is None:
to_exclude = set()
else:
to_exclude = hits_to_exclude
long_hits = [hit.hit_length_qry for hit in nucmer_hits if hit not in to_exclude and hit.hit_length_qry > min_length]
return len(long_hits) > 0 | [
"def",
"_has_qry_hit_longer_than",
"(",
"self",
",",
"nucmer_hits",
",",
"min_length",
",",
"hits_to_exclude",
"=",
"None",
")",
":",
"if",
"hits_to_exclude",
"is",
"None",
":",
"to_exclude",
"=",
"set",
"(",
")",
"else",
":",
"to_exclude",
"=",
"hits_to_exclu... | Returns True iff list of nucmer_hits has a hit longer than min_length, not counting the hits in hits_to_exclude | [
"Returns",
"True",
"iff",
"list",
"of",
"nucmer_hits",
"has",
"a",
"hit",
"longer",
"than",
"min_length",
"not",
"counting",
"the",
"hits",
"in",
"hits_to_exclude"
] | a4befb8c9dbbcd4b3ad1899a95aa3e689d58b638 | https://github.com/sanger-pathogens/circlator/blob/a4befb8c9dbbcd4b3ad1899a95aa3e689d58b638/circlator/merge.py#L210-L217 | train | 211,065 |
sanger-pathogens/circlator | circlator/merge.py | Merger._can_circularise | def _can_circularise(self, start_hit, end_hit):
'''Returns true iff the two hits can be used to circularise the reference sequence of the hits'''
if not(self._is_at_ref_start(start_hit) or self._is_at_ref_end(end_hit)):
return False
if self._is_at_qry_end(start_hit) \
and self._is_at_qry_start(end_hit) \
and start_hit.on_same_strand() \
and end_hit.on_same_strand():
return True
if self._is_at_qry_start(start_hit) \
and self._is_at_qry_end(end_hit) \
and (not start_hit.on_same_strand()) \
and (not end_hit.on_same_strand()):
return True
return False | python | def _can_circularise(self, start_hit, end_hit):
'''Returns true iff the two hits can be used to circularise the reference sequence of the hits'''
if not(self._is_at_ref_start(start_hit) or self._is_at_ref_end(end_hit)):
return False
if self._is_at_qry_end(start_hit) \
and self._is_at_qry_start(end_hit) \
and start_hit.on_same_strand() \
and end_hit.on_same_strand():
return True
if self._is_at_qry_start(start_hit) \
and self._is_at_qry_end(end_hit) \
and (not start_hit.on_same_strand()) \
and (not end_hit.on_same_strand()):
return True
return False | [
"def",
"_can_circularise",
"(",
"self",
",",
"start_hit",
",",
"end_hit",
")",
":",
"if",
"not",
"(",
"self",
".",
"_is_at_ref_start",
"(",
"start_hit",
")",
"or",
"self",
".",
"_is_at_ref_end",
"(",
"end_hit",
")",
")",
":",
"return",
"False",
"if",
"se... | Returns true iff the two hits can be used to circularise the reference sequence of the hits | [
"Returns",
"true",
"iff",
"the",
"two",
"hits",
"can",
"be",
"used",
"to",
"circularise",
"the",
"reference",
"sequence",
"of",
"the",
"hits"
] | a4befb8c9dbbcd4b3ad1899a95aa3e689d58b638 | https://github.com/sanger-pathogens/circlator/blob/a4befb8c9dbbcd4b3ad1899a95aa3e689d58b638/circlator/merge.py#L220-L237 | train | 211,066 |
sanger-pathogens/circlator | circlator/merge.py | Merger._remove_keys_from_dict_with_nonunique_values | def _remove_keys_from_dict_with_nonunique_values(self, d, log_fh=None, log_outprefix=None):
'''Returns a new dictionary, with keys from input dict removed if their value was not unique'''
value_counts = collections.Counter(d.values())
new_d = {}
writing_log_file = None not in [log_fh, log_outprefix]
for key in d:
if value_counts[d[key]] == 1:
new_d[key] = d[key]
elif writing_log_file:
print(log_outprefix, 'Reject because non-unique:', d[key], sep='\t', file=log_fh)
return new_d | python | def _remove_keys_from_dict_with_nonunique_values(self, d, log_fh=None, log_outprefix=None):
'''Returns a new dictionary, with keys from input dict removed if their value was not unique'''
value_counts = collections.Counter(d.values())
new_d = {}
writing_log_file = None not in [log_fh, log_outprefix]
for key in d:
if value_counts[d[key]] == 1:
new_d[key] = d[key]
elif writing_log_file:
print(log_outprefix, 'Reject because non-unique:', d[key], sep='\t', file=log_fh)
return new_d | [
"def",
"_remove_keys_from_dict_with_nonunique_values",
"(",
"self",
",",
"d",
",",
"log_fh",
"=",
"None",
",",
"log_outprefix",
"=",
"None",
")",
":",
"value_counts",
"=",
"collections",
".",
"Counter",
"(",
"d",
".",
"values",
"(",
")",
")",
"new_d",
"=",
... | Returns a new dictionary, with keys from input dict removed if their value was not unique | [
"Returns",
"a",
"new",
"dictionary",
"with",
"keys",
"from",
"input",
"dict",
"removed",
"if",
"their",
"value",
"was",
"not",
"unique"
] | a4befb8c9dbbcd4b3ad1899a95aa3e689d58b638 | https://github.com/sanger-pathogens/circlator/blob/a4befb8c9dbbcd4b3ad1899a95aa3e689d58b638/circlator/merge.py#L296-L308 | train | 211,067 |
sanger-pathogens/circlator | circlator/merge.py | Merger._make_circularised_contig | def _make_circularised_contig(self, ref_start_hit, ref_end_hit):
'''Given a nucmer ref_start_hit and ref_end_hit, returns a new contig. Assumes that these hits can be used to circularise the reference contig of the hits using the query contig'''
assert ref_start_hit.ref_name == ref_end_hit.ref_name
assert ref_start_hit.qry_name == ref_end_hit.qry_name
qry_name = ref_start_hit.qry_name
ref_name = ref_start_hit.ref_name
ref_start_coords = ref_start_hit.ref_coords()
ref_end_coords = ref_end_hit.ref_coords()
if ref_start_coords.intersects(ref_end_coords):
new_ctg = copy.copy(self.reassembly_contigs[qry_name])
new_ctg.id = ref_name
return new_ctg
if ref_start_hit.on_same_strand():
qry_start_coords = ref_end_hit.qry_coords()
qry_end_coords = ref_start_hit.qry_coords()
bases = self.original_contigs[ref_name][ref_start_coords.end+1:ref_end_coords.start] + \
self.reassembly_contigs[qry_name][qry_start_coords.start:qry_end_coords.end+1]
return pyfastaq.sequences.Fasta(ref_name, bases)
else:
qry_start_coords = ref_start_hit.qry_coords()
qry_end_coords = ref_end_hit.qry_coords()
tmp_seq = pyfastaq.sequences.Fasta('x', self.reassembly_contigs[qry_name][qry_start_coords.start:qry_end_coords.end+1])
tmp_seq.revcomp()
return pyfastaq.sequences.Fasta(ref_name, self.original_contigs[ref_name][ref_start_coords.end+1:ref_end_coords.start] + tmp_seq.seq) | python | def _make_circularised_contig(self, ref_start_hit, ref_end_hit):
'''Given a nucmer ref_start_hit and ref_end_hit, returns a new contig. Assumes that these hits can be used to circularise the reference contig of the hits using the query contig'''
assert ref_start_hit.ref_name == ref_end_hit.ref_name
assert ref_start_hit.qry_name == ref_end_hit.qry_name
qry_name = ref_start_hit.qry_name
ref_name = ref_start_hit.ref_name
ref_start_coords = ref_start_hit.ref_coords()
ref_end_coords = ref_end_hit.ref_coords()
if ref_start_coords.intersects(ref_end_coords):
new_ctg = copy.copy(self.reassembly_contigs[qry_name])
new_ctg.id = ref_name
return new_ctg
if ref_start_hit.on_same_strand():
qry_start_coords = ref_end_hit.qry_coords()
qry_end_coords = ref_start_hit.qry_coords()
bases = self.original_contigs[ref_name][ref_start_coords.end+1:ref_end_coords.start] + \
self.reassembly_contigs[qry_name][qry_start_coords.start:qry_end_coords.end+1]
return pyfastaq.sequences.Fasta(ref_name, bases)
else:
qry_start_coords = ref_start_hit.qry_coords()
qry_end_coords = ref_end_hit.qry_coords()
tmp_seq = pyfastaq.sequences.Fasta('x', self.reassembly_contigs[qry_name][qry_start_coords.start:qry_end_coords.end+1])
tmp_seq.revcomp()
return pyfastaq.sequences.Fasta(ref_name, self.original_contigs[ref_name][ref_start_coords.end+1:ref_end_coords.start] + tmp_seq.seq) | [
"def",
"_make_circularised_contig",
"(",
"self",
",",
"ref_start_hit",
",",
"ref_end_hit",
")",
":",
"assert",
"ref_start_hit",
".",
"ref_name",
"==",
"ref_end_hit",
".",
"ref_name",
"assert",
"ref_start_hit",
".",
"qry_name",
"==",
"ref_end_hit",
".",
"qry_name",
... | Given a nucmer ref_start_hit and ref_end_hit, returns a new contig. Assumes that these hits can be used to circularise the reference contig of the hits using the query contig | [
"Given",
"a",
"nucmer",
"ref_start_hit",
"and",
"ref_end_hit",
"returns",
"a",
"new",
"contig",
".",
"Assumes",
"that",
"these",
"hits",
"can",
"be",
"used",
"to",
"circularise",
"the",
"reference",
"contig",
"of",
"the",
"hits",
"using",
"the",
"query",
"co... | a4befb8c9dbbcd4b3ad1899a95aa3e689d58b638 | https://github.com/sanger-pathogens/circlator/blob/a4befb8c9dbbcd4b3ad1899a95aa3e689d58b638/circlator/merge.py#L311-L338 | train | 211,068 |
sanger-pathogens/circlator | circlator/merge.py | Merger._orientation_ok_to_bridge_contigs | def _orientation_ok_to_bridge_contigs(self, start_hit, end_hit):
'''Returns True iff the orientation of the hits means that the query contig of both hits can bridge the reference contigs of the hits'''
assert start_hit.qry_name == end_hit.qry_name
if start_hit.ref_name == end_hit.ref_name:
return False
if (
(self._is_at_ref_end(start_hit) and start_hit.on_same_strand())
or (self._is_at_ref_start(start_hit) and not start_hit.on_same_strand())
):
start_hit_ok = True
else:
start_hit_ok = False
if (
(self._is_at_ref_start(end_hit) and end_hit.on_same_strand())
or (self._is_at_ref_end(end_hit) and not end_hit.on_same_strand())
):
end_hit_ok = True
else:
end_hit_ok = False
return start_hit_ok and end_hit_ok | python | def _orientation_ok_to_bridge_contigs(self, start_hit, end_hit):
'''Returns True iff the orientation of the hits means that the query contig of both hits can bridge the reference contigs of the hits'''
assert start_hit.qry_name == end_hit.qry_name
if start_hit.ref_name == end_hit.ref_name:
return False
if (
(self._is_at_ref_end(start_hit) and start_hit.on_same_strand())
or (self._is_at_ref_start(start_hit) and not start_hit.on_same_strand())
):
start_hit_ok = True
else:
start_hit_ok = False
if (
(self._is_at_ref_start(end_hit) and end_hit.on_same_strand())
or (self._is_at_ref_end(end_hit) and not end_hit.on_same_strand())
):
end_hit_ok = True
else:
end_hit_ok = False
return start_hit_ok and end_hit_ok | [
"def",
"_orientation_ok_to_bridge_contigs",
"(",
"self",
",",
"start_hit",
",",
"end_hit",
")",
":",
"assert",
"start_hit",
".",
"qry_name",
"==",
"end_hit",
".",
"qry_name",
"if",
"start_hit",
".",
"ref_name",
"==",
"end_hit",
".",
"ref_name",
":",
"return",
... | Returns True iff the orientation of the hits means that the query contig of both hits can bridge the reference contigs of the hits | [
"Returns",
"True",
"iff",
"the",
"orientation",
"of",
"the",
"hits",
"means",
"that",
"the",
"query",
"contig",
"of",
"both",
"hits",
"can",
"bridge",
"the",
"reference",
"contigs",
"of",
"the",
"hits"
] | a4befb8c9dbbcd4b3ad1899a95aa3e689d58b638 | https://github.com/sanger-pathogens/circlator/blob/a4befb8c9dbbcd4b3ad1899a95aa3e689d58b638/circlator/merge.py#L451-L473 | train | 211,069 |
sanger-pathogens/circlator | circlator/merge.py | Merger._merge_all_bridged_contigs | def _merge_all_bridged_contigs(self, nucmer_hits, ref_contigs, qry_contigs, log_fh=None, log_outprefix=None):
'''Input is dict of nucmer_hits. Makes any possible contig merges.
Returns True iff any merges were made'''
writing_log_file = None not in [log_fh, log_outprefix]
if len(nucmer_hits) == 0:
if writing_log_file:
print(log_outprefix, 'No nucmer hits, so will not make any merges', sep='\t', file=log_fh)
return
all_nucmer_hits = []
for l in nucmer_hits.values():
all_nucmer_hits.extend(l)
nucmer_hits_by_qry = self._hits_hashed_by_query(all_nucmer_hits)
bridges = self._get_possible_query_bridging_contigs(nucmer_hits_by_qry, log_fh=log_fh, log_outprefix=log_outprefix)
if writing_log_file:
print(log_outprefix, '\tPotential contigs to use for merging: ', ' '.join(sorted(bridges.keys())), sep='', file=log_fh)
bridges = self._filter_bridging_contigs(bridges)
if writing_log_file:
print(log_outprefix, '\tContigs to use for merging after uniqueness filtering: ', ' '.join(sorted(bridges.keys())), sep='', file=log_fh)
merged = set()
made_a_join = False
for qry_name, (start_hit, end_hit) in bridges.items():
if start_hit.ref_name in merged or end_hit.ref_name in merged:
continue
self._merge_bridged_contig_pair(start_hit, end_hit, ref_contigs, qry_contigs, log_fh=log_fh, log_outprefix=log_outprefix)
merged.add(start_hit.ref_name)
merged.add(end_hit.ref_name)
made_a_join = True
if writing_log_file:
print(log_outprefix, '\tMade at least one contig join: ', made_a_join, sep='', file=log_fh)
return made_a_join | python | def _merge_all_bridged_contigs(self, nucmer_hits, ref_contigs, qry_contigs, log_fh=None, log_outprefix=None):
'''Input is dict of nucmer_hits. Makes any possible contig merges.
Returns True iff any merges were made'''
writing_log_file = None not in [log_fh, log_outprefix]
if len(nucmer_hits) == 0:
if writing_log_file:
print(log_outprefix, 'No nucmer hits, so will not make any merges', sep='\t', file=log_fh)
return
all_nucmer_hits = []
for l in nucmer_hits.values():
all_nucmer_hits.extend(l)
nucmer_hits_by_qry = self._hits_hashed_by_query(all_nucmer_hits)
bridges = self._get_possible_query_bridging_contigs(nucmer_hits_by_qry, log_fh=log_fh, log_outprefix=log_outprefix)
if writing_log_file:
print(log_outprefix, '\tPotential contigs to use for merging: ', ' '.join(sorted(bridges.keys())), sep='', file=log_fh)
bridges = self._filter_bridging_contigs(bridges)
if writing_log_file:
print(log_outprefix, '\tContigs to use for merging after uniqueness filtering: ', ' '.join(sorted(bridges.keys())), sep='', file=log_fh)
merged = set()
made_a_join = False
for qry_name, (start_hit, end_hit) in bridges.items():
if start_hit.ref_name in merged or end_hit.ref_name in merged:
continue
self._merge_bridged_contig_pair(start_hit, end_hit, ref_contigs, qry_contigs, log_fh=log_fh, log_outprefix=log_outprefix)
merged.add(start_hit.ref_name)
merged.add(end_hit.ref_name)
made_a_join = True
if writing_log_file:
print(log_outprefix, '\tMade at least one contig join: ', made_a_join, sep='', file=log_fh)
return made_a_join | [
"def",
"_merge_all_bridged_contigs",
"(",
"self",
",",
"nucmer_hits",
",",
"ref_contigs",
",",
"qry_contigs",
",",
"log_fh",
"=",
"None",
",",
"log_outprefix",
"=",
"None",
")",
":",
"writing_log_file",
"=",
"None",
"not",
"in",
"[",
"log_fh",
",",
"log_outpre... | Input is dict of nucmer_hits. Makes any possible contig merges.
Returns True iff any merges were made | [
"Input",
"is",
"dict",
"of",
"nucmer_hits",
".",
"Makes",
"any",
"possible",
"contig",
"merges",
".",
"Returns",
"True",
"iff",
"any",
"merges",
"were",
"made"
] | a4befb8c9dbbcd4b3ad1899a95aa3e689d58b638 | https://github.com/sanger-pathogens/circlator/blob/a4befb8c9dbbcd4b3ad1899a95aa3e689d58b638/circlator/merge.py#L591-L626 | train | 211,070 |
sanger-pathogens/circlator | circlator/merge.py | Merger._write_act_files | def _write_act_files(self, ref_fasta, qry_fasta, coords_file, outprefix):
'''Writes crunch file and shell script to start up ACT, showing comparison of ref and qry'''
if self.verbose:
print('Making ACT files from', ref_fasta, qry_fasta, coords_file)
ref_fasta = os.path.relpath(ref_fasta)
qry_fasta = os.path.relpath(qry_fasta)
coords_file = os.path.relpath(coords_file)
outprefix = os.path.relpath(outprefix)
self._index_fasta(ref_fasta)
self._index_fasta(qry_fasta)
crunch_file = outprefix + '.crunch'
pymummer.coords_file.convert_to_msp_crunch(
coords_file,
crunch_file,
ref_fai=ref_fasta + '.fai',
qry_fai=qry_fasta + '.fai'
)
bash_script = outprefix + '.start_act.sh'
with open(bash_script, 'w') as f:
print('#!/usr/bin/env bash', file=f)
print('act', ref_fasta, crunch_file, qry_fasta, file=f)
pyfastaq.utils.syscall('chmod +x ' + bash_script) | python | def _write_act_files(self, ref_fasta, qry_fasta, coords_file, outprefix):
'''Writes crunch file and shell script to start up ACT, showing comparison of ref and qry'''
if self.verbose:
print('Making ACT files from', ref_fasta, qry_fasta, coords_file)
ref_fasta = os.path.relpath(ref_fasta)
qry_fasta = os.path.relpath(qry_fasta)
coords_file = os.path.relpath(coords_file)
outprefix = os.path.relpath(outprefix)
self._index_fasta(ref_fasta)
self._index_fasta(qry_fasta)
crunch_file = outprefix + '.crunch'
pymummer.coords_file.convert_to_msp_crunch(
coords_file,
crunch_file,
ref_fai=ref_fasta + '.fai',
qry_fai=qry_fasta + '.fai'
)
bash_script = outprefix + '.start_act.sh'
with open(bash_script, 'w') as f:
print('#!/usr/bin/env bash', file=f)
print('act', ref_fasta, crunch_file, qry_fasta, file=f)
pyfastaq.utils.syscall('chmod +x ' + bash_script) | [
"def",
"_write_act_files",
"(",
"self",
",",
"ref_fasta",
",",
"qry_fasta",
",",
"coords_file",
",",
"outprefix",
")",
":",
"if",
"self",
".",
"verbose",
":",
"print",
"(",
"'Making ACT files from'",
",",
"ref_fasta",
",",
"qry_fasta",
",",
"coords_file",
")",... | Writes crunch file and shell script to start up ACT, showing comparison of ref and qry | [
"Writes",
"crunch",
"file",
"and",
"shell",
"script",
"to",
"start",
"up",
"ACT",
"showing",
"comparison",
"of",
"ref",
"and",
"qry"
] | a4befb8c9dbbcd4b3ad1899a95aa3e689d58b638 | https://github.com/sanger-pathogens/circlator/blob/a4befb8c9dbbcd4b3ad1899a95aa3e689d58b638/circlator/merge.py#L636-L659 | train | 211,071 |
sanger-pathogens/circlator | circlator/merge.py | Merger._contigs_dict_to_file | def _contigs_dict_to_file(self, contigs, fname):
'''Writes dictionary of contigs to file'''
f = pyfastaq.utils.open_file_write(fname)
for contig in sorted(contigs, key=lambda x:len(contigs[x]), reverse=True):
print(contigs[contig], file=f)
pyfastaq.utils.close(f) | python | def _contigs_dict_to_file(self, contigs, fname):
'''Writes dictionary of contigs to file'''
f = pyfastaq.utils.open_file_write(fname)
for contig in sorted(contigs, key=lambda x:len(contigs[x]), reverse=True):
print(contigs[contig], file=f)
pyfastaq.utils.close(f) | [
"def",
"_contigs_dict_to_file",
"(",
"self",
",",
"contigs",
",",
"fname",
")",
":",
"f",
"=",
"pyfastaq",
".",
"utils",
".",
"open_file_write",
"(",
"fname",
")",
"for",
"contig",
"in",
"sorted",
"(",
"contigs",
",",
"key",
"=",
"lambda",
"x",
":",
"l... | Writes dictionary of contigs to file | [
"Writes",
"dictionary",
"of",
"contigs",
"to",
"file"
] | a4befb8c9dbbcd4b3ad1899a95aa3e689d58b638 | https://github.com/sanger-pathogens/circlator/blob/a4befb8c9dbbcd4b3ad1899a95aa3e689d58b638/circlator/merge.py#L732-L737 | train | 211,072 |
sanger-pathogens/circlator | circlator/merge.py | Merger._get_spades_circular_nodes | def _get_spades_circular_nodes(self, fastg):
'''Returns set of names of nodes in SPAdes fastg file that are circular. Names will match those in spades fasta file'''
seq_reader = pyfastaq.sequences.file_reader(fastg)
names = set([x.id.rstrip(';') for x in seq_reader if ':' in x.id])
found_fwd = set()
found_rev = set()
for name in names:
l = name.split(':')
if len(l) != 2:
continue
if l[0] == l[1]:
if l[0][-1] == "'":
found_rev.add(l[0][:-1])
else:
found_fwd.add(l[0])
return found_fwd.intersection(found_rev) | python | def _get_spades_circular_nodes(self, fastg):
'''Returns set of names of nodes in SPAdes fastg file that are circular. Names will match those in spades fasta file'''
seq_reader = pyfastaq.sequences.file_reader(fastg)
names = set([x.id.rstrip(';') for x in seq_reader if ':' in x.id])
found_fwd = set()
found_rev = set()
for name in names:
l = name.split(':')
if len(l) != 2:
continue
if l[0] == l[1]:
if l[0][-1] == "'":
found_rev.add(l[0][:-1])
else:
found_fwd.add(l[0])
return found_fwd.intersection(found_rev) | [
"def",
"_get_spades_circular_nodes",
"(",
"self",
",",
"fastg",
")",
":",
"seq_reader",
"=",
"pyfastaq",
".",
"sequences",
".",
"file_reader",
"(",
"fastg",
")",
"names",
"=",
"set",
"(",
"[",
"x",
".",
"id",
".",
"rstrip",
"(",
"';'",
")",
"for",
"x",... | Returns set of names of nodes in SPAdes fastg file that are circular. Names will match those in spades fasta file | [
"Returns",
"set",
"of",
"names",
"of",
"nodes",
"in",
"SPAdes",
"fastg",
"file",
"that",
"are",
"circular",
".",
"Names",
"will",
"match",
"those",
"in",
"spades",
"fasta",
"file"
] | a4befb8c9dbbcd4b3ad1899a95aa3e689d58b638 | https://github.com/sanger-pathogens/circlator/blob/a4befb8c9dbbcd4b3ad1899a95aa3e689d58b638/circlator/merge.py#L740-L756 | train | 211,073 |
sanger-pathogens/circlator | circlator/merge.py | Merger._make_new_contig_from_nucmer_and_spades | def _make_new_contig_from_nucmer_and_spades(self, original_contig, hits, circular_spades, log_fh=None, log_outprefix=None):
'''Tries to make new circularised contig from contig called original_contig. hits = list of nucmer hits, all with ref=original contg. circular_spades=set of query contig names that spades says are circular'''
writing_log_file = None not in [log_fh, log_outprefix]
hits_to_circular_contigs = [x for x in hits if x.qry_name in circular_spades]
if len(hits_to_circular_contigs) == 0:
if writing_log_file:
print(log_outprefix, original_contig, 'No matches to SPAdes circular contigs', sep='\t', file=log_fh)
return None, None
for hit in hits_to_circular_contigs:
print(log_outprefix, original_contig, 'Checking hit:', hit, sep='\t', file=log_fh)
percent_query_covered = 100 * (hit.hit_length_qry / hit.qry_length)
if self.min_spades_circular_percent <= percent_query_covered:
print(log_outprefix, '\t', original_contig, '\t\tHit is long enough. Percent of contig covered by hit is ', percent_query_covered, sep='', file=log_fh)
# the spades contig hit is long enough, but now check that
# the input contig is covered by hits from this spades contig
hit_intervals = [x.ref_coords() for x in hits_to_circular_contigs if x.qry_name == hit.qry_name]
if len(hit_intervals) > 0:
pyfastaq.intervals.merge_overlapping_in_list(hit_intervals)
percent_covered = 100 * pyfastaq.intervals.length_sum_from_list(hit_intervals) / hit.ref_length
if writing_log_file:
print(log_outprefix, '\t', original_contig, '\t\treference bases covered by spades contig:', ', '.join([str(x) for x in hit_intervals]), sep='', file=log_fh)
print(log_outprefix, '\t', original_contig, '\t\t ... which is ', percent_covered, ' percent of ', hit.ref_length, ' bases', sep='', file=log_fh)
if self.min_spades_circular_percent <= percent_covered:
if writing_log_file:
print(log_outprefix, original_contig, '\tUsing hit to call as circular (enough bases covered)', sep='\t', file=log_fh)
return pyfastaq.sequences.Fasta(original_contig, self.reassembly_contigs[hit.qry_name].seq), hit.qry_name
elif writing_log_file:
print(log_outprefix, original_contig, '\tNot using hit to call as circular (not enough bases covered)', sep='\t', file=log_fh)
else:
print(log_outprefix, original_contig, '\tNot using hit to call as circular (hit too short)', sep='\t', file=log_fh)
if writing_log_file:
print(log_outprefix, original_contig, 'No suitable matches to SPAdes circular contigs', sep='\t', file=log_fh)
return None, None | python | def _make_new_contig_from_nucmer_and_spades(self, original_contig, hits, circular_spades, log_fh=None, log_outprefix=None):
'''Tries to make new circularised contig from contig called original_contig. hits = list of nucmer hits, all with ref=original contg. circular_spades=set of query contig names that spades says are circular'''
writing_log_file = None not in [log_fh, log_outprefix]
hits_to_circular_contigs = [x for x in hits if x.qry_name in circular_spades]
if len(hits_to_circular_contigs) == 0:
if writing_log_file:
print(log_outprefix, original_contig, 'No matches to SPAdes circular contigs', sep='\t', file=log_fh)
return None, None
for hit in hits_to_circular_contigs:
print(log_outprefix, original_contig, 'Checking hit:', hit, sep='\t', file=log_fh)
percent_query_covered = 100 * (hit.hit_length_qry / hit.qry_length)
if self.min_spades_circular_percent <= percent_query_covered:
print(log_outprefix, '\t', original_contig, '\t\tHit is long enough. Percent of contig covered by hit is ', percent_query_covered, sep='', file=log_fh)
# the spades contig hit is long enough, but now check that
# the input contig is covered by hits from this spades contig
hit_intervals = [x.ref_coords() for x in hits_to_circular_contigs if x.qry_name == hit.qry_name]
if len(hit_intervals) > 0:
pyfastaq.intervals.merge_overlapping_in_list(hit_intervals)
percent_covered = 100 * pyfastaq.intervals.length_sum_from_list(hit_intervals) / hit.ref_length
if writing_log_file:
print(log_outprefix, '\t', original_contig, '\t\treference bases covered by spades contig:', ', '.join([str(x) for x in hit_intervals]), sep='', file=log_fh)
print(log_outprefix, '\t', original_contig, '\t\t ... which is ', percent_covered, ' percent of ', hit.ref_length, ' bases', sep='', file=log_fh)
if self.min_spades_circular_percent <= percent_covered:
if writing_log_file:
print(log_outprefix, original_contig, '\tUsing hit to call as circular (enough bases covered)', sep='\t', file=log_fh)
return pyfastaq.sequences.Fasta(original_contig, self.reassembly_contigs[hit.qry_name].seq), hit.qry_name
elif writing_log_file:
print(log_outprefix, original_contig, '\tNot using hit to call as circular (not enough bases covered)', sep='\t', file=log_fh)
else:
print(log_outprefix, original_contig, '\tNot using hit to call as circular (hit too short)', sep='\t', file=log_fh)
if writing_log_file:
print(log_outprefix, original_contig, 'No suitable matches to SPAdes circular contigs', sep='\t', file=log_fh)
return None, None | [
"def",
"_make_new_contig_from_nucmer_and_spades",
"(",
"self",
",",
"original_contig",
",",
"hits",
",",
"circular_spades",
",",
"log_fh",
"=",
"None",
",",
"log_outprefix",
"=",
"None",
")",
":",
"writing_log_file",
"=",
"None",
"not",
"in",
"[",
"log_fh",
",",... | Tries to make new circularised contig from contig called original_contig. hits = list of nucmer hits, all with ref=original contg. circular_spades=set of query contig names that spades says are circular | [
"Tries",
"to",
"make",
"new",
"circularised",
"contig",
"from",
"contig",
"called",
"original_contig",
".",
"hits",
"=",
"list",
"of",
"nucmer",
"hits",
"all",
"with",
"ref",
"=",
"original",
"contg",
".",
"circular_spades",
"=",
"set",
"of",
"query",
"conti... | a4befb8c9dbbcd4b3ad1899a95aa3e689d58b638 | https://github.com/sanger-pathogens/circlator/blob/a4befb8c9dbbcd4b3ad1899a95aa3e689d58b638/circlator/merge.py#L759-L799 | train | 211,074 |
matiasb/python-unidiff | unidiff/patch.py | PatchedFile._parse_hunk | def _parse_hunk(self, header, diff, encoding):
"""Parse hunk details."""
header_info = RE_HUNK_HEADER.match(header)
hunk_info = header_info.groups()
hunk = Hunk(*hunk_info)
source_line_no = hunk.source_start
target_line_no = hunk.target_start
expected_source_end = source_line_no + hunk.source_length
expected_target_end = target_line_no + hunk.target_length
for diff_line_no, line in diff:
if encoding is not None:
line = line.decode(encoding)
valid_line = RE_HUNK_EMPTY_BODY_LINE.match(line)
if not valid_line:
valid_line = RE_HUNK_BODY_LINE.match(line)
if not valid_line:
raise UnidiffParseError('Hunk diff line expected: %s' % line)
line_type = valid_line.group('line_type')
if line_type == LINE_TYPE_EMPTY:
line_type = LINE_TYPE_CONTEXT
value = valid_line.group('value')
original_line = Line(value, line_type=line_type)
if line_type == LINE_TYPE_ADDED:
original_line.target_line_no = target_line_no
target_line_no += 1
elif line_type == LINE_TYPE_REMOVED:
original_line.source_line_no = source_line_no
source_line_no += 1
elif line_type == LINE_TYPE_CONTEXT:
original_line.target_line_no = target_line_no
target_line_no += 1
original_line.source_line_no = source_line_no
source_line_no += 1
elif line_type == LINE_TYPE_NO_NEWLINE:
pass
else:
original_line = None
# stop parsing if we got past expected number of lines
if (source_line_no > expected_source_end or
target_line_no > expected_target_end):
raise UnidiffParseError('Hunk is longer than expected')
if original_line:
original_line.diff_line_no = diff_line_no
hunk.append(original_line)
# if hunk source/target lengths are ok, hunk is complete
if (source_line_no == expected_source_end and
target_line_no == expected_target_end):
break
# report an error if we haven't got expected number of lines
if (source_line_no < expected_source_end or
target_line_no < expected_target_end):
raise UnidiffParseError('Hunk is shorter than expected')
self.append(hunk) | python | def _parse_hunk(self, header, diff, encoding):
"""Parse hunk details."""
header_info = RE_HUNK_HEADER.match(header)
hunk_info = header_info.groups()
hunk = Hunk(*hunk_info)
source_line_no = hunk.source_start
target_line_no = hunk.target_start
expected_source_end = source_line_no + hunk.source_length
expected_target_end = target_line_no + hunk.target_length
for diff_line_no, line in diff:
if encoding is not None:
line = line.decode(encoding)
valid_line = RE_HUNK_EMPTY_BODY_LINE.match(line)
if not valid_line:
valid_line = RE_HUNK_BODY_LINE.match(line)
if not valid_line:
raise UnidiffParseError('Hunk diff line expected: %s' % line)
line_type = valid_line.group('line_type')
if line_type == LINE_TYPE_EMPTY:
line_type = LINE_TYPE_CONTEXT
value = valid_line.group('value')
original_line = Line(value, line_type=line_type)
if line_type == LINE_TYPE_ADDED:
original_line.target_line_no = target_line_no
target_line_no += 1
elif line_type == LINE_TYPE_REMOVED:
original_line.source_line_no = source_line_no
source_line_no += 1
elif line_type == LINE_TYPE_CONTEXT:
original_line.target_line_no = target_line_no
target_line_no += 1
original_line.source_line_no = source_line_no
source_line_no += 1
elif line_type == LINE_TYPE_NO_NEWLINE:
pass
else:
original_line = None
# stop parsing if we got past expected number of lines
if (source_line_no > expected_source_end or
target_line_no > expected_target_end):
raise UnidiffParseError('Hunk is longer than expected')
if original_line:
original_line.diff_line_no = diff_line_no
hunk.append(original_line)
# if hunk source/target lengths are ok, hunk is complete
if (source_line_no == expected_source_end and
target_line_no == expected_target_end):
break
# report an error if we haven't got expected number of lines
if (source_line_no < expected_source_end or
target_line_no < expected_target_end):
raise UnidiffParseError('Hunk is shorter than expected')
self.append(hunk) | [
"def",
"_parse_hunk",
"(",
"self",
",",
"header",
",",
"diff",
",",
"encoding",
")",
":",
"header_info",
"=",
"RE_HUNK_HEADER",
".",
"match",
"(",
"header",
")",
"hunk_info",
"=",
"header_info",
".",
"groups",
"(",
")",
"hunk",
"=",
"Hunk",
"(",
"*",
"... | Parse hunk details. | [
"Parse",
"hunk",
"details",
"."
] | 71f510b181dbb3bb3885fe032e81b0d3258b4287 | https://github.com/matiasb/python-unidiff/blob/71f510b181dbb3bb3885fe032e81b0d3258b4287/unidiff/patch.py#L217-L279 | train | 211,075 |
matiasb/python-unidiff | unidiff/patch.py | PatchedFile.path | def path(self):
"""Return the file path abstracted from VCS."""
if (self.source_file.startswith('a/') and
self.target_file.startswith('b/')):
filepath = self.source_file[2:]
elif (self.source_file.startswith('a/') and
self.target_file == '/dev/null'):
filepath = self.source_file[2:]
elif (self.target_file.startswith('b/') and
self.source_file == '/dev/null'):
filepath = self.target_file[2:]
else:
filepath = self.source_file
return filepath | python | def path(self):
"""Return the file path abstracted from VCS."""
if (self.source_file.startswith('a/') and
self.target_file.startswith('b/')):
filepath = self.source_file[2:]
elif (self.source_file.startswith('a/') and
self.target_file == '/dev/null'):
filepath = self.source_file[2:]
elif (self.target_file.startswith('b/') and
self.source_file == '/dev/null'):
filepath = self.target_file[2:]
else:
filepath = self.source_file
return filepath | [
"def",
"path",
"(",
"self",
")",
":",
"if",
"(",
"self",
".",
"source_file",
".",
"startswith",
"(",
"'a/'",
")",
"and",
"self",
".",
"target_file",
".",
"startswith",
"(",
"'b/'",
")",
")",
":",
"filepath",
"=",
"self",
".",
"source_file",
"[",
"2",... | Return the file path abstracted from VCS. | [
"Return",
"the",
"file",
"path",
"abstracted",
"from",
"VCS",
"."
] | 71f510b181dbb3bb3885fe032e81b0d3258b4287 | https://github.com/matiasb/python-unidiff/blob/71f510b181dbb3bb3885fe032e81b0d3258b4287/unidiff/patch.py#L296-L309 | train | 211,076 |
eyurtsev/FlowCytometryTools | FlowCytometryTools/core/utils.py | get_tag_value | def get_tag_value(string, pre, post, tagtype=float, greedy=True):
"""
Extracts the value of a tag from a string.
Parameters
-----------------
pre : str
regular expression to match before the the tag value
post : str | list | tuple
regular expression to match after the the tag value
if list than the regular expressions will be combined into the regular expression (?=post[0]|post[1]|..)
tagtype : str | float | int
the type to which the tag value should be converted to
greedy : bool
Whether the regular expression is gredy or not.
Returns
---------------
Tag value if found, None otherwise
Example
------------
get_tag_value('PID_23.5.txt', pre=r'PID_' , post='(?=_|\.txt)') should return 23.5
get_tag_value('PID_23.5_.txt', pre=r'PID_', post='(?=_|\.txt)') should return 23.5
get_tag_value('PID_23_5_.txt', pre=r'PID_', post='(?=_|\.txt)') should return 23
get_tag_value('PID_23.txt', pre=r'PID_', post='.txt') should return 23
get_tag_value('PID.txt', pre=r'PID_', post='.txt') should return None
TODO Make list/tuple input for pre
"""
greedy = '?' if greedy else '' # For greedy search
if isinstance(post, (list, tuple)):
post = '(?=' + '|'.join(post) + ')'
tag_list = re.findall(r'{pre}(.+{greedy}){post}'.format(pre=pre, post=post, greedy=greedy),
string)
if len(tag_list) > 1:
raise ValueError('More than one matching pattern found... check filename')
elif len(tag_list) == 0:
return None
else:
return tagtype(tag_list[0]) | python | def get_tag_value(string, pre, post, tagtype=float, greedy=True):
"""
Extracts the value of a tag from a string.
Parameters
-----------------
pre : str
regular expression to match before the the tag value
post : str | list | tuple
regular expression to match after the the tag value
if list than the regular expressions will be combined into the regular expression (?=post[0]|post[1]|..)
tagtype : str | float | int
the type to which the tag value should be converted to
greedy : bool
Whether the regular expression is gredy or not.
Returns
---------------
Tag value if found, None otherwise
Example
------------
get_tag_value('PID_23.5.txt', pre=r'PID_' , post='(?=_|\.txt)') should return 23.5
get_tag_value('PID_23.5_.txt', pre=r'PID_', post='(?=_|\.txt)') should return 23.5
get_tag_value('PID_23_5_.txt', pre=r'PID_', post='(?=_|\.txt)') should return 23
get_tag_value('PID_23.txt', pre=r'PID_', post='.txt') should return 23
get_tag_value('PID.txt', pre=r'PID_', post='.txt') should return None
TODO Make list/tuple input for pre
"""
greedy = '?' if greedy else '' # For greedy search
if isinstance(post, (list, tuple)):
post = '(?=' + '|'.join(post) + ')'
tag_list = re.findall(r'{pre}(.+{greedy}){post}'.format(pre=pre, post=post, greedy=greedy),
string)
if len(tag_list) > 1:
raise ValueError('More than one matching pattern found... check filename')
elif len(tag_list) == 0:
return None
else:
return tagtype(tag_list[0]) | [
"def",
"get_tag_value",
"(",
"string",
",",
"pre",
",",
"post",
",",
"tagtype",
"=",
"float",
",",
"greedy",
"=",
"True",
")",
":",
"greedy",
"=",
"'?'",
"if",
"greedy",
"else",
"''",
"# For greedy search",
"if",
"isinstance",
"(",
"post",
",",
"(",
"l... | Extracts the value of a tag from a string.
Parameters
-----------------
pre : str
regular expression to match before the the tag value
post : str | list | tuple
regular expression to match after the the tag value
if list than the regular expressions will be combined into the regular expression (?=post[0]|post[1]|..)
tagtype : str | float | int
the type to which the tag value should be converted to
greedy : bool
Whether the regular expression is gredy or not.
Returns
---------------
Tag value if found, None otherwise
Example
------------
get_tag_value('PID_23.5.txt', pre=r'PID_' , post='(?=_|\.txt)') should return 23.5
get_tag_value('PID_23.5_.txt', pre=r'PID_', post='(?=_|\.txt)') should return 23.5
get_tag_value('PID_23_5_.txt', pre=r'PID_', post='(?=_|\.txt)') should return 23
get_tag_value('PID_23.txt', pre=r'PID_', post='.txt') should return 23
get_tag_value('PID.txt', pre=r'PID_', post='.txt') should return None
TODO Make list/tuple input for pre | [
"Extracts",
"the",
"value",
"of",
"a",
"tag",
"from",
"a",
"string",
"."
] | 4355632508b875273d68c7e2972c17668bcf7b40 | https://github.com/eyurtsev/FlowCytometryTools/blob/4355632508b875273d68c7e2972c17668bcf7b40/FlowCytometryTools/core/utils.py#L16-L65 | train | 211,077 |
eyurtsev/FlowCytometryTools | FlowCytometryTools/core/utils.py | get_files | def get_files(dirname=None, pattern='*.*', recursive=True):
"""
Get all file names within a given directory those names match a
given pattern.
Parameters
----------
dirname : str | None
Directory containing the datafiles.
If None is given, open a dialog box.
pattern : str
Return only files whose names match the specified pattern.
recursive : bool
True : Search recursively within all sub-directories.
False : Search only in given directory.
Returns
-------
matches: list
List of file names (including full path).
"""
# get dirname from user if not given
if dirname is None:
from FlowCytometryTools.gui import dialogs
dirname = dialogs.select_directory_dialog('Select a directory')
# find all files in dirname that match pattern
if recursive: # search subdirs
matches = []
for root, dirnames, filenames in os.walk(dirname):
for filename in fnmatch.filter(filenames, pattern):
matches.append(os.path.join(root, filename))
else:
matches = glob.glob(os.path.join(dirname, pattern))
return matches | python | def get_files(dirname=None, pattern='*.*', recursive=True):
"""
Get all file names within a given directory those names match a
given pattern.
Parameters
----------
dirname : str | None
Directory containing the datafiles.
If None is given, open a dialog box.
pattern : str
Return only files whose names match the specified pattern.
recursive : bool
True : Search recursively within all sub-directories.
False : Search only in given directory.
Returns
-------
matches: list
List of file names (including full path).
"""
# get dirname from user if not given
if dirname is None:
from FlowCytometryTools.gui import dialogs
dirname = dialogs.select_directory_dialog('Select a directory')
# find all files in dirname that match pattern
if recursive: # search subdirs
matches = []
for root, dirnames, filenames in os.walk(dirname):
for filename in fnmatch.filter(filenames, pattern):
matches.append(os.path.join(root, filename))
else:
matches = glob.glob(os.path.join(dirname, pattern))
return matches | [
"def",
"get_files",
"(",
"dirname",
"=",
"None",
",",
"pattern",
"=",
"'*.*'",
",",
"recursive",
"=",
"True",
")",
":",
"# get dirname from user if not given",
"if",
"dirname",
"is",
"None",
":",
"from",
"FlowCytometryTools",
".",
"gui",
"import",
"dialogs",
"... | Get all file names within a given directory those names match a
given pattern.
Parameters
----------
dirname : str | None
Directory containing the datafiles.
If None is given, open a dialog box.
pattern : str
Return only files whose names match the specified pattern.
recursive : bool
True : Search recursively within all sub-directories.
False : Search only in given directory.
Returns
-------
matches: list
List of file names (including full path). | [
"Get",
"all",
"file",
"names",
"within",
"a",
"given",
"directory",
"those",
"names",
"match",
"a",
"given",
"pattern",
"."
] | 4355632508b875273d68c7e2972c17668bcf7b40 | https://github.com/eyurtsev/FlowCytometryTools/blob/4355632508b875273d68c7e2972c17668bcf7b40/FlowCytometryTools/core/utils.py#L68-L102 | train | 211,078 |
eyurtsev/FlowCytometryTools | FlowCytometryTools/core/utils.py | load | def load(path):
"""
Load pickled object from the specified file path.
Parameters
----------
path : string
File path
Returns
-------
unpickled : type of object stored in file
"""
f = open(path, 'rb')
try:
return pickle.load(f)
finally:
f.close() | python | def load(path):
"""
Load pickled object from the specified file path.
Parameters
----------
path : string
File path
Returns
-------
unpickled : type of object stored in file
"""
f = open(path, 'rb')
try:
return pickle.load(f)
finally:
f.close() | [
"def",
"load",
"(",
"path",
")",
":",
"f",
"=",
"open",
"(",
"path",
",",
"'rb'",
")",
"try",
":",
"return",
"pickle",
".",
"load",
"(",
"f",
")",
"finally",
":",
"f",
".",
"close",
"(",
")"
] | Load pickled object from the specified file path.
Parameters
----------
path : string
File path
Returns
-------
unpickled : type of object stored in file | [
"Load",
"pickled",
"object",
"from",
"the",
"specified",
"file",
"path",
"."
] | 4355632508b875273d68c7e2972c17668bcf7b40 | https://github.com/eyurtsev/FlowCytometryTools/blob/4355632508b875273d68c7e2972c17668bcf7b40/FlowCytometryTools/core/utils.py#L123-L140 | train | 211,079 |
eyurtsev/FlowCytometryTools | FlowCytometryTools/core/utils.py | to_iter | def to_iter(obj):
"""Convert an object to a list if it is not already an iterable.
Nones are returned unaltered.
This is an awful function that proliferates an explosion of types, please do not use anymore.
"""
if isinstance(obj, type(None)):
return None
elif isinstance(obj, six.string_types):
return [obj]
else:
# Nesting here since symmetry is broken in isinstance checks.
# Strings are iterables in python 3, so the relative order of if statements is important.
if isinstance(obj, collections.Iterable):
return obj
else:
return [obj] | python | def to_iter(obj):
"""Convert an object to a list if it is not already an iterable.
Nones are returned unaltered.
This is an awful function that proliferates an explosion of types, please do not use anymore.
"""
if isinstance(obj, type(None)):
return None
elif isinstance(obj, six.string_types):
return [obj]
else:
# Nesting here since symmetry is broken in isinstance checks.
# Strings are iterables in python 3, so the relative order of if statements is important.
if isinstance(obj, collections.Iterable):
return obj
else:
return [obj] | [
"def",
"to_iter",
"(",
"obj",
")",
":",
"if",
"isinstance",
"(",
"obj",
",",
"type",
"(",
"None",
")",
")",
":",
"return",
"None",
"elif",
"isinstance",
"(",
"obj",
",",
"six",
".",
"string_types",
")",
":",
"return",
"[",
"obj",
"]",
"else",
":",
... | Convert an object to a list if it is not already an iterable.
Nones are returned unaltered.
This is an awful function that proliferates an explosion of types, please do not use anymore. | [
"Convert",
"an",
"object",
"to",
"a",
"list",
"if",
"it",
"is",
"not",
"already",
"an",
"iterable",
"."
] | 4355632508b875273d68c7e2972c17668bcf7b40 | https://github.com/eyurtsev/FlowCytometryTools/blob/4355632508b875273d68c7e2972c17668bcf7b40/FlowCytometryTools/core/utils.py#L143-L160 | train | 211,080 |
eyurtsev/FlowCytometryTools | FlowCytometryTools/core/utils.py | to_list | def to_list(obj):
"""
Converts an object into a list if it not an iterable, forcing tuples into lists.
Nones are returned unchanged.
"""
obj = to_iter(obj)
if isinstance(obj, type(None)):
return None
else:
return list(obj) | python | def to_list(obj):
"""
Converts an object into a list if it not an iterable, forcing tuples into lists.
Nones are returned unchanged.
"""
obj = to_iter(obj)
if isinstance(obj, type(None)):
return None
else:
return list(obj) | [
"def",
"to_list",
"(",
"obj",
")",
":",
"obj",
"=",
"to_iter",
"(",
"obj",
")",
"if",
"isinstance",
"(",
"obj",
",",
"type",
"(",
"None",
")",
")",
":",
"return",
"None",
"else",
":",
"return",
"list",
"(",
"obj",
")"
] | Converts an object into a list if it not an iterable, forcing tuples into lists.
Nones are returned unchanged. | [
"Converts",
"an",
"object",
"into",
"a",
"list",
"if",
"it",
"not",
"an",
"iterable",
"forcing",
"tuples",
"into",
"lists",
".",
"Nones",
"are",
"returned",
"unchanged",
"."
] | 4355632508b875273d68c7e2972c17668bcf7b40 | https://github.com/eyurtsev/FlowCytometryTools/blob/4355632508b875273d68c7e2972c17668bcf7b40/FlowCytometryTools/core/utils.py#L163-L173 | train | 211,081 |
eyurtsev/FlowCytometryTools | FlowCytometryTools/core/utils.py | BaseObject.copy | def copy(self, deep=True):
"""
Make a copy of this object
Parameters
----------
deep : boolean, default True
Make a deep copy, i.e. also copy data
Returns
-------
copy : type of caller
"""
from copy import copy, deepcopy
if deep:
return deepcopy(self)
else:
return copy(self) | python | def copy(self, deep=True):
"""
Make a copy of this object
Parameters
----------
deep : boolean, default True
Make a deep copy, i.e. also copy data
Returns
-------
copy : type of caller
"""
from copy import copy, deepcopy
if deep:
return deepcopy(self)
else:
return copy(self) | [
"def",
"copy",
"(",
"self",
",",
"deep",
"=",
"True",
")",
":",
"from",
"copy",
"import",
"copy",
",",
"deepcopy",
"if",
"deep",
":",
"return",
"deepcopy",
"(",
"self",
")",
"else",
":",
"return",
"copy",
"(",
"self",
")"
] | Make a copy of this object
Parameters
----------
deep : boolean, default True
Make a deep copy, i.e. also copy data
Returns
-------
copy : type of caller | [
"Make",
"a",
"copy",
"of",
"this",
"object"
] | 4355632508b875273d68c7e2972c17668bcf7b40 | https://github.com/eyurtsev/FlowCytometryTools/blob/4355632508b875273d68c7e2972c17668bcf7b40/FlowCytometryTools/core/utils.py#L196-L213 | train | 211,082 |
eyurtsev/FlowCytometryTools | FlowCytometryTools/core/transforms.py | tlog | def tlog(x, th=1, r=_display_max, d=_l_mmax):
"""
Truncated log10 transform.
Parameters
----------
x : num | num iterable
values to be transformed.
th : num
values below th are transormed to 0.
Must be positive.
r : num (default = 10**4)
maximal transformed value.
d : num (default = log10(2**18))
log10 of maximal possible measured value.
tlog(10**d) = r
Returns
-------
Array of transformed values.
"""
if th <= 0:
raise ValueError('Threshold value must be positive. %s given.' % th)
return where(x <= th, log10(th) * 1. * r / d, log10(x) * 1. * r / d) | python | def tlog(x, th=1, r=_display_max, d=_l_mmax):
"""
Truncated log10 transform.
Parameters
----------
x : num | num iterable
values to be transformed.
th : num
values below th are transormed to 0.
Must be positive.
r : num (default = 10**4)
maximal transformed value.
d : num (default = log10(2**18))
log10 of maximal possible measured value.
tlog(10**d) = r
Returns
-------
Array of transformed values.
"""
if th <= 0:
raise ValueError('Threshold value must be positive. %s given.' % th)
return where(x <= th, log10(th) * 1. * r / d, log10(x) * 1. * r / d) | [
"def",
"tlog",
"(",
"x",
",",
"th",
"=",
"1",
",",
"r",
"=",
"_display_max",
",",
"d",
"=",
"_l_mmax",
")",
":",
"if",
"th",
"<=",
"0",
":",
"raise",
"ValueError",
"(",
"'Threshold value must be positive. %s given.'",
"%",
"th",
")",
"return",
"where",
... | Truncated log10 transform.
Parameters
----------
x : num | num iterable
values to be transformed.
th : num
values below th are transormed to 0.
Must be positive.
r : num (default = 10**4)
maximal transformed value.
d : num (default = log10(2**18))
log10 of maximal possible measured value.
tlog(10**d) = r
Returns
-------
Array of transformed values. | [
"Truncated",
"log10",
"transform",
"."
] | 4355632508b875273d68c7e2972c17668bcf7b40 | https://github.com/eyurtsev/FlowCytometryTools/blob/4355632508b875273d68c7e2972c17668bcf7b40/FlowCytometryTools/core/transforms.py#L57-L80 | train | 211,083 |
eyurtsev/FlowCytometryTools | FlowCytometryTools/core/transforms.py | tlog_inv | def tlog_inv(y, th=1, r=_display_max, d=_l_mmax):
"""
Inverse truncated log10 transform.
Values
Parameters
----------
y : num | num iterable
values to be transformed.
th : num
Inverse values below th are transormed to th.
Must be > positive.
r : num (default = 10**4)
maximal transformed value.
d : num (default = log10(2**18))
log10 of maximal possible measured value.
tlog_inv(r) = 10**d
Returns
-------
Array of transformed values.
"""
if th <= 0:
raise ValueError('Threshold value must be positive. %s given.' % th)
x = 10 ** (y * 1. * d / r)
try:
x[x < th] = th
except TypeError:
if x < th: x = th
return x | python | def tlog_inv(y, th=1, r=_display_max, d=_l_mmax):
"""
Inverse truncated log10 transform.
Values
Parameters
----------
y : num | num iterable
values to be transformed.
th : num
Inverse values below th are transormed to th.
Must be > positive.
r : num (default = 10**4)
maximal transformed value.
d : num (default = log10(2**18))
log10 of maximal possible measured value.
tlog_inv(r) = 10**d
Returns
-------
Array of transformed values.
"""
if th <= 0:
raise ValueError('Threshold value must be positive. %s given.' % th)
x = 10 ** (y * 1. * d / r)
try:
x[x < th] = th
except TypeError:
if x < th: x = th
return x | [
"def",
"tlog_inv",
"(",
"y",
",",
"th",
"=",
"1",
",",
"r",
"=",
"_display_max",
",",
"d",
"=",
"_l_mmax",
")",
":",
"if",
"th",
"<=",
"0",
":",
"raise",
"ValueError",
"(",
"'Threshold value must be positive. %s given.'",
"%",
"th",
")",
"x",
"=",
"10"... | Inverse truncated log10 transform.
Values
Parameters
----------
y : num | num iterable
values to be transformed.
th : num
Inverse values below th are transormed to th.
Must be > positive.
r : num (default = 10**4)
maximal transformed value.
d : num (default = log10(2**18))
log10 of maximal possible measured value.
tlog_inv(r) = 10**d
Returns
-------
Array of transformed values. | [
"Inverse",
"truncated",
"log10",
"transform",
".",
"Values"
] | 4355632508b875273d68c7e2972c17668bcf7b40 | https://github.com/eyurtsev/FlowCytometryTools/blob/4355632508b875273d68c7e2972c17668bcf7b40/FlowCytometryTools/core/transforms.py#L83-L112 | train | 211,084 |
eyurtsev/FlowCytometryTools | FlowCytometryTools/core/transforms.py | hlog_inv | def hlog_inv(y, b=500, r=_display_max, d=_l_mmax):
"""
Inverse of base 10 hyperlog transform.
"""
aux = 1. * d / r * y
s = sign(y)
if s.shape: # to catch case where input is a single number
s[s == 0] = 1
elif s == 0:
s = 1
return s * 10 ** (s * aux) + b * aux - s | python | def hlog_inv(y, b=500, r=_display_max, d=_l_mmax):
"""
Inverse of base 10 hyperlog transform.
"""
aux = 1. * d / r * y
s = sign(y)
if s.shape: # to catch case where input is a single number
s[s == 0] = 1
elif s == 0:
s = 1
return s * 10 ** (s * aux) + b * aux - s | [
"def",
"hlog_inv",
"(",
"y",
",",
"b",
"=",
"500",
",",
"r",
"=",
"_display_max",
",",
"d",
"=",
"_l_mmax",
")",
":",
"aux",
"=",
"1.",
"*",
"d",
"/",
"r",
"*",
"y",
"s",
"=",
"sign",
"(",
"y",
")",
"if",
"s",
".",
"shape",
":",
"# to catch... | Inverse of base 10 hyperlog transform. | [
"Inverse",
"of",
"base",
"10",
"hyperlog",
"transform",
"."
] | 4355632508b875273d68c7e2972c17668bcf7b40 | https://github.com/eyurtsev/FlowCytometryTools/blob/4355632508b875273d68c7e2972c17668bcf7b40/FlowCytometryTools/core/transforms.py#L127-L137 | train | 211,085 |
eyurtsev/FlowCytometryTools | FlowCytometryTools/core/transforms.py | _x_for_spln | def _x_for_spln(x, nx, log_spacing):
"""
Create vector of values to be used in constructing a spline.
Parameters
----------
x : num | num iterable
Resulted values will span the range [min(x), max(x)]
nx : int
Length of returned vector.
log_spacing: bool
False - Create linearly spaced values.
True - Create logarithmically spaced values.
To extend to negative values, the spacing is done separately on the
negative and positive range, and these are later combined.
The number of points in the negative/positive range is proportional
to their relative range in log space. i.e., for data in the range
[-100, 1000] 2/5 of the resulting points will be in the negative range.
Returns
-------
x_spln : array
"""
x = asarray(x)
xmin = min(x)
xmax = max(x)
if xmin == xmax:
return asarray([xmin] * nx)
if xmax <= 0: # all values<=0
return -_x_for_spln(-x, nx, log_spacing)[::-1]
if not log_spacing:
return linspace(xmin, xmax, nx)
# All code below is to handle-log-spacing when x has potentially both negative
# and positive values.
if xmin > 0:
return logspace(log10(xmin), log10(xmax), nx)
else:
lxmax = max([log10(xmax), 0])
lxmin = max([log10(abs(xmin)), 0])
# All the code below is for log-spacing, when xmin < 0 and xmax > 0
if lxmax == 0 and lxmin == 0:
return linspace(xmin, xmax, nx) # Use linear spacing as fallback
if xmin > 0:
x_spln = logspace(lxmin, lxmax, nx)
elif xmin == 0:
x_spln = r_[0, logspace(-1, lxmax, nx - 1)]
else: # (xmin < 0)
f = lxmin / (lxmin + lxmax)
nx_neg = int(f * nx)
nx_pos = nx - nx_neg
if nx <= 1:
# If triggered fix edge case behavior
raise AssertionError(u'nx should never bebe 0 or 1')
# Work-around various edge cases
if nx_neg == 0:
nx_neg = 1
nx_pos = nx_pos - 1
if nx_pos == 0:
nx_pos = 1
nx_neg = nx_neg - 1
x_spln_pos = logspace(-1, lxmax, nx_pos)
x_spln_neg = -logspace(lxmin, -1, nx_neg)
x_spln = r_[x_spln_neg, x_spln_pos]
return x_spln | python | def _x_for_spln(x, nx, log_spacing):
"""
Create vector of values to be used in constructing a spline.
Parameters
----------
x : num | num iterable
Resulted values will span the range [min(x), max(x)]
nx : int
Length of returned vector.
log_spacing: bool
False - Create linearly spaced values.
True - Create logarithmically spaced values.
To extend to negative values, the spacing is done separately on the
negative and positive range, and these are later combined.
The number of points in the negative/positive range is proportional
to their relative range in log space. i.e., for data in the range
[-100, 1000] 2/5 of the resulting points will be in the negative range.
Returns
-------
x_spln : array
"""
x = asarray(x)
xmin = min(x)
xmax = max(x)
if xmin == xmax:
return asarray([xmin] * nx)
if xmax <= 0: # all values<=0
return -_x_for_spln(-x, nx, log_spacing)[::-1]
if not log_spacing:
return linspace(xmin, xmax, nx)
# All code below is to handle-log-spacing when x has potentially both negative
# and positive values.
if xmin > 0:
return logspace(log10(xmin), log10(xmax), nx)
else:
lxmax = max([log10(xmax), 0])
lxmin = max([log10(abs(xmin)), 0])
# All the code below is for log-spacing, when xmin < 0 and xmax > 0
if lxmax == 0 and lxmin == 0:
return linspace(xmin, xmax, nx) # Use linear spacing as fallback
if xmin > 0:
x_spln = logspace(lxmin, lxmax, nx)
elif xmin == 0:
x_spln = r_[0, logspace(-1, lxmax, nx - 1)]
else: # (xmin < 0)
f = lxmin / (lxmin + lxmax)
nx_neg = int(f * nx)
nx_pos = nx - nx_neg
if nx <= 1:
# If triggered fix edge case behavior
raise AssertionError(u'nx should never bebe 0 or 1')
# Work-around various edge cases
if nx_neg == 0:
nx_neg = 1
nx_pos = nx_pos - 1
if nx_pos == 0:
nx_pos = 1
nx_neg = nx_neg - 1
x_spln_pos = logspace(-1, lxmax, nx_pos)
x_spln_neg = -logspace(lxmin, -1, nx_neg)
x_spln = r_[x_spln_neg, x_spln_pos]
return x_spln | [
"def",
"_x_for_spln",
"(",
"x",
",",
"nx",
",",
"log_spacing",
")",
":",
"x",
"=",
"asarray",
"(",
"x",
")",
"xmin",
"=",
"min",
"(",
"x",
")",
"xmax",
"=",
"max",
"(",
"x",
")",
"if",
"xmin",
"==",
"xmax",
":",
"return",
"asarray",
"(",
"[",
... | Create vector of values to be used in constructing a spline.
Parameters
----------
x : num | num iterable
Resulted values will span the range [min(x), max(x)]
nx : int
Length of returned vector.
log_spacing: bool
False - Create linearly spaced values.
True - Create logarithmically spaced values.
To extend to negative values, the spacing is done separately on the
negative and positive range, and these are later combined.
The number of points in the negative/positive range is proportional
to their relative range in log space. i.e., for data in the range
[-100, 1000] 2/5 of the resulting points will be in the negative range.
Returns
-------
x_spln : array | [
"Create",
"vector",
"of",
"values",
"to",
"be",
"used",
"in",
"constructing",
"a",
"spline",
"."
] | 4355632508b875273d68c7e2972c17668bcf7b40 | https://github.com/eyurtsev/FlowCytometryTools/blob/4355632508b875273d68c7e2972c17668bcf7b40/FlowCytometryTools/core/transforms.py#L140-L212 | train | 211,086 |
eyurtsev/FlowCytometryTools | FlowCytometryTools/core/transforms.py | _make_hlog_numeric | def _make_hlog_numeric(b, r, d):
"""
Return a function that numerically computes the hlog transformation for given parameter values.
"""
hlog_obj = lambda y, x, b, r, d: hlog_inv(y, b, r, d) - x
find_inv = vectorize(lambda x: brentq(hlog_obj, -2 * r, 2 * r,
args=(x, b, r, d)))
return find_inv | python | def _make_hlog_numeric(b, r, d):
"""
Return a function that numerically computes the hlog transformation for given parameter values.
"""
hlog_obj = lambda y, x, b, r, d: hlog_inv(y, b, r, d) - x
find_inv = vectorize(lambda x: brentq(hlog_obj, -2 * r, 2 * r,
args=(x, b, r, d)))
return find_inv | [
"def",
"_make_hlog_numeric",
"(",
"b",
",",
"r",
",",
"d",
")",
":",
"hlog_obj",
"=",
"lambda",
"y",
",",
"x",
",",
"b",
",",
"r",
",",
"d",
":",
"hlog_inv",
"(",
"y",
",",
"b",
",",
"r",
",",
"d",
")",
"-",
"x",
"find_inv",
"=",
"vectorize",... | Return a function that numerically computes the hlog transformation for given parameter values. | [
"Return",
"a",
"function",
"that",
"numerically",
"computes",
"the",
"hlog",
"transformation",
"for",
"given",
"parameter",
"values",
"."
] | 4355632508b875273d68c7e2972c17668bcf7b40 | https://github.com/eyurtsev/FlowCytometryTools/blob/4355632508b875273d68c7e2972c17668bcf7b40/FlowCytometryTools/core/transforms.py#L215-L222 | train | 211,087 |
eyurtsev/FlowCytometryTools | FlowCytometryTools/core/transforms.py | hlog | def hlog(x, b=500, r=_display_max, d=_l_mmax):
"""
Base 10 hyperlog transform.
Parameters
----------
x : num | num iterable
values to be transformed.
b : num
Parameter controling the location of the shift
from linear to log transformation.
r : num (default = 10**4)
maximal transformed value.
d : num (default = log10(2**18))
log10 of maximal possible measured value.
hlog_inv(r) = 10**d
Returns
-------
Array of transformed values.
"""
hlog_fun = _make_hlog_numeric(b, r, d)
if not hasattr(x, '__len__'): # if transforming a single number
y = hlog_fun(x)
else:
n = len(x)
if not n: # if transforming empty container
return x
else:
y = hlog_fun(x)
return y | python | def hlog(x, b=500, r=_display_max, d=_l_mmax):
"""
Base 10 hyperlog transform.
Parameters
----------
x : num | num iterable
values to be transformed.
b : num
Parameter controling the location of the shift
from linear to log transformation.
r : num (default = 10**4)
maximal transformed value.
d : num (default = log10(2**18))
log10 of maximal possible measured value.
hlog_inv(r) = 10**d
Returns
-------
Array of transformed values.
"""
hlog_fun = _make_hlog_numeric(b, r, d)
if not hasattr(x, '__len__'): # if transforming a single number
y = hlog_fun(x)
else:
n = len(x)
if not n: # if transforming empty container
return x
else:
y = hlog_fun(x)
return y | [
"def",
"hlog",
"(",
"x",
",",
"b",
"=",
"500",
",",
"r",
"=",
"_display_max",
",",
"d",
"=",
"_l_mmax",
")",
":",
"hlog_fun",
"=",
"_make_hlog_numeric",
"(",
"b",
",",
"r",
",",
"d",
")",
"if",
"not",
"hasattr",
"(",
"x",
",",
"'__len__'",
")",
... | Base 10 hyperlog transform.
Parameters
----------
x : num | num iterable
values to be transformed.
b : num
Parameter controling the location of the shift
from linear to log transformation.
r : num (default = 10**4)
maximal transformed value.
d : num (default = log10(2**18))
log10 of maximal possible measured value.
hlog_inv(r) = 10**d
Returns
-------
Array of transformed values. | [
"Base",
"10",
"hyperlog",
"transform",
"."
] | 4355632508b875273d68c7e2972c17668bcf7b40 | https://github.com/eyurtsev/FlowCytometryTools/blob/4355632508b875273d68c7e2972c17668bcf7b40/FlowCytometryTools/core/transforms.py#L225-L255 | train | 211,088 |
eyurtsev/FlowCytometryTools | FlowCytometryTools/core/transforms.py | transform_frame | def transform_frame(frame, transform, columns=None, direction='forward',
return_all=True, args=(), **kwargs):
"""
Apply transform to specified columns.
direction: 'forward' | 'inverse'
return_all: bool
True - return all columns, with specified ones transformed.
False - return only specified columns.
.. warning:: deprecated
"""
tfun, tname = parse_transform(transform, direction)
columns = to_list(columns)
if columns is None:
columns = frame.columns
if return_all:
transformed = frame.copy()
for c in columns:
transformed[c] = tfun(frame[c], *args, **kwargs)
else:
transformed = frame.filter(columns).apply(tfun, *args, **kwargs)
return transformed | python | def transform_frame(frame, transform, columns=None, direction='forward',
return_all=True, args=(), **kwargs):
"""
Apply transform to specified columns.
direction: 'forward' | 'inverse'
return_all: bool
True - return all columns, with specified ones transformed.
False - return only specified columns.
.. warning:: deprecated
"""
tfun, tname = parse_transform(transform, direction)
columns = to_list(columns)
if columns is None:
columns = frame.columns
if return_all:
transformed = frame.copy()
for c in columns:
transformed[c] = tfun(frame[c], *args, **kwargs)
else:
transformed = frame.filter(columns).apply(tfun, *args, **kwargs)
return transformed | [
"def",
"transform_frame",
"(",
"frame",
",",
"transform",
",",
"columns",
"=",
"None",
",",
"direction",
"=",
"'forward'",
",",
"return_all",
"=",
"True",
",",
"args",
"=",
"(",
")",
",",
"*",
"*",
"kwargs",
")",
":",
"tfun",
",",
"tname",
"=",
"pars... | Apply transform to specified columns.
direction: 'forward' | 'inverse'
return_all: bool
True - return all columns, with specified ones transformed.
False - return only specified columns.
.. warning:: deprecated | [
"Apply",
"transform",
"to",
"specified",
"columns",
"."
] | 4355632508b875273d68c7e2972c17668bcf7b40 | https://github.com/eyurtsev/FlowCytometryTools/blob/4355632508b875273d68c7e2972c17668bcf7b40/FlowCytometryTools/core/transforms.py#L303-L325 | train | 211,089 |
eyurtsev/FlowCytometryTools | FlowCytometryTools/core/transforms.py | Transformation.transform | def transform(self, x, use_spln=False, **kwargs):
"""
Apply transform to x
Parameters
----------
x : float-array-convertible
Data to be transformed.
Should support conversion to an array of floats.
use_spln: bool
True - transform using the spline specified in self.slpn.
If self.spln is None, set the spline.
False - transform using self.tfun
kwargs:
Keyword arguments to be passed to self.set_spline.
Only used if use_spln=True & self.spln=None.
Returns
-------
Array of transformed values.
"""
x = asarray(x, dtype=float)
if use_spln:
if self.spln is None:
self.set_spline(x.min(), x.max(), **kwargs)
return apply_along_axis(self.spln, 0, x)
else:
return self.tfun(x, *self.args, **self.kwargs) | python | def transform(self, x, use_spln=False, **kwargs):
"""
Apply transform to x
Parameters
----------
x : float-array-convertible
Data to be transformed.
Should support conversion to an array of floats.
use_spln: bool
True - transform using the spline specified in self.slpn.
If self.spln is None, set the spline.
False - transform using self.tfun
kwargs:
Keyword arguments to be passed to self.set_spline.
Only used if use_spln=True & self.spln=None.
Returns
-------
Array of transformed values.
"""
x = asarray(x, dtype=float)
if use_spln:
if self.spln is None:
self.set_spline(x.min(), x.max(), **kwargs)
return apply_along_axis(self.spln, 0, x)
else:
return self.tfun(x, *self.args, **self.kwargs) | [
"def",
"transform",
"(",
"self",
",",
"x",
",",
"use_spln",
"=",
"False",
",",
"*",
"*",
"kwargs",
")",
":",
"x",
"=",
"asarray",
"(",
"x",
",",
"dtype",
"=",
"float",
")",
"if",
"use_spln",
":",
"if",
"self",
".",
"spln",
"is",
"None",
":",
"s... | Apply transform to x
Parameters
----------
x : float-array-convertible
Data to be transformed.
Should support conversion to an array of floats.
use_spln: bool
True - transform using the spline specified in self.slpn.
If self.spln is None, set the spline.
False - transform using self.tfun
kwargs:
Keyword arguments to be passed to self.set_spline.
Only used if use_spln=True & self.spln=None.
Returns
-------
Array of transformed values. | [
"Apply",
"transform",
"to",
"x"
] | 4355632508b875273d68c7e2972c17668bcf7b40 | https://github.com/eyurtsev/FlowCytometryTools/blob/4355632508b875273d68c7e2972c17668bcf7b40/FlowCytometryTools/core/transforms.py#L358-L386 | train | 211,090 |
eyurtsev/FlowCytometryTools | fabfile.py | pypi_register | def pypi_register(server='pypitest'):
"""Register and prep user for PyPi upload.
.. note:: May need to weak ~/.pypirc file per issue:
http://stackoverflow.com/questions/1569315
"""
base_command = 'python setup.py register'
if server == 'pypitest':
command = base_command + ' -r https://testpypi.python.org/pypi'
else:
command = base_command
_execute_setup_command(command) | python | def pypi_register(server='pypitest'):
"""Register and prep user for PyPi upload.
.. note:: May need to weak ~/.pypirc file per issue:
http://stackoverflow.com/questions/1569315
"""
base_command = 'python setup.py register'
if server == 'pypitest':
command = base_command + ' -r https://testpypi.python.org/pypi'
else:
command = base_command
_execute_setup_command(command) | [
"def",
"pypi_register",
"(",
"server",
"=",
"'pypitest'",
")",
":",
"base_command",
"=",
"'python setup.py register'",
"if",
"server",
"==",
"'pypitest'",
":",
"command",
"=",
"base_command",
"+",
"' -r https://testpypi.python.org/pypi'",
"else",
":",
"command",
"=",
... | Register and prep user for PyPi upload.
.. note:: May need to weak ~/.pypirc file per issue:
http://stackoverflow.com/questions/1569315 | [
"Register",
"and",
"prep",
"user",
"for",
"PyPi",
"upload",
"."
] | 4355632508b875273d68c7e2972c17668bcf7b40 | https://github.com/eyurtsev/FlowCytometryTools/blob/4355632508b875273d68c7e2972c17668bcf7b40/fabfile.py#L95-L108 | train | 211,091 |
eyurtsev/FlowCytometryTools | FlowCytometryTools/gui/fc_widget.py | apply_format | def apply_format(var, format_str):
"""Format all non-iterables inside of the iterable var using the format_str
Example:
>>> print apply_format([2, [1, 4], 4, 1], '{:.1f}')
will return ['2.0', ['1.0', '4.0'], '4.0', '1.0']
"""
if isinstance(var, (list, tuple)):
new_var = map(lambda x: apply_format(x, format_str), var)
if isinstance(var, tuple):
new_var = '(' + ', '.join(new_var) + ')'
elif isinstance(var, list):
new_var = '[' + ', '.join(new_var) + ']'
return '{}'.format(new_var)
else:
return format_str.format(var) | python | def apply_format(var, format_str):
"""Format all non-iterables inside of the iterable var using the format_str
Example:
>>> print apply_format([2, [1, 4], 4, 1], '{:.1f}')
will return ['2.0', ['1.0', '4.0'], '4.0', '1.0']
"""
if isinstance(var, (list, tuple)):
new_var = map(lambda x: apply_format(x, format_str), var)
if isinstance(var, tuple):
new_var = '(' + ', '.join(new_var) + ')'
elif isinstance(var, list):
new_var = '[' + ', '.join(new_var) + ']'
return '{}'.format(new_var)
else:
return format_str.format(var) | [
"def",
"apply_format",
"(",
"var",
",",
"format_str",
")",
":",
"if",
"isinstance",
"(",
"var",
",",
"(",
"list",
",",
"tuple",
")",
")",
":",
"new_var",
"=",
"map",
"(",
"lambda",
"x",
":",
"apply_format",
"(",
"x",
",",
"format_str",
")",
",",
"v... | Format all non-iterables inside of the iterable var using the format_str
Example:
>>> print apply_format([2, [1, 4], 4, 1], '{:.1f}')
will return ['2.0', ['1.0', '4.0'], '4.0', '1.0'] | [
"Format",
"all",
"non",
"-",
"iterables",
"inside",
"of",
"the",
"iterable",
"var",
"using",
"the",
"format_str"
] | 4355632508b875273d68c7e2972c17668bcf7b40 | https://github.com/eyurtsev/FlowCytometryTools/blob/4355632508b875273d68c7e2972c17668bcf7b40/FlowCytometryTools/gui/fc_widget.py#L14-L30 | train | 211,092 |
eyurtsev/FlowCytometryTools | FlowCytometryTools/gui/fc_widget.py | _check_spawnable | def _check_spawnable(source_channels, target_channels):
"""Check whether gate is spawnable on the target channels."""
if len(target_channels) != len(set(target_channels)):
raise Exception('Spawn channels must be unique')
return source_channels.issubset(
set(target_channels)) | python | def _check_spawnable(source_channels, target_channels):
"""Check whether gate is spawnable on the target channels."""
if len(target_channels) != len(set(target_channels)):
raise Exception('Spawn channels must be unique')
return source_channels.issubset(
set(target_channels)) | [
"def",
"_check_spawnable",
"(",
"source_channels",
",",
"target_channels",
")",
":",
"if",
"len",
"(",
"target_channels",
")",
"!=",
"len",
"(",
"set",
"(",
"target_channels",
")",
")",
":",
"raise",
"Exception",
"(",
"'Spawn channels must be unique'",
")",
"ret... | Check whether gate is spawnable on the target channels. | [
"Check",
"whether",
"gate",
"is",
"spawnable",
"on",
"the",
"target",
"channels",
"."
] | 4355632508b875273d68c7e2972c17668bcf7b40 | https://github.com/eyurtsev/FlowCytometryTools/blob/4355632508b875273d68c7e2972c17668bcf7b40/FlowCytometryTools/gui/fc_widget.py#L76-L81 | train | 211,093 |
eyurtsev/FlowCytometryTools | FlowCytometryTools/gui/fc_widget.py | key_press_handler | def key_press_handler(event, canvas, toolbar=None):
"""
Handles keyboard shortcuts for the FCToolbar.
"""
if event.key is None: return
key = event.key.encode('ascii', 'ignore')
if key in ['1']:
toolbar.create_gate_widget(kind='poly')
elif key in ['2', '3', '4']:
kind = {'2': 'quad', '3': 'horizontal threshold', '4': 'vertical threshold'}[key]
toolbar.create_gate_widget(kind=kind)
elif key in ['9']:
toolbar.remove_active_gate()
elif key in ['0']:
toolbar.load_fcs()
elif key in ['a']:
toolbar.set_axes(('d1', 'd2'), pl.gca())
elif key in ['b']:
toolbar.set_axes(('d2', 'd1'), pl.gca())
elif key in ['c']:
toolbar.set_axes(('d1', 'd3'), pl.gca())
elif key in ['8']:
print(toolbar.get_generation_code()) | python | def key_press_handler(event, canvas, toolbar=None):
"""
Handles keyboard shortcuts for the FCToolbar.
"""
if event.key is None: return
key = event.key.encode('ascii', 'ignore')
if key in ['1']:
toolbar.create_gate_widget(kind='poly')
elif key in ['2', '3', '4']:
kind = {'2': 'quad', '3': 'horizontal threshold', '4': 'vertical threshold'}[key]
toolbar.create_gate_widget(kind=kind)
elif key in ['9']:
toolbar.remove_active_gate()
elif key in ['0']:
toolbar.load_fcs()
elif key in ['a']:
toolbar.set_axes(('d1', 'd2'), pl.gca())
elif key in ['b']:
toolbar.set_axes(('d2', 'd1'), pl.gca())
elif key in ['c']:
toolbar.set_axes(('d1', 'd3'), pl.gca())
elif key in ['8']:
print(toolbar.get_generation_code()) | [
"def",
"key_press_handler",
"(",
"event",
",",
"canvas",
",",
"toolbar",
"=",
"None",
")",
":",
"if",
"event",
".",
"key",
"is",
"None",
":",
"return",
"key",
"=",
"event",
".",
"key",
".",
"encode",
"(",
"'ascii'",
",",
"'ignore'",
")",
"if",
"key",... | Handles keyboard shortcuts for the FCToolbar. | [
"Handles",
"keyboard",
"shortcuts",
"for",
"the",
"FCToolbar",
"."
] | 4355632508b875273d68c7e2972c17668bcf7b40 | https://github.com/eyurtsev/FlowCytometryTools/blob/4355632508b875273d68c7e2972c17668bcf7b40/FlowCytometryTools/gui/fc_widget.py#L825-L849 | train | 211,094 |
eyurtsev/FlowCytometryTools | FlowCytometryTools/gui/fc_widget.py | EventGenerator.add_callback | def add_callback(self, func):
""" Registers a call back function """
if func is None: return
func_list = to_list(func)
if not hasattr(self, 'callback_list'):
self.callback_list = func_list
else:
self.callback_list.extend(func_list) | python | def add_callback(self, func):
""" Registers a call back function """
if func is None: return
func_list = to_list(func)
if not hasattr(self, 'callback_list'):
self.callback_list = func_list
else:
self.callback_list.extend(func_list) | [
"def",
"add_callback",
"(",
"self",
",",
"func",
")",
":",
"if",
"func",
"is",
"None",
":",
"return",
"func_list",
"=",
"to_list",
"(",
"func",
")",
"if",
"not",
"hasattr",
"(",
"self",
",",
"'callback_list'",
")",
":",
"self",
".",
"callback_list",
"=... | Registers a call back function | [
"Registers",
"a",
"call",
"back",
"function"
] | 4355632508b875273d68c7e2972c17668bcf7b40 | https://github.com/eyurtsev/FlowCytometryTools/blob/4355632508b875273d68c7e2972c17668bcf7b40/FlowCytometryTools/gui/fc_widget.py#L65-L73 | train | 211,095 |
eyurtsev/FlowCytometryTools | FlowCytometryTools/gui/fc_widget.py | SpawnableVertex.create_artist | def create_artist(self):
"""
decides whether the artist should be visible
or not in the current axis
current_axis : names of x, y axis
"""
verts = self.coordinates
if not self.tracky:
trans = self.ax.get_xaxis_transform(which='grid')
elif not self.trackx:
trans = self.ax.get_yaxis_transform(which='grid')
else:
trans = self.ax.transData
self.artist = pl.Line2D([verts[0]], [verts[1]], transform=trans, picker=15)
self.update_looks('inactive')
self.ax.add_artist(self.artist) | python | def create_artist(self):
"""
decides whether the artist should be visible
or not in the current axis
current_axis : names of x, y axis
"""
verts = self.coordinates
if not self.tracky:
trans = self.ax.get_xaxis_transform(which='grid')
elif not self.trackx:
trans = self.ax.get_yaxis_transform(which='grid')
else:
trans = self.ax.transData
self.artist = pl.Line2D([verts[0]], [verts[1]], transform=trans, picker=15)
self.update_looks('inactive')
self.ax.add_artist(self.artist) | [
"def",
"create_artist",
"(",
"self",
")",
":",
"verts",
"=",
"self",
".",
"coordinates",
"if",
"not",
"self",
".",
"tracky",
":",
"trans",
"=",
"self",
".",
"ax",
".",
"get_xaxis_transform",
"(",
"which",
"=",
"'grid'",
")",
"elif",
"not",
"self",
".",... | decides whether the artist should be visible
or not in the current axis
current_axis : names of x, y axis | [
"decides",
"whether",
"the",
"artist",
"should",
"be",
"visible",
"or",
"not",
"in",
"the",
"current",
"axis"
] | 4355632508b875273d68c7e2972c17668bcf7b40 | https://github.com/eyurtsev/FlowCytometryTools/blob/4355632508b875273d68c7e2972c17668bcf7b40/FlowCytometryTools/gui/fc_widget.py#L217-L235 | train | 211,096 |
eyurtsev/FlowCytometryTools | FlowCytometryTools/gui/fc_widget.py | SpawnableVertex.ignore | def ignore(self, event):
""" Ignores events. """
if hasattr(event, 'inaxes'):
if event.inaxes != self.ax:
return True
else:
return False | python | def ignore(self, event):
""" Ignores events. """
if hasattr(event, 'inaxes'):
if event.inaxes != self.ax:
return True
else:
return False | [
"def",
"ignore",
"(",
"self",
",",
"event",
")",
":",
"if",
"hasattr",
"(",
"event",
",",
"'inaxes'",
")",
":",
"if",
"event",
".",
"inaxes",
"!=",
"self",
".",
"ax",
":",
"return",
"True",
"else",
":",
"return",
"False"
] | Ignores events. | [
"Ignores",
"events",
"."
] | 4355632508b875273d68c7e2972c17668bcf7b40 | https://github.com/eyurtsev/FlowCytometryTools/blob/4355632508b875273d68c7e2972c17668bcf7b40/FlowCytometryTools/gui/fc_widget.py#L242-L248 | train | 211,097 |
eyurtsev/FlowCytometryTools | FlowCytometryTools/gui/fc_widget.py | BaseGate.spawn | def spawn(self, channels, ax):
""" Spawns a graphical gate that can be used to update the coordinates of the current gate. """
if _check_spawnable(self.source_channels, channels):
sgate = self.gate_type(self.verts, ax, channels)
self.spawn_list.append(sgate)
return sgate
else:
return None | python | def spawn(self, channels, ax):
""" Spawns a graphical gate that can be used to update the coordinates of the current gate. """
if _check_spawnable(self.source_channels, channels):
sgate = self.gate_type(self.verts, ax, channels)
self.spawn_list.append(sgate)
return sgate
else:
return None | [
"def",
"spawn",
"(",
"self",
",",
"channels",
",",
"ax",
")",
":",
"if",
"_check_spawnable",
"(",
"self",
".",
"source_channels",
",",
"channels",
")",
":",
"sgate",
"=",
"self",
".",
"gate_type",
"(",
"self",
".",
"verts",
",",
"ax",
",",
"channels",
... | Spawns a graphical gate that can be used to update the coordinates of the current gate. | [
"Spawns",
"a",
"graphical",
"gate",
"that",
"can",
"be",
"used",
"to",
"update",
"the",
"coordinates",
"of",
"the",
"current",
"gate",
"."
] | 4355632508b875273d68c7e2972c17668bcf7b40 | https://github.com/eyurtsev/FlowCytometryTools/blob/4355632508b875273d68c7e2972c17668bcf7b40/FlowCytometryTools/gui/fc_widget.py#L305-L312 | train | 211,098 |
eyurtsev/FlowCytometryTools | FlowCytometryTools/gui/fc_widget.py | BaseGate.remove_spawned_gates | def remove_spawned_gates(self, spawn_gate=None):
""" Removes all spawned gates. """
if spawn_gate is None:
for sg in list(self.spawn_list):
self.spawn_list.remove(sg)
sg.remove()
else:
spawn_gate.remove()
self.spawn_list.remove(spawn_gate) | python | def remove_spawned_gates(self, spawn_gate=None):
""" Removes all spawned gates. """
if spawn_gate is None:
for sg in list(self.spawn_list):
self.spawn_list.remove(sg)
sg.remove()
else:
spawn_gate.remove()
self.spawn_list.remove(spawn_gate) | [
"def",
"remove_spawned_gates",
"(",
"self",
",",
"spawn_gate",
"=",
"None",
")",
":",
"if",
"spawn_gate",
"is",
"None",
":",
"for",
"sg",
"in",
"list",
"(",
"self",
".",
"spawn_list",
")",
":",
"self",
".",
"spawn_list",
".",
"remove",
"(",
"sg",
")",
... | Removes all spawned gates. | [
"Removes",
"all",
"spawned",
"gates",
"."
] | 4355632508b875273d68c7e2972c17668bcf7b40 | https://github.com/eyurtsev/FlowCytometryTools/blob/4355632508b875273d68c7e2972c17668bcf7b40/FlowCytometryTools/gui/fc_widget.py#L314-L322 | train | 211,099 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.