repository_name stringlengths 5 67 | func_path_in_repository stringlengths 4 234 | func_name stringlengths 0 314 | whole_func_string stringlengths 52 3.87M | language stringclasses 6
values | func_code_string stringlengths 52 3.87M | func_code_tokens listlengths 15 672k | func_documentation_string stringlengths 1 47.2k | func_documentation_tokens listlengths 1 3.92k | split_name stringclasses 1
value | func_code_url stringlengths 85 339 |
|---|---|---|---|---|---|---|---|---|---|---|
TracyWebTech/django-conversejs | conversejs/boshclient.py | BOSHClient.authenticate_xmpp | def authenticate_xmpp(self):
"""Authenticate the user to the XMPP server via the BOSH connection."""
self.request_sid()
self.log.debug('Prepare the XMPP authentication')
# Instantiate a sasl object
sasl = SASLClient(
host=self.to,
service='xmpp',
username=self.jid,
password=self.password
)
# Choose an auth mechanism
sasl.choose_mechanism(self.server_auth, allow_anonymous=False)
# Request challenge
challenge = self.get_challenge(sasl.mechanism)
# Process challenge and generate response
response = sasl.process(base64.b64decode(challenge))
# Send response
resp_root = self.send_challenge_response(response)
success = self.check_authenticate_success(resp_root)
if success is None and\
resp_root.find('{{{0}}}challenge'.format(XMPP_SASL_NS)) is not None:
resp_root = self.send_challenge_response('')
return self.check_authenticate_success(resp_root)
return success | python | def authenticate_xmpp(self):
"""Authenticate the user to the XMPP server via the BOSH connection."""
self.request_sid()
self.log.debug('Prepare the XMPP authentication')
# Instantiate a sasl object
sasl = SASLClient(
host=self.to,
service='xmpp',
username=self.jid,
password=self.password
)
# Choose an auth mechanism
sasl.choose_mechanism(self.server_auth, allow_anonymous=False)
# Request challenge
challenge = self.get_challenge(sasl.mechanism)
# Process challenge and generate response
response = sasl.process(base64.b64decode(challenge))
# Send response
resp_root = self.send_challenge_response(response)
success = self.check_authenticate_success(resp_root)
if success is None and\
resp_root.find('{{{0}}}challenge'.format(XMPP_SASL_NS)) is not None:
resp_root = self.send_challenge_response('')
return self.check_authenticate_success(resp_root)
return success | [
"def",
"authenticate_xmpp",
"(",
"self",
")",
":",
"self",
".",
"request_sid",
"(",
")",
"self",
".",
"log",
".",
"debug",
"(",
"'Prepare the XMPP authentication'",
")",
"# Instantiate a sasl object",
"sasl",
"=",
"SASLClient",
"(",
"host",
"=",
"self",
".",
"... | Authenticate the user to the XMPP server via the BOSH connection. | [
"Authenticate",
"the",
"user",
"to",
"the",
"XMPP",
"server",
"via",
"the",
"BOSH",
"connection",
"."
] | train | https://github.com/TracyWebTech/django-conversejs/blob/cd9176f007ef3853ea6321bf93b466644d89305b/conversejs/boshclient.py#L249-L281 |
gwastro/pycbc-glue | pycbc_glue/ligolw/param.py | getParamsByName | def getParamsByName(elem, name):
"""
Return a list of params with name name under elem.
"""
name = StripParamName(name)
return elem.getElements(lambda e: (e.tagName == ligolw.Param.tagName) and (e.Name == name)) | python | def getParamsByName(elem, name):
"""
Return a list of params with name name under elem.
"""
name = StripParamName(name)
return elem.getElements(lambda e: (e.tagName == ligolw.Param.tagName) and (e.Name == name)) | [
"def",
"getParamsByName",
"(",
"elem",
",",
"name",
")",
":",
"name",
"=",
"StripParamName",
"(",
"name",
")",
"return",
"elem",
".",
"getElements",
"(",
"lambda",
"e",
":",
"(",
"e",
".",
"tagName",
"==",
"ligolw",
".",
"Param",
".",
"tagName",
")",
... | Return a list of params with name name under elem. | [
"Return",
"a",
"list",
"of",
"params",
"with",
"name",
"name",
"under",
"elem",
"."
] | train | https://github.com/gwastro/pycbc-glue/blob/a3e906bae59fbfd707c3ff82e5d008d939ec5e24/pycbc_glue/ligolw/param.py#L91-L96 |
gwastro/pycbc-glue | pycbc_glue/ligolw/param.py | new_param | def new_param(name, type, value, start = None, scale = None, unit = None, dataunit = None, comment = None):
"""
Construct a LIGO Light Weight XML Param document subtree. FIXME:
document keyword arguments.
"""
elem = Param()
elem.Name = name
elem.Type = type
elem.pcdata = value
# FIXME: I have no idea how most of the attributes should be
# encoded, I don't even know what they're supposed to be.
if dataunit is not None:
elem.DataUnit = dataunit
if scale is not None:
elem.Scale = scale
if start is not None:
elem.Start = start
if unit is not None:
elem.Unit = unit
if comment is not None:
elem.appendChild(ligolw.Comment())
elem.childNodes[-1].pcdata = comment
return elem | python | def new_param(name, type, value, start = None, scale = None, unit = None, dataunit = None, comment = None):
"""
Construct a LIGO Light Weight XML Param document subtree. FIXME:
document keyword arguments.
"""
elem = Param()
elem.Name = name
elem.Type = type
elem.pcdata = value
# FIXME: I have no idea how most of the attributes should be
# encoded, I don't even know what they're supposed to be.
if dataunit is not None:
elem.DataUnit = dataunit
if scale is not None:
elem.Scale = scale
if start is not None:
elem.Start = start
if unit is not None:
elem.Unit = unit
if comment is not None:
elem.appendChild(ligolw.Comment())
elem.childNodes[-1].pcdata = comment
return elem | [
"def",
"new_param",
"(",
"name",
",",
"type",
",",
"value",
",",
"start",
"=",
"None",
",",
"scale",
"=",
"None",
",",
"unit",
"=",
"None",
",",
"dataunit",
"=",
"None",
",",
"comment",
"=",
"None",
")",
":",
"elem",
"=",
"Param",
"(",
")",
"elem... | Construct a LIGO Light Weight XML Param document subtree. FIXME:
document keyword arguments. | [
"Construct",
"a",
"LIGO",
"Light",
"Weight",
"XML",
"Param",
"document",
"subtree",
".",
"FIXME",
":",
"document",
"keyword",
"arguments",
"."
] | train | https://github.com/gwastro/pycbc-glue/blob/a3e906bae59fbfd707c3ff82e5d008d939ec5e24/pycbc_glue/ligolw/param.py#L108-L130 |
gwastro/pycbc-glue | pycbc_glue/ligolw/param.py | get_param | def get_param(xmldoc, name):
"""
Scan xmldoc for a param named name. Raises ValueError if not
exactly 1 such param is found.
"""
params = getParamsByName(xmldoc, name)
if len(params) != 1:
raise ValueError("document must contain exactly one %s param" % StripParamName(name))
return params[0] | python | def get_param(xmldoc, name):
"""
Scan xmldoc for a param named name. Raises ValueError if not
exactly 1 such param is found.
"""
params = getParamsByName(xmldoc, name)
if len(params) != 1:
raise ValueError("document must contain exactly one %s param" % StripParamName(name))
return params[0] | [
"def",
"get_param",
"(",
"xmldoc",
",",
"name",
")",
":",
"params",
"=",
"getParamsByName",
"(",
"xmldoc",
",",
"name",
")",
"if",
"len",
"(",
"params",
")",
"!=",
"1",
":",
"raise",
"ValueError",
"(",
"\"document must contain exactly one %s param\"",
"%",
"... | Scan xmldoc for a param named name. Raises ValueError if not
exactly 1 such param is found. | [
"Scan",
"xmldoc",
"for",
"a",
"param",
"named",
"name",
".",
"Raises",
"ValueError",
"if",
"not",
"exactly",
"1",
"such",
"param",
"is",
"found",
"."
] | train | https://github.com/gwastro/pycbc-glue/blob/a3e906bae59fbfd707c3ff82e5d008d939ec5e24/pycbc_glue/ligolw/param.py#L133-L141 |
gwastro/pycbc-glue | pycbc_glue/ligolw/param.py | from_pyvalue | def from_pyvalue(name, value, **kwargs):
"""
Convenience wrapper for new_param() that constructs a Param element
from an instance of a Python builtin type. See new_param() for a
description of the valid keyword arguments.
"""
return new_param(name, ligolwtypes.FromPyType[type(value)], value, **kwargs) | python | def from_pyvalue(name, value, **kwargs):
"""
Convenience wrapper for new_param() that constructs a Param element
from an instance of a Python builtin type. See new_param() for a
description of the valid keyword arguments.
"""
return new_param(name, ligolwtypes.FromPyType[type(value)], value, **kwargs) | [
"def",
"from_pyvalue",
"(",
"name",
",",
"value",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"new_param",
"(",
"name",
",",
"ligolwtypes",
".",
"FromPyType",
"[",
"type",
"(",
"value",
")",
"]",
",",
"value",
",",
"*",
"*",
"kwargs",
")"
] | Convenience wrapper for new_param() that constructs a Param element
from an instance of a Python builtin type. See new_param() for a
description of the valid keyword arguments. | [
"Convenience",
"wrapper",
"for",
"new_param",
"()",
"that",
"constructs",
"a",
"Param",
"element",
"from",
"an",
"instance",
"of",
"a",
"Python",
"builtin",
"type",
".",
"See",
"new_param",
"()",
"for",
"a",
"description",
"of",
"the",
"valid",
"keyword",
"a... | train | https://github.com/gwastro/pycbc-glue/blob/a3e906bae59fbfd707c3ff82e5d008d939ec5e24/pycbc_glue/ligolw/param.py#L144-L150 |
gwastro/pycbc-glue | pycbc_glue/ligolw/param.py | pickle_to_param | def pickle_to_param(obj, name):
"""
Return the top-level element of a document sub-tree containing the
pickled serialization of a Python object.
"""
return from_pyvalue(u"pickle:%s" % name, unicode(pickle.dumps(obj))) | python | def pickle_to_param(obj, name):
"""
Return the top-level element of a document sub-tree containing the
pickled serialization of a Python object.
"""
return from_pyvalue(u"pickle:%s" % name, unicode(pickle.dumps(obj))) | [
"def",
"pickle_to_param",
"(",
"obj",
",",
"name",
")",
":",
"return",
"from_pyvalue",
"(",
"u\"pickle:%s\"",
"%",
"name",
",",
"unicode",
"(",
"pickle",
".",
"dumps",
"(",
"obj",
")",
")",
")"
] | Return the top-level element of a document sub-tree containing the
pickled serialization of a Python object. | [
"Return",
"the",
"top",
"-",
"level",
"element",
"of",
"a",
"document",
"sub",
"-",
"tree",
"containing",
"the",
"pickled",
"serialization",
"of",
"a",
"Python",
"object",
"."
] | train | https://github.com/gwastro/pycbc-glue/blob/a3e906bae59fbfd707c3ff82e5d008d939ec5e24/pycbc_glue/ligolw/param.py#L172-L177 |
gwastro/pycbc-glue | pycbc_glue/ligolw/param.py | pickle_from_param | def pickle_from_param(elem, name):
"""
Retrieve a pickled Python object from the document tree rooted at
elem.
"""
return pickle.loads(str(get_pyvalue(elem, u"pickle:%s" % name))) | python | def pickle_from_param(elem, name):
"""
Retrieve a pickled Python object from the document tree rooted at
elem.
"""
return pickle.loads(str(get_pyvalue(elem, u"pickle:%s" % name))) | [
"def",
"pickle_from_param",
"(",
"elem",
",",
"name",
")",
":",
"return",
"pickle",
".",
"loads",
"(",
"str",
"(",
"get_pyvalue",
"(",
"elem",
",",
"u\"pickle:%s\"",
"%",
"name",
")",
")",
")"
] | Retrieve a pickled Python object from the document tree rooted at
elem. | [
"Retrieve",
"a",
"pickled",
"Python",
"object",
"from",
"the",
"document",
"tree",
"rooted",
"at",
"elem",
"."
] | train | https://github.com/gwastro/pycbc-glue/blob/a3e906bae59fbfd707c3ff82e5d008d939ec5e24/pycbc_glue/ligolw/param.py#L180-L185 |
gwastro/pycbc-glue | pycbc_glue/ligolw/param.py | yaml_to_param | def yaml_to_param(obj, name):
"""
Return the top-level element of a document sub-tree containing the
YAML serialization of a Python object.
"""
return from_pyvalue(u"yaml:%s" % name, unicode(yaml.dump(obj))) | python | def yaml_to_param(obj, name):
"""
Return the top-level element of a document sub-tree containing the
YAML serialization of a Python object.
"""
return from_pyvalue(u"yaml:%s" % name, unicode(yaml.dump(obj))) | [
"def",
"yaml_to_param",
"(",
"obj",
",",
"name",
")",
":",
"return",
"from_pyvalue",
"(",
"u\"yaml:%s\"",
"%",
"name",
",",
"unicode",
"(",
"yaml",
".",
"dump",
"(",
"obj",
")",
")",
")"
] | Return the top-level element of a document sub-tree containing the
YAML serialization of a Python object. | [
"Return",
"the",
"top",
"-",
"level",
"element",
"of",
"a",
"document",
"sub",
"-",
"tree",
"containing",
"the",
"YAML",
"serialization",
"of",
"a",
"Python",
"object",
"."
] | train | https://github.com/gwastro/pycbc-glue/blob/a3e906bae59fbfd707c3ff82e5d008d939ec5e24/pycbc_glue/ligolw/param.py#L188-L193 |
gwastro/pycbc-glue | pycbc_glue/ligolw/param.py | use_in | def use_in(ContentHandler):
"""
Modify ContentHandler, a sub-class of
pycbc_glue.ligolw.LIGOLWContentHandler, to cause it to use the Param
class defined in this module when parsing XML documents.
Example:
>>> from pycbc_glue.ligolw import ligolw
>>> def MyContentHandler(ligolw.LIGOLWContentHandler):
... pass
...
>>> use_in(MyContentHandler)
"""
def startParam(self, parent, attrs):
return Param(attrs)
ContentHandler.startParam = startParam
return ContentHandler | python | def use_in(ContentHandler):
"""
Modify ContentHandler, a sub-class of
pycbc_glue.ligolw.LIGOLWContentHandler, to cause it to use the Param
class defined in this module when parsing XML documents.
Example:
>>> from pycbc_glue.ligolw import ligolw
>>> def MyContentHandler(ligolw.LIGOLWContentHandler):
... pass
...
>>> use_in(MyContentHandler)
"""
def startParam(self, parent, attrs):
return Param(attrs)
ContentHandler.startParam = startParam
return ContentHandler | [
"def",
"use_in",
"(",
"ContentHandler",
")",
":",
"def",
"startParam",
"(",
"self",
",",
"parent",
",",
"attrs",
")",
":",
"return",
"Param",
"(",
"attrs",
")",
"ContentHandler",
".",
"startParam",
"=",
"startParam",
"return",
"ContentHandler"
] | Modify ContentHandler, a sub-class of
pycbc_glue.ligolw.LIGOLWContentHandler, to cause it to use the Param
class defined in this module when parsing XML documents.
Example:
>>> from pycbc_glue.ligolw import ligolw
>>> def MyContentHandler(ligolw.LIGOLWContentHandler):
... pass
...
>>> use_in(MyContentHandler) | [
"Modify",
"ContentHandler",
"a",
"sub",
"-",
"class",
"of",
"pycbc_glue",
".",
"ligolw",
".",
"LIGOLWContentHandler",
"to",
"cause",
"it",
"to",
"use",
"the",
"Param",
"class",
"defined",
"in",
"this",
"module",
"when",
"parsing",
"XML",
"documents",
"."
] | train | https://github.com/gwastro/pycbc-glue/blob/a3e906bae59fbfd707c3ff82e5d008d939ec5e24/pycbc_glue/ligolw/param.py#L294-L313 |
nickstenning/tagalog | tagalog/shipper.py | RoundRobinConnectionPool.all_connections | def all_connections(self):
"""Returns a generator over all current connection objects"""
for i in _xrange(self.num_patterns):
for c in self._available_connections[i]:
yield c
for c in self._in_use_connections[i]:
yield c | python | def all_connections(self):
"""Returns a generator over all current connection objects"""
for i in _xrange(self.num_patterns):
for c in self._available_connections[i]:
yield c
for c in self._in_use_connections[i]:
yield c | [
"def",
"all_connections",
"(",
"self",
")",
":",
"for",
"i",
"in",
"_xrange",
"(",
"self",
".",
"num_patterns",
")",
":",
"for",
"c",
"in",
"self",
".",
"_available_connections",
"[",
"i",
"]",
":",
"yield",
"c",
"for",
"c",
"in",
"self",
".",
"_in_u... | Returns a generator over all current connection objects | [
"Returns",
"a",
"generator",
"over",
"all",
"current",
"connection",
"objects"
] | train | https://github.com/nickstenning/tagalog/blob/c6847a957dc4f96836a5cf13c4eb664fccafaac2/tagalog/shipper.py#L100-L106 |
nickstenning/tagalog | tagalog/shipper.py | RoundRobinConnectionPool.get_connection | def get_connection(self, command_name, *keys, **options):
"""Get a connection from the pool"""
self._checkpid()
try:
connection = self._available_connections[self._pattern_idx].pop()
except IndexError:
connection = self.make_connection()
self._in_use_connections[self._pattern_idx].add(connection)
self._next_pattern()
return connection | python | def get_connection(self, command_name, *keys, **options):
"""Get a connection from the pool"""
self._checkpid()
try:
connection = self._available_connections[self._pattern_idx].pop()
except IndexError:
connection = self.make_connection()
self._in_use_connections[self._pattern_idx].add(connection)
self._next_pattern()
return connection | [
"def",
"get_connection",
"(",
"self",
",",
"command_name",
",",
"*",
"keys",
",",
"*",
"*",
"options",
")",
":",
"self",
".",
"_checkpid",
"(",
")",
"try",
":",
"connection",
"=",
"self",
".",
"_available_connections",
"[",
"self",
".",
"_pattern_idx",
"... | Get a connection from the pool | [
"Get",
"a",
"connection",
"from",
"the",
"pool"
] | train | https://github.com/nickstenning/tagalog/blob/c6847a957dc4f96836a5cf13c4eb664fccafaac2/tagalog/shipper.py#L108-L117 |
nickstenning/tagalog | tagalog/shipper.py | RoundRobinConnectionPool.make_connection | def make_connection(self):
"""Create a new connection"""
if self._created_connections[self._pattern_idx] >= self.max_connections_per_pattern:
raise ConnectionError("Too many connections")
self._created_connections[self._pattern_idx] += 1
conn = self.connection_class(**self.patterns[self._pattern_idx])
conn._pattern_idx = self._pattern_idx
return conn | python | def make_connection(self):
"""Create a new connection"""
if self._created_connections[self._pattern_idx] >= self.max_connections_per_pattern:
raise ConnectionError("Too many connections")
self._created_connections[self._pattern_idx] += 1
conn = self.connection_class(**self.patterns[self._pattern_idx])
conn._pattern_idx = self._pattern_idx
return conn | [
"def",
"make_connection",
"(",
"self",
")",
":",
"if",
"self",
".",
"_created_connections",
"[",
"self",
".",
"_pattern_idx",
"]",
">=",
"self",
".",
"max_connections_per_pattern",
":",
"raise",
"ConnectionError",
"(",
"\"Too many connections\"",
")",
"self",
".",... | Create a new connection | [
"Create",
"a",
"new",
"connection"
] | train | https://github.com/nickstenning/tagalog/blob/c6847a957dc4f96836a5cf13c4eb664fccafaac2/tagalog/shipper.py#L119-L126 |
nickstenning/tagalog | tagalog/shipper.py | RoundRobinConnectionPool.release | def release(self, connection):
"""Releases the connection back to the pool"""
self._checkpid()
if connection.pid == self.pid:
idx = connection._pattern_idx
self._in_use_connections[idx].remove(connection)
self._available_connections[idx].append(connection) | python | def release(self, connection):
"""Releases the connection back to the pool"""
self._checkpid()
if connection.pid == self.pid:
idx = connection._pattern_idx
self._in_use_connections[idx].remove(connection)
self._available_connections[idx].append(connection) | [
"def",
"release",
"(",
"self",
",",
"connection",
")",
":",
"self",
".",
"_checkpid",
"(",
")",
"if",
"connection",
".",
"pid",
"==",
"self",
".",
"pid",
":",
"idx",
"=",
"connection",
".",
"_pattern_idx",
"self",
".",
"_in_use_connections",
"[",
"idx",
... | Releases the connection back to the pool | [
"Releases",
"the",
"connection",
"back",
"to",
"the",
"pool"
] | train | https://github.com/nickstenning/tagalog/blob/c6847a957dc4f96836a5cf13c4eb664fccafaac2/tagalog/shipper.py#L128-L134 |
nickstenning/tagalog | tagalog/shipper.py | RoundRobinConnectionPool.purge | def purge(self, connection):
"""Remove the connection from rotation"""
self._checkpid()
if connection.pid == self.pid:
idx = connection._pattern_idx
if connection in self._in_use_connections[idx]:
self._in_use_connections[idx].remove(connection)
else:
self._available_connections[idx].remove(connection)
connection.disconnect() | python | def purge(self, connection):
"""Remove the connection from rotation"""
self._checkpid()
if connection.pid == self.pid:
idx = connection._pattern_idx
if connection in self._in_use_connections[idx]:
self._in_use_connections[idx].remove(connection)
else:
self._available_connections[idx].remove(connection)
connection.disconnect() | [
"def",
"purge",
"(",
"self",
",",
"connection",
")",
":",
"self",
".",
"_checkpid",
"(",
")",
"if",
"connection",
".",
"pid",
"==",
"self",
".",
"pid",
":",
"idx",
"=",
"connection",
".",
"_pattern_idx",
"if",
"connection",
"in",
"self",
".",
"_in_use_... | Remove the connection from rotation | [
"Remove",
"the",
"connection",
"from",
"rotation"
] | train | https://github.com/nickstenning/tagalog/blob/c6847a957dc4f96836a5cf13c4eb664fccafaac2/tagalog/shipper.py#L136-L145 |
nickstenning/tagalog | tagalog/shipper.py | ResilientStrictRedis.execute_command | def execute_command(self, *args, **options):
"""Execute a command and return a parsed response"""
pool = self.connection_pool
command_name = args[0]
for i in _xrange(self.execution_attempts):
connection = pool.get_connection(command_name, **options)
try:
connection.send_command(*args)
res = self.parse_response(connection, command_name, **options)
pool.release(connection)
return res
except ConnectionError:
pool.purge(connection)
if i >= self.execution_attempts - 1:
raise | python | def execute_command(self, *args, **options):
"""Execute a command and return a parsed response"""
pool = self.connection_pool
command_name = args[0]
for i in _xrange(self.execution_attempts):
connection = pool.get_connection(command_name, **options)
try:
connection.send_command(*args)
res = self.parse_response(connection, command_name, **options)
pool.release(connection)
return res
except ConnectionError:
pool.purge(connection)
if i >= self.execution_attempts - 1:
raise | [
"def",
"execute_command",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"options",
")",
":",
"pool",
"=",
"self",
".",
"connection_pool",
"command_name",
"=",
"args",
"[",
"0",
"]",
"for",
"i",
"in",
"_xrange",
"(",
"self",
".",
"execution_attempts",
"... | Execute a command and return a parsed response | [
"Execute",
"a",
"command",
"and",
"return",
"a",
"parsed",
"response"
] | train | https://github.com/nickstenning/tagalog/blob/c6847a957dc4f96836a5cf13c4eb664fccafaac2/tagalog/shipper.py#L164-L178 |
gwastro/pycbc-glue | pycbc_glue/ligolw/utils/__init__.py | sort_files_by_size | def sort_files_by_size(filenames, verbose = False, reverse = False):
"""
Return a list of the filenames sorted in order from smallest file
to largest file (or largest to smallest if reverse is set to True).
If a filename in the list is None (used by many pycbc_glue.ligolw based
codes to indicate stdin), its size is treated as 0. The filenames
may be any sequence, including generator expressions.
"""
if verbose:
if reverse:
print >>sys.stderr, "sorting files from largest to smallest ..."
else:
print >>sys.stderr, "sorting files from smallest to largest ..."
return sorted(filenames, key = (lambda filename: os.stat(filename)[stat.ST_SIZE] if filename is not None else 0), reverse = reverse) | python | def sort_files_by_size(filenames, verbose = False, reverse = False):
"""
Return a list of the filenames sorted in order from smallest file
to largest file (or largest to smallest if reverse is set to True).
If a filename in the list is None (used by many pycbc_glue.ligolw based
codes to indicate stdin), its size is treated as 0. The filenames
may be any sequence, including generator expressions.
"""
if verbose:
if reverse:
print >>sys.stderr, "sorting files from largest to smallest ..."
else:
print >>sys.stderr, "sorting files from smallest to largest ..."
return sorted(filenames, key = (lambda filename: os.stat(filename)[stat.ST_SIZE] if filename is not None else 0), reverse = reverse) | [
"def",
"sort_files_by_size",
"(",
"filenames",
",",
"verbose",
"=",
"False",
",",
"reverse",
"=",
"False",
")",
":",
"if",
"verbose",
":",
"if",
"reverse",
":",
"print",
">>",
"sys",
".",
"stderr",
",",
"\"sorting files from largest to smallest ...\"",
"else",
... | Return a list of the filenames sorted in order from smallest file
to largest file (or largest to smallest if reverse is set to True).
If a filename in the list is None (used by many pycbc_glue.ligolw based
codes to indicate stdin), its size is treated as 0. The filenames
may be any sequence, including generator expressions. | [
"Return",
"a",
"list",
"of",
"the",
"filenames",
"sorted",
"in",
"order",
"from",
"smallest",
"file",
"to",
"largest",
"file",
"(",
"or",
"largest",
"to",
"smallest",
"if",
"reverse",
"is",
"set",
"to",
"True",
")",
".",
"If",
"a",
"filename",
"in",
"t... | train | https://github.com/gwastro/pycbc-glue/blob/a3e906bae59fbfd707c3ff82e5d008d939ec5e24/pycbc_glue/ligolw/utils/__init__.py#L79-L92 |
gwastro/pycbc-glue | pycbc_glue/ligolw/utils/__init__.py | local_path_from_url | def local_path_from_url(url):
"""
For URLs that point to locations in the local filesystem, extract
and return the filesystem path of the object to which they point.
As a special case pass-through, if the URL is None, the return
value is None. Raises ValueError if the URL is not None and does
not point to a local file.
Example:
>>> print local_path_from_url(None)
None
>>> local_path_from_url("file:///home/me/somefile.xml.gz")
'/home/me/somefile.xml.gz'
"""
if url is None:
return None
scheme, host, path = urlparse.urlparse(url)[:3]
if scheme.lower() not in ("", "file") or host.lower() not in ("", "localhost"):
raise ValueError("%s is not a local file" % repr(url))
return path | python | def local_path_from_url(url):
"""
For URLs that point to locations in the local filesystem, extract
and return the filesystem path of the object to which they point.
As a special case pass-through, if the URL is None, the return
value is None. Raises ValueError if the URL is not None and does
not point to a local file.
Example:
>>> print local_path_from_url(None)
None
>>> local_path_from_url("file:///home/me/somefile.xml.gz")
'/home/me/somefile.xml.gz'
"""
if url is None:
return None
scheme, host, path = urlparse.urlparse(url)[:3]
if scheme.lower() not in ("", "file") or host.lower() not in ("", "localhost"):
raise ValueError("%s is not a local file" % repr(url))
return path | [
"def",
"local_path_from_url",
"(",
"url",
")",
":",
"if",
"url",
"is",
"None",
":",
"return",
"None",
"scheme",
",",
"host",
",",
"path",
"=",
"urlparse",
".",
"urlparse",
"(",
"url",
")",
"[",
":",
"3",
"]",
"if",
"scheme",
".",
"lower",
"(",
")",... | For URLs that point to locations in the local filesystem, extract
and return the filesystem path of the object to which they point.
As a special case pass-through, if the URL is None, the return
value is None. Raises ValueError if the URL is not None and does
not point to a local file.
Example:
>>> print local_path_from_url(None)
None
>>> local_path_from_url("file:///home/me/somefile.xml.gz")
'/home/me/somefile.xml.gz' | [
"For",
"URLs",
"that",
"point",
"to",
"locations",
"in",
"the",
"local",
"filesystem",
"extract",
"and",
"return",
"the",
"filesystem",
"path",
"of",
"the",
"object",
"to",
"which",
"they",
"point",
".",
"As",
"a",
"special",
"case",
"pass",
"-",
"through"... | train | https://github.com/gwastro/pycbc-glue/blob/a3e906bae59fbfd707c3ff82e5d008d939ec5e24/pycbc_glue/ligolw/utils/__init__.py#L95-L115 |
gwastro/pycbc-glue | pycbc_glue/ligolw/utils/__init__.py | load_fileobj | def load_fileobj(fileobj, gz = None, xmldoc = None, contenthandler = None):
"""
Parse the contents of the file object fileobj, and return the
contents as a LIGO Light Weight document tree. The file object
does not need to be seekable.
If the gz parameter is None (the default) then gzip compressed data
will be automatically detected and decompressed, otherwise
decompression can be forced on or off by setting gz to True or
False respectively.
If the optional xmldoc argument is provided and not None, the
parsed XML tree will be appended to that document, otherwise a new
document will be created. The return value is a tuple, the first
element of the tuple is the XML document and the second is a string
containing the MD5 digest in hex digits of the bytestream that was
parsed.
Example:
>>> from pycbc_glue.ligolw import ligolw
>>> import StringIO
>>> f = StringIO.StringIO('<?xml version="1.0" encoding="utf-8" ?><!DOCTYPE LIGO_LW SYSTEM "http://ldas-sw.ligo.caltech.edu/doc/ligolwAPI/html/ligolw_dtd.txt"><LIGO_LW><Table Name="demo:table"><Column Name="name" Type="lstring"/><Column Name="value" Type="real8"/><Stream Name="demo:table" Type="Local" Delimiter=",">"mass",0.5,"velocity",34</Stream></Table></LIGO_LW>')
>>> xmldoc, digest = load_fileobj(f, contenthandler = ligolw.LIGOLWContentHandler)
>>> digest
'6bdcc4726b892aad913531684024ed8e'
The contenthandler argument specifies the SAX content handler to
use when parsing the document. The contenthandler is a required
argument. See the pycbc_glue.ligolw package documentation for typical
parsing scenario involving a custom content handler. See
pycbc_glue.ligolw.ligolw.PartialLIGOLWContentHandler and
pycbc_glue.ligolw.ligolw.FilteringLIGOLWContentHandler for examples of
custom content handlers used to load subsets of documents into
memory.
"""
fileobj = MD5File(fileobj)
md5obj = fileobj.md5obj
if gz or gz is None:
fileobj = RewindableInputFile(fileobj)
magic = fileobj.read(2)
fileobj.seek(0, os.SEEK_SET)
if gz or magic == '\037\213':
fileobj = gzip.GzipFile(mode = "rb", fileobj = fileobj)
if xmldoc is None:
xmldoc = ligolw.Document()
ligolw.make_parser(contenthandler(xmldoc)).parse(fileobj)
return xmldoc, md5obj.hexdigest() | python | def load_fileobj(fileobj, gz = None, xmldoc = None, contenthandler = None):
"""
Parse the contents of the file object fileobj, and return the
contents as a LIGO Light Weight document tree. The file object
does not need to be seekable.
If the gz parameter is None (the default) then gzip compressed data
will be automatically detected and decompressed, otherwise
decompression can be forced on or off by setting gz to True or
False respectively.
If the optional xmldoc argument is provided and not None, the
parsed XML tree will be appended to that document, otherwise a new
document will be created. The return value is a tuple, the first
element of the tuple is the XML document and the second is a string
containing the MD5 digest in hex digits of the bytestream that was
parsed.
Example:
>>> from pycbc_glue.ligolw import ligolw
>>> import StringIO
>>> f = StringIO.StringIO('<?xml version="1.0" encoding="utf-8" ?><!DOCTYPE LIGO_LW SYSTEM "http://ldas-sw.ligo.caltech.edu/doc/ligolwAPI/html/ligolw_dtd.txt"><LIGO_LW><Table Name="demo:table"><Column Name="name" Type="lstring"/><Column Name="value" Type="real8"/><Stream Name="demo:table" Type="Local" Delimiter=",">"mass",0.5,"velocity",34</Stream></Table></LIGO_LW>')
>>> xmldoc, digest = load_fileobj(f, contenthandler = ligolw.LIGOLWContentHandler)
>>> digest
'6bdcc4726b892aad913531684024ed8e'
The contenthandler argument specifies the SAX content handler to
use when parsing the document. The contenthandler is a required
argument. See the pycbc_glue.ligolw package documentation for typical
parsing scenario involving a custom content handler. See
pycbc_glue.ligolw.ligolw.PartialLIGOLWContentHandler and
pycbc_glue.ligolw.ligolw.FilteringLIGOLWContentHandler for examples of
custom content handlers used to load subsets of documents into
memory.
"""
fileobj = MD5File(fileobj)
md5obj = fileobj.md5obj
if gz or gz is None:
fileobj = RewindableInputFile(fileobj)
magic = fileobj.read(2)
fileobj.seek(0, os.SEEK_SET)
if gz or magic == '\037\213':
fileobj = gzip.GzipFile(mode = "rb", fileobj = fileobj)
if xmldoc is None:
xmldoc = ligolw.Document()
ligolw.make_parser(contenthandler(xmldoc)).parse(fileobj)
return xmldoc, md5obj.hexdigest() | [
"def",
"load_fileobj",
"(",
"fileobj",
",",
"gz",
"=",
"None",
",",
"xmldoc",
"=",
"None",
",",
"contenthandler",
"=",
"None",
")",
":",
"fileobj",
"=",
"MD5File",
"(",
"fileobj",
")",
"md5obj",
"=",
"fileobj",
".",
"md5obj",
"if",
"gz",
"or",
"gz",
... | Parse the contents of the file object fileobj, and return the
contents as a LIGO Light Weight document tree. The file object
does not need to be seekable.
If the gz parameter is None (the default) then gzip compressed data
will be automatically detected and decompressed, otherwise
decompression can be forced on or off by setting gz to True or
False respectively.
If the optional xmldoc argument is provided and not None, the
parsed XML tree will be appended to that document, otherwise a new
document will be created. The return value is a tuple, the first
element of the tuple is the XML document and the second is a string
containing the MD5 digest in hex digits of the bytestream that was
parsed.
Example:
>>> from pycbc_glue.ligolw import ligolw
>>> import StringIO
>>> f = StringIO.StringIO('<?xml version="1.0" encoding="utf-8" ?><!DOCTYPE LIGO_LW SYSTEM "http://ldas-sw.ligo.caltech.edu/doc/ligolwAPI/html/ligolw_dtd.txt"><LIGO_LW><Table Name="demo:table"><Column Name="name" Type="lstring"/><Column Name="value" Type="real8"/><Stream Name="demo:table" Type="Local" Delimiter=",">"mass",0.5,"velocity",34</Stream></Table></LIGO_LW>')
>>> xmldoc, digest = load_fileobj(f, contenthandler = ligolw.LIGOLWContentHandler)
>>> digest
'6bdcc4726b892aad913531684024ed8e'
The contenthandler argument specifies the SAX content handler to
use when parsing the document. The contenthandler is a required
argument. See the pycbc_glue.ligolw package documentation for typical
parsing scenario involving a custom content handler. See
pycbc_glue.ligolw.ligolw.PartialLIGOLWContentHandler and
pycbc_glue.ligolw.ligolw.FilteringLIGOLWContentHandler for examples of
custom content handlers used to load subsets of documents into
memory. | [
"Parse",
"the",
"contents",
"of",
"the",
"file",
"object",
"fileobj",
"and",
"return",
"the",
"contents",
"as",
"a",
"LIGO",
"Light",
"Weight",
"document",
"tree",
".",
"The",
"file",
"object",
"does",
"not",
"need",
"to",
"be",
"seekable",
"."
] | train | https://github.com/gwastro/pycbc-glue/blob/a3e906bae59fbfd707c3ff82e5d008d939ec5e24/pycbc_glue/ligolw/utils/__init__.py#L312-L359 |
gwastro/pycbc-glue | pycbc_glue/ligolw/utils/__init__.py | load_filename | def load_filename(filename, verbose = False, **kwargs):
"""
Parse the contents of the file identified by filename, and return
the contents as a LIGO Light Weight document tree. stdin is parsed
if filename is None. Helpful verbosity messages are printed to
stderr if verbose is True. All other keyword arguments are passed
to load_fileobj(), see that function for more information. In
particular note that a content handler must be specified.
Example:
>>> from pycbc_glue.ligolw import ligolw
>>> xmldoc = load_filename("demo.xml", contenthandler = ligolw.LIGOLWContentHandler, verbose = True)
"""
if verbose:
print >>sys.stderr, "reading %s ..." % (("'%s'" % filename) if filename is not None else "stdin")
if filename is not None:
fileobj = open(filename, "rb")
else:
fileobj = sys.stdin
xmldoc, hexdigest = load_fileobj(fileobj, **kwargs)
if verbose:
print >>sys.stderr, "md5sum: %s %s" % (hexdigest, (filename if filename is not None else ""))
return xmldoc | python | def load_filename(filename, verbose = False, **kwargs):
"""
Parse the contents of the file identified by filename, and return
the contents as a LIGO Light Weight document tree. stdin is parsed
if filename is None. Helpful verbosity messages are printed to
stderr if verbose is True. All other keyword arguments are passed
to load_fileobj(), see that function for more information. In
particular note that a content handler must be specified.
Example:
>>> from pycbc_glue.ligolw import ligolw
>>> xmldoc = load_filename("demo.xml", contenthandler = ligolw.LIGOLWContentHandler, verbose = True)
"""
if verbose:
print >>sys.stderr, "reading %s ..." % (("'%s'" % filename) if filename is not None else "stdin")
if filename is not None:
fileobj = open(filename, "rb")
else:
fileobj = sys.stdin
xmldoc, hexdigest = load_fileobj(fileobj, **kwargs)
if verbose:
print >>sys.stderr, "md5sum: %s %s" % (hexdigest, (filename if filename is not None else ""))
return xmldoc | [
"def",
"load_filename",
"(",
"filename",
",",
"verbose",
"=",
"False",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"verbose",
":",
"print",
">>",
"sys",
".",
"stderr",
",",
"\"reading %s ...\"",
"%",
"(",
"(",
"\"'%s'\"",
"%",
"filename",
")",
"if",
"file... | Parse the contents of the file identified by filename, and return
the contents as a LIGO Light Weight document tree. stdin is parsed
if filename is None. Helpful verbosity messages are printed to
stderr if verbose is True. All other keyword arguments are passed
to load_fileobj(), see that function for more information. In
particular note that a content handler must be specified.
Example:
>>> from pycbc_glue.ligolw import ligolw
>>> xmldoc = load_filename("demo.xml", contenthandler = ligolw.LIGOLWContentHandler, verbose = True) | [
"Parse",
"the",
"contents",
"of",
"the",
"file",
"identified",
"by",
"filename",
"and",
"return",
"the",
"contents",
"as",
"a",
"LIGO",
"Light",
"Weight",
"document",
"tree",
".",
"stdin",
"is",
"parsed",
"if",
"filename",
"is",
"None",
".",
"Helpful",
"ve... | train | https://github.com/gwastro/pycbc-glue/blob/a3e906bae59fbfd707c3ff82e5d008d939ec5e24/pycbc_glue/ligolw/utils/__init__.py#L362-L385 |
gwastro/pycbc-glue | pycbc_glue/ligolw/utils/__init__.py | load_url | def load_url(url, verbose = False, **kwargs):
"""
Parse the contents of file at the given URL and return the contents
as a LIGO Light Weight document tree. Any source from which
Python's urllib2 library can read data is acceptable. stdin is
parsed if url is None. Helpful verbosity messages are printed to
stderr if verbose is True. All other keyword arguments are passed
to load_fileobj(), see that function for more information. In
particular note that a content handler must be specified.
Example:
>>> from os import getcwd
>>> from pycbc_glue.ligolw import ligolw
>>> xmldoc = load_url("file://localhost/%s/demo.xml" % getcwd(), contenthandler = ligolw.LIGOLWContentHandler, verbose = True)
"""
if verbose:
print >>sys.stderr, "reading %s ..." % (("'%s'" % url) if url is not None else "stdin")
if url is not None:
scheme, host, path = urlparse.urlparse(url)[:3]
if scheme.lower() in ("", "file") and host.lower() in ("", "localhost"):
fileobj = open(path)
else:
fileobj = urllib2.urlopen(url)
else:
fileobj = sys.stdin
xmldoc, hexdigest = load_fileobj(fileobj, **kwargs)
if verbose:
print >>sys.stderr, "md5sum: %s %s" % (hexdigest, (url if url is not None else ""))
return xmldoc | python | def load_url(url, verbose = False, **kwargs):
"""
Parse the contents of file at the given URL and return the contents
as a LIGO Light Weight document tree. Any source from which
Python's urllib2 library can read data is acceptable. stdin is
parsed if url is None. Helpful verbosity messages are printed to
stderr if verbose is True. All other keyword arguments are passed
to load_fileobj(), see that function for more information. In
particular note that a content handler must be specified.
Example:
>>> from os import getcwd
>>> from pycbc_glue.ligolw import ligolw
>>> xmldoc = load_url("file://localhost/%s/demo.xml" % getcwd(), contenthandler = ligolw.LIGOLWContentHandler, verbose = True)
"""
if verbose:
print >>sys.stderr, "reading %s ..." % (("'%s'" % url) if url is not None else "stdin")
if url is not None:
scheme, host, path = urlparse.urlparse(url)[:3]
if scheme.lower() in ("", "file") and host.lower() in ("", "localhost"):
fileobj = open(path)
else:
fileobj = urllib2.urlopen(url)
else:
fileobj = sys.stdin
xmldoc, hexdigest = load_fileobj(fileobj, **kwargs)
if verbose:
print >>sys.stderr, "md5sum: %s %s" % (hexdigest, (url if url is not None else ""))
return xmldoc | [
"def",
"load_url",
"(",
"url",
",",
"verbose",
"=",
"False",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"verbose",
":",
"print",
">>",
"sys",
".",
"stderr",
",",
"\"reading %s ...\"",
"%",
"(",
"(",
"\"'%s'\"",
"%",
"url",
")",
"if",
"url",
"is",
"no... | Parse the contents of file at the given URL and return the contents
as a LIGO Light Weight document tree. Any source from which
Python's urllib2 library can read data is acceptable. stdin is
parsed if url is None. Helpful verbosity messages are printed to
stderr if verbose is True. All other keyword arguments are passed
to load_fileobj(), see that function for more information. In
particular note that a content handler must be specified.
Example:
>>> from os import getcwd
>>> from pycbc_glue.ligolw import ligolw
>>> xmldoc = load_url("file://localhost/%s/demo.xml" % getcwd(), contenthandler = ligolw.LIGOLWContentHandler, verbose = True) | [
"Parse",
"the",
"contents",
"of",
"file",
"at",
"the",
"given",
"URL",
"and",
"return",
"the",
"contents",
"as",
"a",
"LIGO",
"Light",
"Weight",
"document",
"tree",
".",
"Any",
"source",
"from",
"which",
"Python",
"s",
"urllib2",
"library",
"can",
"read",
... | train | https://github.com/gwastro/pycbc-glue/blob/a3e906bae59fbfd707c3ff82e5d008d939ec5e24/pycbc_glue/ligolw/utils/__init__.py#L388-L417 |
gwastro/pycbc-glue | pycbc_glue/ligolw/utils/__init__.py | write_fileobj | def write_fileobj(xmldoc, fileobj, gz = False, trap_signals = (signal.SIGTERM, signal.SIGTSTP), **kwargs):
"""
Writes the LIGO Light Weight document tree rooted at xmldoc to the
given file object. Internally, the .write() method of the xmldoc
object is invoked and any additional keyword arguments are passed
to that method. The file object need not be seekable. The output
data is gzip compressed on the fly if gz is True. The return value
is a string containing the hex digits of the MD5 digest of the
output bytestream.
This function traps the signals in the trap_signals iterable during
the write process (the default is signal.SIGTERM and
signal.SIGTSTP), and it does this by temporarily installing its own
signal handlers in place of the current handlers. This is done to
prevent Condor eviction during the write process. When the file
write is concluded the original signal handlers are restored.
Then, if signals were trapped during the write process, the signals
are then resent to the current process in the order in which they
were received. The signal.signal() system call cannot be invoked
from threads, and trap_signals must be set to None or an empty
sequence if this function is used from a thread.
Example:
>>> import sys
>>> from pycbc_glue.ligolw import ligolw
>>> xmldoc = load_filename("demo.xml", contenthandler = ligolw.LIGOLWContentHandler)
>>> digest = write_fileobj(xmldoc, sys.stdout) # doctest: +NORMALIZE_WHITESPACE
<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE LIGO_LW SYSTEM "http://ldas-sw.ligo.caltech.edu/doc/ligolwAPI/html/ligolw_dtd.txt">
<LIGO_LW>
<Table Name="demo:table">
<Column Type="lstring" Name="name"/>
<Column Type="real8" Name="value"/>
<Stream Delimiter="," Type="Local" Name="demo:table">
"mass",0.5,"velocity",34
</Stream>
</Table>
</LIGO_LW>
>>> digest
'37044d979a79409b3d782da126636f53'
"""
# initialize SIGTERM and SIGTSTP trap
deferred_signals = []
def newsigterm(signum, frame):
deferred_signals.append(signum)
oldhandlers = {}
if trap_signals is not None:
for sig in trap_signals:
oldhandlers[sig] = signal.getsignal(sig)
signal.signal(sig, newsigterm)
# write the document
with MD5File(fileobj, closable = False) as fileobj:
md5obj = fileobj.md5obj
with fileobj if not gz else GzipFile(mode = "wb", fileobj = fileobj) as fileobj:
with codecs.getwriter("utf_8")(fileobj) as fileobj:
xmldoc.write(fileobj, **kwargs)
# restore original handlers, and send outselves any trapped signals
# in order
for sig, oldhandler in oldhandlers.iteritems():
signal.signal(sig, oldhandler)
while deferred_signals:
os.kill(os.getpid(), deferred_signals.pop(0))
# return the hex digest of the bytestream that was written
return md5obj.hexdigest() | python | def write_fileobj(xmldoc, fileobj, gz = False, trap_signals = (signal.SIGTERM, signal.SIGTSTP), **kwargs):
"""
Writes the LIGO Light Weight document tree rooted at xmldoc to the
given file object. Internally, the .write() method of the xmldoc
object is invoked and any additional keyword arguments are passed
to that method. The file object need not be seekable. The output
data is gzip compressed on the fly if gz is True. The return value
is a string containing the hex digits of the MD5 digest of the
output bytestream.
This function traps the signals in the trap_signals iterable during
the write process (the default is signal.SIGTERM and
signal.SIGTSTP), and it does this by temporarily installing its own
signal handlers in place of the current handlers. This is done to
prevent Condor eviction during the write process. When the file
write is concluded the original signal handlers are restored.
Then, if signals were trapped during the write process, the signals
are then resent to the current process in the order in which they
were received. The signal.signal() system call cannot be invoked
from threads, and trap_signals must be set to None or an empty
sequence if this function is used from a thread.
Example:
>>> import sys
>>> from pycbc_glue.ligolw import ligolw
>>> xmldoc = load_filename("demo.xml", contenthandler = ligolw.LIGOLWContentHandler)
>>> digest = write_fileobj(xmldoc, sys.stdout) # doctest: +NORMALIZE_WHITESPACE
<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE LIGO_LW SYSTEM "http://ldas-sw.ligo.caltech.edu/doc/ligolwAPI/html/ligolw_dtd.txt">
<LIGO_LW>
<Table Name="demo:table">
<Column Type="lstring" Name="name"/>
<Column Type="real8" Name="value"/>
<Stream Delimiter="," Type="Local" Name="demo:table">
"mass",0.5,"velocity",34
</Stream>
</Table>
</LIGO_LW>
>>> digest
'37044d979a79409b3d782da126636f53'
"""
# initialize SIGTERM and SIGTSTP trap
deferred_signals = []
def newsigterm(signum, frame):
deferred_signals.append(signum)
oldhandlers = {}
if trap_signals is not None:
for sig in trap_signals:
oldhandlers[sig] = signal.getsignal(sig)
signal.signal(sig, newsigterm)
# write the document
with MD5File(fileobj, closable = False) as fileobj:
md5obj = fileobj.md5obj
with fileobj if not gz else GzipFile(mode = "wb", fileobj = fileobj) as fileobj:
with codecs.getwriter("utf_8")(fileobj) as fileobj:
xmldoc.write(fileobj, **kwargs)
# restore original handlers, and send outselves any trapped signals
# in order
for sig, oldhandler in oldhandlers.iteritems():
signal.signal(sig, oldhandler)
while deferred_signals:
os.kill(os.getpid(), deferred_signals.pop(0))
# return the hex digest of the bytestream that was written
return md5obj.hexdigest() | [
"def",
"write_fileobj",
"(",
"xmldoc",
",",
"fileobj",
",",
"gz",
"=",
"False",
",",
"trap_signals",
"=",
"(",
"signal",
".",
"SIGTERM",
",",
"signal",
".",
"SIGTSTP",
")",
",",
"*",
"*",
"kwargs",
")",
":",
"# initialize SIGTERM and SIGTSTP trap",
"deferred... | Writes the LIGO Light Weight document tree rooted at xmldoc to the
given file object. Internally, the .write() method of the xmldoc
object is invoked and any additional keyword arguments are passed
to that method. The file object need not be seekable. The output
data is gzip compressed on the fly if gz is True. The return value
is a string containing the hex digits of the MD5 digest of the
output bytestream.
This function traps the signals in the trap_signals iterable during
the write process (the default is signal.SIGTERM and
signal.SIGTSTP), and it does this by temporarily installing its own
signal handlers in place of the current handlers. This is done to
prevent Condor eviction during the write process. When the file
write is concluded the original signal handlers are restored.
Then, if signals were trapped during the write process, the signals
are then resent to the current process in the order in which they
were received. The signal.signal() system call cannot be invoked
from threads, and trap_signals must be set to None or an empty
sequence if this function is used from a thread.
Example:
>>> import sys
>>> from pycbc_glue.ligolw import ligolw
>>> xmldoc = load_filename("demo.xml", contenthandler = ligolw.LIGOLWContentHandler)
>>> digest = write_fileobj(xmldoc, sys.stdout) # doctest: +NORMALIZE_WHITESPACE
<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE LIGO_LW SYSTEM "http://ldas-sw.ligo.caltech.edu/doc/ligolwAPI/html/ligolw_dtd.txt">
<LIGO_LW>
<Table Name="demo:table">
<Column Type="lstring" Name="name"/>
<Column Type="real8" Name="value"/>
<Stream Delimiter="," Type="Local" Name="demo:table">
"mass",0.5,"velocity",34
</Stream>
</Table>
</LIGO_LW>
>>> digest
'37044d979a79409b3d782da126636f53' | [
"Writes",
"the",
"LIGO",
"Light",
"Weight",
"document",
"tree",
"rooted",
"at",
"xmldoc",
"to",
"the",
"given",
"file",
"object",
".",
"Internally",
"the",
".",
"write",
"()",
"method",
"of",
"the",
"xmldoc",
"object",
"is",
"invoked",
"and",
"any",
"addit... | train | https://github.com/gwastro/pycbc-glue/blob/a3e906bae59fbfd707c3ff82e5d008d939ec5e24/pycbc_glue/ligolw/utils/__init__.py#L420-L487 |
gwastro/pycbc-glue | pycbc_glue/ligolw/utils/__init__.py | write_filename | def write_filename(xmldoc, filename, verbose = False, gz = False, **kwargs):
"""
Writes the LIGO Light Weight document tree rooted at xmldoc to the
file name filename. Friendly verbosity messages are printed while
doing so if verbose is True. The output data is gzip compressed on
the fly if gz is True.
Internally, write_fileobj() is used to perform the write. All
additional keyword arguments are passed to write_fileobj().
Example:
>>> write_filename(xmldoc, "demo.xml") # doctest: +SKIP
>>> write_filename(xmldoc, "demo.xml.gz", gz = True) # doctest: +SKIP
"""
if verbose:
print >>sys.stderr, "writing %s ..." % (("'%s'" % filename) if filename is not None else "stdout")
if filename is not None:
if not gz and filename.endswith(".gz"):
warnings.warn("filename '%s' ends in '.gz' but file is not being gzip-compressed" % filename, UserWarning)
fileobj = open(filename, "w")
else:
fileobj = sys.stdout
hexdigest = write_fileobj(xmldoc, fileobj, gz = gz, **kwargs)
if not fileobj is sys.stdout:
fileobj.close()
if verbose:
print >>sys.stderr, "md5sum: %s %s" % (hexdigest, (filename if filename is not None else "")) | python | def write_filename(xmldoc, filename, verbose = False, gz = False, **kwargs):
"""
Writes the LIGO Light Weight document tree rooted at xmldoc to the
file name filename. Friendly verbosity messages are printed while
doing so if verbose is True. The output data is gzip compressed on
the fly if gz is True.
Internally, write_fileobj() is used to perform the write. All
additional keyword arguments are passed to write_fileobj().
Example:
>>> write_filename(xmldoc, "demo.xml") # doctest: +SKIP
>>> write_filename(xmldoc, "demo.xml.gz", gz = True) # doctest: +SKIP
"""
if verbose:
print >>sys.stderr, "writing %s ..." % (("'%s'" % filename) if filename is not None else "stdout")
if filename is not None:
if not gz and filename.endswith(".gz"):
warnings.warn("filename '%s' ends in '.gz' but file is not being gzip-compressed" % filename, UserWarning)
fileobj = open(filename, "w")
else:
fileobj = sys.stdout
hexdigest = write_fileobj(xmldoc, fileobj, gz = gz, **kwargs)
if not fileobj is sys.stdout:
fileobj.close()
if verbose:
print >>sys.stderr, "md5sum: %s %s" % (hexdigest, (filename if filename is not None else "")) | [
"def",
"write_filename",
"(",
"xmldoc",
",",
"filename",
",",
"verbose",
"=",
"False",
",",
"gz",
"=",
"False",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"verbose",
":",
"print",
">>",
"sys",
".",
"stderr",
",",
"\"writing %s ...\"",
"%",
"(",
"(",
"\... | Writes the LIGO Light Weight document tree rooted at xmldoc to the
file name filename. Friendly verbosity messages are printed while
doing so if verbose is True. The output data is gzip compressed on
the fly if gz is True.
Internally, write_fileobj() is used to perform the write. All
additional keyword arguments are passed to write_fileobj().
Example:
>>> write_filename(xmldoc, "demo.xml") # doctest: +SKIP
>>> write_filename(xmldoc, "demo.xml.gz", gz = True) # doctest: +SKIP | [
"Writes",
"the",
"LIGO",
"Light",
"Weight",
"document",
"tree",
"rooted",
"at",
"xmldoc",
"to",
"the",
"file",
"name",
"filename",
".",
"Friendly",
"verbosity",
"messages",
"are",
"printed",
"while",
"doing",
"so",
"if",
"verbose",
"is",
"True",
".",
"The",
... | train | https://github.com/gwastro/pycbc-glue/blob/a3e906bae59fbfd707c3ff82e5d008d939ec5e24/pycbc_glue/ligolw/utils/__init__.py#L490-L517 |
RadhikaG/markdown-magic | magic/magic.py | MagicPattern.handleMatch | def handleMatch(self, m):
"""
Handles user input into [magic] tag, processes it,
and inserts the returned URL into an <img> tag
through a Python ElementTree <img> Element.
"""
userStr = m.group(3)
# print(userStr)
imgURL = processString(userStr)
# print(imgURL)
el = etree.Element('img')
# Sets imgURL to 'src' attribute of <img> tag element
el.set('src', imgURL)
el.set('alt', userStr)
el.set('title', userStr)
return el | python | def handleMatch(self, m):
"""
Handles user input into [magic] tag, processes it,
and inserts the returned URL into an <img> tag
through a Python ElementTree <img> Element.
"""
userStr = m.group(3)
# print(userStr)
imgURL = processString(userStr)
# print(imgURL)
el = etree.Element('img')
# Sets imgURL to 'src' attribute of <img> tag element
el.set('src', imgURL)
el.set('alt', userStr)
el.set('title', userStr)
return el | [
"def",
"handleMatch",
"(",
"self",
",",
"m",
")",
":",
"userStr",
"=",
"m",
".",
"group",
"(",
"3",
")",
"# print(userStr)",
"imgURL",
"=",
"processString",
"(",
"userStr",
")",
"# print(imgURL)",
"el",
"=",
"etree",
".",
"Element",
"(",
"'img'",
")",
... | Handles user input into [magic] tag, processes it,
and inserts the returned URL into an <img> tag
through a Python ElementTree <img> Element. | [
"Handles",
"user",
"input",
"into",
"[",
"magic",
"]",
"tag",
"processes",
"it",
"and",
"inserts",
"the",
"returned",
"URL",
"into",
"an",
"<img",
">",
"tag",
"through",
"a",
"Python",
"ElementTree",
"<img",
">",
"Element",
"."
] | train | https://github.com/RadhikaG/markdown-magic/blob/af99549b033269d861ea13f0541cb4f894057c47/magic/magic.py#L12-L27 |
ebu/PlugIt | examples/simple_service/actions.py | home | def home(request):
"""Show the home page. Send the list of polls"""
polls = []
for row in curDB.execute('SELECT id, title FROM Poll ORDER BY title'):
polls.append({'id': row[0], 'name': row[1]})
return {'polls': polls} | python | def home(request):
"""Show the home page. Send the list of polls"""
polls = []
for row in curDB.execute('SELECT id, title FROM Poll ORDER BY title'):
polls.append({'id': row[0], 'name': row[1]})
return {'polls': polls} | [
"def",
"home",
"(",
"request",
")",
":",
"polls",
"=",
"[",
"]",
"for",
"row",
"in",
"curDB",
".",
"execute",
"(",
"'SELECT id, title FROM Poll ORDER BY title'",
")",
":",
"polls",
".",
"append",
"(",
"{",
"'id'",
":",
"row",
"[",
"0",
"]",
",",
"'name... | Show the home page. Send the list of polls | [
"Show",
"the",
"home",
"page",
".",
"Send",
"the",
"list",
"of",
"polls"
] | train | https://github.com/ebu/PlugIt/blob/de5f1e870f67caaef7a4a58e4bb1ed54d9c5dc53/examples/simple_service/actions.py#L31-L39 |
ebu/PlugIt | examples/simple_service/actions.py | show | def show(request, pollId):
"""Show a poll. We send informations about votes only if the user is an administrator"""
# Get the poll
curDB.execute('SELECT id, title, description FROM Poll WHERE id = ? ORDER BY title', (pollId,))
poll = curDB.fetchone()
if poll is None:
return {}
responses = []
totalVotes = 0
votedFor = 0
# Compute the list of responses
curDB.execute('SELECT id, title FROM Response WHERE pollId = ? ORDER BY title ', (poll[0],))
resps = curDB.fetchall()
for rowRep in resps:
votes = []
nbVotes = 0
# List each votes
for rowVote in curDB.execute('SELECT username FROM Vote WHERE responseId = ?', (rowRep[0],)):
nbVotes += 1
# If the user is and administrator, saves each votes
if request.args.get('ebuio_u_ebuio_admin') == 'True':
votes.append(rowVote[0])
# Save the vote of the current suer
if request.args.get('ebuio_u_username') == rowVote[0]:
votedFor = rowRep[0]
totalVotes += nbVotes
responses.append({'id': rowRep[0], 'title': rowRep[1], 'nbVotes': nbVotes, 'votes': votes})
return {'id': poll[0], 'name': poll[1], 'description': poll[2], 'responses': responses, 'totalVotes': totalVotes, 'votedFor': votedFor} | python | def show(request, pollId):
"""Show a poll. We send informations about votes only if the user is an administrator"""
# Get the poll
curDB.execute('SELECT id, title, description FROM Poll WHERE id = ? ORDER BY title', (pollId,))
poll = curDB.fetchone()
if poll is None:
return {}
responses = []
totalVotes = 0
votedFor = 0
# Compute the list of responses
curDB.execute('SELECT id, title FROM Response WHERE pollId = ? ORDER BY title ', (poll[0],))
resps = curDB.fetchall()
for rowRep in resps:
votes = []
nbVotes = 0
# List each votes
for rowVote in curDB.execute('SELECT username FROM Vote WHERE responseId = ?', (rowRep[0],)):
nbVotes += 1
# If the user is and administrator, saves each votes
if request.args.get('ebuio_u_ebuio_admin') == 'True':
votes.append(rowVote[0])
# Save the vote of the current suer
if request.args.get('ebuio_u_username') == rowVote[0]:
votedFor = rowRep[0]
totalVotes += nbVotes
responses.append({'id': rowRep[0], 'title': rowRep[1], 'nbVotes': nbVotes, 'votes': votes})
return {'id': poll[0], 'name': poll[1], 'description': poll[2], 'responses': responses, 'totalVotes': totalVotes, 'votedFor': votedFor} | [
"def",
"show",
"(",
"request",
",",
"pollId",
")",
":",
"# Get the poll",
"curDB",
".",
"execute",
"(",
"'SELECT id, title, description FROM Poll WHERE id = ? ORDER BY title'",
",",
"(",
"pollId",
",",
")",
")",
"poll",
"=",
"curDB",
".",
"fetchone",
"(",
")",
"... | Show a poll. We send informations about votes only if the user is an administrator | [
"Show",
"a",
"poll",
".",
"We",
"send",
"informations",
"about",
"votes",
"only",
"if",
"the",
"user",
"is",
"an",
"administrator"
] | train | https://github.com/ebu/PlugIt/blob/de5f1e870f67caaef7a4a58e4bb1ed54d9c5dc53/examples/simple_service/actions.py#L44-L83 |
ebu/PlugIt | examples/simple_service/actions.py | vote | def vote(request, pollId, responseId):
"""Vote for a poll"""
username = request.args.get('ebuio_u_username')
# Remove old votes from the same user on the same poll
curDB.execute('DELETE FROM Vote WHERE username = ? AND responseId IN (SELECT id FROM Response WHERE pollId = ?) ', (username, pollId))
# Save the vote
curDB.execute('INSERT INTO Vote (username, responseID) VALUES (?, ?) ', (username, responseId))
coxDB.commit()
# To display a success page, comment this line
return PlugItRedirect("show/" + str(pollId))
# Line to display the success page
return {'id': pollId} | python | def vote(request, pollId, responseId):
"""Vote for a poll"""
username = request.args.get('ebuio_u_username')
# Remove old votes from the same user on the same poll
curDB.execute('DELETE FROM Vote WHERE username = ? AND responseId IN (SELECT id FROM Response WHERE pollId = ?) ', (username, pollId))
# Save the vote
curDB.execute('INSERT INTO Vote (username, responseID) VALUES (?, ?) ', (username, responseId))
coxDB.commit()
# To display a success page, comment this line
return PlugItRedirect("show/" + str(pollId))
# Line to display the success page
return {'id': pollId} | [
"def",
"vote",
"(",
"request",
",",
"pollId",
",",
"responseId",
")",
":",
"username",
"=",
"request",
".",
"args",
".",
"get",
"(",
"'ebuio_u_username'",
")",
"# Remove old votes from the same user on the same poll",
"curDB",
".",
"execute",
"(",
"'DELETE FROM Vote... | Vote for a poll | [
"Vote",
"for",
"a",
"poll"
] | train | https://github.com/ebu/PlugIt/blob/de5f1e870f67caaef7a4a58e4bb1ed54d9c5dc53/examples/simple_service/actions.py#L89-L106 |
ebu/PlugIt | examples/simple_service/actions.py | create | def create(request):
"""Create a new poll"""
errors = []
success = False
listOfResponses = ['', '', ''] # 3 Blank lines by default
title = ''
description = ''
id = ''
if request.method == 'POST': # User saved the form
# Retrieve parameters
title = request.form.get('title')
description = request.form.get('description')
listOfResponses = []
for rep in request.form.getlist('rep[]'):
if rep != '':
listOfResponses.append(rep)
# Test if everything is ok
if title == "":
errors.append("Please set a title !")
if len(listOfResponses) == 0:
errors.append("Please set at least one response !")
# Can we save the new question ?
if len(errors) == 0:
# Yes. Let save data
curDB.execute("INSERT INTO Poll (title, description) VALUES (?, ?)", (title, description))
# The id of the poll
id = curDB.lastrowid
# Insert responses
for rep in listOfResponses:
curDB.execute("INSERT INTO Response (pollId, title) VALUES (?, ?)", (id, rep))
coxDB.commit()
success = True
# Minimum of 3 lines of questions
while len(listOfResponses) < 3:
listOfResponses.append('')
return {'errors': errors, 'success': success, 'listOfResponses': listOfResponses, 'title': title, 'description': description, 'id': id} | python | def create(request):
"""Create a new poll"""
errors = []
success = False
listOfResponses = ['', '', ''] # 3 Blank lines by default
title = ''
description = ''
id = ''
if request.method == 'POST': # User saved the form
# Retrieve parameters
title = request.form.get('title')
description = request.form.get('description')
listOfResponses = []
for rep in request.form.getlist('rep[]'):
if rep != '':
listOfResponses.append(rep)
# Test if everything is ok
if title == "":
errors.append("Please set a title !")
if len(listOfResponses) == 0:
errors.append("Please set at least one response !")
# Can we save the new question ?
if len(errors) == 0:
# Yes. Let save data
curDB.execute("INSERT INTO Poll (title, description) VALUES (?, ?)", (title, description))
# The id of the poll
id = curDB.lastrowid
# Insert responses
for rep in listOfResponses:
curDB.execute("INSERT INTO Response (pollId, title) VALUES (?, ?)", (id, rep))
coxDB.commit()
success = True
# Minimum of 3 lines of questions
while len(listOfResponses) < 3:
listOfResponses.append('')
return {'errors': errors, 'success': success, 'listOfResponses': listOfResponses, 'title': title, 'description': description, 'id': id} | [
"def",
"create",
"(",
"request",
")",
":",
"errors",
"=",
"[",
"]",
"success",
"=",
"False",
"listOfResponses",
"=",
"[",
"''",
",",
"''",
",",
"''",
"]",
"# 3 Blank lines by default",
"title",
"=",
"''",
"description",
"=",
"''",
"id",
"=",
"''",
"if"... | Create a new poll | [
"Create",
"a",
"new",
"poll"
] | train | https://github.com/ebu/PlugIt/blob/de5f1e870f67caaef7a4a58e4bb1ed54d9c5dc53/examples/simple_service/actions.py#L111-L158 |
gwastro/pycbc-glue | pycbc_glue/ligolw/lsctables.py | New | def New(Type, columns = None, **kwargs):
"""
Construct a pre-defined LSC table. The optional columns argument
is a sequence of the names of the columns the table should be
constructed with. If columns = None, then the table is constructed
with all valid columns (use columns = [] to create a table with no
columns).
Example:
>>> import sys
>>> tbl = New(ProcessTable, [u"process_id", u"start_time", u"end_time", u"comment"])
>>> tbl.write(sys.stdout) # doctest: +NORMALIZE_WHITESPACE
<Table Name="process:table">
<Column Type="ilwd:char" Name="process:process_id"/>
<Column Type="int_4s" Name="process:start_time"/>
<Column Type="int_4s" Name="process:end_time"/>
<Column Type="lstring" Name="process:comment"/>
<Stream Delimiter="," Type="Local" Name="process:table">
</Stream>
</Table>
"""
new = Type(sax.xmlreader.AttributesImpl({u"Name": Type.tableName}), **kwargs)
colnamefmt = u":".join(Type.tableName.split(":")[:-1]) + u":%s"
if columns is not None:
for key in columns:
if key not in new.validcolumns:
raise ligolw.ElementError("invalid Column '%s' for Table '%s'" % (key, new.tableName))
new.appendChild(table.Column(sax.xmlreader.AttributesImpl({u"Name": colnamefmt % key, u"Type": new.validcolumns[key]})))
else:
for key, value in new.validcolumns.items():
new.appendChild(table.Column(sax.xmlreader.AttributesImpl({u"Name": colnamefmt % key, u"Type": value})))
new._end_of_columns()
new.appendChild(table.TableStream(sax.xmlreader.AttributesImpl({u"Name": Type.tableName, u"Delimiter": table.TableStream.Delimiter.default, u"Type": table.TableStream.Type.default})))
return new | python | def New(Type, columns = None, **kwargs):
"""
Construct a pre-defined LSC table. The optional columns argument
is a sequence of the names of the columns the table should be
constructed with. If columns = None, then the table is constructed
with all valid columns (use columns = [] to create a table with no
columns).
Example:
>>> import sys
>>> tbl = New(ProcessTable, [u"process_id", u"start_time", u"end_time", u"comment"])
>>> tbl.write(sys.stdout) # doctest: +NORMALIZE_WHITESPACE
<Table Name="process:table">
<Column Type="ilwd:char" Name="process:process_id"/>
<Column Type="int_4s" Name="process:start_time"/>
<Column Type="int_4s" Name="process:end_time"/>
<Column Type="lstring" Name="process:comment"/>
<Stream Delimiter="," Type="Local" Name="process:table">
</Stream>
</Table>
"""
new = Type(sax.xmlreader.AttributesImpl({u"Name": Type.tableName}), **kwargs)
colnamefmt = u":".join(Type.tableName.split(":")[:-1]) + u":%s"
if columns is not None:
for key in columns:
if key not in new.validcolumns:
raise ligolw.ElementError("invalid Column '%s' for Table '%s'" % (key, new.tableName))
new.appendChild(table.Column(sax.xmlreader.AttributesImpl({u"Name": colnamefmt % key, u"Type": new.validcolumns[key]})))
else:
for key, value in new.validcolumns.items():
new.appendChild(table.Column(sax.xmlreader.AttributesImpl({u"Name": colnamefmt % key, u"Type": value})))
new._end_of_columns()
new.appendChild(table.TableStream(sax.xmlreader.AttributesImpl({u"Name": Type.tableName, u"Delimiter": table.TableStream.Delimiter.default, u"Type": table.TableStream.Type.default})))
return new | [
"def",
"New",
"(",
"Type",
",",
"columns",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"new",
"=",
"Type",
"(",
"sax",
".",
"xmlreader",
".",
"AttributesImpl",
"(",
"{",
"u\"Name\"",
":",
"Type",
".",
"tableName",
"}",
")",
",",
"*",
"*",
"kw... | Construct a pre-defined LSC table. The optional columns argument
is a sequence of the names of the columns the table should be
constructed with. If columns = None, then the table is constructed
with all valid columns (use columns = [] to create a table with no
columns).
Example:
>>> import sys
>>> tbl = New(ProcessTable, [u"process_id", u"start_time", u"end_time", u"comment"])
>>> tbl.write(sys.stdout) # doctest: +NORMALIZE_WHITESPACE
<Table Name="process:table">
<Column Type="ilwd:char" Name="process:process_id"/>
<Column Type="int_4s" Name="process:start_time"/>
<Column Type="int_4s" Name="process:end_time"/>
<Column Type="lstring" Name="process:comment"/>
<Stream Delimiter="," Type="Local" Name="process:table">
</Stream>
</Table> | [
"Construct",
"a",
"pre",
"-",
"defined",
"LSC",
"table",
".",
"The",
"optional",
"columns",
"argument",
"is",
"a",
"sequence",
"of",
"the",
"names",
"of",
"the",
"columns",
"the",
"table",
"should",
"be",
"constructed",
"with",
".",
"If",
"columns",
"=",
... | train | https://github.com/gwastro/pycbc-glue/blob/a3e906bae59fbfd707c3ff82e5d008d939ec5e24/pycbc_glue/ligolw/lsctables.py#L90-L124 |
gwastro/pycbc-glue | pycbc_glue/ligolw/lsctables.py | IsTableProperties | def IsTableProperties(Type, tagname, attrs):
"""
obsolete. see .CheckProperties() method of pycbc_glue.ligolw.table.Table
class.
"""
import warnings
warnings.warn("lsctables.IsTableProperties() is deprecated. use pycbc_glue.ligolw.table.Table.CheckProperties() instead", DeprecationWarning)
return Type.CheckProperties(tagname, attrs) | python | def IsTableProperties(Type, tagname, attrs):
"""
obsolete. see .CheckProperties() method of pycbc_glue.ligolw.table.Table
class.
"""
import warnings
warnings.warn("lsctables.IsTableProperties() is deprecated. use pycbc_glue.ligolw.table.Table.CheckProperties() instead", DeprecationWarning)
return Type.CheckProperties(tagname, attrs) | [
"def",
"IsTableProperties",
"(",
"Type",
",",
"tagname",
",",
"attrs",
")",
":",
"import",
"warnings",
"warnings",
".",
"warn",
"(",
"\"lsctables.IsTableProperties() is deprecated. use pycbc_glue.ligolw.table.Table.CheckProperties() instead\"",
",",
"DeprecationWarning",
")",
... | obsolete. see .CheckProperties() method of pycbc_glue.ligolw.table.Table
class. | [
"obsolete",
".",
"see",
".",
"CheckProperties",
"()",
"method",
"of",
"pycbc_glue",
".",
"ligolw",
".",
"table",
".",
"Table",
"class",
"."
] | train | https://github.com/gwastro/pycbc-glue/blob/a3e906bae59fbfd707c3ff82e5d008d939ec5e24/pycbc_glue/ligolw/lsctables.py#L127-L134 |
gwastro/pycbc-glue | pycbc_glue/ligolw/lsctables.py | HasNonLSCTables | def HasNonLSCTables(elem):
"""
Return True if the document tree below elem contains non-LSC
tables, otherwise return False.
"""
return any(t.Name not in TableByName for t in elem.getElementsByTagName(ligolw.Table.tagName)) | python | def HasNonLSCTables(elem):
"""
Return True if the document tree below elem contains non-LSC
tables, otherwise return False.
"""
return any(t.Name not in TableByName for t in elem.getElementsByTagName(ligolw.Table.tagName)) | [
"def",
"HasNonLSCTables",
"(",
"elem",
")",
":",
"return",
"any",
"(",
"t",
".",
"Name",
"not",
"in",
"TableByName",
"for",
"t",
"in",
"elem",
".",
"getElementsByTagName",
"(",
"ligolw",
".",
"Table",
".",
"tagName",
")",
")"
] | Return True if the document tree below elem contains non-LSC
tables, otherwise return False. | [
"Return",
"True",
"if",
"the",
"document",
"tree",
"below",
"elem",
"contains",
"non",
"-",
"LSC",
"tables",
"otherwise",
"return",
"False",
"."
] | train | https://github.com/gwastro/pycbc-glue/blob/a3e906bae59fbfd707c3ff82e5d008d939ec5e24/pycbc_glue/ligolw/lsctables.py#L137-L142 |
gwastro/pycbc-glue | pycbc_glue/ligolw/lsctables.py | instrument_set_from_ifos | def instrument_set_from_ifos(ifos):
"""
Parse the values stored in the "ifos" and "instruments" columns
found in many tables. This function is mostly for internal use by
the .instruments properties of the corresponding row classes. The
mapping from input to output is as follows (rules are applied in
order):
input is None --> output is None
input contains "," --> output is set of strings split on "," with
leading and trailing whitespace stripped from each piece and empty
strings removed from the set
input contains "+" --> output is set of strings split on "+" with
leading and trailing whitespace stripped from each piece and empty
strings removed from the set
else, after stripping input of leading and trailing whitespace,
input has an even length greater than two --> output is set of
two-character pieces
input is a non-empty string --> output is a set containing input as
single value
else output is an empty set.
NOTE: the complexity of this algorithm is a consequence of there
being several conventions in use for encoding a set of instruments
into one of these columns; it has been proposed that L.L.W.
documents standardize on the comma-delimited variant of the
encodings recognized by this function, and for this reason the
inverse function, ifos_from_instrument_set(), implements that
encoding only.
NOTE: to force a string containing an even number of characters to
be interpreted as a single instrument name and not to be be split
into two-character pieces, add a "," or "+" character to the end to
force the comma- or plus-delimited decoding to be used.
ifos_from_instrument_set() does this for you.
Example:
>>> print instrument_set_from_ifos(None)
None
>>> instrument_set_from_ifos(u"")
set([])
>>> instrument_set_from_ifos(u" , ,,")
set([])
>>> instrument_set_from_ifos(u"H1")
set([u'H1'])
>>> instrument_set_from_ifos(u"SWIFT")
set([u'SWIFT'])
>>> instrument_set_from_ifos(u"H1L1")
set([u'H1', u'L1'])
>>> instrument_set_from_ifos(u"H1L1,")
set([u'H1L1'])
>>> instrument_set_from_ifos(u"H1,L1")
set([u'H1', u'L1'])
>>> instrument_set_from_ifos(u"H1+L1")
set([u'H1', u'L1'])
"""
if ifos is None:
return None
if u"," in ifos:
result = set(ifo.strip() for ifo in ifos.split(u","))
result.discard(u"")
return result
if u"+" in ifos:
result = set(ifo.strip() for ifo in ifos.split(u"+"))
result.discard(u"")
return result
ifos = ifos.strip()
if len(ifos) > 2 and not len(ifos) % 2:
# if ifos is a string with an even number of characters
# greater than two, split it into two-character pieces.
# FIXME: remove this when the inspiral codes don't write
# ifos strings like this anymore
return set(ifos[n:n+2] for n in range(0, len(ifos), 2))
if ifos:
return set([ifos])
return set() | python | def instrument_set_from_ifos(ifos):
"""
Parse the values stored in the "ifos" and "instruments" columns
found in many tables. This function is mostly for internal use by
the .instruments properties of the corresponding row classes. The
mapping from input to output is as follows (rules are applied in
order):
input is None --> output is None
input contains "," --> output is set of strings split on "," with
leading and trailing whitespace stripped from each piece and empty
strings removed from the set
input contains "+" --> output is set of strings split on "+" with
leading and trailing whitespace stripped from each piece and empty
strings removed from the set
else, after stripping input of leading and trailing whitespace,
input has an even length greater than two --> output is set of
two-character pieces
input is a non-empty string --> output is a set containing input as
single value
else output is an empty set.
NOTE: the complexity of this algorithm is a consequence of there
being several conventions in use for encoding a set of instruments
into one of these columns; it has been proposed that L.L.W.
documents standardize on the comma-delimited variant of the
encodings recognized by this function, and for this reason the
inverse function, ifos_from_instrument_set(), implements that
encoding only.
NOTE: to force a string containing an even number of characters to
be interpreted as a single instrument name and not to be be split
into two-character pieces, add a "," or "+" character to the end to
force the comma- or plus-delimited decoding to be used.
ifos_from_instrument_set() does this for you.
Example:
>>> print instrument_set_from_ifos(None)
None
>>> instrument_set_from_ifos(u"")
set([])
>>> instrument_set_from_ifos(u" , ,,")
set([])
>>> instrument_set_from_ifos(u"H1")
set([u'H1'])
>>> instrument_set_from_ifos(u"SWIFT")
set([u'SWIFT'])
>>> instrument_set_from_ifos(u"H1L1")
set([u'H1', u'L1'])
>>> instrument_set_from_ifos(u"H1L1,")
set([u'H1L1'])
>>> instrument_set_from_ifos(u"H1,L1")
set([u'H1', u'L1'])
>>> instrument_set_from_ifos(u"H1+L1")
set([u'H1', u'L1'])
"""
if ifos is None:
return None
if u"," in ifos:
result = set(ifo.strip() for ifo in ifos.split(u","))
result.discard(u"")
return result
if u"+" in ifos:
result = set(ifo.strip() for ifo in ifos.split(u"+"))
result.discard(u"")
return result
ifos = ifos.strip()
if len(ifos) > 2 and not len(ifos) % 2:
# if ifos is a string with an even number of characters
# greater than two, split it into two-character pieces.
# FIXME: remove this when the inspiral codes don't write
# ifos strings like this anymore
return set(ifos[n:n+2] for n in range(0, len(ifos), 2))
if ifos:
return set([ifos])
return set() | [
"def",
"instrument_set_from_ifos",
"(",
"ifos",
")",
":",
"if",
"ifos",
"is",
"None",
":",
"return",
"None",
"if",
"u\",\"",
"in",
"ifos",
":",
"result",
"=",
"set",
"(",
"ifo",
".",
"strip",
"(",
")",
"for",
"ifo",
"in",
"ifos",
".",
"split",
"(",
... | Parse the values stored in the "ifos" and "instruments" columns
found in many tables. This function is mostly for internal use by
the .instruments properties of the corresponding row classes. The
mapping from input to output is as follows (rules are applied in
order):
input is None --> output is None
input contains "," --> output is set of strings split on "," with
leading and trailing whitespace stripped from each piece and empty
strings removed from the set
input contains "+" --> output is set of strings split on "+" with
leading and trailing whitespace stripped from each piece and empty
strings removed from the set
else, after stripping input of leading and trailing whitespace,
input has an even length greater than two --> output is set of
two-character pieces
input is a non-empty string --> output is a set containing input as
single value
else output is an empty set.
NOTE: the complexity of this algorithm is a consequence of there
being several conventions in use for encoding a set of instruments
into one of these columns; it has been proposed that L.L.W.
documents standardize on the comma-delimited variant of the
encodings recognized by this function, and for this reason the
inverse function, ifos_from_instrument_set(), implements that
encoding only.
NOTE: to force a string containing an even number of characters to
be interpreted as a single instrument name and not to be be split
into two-character pieces, add a "," or "+" character to the end to
force the comma- or plus-delimited decoding to be used.
ifos_from_instrument_set() does this for you.
Example:
>>> print instrument_set_from_ifos(None)
None
>>> instrument_set_from_ifos(u"")
set([])
>>> instrument_set_from_ifos(u" , ,,")
set([])
>>> instrument_set_from_ifos(u"H1")
set([u'H1'])
>>> instrument_set_from_ifos(u"SWIFT")
set([u'SWIFT'])
>>> instrument_set_from_ifos(u"H1L1")
set([u'H1', u'L1'])
>>> instrument_set_from_ifos(u"H1L1,")
set([u'H1L1'])
>>> instrument_set_from_ifos(u"H1,L1")
set([u'H1', u'L1'])
>>> instrument_set_from_ifos(u"H1+L1")
set([u'H1', u'L1']) | [
"Parse",
"the",
"values",
"stored",
"in",
"the",
"ifos",
"and",
"instruments",
"columns",
"found",
"in",
"many",
"tables",
".",
"This",
"function",
"is",
"mostly",
"for",
"internal",
"use",
"by",
"the",
".",
"instruments",
"properties",
"of",
"the",
"corresp... | train | https://github.com/gwastro/pycbc-glue/blob/a3e906bae59fbfd707c3ff82e5d008d939ec5e24/pycbc_glue/ligolw/lsctables.py#L145-L227 |
gwastro/pycbc-glue | pycbc_glue/ligolw/lsctables.py | ifos_from_instrument_set | def ifos_from_instrument_set(instruments):
"""
Convert an iterable of instrument names into a value suitable for
storage in the "ifos" column found in many tables. This function
is mostly for internal use by the .instruments properties of the
corresponding row classes. The input can be None or an iterable of
zero or more instrument names, none of which may be zero-length,
consist exclusively of spaces, or contain "," or "+" characters.
The output is a single string containing the unique instrument
names concatenated using "," as a delimiter. instruments will only
be iterated over once and so can be a generator expression.
Whitespace is allowed in instrument names but might not be
preserved. Repeated names will not be preserved.
NOTE: in the special case that there is 1 instrument name in the
iterable and it has an even number of characters > 2 in it, the
output will have a "," appended in order to force
instrument_set_from_ifos() to parse the string back into a single
instrument name. This is a special case included temporarily to
disambiguate the encoding until all codes have been ported to the
comma-delimited encoding. This behaviour will be discontinued at
that time. DO NOT WRITE CODE THAT RELIES ON THIS! You have been
warned.
Example:
>>> print ifos_from_instrument_set(None)
None
>>> ifos_from_instrument_set(())
u''
>>> ifos_from_instrument_set((u"H1",))
u'H1'
>>> ifos_from_instrument_set((u"H1",u"H1",u"H1"))
u'H1'
>>> ifos_from_instrument_set((u"H1",u"L1"))
u'H1,L1'
>>> ifos_from_instrument_set((u"SWIFT",))
u'SWIFT'
>>> ifos_from_instrument_set((u"H1L1",))
u'H1L1,'
"""
if instruments is None:
return None
_instruments = sorted(set(instrument.strip() for instrument in instruments))
# safety check: refuse to accept blank names, or names with commas
# or pluses in them as they cannot survive the encode/decode
# process
if not all(_instruments) or any(u"," in instrument or u"+" in instrument for instrument in _instruments):
raise ValueError(instruments)
if len(_instruments) == 1 and len(_instruments[0]) > 2 and not len(_instruments[0]) % 2:
# special case disambiguation. FIXME: remove when
# everything uses the comma-delimited encoding
return u"%s," % _instruments[0]
return u",".join(_instruments) | python | def ifos_from_instrument_set(instruments):
"""
Convert an iterable of instrument names into a value suitable for
storage in the "ifos" column found in many tables. This function
is mostly for internal use by the .instruments properties of the
corresponding row classes. The input can be None or an iterable of
zero or more instrument names, none of which may be zero-length,
consist exclusively of spaces, or contain "," or "+" characters.
The output is a single string containing the unique instrument
names concatenated using "," as a delimiter. instruments will only
be iterated over once and so can be a generator expression.
Whitespace is allowed in instrument names but might not be
preserved. Repeated names will not be preserved.
NOTE: in the special case that there is 1 instrument name in the
iterable and it has an even number of characters > 2 in it, the
output will have a "," appended in order to force
instrument_set_from_ifos() to parse the string back into a single
instrument name. This is a special case included temporarily to
disambiguate the encoding until all codes have been ported to the
comma-delimited encoding. This behaviour will be discontinued at
that time. DO NOT WRITE CODE THAT RELIES ON THIS! You have been
warned.
Example:
>>> print ifos_from_instrument_set(None)
None
>>> ifos_from_instrument_set(())
u''
>>> ifos_from_instrument_set((u"H1",))
u'H1'
>>> ifos_from_instrument_set((u"H1",u"H1",u"H1"))
u'H1'
>>> ifos_from_instrument_set((u"H1",u"L1"))
u'H1,L1'
>>> ifos_from_instrument_set((u"SWIFT",))
u'SWIFT'
>>> ifos_from_instrument_set((u"H1L1",))
u'H1L1,'
"""
if instruments is None:
return None
_instruments = sorted(set(instrument.strip() for instrument in instruments))
# safety check: refuse to accept blank names, or names with commas
# or pluses in them as they cannot survive the encode/decode
# process
if not all(_instruments) or any(u"," in instrument or u"+" in instrument for instrument in _instruments):
raise ValueError(instruments)
if len(_instruments) == 1 and len(_instruments[0]) > 2 and not len(_instruments[0]) % 2:
# special case disambiguation. FIXME: remove when
# everything uses the comma-delimited encoding
return u"%s," % _instruments[0]
return u",".join(_instruments) | [
"def",
"ifos_from_instrument_set",
"(",
"instruments",
")",
":",
"if",
"instruments",
"is",
"None",
":",
"return",
"None",
"_instruments",
"=",
"sorted",
"(",
"set",
"(",
"instrument",
".",
"strip",
"(",
")",
"for",
"instrument",
"in",
"instruments",
")",
")... | Convert an iterable of instrument names into a value suitable for
storage in the "ifos" column found in many tables. This function
is mostly for internal use by the .instruments properties of the
corresponding row classes. The input can be None or an iterable of
zero or more instrument names, none of which may be zero-length,
consist exclusively of spaces, or contain "," or "+" characters.
The output is a single string containing the unique instrument
names concatenated using "," as a delimiter. instruments will only
be iterated over once and so can be a generator expression.
Whitespace is allowed in instrument names but might not be
preserved. Repeated names will not be preserved.
NOTE: in the special case that there is 1 instrument name in the
iterable and it has an even number of characters > 2 in it, the
output will have a "," appended in order to force
instrument_set_from_ifos() to parse the string back into a single
instrument name. This is a special case included temporarily to
disambiguate the encoding until all codes have been ported to the
comma-delimited encoding. This behaviour will be discontinued at
that time. DO NOT WRITE CODE THAT RELIES ON THIS! You have been
warned.
Example:
>>> print ifos_from_instrument_set(None)
None
>>> ifos_from_instrument_set(())
u''
>>> ifos_from_instrument_set((u"H1",))
u'H1'
>>> ifos_from_instrument_set((u"H1",u"H1",u"H1"))
u'H1'
>>> ifos_from_instrument_set((u"H1",u"L1"))
u'H1,L1'
>>> ifos_from_instrument_set((u"SWIFT",))
u'SWIFT'
>>> ifos_from_instrument_set((u"H1L1",))
u'H1L1,' | [
"Convert",
"an",
"iterable",
"of",
"instrument",
"names",
"into",
"a",
"value",
"suitable",
"for",
"storage",
"in",
"the",
"ifos",
"column",
"found",
"in",
"many",
"tables",
".",
"This",
"function",
"is",
"mostly",
"for",
"internal",
"use",
"by",
"the",
".... | train | https://github.com/gwastro/pycbc-glue/blob/a3e906bae59fbfd707c3ff82e5d008d939ec5e24/pycbc_glue/ligolw/lsctables.py#L230-L283 |
gwastro/pycbc-glue | pycbc_glue/ligolw/lsctables.py | use_in | def use_in(ContentHandler):
"""
Modify ContentHandler, a sub-class of
pycbc_glue.ligolw.LIGOLWContentHandler, to cause it to use the Table
classes defined in this module when parsing XML documents.
Example:
>>> from pycbc_glue.ligolw import ligolw
>>> class MyContentHandler(ligolw.LIGOLWContentHandler):
... pass
...
>>> use_in(MyContentHandler)
<class 'pycbc_glue.ligolw.lsctables.MyContentHandler'>
"""
ContentHandler = table.use_in(ContentHandler)
def startTable(self, parent, attrs, __orig_startTable = ContentHandler.startTable):
name = table.StripTableName(attrs[u"Name"])
if name in TableByName:
return TableByName[name](attrs)
return __orig_startTable(self, parent, attrs)
ContentHandler.startTable = startTable
return ContentHandler | python | def use_in(ContentHandler):
"""
Modify ContentHandler, a sub-class of
pycbc_glue.ligolw.LIGOLWContentHandler, to cause it to use the Table
classes defined in this module when parsing XML documents.
Example:
>>> from pycbc_glue.ligolw import ligolw
>>> class MyContentHandler(ligolw.LIGOLWContentHandler):
... pass
...
>>> use_in(MyContentHandler)
<class 'pycbc_glue.ligolw.lsctables.MyContentHandler'>
"""
ContentHandler = table.use_in(ContentHandler)
def startTable(self, parent, attrs, __orig_startTable = ContentHandler.startTable):
name = table.StripTableName(attrs[u"Name"])
if name in TableByName:
return TableByName[name](attrs)
return __orig_startTable(self, parent, attrs)
ContentHandler.startTable = startTable
return ContentHandler | [
"def",
"use_in",
"(",
"ContentHandler",
")",
":",
"ContentHandler",
"=",
"table",
".",
"use_in",
"(",
"ContentHandler",
")",
"def",
"startTable",
"(",
"self",
",",
"parent",
",",
"attrs",
",",
"__orig_startTable",
"=",
"ContentHandler",
".",
"startTable",
")",... | Modify ContentHandler, a sub-class of
pycbc_glue.ligolw.LIGOLWContentHandler, to cause it to use the Table
classes defined in this module when parsing XML documents.
Example:
>>> from pycbc_glue.ligolw import ligolw
>>> class MyContentHandler(ligolw.LIGOLWContentHandler):
... pass
...
>>> use_in(MyContentHandler)
<class 'pycbc_glue.ligolw.lsctables.MyContentHandler'> | [
"Modify",
"ContentHandler",
"a",
"sub",
"-",
"class",
"of",
"pycbc_glue",
".",
"ligolw",
".",
"LIGOLWContentHandler",
"to",
"cause",
"it",
"to",
"use",
"the",
"Table",
"classes",
"defined",
"in",
"this",
"module",
"when",
"parsing",
"XML",
"documents",
"."
] | train | https://github.com/gwastro/pycbc-glue/blob/a3e906bae59fbfd707c3ff82e5d008d939ec5e24/pycbc_glue/ligolw/lsctables.py#L4510-L4535 |
gwastro/pycbc-glue | pycbc_glue/ligolw/lsctables.py | ProcessTable.get_ids_by_program | def get_ids_by_program(self, program):
"""
Return a set containing the process IDs from rows whose
program string equals the given program.
"""
return set(row.process_id for row in self if row.program == program) | python | def get_ids_by_program(self, program):
"""
Return a set containing the process IDs from rows whose
program string equals the given program.
"""
return set(row.process_id for row in self if row.program == program) | [
"def",
"get_ids_by_program",
"(",
"self",
",",
"program",
")",
":",
"return",
"set",
"(",
"row",
".",
"process_id",
"for",
"row",
"in",
"self",
"if",
"row",
".",
"program",
"==",
"program",
")"
] | Return a set containing the process IDs from rows whose
program string equals the given program. | [
"Return",
"a",
"set",
"containing",
"the",
"process",
"IDs",
"from",
"rows",
"whose",
"program",
"string",
"equals",
"the",
"given",
"program",
"."
] | train | https://github.com/gwastro/pycbc-glue/blob/a3e906bae59fbfd707c3ff82e5d008d939ec5e24/pycbc_glue/ligolw/lsctables.py#L320-L325 |
gwastro/pycbc-glue | pycbc_glue/ligolw/lsctables.py | SearchSummaryTable.get_in_segmentlistdict | def get_in_segmentlistdict(self, process_ids = None):
"""
Return a segmentlistdict mapping instrument to in segment
list. If process_ids is a sequence of process IDs, then
only rows with matching IDs are included otherwise all rows
are included.
Note: the result is not coalesced, each segmentlist
contains the segments listed for that instrument as they
appeared in the table.
"""
seglists = segments.segmentlistdict()
for row in self:
ifos = row.instruments or (None,)
if process_ids is None or row.process_id in process_ids:
seglists.extend(dict((ifo, segments.segmentlist([row.in_segment])) for ifo in ifos))
return seglists | python | def get_in_segmentlistdict(self, process_ids = None):
"""
Return a segmentlistdict mapping instrument to in segment
list. If process_ids is a sequence of process IDs, then
only rows with matching IDs are included otherwise all rows
are included.
Note: the result is not coalesced, each segmentlist
contains the segments listed for that instrument as they
appeared in the table.
"""
seglists = segments.segmentlistdict()
for row in self:
ifos = row.instruments or (None,)
if process_ids is None or row.process_id in process_ids:
seglists.extend(dict((ifo, segments.segmentlist([row.in_segment])) for ifo in ifos))
return seglists | [
"def",
"get_in_segmentlistdict",
"(",
"self",
",",
"process_ids",
"=",
"None",
")",
":",
"seglists",
"=",
"segments",
".",
"segmentlistdict",
"(",
")",
"for",
"row",
"in",
"self",
":",
"ifos",
"=",
"row",
".",
"instruments",
"or",
"(",
"None",
",",
")",
... | Return a segmentlistdict mapping instrument to in segment
list. If process_ids is a sequence of process IDs, then
only rows with matching IDs are included otherwise all rows
are included.
Note: the result is not coalesced, each segmentlist
contains the segments listed for that instrument as they
appeared in the table. | [
"Return",
"a",
"segmentlistdict",
"mapping",
"instrument",
"to",
"in",
"segment",
"list",
".",
"If",
"process_ids",
"is",
"a",
"sequence",
"of",
"process",
"IDs",
"then",
"only",
"rows",
"with",
"matching",
"IDs",
"are",
"included",
"otherwise",
"all",
"rows",... | train | https://github.com/gwastro/pycbc-glue/blob/a3e906bae59fbfd707c3ff82e5d008d939ec5e24/pycbc_glue/ligolw/lsctables.py#L546-L562 |
gwastro/pycbc-glue | pycbc_glue/ligolw/lsctables.py | SearchSummaryTable.get_out_segmentlistdict | def get_out_segmentlistdict(self, process_ids = None):
"""
Return a segmentlistdict mapping instrument to out segment
list. If process_ids is a sequence of process IDs, then
only rows with matching IDs are included otherwise all rows
are included.
Note: the result is not coalesced, each segmentlist
contains the segments listed for that instrument as they
appeared in the table.
"""
seglists = segments.segmentlistdict()
for row in self:
ifos = row.instruments or (None,)
if process_ids is None or row.process_id in process_ids:
seglists.extend(dict((ifo, segments.segmentlist([row.out_segment])) for ifo in ifos))
return seglists | python | def get_out_segmentlistdict(self, process_ids = None):
"""
Return a segmentlistdict mapping instrument to out segment
list. If process_ids is a sequence of process IDs, then
only rows with matching IDs are included otherwise all rows
are included.
Note: the result is not coalesced, each segmentlist
contains the segments listed for that instrument as they
appeared in the table.
"""
seglists = segments.segmentlistdict()
for row in self:
ifos = row.instruments or (None,)
if process_ids is None or row.process_id in process_ids:
seglists.extend(dict((ifo, segments.segmentlist([row.out_segment])) for ifo in ifos))
return seglists | [
"def",
"get_out_segmentlistdict",
"(",
"self",
",",
"process_ids",
"=",
"None",
")",
":",
"seglists",
"=",
"segments",
".",
"segmentlistdict",
"(",
")",
"for",
"row",
"in",
"self",
":",
"ifos",
"=",
"row",
".",
"instruments",
"or",
"(",
"None",
",",
")",... | Return a segmentlistdict mapping instrument to out segment
list. If process_ids is a sequence of process IDs, then
only rows with matching IDs are included otherwise all rows
are included.
Note: the result is not coalesced, each segmentlist
contains the segments listed for that instrument as they
appeared in the table. | [
"Return",
"a",
"segmentlistdict",
"mapping",
"instrument",
"to",
"out",
"segment",
"list",
".",
"If",
"process_ids",
"is",
"a",
"sequence",
"of",
"process",
"IDs",
"then",
"only",
"rows",
"with",
"matching",
"IDs",
"are",
"included",
"otherwise",
"all",
"rows"... | train | https://github.com/gwastro/pycbc-glue/blob/a3e906bae59fbfd707c3ff82e5d008d939ec5e24/pycbc_glue/ligolw/lsctables.py#L564-L580 |
gwastro/pycbc-glue | pycbc_glue/ligolw/lsctables.py | ExperimentTable.get_expr_id | def get_expr_id(self, search_group, search, lars_id, instruments, gps_start_time, gps_end_time, comments = None):
"""
Return the expr_def_id for the row in the table whose
values match the givens.
If a matching row is not found, returns None.
@search_group: string representing the search group (e.g., cbc)
@serach: string representing search (e.g., inspiral)
@lars_id: string representing lars_id
@instruments: the instruments; must be a python set
@gps_start_time: string or int representing the gps_start_time of the experiment
@gps_end_time: string or int representing the gps_end_time of the experiment
"""
# create string from instrument set
instruments = ifos_from_instrument_set(instruments)
# look for the ID
for row in self:
if (row.search_group, row.search, row.lars_id, row.instruments, row.gps_start_time, row.gps_end_time, row.comments) == (search_group, search, lars_id, instruments, gps_start_time, gps_end_time, comments):
# found it
return row.experiment_id
# experiment not found in table
return None | python | def get_expr_id(self, search_group, search, lars_id, instruments, gps_start_time, gps_end_time, comments = None):
"""
Return the expr_def_id for the row in the table whose
values match the givens.
If a matching row is not found, returns None.
@search_group: string representing the search group (e.g., cbc)
@serach: string representing search (e.g., inspiral)
@lars_id: string representing lars_id
@instruments: the instruments; must be a python set
@gps_start_time: string or int representing the gps_start_time of the experiment
@gps_end_time: string or int representing the gps_end_time of the experiment
"""
# create string from instrument set
instruments = ifos_from_instrument_set(instruments)
# look for the ID
for row in self:
if (row.search_group, row.search, row.lars_id, row.instruments, row.gps_start_time, row.gps_end_time, row.comments) == (search_group, search, lars_id, instruments, gps_start_time, gps_end_time, comments):
# found it
return row.experiment_id
# experiment not found in table
return None | [
"def",
"get_expr_id",
"(",
"self",
",",
"search_group",
",",
"search",
",",
"lars_id",
",",
"instruments",
",",
"gps_start_time",
",",
"gps_end_time",
",",
"comments",
"=",
"None",
")",
":",
"# create string from instrument set",
"instruments",
"=",
"ifos_from_instr... | Return the expr_def_id for the row in the table whose
values match the givens.
If a matching row is not found, returns None.
@search_group: string representing the search group (e.g., cbc)
@serach: string representing search (e.g., inspiral)
@lars_id: string representing lars_id
@instruments: the instruments; must be a python set
@gps_start_time: string or int representing the gps_start_time of the experiment
@gps_end_time: string or int representing the gps_end_time of the experiment | [
"Return",
"the",
"expr_def_id",
"for",
"the",
"row",
"in",
"the",
"table",
"whose",
"values",
"match",
"the",
"givens",
".",
"If",
"a",
"matching",
"row",
"is",
"not",
"found",
"returns",
"None",
"."
] | train | https://github.com/gwastro/pycbc-glue/blob/a3e906bae59fbfd707c3ff82e5d008d939ec5e24/pycbc_glue/ligolw/lsctables.py#L816-L839 |
gwastro/pycbc-glue | pycbc_glue/ligolw/lsctables.py | ExperimentTable.write_new_expr_id | def write_new_expr_id(self, search_group, search, lars_id, instruments, gps_start_time, gps_end_time, comments = None):
"""
Creates a new def_id for the given arguments and returns it.
If an entry already exists with these, will just return that id.
@search_group: string representing the search group (e.g., cbc)
@serach: string representing search (e.g., inspiral)
@lars_id: string representing lars_id
@instruments: the instruments; must be a python set
@gps_start_time: string or int representing the gps_start_time of the experiment
@gps_end_time: string or int representing the gps_end_time of the experiment
"""
# check if id already exists
check_id = self.get_expr_id( search_group, search, lars_id, instruments, gps_start_time, gps_end_time, comments = comments )
if check_id:
return check_id
# experiment not found in table
row = self.RowType()
row.experiment_id = self.get_next_id()
row.search_group = search_group
row.search = search
row.lars_id = lars_id
row.instruments = ifos_from_instrument_set(instruments)
row.gps_start_time = gps_start_time
row.gps_end_time = gps_end_time
row.comments = comments
self.append(row)
# return new ID
return row.experiment_id | python | def write_new_expr_id(self, search_group, search, lars_id, instruments, gps_start_time, gps_end_time, comments = None):
"""
Creates a new def_id for the given arguments and returns it.
If an entry already exists with these, will just return that id.
@search_group: string representing the search group (e.g., cbc)
@serach: string representing search (e.g., inspiral)
@lars_id: string representing lars_id
@instruments: the instruments; must be a python set
@gps_start_time: string or int representing the gps_start_time of the experiment
@gps_end_time: string or int representing the gps_end_time of the experiment
"""
# check if id already exists
check_id = self.get_expr_id( search_group, search, lars_id, instruments, gps_start_time, gps_end_time, comments = comments )
if check_id:
return check_id
# experiment not found in table
row = self.RowType()
row.experiment_id = self.get_next_id()
row.search_group = search_group
row.search = search
row.lars_id = lars_id
row.instruments = ifos_from_instrument_set(instruments)
row.gps_start_time = gps_start_time
row.gps_end_time = gps_end_time
row.comments = comments
self.append(row)
# return new ID
return row.experiment_id | [
"def",
"write_new_expr_id",
"(",
"self",
",",
"search_group",
",",
"search",
",",
"lars_id",
",",
"instruments",
",",
"gps_start_time",
",",
"gps_end_time",
",",
"comments",
"=",
"None",
")",
":",
"# check if id already exists",
"check_id",
"=",
"self",
".",
"ge... | Creates a new def_id for the given arguments and returns it.
If an entry already exists with these, will just return that id.
@search_group: string representing the search group (e.g., cbc)
@serach: string representing search (e.g., inspiral)
@lars_id: string representing lars_id
@instruments: the instruments; must be a python set
@gps_start_time: string or int representing the gps_start_time of the experiment
@gps_end_time: string or int representing the gps_end_time of the experiment | [
"Creates",
"a",
"new",
"def_id",
"for",
"the",
"given",
"arguments",
"and",
"returns",
"it",
".",
"If",
"an",
"entry",
"already",
"exists",
"with",
"these",
"will",
"just",
"return",
"that",
"id",
"."
] | train | https://github.com/gwastro/pycbc-glue/blob/a3e906bae59fbfd707c3ff82e5d008d939ec5e24/pycbc_glue/ligolw/lsctables.py#L841-L872 |
gwastro/pycbc-glue | pycbc_glue/ligolw/lsctables.py | ExperimentTable.get_row_from_id | def get_row_from_id(self, experiment_id):
"""
Returns row in matching the given experiment_id.
"""
row = [row for row in self if row.experiment_id == experiment_id]
if len(row) > 1:
raise ValueError("duplicate ids in experiment table")
if len(row) == 0:
raise ValueError("id '%s' not found in table" % experiment_id)
return row[0] | python | def get_row_from_id(self, experiment_id):
"""
Returns row in matching the given experiment_id.
"""
row = [row for row in self if row.experiment_id == experiment_id]
if len(row) > 1:
raise ValueError("duplicate ids in experiment table")
if len(row) == 0:
raise ValueError("id '%s' not found in table" % experiment_id)
return row[0] | [
"def",
"get_row_from_id",
"(",
"self",
",",
"experiment_id",
")",
":",
"row",
"=",
"[",
"row",
"for",
"row",
"in",
"self",
"if",
"row",
".",
"experiment_id",
"==",
"experiment_id",
"]",
"if",
"len",
"(",
"row",
")",
">",
"1",
":",
"raise",
"ValueError"... | Returns row in matching the given experiment_id. | [
"Returns",
"row",
"in",
"matching",
"the",
"given",
"experiment_id",
"."
] | train | https://github.com/gwastro/pycbc-glue/blob/a3e906bae59fbfd707c3ff82e5d008d939ec5e24/pycbc_glue/ligolw/lsctables.py#L874-L884 |
gwastro/pycbc-glue | pycbc_glue/ligolw/lsctables.py | ExperimentSummaryTable.as_id_dict | def as_id_dict(self):
"""
Return table as a dictionary mapping experiment_id, time_slide_id,
veto_def_name, and sim_proc_id (if it exists) to the expr_summ_id.
"""
d = {}
for row in self:
if row.experiment_id not in d:
d[row.experiment_id] = {}
if (row.time_slide_id, row.veto_def_name, row.datatype, row.sim_proc_id) in d[row.experiment_id]:
# entry already exists, raise error
raise KeyError("duplicate entries in experiment_summary table")
d[row.experiment_id][(row.time_slide_id, row.veto_def_name, row.datatype, row.sim_proc_id)] = row.experiment_summ_id
return d | python | def as_id_dict(self):
"""
Return table as a dictionary mapping experiment_id, time_slide_id,
veto_def_name, and sim_proc_id (if it exists) to the expr_summ_id.
"""
d = {}
for row in self:
if row.experiment_id not in d:
d[row.experiment_id] = {}
if (row.time_slide_id, row.veto_def_name, row.datatype, row.sim_proc_id) in d[row.experiment_id]:
# entry already exists, raise error
raise KeyError("duplicate entries in experiment_summary table")
d[row.experiment_id][(row.time_slide_id, row.veto_def_name, row.datatype, row.sim_proc_id)] = row.experiment_summ_id
return d | [
"def",
"as_id_dict",
"(",
"self",
")",
":",
"d",
"=",
"{",
"}",
"for",
"row",
"in",
"self",
":",
"if",
"row",
".",
"experiment_id",
"not",
"in",
"d",
":",
"d",
"[",
"row",
".",
"experiment_id",
"]",
"=",
"{",
"}",
"if",
"(",
"row",
".",
"time_s... | Return table as a dictionary mapping experiment_id, time_slide_id,
veto_def_name, and sim_proc_id (if it exists) to the expr_summ_id. | [
"Return",
"table",
"as",
"a",
"dictionary",
"mapping",
"experiment_id",
"time_slide_id",
"veto_def_name",
"and",
"sim_proc_id",
"(",
"if",
"it",
"exists",
")",
"to",
"the",
"expr_summ_id",
"."
] | train | https://github.com/gwastro/pycbc-glue/blob/a3e906bae59fbfd707c3ff82e5d008d939ec5e24/pycbc_glue/ligolw/lsctables.py#L942-L956 |
gwastro/pycbc-glue | pycbc_glue/ligolw/lsctables.py | ExperimentSummaryTable.get_expr_summ_id | def get_expr_summ_id(self, experiment_id, time_slide_id, veto_def_name, datatype, sim_proc_id = None):
"""
Return the expr_summ_id for the row in the table whose experiment_id,
time_slide_id, veto_def_name, and datatype match the given. If sim_proc_id,
will retrieve the injection run matching that sim_proc_id.
If a matching row is not found, returns None.
"""
# look for the ID
for row in self:
if (row.experiment_id, row.time_slide_id, row.veto_def_name, row.datatype, row.sim_proc_id) == (experiment_id, time_slide_id, veto_def_name, datatype, sim_proc_id):
# found it
return row.experiment_summ_id
# if get to here, experiment not found in table
return None | python | def get_expr_summ_id(self, experiment_id, time_slide_id, veto_def_name, datatype, sim_proc_id = None):
"""
Return the expr_summ_id for the row in the table whose experiment_id,
time_slide_id, veto_def_name, and datatype match the given. If sim_proc_id,
will retrieve the injection run matching that sim_proc_id.
If a matching row is not found, returns None.
"""
# look for the ID
for row in self:
if (row.experiment_id, row.time_slide_id, row.veto_def_name, row.datatype, row.sim_proc_id) == (experiment_id, time_slide_id, veto_def_name, datatype, sim_proc_id):
# found it
return row.experiment_summ_id
# if get to here, experiment not found in table
return None | [
"def",
"get_expr_summ_id",
"(",
"self",
",",
"experiment_id",
",",
"time_slide_id",
",",
"veto_def_name",
",",
"datatype",
",",
"sim_proc_id",
"=",
"None",
")",
":",
"# look for the ID",
"for",
"row",
"in",
"self",
":",
"if",
"(",
"row",
".",
"experiment_id",
... | Return the expr_summ_id for the row in the table whose experiment_id,
time_slide_id, veto_def_name, and datatype match the given. If sim_proc_id,
will retrieve the injection run matching that sim_proc_id.
If a matching row is not found, returns None. | [
"Return",
"the",
"expr_summ_id",
"for",
"the",
"row",
"in",
"the",
"table",
"whose",
"experiment_id",
"time_slide_id",
"veto_def_name",
"and",
"datatype",
"match",
"the",
"given",
".",
"If",
"sim_proc_id",
"will",
"retrieve",
"the",
"injection",
"run",
"matching",... | train | https://github.com/gwastro/pycbc-glue/blob/a3e906bae59fbfd707c3ff82e5d008d939ec5e24/pycbc_glue/ligolw/lsctables.py#L958-L973 |
gwastro/pycbc-glue | pycbc_glue/ligolw/lsctables.py | ExperimentSummaryTable.write_experiment_summ | def write_experiment_summ(self, experiment_id, time_slide_id, veto_def_name, datatype, sim_proc_id = None ):
"""
Writes a single entry to the experiment_summ table. This can be used
for either injections or non-injection experiments. However, it is
recommended that this only be used for injection experiments; for
non-injection experiments write_experiment_summ_set should be used to
ensure that an entry gets written for every time-slide performed.
"""
# check if entry alredy exists; if so, return value
check_id = self.get_expr_summ_id(experiment_id, time_slide_id, veto_def_name, datatype, sim_proc_id = sim_proc_id)
if check_id:
return check_id
row = self.RowType()
row.experiment_summ_id = self.get_next_id()
row.experiment_id = experiment_id
row.time_slide_id = time_slide_id
row.veto_def_name = veto_def_name
row.datatype = datatype
row.sim_proc_id = sim_proc_id
row.nevents = None
row.duration = None
self.append(row)
return row.experiment_summ_id | python | def write_experiment_summ(self, experiment_id, time_slide_id, veto_def_name, datatype, sim_proc_id = None ):
"""
Writes a single entry to the experiment_summ table. This can be used
for either injections or non-injection experiments. However, it is
recommended that this only be used for injection experiments; for
non-injection experiments write_experiment_summ_set should be used to
ensure that an entry gets written for every time-slide performed.
"""
# check if entry alredy exists; if so, return value
check_id = self.get_expr_summ_id(experiment_id, time_slide_id, veto_def_name, datatype, sim_proc_id = sim_proc_id)
if check_id:
return check_id
row = self.RowType()
row.experiment_summ_id = self.get_next_id()
row.experiment_id = experiment_id
row.time_slide_id = time_slide_id
row.veto_def_name = veto_def_name
row.datatype = datatype
row.sim_proc_id = sim_proc_id
row.nevents = None
row.duration = None
self.append(row)
return row.experiment_summ_id | [
"def",
"write_experiment_summ",
"(",
"self",
",",
"experiment_id",
",",
"time_slide_id",
",",
"veto_def_name",
",",
"datatype",
",",
"sim_proc_id",
"=",
"None",
")",
":",
"# check if entry alredy exists; if so, return value",
"check_id",
"=",
"self",
".",
"get_expr_summ... | Writes a single entry to the experiment_summ table. This can be used
for either injections or non-injection experiments. However, it is
recommended that this only be used for injection experiments; for
non-injection experiments write_experiment_summ_set should be used to
ensure that an entry gets written for every time-slide performed. | [
"Writes",
"a",
"single",
"entry",
"to",
"the",
"experiment_summ",
"table",
".",
"This",
"can",
"be",
"used",
"for",
"either",
"injections",
"or",
"non",
"-",
"injection",
"experiments",
".",
"However",
"it",
"is",
"recommended",
"that",
"this",
"only",
"be",... | train | https://github.com/gwastro/pycbc-glue/blob/a3e906bae59fbfd707c3ff82e5d008d939ec5e24/pycbc_glue/ligolw/lsctables.py#L975-L999 |
gwastro/pycbc-glue | pycbc_glue/ligolw/lsctables.py | ExperimentSummaryTable.write_non_injection_summary | def write_non_injection_summary(self, experiment_id, time_slide_dict, veto_def_name, write_all_data = True, write_playground = True, write_exclude_play = True, return_dict = False):
"""
Method for writing a new set of non-injection experiments to the experiment
summary table. This ensures that for every entry in the
experiment table, an entry for every slide is added to
the experiment_summ table, rather than just an entry for slides that
have events in them. Default is to write a 3 rows for zero-lag: one for
all_data, playground, and exclude_play. (If all of these are set to false,
will only slide rows.)
Note: sim_proc_id is hard-coded to None because time-slides
are not performed with injections.
@experiment_id: the experiment_id for this experiment_summary set
@time_slide_dict: the time_slide table as a dictionary; used to figure out
what is zero-lag and what is slide
@veto_def_name: the name of the vetoes applied
@write_all_data: if set to True, writes a zero-lag row who's datatype column
is set to 'all_data'
@write_playground: same, but datatype is 'playground'
@write_exclude_play: same, but datatype is 'exclude_play'
@return_dict: if set to true, returns an id_dict of the table
"""
for slide_id in time_slide_dict:
# check if it's zero_lag or not
if not any( time_slide_dict[slide_id].values() ):
if write_all_data:
self.write_experiment_summ( experiment_id, slide_id, veto_def_name, 'all_data', sim_proc_id = None )
if write_playground:
self.write_experiment_summ( experiment_id, slide_id, veto_def_name, 'playground', sim_proc_id = None )
if write_exclude_play:
self.write_experiment_summ( experiment_id, slide_id, veto_def_name, 'exclude_play', sim_proc_id = None )
else:
self.write_experiment_summ( experiment_id, slide_id, veto_def_name, 'slide', sim_proc_id = None )
if return_dict:
return self.as_id_dict() | python | def write_non_injection_summary(self, experiment_id, time_slide_dict, veto_def_name, write_all_data = True, write_playground = True, write_exclude_play = True, return_dict = False):
"""
Method for writing a new set of non-injection experiments to the experiment
summary table. This ensures that for every entry in the
experiment table, an entry for every slide is added to
the experiment_summ table, rather than just an entry for slides that
have events in them. Default is to write a 3 rows for zero-lag: one for
all_data, playground, and exclude_play. (If all of these are set to false,
will only slide rows.)
Note: sim_proc_id is hard-coded to None because time-slides
are not performed with injections.
@experiment_id: the experiment_id for this experiment_summary set
@time_slide_dict: the time_slide table as a dictionary; used to figure out
what is zero-lag and what is slide
@veto_def_name: the name of the vetoes applied
@write_all_data: if set to True, writes a zero-lag row who's datatype column
is set to 'all_data'
@write_playground: same, but datatype is 'playground'
@write_exclude_play: same, but datatype is 'exclude_play'
@return_dict: if set to true, returns an id_dict of the table
"""
for slide_id in time_slide_dict:
# check if it's zero_lag or not
if not any( time_slide_dict[slide_id].values() ):
if write_all_data:
self.write_experiment_summ( experiment_id, slide_id, veto_def_name, 'all_data', sim_proc_id = None )
if write_playground:
self.write_experiment_summ( experiment_id, slide_id, veto_def_name, 'playground', sim_proc_id = None )
if write_exclude_play:
self.write_experiment_summ( experiment_id, slide_id, veto_def_name, 'exclude_play', sim_proc_id = None )
else:
self.write_experiment_summ( experiment_id, slide_id, veto_def_name, 'slide', sim_proc_id = None )
if return_dict:
return self.as_id_dict() | [
"def",
"write_non_injection_summary",
"(",
"self",
",",
"experiment_id",
",",
"time_slide_dict",
",",
"veto_def_name",
",",
"write_all_data",
"=",
"True",
",",
"write_playground",
"=",
"True",
",",
"write_exclude_play",
"=",
"True",
",",
"return_dict",
"=",
"False",... | Method for writing a new set of non-injection experiments to the experiment
summary table. This ensures that for every entry in the
experiment table, an entry for every slide is added to
the experiment_summ table, rather than just an entry for slides that
have events in them. Default is to write a 3 rows for zero-lag: one for
all_data, playground, and exclude_play. (If all of these are set to false,
will only slide rows.)
Note: sim_proc_id is hard-coded to None because time-slides
are not performed with injections.
@experiment_id: the experiment_id for this experiment_summary set
@time_slide_dict: the time_slide table as a dictionary; used to figure out
what is zero-lag and what is slide
@veto_def_name: the name of the vetoes applied
@write_all_data: if set to True, writes a zero-lag row who's datatype column
is set to 'all_data'
@write_playground: same, but datatype is 'playground'
@write_exclude_play: same, but datatype is 'exclude_play'
@return_dict: if set to true, returns an id_dict of the table | [
"Method",
"for",
"writing",
"a",
"new",
"set",
"of",
"non",
"-",
"injection",
"experiments",
"to",
"the",
"experiment",
"summary",
"table",
".",
"This",
"ensures",
"that",
"for",
"every",
"entry",
"in",
"the",
"experiment",
"table",
"an",
"entry",
"for",
"... | train | https://github.com/gwastro/pycbc-glue/blob/a3e906bae59fbfd707c3ff82e5d008d939ec5e24/pycbc_glue/ligolw/lsctables.py#L1001-L1037 |
gwastro/pycbc-glue | pycbc_glue/ligolw/lsctables.py | ExperimentSummaryTable.add_nevents | def add_nevents(self, experiment_summ_id, num_events, add_to_current = True):
"""
Add num_events to the nevents column in a specific entry in the table. If
add_to_current is set to False, will overwrite the current nevents entry in
the row with num_events. Otherwise, default is to add num_events to
the current value.
Note: Can subtract events by passing a negative number to num_events.
"""
for row in self:
if row.experiment_summ_id != experiment_summ_id:
continue
if row.nevents is None:
row.nevents = 0
if add_to_current:
row.nevents += num_events
return row.nevents
else:
row.nevents = num_events
return row.nevents
# if get to here, couldn't find experiment_summ_id in the table
raise ValueError("'%s' could not be found in the table" % (str(experiment_summ_id))) | python | def add_nevents(self, experiment_summ_id, num_events, add_to_current = True):
"""
Add num_events to the nevents column in a specific entry in the table. If
add_to_current is set to False, will overwrite the current nevents entry in
the row with num_events. Otherwise, default is to add num_events to
the current value.
Note: Can subtract events by passing a negative number to num_events.
"""
for row in self:
if row.experiment_summ_id != experiment_summ_id:
continue
if row.nevents is None:
row.nevents = 0
if add_to_current:
row.nevents += num_events
return row.nevents
else:
row.nevents = num_events
return row.nevents
# if get to here, couldn't find experiment_summ_id in the table
raise ValueError("'%s' could not be found in the table" % (str(experiment_summ_id))) | [
"def",
"add_nevents",
"(",
"self",
",",
"experiment_summ_id",
",",
"num_events",
",",
"add_to_current",
"=",
"True",
")",
":",
"for",
"row",
"in",
"self",
":",
"if",
"row",
".",
"experiment_summ_id",
"!=",
"experiment_summ_id",
":",
"continue",
"if",
"row",
... | Add num_events to the nevents column in a specific entry in the table. If
add_to_current is set to False, will overwrite the current nevents entry in
the row with num_events. Otherwise, default is to add num_events to
the current value.
Note: Can subtract events by passing a negative number to num_events. | [
"Add",
"num_events",
"to",
"the",
"nevents",
"column",
"in",
"a",
"specific",
"entry",
"in",
"the",
"table",
".",
"If",
"add_to_current",
"is",
"set",
"to",
"False",
"will",
"overwrite",
"the",
"current",
"nevents",
"entry",
"in",
"the",
"row",
"with",
"nu... | train | https://github.com/gwastro/pycbc-glue/blob/a3e906bae59fbfd707c3ff82e5d008d939ec5e24/pycbc_glue/ligolw/lsctables.py#L1040-L1062 |
gwastro/pycbc-glue | pycbc_glue/ligolw/lsctables.py | ExperimentMapTable.get_experiment_summ_ids | def get_experiment_summ_ids( self, coinc_event_id ):
"""
Gets all the experiment_summ_ids that map to a given coinc_event_id.
"""
experiment_summ_ids = []
for row in self:
if row.coinc_event_id == coinc_event_id:
experiment_summ_ids.append(row.experiment_summ_id)
if len(experiment_summ_ids) == 0:
raise ValueError("'%s' could not be found in the experiment_map table" % coinc_event_id)
return experiment_summ_ids | python | def get_experiment_summ_ids( self, coinc_event_id ):
"""
Gets all the experiment_summ_ids that map to a given coinc_event_id.
"""
experiment_summ_ids = []
for row in self:
if row.coinc_event_id == coinc_event_id:
experiment_summ_ids.append(row.experiment_summ_id)
if len(experiment_summ_ids) == 0:
raise ValueError("'%s' could not be found in the experiment_map table" % coinc_event_id)
return experiment_summ_ids | [
"def",
"get_experiment_summ_ids",
"(",
"self",
",",
"coinc_event_id",
")",
":",
"experiment_summ_ids",
"=",
"[",
"]",
"for",
"row",
"in",
"self",
":",
"if",
"row",
".",
"coinc_event_id",
"==",
"coinc_event_id",
":",
"experiment_summ_ids",
".",
"append",
"(",
"... | Gets all the experiment_summ_ids that map to a given coinc_event_id. | [
"Gets",
"all",
"the",
"experiment_summ_ids",
"that",
"map",
"to",
"a",
"given",
"coinc_event_id",
"."
] | train | https://github.com/gwastro/pycbc-glue/blob/a3e906bae59fbfd707c3ff82e5d008d939ec5e24/pycbc_glue/ligolw/lsctables.py#L1092-L1102 |
gwastro/pycbc-glue | pycbc_glue/ligolw/lsctables.py | SnglBurstTable.get_column | def get_column(self, column):
"""@returns: an array of column values for each row in the table
@param column:
name of column to return
@returntype:
numpy.ndarray
"""
if column.lower() == 'q':
return self.get_q
else:
return self.getColumnByName(column).asarray() | python | def get_column(self, column):
"""@returns: an array of column values for each row in the table
@param column:
name of column to return
@returntype:
numpy.ndarray
"""
if column.lower() == 'q':
return self.get_q
else:
return self.getColumnByName(column).asarray() | [
"def",
"get_column",
"(",
"self",
",",
"column",
")",
":",
"if",
"column",
".",
"lower",
"(",
")",
"==",
"'q'",
":",
"return",
"self",
".",
"get_q",
"else",
":",
"return",
"self",
".",
"getColumnByName",
"(",
"column",
")",
".",
"asarray",
"(",
")"
] | @returns: an array of column values for each row in the table
@param column:
name of column to return
@returntype:
numpy.ndarray | [
"@returns",
":",
"an",
"array",
"of",
"column",
"values",
"for",
"each",
"row",
"in",
"the",
"table"
] | train | https://github.com/gwastro/pycbc-glue/blob/a3e906bae59fbfd707c3ff82e5d008d939ec5e24/pycbc_glue/ligolw/lsctables.py#L1269-L1280 |
gwastro/pycbc-glue | pycbc_glue/ligolw/lsctables.py | SnglInspiralTable.ifocut | def ifocut(self, ifo, inplace=False):
"""
Return a SnglInspiralTable with rows from self having IFO equal
to the given ifo. If inplace, modify self directly, else create
a new table and fill it.
"""
if inplace:
iterutils.inplace_filter(lambda row: row.ifo == ifo, self)
return self
else:
ifoTrigs = self.copy()
ifoTrigs.extend([row for row in self if row.ifo == ifo])
return ifoTrigs | python | def ifocut(self, ifo, inplace=False):
"""
Return a SnglInspiralTable with rows from self having IFO equal
to the given ifo. If inplace, modify self directly, else create
a new table and fill it.
"""
if inplace:
iterutils.inplace_filter(lambda row: row.ifo == ifo, self)
return self
else:
ifoTrigs = self.copy()
ifoTrigs.extend([row for row in self if row.ifo == ifo])
return ifoTrigs | [
"def",
"ifocut",
"(",
"self",
",",
"ifo",
",",
"inplace",
"=",
"False",
")",
":",
"if",
"inplace",
":",
"iterutils",
".",
"inplace_filter",
"(",
"lambda",
"row",
":",
"row",
".",
"ifo",
"==",
"ifo",
",",
"self",
")",
"return",
"self",
"else",
":",
... | Return a SnglInspiralTable with rows from self having IFO equal
to the given ifo. If inplace, modify self directly, else create
a new table and fill it. | [
"Return",
"a",
"SnglInspiralTable",
"with",
"rows",
"from",
"self",
"having",
"IFO",
"equal",
"to",
"the",
"given",
"ifo",
".",
"If",
"inplace",
"modify",
"self",
"directly",
"else",
"create",
"a",
"new",
"table",
"and",
"fill",
"it",
"."
] | train | https://github.com/gwastro/pycbc-glue/blob/a3e906bae59fbfd707c3ff82e5d008d939ec5e24/pycbc_glue/ligolw/lsctables.py#L1971-L1983 |
gwastro/pycbc-glue | pycbc_glue/ligolw/lsctables.py | SnglInspiralTable.getslide | def getslide(self,slide_num):
"""
Return the triggers with a specific slide number.
@param slide_num: the slide number to recover (contained in the event_id)
"""
slideTrigs = self.copy()
slideTrigs.extend(row for row in self if row.get_slide_number() == slide_num)
return slideTrigs | python | def getslide(self,slide_num):
"""
Return the triggers with a specific slide number.
@param slide_num: the slide number to recover (contained in the event_id)
"""
slideTrigs = self.copy()
slideTrigs.extend(row for row in self if row.get_slide_number() == slide_num)
return slideTrigs | [
"def",
"getslide",
"(",
"self",
",",
"slide_num",
")",
":",
"slideTrigs",
"=",
"self",
".",
"copy",
"(",
")",
"slideTrigs",
".",
"extend",
"(",
"row",
"for",
"row",
"in",
"self",
"if",
"row",
".",
"get_slide_number",
"(",
")",
"==",
"slide_num",
")",
... | Return the triggers with a specific slide number.
@param slide_num: the slide number to recover (contained in the event_id) | [
"Return",
"the",
"triggers",
"with",
"a",
"specific",
"slide",
"number",
"."
] | train | https://github.com/gwastro/pycbc-glue/blob/a3e906bae59fbfd707c3ff82e5d008d939ec5e24/pycbc_glue/ligolw/lsctables.py#L2033-L2040 |
gwastro/pycbc-glue | pycbc_glue/ligolw/lsctables.py | SnglInspiral.get_id_parts | def get_id_parts(self):
"""
Return the three pieces of the int_8s-style sngl_inspiral
event_id.
"""
int_event_id = int(self.event_id)
a = int_event_id // 1000000000
slidenum = (int_event_id % 1000000000) // 100000
b = int_event_id % 100000
return int(a), int(slidenum), int(b) | python | def get_id_parts(self):
"""
Return the three pieces of the int_8s-style sngl_inspiral
event_id.
"""
int_event_id = int(self.event_id)
a = int_event_id // 1000000000
slidenum = (int_event_id % 1000000000) // 100000
b = int_event_id % 100000
return int(a), int(slidenum), int(b) | [
"def",
"get_id_parts",
"(",
"self",
")",
":",
"int_event_id",
"=",
"int",
"(",
"self",
".",
"event_id",
")",
"a",
"=",
"int_event_id",
"//",
"1000000000",
"slidenum",
"=",
"(",
"int_event_id",
"%",
"1000000000",
")",
"//",
"100000",
"b",
"=",
"int_event_id... | Return the three pieces of the int_8s-style sngl_inspiral
event_id. | [
"Return",
"the",
"three",
"pieces",
"of",
"the",
"int_8s",
"-",
"style",
"sngl_inspiral",
"event_id",
"."
] | train | https://github.com/gwastro/pycbc-glue/blob/a3e906bae59fbfd707c3ff82e5d008d939ec5e24/pycbc_glue/ligolw/lsctables.py#L2110-L2119 |
gwastro/pycbc-glue | pycbc_glue/ligolw/lsctables.py | SnglInspiral.get_slide_number | def get_slide_number(self):
"""
Return the slide-number for this trigger
"""
a, slide_number, b = self.get_id_parts()
if slide_number > 5000:
slide_number = 5000 - slide_number
return slide_number | python | def get_slide_number(self):
"""
Return the slide-number for this trigger
"""
a, slide_number, b = self.get_id_parts()
if slide_number > 5000:
slide_number = 5000 - slide_number
return slide_number | [
"def",
"get_slide_number",
"(",
"self",
")",
":",
"a",
",",
"slide_number",
",",
"b",
"=",
"self",
".",
"get_id_parts",
"(",
")",
"if",
"slide_number",
">",
"5000",
":",
"slide_number",
"=",
"5000",
"-",
"slide_number",
"return",
"slide_number"
] | Return the slide-number for this trigger | [
"Return",
"the",
"slide",
"-",
"number",
"for",
"this",
"trigger"
] | train | https://github.com/gwastro/pycbc-glue/blob/a3e906bae59fbfd707c3ff82e5d008d939ec5e24/pycbc_glue/ligolw/lsctables.py#L2121-L2128 |
gwastro/pycbc-glue | pycbc_glue/ligolw/lsctables.py | MultiInspiralTable.get_null_snr | def get_null_snr(self):
"""
Get the coherent Null SNR for each row in the table.
"""
null_snr_sq = self.get_coinc_snr()**2 - self.get_column('snr')**2
null_snr_sq[null_snr_sq < 0] = 0.
return null_snr_sq**(1./2.) | python | def get_null_snr(self):
"""
Get the coherent Null SNR for each row in the table.
"""
null_snr_sq = self.get_coinc_snr()**2 - self.get_column('snr')**2
null_snr_sq[null_snr_sq < 0] = 0.
return null_snr_sq**(1./2.) | [
"def",
"get_null_snr",
"(",
"self",
")",
":",
"null_snr_sq",
"=",
"self",
".",
"get_coinc_snr",
"(",
")",
"**",
"2",
"-",
"self",
".",
"get_column",
"(",
"'snr'",
")",
"**",
"2",
"null_snr_sq",
"[",
"null_snr_sq",
"<",
"0",
"]",
"=",
"0.",
"return",
... | Get the coherent Null SNR for each row in the table. | [
"Get",
"the",
"coherent",
"Null",
"SNR",
"for",
"each",
"row",
"in",
"the",
"table",
"."
] | train | https://github.com/gwastro/pycbc-glue/blob/a3e906bae59fbfd707c3ff82e5d008d939ec5e24/pycbc_glue/ligolw/lsctables.py#L2563-L2569 |
gwastro/pycbc-glue | pycbc_glue/ligolw/lsctables.py | MultiInspiralTable.get_sigmasqs | def get_sigmasqs(self, instruments=None):
"""
Return dictionary of single-detector sigmas for each row in the
table.
"""
if len(self):
if not instruments:
instruments = map(str, \
instrument_set_from_ifos(self[0].ifos))
return dict((ifo, self.get_sigmasq(ifo))\
for ifo in instruments)
else:
return dict() | python | def get_sigmasqs(self, instruments=None):
"""
Return dictionary of single-detector sigmas for each row in the
table.
"""
if len(self):
if not instruments:
instruments = map(str, \
instrument_set_from_ifos(self[0].ifos))
return dict((ifo, self.get_sigmasq(ifo))\
for ifo in instruments)
else:
return dict() | [
"def",
"get_sigmasqs",
"(",
"self",
",",
"instruments",
"=",
"None",
")",
":",
"if",
"len",
"(",
"self",
")",
":",
"if",
"not",
"instruments",
":",
"instruments",
"=",
"map",
"(",
"str",
",",
"instrument_set_from_ifos",
"(",
"self",
"[",
"0",
"]",
".",... | Return dictionary of single-detector sigmas for each row in the
table. | [
"Return",
"dictionary",
"of",
"single",
"-",
"detector",
"sigmas",
"for",
"each",
"row",
"in",
"the",
"table",
"."
] | train | https://github.com/gwastro/pycbc-glue/blob/a3e906bae59fbfd707c3ff82e5d008d939ec5e24/pycbc_glue/ligolw/lsctables.py#L2603-L2615 |
gwastro/pycbc-glue | pycbc_glue/ligolw/lsctables.py | MultiInspiralTable.get_sngl_snrs | def get_sngl_snrs(self, instruments=None):
"""
Get the single-detector SNRs for each row in the table.
"""
if len(self) and instruments is None:
instruments = map(str, \
instrument_set_from_ifos(self[0].ifos))
elif instruments is None:
instruments = []
return dict((ifo, self.get_sngl_snr(ifo))\
for ifo in instruments) | python | def get_sngl_snrs(self, instruments=None):
"""
Get the single-detector SNRs for each row in the table.
"""
if len(self) and instruments is None:
instruments = map(str, \
instrument_set_from_ifos(self[0].ifos))
elif instruments is None:
instruments = []
return dict((ifo, self.get_sngl_snr(ifo))\
for ifo in instruments) | [
"def",
"get_sngl_snrs",
"(",
"self",
",",
"instruments",
"=",
"None",
")",
":",
"if",
"len",
"(",
"self",
")",
"and",
"instruments",
"is",
"None",
":",
"instruments",
"=",
"map",
"(",
"str",
",",
"instrument_set_from_ifos",
"(",
"self",
"[",
"0",
"]",
... | Get the single-detector SNRs for each row in the table. | [
"Get",
"the",
"single",
"-",
"detector",
"SNRs",
"for",
"each",
"row",
"in",
"the",
"table",
"."
] | train | https://github.com/gwastro/pycbc-glue/blob/a3e906bae59fbfd707c3ff82e5d008d939ec5e24/pycbc_glue/ligolw/lsctables.py#L2626-L2636 |
gwastro/pycbc-glue | pycbc_glue/ligolw/lsctables.py | MultiInspiralTable.get_sngl_chisqs | def get_sngl_chisqs(self, instruments=None):
"""
Get the single-detector \chi^2 for each row in the table.
"""
if len(self) and instruments is None:
instruments = map(str, \
instrument_set_from_ifos(self[0].ifos))
elif instruments is None:
instruments = []
return dict((ifo, self.get_sngl_chisq(ifo))\
for ifo in instruments) | python | def get_sngl_chisqs(self, instruments=None):
"""
Get the single-detector \chi^2 for each row in the table.
"""
if len(self) and instruments is None:
instruments = map(str, \
instrument_set_from_ifos(self[0].ifos))
elif instruments is None:
instruments = []
return dict((ifo, self.get_sngl_chisq(ifo))\
for ifo in instruments) | [
"def",
"get_sngl_chisqs",
"(",
"self",
",",
"instruments",
"=",
"None",
")",
":",
"if",
"len",
"(",
"self",
")",
"and",
"instruments",
"is",
"None",
":",
"instruments",
"=",
"map",
"(",
"str",
",",
"instrument_set_from_ifos",
"(",
"self",
"[",
"0",
"]",
... | Get the single-detector \chi^2 for each row in the table. | [
"Get",
"the",
"single",
"-",
"detector",
"\\",
"chi^2",
"for",
"each",
"row",
"in",
"the",
"table",
"."
] | train | https://github.com/gwastro/pycbc-glue/blob/a3e906bae59fbfd707c3ff82e5d008d939ec5e24/pycbc_glue/ligolw/lsctables.py#L2646-L2656 |
gwastro/pycbc-glue | pycbc_glue/ligolw/lsctables.py | MultiInspiralTable.get_sngl_bank_chisqs | def get_sngl_bank_chisqs(self, instruments=None):
"""
Get the single-detector \chi^2 for each row in the table.
"""
if len(self) and instruments is None:
instruments = map(str, \
instrument_set_from_ifos(self[0].ifos))
elif instruments is None:
instruments = []
return dict((ifo, self.get_sngl_bank_chisq(ifo))\
for ifo in instruments) | python | def get_sngl_bank_chisqs(self, instruments=None):
"""
Get the single-detector \chi^2 for each row in the table.
"""
if len(self) and instruments is None:
instruments = map(str, \
instrument_set_from_ifos(self[0].ifos))
elif instruments is None:
instruments = []
return dict((ifo, self.get_sngl_bank_chisq(ifo))\
for ifo in instruments) | [
"def",
"get_sngl_bank_chisqs",
"(",
"self",
",",
"instruments",
"=",
"None",
")",
":",
"if",
"len",
"(",
"self",
")",
"and",
"instruments",
"is",
"None",
":",
"instruments",
"=",
"map",
"(",
"str",
",",
"instrument_set_from_ifos",
"(",
"self",
"[",
"0",
... | Get the single-detector \chi^2 for each row in the table. | [
"Get",
"the",
"single",
"-",
"detector",
"\\",
"chi^2",
"for",
"each",
"row",
"in",
"the",
"table",
"."
] | train | https://github.com/gwastro/pycbc-glue/blob/a3e906bae59fbfd707c3ff82e5d008d939ec5e24/pycbc_glue/ligolw/lsctables.py#L2666-L2676 |
gwastro/pycbc-glue | pycbc_glue/ligolw/lsctables.py | MultiInspiralTable.get_sngl_cont_chisqs | def get_sngl_cont_chisqs(self, instruments=None):
"""
Get the single-detector \chi^2 for each row in the table.
"""
if len(self) and instruments is None:
instruments = map(str, \
instrument_set_from_ifos(self[0].ifos))
elif instruments is None:
instruments = []
return dict((ifo, self.get_sngl_cont_chisq(ifo))\
for ifo in instruments) | python | def get_sngl_cont_chisqs(self, instruments=None):
"""
Get the single-detector \chi^2 for each row in the table.
"""
if len(self) and instruments is None:
instruments = map(str, \
instrument_set_from_ifos(self[0].ifos))
elif instruments is None:
instruments = []
return dict((ifo, self.get_sngl_cont_chisq(ifo))\
for ifo in instruments) | [
"def",
"get_sngl_cont_chisqs",
"(",
"self",
",",
"instruments",
"=",
"None",
")",
":",
"if",
"len",
"(",
"self",
")",
"and",
"instruments",
"is",
"None",
":",
"instruments",
"=",
"map",
"(",
"str",
",",
"instrument_set_from_ifos",
"(",
"self",
"[",
"0",
... | Get the single-detector \chi^2 for each row in the table. | [
"Get",
"the",
"single",
"-",
"detector",
"\\",
"chi^2",
"for",
"each",
"row",
"in",
"the",
"table",
"."
] | train | https://github.com/gwastro/pycbc-glue/blob/a3e906bae59fbfd707c3ff82e5d008d939ec5e24/pycbc_glue/ligolw/lsctables.py#L2686-L2696 |
gwastro/pycbc-glue | pycbc_glue/ligolw/lsctables.py | MultiInspiralTable.get_bestnr | def get_bestnr(self, index=4.0, nhigh=3.0, null_snr_threshold=4.25,\
null_grad_thresh=20., null_grad_val = 1./5.):
"""
Get the BestNR statistic for each row in the table
"""
return [row.get_bestnr(index=index, nhigh=nhigh,
null_snr_threshold=null_snr_threshold,
null_grad_thresh=null_grad_thresh,
null_grad_val=null_grad_val)
for row in self] | python | def get_bestnr(self, index=4.0, nhigh=3.0, null_snr_threshold=4.25,\
null_grad_thresh=20., null_grad_val = 1./5.):
"""
Get the BestNR statistic for each row in the table
"""
return [row.get_bestnr(index=index, nhigh=nhigh,
null_snr_threshold=null_snr_threshold,
null_grad_thresh=null_grad_thresh,
null_grad_val=null_grad_val)
for row in self] | [
"def",
"get_bestnr",
"(",
"self",
",",
"index",
"=",
"4.0",
",",
"nhigh",
"=",
"3.0",
",",
"null_snr_threshold",
"=",
"4.25",
",",
"null_grad_thresh",
"=",
"20.",
",",
"null_grad_val",
"=",
"1.",
"/",
"5.",
")",
":",
"return",
"[",
"row",
".",
"get_bes... | Get the BestNR statistic for each row in the table | [
"Get",
"the",
"BestNR",
"statistic",
"for",
"each",
"row",
"in",
"the",
"table"
] | train | https://github.com/gwastro/pycbc-glue/blob/a3e906bae59fbfd707c3ff82e5d008d939ec5e24/pycbc_glue/ligolw/lsctables.py#L2698-L2707 |
gwastro/pycbc-glue | pycbc_glue/ligolw/lsctables.py | MultiInspiral.get_null_snr | def get_null_snr(self):
"""
Get the coherent Null SNR for this row.
"""
null_snr_sq = (numpy.asarray(self.get_sngl_snrs().values())**2)\
.sum() - self.snr**2
if null_snr_sq < 0:
return 0
else:
return null_snr_sq**(1./2.) | python | def get_null_snr(self):
"""
Get the coherent Null SNR for this row.
"""
null_snr_sq = (numpy.asarray(self.get_sngl_snrs().values())**2)\
.sum() - self.snr**2
if null_snr_sq < 0:
return 0
else:
return null_snr_sq**(1./2.) | [
"def",
"get_null_snr",
"(",
"self",
")",
":",
"null_snr_sq",
"=",
"(",
"numpy",
".",
"asarray",
"(",
"self",
".",
"get_sngl_snrs",
"(",
")",
".",
"values",
"(",
")",
")",
"**",
"2",
")",
".",
"sum",
"(",
")",
"-",
"self",
".",
"snr",
"**",
"2",
... | Get the coherent Null SNR for this row. | [
"Get",
"the",
"coherent",
"Null",
"SNR",
"for",
"this",
"row",
"."
] | train | https://github.com/gwastro/pycbc-glue/blob/a3e906bae59fbfd707c3ff82e5d008d939ec5e24/pycbc_glue/ligolw/lsctables.py#L2884-L2893 |
gwastro/pycbc-glue | pycbc_glue/ligolw/lsctables.py | MultiInspiral.get_sngl_snrs | def get_sngl_snrs(self):
"""
Return a dictionary of single-detector SNRs for this row.
"""
return dict((ifo, self.get_sngl_snr(ifo)) for ifo in\
instrument_set_from_ifos(self.ifos)) | python | def get_sngl_snrs(self):
"""
Return a dictionary of single-detector SNRs for this row.
"""
return dict((ifo, self.get_sngl_snr(ifo)) for ifo in\
instrument_set_from_ifos(self.ifos)) | [
"def",
"get_sngl_snrs",
"(",
"self",
")",
":",
"return",
"dict",
"(",
"(",
"ifo",
",",
"self",
".",
"get_sngl_snr",
"(",
"ifo",
")",
")",
"for",
"ifo",
"in",
"instrument_set_from_ifos",
"(",
"self",
".",
"ifos",
")",
")"
] | Return a dictionary of single-detector SNRs for this row. | [
"Return",
"a",
"dictionary",
"of",
"single",
"-",
"detector",
"SNRs",
"for",
"this",
"row",
"."
] | train | https://github.com/gwastro/pycbc-glue/blob/a3e906bae59fbfd707c3ff82e5d008d939ec5e24/pycbc_glue/ligolw/lsctables.py#L2913-L2918 |
gwastro/pycbc-glue | pycbc_glue/ligolw/lsctables.py | MultiInspiral.get_bestnr | def get_bestnr(self, index=4.0, nhigh=3.0, null_snr_threshold=4.25,\
null_grad_thresh=20., null_grad_val = 1./5.):
"""
Return the BestNR statistic for this row.
"""
# weight SNR by chisq
bestnr = self.get_new_snr(index=index, nhigh=nhigh,
column="chisq")
if len(self.get_ifos()) < 3:
return bestnr
# recontour null SNR threshold for higher SNRs
if self.snr > null_grad_thresh:
null_snr_threshold += (self.snr - null_grad_thresh) * null_grad_val
# weight SNR by null SNR
if self.get_null_snr() > null_snr_threshold:
bestnr /= 1 + self.get_null_snr() - null_snr_threshold
return bestnr | python | def get_bestnr(self, index=4.0, nhigh=3.0, null_snr_threshold=4.25,\
null_grad_thresh=20., null_grad_val = 1./5.):
"""
Return the BestNR statistic for this row.
"""
# weight SNR by chisq
bestnr = self.get_new_snr(index=index, nhigh=nhigh,
column="chisq")
if len(self.get_ifos()) < 3:
return bestnr
# recontour null SNR threshold for higher SNRs
if self.snr > null_grad_thresh:
null_snr_threshold += (self.snr - null_grad_thresh) * null_grad_val
# weight SNR by null SNR
if self.get_null_snr() > null_snr_threshold:
bestnr /= 1 + self.get_null_snr() - null_snr_threshold
return bestnr | [
"def",
"get_bestnr",
"(",
"self",
",",
"index",
"=",
"4.0",
",",
"nhigh",
"=",
"3.0",
",",
"null_snr_threshold",
"=",
"4.25",
",",
"null_grad_thresh",
"=",
"20.",
",",
"null_grad_val",
"=",
"1.",
"/",
"5.",
")",
":",
"# weight SNR by chisq",
"bestnr",
"=",... | Return the BestNR statistic for this row. | [
"Return",
"the",
"BestNR",
"statistic",
"for",
"this",
"row",
"."
] | train | https://github.com/gwastro/pycbc-glue/blob/a3e906bae59fbfd707c3ff82e5d008d939ec5e24/pycbc_glue/ligolw/lsctables.py#L2961-L2977 |
gwastro/pycbc-glue | pycbc_glue/ligolw/lsctables.py | SegmentSumTable.get | def get(self, segment_def_id = None):
"""
Return a segmentlist object describing the times spanned by
the segments carrying the given segment_def_id. If
segment_def_id is None then all segments are returned.
Note: the result is not coalesced, the segmentlist
contains the segments as they appear in the table.
"""
if segment_def_id is None:
return segments.segmentlist(row.segment for row in self)
return segments.segmentlist(row.segment for row in self if row.segment_def_id == segment_def_id) | python | def get(self, segment_def_id = None):
"""
Return a segmentlist object describing the times spanned by
the segments carrying the given segment_def_id. If
segment_def_id is None then all segments are returned.
Note: the result is not coalesced, the segmentlist
contains the segments as they appear in the table.
"""
if segment_def_id is None:
return segments.segmentlist(row.segment for row in self)
return segments.segmentlist(row.segment for row in self if row.segment_def_id == segment_def_id) | [
"def",
"get",
"(",
"self",
",",
"segment_def_id",
"=",
"None",
")",
":",
"if",
"segment_def_id",
"is",
"None",
":",
"return",
"segments",
".",
"segmentlist",
"(",
"row",
".",
"segment",
"for",
"row",
"in",
"self",
")",
"return",
"segments",
".",
"segment... | Return a segmentlist object describing the times spanned by
the segments carrying the given segment_def_id. If
segment_def_id is None then all segments are returned.
Note: the result is not coalesced, the segmentlist
contains the segments as they appear in the table. | [
"Return",
"a",
"segmentlist",
"object",
"describing",
"the",
"times",
"spanned",
"by",
"the",
"segments",
"carrying",
"the",
"given",
"segment_def_id",
".",
"If",
"segment_def_id",
"is",
"None",
"then",
"all",
"segments",
"are",
"returned",
"."
] | train | https://github.com/gwastro/pycbc-glue/blob/a3e906bae59fbfd707c3ff82e5d008d939ec5e24/pycbc_glue/ligolw/lsctables.py#L3873-L3884 |
gwastro/pycbc-glue | pycbc_glue/ligolw/lsctables.py | TimeSlideTable.as_dict | def as_dict(self):
"""
Return a ditionary mapping time slide IDs to offset
dictionaries.
"""
d = {}
for row in self:
if row.time_slide_id not in d:
d[row.time_slide_id] = offsetvector.offsetvector()
if row.instrument in d[row.time_slide_id]:
raise KeyError("'%s': duplicate instrument '%s'" % (row.time_slide_id, row.instrument))
d[row.time_slide_id][row.instrument] = row.offset
return d | python | def as_dict(self):
"""
Return a ditionary mapping time slide IDs to offset
dictionaries.
"""
d = {}
for row in self:
if row.time_slide_id not in d:
d[row.time_slide_id] = offsetvector.offsetvector()
if row.instrument in d[row.time_slide_id]:
raise KeyError("'%s': duplicate instrument '%s'" % (row.time_slide_id, row.instrument))
d[row.time_slide_id][row.instrument] = row.offset
return d | [
"def",
"as_dict",
"(",
"self",
")",
":",
"d",
"=",
"{",
"}",
"for",
"row",
"in",
"self",
":",
"if",
"row",
".",
"time_slide_id",
"not",
"in",
"d",
":",
"d",
"[",
"row",
".",
"time_slide_id",
"]",
"=",
"offsetvector",
".",
"offsetvector",
"(",
")",
... | Return a ditionary mapping time slide IDs to offset
dictionaries. | [
"Return",
"a",
"ditionary",
"mapping",
"time",
"slide",
"IDs",
"to",
"offset",
"dictionaries",
"."
] | train | https://github.com/gwastro/pycbc-glue/blob/a3e906bae59fbfd707c3ff82e5d008d939ec5e24/pycbc_glue/ligolw/lsctables.py#L3995-L4007 |
gwastro/pycbc-glue | pycbc_glue/ligolw/lsctables.py | TimeSlideTable.append_offsetvector | def append_offsetvector(self, offsetvect, process):
"""
Append rows describing an instrument --> offset mapping to
this table. offsetvect is a dictionary mapping instrument
to offset. process should be the row in the process table
on which the new time_slide table rows will be blamed (or
any object with a process_id attribute). The return value
is the time_slide_id assigned to the new rows.
"""
time_slide_id = self.get_next_id()
for instrument, offset in offsetvect.items():
row = self.RowType()
row.process_id = process.process_id
row.time_slide_id = time_slide_id
row.instrument = instrument
row.offset = offset
self.append(row)
return time_slide_id | python | def append_offsetvector(self, offsetvect, process):
"""
Append rows describing an instrument --> offset mapping to
this table. offsetvect is a dictionary mapping instrument
to offset. process should be the row in the process table
on which the new time_slide table rows will be blamed (or
any object with a process_id attribute). The return value
is the time_slide_id assigned to the new rows.
"""
time_slide_id = self.get_next_id()
for instrument, offset in offsetvect.items():
row = self.RowType()
row.process_id = process.process_id
row.time_slide_id = time_slide_id
row.instrument = instrument
row.offset = offset
self.append(row)
return time_slide_id | [
"def",
"append_offsetvector",
"(",
"self",
",",
"offsetvect",
",",
"process",
")",
":",
"time_slide_id",
"=",
"self",
".",
"get_next_id",
"(",
")",
"for",
"instrument",
",",
"offset",
"in",
"offsetvect",
".",
"items",
"(",
")",
":",
"row",
"=",
"self",
"... | Append rows describing an instrument --> offset mapping to
this table. offsetvect is a dictionary mapping instrument
to offset. process should be the row in the process table
on which the new time_slide table rows will be blamed (or
any object with a process_id attribute). The return value
is the time_slide_id assigned to the new rows. | [
"Append",
"rows",
"describing",
"an",
"instrument",
"--",
">",
"offset",
"mapping",
"to",
"this",
"table",
".",
"offsetvect",
"is",
"a",
"dictionary",
"mapping",
"instrument",
"to",
"offset",
".",
"process",
"should",
"be",
"the",
"row",
"in",
"the",
"proces... | train | https://github.com/gwastro/pycbc-glue/blob/a3e906bae59fbfd707c3ff82e5d008d939ec5e24/pycbc_glue/ligolw/lsctables.py#L4009-L4026 |
gwastro/pycbc-glue | pycbc_glue/ligolw/lsctables.py | TimeSlideTable.get_time_slide_id | def get_time_slide_id(self, offsetdict, create_new = None, superset_ok = False, nonunique_ok = False):
"""
Return the time_slide_id corresponding to the offset vector
described by offsetdict, a dictionary of instrument/offset
pairs.
If the optional create_new argument is None (the default),
then the table must contain a matching offset vector. The
return value is the ID of that vector. If the table does
not contain a matching offset vector then KeyError is
raised.
If the optional create_new argument is set to a Process
object (or any other object with a process_id attribute),
then if the table does not contain a matching offset vector
a new one will be added to the table and marked as having
been created by the given process. The return value is the
ID of the (possibly newly created) matching offset vector.
If the optional superset_ok argument is False (the default)
then an offset vector in the table is considered to "match"
the requested offset vector only if they contain the exact
same set of instruments. If the superset_ok argument is
True, then an offset vector in the table is considered to
match the requested offset vector as long as it provides
the same offsets for the same instruments as the requested
vector, even if it provides offsets for other instruments
as well.
More than one offset vector in the table might match the
requested vector. If the optional nonunique_ok argument is
False (the default), then KeyError will be raised if more
than one offset vector in the table is found to match the
requested vector. If the optional nonunique_ok is True
then the return value is the ID of one of the matching
offset vectors selected at random.
"""
# look for matching offset vectors
if superset_ok:
ids = [id for id, slide in self.as_dict().items() if offsetdict == dict((instrument, offset) for instrument, offset in slide.items() if instrument in offsetdict)]
else:
ids = [id for id, slide in self.as_dict().items() if offsetdict == slide]
if len(ids) > 1:
# found more than one
if nonunique_ok:
# and that's OK
return ids[0]
# and that's not OK
raise KeyError("%s not unique" % repr(offsetdict))
if len(ids) == 1:
# found one
return ids[0]
# offset vector not found in table
if create_new is None:
# and that's not OK
raise KeyError("%s not found" % repr(offsetdict))
# that's OK, create new vector, return its ID
return self.append_offsetvector(offsetdict, create_new) | python | def get_time_slide_id(self, offsetdict, create_new = None, superset_ok = False, nonunique_ok = False):
"""
Return the time_slide_id corresponding to the offset vector
described by offsetdict, a dictionary of instrument/offset
pairs.
If the optional create_new argument is None (the default),
then the table must contain a matching offset vector. The
return value is the ID of that vector. If the table does
not contain a matching offset vector then KeyError is
raised.
If the optional create_new argument is set to a Process
object (or any other object with a process_id attribute),
then if the table does not contain a matching offset vector
a new one will be added to the table and marked as having
been created by the given process. The return value is the
ID of the (possibly newly created) matching offset vector.
If the optional superset_ok argument is False (the default)
then an offset vector in the table is considered to "match"
the requested offset vector only if they contain the exact
same set of instruments. If the superset_ok argument is
True, then an offset vector in the table is considered to
match the requested offset vector as long as it provides
the same offsets for the same instruments as the requested
vector, even if it provides offsets for other instruments
as well.
More than one offset vector in the table might match the
requested vector. If the optional nonunique_ok argument is
False (the default), then KeyError will be raised if more
than one offset vector in the table is found to match the
requested vector. If the optional nonunique_ok is True
then the return value is the ID of one of the matching
offset vectors selected at random.
"""
# look for matching offset vectors
if superset_ok:
ids = [id for id, slide in self.as_dict().items() if offsetdict == dict((instrument, offset) for instrument, offset in slide.items() if instrument in offsetdict)]
else:
ids = [id for id, slide in self.as_dict().items() if offsetdict == slide]
if len(ids) > 1:
# found more than one
if nonunique_ok:
# and that's OK
return ids[0]
# and that's not OK
raise KeyError("%s not unique" % repr(offsetdict))
if len(ids) == 1:
# found one
return ids[0]
# offset vector not found in table
if create_new is None:
# and that's not OK
raise KeyError("%s not found" % repr(offsetdict))
# that's OK, create new vector, return its ID
return self.append_offsetvector(offsetdict, create_new) | [
"def",
"get_time_slide_id",
"(",
"self",
",",
"offsetdict",
",",
"create_new",
"=",
"None",
",",
"superset_ok",
"=",
"False",
",",
"nonunique_ok",
"=",
"False",
")",
":",
"# look for matching offset vectors",
"if",
"superset_ok",
":",
"ids",
"=",
"[",
"id",
"f... | Return the time_slide_id corresponding to the offset vector
described by offsetdict, a dictionary of instrument/offset
pairs.
If the optional create_new argument is None (the default),
then the table must contain a matching offset vector. The
return value is the ID of that vector. If the table does
not contain a matching offset vector then KeyError is
raised.
If the optional create_new argument is set to a Process
object (or any other object with a process_id attribute),
then if the table does not contain a matching offset vector
a new one will be added to the table and marked as having
been created by the given process. The return value is the
ID of the (possibly newly created) matching offset vector.
If the optional superset_ok argument is False (the default)
then an offset vector in the table is considered to "match"
the requested offset vector only if they contain the exact
same set of instruments. If the superset_ok argument is
True, then an offset vector in the table is considered to
match the requested offset vector as long as it provides
the same offsets for the same instruments as the requested
vector, even if it provides offsets for other instruments
as well.
More than one offset vector in the table might match the
requested vector. If the optional nonunique_ok argument is
False (the default), then KeyError will be raised if more
than one offset vector in the table is found to match the
requested vector. If the optional nonunique_ok is True
then the return value is the ID of one of the matching
offset vectors selected at random. | [
"Return",
"the",
"time_slide_id",
"corresponding",
"to",
"the",
"offset",
"vector",
"described",
"by",
"offsetdict",
"a",
"dictionary",
"of",
"instrument",
"/",
"offset",
"pairs",
"."
] | train | https://github.com/gwastro/pycbc-glue/blob/a3e906bae59fbfd707c3ff82e5d008d939ec5e24/pycbc_glue/ligolw/lsctables.py#L4028-L4085 |
gwastro/pycbc-glue | pycbc_glue/ligolw/lsctables.py | CoincDefTable.get_coinc_def_id | def get_coinc_def_id(self, search, search_coinc_type, create_new = True, description = None):
"""
Return the coinc_def_id for the row in the table whose
search string and search_coinc_type integer have the values
given. If a matching row is not found, the default
behaviour is to create a new row and return the ID assigned
to the new row. If, instead, create_new is False then
KeyError is raised when a matching row is not found. The
optional description parameter can be used to set the
description string assigned to the new row if one is
created, otherwise the new row is left with no description.
"""
# look for the ID
rows = [row for row in self if (row.search, row.search_coinc_type) == (search, search_coinc_type)]
if len(rows) > 1:
raise ValueError("(search, search coincidence type) = ('%s', %d) is not unique" % (search, search_coinc_type))
if len(rows) > 0:
return rows[0].coinc_def_id
# coinc type not found in table
if not create_new:
raise KeyError((search, search_coinc_type))
row = self.RowType()
row.coinc_def_id = self.get_next_id()
row.search = search
row.search_coinc_type = search_coinc_type
row.description = description
self.append(row)
# return new ID
return row.coinc_def_id | python | def get_coinc_def_id(self, search, search_coinc_type, create_new = True, description = None):
"""
Return the coinc_def_id for the row in the table whose
search string and search_coinc_type integer have the values
given. If a matching row is not found, the default
behaviour is to create a new row and return the ID assigned
to the new row. If, instead, create_new is False then
KeyError is raised when a matching row is not found. The
optional description parameter can be used to set the
description string assigned to the new row if one is
created, otherwise the new row is left with no description.
"""
# look for the ID
rows = [row for row in self if (row.search, row.search_coinc_type) == (search, search_coinc_type)]
if len(rows) > 1:
raise ValueError("(search, search coincidence type) = ('%s', %d) is not unique" % (search, search_coinc_type))
if len(rows) > 0:
return rows[0].coinc_def_id
# coinc type not found in table
if not create_new:
raise KeyError((search, search_coinc_type))
row = self.RowType()
row.coinc_def_id = self.get_next_id()
row.search = search
row.search_coinc_type = search_coinc_type
row.description = description
self.append(row)
# return new ID
return row.coinc_def_id | [
"def",
"get_coinc_def_id",
"(",
"self",
",",
"search",
",",
"search_coinc_type",
",",
"create_new",
"=",
"True",
",",
"description",
"=",
"None",
")",
":",
"# look for the ID",
"rows",
"=",
"[",
"row",
"for",
"row",
"in",
"self",
"if",
"(",
"row",
".",
"... | Return the coinc_def_id for the row in the table whose
search string and search_coinc_type integer have the values
given. If a matching row is not found, the default
behaviour is to create a new row and return the ID assigned
to the new row. If, instead, create_new is False then
KeyError is raised when a matching row is not found. The
optional description parameter can be used to set the
description string assigned to the new row if one is
created, otherwise the new row is left with no description. | [
"Return",
"the",
"coinc_def_id",
"for",
"the",
"row",
"in",
"the",
"table",
"whose",
"search",
"string",
"and",
"search_coinc_type",
"integer",
"have",
"the",
"values",
"given",
".",
"If",
"a",
"matching",
"row",
"is",
"not",
"found",
"the",
"default",
"beha... | train | https://github.com/gwastro/pycbc-glue/blob/a3e906bae59fbfd707c3ff82e5d008d939ec5e24/pycbc_glue/ligolw/lsctables.py#L4121-L4151 |
gwastro/pycbc-glue | pycbc_glue/ligolw/lsctables.py | DQSpec.apply_to_segmentlist | def apply_to_segmentlist(self, seglist):
"""
Apply our low and high windows to the segments in a
segmentlist.
"""
for i, seg in enumerate(seglist):
seglist[i] = seg.__class__(seg[0] - self.low_window, seg[1] + self.high_window) | python | def apply_to_segmentlist(self, seglist):
"""
Apply our low and high windows to the segments in a
segmentlist.
"""
for i, seg in enumerate(seglist):
seglist[i] = seg.__class__(seg[0] - self.low_window, seg[1] + self.high_window) | [
"def",
"apply_to_segmentlist",
"(",
"self",
",",
"seglist",
")",
":",
"for",
"i",
",",
"seg",
"in",
"enumerate",
"(",
"seglist",
")",
":",
"seglist",
"[",
"i",
"]",
"=",
"seg",
".",
"__class__",
"(",
"seg",
"[",
"0",
"]",
"-",
"self",
".",
"low_win... | Apply our low and high windows to the segments in a
segmentlist. | [
"Apply",
"our",
"low",
"and",
"high",
"windows",
"to",
"the",
"segments",
"in",
"a",
"segmentlist",
"."
] | train | https://github.com/gwastro/pycbc-glue/blob/a3e906bae59fbfd707c3ff82e5d008d939ec5e24/pycbc_glue/ligolw/lsctables.py#L4278-L4284 |
Faylixe/pygame_vkeyboard | pygame_vkeyboard/vkeyboard.py | synchronizeLayout | def synchronizeLayout(primary, secondary, surface_size):
"""Synchronizes given layouts by normalizing height by using
max height of given layouts to avoid transistion dirty effects.
:param primary: Primary layout used.
:param secondary: Secondary layout used.
:param surface_size: Target surface size on which layout will be displayed.
"""
primary.configure_bound(surface_size)
secondary.configure_bound(surface_size)
# Check for key size.
if (primary.key_size < secondary.key_size):
logging.warning('Normalizing key size from secondary to primary')
secondary.key_size = primary.key_size
elif (primary.key_size > secondary.key_size):
logging.warning('Normalizing key size from primary to secondary')
primary.key_size = secondary.key_size
if (primary.size[1] > secondary.size[1]):
logging.warning('Normalizing layout size from secondary to primary')
secondary.set_size(primary.size, surface_size)
elif (primary.size[1] < secondary.size[1]):
logging.warning('Normalizing layout size from primary to secondary')
primary.set_size(secondary.size, surface_size) | python | def synchronizeLayout(primary, secondary, surface_size):
"""Synchronizes given layouts by normalizing height by using
max height of given layouts to avoid transistion dirty effects.
:param primary: Primary layout used.
:param secondary: Secondary layout used.
:param surface_size: Target surface size on which layout will be displayed.
"""
primary.configure_bound(surface_size)
secondary.configure_bound(surface_size)
# Check for key size.
if (primary.key_size < secondary.key_size):
logging.warning('Normalizing key size from secondary to primary')
secondary.key_size = primary.key_size
elif (primary.key_size > secondary.key_size):
logging.warning('Normalizing key size from primary to secondary')
primary.key_size = secondary.key_size
if (primary.size[1] > secondary.size[1]):
logging.warning('Normalizing layout size from secondary to primary')
secondary.set_size(primary.size, surface_size)
elif (primary.size[1] < secondary.size[1]):
logging.warning('Normalizing layout size from primary to secondary')
primary.set_size(secondary.size, surface_size) | [
"def",
"synchronizeLayout",
"(",
"primary",
",",
"secondary",
",",
"surface_size",
")",
":",
"primary",
".",
"configure_bound",
"(",
"surface_size",
")",
"secondary",
".",
"configure_bound",
"(",
"surface_size",
")",
"# Check for key size.",
"if",
"(",
"primary",
... | Synchronizes given layouts by normalizing height by using
max height of given layouts to avoid transistion dirty effects.
:param primary: Primary layout used.
:param secondary: Secondary layout used.
:param surface_size: Target surface size on which layout will be displayed. | [
"Synchronizes",
"given",
"layouts",
"by",
"normalizing",
"height",
"by",
"using",
"max",
"height",
"of",
"given",
"layouts",
"to",
"avoid",
"transistion",
"dirty",
"effects",
"."
] | train | https://github.com/Faylixe/pygame_vkeyboard/blob/72753a47b4d1d8bf22c9c51ca877aef742481d2a/pygame_vkeyboard/vkeyboard.py#L526-L548 |
Faylixe/pygame_vkeyboard | pygame_vkeyboard/vkeyboard.py | VKeyboardRenderer.draw_key | def draw_key(self, surface, key):
"""Default drawing method for key.
Draw the key accordingly to it type.
:param surface: Surface background should be drawn in.
:param key: Target key to be drawn.
"""
if isinstance(key, VSpaceKey):
self.draw_space_key(surface, key)
elif isinstance(key, VBackKey):
self.draw_back_key(surface, key)
elif isinstance(key, VUppercaseKey):
self.draw_uppercase_key(surface, key)
elif isinstance(key, VSpecialCharKey):
self.draw_special_char_key(surface, key)
else:
self.draw_character_key(surface, key) | python | def draw_key(self, surface, key):
"""Default drawing method for key.
Draw the key accordingly to it type.
:param surface: Surface background should be drawn in.
:param key: Target key to be drawn.
"""
if isinstance(key, VSpaceKey):
self.draw_space_key(surface, key)
elif isinstance(key, VBackKey):
self.draw_back_key(surface, key)
elif isinstance(key, VUppercaseKey):
self.draw_uppercase_key(surface, key)
elif isinstance(key, VSpecialCharKey):
self.draw_special_char_key(surface, key)
else:
self.draw_character_key(surface, key) | [
"def",
"draw_key",
"(",
"self",
",",
"surface",
",",
"key",
")",
":",
"if",
"isinstance",
"(",
"key",
",",
"VSpaceKey",
")",
":",
"self",
".",
"draw_space_key",
"(",
"surface",
",",
"key",
")",
"elif",
"isinstance",
"(",
"key",
",",
"VBackKey",
")",
... | Default drawing method for key.
Draw the key accordingly to it type.
:param surface: Surface background should be drawn in.
:param key: Target key to be drawn. | [
"Default",
"drawing",
"method",
"for",
"key",
"."
] | train | https://github.com/Faylixe/pygame_vkeyboard/blob/72753a47b4d1d8bf22c9c51ca877aef742481d2a/pygame_vkeyboard/vkeyboard.py#L74-L91 |
Faylixe/pygame_vkeyboard | pygame_vkeyboard/vkeyboard.py | VKeyboardRenderer.draw_character_key | def draw_character_key(self, surface, key, special=False):
"""Default drawing method for key.
Key is drawn as a simple rectangle filled using this
cell style background color attribute. Key value is printed
into drawn cell using internal font.
:param surface: Surface background should be drawn in.
:param key: Target key to be drawn.
:param special: BOolean flag that indicates if the drawn key should use special background color if available.
"""
background_color = self.key_background_color
if special and self.special_key_background_color is not None:
background_color = self.special_key_background_color
pygame.draw.rect(surface, background_color[key.state], key.position + key.size)
size = self.font.size(key.value)
x = key.position[0] + ((key.size[0] - size[0]) / 2)
y = key.position[1] + ((key.size[1] - size[1]) / 2)
surface.blit(self.font.render(key.value, 1, self.text_color[key.state], None), (x, y)) | python | def draw_character_key(self, surface, key, special=False):
"""Default drawing method for key.
Key is drawn as a simple rectangle filled using this
cell style background color attribute. Key value is printed
into drawn cell using internal font.
:param surface: Surface background should be drawn in.
:param key: Target key to be drawn.
:param special: BOolean flag that indicates if the drawn key should use special background color if available.
"""
background_color = self.key_background_color
if special and self.special_key_background_color is not None:
background_color = self.special_key_background_color
pygame.draw.rect(surface, background_color[key.state], key.position + key.size)
size = self.font.size(key.value)
x = key.position[0] + ((key.size[0] - size[0]) / 2)
y = key.position[1] + ((key.size[1] - size[1]) / 2)
surface.blit(self.font.render(key.value, 1, self.text_color[key.state], None), (x, y)) | [
"def",
"draw_character_key",
"(",
"self",
",",
"surface",
",",
"key",
",",
"special",
"=",
"False",
")",
":",
"background_color",
"=",
"self",
".",
"key_background_color",
"if",
"special",
"and",
"self",
".",
"special_key_background_color",
"is",
"not",
"None",
... | Default drawing method for key.
Key is drawn as a simple rectangle filled using this
cell style background color attribute. Key value is printed
into drawn cell using internal font.
:param surface: Surface background should be drawn in.
:param key: Target key to be drawn.
:param special: BOolean flag that indicates if the drawn key should use special background color if available. | [
"Default",
"drawing",
"method",
"for",
"key",
"."
] | train | https://github.com/Faylixe/pygame_vkeyboard/blob/72753a47b4d1d8bf22c9c51ca877aef742481d2a/pygame_vkeyboard/vkeyboard.py#L93-L111 |
Faylixe/pygame_vkeyboard | pygame_vkeyboard/vkeyboard.py | VKeyboardRenderer.draw_uppercase_key | def draw_uppercase_key(self, surface, key):
"""Default drawing method for uppercase key. Drawn as character key.
:param surface: Surface background should be drawn in.
:param key: Target key to be drawn.
"""
key.value = u'\u21e7'
if key.is_activated():
key.value = u'\u21ea'
self.draw_character_key(surface, key, True) | python | def draw_uppercase_key(self, surface, key):
"""Default drawing method for uppercase key. Drawn as character key.
:param surface: Surface background should be drawn in.
:param key: Target key to be drawn.
"""
key.value = u'\u21e7'
if key.is_activated():
key.value = u'\u21ea'
self.draw_character_key(surface, key, True) | [
"def",
"draw_uppercase_key",
"(",
"self",
",",
"surface",
",",
"key",
")",
":",
"key",
".",
"value",
"=",
"u'\\u21e7'",
"if",
"key",
".",
"is_activated",
"(",
")",
":",
"key",
".",
"value",
"=",
"u'\\u21ea'",
"self",
".",
"draw_character_key",
"(",
"surf... | Default drawing method for uppercase key. Drawn as character key.
:param surface: Surface background should be drawn in.
:param key: Target key to be drawn. | [
"Default",
"drawing",
"method",
"for",
"uppercase",
"key",
".",
"Drawn",
"as",
"character",
"key",
"."
] | train | https://github.com/Faylixe/pygame_vkeyboard/blob/72753a47b4d1d8bf22c9c51ca877aef742481d2a/pygame_vkeyboard/vkeyboard.py#L133-L142 |
Faylixe/pygame_vkeyboard | pygame_vkeyboard/vkeyboard.py | VKeyboardRenderer.draw_special_char_key | def draw_special_char_key(self, surface, key):
"""Default drawing method for special char key. Drawn as character key.
:param surface: Surface background should be drawn in.
:param key: Target key to be drawn.
"""
key.value = u'#'
if key.is_activated():
key.value = u'Ab'
self.draw_character_key(surface, key, True) | python | def draw_special_char_key(self, surface, key):
"""Default drawing method for special char key. Drawn as character key.
:param surface: Surface background should be drawn in.
:param key: Target key to be drawn.
"""
key.value = u'#'
if key.is_activated():
key.value = u'Ab'
self.draw_character_key(surface, key, True) | [
"def",
"draw_special_char_key",
"(",
"self",
",",
"surface",
",",
"key",
")",
":",
"key",
".",
"value",
"=",
"u'#'",
"if",
"key",
".",
"is_activated",
"(",
")",
":",
"key",
".",
"value",
"=",
"u'Ab'",
"self",
".",
"draw_character_key",
"(",
"surface",
... | Default drawing method for special char key. Drawn as character key.
:param surface: Surface background should be drawn in.
:param key: Target key to be drawn. | [
"Default",
"drawing",
"method",
"for",
"special",
"char",
"key",
".",
"Drawn",
"as",
"character",
"key",
"."
] | train | https://github.com/Faylixe/pygame_vkeyboard/blob/72753a47b4d1d8bf22c9c51ca877aef742481d2a/pygame_vkeyboard/vkeyboard.py#L144-L153 |
Faylixe/pygame_vkeyboard | pygame_vkeyboard/vkeyboard.py | VKey.is_touched | def is_touched(self, position):
"""Hit detection method.
Indicates if this key has been hit by a touch / click event at the given position.
:param position: Event position.
:returns: True is the given position collide this key, False otherwise.
"""
return position[0] >= self.position[0] and position[0] <= self.position[0]+ self.size[0] | python | def is_touched(self, position):
"""Hit detection method.
Indicates if this key has been hit by a touch / click event at the given position.
:param position: Event position.
:returns: True is the given position collide this key, False otherwise.
"""
return position[0] >= self.position[0] and position[0] <= self.position[0]+ self.size[0] | [
"def",
"is_touched",
"(",
"self",
",",
"position",
")",
":",
"return",
"position",
"[",
"0",
"]",
">=",
"self",
".",
"position",
"[",
"0",
"]",
"and",
"position",
"[",
"0",
"]",
"<=",
"self",
".",
"position",
"[",
"0",
"]",
"+",
"self",
".",
"siz... | Hit detection method.
Indicates if this key has been hit by a touch / click event at the given position.
:param position: Event position.
:returns: True is the given position collide this key, False otherwise. | [
"Hit",
"detection",
"method",
".",
"Indicates",
"if",
"this",
"key",
"has",
"been",
"hit",
"by",
"a",
"touch",
"/",
"click",
"event",
"at",
"the",
"given",
"position",
"."
] | train | https://github.com/Faylixe/pygame_vkeyboard/blob/72753a47b4d1d8bf22c9c51ca877aef742481d2a/pygame_vkeyboard/vkeyboard.py#L188-L196 |
Faylixe/pygame_vkeyboard | pygame_vkeyboard/vkeyboard.py | VKeyRow.add_key | def add_key(self, key, first=False):
"""Adds the given key to this row.
:param key: Key to be added to this row.
:param first: BOolean flag that indicates if key is added at the beginning or at the end.
"""
if first:
self.keys = [key] + self.keys
else:
self.keys.append(key)
if isinstance(key, VSpaceKey):
self.space = key | python | def add_key(self, key, first=False):
"""Adds the given key to this row.
:param key: Key to be added to this row.
:param first: BOolean flag that indicates if key is added at the beginning or at the end.
"""
if first:
self.keys = [key] + self.keys
else:
self.keys.append(key)
if isinstance(key, VSpaceKey):
self.space = key | [
"def",
"add_key",
"(",
"self",
",",
"key",
",",
"first",
"=",
"False",
")",
":",
"if",
"first",
":",
"self",
".",
"keys",
"=",
"[",
"key",
"]",
"+",
"self",
".",
"keys",
"else",
":",
"self",
".",
"keys",
".",
"append",
"(",
"key",
")",
"if",
... | Adds the given key to this row.
:param key: Key to be added to this row.
:param first: BOolean flag that indicates if key is added at the beginning or at the end. | [
"Adds",
"the",
"given",
"key",
"to",
"this",
"row",
"."
] | train | https://github.com/Faylixe/pygame_vkeyboard/blob/72753a47b4d1d8bf22c9c51ca877aef742481d2a/pygame_vkeyboard/vkeyboard.py#L323-L334 |
Faylixe/pygame_vkeyboard | pygame_vkeyboard/vkeyboard.py | VKeyRow.set_size | def set_size(self, position, size, padding):
"""Row size setter.
The size correspond to the row height, since the row width is constraint
to the surface width the associated keyboard belongs. Once size is settled,
the size for each child keys is associated.
:param position: Position of this row.
:param size: Size of the row (height)
:param padding: Padding between key.
"""
self.height = size
self.position = position
x = position[0]
for key in self.keys:
key.set_size(size)
key.position = (x, position[1])
x += padding + key.size[0] | python | def set_size(self, position, size, padding):
"""Row size setter.
The size correspond to the row height, since the row width is constraint
to the surface width the associated keyboard belongs. Once size is settled,
the size for each child keys is associated.
:param position: Position of this row.
:param size: Size of the row (height)
:param padding: Padding between key.
"""
self.height = size
self.position = position
x = position[0]
for key in self.keys:
key.set_size(size)
key.position = (x, position[1])
x += padding + key.size[0] | [
"def",
"set_size",
"(",
"self",
",",
"position",
",",
"size",
",",
"padding",
")",
":",
"self",
".",
"height",
"=",
"size",
"self",
".",
"position",
"=",
"position",
"x",
"=",
"position",
"[",
"0",
"]",
"for",
"key",
"in",
"self",
".",
"keys",
":",... | Row size setter.
The size correspond to the row height, since the row width is constraint
to the surface width the associated keyboard belongs. Once size is settled,
the size for each child keys is associated.
:param position: Position of this row.
:param size: Size of the row (height)
:param padding: Padding between key. | [
"Row",
"size",
"setter",
"."
] | train | https://github.com/Faylixe/pygame_vkeyboard/blob/72753a47b4d1d8bf22c9c51ca877aef742481d2a/pygame_vkeyboard/vkeyboard.py#L336-L353 |
Faylixe/pygame_vkeyboard | pygame_vkeyboard/vkeyboard.py | VKeyboardLayout.configure_specials_key | def configure_specials_key(self, keyboard):
"""Configures specials key if needed.
:param keyboard: Keyboard instance this layout belong.
"""
special_row = VKeyRow()
max_length = self.max_length
i = len(self.rows) - 1
current_row = self.rows[i]
special_keys = [VBackKey()]
if self.allow_uppercase: special_keys.append(VUppercaseKey(keyboard))
if self.allow_special_chars: special_keys.append(VSpecialCharKey(keyboard))
while len(special_keys) > 0:
first = False
while len(special_keys) > 0 and len(current_row) < max_length:
current_row.add_key(special_keys.pop(0), first=first)
first = not first
if i > 0:
i -= 1
current_row = self.rows[i]
else:
break
if self.allow_space:
space_length = len(current_row) - len(special_keys)
special_row.add_key(VSpaceKey(space_length))
first = True
# Adding left to the special bar.
while len(special_keys) > 0:
special_row.add_key(special_keys.pop(0), first=first)
first = not first
if len(special_row) > 0:
self.rows.append(special_row) | python | def configure_specials_key(self, keyboard):
"""Configures specials key if needed.
:param keyboard: Keyboard instance this layout belong.
"""
special_row = VKeyRow()
max_length = self.max_length
i = len(self.rows) - 1
current_row = self.rows[i]
special_keys = [VBackKey()]
if self.allow_uppercase: special_keys.append(VUppercaseKey(keyboard))
if self.allow_special_chars: special_keys.append(VSpecialCharKey(keyboard))
while len(special_keys) > 0:
first = False
while len(special_keys) > 0 and len(current_row) < max_length:
current_row.add_key(special_keys.pop(0), first=first)
first = not first
if i > 0:
i -= 1
current_row = self.rows[i]
else:
break
if self.allow_space:
space_length = len(current_row) - len(special_keys)
special_row.add_key(VSpaceKey(space_length))
first = True
# Adding left to the special bar.
while len(special_keys) > 0:
special_row.add_key(special_keys.pop(0), first=first)
first = not first
if len(special_row) > 0:
self.rows.append(special_row) | [
"def",
"configure_specials_key",
"(",
"self",
",",
"keyboard",
")",
":",
"special_row",
"=",
"VKeyRow",
"(",
")",
"max_length",
"=",
"self",
".",
"max_length",
"i",
"=",
"len",
"(",
"self",
".",
"rows",
")",
"-",
"1",
"current_row",
"=",
"self",
".",
"... | Configures specials key if needed.
:param keyboard: Keyboard instance this layout belong. | [
"Configures",
"specials",
"key",
"if",
"needed",
"."
] | train | https://github.com/Faylixe/pygame_vkeyboard/blob/72753a47b4d1d8bf22c9c51ca877aef742481d2a/pygame_vkeyboard/vkeyboard.py#L421-L452 |
Faylixe/pygame_vkeyboard | pygame_vkeyboard/vkeyboard.py | VKeyboardLayout.configure_bound | def configure_bound(self, surface_size):
"""Compute keyboard bound regarding of this layout.
If key_size is None, then it will compute it regarding of the given surface_size.
:param surface_size: Size of the surface this layout will be rendered on.
:raise ValueError: If the layout model is empty.
"""
r = len(self.rows)
max_length = self.max_length
if self.key_size is None:
self.key_size = (surface_size[0] - (self.padding * (max_length + 1))) / max_length
height = self.key_size * r + self.padding * (r + 1)
if height >= surface_size[1] / 2:
logger.warning('Computed keyboard height outbound target surface, reducing key_size to match')
self.key_size = ((surface_size[1] / 2) - (self.padding * (r + 1))) / r
height = self.key_size * r + self.padding * (r + 1)
logger.warning('Normalized key_size to %spx' % self.key_size)
self.set_size((surface_size[0], height), surface_size) | python | def configure_bound(self, surface_size):
"""Compute keyboard bound regarding of this layout.
If key_size is None, then it will compute it regarding of the given surface_size.
:param surface_size: Size of the surface this layout will be rendered on.
:raise ValueError: If the layout model is empty.
"""
r = len(self.rows)
max_length = self.max_length
if self.key_size is None:
self.key_size = (surface_size[0] - (self.padding * (max_length + 1))) / max_length
height = self.key_size * r + self.padding * (r + 1)
if height >= surface_size[1] / 2:
logger.warning('Computed keyboard height outbound target surface, reducing key_size to match')
self.key_size = ((surface_size[1] / 2) - (self.padding * (r + 1))) / r
height = self.key_size * r + self.padding * (r + 1)
logger.warning('Normalized key_size to %spx' % self.key_size)
self.set_size((surface_size[0], height), surface_size) | [
"def",
"configure_bound",
"(",
"self",
",",
"surface_size",
")",
":",
"r",
"=",
"len",
"(",
"self",
".",
"rows",
")",
"max_length",
"=",
"self",
".",
"max_length",
"if",
"self",
".",
"key_size",
"is",
"None",
":",
"self",
".",
"key_size",
"=",
"(",
"... | Compute keyboard bound regarding of this layout.
If key_size is None, then it will compute it regarding of the given surface_size.
:param surface_size: Size of the surface this layout will be rendered on.
:raise ValueError: If the layout model is empty. | [
"Compute",
"keyboard",
"bound",
"regarding",
"of",
"this",
"layout",
".",
"If",
"key_size",
"is",
"None",
"then",
"it",
"will",
"compute",
"it",
"regarding",
"of",
"the",
"given",
"surface_size",
"."
] | train | https://github.com/Faylixe/pygame_vkeyboard/blob/72753a47b4d1d8bf22c9c51ca877aef742481d2a/pygame_vkeyboard/vkeyboard.py#L454-L472 |
Faylixe/pygame_vkeyboard | pygame_vkeyboard/vkeyboard.py | VKeyboardLayout.set_size | def set_size(self, size, surface_size):
"""Sets the size of this layout, and updates
position, and rows accordingly.
:param size: Size of this layout.
:param surface_size: Target surface size on which layout will be displayed.
"""
self.size = size
self.position = (0, surface_size[1] - self.size[1])
y = self.position[1] + self.padding
max_length = self.max_length
for row in self.rows:
r = len(row)
width = (r * self.key_size) + ((r + 1) * self.padding)
x = (surface_size[0] - width) / 2
if row.space is not None:
x -= ((row.space.length - 1) * self.key_size) / 2
row.set_size((x, y), self.key_size, self.padding)
y += self.padding + self.key_size | python | def set_size(self, size, surface_size):
"""Sets the size of this layout, and updates
position, and rows accordingly.
:param size: Size of this layout.
:param surface_size: Target surface size on which layout will be displayed.
"""
self.size = size
self.position = (0, surface_size[1] - self.size[1])
y = self.position[1] + self.padding
max_length = self.max_length
for row in self.rows:
r = len(row)
width = (r * self.key_size) + ((r + 1) * self.padding)
x = (surface_size[0] - width) / 2
if row.space is not None:
x -= ((row.space.length - 1) * self.key_size) / 2
row.set_size((x, y), self.key_size, self.padding)
y += self.padding + self.key_size | [
"def",
"set_size",
"(",
"self",
",",
"size",
",",
"surface_size",
")",
":",
"self",
".",
"size",
"=",
"size",
"self",
".",
"position",
"=",
"(",
"0",
",",
"surface_size",
"[",
"1",
"]",
"-",
"self",
".",
"size",
"[",
"1",
"]",
")",
"y",
"=",
"s... | Sets the size of this layout, and updates
position, and rows accordingly.
:param size: Size of this layout.
:param surface_size: Target surface size on which layout will be displayed. | [
"Sets",
"the",
"size",
"of",
"this",
"layout",
"and",
"updates",
"position",
"and",
"rows",
"accordingly",
"."
] | train | https://github.com/Faylixe/pygame_vkeyboard/blob/72753a47b4d1d8bf22c9c51ca877aef742481d2a/pygame_vkeyboard/vkeyboard.py#L474-L492 |
Faylixe/pygame_vkeyboard | pygame_vkeyboard/vkeyboard.py | VKeyboardLayout.invalidate | def invalidate(self):
""" Rests all keys states. """
for row in self.rows:
for key in row.keys:
key.state = 0 | python | def invalidate(self):
""" Rests all keys states. """
for row in self.rows:
for key in row.keys:
key.state = 0 | [
"def",
"invalidate",
"(",
"self",
")",
":",
"for",
"row",
"in",
"self",
".",
"rows",
":",
"for",
"key",
"in",
"row",
".",
"keys",
":",
"key",
".",
"state",
"=",
"0"
] | Rests all keys states. | [
"Rests",
"all",
"keys",
"states",
"."
] | train | https://github.com/Faylixe/pygame_vkeyboard/blob/72753a47b4d1d8bf22c9c51ca877aef742481d2a/pygame_vkeyboard/vkeyboard.py#L494-L498 |
Faylixe/pygame_vkeyboard | pygame_vkeyboard/vkeyboard.py | VKeyboardLayout.set_uppercase | def set_uppercase(self, uppercase):
"""Sets layout uppercase state.
:param uppercase: True if uppercase, False otherwise.
"""
for row in self.rows:
for key in row.keys:
if type(key) == VKey:
if uppercase:
key.value = key.value.upper()
else:
key.value = key.value.lower() | python | def set_uppercase(self, uppercase):
"""Sets layout uppercase state.
:param uppercase: True if uppercase, False otherwise.
"""
for row in self.rows:
for key in row.keys:
if type(key) == VKey:
if uppercase:
key.value = key.value.upper()
else:
key.value = key.value.lower() | [
"def",
"set_uppercase",
"(",
"self",
",",
"uppercase",
")",
":",
"for",
"row",
"in",
"self",
".",
"rows",
":",
"for",
"key",
"in",
"row",
".",
"keys",
":",
"if",
"type",
"(",
"key",
")",
"==",
"VKey",
":",
"if",
"uppercase",
":",
"key",
".",
"val... | Sets layout uppercase state.
:param uppercase: True if uppercase, False otherwise. | [
"Sets",
"layout",
"uppercase",
"state",
"."
] | train | https://github.com/Faylixe/pygame_vkeyboard/blob/72753a47b4d1d8bf22c9c51ca877aef742481d2a/pygame_vkeyboard/vkeyboard.py#L500-L511 |
Faylixe/pygame_vkeyboard | pygame_vkeyboard/vkeyboard.py | VKeyboardLayout.get_key_at | def get_key_at(self, position):
"""Retrieves if any key is located at the given position
:param position: Position to check key at.
:returns: The located key if any at the given position, None otherwise.
"""
for row in self.rows:
if position in row:
for key in row.keys:
if key.is_touched(position):
return key
return None | python | def get_key_at(self, position):
"""Retrieves if any key is located at the given position
:param position: Position to check key at.
:returns: The located key if any at the given position, None otherwise.
"""
for row in self.rows:
if position in row:
for key in row.keys:
if key.is_touched(position):
return key
return None | [
"def",
"get_key_at",
"(",
"self",
",",
"position",
")",
":",
"for",
"row",
"in",
"self",
".",
"rows",
":",
"if",
"position",
"in",
"row",
":",
"for",
"key",
"in",
"row",
".",
"keys",
":",
"if",
"key",
".",
"is_touched",
"(",
"position",
")",
":",
... | Retrieves if any key is located at the given position
:param position: Position to check key at.
:returns: The located key if any at the given position, None otherwise. | [
"Retrieves",
"if",
"any",
"key",
"is",
"located",
"at",
"the",
"given",
"position",
":",
"param",
"position",
":",
"Position",
"to",
"check",
"key",
"at",
".",
":",
"returns",
":",
"The",
"located",
"key",
"if",
"any",
"at",
"the",
"given",
"position",
... | train | https://github.com/Faylixe/pygame_vkeyboard/blob/72753a47b4d1d8bf22c9c51ca877aef742481d2a/pygame_vkeyboard/vkeyboard.py#L513-L524 |
Faylixe/pygame_vkeyboard | pygame_vkeyboard/vkeyboard.py | VKeyboard.draw | def draw(self):
""" Draw the virtual keyboard into the delegate surface object if enabled. """
if self.state > 0:
self.renderer.draw_background(self.surface, self.layout.position, self.layout.size)
for row in self.layout.rows:
for key in row.keys:
self.renderer.draw_key(self.surface, key) | python | def draw(self):
""" Draw the virtual keyboard into the delegate surface object if enabled. """
if self.state > 0:
self.renderer.draw_background(self.surface, self.layout.position, self.layout.size)
for row in self.layout.rows:
for key in row.keys:
self.renderer.draw_key(self.surface, key) | [
"def",
"draw",
"(",
"self",
")",
":",
"if",
"self",
".",
"state",
">",
"0",
":",
"self",
".",
"renderer",
".",
"draw_background",
"(",
"self",
".",
"surface",
",",
"self",
".",
"layout",
".",
"position",
",",
"self",
".",
"layout",
".",
"size",
")"... | Draw the virtual keyboard into the delegate surface object if enabled. | [
"Draw",
"the",
"virtual",
"keyboard",
"into",
"the",
"delegate",
"surface",
"object",
"if",
"enabled",
"."
] | train | https://github.com/Faylixe/pygame_vkeyboard/blob/72753a47b4d1d8bf22c9c51ca877aef742481d2a/pygame_vkeyboard/vkeyboard.py#L604-L610 |
Faylixe/pygame_vkeyboard | pygame_vkeyboard/vkeyboard.py | VKeyboard.on_uppercase | def on_uppercase(self):
""" Uppercase key press handler. """
self.uppercase = not self.uppercase
self.original_layout.set_uppercase(self.uppercase)
self.special_char_layout.set_uppercase(self.uppercase)
self.invalidate() | python | def on_uppercase(self):
""" Uppercase key press handler. """
self.uppercase = not self.uppercase
self.original_layout.set_uppercase(self.uppercase)
self.special_char_layout.set_uppercase(self.uppercase)
self.invalidate() | [
"def",
"on_uppercase",
"(",
"self",
")",
":",
"self",
".",
"uppercase",
"=",
"not",
"self",
".",
"uppercase",
"self",
".",
"original_layout",
".",
"set_uppercase",
"(",
"self",
".",
"uppercase",
")",
"self",
".",
"special_char_layout",
".",
"set_uppercase",
... | Uppercase key press handler. | [
"Uppercase",
"key",
"press",
"handler",
"."
] | train | https://github.com/Faylixe/pygame_vkeyboard/blob/72753a47b4d1d8bf22c9c51ca877aef742481d2a/pygame_vkeyboard/vkeyboard.py#L612-L617 |
Faylixe/pygame_vkeyboard | pygame_vkeyboard/vkeyboard.py | VKeyboard.on_special_char | def on_special_char(self):
""" Special char key press handler. """
self.special_char = not self.special_char
if self.special_char:
self.set_layout(self.special_char_layout)
else:
self.set_layout(self.original_layout)
self.invalidate() | python | def on_special_char(self):
""" Special char key press handler. """
self.special_char = not self.special_char
if self.special_char:
self.set_layout(self.special_char_layout)
else:
self.set_layout(self.original_layout)
self.invalidate() | [
"def",
"on_special_char",
"(",
"self",
")",
":",
"self",
".",
"special_char",
"=",
"not",
"self",
".",
"special_char",
"if",
"self",
".",
"special_char",
":",
"self",
".",
"set_layout",
"(",
"self",
".",
"special_char_layout",
")",
"else",
":",
"self",
"."... | Special char key press handler. | [
"Special",
"char",
"key",
"press",
"handler",
"."
] | train | https://github.com/Faylixe/pygame_vkeyboard/blob/72753a47b4d1d8bf22c9c51ca877aef742481d2a/pygame_vkeyboard/vkeyboard.py#L619-L626 |
Faylixe/pygame_vkeyboard | pygame_vkeyboard/vkeyboard.py | VKeyboard.on_event | def on_event(self, event):
"""Pygame event processing callback method.
:param event: Event to process.
"""
if self.state > 0:
if event.type == MOUSEBUTTONDOWN:
key = self.layout.get_key_at(pygame.mouse.get_pos())
if key is not None:
self.on_key_down(key)
elif event.type == MOUSEBUTTONUP:
self.on_key_up()
elif event.type == KEYDOWN:
value = pygame.key.name(event.key)
# TODO : Find from layout (consider checking layout key space ?)
elif event.type == KEYUP:
value = pygame.key.name(event.key) | python | def on_event(self, event):
"""Pygame event processing callback method.
:param event: Event to process.
"""
if self.state > 0:
if event.type == MOUSEBUTTONDOWN:
key = self.layout.get_key_at(pygame.mouse.get_pos())
if key is not None:
self.on_key_down(key)
elif event.type == MOUSEBUTTONUP:
self.on_key_up()
elif event.type == KEYDOWN:
value = pygame.key.name(event.key)
# TODO : Find from layout (consider checking layout key space ?)
elif event.type == KEYUP:
value = pygame.key.name(event.key) | [
"def",
"on_event",
"(",
"self",
",",
"event",
")",
":",
"if",
"self",
".",
"state",
">",
"0",
":",
"if",
"event",
".",
"type",
"==",
"MOUSEBUTTONDOWN",
":",
"key",
"=",
"self",
".",
"layout",
".",
"get_key_at",
"(",
"pygame",
".",
"mouse",
".",
"ge... | Pygame event processing callback method.
:param event: Event to process. | [
"Pygame",
"event",
"processing",
"callback",
"method",
"."
] | train | https://github.com/Faylixe/pygame_vkeyboard/blob/72753a47b4d1d8bf22c9c51ca877aef742481d2a/pygame_vkeyboard/vkeyboard.py#L628-L644 |
Faylixe/pygame_vkeyboard | pygame_vkeyboard/vkeyboard.py | VKeyboard.set_key_state | def set_key_state(self, key, state):
"""Sets the key state and redraws it.
:param key: Key to update state for.
:param state: New key state.
"""
key.state = state
self.renderer.draw_key(self.surface, key) | python | def set_key_state(self, key, state):
"""Sets the key state and redraws it.
:param key: Key to update state for.
:param state: New key state.
"""
key.state = state
self.renderer.draw_key(self.surface, key) | [
"def",
"set_key_state",
"(",
"self",
",",
"key",
",",
"state",
")",
":",
"key",
".",
"state",
"=",
"state",
"self",
".",
"renderer",
".",
"draw_key",
"(",
"self",
".",
"surface",
",",
"key",
")"
] | Sets the key state and redraws it.
:param key: Key to update state for.
:param state: New key state. | [
"Sets",
"the",
"key",
"state",
"and",
"redraws",
"it",
"."
] | train | https://github.com/Faylixe/pygame_vkeyboard/blob/72753a47b4d1d8bf22c9c51ca877aef742481d2a/pygame_vkeyboard/vkeyboard.py#L647-L654 |
Faylixe/pygame_vkeyboard | pygame_vkeyboard/vkeyboard.py | VKeyboard.on_key_up | def on_key_up(self):
""" Process key up event by updating buffer and release key. """
if (self.last_pressed is not None):
self.set_key_state(self.last_pressed, 0)
self.buffer = self.last_pressed.update_buffer(self.buffer)
self.text_consumer(self.buffer)
self.last_pressed = None | python | def on_key_up(self):
""" Process key up event by updating buffer and release key. """
if (self.last_pressed is not None):
self.set_key_state(self.last_pressed, 0)
self.buffer = self.last_pressed.update_buffer(self.buffer)
self.text_consumer(self.buffer)
self.last_pressed = None | [
"def",
"on_key_up",
"(",
"self",
")",
":",
"if",
"(",
"self",
".",
"last_pressed",
"is",
"not",
"None",
")",
":",
"self",
".",
"set_key_state",
"(",
"self",
".",
"last_pressed",
",",
"0",
")",
"self",
".",
"buffer",
"=",
"self",
".",
"last_pressed",
... | Process key up event by updating buffer and release key. | [
"Process",
"key",
"up",
"event",
"by",
"updating",
"buffer",
"and",
"release",
"key",
"."
] | train | https://github.com/Faylixe/pygame_vkeyboard/blob/72753a47b4d1d8bf22c9c51ca877aef742481d2a/pygame_vkeyboard/vkeyboard.py#L664-L670 |
Gjum/agarnet | agarnet/world.py | Cell.same_player | def same_player(self, other):
"""
Compares name and color.
Returns True if both are owned by the same player.
"""
return self.name == other.name \
and self.color == other.color | python | def same_player(self, other):
"""
Compares name and color.
Returns True if both are owned by the same player.
"""
return self.name == other.name \
and self.color == other.color | [
"def",
"same_player",
"(",
"self",
",",
"other",
")",
":",
"return",
"self",
".",
"name",
"==",
"other",
".",
"name",
"and",
"self",
".",
"color",
"==",
"other",
".",
"color"
] | Compares name and color.
Returns True if both are owned by the same player. | [
"Compares",
"name",
"and",
"color",
".",
"Returns",
"True",
"if",
"both",
"are",
"owned",
"by",
"the",
"same",
"player",
"."
] | train | https://github.com/Gjum/agarnet/blob/63365ba32aa31c23a6d61438b556ceb8ed65631f/agarnet/world.py#L28-L34 |
Gjum/agarnet | agarnet/world.py | World.reset | def reset(self):
"""
Clears the `cells` and leaderboards, and sets all corners to `0,0`.
"""
self.cells.clear()
self.leaderboard_names.clear()
self.leaderboard_groups.clear()
self.top_left.set(0, 0)
self.bottom_right.set(0, 0) | python | def reset(self):
"""
Clears the `cells` and leaderboards, and sets all corners to `0,0`.
"""
self.cells.clear()
self.leaderboard_names.clear()
self.leaderboard_groups.clear()
self.top_left.set(0, 0)
self.bottom_right.set(0, 0) | [
"def",
"reset",
"(",
"self",
")",
":",
"self",
".",
"cells",
".",
"clear",
"(",
")",
"self",
".",
"leaderboard_names",
".",
"clear",
"(",
")",
"self",
".",
"leaderboard_groups",
".",
"clear",
"(",
")",
"self",
".",
"top_left",
".",
"set",
"(",
"0",
... | Clears the `cells` and leaderboards, and sets all corners to `0,0`. | [
"Clears",
"the",
"cells",
"and",
"leaderboards",
"and",
"sets",
"all",
"corners",
"to",
"0",
"0",
"."
] | train | https://github.com/Gjum/agarnet/blob/63365ba32aa31c23a6d61438b556ceb8ed65631f/agarnet/world.py#L53-L61 |
Gjum/agarnet | agarnet/world.py | Player.reset | def reset(self):
"""
Clears `nick` and `own_ids`, sets `center` to `world.center`,
and then calls `cells_changed()`.
"""
self.own_ids.clear()
self.nick = ''
self.center = self.world.center
self.cells_changed() | python | def reset(self):
"""
Clears `nick` and `own_ids`, sets `center` to `world.center`,
and then calls `cells_changed()`.
"""
self.own_ids.clear()
self.nick = ''
self.center = self.world.center
self.cells_changed() | [
"def",
"reset",
"(",
"self",
")",
":",
"self",
".",
"own_ids",
".",
"clear",
"(",
")",
"self",
".",
"nick",
"=",
"''",
"self",
".",
"center",
"=",
"self",
".",
"world",
".",
"center",
"self",
".",
"cells_changed",
"(",
")"
] | Clears `nick` and `own_ids`, sets `center` to `world.center`,
and then calls `cells_changed()`. | [
"Clears",
"nick",
"and",
"own_ids",
"sets",
"center",
"to",
"world",
".",
"center",
"and",
"then",
"calls",
"cells_changed",
"()",
"."
] | train | https://github.com/Gjum/agarnet/blob/63365ba32aa31c23a6d61438b556ceb8ed65631f/agarnet/world.py#L115-L123 |
Gjum/agarnet | agarnet/world.py | Player.cells_changed | def cells_changed(self):
"""
Calculates `total_size`, `total_mass`, `scale`, and `center`.
Has to be called when the controlled cells (`own_ids`) change.
"""
self.total_size = sum(cell.size for cell in self.own_cells)
self.total_mass = sum(cell.mass for cell in self.own_cells)
self.scale = pow(min(1.0, 64.0 / self.total_size), 0.4) \
if self.total_size > 0 else 1.0
if self.own_ids:
left = min(cell.pos.x for cell in self.own_cells)
right = max(cell.pos.x for cell in self.own_cells)
top = min(cell.pos.y for cell in self.own_cells)
bottom = max(cell.pos.y for cell in self.own_cells)
self.center = Vec(left + right, top + bottom) / 2 | python | def cells_changed(self):
"""
Calculates `total_size`, `total_mass`, `scale`, and `center`.
Has to be called when the controlled cells (`own_ids`) change.
"""
self.total_size = sum(cell.size for cell in self.own_cells)
self.total_mass = sum(cell.mass for cell in self.own_cells)
self.scale = pow(min(1.0, 64.0 / self.total_size), 0.4) \
if self.total_size > 0 else 1.0
if self.own_ids:
left = min(cell.pos.x for cell in self.own_cells)
right = max(cell.pos.x for cell in self.own_cells)
top = min(cell.pos.y for cell in self.own_cells)
bottom = max(cell.pos.y for cell in self.own_cells)
self.center = Vec(left + right, top + bottom) / 2 | [
"def",
"cells_changed",
"(",
"self",
")",
":",
"self",
".",
"total_size",
"=",
"sum",
"(",
"cell",
".",
"size",
"for",
"cell",
"in",
"self",
".",
"own_cells",
")",
"self",
".",
"total_mass",
"=",
"sum",
"(",
"cell",
".",
"mass",
"for",
"cell",
"in",
... | Calculates `total_size`, `total_mass`, `scale`, and `center`.
Has to be called when the controlled cells (`own_ids`) change. | [
"Calculates",
"total_size",
"total_mass",
"scale",
"and",
"center",
"."
] | train | https://github.com/Gjum/agarnet/blob/63365ba32aa31c23a6d61438b556ceb8ed65631f/agarnet/world.py#L125-L141 |
Gjum/agarnet | agarnet/world.py | Player.visible_area | def visible_area(self):
"""
Calculated like in the official client.
Returns (top_left, bottom_right).
"""
# looks like zeach has a nice big screen
half_viewport = Vec(1920, 1080) / 2 / self.scale
top_left = self.world.center - half_viewport
bottom_right = self.world.center + half_viewport
return top_left, bottom_right | python | def visible_area(self):
"""
Calculated like in the official client.
Returns (top_left, bottom_right).
"""
# looks like zeach has a nice big screen
half_viewport = Vec(1920, 1080) / 2 / self.scale
top_left = self.world.center - half_viewport
bottom_right = self.world.center + half_viewport
return top_left, bottom_right | [
"def",
"visible_area",
"(",
"self",
")",
":",
"# looks like zeach has a nice big screen",
"half_viewport",
"=",
"Vec",
"(",
"1920",
",",
"1080",
")",
"/",
"2",
"/",
"self",
".",
"scale",
"top_left",
"=",
"self",
".",
"world",
".",
"center",
"-",
"half_viewpo... | Calculated like in the official client.
Returns (top_left, bottom_right). | [
"Calculated",
"like",
"in",
"the",
"official",
"client",
".",
"Returns",
"(",
"top_left",
"bottom_right",
")",
"."
] | train | https://github.com/Gjum/agarnet/blob/63365ba32aa31c23a6d61438b556ceb8ed65631f/agarnet/world.py#L159-L168 |
gwastro/pycbc-glue | pycbc_glue/ligolw/utils/segments.py | has_segment_tables | def has_segment_tables(xmldoc, name = None):
"""
Return True if the document contains a complete set of segment
tables. Returns False otherwise. If name is given and not None
then the return value is True only if the document's segment
tables, if present, contain a segment list by that name.
"""
try:
names = lsctables.SegmentDefTable.get_table(xmldoc).getColumnByName("name")
lsctables.SegmentTable.get_table(xmldoc)
lsctables.SegmentSumTable.get_table(xmldoc)
except (ValueError, KeyError):
return False
return name is None or name in names | python | def has_segment_tables(xmldoc, name = None):
"""
Return True if the document contains a complete set of segment
tables. Returns False otherwise. If name is given and not None
then the return value is True only if the document's segment
tables, if present, contain a segment list by that name.
"""
try:
names = lsctables.SegmentDefTable.get_table(xmldoc).getColumnByName("name")
lsctables.SegmentTable.get_table(xmldoc)
lsctables.SegmentSumTable.get_table(xmldoc)
except (ValueError, KeyError):
return False
return name is None or name in names | [
"def",
"has_segment_tables",
"(",
"xmldoc",
",",
"name",
"=",
"None",
")",
":",
"try",
":",
"names",
"=",
"lsctables",
".",
"SegmentDefTable",
".",
"get_table",
"(",
"xmldoc",
")",
".",
"getColumnByName",
"(",
"\"name\"",
")",
"lsctables",
".",
"SegmentTable... | Return True if the document contains a complete set of segment
tables. Returns False otherwise. If name is given and not None
then the return value is True only if the document's segment
tables, if present, contain a segment list by that name. | [
"Return",
"True",
"if",
"the",
"document",
"contains",
"a",
"complete",
"set",
"of",
"segment",
"tables",
".",
"Returns",
"False",
"otherwise",
".",
"If",
"name",
"is",
"given",
"and",
"not",
"None",
"then",
"the",
"return",
"value",
"is",
"True",
"only",
... | train | https://github.com/gwastro/pycbc-glue/blob/a3e906bae59fbfd707c3ff82e5d008d939ec5e24/pycbc_glue/ligolw/utils/segments.py#L504-L517 |
gwastro/pycbc-glue | pycbc_glue/ligolw/utils/segments.py | segmenttable_get_by_name | def segmenttable_get_by_name(xmldoc, name):
"""
Retrieve the segmentlists whose name equals name. The result is a
segmentlistdict indexed by instrument.
The output of this function is not coalesced, each segmentlist
contains the segments as found in the segment table.
NOTE: this is a light-weight version of the .get_by_name() method
of the LigolwSegments class intended for use when the full
machinery of that class is not required. Considerably less
document validation and error checking is performed by this
version. Consider using that method instead if your application
will be interfacing with the document via that class anyway.
"""
#
# find required tables
#
def_table = lsctables.SegmentDefTable.get_table(xmldoc)
seg_table = lsctables.SegmentTable.get_table(xmldoc)
#
# segment_def_id --> instrument names mapping but only for
# segment_definer entries bearing the requested name
#
instrument_index = dict((row.segment_def_id, row.instruments) for row in def_table if row.name == name)
#
# populate result segmentlistdict object from segment_def_map table
# and index
#
instruments = set(instrument for instruments in instrument_index.values() for instrument in instruments)
result = segments.segmentlistdict((instrument, segments.segmentlist()) for instrument in instruments)
for row in seg_table:
if row.segment_def_id in instrument_index:
seg = row.segment
for instrument in instrument_index[row.segment_def_id]:
result[instrument].append(seg)
#
# done
#
return result | python | def segmenttable_get_by_name(xmldoc, name):
"""
Retrieve the segmentlists whose name equals name. The result is a
segmentlistdict indexed by instrument.
The output of this function is not coalesced, each segmentlist
contains the segments as found in the segment table.
NOTE: this is a light-weight version of the .get_by_name() method
of the LigolwSegments class intended for use when the full
machinery of that class is not required. Considerably less
document validation and error checking is performed by this
version. Consider using that method instead if your application
will be interfacing with the document via that class anyway.
"""
#
# find required tables
#
def_table = lsctables.SegmentDefTable.get_table(xmldoc)
seg_table = lsctables.SegmentTable.get_table(xmldoc)
#
# segment_def_id --> instrument names mapping but only for
# segment_definer entries bearing the requested name
#
instrument_index = dict((row.segment_def_id, row.instruments) for row in def_table if row.name == name)
#
# populate result segmentlistdict object from segment_def_map table
# and index
#
instruments = set(instrument for instruments in instrument_index.values() for instrument in instruments)
result = segments.segmentlistdict((instrument, segments.segmentlist()) for instrument in instruments)
for row in seg_table:
if row.segment_def_id in instrument_index:
seg = row.segment
for instrument in instrument_index[row.segment_def_id]:
result[instrument].append(seg)
#
# done
#
return result | [
"def",
"segmenttable_get_by_name",
"(",
"xmldoc",
",",
"name",
")",
":",
"#",
"# find required tables",
"#",
"def_table",
"=",
"lsctables",
".",
"SegmentDefTable",
".",
"get_table",
"(",
"xmldoc",
")",
"seg_table",
"=",
"lsctables",
".",
"SegmentTable",
".",
"ge... | Retrieve the segmentlists whose name equals name. The result is a
segmentlistdict indexed by instrument.
The output of this function is not coalesced, each segmentlist
contains the segments as found in the segment table.
NOTE: this is a light-weight version of the .get_by_name() method
of the LigolwSegments class intended for use when the full
machinery of that class is not required. Considerably less
document validation and error checking is performed by this
version. Consider using that method instead if your application
will be interfacing with the document via that class anyway. | [
"Retrieve",
"the",
"segmentlists",
"whose",
"name",
"equals",
"name",
".",
"The",
"result",
"is",
"a",
"segmentlistdict",
"indexed",
"by",
"instrument",
"."
] | train | https://github.com/gwastro/pycbc-glue/blob/a3e906bae59fbfd707c3ff82e5d008d939ec5e24/pycbc_glue/ligolw/utils/segments.py#L520-L567 |
gwastro/pycbc-glue | pycbc_glue/ligolw/utils/segments.py | LigolwSegmentList.sort | def sort(self, *args):
"""
Sort the internal segment lists. The optional args are
passed to the .sort() method of the segment lists. This
can be used to control the sort order by providing an
alternate comparison function. The default is to sort by
start time with ties broken by end time.
"""
self.valid.sort(*args)
self.active.sort(*args) | python | def sort(self, *args):
"""
Sort the internal segment lists. The optional args are
passed to the .sort() method of the segment lists. This
can be used to control the sort order by providing an
alternate comparison function. The default is to sort by
start time with ties broken by end time.
"""
self.valid.sort(*args)
self.active.sort(*args) | [
"def",
"sort",
"(",
"self",
",",
"*",
"args",
")",
":",
"self",
".",
"valid",
".",
"sort",
"(",
"*",
"args",
")",
"self",
".",
"active",
".",
"sort",
"(",
"*",
"args",
")"
] | Sort the internal segment lists. The optional args are
passed to the .sort() method of the segment lists. This
can be used to control the sort order by providing an
alternate comparison function. The default is to sort by
start time with ties broken by end time. | [
"Sort",
"the",
"internal",
"segment",
"lists",
".",
"The",
"optional",
"args",
"are",
"passed",
"to",
"the",
".",
"sort",
"()",
"method",
"of",
"the",
"segment",
"lists",
".",
"This",
"can",
"be",
"used",
"to",
"control",
"the",
"sort",
"order",
"by",
... | train | https://github.com/gwastro/pycbc-glue/blob/a3e906bae59fbfd707c3ff82e5d008d939ec5e24/pycbc_glue/ligolw/utils/segments.py#L112-L121 |
gwastro/pycbc-glue | pycbc_glue/ligolw/utils/segments.py | LigolwSegments.insert_from_segwizard | def insert_from_segwizard(self, fileobj, instruments, name, version = None, comment = None):
"""
Parse the contents of the file object fileobj as a
segwizard-format segment list, and insert the result as a
new list of "active" segments into this LigolwSegments
object. A new entry will be created in the segment_definer
table for the segment list, and instruments, name and
comment are used to populate the entry's metadata. Note
that the "valid" segments are left empty, nominally
indicating that there are no periods of validity.
"""
self.add(LigolwSegmentList(active = segmentsUtils.fromsegwizard(fileobj, coltype = LIGOTimeGPS), instruments = instruments, name = name, version = version, comment = comment)) | python | def insert_from_segwizard(self, fileobj, instruments, name, version = None, comment = None):
"""
Parse the contents of the file object fileobj as a
segwizard-format segment list, and insert the result as a
new list of "active" segments into this LigolwSegments
object. A new entry will be created in the segment_definer
table for the segment list, and instruments, name and
comment are used to populate the entry's metadata. Note
that the "valid" segments are left empty, nominally
indicating that there are no periods of validity.
"""
self.add(LigolwSegmentList(active = segmentsUtils.fromsegwizard(fileobj, coltype = LIGOTimeGPS), instruments = instruments, name = name, version = version, comment = comment)) | [
"def",
"insert_from_segwizard",
"(",
"self",
",",
"fileobj",
",",
"instruments",
",",
"name",
",",
"version",
"=",
"None",
",",
"comment",
"=",
"None",
")",
":",
"self",
".",
"add",
"(",
"LigolwSegmentList",
"(",
"active",
"=",
"segmentsUtils",
".",
"froms... | Parse the contents of the file object fileobj as a
segwizard-format segment list, and insert the result as a
new list of "active" segments into this LigolwSegments
object. A new entry will be created in the segment_definer
table for the segment list, and instruments, name and
comment are used to populate the entry's metadata. Note
that the "valid" segments are left empty, nominally
indicating that there are no periods of validity. | [
"Parse",
"the",
"contents",
"of",
"the",
"file",
"object",
"fileobj",
"as",
"a",
"segwizard",
"-",
"format",
"segment",
"list",
"and",
"insert",
"the",
"result",
"as",
"a",
"new",
"list",
"of",
"active",
"segments",
"into",
"this",
"LigolwSegments",
"object"... | train | https://github.com/gwastro/pycbc-glue/blob/a3e906bae59fbfd707c3ff82e5d008d939ec5e24/pycbc_glue/ligolw/utils/segments.py#L298-L309 |
gwastro/pycbc-glue | pycbc_glue/ligolw/utils/segments.py | LigolwSegments.insert_from_segmentlistdict | def insert_from_segmentlistdict(self, seglists, name, version = None, comment = None, valid=None):
"""
Insert the segments from the segmentlistdict object
seglists as a new list of "active" segments into this
LigolwSegments object. The dictionary's keys are assumed
to provide the instrument name for each segment list. A
new entry will be created in the segment_definer table for
the segment lists, and the dictionary's keys, the name, and
comment will be used to populate the entry's metadata.
"""
for instrument, segments in seglists.items():
if valid is None:
curr_valid = ()
else:
curr_valid = valid[instrument]
self.add(LigolwSegmentList(active = segments, instruments = set([instrument]), name = name, version = version, comment = comment, valid = curr_valid)) | python | def insert_from_segmentlistdict(self, seglists, name, version = None, comment = None, valid=None):
"""
Insert the segments from the segmentlistdict object
seglists as a new list of "active" segments into this
LigolwSegments object. The dictionary's keys are assumed
to provide the instrument name for each segment list. A
new entry will be created in the segment_definer table for
the segment lists, and the dictionary's keys, the name, and
comment will be used to populate the entry's metadata.
"""
for instrument, segments in seglists.items():
if valid is None:
curr_valid = ()
else:
curr_valid = valid[instrument]
self.add(LigolwSegmentList(active = segments, instruments = set([instrument]), name = name, version = version, comment = comment, valid = curr_valid)) | [
"def",
"insert_from_segmentlistdict",
"(",
"self",
",",
"seglists",
",",
"name",
",",
"version",
"=",
"None",
",",
"comment",
"=",
"None",
",",
"valid",
"=",
"None",
")",
":",
"for",
"instrument",
",",
"segments",
"in",
"seglists",
".",
"items",
"(",
")"... | Insert the segments from the segmentlistdict object
seglists as a new list of "active" segments into this
LigolwSegments object. The dictionary's keys are assumed
to provide the instrument name for each segment list. A
new entry will be created in the segment_definer table for
the segment lists, and the dictionary's keys, the name, and
comment will be used to populate the entry's metadata. | [
"Insert",
"the",
"segments",
"from",
"the",
"segmentlistdict",
"object",
"seglists",
"as",
"a",
"new",
"list",
"of",
"active",
"segments",
"into",
"this",
"LigolwSegments",
"object",
".",
"The",
"dictionary",
"s",
"keys",
"are",
"assumed",
"to",
"provide",
"th... | train | https://github.com/gwastro/pycbc-glue/blob/a3e906bae59fbfd707c3ff82e5d008d939ec5e24/pycbc_glue/ligolw/utils/segments.py#L312-L327 |
gwastro/pycbc-glue | pycbc_glue/ligolw/utils/segments.py | LigolwSegments.optimize | def optimize(self):
"""
Identifies segment lists that differ only in their
instruments --- they have the same valid and active
segments, the same name, version and the same comment ---
and then deletes all but one of them, leaving just a single
list having the union of the instruments.
"""
self.sort()
segment_lists = dict(enumerate(self))
for target, source in [(idx_a, idx_b) for (idx_a, seglist_a), (idx_b, seglist_b) in iterutils.choices(segment_lists.items(), 2) if seglist_a.valid == seglist_b.valid and seglist_a.active == seglist_b.active and seglist_a.name == seglist_b.name and seglist_a.version == seglist_b.version and seglist_a.comment == seglist_b.comment]:
try:
source = segment_lists.pop(source)
except KeyError:
continue
segment_lists[target].instruments |= source.instruments
self.clear()
self.update(segment_lists.values()) | python | def optimize(self):
"""
Identifies segment lists that differ only in their
instruments --- they have the same valid and active
segments, the same name, version and the same comment ---
and then deletes all but one of them, leaving just a single
list having the union of the instruments.
"""
self.sort()
segment_lists = dict(enumerate(self))
for target, source in [(idx_a, idx_b) for (idx_a, seglist_a), (idx_b, seglist_b) in iterutils.choices(segment_lists.items(), 2) if seglist_a.valid == seglist_b.valid and seglist_a.active == seglist_b.active and seglist_a.name == seglist_b.name and seglist_a.version == seglist_b.version and seglist_a.comment == seglist_b.comment]:
try:
source = segment_lists.pop(source)
except KeyError:
continue
segment_lists[target].instruments |= source.instruments
self.clear()
self.update(segment_lists.values()) | [
"def",
"optimize",
"(",
"self",
")",
":",
"self",
".",
"sort",
"(",
")",
"segment_lists",
"=",
"dict",
"(",
"enumerate",
"(",
"self",
")",
")",
"for",
"target",
",",
"source",
"in",
"[",
"(",
"idx_a",
",",
"idx_b",
")",
"for",
"(",
"idx_a",
",",
... | Identifies segment lists that differ only in their
instruments --- they have the same valid and active
segments, the same name, version and the same comment ---
and then deletes all but one of them, leaving just a single
list having the union of the instruments. | [
"Identifies",
"segment",
"lists",
"that",
"differ",
"only",
"in",
"their",
"instruments",
"---",
"they",
"have",
"the",
"same",
"valid",
"and",
"active",
"segments",
"the",
"same",
"name",
"version",
"and",
"the",
"same",
"comment",
"---",
"and",
"then",
"de... | train | https://github.com/gwastro/pycbc-glue/blob/a3e906bae59fbfd707c3ff82e5d008d939ec5e24/pycbc_glue/ligolw/utils/segments.py#L351-L368 |
gwastro/pycbc-glue | pycbc_glue/ligolw/utils/segments.py | LigolwSegments.get_by_name | def get_by_name(self, name, clip_to_valid = False):
"""
Retrieve the active segmentlists whose name equals name.
The result is a segmentlistdict indexed by instrument. All
segmentlist objects within it will be copies of the
contents of this object, modifications will not affect the
contents of this object. If clip_to_valid is True then the
segmentlists will be intersected with their respective
intervals of validity, otherwise they will be the verbatim
active segments.
NOTE: the intersection operation required by clip_to_valid
will yield undefined results unless the active and valid
segmentlist objects are coalesced.
"""
result = segments.segmentlistdict()
for seglist in self:
if seglist.name != name:
continue
segs = seglist.active
if clip_to_valid:
# do not use in-place intersection
segs = segs & seglist.valid
for instrument in seglist.instruments:
if instrument in result:
raise ValueError("multiple '%s' segmentlists for instrument '%s'" % (name, instrument))
result[instrument] = segs.copy()
return result | python | def get_by_name(self, name, clip_to_valid = False):
"""
Retrieve the active segmentlists whose name equals name.
The result is a segmentlistdict indexed by instrument. All
segmentlist objects within it will be copies of the
contents of this object, modifications will not affect the
contents of this object. If clip_to_valid is True then the
segmentlists will be intersected with their respective
intervals of validity, otherwise they will be the verbatim
active segments.
NOTE: the intersection operation required by clip_to_valid
will yield undefined results unless the active and valid
segmentlist objects are coalesced.
"""
result = segments.segmentlistdict()
for seglist in self:
if seglist.name != name:
continue
segs = seglist.active
if clip_to_valid:
# do not use in-place intersection
segs = segs & seglist.valid
for instrument in seglist.instruments:
if instrument in result:
raise ValueError("multiple '%s' segmentlists for instrument '%s'" % (name, instrument))
result[instrument] = segs.copy()
return result | [
"def",
"get_by_name",
"(",
"self",
",",
"name",
",",
"clip_to_valid",
"=",
"False",
")",
":",
"result",
"=",
"segments",
".",
"segmentlistdict",
"(",
")",
"for",
"seglist",
"in",
"self",
":",
"if",
"seglist",
".",
"name",
"!=",
"name",
":",
"continue",
... | Retrieve the active segmentlists whose name equals name.
The result is a segmentlistdict indexed by instrument. All
segmentlist objects within it will be copies of the
contents of this object, modifications will not affect the
contents of this object. If clip_to_valid is True then the
segmentlists will be intersected with their respective
intervals of validity, otherwise they will be the verbatim
active segments.
NOTE: the intersection operation required by clip_to_valid
will yield undefined results unless the active and valid
segmentlist objects are coalesced. | [
"Retrieve",
"the",
"active",
"segmentlists",
"whose",
"name",
"equals",
"name",
".",
"The",
"result",
"is",
"a",
"segmentlistdict",
"indexed",
"by",
"instrument",
".",
"All",
"segmentlist",
"objects",
"within",
"it",
"will",
"be",
"copies",
"of",
"the",
"conte... | train | https://github.com/gwastro/pycbc-glue/blob/a3e906bae59fbfd707c3ff82e5d008d939ec5e24/pycbc_glue/ligolw/utils/segments.py#L371-L398 |
gwastro/pycbc-glue | pycbc_glue/ligolw/utils/segments.py | LigolwSegments.finalize | def finalize(self, process_row = None):
"""
Restore the LigolwSegmentList objects to the XML tables in
preparation for output. All segments from all segment
lists are inserted into the tables in time order, but this
is NOT behaviour external applications should rely on.
This is done simply in the belief that it might assist in
constructing well balanced indexed databases from the
resulting files. If that proves not to be the case, or for
some reason this behaviour proves inconvenient to preserve,
then it might be discontinued without notice. You've been
warned.
"""
if process_row is not None:
process_id = process_row.process_id
elif self.process is not None:
process_id = self.process.process_id
else:
raise ValueError("must supply a process row to .__init__()")
#
# ensure ID generators are synchronized with table contents
#
self.segment_def_table.sync_next_id()
self.segment_table.sync_next_id()
self.segment_sum_table.sync_next_id()
#
# put all segment lists in time order
#
self.sort()
#
# generator function to convert segments into row objects,
# each paired with the table to which the row is to be
# appended
#
def row_generator(segs, target_table, process_id, segment_def_id):
id_column = target_table.next_id.column_name
for seg in segs:
row = target_table.RowType()
row.segment = seg
row.process_id = process_id
row.segment_def_id = segment_def_id
setattr(row, id_column, target_table.get_next_id())
if 'comment' in target_table.validcolumns:
row.comment = None
yield row, target_table
#
# populate the segment_definer table from the list of
# LigolwSegmentList objects and construct a matching list
# of table row generators. empty ourselves to prevent this
# process from being repeated
#
row_generators = []
while self:
ligolw_segment_list = self.pop()
segment_def_row = self.segment_def_table.RowType()
segment_def_row.process_id = process_id
segment_def_row.segment_def_id = self.segment_def_table.get_next_id()
segment_def_row.instruments = ligolw_segment_list.instruments
segment_def_row.name = ligolw_segment_list.name
segment_def_row.version = ligolw_segment_list.version
segment_def_row.comment = ligolw_segment_list.comment
self.segment_def_table.append(segment_def_row)
row_generators.append(row_generator(ligolw_segment_list.valid, self.segment_sum_table, process_id, segment_def_row.segment_def_id))
row_generators.append(row_generator(ligolw_segment_list.active, self.segment_table, process_id, segment_def_row.segment_def_id))
#
# populate segment and segment_summary tables by pulling
# rows from the generators in time order
#
for row, target_table in iterutils.inorder(*row_generators):
target_table.append(row) | python | def finalize(self, process_row = None):
"""
Restore the LigolwSegmentList objects to the XML tables in
preparation for output. All segments from all segment
lists are inserted into the tables in time order, but this
is NOT behaviour external applications should rely on.
This is done simply in the belief that it might assist in
constructing well balanced indexed databases from the
resulting files. If that proves not to be the case, or for
some reason this behaviour proves inconvenient to preserve,
then it might be discontinued without notice. You've been
warned.
"""
if process_row is not None:
process_id = process_row.process_id
elif self.process is not None:
process_id = self.process.process_id
else:
raise ValueError("must supply a process row to .__init__()")
#
# ensure ID generators are synchronized with table contents
#
self.segment_def_table.sync_next_id()
self.segment_table.sync_next_id()
self.segment_sum_table.sync_next_id()
#
# put all segment lists in time order
#
self.sort()
#
# generator function to convert segments into row objects,
# each paired with the table to which the row is to be
# appended
#
def row_generator(segs, target_table, process_id, segment_def_id):
id_column = target_table.next_id.column_name
for seg in segs:
row = target_table.RowType()
row.segment = seg
row.process_id = process_id
row.segment_def_id = segment_def_id
setattr(row, id_column, target_table.get_next_id())
if 'comment' in target_table.validcolumns:
row.comment = None
yield row, target_table
#
# populate the segment_definer table from the list of
# LigolwSegmentList objects and construct a matching list
# of table row generators. empty ourselves to prevent this
# process from being repeated
#
row_generators = []
while self:
ligolw_segment_list = self.pop()
segment_def_row = self.segment_def_table.RowType()
segment_def_row.process_id = process_id
segment_def_row.segment_def_id = self.segment_def_table.get_next_id()
segment_def_row.instruments = ligolw_segment_list.instruments
segment_def_row.name = ligolw_segment_list.name
segment_def_row.version = ligolw_segment_list.version
segment_def_row.comment = ligolw_segment_list.comment
self.segment_def_table.append(segment_def_row)
row_generators.append(row_generator(ligolw_segment_list.valid, self.segment_sum_table, process_id, segment_def_row.segment_def_id))
row_generators.append(row_generator(ligolw_segment_list.active, self.segment_table, process_id, segment_def_row.segment_def_id))
#
# populate segment and segment_summary tables by pulling
# rows from the generators in time order
#
for row, target_table in iterutils.inorder(*row_generators):
target_table.append(row) | [
"def",
"finalize",
"(",
"self",
",",
"process_row",
"=",
"None",
")",
":",
"if",
"process_row",
"is",
"not",
"None",
":",
"process_id",
"=",
"process_row",
".",
"process_id",
"elif",
"self",
".",
"process",
"is",
"not",
"None",
":",
"process_id",
"=",
"s... | Restore the LigolwSegmentList objects to the XML tables in
preparation for output. All segments from all segment
lists are inserted into the tables in time order, but this
is NOT behaviour external applications should rely on.
This is done simply in the belief that it might assist in
constructing well balanced indexed databases from the
resulting files. If that proves not to be the case, or for
some reason this behaviour proves inconvenient to preserve,
then it might be discontinued without notice. You've been
warned. | [
"Restore",
"the",
"LigolwSegmentList",
"objects",
"to",
"the",
"XML",
"tables",
"in",
"preparation",
"for",
"output",
".",
"All",
"segments",
"from",
"all",
"segment",
"lists",
"are",
"inserted",
"into",
"the",
"tables",
"in",
"time",
"order",
"but",
"this",
... | train | https://github.com/gwastro/pycbc-glue/blob/a3e906bae59fbfd707c3ff82e5d008d939ec5e24/pycbc_glue/ligolw/utils/segments.py#L401-L481 |
fractalego/parvusdb | parvusdb/utils/graph_builder.py | GraphBuilder.add_graph | def add_graph(self, rhs_graph):
"""
Adds a graph to self.g
:param rhs_graph: the graph to add
:return: itself
"""
rhs_graph = self.__substitute_names_in_graph(rhs_graph)
self.g = self.__merge_graphs(self.g, rhs_graph)
return self | python | def add_graph(self, rhs_graph):
"""
Adds a graph to self.g
:param rhs_graph: the graph to add
:return: itself
"""
rhs_graph = self.__substitute_names_in_graph(rhs_graph)
self.g = self.__merge_graphs(self.g, rhs_graph)
return self | [
"def",
"add_graph",
"(",
"self",
",",
"rhs_graph",
")",
":",
"rhs_graph",
"=",
"self",
".",
"__substitute_names_in_graph",
"(",
"rhs_graph",
")",
"self",
".",
"g",
"=",
"self",
".",
"__merge_graphs",
"(",
"self",
".",
"g",
",",
"rhs_graph",
")",
"return",
... | Adds a graph to self.g
:param rhs_graph: the graph to add
:return: itself | [
"Adds",
"a",
"graph",
"to",
"self",
".",
"g"
] | train | https://github.com/fractalego/parvusdb/blob/d5e818d3f3c3decfd4835ef2133aa956b6d87b1d/parvusdb/utils/graph_builder.py#L21-L30 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.