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 |
|---|---|---|---|---|---|---|---|---|---|---|
onjin/liquimigrate | liquimigrate/management/commands/liquibase.py | Command.handle | def handle(self, *args, **options):
"""
Handle liquibase command parameters
"""
database = getattr(
settings, 'LIQUIMIGRATE_DATABASE', options['database'])
try:
dbsettings = databases[database]
except KeyError:
raise CommandError("don't know such a connection: %s" % database)
verbosity = int(options.get('verbosity'))
# get driver
driver_class = (
options.get('driver')
or dbsettings.get('ENGINE').split('.')[-1])
dbtag, driver, classpath = LIQUIBASE_DRIVERS.get(
driver_class, (None, None, None))
classpath = options.get('classpath') or classpath
if driver is None:
raise CommandError(
"unsupported db driver '%s'\n"
"available drivers: %s" % (
driver_class, ' '.join(LIQUIBASE_DRIVERS.keys())))
# command options
changelog_file = (
options.get('changelog_file')
or _get_changelog_file(options['database']))
username = options.get('username') or dbsettings.get('USER') or ''
password = options.get('password') or dbsettings.get('PASSWORD') or ''
url = options.get('url') or _get_url_for_db(dbtag, dbsettings)
command = options['command']
cmdargs = {
'jar': LIQUIBASE_JAR,
'changelog_file': changelog_file,
'username': username,
'password': password,
'command': command,
'driver': driver,
'classpath': classpath,
'url': url,
'args': ' '.join(args),
}
cmdline = "java -jar %(jar)s --changeLogFile %(changelog_file)s \
--username=%(username)s --password=%(password)s \
--driver=%(driver)s --classpath=%(classpath)s --url=%(url)s \
%(command)s %(args)s" % (cmdargs)
if verbosity > 0:
print("changelog file: %s" % (changelog_file,))
print("executing: %s" % (cmdline,))
created_models = None # we dont know it
if emit_pre_migrate_signal and not options.get('no_signals'):
if django_19_or_newer:
emit_pre_migrate_signal(
1, options.get('interactive'), database)
else:
emit_pre_migrate_signal(
created_models, 1, options.get('interactive'), database)
rc = os.system(cmdline)
if rc == 0:
try:
if not options.get('no_signals'):
if emit_post_migrate_signal:
if django_19_or_newer:
emit_post_migrate_signal(
0, options.get('interactive'), database)
else:
emit_post_migrate_signal(
created_models, 0,
options.get('interactive'), database)
elif emit_post_sync_signal:
emit_post_sync_signal(
created_models, 0,
options.get('interactive'), database)
if not django_19_or_newer:
call_command(
'loaddata', 'initial_data', verbosity=1,
database=database)
except TypeError:
# singledb (1.1 and older)
emit_post_sync_signal(
created_models, 0, options.get('interactive'))
call_command(
'loaddata', 'initial_data', verbosity=0)
else:
raise CommandError('Liquibase returned an error code %s' % rc) | python | def handle(self, *args, **options):
"""
Handle liquibase command parameters
"""
database = getattr(
settings, 'LIQUIMIGRATE_DATABASE', options['database'])
try:
dbsettings = databases[database]
except KeyError:
raise CommandError("don't know such a connection: %s" % database)
verbosity = int(options.get('verbosity'))
# get driver
driver_class = (
options.get('driver')
or dbsettings.get('ENGINE').split('.')[-1])
dbtag, driver, classpath = LIQUIBASE_DRIVERS.get(
driver_class, (None, None, None))
classpath = options.get('classpath') or classpath
if driver is None:
raise CommandError(
"unsupported db driver '%s'\n"
"available drivers: %s" % (
driver_class, ' '.join(LIQUIBASE_DRIVERS.keys())))
# command options
changelog_file = (
options.get('changelog_file')
or _get_changelog_file(options['database']))
username = options.get('username') or dbsettings.get('USER') or ''
password = options.get('password') or dbsettings.get('PASSWORD') or ''
url = options.get('url') or _get_url_for_db(dbtag, dbsettings)
command = options['command']
cmdargs = {
'jar': LIQUIBASE_JAR,
'changelog_file': changelog_file,
'username': username,
'password': password,
'command': command,
'driver': driver,
'classpath': classpath,
'url': url,
'args': ' '.join(args),
}
cmdline = "java -jar %(jar)s --changeLogFile %(changelog_file)s \
--username=%(username)s --password=%(password)s \
--driver=%(driver)s --classpath=%(classpath)s --url=%(url)s \
%(command)s %(args)s" % (cmdargs)
if verbosity > 0:
print("changelog file: %s" % (changelog_file,))
print("executing: %s" % (cmdline,))
created_models = None # we dont know it
if emit_pre_migrate_signal and not options.get('no_signals'):
if django_19_or_newer:
emit_pre_migrate_signal(
1, options.get('interactive'), database)
else:
emit_pre_migrate_signal(
created_models, 1, options.get('interactive'), database)
rc = os.system(cmdline)
if rc == 0:
try:
if not options.get('no_signals'):
if emit_post_migrate_signal:
if django_19_or_newer:
emit_post_migrate_signal(
0, options.get('interactive'), database)
else:
emit_post_migrate_signal(
created_models, 0,
options.get('interactive'), database)
elif emit_post_sync_signal:
emit_post_sync_signal(
created_models, 0,
options.get('interactive'), database)
if not django_19_or_newer:
call_command(
'loaddata', 'initial_data', verbosity=1,
database=database)
except TypeError:
# singledb (1.1 and older)
emit_post_sync_signal(
created_models, 0, options.get('interactive'))
call_command(
'loaddata', 'initial_data', verbosity=0)
else:
raise CommandError('Liquibase returned an error code %s' % rc) | [
"def",
"handle",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"options",
")",
":",
"database",
"=",
"getattr",
"(",
"settings",
",",
"'LIQUIMIGRATE_DATABASE'",
",",
"options",
"[",
"'database'",
"]",
")",
"try",
":",
"dbsettings",
"=",
"databases",
"[",... | Handle liquibase command parameters | [
"Handle",
"liquibase",
"command",
"parameters"
] | train | https://github.com/onjin/liquimigrate/blob/c159a92198a849176fb53fc2db0736049f12031f/liquimigrate/management/commands/liquibase.py#L90-L190 |
nickstenning/tagalog | tagalog/io.py | messages | def messages(fp, key='@message'):
"""
Read lines of UTF-8 from the file-like object given in ``fp``, with the
same fault-tolerance as :function:`tagalog.io.lines`, but instead yield
dicts with the line data stored in the key given by ``key`` (default:
"@message").
"""
for line in lines(fp):
txt = line.rstrip('\n')
yield {key: txt} | python | def messages(fp, key='@message'):
"""
Read lines of UTF-8 from the file-like object given in ``fp``, with the
same fault-tolerance as :function:`tagalog.io.lines`, but instead yield
dicts with the line data stored in the key given by ``key`` (default:
"@message").
"""
for line in lines(fp):
txt = line.rstrip('\n')
yield {key: txt} | [
"def",
"messages",
"(",
"fp",
",",
"key",
"=",
"'@message'",
")",
":",
"for",
"line",
"in",
"lines",
"(",
"fp",
")",
":",
"txt",
"=",
"line",
".",
"rstrip",
"(",
"'\\n'",
")",
"yield",
"{",
"key",
":",
"txt",
"}"
] | Read lines of UTF-8 from the file-like object given in ``fp``, with the
same fault-tolerance as :function:`tagalog.io.lines`, but instead yield
dicts with the line data stored in the key given by ``key`` (default:
"@message"). | [
"Read",
"lines",
"of",
"UTF",
"-",
"8",
"from",
"the",
"file",
"-",
"like",
"object",
"given",
"in",
"fp",
"with",
"the",
"same",
"fault",
"-",
"tolerance",
"as",
":",
"function",
":",
"tagalog",
".",
"io",
".",
"lines",
"but",
"instead",
"yield",
"d... | train | https://github.com/nickstenning/tagalog/blob/c6847a957dc4f96836a5cf13c4eb664fccafaac2/tagalog/io.py#L12-L21 |
nickstenning/tagalog | tagalog/io.py | lines | def lines(fp):
"""
Read lines of UTF-8 from the file-like object given in ``fp``, making sure
that when reading from STDIN, reads are at most line-buffered.
UTF-8 decoding errors are handled silently. Invalid characters are
replaced by U+FFFD REPLACEMENT CHARACTER.
Line endings are normalised to newlines by Python's universal newlines
feature.
Returns an iterator yielding lines.
"""
if fp.fileno() == sys.stdin.fileno():
close = True
try: # Python 3
fp = open(fp.fileno(), mode='r', buffering=BUF_LINEBUFFERED, errors='replace')
decode = False
except TypeError:
fp = os.fdopen(fp.fileno(), 'rU', BUF_LINEBUFFERED)
decode = True
else:
close = False
try:
# only decode if the fp doesn't already have an encoding
decode = (fp.encoding != UTF8)
except AttributeError:
# fp has been opened in binary mode
decode = True
try:
while 1:
l = fp.readline()
if l:
if decode:
l = l.decode(UTF8, 'replace')
yield l
else:
break
finally:
if close:
fp.close() | python | def lines(fp):
"""
Read lines of UTF-8 from the file-like object given in ``fp``, making sure
that when reading from STDIN, reads are at most line-buffered.
UTF-8 decoding errors are handled silently. Invalid characters are
replaced by U+FFFD REPLACEMENT CHARACTER.
Line endings are normalised to newlines by Python's universal newlines
feature.
Returns an iterator yielding lines.
"""
if fp.fileno() == sys.stdin.fileno():
close = True
try: # Python 3
fp = open(fp.fileno(), mode='r', buffering=BUF_LINEBUFFERED, errors='replace')
decode = False
except TypeError:
fp = os.fdopen(fp.fileno(), 'rU', BUF_LINEBUFFERED)
decode = True
else:
close = False
try:
# only decode if the fp doesn't already have an encoding
decode = (fp.encoding != UTF8)
except AttributeError:
# fp has been opened in binary mode
decode = True
try:
while 1:
l = fp.readline()
if l:
if decode:
l = l.decode(UTF8, 'replace')
yield l
else:
break
finally:
if close:
fp.close() | [
"def",
"lines",
"(",
"fp",
")",
":",
"if",
"fp",
".",
"fileno",
"(",
")",
"==",
"sys",
".",
"stdin",
".",
"fileno",
"(",
")",
":",
"close",
"=",
"True",
"try",
":",
"# Python 3",
"fp",
"=",
"open",
"(",
"fp",
".",
"fileno",
"(",
")",
",",
"mo... | Read lines of UTF-8 from the file-like object given in ``fp``, making sure
that when reading from STDIN, reads are at most line-buffered.
UTF-8 decoding errors are handled silently. Invalid characters are
replaced by U+FFFD REPLACEMENT CHARACTER.
Line endings are normalised to newlines by Python's universal newlines
feature.
Returns an iterator yielding lines. | [
"Read",
"lines",
"of",
"UTF",
"-",
"8",
"from",
"the",
"file",
"-",
"like",
"object",
"given",
"in",
"fp",
"making",
"sure",
"that",
"when",
"reading",
"from",
"STDIN",
"reads",
"are",
"at",
"most",
"line",
"-",
"buffered",
"."
] | train | https://github.com/nickstenning/tagalog/blob/c6847a957dc4f96836a5cf13c4eb664fccafaac2/tagalog/io.py#L24-L68 |
blaklites/fb | fb/graph.py | api.publish | def publish(self, cat, **kwargs):
"""
This method is used for creating objects in the facebook graph.
The first paramter is "cat", the category of publish. In addition to "cat"
"id" must also be passed and is catched by "kwargs"
"""
res=request.publish_cat1("POST", self.con, self.token, cat, kwargs)
return res | python | def publish(self, cat, **kwargs):
"""
This method is used for creating objects in the facebook graph.
The first paramter is "cat", the category of publish. In addition to "cat"
"id" must also be passed and is catched by "kwargs"
"""
res=request.publish_cat1("POST", self.con, self.token, cat, kwargs)
return res | [
"def",
"publish",
"(",
"self",
",",
"cat",
",",
"*",
"*",
"kwargs",
")",
":",
"res",
"=",
"request",
".",
"publish_cat1",
"(",
"\"POST\"",
",",
"self",
".",
"con",
",",
"self",
".",
"token",
",",
"cat",
",",
"kwargs",
")",
"return",
"res"
] | This method is used for creating objects in the facebook graph.
The first paramter is "cat", the category of publish. In addition to "cat"
"id" must also be passed and is catched by "kwargs" | [
"This",
"method",
"is",
"used",
"for",
"creating",
"objects",
"in",
"the",
"facebook",
"graph",
".",
"The",
"first",
"paramter",
"is",
"cat",
"the",
"category",
"of",
"publish",
".",
"In",
"addition",
"to",
"cat",
"id",
"must",
"also",
"be",
"passed",
"a... | train | https://github.com/blaklites/fb/blob/4ddba4dae204463ed24f473872215c5a26370a81/fb/graph.py#L15-L22 |
blaklites/fb | fb/graph.py | api.get_object | def get_object(self, cat, **kwargs):
"""
This method is used for retrieving objects from facebook. "cat", the category, must be
passed. When cat is "single", pass the "id "and desired "fields" of the single object. If the
cat is "multiple", only pass the "ids" of the objects to be fetched.
"""
if 'id' not in kwargs.keys():
kwargs['id']=''
res=request.get_object_cat1(self.con, self.token, cat, kwargs)
return res | python | def get_object(self, cat, **kwargs):
"""
This method is used for retrieving objects from facebook. "cat", the category, must be
passed. When cat is "single", pass the "id "and desired "fields" of the single object. If the
cat is "multiple", only pass the "ids" of the objects to be fetched.
"""
if 'id' not in kwargs.keys():
kwargs['id']=''
res=request.get_object_cat1(self.con, self.token, cat, kwargs)
return res | [
"def",
"get_object",
"(",
"self",
",",
"cat",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"'id'",
"not",
"in",
"kwargs",
".",
"keys",
"(",
")",
":",
"kwargs",
"[",
"'id'",
"]",
"=",
"''",
"res",
"=",
"request",
".",
"get_object_cat1",
"(",
"self",
"... | This method is used for retrieving objects from facebook. "cat", the category, must be
passed. When cat is "single", pass the "id "and desired "fields" of the single object. If the
cat is "multiple", only pass the "ids" of the objects to be fetched. | [
"This",
"method",
"is",
"used",
"for",
"retrieving",
"objects",
"from",
"facebook",
".",
"cat",
"the",
"category",
"must",
"be",
"passed",
".",
"When",
"cat",
"is",
"single",
"pass",
"the",
"id",
"and",
"desired",
"fields",
"of",
"the",
"single",
"object",... | train | https://github.com/blaklites/fb/blob/4ddba4dae204463ed24f473872215c5a26370a81/fb/graph.py#L25-L34 |
blaklites/fb | fb/graph.py | api.delete | def delete(self, **kwargs):
"""
Used for deleting objects from the facebook graph. Just pass the id of the object to be
deleted. But in case of like, have to pass the cat ("likes") and object id as a like has no id
itself in the facebook graph
"""
if 'cat' not in kwargs.keys():
kwargs['cat']=''
cat=kwargs['cat']
del kwargs['cat']
res=request.publish_cat1("DELETE", self.con, self.token, cat, kwargs)
return res | python | def delete(self, **kwargs):
"""
Used for deleting objects from the facebook graph. Just pass the id of the object to be
deleted. But in case of like, have to pass the cat ("likes") and object id as a like has no id
itself in the facebook graph
"""
if 'cat' not in kwargs.keys():
kwargs['cat']=''
cat=kwargs['cat']
del kwargs['cat']
res=request.publish_cat1("DELETE", self.con, self.token, cat, kwargs)
return res | [
"def",
"delete",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"'cat'",
"not",
"in",
"kwargs",
".",
"keys",
"(",
")",
":",
"kwargs",
"[",
"'cat'",
"]",
"=",
"''",
"cat",
"=",
"kwargs",
"[",
"'cat'",
"]",
"del",
"kwargs",
"[",
"'cat'",
"... | Used for deleting objects from the facebook graph. Just pass the id of the object to be
deleted. But in case of like, have to pass the cat ("likes") and object id as a like has no id
itself in the facebook graph | [
"Used",
"for",
"deleting",
"objects",
"from",
"the",
"facebook",
"graph",
".",
"Just",
"pass",
"the",
"id",
"of",
"the",
"object",
"to",
"be",
"deleted",
".",
"But",
"in",
"case",
"of",
"like",
"have",
"to",
"pass",
"the",
"cat",
"(",
"likes",
")",
"... | train | https://github.com/blaklites/fb/blob/4ddba4dae204463ed24f473872215c5a26370a81/fb/graph.py#L37-L48 |
gwastro/pycbc-glue | pycbc_glue/ligolw/table.py | getColumnsByName | def getColumnsByName(elem, name):
"""
Return a list of Column elements named name under elem. The name
comparison is done with CompareColumnNames().
"""
name = StripColumnName(name)
return elem.getElements(lambda e: (e.tagName == ligolw.Column.tagName) and (e.Name == name)) | python | def getColumnsByName(elem, name):
"""
Return a list of Column elements named name under elem. The name
comparison is done with CompareColumnNames().
"""
name = StripColumnName(name)
return elem.getElements(lambda e: (e.tagName == ligolw.Column.tagName) and (e.Name == name)) | [
"def",
"getColumnsByName",
"(",
"elem",
",",
"name",
")",
":",
"name",
"=",
"StripColumnName",
"(",
"name",
")",
"return",
"elem",
".",
"getElements",
"(",
"lambda",
"e",
":",
"(",
"e",
".",
"tagName",
"==",
"ligolw",
".",
"Column",
".",
"tagName",
")"... | Return a list of Column elements named name under elem. The name
comparison is done with CompareColumnNames(). | [
"Return",
"a",
"list",
"of",
"Column",
"elements",
"named",
"name",
"under",
"elem",
".",
"The",
"name",
"comparison",
"is",
"done",
"with",
"CompareColumnNames",
"()",
"."
] | train | https://github.com/gwastro/pycbc-glue/blob/a3e906bae59fbfd707c3ff82e5d008d939ec5e24/pycbc_glue/ligolw/table.py#L143-L149 |
gwastro/pycbc-glue | pycbc_glue/ligolw/table.py | StripTableName | def StripTableName(name):
"""
Return the significant portion of a table name according to LIGO LW
naming conventions.
Example:
>>> StripTableName("sngl_burst_group:sngl_burst:table")
'sngl_burst'
>>> StripTableName("sngl_burst:table")
'sngl_burst'
>>> StripTableName("sngl_burst")
'sngl_burst'
"""
if name.lower() != name:
warnings.warn("table name \"%s\" is not lower case" % name)
try:
return TablePattern.search(name).group("Name")
except AttributeError:
return name | python | def StripTableName(name):
"""
Return the significant portion of a table name according to LIGO LW
naming conventions.
Example:
>>> StripTableName("sngl_burst_group:sngl_burst:table")
'sngl_burst'
>>> StripTableName("sngl_burst:table")
'sngl_burst'
>>> StripTableName("sngl_burst")
'sngl_burst'
"""
if name.lower() != name:
warnings.warn("table name \"%s\" is not lower case" % name)
try:
return TablePattern.search(name).group("Name")
except AttributeError:
return name | [
"def",
"StripTableName",
"(",
"name",
")",
":",
"if",
"name",
".",
"lower",
"(",
")",
"!=",
"name",
":",
"warnings",
".",
"warn",
"(",
"\"table name \\\"%s\\\" is not lower case\"",
"%",
"name",
")",
"try",
":",
"return",
"TablePattern",
".",
"search",
"(",
... | Return the significant portion of a table name according to LIGO LW
naming conventions.
Example:
>>> StripTableName("sngl_burst_group:sngl_burst:table")
'sngl_burst'
>>> StripTableName("sngl_burst:table")
'sngl_burst'
>>> StripTableName("sngl_burst")
'sngl_burst' | [
"Return",
"the",
"significant",
"portion",
"of",
"a",
"table",
"name",
"according",
"to",
"LIGO",
"LW",
"naming",
"conventions",
"."
] | train | https://github.com/gwastro/pycbc-glue/blob/a3e906bae59fbfd707c3ff82e5d008d939ec5e24/pycbc_glue/ligolw/table.py#L168-L187 |
gwastro/pycbc-glue | pycbc_glue/ligolw/table.py | getTablesByName | def getTablesByName(elem, name):
"""
Return a list of Table elements named name under elem. The name
comparison is done using CompareTableNames().
"""
name = StripTableName(name)
return elem.getElements(lambda e: (e.tagName == ligolw.Table.tagName) and (e.Name == name)) | python | def getTablesByName(elem, name):
"""
Return a list of Table elements named name under elem. The name
comparison is done using CompareTableNames().
"""
name = StripTableName(name)
return elem.getElements(lambda e: (e.tagName == ligolw.Table.tagName) and (e.Name == name)) | [
"def",
"getTablesByName",
"(",
"elem",
",",
"name",
")",
":",
"name",
"=",
"StripTableName",
"(",
"name",
")",
"return",
"elem",
".",
"getElements",
"(",
"lambda",
"e",
":",
"(",
"e",
".",
"tagName",
"==",
"ligolw",
".",
"Table",
".",
"tagName",
")",
... | Return a list of Table elements named name under elem. The name
comparison is done using CompareTableNames(). | [
"Return",
"a",
"list",
"of",
"Table",
"elements",
"named",
"name",
"under",
"elem",
".",
"The",
"name",
"comparison",
"is",
"done",
"using",
"CompareTableNames",
"()",
"."
] | train | https://github.com/gwastro/pycbc-glue/blob/a3e906bae59fbfd707c3ff82e5d008d939ec5e24/pycbc_glue/ligolw/table.py#L208-L214 |
gwastro/pycbc-glue | pycbc_glue/ligolw/table.py | get_table | def get_table(xmldoc, name):
"""
Scan xmldoc for a Table element named name. The comparison is done
using CompareTableNames(). Raises ValueError if not exactly 1 such
table is found.
NOTE: if a Table sub-class has its .tableName attribute set, then
its .get_table() class method can be used instead. This is true
for all Table classes in the pycbc_glue.ligolw.lsctables module, and it
is recommended to always use the .get_table() class method of those
classes to retrieve those standard tables instead of calling this
function and passing the .tableName attribute. The example below
shows both techniques.
Example:
>>> import ligolw
>>> import lsctables
>>> xmldoc = ligolw.Document()
>>> xmldoc.appendChild(ligolw.LIGO_LW()).appendChild(lsctables.New(lsctables.SnglInspiralTable))
[]
>>> # find table with this function
>>> sngl_inspiral_table = get_table(xmldoc, lsctables.SnglInspiralTable.tableName)
>>> # find table with .get_table() class method (preferred)
>>> sngl_inspiral_table = lsctables.SnglInspiralTable.get_table(xmldoc)
See also the .get_table() class method of the Table class.
"""
tables = getTablesByName(xmldoc, name)
if len(tables) != 1:
raise ValueError("document must contain exactly one %s table" % StripTableName(name))
return tables[0] | python | def get_table(xmldoc, name):
"""
Scan xmldoc for a Table element named name. The comparison is done
using CompareTableNames(). Raises ValueError if not exactly 1 such
table is found.
NOTE: if a Table sub-class has its .tableName attribute set, then
its .get_table() class method can be used instead. This is true
for all Table classes in the pycbc_glue.ligolw.lsctables module, and it
is recommended to always use the .get_table() class method of those
classes to retrieve those standard tables instead of calling this
function and passing the .tableName attribute. The example below
shows both techniques.
Example:
>>> import ligolw
>>> import lsctables
>>> xmldoc = ligolw.Document()
>>> xmldoc.appendChild(ligolw.LIGO_LW()).appendChild(lsctables.New(lsctables.SnglInspiralTable))
[]
>>> # find table with this function
>>> sngl_inspiral_table = get_table(xmldoc, lsctables.SnglInspiralTable.tableName)
>>> # find table with .get_table() class method (preferred)
>>> sngl_inspiral_table = lsctables.SnglInspiralTable.get_table(xmldoc)
See also the .get_table() class method of the Table class.
"""
tables = getTablesByName(xmldoc, name)
if len(tables) != 1:
raise ValueError("document must contain exactly one %s table" % StripTableName(name))
return tables[0] | [
"def",
"get_table",
"(",
"xmldoc",
",",
"name",
")",
":",
"tables",
"=",
"getTablesByName",
"(",
"xmldoc",
",",
"name",
")",
"if",
"len",
"(",
"tables",
")",
"!=",
"1",
":",
"raise",
"ValueError",
"(",
"\"document must contain exactly one %s table\"",
"%",
"... | Scan xmldoc for a Table element named name. The comparison is done
using CompareTableNames(). Raises ValueError if not exactly 1 such
table is found.
NOTE: if a Table sub-class has its .tableName attribute set, then
its .get_table() class method can be used instead. This is true
for all Table classes in the pycbc_glue.ligolw.lsctables module, and it
is recommended to always use the .get_table() class method of those
classes to retrieve those standard tables instead of calling this
function and passing the .tableName attribute. The example below
shows both techniques.
Example:
>>> import ligolw
>>> import lsctables
>>> xmldoc = ligolw.Document()
>>> xmldoc.appendChild(ligolw.LIGO_LW()).appendChild(lsctables.New(lsctables.SnglInspiralTable))
[]
>>> # find table with this function
>>> sngl_inspiral_table = get_table(xmldoc, lsctables.SnglInspiralTable.tableName)
>>> # find table with .get_table() class method (preferred)
>>> sngl_inspiral_table = lsctables.SnglInspiralTable.get_table(xmldoc)
See also the .get_table() class method of the Table class. | [
"Scan",
"xmldoc",
"for",
"a",
"Table",
"element",
"named",
"name",
".",
"The",
"comparison",
"is",
"done",
"using",
"CompareTableNames",
"()",
".",
"Raises",
"ValueError",
"if",
"not",
"exactly",
"1",
"such",
"table",
"is",
"found",
"."
] | train | https://github.com/gwastro/pycbc-glue/blob/a3e906bae59fbfd707c3ff82e5d008d939ec5e24/pycbc_glue/ligolw/table.py#L235-L266 |
gwastro/pycbc-glue | pycbc_glue/ligolw/table.py | reassign_ids | def reassign_ids(elem):
"""
Recurses over all Table elements below elem whose next_id
attributes are not None, and uses the .get_next_id() method of each
of those Tables to generate and assign new IDs to their rows. The
modifications are recorded, and finally all ID attributes in all
rows of all tables are updated to fix cross references to the
modified IDs.
This function is used by ligolw_add to assign new IDs to rows when
merging documents in order to make sure there are no ID collisions.
Using this function in this way requires the .get_next_id() methods
of all Table elements to yield unused IDs, otherwise collisions
will result anyway. See the .sync_next_id() method of the Table
class for a way to initialize the .next_id attributes so that
collisions will not occur.
Example:
>>> import ligolw
>>> import lsctables
>>> xmldoc = ligolw.Document()
>>> xmldoc.appendChild(ligolw.LIGO_LW()).appendChild(lsctables.New(lsctables.SnglInspiralTable))
[]
>>> reassign_ids(xmldoc)
"""
mapping = {}
for tbl in elem.getElementsByTagName(ligolw.Table.tagName):
if tbl.next_id is not None:
tbl.updateKeyMapping(mapping)
for tbl in elem.getElementsByTagName(ligolw.Table.tagName):
tbl.applyKeyMapping(mapping) | python | def reassign_ids(elem):
"""
Recurses over all Table elements below elem whose next_id
attributes are not None, and uses the .get_next_id() method of each
of those Tables to generate and assign new IDs to their rows. The
modifications are recorded, and finally all ID attributes in all
rows of all tables are updated to fix cross references to the
modified IDs.
This function is used by ligolw_add to assign new IDs to rows when
merging documents in order to make sure there are no ID collisions.
Using this function in this way requires the .get_next_id() methods
of all Table elements to yield unused IDs, otherwise collisions
will result anyway. See the .sync_next_id() method of the Table
class for a way to initialize the .next_id attributes so that
collisions will not occur.
Example:
>>> import ligolw
>>> import lsctables
>>> xmldoc = ligolw.Document()
>>> xmldoc.appendChild(ligolw.LIGO_LW()).appendChild(lsctables.New(lsctables.SnglInspiralTable))
[]
>>> reassign_ids(xmldoc)
"""
mapping = {}
for tbl in elem.getElementsByTagName(ligolw.Table.tagName):
if tbl.next_id is not None:
tbl.updateKeyMapping(mapping)
for tbl in elem.getElementsByTagName(ligolw.Table.tagName):
tbl.applyKeyMapping(mapping) | [
"def",
"reassign_ids",
"(",
"elem",
")",
":",
"mapping",
"=",
"{",
"}",
"for",
"tbl",
"in",
"elem",
".",
"getElementsByTagName",
"(",
"ligolw",
".",
"Table",
".",
"tagName",
")",
":",
"if",
"tbl",
".",
"next_id",
"is",
"not",
"None",
":",
"tbl",
".",... | Recurses over all Table elements below elem whose next_id
attributes are not None, and uses the .get_next_id() method of each
of those Tables to generate and assign new IDs to their rows. The
modifications are recorded, and finally all ID attributes in all
rows of all tables are updated to fix cross references to the
modified IDs.
This function is used by ligolw_add to assign new IDs to rows when
merging documents in order to make sure there are no ID collisions.
Using this function in this way requires the .get_next_id() methods
of all Table elements to yield unused IDs, otherwise collisions
will result anyway. See the .sync_next_id() method of the Table
class for a way to initialize the .next_id attributes so that
collisions will not occur.
Example:
>>> import ligolw
>>> import lsctables
>>> xmldoc = ligolw.Document()
>>> xmldoc.appendChild(ligolw.LIGO_LW()).appendChild(lsctables.New(lsctables.SnglInspiralTable))
[]
>>> reassign_ids(xmldoc) | [
"Recurses",
"over",
"all",
"Table",
"elements",
"below",
"elem",
"whose",
"next_id",
"attributes",
"are",
"not",
"None",
"and",
"uses",
"the",
".",
"get_next_id",
"()",
"method",
"of",
"each",
"of",
"those",
"Tables",
"to",
"generate",
"and",
"assign",
"new"... | train | https://github.com/gwastro/pycbc-glue/blob/a3e906bae59fbfd707c3ff82e5d008d939ec5e24/pycbc_glue/ligolw/table.py#L269-L300 |
gwastro/pycbc-glue | pycbc_glue/ligolw/table.py | reset_next_ids | def reset_next_ids(classes):
"""
For each class in the list, if the .next_id attribute is not None
(meaning the table has an ID generator associated with it), set
.next_id to 0. This has the effect of reseting the ID generators,
and is useful in applications that process multiple documents and
add new rows to tables in those documents. Calling this function
between documents prevents new row IDs from growing continuously
from document to document. There is no need to do this, it's
purpose is merely aesthetic, but it can be confusing to open a
document and find process ID 300 in the process table and wonder
what happened to the other 299 processes.
Example:
>>> import lsctables
>>> reset_next_ids(lsctables.TableByName.values())
"""
for cls in classes:
if cls.next_id is not None:
cls.set_next_id(type(cls.next_id)(0)) | python | def reset_next_ids(classes):
"""
For each class in the list, if the .next_id attribute is not None
(meaning the table has an ID generator associated with it), set
.next_id to 0. This has the effect of reseting the ID generators,
and is useful in applications that process multiple documents and
add new rows to tables in those documents. Calling this function
between documents prevents new row IDs from growing continuously
from document to document. There is no need to do this, it's
purpose is merely aesthetic, but it can be confusing to open a
document and find process ID 300 in the process table and wonder
what happened to the other 299 processes.
Example:
>>> import lsctables
>>> reset_next_ids(lsctables.TableByName.values())
"""
for cls in classes:
if cls.next_id is not None:
cls.set_next_id(type(cls.next_id)(0)) | [
"def",
"reset_next_ids",
"(",
"classes",
")",
":",
"for",
"cls",
"in",
"classes",
":",
"if",
"cls",
".",
"next_id",
"is",
"not",
"None",
":",
"cls",
".",
"set_next_id",
"(",
"type",
"(",
"cls",
".",
"next_id",
")",
"(",
"0",
")",
")"
] | For each class in the list, if the .next_id attribute is not None
(meaning the table has an ID generator associated with it), set
.next_id to 0. This has the effect of reseting the ID generators,
and is useful in applications that process multiple documents and
add new rows to tables in those documents. Calling this function
between documents prevents new row IDs from growing continuously
from document to document. There is no need to do this, it's
purpose is merely aesthetic, but it can be confusing to open a
document and find process ID 300 in the process table and wonder
what happened to the other 299 processes.
Example:
>>> import lsctables
>>> reset_next_ids(lsctables.TableByName.values()) | [
"For",
"each",
"class",
"in",
"the",
"list",
"if",
"the",
".",
"next_id",
"attribute",
"is",
"not",
"None",
"(",
"meaning",
"the",
"table",
"has",
"an",
"ID",
"generator",
"associated",
"with",
"it",
")",
"set",
".",
"next_id",
"to",
"0",
".",
"This",
... | train | https://github.com/gwastro/pycbc-glue/blob/a3e906bae59fbfd707c3ff82e5d008d939ec5e24/pycbc_glue/ligolw/table.py#L303-L323 |
gwastro/pycbc-glue | pycbc_glue/ligolw/table.py | use_in | def use_in(ContentHandler):
"""
Modify ContentHandler, a sub-class of
pycbc_glue.ligolw.LIGOLWContentHandler, to cause it to use the Table,
Column, and Stream classes defined in this module when parsing XML
documents.
Example:
>>> from pycbc_glue.ligolw import ligolw
>>> class LIGOLWContentHandler(ligolw.LIGOLWContentHandler):
... pass
...
>>> use_in(LIGOLWContentHandler)
<class 'pycbc_glue.ligolw.table.LIGOLWContentHandler'>
"""
def startColumn(self, parent, attrs):
return Column(attrs)
def startStream(self, parent, attrs, __orig_startStream = ContentHandler.startStream):
if parent.tagName == ligolw.Table.tagName:
parent._end_of_columns()
return TableStream(attrs).config(parent)
return __orig_startStream(self, parent, attrs)
def startTable(self, parent, attrs):
return Table(attrs)
ContentHandler.startColumn = startColumn
ContentHandler.startStream = startStream
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,
Column, and Stream classes defined in this module when parsing XML
documents.
Example:
>>> from pycbc_glue.ligolw import ligolw
>>> class LIGOLWContentHandler(ligolw.LIGOLWContentHandler):
... pass
...
>>> use_in(LIGOLWContentHandler)
<class 'pycbc_glue.ligolw.table.LIGOLWContentHandler'>
"""
def startColumn(self, parent, attrs):
return Column(attrs)
def startStream(self, parent, attrs, __orig_startStream = ContentHandler.startStream):
if parent.tagName == ligolw.Table.tagName:
parent._end_of_columns()
return TableStream(attrs).config(parent)
return __orig_startStream(self, parent, attrs)
def startTable(self, parent, attrs):
return Table(attrs)
ContentHandler.startColumn = startColumn
ContentHandler.startStream = startStream
ContentHandler.startTable = startTable
return ContentHandler | [
"def",
"use_in",
"(",
"ContentHandler",
")",
":",
"def",
"startColumn",
"(",
"self",
",",
"parent",
",",
"attrs",
")",
":",
"return",
"Column",
"(",
"attrs",
")",
"def",
"startStream",
"(",
"self",
",",
"parent",
",",
"attrs",
",",
"__orig_startStream",
... | Modify ContentHandler, a sub-class of
pycbc_glue.ligolw.LIGOLWContentHandler, to cause it to use the Table,
Column, and Stream classes defined in this module when parsing XML
documents.
Example:
>>> from pycbc_glue.ligolw import ligolw
>>> class LIGOLWContentHandler(ligolw.LIGOLWContentHandler):
... pass
...
>>> use_in(LIGOLWContentHandler)
<class 'pycbc_glue.ligolw.table.LIGOLWContentHandler'> | [
"Modify",
"ContentHandler",
"a",
"sub",
"-",
"class",
"of",
"pycbc_glue",
".",
"ligolw",
".",
"LIGOLWContentHandler",
"to",
"cause",
"it",
"to",
"use",
"the",
"Table",
"Column",
"and",
"Stream",
"classes",
"defined",
"in",
"this",
"module",
"when",
"parsing",
... | train | https://github.com/gwastro/pycbc-glue/blob/a3e906bae59fbfd707c3ff82e5d008d939ec5e24/pycbc_glue/ligolw/table.py#L1076-L1108 |
gwastro/pycbc-glue | pycbc_glue/ligolw/table.py | Column.count | def count(self, value):
"""
Return the number of rows with this column equal to value.
"""
return sum(getattr(row, self.Name) == value for row in self.parentNode) | python | def count(self, value):
"""
Return the number of rows with this column equal to value.
"""
return sum(getattr(row, self.Name) == value for row in self.parentNode) | [
"def",
"count",
"(",
"self",
",",
"value",
")",
":",
"return",
"sum",
"(",
"getattr",
"(",
"row",
",",
"self",
".",
"Name",
")",
"==",
"value",
"for",
"row",
"in",
"self",
".",
"parentNode",
")"
] | Return the number of rows with this column equal to value. | [
"Return",
"the",
"number",
"of",
"rows",
"with",
"this",
"column",
"equal",
"to",
"value",
"."
] | train | https://github.com/gwastro/pycbc-glue/blob/a3e906bae59fbfd707c3ff82e5d008d939ec5e24/pycbc_glue/ligolw/table.py#L457-L461 |
gwastro/pycbc-glue | pycbc_glue/ligolw/table.py | Column.index | def index(self, value):
"""
Return the smallest index of the row(s) with this column
equal to value.
"""
for i in xrange(len(self.parentNode)):
if getattr(self.parentNode[i], self.Name) == value:
return i
raise ValueError(value) | python | def index(self, value):
"""
Return the smallest index of the row(s) with this column
equal to value.
"""
for i in xrange(len(self.parentNode)):
if getattr(self.parentNode[i], self.Name) == value:
return i
raise ValueError(value) | [
"def",
"index",
"(",
"self",
",",
"value",
")",
":",
"for",
"i",
"in",
"xrange",
"(",
"len",
"(",
"self",
".",
"parentNode",
")",
")",
":",
"if",
"getattr",
"(",
"self",
".",
"parentNode",
"[",
"i",
"]",
",",
"self",
".",
"Name",
")",
"==",
"va... | Return the smallest index of the row(s) with this column
equal to value. | [
"Return",
"the",
"smallest",
"index",
"of",
"the",
"row",
"(",
"s",
")",
"with",
"this",
"column",
"equal",
"to",
"value",
"."
] | train | https://github.com/gwastro/pycbc-glue/blob/a3e906bae59fbfd707c3ff82e5d008d939ec5e24/pycbc_glue/ligolw/table.py#L463-L471 |
gwastro/pycbc-glue | pycbc_glue/ligolw/table.py | Column.asarray | def asarray(self):
"""
Construct a numpy array from this column. Note that this
creates a copy of the data, so modifications made to the
array will *not* be recorded in the original document.
"""
# most codes don't use this feature, this is the only place
# numpy is used here, and importing numpy can be
# time-consuming, so we derfer the import until needed.
import numpy
try:
dtype = ligolwtypes.ToNumPyType[self.Type]
except KeyError as e:
raise TypeError("cannot determine numpy dtype for Column '%s': %s" % (self.getAttribute("Name"), e))
return numpy.fromiter(self, dtype = dtype) | python | def asarray(self):
"""
Construct a numpy array from this column. Note that this
creates a copy of the data, so modifications made to the
array will *not* be recorded in the original document.
"""
# most codes don't use this feature, this is the only place
# numpy is used here, and importing numpy can be
# time-consuming, so we derfer the import until needed.
import numpy
try:
dtype = ligolwtypes.ToNumPyType[self.Type]
except KeyError as e:
raise TypeError("cannot determine numpy dtype for Column '%s': %s" % (self.getAttribute("Name"), e))
return numpy.fromiter(self, dtype = dtype) | [
"def",
"asarray",
"(",
"self",
")",
":",
"# most codes don't use this feature, this is the only place",
"# numpy is used here, and importing numpy can be",
"# time-consuming, so we derfer the import until needed.",
"import",
"numpy",
"try",
":",
"dtype",
"=",
"ligolwtypes",
".",
"T... | Construct a numpy array from this column. Note that this
creates a copy of the data, so modifications made to the
array will *not* be recorded in the original document. | [
"Construct",
"a",
"numpy",
"array",
"from",
"this",
"column",
".",
"Note",
"that",
"this",
"creates",
"a",
"copy",
"of",
"the",
"data",
"so",
"modifications",
"made",
"to",
"the",
"array",
"will",
"*",
"not",
"*",
"be",
"recorded",
"in",
"the",
"original... | train | https://github.com/gwastro/pycbc-glue/blob/a3e906bae59fbfd707c3ff82e5d008d939ec5e24/pycbc_glue/ligolw/table.py#L483-L497 |
gwastro/pycbc-glue | pycbc_glue/ligolw/table.py | TableStream.unlink | def unlink(self):
"""
Break internal references within the document tree rooted
on this element to promote garbage collection.
"""
self._tokenizer = None
self._rowbuilder = None
super(TableStream, self).unlink() | python | def unlink(self):
"""
Break internal references within the document tree rooted
on this element to promote garbage collection.
"""
self._tokenizer = None
self._rowbuilder = None
super(TableStream, self).unlink() | [
"def",
"unlink",
"(",
"self",
")",
":",
"self",
".",
"_tokenizer",
"=",
"None",
"self",
".",
"_rowbuilder",
"=",
"None",
"super",
"(",
"TableStream",
",",
"self",
")",
".",
"unlink",
"(",
")"
] | Break internal references within the document tree rooted
on this element to promote garbage collection. | [
"Break",
"internal",
"references",
"within",
"the",
"document",
"tree",
"rooted",
"on",
"this",
"element",
"to",
"promote",
"garbage",
"collection",
"."
] | train | https://github.com/gwastro/pycbc-glue/blob/a3e906bae59fbfd707c3ff82e5d008d939ec5e24/pycbc_glue/ligolw/table.py#L615-L622 |
gwastro/pycbc-glue | pycbc_glue/ligolw/table.py | Table.copy | def copy(self):
"""
Construct and return a new Table document subtree whose
structure is the same as this table, that is it has the
same columns etc.. The rows are not copied. Note that a
fair amount of metadata is shared between the original and
new tables. In particular, a copy of the Table object
itself is created (but with no rows), and copies of the
child nodes are created. All other object references are
shared between the two instances, such as the RowType
attribute on the Table object.
"""
new = copy.copy(self)
new.childNodes = map(copy.copy, self.childNodes)
for child in new.childNodes:
child.parentNode = new
del new[:]
new._end_of_columns()
new._end_of_rows()
return new | python | def copy(self):
"""
Construct and return a new Table document subtree whose
structure is the same as this table, that is it has the
same columns etc.. The rows are not copied. Note that a
fair amount of metadata is shared between the original and
new tables. In particular, a copy of the Table object
itself is created (but with no rows), and copies of the
child nodes are created. All other object references are
shared between the two instances, such as the RowType
attribute on the Table object.
"""
new = copy.copy(self)
new.childNodes = map(copy.copy, self.childNodes)
for child in new.childNodes:
child.parentNode = new
del new[:]
new._end_of_columns()
new._end_of_rows()
return new | [
"def",
"copy",
"(",
"self",
")",
":",
"new",
"=",
"copy",
".",
"copy",
"(",
"self",
")",
"new",
".",
"childNodes",
"=",
"map",
"(",
"copy",
".",
"copy",
",",
"self",
".",
"childNodes",
")",
"for",
"child",
"in",
"new",
".",
"childNodes",
":",
"ch... | Construct and return a new Table document subtree whose
structure is the same as this table, that is it has the
same columns etc.. The rows are not copied. Note that a
fair amount of metadata is shared between the original and
new tables. In particular, a copy of the Table object
itself is created (but with no rows), and copies of the
child nodes are created. All other object references are
shared between the two instances, such as the RowType
attribute on the Table object. | [
"Construct",
"and",
"return",
"a",
"new",
"Table",
"document",
"subtree",
"whose",
"structure",
"is",
"the",
"same",
"as",
"this",
"table",
"that",
"is",
"it",
"has",
"the",
"same",
"columns",
"etc",
"..",
"The",
"rows",
"are",
"not",
"copied",
".",
"Not... | train | https://github.com/gwastro/pycbc-glue/blob/a3e906bae59fbfd707c3ff82e5d008d939ec5e24/pycbc_glue/ligolw/table.py#L741-L760 |
gwastro/pycbc-glue | pycbc_glue/ligolw/table.py | Table.CheckProperties | def CheckProperties(cls, tagname, attrs):
"""
Return True if tagname and attrs are the XML tag name and
element attributes, respectively, of a Table element whose
Name attribute matches the .tableName attribute of this
class according to CompareTableNames(); return False
otherwise. The Table parent class does not provide a
.tableName attribute, but sub-classes, especially those in
lsctables.py, do provide a value for that attribute. See
also .CheckElement()
Example:
>>> import lsctables
>>> lsctables.ProcessTable.CheckProperties(u"Table", {u"Name": u"process:table"})
True
"""
return tagname == cls.tagName and not CompareTableNames(attrs[u"Name"], cls.tableName) | python | def CheckProperties(cls, tagname, attrs):
"""
Return True if tagname and attrs are the XML tag name and
element attributes, respectively, of a Table element whose
Name attribute matches the .tableName attribute of this
class according to CompareTableNames(); return False
otherwise. The Table parent class does not provide a
.tableName attribute, but sub-classes, especially those in
lsctables.py, do provide a value for that attribute. See
also .CheckElement()
Example:
>>> import lsctables
>>> lsctables.ProcessTable.CheckProperties(u"Table", {u"Name": u"process:table"})
True
"""
return tagname == cls.tagName and not CompareTableNames(attrs[u"Name"], cls.tableName) | [
"def",
"CheckProperties",
"(",
"cls",
",",
"tagname",
",",
"attrs",
")",
":",
"return",
"tagname",
"==",
"cls",
".",
"tagName",
"and",
"not",
"CompareTableNames",
"(",
"attrs",
"[",
"u\"Name\"",
"]",
",",
"cls",
".",
"tableName",
")"
] | Return True if tagname and attrs are the XML tag name and
element attributes, respectively, of a Table element whose
Name attribute matches the .tableName attribute of this
class according to CompareTableNames(); return False
otherwise. The Table parent class does not provide a
.tableName attribute, but sub-classes, especially those in
lsctables.py, do provide a value for that attribute. See
also .CheckElement()
Example:
>>> import lsctables
>>> lsctables.ProcessTable.CheckProperties(u"Table", {u"Name": u"process:table"})
True | [
"Return",
"True",
"if",
"tagname",
"and",
"attrs",
"are",
"the",
"XML",
"tag",
"name",
"and",
"element",
"attributes",
"respectively",
"of",
"a",
"Table",
"element",
"whose",
"Name",
"attribute",
"matches",
"the",
".",
"tableName",
"attribute",
"of",
"this",
... | train | https://github.com/gwastro/pycbc-glue/blob/a3e906bae59fbfd707c3ff82e5d008d939ec5e24/pycbc_glue/ligolw/table.py#L775-L792 |
gwastro/pycbc-glue | pycbc_glue/ligolw/table.py | Table.getColumnByName | def getColumnByName(self, name):
"""
Retrieve and return the Column child element named name.
The comparison is done using CompareColumnNames(). Raises
KeyError if this table has no column by that name.
Example:
>>> import lsctables
>>> tbl = lsctables.New(lsctables.SnglInspiralTable)
>>> col = tbl.getColumnByName("mass1")
"""
try:
col, = getColumnsByName(self, name)
except ValueError:
# did not find exactly 1 matching child
raise KeyError(name)
return col | python | def getColumnByName(self, name):
"""
Retrieve and return the Column child element named name.
The comparison is done using CompareColumnNames(). Raises
KeyError if this table has no column by that name.
Example:
>>> import lsctables
>>> tbl = lsctables.New(lsctables.SnglInspiralTable)
>>> col = tbl.getColumnByName("mass1")
"""
try:
col, = getColumnsByName(self, name)
except ValueError:
# did not find exactly 1 matching child
raise KeyError(name)
return col | [
"def",
"getColumnByName",
"(",
"self",
",",
"name",
")",
":",
"try",
":",
"col",
",",
"=",
"getColumnsByName",
"(",
"self",
",",
"name",
")",
"except",
"ValueError",
":",
"# did not find exactly 1 matching child",
"raise",
"KeyError",
"(",
"name",
")",
"return... | Retrieve and return the Column child element named name.
The comparison is done using CompareColumnNames(). Raises
KeyError if this table has no column by that name.
Example:
>>> import lsctables
>>> tbl = lsctables.New(lsctables.SnglInspiralTable)
>>> col = tbl.getColumnByName("mass1") | [
"Retrieve",
"and",
"return",
"the",
"Column",
"child",
"element",
"named",
"name",
".",
"The",
"comparison",
"is",
"done",
"using",
"CompareColumnNames",
"()",
".",
"Raises",
"KeyError",
"if",
"this",
"table",
"has",
"no",
"column",
"by",
"that",
"name",
"."... | train | https://github.com/gwastro/pycbc-glue/blob/a3e906bae59fbfd707c3ff82e5d008d939ec5e24/pycbc_glue/ligolw/table.py#L799-L816 |
gwastro/pycbc-glue | pycbc_glue/ligolw/table.py | Table.appendColumn | def appendColumn(self, name):
"""
Append a Column element named "name" to the table. Returns
the new child. Raises ValueError if the table already has
a column by that name, and KeyError if the validcolumns
attribute of this table does not contain an entry for a
column by that name.
Note that the name string is assumed to be "pre-stripped",
that is it is the significant portion of the elements Name
attribute. The Column element's Name attribute will be
constructed by pre-pending the stripped Table element's
name and a colon.
Example:
>>> import lsctables
>>> process_table = lsctables.New(lsctables.ProcessTable, [])
>>> col = process_table.appendColumn("program")
>>> col.getAttribute("Name")
'process:program'
>>> col.Name
'program'
"""
try:
self.getColumnByName(name)
# if we get here the table already has that column
raise ValueError("duplicate Column '%s'" % name)
except KeyError:
pass
column = Column(AttributesImpl({u"Name": "%s:%s" % (StripTableName(self.tableName), name), u"Type": self.validcolumns[name]}))
streams = self.getElementsByTagName(ligolw.Stream.tagName)
if streams:
self.insertBefore(column, streams[0])
else:
self.appendChild(column)
return column | python | def appendColumn(self, name):
"""
Append a Column element named "name" to the table. Returns
the new child. Raises ValueError if the table already has
a column by that name, and KeyError if the validcolumns
attribute of this table does not contain an entry for a
column by that name.
Note that the name string is assumed to be "pre-stripped",
that is it is the significant portion of the elements Name
attribute. The Column element's Name attribute will be
constructed by pre-pending the stripped Table element's
name and a colon.
Example:
>>> import lsctables
>>> process_table = lsctables.New(lsctables.ProcessTable, [])
>>> col = process_table.appendColumn("program")
>>> col.getAttribute("Name")
'process:program'
>>> col.Name
'program'
"""
try:
self.getColumnByName(name)
# if we get here the table already has that column
raise ValueError("duplicate Column '%s'" % name)
except KeyError:
pass
column = Column(AttributesImpl({u"Name": "%s:%s" % (StripTableName(self.tableName), name), u"Type": self.validcolumns[name]}))
streams = self.getElementsByTagName(ligolw.Stream.tagName)
if streams:
self.insertBefore(column, streams[0])
else:
self.appendChild(column)
return column | [
"def",
"appendColumn",
"(",
"self",
",",
"name",
")",
":",
"try",
":",
"self",
".",
"getColumnByName",
"(",
"name",
")",
"# if we get here the table already has that column",
"raise",
"ValueError",
"(",
"\"duplicate Column '%s'\"",
"%",
"name",
")",
"except",
"KeyEr... | Append a Column element named "name" to the table. Returns
the new child. Raises ValueError if the table already has
a column by that name, and KeyError if the validcolumns
attribute of this table does not contain an entry for a
column by that name.
Note that the name string is assumed to be "pre-stripped",
that is it is the significant portion of the elements Name
attribute. The Column element's Name attribute will be
constructed by pre-pending the stripped Table element's
name and a colon.
Example:
>>> import lsctables
>>> process_table = lsctables.New(lsctables.ProcessTable, [])
>>> col = process_table.appendColumn("program")
>>> col.getAttribute("Name")
'process:program'
>>> col.Name
'program' | [
"Append",
"a",
"Column",
"element",
"named",
"name",
"to",
"the",
"table",
".",
"Returns",
"the",
"new",
"child",
".",
"Raises",
"ValueError",
"if",
"the",
"table",
"already",
"has",
"a",
"column",
"by",
"that",
"name",
"and",
"KeyError",
"if",
"the",
"v... | train | https://github.com/gwastro/pycbc-glue/blob/a3e906bae59fbfd707c3ff82e5d008d939ec5e24/pycbc_glue/ligolw/table.py#L819-L855 |
gwastro/pycbc-glue | pycbc_glue/ligolw/table.py | Table.appendRow | def appendRow(self, *args, **kwargs):
"""
Create and append a new row to this table, then return it
All positional and keyword arguments are passed to the RowType
constructor for this table.
"""
row = self.RowType(*args, **kwargs)
self.append(row)
return row | python | def appendRow(self, *args, **kwargs):
"""
Create and append a new row to this table, then return it
All positional and keyword arguments are passed to the RowType
constructor for this table.
"""
row = self.RowType(*args, **kwargs)
self.append(row)
return row | [
"def",
"appendRow",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"row",
"=",
"self",
".",
"RowType",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"self",
".",
"append",
"(",
"row",
")",
"return",
"row"
] | Create and append a new row to this table, then return it
All positional and keyword arguments are passed to the RowType
constructor for this table. | [
"Create",
"and",
"append",
"a",
"new",
"row",
"to",
"this",
"table",
"then",
"return",
"it"
] | train | https://github.com/gwastro/pycbc-glue/blob/a3e906bae59fbfd707c3ff82e5d008d939ec5e24/pycbc_glue/ligolw/table.py#L862-L871 |
gwastro/pycbc-glue | pycbc_glue/ligolw/table.py | Table._update_column_info | def _update_column_info(self):
"""
Used for validation during parsing, and additional
book-keeping. For internal use only.
"""
del self.columnnames[:]
del self.columntypes[:]
del self.columnpytypes[:]
for child in self.getElementsByTagName(ligolw.Column.tagName):
if self.validcolumns is not None:
try:
if self.validcolumns[child.Name] != child.Type:
raise ligolw.ElementError("invalid type '%s' for Column '%s' in Table '%s', expected type '%s'" % (child.Type, child.getAttribute("Name"), self.getAttribute("Name"), self.validcolumns[child.Name]))
except KeyError:
raise ligolw.ElementError("invalid Column '%s' for Table '%s'" % (child.getAttribute("Name"), self.getAttribute("Name")))
if child.Name in self.columnnames:
raise ligolw.ElementError("duplicate Column '%s' in Table '%s'" % (child.getAttribute("Name"), self.getAttribute("Name")))
self.columnnames.append(child.Name)
self.columntypes.append(child.Type)
try:
self.columnpytypes.append(ligolwtypes.ToPyType[child.Type])
except KeyError:
raise ligolw.ElementError("unrecognized Type '%s' for Column '%s' in Table '%s'" % (child.Type, child.getAttribute("Name"), self.getAttribute("Name"))) | python | def _update_column_info(self):
"""
Used for validation during parsing, and additional
book-keeping. For internal use only.
"""
del self.columnnames[:]
del self.columntypes[:]
del self.columnpytypes[:]
for child in self.getElementsByTagName(ligolw.Column.tagName):
if self.validcolumns is not None:
try:
if self.validcolumns[child.Name] != child.Type:
raise ligolw.ElementError("invalid type '%s' for Column '%s' in Table '%s', expected type '%s'" % (child.Type, child.getAttribute("Name"), self.getAttribute("Name"), self.validcolumns[child.Name]))
except KeyError:
raise ligolw.ElementError("invalid Column '%s' for Table '%s'" % (child.getAttribute("Name"), self.getAttribute("Name")))
if child.Name in self.columnnames:
raise ligolw.ElementError("duplicate Column '%s' in Table '%s'" % (child.getAttribute("Name"), self.getAttribute("Name")))
self.columnnames.append(child.Name)
self.columntypes.append(child.Type)
try:
self.columnpytypes.append(ligolwtypes.ToPyType[child.Type])
except KeyError:
raise ligolw.ElementError("unrecognized Type '%s' for Column '%s' in Table '%s'" % (child.Type, child.getAttribute("Name"), self.getAttribute("Name"))) | [
"def",
"_update_column_info",
"(",
"self",
")",
":",
"del",
"self",
".",
"columnnames",
"[",
":",
"]",
"del",
"self",
".",
"columntypes",
"[",
":",
"]",
"del",
"self",
".",
"columnpytypes",
"[",
":",
"]",
"for",
"child",
"in",
"self",
".",
"getElements... | Used for validation during parsing, and additional
book-keeping. For internal use only. | [
"Used",
"for",
"validation",
"during",
"parsing",
"and",
"additional",
"book",
"-",
"keeping",
".",
"For",
"internal",
"use",
"only",
"."
] | train | https://github.com/gwastro/pycbc-glue/blob/a3e906bae59fbfd707c3ff82e5d008d939ec5e24/pycbc_glue/ligolw/table.py#L878-L900 |
gwastro/pycbc-glue | pycbc_glue/ligolw/table.py | Table._verifyChildren | def _verifyChildren(self, i):
"""
Used for validation during parsing, and additional
book-keeping. For internal use only.
"""
super(Table, self)._verifyChildren(i)
child = self.childNodes[i]
if child.tagName == ligolw.Column.tagName:
self._update_column_info()
elif child.tagName == ligolw.Stream.tagName:
# require agreement of non-stripped strings
if child.getAttribute("Name") != self.getAttribute("Name"):
raise ligolw.ElementError("Stream name '%s' does not match Table name '%s'" % (child.getAttribute("Name"), self.getAttribute("Name"))) | python | def _verifyChildren(self, i):
"""
Used for validation during parsing, and additional
book-keeping. For internal use only.
"""
super(Table, self)._verifyChildren(i)
child = self.childNodes[i]
if child.tagName == ligolw.Column.tagName:
self._update_column_info()
elif child.tagName == ligolw.Stream.tagName:
# require agreement of non-stripped strings
if child.getAttribute("Name") != self.getAttribute("Name"):
raise ligolw.ElementError("Stream name '%s' does not match Table name '%s'" % (child.getAttribute("Name"), self.getAttribute("Name"))) | [
"def",
"_verifyChildren",
"(",
"self",
",",
"i",
")",
":",
"super",
"(",
"Table",
",",
"self",
")",
".",
"_verifyChildren",
"(",
"i",
")",
"child",
"=",
"self",
".",
"childNodes",
"[",
"i",
"]",
"if",
"child",
".",
"tagName",
"==",
"ligolw",
".",
"... | Used for validation during parsing, and additional
book-keeping. For internal use only. | [
"Used",
"for",
"validation",
"during",
"parsing",
"and",
"additional",
"book",
"-",
"keeping",
".",
"For",
"internal",
"use",
"only",
"."
] | train | https://github.com/gwastro/pycbc-glue/blob/a3e906bae59fbfd707c3ff82e5d008d939ec5e24/pycbc_glue/ligolw/table.py#L902-L914 |
gwastro/pycbc-glue | pycbc_glue/ligolw/table.py | Table.removeChild | def removeChild(self, child):
"""
Remove a child from this element. The child element is
returned, and it's parentNode element is reset.
"""
super(Table, self).removeChild(child)
if child.tagName == ligolw.Column.tagName:
self._update_column_info()
return child | python | def removeChild(self, child):
"""
Remove a child from this element. The child element is
returned, and it's parentNode element is reset.
"""
super(Table, self).removeChild(child)
if child.tagName == ligolw.Column.tagName:
self._update_column_info()
return child | [
"def",
"removeChild",
"(",
"self",
",",
"child",
")",
":",
"super",
"(",
"Table",
",",
"self",
")",
".",
"removeChild",
"(",
"child",
")",
"if",
"child",
".",
"tagName",
"==",
"ligolw",
".",
"Column",
".",
"tagName",
":",
"self",
".",
"_update_column_i... | Remove a child from this element. The child element is
returned, and it's parentNode element is reset. | [
"Remove",
"a",
"child",
"from",
"this",
"element",
".",
"The",
"child",
"element",
"is",
"returned",
"and",
"it",
"s",
"parentNode",
"element",
"is",
"reset",
"."
] | train | https://github.com/gwastro/pycbc-glue/blob/a3e906bae59fbfd707c3ff82e5d008d939ec5e24/pycbc_glue/ligolw/table.py#L934-L942 |
gwastro/pycbc-glue | pycbc_glue/ligolw/table.py | Table.sync_next_id | def sync_next_id(self):
"""
Determines the highest-numbered ID in this table, and sets
the table's .next_id attribute to the next highest ID in
sequence. If the .next_id attribute is already set to a
value greater than the highest value found, then it is left
unmodified. The return value is the ID identified by this
method. If the table's .next_id attribute is None, then
this function is a no-op.
Note that tables of the same name typically share a common
.next_id attribute (it is a class attribute, not an
attribute of each instance) so that IDs can be generated
that are unique across all tables in the document. Running
sync_next_id() on all the tables in a document that are of
the same type will have the effect of setting the ID to the
next ID higher than any ID in any of those tables.
Example:
>>> import lsctables
>>> tbl = lsctables.New(lsctables.ProcessTable)
>>> print tbl.sync_next_id()
process:process_id:0
"""
if self.next_id is not None:
if len(self):
n = max(self.getColumnByName(self.next_id.column_name)) + 1
else:
n = type(self.next_id)(0)
if n > self.next_id:
self.set_next_id(n)
return self.next_id | python | def sync_next_id(self):
"""
Determines the highest-numbered ID in this table, and sets
the table's .next_id attribute to the next highest ID in
sequence. If the .next_id attribute is already set to a
value greater than the highest value found, then it is left
unmodified. The return value is the ID identified by this
method. If the table's .next_id attribute is None, then
this function is a no-op.
Note that tables of the same name typically share a common
.next_id attribute (it is a class attribute, not an
attribute of each instance) so that IDs can be generated
that are unique across all tables in the document. Running
sync_next_id() on all the tables in a document that are of
the same type will have the effect of setting the ID to the
next ID higher than any ID in any of those tables.
Example:
>>> import lsctables
>>> tbl = lsctables.New(lsctables.ProcessTable)
>>> print tbl.sync_next_id()
process:process_id:0
"""
if self.next_id is not None:
if len(self):
n = max(self.getColumnByName(self.next_id.column_name)) + 1
else:
n = type(self.next_id)(0)
if n > self.next_id:
self.set_next_id(n)
return self.next_id | [
"def",
"sync_next_id",
"(",
"self",
")",
":",
"if",
"self",
".",
"next_id",
"is",
"not",
"None",
":",
"if",
"len",
"(",
"self",
")",
":",
"n",
"=",
"max",
"(",
"self",
".",
"getColumnByName",
"(",
"self",
".",
"next_id",
".",
"column_name",
")",
")... | Determines the highest-numbered ID in this table, and sets
the table's .next_id attribute to the next highest ID in
sequence. If the .next_id attribute is already set to a
value greater than the highest value found, then it is left
unmodified. The return value is the ID identified by this
method. If the table's .next_id attribute is None, then
this function is a no-op.
Note that tables of the same name typically share a common
.next_id attribute (it is a class attribute, not an
attribute of each instance) so that IDs can be generated
that are unique across all tables in the document. Running
sync_next_id() on all the tables in a document that are of
the same type will have the effect of setting the ID to the
next ID higher than any ID in any of those tables.
Example:
>>> import lsctables
>>> tbl = lsctables.New(lsctables.ProcessTable)
>>> print tbl.sync_next_id()
process:process_id:0 | [
"Determines",
"the",
"highest",
"-",
"numbered",
"ID",
"in",
"this",
"table",
"and",
"sets",
"the",
"table",
"s",
".",
"next_id",
"attribute",
"to",
"the",
"next",
"highest",
"ID",
"in",
"sequence",
".",
"If",
"the",
".",
"next_id",
"attribute",
"is",
"a... | train | https://github.com/gwastro/pycbc-glue/blob/a3e906bae59fbfd707c3ff82e5d008d939ec5e24/pycbc_glue/ligolw/table.py#L987-L1019 |
gwastro/pycbc-glue | pycbc_glue/ligolw/table.py | Table.updateKeyMapping | def updateKeyMapping(self, mapping):
"""
Used as the first half of the row key reassignment
algorithm. Accepts a dictionary mapping old key --> new
key. Iterates over the rows in this table, using the
table's next_id attribute to assign a new ID to each row,
recording the changes in the mapping. Returns the mapping.
Raises ValueError if the table's next_id attribute is None.
"""
if self.next_id is None:
raise ValueError(self)
try:
column = self.getColumnByName(self.next_id.column_name)
except KeyError:
# table is missing its ID column, this is a no-op
return mapping
for i, old in enumerate(column):
if old is None:
raise ValueError("null row ID encountered in Table '%s', row %d" % (self.getAttribute("Name"), i))
if old in mapping:
column[i] = mapping[old]
else:
column[i] = mapping[old] = self.get_next_id()
return mapping | python | def updateKeyMapping(self, mapping):
"""
Used as the first half of the row key reassignment
algorithm. Accepts a dictionary mapping old key --> new
key. Iterates over the rows in this table, using the
table's next_id attribute to assign a new ID to each row,
recording the changes in the mapping. Returns the mapping.
Raises ValueError if the table's next_id attribute is None.
"""
if self.next_id is None:
raise ValueError(self)
try:
column = self.getColumnByName(self.next_id.column_name)
except KeyError:
# table is missing its ID column, this is a no-op
return mapping
for i, old in enumerate(column):
if old is None:
raise ValueError("null row ID encountered in Table '%s', row %d" % (self.getAttribute("Name"), i))
if old in mapping:
column[i] = mapping[old]
else:
column[i] = mapping[old] = self.get_next_id()
return mapping | [
"def",
"updateKeyMapping",
"(",
"self",
",",
"mapping",
")",
":",
"if",
"self",
".",
"next_id",
"is",
"None",
":",
"raise",
"ValueError",
"(",
"self",
")",
"try",
":",
"column",
"=",
"self",
".",
"getColumnByName",
"(",
"self",
".",
"next_id",
".",
"co... | Used as the first half of the row key reassignment
algorithm. Accepts a dictionary mapping old key --> new
key. Iterates over the rows in this table, using the
table's next_id attribute to assign a new ID to each row,
recording the changes in the mapping. Returns the mapping.
Raises ValueError if the table's next_id attribute is None. | [
"Used",
"as",
"the",
"first",
"half",
"of",
"the",
"row",
"key",
"reassignment",
"algorithm",
".",
"Accepts",
"a",
"dictionary",
"mapping",
"old",
"key",
"--",
">",
"new",
"key",
".",
"Iterates",
"over",
"the",
"rows",
"in",
"this",
"table",
"using",
"th... | train | https://github.com/gwastro/pycbc-glue/blob/a3e906bae59fbfd707c3ff82e5d008d939ec5e24/pycbc_glue/ligolw/table.py#L1021-L1044 |
gwastro/pycbc-glue | pycbc_glue/ligolw/table.py | Table.applyKeyMapping | def applyKeyMapping(self, mapping):
"""
Used as the second half of the key reassignment algorithm.
Loops over each row in the table, replacing references to
old row keys with the new values from the mapping.
"""
for coltype, colname in zip(self.columntypes, self.columnnames):
if coltype in ligolwtypes.IDTypes and (self.next_id is None or colname != self.next_id.column_name):
column = self.getColumnByName(colname)
for i, old in enumerate(column):
try:
column[i] = mapping[old]
except KeyError:
pass | python | def applyKeyMapping(self, mapping):
"""
Used as the second half of the key reassignment algorithm.
Loops over each row in the table, replacing references to
old row keys with the new values from the mapping.
"""
for coltype, colname in zip(self.columntypes, self.columnnames):
if coltype in ligolwtypes.IDTypes and (self.next_id is None or colname != self.next_id.column_name):
column = self.getColumnByName(colname)
for i, old in enumerate(column):
try:
column[i] = mapping[old]
except KeyError:
pass | [
"def",
"applyKeyMapping",
"(",
"self",
",",
"mapping",
")",
":",
"for",
"coltype",
",",
"colname",
"in",
"zip",
"(",
"self",
".",
"columntypes",
",",
"self",
".",
"columnnames",
")",
":",
"if",
"coltype",
"in",
"ligolwtypes",
".",
"IDTypes",
"and",
"(",
... | Used as the second half of the key reassignment algorithm.
Loops over each row in the table, replacing references to
old row keys with the new values from the mapping. | [
"Used",
"as",
"the",
"second",
"half",
"of",
"the",
"key",
"reassignment",
"algorithm",
".",
"Loops",
"over",
"each",
"row",
"in",
"the",
"table",
"replacing",
"references",
"to",
"old",
"row",
"keys",
"with",
"the",
"new",
"values",
"from",
"the",
"mappin... | train | https://github.com/gwastro/pycbc-glue/blob/a3e906bae59fbfd707c3ff82e5d008d939ec5e24/pycbc_glue/ligolw/table.py#L1046-L1059 |
KenjiTakahashi/td | td/main.py | Parser._part | def _part(self, name, func, args, help, **kwargs):
"""Parses arguments of a single command (e.g. 'v').
If :args: is empty, it assumes that command takes no further arguments.
:name: Name of the command.
:func: Arg method to execute.
:args: Dictionary of CLI arguments pointed at Arg method arguments.
:help: Commands' help text.
:kwargs: Additional arguments for :func:.
"""
while self.argv:
arg = self.argv.popleft()
if arg == "-h" or arg == "--help":
print(help)
return
try:
argname, argarg = args[arg]
kwargs[argname] = argarg and self.argv.popleft() or True
except KeyError:
raise UnrecognizedArgumentError(name, arg)
except IndexError:
valids = ["-s", "--sort", "-d", "--done", "-D", "--undone"]
if arg not in valids:
raise NotEnoughArgumentsError(name)
kwargs[argname] = True
func(**kwargs) | python | def _part(self, name, func, args, help, **kwargs):
"""Parses arguments of a single command (e.g. 'v').
If :args: is empty, it assumes that command takes no further arguments.
:name: Name of the command.
:func: Arg method to execute.
:args: Dictionary of CLI arguments pointed at Arg method arguments.
:help: Commands' help text.
:kwargs: Additional arguments for :func:.
"""
while self.argv:
arg = self.argv.popleft()
if arg == "-h" or arg == "--help":
print(help)
return
try:
argname, argarg = args[arg]
kwargs[argname] = argarg and self.argv.popleft() or True
except KeyError:
raise UnrecognizedArgumentError(name, arg)
except IndexError:
valids = ["-s", "--sort", "-d", "--done", "-D", "--undone"]
if arg not in valids:
raise NotEnoughArgumentsError(name)
kwargs[argname] = True
func(**kwargs) | [
"def",
"_part",
"(",
"self",
",",
"name",
",",
"func",
",",
"args",
",",
"help",
",",
"*",
"*",
"kwargs",
")",
":",
"while",
"self",
".",
"argv",
":",
"arg",
"=",
"self",
".",
"argv",
".",
"popleft",
"(",
")",
"if",
"arg",
"==",
"\"-h\"",
"or",... | Parses arguments of a single command (e.g. 'v').
If :args: is empty, it assumes that command takes no further arguments.
:name: Name of the command.
:func: Arg method to execute.
:args: Dictionary of CLI arguments pointed at Arg method arguments.
:help: Commands' help text.
:kwargs: Additional arguments for :func:. | [
"Parses",
"arguments",
"of",
"a",
"single",
"command",
"(",
"e",
".",
"g",
".",
"v",
")",
"."
] | train | https://github.com/KenjiTakahashi/td/blob/7311eabc63efe6fe6600687c3026f0837454c2e4/td/main.py#L118-L145 |
KenjiTakahashi/td | td/main.py | Parser.rock | def rock(self):
"""Starts and does the parsing."""
if not self.argv:
self.arg.view()
while(self.argv):
arg = self.argv.popleft()
if arg == "-h" or arg == "--help":
print(
"""Usage: td [-h (--help)] [-v (--version)] [command]"""
""", where [command] is one of:\n\n"""
"""v (view)\tChanges the way next output"""
""" will look like. See [td v -h].\n"""
"""m (modify)\tApplies one time changes to"""
""" the database. See [td m -h].\n"""
"""o (options)\tSets persistent options, applied"""
""" on every next execution. See [td o -h].\n"""
"""a (add)\t\tAdds new item. See [td a -h].\n"""
"""e (edit)\tEdits existing item. See [td e -h].\n"""
"""r (rm)\t\tRemoves existing item. See [td r -h].\n"""
"""d (done)\tMarks items as done. See [td d -h].\n"""
"""D (undone)\tMarks items as not done. See [td D -h].\n"""
"""\nAdditional options:\n"""
""" -h (--help)\tShows this screen.\n"""
""" -v (--version)Shows version number."""
)
elif arg == "-v" or arg == "--version":
print("td :: {}".format(__version__))
elif arg == "v" or arg == "view":
self._part("view", self.arg.view, {
"--no-color": ("nocolor", False),
"-s": ("sort", True), "--sort": ("sort", True),
"-p": ("purge", False), "--purge": ("purge", False),
"-d": ("done", True), "--done": ("done", True),
"-D": ("undone", True), "--undone": ("undone", True)
},
"""Usage: td v [-h (--help)] [command(s)]"""
""", where [command(s)] are any of:\n\n"""
"""-s (--sort) <pattern>\tSorts the output using"""
""" <pattern>.\n"""
"""-p (--purge)\t\tHides items marked as done.\n"""
"""-d (--done) <pattern>\tDisplays items matching"""
""" <pattern> as done.\n"""
"""-D (--undone) <pattern>\tDisplays items matching"""
""" <pattern> as not done.\n"""
"""--no-color\t\tDo not add color codes to the output.\n"""
"""\nAdditional options:\n"""
""" -h (--help)\t\tShows this screen."""
)
elif arg == "m" or arg == "modify":
self._part("modify", self.arg.modify, {
"-s": ("sort", True), "--sort": ("sort", True),
"-p": ("purge", False), "--purge": ("purge", False),
"-d": ("done", True), "--done": ("done", True),
"-D": ("undone", True), "--undone": ("undone", True)
},
"""Usage: td m [-h (--help)] [command(s)]"""
""", where [command(s)] are any of:\n\n"""
"""-s (--sort) <pattern>\tSorts database using"""
""" <pattern>.\n"""
"""-p (--purge)\t\tRemoves items marked as done.\n"""
"""-d (--done) <pattern>\tMarks items matching"""
""" <pattern> as done.\n"""
"""-D (--undone) <pattern>\tMarks items matching"""
""" <pattern> as not done.\n"""
"""\nAdditional options:\n"""
""" -h (--help)\t\tShows this screen."""
)
elif arg == "a" or arg == "add":
args = dict()
if self.argv and self.arg.model.exists(self.argv[0]):
args["parent"] = self.argv.popleft()
self._part("add", self.arg.add, {
"-n": ("name", True), "--name": ("name", True),
"-p": ("priority", True), "--priority": ("priority", True),
"-c": ("comment", True), "--comment": ("comment", True)
},
"""Usage: td a [-h (--help)] [parent] [command(s)]"""
""", where [command(s)] are any of:\n\n"""
"""-n (--name) <text>\t\tSets item's name.\n"""
"""-p (--priority) <no|name>\tSets item's priority.\n"""
"""-c (--comment) <text>\t\tSets item's comment.\n"""
"""\nIf [parent] index is specified, new item will"""
""" become it's child.\n"""
"""If any of the arguments is omitted,"""
""" this command will launch an interactive session"""
""" letting the user supply the rest of them.\n"""
"""\nAdditional options:\n"""
""" -h (--help)\t\t\tShows this screen.""",
**args
)
elif arg == "e" or arg == "edit":
if not self.argv:
raise NotEnoughArgumentsError("edit")
args = dict()
if self.argv[0] not in ["-h", "--help"]:
args["index"] = self.argv.popleft()
self._part("edit", self.arg.edit, {
"--parent": ("parent", True),
"-n": ("name", True), "--name": ("name", True),
"-p": ("priority", True), "--priority": ("priority", True),
"-c": ("comment", True), "--comment": ("comment", True)
},
"""Usage: td e [-h (--help)] <index> [command(s)]"""
""", where [command(s)] are any of:\n\n"""
"""--parent <index>\t\tChanges item's parent.\n"""
"""-n (--name) <text>\t\tChanges item's name.\n"""
"""-p (--priority) <no|name>\tChanges item's priority.\n"""
"""-c (--comment) <text>\t\tChanges item's comment.\n"""
"""\nIndex argument is required and has to point at"""
""" an existing item.\n"""
"""If any of the arguments is omitted, it will launch"""
""" an interactive session letting the user supply the"""
""" rest of them.\n"""
"""\nAdditions options:\n"""
""" -h (--help)\t\t\tShows this screen.""",
**args
)
elif arg == "r" or arg == "rm":
args = dict()
if not self.argv:
raise NotEnoughArgumentsError("rm")
elif self.argv[0] not in ["-h", "--help"]:
args["index"] = self.argv.popleft()
self._part("rm", self.arg.rm, {
},
"""Usage: td r [-h (--help)] <index>\n\n"""
"""Index argument is required and has to point at"""
""" an existing item.\n"""
"""\nAdditions options:\n"""
""" -h (--help)\tShows this screen.""",
**args
)
elif arg == "d" or arg == "done":
args = dict()
if not self.argv:
raise NotEnoughArgumentsError("done")
elif self.argv[0] not in ["-h", "--help"]:
args["index"] = self.argv.popleft()
self._part("done", self.arg.done, {
},
"""Usage: td d [-h (--help)] <index>\n\n"""
"""Index argument is required and has to point at"""
""" an existing item.\n"""
"""\nAdditional options:\n"""
""" -h (--help)\tShows this screen.""",
**args
)
elif arg == "D" or arg == "undone":
args = dict()
if not self.argv:
raise NotEnoughArgumentsError("undone")
elif self.argv[0] not in ["-h", "--help"]:
args["index"] = self.argv.popleft()
self._part("undone", self.arg.undone, {
},
"""Usage: td D [-h (--help)] <index>\n\n"""
"""Index argument is required and has to point at"""
""" an existing item.\n"""
"""\nAdditional options:\n"""
""" -h (--help)\tShows this screen.""",
**args
)
elif arg == "o" or arg == "options":
self._part("options", self.arg.options, {
"-g": ("glob", False), "--global": ("glob", False),
"-s": ("sort", True), "--sort": ("sort", True),
"-p": ("purge", False), "--purge": ("purge", False),
"-d": ("done", True), "--done": ("done", True),
"-D": ("undone", True), "--undone": ("undone", True)
},
"""Usage: td o [-h (--help)] [command(s)]"""
""", where [command(s)] are any of:\n\n"""
"""-g (--global)\t\tApply specified options to all"""
""" ToDo lists (store in ~/.tdrc).\n"""
"""-s (--sort) <pattern>\tAlways sorts using"""
""" <pattern>.\n"""
"""-p (--purge)\t\tAlways removes items marked"""
"""as done.\n"""
"""-d (--done) <pattern>\tAlways marks items maching"""
""" <pattern> as done.\n"""
"""-D (--undone) <pattern>\tAlways marks items maching"""
""" <pattern> as not done.\n"""
"""\nAdditional options:\n"""
""" -h (--help)\t\tShows this screen."""
)
else:
raise UnrecognizedCommandError("td", arg) | python | def rock(self):
"""Starts and does the parsing."""
if not self.argv:
self.arg.view()
while(self.argv):
arg = self.argv.popleft()
if arg == "-h" or arg == "--help":
print(
"""Usage: td [-h (--help)] [-v (--version)] [command]"""
""", where [command] is one of:\n\n"""
"""v (view)\tChanges the way next output"""
""" will look like. See [td v -h].\n"""
"""m (modify)\tApplies one time changes to"""
""" the database. See [td m -h].\n"""
"""o (options)\tSets persistent options, applied"""
""" on every next execution. See [td o -h].\n"""
"""a (add)\t\tAdds new item. See [td a -h].\n"""
"""e (edit)\tEdits existing item. See [td e -h].\n"""
"""r (rm)\t\tRemoves existing item. See [td r -h].\n"""
"""d (done)\tMarks items as done. See [td d -h].\n"""
"""D (undone)\tMarks items as not done. See [td D -h].\n"""
"""\nAdditional options:\n"""
""" -h (--help)\tShows this screen.\n"""
""" -v (--version)Shows version number."""
)
elif arg == "-v" or arg == "--version":
print("td :: {}".format(__version__))
elif arg == "v" or arg == "view":
self._part("view", self.arg.view, {
"--no-color": ("nocolor", False),
"-s": ("sort", True), "--sort": ("sort", True),
"-p": ("purge", False), "--purge": ("purge", False),
"-d": ("done", True), "--done": ("done", True),
"-D": ("undone", True), "--undone": ("undone", True)
},
"""Usage: td v [-h (--help)] [command(s)]"""
""", where [command(s)] are any of:\n\n"""
"""-s (--sort) <pattern>\tSorts the output using"""
""" <pattern>.\n"""
"""-p (--purge)\t\tHides items marked as done.\n"""
"""-d (--done) <pattern>\tDisplays items matching"""
""" <pattern> as done.\n"""
"""-D (--undone) <pattern>\tDisplays items matching"""
""" <pattern> as not done.\n"""
"""--no-color\t\tDo not add color codes to the output.\n"""
"""\nAdditional options:\n"""
""" -h (--help)\t\tShows this screen."""
)
elif arg == "m" or arg == "modify":
self._part("modify", self.arg.modify, {
"-s": ("sort", True), "--sort": ("sort", True),
"-p": ("purge", False), "--purge": ("purge", False),
"-d": ("done", True), "--done": ("done", True),
"-D": ("undone", True), "--undone": ("undone", True)
},
"""Usage: td m [-h (--help)] [command(s)]"""
""", where [command(s)] are any of:\n\n"""
"""-s (--sort) <pattern>\tSorts database using"""
""" <pattern>.\n"""
"""-p (--purge)\t\tRemoves items marked as done.\n"""
"""-d (--done) <pattern>\tMarks items matching"""
""" <pattern> as done.\n"""
"""-D (--undone) <pattern>\tMarks items matching"""
""" <pattern> as not done.\n"""
"""\nAdditional options:\n"""
""" -h (--help)\t\tShows this screen."""
)
elif arg == "a" or arg == "add":
args = dict()
if self.argv and self.arg.model.exists(self.argv[0]):
args["parent"] = self.argv.popleft()
self._part("add", self.arg.add, {
"-n": ("name", True), "--name": ("name", True),
"-p": ("priority", True), "--priority": ("priority", True),
"-c": ("comment", True), "--comment": ("comment", True)
},
"""Usage: td a [-h (--help)] [parent] [command(s)]"""
""", where [command(s)] are any of:\n\n"""
"""-n (--name) <text>\t\tSets item's name.\n"""
"""-p (--priority) <no|name>\tSets item's priority.\n"""
"""-c (--comment) <text>\t\tSets item's comment.\n"""
"""\nIf [parent] index is specified, new item will"""
""" become it's child.\n"""
"""If any of the arguments is omitted,"""
""" this command will launch an interactive session"""
""" letting the user supply the rest of them.\n"""
"""\nAdditional options:\n"""
""" -h (--help)\t\t\tShows this screen.""",
**args
)
elif arg == "e" or arg == "edit":
if not self.argv:
raise NotEnoughArgumentsError("edit")
args = dict()
if self.argv[0] not in ["-h", "--help"]:
args["index"] = self.argv.popleft()
self._part("edit", self.arg.edit, {
"--parent": ("parent", True),
"-n": ("name", True), "--name": ("name", True),
"-p": ("priority", True), "--priority": ("priority", True),
"-c": ("comment", True), "--comment": ("comment", True)
},
"""Usage: td e [-h (--help)] <index> [command(s)]"""
""", where [command(s)] are any of:\n\n"""
"""--parent <index>\t\tChanges item's parent.\n"""
"""-n (--name) <text>\t\tChanges item's name.\n"""
"""-p (--priority) <no|name>\tChanges item's priority.\n"""
"""-c (--comment) <text>\t\tChanges item's comment.\n"""
"""\nIndex argument is required and has to point at"""
""" an existing item.\n"""
"""If any of the arguments is omitted, it will launch"""
""" an interactive session letting the user supply the"""
""" rest of them.\n"""
"""\nAdditions options:\n"""
""" -h (--help)\t\t\tShows this screen.""",
**args
)
elif arg == "r" or arg == "rm":
args = dict()
if not self.argv:
raise NotEnoughArgumentsError("rm")
elif self.argv[0] not in ["-h", "--help"]:
args["index"] = self.argv.popleft()
self._part("rm", self.arg.rm, {
},
"""Usage: td r [-h (--help)] <index>\n\n"""
"""Index argument is required and has to point at"""
""" an existing item.\n"""
"""\nAdditions options:\n"""
""" -h (--help)\tShows this screen.""",
**args
)
elif arg == "d" or arg == "done":
args = dict()
if not self.argv:
raise NotEnoughArgumentsError("done")
elif self.argv[0] not in ["-h", "--help"]:
args["index"] = self.argv.popleft()
self._part("done", self.arg.done, {
},
"""Usage: td d [-h (--help)] <index>\n\n"""
"""Index argument is required and has to point at"""
""" an existing item.\n"""
"""\nAdditional options:\n"""
""" -h (--help)\tShows this screen.""",
**args
)
elif arg == "D" or arg == "undone":
args = dict()
if not self.argv:
raise NotEnoughArgumentsError("undone")
elif self.argv[0] not in ["-h", "--help"]:
args["index"] = self.argv.popleft()
self._part("undone", self.arg.undone, {
},
"""Usage: td D [-h (--help)] <index>\n\n"""
"""Index argument is required and has to point at"""
""" an existing item.\n"""
"""\nAdditional options:\n"""
""" -h (--help)\tShows this screen.""",
**args
)
elif arg == "o" or arg == "options":
self._part("options", self.arg.options, {
"-g": ("glob", False), "--global": ("glob", False),
"-s": ("sort", True), "--sort": ("sort", True),
"-p": ("purge", False), "--purge": ("purge", False),
"-d": ("done", True), "--done": ("done", True),
"-D": ("undone", True), "--undone": ("undone", True)
},
"""Usage: td o [-h (--help)] [command(s)]"""
""", where [command(s)] are any of:\n\n"""
"""-g (--global)\t\tApply specified options to all"""
""" ToDo lists (store in ~/.tdrc).\n"""
"""-s (--sort) <pattern>\tAlways sorts using"""
""" <pattern>.\n"""
"""-p (--purge)\t\tAlways removes items marked"""
"""as done.\n"""
"""-d (--done) <pattern>\tAlways marks items maching"""
""" <pattern> as done.\n"""
"""-D (--undone) <pattern>\tAlways marks items maching"""
""" <pattern> as not done.\n"""
"""\nAdditional options:\n"""
""" -h (--help)\t\tShows this screen."""
)
else:
raise UnrecognizedCommandError("td", arg) | [
"def",
"rock",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"argv",
":",
"self",
".",
"arg",
".",
"view",
"(",
")",
"while",
"(",
"self",
".",
"argv",
")",
":",
"arg",
"=",
"self",
".",
"argv",
".",
"popleft",
"(",
")",
"if",
"arg",
"==",... | Starts and does the parsing. | [
"Starts",
"and",
"does",
"the",
"parsing",
"."
] | train | https://github.com/KenjiTakahashi/td/blob/7311eabc63efe6fe6600687c3026f0837454c2e4/td/main.py#L148-L334 |
KenjiTakahashi/td | td/main.py | Get.input | def input(self, field):
"""Gets user input for given field.
Can be interrupted with ^C.
:field: Field name.
:returns: User input.
"""
try:
desc = Get.TYPES[field]
return input("{}|{}[{}]> ".format(
field, "-" * (Get._LEN - len(field) - len(desc)), desc
))
except KeyboardInterrupt:
print()
exit(0) | python | def input(self, field):
"""Gets user input for given field.
Can be interrupted with ^C.
:field: Field name.
:returns: User input.
"""
try:
desc = Get.TYPES[field]
return input("{}|{}[{}]> ".format(
field, "-" * (Get._LEN - len(field) - len(desc)), desc
))
except KeyboardInterrupt:
print()
exit(0) | [
"def",
"input",
"(",
"self",
",",
"field",
")",
":",
"try",
":",
"desc",
"=",
"Get",
".",
"TYPES",
"[",
"field",
"]",
"return",
"input",
"(",
"\"{}|{}[{}]> \"",
".",
"format",
"(",
"field",
",",
"\"-\"",
"*",
"(",
"Get",
".",
"_LEN",
"-",
"len",
... | Gets user input for given field.
Can be interrupted with ^C.
:field: Field name.
:returns: User input. | [
"Gets",
"user",
"input",
"for",
"given",
"field",
"."
] | train | https://github.com/KenjiTakahashi/td/blob/7311eabc63efe6fe6600687c3026f0837454c2e4/td/main.py#L366-L382 |
KenjiTakahashi/td | td/main.py | Get.get | def get(self, field, value=None):
"""Gets user input for given field and checks if it is valid.
If input is invalid, it will ask the user to enter it again.
Defaults values to empty or :value:.
It does not check validity of parent index. It can only be tested
further down the road, so for now accept anything.
:field: Field name.
:value: Default value to use for field.
:returns: User input.
"""
self.value = value
val = self.input(field)
if field == 'name':
while True:
if val != '':
break
print("Name cannot be empty.")
val = self.input(field)
elif field == 'priority':
if val == '': # Use default priority
return None
while True:
if val in Get.PRIORITIES.values():
break
c, val = val, Get.PRIORITIES.get(val)
if val:
break
print("Unrecognized priority number or name [{}].".format(c))
val = self.input(field)
val = int(val)
return val | python | def get(self, field, value=None):
"""Gets user input for given field and checks if it is valid.
If input is invalid, it will ask the user to enter it again.
Defaults values to empty or :value:.
It does not check validity of parent index. It can only be tested
further down the road, so for now accept anything.
:field: Field name.
:value: Default value to use for field.
:returns: User input.
"""
self.value = value
val = self.input(field)
if field == 'name':
while True:
if val != '':
break
print("Name cannot be empty.")
val = self.input(field)
elif field == 'priority':
if val == '': # Use default priority
return None
while True:
if val in Get.PRIORITIES.values():
break
c, val = val, Get.PRIORITIES.get(val)
if val:
break
print("Unrecognized priority number or name [{}].".format(c))
val = self.input(field)
val = int(val)
return val | [
"def",
"get",
"(",
"self",
",",
"field",
",",
"value",
"=",
"None",
")",
":",
"self",
".",
"value",
"=",
"value",
"val",
"=",
"self",
".",
"input",
"(",
"field",
")",
"if",
"field",
"==",
"'name'",
":",
"while",
"True",
":",
"if",
"val",
"!=",
... | Gets user input for given field and checks if it is valid.
If input is invalid, it will ask the user to enter it again.
Defaults values to empty or :value:.
It does not check validity of parent index. It can only be tested
further down the road, so for now accept anything.
:field: Field name.
:value: Default value to use for field.
:returns: User input. | [
"Gets",
"user",
"input",
"for",
"given",
"field",
"and",
"checks",
"if",
"it",
"is",
"valid",
"."
] | train | https://github.com/KenjiTakahashi/td/blob/7311eabc63efe6fe6600687c3026f0837454c2e4/td/main.py#L384-L418 |
KenjiTakahashi/td | td/main.py | Arg._getPattern | def _getPattern(self, ipattern, done=None):
"""Parses sort pattern.
:ipattern: A pattern to parse.
:done: If :ipattern: refers to done|undone,
use this to indicate proper state.
:returns: A pattern suitable for Model.modify.
"""
if ipattern is None:
return None
if ipattern is True:
if done is not None:
return ([(None, None, done)], {})
# REMEMBER: This False is for sort reverse!
return ([(0, False)], {})
def _getReverse(pm):
return pm == '-'
def _getIndex(k):
try:
return int(k)
except ValueError:
raise InvalidPatternError(k, "Invalid level number")
def _getDone(p):
v = p.split('=')
if len(v) == 2:
try:
return (Model.indexes[v[0]], v[1], done)
except KeyError:
raise InvalidPatternError(v[0], 'Invalid field name')
return (None, v[0], done)
ipattern1 = list()
ipattern2 = dict()
for s in ipattern.split(','):
if done is not None:
v = done
else:
v = _getReverse(s[-1])
k = s.split(':')
if len(k) == 1:
if done is not None:
ipattern1.append(_getDone(k[0]))
continue
ko = k[0][:-1]
try:
if len(k[0]) == 1:
k = 0
else:
k = Model.indexes[ko]
except KeyError:
k = _getIndex(k[0][:-1])
else:
ipattern1.append((k, v))
continue
v = (0, v)
elif len(k) == 2:
try:
if done is not None:
v = _getDone(k[1])
else:
v = (Model.indexes[k[1][:-1]], v)
k = _getIndex(k[0])
except KeyError:
raise InvalidPatternError(k[1][:-1], 'Invalid field name')
else:
raise InvalidPatternError(s, 'Unrecognized token in')
ipattern2.setdefault(k, []).append(v)
return (ipattern1, ipattern2) | python | def _getPattern(self, ipattern, done=None):
"""Parses sort pattern.
:ipattern: A pattern to parse.
:done: If :ipattern: refers to done|undone,
use this to indicate proper state.
:returns: A pattern suitable for Model.modify.
"""
if ipattern is None:
return None
if ipattern is True:
if done is not None:
return ([(None, None, done)], {})
# REMEMBER: This False is for sort reverse!
return ([(0, False)], {})
def _getReverse(pm):
return pm == '-'
def _getIndex(k):
try:
return int(k)
except ValueError:
raise InvalidPatternError(k, "Invalid level number")
def _getDone(p):
v = p.split('=')
if len(v) == 2:
try:
return (Model.indexes[v[0]], v[1], done)
except KeyError:
raise InvalidPatternError(v[0], 'Invalid field name')
return (None, v[0], done)
ipattern1 = list()
ipattern2 = dict()
for s in ipattern.split(','):
if done is not None:
v = done
else:
v = _getReverse(s[-1])
k = s.split(':')
if len(k) == 1:
if done is not None:
ipattern1.append(_getDone(k[0]))
continue
ko = k[0][:-1]
try:
if len(k[0]) == 1:
k = 0
else:
k = Model.indexes[ko]
except KeyError:
k = _getIndex(k[0][:-1])
else:
ipattern1.append((k, v))
continue
v = (0, v)
elif len(k) == 2:
try:
if done is not None:
v = _getDone(k[1])
else:
v = (Model.indexes[k[1][:-1]], v)
k = _getIndex(k[0])
except KeyError:
raise InvalidPatternError(k[1][:-1], 'Invalid field name')
else:
raise InvalidPatternError(s, 'Unrecognized token in')
ipattern2.setdefault(k, []).append(v)
return (ipattern1, ipattern2) | [
"def",
"_getPattern",
"(",
"self",
",",
"ipattern",
",",
"done",
"=",
"None",
")",
":",
"if",
"ipattern",
"is",
"None",
":",
"return",
"None",
"if",
"ipattern",
"is",
"True",
":",
"if",
"done",
"is",
"not",
"None",
":",
"return",
"(",
"[",
"(",
"No... | Parses sort pattern.
:ipattern: A pattern to parse.
:done: If :ipattern: refers to done|undone,
use this to indicate proper state.
:returns: A pattern suitable for Model.modify. | [
"Parses",
"sort",
"pattern",
"."
] | train | https://github.com/KenjiTakahashi/td/blob/7311eabc63efe6fe6600687c3026f0837454c2e4/td/main.py#L439-L509 |
KenjiTakahashi/td | td/main.py | Arg._getDone | def _getDone(self, done, undone):
"""Parses the done|undone state.
:done: Done marking pattern.
:undone: Not done marking pattern.
:returns: Pattern for done|undone or None if neither were specified.
"""
if done:
return self._getPattern(done, True)
if undone:
return self._getPattern(undone, False) | python | def _getDone(self, done, undone):
"""Parses the done|undone state.
:done: Done marking pattern.
:undone: Not done marking pattern.
:returns: Pattern for done|undone or None if neither were specified.
"""
if done:
return self._getPattern(done, True)
if undone:
return self._getPattern(undone, False) | [
"def",
"_getDone",
"(",
"self",
",",
"done",
",",
"undone",
")",
":",
"if",
"done",
":",
"return",
"self",
".",
"_getPattern",
"(",
"done",
",",
"True",
")",
"if",
"undone",
":",
"return",
"self",
".",
"_getPattern",
"(",
"undone",
",",
"False",
")"
... | Parses the done|undone state.
:done: Done marking pattern.
:undone: Not done marking pattern.
:returns: Pattern for done|undone or None if neither were specified. | [
"Parses",
"the",
"done|undone",
"state",
"."
] | train | https://github.com/KenjiTakahashi/td/blob/7311eabc63efe6fe6600687c3026f0837454c2e4/td/main.py#L511-L522 |
KenjiTakahashi/td | td/main.py | Arg.view | def view(self, sort=None, purge=False, done=None, undone=None, **kwargs):
"""Handles the 'v' command.
:sort: Sort pattern.
:purge: Whether to purge items marked as 'done'.
:done: Done pattern.
:undone: Not done pattern.
:kwargs: Additional arguments to pass to the View object.
"""
View(self.model.modify(
sort=self._getPattern(sort),
purge=purge,
done=self._getDone(done, undone)
), **kwargs) | python | def view(self, sort=None, purge=False, done=None, undone=None, **kwargs):
"""Handles the 'v' command.
:sort: Sort pattern.
:purge: Whether to purge items marked as 'done'.
:done: Done pattern.
:undone: Not done pattern.
:kwargs: Additional arguments to pass to the View object.
"""
View(self.model.modify(
sort=self._getPattern(sort),
purge=purge,
done=self._getDone(done, undone)
), **kwargs) | [
"def",
"view",
"(",
"self",
",",
"sort",
"=",
"None",
",",
"purge",
"=",
"False",
",",
"done",
"=",
"None",
",",
"undone",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"View",
"(",
"self",
".",
"model",
".",
"modify",
"(",
"sort",
"=",
"self... | Handles the 'v' command.
:sort: Sort pattern.
:purge: Whether to purge items marked as 'done'.
:done: Done pattern.
:undone: Not done pattern.
:kwargs: Additional arguments to pass to the View object. | [
"Handles",
"the",
"v",
"command",
"."
] | train | https://github.com/KenjiTakahashi/td/blob/7311eabc63efe6fe6600687c3026f0837454c2e4/td/main.py#L524-L538 |
KenjiTakahashi/td | td/main.py | Arg.modify | def modify(self, sort=None, purge=False, done=None, undone=None):
"""Handles the 'm' command.
:sort: Sort pattern.
:purge: Whether to purge items marked as 'done'.
:done: Done pattern.
:undone: Not done pattern.
"""
self.model.modifyInPlace(
sort=self._getPattern(sort),
purge=purge,
done=self._getDone(done, undone)
) | python | def modify(self, sort=None, purge=False, done=None, undone=None):
"""Handles the 'm' command.
:sort: Sort pattern.
:purge: Whether to purge items marked as 'done'.
:done: Done pattern.
:undone: Not done pattern.
"""
self.model.modifyInPlace(
sort=self._getPattern(sort),
purge=purge,
done=self._getDone(done, undone)
) | [
"def",
"modify",
"(",
"self",
",",
"sort",
"=",
"None",
",",
"purge",
"=",
"False",
",",
"done",
"=",
"None",
",",
"undone",
"=",
"None",
")",
":",
"self",
".",
"model",
".",
"modifyInPlace",
"(",
"sort",
"=",
"self",
".",
"_getPattern",
"(",
"sort... | Handles the 'm' command.
:sort: Sort pattern.
:purge: Whether to purge items marked as 'done'.
:done: Done pattern.
:undone: Not done pattern. | [
"Handles",
"the",
"m",
"command",
"."
] | train | https://github.com/KenjiTakahashi/td/blob/7311eabc63efe6fe6600687c3026f0837454c2e4/td/main.py#L540-L553 |
KenjiTakahashi/td | td/main.py | Arg.add | def add(self, **args):
"""Handles the 'a' command.
:args: Arguments supplied to the 'a' command.
"""
kwargs = self.getKwargs(args)
if kwargs:
self.model.add(**kwargs) | python | def add(self, **args):
"""Handles the 'a' command.
:args: Arguments supplied to the 'a' command.
"""
kwargs = self.getKwargs(args)
if kwargs:
self.model.add(**kwargs) | [
"def",
"add",
"(",
"self",
",",
"*",
"*",
"args",
")",
":",
"kwargs",
"=",
"self",
".",
"getKwargs",
"(",
"args",
")",
"if",
"kwargs",
":",
"self",
".",
"model",
".",
"add",
"(",
"*",
"*",
"kwargs",
")"
] | Handles the 'a' command.
:args: Arguments supplied to the 'a' command. | [
"Handles",
"the",
"a",
"command",
"."
] | train | https://github.com/KenjiTakahashi/td/blob/7311eabc63efe6fe6600687c3026f0837454c2e4/td/main.py#L555-L563 |
KenjiTakahashi/td | td/main.py | Arg.edit | def edit(self, **args):
"""Handles the 'e' command.
:args: Arguments supplied to the 'e' command.
"""
if self.model.exists(args["index"]):
values = dict(zip(
['parent', 'name', 'priority', 'comment', 'done'],
self.model.get(args["index"])
))
kwargs = self.getKwargs(args, values)
if kwargs:
self.model.edit(args["index"], **kwargs) | python | def edit(self, **args):
"""Handles the 'e' command.
:args: Arguments supplied to the 'e' command.
"""
if self.model.exists(args["index"]):
values = dict(zip(
['parent', 'name', 'priority', 'comment', 'done'],
self.model.get(args["index"])
))
kwargs = self.getKwargs(args, values)
if kwargs:
self.model.edit(args["index"], **kwargs) | [
"def",
"edit",
"(",
"self",
",",
"*",
"*",
"args",
")",
":",
"if",
"self",
".",
"model",
".",
"exists",
"(",
"args",
"[",
"\"index\"",
"]",
")",
":",
"values",
"=",
"dict",
"(",
"zip",
"(",
"[",
"'parent'",
",",
"'name'",
",",
"'priority'",
",",
... | Handles the 'e' command.
:args: Arguments supplied to the 'e' command. | [
"Handles",
"the",
"e",
"command",
"."
] | train | https://github.com/KenjiTakahashi/td/blob/7311eabc63efe6fe6600687c3026f0837454c2e4/td/main.py#L565-L578 |
KenjiTakahashi/td | td/main.py | Arg.rm | def rm(self, index):
"""Handles the 'r' command.
:index: Index of the item to remove.
"""
if self.model.exists(index):
self.model.remove(index) | python | def rm(self, index):
"""Handles the 'r' command.
:index: Index of the item to remove.
"""
if self.model.exists(index):
self.model.remove(index) | [
"def",
"rm",
"(",
"self",
",",
"index",
")",
":",
"if",
"self",
".",
"model",
".",
"exists",
"(",
"index",
")",
":",
"self",
".",
"model",
".",
"remove",
"(",
"index",
")"
] | Handles the 'r' command.
:index: Index of the item to remove. | [
"Handles",
"the",
"r",
"command",
"."
] | train | https://github.com/KenjiTakahashi/td/blob/7311eabc63efe6fe6600687c3026f0837454c2e4/td/main.py#L580-L587 |
KenjiTakahashi/td | td/main.py | Arg.done | def done(self, index):
"""Handles the 'd' command.
:index: Index of the item to mark as done.
"""
if self.model.exists(index):
self.model.edit(index, done=True) | python | def done(self, index):
"""Handles the 'd' command.
:index: Index of the item to mark as done.
"""
if self.model.exists(index):
self.model.edit(index, done=True) | [
"def",
"done",
"(",
"self",
",",
"index",
")",
":",
"if",
"self",
".",
"model",
".",
"exists",
"(",
"index",
")",
":",
"self",
".",
"model",
".",
"edit",
"(",
"index",
",",
"done",
"=",
"True",
")"
] | Handles the 'd' command.
:index: Index of the item to mark as done. | [
"Handles",
"the",
"d",
"command",
"."
] | train | https://github.com/KenjiTakahashi/td/blob/7311eabc63efe6fe6600687c3026f0837454c2e4/td/main.py#L589-L596 |
KenjiTakahashi/td | td/main.py | Arg.undone | def undone(self, index):
"""Handles the 'D' command.
:index: Index of the item to mark as not done.
"""
if self.model.exists(index):
self.model.edit(index, done=False) | python | def undone(self, index):
"""Handles the 'D' command.
:index: Index of the item to mark as not done.
"""
if self.model.exists(index):
self.model.edit(index, done=False) | [
"def",
"undone",
"(",
"self",
",",
"index",
")",
":",
"if",
"self",
".",
"model",
".",
"exists",
"(",
"index",
")",
":",
"self",
".",
"model",
".",
"edit",
"(",
"index",
",",
"done",
"=",
"False",
")"
] | Handles the 'D' command.
:index: Index of the item to mark as not done. | [
"Handles",
"the",
"D",
"command",
"."
] | train | https://github.com/KenjiTakahashi/td/blob/7311eabc63efe6fe6600687c3026f0837454c2e4/td/main.py#L598-L605 |
KenjiTakahashi/td | td/main.py | Arg.options | def options(self, glob=False, **args):
"""Handles the 'o' command.
:glob: Whether to store specified options globally.
:args: Arguments supplied to the 'o' command (excluding '-g').
"""
kwargs = {}
for argname, argarg in args.items():
if argname == "sort":
argarg = self._getPattern(argarg)
if argname not in ["done", "undone"]:
kwargs[argname] = argarg
if "done" in args or "undone" in args:
kwargs["done"] = self._getDone(
args.get("done"), args.get("undone")
)
self.model.setOptions(glob=glob, **kwargs) | python | def options(self, glob=False, **args):
"""Handles the 'o' command.
:glob: Whether to store specified options globally.
:args: Arguments supplied to the 'o' command (excluding '-g').
"""
kwargs = {}
for argname, argarg in args.items():
if argname == "sort":
argarg = self._getPattern(argarg)
if argname not in ["done", "undone"]:
kwargs[argname] = argarg
if "done" in args or "undone" in args:
kwargs["done"] = self._getDone(
args.get("done"), args.get("undone")
)
self.model.setOptions(glob=glob, **kwargs) | [
"def",
"options",
"(",
"self",
",",
"glob",
"=",
"False",
",",
"*",
"*",
"args",
")",
":",
"kwargs",
"=",
"{",
"}",
"for",
"argname",
",",
"argarg",
"in",
"args",
".",
"items",
"(",
")",
":",
"if",
"argname",
"==",
"\"sort\"",
":",
"argarg",
"=",... | Handles the 'o' command.
:glob: Whether to store specified options globally.
:args: Arguments supplied to the 'o' command (excluding '-g'). | [
"Handles",
"the",
"o",
"command",
"."
] | train | https://github.com/KenjiTakahashi/td/blob/7311eabc63efe6fe6600687c3026f0837454c2e4/td/main.py#L607-L625 |
KenjiTakahashi/td | td/main.py | Arg.getKwargs | def getKwargs(self, args, values={}, get=Get()):
"""Gets necessary data from user input.
:args: Dictionary of arguments supplied in command line.
:values: Default values dictionary, supplied for editing.
:get: Object used to get values from user input.
:returns: A dictionary containing data gathered from user input.
"""
kwargs = dict()
for field in ['name', 'priority', 'comment', 'parent']:
fvalue = args.get(field) or get.get(field, values.get(field))
if fvalue is not None:
kwargs[field] = fvalue
return kwargs | python | def getKwargs(self, args, values={}, get=Get()):
"""Gets necessary data from user input.
:args: Dictionary of arguments supplied in command line.
:values: Default values dictionary, supplied for editing.
:get: Object used to get values from user input.
:returns: A dictionary containing data gathered from user input.
"""
kwargs = dict()
for field in ['name', 'priority', 'comment', 'parent']:
fvalue = args.get(field) or get.get(field, values.get(field))
if fvalue is not None:
kwargs[field] = fvalue
return kwargs | [
"def",
"getKwargs",
"(",
"self",
",",
"args",
",",
"values",
"=",
"{",
"}",
",",
"get",
"=",
"Get",
"(",
")",
")",
":",
"kwargs",
"=",
"dict",
"(",
")",
"for",
"field",
"in",
"[",
"'name'",
",",
"'priority'",
",",
"'comment'",
",",
"'parent'",
"]... | Gets necessary data from user input.
:args: Dictionary of arguments supplied in command line.
:values: Default values dictionary, supplied for editing.
:get: Object used to get values from user input.
:returns: A dictionary containing data gathered from user input. | [
"Gets",
"necessary",
"data",
"from",
"user",
"input",
"."
] | train | https://github.com/KenjiTakahashi/td/blob/7311eabc63efe6fe6600687c3026f0837454c2e4/td/main.py#L627-L641 |
gwastro/pycbc-glue | pycbc_glue/lal.py | CacheEntry.url | def url(self):
"""
The cache entry's URL. The URL is constructed from the
values of the scheme, host, and path attributes. Assigning
a value to the URL attribute causes the value to be parsed
and the scheme, host and path attributes updated.
"""
return urlparse.urlunparse((self.scheme, self.host, self.path, None, None, None)) | python | def url(self):
"""
The cache entry's URL. The URL is constructed from the
values of the scheme, host, and path attributes. Assigning
a value to the URL attribute causes the value to be parsed
and the scheme, host and path attributes updated.
"""
return urlparse.urlunparse((self.scheme, self.host, self.path, None, None, None)) | [
"def",
"url",
"(",
"self",
")",
":",
"return",
"urlparse",
".",
"urlunparse",
"(",
"(",
"self",
".",
"scheme",
",",
"self",
".",
"host",
",",
"self",
".",
"path",
",",
"None",
",",
"None",
",",
"None",
")",
")"
] | The cache entry's URL. The URL is constructed from the
values of the scheme, host, and path attributes. Assigning
a value to the URL attribute causes the value to be parsed
and the scheme, host and path attributes updated. | [
"The",
"cache",
"entry",
"s",
"URL",
".",
"The",
"URL",
"is",
"constructed",
"from",
"the",
"values",
"of",
"the",
"scheme",
"host",
"and",
"path",
"attributes",
".",
"Assigning",
"a",
"value",
"to",
"the",
"URL",
"attribute",
"causes",
"the",
"value",
"... | train | https://github.com/gwastro/pycbc-glue/blob/a3e906bae59fbfd707c3ff82e5d008d939ec5e24/pycbc_glue/lal.py#L558-L565 |
gwastro/pycbc-glue | pycbc_glue/lal.py | CacheEntry.segmentlistdict | def segmentlistdict(self):
"""
A segmentlistdict object describing the instruments and
time spanned by this CacheEntry. A new object is
constructed each time this attribute is accessed (segments
are immutable so there is no reason to try to share a
reference to the CacheEntry's internal segment;
modifications of one would not be reflected in the other
anyway).
Example:
>>> c = CacheEntry(u"H1 S5 815901601 576.5 file://localhost/home/kipp/tmp/1/H1-815901601-576.xml")
>>> c.segmentlistdict
{u'H1': [segment(LIGOTimeGPS(815901601, 0), LIGOTimeGPS(815902177, 500000000))]}
The \"observatory\" column of the cache entry, which is
frequently used to store instrument names, is parsed into
instrument names for the dictionary keys using the same
rules as pycbc_glue.ligolw.lsctables.instrument_set_from_ifos().
Example:
>>> c = CacheEntry(u"H1H2, S5 815901601 576.5 file://localhost/home/kipp/tmp/1/H1H2-815901601-576.xml")
>>> c.segmentlistdict
{u'H1H2': [segment(LIGOTimeGPS(815901601, 0), LIGOTimeGPS(815902177, 500000000))]}
"""
# the import has to be done here to break the cyclic
# dependancy
from pycbc_glue.ligolw.lsctables import instrument_set_from_ifos
instruments = instrument_set_from_ifos(self.observatory) or (None,)
return segments.segmentlistdict((instrument, segments.segmentlist(self.segment is not None and [self.segment] or [])) for instrument in instruments) | python | def segmentlistdict(self):
"""
A segmentlistdict object describing the instruments and
time spanned by this CacheEntry. A new object is
constructed each time this attribute is accessed (segments
are immutable so there is no reason to try to share a
reference to the CacheEntry's internal segment;
modifications of one would not be reflected in the other
anyway).
Example:
>>> c = CacheEntry(u"H1 S5 815901601 576.5 file://localhost/home/kipp/tmp/1/H1-815901601-576.xml")
>>> c.segmentlistdict
{u'H1': [segment(LIGOTimeGPS(815901601, 0), LIGOTimeGPS(815902177, 500000000))]}
The \"observatory\" column of the cache entry, which is
frequently used to store instrument names, is parsed into
instrument names for the dictionary keys using the same
rules as pycbc_glue.ligolw.lsctables.instrument_set_from_ifos().
Example:
>>> c = CacheEntry(u"H1H2, S5 815901601 576.5 file://localhost/home/kipp/tmp/1/H1H2-815901601-576.xml")
>>> c.segmentlistdict
{u'H1H2': [segment(LIGOTimeGPS(815901601, 0), LIGOTimeGPS(815902177, 500000000))]}
"""
# the import has to be done here to break the cyclic
# dependancy
from pycbc_glue.ligolw.lsctables import instrument_set_from_ifos
instruments = instrument_set_from_ifos(self.observatory) or (None,)
return segments.segmentlistdict((instrument, segments.segmentlist(self.segment is not None and [self.segment] or [])) for instrument in instruments) | [
"def",
"segmentlistdict",
"(",
"self",
")",
":",
"# the import has to be done here to break the cyclic",
"# dependancy",
"from",
"pycbc_glue",
".",
"ligolw",
".",
"lsctables",
"import",
"instrument_set_from_ifos",
"instruments",
"=",
"instrument_set_from_ifos",
"(",
"self",
... | A segmentlistdict object describing the instruments and
time spanned by this CacheEntry. A new object is
constructed each time this attribute is accessed (segments
are immutable so there is no reason to try to share a
reference to the CacheEntry's internal segment;
modifications of one would not be reflected in the other
anyway).
Example:
>>> c = CacheEntry(u"H1 S5 815901601 576.5 file://localhost/home/kipp/tmp/1/H1-815901601-576.xml")
>>> c.segmentlistdict
{u'H1': [segment(LIGOTimeGPS(815901601, 0), LIGOTimeGPS(815902177, 500000000))]}
The \"observatory\" column of the cache entry, which is
frequently used to store instrument names, is parsed into
instrument names for the dictionary keys using the same
rules as pycbc_glue.ligolw.lsctables.instrument_set_from_ifos().
Example:
>>> c = CacheEntry(u"H1H2, S5 815901601 576.5 file://localhost/home/kipp/tmp/1/H1H2-815901601-576.xml")
>>> c.segmentlistdict
{u'H1H2': [segment(LIGOTimeGPS(815901601, 0), LIGOTimeGPS(815902177, 500000000))]} | [
"A",
"segmentlistdict",
"object",
"describing",
"the",
"instruments",
"and",
"time",
"spanned",
"by",
"this",
"CacheEntry",
".",
"A",
"new",
"object",
"is",
"constructed",
"each",
"time",
"this",
"attribute",
"is",
"accessed",
"(",
"segments",
"are",
"immutable"... | train | https://github.com/gwastro/pycbc-glue/blob/a3e906bae59fbfd707c3ff82e5d008d939ec5e24/pycbc_glue/lal.py#L572-L603 |
gwastro/pycbc-glue | pycbc_glue/lal.py | CacheEntry.from_T050017 | def from_T050017(cls, url, coltype = LIGOTimeGPS):
"""
Parse a URL in the style of T050017-00 into a CacheEntry.
The T050017-00 file name format is, essentially,
observatory-description-start-duration.extension
Example:
>>> c = CacheEntry.from_T050017("file://localhost/data/node144/frames/S5/strain-L2/LLO/L-L1_RDS_C03_L2-8365/L-L1_RDS_C03_L2-836562330-83.gwf")
>>> c.observatory
'L'
>>> c.host
'localhost'
>>> os.path.basename(c.path)
'L-L1_RDS_C03_L2-836562330-83.gwf'
"""
match = cls._url_regex.search(url)
if not match:
raise ValueError("could not convert %s to CacheEntry" % repr(url))
observatory = match.group("obs")
description = match.group("dsc")
start = match.group("strt")
duration = match.group("dur")
if start == "-" and duration == "-":
# no segment information
segment = None
else:
segment = segments.segment(coltype(start), coltype(start) + coltype(duration))
return cls(observatory, description, segment, url) | python | def from_T050017(cls, url, coltype = LIGOTimeGPS):
"""
Parse a URL in the style of T050017-00 into a CacheEntry.
The T050017-00 file name format is, essentially,
observatory-description-start-duration.extension
Example:
>>> c = CacheEntry.from_T050017("file://localhost/data/node144/frames/S5/strain-L2/LLO/L-L1_RDS_C03_L2-8365/L-L1_RDS_C03_L2-836562330-83.gwf")
>>> c.observatory
'L'
>>> c.host
'localhost'
>>> os.path.basename(c.path)
'L-L1_RDS_C03_L2-836562330-83.gwf'
"""
match = cls._url_regex.search(url)
if not match:
raise ValueError("could not convert %s to CacheEntry" % repr(url))
observatory = match.group("obs")
description = match.group("dsc")
start = match.group("strt")
duration = match.group("dur")
if start == "-" and duration == "-":
# no segment information
segment = None
else:
segment = segments.segment(coltype(start), coltype(start) + coltype(duration))
return cls(observatory, description, segment, url) | [
"def",
"from_T050017",
"(",
"cls",
",",
"url",
",",
"coltype",
"=",
"LIGOTimeGPS",
")",
":",
"match",
"=",
"cls",
".",
"_url_regex",
".",
"search",
"(",
"url",
")",
"if",
"not",
"match",
":",
"raise",
"ValueError",
"(",
"\"could not convert %s to CacheEntry\... | Parse a URL in the style of T050017-00 into a CacheEntry.
The T050017-00 file name format is, essentially,
observatory-description-start-duration.extension
Example:
>>> c = CacheEntry.from_T050017("file://localhost/data/node144/frames/S5/strain-L2/LLO/L-L1_RDS_C03_L2-8365/L-L1_RDS_C03_L2-836562330-83.gwf")
>>> c.observatory
'L'
>>> c.host
'localhost'
>>> os.path.basename(c.path)
'L-L1_RDS_C03_L2-836562330-83.gwf' | [
"Parse",
"a",
"URL",
"in",
"the",
"style",
"of",
"T050017",
"-",
"00",
"into",
"a",
"CacheEntry",
".",
"The",
"T050017",
"-",
"00",
"file",
"name",
"format",
"is",
"essentially"
] | train | https://github.com/gwastro/pycbc-glue/blob/a3e906bae59fbfd707c3ff82e5d008d939ec5e24/pycbc_glue/lal.py#L606-L635 |
gwastro/pycbc-glue | pycbc_glue/lal.py | Cache.fromfile | def fromfile(cls, fileobj, coltype=LIGOTimeGPS):
"""
Return a Cache object whose entries are read from an open file.
"""
c = [cls.entry_class(line, coltype=coltype) for line in fileobj]
return cls(c) | python | def fromfile(cls, fileobj, coltype=LIGOTimeGPS):
"""
Return a Cache object whose entries are read from an open file.
"""
c = [cls.entry_class(line, coltype=coltype) for line in fileobj]
return cls(c) | [
"def",
"fromfile",
"(",
"cls",
",",
"fileobj",
",",
"coltype",
"=",
"LIGOTimeGPS",
")",
":",
"c",
"=",
"[",
"cls",
".",
"entry_class",
"(",
"line",
",",
"coltype",
"=",
"coltype",
")",
"for",
"line",
"in",
"fileobj",
"]",
"return",
"cls",
"(",
"c",
... | Return a Cache object whose entries are read from an open file. | [
"Return",
"a",
"Cache",
"object",
"whose",
"entries",
"are",
"read",
"from",
"an",
"open",
"file",
"."
] | train | https://github.com/gwastro/pycbc-glue/blob/a3e906bae59fbfd707c3ff82e5d008d939ec5e24/pycbc_glue/lal.py#L652-L657 |
gwastro/pycbc-glue | pycbc_glue/lal.py | Cache.fromfilenames | def fromfilenames(cls, filenames, coltype=LIGOTimeGPS):
"""
Read Cache objects from the files named and concatenate the results into a
single Cache.
"""
cache = cls()
for filename in filenames:
cache.extend(cls.fromfile(open(filename), coltype=coltype))
return cache | python | def fromfilenames(cls, filenames, coltype=LIGOTimeGPS):
"""
Read Cache objects from the files named and concatenate the results into a
single Cache.
"""
cache = cls()
for filename in filenames:
cache.extend(cls.fromfile(open(filename), coltype=coltype))
return cache | [
"def",
"fromfilenames",
"(",
"cls",
",",
"filenames",
",",
"coltype",
"=",
"LIGOTimeGPS",
")",
":",
"cache",
"=",
"cls",
"(",
")",
"for",
"filename",
"in",
"filenames",
":",
"cache",
".",
"extend",
"(",
"cls",
".",
"fromfile",
"(",
"open",
"(",
"filena... | Read Cache objects from the files named and concatenate the results into a
single Cache. | [
"Read",
"Cache",
"objects",
"from",
"the",
"files",
"named",
"and",
"concatenate",
"the",
"results",
"into",
"a",
"single",
"Cache",
"."
] | train | https://github.com/gwastro/pycbc-glue/blob/a3e906bae59fbfd707c3ff82e5d008d939ec5e24/pycbc_glue/lal.py#L660-L668 |
gwastro/pycbc-glue | pycbc_glue/lal.py | Cache.from_urls | def from_urls(cls, urllist, coltype=LIGOTimeGPS):
"""
Return a Cache whose entries are inferred from the URLs
in urllist, if possible. PFN lists will also work; for PFNs, the path
will be absolutized and "file://" and "localhost" will be assumed
for the schemes and hosts.
The filenames must be in the format set forth by DASWG in T050017-00.
"""
def pfn_to_url(url):
scheme, host, path, dummy, dummy = urlparse.urlsplit(url)
if scheme == "": path = os.path.abspath(path)
return urlparse.urlunsplit((scheme or "file", host or "localhost",
path, "", ""))
return cls([cls.entry_class.from_T050017(pfn_to_url(f), coltype=coltype) \
for f in urllist]) | python | def from_urls(cls, urllist, coltype=LIGOTimeGPS):
"""
Return a Cache whose entries are inferred from the URLs
in urllist, if possible. PFN lists will also work; for PFNs, the path
will be absolutized and "file://" and "localhost" will be assumed
for the schemes and hosts.
The filenames must be in the format set forth by DASWG in T050017-00.
"""
def pfn_to_url(url):
scheme, host, path, dummy, dummy = urlparse.urlsplit(url)
if scheme == "": path = os.path.abspath(path)
return urlparse.urlunsplit((scheme or "file", host or "localhost",
path, "", ""))
return cls([cls.entry_class.from_T050017(pfn_to_url(f), coltype=coltype) \
for f in urllist]) | [
"def",
"from_urls",
"(",
"cls",
",",
"urllist",
",",
"coltype",
"=",
"LIGOTimeGPS",
")",
":",
"def",
"pfn_to_url",
"(",
"url",
")",
":",
"scheme",
",",
"host",
",",
"path",
",",
"dummy",
",",
"dummy",
"=",
"urlparse",
".",
"urlsplit",
"(",
"url",
")"... | Return a Cache whose entries are inferred from the URLs
in urllist, if possible. PFN lists will also work; for PFNs, the path
will be absolutized and "file://" and "localhost" will be assumed
for the schemes and hosts.
The filenames must be in the format set forth by DASWG in T050017-00. | [
"Return",
"a",
"Cache",
"whose",
"entries",
"are",
"inferred",
"from",
"the",
"URLs",
"in",
"urllist",
"if",
"possible",
".",
"PFN",
"lists",
"will",
"also",
"work",
";",
"for",
"PFNs",
"the",
"path",
"will",
"be",
"absolutized",
"and",
"file",
":",
"//"... | train | https://github.com/gwastro/pycbc-glue/blob/a3e906bae59fbfd707c3ff82e5d008d939ec5e24/pycbc_glue/lal.py#L671-L686 |
gwastro/pycbc-glue | pycbc_glue/lal.py | Cache.unique | def unique(self):
"""
Return a Cache which has every element of self, but without
duplication. Preserve order. Does not hash, so a bit slow.
"""
new = self.__class__([])
for elem in self:
if elem not in new:
new.append(elem)
return new | python | def unique(self):
"""
Return a Cache which has every element of self, but without
duplication. Preserve order. Does not hash, so a bit slow.
"""
new = self.__class__([])
for elem in self:
if elem not in new:
new.append(elem)
return new | [
"def",
"unique",
"(",
"self",
")",
":",
"new",
"=",
"self",
".",
"__class__",
"(",
"[",
"]",
")",
"for",
"elem",
"in",
"self",
":",
"if",
"elem",
"not",
"in",
"new",
":",
"new",
".",
"append",
"(",
"elem",
")",
"return",
"new"
] | Return a Cache which has every element of self, but without
duplication. Preserve order. Does not hash, so a bit slow. | [
"Return",
"a",
"Cache",
"which",
"has",
"every",
"element",
"of",
"self",
"but",
"without",
"duplication",
".",
"Preserve",
"order",
".",
"Does",
"not",
"hash",
"so",
"a",
"bit",
"slow",
"."
] | train | https://github.com/gwastro/pycbc-glue/blob/a3e906bae59fbfd707c3ff82e5d008d939ec5e24/pycbc_glue/lal.py#L735-L744 |
gwastro/pycbc-glue | pycbc_glue/lal.py | Cache.tofile | def tofile(self, fileobj):
"""
write a cache object to the fileobj as a lal cache file
"""
for entry in self:
print >>fileobj, str(entry)
fileobj.close() | python | def tofile(self, fileobj):
"""
write a cache object to the fileobj as a lal cache file
"""
for entry in self:
print >>fileobj, str(entry)
fileobj.close() | [
"def",
"tofile",
"(",
"self",
",",
"fileobj",
")",
":",
"for",
"entry",
"in",
"self",
":",
"print",
">>",
"fileobj",
",",
"str",
"(",
"entry",
")",
"fileobj",
".",
"close",
"(",
")"
] | write a cache object to the fileobj as a lal cache file | [
"write",
"a",
"cache",
"object",
"to",
"the",
"fileobj",
"as",
"a",
"lal",
"cache",
"file"
] | train | https://github.com/gwastro/pycbc-glue/blob/a3e906bae59fbfd707c3ff82e5d008d939ec5e24/pycbc_glue/lal.py#L747-L753 |
gwastro/pycbc-glue | pycbc_glue/lal.py | Cache.topfnfile | def topfnfile(self, fileobj):
"""
write a cache object to filename as a plain text pfn file
"""
for entry in self:
print >>fileobj, entry.path
fileobj.close() | python | def topfnfile(self, fileobj):
"""
write a cache object to filename as a plain text pfn file
"""
for entry in self:
print >>fileobj, entry.path
fileobj.close() | [
"def",
"topfnfile",
"(",
"self",
",",
"fileobj",
")",
":",
"for",
"entry",
"in",
"self",
":",
"print",
">>",
"fileobj",
",",
"entry",
".",
"path",
"fileobj",
".",
"close",
"(",
")"
] | write a cache object to filename as a plain text pfn file | [
"write",
"a",
"cache",
"object",
"to",
"filename",
"as",
"a",
"plain",
"text",
"pfn",
"file"
] | train | https://github.com/gwastro/pycbc-glue/blob/a3e906bae59fbfd707c3ff82e5d008d939ec5e24/pycbc_glue/lal.py#L755-L761 |
gwastro/pycbc-glue | pycbc_glue/lal.py | Cache.to_segmentlistdict | def to_segmentlistdict(self):
"""
Return a segmentlistdict object describing the instruments
and times spanned by the entries in this Cache. The return
value is coalesced.
"""
d = segments.segmentlistdict()
for entry in self:
d |= entry.segmentlistdict
return d | python | def to_segmentlistdict(self):
"""
Return a segmentlistdict object describing the instruments
and times spanned by the entries in this Cache. The return
value is coalesced.
"""
d = segments.segmentlistdict()
for entry in self:
d |= entry.segmentlistdict
return d | [
"def",
"to_segmentlistdict",
"(",
"self",
")",
":",
"d",
"=",
"segments",
".",
"segmentlistdict",
"(",
")",
"for",
"entry",
"in",
"self",
":",
"d",
"|=",
"entry",
".",
"segmentlistdict",
"return",
"d"
] | Return a segmentlistdict object describing the instruments
and times spanned by the entries in this Cache. The return
value is coalesced. | [
"Return",
"a",
"segmentlistdict",
"object",
"describing",
"the",
"instruments",
"and",
"times",
"spanned",
"by",
"the",
"entries",
"in",
"this",
"Cache",
".",
"The",
"return",
"value",
"is",
"coalesced",
"."
] | train | https://github.com/gwastro/pycbc-glue/blob/a3e906bae59fbfd707c3ff82e5d008d939ec5e24/pycbc_glue/lal.py#L763-L772 |
gwastro/pycbc-glue | pycbc_glue/lal.py | Cache.sieve | def sieve(self, ifos=None, description=None, segment=None,
segmentlist=None, exact_match=False):
"""
Return a Cache object with those CacheEntries that
contain the given patterns (or overlap, in the case of
segment or segmentlist). If exact_match is True, then
non-None ifos, description, and segment patterns must
match exactly, and a non-None segmentlist must contain
a segment which matches exactly).
It makes little sense to specify both segment and
segmentlist arguments, but it is not prohibited.
Bash-style wildcards (*?) are allowed for ifos and description.
"""
if exact_match:
segment_func = lambda e: e.segment == segment
segmentlist_func = lambda e: e.segment in segmentlist
else:
if ifos is not None: ifos = "*" + ifos + "*"
if description is not None: description = "*" + description + "*"
segment_func = lambda e: segment.intersects(e.segment)
segmentlist_func = lambda e: segmentlist.intersects_segment(e.segment)
c = self
if ifos is not None:
ifos_regexp = re.compile(fnmatch.translate(ifos))
c = [entry for entry in c if ifos_regexp.match(entry.observatory) is not None]
if description is not None:
descr_regexp = re.compile(fnmatch.translate(description))
c = [entry for entry in c if descr_regexp.match(entry.description) is not None]
if segment is not None:
c = [entry for entry in c if segment_func(entry)]
if segmentlist is not None:
# must coalesce for intersects_segment() to work
segmentlist.coalesce()
c = [entry for entry in c if segmentlist_func(entry)]
return self.__class__(c) | python | def sieve(self, ifos=None, description=None, segment=None,
segmentlist=None, exact_match=False):
"""
Return a Cache object with those CacheEntries that
contain the given patterns (or overlap, in the case of
segment or segmentlist). If exact_match is True, then
non-None ifos, description, and segment patterns must
match exactly, and a non-None segmentlist must contain
a segment which matches exactly).
It makes little sense to specify both segment and
segmentlist arguments, but it is not prohibited.
Bash-style wildcards (*?) are allowed for ifos and description.
"""
if exact_match:
segment_func = lambda e: e.segment == segment
segmentlist_func = lambda e: e.segment in segmentlist
else:
if ifos is not None: ifos = "*" + ifos + "*"
if description is not None: description = "*" + description + "*"
segment_func = lambda e: segment.intersects(e.segment)
segmentlist_func = lambda e: segmentlist.intersects_segment(e.segment)
c = self
if ifos is not None:
ifos_regexp = re.compile(fnmatch.translate(ifos))
c = [entry for entry in c if ifos_regexp.match(entry.observatory) is not None]
if description is not None:
descr_regexp = re.compile(fnmatch.translate(description))
c = [entry for entry in c if descr_regexp.match(entry.description) is not None]
if segment is not None:
c = [entry for entry in c if segment_func(entry)]
if segmentlist is not None:
# must coalesce for intersects_segment() to work
segmentlist.coalesce()
c = [entry for entry in c if segmentlist_func(entry)]
return self.__class__(c) | [
"def",
"sieve",
"(",
"self",
",",
"ifos",
"=",
"None",
",",
"description",
"=",
"None",
",",
"segment",
"=",
"None",
",",
"segmentlist",
"=",
"None",
",",
"exact_match",
"=",
"False",
")",
":",
"if",
"exact_match",
":",
"segment_func",
"=",
"lambda",
"... | Return a Cache object with those CacheEntries that
contain the given patterns (or overlap, in the case of
segment or segmentlist). If exact_match is True, then
non-None ifos, description, and segment patterns must
match exactly, and a non-None segmentlist must contain
a segment which matches exactly).
It makes little sense to specify both segment and
segmentlist arguments, but it is not prohibited.
Bash-style wildcards (*?) are allowed for ifos and description. | [
"Return",
"a",
"Cache",
"object",
"with",
"those",
"CacheEntries",
"that",
"contain",
"the",
"given",
"patterns",
"(",
"or",
"overlap",
"in",
"the",
"case",
"of",
"segment",
"or",
"segmentlist",
")",
".",
"If",
"exact_match",
"is",
"True",
"then",
"non",
"... | train | https://github.com/gwastro/pycbc-glue/blob/a3e906bae59fbfd707c3ff82e5d008d939ec5e24/pycbc_glue/lal.py#L774-L816 |
gwastro/pycbc-glue | pycbc_glue/lal.py | Cache.checkfilesexist | def checkfilesexist(self, on_missing="warn"):
'''
Runs through the entries of the Cache() object and checks each entry
if the file which it points to exists or not. If the file does exist then
it adds the entry to the Cache() object containing found files, otherwise it
adds the entry to the Cache() object containing all entries that are missing.
It returns both in the follwing order: Cache_Found, Cache_Missed.
Pass on_missing to control how missing files are handled:
"warn": print a warning message saying how many files
are missing out of the total checked.
"error": raise an exception if any are missing
"ignore": do nothing
'''
if on_missing not in ("warn", "error", "ignore"):
raise ValueError("on_missing must be \"warn\", \"error\", or \"ignore\".")
c_found = []
c_missed = []
for entry in self:
if os.path.isfile(entry.path):
c_found.append(entry)
else:
c_missed.append(entry)
if len(c_missed) > 0:
msg = "%d of %d files in the cache were not found "\
"on disk" % (len(c_missed), len(self))
if on_missing == "warn":
print >>sys.stderr, "warning: " + msg
elif on_missing == "error":
raise ValueError(msg)
elif on_missing == "ignore":
pass
else:
raise ValueError("Why am I here? "\
"Please file a bug report!")
return self.__class__(c_found), self.__class__(c_missed) | python | def checkfilesexist(self, on_missing="warn"):
'''
Runs through the entries of the Cache() object and checks each entry
if the file which it points to exists or not. If the file does exist then
it adds the entry to the Cache() object containing found files, otherwise it
adds the entry to the Cache() object containing all entries that are missing.
It returns both in the follwing order: Cache_Found, Cache_Missed.
Pass on_missing to control how missing files are handled:
"warn": print a warning message saying how many files
are missing out of the total checked.
"error": raise an exception if any are missing
"ignore": do nothing
'''
if on_missing not in ("warn", "error", "ignore"):
raise ValueError("on_missing must be \"warn\", \"error\", or \"ignore\".")
c_found = []
c_missed = []
for entry in self:
if os.path.isfile(entry.path):
c_found.append(entry)
else:
c_missed.append(entry)
if len(c_missed) > 0:
msg = "%d of %d files in the cache were not found "\
"on disk" % (len(c_missed), len(self))
if on_missing == "warn":
print >>sys.stderr, "warning: " + msg
elif on_missing == "error":
raise ValueError(msg)
elif on_missing == "ignore":
pass
else:
raise ValueError("Why am I here? "\
"Please file a bug report!")
return self.__class__(c_found), self.__class__(c_missed) | [
"def",
"checkfilesexist",
"(",
"self",
",",
"on_missing",
"=",
"\"warn\"",
")",
":",
"if",
"on_missing",
"not",
"in",
"(",
"\"warn\"",
",",
"\"error\"",
",",
"\"ignore\"",
")",
":",
"raise",
"ValueError",
"(",
"\"on_missing must be \\\"warn\\\", \\\"error\\\", or \\... | Runs through the entries of the Cache() object and checks each entry
if the file which it points to exists or not. If the file does exist then
it adds the entry to the Cache() object containing found files, otherwise it
adds the entry to the Cache() object containing all entries that are missing.
It returns both in the follwing order: Cache_Found, Cache_Missed.
Pass on_missing to control how missing files are handled:
"warn": print a warning message saying how many files
are missing out of the total checked.
"error": raise an exception if any are missing
"ignore": do nothing | [
"Runs",
"through",
"the",
"entries",
"of",
"the",
"Cache",
"()",
"object",
"and",
"checks",
"each",
"entry",
"if",
"the",
"file",
"which",
"it",
"points",
"to",
"exists",
"or",
"not",
".",
"If",
"the",
"file",
"does",
"exist",
"then",
"it",
"adds",
"th... | train | https://github.com/gwastro/pycbc-glue/blob/a3e906bae59fbfd707c3ff82e5d008d939ec5e24/pycbc_glue/lal.py#L824-L861 |
gwastro/pycbc-glue | pycbc_glue/ligolw/ilwd.py | get_ilwdchar_class | def get_ilwdchar_class(tbl_name, col_name, namespace = globals()):
"""
Searches this module's namespace for a subclass of _ilwd.ilwdchar
whose table_name and column_name attributes match those provided.
If a matching subclass is found it is returned; otherwise a new
class is defined, added to this module's namespace, and returned.
Example:
>>> process_id = get_ilwdchar_class("process", "process_id")
>>> x = process_id(10)
>>> str(type(x))
"<class 'pycbc_glue.ligolw.ilwd.process_process_id_class'>"
>>> str(x)
'process:process_id:10'
Retrieving and storing the class provides a convenient mechanism
for quickly constructing new ID objects.
Example:
>>> for i in range(10):
... print str(process_id(i))
...
process:process_id:0
process:process_id:1
process:process_id:2
process:process_id:3
process:process_id:4
process:process_id:5
process:process_id:6
process:process_id:7
process:process_id:8
process:process_id:9
"""
#
# if the class already exists, retrieve and return it
#
key = (str(tbl_name), str(col_name))
cls_name = "%s_%s_class" % key
assert cls_name != "get_ilwdchar_class"
try:
return namespace[cls_name]
except KeyError:
pass
#
# otherwise define a new class, and add it to the cache
#
class new_class(_ilwd.ilwdchar):
__slots__ = ()
table_name, column_name = key
index_offset = len("%s:%s:" % key)
new_class.__name__ = cls_name
namespace[cls_name] = new_class
#
# pickle support
#
copy_reg.pickle(new_class, lambda x: (ilwdchar, (unicode(x),)))
#
# return the new class
#
return new_class | python | def get_ilwdchar_class(tbl_name, col_name, namespace = globals()):
"""
Searches this module's namespace for a subclass of _ilwd.ilwdchar
whose table_name and column_name attributes match those provided.
If a matching subclass is found it is returned; otherwise a new
class is defined, added to this module's namespace, and returned.
Example:
>>> process_id = get_ilwdchar_class("process", "process_id")
>>> x = process_id(10)
>>> str(type(x))
"<class 'pycbc_glue.ligolw.ilwd.process_process_id_class'>"
>>> str(x)
'process:process_id:10'
Retrieving and storing the class provides a convenient mechanism
for quickly constructing new ID objects.
Example:
>>> for i in range(10):
... print str(process_id(i))
...
process:process_id:0
process:process_id:1
process:process_id:2
process:process_id:3
process:process_id:4
process:process_id:5
process:process_id:6
process:process_id:7
process:process_id:8
process:process_id:9
"""
#
# if the class already exists, retrieve and return it
#
key = (str(tbl_name), str(col_name))
cls_name = "%s_%s_class" % key
assert cls_name != "get_ilwdchar_class"
try:
return namespace[cls_name]
except KeyError:
pass
#
# otherwise define a new class, and add it to the cache
#
class new_class(_ilwd.ilwdchar):
__slots__ = ()
table_name, column_name = key
index_offset = len("%s:%s:" % key)
new_class.__name__ = cls_name
namespace[cls_name] = new_class
#
# pickle support
#
copy_reg.pickle(new_class, lambda x: (ilwdchar, (unicode(x),)))
#
# return the new class
#
return new_class | [
"def",
"get_ilwdchar_class",
"(",
"tbl_name",
",",
"col_name",
",",
"namespace",
"=",
"globals",
"(",
")",
")",
":",
"#",
"# if the class already exists, retrieve and return it",
"#",
"key",
"=",
"(",
"str",
"(",
"tbl_name",
")",
",",
"str",
"(",
"col_name",
"... | Searches this module's namespace for a subclass of _ilwd.ilwdchar
whose table_name and column_name attributes match those provided.
If a matching subclass is found it is returned; otherwise a new
class is defined, added to this module's namespace, and returned.
Example:
>>> process_id = get_ilwdchar_class("process", "process_id")
>>> x = process_id(10)
>>> str(type(x))
"<class 'pycbc_glue.ligolw.ilwd.process_process_id_class'>"
>>> str(x)
'process:process_id:10'
Retrieving and storing the class provides a convenient mechanism
for quickly constructing new ID objects.
Example:
>>> for i in range(10):
... print str(process_id(i))
...
process:process_id:0
process:process_id:1
process:process_id:2
process:process_id:3
process:process_id:4
process:process_id:5
process:process_id:6
process:process_id:7
process:process_id:8
process:process_id:9 | [
"Searches",
"this",
"module",
"s",
"namespace",
"for",
"a",
"subclass",
"of",
"_ilwd",
".",
"ilwdchar",
"whose",
"table_name",
"and",
"column_name",
"attributes",
"match",
"those",
"provided",
".",
"If",
"a",
"matching",
"subclass",
"is",
"found",
"it",
"is",
... | train | https://github.com/gwastro/pycbc-glue/blob/a3e906bae59fbfd707c3ff82e5d008d939ec5e24/pycbc_glue/ligolw/ilwd.py#L157-L227 |
gwastro/pycbc-glue | pycbc_glue/ligolw/utils/process.py | get_username | def get_username():
"""
Try to retrieve the username from a variety of sources. First the
environment variable LOGNAME is tried, if that is not set the
environment variable USERNAME is tried, if that is not set the
password database is consulted (only on Unix systems, if the import
of the pwd module succeeds), finally if that fails KeyError is
raised.
"""
try:
return os.environ["LOGNAME"]
except KeyError:
pass
try:
return os.environ["USERNAME"]
except KeyError:
pass
try:
import pwd
return pwd.getpwuid(os.getuid())[0]
except (ImportError, KeyError):
raise KeyError | python | def get_username():
"""
Try to retrieve the username from a variety of sources. First the
environment variable LOGNAME is tried, if that is not set the
environment variable USERNAME is tried, if that is not set the
password database is consulted (only on Unix systems, if the import
of the pwd module succeeds), finally if that fails KeyError is
raised.
"""
try:
return os.environ["LOGNAME"]
except KeyError:
pass
try:
return os.environ["USERNAME"]
except KeyError:
pass
try:
import pwd
return pwd.getpwuid(os.getuid())[0]
except (ImportError, KeyError):
raise KeyError | [
"def",
"get_username",
"(",
")",
":",
"try",
":",
"return",
"os",
".",
"environ",
"[",
"\"LOGNAME\"",
"]",
"except",
"KeyError",
":",
"pass",
"try",
":",
"return",
"os",
".",
"environ",
"[",
"\"USERNAME\"",
"]",
"except",
"KeyError",
":",
"pass",
"try",
... | Try to retrieve the username from a variety of sources. First the
environment variable LOGNAME is tried, if that is not set the
environment variable USERNAME is tried, if that is not set the
password database is consulted (only on Unix systems, if the import
of the pwd module succeeds), finally if that fails KeyError is
raised. | [
"Try",
"to",
"retrieve",
"the",
"username",
"from",
"a",
"variety",
"of",
"sources",
".",
"First",
"the",
"environment",
"variable",
"LOGNAME",
"is",
"tried",
"if",
"that",
"is",
"not",
"set",
"the",
"environment",
"variable",
"USERNAME",
"is",
"tried",
"if"... | train | https://github.com/gwastro/pycbc-glue/blob/a3e906bae59fbfd707c3ff82e5d008d939ec5e24/pycbc_glue/ligolw/utils/process.py#L68-L89 |
gwastro/pycbc-glue | pycbc_glue/ligolw/utils/process.py | append_process | def append_process(xmldoc, program = None, version = None, cvs_repository = None, cvs_entry_time = None, comment = None, is_online = False, jobid = 0, domain = None, ifos = None):
"""
Add an entry to the process table in xmldoc. program, version,
cvs_repository, comment, and domain should all be strings or
unicodes. cvs_entry_time should be a string or unicode in the
format "YYYY/MM/DD HH:MM:SS". is_online should be a boolean, jobid
an integer. ifos should be an iterable (set, tuple, etc.) of
instrument names.
See also register_to_xmldoc().
"""
try:
proctable = lsctables.ProcessTable.get_table(xmldoc)
except ValueError:
proctable = lsctables.New(lsctables.ProcessTable)
xmldoc.childNodes[0].appendChild(proctable)
proctable.sync_next_id()
process = proctable.RowType()
process.program = program
process.version = version
process.cvs_repository = cvs_repository
# FIXME: remove the "" case when the git versioning business is
# sorted out
if cvs_entry_time is not None and cvs_entry_time != "":
try:
# try the git_version format first
process.cvs_entry_time = _UTCToGPS(time.strptime(cvs_entry_time, "%Y-%m-%d %H:%M:%S +0000"))
except ValueError:
# fall back to the old cvs format
process.cvs_entry_time = _UTCToGPS(time.strptime(cvs_entry_time, "%Y/%m/%d %H:%M:%S"))
else:
process.cvs_entry_time = None
process.comment = comment
process.is_online = int(is_online)
process.node = socket.gethostname()
try:
process.username = get_username()
except KeyError:
process.username = None
process.unix_procid = os.getpid()
process.start_time = _UTCToGPS(time.gmtime())
process.end_time = None
process.jobid = jobid
process.domain = domain
process.instruments = ifos
process.process_id = proctable.get_next_id()
proctable.append(process)
return process | python | def append_process(xmldoc, program = None, version = None, cvs_repository = None, cvs_entry_time = None, comment = None, is_online = False, jobid = 0, domain = None, ifos = None):
"""
Add an entry to the process table in xmldoc. program, version,
cvs_repository, comment, and domain should all be strings or
unicodes. cvs_entry_time should be a string or unicode in the
format "YYYY/MM/DD HH:MM:SS". is_online should be a boolean, jobid
an integer. ifos should be an iterable (set, tuple, etc.) of
instrument names.
See also register_to_xmldoc().
"""
try:
proctable = lsctables.ProcessTable.get_table(xmldoc)
except ValueError:
proctable = lsctables.New(lsctables.ProcessTable)
xmldoc.childNodes[0].appendChild(proctable)
proctable.sync_next_id()
process = proctable.RowType()
process.program = program
process.version = version
process.cvs_repository = cvs_repository
# FIXME: remove the "" case when the git versioning business is
# sorted out
if cvs_entry_time is not None and cvs_entry_time != "":
try:
# try the git_version format first
process.cvs_entry_time = _UTCToGPS(time.strptime(cvs_entry_time, "%Y-%m-%d %H:%M:%S +0000"))
except ValueError:
# fall back to the old cvs format
process.cvs_entry_time = _UTCToGPS(time.strptime(cvs_entry_time, "%Y/%m/%d %H:%M:%S"))
else:
process.cvs_entry_time = None
process.comment = comment
process.is_online = int(is_online)
process.node = socket.gethostname()
try:
process.username = get_username()
except KeyError:
process.username = None
process.unix_procid = os.getpid()
process.start_time = _UTCToGPS(time.gmtime())
process.end_time = None
process.jobid = jobid
process.domain = domain
process.instruments = ifos
process.process_id = proctable.get_next_id()
proctable.append(process)
return process | [
"def",
"append_process",
"(",
"xmldoc",
",",
"program",
"=",
"None",
",",
"version",
"=",
"None",
",",
"cvs_repository",
"=",
"None",
",",
"cvs_entry_time",
"=",
"None",
",",
"comment",
"=",
"None",
",",
"is_online",
"=",
"False",
",",
"jobid",
"=",
"0",... | Add an entry to the process table in xmldoc. program, version,
cvs_repository, comment, and domain should all be strings or
unicodes. cvs_entry_time should be a string or unicode in the
format "YYYY/MM/DD HH:MM:SS". is_online should be a boolean, jobid
an integer. ifos should be an iterable (set, tuple, etc.) of
instrument names.
See also register_to_xmldoc(). | [
"Add",
"an",
"entry",
"to",
"the",
"process",
"table",
"in",
"xmldoc",
".",
"program",
"version",
"cvs_repository",
"comment",
"and",
"domain",
"should",
"all",
"be",
"strings",
"or",
"unicodes",
".",
"cvs_entry_time",
"should",
"be",
"a",
"string",
"or",
"u... | train | https://github.com/gwastro/pycbc-glue/blob/a3e906bae59fbfd707c3ff82e5d008d939ec5e24/pycbc_glue/ligolw/utils/process.py#L92-L141 |
gwastro/pycbc-glue | pycbc_glue/ligolw/utils/process.py | append_process_params | def append_process_params(xmldoc, process, params):
"""
xmldoc is an XML document tree, process is the row in the process
table for which these are the parameters, and params is a list of
(name, type, value) tuples one for each parameter.
See also process_params_from_dict(), register_to_xmldoc().
"""
try:
paramtable = lsctables.ProcessParamsTable.get_table(xmldoc)
except ValueError:
paramtable = lsctables.New(lsctables.ProcessParamsTable)
xmldoc.childNodes[0].appendChild(paramtable)
for name, typ, value in params:
row = paramtable.RowType()
row.program = process.program
row.process_id = process.process_id
row.param = unicode(name)
if typ is not None:
row.type = unicode(typ)
if row.type not in ligolwtypes.Types:
raise ValueError("invalid type '%s' for parameter '%s'" % (row.type, row.param))
else:
row.type = None
if value is not None:
row.value = unicode(value)
else:
row.value = None
paramtable.append(row)
return process | python | def append_process_params(xmldoc, process, params):
"""
xmldoc is an XML document tree, process is the row in the process
table for which these are the parameters, and params is a list of
(name, type, value) tuples one for each parameter.
See also process_params_from_dict(), register_to_xmldoc().
"""
try:
paramtable = lsctables.ProcessParamsTable.get_table(xmldoc)
except ValueError:
paramtable = lsctables.New(lsctables.ProcessParamsTable)
xmldoc.childNodes[0].appendChild(paramtable)
for name, typ, value in params:
row = paramtable.RowType()
row.program = process.program
row.process_id = process.process_id
row.param = unicode(name)
if typ is not None:
row.type = unicode(typ)
if row.type not in ligolwtypes.Types:
raise ValueError("invalid type '%s' for parameter '%s'" % (row.type, row.param))
else:
row.type = None
if value is not None:
row.value = unicode(value)
else:
row.value = None
paramtable.append(row)
return process | [
"def",
"append_process_params",
"(",
"xmldoc",
",",
"process",
",",
"params",
")",
":",
"try",
":",
"paramtable",
"=",
"lsctables",
".",
"ProcessParamsTable",
".",
"get_table",
"(",
"xmldoc",
")",
"except",
"ValueError",
":",
"paramtable",
"=",
"lsctables",
".... | xmldoc is an XML document tree, process is the row in the process
table for which these are the parameters, and params is a list of
(name, type, value) tuples one for each parameter.
See also process_params_from_dict(), register_to_xmldoc(). | [
"xmldoc",
"is",
"an",
"XML",
"document",
"tree",
"process",
"is",
"the",
"row",
"in",
"the",
"process",
"table",
"for",
"which",
"these",
"are",
"the",
"parameters",
"and",
"params",
"is",
"a",
"list",
"of",
"(",
"name",
"type",
"value",
")",
"tuples",
... | train | https://github.com/gwastro/pycbc-glue/blob/a3e906bae59fbfd707c3ff82e5d008d939ec5e24/pycbc_glue/ligolw/utils/process.py#L152-L182 |
gwastro/pycbc-glue | pycbc_glue/ligolw/utils/process.py | get_process_params | def get_process_params(xmldoc, program, param, require_unique_program = True):
"""
Return a list of the values stored in the process_params table for
params named param for the program(s) named program. The values
are returned as Python native types, not as the strings appearing
in the XML document. If require_unique_program is True (default),
then the document must contain exactly one program with the
requested name, otherwise ValueError is raised. If
require_unique_program is not True, then there must be at least one
program with the requested name otherwise ValueError is raised.
"""
process_ids = lsctables.ProcessTable.get_table(xmldoc).get_ids_by_program(program)
if len(process_ids) < 1:
raise ValueError("process table must contain at least one program named '%s'" % program)
elif require_unique_program and len(process_ids) != 1:
raise ValueError("process table must contain exactly one program named '%s'" % program)
return [row.pyvalue for row in lsctables.ProcessParamsTable.get_table(xmldoc) if (row.process_id in process_ids) and (row.param == param)] | python | def get_process_params(xmldoc, program, param, require_unique_program = True):
"""
Return a list of the values stored in the process_params table for
params named param for the program(s) named program. The values
are returned as Python native types, not as the strings appearing
in the XML document. If require_unique_program is True (default),
then the document must contain exactly one program with the
requested name, otherwise ValueError is raised. If
require_unique_program is not True, then there must be at least one
program with the requested name otherwise ValueError is raised.
"""
process_ids = lsctables.ProcessTable.get_table(xmldoc).get_ids_by_program(program)
if len(process_ids) < 1:
raise ValueError("process table must contain at least one program named '%s'" % program)
elif require_unique_program and len(process_ids) != 1:
raise ValueError("process table must contain exactly one program named '%s'" % program)
return [row.pyvalue for row in lsctables.ProcessParamsTable.get_table(xmldoc) if (row.process_id in process_ids) and (row.param == param)] | [
"def",
"get_process_params",
"(",
"xmldoc",
",",
"program",
",",
"param",
",",
"require_unique_program",
"=",
"True",
")",
":",
"process_ids",
"=",
"lsctables",
".",
"ProcessTable",
".",
"get_table",
"(",
"xmldoc",
")",
".",
"get_ids_by_program",
"(",
"program",... | Return a list of the values stored in the process_params table for
params named param for the program(s) named program. The values
are returned as Python native types, not as the strings appearing
in the XML document. If require_unique_program is True (default),
then the document must contain exactly one program with the
requested name, otherwise ValueError is raised. If
require_unique_program is not True, then there must be at least one
program with the requested name otherwise ValueError is raised. | [
"Return",
"a",
"list",
"of",
"the",
"values",
"stored",
"in",
"the",
"process_params",
"table",
"for",
"params",
"named",
"param",
"for",
"the",
"program",
"(",
"s",
")",
"named",
"program",
".",
"The",
"values",
"are",
"returned",
"as",
"Python",
"native"... | train | https://github.com/gwastro/pycbc-glue/blob/a3e906bae59fbfd707c3ff82e5d008d939ec5e24/pycbc_glue/ligolw/utils/process.py#L185-L201 |
gwastro/pycbc-glue | pycbc_glue/ligolw/utils/process.py | doc_includes_process | def doc_includes_process(xmldoc, program):
"""
Return True if the process table in xmldoc includes entries for a
program named program.
"""
return program in lsctables.ProcessTable.get_table(xmldoc).getColumnByName(u"program") | python | def doc_includes_process(xmldoc, program):
"""
Return True if the process table in xmldoc includes entries for a
program named program.
"""
return program in lsctables.ProcessTable.get_table(xmldoc).getColumnByName(u"program") | [
"def",
"doc_includes_process",
"(",
"xmldoc",
",",
"program",
")",
":",
"return",
"program",
"in",
"lsctables",
".",
"ProcessTable",
".",
"get_table",
"(",
"xmldoc",
")",
".",
"getColumnByName",
"(",
"u\"program\"",
")"
] | Return True if the process table in xmldoc includes entries for a
program named program. | [
"Return",
"True",
"if",
"the",
"process",
"table",
"in",
"xmldoc",
"includes",
"entries",
"for",
"a",
"program",
"named",
"program",
"."
] | train | https://github.com/gwastro/pycbc-glue/blob/a3e906bae59fbfd707c3ff82e5d008d939ec5e24/pycbc_glue/ligolw/utils/process.py#L204-L209 |
gwastro/pycbc-glue | pycbc_glue/ligolw/utils/process.py | process_params_from_dict | def process_params_from_dict(paramdict):
"""
Generator function yields (name, type, value) tuples constructed
from a dictionary of name/value pairs. The tuples are suitable for
input to append_process_params(). This is intended as a
convenience for converting command-line options into process_params
rows. The name values in the output have "--" prepended to them
and all "_" characters replaced with "-". The type strings are
guessed from the Python types of the values. If a value is a
Python list (or instance of a subclass thereof), then one tuple is
produced for each of the items in the list.
Example:
>>> list(process_params_from_dict({"verbose": True, "window": 4.0, "include": ["/tmp", "/var/tmp"]}))
[(u'--window', u'real_8', 4.0), (u'--verbose', None, None), (u'--include', u'lstring', '/tmp'), (u'--include', u'lstring', '/var/tmp')]
"""
for name, values in paramdict.items():
# change the name back to the form it had on the command line
name = u"--%s" % name.replace("_", "-")
if values is True or values is False:
yield (name, None, None)
elif values is not None:
if not isinstance(values, list):
values = [values]
for value in values:
yield (name, ligolwtypes.FromPyType[type(value)], value) | python | def process_params_from_dict(paramdict):
"""
Generator function yields (name, type, value) tuples constructed
from a dictionary of name/value pairs. The tuples are suitable for
input to append_process_params(). This is intended as a
convenience for converting command-line options into process_params
rows. The name values in the output have "--" prepended to them
and all "_" characters replaced with "-". The type strings are
guessed from the Python types of the values. If a value is a
Python list (or instance of a subclass thereof), then one tuple is
produced for each of the items in the list.
Example:
>>> list(process_params_from_dict({"verbose": True, "window": 4.0, "include": ["/tmp", "/var/tmp"]}))
[(u'--window', u'real_8', 4.0), (u'--verbose', None, None), (u'--include', u'lstring', '/tmp'), (u'--include', u'lstring', '/var/tmp')]
"""
for name, values in paramdict.items():
# change the name back to the form it had on the command line
name = u"--%s" % name.replace("_", "-")
if values is True or values is False:
yield (name, None, None)
elif values is not None:
if not isinstance(values, list):
values = [values]
for value in values:
yield (name, ligolwtypes.FromPyType[type(value)], value) | [
"def",
"process_params_from_dict",
"(",
"paramdict",
")",
":",
"for",
"name",
",",
"values",
"in",
"paramdict",
".",
"items",
"(",
")",
":",
"# change the name back to the form it had on the command line",
"name",
"=",
"u\"--%s\"",
"%",
"name",
".",
"replace",
"(",
... | Generator function yields (name, type, value) tuples constructed
from a dictionary of name/value pairs. The tuples are suitable for
input to append_process_params(). This is intended as a
convenience for converting command-line options into process_params
rows. The name values in the output have "--" prepended to them
and all "_" characters replaced with "-". The type strings are
guessed from the Python types of the values. If a value is a
Python list (or instance of a subclass thereof), then one tuple is
produced for each of the items in the list.
Example:
>>> list(process_params_from_dict({"verbose": True, "window": 4.0, "include": ["/tmp", "/var/tmp"]}))
[(u'--window', u'real_8', 4.0), (u'--verbose', None, None), (u'--include', u'lstring', '/tmp'), (u'--include', u'lstring', '/var/tmp')] | [
"Generator",
"function",
"yields",
"(",
"name",
"type",
"value",
")",
"tuples",
"constructed",
"from",
"a",
"dictionary",
"of",
"name",
"/",
"value",
"pairs",
".",
"The",
"tuples",
"are",
"suitable",
"for",
"input",
"to",
"append_process_params",
"()",
".",
... | train | https://github.com/gwastro/pycbc-glue/blob/a3e906bae59fbfd707c3ff82e5d008d939ec5e24/pycbc_glue/ligolw/utils/process.py#L212-L239 |
gwastro/pycbc-glue | pycbc_glue/ligolw/utils/process.py | register_to_xmldoc | def register_to_xmldoc(xmldoc, program, paramdict, **kwargs):
"""
Register the current process and params to an XML document.
program is the name of the program. paramdict is a dictionary of
name/value pairs that will be used to populate the process_params
table; see process_params_from_dict() for information on how these
name/value pairs are interpreted. Any additional keyword arguments
are passed to append_process(). Returns the new row from the
process table.
"""
process = append_process(xmldoc, program = program, **kwargs)
append_process_params(xmldoc, process, process_params_from_dict(paramdict))
return process | python | def register_to_xmldoc(xmldoc, program, paramdict, **kwargs):
"""
Register the current process and params to an XML document.
program is the name of the program. paramdict is a dictionary of
name/value pairs that will be used to populate the process_params
table; see process_params_from_dict() for information on how these
name/value pairs are interpreted. Any additional keyword arguments
are passed to append_process(). Returns the new row from the
process table.
"""
process = append_process(xmldoc, program = program, **kwargs)
append_process_params(xmldoc, process, process_params_from_dict(paramdict))
return process | [
"def",
"register_to_xmldoc",
"(",
"xmldoc",
",",
"program",
",",
"paramdict",
",",
"*",
"*",
"kwargs",
")",
":",
"process",
"=",
"append_process",
"(",
"xmldoc",
",",
"program",
"=",
"program",
",",
"*",
"*",
"kwargs",
")",
"append_process_params",
"(",
"x... | Register the current process and params to an XML document.
program is the name of the program. paramdict is a dictionary of
name/value pairs that will be used to populate the process_params
table; see process_params_from_dict() for information on how these
name/value pairs are interpreted. Any additional keyword arguments
are passed to append_process(). Returns the new row from the
process table. | [
"Register",
"the",
"current",
"process",
"and",
"params",
"to",
"an",
"XML",
"document",
".",
"program",
"is",
"the",
"name",
"of",
"the",
"program",
".",
"paramdict",
"is",
"a",
"dictionary",
"of",
"name",
"/",
"value",
"pairs",
"that",
"will",
"be",
"u... | train | https://github.com/gwastro/pycbc-glue/blob/a3e906bae59fbfd707c3ff82e5d008d939ec5e24/pycbc_glue/ligolw/utils/process.py#L242-L254 |
gwastro/pycbc-glue | pycbc_glue/ligolw/utils/process.py | register_to_ldbd | def register_to_ldbd(client, program, paramdict, version = u'0', cvs_repository = u'-', cvs_entry_time = 0, comment = u'-', is_online = False, jobid = 0, domain = None, ifos = u'-'):
"""
Register the current process and params to a database via a
LDBDClient. The program and paramdict arguments and any additional
keyword arguments are the same as those for register_to_xmldoc().
Returns the new row from the process table.
"""
xmldoc = ligolw.Document()
xmldoc.appendChild(ligolw.LIGO_LW())
process = register_to_xmldoc(xmldoc, program, paramdict, version = version, cvs_repository = cvs_repository, cvs_entry_time = cvs_entry_time, comment = comment, is_online = is_online, jobid = jobid, domain = domain, ifos = ifos)
fake_file = StringIO.StringIO()
xmldoc.write(fake_file)
client.insert(fake_file.getvalue())
return process | python | def register_to_ldbd(client, program, paramdict, version = u'0', cvs_repository = u'-', cvs_entry_time = 0, comment = u'-', is_online = False, jobid = 0, domain = None, ifos = u'-'):
"""
Register the current process and params to a database via a
LDBDClient. The program and paramdict arguments and any additional
keyword arguments are the same as those for register_to_xmldoc().
Returns the new row from the process table.
"""
xmldoc = ligolw.Document()
xmldoc.appendChild(ligolw.LIGO_LW())
process = register_to_xmldoc(xmldoc, program, paramdict, version = version, cvs_repository = cvs_repository, cvs_entry_time = cvs_entry_time, comment = comment, is_online = is_online, jobid = jobid, domain = domain, ifos = ifos)
fake_file = StringIO.StringIO()
xmldoc.write(fake_file)
client.insert(fake_file.getvalue())
return process | [
"def",
"register_to_ldbd",
"(",
"client",
",",
"program",
",",
"paramdict",
",",
"version",
"=",
"u'0'",
",",
"cvs_repository",
"=",
"u'-'",
",",
"cvs_entry_time",
"=",
"0",
",",
"comment",
"=",
"u'-'",
",",
"is_online",
"=",
"False",
",",
"jobid",
"=",
... | Register the current process and params to a database via a
LDBDClient. The program and paramdict arguments and any additional
keyword arguments are the same as those for register_to_xmldoc().
Returns the new row from the process table. | [
"Register",
"the",
"current",
"process",
"and",
"params",
"to",
"a",
"database",
"via",
"a",
"LDBDClient",
".",
"The",
"program",
"and",
"paramdict",
"arguments",
"and",
"any",
"additional",
"keyword",
"arguments",
"are",
"the",
"same",
"as",
"those",
"for",
... | train | https://github.com/gwastro/pycbc-glue/blob/a3e906bae59fbfd707c3ff82e5d008d939ec5e24/pycbc_glue/ligolw/utils/process.py#L258-L273 |
ebu/PlugIt | plugit_proxy/templatetags/plugit_tags.py | plugitInclude | def plugitInclude(parser, token):
"""
Load and render a template, using the same context of a specific action.
Example: {% plugitInclude "/menuBar" %}
"""
bits = token.split_contents()
if len(bits) != 2:
raise TemplateSyntaxError("'plugitInclude' tag takes one argument: the tempalte's action to use")
action = parser.compile_filter(bits[1])
return PlugItIncludeNode(action) | python | def plugitInclude(parser, token):
"""
Load and render a template, using the same context of a specific action.
Example: {% plugitInclude "/menuBar" %}
"""
bits = token.split_contents()
if len(bits) != 2:
raise TemplateSyntaxError("'plugitInclude' tag takes one argument: the tempalte's action to use")
action = parser.compile_filter(bits[1])
return PlugItIncludeNode(action) | [
"def",
"plugitInclude",
"(",
"parser",
",",
"token",
")",
":",
"bits",
"=",
"token",
".",
"split_contents",
"(",
")",
"if",
"len",
"(",
"bits",
")",
"!=",
"2",
":",
"raise",
"TemplateSyntaxError",
"(",
"\"'plugitInclude' tag takes one argument: the tempalte's acti... | Load and render a template, using the same context of a specific action.
Example: {% plugitInclude "/menuBar" %} | [
"Load",
"and",
"render",
"a",
"template",
"using",
"the",
"same",
"context",
"of",
"a",
"specific",
"action",
"."
] | train | https://github.com/ebu/PlugIt/blob/de5f1e870f67caaef7a4a58e4bb1ed54d9c5dc53/plugit_proxy/templatetags/plugit_tags.py#L37-L50 |
gwastro/pycbc-glue | pycbc_glue/ligolw/dbtables.py | install_signal_trap | def install_signal_trap(signums = (signal.SIGTERM, signal.SIGTSTP), retval = 1):
"""
Installs a signal handler to erase temporary scratch files when a
signal is received. This can be used to help ensure scratch files
are erased when jobs are evicted by Condor. signums is a squence
of the signals to trap, the default value is a list of the signals
used by Condor to kill and/or evict jobs.
The logic is as follows. If the current signal handler is
signal.SIG_IGN, i.e. the signal is being ignored, then the signal
handler is not modified since the reception of that signal would
not normally cause a scratch file to be leaked. Otherwise a signal
handler is installed that erases the scratch files. If the
original signal handler was a Python callable, then after the
scratch files are erased the original signal handler will be
invoked. If program control returns from that handler, i.e. that
handler does not cause the interpreter to exit, then sys.exit() is
invoked and retval is returned to the shell as the exit code.
Note: by invoking sys.exit(), the signal handler causes the Python
interpreter to do a normal shutdown. That means it invokes
atexit() handlers, and does other garbage collection tasks that it
normally would not do when killed by a signal.
Note: this function will not replace a signal handler more than
once, that is if it has already been used to set a handler
on a signal then it will be a no-op when called again for that
signal until uninstall_signal_trap() is used to remove the handler
from that signal.
Note: this function is called by get_connection_filename()
whenever it creates a scratch file.
"""
# NOTE: this must be called with the temporary_files_lock held.
# ignore signums we've already replaced
signums = set(signums) - set(origactions)
def temporary_file_cleanup_on_signal(signum, frame):
with temporary_files_lock:
temporary_files.clear()
if callable(origactions[signum]):
# original action is callable, chain to it
return origactions[signum](signum, frame)
# original action was not callable or the callable
# returned. invoke sys.exit() with retval as exit code
sys.exit(retval)
for signum in signums:
origactions[signum] = signal.getsignal(signum)
if origactions[signum] != signal.SIG_IGN:
# signal is not being ignored, so install our
# handler
signal.signal(signum, temporary_file_cleanup_on_signal) | python | def install_signal_trap(signums = (signal.SIGTERM, signal.SIGTSTP), retval = 1):
"""
Installs a signal handler to erase temporary scratch files when a
signal is received. This can be used to help ensure scratch files
are erased when jobs are evicted by Condor. signums is a squence
of the signals to trap, the default value is a list of the signals
used by Condor to kill and/or evict jobs.
The logic is as follows. If the current signal handler is
signal.SIG_IGN, i.e. the signal is being ignored, then the signal
handler is not modified since the reception of that signal would
not normally cause a scratch file to be leaked. Otherwise a signal
handler is installed that erases the scratch files. If the
original signal handler was a Python callable, then after the
scratch files are erased the original signal handler will be
invoked. If program control returns from that handler, i.e. that
handler does not cause the interpreter to exit, then sys.exit() is
invoked and retval is returned to the shell as the exit code.
Note: by invoking sys.exit(), the signal handler causes the Python
interpreter to do a normal shutdown. That means it invokes
atexit() handlers, and does other garbage collection tasks that it
normally would not do when killed by a signal.
Note: this function will not replace a signal handler more than
once, that is if it has already been used to set a handler
on a signal then it will be a no-op when called again for that
signal until uninstall_signal_trap() is used to remove the handler
from that signal.
Note: this function is called by get_connection_filename()
whenever it creates a scratch file.
"""
# NOTE: this must be called with the temporary_files_lock held.
# ignore signums we've already replaced
signums = set(signums) - set(origactions)
def temporary_file_cleanup_on_signal(signum, frame):
with temporary_files_lock:
temporary_files.clear()
if callable(origactions[signum]):
# original action is callable, chain to it
return origactions[signum](signum, frame)
# original action was not callable or the callable
# returned. invoke sys.exit() with retval as exit code
sys.exit(retval)
for signum in signums:
origactions[signum] = signal.getsignal(signum)
if origactions[signum] != signal.SIG_IGN:
# signal is not being ignored, so install our
# handler
signal.signal(signum, temporary_file_cleanup_on_signal) | [
"def",
"install_signal_trap",
"(",
"signums",
"=",
"(",
"signal",
".",
"SIGTERM",
",",
"signal",
".",
"SIGTSTP",
")",
",",
"retval",
"=",
"1",
")",
":",
"# NOTE: this must be called with the temporary_files_lock held.",
"# ignore signums we've already replaced",
"signums... | Installs a signal handler to erase temporary scratch files when a
signal is received. This can be used to help ensure scratch files
are erased when jobs are evicted by Condor. signums is a squence
of the signals to trap, the default value is a list of the signals
used by Condor to kill and/or evict jobs.
The logic is as follows. If the current signal handler is
signal.SIG_IGN, i.e. the signal is being ignored, then the signal
handler is not modified since the reception of that signal would
not normally cause a scratch file to be leaked. Otherwise a signal
handler is installed that erases the scratch files. If the
original signal handler was a Python callable, then after the
scratch files are erased the original signal handler will be
invoked. If program control returns from that handler, i.e. that
handler does not cause the interpreter to exit, then sys.exit() is
invoked and retval is returned to the shell as the exit code.
Note: by invoking sys.exit(), the signal handler causes the Python
interpreter to do a normal shutdown. That means it invokes
atexit() handlers, and does other garbage collection tasks that it
normally would not do when killed by a signal.
Note: this function will not replace a signal handler more than
once, that is if it has already been used to set a handler
on a signal then it will be a no-op when called again for that
signal until uninstall_signal_trap() is used to remove the handler
from that signal.
Note: this function is called by get_connection_filename()
whenever it creates a scratch file. | [
"Installs",
"a",
"signal",
"handler",
"to",
"erase",
"temporary",
"scratch",
"files",
"when",
"a",
"signal",
"is",
"received",
".",
"This",
"can",
"be",
"used",
"to",
"help",
"ensure",
"scratch",
"files",
"are",
"erased",
"when",
"jobs",
"are",
"evicted",
... | train | https://github.com/gwastro/pycbc-glue/blob/a3e906bae59fbfd707c3ff82e5d008d939ec5e24/pycbc_glue/ligolw/dbtables.py#L109-L161 |
gwastro/pycbc-glue | pycbc_glue/ligolw/dbtables.py | uninstall_signal_trap | def uninstall_signal_trap(signums = None):
"""
Undo the effects of install_signal_trap(). Restores the original
signal handlers. If signums is a sequence of signal numbers only
the signal handlers for those signals will be restored (KeyError
will be raised if one of them is not one that install_signal_trap()
installed a handler for, in which case some undefined number of
handlers will have been restored). If signums is None (the
default) then all signals that have been modified by previous calls
to install_signal_trap() are restored.
Note: this function is called by put_connection_filename() and
discard_connection_filename() whenever they remove a scratch file
and there are then no more scrach files in use.
"""
# NOTE: this must be called with the temporary_files_lock held.
if signums is None:
signums = origactions.keys()
for signum in signums:
signal.signal(signum, origactions.pop(signum)) | python | def uninstall_signal_trap(signums = None):
"""
Undo the effects of install_signal_trap(). Restores the original
signal handlers. If signums is a sequence of signal numbers only
the signal handlers for those signals will be restored (KeyError
will be raised if one of them is not one that install_signal_trap()
installed a handler for, in which case some undefined number of
handlers will have been restored). If signums is None (the
default) then all signals that have been modified by previous calls
to install_signal_trap() are restored.
Note: this function is called by put_connection_filename() and
discard_connection_filename() whenever they remove a scratch file
and there are then no more scrach files in use.
"""
# NOTE: this must be called with the temporary_files_lock held.
if signums is None:
signums = origactions.keys()
for signum in signums:
signal.signal(signum, origactions.pop(signum)) | [
"def",
"uninstall_signal_trap",
"(",
"signums",
"=",
"None",
")",
":",
"# NOTE: this must be called with the temporary_files_lock held.",
"if",
"signums",
"is",
"None",
":",
"signums",
"=",
"origactions",
".",
"keys",
"(",
")",
"for",
"signum",
"in",
"signums",
":"... | Undo the effects of install_signal_trap(). Restores the original
signal handlers. If signums is a sequence of signal numbers only
the signal handlers for those signals will be restored (KeyError
will be raised if one of them is not one that install_signal_trap()
installed a handler for, in which case some undefined number of
handlers will have been restored). If signums is None (the
default) then all signals that have been modified by previous calls
to install_signal_trap() are restored.
Note: this function is called by put_connection_filename() and
discard_connection_filename() whenever they remove a scratch file
and there are then no more scrach files in use. | [
"Undo",
"the",
"effects",
"of",
"install_signal_trap",
"()",
".",
"Restores",
"the",
"original",
"signal",
"handlers",
".",
"If",
"signums",
"is",
"a",
"sequence",
"of",
"signal",
"numbers",
"only",
"the",
"signal",
"handlers",
"for",
"those",
"signals",
"will... | train | https://github.com/gwastro/pycbc-glue/blob/a3e906bae59fbfd707c3ff82e5d008d939ec5e24/pycbc_glue/ligolw/dbtables.py#L164-L183 |
gwastro/pycbc-glue | pycbc_glue/ligolw/dbtables.py | get_connection_filename | def get_connection_filename(filename, tmp_path = None, replace_file = False, verbose = False):
"""
Utility code for moving database files to a (presumably local)
working location for improved performance and reduced fileserver
load.
"""
def mktmp(path, suffix = ".sqlite", verbose = False):
with temporary_files_lock:
# make sure the clean-up signal traps are installed
install_signal_trap()
# create the remporary file and replace it's
# unlink() function
temporary_file = tempfile.NamedTemporaryFile(suffix = suffix, dir = path if path != "_CONDOR_SCRATCH_DIR" else os.getenv("_CONDOR_SCRATCH_DIR"))
def new_unlink(self, orig_unlink = temporary_file.unlink):
# also remove a -journal partner, ignore all errors
try:
orig_unlink("%s-journal" % self)
except:
pass
orig_unlink(self)
temporary_file.unlink = new_unlink
filename = temporary_file.name
# hang onto reference to prevent its removal
temporary_files[filename] = temporary_file
if verbose:
print >>sys.stderr, "using '%s' as workspace" % filename
# mkstemp() ignores umask, creates all files accessible
# only by owner; we should respect umask. note that
# os.umask() sets it, too, so we have to set it back after
# we know what it is
umsk = os.umask(0777)
os.umask(umsk)
os.chmod(filename, 0666 & ~umsk)
return filename
def truncate(filename, verbose = False):
if verbose:
print >>sys.stderr, "'%s' exists, truncating ..." % filename,
try:
fd = os.open(filename, os.O_WRONLY | os.O_TRUNC)
except Exception as e:
if verbose:
print >>sys.stderr, "cannot truncate '%s': %s" % (filename, str(e))
return
os.close(fd)
if verbose:
print >>sys.stderr, "done."
def cpy(srcname, dstname, verbose = False):
if verbose:
print >>sys.stderr, "copying '%s' to '%s' ..." % (srcname, dstname),
shutil.copy2(srcname, dstname)
if verbose:
print >>sys.stderr, "done."
try:
# try to preserve permission bits. according to
# the documentation, copy() and copy2() are
# supposed preserve them but don't. maybe they
# don't preserve them if the destination file
# already exists?
shutil.copystat(srcname, dstname)
except Exception as e:
if verbose:
print >>sys.stderr, "warning: ignoring failure to copy permission bits from '%s' to '%s': %s" % (filename, target, str(e))
database_exists = os.access(filename, os.F_OK)
if tmp_path is not None:
# for suffix, can't use splitext() because it only keeps
# the last bit, e.g. won't give ".xml.gz" but just ".gz"
target = mktmp(tmp_path, suffix = ".".join(os.path.split(filename)[-1].split(".")[1:]), verbose = verbose)
if database_exists:
if replace_file:
# truncate database so that if this job
# fails the user won't think the database
# file is valid
truncate(filename, verbose = verbose)
else:
# need to copy existing database to work
# space for modifications
i = 1
while True:
try:
cpy(filename, target, verbose = verbose)
except IOError as e:
import errno
import time
if e.errno not in (errno.EPERM, errno.ENOSPC):
# anything other
# than out-of-space
# is a real error
raise
if i < 5:
if verbose:
print >>sys.stderr, "warning: attempt %d: %s, sleeping and trying again ..." % (i, errno.errorcode[e.errno])
time.sleep(10)
i += 1
continue
if verbose:
print >>sys.stderr, "warning: attempt %d: %s: working with original file '%s'" % (i, errno.errorcode[e.errno], filename)
with temporary_files_lock:
del temporary_files[target]
target = filename
break
else:
with temporary_files_lock:
if filename in temporary_files:
raise ValueError("file '%s' appears to be in use already as a temporary database file and is to be deleted" % filename)
target = filename
if database_exists and replace_file:
truncate(target, verbose = verbose)
del mktmp
del truncate
del cpy
return target | python | def get_connection_filename(filename, tmp_path = None, replace_file = False, verbose = False):
"""
Utility code for moving database files to a (presumably local)
working location for improved performance and reduced fileserver
load.
"""
def mktmp(path, suffix = ".sqlite", verbose = False):
with temporary_files_lock:
# make sure the clean-up signal traps are installed
install_signal_trap()
# create the remporary file and replace it's
# unlink() function
temporary_file = tempfile.NamedTemporaryFile(suffix = suffix, dir = path if path != "_CONDOR_SCRATCH_DIR" else os.getenv("_CONDOR_SCRATCH_DIR"))
def new_unlink(self, orig_unlink = temporary_file.unlink):
# also remove a -journal partner, ignore all errors
try:
orig_unlink("%s-journal" % self)
except:
pass
orig_unlink(self)
temporary_file.unlink = new_unlink
filename = temporary_file.name
# hang onto reference to prevent its removal
temporary_files[filename] = temporary_file
if verbose:
print >>sys.stderr, "using '%s' as workspace" % filename
# mkstemp() ignores umask, creates all files accessible
# only by owner; we should respect umask. note that
# os.umask() sets it, too, so we have to set it back after
# we know what it is
umsk = os.umask(0777)
os.umask(umsk)
os.chmod(filename, 0666 & ~umsk)
return filename
def truncate(filename, verbose = False):
if verbose:
print >>sys.stderr, "'%s' exists, truncating ..." % filename,
try:
fd = os.open(filename, os.O_WRONLY | os.O_TRUNC)
except Exception as e:
if verbose:
print >>sys.stderr, "cannot truncate '%s': %s" % (filename, str(e))
return
os.close(fd)
if verbose:
print >>sys.stderr, "done."
def cpy(srcname, dstname, verbose = False):
if verbose:
print >>sys.stderr, "copying '%s' to '%s' ..." % (srcname, dstname),
shutil.copy2(srcname, dstname)
if verbose:
print >>sys.stderr, "done."
try:
# try to preserve permission bits. according to
# the documentation, copy() and copy2() are
# supposed preserve them but don't. maybe they
# don't preserve them if the destination file
# already exists?
shutil.copystat(srcname, dstname)
except Exception as e:
if verbose:
print >>sys.stderr, "warning: ignoring failure to copy permission bits from '%s' to '%s': %s" % (filename, target, str(e))
database_exists = os.access(filename, os.F_OK)
if tmp_path is not None:
# for suffix, can't use splitext() because it only keeps
# the last bit, e.g. won't give ".xml.gz" but just ".gz"
target = mktmp(tmp_path, suffix = ".".join(os.path.split(filename)[-1].split(".")[1:]), verbose = verbose)
if database_exists:
if replace_file:
# truncate database so that if this job
# fails the user won't think the database
# file is valid
truncate(filename, verbose = verbose)
else:
# need to copy existing database to work
# space for modifications
i = 1
while True:
try:
cpy(filename, target, verbose = verbose)
except IOError as e:
import errno
import time
if e.errno not in (errno.EPERM, errno.ENOSPC):
# anything other
# than out-of-space
# is a real error
raise
if i < 5:
if verbose:
print >>sys.stderr, "warning: attempt %d: %s, sleeping and trying again ..." % (i, errno.errorcode[e.errno])
time.sleep(10)
i += 1
continue
if verbose:
print >>sys.stderr, "warning: attempt %d: %s: working with original file '%s'" % (i, errno.errorcode[e.errno], filename)
with temporary_files_lock:
del temporary_files[target]
target = filename
break
else:
with temporary_files_lock:
if filename in temporary_files:
raise ValueError("file '%s' appears to be in use already as a temporary database file and is to be deleted" % filename)
target = filename
if database_exists and replace_file:
truncate(target, verbose = verbose)
del mktmp
del truncate
del cpy
return target | [
"def",
"get_connection_filename",
"(",
"filename",
",",
"tmp_path",
"=",
"None",
",",
"replace_file",
"=",
"False",
",",
"verbose",
"=",
"False",
")",
":",
"def",
"mktmp",
"(",
"path",
",",
"suffix",
"=",
"\".sqlite\"",
",",
"verbose",
"=",
"False",
")",
... | Utility code for moving database files to a (presumably local)
working location for improved performance and reduced fileserver
load. | [
"Utility",
"code",
"for",
"moving",
"database",
"files",
"to",
"a",
"(",
"presumably",
"local",
")",
"working",
"location",
"for",
"improved",
"performance",
"and",
"reduced",
"fileserver",
"load",
"."
] | train | https://github.com/gwastro/pycbc-glue/blob/a3e906bae59fbfd707c3ff82e5d008d939ec5e24/pycbc_glue/ligolw/dbtables.py#L191-L307 |
gwastro/pycbc-glue | pycbc_glue/ligolw/dbtables.py | set_temp_store_directory | def set_temp_store_directory(connection, temp_store_directory, verbose = False):
"""
Sets the temp_store_directory parameter in sqlite.
"""
if temp_store_directory == "_CONDOR_SCRATCH_DIR":
temp_store_directory = os.getenv("_CONDOR_SCRATCH_DIR")
if verbose:
print >>sys.stderr, "setting the temp_store_directory to %s ..." % temp_store_directory,
cursor = connection.cursor()
cursor.execute("PRAGMA temp_store_directory = '%s'" % temp_store_directory)
cursor.close()
if verbose:
print >>sys.stderr, "done" | python | def set_temp_store_directory(connection, temp_store_directory, verbose = False):
"""
Sets the temp_store_directory parameter in sqlite.
"""
if temp_store_directory == "_CONDOR_SCRATCH_DIR":
temp_store_directory = os.getenv("_CONDOR_SCRATCH_DIR")
if verbose:
print >>sys.stderr, "setting the temp_store_directory to %s ..." % temp_store_directory,
cursor = connection.cursor()
cursor.execute("PRAGMA temp_store_directory = '%s'" % temp_store_directory)
cursor.close()
if verbose:
print >>sys.stderr, "done" | [
"def",
"set_temp_store_directory",
"(",
"connection",
",",
"temp_store_directory",
",",
"verbose",
"=",
"False",
")",
":",
"if",
"temp_store_directory",
"==",
"\"_CONDOR_SCRATCH_DIR\"",
":",
"temp_store_directory",
"=",
"os",
".",
"getenv",
"(",
"\"_CONDOR_SCRATCH_DIR\"... | Sets the temp_store_directory parameter in sqlite. | [
"Sets",
"the",
"temp_store_directory",
"parameter",
"in",
"sqlite",
"."
] | train | https://github.com/gwastro/pycbc-glue/blob/a3e906bae59fbfd707c3ff82e5d008d939ec5e24/pycbc_glue/ligolw/dbtables.py#L310-L322 |
gwastro/pycbc-glue | pycbc_glue/ligolw/dbtables.py | put_connection_filename | def put_connection_filename(filename, working_filename, verbose = False):
"""
This function reverses the effect of a previous call to
get_connection_filename(), restoring the working copy to its
original location if the two are different. This function should
always be called after calling get_connection_filename() when the
file is no longer in use.
During the move operation, this function traps the signals used by
Condor to evict jobs. This reduces the risk of corrupting a
document by the job terminating part-way through the restoration of
the file to its original location. When the move operation is
concluded, the original signal handlers are restored and if any
signals were trapped they are resent to the current process in
order. Typically this will result in the signal handlers installed
by the install_signal_trap() function being invoked, meaning any
other scratch files that might be in use get deleted and the
current process is terminated.
"""
if working_filename != filename:
# initialize SIGTERM and SIGTSTP trap
deferred_signals = []
def newsigterm(signum, frame):
deferred_signals.append(signum)
oldhandlers = {}
for sig in (signal.SIGTERM, signal.SIGTSTP):
oldhandlers[sig] = signal.getsignal(sig)
signal.signal(sig, newsigterm)
# replace document
if verbose:
print >>sys.stderr, "moving '%s' to '%s' ..." % (working_filename, filename),
shutil.move(working_filename, filename)
if verbose:
print >>sys.stderr, "done."
# remove reference to tempfile.TemporaryFile object.
# because we've just deleted the file above, this would
# produce an annoying but harmless message about an ignored
# OSError, so we create a dummy file for the TemporaryFile
# to delete. ignore any errors that occur when trying to
# make the dummy file. FIXME: this is stupid, find a
# better way to shut TemporaryFile up
try:
open(working_filename, "w").close()
except:
pass
with temporary_files_lock:
del temporary_files[working_filename]
# restore original handlers, and send ourselves 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))
# if there are no more temporary files in place, remove the
# temporary-file signal traps
with temporary_files_lock:
if not temporary_files:
uninstall_signal_trap() | python | def put_connection_filename(filename, working_filename, verbose = False):
"""
This function reverses the effect of a previous call to
get_connection_filename(), restoring the working copy to its
original location if the two are different. This function should
always be called after calling get_connection_filename() when the
file is no longer in use.
During the move operation, this function traps the signals used by
Condor to evict jobs. This reduces the risk of corrupting a
document by the job terminating part-way through the restoration of
the file to its original location. When the move operation is
concluded, the original signal handlers are restored and if any
signals were trapped they are resent to the current process in
order. Typically this will result in the signal handlers installed
by the install_signal_trap() function being invoked, meaning any
other scratch files that might be in use get deleted and the
current process is terminated.
"""
if working_filename != filename:
# initialize SIGTERM and SIGTSTP trap
deferred_signals = []
def newsigterm(signum, frame):
deferred_signals.append(signum)
oldhandlers = {}
for sig in (signal.SIGTERM, signal.SIGTSTP):
oldhandlers[sig] = signal.getsignal(sig)
signal.signal(sig, newsigterm)
# replace document
if verbose:
print >>sys.stderr, "moving '%s' to '%s' ..." % (working_filename, filename),
shutil.move(working_filename, filename)
if verbose:
print >>sys.stderr, "done."
# remove reference to tempfile.TemporaryFile object.
# because we've just deleted the file above, this would
# produce an annoying but harmless message about an ignored
# OSError, so we create a dummy file for the TemporaryFile
# to delete. ignore any errors that occur when trying to
# make the dummy file. FIXME: this is stupid, find a
# better way to shut TemporaryFile up
try:
open(working_filename, "w").close()
except:
pass
with temporary_files_lock:
del temporary_files[working_filename]
# restore original handlers, and send ourselves 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))
# if there are no more temporary files in place, remove the
# temporary-file signal traps
with temporary_files_lock:
if not temporary_files:
uninstall_signal_trap() | [
"def",
"put_connection_filename",
"(",
"filename",
",",
"working_filename",
",",
"verbose",
"=",
"False",
")",
":",
"if",
"working_filename",
"!=",
"filename",
":",
"# initialize SIGTERM and SIGTSTP trap",
"deferred_signals",
"=",
"[",
"]",
"def",
"newsigterm",
"(",
... | This function reverses the effect of a previous call to
get_connection_filename(), restoring the working copy to its
original location if the two are different. This function should
always be called after calling get_connection_filename() when the
file is no longer in use.
During the move operation, this function traps the signals used by
Condor to evict jobs. This reduces the risk of corrupting a
document by the job terminating part-way through the restoration of
the file to its original location. When the move operation is
concluded, the original signal handlers are restored and if any
signals were trapped they are resent to the current process in
order. Typically this will result in the signal handlers installed
by the install_signal_trap() function being invoked, meaning any
other scratch files that might be in use get deleted and the
current process is terminated. | [
"This",
"function",
"reverses",
"the",
"effect",
"of",
"a",
"previous",
"call",
"to",
"get_connection_filename",
"()",
"restoring",
"the",
"working",
"copy",
"to",
"its",
"original",
"location",
"if",
"the",
"two",
"are",
"different",
".",
"This",
"function",
... | train | https://github.com/gwastro/pycbc-glue/blob/a3e906bae59fbfd707c3ff82e5d008d939ec5e24/pycbc_glue/ligolw/dbtables.py#L325-L386 |
gwastro/pycbc-glue | pycbc_glue/ligolw/dbtables.py | discard_connection_filename | def discard_connection_filename(filename, working_filename, verbose = False):
"""
Like put_connection_filename(), but the working copy is simply
deleted instead of being copied back to its original location.
This is a useful performance boost if it is known that no
modifications were made to the file, for example if queries were
performed but no updates.
Note that the file is not deleted if the working copy and original
file are the same, so it is always safe to call this function after
a call to get_connection_filename() even if a separate working copy
is not created.
"""
if working_filename == filename:
return
with temporary_files_lock:
if verbose:
print >>sys.stderr, "removing '%s' ..." % working_filename,
# remove reference to tempfile.TemporaryFile object
del temporary_files[working_filename]
if verbose:
print >>sys.stderr, "done."
# if there are no more temporary files in place, remove the
# temporary-file signal traps
if not temporary_files:
uninstall_signal_trap() | python | def discard_connection_filename(filename, working_filename, verbose = False):
"""
Like put_connection_filename(), but the working copy is simply
deleted instead of being copied back to its original location.
This is a useful performance boost if it is known that no
modifications were made to the file, for example if queries were
performed but no updates.
Note that the file is not deleted if the working copy and original
file are the same, so it is always safe to call this function after
a call to get_connection_filename() even if a separate working copy
is not created.
"""
if working_filename == filename:
return
with temporary_files_lock:
if verbose:
print >>sys.stderr, "removing '%s' ..." % working_filename,
# remove reference to tempfile.TemporaryFile object
del temporary_files[working_filename]
if verbose:
print >>sys.stderr, "done."
# if there are no more temporary files in place, remove the
# temporary-file signal traps
if not temporary_files:
uninstall_signal_trap() | [
"def",
"discard_connection_filename",
"(",
"filename",
",",
"working_filename",
",",
"verbose",
"=",
"False",
")",
":",
"if",
"working_filename",
"==",
"filename",
":",
"return",
"with",
"temporary_files_lock",
":",
"if",
"verbose",
":",
"print",
">>",
"sys",
".... | Like put_connection_filename(), but the working copy is simply
deleted instead of being copied back to its original location.
This is a useful performance boost if it is known that no
modifications were made to the file, for example if queries were
performed but no updates.
Note that the file is not deleted if the working copy and original
file are the same, so it is always safe to call this function after
a call to get_connection_filename() even if a separate working copy
is not created. | [
"Like",
"put_connection_filename",
"()",
"but",
"the",
"working",
"copy",
"is",
"simply",
"deleted",
"instead",
"of",
"being",
"copied",
"back",
"to",
"its",
"original",
"location",
".",
"This",
"is",
"a",
"useful",
"performance",
"boost",
"if",
"it",
"is",
... | train | https://github.com/gwastro/pycbc-glue/blob/a3e906bae59fbfd707c3ff82e5d008d939ec5e24/pycbc_glue/ligolw/dbtables.py#L389-L414 |
gwastro/pycbc-glue | pycbc_glue/ligolw/dbtables.py | idmap_sync | def idmap_sync(connection):
"""
Iterate over the tables in the database, ensure that there exists a
custom DBTable class for each, and synchronize that table's ID
generator to the ID values in the database.
"""
xmldoc = get_xml(connection)
for tbl in xmldoc.getElementsByTagName(DBTable.tagName):
tbl.sync_next_id()
xmldoc.unlink() | python | def idmap_sync(connection):
"""
Iterate over the tables in the database, ensure that there exists a
custom DBTable class for each, and synchronize that table's ID
generator to the ID values in the database.
"""
xmldoc = get_xml(connection)
for tbl in xmldoc.getElementsByTagName(DBTable.tagName):
tbl.sync_next_id()
xmldoc.unlink() | [
"def",
"idmap_sync",
"(",
"connection",
")",
":",
"xmldoc",
"=",
"get_xml",
"(",
"connection",
")",
"for",
"tbl",
"in",
"xmldoc",
".",
"getElementsByTagName",
"(",
"DBTable",
".",
"tagName",
")",
":",
"tbl",
".",
"sync_next_id",
"(",
")",
"xmldoc",
".",
... | Iterate over the tables in the database, ensure that there exists a
custom DBTable class for each, and synchronize that table's ID
generator to the ID values in the database. | [
"Iterate",
"over",
"the",
"tables",
"in",
"the",
"database",
"ensure",
"that",
"there",
"exists",
"a",
"custom",
"DBTable",
"class",
"for",
"each",
"and",
"synchronize",
"that",
"table",
"s",
"ID",
"generator",
"to",
"the",
"ID",
"values",
"in",
"the",
"da... | train | https://github.com/gwastro/pycbc-glue/blob/a3e906bae59fbfd707c3ff82e5d008d939ec5e24/pycbc_glue/ligolw/dbtables.py#L451-L460 |
gwastro/pycbc-glue | pycbc_glue/ligolw/dbtables.py | idmap_get_new | def idmap_get_new(connection, old, tbl):
"""
From the old ID string, obtain a replacement ID string by either
grabbing it from the _idmap_ table if one has already been assigned
to the old ID, or by using the current value of the Table
instance's next_id class attribute. In the latter case, the new ID
is recorded in the _idmap_ table, and the class attribute
incremented by 1.
This function is for internal use, it forms part of the code used
to re-map row IDs when merging multiple documents.
"""
cursor = connection.cursor()
cursor.execute("SELECT new FROM _idmap_ WHERE old == ?", (old,))
new = cursor.fetchone()
if new is not None:
# a new ID has already been created for this old ID
return ilwd.ilwdchar(new[0])
# this ID was not found in _idmap_ table, assign a new ID and
# record it
new = tbl.get_next_id()
cursor.execute("INSERT INTO _idmap_ VALUES (?, ?)", (old, new))
return new | python | def idmap_get_new(connection, old, tbl):
"""
From the old ID string, obtain a replacement ID string by either
grabbing it from the _idmap_ table if one has already been assigned
to the old ID, or by using the current value of the Table
instance's next_id class attribute. In the latter case, the new ID
is recorded in the _idmap_ table, and the class attribute
incremented by 1.
This function is for internal use, it forms part of the code used
to re-map row IDs when merging multiple documents.
"""
cursor = connection.cursor()
cursor.execute("SELECT new FROM _idmap_ WHERE old == ?", (old,))
new = cursor.fetchone()
if new is not None:
# a new ID has already been created for this old ID
return ilwd.ilwdchar(new[0])
# this ID was not found in _idmap_ table, assign a new ID and
# record it
new = tbl.get_next_id()
cursor.execute("INSERT INTO _idmap_ VALUES (?, ?)", (old, new))
return new | [
"def",
"idmap_get_new",
"(",
"connection",
",",
"old",
",",
"tbl",
")",
":",
"cursor",
"=",
"connection",
".",
"cursor",
"(",
")",
"cursor",
".",
"execute",
"(",
"\"SELECT new FROM _idmap_ WHERE old == ?\"",
",",
"(",
"old",
",",
")",
")",
"new",
"=",
"cur... | From the old ID string, obtain a replacement ID string by either
grabbing it from the _idmap_ table if one has already been assigned
to the old ID, or by using the current value of the Table
instance's next_id class attribute. In the latter case, the new ID
is recorded in the _idmap_ table, and the class attribute
incremented by 1.
This function is for internal use, it forms part of the code used
to re-map row IDs when merging multiple documents. | [
"From",
"the",
"old",
"ID",
"string",
"obtain",
"a",
"replacement",
"ID",
"string",
"by",
"either",
"grabbing",
"it",
"from",
"the",
"_idmap_",
"table",
"if",
"one",
"has",
"already",
"been",
"assigned",
"to",
"the",
"old",
"ID",
"or",
"by",
"using",
"th... | train | https://github.com/gwastro/pycbc-glue/blob/a3e906bae59fbfd707c3ff82e5d008d939ec5e24/pycbc_glue/ligolw/dbtables.py#L463-L485 |
gwastro/pycbc-glue | pycbc_glue/ligolw/dbtables.py | idmap_get_max_id | def idmap_get_max_id(connection, id_class):
"""
Given an ilwd:char ID class, return the highest ID from the table
for whose IDs that is the class.
Example:
>>> event_id = ilwd.ilwdchar("sngl_burst:event_id:0")
>>> print event_id
sngl_inspiral:event_id:0
>>> max_id = get_max_id(connection, type(event_id))
>>> print max_id
sngl_inspiral:event_id:1054
"""
cursor = connection.cursor()
cursor.execute("SELECT MAX(CAST(SUBSTR(%s, %d, 10) AS INTEGER)) FROM %s" % (id_class.column_name, id_class.index_offset + 1, id_class.table_name))
maxid = cursor.fetchone()[0]
cursor.close()
if maxid is None:
return None
return id_class(maxid) | python | def idmap_get_max_id(connection, id_class):
"""
Given an ilwd:char ID class, return the highest ID from the table
for whose IDs that is the class.
Example:
>>> event_id = ilwd.ilwdchar("sngl_burst:event_id:0")
>>> print event_id
sngl_inspiral:event_id:0
>>> max_id = get_max_id(connection, type(event_id))
>>> print max_id
sngl_inspiral:event_id:1054
"""
cursor = connection.cursor()
cursor.execute("SELECT MAX(CAST(SUBSTR(%s, %d, 10) AS INTEGER)) FROM %s" % (id_class.column_name, id_class.index_offset + 1, id_class.table_name))
maxid = cursor.fetchone()[0]
cursor.close()
if maxid is None:
return None
return id_class(maxid) | [
"def",
"idmap_get_max_id",
"(",
"connection",
",",
"id_class",
")",
":",
"cursor",
"=",
"connection",
".",
"cursor",
"(",
")",
"cursor",
".",
"execute",
"(",
"\"SELECT MAX(CAST(SUBSTR(%s, %d, 10) AS INTEGER)) FROM %s\"",
"%",
"(",
"id_class",
".",
"column_name",
","... | Given an ilwd:char ID class, return the highest ID from the table
for whose IDs that is the class.
Example:
>>> event_id = ilwd.ilwdchar("sngl_burst:event_id:0")
>>> print event_id
sngl_inspiral:event_id:0
>>> max_id = get_max_id(connection, type(event_id))
>>> print max_id
sngl_inspiral:event_id:1054 | [
"Given",
"an",
"ilwd",
":",
"char",
"ID",
"class",
"return",
"the",
"highest",
"ID",
"from",
"the",
"table",
"for",
"whose",
"IDs",
"that",
"is",
"the",
"class",
"."
] | train | https://github.com/gwastro/pycbc-glue/blob/a3e906bae59fbfd707c3ff82e5d008d939ec5e24/pycbc_glue/ligolw/dbtables.py#L488-L508 |
gwastro/pycbc-glue | pycbc_glue/ligolw/dbtables.py | get_table_names | def get_table_names(connection):
"""
Return a list of the table names in the database.
"""
cursor = connection.cursor()
cursor.execute("SELECT name FROM sqlite_master WHERE type == 'table'")
return [name for (name,) in cursor] | python | def get_table_names(connection):
"""
Return a list of the table names in the database.
"""
cursor = connection.cursor()
cursor.execute("SELECT name FROM sqlite_master WHERE type == 'table'")
return [name for (name,) in cursor] | [
"def",
"get_table_names",
"(",
"connection",
")",
":",
"cursor",
"=",
"connection",
".",
"cursor",
"(",
")",
"cursor",
".",
"execute",
"(",
"\"SELECT name FROM sqlite_master WHERE type == 'table'\"",
")",
"return",
"[",
"name",
"for",
"(",
"name",
",",
")",
"in"... | Return a list of the table names in the database. | [
"Return",
"a",
"list",
"of",
"the",
"table",
"names",
"in",
"the",
"database",
"."
] | train | https://github.com/gwastro/pycbc-glue/blob/a3e906bae59fbfd707c3ff82e5d008d939ec5e24/pycbc_glue/ligolw/dbtables.py#L534-L540 |
gwastro/pycbc-glue | pycbc_glue/ligolw/dbtables.py | get_column_info | def get_column_info(connection, table_name):
"""
Return an in order list of (name, type) tuples describing the
columns in the given table.
"""
cursor = connection.cursor()
cursor.execute("SELECT sql FROM sqlite_master WHERE type == 'table' AND name == ?", (table_name,))
statement, = cursor.fetchone()
coldefs = re.match(_sql_create_table_pattern, statement).groupdict()["coldefs"]
return [(coldef.groupdict()["name"], coldef.groupdict()["type"]) for coldef in re.finditer(_sql_coldef_pattern, coldefs) if coldef.groupdict()["name"].upper() not in ("PRIMARY", "UNIQUE", "CHECK")] | python | def get_column_info(connection, table_name):
"""
Return an in order list of (name, type) tuples describing the
columns in the given table.
"""
cursor = connection.cursor()
cursor.execute("SELECT sql FROM sqlite_master WHERE type == 'table' AND name == ?", (table_name,))
statement, = cursor.fetchone()
coldefs = re.match(_sql_create_table_pattern, statement).groupdict()["coldefs"]
return [(coldef.groupdict()["name"], coldef.groupdict()["type"]) for coldef in re.finditer(_sql_coldef_pattern, coldefs) if coldef.groupdict()["name"].upper() not in ("PRIMARY", "UNIQUE", "CHECK")] | [
"def",
"get_column_info",
"(",
"connection",
",",
"table_name",
")",
":",
"cursor",
"=",
"connection",
".",
"cursor",
"(",
")",
"cursor",
".",
"execute",
"(",
"\"SELECT sql FROM sqlite_master WHERE type == 'table' AND name == ?\"",
",",
"(",
"table_name",
",",
")",
... | Return an in order list of (name, type) tuples describing the
columns in the given table. | [
"Return",
"an",
"in",
"order",
"list",
"of",
"(",
"name",
"type",
")",
"tuples",
"describing",
"the",
"columns",
"in",
"the",
"given",
"table",
"."
] | train | https://github.com/gwastro/pycbc-glue/blob/a3e906bae59fbfd707c3ff82e5d008d939ec5e24/pycbc_glue/ligolw/dbtables.py#L543-L552 |
gwastro/pycbc-glue | pycbc_glue/ligolw/dbtables.py | get_xml | def get_xml(connection, table_names = None):
"""
Construct an XML document tree wrapping around the contents of the
database. On success the return value is a ligolw.LIGO_LW element
containing the tables as children. Arguments are a connection to
to a database, and an optional list of table names to dump. If
table_names is not provided the set is obtained from get_table_names()
"""
ligo_lw = ligolw.LIGO_LW()
if table_names is None:
table_names = get_table_names(connection)
for table_name in table_names:
# build the table document tree. copied from
# lsctables.New()
try:
cls = TableByName[table_name]
except KeyError:
cls = DBTable
table_elem = cls(AttributesImpl({u"Name": u"%s:table" % table_name}), connection = connection)
for column_name, column_type in get_column_info(connection, table_elem.Name):
if table_elem.validcolumns is not None:
# use the pre-defined column type
column_type = table_elem.validcolumns[column_name]
else:
# guess the column type
column_type = ligolwtypes.FromSQLiteType[column_type]
table_elem.appendChild(table.Column(AttributesImpl({u"Name": u"%s:%s" % (table_name, column_name), u"Type": column_type})))
table_elem._end_of_columns()
table_elem.appendChild(table.TableStream(AttributesImpl({u"Name": u"%s:table" % table_name, u"Delimiter": table.TableStream.Delimiter.default, u"Type": table.TableStream.Type.default})))
ligo_lw.appendChild(table_elem)
return ligo_lw | python | def get_xml(connection, table_names = None):
"""
Construct an XML document tree wrapping around the contents of the
database. On success the return value is a ligolw.LIGO_LW element
containing the tables as children. Arguments are a connection to
to a database, and an optional list of table names to dump. If
table_names is not provided the set is obtained from get_table_names()
"""
ligo_lw = ligolw.LIGO_LW()
if table_names is None:
table_names = get_table_names(connection)
for table_name in table_names:
# build the table document tree. copied from
# lsctables.New()
try:
cls = TableByName[table_name]
except KeyError:
cls = DBTable
table_elem = cls(AttributesImpl({u"Name": u"%s:table" % table_name}), connection = connection)
for column_name, column_type in get_column_info(connection, table_elem.Name):
if table_elem.validcolumns is not None:
# use the pre-defined column type
column_type = table_elem.validcolumns[column_name]
else:
# guess the column type
column_type = ligolwtypes.FromSQLiteType[column_type]
table_elem.appendChild(table.Column(AttributesImpl({u"Name": u"%s:%s" % (table_name, column_name), u"Type": column_type})))
table_elem._end_of_columns()
table_elem.appendChild(table.TableStream(AttributesImpl({u"Name": u"%s:table" % table_name, u"Delimiter": table.TableStream.Delimiter.default, u"Type": table.TableStream.Type.default})))
ligo_lw.appendChild(table_elem)
return ligo_lw | [
"def",
"get_xml",
"(",
"connection",
",",
"table_names",
"=",
"None",
")",
":",
"ligo_lw",
"=",
"ligolw",
".",
"LIGO_LW",
"(",
")",
"if",
"table_names",
"is",
"None",
":",
"table_names",
"=",
"get_table_names",
"(",
"connection",
")",
"for",
"table_name",
... | Construct an XML document tree wrapping around the contents of the
database. On success the return value is a ligolw.LIGO_LW element
containing the tables as children. Arguments are a connection to
to a database, and an optional list of table names to dump. If
table_names is not provided the set is obtained from get_table_names() | [
"Construct",
"an",
"XML",
"document",
"tree",
"wrapping",
"around",
"the",
"contents",
"of",
"the",
"database",
".",
"On",
"success",
"the",
"return",
"value",
"is",
"a",
"ligolw",
".",
"LIGO_LW",
"element",
"containing",
"the",
"tables",
"as",
"children",
"... | train | https://github.com/gwastro/pycbc-glue/blob/a3e906bae59fbfd707c3ff82e5d008d939ec5e24/pycbc_glue/ligolw/dbtables.py#L555-L587 |
gwastro/pycbc-glue | pycbc_glue/ligolw/dbtables.py | build_indexes | def build_indexes(connection, verbose = False):
"""
Using the how_to_index annotations in the table class definitions,
construct a set of indexes for the database at the given
connection.
"""
cursor = connection.cursor()
for table_name in get_table_names(connection):
# FIXME: figure out how to do this extensibly
if table_name in TableByName:
how_to_index = TableByName[table_name].how_to_index
elif table_name in lsctables.TableByName:
how_to_index = lsctables.TableByName[table_name].how_to_index
else:
continue
if how_to_index is not None:
if verbose:
print >>sys.stderr, "indexing %s table ..." % table_name
for index_name, cols in how_to_index.iteritems():
cursor.execute("CREATE INDEX IF NOT EXISTS %s ON %s (%s)" % (index_name, table_name, ",".join(cols)))
connection.commit() | python | def build_indexes(connection, verbose = False):
"""
Using the how_to_index annotations in the table class definitions,
construct a set of indexes for the database at the given
connection.
"""
cursor = connection.cursor()
for table_name in get_table_names(connection):
# FIXME: figure out how to do this extensibly
if table_name in TableByName:
how_to_index = TableByName[table_name].how_to_index
elif table_name in lsctables.TableByName:
how_to_index = lsctables.TableByName[table_name].how_to_index
else:
continue
if how_to_index is not None:
if verbose:
print >>sys.stderr, "indexing %s table ..." % table_name
for index_name, cols in how_to_index.iteritems():
cursor.execute("CREATE INDEX IF NOT EXISTS %s ON %s (%s)" % (index_name, table_name, ",".join(cols)))
connection.commit() | [
"def",
"build_indexes",
"(",
"connection",
",",
"verbose",
"=",
"False",
")",
":",
"cursor",
"=",
"connection",
".",
"cursor",
"(",
")",
"for",
"table_name",
"in",
"get_table_names",
"(",
"connection",
")",
":",
"# FIXME: figure out how to do this extensibly",
"i... | Using the how_to_index annotations in the table class definitions,
construct a set of indexes for the database at the given
connection. | [
"Using",
"the",
"how_to_index",
"annotations",
"in",
"the",
"table",
"class",
"definitions",
"construct",
"a",
"set",
"of",
"indexes",
"for",
"the",
"database",
"at",
"the",
"given",
"connection",
"."
] | train | https://github.com/gwastro/pycbc-glue/blob/a3e906bae59fbfd707c3ff82e5d008d939ec5e24/pycbc_glue/ligolw/dbtables.py#L954-L974 |
gwastro/pycbc-glue | pycbc_glue/ligolw/dbtables.py | use_in | def use_in(ContentHandler):
"""
Modify ContentHandler, a sub-class of
pycbc_glue.ligolw.LIGOLWContentHandler, to cause it to use the DBTable
class defined in this module when parsing XML documents. Instances
of the class must provide a connection attribute. When a document
is parsed, the value of this attribute will be passed to the
DBTable class' .__init__() method as each table object is created,
and thus sets the database connection for all table objects in the
document.
Example:
>>> import sqlite3
>>> from pycbc_glue.ligolw import ligolw
>>> class MyContentHandler(ligolw.LIGOLWContentHandler):
... def __init__(self, *args):
... super(MyContentHandler, self).__init__(*args)
... self.connection = sqlite3.connection()
...
>>> use_in(MyContentHandler)
Multiple database files can be in use at once by creating a content
handler class for each one.
"""
ContentHandler = lsctables.use_in(ContentHandler)
def startTable(self, parent, attrs):
name = table.StripTableName(attrs[u"Name"])
if name in TableByName:
return TableByName[name](attrs, connection = self.connection)
return DBTable(attrs, connection = self.connection)
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 DBTable
class defined in this module when parsing XML documents. Instances
of the class must provide a connection attribute. When a document
is parsed, the value of this attribute will be passed to the
DBTable class' .__init__() method as each table object is created,
and thus sets the database connection for all table objects in the
document.
Example:
>>> import sqlite3
>>> from pycbc_glue.ligolw import ligolw
>>> class MyContentHandler(ligolw.LIGOLWContentHandler):
... def __init__(self, *args):
... super(MyContentHandler, self).__init__(*args)
... self.connection = sqlite3.connection()
...
>>> use_in(MyContentHandler)
Multiple database files can be in use at once by creating a content
handler class for each one.
"""
ContentHandler = lsctables.use_in(ContentHandler)
def startTable(self, parent, attrs):
name = table.StripTableName(attrs[u"Name"])
if name in TableByName:
return TableByName[name](attrs, connection = self.connection)
return DBTable(attrs, connection = self.connection)
ContentHandler.startTable = startTable
return ContentHandler | [
"def",
"use_in",
"(",
"ContentHandler",
")",
":",
"ContentHandler",
"=",
"lsctables",
".",
"use_in",
"(",
"ContentHandler",
")",
"def",
"startTable",
"(",
"self",
",",
"parent",
",",
"attrs",
")",
":",
"name",
"=",
"table",
".",
"StripTableName",
"(",
"att... | Modify ContentHandler, a sub-class of
pycbc_glue.ligolw.LIGOLWContentHandler, to cause it to use the DBTable
class defined in this module when parsing XML documents. Instances
of the class must provide a connection attribute. When a document
is parsed, the value of this attribute will be passed to the
DBTable class' .__init__() method as each table object is created,
and thus sets the database connection for all table objects in the
document.
Example:
>>> import sqlite3
>>> from pycbc_glue.ligolw import ligolw
>>> class MyContentHandler(ligolw.LIGOLWContentHandler):
... def __init__(self, *args):
... super(MyContentHandler, self).__init__(*args)
... self.connection = sqlite3.connection()
...
>>> use_in(MyContentHandler)
Multiple database files can be in use at once by creating a content
handler class for each one. | [
"Modify",
"ContentHandler",
"a",
"sub",
"-",
"class",
"of",
"pycbc_glue",
".",
"ligolw",
".",
"LIGOLWContentHandler",
"to",
"cause",
"it",
"to",
"use",
"the",
"DBTable",
"class",
"defined",
"in",
"this",
"module",
"when",
"parsing",
"XML",
"documents",
".",
... | train | https://github.com/gwastro/pycbc-glue/blob/a3e906bae59fbfd707c3ff82e5d008d939ec5e24/pycbc_glue/ligolw/dbtables.py#L1011-L1046 |
gwastro/pycbc-glue | pycbc_glue/ligolw/dbtables.py | DBTable._append | def _append(self, row):
"""
Standard .append() method. This method is for intended for
internal use only.
"""
self.cursor.execute(self.append_statement, self.append_attrgetter(row)) | python | def _append(self, row):
"""
Standard .append() method. This method is for intended for
internal use only.
"""
self.cursor.execute(self.append_statement, self.append_attrgetter(row)) | [
"def",
"_append",
"(",
"self",
",",
"row",
")",
":",
"self",
".",
"cursor",
".",
"execute",
"(",
"self",
".",
"append_statement",
",",
"self",
".",
"append_attrgetter",
"(",
"row",
")",
")"
] | Standard .append() method. This method is for intended for
internal use only. | [
"Standard",
".",
"append",
"()",
"method",
".",
"This",
"method",
"is",
"for",
"intended",
"for",
"internal",
"use",
"only",
"."
] | train | https://github.com/gwastro/pycbc-glue/blob/a3e906bae59fbfd707c3ff82e5d008d939ec5e24/pycbc_glue/ligolw/dbtables.py#L773-L778 |
gwastro/pycbc-glue | pycbc_glue/ligolw/dbtables.py | DBTable._remapping_append | def _remapping_append(self, row):
"""
Replacement for the standard .append() method. This
version performs on the fly row ID reassignment, and so
also performs the function of the updateKeyMapping()
method. SQLite does not permit the PRIMARY KEY of a row to
be modified, so it needs to be done prior to insertion.
This method is intended for internal use only.
"""
if self.next_id is not None:
# assign (and record) a new ID before inserting the
# row to avoid collisions with existing rows
setattr(row, self.next_id.column_name, idmap_get_new(self.connection, getattr(row, self.next_id.column_name), self))
self._append(row) | python | def _remapping_append(self, row):
"""
Replacement for the standard .append() method. This
version performs on the fly row ID reassignment, and so
also performs the function of the updateKeyMapping()
method. SQLite does not permit the PRIMARY KEY of a row to
be modified, so it needs to be done prior to insertion.
This method is intended for internal use only.
"""
if self.next_id is not None:
# assign (and record) a new ID before inserting the
# row to avoid collisions with existing rows
setattr(row, self.next_id.column_name, idmap_get_new(self.connection, getattr(row, self.next_id.column_name), self))
self._append(row) | [
"def",
"_remapping_append",
"(",
"self",
",",
"row",
")",
":",
"if",
"self",
".",
"next_id",
"is",
"not",
"None",
":",
"# assign (and record) a new ID before inserting the",
"# row to avoid collisions with existing rows",
"setattr",
"(",
"row",
",",
"self",
".",
"next... | Replacement for the standard .append() method. This
version performs on the fly row ID reassignment, and so
also performs the function of the updateKeyMapping()
method. SQLite does not permit the PRIMARY KEY of a row to
be modified, so it needs to be done prior to insertion.
This method is intended for internal use only. | [
"Replacement",
"for",
"the",
"standard",
".",
"append",
"()",
"method",
".",
"This",
"version",
"performs",
"on",
"the",
"fly",
"row",
"ID",
"reassignment",
"and",
"so",
"also",
"performs",
"the",
"function",
"of",
"the",
"updateKeyMapping",
"()",
"method",
... | train | https://github.com/gwastro/pycbc-glue/blob/a3e906bae59fbfd707c3ff82e5d008d939ec5e24/pycbc_glue/ligolw/dbtables.py#L780-L793 |
gwastro/pycbc-glue | pycbc_glue/ligolw/dbtables.py | DBTable.row_from_cols | def row_from_cols(self, values):
"""
Given an iterable of values in the order of columns in the
database, construct and return a row object. This is a
convenience function for turning the results of database
queries into Python objects.
"""
row = self.RowType()
for c, t, v in zip(self.dbcolumnnames, self.dbcolumntypes, values):
if t in ligolwtypes.IDTypes:
v = ilwd.ilwdchar(v)
setattr(row, c, v)
return row | python | def row_from_cols(self, values):
"""
Given an iterable of values in the order of columns in the
database, construct and return a row object. This is a
convenience function for turning the results of database
queries into Python objects.
"""
row = self.RowType()
for c, t, v in zip(self.dbcolumnnames, self.dbcolumntypes, values):
if t in ligolwtypes.IDTypes:
v = ilwd.ilwdchar(v)
setattr(row, c, v)
return row | [
"def",
"row_from_cols",
"(",
"self",
",",
"values",
")",
":",
"row",
"=",
"self",
".",
"RowType",
"(",
")",
"for",
"c",
",",
"t",
",",
"v",
"in",
"zip",
"(",
"self",
".",
"dbcolumnnames",
",",
"self",
".",
"dbcolumntypes",
",",
"values",
")",
":",
... | Given an iterable of values in the order of columns in the
database, construct and return a row object. This is a
convenience function for turning the results of database
queries into Python objects. | [
"Given",
"an",
"iterable",
"of",
"values",
"in",
"the",
"order",
"of",
"columns",
"in",
"the",
"database",
"construct",
"and",
"return",
"a",
"row",
"object",
".",
"This",
"is",
"a",
"convenience",
"function",
"for",
"turning",
"the",
"results",
"of",
"dat... | train | https://github.com/gwastro/pycbc-glue/blob/a3e906bae59fbfd707c3ff82e5d008d939ec5e24/pycbc_glue/ligolw/dbtables.py#L797-L809 |
gwastro/pycbc-glue | pycbc_glue/ligolw/dbtables.py | DBTable.applyKeyMapping | def applyKeyMapping(self):
"""
Used as the second half of the key reassignment algorithm.
Loops over each row in the table, replacing references to
old row keys with the new values from the _idmap_ table.
"""
assignments = ", ".join("%s = (SELECT new FROM _idmap_ WHERE old == %s)" % (colname, colname) for coltype, colname in zip(self.dbcolumntypes, self.dbcolumnnames) if coltype in ligolwtypes.IDTypes and (self.next_id is None or colname != self.next_id.column_name))
if assignments:
# SQLite documentation says ROWID is monotonically
# increasing starting at 1 for the first row unless
# it ever wraps around, then it is randomly
# assigned. ROWID is a 64 bit integer, so the only
# way it will wrap is if somebody sets it to a very
# high number manually. This library does not do
# that, so I don't bother checking.
self.cursor.execute("UPDATE %s SET %s WHERE ROWID > %d" % (self.Name, assignments, self.last_maxrowid))
self.last_maxrowid = self.maxrowid() or 0 | python | def applyKeyMapping(self):
"""
Used as the second half of the key reassignment algorithm.
Loops over each row in the table, replacing references to
old row keys with the new values from the _idmap_ table.
"""
assignments = ", ".join("%s = (SELECT new FROM _idmap_ WHERE old == %s)" % (colname, colname) for coltype, colname in zip(self.dbcolumntypes, self.dbcolumnnames) if coltype in ligolwtypes.IDTypes and (self.next_id is None or colname != self.next_id.column_name))
if assignments:
# SQLite documentation says ROWID is monotonically
# increasing starting at 1 for the first row unless
# it ever wraps around, then it is randomly
# assigned. ROWID is a 64 bit integer, so the only
# way it will wrap is if somebody sets it to a very
# high number manually. This library does not do
# that, so I don't bother checking.
self.cursor.execute("UPDATE %s SET %s WHERE ROWID > %d" % (self.Name, assignments, self.last_maxrowid))
self.last_maxrowid = self.maxrowid() or 0 | [
"def",
"applyKeyMapping",
"(",
"self",
")",
":",
"assignments",
"=",
"\", \"",
".",
"join",
"(",
"\"%s = (SELECT new FROM _idmap_ WHERE old == %s)\"",
"%",
"(",
"colname",
",",
"colname",
")",
"for",
"coltype",
",",
"colname",
"in",
"zip",
"(",
"self",
".",
"d... | Used as the second half of the key reassignment algorithm.
Loops over each row in the table, replacing references to
old row keys with the new values from the _idmap_ table. | [
"Used",
"as",
"the",
"second",
"half",
"of",
"the",
"key",
"reassignment",
"algorithm",
".",
"Loops",
"over",
"each",
"row",
"in",
"the",
"table",
"replacing",
"references",
"to",
"old",
"row",
"keys",
"with",
"the",
"new",
"values",
"from",
"the",
"_idmap... | train | https://github.com/gwastro/pycbc-glue/blob/a3e906bae59fbfd707c3ff82e5d008d939ec5e24/pycbc_glue/ligolw/dbtables.py#L818-L834 |
gwastro/pycbc-glue | pycbc_glue/ligolw/dbtables.py | TimeSlideTable.as_dict | def as_dict(self):
"""
Return a ditionary mapping time slide IDs to offset
dictionaries.
"""
return dict((ilwd.ilwdchar(id), offsetvector.offsetvector((instrument, offset) for id, instrument, offset in values)) for id, values in itertools.groupby(self.cursor.execute("SELECT time_slide_id, instrument, offset FROM time_slide ORDER BY time_slide_id"), lambda (id, instrument, offset): id)) | python | def as_dict(self):
"""
Return a ditionary mapping time slide IDs to offset
dictionaries.
"""
return dict((ilwd.ilwdchar(id), offsetvector.offsetvector((instrument, offset) for id, instrument, offset in values)) for id, values in itertools.groupby(self.cursor.execute("SELECT time_slide_id, instrument, offset FROM time_slide ORDER BY time_slide_id"), lambda (id, instrument, offset): id)) | [
"def",
"as_dict",
"(",
"self",
")",
":",
"return",
"dict",
"(",
"(",
"ilwd",
".",
"ilwdchar",
"(",
"id",
")",
",",
"offsetvector",
".",
"offsetvector",
"(",
"(",
"instrument",
",",
"offset",
")",
"for",
"id",
",",
"instrument",
",",
"offset",
"in",
"... | 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/dbtables.py#L868-L873 |
gwastro/pycbc-glue | pycbc_glue/ligolw/dbtables.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(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(offsetdict)
# that's OK, create new vector
id = self.get_next_id()
for instrument, offset in offsetdict.items():
row = self.RowType()
row.process_id = create_new.process_id
row.time_slide_id = id
row.instrument = instrument
row.offset = offset
self.append(row)
# return new ID
return id | 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(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(offsetdict)
# that's OK, create new vector
id = self.get_next_id()
for instrument, offset in offsetdict.items():
row = self.RowType()
row.process_id = create_new.process_id
row.time_slide_id = id
row.instrument = instrument
row.offset = offset
self.append(row)
# return new ID
return id | [
"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/dbtables.py#L875-L942 |
gwastro/pycbc-glue | pycbc_glue/LDBDWClient.py | findCredential | def findCredential():
"""
Follow the usual path that GSI libraries would
follow to find a valid proxy credential but
also allow an end entity certificate to be used
along with an unencrypted private key if they
are pointed to by X509_USER_CERT and X509_USER_KEY
since we expect this will be the output from
the eventual ligo-login wrapper around
kinit and then myproxy-login.
"""
# use X509_USER_PROXY from environment if set
if os.environ.has_key('X509_USER_PROXY'):
filePath = os.environ['X509_USER_PROXY']
if validateProxy(filePath):
return filePath, filePath
else:
RFCproxyUsage()
sys.exit(1)
# use X509_USER_CERT and X509_USER_KEY if set
if os.environ.has_key('X509_USER_CERT'):
if os.environ.has_key('X509_USER_KEY'):
certFile = os.environ['X509_USER_CERT']
keyFile = os.environ['X509_USER_KEY']
return certFile, keyFile
# search for proxy file on disk
uid = os.getuid()
path = "/tmp/x509up_u%d" % uid
if os.access(path, os.R_OK):
if validateProxy(path):
return path, path
else:
RFCproxyUsage()
sys.exit(1)
# if we get here could not find a credential
RFCproxyUsage()
sys.exit(1) | python | def findCredential():
"""
Follow the usual path that GSI libraries would
follow to find a valid proxy credential but
also allow an end entity certificate to be used
along with an unencrypted private key if they
are pointed to by X509_USER_CERT and X509_USER_KEY
since we expect this will be the output from
the eventual ligo-login wrapper around
kinit and then myproxy-login.
"""
# use X509_USER_PROXY from environment if set
if os.environ.has_key('X509_USER_PROXY'):
filePath = os.environ['X509_USER_PROXY']
if validateProxy(filePath):
return filePath, filePath
else:
RFCproxyUsage()
sys.exit(1)
# use X509_USER_CERT and X509_USER_KEY if set
if os.environ.has_key('X509_USER_CERT'):
if os.environ.has_key('X509_USER_KEY'):
certFile = os.environ['X509_USER_CERT']
keyFile = os.environ['X509_USER_KEY']
return certFile, keyFile
# search for proxy file on disk
uid = os.getuid()
path = "/tmp/x509up_u%d" % uid
if os.access(path, os.R_OK):
if validateProxy(path):
return path, path
else:
RFCproxyUsage()
sys.exit(1)
# if we get here could not find a credential
RFCproxyUsage()
sys.exit(1) | [
"def",
"findCredential",
"(",
")",
":",
"# use X509_USER_PROXY from environment if set",
"if",
"os",
".",
"environ",
".",
"has_key",
"(",
"'X509_USER_PROXY'",
")",
":",
"filePath",
"=",
"os",
".",
"environ",
"[",
"'X509_USER_PROXY'",
"]",
"if",
"validateProxy",
"(... | Follow the usual path that GSI libraries would
follow to find a valid proxy credential but
also allow an end entity certificate to be used
along with an unencrypted private key if they
are pointed to by X509_USER_CERT and X509_USER_KEY
since we expect this will be the output from
the eventual ligo-login wrapper around
kinit and then myproxy-login. | [
"Follow",
"the",
"usual",
"path",
"that",
"GSI",
"libraries",
"would",
"follow",
"to",
"find",
"a",
"valid",
"proxy",
"credential",
"but",
"also",
"allow",
"an",
"end",
"entity",
"certificate",
"to",
"be",
"used",
"along",
"with",
"an",
"unencrypted",
"priva... | train | https://github.com/gwastro/pycbc-glue/blob/a3e906bae59fbfd707c3ff82e5d008d939ec5e24/pycbc_glue/LDBDWClient.py#L147-L188 |
gwastro/pycbc-glue | pycbc_glue/LDBDWClient.py | validateProxy | def validateProxy(path):
"""
Test that the proxy certificate is RFC 3820
compliant and that it is valid for at least
the next 15 minutes.
"""
# load the proxy from path
try:
proxy = M2Crypto.X509.load_cert(path)
except Exception, e:
msg = "Unable to load proxy from path %s : %s" % (path, e)
print >>sys.stderr, msg
sys.exit(1)
# make sure the proxy is RFC 3820 compliant
# or is an end-entity X.509 certificate
try:
proxy.get_ext("proxyCertInfo")
except LookupError:
# it is not an RFC 3820 proxy so check
# if it is an old globus legacy proxy
subject = proxy.get_subject().as_text()
if re.search(r'.+CN=proxy$', subject):
# it is so print warning and exit
RFCproxyUsage()
sys.exit(1)
# attempt to make sure the proxy is still good for more than 15 minutes
try:
expireASN1 = proxy.get_not_after().__str__()
expireGMT = time.strptime(expireASN1, "%b %d %H:%M:%S %Y %Z")
expireUTC = calendar.timegm(expireGMT)
now = int(time.time())
secondsLeft = expireUTC - now
except Exception, e:
# problem getting or parsing time so just let the client
# continue and pass the issue along to the server
secondsLeft = 3600
if secondsLeft <= 0:
msg = """\
Your proxy certificate is expired.
Please generate a new proxy certificate and
try again.
"""
print >>sys.stderr, msg
sys.exit(1)
if secondsLeft < (60 * 15):
msg = """\
Your proxy certificate expires in less than
15 minutes.
Please generate a new proxy certificate and
try again.
"""
print >>sys.stderr, msg
sys.exit(1)
# return True to indicate validated proxy
return True | python | def validateProxy(path):
"""
Test that the proxy certificate is RFC 3820
compliant and that it is valid for at least
the next 15 minutes.
"""
# load the proxy from path
try:
proxy = M2Crypto.X509.load_cert(path)
except Exception, e:
msg = "Unable to load proxy from path %s : %s" % (path, e)
print >>sys.stderr, msg
sys.exit(1)
# make sure the proxy is RFC 3820 compliant
# or is an end-entity X.509 certificate
try:
proxy.get_ext("proxyCertInfo")
except LookupError:
# it is not an RFC 3820 proxy so check
# if it is an old globus legacy proxy
subject = proxy.get_subject().as_text()
if re.search(r'.+CN=proxy$', subject):
# it is so print warning and exit
RFCproxyUsage()
sys.exit(1)
# attempt to make sure the proxy is still good for more than 15 minutes
try:
expireASN1 = proxy.get_not_after().__str__()
expireGMT = time.strptime(expireASN1, "%b %d %H:%M:%S %Y %Z")
expireUTC = calendar.timegm(expireGMT)
now = int(time.time())
secondsLeft = expireUTC - now
except Exception, e:
# problem getting or parsing time so just let the client
# continue and pass the issue along to the server
secondsLeft = 3600
if secondsLeft <= 0:
msg = """\
Your proxy certificate is expired.
Please generate a new proxy certificate and
try again.
"""
print >>sys.stderr, msg
sys.exit(1)
if secondsLeft < (60 * 15):
msg = """\
Your proxy certificate expires in less than
15 minutes.
Please generate a new proxy certificate and
try again.
"""
print >>sys.stderr, msg
sys.exit(1)
# return True to indicate validated proxy
return True | [
"def",
"validateProxy",
"(",
"path",
")",
":",
"# load the proxy from path",
"try",
":",
"proxy",
"=",
"M2Crypto",
".",
"X509",
".",
"load_cert",
"(",
"path",
")",
"except",
"Exception",
",",
"e",
":",
"msg",
"=",
"\"Unable to load proxy from path %s : %s\"",
"%... | Test that the proxy certificate is RFC 3820
compliant and that it is valid for at least
the next 15 minutes. | [
"Test",
"that",
"the",
"proxy",
"certificate",
"is",
"RFC",
"3820",
"compliant",
"and",
"that",
"it",
"is",
"valid",
"for",
"at",
"least",
"the",
"next",
"15",
"minutes",
"."
] | train | https://github.com/gwastro/pycbc-glue/blob/a3e906bae59fbfd707c3ff82e5d008d939ec5e24/pycbc_glue/LDBDWClient.py#L190-L252 |
pesaply/sarafu | profile.py | CustomerProfile.save | def save(self, *args, **kwargs):
"""If creating new instance, create profile on Authorize.NET also"""
data = kwargs.pop('data', {})
sync = kwargs.pop('sync', True)
if not self.id and sync:
self.push_to_server(data)
super(CustomerProfile, self).save(*args, **kwargs) | python | def save(self, *args, **kwargs):
"""If creating new instance, create profile on Authorize.NET also"""
data = kwargs.pop('data', {})
sync = kwargs.pop('sync', True)
if not self.id and sync:
self.push_to_server(data)
super(CustomerProfile, self).save(*args, **kwargs) | [
"def",
"save",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"data",
"=",
"kwargs",
".",
"pop",
"(",
"'data'",
",",
"{",
"}",
")",
"sync",
"=",
"kwargs",
".",
"pop",
"(",
"'sync'",
",",
"True",
")",
"if",
"not",
"self",
".... | If creating new instance, create profile on Authorize.NET also | [
"If",
"creating",
"new",
"instance",
"create",
"profile",
"on",
"Authorize",
".",
"NET",
"also"
] | train | https://github.com/pesaply/sarafu/blob/8c1296d48427a6cf17ffc5600d100b49acc9c5b7/profile.py#L266-L272 |
pesaply/sarafu | profile.py | CustomerProfile.delete | def delete(self):
"""Delete the customer profile remotely and locally"""
response = delete_profile(self.profile_id)
response.raise_if_error()
super(CustomerProfile, self).delete() | python | def delete(self):
"""Delete the customer profile remotely and locally"""
response = delete_profile(self.profile_id)
response.raise_if_error()
super(CustomerProfile, self).delete() | [
"def",
"delete",
"(",
"self",
")",
":",
"response",
"=",
"delete_profile",
"(",
"self",
".",
"profile_id",
")",
"response",
".",
"raise_if_error",
"(",
")",
"super",
"(",
"CustomerProfile",
",",
"self",
")",
".",
"delete",
"(",
")"
] | Delete the customer profile remotely and locally | [
"Delete",
"the",
"customer",
"profile",
"remotely",
"and",
"locally"
] | train | https://github.com/pesaply/sarafu/blob/8c1296d48427a6cf17ffc5600d100b49acc9c5b7/profile.py#L274-L278 |
pesaply/sarafu | profile.py | CustomerProfile.push_to_server | def push_to_server(self, data):
"""Create customer profile for given ``customer`` on Authorize.NET"""
output = add_profile(self.customer.pk, data, data)
output['response'].raise_if_error()
self.profile_id = output['profile_id']
self.payment_profile_ids = output['payment_profile_ids'] | python | def push_to_server(self, data):
"""Create customer profile for given ``customer`` on Authorize.NET"""
output = add_profile(self.customer.pk, data, data)
output['response'].raise_if_error()
self.profile_id = output['profile_id']
self.payment_profile_ids = output['payment_profile_ids'] | [
"def",
"push_to_server",
"(",
"self",
",",
"data",
")",
":",
"output",
"=",
"add_profile",
"(",
"self",
".",
"customer",
".",
"pk",
",",
"data",
",",
"data",
")",
"output",
"[",
"'response'",
"]",
".",
"raise_if_error",
"(",
")",
"self",
".",
"profile_... | Create customer profile for given ``customer`` on Authorize.NET | [
"Create",
"customer",
"profile",
"for",
"given",
"customer",
"on",
"Authorize",
".",
"NET"
] | train | https://github.com/pesaply/sarafu/blob/8c1296d48427a6cf17ffc5600d100b49acc9c5b7/profile.py#L280-L285 |
pesaply/sarafu | profile.py | CustomerProfile.sync | def sync(self):
"""Overwrite local customer profile data with remote data"""
output = get_profile(self.profile_id)
output['response'].raise_if_error()
for payment_profile in output['payment_profiles']:
instance, created = CustomerPaymentProfile.objects.get_or_create(
customer_profile=self,
payment_profile_id=payment_profile['payment_profile_id']
)
instance.sync(payment_profile) | python | def sync(self):
"""Overwrite local customer profile data with remote data"""
output = get_profile(self.profile_id)
output['response'].raise_if_error()
for payment_profile in output['payment_profiles']:
instance, created = CustomerPaymentProfile.objects.get_or_create(
customer_profile=self,
payment_profile_id=payment_profile['payment_profile_id']
)
instance.sync(payment_profile) | [
"def",
"sync",
"(",
"self",
")",
":",
"output",
"=",
"get_profile",
"(",
"self",
".",
"profile_id",
")",
"output",
"[",
"'response'",
"]",
".",
"raise_if_error",
"(",
")",
"for",
"payment_profile",
"in",
"output",
"[",
"'payment_profiles'",
"]",
":",
"inst... | Overwrite local customer profile data with remote data | [
"Overwrite",
"local",
"customer",
"profile",
"data",
"with",
"remote",
"data"
] | train | https://github.com/pesaply/sarafu/blob/8c1296d48427a6cf17ffc5600d100b49acc9c5b7/profile.py#L287-L296 |
pesaply/sarafu | profile.py | CustomerPaymentProfile.save | def save(self, *args, **kwargs):
"""Sync payment profile on Authorize.NET if sync kwarg is not False"""
if kwargs.pop('sync', True):
self.push_to_server()
self.card_code = None
self.card_number = "XXXX%s" % self.card_number[-4:]
super(CustomerPaymentProfile, self).save(*args, **kwargs) | python | def save(self, *args, **kwargs):
"""Sync payment profile on Authorize.NET if sync kwarg is not False"""
if kwargs.pop('sync', True):
self.push_to_server()
self.card_code = None
self.card_number = "XXXX%s" % self.card_number[-4:]
super(CustomerPaymentProfile, self).save(*args, **kwargs) | [
"def",
"save",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"kwargs",
".",
"pop",
"(",
"'sync'",
",",
"True",
")",
":",
"self",
".",
"push_to_server",
"(",
")",
"self",
".",
"card_code",
"=",
"None",
"self",
".",
"card_... | Sync payment profile on Authorize.NET if sync kwarg is not False | [
"Sync",
"payment",
"profile",
"on",
"Authorize",
".",
"NET",
"if",
"sync",
"kwarg",
"is",
"not",
"False"
] | train | https://github.com/pesaply/sarafu/blob/8c1296d48427a6cf17ffc5600d100b49acc9c5b7/profile.py#L331-L337 |
pesaply/sarafu | profile.py | CustomerPaymentProfile.push_to_server | def push_to_server(self):
"""
Use appropriate CIM API call to save payment profile to Authorize.NET
1. If customer has no profile yet, create one with this payment profile
2. If payment profile is not on Authorize.NET yet, create it there
3. If payment profile exists on Authorize.NET update it there
"""
if not self.customer_profile_id:
try:
self.customer_profile = CustomerProfile.objects.get(
customer=self.customer)
except CustomerProfile.DoesNotExist:
pass
if self.payment_profile_id:
response = update_payment_profile(
self.customer_profile.profile_id,
self.payment_profile_id,
self.raw_data,
self.raw_data,
)
response.raise_if_error()
elif self.customer_profile_id:
output = create_payment_profile(
self.customer_profile.profile_id,
self.raw_data,
self.raw_data,
)
response = output['response']
response.raise_if_error()
self.payment_profile_id = output['payment_profile_id']
else:
output = add_profile(
self.customer.id,
self.raw_data,
self.raw_data,
)
response = output['response']
response.raise_if_error()
self.customer_profile = CustomerProfile.objects.create(
customer=self.customer,
profile_id=output['profile_id'],
sync=False,
)
self.payment_profile_id = output['payment_profile_ids'][0] | python | def push_to_server(self):
"""
Use appropriate CIM API call to save payment profile to Authorize.NET
1. If customer has no profile yet, create one with this payment profile
2. If payment profile is not on Authorize.NET yet, create it there
3. If payment profile exists on Authorize.NET update it there
"""
if not self.customer_profile_id:
try:
self.customer_profile = CustomerProfile.objects.get(
customer=self.customer)
except CustomerProfile.DoesNotExist:
pass
if self.payment_profile_id:
response = update_payment_profile(
self.customer_profile.profile_id,
self.payment_profile_id,
self.raw_data,
self.raw_data,
)
response.raise_if_error()
elif self.customer_profile_id:
output = create_payment_profile(
self.customer_profile.profile_id,
self.raw_data,
self.raw_data,
)
response = output['response']
response.raise_if_error()
self.payment_profile_id = output['payment_profile_id']
else:
output = add_profile(
self.customer.id,
self.raw_data,
self.raw_data,
)
response = output['response']
response.raise_if_error()
self.customer_profile = CustomerProfile.objects.create(
customer=self.customer,
profile_id=output['profile_id'],
sync=False,
)
self.payment_profile_id = output['payment_profile_ids'][0] | [
"def",
"push_to_server",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"customer_profile_id",
":",
"try",
":",
"self",
".",
"customer_profile",
"=",
"CustomerProfile",
".",
"objects",
".",
"get",
"(",
"customer",
"=",
"self",
".",
"customer",
")",
"exce... | Use appropriate CIM API call to save payment profile to Authorize.NET
1. If customer has no profile yet, create one with this payment profile
2. If payment profile is not on Authorize.NET yet, create it there
3. If payment profile exists on Authorize.NET update it there | [
"Use",
"appropriate",
"CIM",
"API",
"call",
"to",
"save",
"payment",
"profile",
"to",
"Authorize",
".",
"NET",
"1",
".",
"If",
"customer",
"has",
"no",
"profile",
"yet",
"create",
"one",
"with",
"this",
"payment",
"profile",
"2",
".",
"If",
"payment",
"p... | train | https://github.com/pesaply/sarafu/blob/8c1296d48427a6cf17ffc5600d100b49acc9c5b7/profile.py#L339-L382 |
pesaply/sarafu | profile.py | CustomerPaymentProfile.sync | def sync(self, data):
"""Overwrite local customer payment profile data with remote data"""
for k, v in data.get('billing', {}).items():
setattr(self, k, v)
self.card_number = data.get('credit_card', {}).get('card_number',
self.card_number)
self.save(sync=False) | python | def sync(self, data):
"""Overwrite local customer payment profile data with remote data"""
for k, v in data.get('billing', {}).items():
setattr(self, k, v)
self.card_number = data.get('credit_card', {}).get('card_number',
self.card_number)
self.save(sync=False) | [
"def",
"sync",
"(",
"self",
",",
"data",
")",
":",
"for",
"k",
",",
"v",
"in",
"data",
".",
"get",
"(",
"'billing'",
",",
"{",
"}",
")",
".",
"items",
"(",
")",
":",
"setattr",
"(",
"self",
",",
"k",
",",
"v",
")",
"self",
".",
"card_number",... | Overwrite local customer payment profile data with remote data | [
"Overwrite",
"local",
"customer",
"payment",
"profile",
"data",
"with",
"remote",
"data"
] | train | https://github.com/pesaply/sarafu/blob/8c1296d48427a6cf17ffc5600d100b49acc9c5b7/profile.py#L391-L397 |
pesaply/sarafu | profile.py | CustomerPaymentProfile.delete | def delete(self):
"""Delete the customer payment profile remotely and locally"""
response = delete_payment_profile(self.customer_profile.profile_id,
self.payment_profile_id)
response.raise_if_error()
return super(CustomerPaymentProfile, self).delete() | python | def delete(self):
"""Delete the customer payment profile remotely and locally"""
response = delete_payment_profile(self.customer_profile.profile_id,
self.payment_profile_id)
response.raise_if_error()
return super(CustomerPaymentProfile, self).delete() | [
"def",
"delete",
"(",
"self",
")",
":",
"response",
"=",
"delete_payment_profile",
"(",
"self",
".",
"customer_profile",
".",
"profile_id",
",",
"self",
".",
"payment_profile_id",
")",
"response",
".",
"raise_if_error",
"(",
")",
"return",
"super",
"(",
"Custo... | Delete the customer payment profile remotely and locally | [
"Delete",
"the",
"customer",
"payment",
"profile",
"remotely",
"and",
"locally"
] | train | https://github.com/pesaply/sarafu/blob/8c1296d48427a6cf17ffc5600d100b49acc9c5b7/profile.py#L399-L404 |
onjin/liquimigrate | liquimigrate/changesets.py | get_changelog_file_for_database | def get_changelog_file_for_database(database=DEFAULT_DB_ALIAS):
"""get changelog filename for given `database` DB alias"""
from django.conf import settings
try:
return settings.LIQUIMIGRATE_CHANGELOG_FILES[database]
except AttributeError:
if database == DEFAULT_DB_ALIAS:
try:
return settings.LIQUIMIGRATE_CHANGELOG_FILE
except AttributeError:
raise ImproperlyConfigured(
'Please set LIQUIMIGRATE_CHANGELOG_FILE or '
'LIQUIMIGRATE_CHANGELOG_FILES in your '
'project settings')
else:
raise ImproperlyConfigured(
'LIQUIMIGRATE_CHANGELOG_FILES dictionary setting '
'is required for multiple databases support')
except KeyError:
raise ImproperlyConfigured(
"Liquibase changelog file is not set for database: %s" % database) | python | def get_changelog_file_for_database(database=DEFAULT_DB_ALIAS):
"""get changelog filename for given `database` DB alias"""
from django.conf import settings
try:
return settings.LIQUIMIGRATE_CHANGELOG_FILES[database]
except AttributeError:
if database == DEFAULT_DB_ALIAS:
try:
return settings.LIQUIMIGRATE_CHANGELOG_FILE
except AttributeError:
raise ImproperlyConfigured(
'Please set LIQUIMIGRATE_CHANGELOG_FILE or '
'LIQUIMIGRATE_CHANGELOG_FILES in your '
'project settings')
else:
raise ImproperlyConfigured(
'LIQUIMIGRATE_CHANGELOG_FILES dictionary setting '
'is required for multiple databases support')
except KeyError:
raise ImproperlyConfigured(
"Liquibase changelog file is not set for database: %s" % database) | [
"def",
"get_changelog_file_for_database",
"(",
"database",
"=",
"DEFAULT_DB_ALIAS",
")",
":",
"from",
"django",
".",
"conf",
"import",
"settings",
"try",
":",
"return",
"settings",
".",
"LIQUIMIGRATE_CHANGELOG_FILES",
"[",
"database",
"]",
"except",
"AttributeError",
... | get changelog filename for given `database` DB alias | [
"get",
"changelog",
"filename",
"for",
"given",
"database",
"DB",
"alias"
] | train | https://github.com/onjin/liquimigrate/blob/c159a92198a849176fb53fc2db0736049f12031f/liquimigrate/changesets.py#L161-L183 |
onjin/liquimigrate | liquimigrate/changesets.py | find_target_migration_file | def find_target_migration_file(database=DEFAULT_DB_ALIAS, changelog_file=None):
"""Finds best matching target migration file"""
if not database:
database = DEFAULT_DB_ALIAS
if not changelog_file:
changelog_file = get_changelog_file_for_database(database)
try:
doc = minidom.parse(changelog_file)
except ExpatError as ex:
raise InvalidChangelogFile(
'Could not parse XML file %s: %s' % (changelog_file, ex))
try:
dbchglog = doc.getElementsByTagName('databaseChangeLog')[0]
except IndexError:
raise InvalidChangelogFile(
'Missing <databaseChangeLog> node in file %s' % (
changelog_file))
else:
nodes = list(filter(lambda x: x.nodeType is x.ELEMENT_NODE,
dbchglog.childNodes))
if not nodes:
return changelog_file
last_node = nodes[-1]
if last_node.tagName == 'include':
last_file = last_node.attributes.get('file').firstChild.data
return find_target_migration_file(
database=database, changelog_file=last_file)
else:
return changelog_file | python | def find_target_migration_file(database=DEFAULT_DB_ALIAS, changelog_file=None):
"""Finds best matching target migration file"""
if not database:
database = DEFAULT_DB_ALIAS
if not changelog_file:
changelog_file = get_changelog_file_for_database(database)
try:
doc = minidom.parse(changelog_file)
except ExpatError as ex:
raise InvalidChangelogFile(
'Could not parse XML file %s: %s' % (changelog_file, ex))
try:
dbchglog = doc.getElementsByTagName('databaseChangeLog')[0]
except IndexError:
raise InvalidChangelogFile(
'Missing <databaseChangeLog> node in file %s' % (
changelog_file))
else:
nodes = list(filter(lambda x: x.nodeType is x.ELEMENT_NODE,
dbchglog.childNodes))
if not nodes:
return changelog_file
last_node = nodes[-1]
if last_node.tagName == 'include':
last_file = last_node.attributes.get('file').firstChild.data
return find_target_migration_file(
database=database, changelog_file=last_file)
else:
return changelog_file | [
"def",
"find_target_migration_file",
"(",
"database",
"=",
"DEFAULT_DB_ALIAS",
",",
"changelog_file",
"=",
"None",
")",
":",
"if",
"not",
"database",
":",
"database",
"=",
"DEFAULT_DB_ALIAS",
"if",
"not",
"changelog_file",
":",
"changelog_file",
"=",
"get_changelog_... | Finds best matching target migration file | [
"Finds",
"best",
"matching",
"target",
"migration",
"file"
] | train | https://github.com/onjin/liquimigrate/blob/c159a92198a849176fb53fc2db0736049f12031f/liquimigrate/changesets.py#L186-L220 |
TracyWebTech/django-conversejs | conversejs/boshclient.py | BOSHClient.connection | def connection(self):
"""Returns an stablished connection"""
if self._connection:
return self._connection
self.log.debug('Initializing connection to %s' % (self.bosh_service.
netloc))
if self.bosh_service.scheme == 'http':
Connection = httplib.HTTPConnection
elif self.bosh_service.scheme == 'https':
Connection = httplib.HTTPSConnection
else:
# TODO: raise proper exception
raise Exception('Invalid URL scheme %s' % self.bosh_service.scheme)
self._connection = Connection(self.bosh_service.netloc, timeout=10)
self.log.debug('Connection initialized')
# TODO add exceptions handler there (URL not found etc)
return self._connection | python | def connection(self):
"""Returns an stablished connection"""
if self._connection:
return self._connection
self.log.debug('Initializing connection to %s' % (self.bosh_service.
netloc))
if self.bosh_service.scheme == 'http':
Connection = httplib.HTTPConnection
elif self.bosh_service.scheme == 'https':
Connection = httplib.HTTPSConnection
else:
# TODO: raise proper exception
raise Exception('Invalid URL scheme %s' % self.bosh_service.scheme)
self._connection = Connection(self.bosh_service.netloc, timeout=10)
self.log.debug('Connection initialized')
# TODO add exceptions handler there (URL not found etc)
return self._connection | [
"def",
"connection",
"(",
"self",
")",
":",
"if",
"self",
".",
"_connection",
":",
"return",
"self",
".",
"_connection",
"self",
".",
"log",
".",
"debug",
"(",
"'Initializing connection to %s'",
"%",
"(",
"self",
".",
"bosh_service",
".",
"netloc",
")",
")... | Returns an stablished connection | [
"Returns",
"an",
"stablished",
"connection"
] | train | https://github.com/TracyWebTech/django-conversejs/blob/cd9176f007ef3853ea6321bf93b466644d89305b/conversejs/boshclient.py#L75-L95 |
TracyWebTech/django-conversejs | conversejs/boshclient.py | BOSHClient.request_sid | def request_sid(self):
""" Request a BOSH session according to
http://xmpp.org/extensions/xep-0124.html#session-request
Returns the new SID (str).
"""
if self._sid:
return self._sid
self.log.debug('Prepare to request BOSH session')
data = self.send_request(self.get_body(sid_request=True))
if not data:
return None
# This is XML. response_body contains the <body/> element of the
# response.
response_body = ET.fromstring(data)
# Get the remote Session ID
self._sid = response_body.get('sid')
self.log.debug('sid = %s' % self._sid)
# Get the longest time (s) that the XMPP server will wait before
# responding to any request.
self.server_wait = response_body.get('wait')
self.log.debug('wait = %s' % self.server_wait)
# Get the authid
self.authid = response_body.get('authid')
# Get the allowed authentication methods using xpath
search_for = '{{{0}}}features/{{{1}}}mechanisms/{{{2}}}mechanism'.format(
JABBER_STREAMS_NS, XMPP_SASL_NS, XMPP_SASL_NS
)
self.log.debug('Looking for "%s" into response body', search_for)
mechanisms = response_body.findall(search_for)
self.server_auth = []
for mechanism in mechanisms:
self.server_auth.append(mechanism.text)
self.log.debug('New AUTH method: %s' % mechanism.text)
if not self.server_auth:
self.log.debug(('The server didn\'t send the allowed '
'authentication methods'))
self._sid = None
return self._sid | python | def request_sid(self):
""" Request a BOSH session according to
http://xmpp.org/extensions/xep-0124.html#session-request
Returns the new SID (str).
"""
if self._sid:
return self._sid
self.log.debug('Prepare to request BOSH session')
data = self.send_request(self.get_body(sid_request=True))
if not data:
return None
# This is XML. response_body contains the <body/> element of the
# response.
response_body = ET.fromstring(data)
# Get the remote Session ID
self._sid = response_body.get('sid')
self.log.debug('sid = %s' % self._sid)
# Get the longest time (s) that the XMPP server will wait before
# responding to any request.
self.server_wait = response_body.get('wait')
self.log.debug('wait = %s' % self.server_wait)
# Get the authid
self.authid = response_body.get('authid')
# Get the allowed authentication methods using xpath
search_for = '{{{0}}}features/{{{1}}}mechanisms/{{{2}}}mechanism'.format(
JABBER_STREAMS_NS, XMPP_SASL_NS, XMPP_SASL_NS
)
self.log.debug('Looking for "%s" into response body', search_for)
mechanisms = response_body.findall(search_for)
self.server_auth = []
for mechanism in mechanisms:
self.server_auth.append(mechanism.text)
self.log.debug('New AUTH method: %s' % mechanism.text)
if not self.server_auth:
self.log.debug(('The server didn\'t send the allowed '
'authentication methods'))
self._sid = None
return self._sid | [
"def",
"request_sid",
"(",
"self",
")",
":",
"if",
"self",
".",
"_sid",
":",
"return",
"self",
".",
"_sid",
"self",
".",
"log",
".",
"debug",
"(",
"'Prepare to request BOSH session'",
")",
"data",
"=",
"self",
".",
"send_request",
"(",
"self",
".",
"get_... | Request a BOSH session according to
http://xmpp.org/extensions/xep-0124.html#session-request
Returns the new SID (str). | [
"Request",
"a",
"BOSH",
"session",
"according",
"to",
"http",
":",
"//",
"xmpp",
".",
"org",
"/",
"extensions",
"/",
"xep",
"-",
"0124",
".",
"html#session",
"-",
"request",
"Returns",
"the",
"new",
"SID",
"(",
"str",
")",
"."
] | train | https://github.com/TracyWebTech/django-conversejs/blob/cd9176f007ef3853ea6321bf93b466644d89305b/conversejs/boshclient.py#L169-L217 |
TracyWebTech/django-conversejs | conversejs/boshclient.py | BOSHClient.send_challenge_response | def send_challenge_response(self, response_plain):
"""Send a challenge response to server"""
# Get a basic stanza body
body = self.get_body()
# Create a response tag and add the response content on it
# using base64 encoding
response_node = ET.SubElement(body, 'response')
response_node.set('xmlns', XMPP_SASL_NS)
response_node.text = base64.b64encode(response_plain)
# Send the challenge response to server
resp_root = ET.fromstring(self.send_request(body))
return resp_root | python | def send_challenge_response(self, response_plain):
"""Send a challenge response to server"""
# Get a basic stanza body
body = self.get_body()
# Create a response tag and add the response content on it
# using base64 encoding
response_node = ET.SubElement(body, 'response')
response_node.set('xmlns', XMPP_SASL_NS)
response_node.text = base64.b64encode(response_plain)
# Send the challenge response to server
resp_root = ET.fromstring(self.send_request(body))
return resp_root | [
"def",
"send_challenge_response",
"(",
"self",
",",
"response_plain",
")",
":",
"# Get a basic stanza body",
"body",
"=",
"self",
".",
"get_body",
"(",
")",
"# Create a response tag and add the response content on it",
"# using base64 encoding",
"response_node",
"=",
"ET",
... | Send a challenge response to server | [
"Send",
"a",
"challenge",
"response",
"to",
"server"
] | train | https://github.com/TracyWebTech/django-conversejs/blob/cd9176f007ef3853ea6321bf93b466644d89305b/conversejs/boshclient.py#L233-L247 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.