repo
stringlengths 7
55
| path
stringlengths 4
127
| func_name
stringlengths 1
88
| original_string
stringlengths 75
19.8k
| language
stringclasses 1
value | code
stringlengths 75
19.8k
| code_tokens
list | docstring
stringlengths 3
17.3k
| docstring_tokens
list | sha
stringlengths 40
40
| url
stringlengths 87
242
| partition
stringclasses 1
value |
---|---|---|---|---|---|---|---|---|---|---|---|
sirfoga/pyhal | hal/times/dates.py | Day.get_just_date | def get_just_date(self):
"""Parses just date from date-time
:return: Just day, month and year (setting hours to 00:00:00)
"""
return datetime.datetime(
self.date_time.year,
self.date_time.month,
self.date_time.day
) | python | def get_just_date(self):
"""Parses just date from date-time
:return: Just day, month and year (setting hours to 00:00:00)
"""
return datetime.datetime(
self.date_time.year,
self.date_time.month,
self.date_time.day
) | [
"def",
"get_just_date",
"(",
"self",
")",
":",
"return",
"datetime",
".",
"datetime",
"(",
"self",
".",
"date_time",
".",
"year",
",",
"self",
".",
"date_time",
".",
"month",
",",
"self",
".",
"date_time",
".",
"day",
")"
]
| Parses just date from date-time
:return: Just day, month and year (setting hours to 00:00:00) | [
"Parses",
"just",
"date",
"from",
"date",
"-",
"time"
]
| 4394d8a1f7e45bea28a255ec390f4962ee64d33a | https://github.com/sirfoga/pyhal/blob/4394d8a1f7e45bea28a255ec390f4962ee64d33a/hal/times/dates.py#L74-L83 | train |
sirfoga/pyhal | hal/times/dates.py | Day.is_date_in_between | def is_date_in_between(self, start, end, include_start=True,
include_end=True):
"""Checks if date is in between dates
:param start: Date cannot be before this date
:param end: Date cannot be after this date
:param include_start: True iff date is start
:param include_end: True iff date is end
:return: True iff date is in between dates
"""
start = Day(start).get_just_date()
now = self.get_just_date()
end = Day(end).get_just_date()
if start < now < end:
return True
if include_start and now == start:
return True
if include_end and now == end:
return True
return False | python | def is_date_in_between(self, start, end, include_start=True,
include_end=True):
"""Checks if date is in between dates
:param start: Date cannot be before this date
:param end: Date cannot be after this date
:param include_start: True iff date is start
:param include_end: True iff date is end
:return: True iff date is in between dates
"""
start = Day(start).get_just_date()
now = self.get_just_date()
end = Day(end).get_just_date()
if start < now < end:
return True
if include_start and now == start:
return True
if include_end and now == end:
return True
return False | [
"def",
"is_date_in_between",
"(",
"self",
",",
"start",
",",
"end",
",",
"include_start",
"=",
"True",
",",
"include_end",
"=",
"True",
")",
":",
"start",
"=",
"Day",
"(",
"start",
")",
".",
"get_just_date",
"(",
")",
"now",
"=",
"self",
".",
"get_just_date",
"(",
")",
"end",
"=",
"Day",
"(",
"end",
")",
".",
"get_just_date",
"(",
")",
"if",
"start",
"<",
"now",
"<",
"end",
":",
"return",
"True",
"if",
"include_start",
"and",
"now",
"==",
"start",
":",
"return",
"True",
"if",
"include_end",
"and",
"now",
"==",
"end",
":",
"return",
"True",
"return",
"False"
]
| Checks if date is in between dates
:param start: Date cannot be before this date
:param end: Date cannot be after this date
:param include_start: True iff date is start
:param include_end: True iff date is end
:return: True iff date is in between dates | [
"Checks",
"if",
"date",
"is",
"in",
"between",
"dates"
]
| 4394d8a1f7e45bea28a255ec390f4962ee64d33a | https://github.com/sirfoga/pyhal/blob/4394d8a1f7e45bea28a255ec390f4962ee64d33a/hal/times/dates.py#L96-L120 | train |
sirfoga/pyhal | hal/times/dates.py | Day.get_next_weekday | def get_next_weekday(self, including_today=False):
"""Gets next week day
:param including_today: If today is sunday and requesting next sunday
:return: Date of next monday, tuesday ..
"""
weekday = self.date_time.weekday()
return Weekday.get_next(weekday, including_today=including_today) | python | def get_next_weekday(self, including_today=False):
"""Gets next week day
:param including_today: If today is sunday and requesting next sunday
:return: Date of next monday, tuesday ..
"""
weekday = self.date_time.weekday()
return Weekday.get_next(weekday, including_today=including_today) | [
"def",
"get_next_weekday",
"(",
"self",
",",
"including_today",
"=",
"False",
")",
":",
"weekday",
"=",
"self",
".",
"date_time",
".",
"weekday",
"(",
")",
"return",
"Weekday",
".",
"get_next",
"(",
"weekday",
",",
"including_today",
"=",
"including_today",
")"
]
| Gets next week day
:param including_today: If today is sunday and requesting next sunday
:return: Date of next monday, tuesday .. | [
"Gets",
"next",
"week",
"day"
]
| 4394d8a1f7e45bea28a255ec390f4962ee64d33a | https://github.com/sirfoga/pyhal/blob/4394d8a1f7e45bea28a255ec390f4962ee64d33a/hal/times/dates.py#L122-L129 | train |
sirfoga/pyhal | hal/times/dates.py | Day.get_last_weekday | def get_last_weekday(self, including_today=False):
"""Gets last week day
:param including_today: If today is sunday and requesting next sunday
:return: Date of last monday, tuesday ..
"""
weekday = self.date_time.weekday()
return Weekday.get_last(weekday, including_today=including_today) | python | def get_last_weekday(self, including_today=False):
"""Gets last week day
:param including_today: If today is sunday and requesting next sunday
:return: Date of last monday, tuesday ..
"""
weekday = self.date_time.weekday()
return Weekday.get_last(weekday, including_today=including_today) | [
"def",
"get_last_weekday",
"(",
"self",
",",
"including_today",
"=",
"False",
")",
":",
"weekday",
"=",
"self",
".",
"date_time",
".",
"weekday",
"(",
")",
"return",
"Weekday",
".",
"get_last",
"(",
"weekday",
",",
"including_today",
"=",
"including_today",
")"
]
| Gets last week day
:param including_today: If today is sunday and requesting next sunday
:return: Date of last monday, tuesday .. | [
"Gets",
"last",
"week",
"day"
]
| 4394d8a1f7e45bea28a255ec390f4962ee64d33a | https://github.com/sirfoga/pyhal/blob/4394d8a1f7e45bea28a255ec390f4962ee64d33a/hal/times/dates.py#L131-L138 | train |
NoviceLive/intellicoder | intellicoder/main.py | cli | def cli(context, verbose, quiet, database, sense):
"""Position Independent Programming For Humans."""
logger = logging.getLogger()
handler = logging.StreamHandler(sys.stderr)
handler.setFormatter(LevelFormatter())
logger.addHandler(handler)
logger.setLevel(logging.WARNING + (quiet-verbose)*10)
logging.debug(_('Subcommand: %s'), context.invoked_subcommand)
context.obj['database'] = Database(database)
try:
context.obj['sense'] = SenseWithExport(sense).__enter__()
except Exception:
pass | python | def cli(context, verbose, quiet, database, sense):
"""Position Independent Programming For Humans."""
logger = logging.getLogger()
handler = logging.StreamHandler(sys.stderr)
handler.setFormatter(LevelFormatter())
logger.addHandler(handler)
logger.setLevel(logging.WARNING + (quiet-verbose)*10)
logging.debug(_('Subcommand: %s'), context.invoked_subcommand)
context.obj['database'] = Database(database)
try:
context.obj['sense'] = SenseWithExport(sense).__enter__()
except Exception:
pass | [
"def",
"cli",
"(",
"context",
",",
"verbose",
",",
"quiet",
",",
"database",
",",
"sense",
")",
":",
"logger",
"=",
"logging",
".",
"getLogger",
"(",
")",
"handler",
"=",
"logging",
".",
"StreamHandler",
"(",
"sys",
".",
"stderr",
")",
"handler",
".",
"setFormatter",
"(",
"LevelFormatter",
"(",
")",
")",
"logger",
".",
"addHandler",
"(",
"handler",
")",
"logger",
".",
"setLevel",
"(",
"logging",
".",
"WARNING",
"+",
"(",
"quiet",
"-",
"verbose",
")",
"*",
"10",
")",
"logging",
".",
"debug",
"(",
"_",
"(",
"'Subcommand: %s'",
")",
",",
"context",
".",
"invoked_subcommand",
")",
"context",
".",
"obj",
"[",
"'database'",
"]",
"=",
"Database",
"(",
"database",
")",
"try",
":",
"context",
".",
"obj",
"[",
"'sense'",
"]",
"=",
"SenseWithExport",
"(",
"sense",
")",
".",
"__enter__",
"(",
")",
"except",
"Exception",
":",
"pass"
]
| Position Independent Programming For Humans. | [
"Position",
"Independent",
"Programming",
"For",
"Humans",
"."
]
| 6cac5ebfce65c370dbebe47756a1789b120ef982 | https://github.com/NoviceLive/intellicoder/blob/6cac5ebfce65c370dbebe47756a1789b120ef982/intellicoder/main.py#L57-L69 | train |
NoviceLive/intellicoder | intellicoder/main.py | search | def search(context, keywords, module, raw, kind):
"""Query Windows identifiers and locations.
Windows database must be prepared before using this.
"""
logging.info(_('Entering search mode'))
sense = context.obj['sense']
func = sense.query_names if module else sense.query_info
none = True
for keyword in keywords:
output = func(keyword, raw, kind)
if output:
none = False
print(output)
else:
logging.warning(_('No results: %s'), keyword)
sys.exit(1 if none else 0) | python | def search(context, keywords, module, raw, kind):
"""Query Windows identifiers and locations.
Windows database must be prepared before using this.
"""
logging.info(_('Entering search mode'))
sense = context.obj['sense']
func = sense.query_names if module else sense.query_info
none = True
for keyword in keywords:
output = func(keyword, raw, kind)
if output:
none = False
print(output)
else:
logging.warning(_('No results: %s'), keyword)
sys.exit(1 if none else 0) | [
"def",
"search",
"(",
"context",
",",
"keywords",
",",
"module",
",",
"raw",
",",
"kind",
")",
":",
"logging",
".",
"info",
"(",
"_",
"(",
"'Entering search mode'",
")",
")",
"sense",
"=",
"context",
".",
"obj",
"[",
"'sense'",
"]",
"func",
"=",
"sense",
".",
"query_names",
"if",
"module",
"else",
"sense",
".",
"query_info",
"none",
"=",
"True",
"for",
"keyword",
"in",
"keywords",
":",
"output",
"=",
"func",
"(",
"keyword",
",",
"raw",
",",
"kind",
")",
"if",
"output",
":",
"none",
"=",
"False",
"print",
"(",
"output",
")",
"else",
":",
"logging",
".",
"warning",
"(",
"_",
"(",
"'No results: %s'",
")",
",",
"keyword",
")",
"sys",
".",
"exit",
"(",
"1",
"if",
"none",
"else",
"0",
")"
]
| Query Windows identifiers and locations.
Windows database must be prepared before using this. | [
"Query",
"Windows",
"identifiers",
"and",
"locations",
"."
]
| 6cac5ebfce65c370dbebe47756a1789b120ef982 | https://github.com/NoviceLive/intellicoder/blob/6cac5ebfce65c370dbebe47756a1789b120ef982/intellicoder/main.py#L192-L208 | train |
NoviceLive/intellicoder | intellicoder/main.py | winapi | def winapi(context, names):
"""Query Win32 API declarations.
Windows database must be prepared before using this.
"""
logging.info(_('Entering winapi mode'))
sense = context.obj['sense']
none = True
for name in names:
code = sense.query_args(name)
if code:
none = False
print(stylify_code(code))
else:
logging.warning(_('Function not found: %s'), name)
sys.exit(1 if none else 0) | python | def winapi(context, names):
"""Query Win32 API declarations.
Windows database must be prepared before using this.
"""
logging.info(_('Entering winapi mode'))
sense = context.obj['sense']
none = True
for name in names:
code = sense.query_args(name)
if code:
none = False
print(stylify_code(code))
else:
logging.warning(_('Function not found: %s'), name)
sys.exit(1 if none else 0) | [
"def",
"winapi",
"(",
"context",
",",
"names",
")",
":",
"logging",
".",
"info",
"(",
"_",
"(",
"'Entering winapi mode'",
")",
")",
"sense",
"=",
"context",
".",
"obj",
"[",
"'sense'",
"]",
"none",
"=",
"True",
"for",
"name",
"in",
"names",
":",
"code",
"=",
"sense",
".",
"query_args",
"(",
"name",
")",
"if",
"code",
":",
"none",
"=",
"False",
"print",
"(",
"stylify_code",
"(",
"code",
")",
")",
"else",
":",
"logging",
".",
"warning",
"(",
"_",
"(",
"'Function not found: %s'",
")",
",",
"name",
")",
"sys",
".",
"exit",
"(",
"1",
"if",
"none",
"else",
"0",
")"
]
| Query Win32 API declarations.
Windows database must be prepared before using this. | [
"Query",
"Win32",
"API",
"declarations",
"."
]
| 6cac5ebfce65c370dbebe47756a1789b120ef982 | https://github.com/NoviceLive/intellicoder/blob/6cac5ebfce65c370dbebe47756a1789b120ef982/intellicoder/main.py#L214-L229 | train |
NoviceLive/intellicoder | intellicoder/main.py | kinds | def kinds(context, show_all, ids_or_names):
"""Operate on IntelliSense kind ids and names.
Without an argument, list all available kinds and their ids.
Windows database must be prepared before using this.
"""
logging.info(_('Entering kind mode'))
logging.debug('args: %s', ids_or_names)
sense = context.obj['sense']
none = True
if show_all:
none = False
print(sense.query_kinds(None))
else:
for id_or_name in ids_or_names:
id_name = sense.query_kinds(id_or_name)
if id_name:
none = False
print(id_name)
sys.exit(1 if none else 0) | python | def kinds(context, show_all, ids_or_names):
"""Operate on IntelliSense kind ids and names.
Without an argument, list all available kinds and their ids.
Windows database must be prepared before using this.
"""
logging.info(_('Entering kind mode'))
logging.debug('args: %s', ids_or_names)
sense = context.obj['sense']
none = True
if show_all:
none = False
print(sense.query_kinds(None))
else:
for id_or_name in ids_or_names:
id_name = sense.query_kinds(id_or_name)
if id_name:
none = False
print(id_name)
sys.exit(1 if none else 0) | [
"def",
"kinds",
"(",
"context",
",",
"show_all",
",",
"ids_or_names",
")",
":",
"logging",
".",
"info",
"(",
"_",
"(",
"'Entering kind mode'",
")",
")",
"logging",
".",
"debug",
"(",
"'args: %s'",
",",
"ids_or_names",
")",
"sense",
"=",
"context",
".",
"obj",
"[",
"'sense'",
"]",
"none",
"=",
"True",
"if",
"show_all",
":",
"none",
"=",
"False",
"print",
"(",
"sense",
".",
"query_kinds",
"(",
"None",
")",
")",
"else",
":",
"for",
"id_or_name",
"in",
"ids_or_names",
":",
"id_name",
"=",
"sense",
".",
"query_kinds",
"(",
"id_or_name",
")",
"if",
"id_name",
":",
"none",
"=",
"False",
"print",
"(",
"id_name",
")",
"sys",
".",
"exit",
"(",
"1",
"if",
"none",
"else",
"0",
")"
]
| Operate on IntelliSense kind ids and names.
Without an argument, list all available kinds and their ids.
Windows database must be prepared before using this. | [
"Operate",
"on",
"IntelliSense",
"kind",
"ids",
"and",
"names",
"."
]
| 6cac5ebfce65c370dbebe47756a1789b120ef982 | https://github.com/NoviceLive/intellicoder/blob/6cac5ebfce65c370dbebe47756a1789b120ef982/intellicoder/main.py#L237-L257 | train |
NoviceLive/intellicoder | intellicoder/main.py | export | def export(context, keywords, module, update):
"""Operate on libraries and exported functions.
Query the module name containing the function by default.
Windows database must be prepared before using this.
"""
logging.info(_('Export Mode'))
database = context.obj['sense']
none = True
if update:
exports = OrderedDict()
from .executables.pe import PE
for filename in keywords:
module = split_ext(filename, basename=True)[0]
with open(filename, 'rb') as stream:
exports.update(
{module: PE(stream).get_export_table()})
database.make_export(exports)
none = False
elif module:
for module_name in keywords:
funcs = database.query_module_funcs(module_name)
if funcs:
none = False
print(', '.join(map(str, funcs)))
else:
logging.warning(_('No function for module: %s'),
module_name)
else:
for func_name in keywords:
module_name = database.query_func_module(func_name)
if module_name:
none = False
print(repr(module_name))
else:
logging.warning(_('No module for function: %s'),
func_name)
sys.exit(1 if none else 0) | python | def export(context, keywords, module, update):
"""Operate on libraries and exported functions.
Query the module name containing the function by default.
Windows database must be prepared before using this.
"""
logging.info(_('Export Mode'))
database = context.obj['sense']
none = True
if update:
exports = OrderedDict()
from .executables.pe import PE
for filename in keywords:
module = split_ext(filename, basename=True)[0]
with open(filename, 'rb') as stream:
exports.update(
{module: PE(stream).get_export_table()})
database.make_export(exports)
none = False
elif module:
for module_name in keywords:
funcs = database.query_module_funcs(module_name)
if funcs:
none = False
print(', '.join(map(str, funcs)))
else:
logging.warning(_('No function for module: %s'),
module_name)
else:
for func_name in keywords:
module_name = database.query_func_module(func_name)
if module_name:
none = False
print(repr(module_name))
else:
logging.warning(_('No module for function: %s'),
func_name)
sys.exit(1 if none else 0) | [
"def",
"export",
"(",
"context",
",",
"keywords",
",",
"module",
",",
"update",
")",
":",
"logging",
".",
"info",
"(",
"_",
"(",
"'Export Mode'",
")",
")",
"database",
"=",
"context",
".",
"obj",
"[",
"'sense'",
"]",
"none",
"=",
"True",
"if",
"update",
":",
"exports",
"=",
"OrderedDict",
"(",
")",
"from",
".",
"executables",
".",
"pe",
"import",
"PE",
"for",
"filename",
"in",
"keywords",
":",
"module",
"=",
"split_ext",
"(",
"filename",
",",
"basename",
"=",
"True",
")",
"[",
"0",
"]",
"with",
"open",
"(",
"filename",
",",
"'rb'",
")",
"as",
"stream",
":",
"exports",
".",
"update",
"(",
"{",
"module",
":",
"PE",
"(",
"stream",
")",
".",
"get_export_table",
"(",
")",
"}",
")",
"database",
".",
"make_export",
"(",
"exports",
")",
"none",
"=",
"False",
"elif",
"module",
":",
"for",
"module_name",
"in",
"keywords",
":",
"funcs",
"=",
"database",
".",
"query_module_funcs",
"(",
"module_name",
")",
"if",
"funcs",
":",
"none",
"=",
"False",
"print",
"(",
"', '",
".",
"join",
"(",
"map",
"(",
"str",
",",
"funcs",
")",
")",
")",
"else",
":",
"logging",
".",
"warning",
"(",
"_",
"(",
"'No function for module: %s'",
")",
",",
"module_name",
")",
"else",
":",
"for",
"func_name",
"in",
"keywords",
":",
"module_name",
"=",
"database",
".",
"query_func_module",
"(",
"func_name",
")",
"if",
"module_name",
":",
"none",
"=",
"False",
"print",
"(",
"repr",
"(",
"module_name",
")",
")",
"else",
":",
"logging",
".",
"warning",
"(",
"_",
"(",
"'No module for function: %s'",
")",
",",
"func_name",
")",
"sys",
".",
"exit",
"(",
"1",
"if",
"none",
"else",
"0",
")"
]
| Operate on libraries and exported functions.
Query the module name containing the function by default.
Windows database must be prepared before using this. | [
"Operate",
"on",
"libraries",
"and",
"exported",
"functions",
"."
]
| 6cac5ebfce65c370dbebe47756a1789b120ef982 | https://github.com/NoviceLive/intellicoder/blob/6cac5ebfce65c370dbebe47756a1789b120ef982/intellicoder/main.py#L267-L305 | train |
NoviceLive/intellicoder | intellicoder/main.py | add | def add(context, filenames):
"""Add data on Linux system calls.
Arguments shall be *.tbl files from Linux x86 source code,
or output from grep.
Delete the old database before adding if necessary.
"""
logging.info(_('Current Mode: Add Linux data'))
context.obj['database'].add_data(filenames)
sys.exit(0) | python | def add(context, filenames):
"""Add data on Linux system calls.
Arguments shall be *.tbl files from Linux x86 source code,
or output from grep.
Delete the old database before adding if necessary.
"""
logging.info(_('Current Mode: Add Linux data'))
context.obj['database'].add_data(filenames)
sys.exit(0) | [
"def",
"add",
"(",
"context",
",",
"filenames",
")",
":",
"logging",
".",
"info",
"(",
"_",
"(",
"'Current Mode: Add Linux data'",
")",
")",
"context",
".",
"obj",
"[",
"'database'",
"]",
".",
"add_data",
"(",
"filenames",
")",
"sys",
".",
"exit",
"(",
"0",
")"
]
| Add data on Linux system calls.
Arguments shall be *.tbl files from Linux x86 source code,
or output from grep.
Delete the old database before adding if necessary. | [
"Add",
"data",
"on",
"Linux",
"system",
"calls",
"."
]
| 6cac5ebfce65c370dbebe47756a1789b120ef982 | https://github.com/NoviceLive/intellicoder/blob/6cac5ebfce65c370dbebe47756a1789b120ef982/intellicoder/main.py#L312-L322 | train |
NoviceLive/intellicoder | intellicoder/main.py | make | def make(filenames, x64, cl_args, link_args, output):
"""Make binaries from sources.
Note that this is incomplete.
"""
from .msbuild import Builder
builder = Builder()
builder.build(list(filenames), x64=x64,
cl_args=cl_args, link_args=link_args,
out_dir=output) | python | def make(filenames, x64, cl_args, link_args, output):
"""Make binaries from sources.
Note that this is incomplete.
"""
from .msbuild import Builder
builder = Builder()
builder.build(list(filenames), x64=x64,
cl_args=cl_args, link_args=link_args,
out_dir=output) | [
"def",
"make",
"(",
"filenames",
",",
"x64",
",",
"cl_args",
",",
"link_args",
",",
"output",
")",
":",
"from",
".",
"msbuild",
"import",
"Builder",
"builder",
"=",
"Builder",
"(",
")",
"builder",
".",
"build",
"(",
"list",
"(",
"filenames",
")",
",",
"x64",
"=",
"x64",
",",
"cl_args",
"=",
"cl_args",
",",
"link_args",
"=",
"link_args",
",",
"out_dir",
"=",
"output",
")"
]
| Make binaries from sources.
Note that this is incomplete. | [
"Make",
"binaries",
"from",
"sources",
"."
]
| 6cac5ebfce65c370dbebe47756a1789b120ef982 | https://github.com/NoviceLive/intellicoder/blob/6cac5ebfce65c370dbebe47756a1789b120ef982/intellicoder/main.py#L331-L340 | train |
NoviceLive/intellicoder | intellicoder/main.py | info | def info(context, keywords, x86, x64, x32, common):
"""Find in the Linux system calls.
"""
logging.info(_('Current Mode: Find in Linux'))
database = context.obj['database']
for one in keywords:
abis = ['i386', 'x64', 'common', 'x32']
if x86:
abis = ['i386']
if x64:
abis = ['x64', 'common']
if x32:
abis = ['x32', 'common']
if common:
abis = ['common']
items = database.query_item(one, abis)
if not items:
logging.warning(_('Item not found: %s %s'), one, abis)
continue
for item in items:
print(item.name, item.abi, item.number)
decl = database.query_decl(name=item.name)
if not decl:
logging.warning(_('Decl not found: %s'), item.name)
continue
for one in decl:
print(one.decl(), '/* {} */'.format(one.filename))
sys.exit(0) | python | def info(context, keywords, x86, x64, x32, common):
"""Find in the Linux system calls.
"""
logging.info(_('Current Mode: Find in Linux'))
database = context.obj['database']
for one in keywords:
abis = ['i386', 'x64', 'common', 'x32']
if x86:
abis = ['i386']
if x64:
abis = ['x64', 'common']
if x32:
abis = ['x32', 'common']
if common:
abis = ['common']
items = database.query_item(one, abis)
if not items:
logging.warning(_('Item not found: %s %s'), one, abis)
continue
for item in items:
print(item.name, item.abi, item.number)
decl = database.query_decl(name=item.name)
if not decl:
logging.warning(_('Decl not found: %s'), item.name)
continue
for one in decl:
print(one.decl(), '/* {} */'.format(one.filename))
sys.exit(0) | [
"def",
"info",
"(",
"context",
",",
"keywords",
",",
"x86",
",",
"x64",
",",
"x32",
",",
"common",
")",
":",
"logging",
".",
"info",
"(",
"_",
"(",
"'Current Mode: Find in Linux'",
")",
")",
"database",
"=",
"context",
".",
"obj",
"[",
"'database'",
"]",
"for",
"one",
"in",
"keywords",
":",
"abis",
"=",
"[",
"'i386'",
",",
"'x64'",
",",
"'common'",
",",
"'x32'",
"]",
"if",
"x86",
":",
"abis",
"=",
"[",
"'i386'",
"]",
"if",
"x64",
":",
"abis",
"=",
"[",
"'x64'",
",",
"'common'",
"]",
"if",
"x32",
":",
"abis",
"=",
"[",
"'x32'",
",",
"'common'",
"]",
"if",
"common",
":",
"abis",
"=",
"[",
"'common'",
"]",
"items",
"=",
"database",
".",
"query_item",
"(",
"one",
",",
"abis",
")",
"if",
"not",
"items",
":",
"logging",
".",
"warning",
"(",
"_",
"(",
"'Item not found: %s %s'",
")",
",",
"one",
",",
"abis",
")",
"continue",
"for",
"item",
"in",
"items",
":",
"print",
"(",
"item",
".",
"name",
",",
"item",
".",
"abi",
",",
"item",
".",
"number",
")",
"decl",
"=",
"database",
".",
"query_decl",
"(",
"name",
"=",
"item",
".",
"name",
")",
"if",
"not",
"decl",
":",
"logging",
".",
"warning",
"(",
"_",
"(",
"'Decl not found: %s'",
")",
",",
"item",
".",
"name",
")",
"continue",
"for",
"one",
"in",
"decl",
":",
"print",
"(",
"one",
".",
"decl",
"(",
")",
",",
"'/* {} */'",
".",
"format",
"(",
"one",
".",
"filename",
")",
")",
"sys",
".",
"exit",
"(",
"0",
")"
]
| Find in the Linux system calls. | [
"Find",
"in",
"the",
"Linux",
"system",
"calls",
"."
]
| 6cac5ebfce65c370dbebe47756a1789b120ef982 | https://github.com/NoviceLive/intellicoder/blob/6cac5ebfce65c370dbebe47756a1789b120ef982/intellicoder/main.py#L350-L377 | train |
NoviceLive/intellicoder | intellicoder/main.py | conv | def conv(arg, source, target, filename, section):
"""Convert binary.
Extract bytes in the given section from binary files
and construct C source code
that can be used to test as shellcode.
Supported executable formats:
ELF via pyelftools and PE via pefile.
"""
logging.info(_('This is Binary Conversion mode.'))
section = section.encode('utf-8')
if source == 'sec':
arg = open(arg, 'rb')
if source == 'sec':
kwargs = dict(section_name=section)
else:
kwargs = dict()
result = Converter.uni_from(source, arg, **kwargs).uni_to(target)
if result:
if filename:
logging.info(
_('Writing shellcode to the file: %s'), filename)
mode = 'wb' if target == 'bin' else 'w'
with open(filename, mode) as output:
output.write(result)
else:
print(result)
else:
logging.error(_('Failed.'))
if source == 'sec':
arg.close()
return 0 | python | def conv(arg, source, target, filename, section):
"""Convert binary.
Extract bytes in the given section from binary files
and construct C source code
that can be used to test as shellcode.
Supported executable formats:
ELF via pyelftools and PE via pefile.
"""
logging.info(_('This is Binary Conversion mode.'))
section = section.encode('utf-8')
if source == 'sec':
arg = open(arg, 'rb')
if source == 'sec':
kwargs = dict(section_name=section)
else:
kwargs = dict()
result = Converter.uni_from(source, arg, **kwargs).uni_to(target)
if result:
if filename:
logging.info(
_('Writing shellcode to the file: %s'), filename)
mode = 'wb' if target == 'bin' else 'w'
with open(filename, mode) as output:
output.write(result)
else:
print(result)
else:
logging.error(_('Failed.'))
if source == 'sec':
arg.close()
return 0 | [
"def",
"conv",
"(",
"arg",
",",
"source",
",",
"target",
",",
"filename",
",",
"section",
")",
":",
"logging",
".",
"info",
"(",
"_",
"(",
"'This is Binary Conversion mode.'",
")",
")",
"section",
"=",
"section",
".",
"encode",
"(",
"'utf-8'",
")",
"if",
"source",
"==",
"'sec'",
":",
"arg",
"=",
"open",
"(",
"arg",
",",
"'rb'",
")",
"if",
"source",
"==",
"'sec'",
":",
"kwargs",
"=",
"dict",
"(",
"section_name",
"=",
"section",
")",
"else",
":",
"kwargs",
"=",
"dict",
"(",
")",
"result",
"=",
"Converter",
".",
"uni_from",
"(",
"source",
",",
"arg",
",",
"*",
"*",
"kwargs",
")",
".",
"uni_to",
"(",
"target",
")",
"if",
"result",
":",
"if",
"filename",
":",
"logging",
".",
"info",
"(",
"_",
"(",
"'Writing shellcode to the file: %s'",
")",
",",
"filename",
")",
"mode",
"=",
"'wb'",
"if",
"target",
"==",
"'bin'",
"else",
"'w'",
"with",
"open",
"(",
"filename",
",",
"mode",
")",
"as",
"output",
":",
"output",
".",
"write",
"(",
"result",
")",
"else",
":",
"print",
"(",
"result",
")",
"else",
":",
"logging",
".",
"error",
"(",
"_",
"(",
"'Failed.'",
")",
")",
"if",
"source",
"==",
"'sec'",
":",
"arg",
".",
"close",
"(",
")",
"return",
"0"
]
| Convert binary.
Extract bytes in the given section from binary files
and construct C source code
that can be used to test as shellcode.
Supported executable formats:
ELF via pyelftools and PE via pefile. | [
"Convert",
"binary",
"."
]
| 6cac5ebfce65c370dbebe47756a1789b120ef982 | https://github.com/NoviceLive/intellicoder/blob/6cac5ebfce65c370dbebe47756a1789b120ef982/intellicoder/main.py#L392-L424 | train |
loganasherjones/yapconf | yapconf/sources.py | get_source | def get_source(label, source_type, **kwargs):
"""Get a config source based on type and keyword args.
This is meant to be used internally by the spec via ``add_source``.
Args:
label (str): The label for this source.
source_type: The type of source. See ``yapconf.SUPPORTED_SOURCES``
Keyword Args:
The keyword arguments are based on the source_type. Please see the
documentation of the individual sources for a detailed list of all
possible arguments.
Returns (yapconf.sources.ConfigSource):
A valid config source which can be used for generating an override.
Raises:
YapconfSourceError: If there is some kind of error with this source
definition.
"""
if source_type not in yapconf.ALL_SUPPORTED_SOURCES:
raise YapconfSourceError(
'Invalid source type %s. Supported types are %s.' %
(source_type, yapconf.ALL_SUPPORTED_SOURCES)
)
if source_type not in yapconf.SUPPORTED_SOURCES:
raise YapconfSourceError(
'Unsupported source type "%s". If you want to use this type, you '
'will need to install the correct client for it (try `pip install '
'yapconf[%s]. Currently supported types are %s. All supported '
'types are %s' %
(source_type, source_type, yapconf.SUPPORTED_SOURCES,
yapconf.ALL_SUPPORTED_SOURCES)
)
# We pop arguments from kwargs because the individual config sources
# have better error messages if a keyword argument is missed.
if source_type == 'dict':
return DictConfigSource(label, data=kwargs.get('data'))
elif source_type == 'json':
return JsonConfigSource(label, **kwargs)
elif source_type == 'yaml':
filename = kwargs.get('filename')
if 'filename' in kwargs:
kwargs.pop('filename')
return YamlConfigSource(label, filename, **kwargs)
elif source_type == 'environment':
return EnvironmentConfigSource(label)
elif source_type == 'etcd':
return EtcdConfigSource(
label, kwargs.get('client'), kwargs.get('key', '/')
)
elif source_type == 'kubernetes':
name = kwargs.get('name')
if 'name' in kwargs:
kwargs.pop('name')
client = kwargs.get('client')
if 'client' in kwargs:
kwargs.pop('client')
return KubernetesConfigSource(label, client, name, **kwargs)
else:
raise NotImplementedError(
'No implementation for source type %s' % source_type
) | python | def get_source(label, source_type, **kwargs):
"""Get a config source based on type and keyword args.
This is meant to be used internally by the spec via ``add_source``.
Args:
label (str): The label for this source.
source_type: The type of source. See ``yapconf.SUPPORTED_SOURCES``
Keyword Args:
The keyword arguments are based on the source_type. Please see the
documentation of the individual sources for a detailed list of all
possible arguments.
Returns (yapconf.sources.ConfigSource):
A valid config source which can be used for generating an override.
Raises:
YapconfSourceError: If there is some kind of error with this source
definition.
"""
if source_type not in yapconf.ALL_SUPPORTED_SOURCES:
raise YapconfSourceError(
'Invalid source type %s. Supported types are %s.' %
(source_type, yapconf.ALL_SUPPORTED_SOURCES)
)
if source_type not in yapconf.SUPPORTED_SOURCES:
raise YapconfSourceError(
'Unsupported source type "%s". If you want to use this type, you '
'will need to install the correct client for it (try `pip install '
'yapconf[%s]. Currently supported types are %s. All supported '
'types are %s' %
(source_type, source_type, yapconf.SUPPORTED_SOURCES,
yapconf.ALL_SUPPORTED_SOURCES)
)
# We pop arguments from kwargs because the individual config sources
# have better error messages if a keyword argument is missed.
if source_type == 'dict':
return DictConfigSource(label, data=kwargs.get('data'))
elif source_type == 'json':
return JsonConfigSource(label, **kwargs)
elif source_type == 'yaml':
filename = kwargs.get('filename')
if 'filename' in kwargs:
kwargs.pop('filename')
return YamlConfigSource(label, filename, **kwargs)
elif source_type == 'environment':
return EnvironmentConfigSource(label)
elif source_type == 'etcd':
return EtcdConfigSource(
label, kwargs.get('client'), kwargs.get('key', '/')
)
elif source_type == 'kubernetes':
name = kwargs.get('name')
if 'name' in kwargs:
kwargs.pop('name')
client = kwargs.get('client')
if 'client' in kwargs:
kwargs.pop('client')
return KubernetesConfigSource(label, client, name, **kwargs)
else:
raise NotImplementedError(
'No implementation for source type %s' % source_type
) | [
"def",
"get_source",
"(",
"label",
",",
"source_type",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"source_type",
"not",
"in",
"yapconf",
".",
"ALL_SUPPORTED_SOURCES",
":",
"raise",
"YapconfSourceError",
"(",
"'Invalid source type %s. Supported types are %s.'",
"%",
"(",
"source_type",
",",
"yapconf",
".",
"ALL_SUPPORTED_SOURCES",
")",
")",
"if",
"source_type",
"not",
"in",
"yapconf",
".",
"SUPPORTED_SOURCES",
":",
"raise",
"YapconfSourceError",
"(",
"'Unsupported source type \"%s\". If you want to use this type, you '",
"'will need to install the correct client for it (try `pip install '",
"'yapconf[%s]. Currently supported types are %s. All supported '",
"'types are %s'",
"%",
"(",
"source_type",
",",
"source_type",
",",
"yapconf",
".",
"SUPPORTED_SOURCES",
",",
"yapconf",
".",
"ALL_SUPPORTED_SOURCES",
")",
")",
"# We pop arguments from kwargs because the individual config sources",
"# have better error messages if a keyword argument is missed.",
"if",
"source_type",
"==",
"'dict'",
":",
"return",
"DictConfigSource",
"(",
"label",
",",
"data",
"=",
"kwargs",
".",
"get",
"(",
"'data'",
")",
")",
"elif",
"source_type",
"==",
"'json'",
":",
"return",
"JsonConfigSource",
"(",
"label",
",",
"*",
"*",
"kwargs",
")",
"elif",
"source_type",
"==",
"'yaml'",
":",
"filename",
"=",
"kwargs",
".",
"get",
"(",
"'filename'",
")",
"if",
"'filename'",
"in",
"kwargs",
":",
"kwargs",
".",
"pop",
"(",
"'filename'",
")",
"return",
"YamlConfigSource",
"(",
"label",
",",
"filename",
",",
"*",
"*",
"kwargs",
")",
"elif",
"source_type",
"==",
"'environment'",
":",
"return",
"EnvironmentConfigSource",
"(",
"label",
")",
"elif",
"source_type",
"==",
"'etcd'",
":",
"return",
"EtcdConfigSource",
"(",
"label",
",",
"kwargs",
".",
"get",
"(",
"'client'",
")",
",",
"kwargs",
".",
"get",
"(",
"'key'",
",",
"'/'",
")",
")",
"elif",
"source_type",
"==",
"'kubernetes'",
":",
"name",
"=",
"kwargs",
".",
"get",
"(",
"'name'",
")",
"if",
"'name'",
"in",
"kwargs",
":",
"kwargs",
".",
"pop",
"(",
"'name'",
")",
"client",
"=",
"kwargs",
".",
"get",
"(",
"'client'",
")",
"if",
"'client'",
"in",
"kwargs",
":",
"kwargs",
".",
"pop",
"(",
"'client'",
")",
"return",
"KubernetesConfigSource",
"(",
"label",
",",
"client",
",",
"name",
",",
"*",
"*",
"kwargs",
")",
"else",
":",
"raise",
"NotImplementedError",
"(",
"'No implementation for source type %s'",
"%",
"source_type",
")"
]
| Get a config source based on type and keyword args.
This is meant to be used internally by the spec via ``add_source``.
Args:
label (str): The label for this source.
source_type: The type of source. See ``yapconf.SUPPORTED_SOURCES``
Keyword Args:
The keyword arguments are based on the source_type. Please see the
documentation of the individual sources for a detailed list of all
possible arguments.
Returns (yapconf.sources.ConfigSource):
A valid config source which can be used for generating an override.
Raises:
YapconfSourceError: If there is some kind of error with this source
definition. | [
"Get",
"a",
"config",
"source",
"based",
"on",
"type",
"and",
"keyword",
"args",
"."
]
| d2970e6e7e3334615d4d978d8b0ca33006d79d16 | https://github.com/loganasherjones/yapconf/blob/d2970e6e7e3334615d4d978d8b0ca33006d79d16/yapconf/sources.py#L23-L95 | train |
iqbal-lab-org/cluster_vcf_records | cluster_vcf_records/vcf_record_cluster.py | VcfRecordCluster.make_simple_merged_vcf_with_no_combinations | def make_simple_merged_vcf_with_no_combinations(self, ref_seq):
'''Does a simple merging of all variants in this cluster.
Assumes one ALT in each variant. Uses the ALT for each
variant, making one new vcf_record that has all the variants
put together'''
if len(self) <= 1:
return
merged_vcf_record = self.vcf_records[0]
for i in range(1, len(self.vcf_records), 1):
if self.vcf_records[i].intersects(merged_vcf_record):
return
else:
merged_vcf_record = merged_vcf_record.merge(self.vcf_records[i], ref_seq)
self.vcf_records = [merged_vcf_record] | python | def make_simple_merged_vcf_with_no_combinations(self, ref_seq):
'''Does a simple merging of all variants in this cluster.
Assumes one ALT in each variant. Uses the ALT for each
variant, making one new vcf_record that has all the variants
put together'''
if len(self) <= 1:
return
merged_vcf_record = self.vcf_records[0]
for i in range(1, len(self.vcf_records), 1):
if self.vcf_records[i].intersects(merged_vcf_record):
return
else:
merged_vcf_record = merged_vcf_record.merge(self.vcf_records[i], ref_seq)
self.vcf_records = [merged_vcf_record] | [
"def",
"make_simple_merged_vcf_with_no_combinations",
"(",
"self",
",",
"ref_seq",
")",
":",
"if",
"len",
"(",
"self",
")",
"<=",
"1",
":",
"return",
"merged_vcf_record",
"=",
"self",
".",
"vcf_records",
"[",
"0",
"]",
"for",
"i",
"in",
"range",
"(",
"1",
",",
"len",
"(",
"self",
".",
"vcf_records",
")",
",",
"1",
")",
":",
"if",
"self",
".",
"vcf_records",
"[",
"i",
"]",
".",
"intersects",
"(",
"merged_vcf_record",
")",
":",
"return",
"else",
":",
"merged_vcf_record",
"=",
"merged_vcf_record",
".",
"merge",
"(",
"self",
".",
"vcf_records",
"[",
"i",
"]",
",",
"ref_seq",
")",
"self",
".",
"vcf_records",
"=",
"[",
"merged_vcf_record",
"]"
]
| Does a simple merging of all variants in this cluster.
Assumes one ALT in each variant. Uses the ALT for each
variant, making one new vcf_record that has all the variants
put together | [
"Does",
"a",
"simple",
"merging",
"of",
"all",
"variants",
"in",
"this",
"cluster",
".",
"Assumes",
"one",
"ALT",
"in",
"each",
"variant",
".",
"Uses",
"the",
"ALT",
"for",
"each",
"variant",
"making",
"one",
"new",
"vcf_record",
"that",
"has",
"all",
"the",
"variants",
"put",
"together"
]
| 0db26af36b6da97a7361364457d2152dc756055c | https://github.com/iqbal-lab-org/cluster_vcf_records/blob/0db26af36b6da97a7361364457d2152dc756055c/cluster_vcf_records/vcf_record_cluster.py#L140-L156 | train |
iqbal-lab-org/cluster_vcf_records | cluster_vcf_records/vcf_record_cluster.py | VcfRecordCluster.make_simple_gt_aware_merged_vcf_with_no_combinations | def make_simple_gt_aware_merged_vcf_with_no_combinations(self, ref_seq):
'''Does a simple merging of all variants in this cluster.
Assumes one ALT in each variant. Uses the called allele for each
variant, making one new vcf_record that has all the variants
put together'''
if len(self) <= 1:
return
merged_vcf_record = self.vcf_records[0]
for i in range(1, len(self.vcf_records), 1):
if self.vcf_records[i].intersects(merged_vcf_record):
return
else:
merged_vcf_record = merged_vcf_record.gt_aware_merge(self.vcf_records[i], ref_seq)
self.vcf_records = [merged_vcf_record] | python | def make_simple_gt_aware_merged_vcf_with_no_combinations(self, ref_seq):
'''Does a simple merging of all variants in this cluster.
Assumes one ALT in each variant. Uses the called allele for each
variant, making one new vcf_record that has all the variants
put together'''
if len(self) <= 1:
return
merged_vcf_record = self.vcf_records[0]
for i in range(1, len(self.vcf_records), 1):
if self.vcf_records[i].intersects(merged_vcf_record):
return
else:
merged_vcf_record = merged_vcf_record.gt_aware_merge(self.vcf_records[i], ref_seq)
self.vcf_records = [merged_vcf_record] | [
"def",
"make_simple_gt_aware_merged_vcf_with_no_combinations",
"(",
"self",
",",
"ref_seq",
")",
":",
"if",
"len",
"(",
"self",
")",
"<=",
"1",
":",
"return",
"merged_vcf_record",
"=",
"self",
".",
"vcf_records",
"[",
"0",
"]",
"for",
"i",
"in",
"range",
"(",
"1",
",",
"len",
"(",
"self",
".",
"vcf_records",
")",
",",
"1",
")",
":",
"if",
"self",
".",
"vcf_records",
"[",
"i",
"]",
".",
"intersects",
"(",
"merged_vcf_record",
")",
":",
"return",
"else",
":",
"merged_vcf_record",
"=",
"merged_vcf_record",
".",
"gt_aware_merge",
"(",
"self",
".",
"vcf_records",
"[",
"i",
"]",
",",
"ref_seq",
")",
"self",
".",
"vcf_records",
"=",
"[",
"merged_vcf_record",
"]"
]
| Does a simple merging of all variants in this cluster.
Assumes one ALT in each variant. Uses the called allele for each
variant, making one new vcf_record that has all the variants
put together | [
"Does",
"a",
"simple",
"merging",
"of",
"all",
"variants",
"in",
"this",
"cluster",
".",
"Assumes",
"one",
"ALT",
"in",
"each",
"variant",
".",
"Uses",
"the",
"called",
"allele",
"for",
"each",
"variant",
"making",
"one",
"new",
"vcf_record",
"that",
"has",
"all",
"the",
"variants",
"put",
"together"
]
| 0db26af36b6da97a7361364457d2152dc756055c | https://github.com/iqbal-lab-org/cluster_vcf_records/blob/0db26af36b6da97a7361364457d2152dc756055c/cluster_vcf_records/vcf_record_cluster.py#L158-L174 | train |
iqbal-lab-org/cluster_vcf_records | cluster_vcf_records/vcf_record_cluster.py | VcfRecordCluster.make_separate_indels_and_one_alt_with_all_snps_no_combinations | def make_separate_indels_and_one_alt_with_all_snps_no_combinations(self, ref_seq):
'''Returns a VCF record, where each indel from this
cluster is in a separate ALT. Then all the remaining SNPs are
applied to make one ALT. If >1 SNP in same place, either one
might be used'''
final_start_position = min([x.POS for x in self.vcf_records])
final_end_position = max([x.ref_end_pos() for x in self.vcf_records])
snps = []
new_vcf_records = []
for record in self.vcf_records:
if record.is_snp():
snps.append(copy.copy(record))
else:
new_record = copy.copy(record)
new_record.add_flanking_seqs(ref_seq, final_start_position, final_end_position)
new_vcf_records.append(new_record)
if len(snps):
new_record = copy.copy(snps[0])
for snp in snps[1:]:
merged = new_record.merge(snp, ref_seq)
if merged is not None:
new_record = merged
new_record.add_flanking_seqs(ref_seq, final_start_position, final_end_position)
new_vcf_records.append(new_record)
alts = ','.join(sorted(list(set([x.ALT[0] for x in new_vcf_records]))))
new_record = vcf_record.VcfRecord('\t'.join([self.vcf_records[0].CHROM, str(final_start_position + 1), '.', new_vcf_records[0].REF, alts, '.', 'PASS', '.']))
return new_record | python | def make_separate_indels_and_one_alt_with_all_snps_no_combinations(self, ref_seq):
'''Returns a VCF record, where each indel from this
cluster is in a separate ALT. Then all the remaining SNPs are
applied to make one ALT. If >1 SNP in same place, either one
might be used'''
final_start_position = min([x.POS for x in self.vcf_records])
final_end_position = max([x.ref_end_pos() for x in self.vcf_records])
snps = []
new_vcf_records = []
for record in self.vcf_records:
if record.is_snp():
snps.append(copy.copy(record))
else:
new_record = copy.copy(record)
new_record.add_flanking_seqs(ref_seq, final_start_position, final_end_position)
new_vcf_records.append(new_record)
if len(snps):
new_record = copy.copy(snps[0])
for snp in snps[1:]:
merged = new_record.merge(snp, ref_seq)
if merged is not None:
new_record = merged
new_record.add_flanking_seqs(ref_seq, final_start_position, final_end_position)
new_vcf_records.append(new_record)
alts = ','.join(sorted(list(set([x.ALT[0] for x in new_vcf_records]))))
new_record = vcf_record.VcfRecord('\t'.join([self.vcf_records[0].CHROM, str(final_start_position + 1), '.', new_vcf_records[0].REF, alts, '.', 'PASS', '.']))
return new_record | [
"def",
"make_separate_indels_and_one_alt_with_all_snps_no_combinations",
"(",
"self",
",",
"ref_seq",
")",
":",
"final_start_position",
"=",
"min",
"(",
"[",
"x",
".",
"POS",
"for",
"x",
"in",
"self",
".",
"vcf_records",
"]",
")",
"final_end_position",
"=",
"max",
"(",
"[",
"x",
".",
"ref_end_pos",
"(",
")",
"for",
"x",
"in",
"self",
".",
"vcf_records",
"]",
")",
"snps",
"=",
"[",
"]",
"new_vcf_records",
"=",
"[",
"]",
"for",
"record",
"in",
"self",
".",
"vcf_records",
":",
"if",
"record",
".",
"is_snp",
"(",
")",
":",
"snps",
".",
"append",
"(",
"copy",
".",
"copy",
"(",
"record",
")",
")",
"else",
":",
"new_record",
"=",
"copy",
".",
"copy",
"(",
"record",
")",
"new_record",
".",
"add_flanking_seqs",
"(",
"ref_seq",
",",
"final_start_position",
",",
"final_end_position",
")",
"new_vcf_records",
".",
"append",
"(",
"new_record",
")",
"if",
"len",
"(",
"snps",
")",
":",
"new_record",
"=",
"copy",
".",
"copy",
"(",
"snps",
"[",
"0",
"]",
")",
"for",
"snp",
"in",
"snps",
"[",
"1",
":",
"]",
":",
"merged",
"=",
"new_record",
".",
"merge",
"(",
"snp",
",",
"ref_seq",
")",
"if",
"merged",
"is",
"not",
"None",
":",
"new_record",
"=",
"merged",
"new_record",
".",
"add_flanking_seqs",
"(",
"ref_seq",
",",
"final_start_position",
",",
"final_end_position",
")",
"new_vcf_records",
".",
"append",
"(",
"new_record",
")",
"alts",
"=",
"','",
".",
"join",
"(",
"sorted",
"(",
"list",
"(",
"set",
"(",
"[",
"x",
".",
"ALT",
"[",
"0",
"]",
"for",
"x",
"in",
"new_vcf_records",
"]",
")",
")",
")",
")",
"new_record",
"=",
"vcf_record",
".",
"VcfRecord",
"(",
"'\\t'",
".",
"join",
"(",
"[",
"self",
".",
"vcf_records",
"[",
"0",
"]",
".",
"CHROM",
",",
"str",
"(",
"final_start_position",
"+",
"1",
")",
",",
"'.'",
",",
"new_vcf_records",
"[",
"0",
"]",
".",
"REF",
",",
"alts",
",",
"'.'",
",",
"'PASS'",
",",
"'.'",
"]",
")",
")",
"return",
"new_record"
]
| Returns a VCF record, where each indel from this
cluster is in a separate ALT. Then all the remaining SNPs are
applied to make one ALT. If >1 SNP in same place, either one
might be used | [
"Returns",
"a",
"VCF",
"record",
"where",
"each",
"indel",
"from",
"this",
"cluster",
"is",
"in",
"a",
"separate",
"ALT",
".",
"Then",
"all",
"the",
"remaining",
"SNPs",
"are",
"applied",
"to",
"make",
"one",
"ALT",
".",
"If",
">",
"1",
"SNP",
"in",
"same",
"place",
"either",
"one",
"might",
"be",
"used"
]
| 0db26af36b6da97a7361364457d2152dc756055c | https://github.com/iqbal-lab-org/cluster_vcf_records/blob/0db26af36b6da97a7361364457d2152dc756055c/cluster_vcf_records/vcf_record_cluster.py#L177-L207 | train |
sirfoga/pyhal | hal/streams/markdown.py | MarkdownTable._get_header | def _get_header(self):
"""Gets header of table
:return: markdown-formatted header"""
out = self._get_row(self.labels)
out += "\n"
out += self._get_row(["---"] * len(self.labels)) # line below headers
return out | python | def _get_header(self):
"""Gets header of table
:return: markdown-formatted header"""
out = self._get_row(self.labels)
out += "\n"
out += self._get_row(["---"] * len(self.labels)) # line below headers
return out | [
"def",
"_get_header",
"(",
"self",
")",
":",
"out",
"=",
"self",
".",
"_get_row",
"(",
"self",
".",
"labels",
")",
"out",
"+=",
"\"\\n\"",
"out",
"+=",
"self",
".",
"_get_row",
"(",
"[",
"\"---\"",
"]",
"*",
"len",
"(",
"self",
".",
"labels",
")",
")",
"# line below headers",
"return",
"out"
]
| Gets header of table
:return: markdown-formatted header | [
"Gets",
"header",
"of",
"table"
]
| 4394d8a1f7e45bea28a255ec390f4962ee64d33a | https://github.com/sirfoga/pyhal/blob/4394d8a1f7e45bea28a255ec390f4962ee64d33a/hal/streams/markdown.py#L64-L71 | train |
portfors-lab/sparkle | sparkle/gui/stim/auto_parameters_editor.py | Parametizer.setModel | def setModel(self, model):
"""sets the model for the auto parameters
:param model: The data stucture for this editor to provide access to
:type model: :class:`QAutoParameterModel<sparkle.gui.stim.qauto_parameter_model.QAutoParameterModel>`
"""
self.paramList.setModel(model)
model.hintRequested.connect(self.hintRequested)
model.rowsInserted.connect(self.updateTitle)
model.rowsRemoved.connect(self.updateTitle)
self.updateTitle() | python | def setModel(self, model):
"""sets the model for the auto parameters
:param model: The data stucture for this editor to provide access to
:type model: :class:`QAutoParameterModel<sparkle.gui.stim.qauto_parameter_model.QAutoParameterModel>`
"""
self.paramList.setModel(model)
model.hintRequested.connect(self.hintRequested)
model.rowsInserted.connect(self.updateTitle)
model.rowsRemoved.connect(self.updateTitle)
self.updateTitle() | [
"def",
"setModel",
"(",
"self",
",",
"model",
")",
":",
"self",
".",
"paramList",
".",
"setModel",
"(",
"model",
")",
"model",
".",
"hintRequested",
".",
"connect",
"(",
"self",
".",
"hintRequested",
")",
"model",
".",
"rowsInserted",
".",
"connect",
"(",
"self",
".",
"updateTitle",
")",
"model",
".",
"rowsRemoved",
".",
"connect",
"(",
"self",
".",
"updateTitle",
")",
"self",
".",
"updateTitle",
"(",
")"
]
| sets the model for the auto parameters
:param model: The data stucture for this editor to provide access to
:type model: :class:`QAutoParameterModel<sparkle.gui.stim.qauto_parameter_model.QAutoParameterModel>` | [
"sets",
"the",
"model",
"for",
"the",
"auto",
"parameters"
]
| 5fad1cf2bec58ec6b15d91da20f6236a74826110 | https://github.com/portfors-lab/sparkle/blob/5fad1cf2bec58ec6b15d91da20f6236a74826110/sparkle/gui/stim/auto_parameters_editor.py#L53-L63 | train |
portfors-lab/sparkle | sparkle/gui/stim/auto_parameters_editor.py | Parametizer.updateTitle | def updateTitle(self):
"""Updates the Title of this widget according to how many parameters are currently in the model"""
title = 'Auto Parameters ({})'.format(self.paramList.model().rowCount())
self.titleChange.emit(title)
self.setWindowTitle(title) | python | def updateTitle(self):
"""Updates the Title of this widget according to how many parameters are currently in the model"""
title = 'Auto Parameters ({})'.format(self.paramList.model().rowCount())
self.titleChange.emit(title)
self.setWindowTitle(title) | [
"def",
"updateTitle",
"(",
"self",
")",
":",
"title",
"=",
"'Auto Parameters ({})'",
".",
"format",
"(",
"self",
".",
"paramList",
".",
"model",
"(",
")",
".",
"rowCount",
"(",
")",
")",
"self",
".",
"titleChange",
".",
"emit",
"(",
"title",
")",
"self",
".",
"setWindowTitle",
"(",
"title",
")"
]
| Updates the Title of this widget according to how many parameters are currently in the model | [
"Updates",
"the",
"Title",
"of",
"this",
"widget",
"according",
"to",
"how",
"many",
"parameters",
"are",
"currently",
"in",
"the",
"model"
]
| 5fad1cf2bec58ec6b15d91da20f6236a74826110 | https://github.com/portfors-lab/sparkle/blob/5fad1cf2bec58ec6b15d91da20f6236a74826110/sparkle/gui/stim/auto_parameters_editor.py#L65-L69 | train |
portfors-lab/sparkle | sparkle/gui/stim/auto_parameters_editor.py | Parametizer.showEvent | def showEvent(self, event):
"""When this widget is shown it has an effect of putting
other widgets in the parent widget into different editing modes, emits
signal to notify other widgets. Restores the previous selection the last
time this widget was visible"""
selected = self.paramList.selectedIndexes()
model = self.paramList.model()
self.visibilityChanged.emit(1)
if len(selected) > 0:
# select the correct components in the StimulusView
self.paramList.parameterChanged.emit(model.selection(selected[0]))
self.hintRequested.emit('Select parameter to edit. \n\nParameter must have selected components in order to edit fields')
elif model.rowCount() > 0:
# just select first item
self.paramList.selectRow(0)
self.paramList.parameterChanged.emit(model.selection(model.index(0,0)))
self.hintRequested.emit('Select parameter to edit. \n\nParameter must have selected components in order to edit fields')
else:
model.emptied.emit(True)
self.hintRequested.emit('To add a parameter, Drag "Add" onto empty auto-parameter table') | python | def showEvent(self, event):
"""When this widget is shown it has an effect of putting
other widgets in the parent widget into different editing modes, emits
signal to notify other widgets. Restores the previous selection the last
time this widget was visible"""
selected = self.paramList.selectedIndexes()
model = self.paramList.model()
self.visibilityChanged.emit(1)
if len(selected) > 0:
# select the correct components in the StimulusView
self.paramList.parameterChanged.emit(model.selection(selected[0]))
self.hintRequested.emit('Select parameter to edit. \n\nParameter must have selected components in order to edit fields')
elif model.rowCount() > 0:
# just select first item
self.paramList.selectRow(0)
self.paramList.parameterChanged.emit(model.selection(model.index(0,0)))
self.hintRequested.emit('Select parameter to edit. \n\nParameter must have selected components in order to edit fields')
else:
model.emptied.emit(True)
self.hintRequested.emit('To add a parameter, Drag "Add" onto empty auto-parameter table') | [
"def",
"showEvent",
"(",
"self",
",",
"event",
")",
":",
"selected",
"=",
"self",
".",
"paramList",
".",
"selectedIndexes",
"(",
")",
"model",
"=",
"self",
".",
"paramList",
".",
"model",
"(",
")",
"self",
".",
"visibilityChanged",
".",
"emit",
"(",
"1",
")",
"if",
"len",
"(",
"selected",
")",
">",
"0",
":",
"# select the correct components in the StimulusView",
"self",
".",
"paramList",
".",
"parameterChanged",
".",
"emit",
"(",
"model",
".",
"selection",
"(",
"selected",
"[",
"0",
"]",
")",
")",
"self",
".",
"hintRequested",
".",
"emit",
"(",
"'Select parameter to edit. \\n\\nParameter must have selected components in order to edit fields'",
")",
"elif",
"model",
".",
"rowCount",
"(",
")",
">",
"0",
":",
"# just select first item",
"self",
".",
"paramList",
".",
"selectRow",
"(",
"0",
")",
"self",
".",
"paramList",
".",
"parameterChanged",
".",
"emit",
"(",
"model",
".",
"selection",
"(",
"model",
".",
"index",
"(",
"0",
",",
"0",
")",
")",
")",
"self",
".",
"hintRequested",
".",
"emit",
"(",
"'Select parameter to edit. \\n\\nParameter must have selected components in order to edit fields'",
")",
"else",
":",
"model",
".",
"emptied",
".",
"emit",
"(",
"True",
")",
"self",
".",
"hintRequested",
".",
"emit",
"(",
"'To add a parameter, Drag \"Add\" onto empty auto-parameter table'",
")"
]
| When this widget is shown it has an effect of putting
other widgets in the parent widget into different editing modes, emits
signal to notify other widgets. Restores the previous selection the last
time this widget was visible | [
"When",
"this",
"widget",
"is",
"shown",
"it",
"has",
"an",
"effect",
"of",
"putting",
"other",
"widgets",
"in",
"the",
"parent",
"widget",
"into",
"different",
"editing",
"modes",
"emits",
"signal",
"to",
"notify",
"other",
"widgets",
".",
"Restores",
"the",
"previous",
"selection",
"the",
"last",
"time",
"this",
"widget",
"was",
"visible"
]
| 5fad1cf2bec58ec6b15d91da20f6236a74826110 | https://github.com/portfors-lab/sparkle/blob/5fad1cf2bec58ec6b15d91da20f6236a74826110/sparkle/gui/stim/auto_parameters_editor.py#L71-L91 | train |
portfors-lab/sparkle | sparkle/gui/stim/auto_parameters_editor.py | Parametizer.closeEvent | def closeEvent(self, event):
"""Emits a signal to update start values on components"""
self.visibilityChanged.emit(0)
model = self.paramList.model()
model.hintRequested.disconnect()
model.rowsInserted.disconnect()
model.rowsRemoved.disconnect() | python | def closeEvent(self, event):
"""Emits a signal to update start values on components"""
self.visibilityChanged.emit(0)
model = self.paramList.model()
model.hintRequested.disconnect()
model.rowsInserted.disconnect()
model.rowsRemoved.disconnect() | [
"def",
"closeEvent",
"(",
"self",
",",
"event",
")",
":",
"self",
".",
"visibilityChanged",
".",
"emit",
"(",
"0",
")",
"model",
"=",
"self",
".",
"paramList",
".",
"model",
"(",
")",
"model",
".",
"hintRequested",
".",
"disconnect",
"(",
")",
"model",
".",
"rowsInserted",
".",
"disconnect",
"(",
")",
"model",
".",
"rowsRemoved",
".",
"disconnect",
"(",
")"
]
| Emits a signal to update start values on components | [
"Emits",
"a",
"signal",
"to",
"update",
"start",
"values",
"on",
"components"
]
| 5fad1cf2bec58ec6b15d91da20f6236a74826110 | https://github.com/portfors-lab/sparkle/blob/5fad1cf2bec58ec6b15d91da20f6236a74826110/sparkle/gui/stim/auto_parameters_editor.py#L98-L104 | train |
yamcs/yamcs-python | yamcs-client/examples/authenticate.py | authenticate_with_access_token | def authenticate_with_access_token(access_token):
"""Authenticate using an existing access token."""
credentials = Credentials(access_token=access_token)
client = YamcsClient('localhost:8090', credentials=credentials)
for link in client.list_data_links('simulator'):
print(link) | python | def authenticate_with_access_token(access_token):
"""Authenticate using an existing access token."""
credentials = Credentials(access_token=access_token)
client = YamcsClient('localhost:8090', credentials=credentials)
for link in client.list_data_links('simulator'):
print(link) | [
"def",
"authenticate_with_access_token",
"(",
"access_token",
")",
":",
"credentials",
"=",
"Credentials",
"(",
"access_token",
"=",
"access_token",
")",
"client",
"=",
"YamcsClient",
"(",
"'localhost:8090'",
",",
"credentials",
"=",
"credentials",
")",
"for",
"link",
"in",
"client",
".",
"list_data_links",
"(",
"'simulator'",
")",
":",
"print",
"(",
"link",
")"
]
| Authenticate using an existing access token. | [
"Authenticate",
"using",
"an",
"existing",
"access",
"token",
"."
]
| 1082fee8a299010cc44416bbb7518fac0ef08b48 | https://github.com/yamcs/yamcs-python/blob/1082fee8a299010cc44416bbb7518fac0ef08b48/yamcs-client/examples/authenticate.py#L24-L30 | train |
sirfoga/pyhal | hal/streams/pretty_table.py | pretty_format_table | def pretty_format_table(labels, data, num_format="{:.3f}", line_separator="\n"):
"""Parses and creates pretty table
:param labels: List of labels of data
:param data: Matrix of any type
:param num_format: Format numbers with this format
:param line_separator: Separate each new line with this
:return: Pretty formatted table (first row is labels, then actual data)
"""
table = SqlTable(labels, data, num_format, line_separator)
return table.build() | python | def pretty_format_table(labels, data, num_format="{:.3f}", line_separator="\n"):
"""Parses and creates pretty table
:param labels: List of labels of data
:param data: Matrix of any type
:param num_format: Format numbers with this format
:param line_separator: Separate each new line with this
:return: Pretty formatted table (first row is labels, then actual data)
"""
table = SqlTable(labels, data, num_format, line_separator)
return table.build() | [
"def",
"pretty_format_table",
"(",
"labels",
",",
"data",
",",
"num_format",
"=",
"\"{:.3f}\"",
",",
"line_separator",
"=",
"\"\\n\"",
")",
":",
"table",
"=",
"SqlTable",
"(",
"labels",
",",
"data",
",",
"num_format",
",",
"line_separator",
")",
"return",
"table",
".",
"build",
"(",
")"
]
| Parses and creates pretty table
:param labels: List of labels of data
:param data: Matrix of any type
:param num_format: Format numbers with this format
:param line_separator: Separate each new line with this
:return: Pretty formatted table (first row is labels, then actual data) | [
"Parses",
"and",
"creates",
"pretty",
"table"
]
| 4394d8a1f7e45bea28a255ec390f4962ee64d33a | https://github.com/sirfoga/pyhal/blob/4394d8a1f7e45bea28a255ec390f4962ee64d33a/hal/streams/pretty_table.py#L170-L180 | train |
sirfoga/pyhal | hal/streams/pretty_table.py | SqlTable._parse | def _parse(self):
"""Parses raw data"""
for i in range(len(self.data)):
self._parse_row(i) | python | def _parse(self):
"""Parses raw data"""
for i in range(len(self.data)):
self._parse_row(i) | [
"def",
"_parse",
"(",
"self",
")",
":",
"for",
"i",
"in",
"range",
"(",
"len",
"(",
"self",
".",
"data",
")",
")",
":",
"self",
".",
"_parse_row",
"(",
"i",
")"
]
| Parses raw data | [
"Parses",
"raw",
"data"
]
| 4394d8a1f7e45bea28a255ec390f4962ee64d33a | https://github.com/sirfoga/pyhal/blob/4394d8a1f7e45bea28a255ec390f4962ee64d33a/hal/streams/pretty_table.py#L64-L67 | train |
sirfoga/pyhal | hal/streams/pretty_table.py | SqlTable._calculate_optimal_column_widths | def _calculate_optimal_column_widths(self):
"""Calculates widths of columns
:return: Length of longest data in each column (labels and data)
"""
columns = len(self.data[0]) # number of columns
str_labels = [parse_colorama(str(l)) for l in
self.labels] # labels as strings
str_data = [[parse_colorama(str(col)) for col in row] for row in
self.data]
# values as strings
widths = [0] * columns # length of longest string in each column
for row in str_data: # calculate max width in each column
widths = [max(w, len(c)) for w, c in zip(widths, row)]
# check if label name is longer than data
for col, label in enumerate(str_labels):
if len(label) > widths[col]:
widths[col] = len(label)
self.widths = widths | python | def _calculate_optimal_column_widths(self):
"""Calculates widths of columns
:return: Length of longest data in each column (labels and data)
"""
columns = len(self.data[0]) # number of columns
str_labels = [parse_colorama(str(l)) for l in
self.labels] # labels as strings
str_data = [[parse_colorama(str(col)) for col in row] for row in
self.data]
# values as strings
widths = [0] * columns # length of longest string in each column
for row in str_data: # calculate max width in each column
widths = [max(w, len(c)) for w, c in zip(widths, row)]
# check if label name is longer than data
for col, label in enumerate(str_labels):
if len(label) > widths[col]:
widths[col] = len(label)
self.widths = widths | [
"def",
"_calculate_optimal_column_widths",
"(",
"self",
")",
":",
"columns",
"=",
"len",
"(",
"self",
".",
"data",
"[",
"0",
"]",
")",
"# number of columns",
"str_labels",
"=",
"[",
"parse_colorama",
"(",
"str",
"(",
"l",
")",
")",
"for",
"l",
"in",
"self",
".",
"labels",
"]",
"# labels as strings",
"str_data",
"=",
"[",
"[",
"parse_colorama",
"(",
"str",
"(",
"col",
")",
")",
"for",
"col",
"in",
"row",
"]",
"for",
"row",
"in",
"self",
".",
"data",
"]",
"# values as strings",
"widths",
"=",
"[",
"0",
"]",
"*",
"columns",
"# length of longest string in each column",
"for",
"row",
"in",
"str_data",
":",
"# calculate max width in each column",
"widths",
"=",
"[",
"max",
"(",
"w",
",",
"len",
"(",
"c",
")",
")",
"for",
"w",
",",
"c",
"in",
"zip",
"(",
"widths",
",",
"row",
")",
"]",
"# check if label name is longer than data",
"for",
"col",
",",
"label",
"in",
"enumerate",
"(",
"str_labels",
")",
":",
"if",
"len",
"(",
"label",
")",
">",
"widths",
"[",
"col",
"]",
":",
"widths",
"[",
"col",
"]",
"=",
"len",
"(",
"label",
")",
"self",
".",
"widths",
"=",
"widths"
]
| Calculates widths of columns
:return: Length of longest data in each column (labels and data) | [
"Calculates",
"widths",
"of",
"columns"
]
| 4394d8a1f7e45bea28a255ec390f4962ee64d33a | https://github.com/sirfoga/pyhal/blob/4394d8a1f7e45bea28a255ec390f4962ee64d33a/hal/streams/pretty_table.py#L69-L90 | train |
sirfoga/pyhal | hal/streams/pretty_table.py | SqlTable.get_blank_row | def get_blank_row(self, filler="-", splitter="+"):
"""Gets blank row
:param filler: Fill empty columns with this char
:param splitter: Separate columns with this char
:return: Pretty formatted blank row (with no meaningful data in it)
"""
return self.get_pretty_row(
["" for _ in self.widths], # blanks
filler, # fill with this
splitter, # split columns with this
) | python | def get_blank_row(self, filler="-", splitter="+"):
"""Gets blank row
:param filler: Fill empty columns with this char
:param splitter: Separate columns with this char
:return: Pretty formatted blank row (with no meaningful data in it)
"""
return self.get_pretty_row(
["" for _ in self.widths], # blanks
filler, # fill with this
splitter, # split columns with this
) | [
"def",
"get_blank_row",
"(",
"self",
",",
"filler",
"=",
"\"-\"",
",",
"splitter",
"=",
"\"+\"",
")",
":",
"return",
"self",
".",
"get_pretty_row",
"(",
"[",
"\"\"",
"for",
"_",
"in",
"self",
".",
"widths",
"]",
",",
"# blanks",
"filler",
",",
"# fill with this",
"splitter",
",",
"# split columns with this",
")"
]
| Gets blank row
:param filler: Fill empty columns with this char
:param splitter: Separate columns with this char
:return: Pretty formatted blank row (with no meaningful data in it) | [
"Gets",
"blank",
"row"
]
| 4394d8a1f7e45bea28a255ec390f4962ee64d33a | https://github.com/sirfoga/pyhal/blob/4394d8a1f7e45bea28a255ec390f4962ee64d33a/hal/streams/pretty_table.py#L111-L122 | train |
sirfoga/pyhal | hal/streams/pretty_table.py | SqlTable.build | def build(self):
"""Builds pretty-formatted table
:return: pretty table
"""
self._calculate_optimal_column_widths()
pretty_table = self.get_blank_row() + self.new_line # first row
pretty_table += self.pretty_format_row(self.labels) + self.new_line
pretty_table += self.get_blank_row() + self.new_line
for row in self.data: # append each row
pretty_table += self.pretty_format_row(row) + self.new_line
pretty_table += self.get_blank_row() # ending line
return pretty_table | python | def build(self):
"""Builds pretty-formatted table
:return: pretty table
"""
self._calculate_optimal_column_widths()
pretty_table = self.get_blank_row() + self.new_line # first row
pretty_table += self.pretty_format_row(self.labels) + self.new_line
pretty_table += self.get_blank_row() + self.new_line
for row in self.data: # append each row
pretty_table += self.pretty_format_row(row) + self.new_line
pretty_table += self.get_blank_row() # ending line
return pretty_table | [
"def",
"build",
"(",
"self",
")",
":",
"self",
".",
"_calculate_optimal_column_widths",
"(",
")",
"pretty_table",
"=",
"self",
".",
"get_blank_row",
"(",
")",
"+",
"self",
".",
"new_line",
"# first row",
"pretty_table",
"+=",
"self",
".",
"pretty_format_row",
"(",
"self",
".",
"labels",
")",
"+",
"self",
".",
"new_line",
"pretty_table",
"+=",
"self",
".",
"get_blank_row",
"(",
")",
"+",
"self",
".",
"new_line",
"for",
"row",
"in",
"self",
".",
"data",
":",
"# append each row",
"pretty_table",
"+=",
"self",
".",
"pretty_format_row",
"(",
"row",
")",
"+",
"self",
".",
"new_line",
"pretty_table",
"+=",
"self",
".",
"get_blank_row",
"(",
")",
"# ending line",
"return",
"pretty_table"
]
| Builds pretty-formatted table
:return: pretty table | [
"Builds",
"pretty",
"-",
"formatted",
"table"
]
| 4394d8a1f7e45bea28a255ec390f4962ee64d33a | https://github.com/sirfoga/pyhal/blob/4394d8a1f7e45bea28a255ec390f4962ee64d33a/hal/streams/pretty_table.py#L138-L153 | train |
sirfoga/pyhal | hal/streams/pretty_table.py | SqlTable.from_df | def from_df(data_frame):
"""Parses data and builds an instance of this class
:param data_frame: pandas DataFrame
:return: SqlTable
"""
labels = data_frame.keys().tolist()
data = data_frame.values.tolist()
return SqlTable(labels, data, "{:.3f}", "\n") | python | def from_df(data_frame):
"""Parses data and builds an instance of this class
:param data_frame: pandas DataFrame
:return: SqlTable
"""
labels = data_frame.keys().tolist()
data = data_frame.values.tolist()
return SqlTable(labels, data, "{:.3f}", "\n") | [
"def",
"from_df",
"(",
"data_frame",
")",
":",
"labels",
"=",
"data_frame",
".",
"keys",
"(",
")",
".",
"tolist",
"(",
")",
"data",
"=",
"data_frame",
".",
"values",
".",
"tolist",
"(",
")",
"return",
"SqlTable",
"(",
"labels",
",",
"data",
",",
"\"{:.3f}\"",
",",
"\"\\n\"",
")"
]
| Parses data and builds an instance of this class
:param data_frame: pandas DataFrame
:return: SqlTable | [
"Parses",
"data",
"and",
"builds",
"an",
"instance",
"of",
"this",
"class"
]
| 4394d8a1f7e45bea28a255ec390f4962ee64d33a | https://github.com/sirfoga/pyhal/blob/4394d8a1f7e45bea28a255ec390f4962ee64d33a/hal/streams/pretty_table.py#L159-L167 | train |
lowandrew/OLCTools | sipprCommon/editsamheaders.py | editheaders | def editheaders():
"""Edits the headers of SAM files to remove 'secondary alignments'"""
# Read stdin - this will be the output from samtools view
for line in fileinput.input():
try:
# Get the flag value from the input
columns = line.split('\t')
# The FLAG is in the second column
flag = int(columns[1])
# Subtracts 256 from the flag if the & bitwise operator evaluates to true
# See http://www.tutorialspoint.com/python/bitwise_operators_example.htm
# For the test case, flags of 256 became 0, and flags of 272 became 16
columns[1] = str((flag - 256) if (flag & 256) else flag)
# update = [columns[0], str(flag), columns[2:]]
sys.stdout.write('\t'.join(columns))
# Don't fail on IOErrors, or ValueErrors, and still print line to stdout
except (IOError, ValueError):
sys.stdout.write(line)
pass
# Try except statements to get rid of file closing errors
try:
sys.stdout.flush()
sys.stdout.close()
except:
pass
try:
sys.stderr.close()
except:
pass | python | def editheaders():
"""Edits the headers of SAM files to remove 'secondary alignments'"""
# Read stdin - this will be the output from samtools view
for line in fileinput.input():
try:
# Get the flag value from the input
columns = line.split('\t')
# The FLAG is in the second column
flag = int(columns[1])
# Subtracts 256 from the flag if the & bitwise operator evaluates to true
# See http://www.tutorialspoint.com/python/bitwise_operators_example.htm
# For the test case, flags of 256 became 0, and flags of 272 became 16
columns[1] = str((flag - 256) if (flag & 256) else flag)
# update = [columns[0], str(flag), columns[2:]]
sys.stdout.write('\t'.join(columns))
# Don't fail on IOErrors, or ValueErrors, and still print line to stdout
except (IOError, ValueError):
sys.stdout.write(line)
pass
# Try except statements to get rid of file closing errors
try:
sys.stdout.flush()
sys.stdout.close()
except:
pass
try:
sys.stderr.close()
except:
pass | [
"def",
"editheaders",
"(",
")",
":",
"# Read stdin - this will be the output from samtools view",
"for",
"line",
"in",
"fileinput",
".",
"input",
"(",
")",
":",
"try",
":",
"# Get the flag value from the input",
"columns",
"=",
"line",
".",
"split",
"(",
"'\\t'",
")",
"# The FLAG is in the second column",
"flag",
"=",
"int",
"(",
"columns",
"[",
"1",
"]",
")",
"# Subtracts 256 from the flag if the & bitwise operator evaluates to true",
"# See http://www.tutorialspoint.com/python/bitwise_operators_example.htm",
"# For the test case, flags of 256 became 0, and flags of 272 became 16",
"columns",
"[",
"1",
"]",
"=",
"str",
"(",
"(",
"flag",
"-",
"256",
")",
"if",
"(",
"flag",
"&",
"256",
")",
"else",
"flag",
")",
"# update = [columns[0], str(flag), columns[2:]]",
"sys",
".",
"stdout",
".",
"write",
"(",
"'\\t'",
".",
"join",
"(",
"columns",
")",
")",
"# Don't fail on IOErrors, or ValueErrors, and still print line to stdout",
"except",
"(",
"IOError",
",",
"ValueError",
")",
":",
"sys",
".",
"stdout",
".",
"write",
"(",
"line",
")",
"pass",
"# Try except statements to get rid of file closing errors",
"try",
":",
"sys",
".",
"stdout",
".",
"flush",
"(",
")",
"sys",
".",
"stdout",
".",
"close",
"(",
")",
"except",
":",
"pass",
"try",
":",
"sys",
".",
"stderr",
".",
"close",
"(",
")",
"except",
":",
"pass"
]
| Edits the headers of SAM files to remove 'secondary alignments | [
"Edits",
"the",
"headers",
"of",
"SAM",
"files",
"to",
"remove",
"secondary",
"alignments"
]
| 88aa90ac85f84d0bbeb03e43c29b0a9d36e4ce2a | https://github.com/lowandrew/OLCTools/blob/88aa90ac85f84d0bbeb03e43c29b0a9d36e4ce2a/sipprCommon/editsamheaders.py#L12-L40 | train |
iqbal-lab-org/cluster_vcf_records | cluster_vcf_records/vcf_record.py | VcfRecord.ref_string_matches_ref_sequence | def ref_string_matches_ref_sequence(self, ref_sequence):
'''Returns true iff the REF string in the record agrees with
the given ref_sequence'''
# you never know what you're gonna get...
if self.POS < 0:
return False
end_pos = self.ref_end_pos()
if end_pos >= len(ref_sequence):
return False
return self.REF == ref_sequence[self.POS:end_pos + 1] | python | def ref_string_matches_ref_sequence(self, ref_sequence):
'''Returns true iff the REF string in the record agrees with
the given ref_sequence'''
# you never know what you're gonna get...
if self.POS < 0:
return False
end_pos = self.ref_end_pos()
if end_pos >= len(ref_sequence):
return False
return self.REF == ref_sequence[self.POS:end_pos + 1] | [
"def",
"ref_string_matches_ref_sequence",
"(",
"self",
",",
"ref_sequence",
")",
":",
"# you never know what you're gonna get...",
"if",
"self",
".",
"POS",
"<",
"0",
":",
"return",
"False",
"end_pos",
"=",
"self",
".",
"ref_end_pos",
"(",
")",
"if",
"end_pos",
">=",
"len",
"(",
"ref_sequence",
")",
":",
"return",
"False",
"return",
"self",
".",
"REF",
"==",
"ref_sequence",
"[",
"self",
".",
"POS",
":",
"end_pos",
"+",
"1",
"]"
]
| Returns true iff the REF string in the record agrees with
the given ref_sequence | [
"Returns",
"true",
"iff",
"the",
"REF",
"string",
"in",
"the",
"record",
"agrees",
"with",
"the",
"given",
"ref_sequence"
]
| 0db26af36b6da97a7361364457d2152dc756055c | https://github.com/iqbal-lab-org/cluster_vcf_records/blob/0db26af36b6da97a7361364457d2152dc756055c/cluster_vcf_records/vcf_record.py#L87-L98 | train |
iqbal-lab-org/cluster_vcf_records | cluster_vcf_records/vcf_record.py | VcfRecord.ref_string_matches_dict_of_ref_sequences | def ref_string_matches_dict_of_ref_sequences(self, ref_sequences):
'''Returns true iff there is a sequence called self.CHROM in the
dict of ref_sequences, and the REF string matches'''
return self.CHROM in ref_sequences and self.ref_string_matches_ref_sequence(ref_sequences[self.CHROM]) | python | def ref_string_matches_dict_of_ref_sequences(self, ref_sequences):
'''Returns true iff there is a sequence called self.CHROM in the
dict of ref_sequences, and the REF string matches'''
return self.CHROM in ref_sequences and self.ref_string_matches_ref_sequence(ref_sequences[self.CHROM]) | [
"def",
"ref_string_matches_dict_of_ref_sequences",
"(",
"self",
",",
"ref_sequences",
")",
":",
"return",
"self",
".",
"CHROM",
"in",
"ref_sequences",
"and",
"self",
".",
"ref_string_matches_ref_sequence",
"(",
"ref_sequences",
"[",
"self",
".",
"CHROM",
"]",
")"
]
| Returns true iff there is a sequence called self.CHROM in the
dict of ref_sequences, and the REF string matches | [
"Returns",
"true",
"iff",
"there",
"is",
"a",
"sequence",
"called",
"self",
".",
"CHROM",
"in",
"the",
"dict",
"of",
"ref_sequences",
"and",
"the",
"REF",
"string",
"matches"
]
| 0db26af36b6da97a7361364457d2152dc756055c | https://github.com/iqbal-lab-org/cluster_vcf_records/blob/0db26af36b6da97a7361364457d2152dc756055c/cluster_vcf_records/vcf_record.py#L101-L104 | train |
iqbal-lab-org/cluster_vcf_records | cluster_vcf_records/vcf_record.py | VcfRecord.is_snp | def is_snp(self):
'''Returns true iff this variant is a SNP'''
nucleotides = {'A', 'C', 'G', 'T'}
return len(self.REF) == 1 and self.REF in nucleotides and set(self.ALT).issubset(nucleotides) | python | def is_snp(self):
'''Returns true iff this variant is a SNP'''
nucleotides = {'A', 'C', 'G', 'T'}
return len(self.REF) == 1 and self.REF in nucleotides and set(self.ALT).issubset(nucleotides) | [
"def",
"is_snp",
"(",
"self",
")",
":",
"nucleotides",
"=",
"{",
"'A'",
",",
"'C'",
",",
"'G'",
",",
"'T'",
"}",
"return",
"len",
"(",
"self",
".",
"REF",
")",
"==",
"1",
"and",
"self",
".",
"REF",
"in",
"nucleotides",
"and",
"set",
"(",
"self",
".",
"ALT",
")",
".",
"issubset",
"(",
"nucleotides",
")"
]
| Returns true iff this variant is a SNP | [
"Returns",
"true",
"iff",
"this",
"variant",
"is",
"a",
"SNP"
]
| 0db26af36b6da97a7361364457d2152dc756055c | https://github.com/iqbal-lab-org/cluster_vcf_records/blob/0db26af36b6da97a7361364457d2152dc756055c/cluster_vcf_records/vcf_record.py#L113-L116 | train |
iqbal-lab-org/cluster_vcf_records | cluster_vcf_records/vcf_record.py | VcfRecord.add_flanking_seqs | def add_flanking_seqs(self, ref_seq, new_start, new_end):
'''Adds new_start many nucleotides at the start, and new_end many nucleotides
at the end from the appropriate nucleotides in reference sequence ref_seq.'''
if new_start > self.POS or new_end < self.ref_end_pos():
raise Error('new start and end positions must not try to shrink VCF record. new_start=' + str(new_start) + ', new_end=' + str(new_end) + '. VCF=' + str(self))
new_start_nucleotides = ref_seq[new_start:self.POS]
new_end_nucleotodes = ref_seq[self.ref_end_pos() + 1:new_end + 1]
self.POS = new_start
self.REF = new_start_nucleotides + self.REF + new_end_nucleotodes
self.ALT = [new_start_nucleotides + x + new_end_nucleotodes for x in self.ALT] | python | def add_flanking_seqs(self, ref_seq, new_start, new_end):
'''Adds new_start many nucleotides at the start, and new_end many nucleotides
at the end from the appropriate nucleotides in reference sequence ref_seq.'''
if new_start > self.POS or new_end < self.ref_end_pos():
raise Error('new start and end positions must not try to shrink VCF record. new_start=' + str(new_start) + ', new_end=' + str(new_end) + '. VCF=' + str(self))
new_start_nucleotides = ref_seq[new_start:self.POS]
new_end_nucleotodes = ref_seq[self.ref_end_pos() + 1:new_end + 1]
self.POS = new_start
self.REF = new_start_nucleotides + self.REF + new_end_nucleotodes
self.ALT = [new_start_nucleotides + x + new_end_nucleotodes for x in self.ALT] | [
"def",
"add_flanking_seqs",
"(",
"self",
",",
"ref_seq",
",",
"new_start",
",",
"new_end",
")",
":",
"if",
"new_start",
">",
"self",
".",
"POS",
"or",
"new_end",
"<",
"self",
".",
"ref_end_pos",
"(",
")",
":",
"raise",
"Error",
"(",
"'new start and end positions must not try to shrink VCF record. new_start='",
"+",
"str",
"(",
"new_start",
")",
"+",
"', new_end='",
"+",
"str",
"(",
"new_end",
")",
"+",
"'. VCF='",
"+",
"str",
"(",
"self",
")",
")",
"new_start_nucleotides",
"=",
"ref_seq",
"[",
"new_start",
":",
"self",
".",
"POS",
"]",
"new_end_nucleotodes",
"=",
"ref_seq",
"[",
"self",
".",
"ref_end_pos",
"(",
")",
"+",
"1",
":",
"new_end",
"+",
"1",
"]",
"self",
".",
"POS",
"=",
"new_start",
"self",
".",
"REF",
"=",
"new_start_nucleotides",
"+",
"self",
".",
"REF",
"+",
"new_end_nucleotodes",
"self",
".",
"ALT",
"=",
"[",
"new_start_nucleotides",
"+",
"x",
"+",
"new_end_nucleotodes",
"for",
"x",
"in",
"self",
".",
"ALT",
"]"
]
| Adds new_start many nucleotides at the start, and new_end many nucleotides
at the end from the appropriate nucleotides in reference sequence ref_seq. | [
"Adds",
"new_start",
"many",
"nucleotides",
"at",
"the",
"start",
"and",
"new_end",
"many",
"nucleotides",
"at",
"the",
"end",
"from",
"the",
"appropriate",
"nucleotides",
"in",
"reference",
"sequence",
"ref_seq",
"."
]
| 0db26af36b6da97a7361364457d2152dc756055c | https://github.com/iqbal-lab-org/cluster_vcf_records/blob/0db26af36b6da97a7361364457d2152dc756055c/cluster_vcf_records/vcf_record.py#L270-L280 | train |
iqbal-lab-org/cluster_vcf_records | cluster_vcf_records/vcf_record.py | VcfRecord.remove_useless_start_nucleotides | def remove_useless_start_nucleotides(self):
'''Removes duplicated nucleotides at the start of REF and ALT.
But always leaves at least one nucleotide in each of REF and ALT.
eg if variant is at position 42, REF=GCTGA, ALT=GCA, then
sets position=41, REF=CTGA, ALT=CA.
Assumes only one ALT, and does nothing if there is >1 ALT'''
if len(self.REF) == 1 or len(self.ALT) != 1:
return
i = 0
while i < len(self.REF) and i < len(self.ALT[0]) and self.REF[i] == self.ALT[0][i]:
i += 1
if i > 0:
self.REF = self.REF[i - 1:]
self.ALT = [self.ALT[0][i - 1:]]
self.POS += i - 1 | python | def remove_useless_start_nucleotides(self):
'''Removes duplicated nucleotides at the start of REF and ALT.
But always leaves at least one nucleotide in each of REF and ALT.
eg if variant is at position 42, REF=GCTGA, ALT=GCA, then
sets position=41, REF=CTGA, ALT=CA.
Assumes only one ALT, and does nothing if there is >1 ALT'''
if len(self.REF) == 1 or len(self.ALT) != 1:
return
i = 0
while i < len(self.REF) and i < len(self.ALT[0]) and self.REF[i] == self.ALT[0][i]:
i += 1
if i > 0:
self.REF = self.REF[i - 1:]
self.ALT = [self.ALT[0][i - 1:]]
self.POS += i - 1 | [
"def",
"remove_useless_start_nucleotides",
"(",
"self",
")",
":",
"if",
"len",
"(",
"self",
".",
"REF",
")",
"==",
"1",
"or",
"len",
"(",
"self",
".",
"ALT",
")",
"!=",
"1",
":",
"return",
"i",
"=",
"0",
"while",
"i",
"<",
"len",
"(",
"self",
".",
"REF",
")",
"and",
"i",
"<",
"len",
"(",
"self",
".",
"ALT",
"[",
"0",
"]",
")",
"and",
"self",
".",
"REF",
"[",
"i",
"]",
"==",
"self",
".",
"ALT",
"[",
"0",
"]",
"[",
"i",
"]",
":",
"i",
"+=",
"1",
"if",
"i",
">",
"0",
":",
"self",
".",
"REF",
"=",
"self",
".",
"REF",
"[",
"i",
"-",
"1",
":",
"]",
"self",
".",
"ALT",
"=",
"[",
"self",
".",
"ALT",
"[",
"0",
"]",
"[",
"i",
"-",
"1",
":",
"]",
"]",
"self",
".",
"POS",
"+=",
"i",
"-",
"1"
]
| Removes duplicated nucleotides at the start of REF and ALT.
But always leaves at least one nucleotide in each of REF and ALT.
eg if variant is at position 42, REF=GCTGA, ALT=GCA, then
sets position=41, REF=CTGA, ALT=CA.
Assumes only one ALT, and does nothing if there is >1 ALT | [
"Removes",
"duplicated",
"nucleotides",
"at",
"the",
"start",
"of",
"REF",
"and",
"ALT",
".",
"But",
"always",
"leaves",
"at",
"least",
"one",
"nucleotide",
"in",
"each",
"of",
"REF",
"and",
"ALT",
".",
"eg",
"if",
"variant",
"is",
"at",
"position",
"42",
"REF",
"=",
"GCTGA",
"ALT",
"=",
"GCA",
"then",
"sets",
"position",
"=",
"41",
"REF",
"=",
"CTGA",
"ALT",
"=",
"CA",
".",
"Assumes",
"only",
"one",
"ALT",
"and",
"does",
"nothing",
"if",
"there",
"is",
">",
"1",
"ALT"
]
| 0db26af36b6da97a7361364457d2152dc756055c | https://github.com/iqbal-lab-org/cluster_vcf_records/blob/0db26af36b6da97a7361364457d2152dc756055c/cluster_vcf_records/vcf_record.py#L310-L326 | train |
iqbal-lab-org/cluster_vcf_records | cluster_vcf_records/vcf_record.py | VcfRecord.inferred_var_seqs_plus_flanks | def inferred_var_seqs_plus_flanks(self, ref_seq, flank_length):
'''Returns start position of first flank sequence, plus a list of sequences -
the REF, plus one for each ALT.sequence. Order same as in ALT column'''
flank_start = max(0, self.POS - flank_length)
flank_end = min(len(ref_seq) - 1, self.ref_end_pos() + flank_length)
seqs = [ref_seq[flank_start:self.POS] + self.REF + ref_seq[self.ref_end_pos() + 1: flank_end + 1]]
for alt in self.ALT:
seqs.append(ref_seq[flank_start:self.POS] + alt + ref_seq[self.ref_end_pos() + 1: flank_end + 1])
return flank_start, seqs | python | def inferred_var_seqs_plus_flanks(self, ref_seq, flank_length):
'''Returns start position of first flank sequence, plus a list of sequences -
the REF, plus one for each ALT.sequence. Order same as in ALT column'''
flank_start = max(0, self.POS - flank_length)
flank_end = min(len(ref_seq) - 1, self.ref_end_pos() + flank_length)
seqs = [ref_seq[flank_start:self.POS] + self.REF + ref_seq[self.ref_end_pos() + 1: flank_end + 1]]
for alt in self.ALT:
seqs.append(ref_seq[flank_start:self.POS] + alt + ref_seq[self.ref_end_pos() + 1: flank_end + 1])
return flank_start, seqs | [
"def",
"inferred_var_seqs_plus_flanks",
"(",
"self",
",",
"ref_seq",
",",
"flank_length",
")",
":",
"flank_start",
"=",
"max",
"(",
"0",
",",
"self",
".",
"POS",
"-",
"flank_length",
")",
"flank_end",
"=",
"min",
"(",
"len",
"(",
"ref_seq",
")",
"-",
"1",
",",
"self",
".",
"ref_end_pos",
"(",
")",
"+",
"flank_length",
")",
"seqs",
"=",
"[",
"ref_seq",
"[",
"flank_start",
":",
"self",
".",
"POS",
"]",
"+",
"self",
".",
"REF",
"+",
"ref_seq",
"[",
"self",
".",
"ref_end_pos",
"(",
")",
"+",
"1",
":",
"flank_end",
"+",
"1",
"]",
"]",
"for",
"alt",
"in",
"self",
".",
"ALT",
":",
"seqs",
".",
"append",
"(",
"ref_seq",
"[",
"flank_start",
":",
"self",
".",
"POS",
"]",
"+",
"alt",
"+",
"ref_seq",
"[",
"self",
".",
"ref_end_pos",
"(",
")",
"+",
"1",
":",
"flank_end",
"+",
"1",
"]",
")",
"return",
"flank_start",
",",
"seqs"
]
| Returns start position of first flank sequence, plus a list of sequences -
the REF, plus one for each ALT.sequence. Order same as in ALT column | [
"Returns",
"start",
"position",
"of",
"first",
"flank",
"sequence",
"plus",
"a",
"list",
"of",
"sequences",
"-",
"the",
"REF",
"plus",
"one",
"for",
"each",
"ALT",
".",
"sequence",
".",
"Order",
"same",
"as",
"in",
"ALT",
"column"
]
| 0db26af36b6da97a7361364457d2152dc756055c | https://github.com/iqbal-lab-org/cluster_vcf_records/blob/0db26af36b6da97a7361364457d2152dc756055c/cluster_vcf_records/vcf_record.py#L336-L346 | train |
iqbal-lab-org/cluster_vcf_records | cluster_vcf_records/vcf_record.py | VcfRecord.total_coverage | def total_coverage(self):
'''Returns the sum of COV data, if present. Otherwise returns None'''
if 'COV' in self.FORMAT:
return sum([int(x) for x in self.FORMAT['COV'].split(',')])
else:
return None | python | def total_coverage(self):
'''Returns the sum of COV data, if present. Otherwise returns None'''
if 'COV' in self.FORMAT:
return sum([int(x) for x in self.FORMAT['COV'].split(',')])
else:
return None | [
"def",
"total_coverage",
"(",
"self",
")",
":",
"if",
"'COV'",
"in",
"self",
".",
"FORMAT",
":",
"return",
"sum",
"(",
"[",
"int",
"(",
"x",
")",
"for",
"x",
"in",
"self",
".",
"FORMAT",
"[",
"'COV'",
"]",
".",
"split",
"(",
"','",
")",
"]",
")",
"else",
":",
"return",
"None"
]
| Returns the sum of COV data, if present. Otherwise returns None | [
"Returns",
"the",
"sum",
"of",
"COV",
"data",
"if",
"present",
".",
"Otherwise",
"returns",
"None"
]
| 0db26af36b6da97a7361364457d2152dc756055c | https://github.com/iqbal-lab-org/cluster_vcf_records/blob/0db26af36b6da97a7361364457d2152dc756055c/cluster_vcf_records/vcf_record.py#L349-L354 | train |
JukeboxPipeline/jukeboxmaya | src/jukeboxmaya/reftrack/refobjinter.py | MayaRefobjInterface.set_parent | def set_parent(self, child, parent):
"""Set the parent of the child reftrack node
:param child: the child reftrack node
:type child: str
:param parent: the parent reftrack node
:type parent: str
:returns: None
:rtype: None
:raises: None
"""
parents = cmds.listConnections("%s.parent" % child, plugs=True, source=True)
if parents:
# there is only one parent at a time
cmds.disconnectAttr("%s.parent" % child, "%s" % parents[0])
if parent:
cmds.connectAttr("%s.parent" % child, "%s.children" % parent, force=True, nextAvailable=True) | python | def set_parent(self, child, parent):
"""Set the parent of the child reftrack node
:param child: the child reftrack node
:type child: str
:param parent: the parent reftrack node
:type parent: str
:returns: None
:rtype: None
:raises: None
"""
parents = cmds.listConnections("%s.parent" % child, plugs=True, source=True)
if parents:
# there is only one parent at a time
cmds.disconnectAttr("%s.parent" % child, "%s" % parents[0])
if parent:
cmds.connectAttr("%s.parent" % child, "%s.children" % parent, force=True, nextAvailable=True) | [
"def",
"set_parent",
"(",
"self",
",",
"child",
",",
"parent",
")",
":",
"parents",
"=",
"cmds",
".",
"listConnections",
"(",
"\"%s.parent\"",
"%",
"child",
",",
"plugs",
"=",
"True",
",",
"source",
"=",
"True",
")",
"if",
"parents",
":",
"# there is only one parent at a time",
"cmds",
".",
"disconnectAttr",
"(",
"\"%s.parent\"",
"%",
"child",
",",
"\"%s\"",
"%",
"parents",
"[",
"0",
"]",
")",
"if",
"parent",
":",
"cmds",
".",
"connectAttr",
"(",
"\"%s.parent\"",
"%",
"child",
",",
"\"%s.children\"",
"%",
"parent",
",",
"force",
"=",
"True",
",",
"nextAvailable",
"=",
"True",
")"
]
| Set the parent of the child reftrack node
:param child: the child reftrack node
:type child: str
:param parent: the parent reftrack node
:type parent: str
:returns: None
:rtype: None
:raises: None | [
"Set",
"the",
"parent",
"of",
"the",
"child",
"reftrack",
"node"
]
| c8d6318d53cdb5493453c4a6b65ef75bdb2d5f2c | https://github.com/JukeboxPipeline/jukeboxmaya/blob/c8d6318d53cdb5493453c4a6b65ef75bdb2d5f2c/src/jukeboxmaya/reftrack/refobjinter.py#L62-L78 | train |
JukeboxPipeline/jukeboxmaya | src/jukeboxmaya/reftrack/refobjinter.py | MayaRefobjInterface.get_children | def get_children(self, refobj):
"""Get the children reftrack nodes of the given node
It is the reverse query of :meth:`RefobjInterface.get_parent`
:param refobj: the parent reftrack node
:type refobj: str
:returns: a list with children reftrack nodes
:rtype: list
:raises: None
"""
children = cmds.listConnections("%s.children" % refobj, d=False)
if not children:
children = []
return children | python | def get_children(self, refobj):
"""Get the children reftrack nodes of the given node
It is the reverse query of :meth:`RefobjInterface.get_parent`
:param refobj: the parent reftrack node
:type refobj: str
:returns: a list with children reftrack nodes
:rtype: list
:raises: None
"""
children = cmds.listConnections("%s.children" % refobj, d=False)
if not children:
children = []
return children | [
"def",
"get_children",
"(",
"self",
",",
"refobj",
")",
":",
"children",
"=",
"cmds",
".",
"listConnections",
"(",
"\"%s.children\"",
"%",
"refobj",
",",
"d",
"=",
"False",
")",
"if",
"not",
"children",
":",
"children",
"=",
"[",
"]",
"return",
"children"
]
| Get the children reftrack nodes of the given node
It is the reverse query of :meth:`RefobjInterface.get_parent`
:param refobj: the parent reftrack node
:type refobj: str
:returns: a list with children reftrack nodes
:rtype: list
:raises: None | [
"Get",
"the",
"children",
"reftrack",
"nodes",
"of",
"the",
"given",
"node"
]
| c8d6318d53cdb5493453c4a6b65ef75bdb2d5f2c | https://github.com/JukeboxPipeline/jukeboxmaya/blob/c8d6318d53cdb5493453c4a6b65ef75bdb2d5f2c/src/jukeboxmaya/reftrack/refobjinter.py#L80-L94 | train |
JukeboxPipeline/jukeboxmaya | src/jukeboxmaya/reftrack/refobjinter.py | MayaRefobjInterface.get_typ | def get_typ(self, refobj):
"""Return the entity type of the given reftrack node
See: :data:`MayaRefobjInterface.types`.
:param refobj: the reftrack node to query
:type refobj: str
:returns: the entity type
:rtype: str
:raises: ValueError
"""
enum = cmds.getAttr("%s.type" % refobj)
try:
return JB_ReftrackNode.types[enum]
except IndexError:
raise ValueError("The type on the node %s could not be associated with an available type: %s" %
(refobj, JB_ReftrackNode.types)) | python | def get_typ(self, refobj):
"""Return the entity type of the given reftrack node
See: :data:`MayaRefobjInterface.types`.
:param refobj: the reftrack node to query
:type refobj: str
:returns: the entity type
:rtype: str
:raises: ValueError
"""
enum = cmds.getAttr("%s.type" % refobj)
try:
return JB_ReftrackNode.types[enum]
except IndexError:
raise ValueError("The type on the node %s could not be associated with an available type: %s" %
(refobj, JB_ReftrackNode.types)) | [
"def",
"get_typ",
"(",
"self",
",",
"refobj",
")",
":",
"enum",
"=",
"cmds",
".",
"getAttr",
"(",
"\"%s.type\"",
"%",
"refobj",
")",
"try",
":",
"return",
"JB_ReftrackNode",
".",
"types",
"[",
"enum",
"]",
"except",
"IndexError",
":",
"raise",
"ValueError",
"(",
"\"The type on the node %s could not be associated with an available type: %s\"",
"%",
"(",
"refobj",
",",
"JB_ReftrackNode",
".",
"types",
")",
")"
]
| Return the entity type of the given reftrack node
See: :data:`MayaRefobjInterface.types`.
:param refobj: the reftrack node to query
:type refobj: str
:returns: the entity type
:rtype: str
:raises: ValueError | [
"Return",
"the",
"entity",
"type",
"of",
"the",
"given",
"reftrack",
"node"
]
| c8d6318d53cdb5493453c4a6b65ef75bdb2d5f2c | https://github.com/JukeboxPipeline/jukeboxmaya/blob/c8d6318d53cdb5493453c4a6b65ef75bdb2d5f2c/src/jukeboxmaya/reftrack/refobjinter.py#L96-L112 | train |
JukeboxPipeline/jukeboxmaya | src/jukeboxmaya/reftrack/refobjinter.py | MayaRefobjInterface.set_typ | def set_typ(self, refobj, typ):
"""Set the type of the given refobj
:param refobj: the reftrack node to edit
:type refobj: refobj
:param typ: the entity type
:type typ: str
:returns: None
:rtype: None
:raises: ValueError
"""
try:
enum = JB_ReftrackNode.types.index(typ)
except ValueError:
raise ValueError("The given type %s could not be found in available types: %" % (typ, JB_ReftrackNode.types))
cmds.setAttr("%s.type" % refobj, enum) | python | def set_typ(self, refobj, typ):
"""Set the type of the given refobj
:param refobj: the reftrack node to edit
:type refobj: refobj
:param typ: the entity type
:type typ: str
:returns: None
:rtype: None
:raises: ValueError
"""
try:
enum = JB_ReftrackNode.types.index(typ)
except ValueError:
raise ValueError("The given type %s could not be found in available types: %" % (typ, JB_ReftrackNode.types))
cmds.setAttr("%s.type" % refobj, enum) | [
"def",
"set_typ",
"(",
"self",
",",
"refobj",
",",
"typ",
")",
":",
"try",
":",
"enum",
"=",
"JB_ReftrackNode",
".",
"types",
".",
"index",
"(",
"typ",
")",
"except",
"ValueError",
":",
"raise",
"ValueError",
"(",
"\"The given type %s could not be found in available types: %\"",
"%",
"(",
"typ",
",",
"JB_ReftrackNode",
".",
"types",
")",
")",
"cmds",
".",
"setAttr",
"(",
"\"%s.type\"",
"%",
"refobj",
",",
"enum",
")"
]
| Set the type of the given refobj
:param refobj: the reftrack node to edit
:type refobj: refobj
:param typ: the entity type
:type typ: str
:returns: None
:rtype: None
:raises: ValueError | [
"Set",
"the",
"type",
"of",
"the",
"given",
"refobj"
]
| c8d6318d53cdb5493453c4a6b65ef75bdb2d5f2c | https://github.com/JukeboxPipeline/jukeboxmaya/blob/c8d6318d53cdb5493453c4a6b65ef75bdb2d5f2c/src/jukeboxmaya/reftrack/refobjinter.py#L114-L129 | train |
JukeboxPipeline/jukeboxmaya | src/jukeboxmaya/reftrack/refobjinter.py | MayaRefobjInterface.create_refobj | def create_refobj(self, ):
"""Create and return a new reftrack node
:returns: the new reftrack node
:rtype: str
:raises: None
"""
n = cmds.createNode("jb_reftrack")
cmds.lockNode(n, lock=True)
return n | python | def create_refobj(self, ):
"""Create and return a new reftrack node
:returns: the new reftrack node
:rtype: str
:raises: None
"""
n = cmds.createNode("jb_reftrack")
cmds.lockNode(n, lock=True)
return n | [
"def",
"create_refobj",
"(",
"self",
",",
")",
":",
"n",
"=",
"cmds",
".",
"createNode",
"(",
"\"jb_reftrack\"",
")",
"cmds",
".",
"lockNode",
"(",
"n",
",",
"lock",
"=",
"True",
")",
"return",
"n"
]
| Create and return a new reftrack node
:returns: the new reftrack node
:rtype: str
:raises: None | [
"Create",
"and",
"return",
"a",
"new",
"reftrack",
"node"
]
| c8d6318d53cdb5493453c4a6b65ef75bdb2d5f2c | https://github.com/JukeboxPipeline/jukeboxmaya/blob/c8d6318d53cdb5493453c4a6b65ef75bdb2d5f2c/src/jukeboxmaya/reftrack/refobjinter.py#L155-L164 | train |
JukeboxPipeline/jukeboxmaya | src/jukeboxmaya/reftrack/refobjinter.py | MayaRefobjInterface.referenced_by | def referenced_by(self, refobj):
"""Return the reference that holds the given reftrack node.
Returns None if it is imported/in the current scene.
:param refobj: the reftrack node to query
:type refobj: str
:returns: the reference node that holds the given refobj
:rtype: str | None
:raises: None
"""
try:
ref = cmds.referenceQuery(refobj, referenceNode=True)
return ref
except RuntimeError as e:
if str(e).endswith("' is not from a referenced file.\n"):
return None
else:
raise e | python | def referenced_by(self, refobj):
"""Return the reference that holds the given reftrack node.
Returns None if it is imported/in the current scene.
:param refobj: the reftrack node to query
:type refobj: str
:returns: the reference node that holds the given refobj
:rtype: str | None
:raises: None
"""
try:
ref = cmds.referenceQuery(refobj, referenceNode=True)
return ref
except RuntimeError as e:
if str(e).endswith("' is not from a referenced file.\n"):
return None
else:
raise e | [
"def",
"referenced_by",
"(",
"self",
",",
"refobj",
")",
":",
"try",
":",
"ref",
"=",
"cmds",
".",
"referenceQuery",
"(",
"refobj",
",",
"referenceNode",
"=",
"True",
")",
"return",
"ref",
"except",
"RuntimeError",
"as",
"e",
":",
"if",
"str",
"(",
"e",
")",
".",
"endswith",
"(",
"\"' is not from a referenced file.\\n\"",
")",
":",
"return",
"None",
"else",
":",
"raise",
"e"
]
| Return the reference that holds the given reftrack node.
Returns None if it is imported/in the current scene.
:param refobj: the reftrack node to query
:type refobj: str
:returns: the reference node that holds the given refobj
:rtype: str | None
:raises: None | [
"Return",
"the",
"reference",
"that",
"holds",
"the",
"given",
"reftrack",
"node",
"."
]
| c8d6318d53cdb5493453c4a6b65ef75bdb2d5f2c | https://github.com/JukeboxPipeline/jukeboxmaya/blob/c8d6318d53cdb5493453c4a6b65ef75bdb2d5f2c/src/jukeboxmaya/reftrack/refobjinter.py#L166-L184 | train |
JukeboxPipeline/jukeboxmaya | src/jukeboxmaya/reftrack/refobjinter.py | MayaRefobjInterface.delete_refobj | def delete_refobj(self, refobj):
"""Delete the given reftrack node
:param refobj: the node to delete
:type refobj: str
:returns: None
:rtype: None
:raises: None
"""
with common.locknode(refobj, lock=False):
cmds.delete(refobj) | python | def delete_refobj(self, refobj):
"""Delete the given reftrack node
:param refobj: the node to delete
:type refobj: str
:returns: None
:rtype: None
:raises: None
"""
with common.locknode(refobj, lock=False):
cmds.delete(refobj) | [
"def",
"delete_refobj",
"(",
"self",
",",
"refobj",
")",
":",
"with",
"common",
".",
"locknode",
"(",
"refobj",
",",
"lock",
"=",
"False",
")",
":",
"cmds",
".",
"delete",
"(",
"refobj",
")"
]
| Delete the given reftrack node
:param refobj: the node to delete
:type refobj: str
:returns: None
:rtype: None
:raises: None | [
"Delete",
"the",
"given",
"reftrack",
"node"
]
| c8d6318d53cdb5493453c4a6b65ef75bdb2d5f2c | https://github.com/JukeboxPipeline/jukeboxmaya/blob/c8d6318d53cdb5493453c4a6b65ef75bdb2d5f2c/src/jukeboxmaya/reftrack/refobjinter.py#L197-L207 | train |
JukeboxPipeline/jukeboxmaya | src/jukeboxmaya/reftrack/refobjinter.py | MayaRefobjInterface.get_current_element | def get_current_element(self, ):
"""Return the currently open Shot or Asset
:returns: the currently open element
:rtype: :class:`jukeboxcore.djadapter.models.Asset` | :class:`jukeboxcore.djadapter.models.Shot` | None
:raises: :class:`djadapter.models.TaskFile.DoesNotExist`
"""
n = jbscene.get_current_scene_node()
if not n:
return None
tfid = cmds.getAttr("%s.taskfile_id" % n)
try:
tf = djadapter.taskfiles.get(pk=tfid)
return tf.task.element
except djadapter.models.TaskFile.DoesNotExist:
raise djadapter.models.TaskFile.DoesNotExist("Could not find the taskfile that was set on the scene node. Id was %s" % tfid) | python | def get_current_element(self, ):
"""Return the currently open Shot or Asset
:returns: the currently open element
:rtype: :class:`jukeboxcore.djadapter.models.Asset` | :class:`jukeboxcore.djadapter.models.Shot` | None
:raises: :class:`djadapter.models.TaskFile.DoesNotExist`
"""
n = jbscene.get_current_scene_node()
if not n:
return None
tfid = cmds.getAttr("%s.taskfile_id" % n)
try:
tf = djadapter.taskfiles.get(pk=tfid)
return tf.task.element
except djadapter.models.TaskFile.DoesNotExist:
raise djadapter.models.TaskFile.DoesNotExist("Could not find the taskfile that was set on the scene node. Id was %s" % tfid) | [
"def",
"get_current_element",
"(",
"self",
",",
")",
":",
"n",
"=",
"jbscene",
".",
"get_current_scene_node",
"(",
")",
"if",
"not",
"n",
":",
"return",
"None",
"tfid",
"=",
"cmds",
".",
"getAttr",
"(",
"\"%s.taskfile_id\"",
"%",
"n",
")",
"try",
":",
"tf",
"=",
"djadapter",
".",
"taskfiles",
".",
"get",
"(",
"pk",
"=",
"tfid",
")",
"return",
"tf",
".",
"task",
".",
"element",
"except",
"djadapter",
".",
"models",
".",
"TaskFile",
".",
"DoesNotExist",
":",
"raise",
"djadapter",
".",
"models",
".",
"TaskFile",
".",
"DoesNotExist",
"(",
"\"Could not find the taskfile that was set on the scene node. Id was %s\"",
"%",
"tfid",
")"
]
| Return the currently open Shot or Asset
:returns: the currently open element
:rtype: :class:`jukeboxcore.djadapter.models.Asset` | :class:`jukeboxcore.djadapter.models.Shot` | None
:raises: :class:`djadapter.models.TaskFile.DoesNotExist` | [
"Return",
"the",
"currently",
"open",
"Shot",
"or",
"Asset"
]
| c8d6318d53cdb5493453c4a6b65ef75bdb2d5f2c | https://github.com/JukeboxPipeline/jukeboxmaya/blob/c8d6318d53cdb5493453c4a6b65ef75bdb2d5f2c/src/jukeboxmaya/reftrack/refobjinter.py#L218-L233 | train |
JukeboxPipeline/jukeboxmaya | src/jukeboxmaya/reftrack/refobjinter.py | MayaRefobjInterface.set_reference | def set_reference(self, refobj, reference):
"""Connect the given reftrack node with the given refernce node
:param refobj: the reftrack node to update
:type refobj: str
:param reference: the reference node
:type reference: str
:returns: None
:rtype: None
:raises: None
"""
refnodeattr = "%s.referencenode" % refobj
if reference:
cmds.connectAttr("%s.message" % reference, refnodeattr, force=True)
ns = cmds.referenceQuery(reference, namespace=True)
cmds.setAttr("%s.namespace" % refobj, ns, type="string")
else:
conns = cmds.listConnections(refnodeattr, plugs=True)
if not conns:
return
for c in conns:
cmds.disconnectAttr(c, refnodeattr) | python | def set_reference(self, refobj, reference):
"""Connect the given reftrack node with the given refernce node
:param refobj: the reftrack node to update
:type refobj: str
:param reference: the reference node
:type reference: str
:returns: None
:rtype: None
:raises: None
"""
refnodeattr = "%s.referencenode" % refobj
if reference:
cmds.connectAttr("%s.message" % reference, refnodeattr, force=True)
ns = cmds.referenceQuery(reference, namespace=True)
cmds.setAttr("%s.namespace" % refobj, ns, type="string")
else:
conns = cmds.listConnections(refnodeattr, plugs=True)
if not conns:
return
for c in conns:
cmds.disconnectAttr(c, refnodeattr) | [
"def",
"set_reference",
"(",
"self",
",",
"refobj",
",",
"reference",
")",
":",
"refnodeattr",
"=",
"\"%s.referencenode\"",
"%",
"refobj",
"if",
"reference",
":",
"cmds",
".",
"connectAttr",
"(",
"\"%s.message\"",
"%",
"reference",
",",
"refnodeattr",
",",
"force",
"=",
"True",
")",
"ns",
"=",
"cmds",
".",
"referenceQuery",
"(",
"reference",
",",
"namespace",
"=",
"True",
")",
"cmds",
".",
"setAttr",
"(",
"\"%s.namespace\"",
"%",
"refobj",
",",
"ns",
",",
"type",
"=",
"\"string\"",
")",
"else",
":",
"conns",
"=",
"cmds",
".",
"listConnections",
"(",
"refnodeattr",
",",
"plugs",
"=",
"True",
")",
"if",
"not",
"conns",
":",
"return",
"for",
"c",
"in",
"conns",
":",
"cmds",
".",
"disconnectAttr",
"(",
"c",
",",
"refnodeattr",
")"
]
| Connect the given reftrack node with the given refernce node
:param refobj: the reftrack node to update
:type refobj: str
:param reference: the reference node
:type reference: str
:returns: None
:rtype: None
:raises: None | [
"Connect",
"the",
"given",
"reftrack",
"node",
"with",
"the",
"given",
"refernce",
"node"
]
| c8d6318d53cdb5493453c4a6b65ef75bdb2d5f2c | https://github.com/JukeboxPipeline/jukeboxmaya/blob/c8d6318d53cdb5493453c4a6b65ef75bdb2d5f2c/src/jukeboxmaya/reftrack/refobjinter.py#L235-L256 | train |
JukeboxPipeline/jukeboxmaya | src/jukeboxmaya/reftrack/refobjinter.py | MayaRefobjInterface.get_reference | def get_reference(self, refobj):
"""Return the reference node that the reftrack node is connected to or None if it is imported.
:param refobj: the reftrack node to query
:type refobj: str
:returns: the reference node
:rtype: str | None
:raises: None
"""
c = cmds.listConnections("%s.referencenode" % refobj, d=False)
return c[0] if c else None | python | def get_reference(self, refobj):
"""Return the reference node that the reftrack node is connected to or None if it is imported.
:param refobj: the reftrack node to query
:type refobj: str
:returns: the reference node
:rtype: str | None
:raises: None
"""
c = cmds.listConnections("%s.referencenode" % refobj, d=False)
return c[0] if c else None | [
"def",
"get_reference",
"(",
"self",
",",
"refobj",
")",
":",
"c",
"=",
"cmds",
".",
"listConnections",
"(",
"\"%s.referencenode\"",
"%",
"refobj",
",",
"d",
"=",
"False",
")",
"return",
"c",
"[",
"0",
"]",
"if",
"c",
"else",
"None"
]
| Return the reference node that the reftrack node is connected to or None if it is imported.
:param refobj: the reftrack node to query
:type refobj: str
:returns: the reference node
:rtype: str | None
:raises: None | [
"Return",
"the",
"reference",
"node",
"that",
"the",
"reftrack",
"node",
"is",
"connected",
"to",
"or",
"None",
"if",
"it",
"is",
"imported",
"."
]
| c8d6318d53cdb5493453c4a6b65ef75bdb2d5f2c | https://github.com/JukeboxPipeline/jukeboxmaya/blob/c8d6318d53cdb5493453c4a6b65ef75bdb2d5f2c/src/jukeboxmaya/reftrack/refobjinter.py#L258-L268 | train |
JukeboxPipeline/jukeboxmaya | src/jukeboxmaya/reftrack/refobjinter.py | MayaRefobjInterface.get_status | def get_status(self, refobj):
"""Return the status of the given reftrack node
See: :data:`Reftrack.LOADED`, :data:`Reftrack.UNLOADED`, :data:`Reftrack.IMPORTED`.
:param refobj: the reftrack node to query
:type refobj: str
:returns: the status of the given reftrack node
:rtype: str
:raises: None
"""
reference = self.get_reference(refobj)
return Reftrack.IMPORTED if not reference else Reftrack.LOADED if cmds.referenceQuery(reference, isLoaded=True) else Reftrack.UNLOADED | python | def get_status(self, refobj):
"""Return the status of the given reftrack node
See: :data:`Reftrack.LOADED`, :data:`Reftrack.UNLOADED`, :data:`Reftrack.IMPORTED`.
:param refobj: the reftrack node to query
:type refobj: str
:returns: the status of the given reftrack node
:rtype: str
:raises: None
"""
reference = self.get_reference(refobj)
return Reftrack.IMPORTED if not reference else Reftrack.LOADED if cmds.referenceQuery(reference, isLoaded=True) else Reftrack.UNLOADED | [
"def",
"get_status",
"(",
"self",
",",
"refobj",
")",
":",
"reference",
"=",
"self",
".",
"get_reference",
"(",
"refobj",
")",
"return",
"Reftrack",
".",
"IMPORTED",
"if",
"not",
"reference",
"else",
"Reftrack",
".",
"LOADED",
"if",
"cmds",
".",
"referenceQuery",
"(",
"reference",
",",
"isLoaded",
"=",
"True",
")",
"else",
"Reftrack",
".",
"UNLOADED"
]
| Return the status of the given reftrack node
See: :data:`Reftrack.LOADED`, :data:`Reftrack.UNLOADED`, :data:`Reftrack.IMPORTED`.
:param refobj: the reftrack node to query
:type refobj: str
:returns: the status of the given reftrack node
:rtype: str
:raises: None | [
"Return",
"the",
"status",
"of",
"the",
"given",
"reftrack",
"node"
]
| c8d6318d53cdb5493453c4a6b65ef75bdb2d5f2c | https://github.com/JukeboxPipeline/jukeboxmaya/blob/c8d6318d53cdb5493453c4a6b65ef75bdb2d5f2c/src/jukeboxmaya/reftrack/refobjinter.py#L270-L282 | train |
JukeboxPipeline/jukeboxmaya | src/jukeboxmaya/reftrack/refobjinter.py | MayaRefobjInterface.get_taskfile | def get_taskfile(self, refobj):
"""Return the taskfile that is loaded and represented by the refobj
:param refobj: the reftrack node to query
:type refobj: str
:returns: The taskfile that is loaded in the scene
:rtype: :class:`jukeboxcore.djadapter.TaskFile`
:raises: None
"""
tfid = cmds.getAttr("%s.taskfile_id" % refobj)
try:
return djadapter.taskfiles.get(pk=tfid)
except djadapter.models.TaskFile.DoesNotExist:
raise djadapter.models.TaskFile.DoesNotExist("Could not find the taskfile that was set on the node %s. Id was %s" % (refobj, tfid)) | python | def get_taskfile(self, refobj):
"""Return the taskfile that is loaded and represented by the refobj
:param refobj: the reftrack node to query
:type refobj: str
:returns: The taskfile that is loaded in the scene
:rtype: :class:`jukeboxcore.djadapter.TaskFile`
:raises: None
"""
tfid = cmds.getAttr("%s.taskfile_id" % refobj)
try:
return djadapter.taskfiles.get(pk=tfid)
except djadapter.models.TaskFile.DoesNotExist:
raise djadapter.models.TaskFile.DoesNotExist("Could not find the taskfile that was set on the node %s. Id was %s" % (refobj, tfid)) | [
"def",
"get_taskfile",
"(",
"self",
",",
"refobj",
")",
":",
"tfid",
"=",
"cmds",
".",
"getAttr",
"(",
"\"%s.taskfile_id\"",
"%",
"refobj",
")",
"try",
":",
"return",
"djadapter",
".",
"taskfiles",
".",
"get",
"(",
"pk",
"=",
"tfid",
")",
"except",
"djadapter",
".",
"models",
".",
"TaskFile",
".",
"DoesNotExist",
":",
"raise",
"djadapter",
".",
"models",
".",
"TaskFile",
".",
"DoesNotExist",
"(",
"\"Could not find the taskfile that was set on the node %s. Id was %s\"",
"%",
"(",
"refobj",
",",
"tfid",
")",
")"
]
| Return the taskfile that is loaded and represented by the refobj
:param refobj: the reftrack node to query
:type refobj: str
:returns: The taskfile that is loaded in the scene
:rtype: :class:`jukeboxcore.djadapter.TaskFile`
:raises: None | [
"Return",
"the",
"taskfile",
"that",
"is",
"loaded",
"and",
"represented",
"by",
"the",
"refobj"
]
| c8d6318d53cdb5493453c4a6b65ef75bdb2d5f2c | https://github.com/JukeboxPipeline/jukeboxmaya/blob/c8d6318d53cdb5493453c4a6b65ef75bdb2d5f2c/src/jukeboxmaya/reftrack/refobjinter.py#L284-L297 | train |
JukeboxPipeline/jukeboxmaya | src/jukeboxmaya/reftrack/refobjinter.py | MayaRefobjInterface.connect_reftrack_scenenode | def connect_reftrack_scenenode(self, refobj, scenenode):
"""Connect the given reftrack node with the given scene node
:param refobj: the reftrack node to connect
:type refobj: str
:param scenenode: the jb_sceneNode to connect
:type scenenode: str
:returns: None
:rtype: None
:raises: None
"""
conns = [("%s.scenenode" % refobj, "%s.reftrack" % scenenode),
("%s.taskfile_id" % scenenode, "%s.taskfile_id" % refobj)]
for src, dst in conns:
if not cmds.isConnected(src, dst):
cmds.connectAttr(src, dst, force=True) | python | def connect_reftrack_scenenode(self, refobj, scenenode):
"""Connect the given reftrack node with the given scene node
:param refobj: the reftrack node to connect
:type refobj: str
:param scenenode: the jb_sceneNode to connect
:type scenenode: str
:returns: None
:rtype: None
:raises: None
"""
conns = [("%s.scenenode" % refobj, "%s.reftrack" % scenenode),
("%s.taskfile_id" % scenenode, "%s.taskfile_id" % refobj)]
for src, dst in conns:
if not cmds.isConnected(src, dst):
cmds.connectAttr(src, dst, force=True) | [
"def",
"connect_reftrack_scenenode",
"(",
"self",
",",
"refobj",
",",
"scenenode",
")",
":",
"conns",
"=",
"[",
"(",
"\"%s.scenenode\"",
"%",
"refobj",
",",
"\"%s.reftrack\"",
"%",
"scenenode",
")",
",",
"(",
"\"%s.taskfile_id\"",
"%",
"scenenode",
",",
"\"%s.taskfile_id\"",
"%",
"refobj",
")",
"]",
"for",
"src",
",",
"dst",
"in",
"conns",
":",
"if",
"not",
"cmds",
".",
"isConnected",
"(",
"src",
",",
"dst",
")",
":",
"cmds",
".",
"connectAttr",
"(",
"src",
",",
"dst",
",",
"force",
"=",
"True",
")"
]
| Connect the given reftrack node with the given scene node
:param refobj: the reftrack node to connect
:type refobj: str
:param scenenode: the jb_sceneNode to connect
:type scenenode: str
:returns: None
:rtype: None
:raises: None | [
"Connect",
"the",
"given",
"reftrack",
"node",
"with",
"the",
"given",
"scene",
"node"
]
| c8d6318d53cdb5493453c4a6b65ef75bdb2d5f2c | https://github.com/JukeboxPipeline/jukeboxmaya/blob/c8d6318d53cdb5493453c4a6b65ef75bdb2d5f2c/src/jukeboxmaya/reftrack/refobjinter.py#L299-L314 | train |
sirfoga/pyhal | hal/internet/engines.py | SearchEngine.get_search_page | def get_search_page(self, query):
"""Gets HTML source
:param query: query to search engine
:return: HTML source of search page of given query
"""
query_web_page = Webpage(self.url + self.parse_query(query))
query_web_page.get_html_source() # get html source
return query_web_page.source | python | def get_search_page(self, query):
"""Gets HTML source
:param query: query to search engine
:return: HTML source of search page of given query
"""
query_web_page = Webpage(self.url + self.parse_query(query))
query_web_page.get_html_source() # get html source
return query_web_page.source | [
"def",
"get_search_page",
"(",
"self",
",",
"query",
")",
":",
"query_web_page",
"=",
"Webpage",
"(",
"self",
".",
"url",
"+",
"self",
".",
"parse_query",
"(",
"query",
")",
")",
"query_web_page",
".",
"get_html_source",
"(",
")",
"# get html source",
"return",
"query_web_page",
".",
"source"
]
| Gets HTML source
:param query: query to search engine
:return: HTML source of search page of given query | [
"Gets",
"HTML",
"source"
]
| 4394d8a1f7e45bea28a255ec390f4962ee64d33a | https://github.com/sirfoga/pyhal/blob/4394d8a1f7e45bea28a255ec390f4962ee64d33a/hal/internet/engines.py#L51-L59 | train |
klahnakoski/mo-logs | mo_logs/constants.py | set | def set(constants):
"""
REACH INTO THE MODULES AND OBJECTS TO SET CONSTANTS.
THINK OF THIS AS PRIMITIVE DEPENDENCY INJECTION FOR MODULES.
USEFUL FOR SETTING DEBUG FLAGS.
"""
if not constants:
return
constants = wrap(constants)
for k, new_value in constants.leaves():
errors = []
try:
old_value = mo_dots_set_attr(sys.modules, k, new_value)
continue
except Exception as e:
errors.append(e)
# ONE MODULE IS MISSING, THE CALLING MODULE
try:
caller_globals = sys._getframe(1).f_globals
caller_file = caller_globals["__file__"]
if not caller_file.endswith(".py"):
raise Exception("do not know how to handle non-python caller")
caller_module = caller_file[:-3].replace("/", ".")
path = split_field(k)
for i, p in enumerate(path):
if i == 0:
continue
prefix = join_field(path[:1])
name = join_field(path[i:])
if caller_module.endswith(prefix):
old_value = mo_dots_set_attr(caller_globals, name, new_value)
if DEBUG:
from mo_logs import Log
Log.note(
"Changed {{module}}[{{attribute}}] from {{old_value}} to {{new_value}}",
module=prefix,
attribute=name,
old_value=old_value,
new_value=new_value
)
break
except Exception as e:
errors.append(e)
if errors:
from mo_logs import Log
Log.error("Can not set constant {{path}}", path=k, cause=errors) | python | def set(constants):
"""
REACH INTO THE MODULES AND OBJECTS TO SET CONSTANTS.
THINK OF THIS AS PRIMITIVE DEPENDENCY INJECTION FOR MODULES.
USEFUL FOR SETTING DEBUG FLAGS.
"""
if not constants:
return
constants = wrap(constants)
for k, new_value in constants.leaves():
errors = []
try:
old_value = mo_dots_set_attr(sys.modules, k, new_value)
continue
except Exception as e:
errors.append(e)
# ONE MODULE IS MISSING, THE CALLING MODULE
try:
caller_globals = sys._getframe(1).f_globals
caller_file = caller_globals["__file__"]
if not caller_file.endswith(".py"):
raise Exception("do not know how to handle non-python caller")
caller_module = caller_file[:-3].replace("/", ".")
path = split_field(k)
for i, p in enumerate(path):
if i == 0:
continue
prefix = join_field(path[:1])
name = join_field(path[i:])
if caller_module.endswith(prefix):
old_value = mo_dots_set_attr(caller_globals, name, new_value)
if DEBUG:
from mo_logs import Log
Log.note(
"Changed {{module}}[{{attribute}}] from {{old_value}} to {{new_value}}",
module=prefix,
attribute=name,
old_value=old_value,
new_value=new_value
)
break
except Exception as e:
errors.append(e)
if errors:
from mo_logs import Log
Log.error("Can not set constant {{path}}", path=k, cause=errors) | [
"def",
"set",
"(",
"constants",
")",
":",
"if",
"not",
"constants",
":",
"return",
"constants",
"=",
"wrap",
"(",
"constants",
")",
"for",
"k",
",",
"new_value",
"in",
"constants",
".",
"leaves",
"(",
")",
":",
"errors",
"=",
"[",
"]",
"try",
":",
"old_value",
"=",
"mo_dots_set_attr",
"(",
"sys",
".",
"modules",
",",
"k",
",",
"new_value",
")",
"continue",
"except",
"Exception",
"as",
"e",
":",
"errors",
".",
"append",
"(",
"e",
")",
"# ONE MODULE IS MISSING, THE CALLING MODULE",
"try",
":",
"caller_globals",
"=",
"sys",
".",
"_getframe",
"(",
"1",
")",
".",
"f_globals",
"caller_file",
"=",
"caller_globals",
"[",
"\"__file__\"",
"]",
"if",
"not",
"caller_file",
".",
"endswith",
"(",
"\".py\"",
")",
":",
"raise",
"Exception",
"(",
"\"do not know how to handle non-python caller\"",
")",
"caller_module",
"=",
"caller_file",
"[",
":",
"-",
"3",
"]",
".",
"replace",
"(",
"\"/\"",
",",
"\".\"",
")",
"path",
"=",
"split_field",
"(",
"k",
")",
"for",
"i",
",",
"p",
"in",
"enumerate",
"(",
"path",
")",
":",
"if",
"i",
"==",
"0",
":",
"continue",
"prefix",
"=",
"join_field",
"(",
"path",
"[",
":",
"1",
"]",
")",
"name",
"=",
"join_field",
"(",
"path",
"[",
"i",
":",
"]",
")",
"if",
"caller_module",
".",
"endswith",
"(",
"prefix",
")",
":",
"old_value",
"=",
"mo_dots_set_attr",
"(",
"caller_globals",
",",
"name",
",",
"new_value",
")",
"if",
"DEBUG",
":",
"from",
"mo_logs",
"import",
"Log",
"Log",
".",
"note",
"(",
"\"Changed {{module}}[{{attribute}}] from {{old_value}} to {{new_value}}\"",
",",
"module",
"=",
"prefix",
",",
"attribute",
"=",
"name",
",",
"old_value",
"=",
"old_value",
",",
"new_value",
"=",
"new_value",
")",
"break",
"except",
"Exception",
"as",
"e",
":",
"errors",
".",
"append",
"(",
"e",
")",
"if",
"errors",
":",
"from",
"mo_logs",
"import",
"Log",
"Log",
".",
"error",
"(",
"\"Can not set constant {{path}}\"",
",",
"path",
"=",
"k",
",",
"cause",
"=",
"errors",
")"
]
| REACH INTO THE MODULES AND OBJECTS TO SET CONSTANTS.
THINK OF THIS AS PRIMITIVE DEPENDENCY INJECTION FOR MODULES.
USEFUL FOR SETTING DEBUG FLAGS. | [
"REACH",
"INTO",
"THE",
"MODULES",
"AND",
"OBJECTS",
"TO",
"SET",
"CONSTANTS",
".",
"THINK",
"OF",
"THIS",
"AS",
"PRIMITIVE",
"DEPENDENCY",
"INJECTION",
"FOR",
"MODULES",
".",
"USEFUL",
"FOR",
"SETTING",
"DEBUG",
"FLAGS",
"."
]
| 0971277ac9caf28a755b766b70621916957d4fea | https://github.com/klahnakoski/mo-logs/blob/0971277ac9caf28a755b766b70621916957d4fea/mo_logs/constants.py#L19-L70 | train |
portfors-lab/sparkle | sparkle/gui/plotting/raster_bounds_dlg.py | RasterBoundsDialog.values | def values(self):
"""Gets the user enter max and min values of where the
raster points should appear on the y-axis
:returns: (float, float) -- (min, max) y-values to bound the raster plot by
"""
lower = float(self.lowerSpnbx.value())
upper = float(self.upperSpnbx.value())
return (lower, upper) | python | def values(self):
"""Gets the user enter max and min values of where the
raster points should appear on the y-axis
:returns: (float, float) -- (min, max) y-values to bound the raster plot by
"""
lower = float(self.lowerSpnbx.value())
upper = float(self.upperSpnbx.value())
return (lower, upper) | [
"def",
"values",
"(",
"self",
")",
":",
"lower",
"=",
"float",
"(",
"self",
".",
"lowerSpnbx",
".",
"value",
"(",
")",
")",
"upper",
"=",
"float",
"(",
"self",
".",
"upperSpnbx",
".",
"value",
"(",
")",
")",
"return",
"(",
"lower",
",",
"upper",
")"
]
| Gets the user enter max and min values of where the
raster points should appear on the y-axis
:returns: (float, float) -- (min, max) y-values to bound the raster plot by | [
"Gets",
"the",
"user",
"enter",
"max",
"and",
"min",
"values",
"of",
"where",
"the",
"raster",
"points",
"should",
"appear",
"on",
"the",
"y",
"-",
"axis"
]
| 5fad1cf2bec58ec6b15d91da20f6236a74826110 | https://github.com/portfors-lab/sparkle/blob/5fad1cf2bec58ec6b15d91da20f6236a74826110/sparkle/gui/plotting/raster_bounds_dlg.py#L16-L24 | train |
JukeboxPipeline/jukeboxmaya | src/jukeboxmaya/menu.py | Menu._delete | def _delete(self, ):
""" Delete the menu and remove it from parent
Deletes all children, so they do not reference to this instance and it can be garbage collected.
Sets parent to None, so parent is also garbage collectable
This has proven to be very unreliable. so we delete the menu from the parent manually too.
:returns: None
:rtype: None
:raises: None
"""
for k in self.keys():
try:
self[k]._delete()
except KeyError:
pass
if self.__parent is not None:
del self.__parent[self.__name]
self.__parent = None
cmds.deleteUI(self.__menustring) | python | def _delete(self, ):
""" Delete the menu and remove it from parent
Deletes all children, so they do not reference to this instance and it can be garbage collected.
Sets parent to None, so parent is also garbage collectable
This has proven to be very unreliable. so we delete the menu from the parent manually too.
:returns: None
:rtype: None
:raises: None
"""
for k in self.keys():
try:
self[k]._delete()
except KeyError:
pass
if self.__parent is not None:
del self.__parent[self.__name]
self.__parent = None
cmds.deleteUI(self.__menustring) | [
"def",
"_delete",
"(",
"self",
",",
")",
":",
"for",
"k",
"in",
"self",
".",
"keys",
"(",
")",
":",
"try",
":",
"self",
"[",
"k",
"]",
".",
"_delete",
"(",
")",
"except",
"KeyError",
":",
"pass",
"if",
"self",
".",
"__parent",
"is",
"not",
"None",
":",
"del",
"self",
".",
"__parent",
"[",
"self",
".",
"__name",
"]",
"self",
".",
"__parent",
"=",
"None",
"cmds",
".",
"deleteUI",
"(",
"self",
".",
"__menustring",
")"
]
| Delete the menu and remove it from parent
Deletes all children, so they do not reference to this instance and it can be garbage collected.
Sets parent to None, so parent is also garbage collectable
This has proven to be very unreliable. so we delete the menu from the parent manually too.
:returns: None
:rtype: None
:raises: None | [
"Delete",
"the",
"menu",
"and",
"remove",
"it",
"from",
"parent"
]
| c8d6318d53cdb5493453c4a6b65ef75bdb2d5f2c | https://github.com/JukeboxPipeline/jukeboxmaya/blob/c8d6318d53cdb5493453c4a6b65ef75bdb2d5f2c/src/jukeboxmaya/menu.py#L91-L111 | train |
JukeboxPipeline/jukeboxmaya | src/jukeboxmaya/menu.py | MenuManager.create_menu | def create_menu(self, name, parent=None, **kwargs):
""" Creates a maya menu or menu item
:param name: Used to access a menu via its parent. Unless the nolabel flag is set to True, the name will also become the label of the menu.
:type name: str
:param parent: Optional - The parent menu. If None, this will create a toplevel menu. If parent menu is a Menu instance, this will create a menu item. Default is None.
:type parent: Menu|None
:param nolabel: Optional - If nolabel=True, the label flag for the maya command will not be overwritten by name
:type nolabel: bool
:param kwargs: all keyword arguments used for the cmds.menu/cmds.menuitem command
:type kwargs: named arguments
:returns: None
:rtype: None
:raises: errors.MenuExistsError
"""
m = Menu(name, parent, **kwargs)
if parent is None:
self.menus[name] = m
return m | python | def create_menu(self, name, parent=None, **kwargs):
""" Creates a maya menu or menu item
:param name: Used to access a menu via its parent. Unless the nolabel flag is set to True, the name will also become the label of the menu.
:type name: str
:param parent: Optional - The parent menu. If None, this will create a toplevel menu. If parent menu is a Menu instance, this will create a menu item. Default is None.
:type parent: Menu|None
:param nolabel: Optional - If nolabel=True, the label flag for the maya command will not be overwritten by name
:type nolabel: bool
:param kwargs: all keyword arguments used for the cmds.menu/cmds.menuitem command
:type kwargs: named arguments
:returns: None
:rtype: None
:raises: errors.MenuExistsError
"""
m = Menu(name, parent, **kwargs)
if parent is None:
self.menus[name] = m
return m | [
"def",
"create_menu",
"(",
"self",
",",
"name",
",",
"parent",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"m",
"=",
"Menu",
"(",
"name",
",",
"parent",
",",
"*",
"*",
"kwargs",
")",
"if",
"parent",
"is",
"None",
":",
"self",
".",
"menus",
"[",
"name",
"]",
"=",
"m",
"return",
"m"
]
| Creates a maya menu or menu item
:param name: Used to access a menu via its parent. Unless the nolabel flag is set to True, the name will also become the label of the menu.
:type name: str
:param parent: Optional - The parent menu. If None, this will create a toplevel menu. If parent menu is a Menu instance, this will create a menu item. Default is None.
:type parent: Menu|None
:param nolabel: Optional - If nolabel=True, the label flag for the maya command will not be overwritten by name
:type nolabel: bool
:param kwargs: all keyword arguments used for the cmds.menu/cmds.menuitem command
:type kwargs: named arguments
:returns: None
:rtype: None
:raises: errors.MenuExistsError | [
"Creates",
"a",
"maya",
"menu",
"or",
"menu",
"item"
]
| c8d6318d53cdb5493453c4a6b65ef75bdb2d5f2c | https://github.com/JukeboxPipeline/jukeboxmaya/blob/c8d6318d53cdb5493453c4a6b65ef75bdb2d5f2c/src/jukeboxmaya/menu.py#L188-L206 | train |
JukeboxPipeline/jukeboxmaya | src/jukeboxmaya/menu.py | MenuManager.delete_menu | def delete_menu(self, menu):
""" Delete the specified menu
:param menu:
:type menu:
:returns:
:rtype:
:raises:
"""
if menu.parent is None:
del self.menus[menu.name()]
menu._delete() | python | def delete_menu(self, menu):
""" Delete the specified menu
:param menu:
:type menu:
:returns:
:rtype:
:raises:
"""
if menu.parent is None:
del self.menus[menu.name()]
menu._delete() | [
"def",
"delete_menu",
"(",
"self",
",",
"menu",
")",
":",
"if",
"menu",
".",
"parent",
"is",
"None",
":",
"del",
"self",
".",
"menus",
"[",
"menu",
".",
"name",
"(",
")",
"]",
"menu",
".",
"_delete",
"(",
")"
]
| Delete the specified menu
:param menu:
:type menu:
:returns:
:rtype:
:raises: | [
"Delete",
"the",
"specified",
"menu"
]
| c8d6318d53cdb5493453c4a6b65ef75bdb2d5f2c | https://github.com/JukeboxPipeline/jukeboxmaya/blob/c8d6318d53cdb5493453c4a6b65ef75bdb2d5f2c/src/jukeboxmaya/menu.py#L208-L219 | train |
JukeboxPipeline/jukeboxmaya | src/jukeboxmaya/menu.py | MenuManager.delete_all_menus | def delete_all_menus(self, ):
""" Delete all menues managed by this manager
:returns: None
:rtype: None
:raises: None
"""
for m in self.menus.itervalues():
m._delete()
self.menus.clear() | python | def delete_all_menus(self, ):
""" Delete all menues managed by this manager
:returns: None
:rtype: None
:raises: None
"""
for m in self.menus.itervalues():
m._delete()
self.menus.clear() | [
"def",
"delete_all_menus",
"(",
"self",
",",
")",
":",
"for",
"m",
"in",
"self",
".",
"menus",
".",
"itervalues",
"(",
")",
":",
"m",
".",
"_delete",
"(",
")",
"self",
".",
"menus",
".",
"clear",
"(",
")"
]
| Delete all menues managed by this manager
:returns: None
:rtype: None
:raises: None | [
"Delete",
"all",
"menues",
"managed",
"by",
"this",
"manager"
]
| c8d6318d53cdb5493453c4a6b65ef75bdb2d5f2c | https://github.com/JukeboxPipeline/jukeboxmaya/blob/c8d6318d53cdb5493453c4a6b65ef75bdb2d5f2c/src/jukeboxmaya/menu.py#L221-L230 | train |
ClearcodeHQ/matchbox | src/matchbox/index.py | MatchIndex.add_mismatch | def add_mismatch(self, entity, *traits):
"""
Add a mismatching entity to the index.
We do this by simply adding the mismatch to the index.
:param collections.Hashable entity: an object to be mismatching the values of `traits_indexed_by`
:param list traits: a list of hashable traits to index the entity with
"""
for trait in traits:
self.index[trait].add(entity) | python | def add_mismatch(self, entity, *traits):
"""
Add a mismatching entity to the index.
We do this by simply adding the mismatch to the index.
:param collections.Hashable entity: an object to be mismatching the values of `traits_indexed_by`
:param list traits: a list of hashable traits to index the entity with
"""
for trait in traits:
self.index[trait].add(entity) | [
"def",
"add_mismatch",
"(",
"self",
",",
"entity",
",",
"*",
"traits",
")",
":",
"for",
"trait",
"in",
"traits",
":",
"self",
".",
"index",
"[",
"trait",
"]",
".",
"add",
"(",
"entity",
")"
]
| Add a mismatching entity to the index.
We do this by simply adding the mismatch to the index.
:param collections.Hashable entity: an object to be mismatching the values of `traits_indexed_by`
:param list traits: a list of hashable traits to index the entity with | [
"Add",
"a",
"mismatching",
"entity",
"to",
"the",
"index",
"."
]
| 22f5bd163ad22ceacb0fcd5d4ddae9069d1a94f4 | https://github.com/ClearcodeHQ/matchbox/blob/22f5bd163ad22ceacb0fcd5d4ddae9069d1a94f4/src/matchbox/index.py#L141-L151 | train |
ClearcodeHQ/matchbox | src/matchbox/index.py | MatchIndex.add_match | def add_match(self, entity, *traits):
"""
Add a matching entity to the index.
We have to maintain the constraints of the data layout:
- `self.mismatch_unknown` must still contain all matched entities
- each key of the index must mismatch all known matching entities except those this particular key
explicitly includes
For data layout description, see the class-level docstring.
:param collections.Hashable entity: an object to be matching the values of `traits_indexed_by`
:param list traits: a list of hashable values to index the object with
"""
# The index traits of `traits_indexed_by` might have already been used to index some other entities. Those
# relations are to be preserved. If the trait was not used to index any entity, we initialize them to mismatch
# all matching entities known so far.
for trait in traits:
if trait not in self.index:
self.index[trait] = self.mismatch_unknown.copy()
# Now each known trait this entity is not matching, will explicitly mismatch currently added entity.
for existing_trait in self.index:
if existing_trait not in traits:
self.index[existing_trait].add(entity)
# From now on, any new matching or mismatching index will mismatch this entity by default.
self.mismatch_unknown.add(entity) | python | def add_match(self, entity, *traits):
"""
Add a matching entity to the index.
We have to maintain the constraints of the data layout:
- `self.mismatch_unknown` must still contain all matched entities
- each key of the index must mismatch all known matching entities except those this particular key
explicitly includes
For data layout description, see the class-level docstring.
:param collections.Hashable entity: an object to be matching the values of `traits_indexed_by`
:param list traits: a list of hashable values to index the object with
"""
# The index traits of `traits_indexed_by` might have already been used to index some other entities. Those
# relations are to be preserved. If the trait was not used to index any entity, we initialize them to mismatch
# all matching entities known so far.
for trait in traits:
if trait not in self.index:
self.index[trait] = self.mismatch_unknown.copy()
# Now each known trait this entity is not matching, will explicitly mismatch currently added entity.
for existing_trait in self.index:
if existing_trait not in traits:
self.index[existing_trait].add(entity)
# From now on, any new matching or mismatching index will mismatch this entity by default.
self.mismatch_unknown.add(entity) | [
"def",
"add_match",
"(",
"self",
",",
"entity",
",",
"*",
"traits",
")",
":",
"# The index traits of `traits_indexed_by` might have already been used to index some other entities. Those",
"# relations are to be preserved. If the trait was not used to index any entity, we initialize them to mismatch",
"# all matching entities known so far.",
"for",
"trait",
"in",
"traits",
":",
"if",
"trait",
"not",
"in",
"self",
".",
"index",
":",
"self",
".",
"index",
"[",
"trait",
"]",
"=",
"self",
".",
"mismatch_unknown",
".",
"copy",
"(",
")",
"# Now each known trait this entity is not matching, will explicitly mismatch currently added entity.",
"for",
"existing_trait",
"in",
"self",
".",
"index",
":",
"if",
"existing_trait",
"not",
"in",
"traits",
":",
"self",
".",
"index",
"[",
"existing_trait",
"]",
".",
"add",
"(",
"entity",
")",
"# From now on, any new matching or mismatching index will mismatch this entity by default.",
"self",
".",
"mismatch_unknown",
".",
"add",
"(",
"entity",
")"
]
| Add a matching entity to the index.
We have to maintain the constraints of the data layout:
- `self.mismatch_unknown` must still contain all matched entities
- each key of the index must mismatch all known matching entities except those this particular key
explicitly includes
For data layout description, see the class-level docstring.
:param collections.Hashable entity: an object to be matching the values of `traits_indexed_by`
:param list traits: a list of hashable values to index the object with | [
"Add",
"a",
"matching",
"entity",
"to",
"the",
"index",
"."
]
| 22f5bd163ad22ceacb0fcd5d4ddae9069d1a94f4 | https://github.com/ClearcodeHQ/matchbox/blob/22f5bd163ad22ceacb0fcd5d4ddae9069d1a94f4/src/matchbox/index.py#L153-L180 | train |
raymondEhlers/pachyderm | pachyderm/projectors.py | hist_axis_func | def hist_axis_func(axis_type: enum.Enum) -> Callable[[Hist], Axis]:
""" Wrapper to retrieve the axis of a given histogram.
This can be convenient outside of just projections, so it's made available in the API.
Args:
axis_type: The type of axis to retrieve.
Returns:
Callable to retrieve the specified axis when given a hist.
"""
def axis_func(hist: Hist) -> Axis:
""" Retrieve the axis associated with the ``HistAxisRange`` object for a given hist.
Args:
hist: Histogram from which the selected axis should be retrieved.
axis_type: Enumeration corresponding to the axis to be restricted. The numerical
value of the enum should be axis number (for a THnBase).
Returns:
ROOT.TAxis: The axis associated with the ``HistAxisRange`` object.
"""
# Determine the axis_type value
# Use try here instead of checking for a particular type to protect against type changes
# (say in the enum)
try:
# Try to extract the value from an enum
hist_axis_type = axis_type.value
except AttributeError:
# Seems that we received an int, so just use that value
hist_axis_type = axis_type
if hasattr(hist, "ProjectionND") and hasattr(hist, "Projection"):
# THnBase defines ProjectionND and Projection, so we will use those as proxies.
# Return the proper THn access
#logger.debug(f"From hist: {hist}, hist_axis_type: {hist_axis_type}, axis: {hist.GetAxis(hist_axis_type.value)}")
return hist.GetAxis(hist_axis_type)
else:
# If it's not a THn, then it must be a TH1 derived
axis_function_map = {
TH1AxisType.x_axis.value: hist.GetXaxis,
TH1AxisType.y_axis.value: hist.GetYaxis,
TH1AxisType.z_axis.value: hist.GetZaxis
}
# Retrieve the axis function and execute it. It is done separately to
# clarify any possible errors.
return_func = axis_function_map[hist_axis_type]
return return_func()
return axis_func | python | def hist_axis_func(axis_type: enum.Enum) -> Callable[[Hist], Axis]:
""" Wrapper to retrieve the axis of a given histogram.
This can be convenient outside of just projections, so it's made available in the API.
Args:
axis_type: The type of axis to retrieve.
Returns:
Callable to retrieve the specified axis when given a hist.
"""
def axis_func(hist: Hist) -> Axis:
""" Retrieve the axis associated with the ``HistAxisRange`` object for a given hist.
Args:
hist: Histogram from which the selected axis should be retrieved.
axis_type: Enumeration corresponding to the axis to be restricted. The numerical
value of the enum should be axis number (for a THnBase).
Returns:
ROOT.TAxis: The axis associated with the ``HistAxisRange`` object.
"""
# Determine the axis_type value
# Use try here instead of checking for a particular type to protect against type changes
# (say in the enum)
try:
# Try to extract the value from an enum
hist_axis_type = axis_type.value
except AttributeError:
# Seems that we received an int, so just use that value
hist_axis_type = axis_type
if hasattr(hist, "ProjectionND") and hasattr(hist, "Projection"):
# THnBase defines ProjectionND and Projection, so we will use those as proxies.
# Return the proper THn access
#logger.debug(f"From hist: {hist}, hist_axis_type: {hist_axis_type}, axis: {hist.GetAxis(hist_axis_type.value)}")
return hist.GetAxis(hist_axis_type)
else:
# If it's not a THn, then it must be a TH1 derived
axis_function_map = {
TH1AxisType.x_axis.value: hist.GetXaxis,
TH1AxisType.y_axis.value: hist.GetYaxis,
TH1AxisType.z_axis.value: hist.GetZaxis
}
# Retrieve the axis function and execute it. It is done separately to
# clarify any possible errors.
return_func = axis_function_map[hist_axis_type]
return return_func()
return axis_func | [
"def",
"hist_axis_func",
"(",
"axis_type",
":",
"enum",
".",
"Enum",
")",
"->",
"Callable",
"[",
"[",
"Hist",
"]",
",",
"Axis",
"]",
":",
"def",
"axis_func",
"(",
"hist",
":",
"Hist",
")",
"->",
"Axis",
":",
"\"\"\" Retrieve the axis associated with the ``HistAxisRange`` object for a given hist.\n\n Args:\n hist: Histogram from which the selected axis should be retrieved.\n axis_type: Enumeration corresponding to the axis to be restricted. The numerical\n value of the enum should be axis number (for a THnBase).\n Returns:\n ROOT.TAxis: The axis associated with the ``HistAxisRange`` object.\n \"\"\"",
"# Determine the axis_type value",
"# Use try here instead of checking for a particular type to protect against type changes",
"# (say in the enum)",
"try",
":",
"# Try to extract the value from an enum",
"hist_axis_type",
"=",
"axis_type",
".",
"value",
"except",
"AttributeError",
":",
"# Seems that we received an int, so just use that value",
"hist_axis_type",
"=",
"axis_type",
"if",
"hasattr",
"(",
"hist",
",",
"\"ProjectionND\"",
")",
"and",
"hasattr",
"(",
"hist",
",",
"\"Projection\"",
")",
":",
"# THnBase defines ProjectionND and Projection, so we will use those as proxies.",
"# Return the proper THn access",
"#logger.debug(f\"From hist: {hist}, hist_axis_type: {hist_axis_type}, axis: {hist.GetAxis(hist_axis_type.value)}\")",
"return",
"hist",
".",
"GetAxis",
"(",
"hist_axis_type",
")",
"else",
":",
"# If it's not a THn, then it must be a TH1 derived",
"axis_function_map",
"=",
"{",
"TH1AxisType",
".",
"x_axis",
".",
"value",
":",
"hist",
".",
"GetXaxis",
",",
"TH1AxisType",
".",
"y_axis",
".",
"value",
":",
"hist",
".",
"GetYaxis",
",",
"TH1AxisType",
".",
"z_axis",
".",
"value",
":",
"hist",
".",
"GetZaxis",
"}",
"# Retrieve the axis function and execute it. It is done separately to",
"# clarify any possible errors.",
"return_func",
"=",
"axis_function_map",
"[",
"hist_axis_type",
"]",
"return",
"return_func",
"(",
")",
"return",
"axis_func"
]
| Wrapper to retrieve the axis of a given histogram.
This can be convenient outside of just projections, so it's made available in the API.
Args:
axis_type: The type of axis to retrieve.
Returns:
Callable to retrieve the specified axis when given a hist. | [
"Wrapper",
"to",
"retrieve",
"the",
"axis",
"of",
"a",
"given",
"histogram",
"."
]
| aaa1d8374fd871246290ce76f1796f2f7582b01d | https://github.com/raymondEhlers/pachyderm/blob/aaa1d8374fd871246290ce76f1796f2f7582b01d/pachyderm/projectors.py#L29-L77 | train |
raymondEhlers/pachyderm | pachyderm/projectors.py | HistAxisRange.axis | def axis(self) -> Callable[[Any], Any]:
""" Determine the axis to return based on the hist type. """
axis_func = hist_axis_func(
axis_type = self.axis_type
)
return axis_func | python | def axis(self) -> Callable[[Any], Any]:
""" Determine the axis to return based on the hist type. """
axis_func = hist_axis_func(
axis_type = self.axis_type
)
return axis_func | [
"def",
"axis",
"(",
"self",
")",
"->",
"Callable",
"[",
"[",
"Any",
"]",
",",
"Any",
"]",
":",
"axis_func",
"=",
"hist_axis_func",
"(",
"axis_type",
"=",
"self",
".",
"axis_type",
")",
"return",
"axis_func"
]
| Determine the axis to return based on the hist type. | [
"Determine",
"the",
"axis",
"to",
"return",
"based",
"on",
"the",
"hist",
"type",
"."
]
| aaa1d8374fd871246290ce76f1796f2f7582b01d | https://github.com/raymondEhlers/pachyderm/blob/aaa1d8374fd871246290ce76f1796f2f7582b01d/pachyderm/projectors.py#L116-L121 | train |
raymondEhlers/pachyderm | pachyderm/projectors.py | HistAxisRange.apply_range_set | def apply_range_set(self, hist: Hist) -> None:
""" Apply the associated range set to the axis of a given hist.
Note:
The min and max values should be bins, not user ranges! For more, see the binning
explanation in ``apply_func_to_find_bin(...)``.
Args:
hist: Histogram to which the axis range restriction should be applied.
Returns:
None. The range is set on the axis.
"""
# Do individual assignments to clarify which particular value is causing an error here.
axis = self.axis(hist)
#logger.debug(f"axis: {axis}, axis(): {axis.GetName()}")
# Help out mypy
assert not isinstance(self.min_val, float)
assert not isinstance(self.max_val, float)
# Evaluate the functions to determine the values.
min_val = self.min_val(axis)
max_val = self.max_val(axis)
# NOTE: Using SetRangeUser() here was a bug, since I've been passing bin values! In general,
# passing bin values is more flexible, but requires the values to be passed to
# ``apply_func_to_find_bin()`` to be shifted by some small epsilon to get the desired bin.
self.axis(hist).SetRange(min_val, max_val) | python | def apply_range_set(self, hist: Hist) -> None:
""" Apply the associated range set to the axis of a given hist.
Note:
The min and max values should be bins, not user ranges! For more, see the binning
explanation in ``apply_func_to_find_bin(...)``.
Args:
hist: Histogram to which the axis range restriction should be applied.
Returns:
None. The range is set on the axis.
"""
# Do individual assignments to clarify which particular value is causing an error here.
axis = self.axis(hist)
#logger.debug(f"axis: {axis}, axis(): {axis.GetName()}")
# Help out mypy
assert not isinstance(self.min_val, float)
assert not isinstance(self.max_val, float)
# Evaluate the functions to determine the values.
min_val = self.min_val(axis)
max_val = self.max_val(axis)
# NOTE: Using SetRangeUser() here was a bug, since I've been passing bin values! In general,
# passing bin values is more flexible, but requires the values to be passed to
# ``apply_func_to_find_bin()`` to be shifted by some small epsilon to get the desired bin.
self.axis(hist).SetRange(min_val, max_val) | [
"def",
"apply_range_set",
"(",
"self",
",",
"hist",
":",
"Hist",
")",
"->",
"None",
":",
"# Do individual assignments to clarify which particular value is causing an error here.",
"axis",
"=",
"self",
".",
"axis",
"(",
"hist",
")",
"#logger.debug(f\"axis: {axis}, axis(): {axis.GetName()}\")",
"# Help out mypy",
"assert",
"not",
"isinstance",
"(",
"self",
".",
"min_val",
",",
"float",
")",
"assert",
"not",
"isinstance",
"(",
"self",
".",
"max_val",
",",
"float",
")",
"# Evaluate the functions to determine the values.",
"min_val",
"=",
"self",
".",
"min_val",
"(",
"axis",
")",
"max_val",
"=",
"self",
".",
"max_val",
"(",
"axis",
")",
"# NOTE: Using SetRangeUser() here was a bug, since I've been passing bin values! In general,",
"# passing bin values is more flexible, but requires the values to be passed to",
"# ``apply_func_to_find_bin()`` to be shifted by some small epsilon to get the desired bin.",
"self",
".",
"axis",
"(",
"hist",
")",
".",
"SetRange",
"(",
"min_val",
",",
"max_val",
")"
]
| Apply the associated range set to the axis of a given hist.
Note:
The min and max values should be bins, not user ranges! For more, see the binning
explanation in ``apply_func_to_find_bin(...)``.
Args:
hist: Histogram to which the axis range restriction should be applied.
Returns:
None. The range is set on the axis. | [
"Apply",
"the",
"associated",
"range",
"set",
"to",
"the",
"axis",
"of",
"a",
"given",
"hist",
"."
]
| aaa1d8374fd871246290ce76f1796f2f7582b01d | https://github.com/raymondEhlers/pachyderm/blob/aaa1d8374fd871246290ce76f1796f2f7582b01d/pachyderm/projectors.py#L123-L147 | train |
raymondEhlers/pachyderm | pachyderm/projectors.py | HistAxisRange.apply_func_to_find_bin | def apply_func_to_find_bin(
func: Union[None, Callable[..., Union[float, int, Any]]],
values: Optional[float] = None
) -> Callable[[Any], Union[float, int]]:
""" Closure to determine the bin associated with a value on an axis.
It can apply a function to an axis if necessary to determine the proper bin. Otherwise,
it can just return a stored value.
Note:
To properly determine the value, carefully note the information below. In many cases,
such as when we want values [2, 5), the values need to be shifted by a small epsilon
to retrieve the proper bin. This is done automatically in ``SetRangeUser()``.
>>> hist = ROOT.TH1D("test", "test", 10, 0, 10)
>>> x = 2, y = 5
>>> hist.FindBin(x)
2
>>> hist.FindBin(x+epsilon)
2
>>> hist.FindBin(y)
6
>>> hist.FindBin(y-epsilon)
5
Note that the bin + epsilon on the lower bin is not strictly necessary, but it is
used for consistency with the upper bound.
Args:
func (Callable): Function to apply to the histogram axis. If it is None, the value
will be returned.
values (int or float): Value to pass to the function. Default: None (in which case,
it won't be passed).
Returns:
Function to be called with an axis to determine the desired bin on that axis.
"""
def return_func(axis) -> Any:
""" Apply the stored function and value to a given axis.
Args:
axis (TAxis or similar): Axis to which the function should be applied.
Returns:
any: The value returned by the function. Often a float or int, but not necessarily.
"""
#logger.debug(f"func: {func}, values: {values}")
if func:
if values is not None:
return func(axis, values)
else:
return func(axis)
else:
return values
return return_func | python | def apply_func_to_find_bin(
func: Union[None, Callable[..., Union[float, int, Any]]],
values: Optional[float] = None
) -> Callable[[Any], Union[float, int]]:
""" Closure to determine the bin associated with a value on an axis.
It can apply a function to an axis if necessary to determine the proper bin. Otherwise,
it can just return a stored value.
Note:
To properly determine the value, carefully note the information below. In many cases,
such as when we want values [2, 5), the values need to be shifted by a small epsilon
to retrieve the proper bin. This is done automatically in ``SetRangeUser()``.
>>> hist = ROOT.TH1D("test", "test", 10, 0, 10)
>>> x = 2, y = 5
>>> hist.FindBin(x)
2
>>> hist.FindBin(x+epsilon)
2
>>> hist.FindBin(y)
6
>>> hist.FindBin(y-epsilon)
5
Note that the bin + epsilon on the lower bin is not strictly necessary, but it is
used for consistency with the upper bound.
Args:
func (Callable): Function to apply to the histogram axis. If it is None, the value
will be returned.
values (int or float): Value to pass to the function. Default: None (in which case,
it won't be passed).
Returns:
Function to be called with an axis to determine the desired bin on that axis.
"""
def return_func(axis) -> Any:
""" Apply the stored function and value to a given axis.
Args:
axis (TAxis or similar): Axis to which the function should be applied.
Returns:
any: The value returned by the function. Often a float or int, but not necessarily.
"""
#logger.debug(f"func: {func}, values: {values}")
if func:
if values is not None:
return func(axis, values)
else:
return func(axis)
else:
return values
return return_func | [
"def",
"apply_func_to_find_bin",
"(",
"func",
":",
"Union",
"[",
"None",
",",
"Callable",
"[",
"...",
",",
"Union",
"[",
"float",
",",
"int",
",",
"Any",
"]",
"]",
"]",
",",
"values",
":",
"Optional",
"[",
"float",
"]",
"=",
"None",
")",
"->",
"Callable",
"[",
"[",
"Any",
"]",
",",
"Union",
"[",
"float",
",",
"int",
"]",
"]",
":",
"def",
"return_func",
"(",
"axis",
")",
"->",
"Any",
":",
"\"\"\" Apply the stored function and value to a given axis.\n\n Args:\n axis (TAxis or similar): Axis to which the function should be applied.\n Returns:\n any: The value returned by the function. Often a float or int, but not necessarily.\n \"\"\"",
"#logger.debug(f\"func: {func}, values: {values}\")",
"if",
"func",
":",
"if",
"values",
"is",
"not",
"None",
":",
"return",
"func",
"(",
"axis",
",",
"values",
")",
"else",
":",
"return",
"func",
"(",
"axis",
")",
"else",
":",
"return",
"values",
"return",
"return_func"
]
| Closure to determine the bin associated with a value on an axis.
It can apply a function to an axis if necessary to determine the proper bin. Otherwise,
it can just return a stored value.
Note:
To properly determine the value, carefully note the information below. In many cases,
such as when we want values [2, 5), the values need to be shifted by a small epsilon
to retrieve the proper bin. This is done automatically in ``SetRangeUser()``.
>>> hist = ROOT.TH1D("test", "test", 10, 0, 10)
>>> x = 2, y = 5
>>> hist.FindBin(x)
2
>>> hist.FindBin(x+epsilon)
2
>>> hist.FindBin(y)
6
>>> hist.FindBin(y-epsilon)
5
Note that the bin + epsilon on the lower bin is not strictly necessary, but it is
used for consistency with the upper bound.
Args:
func (Callable): Function to apply to the histogram axis. If it is None, the value
will be returned.
values (int or float): Value to pass to the function. Default: None (in which case,
it won't be passed).
Returns:
Function to be called with an axis to determine the desired bin on that axis. | [
"Closure",
"to",
"determine",
"the",
"bin",
"associated",
"with",
"a",
"value",
"on",
"an",
"axis",
"."
]
| aaa1d8374fd871246290ce76f1796f2f7582b01d | https://github.com/raymondEhlers/pachyderm/blob/aaa1d8374fd871246290ce76f1796f2f7582b01d/pachyderm/projectors.py#L150-L203 | train |
raymondEhlers/pachyderm | pachyderm/projectors.py | HistProjector.call_projection_function | def call_projection_function(self, hist: Hist) -> Hist:
""" Calls the actual projection function for the hist.
Args:
hist: Histogram from which the projections should be performed.
Returns:
The projected histogram.
"""
# Restrict projection axis ranges
for axis in self.projection_axes:
logger.debug(f"Apply projection axes hist range: {axis.name}")
axis.apply_range_set(hist)
projected_hist = None
if hasattr(hist, "ProjectionND") and hasattr(hist, "Projection"):
# THnBase defines ProjectionND and Projection, so we will use those as proxies.
projected_hist = self._project_THn(hist = hist)
elif hasattr(hist, "ProjectionZ") and hasattr(hist, "Project3D"):
# TH3 defines ProjectionZ and Project3D, so we will use those as proxies.
projected_hist = self._project_TH3(hist = hist)
elif hasattr(hist, "ProjectionX") and hasattr(hist, "ProjectionY"):
# TH2 defines ProjectionX and ProjectionY, so we will use those as proxies.
projected_hist = self._project_TH2(hist = hist)
else:
raise TypeError(type(hist), f"Could not recognize hist {hist} of type {type(hist)}")
# Cleanup restricted axes
self.cleanup_cuts(hist, cut_axes = self.projection_axes)
return projected_hist | python | def call_projection_function(self, hist: Hist) -> Hist:
""" Calls the actual projection function for the hist.
Args:
hist: Histogram from which the projections should be performed.
Returns:
The projected histogram.
"""
# Restrict projection axis ranges
for axis in self.projection_axes:
logger.debug(f"Apply projection axes hist range: {axis.name}")
axis.apply_range_set(hist)
projected_hist = None
if hasattr(hist, "ProjectionND") and hasattr(hist, "Projection"):
# THnBase defines ProjectionND and Projection, so we will use those as proxies.
projected_hist = self._project_THn(hist = hist)
elif hasattr(hist, "ProjectionZ") and hasattr(hist, "Project3D"):
# TH3 defines ProjectionZ and Project3D, so we will use those as proxies.
projected_hist = self._project_TH3(hist = hist)
elif hasattr(hist, "ProjectionX") and hasattr(hist, "ProjectionY"):
# TH2 defines ProjectionX and ProjectionY, so we will use those as proxies.
projected_hist = self._project_TH2(hist = hist)
else:
raise TypeError(type(hist), f"Could not recognize hist {hist} of type {type(hist)}")
# Cleanup restricted axes
self.cleanup_cuts(hist, cut_axes = self.projection_axes)
return projected_hist | [
"def",
"call_projection_function",
"(",
"self",
",",
"hist",
":",
"Hist",
")",
"->",
"Hist",
":",
"# Restrict projection axis ranges",
"for",
"axis",
"in",
"self",
".",
"projection_axes",
":",
"logger",
".",
"debug",
"(",
"f\"Apply projection axes hist range: {axis.name}\"",
")",
"axis",
".",
"apply_range_set",
"(",
"hist",
")",
"projected_hist",
"=",
"None",
"if",
"hasattr",
"(",
"hist",
",",
"\"ProjectionND\"",
")",
"and",
"hasattr",
"(",
"hist",
",",
"\"Projection\"",
")",
":",
"# THnBase defines ProjectionND and Projection, so we will use those as proxies.",
"projected_hist",
"=",
"self",
".",
"_project_THn",
"(",
"hist",
"=",
"hist",
")",
"elif",
"hasattr",
"(",
"hist",
",",
"\"ProjectionZ\"",
")",
"and",
"hasattr",
"(",
"hist",
",",
"\"Project3D\"",
")",
":",
"# TH3 defines ProjectionZ and Project3D, so we will use those as proxies.",
"projected_hist",
"=",
"self",
".",
"_project_TH3",
"(",
"hist",
"=",
"hist",
")",
"elif",
"hasattr",
"(",
"hist",
",",
"\"ProjectionX\"",
")",
"and",
"hasattr",
"(",
"hist",
",",
"\"ProjectionY\"",
")",
":",
"# TH2 defines ProjectionX and ProjectionY, so we will use those as proxies.",
"projected_hist",
"=",
"self",
".",
"_project_TH2",
"(",
"hist",
"=",
"hist",
")",
"else",
":",
"raise",
"TypeError",
"(",
"type",
"(",
"hist",
")",
",",
"f\"Could not recognize hist {hist} of type {type(hist)}\"",
")",
"# Cleanup restricted axes",
"self",
".",
"cleanup_cuts",
"(",
"hist",
",",
"cut_axes",
"=",
"self",
".",
"projection_axes",
")",
"return",
"projected_hist"
]
| Calls the actual projection function for the hist.
Args:
hist: Histogram from which the projections should be performed.
Returns:
The projected histogram. | [
"Calls",
"the",
"actual",
"projection",
"function",
"for",
"the",
"hist",
"."
]
| aaa1d8374fd871246290ce76f1796f2f7582b01d | https://github.com/raymondEhlers/pachyderm/blob/aaa1d8374fd871246290ce76f1796f2f7582b01d/pachyderm/projectors.py#L314-L343 | train |
raymondEhlers/pachyderm | pachyderm/projectors.py | HistProjector._project_THn | def _project_THn(self, hist: Hist) -> Any:
""" Perform the actual THn -> THn or TH1 projection.
This projection could be to 1D, 2D, 3D, or ND.
Args:
hist (ROOT.THnBase): Histogram from which the projections should be performed.
Returns:
ROOT.THnBase or ROOT.TH1: The projected histogram.
"""
# THnBase projections args are given as a list of axes, followed by any possible options.
projection_axes = [axis.axis_type.value for axis in self.projection_axes]
# Handle ROOT THnBase quirk...
# 2D projection are called as (y, x, options), so we should reverse the order so it performs
# as expected
if len(projection_axes) == 2:
# Reverses in place
projection_axes.reverse()
# Test calculating errors
# Add "E" to ensure that errors will be calculated
args = projection_axes + ["E"]
# Do the actual projection
logger.debug(f"hist: {hist.GetName()} args: {args}")
if len(projection_axes) > 3:
# Project into a THnBase object.
projected_hist = hist.ProjectionND(*args)
else:
# Project a TH1 derived object.
projected_hist = hist.Projection(*args)
return projected_hist | python | def _project_THn(self, hist: Hist) -> Any:
""" Perform the actual THn -> THn or TH1 projection.
This projection could be to 1D, 2D, 3D, or ND.
Args:
hist (ROOT.THnBase): Histogram from which the projections should be performed.
Returns:
ROOT.THnBase or ROOT.TH1: The projected histogram.
"""
# THnBase projections args are given as a list of axes, followed by any possible options.
projection_axes = [axis.axis_type.value for axis in self.projection_axes]
# Handle ROOT THnBase quirk...
# 2D projection are called as (y, x, options), so we should reverse the order so it performs
# as expected
if len(projection_axes) == 2:
# Reverses in place
projection_axes.reverse()
# Test calculating errors
# Add "E" to ensure that errors will be calculated
args = projection_axes + ["E"]
# Do the actual projection
logger.debug(f"hist: {hist.GetName()} args: {args}")
if len(projection_axes) > 3:
# Project into a THnBase object.
projected_hist = hist.ProjectionND(*args)
else:
# Project a TH1 derived object.
projected_hist = hist.Projection(*args)
return projected_hist | [
"def",
"_project_THn",
"(",
"self",
",",
"hist",
":",
"Hist",
")",
"->",
"Any",
":",
"# THnBase projections args are given as a list of axes, followed by any possible options.",
"projection_axes",
"=",
"[",
"axis",
".",
"axis_type",
".",
"value",
"for",
"axis",
"in",
"self",
".",
"projection_axes",
"]",
"# Handle ROOT THnBase quirk...",
"# 2D projection are called as (y, x, options), so we should reverse the order so it performs",
"# as expected",
"if",
"len",
"(",
"projection_axes",
")",
"==",
"2",
":",
"# Reverses in place",
"projection_axes",
".",
"reverse",
"(",
")",
"# Test calculating errors",
"# Add \"E\" to ensure that errors will be calculated",
"args",
"=",
"projection_axes",
"+",
"[",
"\"E\"",
"]",
"# Do the actual projection",
"logger",
".",
"debug",
"(",
"f\"hist: {hist.GetName()} args: {args}\"",
")",
"if",
"len",
"(",
"projection_axes",
")",
">",
"3",
":",
"# Project into a THnBase object.",
"projected_hist",
"=",
"hist",
".",
"ProjectionND",
"(",
"*",
"args",
")",
"else",
":",
"# Project a TH1 derived object.",
"projected_hist",
"=",
"hist",
".",
"Projection",
"(",
"*",
"args",
")",
"return",
"projected_hist"
]
| Perform the actual THn -> THn or TH1 projection.
This projection could be to 1D, 2D, 3D, or ND.
Args:
hist (ROOT.THnBase): Histogram from which the projections should be performed.
Returns:
ROOT.THnBase or ROOT.TH1: The projected histogram. | [
"Perform",
"the",
"actual",
"THn",
"-",
">",
"THn",
"or",
"TH1",
"projection",
"."
]
| aaa1d8374fd871246290ce76f1796f2f7582b01d | https://github.com/raymondEhlers/pachyderm/blob/aaa1d8374fd871246290ce76f1796f2f7582b01d/pachyderm/projectors.py#L345-L378 | train |
raymondEhlers/pachyderm | pachyderm/projectors.py | HistProjector._project_TH3 | def _project_TH3(self, hist: Hist) -> Any:
""" Perform the actual TH3 -> TH1 projection.
This projection could be to 1D or 2D.
Args:
hist (ROOT.TH3): Histogram from which the projections should be performed.
Returns:
ROOT.TH1: The projected histogram.
"""
# Axis length validation
if len(self.projection_axes) < 1 or len(self.projection_axes) > 2:
raise ValueError(len(self.projection_axes), "Invalid number of axes")
# Need to concatenate the names of the axes together
projection_axis_name = ""
for axis in self.projection_axes:
# Determine the axis name based on the name of the axis type.
# [:1] returns just the first letter. For example, we could get "xy" if the first axis as
# x_axis and the second was y_axis.
# NOTE: Careful. This depends on the name of the enumerated values!!! Since this isn't terribly
# safe, we then perform additional validation on the same to ensure that it is one of the
# expected axis names.
proj_axis_name = axis.axis_type.name[:1]
if proj_axis_name not in ["x", "y", "z"]:
raise ValueError(f"Projection axis name {proj_axis_name} is not 'x', 'y', or 'z'. Please check your configuration.")
projection_axis_name += proj_axis_name
# Handle ROOT Project3D quirk...
# 2D projection are called as (y, x, options), so we should reverse the order so it performs
# as expected.
# NOTE: This isn't well documented in TH3. It is instead described in THnBase.Projection(...)
if len(self.projection_axes) == 2:
# Reverse the axes
projection_axis_name = projection_axis_name[::-1]
# Do the actual projection
logger.info(f"Projecting onto axes \"{projection_axis_name}\" from hist {hist.GetName()}")
projected_hist = hist.Project3D(projection_axis_name)
return projected_hist | python | def _project_TH3(self, hist: Hist) -> Any:
""" Perform the actual TH3 -> TH1 projection.
This projection could be to 1D or 2D.
Args:
hist (ROOT.TH3): Histogram from which the projections should be performed.
Returns:
ROOT.TH1: The projected histogram.
"""
# Axis length validation
if len(self.projection_axes) < 1 or len(self.projection_axes) > 2:
raise ValueError(len(self.projection_axes), "Invalid number of axes")
# Need to concatenate the names of the axes together
projection_axis_name = ""
for axis in self.projection_axes:
# Determine the axis name based on the name of the axis type.
# [:1] returns just the first letter. For example, we could get "xy" if the first axis as
# x_axis and the second was y_axis.
# NOTE: Careful. This depends on the name of the enumerated values!!! Since this isn't terribly
# safe, we then perform additional validation on the same to ensure that it is one of the
# expected axis names.
proj_axis_name = axis.axis_type.name[:1]
if proj_axis_name not in ["x", "y", "z"]:
raise ValueError(f"Projection axis name {proj_axis_name} is not 'x', 'y', or 'z'. Please check your configuration.")
projection_axis_name += proj_axis_name
# Handle ROOT Project3D quirk...
# 2D projection are called as (y, x, options), so we should reverse the order so it performs
# as expected.
# NOTE: This isn't well documented in TH3. It is instead described in THnBase.Projection(...)
if len(self.projection_axes) == 2:
# Reverse the axes
projection_axis_name = projection_axis_name[::-1]
# Do the actual projection
logger.info(f"Projecting onto axes \"{projection_axis_name}\" from hist {hist.GetName()}")
projected_hist = hist.Project3D(projection_axis_name)
return projected_hist | [
"def",
"_project_TH3",
"(",
"self",
",",
"hist",
":",
"Hist",
")",
"->",
"Any",
":",
"# Axis length validation",
"if",
"len",
"(",
"self",
".",
"projection_axes",
")",
"<",
"1",
"or",
"len",
"(",
"self",
".",
"projection_axes",
")",
">",
"2",
":",
"raise",
"ValueError",
"(",
"len",
"(",
"self",
".",
"projection_axes",
")",
",",
"\"Invalid number of axes\"",
")",
"# Need to concatenate the names of the axes together",
"projection_axis_name",
"=",
"\"\"",
"for",
"axis",
"in",
"self",
".",
"projection_axes",
":",
"# Determine the axis name based on the name of the axis type.",
"# [:1] returns just the first letter. For example, we could get \"xy\" if the first axis as",
"# x_axis and the second was y_axis.",
"# NOTE: Careful. This depends on the name of the enumerated values!!! Since this isn't terribly",
"# safe, we then perform additional validation on the same to ensure that it is one of the",
"# expected axis names.",
"proj_axis_name",
"=",
"axis",
".",
"axis_type",
".",
"name",
"[",
":",
"1",
"]",
"if",
"proj_axis_name",
"not",
"in",
"[",
"\"x\"",
",",
"\"y\"",
",",
"\"z\"",
"]",
":",
"raise",
"ValueError",
"(",
"f\"Projection axis name {proj_axis_name} is not 'x', 'y', or 'z'. Please check your configuration.\"",
")",
"projection_axis_name",
"+=",
"proj_axis_name",
"# Handle ROOT Project3D quirk...",
"# 2D projection are called as (y, x, options), so we should reverse the order so it performs",
"# as expected.",
"# NOTE: This isn't well documented in TH3. It is instead described in THnBase.Projection(...)",
"if",
"len",
"(",
"self",
".",
"projection_axes",
")",
"==",
"2",
":",
"# Reverse the axes",
"projection_axis_name",
"=",
"projection_axis_name",
"[",
":",
":",
"-",
"1",
"]",
"# Do the actual projection",
"logger",
".",
"info",
"(",
"f\"Projecting onto axes \\\"{projection_axis_name}\\\" from hist {hist.GetName()}\"",
")",
"projected_hist",
"=",
"hist",
".",
"Project3D",
"(",
"projection_axis_name",
")",
"return",
"projected_hist"
]
| Perform the actual TH3 -> TH1 projection.
This projection could be to 1D or 2D.
Args:
hist (ROOT.TH3): Histogram from which the projections should be performed.
Returns:
ROOT.TH1: The projected histogram. | [
"Perform",
"the",
"actual",
"TH3",
"-",
">",
"TH1",
"projection",
"."
]
| aaa1d8374fd871246290ce76f1796f2f7582b01d | https://github.com/raymondEhlers/pachyderm/blob/aaa1d8374fd871246290ce76f1796f2f7582b01d/pachyderm/projectors.py#L380-L420 | train |
raymondEhlers/pachyderm | pachyderm/projectors.py | HistProjector._project_TH2 | def _project_TH2(self, hist: Hist) -> Any:
""" Perform the actual TH2 -> TH1 projection.
This projection can only be to 1D.
Args:
hist (ROOT.TH2): Histogram from which the projections should be performed.
Returns:
ROOT.TH1: The projected histogram.
"""
if len(self.projection_axes) != 1:
raise ValueError(len(self.projection_axes), "Invalid number of axes")
#logger.debug(f"self.projection_axes[0].axis: {self.projection_axes[0].axis}, axis range name: {self.projection_axes[0].name}, axis_type: {self.projection_axes[0].axis_type}")
# NOTE: We cannot use TH3.ProjectionZ(...) because it has different semantics than ProjectionX
# and ProjectionY. In particular, it doesn't respect the axis limits of axis onto which it
# is projected. So we have to separate the projection by histogram type as opposed to axis
# length.
projection_func_map = {
TH1AxisType.x_axis.value: hist.ProjectionX,
TH1AxisType.y_axis.value: hist.ProjectionY
}
# Determine the axis_type value
# Use try here instead of checking for a particular type to protect against type changes (say
# in the enum)
try:
# Try to extract the value from an enum
axis_type = self.projection_axes[0].axis_type.value
except ValueError:
# Seems that we received an int, so just use that value
axis_type = self.axis_type # type: ignore
projection_func = projection_func_map[axis_type]
# Do the actual projection
logger.info(f"Projecting onto axis range {self.projection_axes[0].name} from hist {hist.GetName()}")
projected_hist = projection_func()
return projected_hist | python | def _project_TH2(self, hist: Hist) -> Any:
""" Perform the actual TH2 -> TH1 projection.
This projection can only be to 1D.
Args:
hist (ROOT.TH2): Histogram from which the projections should be performed.
Returns:
ROOT.TH1: The projected histogram.
"""
if len(self.projection_axes) != 1:
raise ValueError(len(self.projection_axes), "Invalid number of axes")
#logger.debug(f"self.projection_axes[0].axis: {self.projection_axes[0].axis}, axis range name: {self.projection_axes[0].name}, axis_type: {self.projection_axes[0].axis_type}")
# NOTE: We cannot use TH3.ProjectionZ(...) because it has different semantics than ProjectionX
# and ProjectionY. In particular, it doesn't respect the axis limits of axis onto which it
# is projected. So we have to separate the projection by histogram type as opposed to axis
# length.
projection_func_map = {
TH1AxisType.x_axis.value: hist.ProjectionX,
TH1AxisType.y_axis.value: hist.ProjectionY
}
# Determine the axis_type value
# Use try here instead of checking for a particular type to protect against type changes (say
# in the enum)
try:
# Try to extract the value from an enum
axis_type = self.projection_axes[0].axis_type.value
except ValueError:
# Seems that we received an int, so just use that value
axis_type = self.axis_type # type: ignore
projection_func = projection_func_map[axis_type]
# Do the actual projection
logger.info(f"Projecting onto axis range {self.projection_axes[0].name} from hist {hist.GetName()}")
projected_hist = projection_func()
return projected_hist | [
"def",
"_project_TH2",
"(",
"self",
",",
"hist",
":",
"Hist",
")",
"->",
"Any",
":",
"if",
"len",
"(",
"self",
".",
"projection_axes",
")",
"!=",
"1",
":",
"raise",
"ValueError",
"(",
"len",
"(",
"self",
".",
"projection_axes",
")",
",",
"\"Invalid number of axes\"",
")",
"#logger.debug(f\"self.projection_axes[0].axis: {self.projection_axes[0].axis}, axis range name: {self.projection_axes[0].name}, axis_type: {self.projection_axes[0].axis_type}\")",
"# NOTE: We cannot use TH3.ProjectionZ(...) because it has different semantics than ProjectionX",
"# and ProjectionY. In particular, it doesn't respect the axis limits of axis onto which it",
"# is projected. So we have to separate the projection by histogram type as opposed to axis",
"# length.",
"projection_func_map",
"=",
"{",
"TH1AxisType",
".",
"x_axis",
".",
"value",
":",
"hist",
".",
"ProjectionX",
",",
"TH1AxisType",
".",
"y_axis",
".",
"value",
":",
"hist",
".",
"ProjectionY",
"}",
"# Determine the axis_type value",
"# Use try here instead of checking for a particular type to protect against type changes (say",
"# in the enum)",
"try",
":",
"# Try to extract the value from an enum",
"axis_type",
"=",
"self",
".",
"projection_axes",
"[",
"0",
"]",
".",
"axis_type",
".",
"value",
"except",
"ValueError",
":",
"# Seems that we received an int, so just use that value",
"axis_type",
"=",
"self",
".",
"axis_type",
"# type: ignore",
"projection_func",
"=",
"projection_func_map",
"[",
"axis_type",
"]",
"# Do the actual projection",
"logger",
".",
"info",
"(",
"f\"Projecting onto axis range {self.projection_axes[0].name} from hist {hist.GetName()}\"",
")",
"projected_hist",
"=",
"projection_func",
"(",
")",
"return",
"projected_hist"
]
| Perform the actual TH2 -> TH1 projection.
This projection can only be to 1D.
Args:
hist (ROOT.TH2): Histogram from which the projections should be performed.
Returns:
ROOT.TH1: The projected histogram. | [
"Perform",
"the",
"actual",
"TH2",
"-",
">",
"TH1",
"projection",
"."
]
| aaa1d8374fd871246290ce76f1796f2f7582b01d | https://github.com/raymondEhlers/pachyderm/blob/aaa1d8374fd871246290ce76f1796f2f7582b01d/pachyderm/projectors.py#L422-L461 | train |
raymondEhlers/pachyderm | pachyderm/projectors.py | HistProjector._project_observable | def _project_observable(self, input_key: str,
input_observable: Any,
get_hist_args: Dict[str, Any] = None,
projection_name_args: Dict[str, Any] = None,
**kwargs) -> Hist:
""" Perform a projection for a single observable.
Note:
All cuts on the original histograms will be reset when this function is completed.
Args:
input_key: Key to describe the input observable.
input_observable: Observable to project from.
get_hist_args: Arguments to pass to ``get_hist(...)``. Made available so the args can be cached
to avoid a ``deepcopy`` when looping. Default: None. In this case, they will be retrieved
automatically.
projection_name_args: Arguments to pass to ``projection_name(...)``. Made available so the args
can be cached to avoid a ``deepcopy`` when looping. Default: None. In this case, they will be
retrieved automatically.
kwargs: Additional named args to be passed to projection_name(...) and output_key_name(...).
Returns:
The projected histogram.
"""
# Validation of other optional arguments.
if get_hist_args is None:
get_hist_args = copy.deepcopy(kwargs)
if projection_name_args is None:
projection_name_args = copy.deepcopy(kwargs)
# Retrieve histogram
# We update ``input_observable`` in ``get_hist_args`` every loop, so we don't have to worry
# about passing the wrong observable.
get_hist_args.update({"observable": input_observable})
hist = self.get_hist(**get_hist_args)
# Define projection name
projection_name_args.update(self.projection_information)
# In principle, we could have overwritten one of the kwargs, so we ensure with one of the other
# updates, so we update it again to be certain.
projection_name_args.update(kwargs)
# Put the values included by default last to ensure nothing overwrites these values
projection_name_args.update({ # type: ignore
"input_key": input_key,
"input_observable": input_observable,
"input_hist": hist
})
projection_name = self.projection_name(**projection_name_args)
# First apply the cuts
# Restricting the range with SetRange(User) works properly for both THn and TH1.
logger.debug(f"hist: {hist}")
for axis in self.additional_axis_cuts:
logger.debug(f"Apply additional axis hist range: {axis.name}")
axis.apply_range_set(hist)
# We need to ensure that it isn't empty so at least one project occurs
if self.projection_dependent_cut_axes == []:
self.projection_dependent_cut_axes.append([])
# Validate the projection dependent cut axes
# It is invalid to have PDCA on the same axes as the projection axes.
duplicated_axes = [
PDCA
for PA in self.projection_axes
for PDCA_group in self.projection_dependent_cut_axes
for PDCA in PDCA_group
if PDCA.axis_type == PA.axis_type
]
if duplicated_axes:
raise ValueError(
f"Axis {duplicated_axes} is in the projection axes and the projection dependent cut axes."
" This configuration is not allowed, as the range in the PDCA will be overwritten by the projection axes!"
" Please revise your configuration."
)
# Perform the projections
hists = []
for i, axes in enumerate(self.projection_dependent_cut_axes):
# Projection dependent range set
for axis in axes:
logger.debug(f"Apply projection dependent hist range: {axis.name}")
axis.apply_range_set(hist)
# Do the projection
projected_hist = self.call_projection_function(hist)
projected_hist.SetName(f"{projection_name}_{i}")
hists.append(projected_hist)
# Cleanup projection dependent cuts (although they should be set again on the next
# iteration of the loop)
self.cleanup_cuts(hist, cut_axes = axes)
# Cleanup the rest of the cuts
self.cleanup_cuts(hist, cut_axes = self.additional_axis_cuts)
# Combine all of the projections together
output_hist = hists[0]
for temp_hist in hists[1:]:
output_hist.Add(temp_hist)
# Final settings
output_hist.SetName(projection_name)
# Ensure that the hist doesn't get deleted by ROOT
# A reference to the histogram within python may not be enough
output_hist.SetDirectory(0)
return output_hist, projection_name, projection_name_args | python | def _project_observable(self, input_key: str,
input_observable: Any,
get_hist_args: Dict[str, Any] = None,
projection_name_args: Dict[str, Any] = None,
**kwargs) -> Hist:
""" Perform a projection for a single observable.
Note:
All cuts on the original histograms will be reset when this function is completed.
Args:
input_key: Key to describe the input observable.
input_observable: Observable to project from.
get_hist_args: Arguments to pass to ``get_hist(...)``. Made available so the args can be cached
to avoid a ``deepcopy`` when looping. Default: None. In this case, they will be retrieved
automatically.
projection_name_args: Arguments to pass to ``projection_name(...)``. Made available so the args
can be cached to avoid a ``deepcopy`` when looping. Default: None. In this case, they will be
retrieved automatically.
kwargs: Additional named args to be passed to projection_name(...) and output_key_name(...).
Returns:
The projected histogram.
"""
# Validation of other optional arguments.
if get_hist_args is None:
get_hist_args = copy.deepcopy(kwargs)
if projection_name_args is None:
projection_name_args = copy.deepcopy(kwargs)
# Retrieve histogram
# We update ``input_observable`` in ``get_hist_args`` every loop, so we don't have to worry
# about passing the wrong observable.
get_hist_args.update({"observable": input_observable})
hist = self.get_hist(**get_hist_args)
# Define projection name
projection_name_args.update(self.projection_information)
# In principle, we could have overwritten one of the kwargs, so we ensure with one of the other
# updates, so we update it again to be certain.
projection_name_args.update(kwargs)
# Put the values included by default last to ensure nothing overwrites these values
projection_name_args.update({ # type: ignore
"input_key": input_key,
"input_observable": input_observable,
"input_hist": hist
})
projection_name = self.projection_name(**projection_name_args)
# First apply the cuts
# Restricting the range with SetRange(User) works properly for both THn and TH1.
logger.debug(f"hist: {hist}")
for axis in self.additional_axis_cuts:
logger.debug(f"Apply additional axis hist range: {axis.name}")
axis.apply_range_set(hist)
# We need to ensure that it isn't empty so at least one project occurs
if self.projection_dependent_cut_axes == []:
self.projection_dependent_cut_axes.append([])
# Validate the projection dependent cut axes
# It is invalid to have PDCA on the same axes as the projection axes.
duplicated_axes = [
PDCA
for PA in self.projection_axes
for PDCA_group in self.projection_dependent_cut_axes
for PDCA in PDCA_group
if PDCA.axis_type == PA.axis_type
]
if duplicated_axes:
raise ValueError(
f"Axis {duplicated_axes} is in the projection axes and the projection dependent cut axes."
" This configuration is not allowed, as the range in the PDCA will be overwritten by the projection axes!"
" Please revise your configuration."
)
# Perform the projections
hists = []
for i, axes in enumerate(self.projection_dependent_cut_axes):
# Projection dependent range set
for axis in axes:
logger.debug(f"Apply projection dependent hist range: {axis.name}")
axis.apply_range_set(hist)
# Do the projection
projected_hist = self.call_projection_function(hist)
projected_hist.SetName(f"{projection_name}_{i}")
hists.append(projected_hist)
# Cleanup projection dependent cuts (although they should be set again on the next
# iteration of the loop)
self.cleanup_cuts(hist, cut_axes = axes)
# Cleanup the rest of the cuts
self.cleanup_cuts(hist, cut_axes = self.additional_axis_cuts)
# Combine all of the projections together
output_hist = hists[0]
for temp_hist in hists[1:]:
output_hist.Add(temp_hist)
# Final settings
output_hist.SetName(projection_name)
# Ensure that the hist doesn't get deleted by ROOT
# A reference to the histogram within python may not be enough
output_hist.SetDirectory(0)
return output_hist, projection_name, projection_name_args | [
"def",
"_project_observable",
"(",
"self",
",",
"input_key",
":",
"str",
",",
"input_observable",
":",
"Any",
",",
"get_hist_args",
":",
"Dict",
"[",
"str",
",",
"Any",
"]",
"=",
"None",
",",
"projection_name_args",
":",
"Dict",
"[",
"str",
",",
"Any",
"]",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
"->",
"Hist",
":",
"# Validation of other optional arguments.",
"if",
"get_hist_args",
"is",
"None",
":",
"get_hist_args",
"=",
"copy",
".",
"deepcopy",
"(",
"kwargs",
")",
"if",
"projection_name_args",
"is",
"None",
":",
"projection_name_args",
"=",
"copy",
".",
"deepcopy",
"(",
"kwargs",
")",
"# Retrieve histogram",
"# We update ``input_observable`` in ``get_hist_args`` every loop, so we don't have to worry",
"# about passing the wrong observable.",
"get_hist_args",
".",
"update",
"(",
"{",
"\"observable\"",
":",
"input_observable",
"}",
")",
"hist",
"=",
"self",
".",
"get_hist",
"(",
"*",
"*",
"get_hist_args",
")",
"# Define projection name",
"projection_name_args",
".",
"update",
"(",
"self",
".",
"projection_information",
")",
"# In principle, we could have overwritten one of the kwargs, so we ensure with one of the other",
"# updates, so we update it again to be certain.",
"projection_name_args",
".",
"update",
"(",
"kwargs",
")",
"# Put the values included by default last to ensure nothing overwrites these values",
"projection_name_args",
".",
"update",
"(",
"{",
"# type: ignore",
"\"input_key\"",
":",
"input_key",
",",
"\"input_observable\"",
":",
"input_observable",
",",
"\"input_hist\"",
":",
"hist",
"}",
")",
"projection_name",
"=",
"self",
".",
"projection_name",
"(",
"*",
"*",
"projection_name_args",
")",
"# First apply the cuts",
"# Restricting the range with SetRange(User) works properly for both THn and TH1.",
"logger",
".",
"debug",
"(",
"f\"hist: {hist}\"",
")",
"for",
"axis",
"in",
"self",
".",
"additional_axis_cuts",
":",
"logger",
".",
"debug",
"(",
"f\"Apply additional axis hist range: {axis.name}\"",
")",
"axis",
".",
"apply_range_set",
"(",
"hist",
")",
"# We need to ensure that it isn't empty so at least one project occurs",
"if",
"self",
".",
"projection_dependent_cut_axes",
"==",
"[",
"]",
":",
"self",
".",
"projection_dependent_cut_axes",
".",
"append",
"(",
"[",
"]",
")",
"# Validate the projection dependent cut axes",
"# It is invalid to have PDCA on the same axes as the projection axes.",
"duplicated_axes",
"=",
"[",
"PDCA",
"for",
"PA",
"in",
"self",
".",
"projection_axes",
"for",
"PDCA_group",
"in",
"self",
".",
"projection_dependent_cut_axes",
"for",
"PDCA",
"in",
"PDCA_group",
"if",
"PDCA",
".",
"axis_type",
"==",
"PA",
".",
"axis_type",
"]",
"if",
"duplicated_axes",
":",
"raise",
"ValueError",
"(",
"f\"Axis {duplicated_axes} is in the projection axes and the projection dependent cut axes.\"",
"\" This configuration is not allowed, as the range in the PDCA will be overwritten by the projection axes!\"",
"\" Please revise your configuration.\"",
")",
"# Perform the projections",
"hists",
"=",
"[",
"]",
"for",
"i",
",",
"axes",
"in",
"enumerate",
"(",
"self",
".",
"projection_dependent_cut_axes",
")",
":",
"# Projection dependent range set",
"for",
"axis",
"in",
"axes",
":",
"logger",
".",
"debug",
"(",
"f\"Apply projection dependent hist range: {axis.name}\"",
")",
"axis",
".",
"apply_range_set",
"(",
"hist",
")",
"# Do the projection",
"projected_hist",
"=",
"self",
".",
"call_projection_function",
"(",
"hist",
")",
"projected_hist",
".",
"SetName",
"(",
"f\"{projection_name}_{i}\"",
")",
"hists",
".",
"append",
"(",
"projected_hist",
")",
"# Cleanup projection dependent cuts (although they should be set again on the next",
"# iteration of the loop)",
"self",
".",
"cleanup_cuts",
"(",
"hist",
",",
"cut_axes",
"=",
"axes",
")",
"# Cleanup the rest of the cuts",
"self",
".",
"cleanup_cuts",
"(",
"hist",
",",
"cut_axes",
"=",
"self",
".",
"additional_axis_cuts",
")",
"# Combine all of the projections together",
"output_hist",
"=",
"hists",
"[",
"0",
"]",
"for",
"temp_hist",
"in",
"hists",
"[",
"1",
":",
"]",
":",
"output_hist",
".",
"Add",
"(",
"temp_hist",
")",
"# Final settings",
"output_hist",
".",
"SetName",
"(",
"projection_name",
")",
"# Ensure that the hist doesn't get deleted by ROOT",
"# A reference to the histogram within python may not be enough",
"output_hist",
".",
"SetDirectory",
"(",
"0",
")",
"return",
"output_hist",
",",
"projection_name",
",",
"projection_name_args"
]
| Perform a projection for a single observable.
Note:
All cuts on the original histograms will be reset when this function is completed.
Args:
input_key: Key to describe the input observable.
input_observable: Observable to project from.
get_hist_args: Arguments to pass to ``get_hist(...)``. Made available so the args can be cached
to avoid a ``deepcopy`` when looping. Default: None. In this case, they will be retrieved
automatically.
projection_name_args: Arguments to pass to ``projection_name(...)``. Made available so the args
can be cached to avoid a ``deepcopy`` when looping. Default: None. In this case, they will be
retrieved automatically.
kwargs: Additional named args to be passed to projection_name(...) and output_key_name(...).
Returns:
The projected histogram. | [
"Perform",
"a",
"projection",
"for",
"a",
"single",
"observable",
"."
]
| aaa1d8374fd871246290ce76f1796f2f7582b01d | https://github.com/raymondEhlers/pachyderm/blob/aaa1d8374fd871246290ce76f1796f2f7582b01d/pachyderm/projectors.py#L463-L570 | train |
raymondEhlers/pachyderm | pachyderm/projectors.py | HistProjector._project_single_observable | def _project_single_observable(self, **kwargs: Dict[str, Any]) -> Hist:
""" Driver function for projecting and storing a single observable.
Args:
kwargs (dict): Additional named args to be passed to projection_name(...) and output_key_name(...)
Returns:
The projected histogram. The histogram is also stored in the output specified by ``output_observable``.
"""
# Help out mypy
assert isinstance(self.output_attribute_name, str)
# Run the actual projection.
output_hist, projection_name, projection_name_args, = self._project_observable(
input_key = "single_observable",
input_observable = self.observable_to_project_from,
**kwargs,
)
# Store the output.
output_hist_args = projection_name_args
output_hist_args.update({ # type: ignore
"output_hist": output_hist,
"projection_name": projection_name
})
# Store the final histogram.
output_hist = self.output_hist(**output_hist_args) # type: ignore
# Store the final output hist
if not hasattr(self.output_observable, self.output_attribute_name):
raise ValueError(f"Attempted to assign hist to non-existent attribute {self.output_attribute_name} of object {self.output_observable}. Check the attribute name!")
# Actually store the histogram.
setattr(self.output_observable, self.output_attribute_name, output_hist)
# Return the observable
return output_hist | python | def _project_single_observable(self, **kwargs: Dict[str, Any]) -> Hist:
""" Driver function for projecting and storing a single observable.
Args:
kwargs (dict): Additional named args to be passed to projection_name(...) and output_key_name(...)
Returns:
The projected histogram. The histogram is also stored in the output specified by ``output_observable``.
"""
# Help out mypy
assert isinstance(self.output_attribute_name, str)
# Run the actual projection.
output_hist, projection_name, projection_name_args, = self._project_observable(
input_key = "single_observable",
input_observable = self.observable_to_project_from,
**kwargs,
)
# Store the output.
output_hist_args = projection_name_args
output_hist_args.update({ # type: ignore
"output_hist": output_hist,
"projection_name": projection_name
})
# Store the final histogram.
output_hist = self.output_hist(**output_hist_args) # type: ignore
# Store the final output hist
if not hasattr(self.output_observable, self.output_attribute_name):
raise ValueError(f"Attempted to assign hist to non-existent attribute {self.output_attribute_name} of object {self.output_observable}. Check the attribute name!")
# Actually store the histogram.
setattr(self.output_observable, self.output_attribute_name, output_hist)
# Return the observable
return output_hist | [
"def",
"_project_single_observable",
"(",
"self",
",",
"*",
"*",
"kwargs",
":",
"Dict",
"[",
"str",
",",
"Any",
"]",
")",
"->",
"Hist",
":",
"# Help out mypy",
"assert",
"isinstance",
"(",
"self",
".",
"output_attribute_name",
",",
"str",
")",
"# Run the actual projection.",
"output_hist",
",",
"projection_name",
",",
"projection_name_args",
",",
"=",
"self",
".",
"_project_observable",
"(",
"input_key",
"=",
"\"single_observable\"",
",",
"input_observable",
"=",
"self",
".",
"observable_to_project_from",
",",
"*",
"*",
"kwargs",
",",
")",
"# Store the output.",
"output_hist_args",
"=",
"projection_name_args",
"output_hist_args",
".",
"update",
"(",
"{",
"# type: ignore",
"\"output_hist\"",
":",
"output_hist",
",",
"\"projection_name\"",
":",
"projection_name",
"}",
")",
"# Store the final histogram.",
"output_hist",
"=",
"self",
".",
"output_hist",
"(",
"*",
"*",
"output_hist_args",
")",
"# type: ignore",
"# Store the final output hist",
"if",
"not",
"hasattr",
"(",
"self",
".",
"output_observable",
",",
"self",
".",
"output_attribute_name",
")",
":",
"raise",
"ValueError",
"(",
"f\"Attempted to assign hist to non-existent attribute {self.output_attribute_name} of object {self.output_observable}. Check the attribute name!\"",
")",
"# Actually store the histogram.",
"setattr",
"(",
"self",
".",
"output_observable",
",",
"self",
".",
"output_attribute_name",
",",
"output_hist",
")",
"# Return the observable",
"return",
"output_hist"
]
| Driver function for projecting and storing a single observable.
Args:
kwargs (dict): Additional named args to be passed to projection_name(...) and output_key_name(...)
Returns:
The projected histogram. The histogram is also stored in the output specified by ``output_observable``. | [
"Driver",
"function",
"for",
"projecting",
"and",
"storing",
"a",
"single",
"observable",
"."
]
| aaa1d8374fd871246290ce76f1796f2f7582b01d | https://github.com/raymondEhlers/pachyderm/blob/aaa1d8374fd871246290ce76f1796f2f7582b01d/pachyderm/projectors.py#L572-L606 | train |
raymondEhlers/pachyderm | pachyderm/projectors.py | HistProjector._project_dict | def _project_dict(self, **kwargs: Dict[str, Any]) -> Dict[str, Hist]:
""" Driver function for projecting and storing a dictionary of observables.
Args:
kwargs (dict): Additional named args to be passed to projection_name(...) and output_key_name(...)
Returns:
The projected histograms. The projected histograms are also stored in ``output_observable``.
"""
# Setup function arguments with values which don't change per loop.
get_hist_args = copy.deepcopy(kwargs)
projection_name_args = copy.deepcopy(kwargs)
for key, input_observable in self.observable_to_project_from.items():
output_hist, projection_name, projection_name_args, = self._project_observable(
input_key = key,
input_observable = input_observable,
get_hist_args = get_hist_args,
projection_name_args = projection_name_args,
**kwargs,
)
# Store the output observable
output_hist_args = projection_name_args
output_hist_args.update({ # type: ignore
"output_hist": output_hist,
"projection_name": projection_name
})
output_key_name = self.output_key_name(**output_hist_args) # type: ignore
self.output_observable[output_key_name] = self.output_hist(**output_hist_args) # type: ignore
return self.output_observable | python | def _project_dict(self, **kwargs: Dict[str, Any]) -> Dict[str, Hist]:
""" Driver function for projecting and storing a dictionary of observables.
Args:
kwargs (dict): Additional named args to be passed to projection_name(...) and output_key_name(...)
Returns:
The projected histograms. The projected histograms are also stored in ``output_observable``.
"""
# Setup function arguments with values which don't change per loop.
get_hist_args = copy.deepcopy(kwargs)
projection_name_args = copy.deepcopy(kwargs)
for key, input_observable in self.observable_to_project_from.items():
output_hist, projection_name, projection_name_args, = self._project_observable(
input_key = key,
input_observable = input_observable,
get_hist_args = get_hist_args,
projection_name_args = projection_name_args,
**kwargs,
)
# Store the output observable
output_hist_args = projection_name_args
output_hist_args.update({ # type: ignore
"output_hist": output_hist,
"projection_name": projection_name
})
output_key_name = self.output_key_name(**output_hist_args) # type: ignore
self.output_observable[output_key_name] = self.output_hist(**output_hist_args) # type: ignore
return self.output_observable | [
"def",
"_project_dict",
"(",
"self",
",",
"*",
"*",
"kwargs",
":",
"Dict",
"[",
"str",
",",
"Any",
"]",
")",
"->",
"Dict",
"[",
"str",
",",
"Hist",
"]",
":",
"# Setup function arguments with values which don't change per loop.",
"get_hist_args",
"=",
"copy",
".",
"deepcopy",
"(",
"kwargs",
")",
"projection_name_args",
"=",
"copy",
".",
"deepcopy",
"(",
"kwargs",
")",
"for",
"key",
",",
"input_observable",
"in",
"self",
".",
"observable_to_project_from",
".",
"items",
"(",
")",
":",
"output_hist",
",",
"projection_name",
",",
"projection_name_args",
",",
"=",
"self",
".",
"_project_observable",
"(",
"input_key",
"=",
"key",
",",
"input_observable",
"=",
"input_observable",
",",
"get_hist_args",
"=",
"get_hist_args",
",",
"projection_name_args",
"=",
"projection_name_args",
",",
"*",
"*",
"kwargs",
",",
")",
"# Store the output observable",
"output_hist_args",
"=",
"projection_name_args",
"output_hist_args",
".",
"update",
"(",
"{",
"# type: ignore",
"\"output_hist\"",
":",
"output_hist",
",",
"\"projection_name\"",
":",
"projection_name",
"}",
")",
"output_key_name",
"=",
"self",
".",
"output_key_name",
"(",
"*",
"*",
"output_hist_args",
")",
"# type: ignore",
"self",
".",
"output_observable",
"[",
"output_key_name",
"]",
"=",
"self",
".",
"output_hist",
"(",
"*",
"*",
"output_hist_args",
")",
"# type: ignore",
"return",
"self",
".",
"output_observable"
]
| Driver function for projecting and storing a dictionary of observables.
Args:
kwargs (dict): Additional named args to be passed to projection_name(...) and output_key_name(...)
Returns:
The projected histograms. The projected histograms are also stored in ``output_observable``. | [
"Driver",
"function",
"for",
"projecting",
"and",
"storing",
"a",
"dictionary",
"of",
"observables",
"."
]
| aaa1d8374fd871246290ce76f1796f2f7582b01d | https://github.com/raymondEhlers/pachyderm/blob/aaa1d8374fd871246290ce76f1796f2f7582b01d/pachyderm/projectors.py#L608-L637 | train |
raymondEhlers/pachyderm | pachyderm/projectors.py | HistProjector.cleanup_cuts | def cleanup_cuts(self, hist: Hist, cut_axes: Iterable[HistAxisRange]) -> None:
""" Cleanup applied cuts by resetting the axis to the full range.
Inspired by: https://github.com/matplo/rootutils/blob/master/python/2.7/THnSparseWrapper.py
Args:
hist: Histogram for which the axes should be reset.
cut_axes: List of axis cuts, which correspond to axes that should be reset.
"""
for axis in cut_axes:
# According to the function TAxis::SetRange(first, last), the widest possible range is
# (1, Nbins). Anything beyond that will be reset to (1, Nbins)
axis.axis(hist).SetRange(1, axis.axis(hist).GetNbins()) | python | def cleanup_cuts(self, hist: Hist, cut_axes: Iterable[HistAxisRange]) -> None:
""" Cleanup applied cuts by resetting the axis to the full range.
Inspired by: https://github.com/matplo/rootutils/blob/master/python/2.7/THnSparseWrapper.py
Args:
hist: Histogram for which the axes should be reset.
cut_axes: List of axis cuts, which correspond to axes that should be reset.
"""
for axis in cut_axes:
# According to the function TAxis::SetRange(first, last), the widest possible range is
# (1, Nbins). Anything beyond that will be reset to (1, Nbins)
axis.axis(hist).SetRange(1, axis.axis(hist).GetNbins()) | [
"def",
"cleanup_cuts",
"(",
"self",
",",
"hist",
":",
"Hist",
",",
"cut_axes",
":",
"Iterable",
"[",
"HistAxisRange",
"]",
")",
"->",
"None",
":",
"for",
"axis",
"in",
"cut_axes",
":",
"# According to the function TAxis::SetRange(first, last), the widest possible range is",
"# (1, Nbins). Anything beyond that will be reset to (1, Nbins)",
"axis",
".",
"axis",
"(",
"hist",
")",
".",
"SetRange",
"(",
"1",
",",
"axis",
".",
"axis",
"(",
"hist",
")",
".",
"GetNbins",
"(",
")",
")"
]
| Cleanup applied cuts by resetting the axis to the full range.
Inspired by: https://github.com/matplo/rootutils/blob/master/python/2.7/THnSparseWrapper.py
Args:
hist: Histogram for which the axes should be reset.
cut_axes: List of axis cuts, which correspond to axes that should be reset. | [
"Cleanup",
"applied",
"cuts",
"by",
"resetting",
"the",
"axis",
"to",
"the",
"full",
"range",
"."
]
| aaa1d8374fd871246290ce76f1796f2f7582b01d | https://github.com/raymondEhlers/pachyderm/blob/aaa1d8374fd871246290ce76f1796f2f7582b01d/pachyderm/projectors.py#L655-L667 | train |
raymondEhlers/pachyderm | pachyderm/projectors.py | HistProjector.projection_name | def projection_name(self, **kwargs: Dict[str, Any]) -> str:
""" Define the projection name for this projector.
Note:
This function is just a basic placeholder and likely should be overridden.
Args:
kwargs: Projection information dict combined with additional arguments passed to the
projection function.
Returns:
Projection name string formatted with the passed options. By default, it returns
``projection_name_format`` formatted with the arguments to this function.
"""
return self.projection_name_format.format(**kwargs) | python | def projection_name(self, **kwargs: Dict[str, Any]) -> str:
""" Define the projection name for this projector.
Note:
This function is just a basic placeholder and likely should be overridden.
Args:
kwargs: Projection information dict combined with additional arguments passed to the
projection function.
Returns:
Projection name string formatted with the passed options. By default, it returns
``projection_name_format`` formatted with the arguments to this function.
"""
return self.projection_name_format.format(**kwargs) | [
"def",
"projection_name",
"(",
"self",
",",
"*",
"*",
"kwargs",
":",
"Dict",
"[",
"str",
",",
"Any",
"]",
")",
"->",
"str",
":",
"return",
"self",
".",
"projection_name_format",
".",
"format",
"(",
"*",
"*",
"kwargs",
")"
]
| Define the projection name for this projector.
Note:
This function is just a basic placeholder and likely should be overridden.
Args:
kwargs: Projection information dict combined with additional arguments passed to the
projection function.
Returns:
Projection name string formatted with the passed options. By default, it returns
``projection_name_format`` formatted with the arguments to this function. | [
"Define",
"the",
"projection",
"name",
"for",
"this",
"projector",
"."
]
| aaa1d8374fd871246290ce76f1796f2f7582b01d | https://github.com/raymondEhlers/pachyderm/blob/aaa1d8374fd871246290ce76f1796f2f7582b01d/pachyderm/projectors.py#L672-L685 | train |
raymondEhlers/pachyderm | pachyderm/projectors.py | HistProjector.get_hist | def get_hist(self, observable: Any, **kwargs: Dict[str, Any]) -> Any:
""" Get the histogram that may be stored in some object.
This histogram is used to project from.
Note:
The output object could just be the raw ROOT histogram.
Note:
This function is just a basic placeholder and likely should be overridden.
Args:
observable (object): The input object. It could be a histogram or something more complex
kwargs: Additional arguments passed to the projection function
Return:
ROOT.TH1 or ROOT.THnBase histogram which should be projected. By default, it returns the
observable (input object).
"""
return observable | python | def get_hist(self, observable: Any, **kwargs: Dict[str, Any]) -> Any:
""" Get the histogram that may be stored in some object.
This histogram is used to project from.
Note:
The output object could just be the raw ROOT histogram.
Note:
This function is just a basic placeholder and likely should be overridden.
Args:
observable (object): The input object. It could be a histogram or something more complex
kwargs: Additional arguments passed to the projection function
Return:
ROOT.TH1 or ROOT.THnBase histogram which should be projected. By default, it returns the
observable (input object).
"""
return observable | [
"def",
"get_hist",
"(",
"self",
",",
"observable",
":",
"Any",
",",
"*",
"*",
"kwargs",
":",
"Dict",
"[",
"str",
",",
"Any",
"]",
")",
"->",
"Any",
":",
"return",
"observable"
]
| Get the histogram that may be stored in some object.
This histogram is used to project from.
Note:
The output object could just be the raw ROOT histogram.
Note:
This function is just a basic placeholder and likely should be overridden.
Args:
observable (object): The input object. It could be a histogram or something more complex
kwargs: Additional arguments passed to the projection function
Return:
ROOT.TH1 or ROOT.THnBase histogram which should be projected. By default, it returns the
observable (input object). | [
"Get",
"the",
"histogram",
"that",
"may",
"be",
"stored",
"in",
"some",
"object",
"."
]
| aaa1d8374fd871246290ce76f1796f2f7582b01d | https://github.com/raymondEhlers/pachyderm/blob/aaa1d8374fd871246290ce76f1796f2f7582b01d/pachyderm/projectors.py#L687-L705 | train |
raymondEhlers/pachyderm | pachyderm/projectors.py | HistProjector.output_key_name | def output_key_name(self, input_key: str, output_hist: Hist, projection_name: str, **kwargs) -> str:
""" Returns the key under which the output object should be stored.
Note:
This function is just a basic placeholder which returns the projection name
and likely should be overridden.
Args:
input_key: Key of the input hist in the input dict
output_hist: The output histogram
projection_name: Projection name for the output histogram
kwargs: Projection information dict combined with additional arguments passed to
the projection function.
Returns:
Key under which the output object should be stored. By default, it returns the
projection name.
"""
return projection_name | python | def output_key_name(self, input_key: str, output_hist: Hist, projection_name: str, **kwargs) -> str:
""" Returns the key under which the output object should be stored.
Note:
This function is just a basic placeholder which returns the projection name
and likely should be overridden.
Args:
input_key: Key of the input hist in the input dict
output_hist: The output histogram
projection_name: Projection name for the output histogram
kwargs: Projection information dict combined with additional arguments passed to
the projection function.
Returns:
Key under which the output object should be stored. By default, it returns the
projection name.
"""
return projection_name | [
"def",
"output_key_name",
"(",
"self",
",",
"input_key",
":",
"str",
",",
"output_hist",
":",
"Hist",
",",
"projection_name",
":",
"str",
",",
"*",
"*",
"kwargs",
")",
"->",
"str",
":",
"return",
"projection_name"
]
| Returns the key under which the output object should be stored.
Note:
This function is just a basic placeholder which returns the projection name
and likely should be overridden.
Args:
input_key: Key of the input hist in the input dict
output_hist: The output histogram
projection_name: Projection name for the output histogram
kwargs: Projection information dict combined with additional arguments passed to
the projection function.
Returns:
Key under which the output object should be stored. By default, it returns the
projection name. | [
"Returns",
"the",
"key",
"under",
"which",
"the",
"output",
"object",
"should",
"be",
"stored",
"."
]
| aaa1d8374fd871246290ce76f1796f2f7582b01d | https://github.com/raymondEhlers/pachyderm/blob/aaa1d8374fd871246290ce76f1796f2f7582b01d/pachyderm/projectors.py#L707-L724 | train |
raymondEhlers/pachyderm | pachyderm/projectors.py | HistProjector.output_hist | def output_hist(self, output_hist: Hist, input_observable: Any, **kwargs: Dict[str, Any]) -> Union[Hist, Any]:
""" Return an output object. It should store the ``output_hist``.
Note:
The output object could just be the raw histogram.
Note:
This function is just a basic placeholder which returns the given output object (a histogram)
and likely should be overridden.
Args:
output_hist: The output histogram
input_observable (object): The corresponding input object. It could be a histogram or something
more complex.
kwargs: Projection information dict combined with additional arguments passed to the
projection function
Return:
The output object which should be stored in the output dict. By default, it returns the
output hist.
"""
return output_hist | python | def output_hist(self, output_hist: Hist, input_observable: Any, **kwargs: Dict[str, Any]) -> Union[Hist, Any]:
""" Return an output object. It should store the ``output_hist``.
Note:
The output object could just be the raw histogram.
Note:
This function is just a basic placeholder which returns the given output object (a histogram)
and likely should be overridden.
Args:
output_hist: The output histogram
input_observable (object): The corresponding input object. It could be a histogram or something
more complex.
kwargs: Projection information dict combined with additional arguments passed to the
projection function
Return:
The output object which should be stored in the output dict. By default, it returns the
output hist.
"""
return output_hist | [
"def",
"output_hist",
"(",
"self",
",",
"output_hist",
":",
"Hist",
",",
"input_observable",
":",
"Any",
",",
"*",
"*",
"kwargs",
":",
"Dict",
"[",
"str",
",",
"Any",
"]",
")",
"->",
"Union",
"[",
"Hist",
",",
"Any",
"]",
":",
"return",
"output_hist"
]
| Return an output object. It should store the ``output_hist``.
Note:
The output object could just be the raw histogram.
Note:
This function is just a basic placeholder which returns the given output object (a histogram)
and likely should be overridden.
Args:
output_hist: The output histogram
input_observable (object): The corresponding input object. It could be a histogram or something
more complex.
kwargs: Projection information dict combined with additional arguments passed to the
projection function
Return:
The output object which should be stored in the output dict. By default, it returns the
output hist. | [
"Return",
"an",
"output",
"object",
".",
"It",
"should",
"store",
"the",
"output_hist",
"."
]
| aaa1d8374fd871246290ce76f1796f2f7582b01d | https://github.com/raymondEhlers/pachyderm/blob/aaa1d8374fd871246290ce76f1796f2f7582b01d/pachyderm/projectors.py#L726-L746 | train |
lsst-sqre/sqre-codekit | codekit/cli/github_mv_repos_to_team.py | run | def run():
"""Move the repos"""
args = parse_args()
codetools.setup_logging(args.debug)
global g
g = pygithub.login_github(token_path=args.token_path, token=args.token)
org = g.get_organization(args.org)
# only iterate over all teams once
try:
teams = list(org.get_teams())
except github.RateLimitExceededException:
raise
except github.GithubException as e:
msg = 'error getting teams'
raise pygithub.CaughtOrganizationError(org, e, msg) from None
old_team = find_team(teams, args.oldteam)
new_team = find_team(teams, args.newteam)
move_me = args.repos
debug(len(move_me), 'repos to be moved')
added = []
removed = []
for name in move_me:
try:
r = org.get_repo(name)
except github.RateLimitExceededException:
raise
except github.GithubException as e:
msg = "error getting repo by name: {r}".format(r=name)
raise pygithub.CaughtOrganizationError(org, e, msg) from None
# Add team to the repo
debug("Adding {repo} to '{team}' ...".format(
repo=r.full_name,
team=args.newteam
))
if not args.dry_run:
try:
new_team.add_to_repos(r)
added += r.full_name
debug(' ok')
except github.RateLimitExceededException:
raise
except github.GithubException:
debug(' FAILED')
if old_team.name in 'Owners':
warn("Removing repo {repo} from team 'Owners' is not allowed"
.format(repo=r.full_name))
debug("Removing {repo} from '{team}' ...".format(
repo=r.full_name,
team=args.oldteam
))
if not args.dry_run:
try:
old_team.remove_from_repos(r)
removed += r.full_name
debug(' ok')
except github.RateLimitExceededException:
raise
except github.GithubException:
debug(' FAILED')
info('Added:', added)
info('Removed:', removed) | python | def run():
"""Move the repos"""
args = parse_args()
codetools.setup_logging(args.debug)
global g
g = pygithub.login_github(token_path=args.token_path, token=args.token)
org = g.get_organization(args.org)
# only iterate over all teams once
try:
teams = list(org.get_teams())
except github.RateLimitExceededException:
raise
except github.GithubException as e:
msg = 'error getting teams'
raise pygithub.CaughtOrganizationError(org, e, msg) from None
old_team = find_team(teams, args.oldteam)
new_team = find_team(teams, args.newteam)
move_me = args.repos
debug(len(move_me), 'repos to be moved')
added = []
removed = []
for name in move_me:
try:
r = org.get_repo(name)
except github.RateLimitExceededException:
raise
except github.GithubException as e:
msg = "error getting repo by name: {r}".format(r=name)
raise pygithub.CaughtOrganizationError(org, e, msg) from None
# Add team to the repo
debug("Adding {repo} to '{team}' ...".format(
repo=r.full_name,
team=args.newteam
))
if not args.dry_run:
try:
new_team.add_to_repos(r)
added += r.full_name
debug(' ok')
except github.RateLimitExceededException:
raise
except github.GithubException:
debug(' FAILED')
if old_team.name in 'Owners':
warn("Removing repo {repo} from team 'Owners' is not allowed"
.format(repo=r.full_name))
debug("Removing {repo} from '{team}' ...".format(
repo=r.full_name,
team=args.oldteam
))
if not args.dry_run:
try:
old_team.remove_from_repos(r)
removed += r.full_name
debug(' ok')
except github.RateLimitExceededException:
raise
except github.GithubException:
debug(' FAILED')
info('Added:', added)
info('Removed:', removed) | [
"def",
"run",
"(",
")",
":",
"args",
"=",
"parse_args",
"(",
")",
"codetools",
".",
"setup_logging",
"(",
"args",
".",
"debug",
")",
"global",
"g",
"g",
"=",
"pygithub",
".",
"login_github",
"(",
"token_path",
"=",
"args",
".",
"token_path",
",",
"token",
"=",
"args",
".",
"token",
")",
"org",
"=",
"g",
".",
"get_organization",
"(",
"args",
".",
"org",
")",
"# only iterate over all teams once",
"try",
":",
"teams",
"=",
"list",
"(",
"org",
".",
"get_teams",
"(",
")",
")",
"except",
"github",
".",
"RateLimitExceededException",
":",
"raise",
"except",
"github",
".",
"GithubException",
"as",
"e",
":",
"msg",
"=",
"'error getting teams'",
"raise",
"pygithub",
".",
"CaughtOrganizationError",
"(",
"org",
",",
"e",
",",
"msg",
")",
"from",
"None",
"old_team",
"=",
"find_team",
"(",
"teams",
",",
"args",
".",
"oldteam",
")",
"new_team",
"=",
"find_team",
"(",
"teams",
",",
"args",
".",
"newteam",
")",
"move_me",
"=",
"args",
".",
"repos",
"debug",
"(",
"len",
"(",
"move_me",
")",
",",
"'repos to be moved'",
")",
"added",
"=",
"[",
"]",
"removed",
"=",
"[",
"]",
"for",
"name",
"in",
"move_me",
":",
"try",
":",
"r",
"=",
"org",
".",
"get_repo",
"(",
"name",
")",
"except",
"github",
".",
"RateLimitExceededException",
":",
"raise",
"except",
"github",
".",
"GithubException",
"as",
"e",
":",
"msg",
"=",
"\"error getting repo by name: {r}\"",
".",
"format",
"(",
"r",
"=",
"name",
")",
"raise",
"pygithub",
".",
"CaughtOrganizationError",
"(",
"org",
",",
"e",
",",
"msg",
")",
"from",
"None",
"# Add team to the repo",
"debug",
"(",
"\"Adding {repo} to '{team}' ...\"",
".",
"format",
"(",
"repo",
"=",
"r",
".",
"full_name",
",",
"team",
"=",
"args",
".",
"newteam",
")",
")",
"if",
"not",
"args",
".",
"dry_run",
":",
"try",
":",
"new_team",
".",
"add_to_repos",
"(",
"r",
")",
"added",
"+=",
"r",
".",
"full_name",
"debug",
"(",
"' ok'",
")",
"except",
"github",
".",
"RateLimitExceededException",
":",
"raise",
"except",
"github",
".",
"GithubException",
":",
"debug",
"(",
"' FAILED'",
")",
"if",
"old_team",
".",
"name",
"in",
"'Owners'",
":",
"warn",
"(",
"\"Removing repo {repo} from team 'Owners' is not allowed\"",
".",
"format",
"(",
"repo",
"=",
"r",
".",
"full_name",
")",
")",
"debug",
"(",
"\"Removing {repo} from '{team}' ...\"",
".",
"format",
"(",
"repo",
"=",
"r",
".",
"full_name",
",",
"team",
"=",
"args",
".",
"oldteam",
")",
")",
"if",
"not",
"args",
".",
"dry_run",
":",
"try",
":",
"old_team",
".",
"remove_from_repos",
"(",
"r",
")",
"removed",
"+=",
"r",
".",
"full_name",
"debug",
"(",
"' ok'",
")",
"except",
"github",
".",
"RateLimitExceededException",
":",
"raise",
"except",
"github",
".",
"GithubException",
":",
"debug",
"(",
"' FAILED'",
")",
"info",
"(",
"'Added:'",
",",
"added",
")",
"info",
"(",
"'Removed:'",
",",
"removed",
")"
]
| Move the repos | [
"Move",
"the",
"repos"
]
| 98122404cd9065d4d1d570867fe518042669126c | https://github.com/lsst-sqre/sqre-codekit/blob/98122404cd9065d4d1d570867fe518042669126c/codekit/cli/github_mv_repos_to_team.py#L91-L163 | train |
yamcs/yamcs-python | yamcs-client/examples/parameter_subscription.py | poll_values | def poll_values():
"""Shows how to poll values from the subscription."""
subscription = processor.create_parameter_subscription([
'/YSS/SIMULATOR/BatteryVoltage1'
])
sleep(5)
print('Latest value:')
print(subscription.get_value('/YSS/SIMULATOR/BatteryVoltage1'))
sleep(5)
print('Latest value:')
print(subscription.get_value('/YSS/SIMULATOR/BatteryVoltage1')) | python | def poll_values():
"""Shows how to poll values from the subscription."""
subscription = processor.create_parameter_subscription([
'/YSS/SIMULATOR/BatteryVoltage1'
])
sleep(5)
print('Latest value:')
print(subscription.get_value('/YSS/SIMULATOR/BatteryVoltage1'))
sleep(5)
print('Latest value:')
print(subscription.get_value('/YSS/SIMULATOR/BatteryVoltage1')) | [
"def",
"poll_values",
"(",
")",
":",
"subscription",
"=",
"processor",
".",
"create_parameter_subscription",
"(",
"[",
"'/YSS/SIMULATOR/BatteryVoltage1'",
"]",
")",
"sleep",
"(",
"5",
")",
"print",
"(",
"'Latest value:'",
")",
"print",
"(",
"subscription",
".",
"get_value",
"(",
"'/YSS/SIMULATOR/BatteryVoltage1'",
")",
")",
"sleep",
"(",
"5",
")",
"print",
"(",
"'Latest value:'",
")",
"print",
"(",
"subscription",
".",
"get_value",
"(",
"'/YSS/SIMULATOR/BatteryVoltage1'",
")",
")"
]
| Shows how to poll values from the subscription. | [
"Shows",
"how",
"to",
"poll",
"values",
"from",
"the",
"subscription",
"."
]
| 1082fee8a299010cc44416bbb7518fac0ef08b48 | https://github.com/yamcs/yamcs-python/blob/1082fee8a299010cc44416bbb7518fac0ef08b48/yamcs-client/examples/parameter_subscription.py#L8-L20 | train |
yamcs/yamcs-python | yamcs-client/examples/parameter_subscription.py | receive_callbacks | def receive_callbacks():
"""Shows how to receive callbacks on value updates."""
def print_data(data):
for parameter in data.parameters:
print(parameter)
processor.create_parameter_subscription('/YSS/SIMULATOR/BatteryVoltage1',
on_data=print_data)
sleep(5) | python | def receive_callbacks():
"""Shows how to receive callbacks on value updates."""
def print_data(data):
for parameter in data.parameters:
print(parameter)
processor.create_parameter_subscription('/YSS/SIMULATOR/BatteryVoltage1',
on_data=print_data)
sleep(5) | [
"def",
"receive_callbacks",
"(",
")",
":",
"def",
"print_data",
"(",
"data",
")",
":",
"for",
"parameter",
"in",
"data",
".",
"parameters",
":",
"print",
"(",
"parameter",
")",
"processor",
".",
"create_parameter_subscription",
"(",
"'/YSS/SIMULATOR/BatteryVoltage1'",
",",
"on_data",
"=",
"print_data",
")",
"sleep",
"(",
"5",
")"
]
| Shows how to receive callbacks on value updates. | [
"Shows",
"how",
"to",
"receive",
"callbacks",
"on",
"value",
"updates",
"."
]
| 1082fee8a299010cc44416bbb7518fac0ef08b48 | https://github.com/yamcs/yamcs-python/blob/1082fee8a299010cc44416bbb7518fac0ef08b48/yamcs-client/examples/parameter_subscription.py#L23-L31 | train |
yamcs/yamcs-python | yamcs-client/examples/parameter_subscription.py | manage_subscription | def manage_subscription():
"""Shows how to interact with a parameter subscription."""
subscription = processor.create_parameter_subscription([
'/YSS/SIMULATOR/BatteryVoltage1'
])
sleep(5)
print('Adding extra items to the existing subscription...')
subscription.add([
'/YSS/SIMULATOR/Alpha',
'/YSS/SIMULATOR/BatteryVoltage2',
'MDB:OPS Name/SIMULATOR_PrimBusVoltage1',
])
sleep(5)
print('Shrinking subscription...')
subscription.remove('/YSS/SIMULATOR/Alpha')
print('Cancelling the subscription...')
subscription.cancel()
print('Last values from cache:')
print(subscription.get_value('/YSS/SIMULATOR/BatteryVoltage1'))
print(subscription.get_value('/YSS/SIMULATOR/BatteryVoltage2'))
print(subscription.get_value('/YSS/SIMULATOR/Alpha'))
print(subscription.get_value('MDB:OPS Name/SIMULATOR_PrimBusVoltage1')) | python | def manage_subscription():
"""Shows how to interact with a parameter subscription."""
subscription = processor.create_parameter_subscription([
'/YSS/SIMULATOR/BatteryVoltage1'
])
sleep(5)
print('Adding extra items to the existing subscription...')
subscription.add([
'/YSS/SIMULATOR/Alpha',
'/YSS/SIMULATOR/BatteryVoltage2',
'MDB:OPS Name/SIMULATOR_PrimBusVoltage1',
])
sleep(5)
print('Shrinking subscription...')
subscription.remove('/YSS/SIMULATOR/Alpha')
print('Cancelling the subscription...')
subscription.cancel()
print('Last values from cache:')
print(subscription.get_value('/YSS/SIMULATOR/BatteryVoltage1'))
print(subscription.get_value('/YSS/SIMULATOR/BatteryVoltage2'))
print(subscription.get_value('/YSS/SIMULATOR/Alpha'))
print(subscription.get_value('MDB:OPS Name/SIMULATOR_PrimBusVoltage1')) | [
"def",
"manage_subscription",
"(",
")",
":",
"subscription",
"=",
"processor",
".",
"create_parameter_subscription",
"(",
"[",
"'/YSS/SIMULATOR/BatteryVoltage1'",
"]",
")",
"sleep",
"(",
"5",
")",
"print",
"(",
"'Adding extra items to the existing subscription...'",
")",
"subscription",
".",
"add",
"(",
"[",
"'/YSS/SIMULATOR/Alpha'",
",",
"'/YSS/SIMULATOR/BatteryVoltage2'",
",",
"'MDB:OPS Name/SIMULATOR_PrimBusVoltage1'",
",",
"]",
")",
"sleep",
"(",
"5",
")",
"print",
"(",
"'Shrinking subscription...'",
")",
"subscription",
".",
"remove",
"(",
"'/YSS/SIMULATOR/Alpha'",
")",
"print",
"(",
"'Cancelling the subscription...'",
")",
"subscription",
".",
"cancel",
"(",
")",
"print",
"(",
"'Last values from cache:'",
")",
"print",
"(",
"subscription",
".",
"get_value",
"(",
"'/YSS/SIMULATOR/BatteryVoltage1'",
")",
")",
"print",
"(",
"subscription",
".",
"get_value",
"(",
"'/YSS/SIMULATOR/BatteryVoltage2'",
")",
")",
"print",
"(",
"subscription",
".",
"get_value",
"(",
"'/YSS/SIMULATOR/Alpha'",
")",
")",
"print",
"(",
"subscription",
".",
"get_value",
"(",
"'MDB:OPS Name/SIMULATOR_PrimBusVoltage1'",
")",
")"
]
| Shows how to interact with a parameter subscription. | [
"Shows",
"how",
"to",
"interact",
"with",
"a",
"parameter",
"subscription",
"."
]
| 1082fee8a299010cc44416bbb7518fac0ef08b48 | https://github.com/yamcs/yamcs-python/blob/1082fee8a299010cc44416bbb7518fac0ef08b48/yamcs-client/examples/parameter_subscription.py#L34-L61 | train |
portfors-lab/sparkle | sparkle/gui/stim/stimulusview.py | StimulusView.setPixelScale | def setPixelScale(self, pxms):
"""Sets the zoom scale
:param pxms: number of pixels per ms
:type pxms: int
:returns: float -- the miliseconds between grid lines
"""
pxms = float(pxms)/2
self.pixelsPerms = pxms
if pxms*self.gridms < GRID_PIXEL_MIN:
self.gridms = self.gridms*2
elif pxms*self.gridms > GRID_PIXEL_MAX:
self.gridms = self.gridms/2
self._viewIsDirty = True
self.viewport().update()
return self.gridms | python | def setPixelScale(self, pxms):
"""Sets the zoom scale
:param pxms: number of pixels per ms
:type pxms: int
:returns: float -- the miliseconds between grid lines
"""
pxms = float(pxms)/2
self.pixelsPerms = pxms
if pxms*self.gridms < GRID_PIXEL_MIN:
self.gridms = self.gridms*2
elif pxms*self.gridms > GRID_PIXEL_MAX:
self.gridms = self.gridms/2
self._viewIsDirty = True
self.viewport().update()
return self.gridms | [
"def",
"setPixelScale",
"(",
"self",
",",
"pxms",
")",
":",
"pxms",
"=",
"float",
"(",
"pxms",
")",
"/",
"2",
"self",
".",
"pixelsPerms",
"=",
"pxms",
"if",
"pxms",
"*",
"self",
".",
"gridms",
"<",
"GRID_PIXEL_MIN",
":",
"self",
".",
"gridms",
"=",
"self",
".",
"gridms",
"*",
"2",
"elif",
"pxms",
"*",
"self",
".",
"gridms",
">",
"GRID_PIXEL_MAX",
":",
"self",
".",
"gridms",
"=",
"self",
".",
"gridms",
"/",
"2",
"self",
".",
"_viewIsDirty",
"=",
"True",
"self",
".",
"viewport",
"(",
")",
".",
"update",
"(",
")",
"return",
"self",
".",
"gridms"
]
| Sets the zoom scale
:param pxms: number of pixels per ms
:type pxms: int
:returns: float -- the miliseconds between grid lines | [
"Sets",
"the",
"zoom",
"scale"
]
| 5fad1cf2bec58ec6b15d91da20f6236a74826110 | https://github.com/portfors-lab/sparkle/blob/5fad1cf2bec58ec6b15d91da20f6236a74826110/sparkle/gui/stim/stimulusview.py#L50-L66 | train |
portfors-lab/sparkle | sparkle/gui/stim/stimulusview.py | StimulusView.indexXY | def indexXY(self, index):
"""Returns the top left coordinates of the item for the given index
:param index: index for the item
:type index: :qtdoc:`QModelIndex`
:returns: (int, int) -- (x, y) view coordinates of item
"""
rect = self.visualRect(index)
return rect.x(), rect.y() | python | def indexXY(self, index):
"""Returns the top left coordinates of the item for the given index
:param index: index for the item
:type index: :qtdoc:`QModelIndex`
:returns: (int, int) -- (x, y) view coordinates of item
"""
rect = self.visualRect(index)
return rect.x(), rect.y() | [
"def",
"indexXY",
"(",
"self",
",",
"index",
")",
":",
"rect",
"=",
"self",
".",
"visualRect",
"(",
"index",
")",
"return",
"rect",
".",
"x",
"(",
")",
",",
"rect",
".",
"y",
"(",
")"
]
| Returns the top left coordinates of the item for the given index
:param index: index for the item
:type index: :qtdoc:`QModelIndex`
:returns: (int, int) -- (x, y) view coordinates of item | [
"Returns",
"the",
"top",
"left",
"coordinates",
"of",
"the",
"item",
"for",
"the",
"given",
"index"
]
| 5fad1cf2bec58ec6b15d91da20f6236a74826110 | https://github.com/portfors-lab/sparkle/blob/5fad1cf2bec58ec6b15d91da20f6236a74826110/sparkle/gui/stim/stimulusview.py#L82-L90 | train |
portfors-lab/sparkle | sparkle/gui/stim/stimulusview.py | StimulusView.mouseDoubleClickEvent | def mouseDoubleClickEvent(self, event):
"""Launches an editor for the component, if the mouse cursor is over an item"""
if self.mode == BuildMode:
if event.button() == QtCore.Qt.LeftButton:
index = self.indexAt(event.pos())
self.edit(index) | python | def mouseDoubleClickEvent(self, event):
"""Launches an editor for the component, if the mouse cursor is over an item"""
if self.mode == BuildMode:
if event.button() == QtCore.Qt.LeftButton:
index = self.indexAt(event.pos())
self.edit(index) | [
"def",
"mouseDoubleClickEvent",
"(",
"self",
",",
"event",
")",
":",
"if",
"self",
".",
"mode",
"==",
"BuildMode",
":",
"if",
"event",
".",
"button",
"(",
")",
"==",
"QtCore",
".",
"Qt",
".",
"LeftButton",
":",
"index",
"=",
"self",
".",
"indexAt",
"(",
"event",
".",
"pos",
"(",
")",
")",
"self",
".",
"edit",
"(",
"index",
")"
]
| Launches an editor for the component, if the mouse cursor is over an item | [
"Launches",
"an",
"editor",
"for",
"the",
"component",
"if",
"the",
"mouse",
"cursor",
"is",
"over",
"an",
"item"
]
| 5fad1cf2bec58ec6b15d91da20f6236a74826110 | https://github.com/portfors-lab/sparkle/blob/5fad1cf2bec58ec6b15d91da20f6236a74826110/sparkle/gui/stim/stimulusview.py#L322-L327 | train |
portfors-lab/sparkle | sparkle/gui/stim/stimulusview.py | StimulusView.mousePressEvent | def mousePressEvent(self, event):
"""In Auto-parameter selection mode, mouse press over an item emits
`componentSelected`"""
if self.mode == BuildMode:
super(StimulusView, self).mousePressEvent(event)
else:
# select and de-select components
index = self.indexAt(event.pos())
if index.isValid():
self.selectionModel().select(index, QtGui.QItemSelectionModel.Toggle)
comp = self.model().data(index, AbstractDragView.DragRole)
self.componentSelected.emit(comp)
self.hintRequested.emit('Click components to toggle more members of auto-parameter\n\n-or-\n\nEdit fields of auto-parameter (parameter type should be selected first)') | python | def mousePressEvent(self, event):
"""In Auto-parameter selection mode, mouse press over an item emits
`componentSelected`"""
if self.mode == BuildMode:
super(StimulusView, self).mousePressEvent(event)
else:
# select and de-select components
index = self.indexAt(event.pos())
if index.isValid():
self.selectionModel().select(index, QtGui.QItemSelectionModel.Toggle)
comp = self.model().data(index, AbstractDragView.DragRole)
self.componentSelected.emit(comp)
self.hintRequested.emit('Click components to toggle more members of auto-parameter\n\n-or-\n\nEdit fields of auto-parameter (parameter type should be selected first)') | [
"def",
"mousePressEvent",
"(",
"self",
",",
"event",
")",
":",
"if",
"self",
".",
"mode",
"==",
"BuildMode",
":",
"super",
"(",
"StimulusView",
",",
"self",
")",
".",
"mousePressEvent",
"(",
"event",
")",
"else",
":",
"# select and de-select components",
"index",
"=",
"self",
".",
"indexAt",
"(",
"event",
".",
"pos",
"(",
")",
")",
"if",
"index",
".",
"isValid",
"(",
")",
":",
"self",
".",
"selectionModel",
"(",
")",
".",
"select",
"(",
"index",
",",
"QtGui",
".",
"QItemSelectionModel",
".",
"Toggle",
")",
"comp",
"=",
"self",
".",
"model",
"(",
")",
".",
"data",
"(",
"index",
",",
"AbstractDragView",
".",
"DragRole",
")",
"self",
".",
"componentSelected",
".",
"emit",
"(",
"comp",
")",
"self",
".",
"hintRequested",
".",
"emit",
"(",
"'Click components to toggle more members of auto-parameter\\n\\n-or-\\n\\nEdit fields of auto-parameter (parameter type should be selected first)'",
")"
]
| In Auto-parameter selection mode, mouse press over an item emits
`componentSelected` | [
"In",
"Auto",
"-",
"parameter",
"selection",
"mode",
"mouse",
"press",
"over",
"an",
"item",
"emits",
"componentSelected"
]
| 5fad1cf2bec58ec6b15d91da20f6236a74826110 | https://github.com/portfors-lab/sparkle/blob/5fad1cf2bec58ec6b15d91da20f6236a74826110/sparkle/gui/stim/stimulusview.py#L351-L363 | train |
portfors-lab/sparkle | sparkle/gui/stim/stimulusview.py | StimulusView.visualRegionForSelection | def visualRegionForSelection(self, selection):
"""Gets the region of all of the components in selection
:param selection: a selection model for this view
:type selection: :qtdoc:`QItemSelectionModel`
:returns: :qtdoc:`QRegion` -- union of rects of the selected components
"""
region = QtGui.QRegion()
for index in selection.indexes():
region = region.united(self._rects[index.row()][index.column()])
return region | python | def visualRegionForSelection(self, selection):
"""Gets the region of all of the components in selection
:param selection: a selection model for this view
:type selection: :qtdoc:`QItemSelectionModel`
:returns: :qtdoc:`QRegion` -- union of rects of the selected components
"""
region = QtGui.QRegion()
for index in selection.indexes():
region = region.united(self._rects[index.row()][index.column()])
return region | [
"def",
"visualRegionForSelection",
"(",
"self",
",",
"selection",
")",
":",
"region",
"=",
"QtGui",
".",
"QRegion",
"(",
")",
"for",
"index",
"in",
"selection",
".",
"indexes",
"(",
")",
":",
"region",
"=",
"region",
".",
"united",
"(",
"self",
".",
"_rects",
"[",
"index",
".",
"row",
"(",
")",
"]",
"[",
"index",
".",
"column",
"(",
")",
"]",
")",
"return",
"region"
]
| Gets the region of all of the components in selection
:param selection: a selection model for this view
:type selection: :qtdoc:`QItemSelectionModel`
:returns: :qtdoc:`QRegion` -- union of rects of the selected components | [
"Gets",
"the",
"region",
"of",
"all",
"of",
"the",
"components",
"in",
"selection"
]
| 5fad1cf2bec58ec6b15d91da20f6236a74826110 | https://github.com/portfors-lab/sparkle/blob/5fad1cf2bec58ec6b15d91da20f6236a74826110/sparkle/gui/stim/stimulusview.py#L474-L485 | train |
portfors-lab/sparkle | sparkle/gui/stim/stimulusview.py | ComponentDelegate.sizeHint | def sizeHint(self, option, index):
"""Size based on component duration and a fixed height"""
# calculate size by data component
component = index.internalPointer()
width = self.component.duration() * self.pixelsPerms*1000
return QtCore.QSize(width, 50) | python | def sizeHint(self, option, index):
"""Size based on component duration and a fixed height"""
# calculate size by data component
component = index.internalPointer()
width = self.component.duration() * self.pixelsPerms*1000
return QtCore.QSize(width, 50) | [
"def",
"sizeHint",
"(",
"self",
",",
"option",
",",
"index",
")",
":",
"# calculate size by data component",
"component",
"=",
"index",
".",
"internalPointer",
"(",
")",
"width",
"=",
"self",
".",
"component",
".",
"duration",
"(",
")",
"*",
"self",
".",
"pixelsPerms",
"*",
"1000",
"return",
"QtCore",
".",
"QSize",
"(",
"width",
",",
"50",
")"
]
| Size based on component duration and a fixed height | [
"Size",
"based",
"on",
"component",
"duration",
"and",
"a",
"fixed",
"height"
]
| 5fad1cf2bec58ec6b15d91da20f6236a74826110 | https://github.com/portfors-lab/sparkle/blob/5fad1cf2bec58ec6b15d91da20f6236a74826110/sparkle/gui/stim/stimulusview.py#L558-L563 | train |
JukeboxPipeline/jukeboxmaya | src/jukeboxmaya/reftrack/__init__.py | get_namespace | def get_namespace(taskfileinfo):
"""Return a suitable name for a namespace for the taskfileinfo
Returns the name of the shot/asset with a "_1" suffix.
When you create the namespace the number will automatically be incremented by Maya.
:param taskfileinfo: the taskfile info for the file that needs a namespace
:type taskfileinfo: :class:`jukeboxcore.filesys.TaskFileInfo`
:returns: a namespace suggestion
:rtype: str
:raises: None
"""
element = taskfileinfo.task.element
name = element.name
return name + "_1" | python | def get_namespace(taskfileinfo):
"""Return a suitable name for a namespace for the taskfileinfo
Returns the name of the shot/asset with a "_1" suffix.
When you create the namespace the number will automatically be incremented by Maya.
:param taskfileinfo: the taskfile info for the file that needs a namespace
:type taskfileinfo: :class:`jukeboxcore.filesys.TaskFileInfo`
:returns: a namespace suggestion
:rtype: str
:raises: None
"""
element = taskfileinfo.task.element
name = element.name
return name + "_1" | [
"def",
"get_namespace",
"(",
"taskfileinfo",
")",
":",
"element",
"=",
"taskfileinfo",
".",
"task",
".",
"element",
"name",
"=",
"element",
".",
"name",
"return",
"name",
"+",
"\"_1\""
]
| Return a suitable name for a namespace for the taskfileinfo
Returns the name of the shot/asset with a "_1" suffix.
When you create the namespace the number will automatically be incremented by Maya.
:param taskfileinfo: the taskfile info for the file that needs a namespace
:type taskfileinfo: :class:`jukeboxcore.filesys.TaskFileInfo`
:returns: a namespace suggestion
:rtype: str
:raises: None | [
"Return",
"a",
"suitable",
"name",
"for",
"a",
"namespace",
"for",
"the",
"taskfileinfo"
]
| c8d6318d53cdb5493453c4a6b65ef75bdb2d5f2c | https://github.com/JukeboxPipeline/jukeboxmaya/blob/c8d6318d53cdb5493453c4a6b65ef75bdb2d5f2c/src/jukeboxmaya/reftrack/__init__.py#L7-L21 | train |
JukeboxPipeline/jukeboxmaya | src/jukeboxmaya/reftrack/__init__.py | get_groupname | def get_groupname(taskfileinfo):
"""Return a suitable name for a groupname for the given taskfileinfo.
:param taskfileinfo: the taskfile info for the file that needs a group when importing/referencing
:type taskfileinfo: :class:`jukeboxcore.filesys.TaskFileInfo`
:returns: None
:rtype: None
:raises: None
"""
element = taskfileinfo.task.element
name = element.name
return name + "_grp" | python | def get_groupname(taskfileinfo):
"""Return a suitable name for a groupname for the given taskfileinfo.
:param taskfileinfo: the taskfile info for the file that needs a group when importing/referencing
:type taskfileinfo: :class:`jukeboxcore.filesys.TaskFileInfo`
:returns: None
:rtype: None
:raises: None
"""
element = taskfileinfo.task.element
name = element.name
return name + "_grp" | [
"def",
"get_groupname",
"(",
"taskfileinfo",
")",
":",
"element",
"=",
"taskfileinfo",
".",
"task",
".",
"element",
"name",
"=",
"element",
".",
"name",
"return",
"name",
"+",
"\"_grp\""
]
| Return a suitable name for a groupname for the given taskfileinfo.
:param taskfileinfo: the taskfile info for the file that needs a group when importing/referencing
:type taskfileinfo: :class:`jukeboxcore.filesys.TaskFileInfo`
:returns: None
:rtype: None
:raises: None | [
"Return",
"a",
"suitable",
"name",
"for",
"a",
"groupname",
"for",
"the",
"given",
"taskfileinfo",
"."
]
| c8d6318d53cdb5493453c4a6b65ef75bdb2d5f2c | https://github.com/JukeboxPipeline/jukeboxmaya/blob/c8d6318d53cdb5493453c4a6b65ef75bdb2d5f2c/src/jukeboxmaya/reftrack/__init__.py#L24-L35 | train |
JukeboxPipeline/jukeboxmaya | src/jukeboxmaya/reftrack/__init__.py | group_content | def group_content(content, namespace, grpname, grpnodetype):
"""Group the given content in the given namespace under a node of type
grpnodetype with the name grpname
:param content: the nodes to group
:type content: :class:`list`
:param namespace: the namespace to use
:type namespace: str | None
:param grpname: the name of the new grpnode
:type grpname: str
:param grpnodetype: the nodetype for the grpnode
:type grpnodetype: str
:returns: the created group node
:rtype: str
:raises: None
"""
with common.preserve_namespace(namespace):
grpnode = cmds.createNode(grpnodetype, name=grpname) # create grp node
cmds.group(content, uag=grpnode) # group content
return grpnode | python | def group_content(content, namespace, grpname, grpnodetype):
"""Group the given content in the given namespace under a node of type
grpnodetype with the name grpname
:param content: the nodes to group
:type content: :class:`list`
:param namespace: the namespace to use
:type namespace: str | None
:param grpname: the name of the new grpnode
:type grpname: str
:param grpnodetype: the nodetype for the grpnode
:type grpnodetype: str
:returns: the created group node
:rtype: str
:raises: None
"""
with common.preserve_namespace(namespace):
grpnode = cmds.createNode(grpnodetype, name=grpname) # create grp node
cmds.group(content, uag=grpnode) # group content
return grpnode | [
"def",
"group_content",
"(",
"content",
",",
"namespace",
",",
"grpname",
",",
"grpnodetype",
")",
":",
"with",
"common",
".",
"preserve_namespace",
"(",
"namespace",
")",
":",
"grpnode",
"=",
"cmds",
".",
"createNode",
"(",
"grpnodetype",
",",
"name",
"=",
"grpname",
")",
"# create grp node",
"cmds",
".",
"group",
"(",
"content",
",",
"uag",
"=",
"grpnode",
")",
"# group content",
"return",
"grpnode"
]
| Group the given content in the given namespace under a node of type
grpnodetype with the name grpname
:param content: the nodes to group
:type content: :class:`list`
:param namespace: the namespace to use
:type namespace: str | None
:param grpname: the name of the new grpnode
:type grpname: str
:param grpnodetype: the nodetype for the grpnode
:type grpnodetype: str
:returns: the created group node
:rtype: str
:raises: None | [
"Group",
"the",
"given",
"content",
"in",
"the",
"given",
"namespace",
"under",
"a",
"node",
"of",
"type",
"grpnodetype",
"with",
"the",
"name",
"grpname"
]
| c8d6318d53cdb5493453c4a6b65ef75bdb2d5f2c | https://github.com/JukeboxPipeline/jukeboxmaya/blob/c8d6318d53cdb5493453c4a6b65ef75bdb2d5f2c/src/jukeboxmaya/reftrack/__init__.py#L38-L57 | train |
portfors-lab/sparkle | sparkle/gui/stim/component_label.py | ComponentTemplateTable.getLabelByName | def getLabelByName(self, name):
"""Gets a label widget by it component name
:param name: name of the AbstractStimulusComponent which this label is named after
:type name: str
:returns: :class:`DragLabel<sparkle.gui.drag_label.DragLabel>`
"""
name = name.lower()
if name in self.stimLabels:
return self.stimLabels[name]
else:
return None | python | def getLabelByName(self, name):
"""Gets a label widget by it component name
:param name: name of the AbstractStimulusComponent which this label is named after
:type name: str
:returns: :class:`DragLabel<sparkle.gui.drag_label.DragLabel>`
"""
name = name.lower()
if name in self.stimLabels:
return self.stimLabels[name]
else:
return None | [
"def",
"getLabelByName",
"(",
"self",
",",
"name",
")",
":",
"name",
"=",
"name",
".",
"lower",
"(",
")",
"if",
"name",
"in",
"self",
".",
"stimLabels",
":",
"return",
"self",
".",
"stimLabels",
"[",
"name",
"]",
"else",
":",
"return",
"None"
]
| Gets a label widget by it component name
:param name: name of the AbstractStimulusComponent which this label is named after
:type name: str
:returns: :class:`DragLabel<sparkle.gui.drag_label.DragLabel>` | [
"Gets",
"a",
"label",
"widget",
"by",
"it",
"component",
"name"
]
| 5fad1cf2bec58ec6b15d91da20f6236a74826110 | https://github.com/portfors-lab/sparkle/blob/5fad1cf2bec58ec6b15d91da20f6236a74826110/sparkle/gui/stim/component_label.py#L37-L48 | train |
rmb938/vmw-cloudinit-metadata | vmw_cloudinit_metadata/vspc/async_telnet.py | AsyncTelnet.read_byte | def read_byte(self):
"""Read one byte of cooked data
"""
buf = b''
if len(self.cookedq) > 0:
buf = bytes([self.cookedq[0]])
self.cookedq = self.cookedq[1:]
else:
yield from self.process_rawq()
if not self.eof:
yield from self.fill_rawq()
yield from self.process_rawq()
# There now should be data so lets read again
buf = yield from self.read_byte()
return buf | python | def read_byte(self):
"""Read one byte of cooked data
"""
buf = b''
if len(self.cookedq) > 0:
buf = bytes([self.cookedq[0]])
self.cookedq = self.cookedq[1:]
else:
yield from self.process_rawq()
if not self.eof:
yield from self.fill_rawq()
yield from self.process_rawq()
# There now should be data so lets read again
buf = yield from self.read_byte()
return buf | [
"def",
"read_byte",
"(",
"self",
")",
":",
"buf",
"=",
"b''",
"if",
"len",
"(",
"self",
".",
"cookedq",
")",
">",
"0",
":",
"buf",
"=",
"bytes",
"(",
"[",
"self",
".",
"cookedq",
"[",
"0",
"]",
"]",
")",
"self",
".",
"cookedq",
"=",
"self",
".",
"cookedq",
"[",
"1",
":",
"]",
"else",
":",
"yield",
"from",
"self",
".",
"process_rawq",
"(",
")",
"if",
"not",
"self",
".",
"eof",
":",
"yield",
"from",
"self",
".",
"fill_rawq",
"(",
")",
"yield",
"from",
"self",
".",
"process_rawq",
"(",
")",
"# There now should be data so lets read again",
"buf",
"=",
"yield",
"from",
"self",
".",
"read_byte",
"(",
")",
"return",
"buf"
]
| Read one byte of cooked data | [
"Read",
"one",
"byte",
"of",
"cooked",
"data"
]
| b667b2a0e10e11dbd6cf058d9b5be70b97b7950e | https://github.com/rmb938/vmw-cloudinit-metadata/blob/b667b2a0e10e11dbd6cf058d9b5be70b97b7950e/vmw_cloudinit_metadata/vspc/async_telnet.py#L154-L169 | train |
rmb938/vmw-cloudinit-metadata | vmw_cloudinit_metadata/vspc/async_telnet.py | AsyncTelnet.read_line | def read_line(self):
"""Read data until \n is found
"""
buf = b''
while not self.eof and buf.endswith(b'\n') is False:
buf += yield from self.read_byte()
if self.eof:
buf = b''
# Remove \n character
buf = buf.replace(b'\n', b'')
return buf | python | def read_line(self):
"""Read data until \n is found
"""
buf = b''
while not self.eof and buf.endswith(b'\n') is False:
buf += yield from self.read_byte()
if self.eof:
buf = b''
# Remove \n character
buf = buf.replace(b'\n', b'')
return buf | [
"def",
"read_line",
"(",
"self",
")",
":",
"buf",
"=",
"b''",
"while",
"not",
"self",
".",
"eof",
"and",
"buf",
".",
"endswith",
"(",
"b'\\n'",
")",
"is",
"False",
":",
"buf",
"+=",
"yield",
"from",
"self",
".",
"read_byte",
"(",
")",
"if",
"self",
".",
"eof",
":",
"buf",
"=",
"b''",
"# Remove \\n character",
"buf",
"=",
"buf",
".",
"replace",
"(",
"b'\\n'",
",",
"b''",
")",
"return",
"buf"
]
| Read data until \n is found | [
"Read",
"data",
"until",
"\\",
"n",
"is",
"found"
]
| b667b2a0e10e11dbd6cf058d9b5be70b97b7950e | https://github.com/rmb938/vmw-cloudinit-metadata/blob/b667b2a0e10e11dbd6cf058d9b5be70b97b7950e/vmw_cloudinit_metadata/vspc/async_telnet.py#L172-L185 | train |
tBaxter/python-card-me | card_me/icalendar.py | getTzid | def getTzid(tzid, smart=True):
"""Return the tzid if it exists, or None."""
tz = __tzidMap.get(toUnicode(tzid), None)
if smart and tzid and not tz:
try:
from pytz import timezone, UnknownTimeZoneError
try:
tz = timezone(tzid)
registerTzid(toUnicode(tzid), tz)
except UnknownTimeZoneError:
pass
except ImportError:
pass
return tz | python | def getTzid(tzid, smart=True):
"""Return the tzid if it exists, or None."""
tz = __tzidMap.get(toUnicode(tzid), None)
if smart and tzid and not tz:
try:
from pytz import timezone, UnknownTimeZoneError
try:
tz = timezone(tzid)
registerTzid(toUnicode(tzid), tz)
except UnknownTimeZoneError:
pass
except ImportError:
pass
return tz | [
"def",
"getTzid",
"(",
"tzid",
",",
"smart",
"=",
"True",
")",
":",
"tz",
"=",
"__tzidMap",
".",
"get",
"(",
"toUnicode",
"(",
"tzid",
")",
",",
"None",
")",
"if",
"smart",
"and",
"tzid",
"and",
"not",
"tz",
":",
"try",
":",
"from",
"pytz",
"import",
"timezone",
",",
"UnknownTimeZoneError",
"try",
":",
"tz",
"=",
"timezone",
"(",
"tzid",
")",
"registerTzid",
"(",
"toUnicode",
"(",
"tzid",
")",
",",
"tz",
")",
"except",
"UnknownTimeZoneError",
":",
"pass",
"except",
"ImportError",
":",
"pass",
"return",
"tz"
]
| Return the tzid if it exists, or None. | [
"Return",
"the",
"tzid",
"if",
"it",
"exists",
"or",
"None",
"."
]
| ffebc7fed44f83983b7438e57263dcda67207664 | https://github.com/tBaxter/python-card-me/blob/ffebc7fed44f83983b7438e57263dcda67207664/card_me/icalendar.py#L52-L65 | train |
tBaxter/python-card-me | card_me/icalendar.py | dateTimeToString | def dateTimeToString(dateTime, convertToUTC=False):
"""
Ignore tzinfo unless convertToUTC. Output string.
"""
if dateTime.tzinfo and convertToUTC:
dateTime = dateTime.astimezone(utc)
datestr = "{}{}{}T{}{}{}".format(
numToDigits(dateTime.year, 4),
numToDigits(dateTime.month, 2),
numToDigits(dateTime.day, 2),
numToDigits(dateTime.hour, 2),
numToDigits(dateTime.minute, 2),
numToDigits(dateTime.second, 2),
)
if tzinfo_eq(dateTime.tzinfo, utc):
datestr += "Z"
return datestr | python | def dateTimeToString(dateTime, convertToUTC=False):
"""
Ignore tzinfo unless convertToUTC. Output string.
"""
if dateTime.tzinfo and convertToUTC:
dateTime = dateTime.astimezone(utc)
datestr = "{}{}{}T{}{}{}".format(
numToDigits(dateTime.year, 4),
numToDigits(dateTime.month, 2),
numToDigits(dateTime.day, 2),
numToDigits(dateTime.hour, 2),
numToDigits(dateTime.minute, 2),
numToDigits(dateTime.second, 2),
)
if tzinfo_eq(dateTime.tzinfo, utc):
datestr += "Z"
return datestr | [
"def",
"dateTimeToString",
"(",
"dateTime",
",",
"convertToUTC",
"=",
"False",
")",
":",
"if",
"dateTime",
".",
"tzinfo",
"and",
"convertToUTC",
":",
"dateTime",
"=",
"dateTime",
".",
"astimezone",
"(",
"utc",
")",
"datestr",
"=",
"\"{}{}{}T{}{}{}\"",
".",
"format",
"(",
"numToDigits",
"(",
"dateTime",
".",
"year",
",",
"4",
")",
",",
"numToDigits",
"(",
"dateTime",
".",
"month",
",",
"2",
")",
",",
"numToDigits",
"(",
"dateTime",
".",
"day",
",",
"2",
")",
",",
"numToDigits",
"(",
"dateTime",
".",
"hour",
",",
"2",
")",
",",
"numToDigits",
"(",
"dateTime",
".",
"minute",
",",
"2",
")",
",",
"numToDigits",
"(",
"dateTime",
".",
"second",
",",
"2",
")",
",",
")",
"if",
"tzinfo_eq",
"(",
"dateTime",
".",
"tzinfo",
",",
"utc",
")",
":",
"datestr",
"+=",
"\"Z\"",
"return",
"datestr"
]
| Ignore tzinfo unless convertToUTC. Output string. | [
"Ignore",
"tzinfo",
"unless",
"convertToUTC",
".",
"Output",
"string",
"."
]
| ffebc7fed44f83983b7438e57263dcda67207664 | https://github.com/tBaxter/python-card-me/blob/ffebc7fed44f83983b7438e57263dcda67207664/card_me/icalendar.py#L1564-L1581 | train |
tBaxter/python-card-me | card_me/icalendar.py | RecurringComponent.getrruleset | def getrruleset(self, addRDate=False):
"""
Get an rruleset created from self.
If addRDate is True, add an RDATE for dtstart if it's not included in
an RRULE, and count is decremented if it exists.
Note that for rules which don't match DTSTART, DTSTART may not appear
in list(rruleset), although it should. By default, an RDATE is not
created in these cases, and count isn't updated, so dateutil may list
a spurious occurrence.
"""
rruleset = None
for name in DATESANDRULES:
addfunc = None
for line in self.contents.get(name, ()):
# don't bother creating a rruleset unless there's a rule
if rruleset is None:
rruleset = rrule.rruleset()
if addfunc is None:
addfunc = getattr(rruleset, name)
if name in DATENAMES:
if type(line.value[0]) == datetime.datetime:
map(addfunc, line.value)
elif type(line.value[0]) == datetime.date:
for dt in line.value:
addfunc(datetime.datetime(dt.year, dt.month, dt.day))
else:
# ignore RDATEs with PERIOD values for now
pass
elif name in RULENAMES:
try:
dtstart = self.dtstart.value
except (AttributeError, KeyError):
# Special for VTODO - try DUE property instead
try:
if self.name == "VTODO":
dtstart = self.due.value
else:
# if there's no dtstart, just return None
print('failed to get dtstart with VTODO')
return None
except (AttributeError, KeyError):
# if there's no due, just return None
print('failed to find DUE at all.')
return None
# a Ruby iCalendar library escapes semi-colons in rrules,
# so also remove any backslashes
value = str_(line.value).replace('\\', '')
rule = rrule.rrulestr(value, dtstart=dtstart)
until = rule._until
if until is not None and isinstance(dtstart, datetime.datetime) and \
(until.tzinfo != dtstart.tzinfo):
# dateutil converts the UNTIL date to a datetime,
# check to see if the UNTIL parameter value was a date
vals = dict(pair.split('=') for pair in
line.value.upper().split(';'))
if len(vals.get('UNTIL', '')) == 8:
until = datetime.datetime.combine(until.date(), dtstart.time())
# While RFC2445 says UNTIL MUST be UTC, Chandler allows
# floating recurring events, and uses floating UNTIL values.
# Also, some odd floating UNTIL but timezoned DTSTART values
# have shown up in the wild, so put floating UNTIL values
# DTSTART's timezone
if until.tzinfo is None:
until = until.replace(tzinfo=dtstart.tzinfo)
if dtstart.tzinfo is not None:
until = until.astimezone(dtstart.tzinfo)
# RFC2445 actually states that UNTIL must be a UTC value. Whilst the
# changes above work OK, one problem case is if DTSTART is floating but
# UNTIL is properly specified as UTC (or with a TZID). In that case dateutil
# will fail datetime comparisons. There is no easy solution to this as
# there is no obvious timezone (at this point) to do proper floating time
# offset compisons. The best we can do is treat the UNTIL value as floating.
# This could mean incorrect determination of the last instance. The better
# solution here is to encourage clients to use COUNT rather than UNTIL
# when DTSTART is floating.
if dtstart.tzinfo is None:
until = until.replace(tzinfo=None)
rule._until = until
# add the rrule or exrule to the rruleset
addfunc(rule)
if name == 'rrule' and addRDate:
try:
# dateutils does not work with all-day (datetime.date) items
# so we need to convert to a datetime.datetime
# (which is what dateutils does internally)
if not isinstance(dtstart, datetime.datetime):
adddtstart = datetime.datetime.fromordinal(dtstart.toordinal())
else:
adddtstart = dtstart
if rruleset._rrule[-1][0] != adddtstart:
rruleset.rdate(adddtstart)
added = True
else:
added = False
except IndexError:
# it's conceivable that an rrule might have 0 datetimes
added = False
if added and rruleset._rrule[-1]._count is not None:
rruleset._rrule[-1]._count -= 1
return rruleset | python | def getrruleset(self, addRDate=False):
"""
Get an rruleset created from self.
If addRDate is True, add an RDATE for dtstart if it's not included in
an RRULE, and count is decremented if it exists.
Note that for rules which don't match DTSTART, DTSTART may not appear
in list(rruleset), although it should. By default, an RDATE is not
created in these cases, and count isn't updated, so dateutil may list
a spurious occurrence.
"""
rruleset = None
for name in DATESANDRULES:
addfunc = None
for line in self.contents.get(name, ()):
# don't bother creating a rruleset unless there's a rule
if rruleset is None:
rruleset = rrule.rruleset()
if addfunc is None:
addfunc = getattr(rruleset, name)
if name in DATENAMES:
if type(line.value[0]) == datetime.datetime:
map(addfunc, line.value)
elif type(line.value[0]) == datetime.date:
for dt in line.value:
addfunc(datetime.datetime(dt.year, dt.month, dt.day))
else:
# ignore RDATEs with PERIOD values for now
pass
elif name in RULENAMES:
try:
dtstart = self.dtstart.value
except (AttributeError, KeyError):
# Special for VTODO - try DUE property instead
try:
if self.name == "VTODO":
dtstart = self.due.value
else:
# if there's no dtstart, just return None
print('failed to get dtstart with VTODO')
return None
except (AttributeError, KeyError):
# if there's no due, just return None
print('failed to find DUE at all.')
return None
# a Ruby iCalendar library escapes semi-colons in rrules,
# so also remove any backslashes
value = str_(line.value).replace('\\', '')
rule = rrule.rrulestr(value, dtstart=dtstart)
until = rule._until
if until is not None and isinstance(dtstart, datetime.datetime) and \
(until.tzinfo != dtstart.tzinfo):
# dateutil converts the UNTIL date to a datetime,
# check to see if the UNTIL parameter value was a date
vals = dict(pair.split('=') for pair in
line.value.upper().split(';'))
if len(vals.get('UNTIL', '')) == 8:
until = datetime.datetime.combine(until.date(), dtstart.time())
# While RFC2445 says UNTIL MUST be UTC, Chandler allows
# floating recurring events, and uses floating UNTIL values.
# Also, some odd floating UNTIL but timezoned DTSTART values
# have shown up in the wild, so put floating UNTIL values
# DTSTART's timezone
if until.tzinfo is None:
until = until.replace(tzinfo=dtstart.tzinfo)
if dtstart.tzinfo is not None:
until = until.astimezone(dtstart.tzinfo)
# RFC2445 actually states that UNTIL must be a UTC value. Whilst the
# changes above work OK, one problem case is if DTSTART is floating but
# UNTIL is properly specified as UTC (or with a TZID). In that case dateutil
# will fail datetime comparisons. There is no easy solution to this as
# there is no obvious timezone (at this point) to do proper floating time
# offset compisons. The best we can do is treat the UNTIL value as floating.
# This could mean incorrect determination of the last instance. The better
# solution here is to encourage clients to use COUNT rather than UNTIL
# when DTSTART is floating.
if dtstart.tzinfo is None:
until = until.replace(tzinfo=None)
rule._until = until
# add the rrule or exrule to the rruleset
addfunc(rule)
if name == 'rrule' and addRDate:
try:
# dateutils does not work with all-day (datetime.date) items
# so we need to convert to a datetime.datetime
# (which is what dateutils does internally)
if not isinstance(dtstart, datetime.datetime):
adddtstart = datetime.datetime.fromordinal(dtstart.toordinal())
else:
adddtstart = dtstart
if rruleset._rrule[-1][0] != adddtstart:
rruleset.rdate(adddtstart)
added = True
else:
added = False
except IndexError:
# it's conceivable that an rrule might have 0 datetimes
added = False
if added and rruleset._rrule[-1]._count is not None:
rruleset._rrule[-1]._count -= 1
return rruleset | [
"def",
"getrruleset",
"(",
"self",
",",
"addRDate",
"=",
"False",
")",
":",
"rruleset",
"=",
"None",
"for",
"name",
"in",
"DATESANDRULES",
":",
"addfunc",
"=",
"None",
"for",
"line",
"in",
"self",
".",
"contents",
".",
"get",
"(",
"name",
",",
"(",
")",
")",
":",
"# don't bother creating a rruleset unless there's a rule",
"if",
"rruleset",
"is",
"None",
":",
"rruleset",
"=",
"rrule",
".",
"rruleset",
"(",
")",
"if",
"addfunc",
"is",
"None",
":",
"addfunc",
"=",
"getattr",
"(",
"rruleset",
",",
"name",
")",
"if",
"name",
"in",
"DATENAMES",
":",
"if",
"type",
"(",
"line",
".",
"value",
"[",
"0",
"]",
")",
"==",
"datetime",
".",
"datetime",
":",
"map",
"(",
"addfunc",
",",
"line",
".",
"value",
")",
"elif",
"type",
"(",
"line",
".",
"value",
"[",
"0",
"]",
")",
"==",
"datetime",
".",
"date",
":",
"for",
"dt",
"in",
"line",
".",
"value",
":",
"addfunc",
"(",
"datetime",
".",
"datetime",
"(",
"dt",
".",
"year",
",",
"dt",
".",
"month",
",",
"dt",
".",
"day",
")",
")",
"else",
":",
"# ignore RDATEs with PERIOD values for now",
"pass",
"elif",
"name",
"in",
"RULENAMES",
":",
"try",
":",
"dtstart",
"=",
"self",
".",
"dtstart",
".",
"value",
"except",
"(",
"AttributeError",
",",
"KeyError",
")",
":",
"# Special for VTODO - try DUE property instead",
"try",
":",
"if",
"self",
".",
"name",
"==",
"\"VTODO\"",
":",
"dtstart",
"=",
"self",
".",
"due",
".",
"value",
"else",
":",
"# if there's no dtstart, just return None",
"print",
"(",
"'failed to get dtstart with VTODO'",
")",
"return",
"None",
"except",
"(",
"AttributeError",
",",
"KeyError",
")",
":",
"# if there's no due, just return None",
"print",
"(",
"'failed to find DUE at all.'",
")",
"return",
"None",
"# a Ruby iCalendar library escapes semi-colons in rrules,",
"# so also remove any backslashes",
"value",
"=",
"str_",
"(",
"line",
".",
"value",
")",
".",
"replace",
"(",
"'\\\\'",
",",
"''",
")",
"rule",
"=",
"rrule",
".",
"rrulestr",
"(",
"value",
",",
"dtstart",
"=",
"dtstart",
")",
"until",
"=",
"rule",
".",
"_until",
"if",
"until",
"is",
"not",
"None",
"and",
"isinstance",
"(",
"dtstart",
",",
"datetime",
".",
"datetime",
")",
"and",
"(",
"until",
".",
"tzinfo",
"!=",
"dtstart",
".",
"tzinfo",
")",
":",
"# dateutil converts the UNTIL date to a datetime,",
"# check to see if the UNTIL parameter value was a date",
"vals",
"=",
"dict",
"(",
"pair",
".",
"split",
"(",
"'='",
")",
"for",
"pair",
"in",
"line",
".",
"value",
".",
"upper",
"(",
")",
".",
"split",
"(",
"';'",
")",
")",
"if",
"len",
"(",
"vals",
".",
"get",
"(",
"'UNTIL'",
",",
"''",
")",
")",
"==",
"8",
":",
"until",
"=",
"datetime",
".",
"datetime",
".",
"combine",
"(",
"until",
".",
"date",
"(",
")",
",",
"dtstart",
".",
"time",
"(",
")",
")",
"# While RFC2445 says UNTIL MUST be UTC, Chandler allows",
"# floating recurring events, and uses floating UNTIL values.",
"# Also, some odd floating UNTIL but timezoned DTSTART values",
"# have shown up in the wild, so put floating UNTIL values",
"# DTSTART's timezone",
"if",
"until",
".",
"tzinfo",
"is",
"None",
":",
"until",
"=",
"until",
".",
"replace",
"(",
"tzinfo",
"=",
"dtstart",
".",
"tzinfo",
")",
"if",
"dtstart",
".",
"tzinfo",
"is",
"not",
"None",
":",
"until",
"=",
"until",
".",
"astimezone",
"(",
"dtstart",
".",
"tzinfo",
")",
"# RFC2445 actually states that UNTIL must be a UTC value. Whilst the",
"# changes above work OK, one problem case is if DTSTART is floating but",
"# UNTIL is properly specified as UTC (or with a TZID). In that case dateutil",
"# will fail datetime comparisons. There is no easy solution to this as",
"# there is no obvious timezone (at this point) to do proper floating time",
"# offset compisons. The best we can do is treat the UNTIL value as floating.",
"# This could mean incorrect determination of the last instance. The better",
"# solution here is to encourage clients to use COUNT rather than UNTIL",
"# when DTSTART is floating.",
"if",
"dtstart",
".",
"tzinfo",
"is",
"None",
":",
"until",
"=",
"until",
".",
"replace",
"(",
"tzinfo",
"=",
"None",
")",
"rule",
".",
"_until",
"=",
"until",
"# add the rrule or exrule to the rruleset",
"addfunc",
"(",
"rule",
")",
"if",
"name",
"==",
"'rrule'",
"and",
"addRDate",
":",
"try",
":",
"# dateutils does not work with all-day (datetime.date) items",
"# so we need to convert to a datetime.datetime",
"# (which is what dateutils does internally)",
"if",
"not",
"isinstance",
"(",
"dtstart",
",",
"datetime",
".",
"datetime",
")",
":",
"adddtstart",
"=",
"datetime",
".",
"datetime",
".",
"fromordinal",
"(",
"dtstart",
".",
"toordinal",
"(",
")",
")",
"else",
":",
"adddtstart",
"=",
"dtstart",
"if",
"rruleset",
".",
"_rrule",
"[",
"-",
"1",
"]",
"[",
"0",
"]",
"!=",
"adddtstart",
":",
"rruleset",
".",
"rdate",
"(",
"adddtstart",
")",
"added",
"=",
"True",
"else",
":",
"added",
"=",
"False",
"except",
"IndexError",
":",
"# it's conceivable that an rrule might have 0 datetimes",
"added",
"=",
"False",
"if",
"added",
"and",
"rruleset",
".",
"_rrule",
"[",
"-",
"1",
"]",
".",
"_count",
"is",
"not",
"None",
":",
"rruleset",
".",
"_rrule",
"[",
"-",
"1",
"]",
".",
"_count",
"-=",
"1",
"return",
"rruleset"
]
| Get an rruleset created from self.
If addRDate is True, add an RDATE for dtstart if it's not included in
an RRULE, and count is decremented if it exists.
Note that for rules which don't match DTSTART, DTSTART may not appear
in list(rruleset), although it should. By default, an RDATE is not
created in these cases, and count isn't updated, so dateutil may list
a spurious occurrence. | [
"Get",
"an",
"rruleset",
"created",
"from",
"self",
"."
]
| ffebc7fed44f83983b7438e57263dcda67207664 | https://github.com/tBaxter/python-card-me/blob/ffebc7fed44f83983b7438e57263dcda67207664/card_me/icalendar.py#L361-L471 | train |
tBaxter/python-card-me | card_me/icalendar.py | DateTimeBehavior.transformToNative | def transformToNative(obj):
"""Turn obj.value into a datetime.
RFC2445 allows times without time zone information, "floating times"
in some properties. Mostly, this isn't what you want, but when parsing
a file, real floating times are noted by setting to 'TRUE' the
X-VOBJ-FLOATINGTIME-ALLOWED parameter.
"""
if obj.isNative:
return obj
obj.isNative = True
if obj.value == '':
return obj
obj.value = obj.value
#we're cheating a little here, parseDtstart allows DATE
obj.value = parseDtstart(obj)
if obj.value.tzinfo is None:
obj.params['X-VOBJ-FLOATINGTIME-ALLOWED'] = ['TRUE']
if obj.params.get('TZID'):
# Keep a copy of the original TZID around
obj.params['X-VOBJ-ORIGINAL-TZID'] = [obj.params['TZID']]
del obj.params['TZID']
return obj | python | def transformToNative(obj):
"""Turn obj.value into a datetime.
RFC2445 allows times without time zone information, "floating times"
in some properties. Mostly, this isn't what you want, but when parsing
a file, real floating times are noted by setting to 'TRUE' the
X-VOBJ-FLOATINGTIME-ALLOWED parameter.
"""
if obj.isNative:
return obj
obj.isNative = True
if obj.value == '':
return obj
obj.value = obj.value
#we're cheating a little here, parseDtstart allows DATE
obj.value = parseDtstart(obj)
if obj.value.tzinfo is None:
obj.params['X-VOBJ-FLOATINGTIME-ALLOWED'] = ['TRUE']
if obj.params.get('TZID'):
# Keep a copy of the original TZID around
obj.params['X-VOBJ-ORIGINAL-TZID'] = [obj.params['TZID']]
del obj.params['TZID']
return obj | [
"def",
"transformToNative",
"(",
"obj",
")",
":",
"if",
"obj",
".",
"isNative",
":",
"return",
"obj",
"obj",
".",
"isNative",
"=",
"True",
"if",
"obj",
".",
"value",
"==",
"''",
":",
"return",
"obj",
"obj",
".",
"value",
"=",
"obj",
".",
"value",
"#we're cheating a little here, parseDtstart allows DATE",
"obj",
".",
"value",
"=",
"parseDtstart",
"(",
"obj",
")",
"if",
"obj",
".",
"value",
".",
"tzinfo",
"is",
"None",
":",
"obj",
".",
"params",
"[",
"'X-VOBJ-FLOATINGTIME-ALLOWED'",
"]",
"=",
"[",
"'TRUE'",
"]",
"if",
"obj",
".",
"params",
".",
"get",
"(",
"'TZID'",
")",
":",
"# Keep a copy of the original TZID around",
"obj",
".",
"params",
"[",
"'X-VOBJ-ORIGINAL-TZID'",
"]",
"=",
"[",
"obj",
".",
"params",
"[",
"'TZID'",
"]",
"]",
"del",
"obj",
".",
"params",
"[",
"'TZID'",
"]",
"return",
"obj"
]
| Turn obj.value into a datetime.
RFC2445 allows times without time zone information, "floating times"
in some properties. Mostly, this isn't what you want, but when parsing
a file, real floating times are noted by setting to 'TRUE' the
X-VOBJ-FLOATINGTIME-ALLOWED parameter. | [
"Turn",
"obj",
".",
"value",
"into",
"a",
"datetime",
"."
]
| ffebc7fed44f83983b7438e57263dcda67207664 | https://github.com/tBaxter/python-card-me/blob/ffebc7fed44f83983b7438e57263dcda67207664/card_me/icalendar.py#L669-L692 | train |
tBaxter/python-card-me | card_me/icalendar.py | DateTimeBehavior.transformFromNative | def transformFromNative(cls, obj):
"""Replace the datetime in obj.value with an ISO 8601 string."""
# print('transforming from native')
if obj.isNative:
obj.isNative = False
tzid = TimezoneComponent.registerTzinfo(obj.value.tzinfo)
obj.value = dateTimeToString(obj.value, cls.forceUTC)
if not cls.forceUTC and tzid is not None:
obj.tzid_param = tzid
if obj.params.get('X-VOBJ-ORIGINAL-TZID'):
if not hasattr(obj, 'tzid_param'):
obj.tzid_param = obj.x_vobj_original_tzid_param
del obj.params['X-VOBJ-ORIGINAL-TZID']
return obj | python | def transformFromNative(cls, obj):
"""Replace the datetime in obj.value with an ISO 8601 string."""
# print('transforming from native')
if obj.isNative:
obj.isNative = False
tzid = TimezoneComponent.registerTzinfo(obj.value.tzinfo)
obj.value = dateTimeToString(obj.value, cls.forceUTC)
if not cls.forceUTC and tzid is not None:
obj.tzid_param = tzid
if obj.params.get('X-VOBJ-ORIGINAL-TZID'):
if not hasattr(obj, 'tzid_param'):
obj.tzid_param = obj.x_vobj_original_tzid_param
del obj.params['X-VOBJ-ORIGINAL-TZID']
return obj | [
"def",
"transformFromNative",
"(",
"cls",
",",
"obj",
")",
":",
"# print('transforming from native')",
"if",
"obj",
".",
"isNative",
":",
"obj",
".",
"isNative",
"=",
"False",
"tzid",
"=",
"TimezoneComponent",
".",
"registerTzinfo",
"(",
"obj",
".",
"value",
".",
"tzinfo",
")",
"obj",
".",
"value",
"=",
"dateTimeToString",
"(",
"obj",
".",
"value",
",",
"cls",
".",
"forceUTC",
")",
"if",
"not",
"cls",
".",
"forceUTC",
"and",
"tzid",
"is",
"not",
"None",
":",
"obj",
".",
"tzid_param",
"=",
"tzid",
"if",
"obj",
".",
"params",
".",
"get",
"(",
"'X-VOBJ-ORIGINAL-TZID'",
")",
":",
"if",
"not",
"hasattr",
"(",
"obj",
",",
"'tzid_param'",
")",
":",
"obj",
".",
"tzid_param",
"=",
"obj",
".",
"x_vobj_original_tzid_param",
"del",
"obj",
".",
"params",
"[",
"'X-VOBJ-ORIGINAL-TZID'",
"]",
"return",
"obj"
]
| Replace the datetime in obj.value with an ISO 8601 string. | [
"Replace",
"the",
"datetime",
"in",
"obj",
".",
"value",
"with",
"an",
"ISO",
"8601",
"string",
"."
]
| ffebc7fed44f83983b7438e57263dcda67207664 | https://github.com/tBaxter/python-card-me/blob/ffebc7fed44f83983b7438e57263dcda67207664/card_me/icalendar.py#L695-L709 | train |
Egregors/cbrf | cbrf/api.py | get_currencies_info | def get_currencies_info() -> Element:
"""Get META information about currencies
url: http://www.cbr.ru/scripts/XML_val.asp
:return: :class: `Element <Element 'Valuta'>` object
:rtype: ElementTree.Element
"""
response = requests.get(const.CBRF_API_URLS['info'])
return XML(response.text) | python | def get_currencies_info() -> Element:
"""Get META information about currencies
url: http://www.cbr.ru/scripts/XML_val.asp
:return: :class: `Element <Element 'Valuta'>` object
:rtype: ElementTree.Element
"""
response = requests.get(const.CBRF_API_URLS['info'])
return XML(response.text) | [
"def",
"get_currencies_info",
"(",
")",
"->",
"Element",
":",
"response",
"=",
"requests",
".",
"get",
"(",
"const",
".",
"CBRF_API_URLS",
"[",
"'info'",
"]",
")",
"return",
"XML",
"(",
"response",
".",
"text",
")"
]
| Get META information about currencies
url: http://www.cbr.ru/scripts/XML_val.asp
:return: :class: `Element <Element 'Valuta'>` object
:rtype: ElementTree.Element | [
"Get",
"META",
"information",
"about",
"currencies"
]
| e4ce332fcead83c75966337c97c0ae070fb7e576 | https://github.com/Egregors/cbrf/blob/e4ce332fcead83c75966337c97c0ae070fb7e576/cbrf/api.py#L22-L32 | train |
Egregors/cbrf | cbrf/api.py | get_daily_rates | def get_daily_rates(date_req: datetime.datetime = None, lang: str = 'rus') -> Element:
""" Getting currency for current day.
see example: http://www.cbr.ru/scripts/Root.asp?PrtId=SXML
:param date_req:
:type date_req: datetime.datetime
:param lang: language of API response ('eng' || 'rus')
:type lang: str
:return: :class: `Element <Element 'ValCurs'>` object
:rtype: ElementTree.Element
"""
if lang not in ['rus', 'eng']:
raise ValueError('"lang" must be string. "rus" or "eng"')
base_url = const.CBRF_API_URLS['daily_rus'] if lang == 'rus' \
else const.CBRF_API_URLS['daily_eng']
url = base_url + 'date_req=' + utils.date_to_str(date_req) if date_req else base_url
response = requests.get(url=url)
return XML(response.text) | python | def get_daily_rates(date_req: datetime.datetime = None, lang: str = 'rus') -> Element:
""" Getting currency for current day.
see example: http://www.cbr.ru/scripts/Root.asp?PrtId=SXML
:param date_req:
:type date_req: datetime.datetime
:param lang: language of API response ('eng' || 'rus')
:type lang: str
:return: :class: `Element <Element 'ValCurs'>` object
:rtype: ElementTree.Element
"""
if lang not in ['rus', 'eng']:
raise ValueError('"lang" must be string. "rus" or "eng"')
base_url = const.CBRF_API_URLS['daily_rus'] if lang == 'rus' \
else const.CBRF_API_URLS['daily_eng']
url = base_url + 'date_req=' + utils.date_to_str(date_req) if date_req else base_url
response = requests.get(url=url)
return XML(response.text) | [
"def",
"get_daily_rates",
"(",
"date_req",
":",
"datetime",
".",
"datetime",
"=",
"None",
",",
"lang",
":",
"str",
"=",
"'rus'",
")",
"->",
"Element",
":",
"if",
"lang",
"not",
"in",
"[",
"'rus'",
",",
"'eng'",
"]",
":",
"raise",
"ValueError",
"(",
"'\"lang\" must be string. \"rus\" or \"eng\"'",
")",
"base_url",
"=",
"const",
".",
"CBRF_API_URLS",
"[",
"'daily_rus'",
"]",
"if",
"lang",
"==",
"'rus'",
"else",
"const",
".",
"CBRF_API_URLS",
"[",
"'daily_eng'",
"]",
"url",
"=",
"base_url",
"+",
"'date_req='",
"+",
"utils",
".",
"date_to_str",
"(",
"date_req",
")",
"if",
"date_req",
"else",
"base_url",
"response",
"=",
"requests",
".",
"get",
"(",
"url",
"=",
"url",
")",
"return",
"XML",
"(",
"response",
".",
"text",
")"
]
| Getting currency for current day.
see example: http://www.cbr.ru/scripts/Root.asp?PrtId=SXML
:param date_req:
:type date_req: datetime.datetime
:param lang: language of API response ('eng' || 'rus')
:type lang: str
:return: :class: `Element <Element 'ValCurs'>` object
:rtype: ElementTree.Element | [
"Getting",
"currency",
"for",
"current",
"day",
"."
]
| e4ce332fcead83c75966337c97c0ae070fb7e576 | https://github.com/Egregors/cbrf/blob/e4ce332fcead83c75966337c97c0ae070fb7e576/cbrf/api.py#L35-L58 | train |
stu-gott/pykira | pykira/utils.py | mangleIR | def mangleIR(data, ignore_errors=False):
"""Mangle a raw Kira data packet into shorthand"""
try:
# Packet mangling algorithm inspired by Rex Becket's kirarx vera plugin
# Determine a median value for the timing packets and categorize each
# timing as longer or shorter than that. This will always work for signals
# that use pulse width modulation (since varying by long-short is basically
# the definition of what PWM is). By lucky coincidence this also works with
# the RC-5/RC-6 encodings used by Phillips (manchester encoding)
# because time variations of opposite-phase/same-phase are either N or 2*N
if isinstance(data, bytes):
data = data.decode('ascii')
data = data.strip()
times = [int(x, 16) for x in data.split()[2:]]
minTime = min(times[2:-1])
maxTime = max(times[2:-1])
margin = (maxTime - minTime) / 2 + minTime
return ''.join([(x < margin and 'S' or 'L') for x in times])
except:
# Probably a mangled packet.
if not ignore_errors:
raise | python | def mangleIR(data, ignore_errors=False):
"""Mangle a raw Kira data packet into shorthand"""
try:
# Packet mangling algorithm inspired by Rex Becket's kirarx vera plugin
# Determine a median value for the timing packets and categorize each
# timing as longer or shorter than that. This will always work for signals
# that use pulse width modulation (since varying by long-short is basically
# the definition of what PWM is). By lucky coincidence this also works with
# the RC-5/RC-6 encodings used by Phillips (manchester encoding)
# because time variations of opposite-phase/same-phase are either N or 2*N
if isinstance(data, bytes):
data = data.decode('ascii')
data = data.strip()
times = [int(x, 16) for x in data.split()[2:]]
minTime = min(times[2:-1])
maxTime = max(times[2:-1])
margin = (maxTime - minTime) / 2 + minTime
return ''.join([(x < margin and 'S' or 'L') for x in times])
except:
# Probably a mangled packet.
if not ignore_errors:
raise | [
"def",
"mangleIR",
"(",
"data",
",",
"ignore_errors",
"=",
"False",
")",
":",
"try",
":",
"# Packet mangling algorithm inspired by Rex Becket's kirarx vera plugin",
"# Determine a median value for the timing packets and categorize each",
"# timing as longer or shorter than that. This will always work for signals",
"# that use pulse width modulation (since varying by long-short is basically",
"# the definition of what PWM is). By lucky coincidence this also works with",
"# the RC-5/RC-6 encodings used by Phillips (manchester encoding)",
"# because time variations of opposite-phase/same-phase are either N or 2*N",
"if",
"isinstance",
"(",
"data",
",",
"bytes",
")",
":",
"data",
"=",
"data",
".",
"decode",
"(",
"'ascii'",
")",
"data",
"=",
"data",
".",
"strip",
"(",
")",
"times",
"=",
"[",
"int",
"(",
"x",
",",
"16",
")",
"for",
"x",
"in",
"data",
".",
"split",
"(",
")",
"[",
"2",
":",
"]",
"]",
"minTime",
"=",
"min",
"(",
"times",
"[",
"2",
":",
"-",
"1",
"]",
")",
"maxTime",
"=",
"max",
"(",
"times",
"[",
"2",
":",
"-",
"1",
"]",
")",
"margin",
"=",
"(",
"maxTime",
"-",
"minTime",
")",
"/",
"2",
"+",
"minTime",
"return",
"''",
".",
"join",
"(",
"[",
"(",
"x",
"<",
"margin",
"and",
"'S'",
"or",
"'L'",
")",
"for",
"x",
"in",
"times",
"]",
")",
"except",
":",
"# Probably a mangled packet.",
"if",
"not",
"ignore_errors",
":",
"raise"
]
| Mangle a raw Kira data packet into shorthand | [
"Mangle",
"a",
"raw",
"Kira",
"data",
"packet",
"into",
"shorthand"
]
| b48522ceed694a5393ac4ed8c9a6f11c20f7b150 | https://github.com/stu-gott/pykira/blob/b48522ceed694a5393ac4ed8c9a6f11c20f7b150/pykira/utils.py#L7-L28 | train |
stu-gott/pykira | pykira/utils.py | mangleNec | def mangleNec(code, freq=40):
"""Convert NEC code to shorthand notation"""
# base time is 550 microseconds
# unit of burst time
# lead in pattern: 214d 10b3
# "1" burst pattern: 0226 0960
# "0" burst pattern: 0226 0258
# lead out pattern: 0226 2000
# there's large disagreement between devices as to a common preamble
# or the "long" off period for the representation of a binary 1
# thus we can't construct a code suitable for transmission
# without more information--but it's good enough for creating
# a shorthand representaiton for use with recv
timings = []
for octet in binascii.unhexlify(code.replace(" ", "")):
burst = lambda x: x and "0226 06AD" or "0226 0258"
for bit in reversed("%08d" % int(bin(ord(octet))[2:])):
bit = int(bit)
timings.append(burst(bit))
return mangleIR("K %0X22 214d 10b3 " % freq + " ".join(timings) + " 0226 2000") | python | def mangleNec(code, freq=40):
"""Convert NEC code to shorthand notation"""
# base time is 550 microseconds
# unit of burst time
# lead in pattern: 214d 10b3
# "1" burst pattern: 0226 0960
# "0" burst pattern: 0226 0258
# lead out pattern: 0226 2000
# there's large disagreement between devices as to a common preamble
# or the "long" off period for the representation of a binary 1
# thus we can't construct a code suitable for transmission
# without more information--but it's good enough for creating
# a shorthand representaiton for use with recv
timings = []
for octet in binascii.unhexlify(code.replace(" ", "")):
burst = lambda x: x and "0226 06AD" or "0226 0258"
for bit in reversed("%08d" % int(bin(ord(octet))[2:])):
bit = int(bit)
timings.append(burst(bit))
return mangleIR("K %0X22 214d 10b3 " % freq + " ".join(timings) + " 0226 2000") | [
"def",
"mangleNec",
"(",
"code",
",",
"freq",
"=",
"40",
")",
":",
"# base time is 550 microseconds",
"# unit of burst time",
"# lead in pattern: 214d 10b3",
"# \"1\" burst pattern: 0226 0960",
"# \"0\" burst pattern: 0226 0258",
"# lead out pattern: 0226 2000",
"# there's large disagreement between devices as to a common preamble",
"# or the \"long\" off period for the representation of a binary 1",
"# thus we can't construct a code suitable for transmission",
"# without more information--but it's good enough for creating",
"# a shorthand representaiton for use with recv",
"timings",
"=",
"[",
"]",
"for",
"octet",
"in",
"binascii",
".",
"unhexlify",
"(",
"code",
".",
"replace",
"(",
"\" \"",
",",
"\"\"",
")",
")",
":",
"burst",
"=",
"lambda",
"x",
":",
"x",
"and",
"\"0226 06AD\"",
"or",
"\"0226 0258\"",
"for",
"bit",
"in",
"reversed",
"(",
"\"%08d\"",
"%",
"int",
"(",
"bin",
"(",
"ord",
"(",
"octet",
")",
")",
"[",
"2",
":",
"]",
")",
")",
":",
"bit",
"=",
"int",
"(",
"bit",
")",
"timings",
".",
"append",
"(",
"burst",
"(",
"bit",
")",
")",
"return",
"mangleIR",
"(",
"\"K %0X22 214d 10b3 \"",
"%",
"freq",
"+",
"\" \"",
".",
"join",
"(",
"timings",
")",
"+",
"\" 0226 2000\"",
")"
]
| Convert NEC code to shorthand notation | [
"Convert",
"NEC",
"code",
"to",
"shorthand",
"notation"
]
| b48522ceed694a5393ac4ed8c9a6f11c20f7b150 | https://github.com/stu-gott/pykira/blob/b48522ceed694a5393ac4ed8c9a6f11c20f7b150/pykira/utils.py#L46-L65 | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.