repository_name stringlengths 7 55 | func_path_in_repository stringlengths 4 223 | func_name stringlengths 1 134 | whole_func_string stringlengths 75 104k | language stringclasses 1
value | func_code_string stringlengths 75 104k | func_code_tokens listlengths 19 28.4k | func_documentation_string stringlengths 1 46.9k | func_documentation_tokens listlengths 1 1.97k | split_name stringclasses 1
value | func_code_url stringlengths 87 315 |
|---|---|---|---|---|---|---|---|---|---|---|
useblocks/sphinxcontrib-needs | sphinxcontrib/needs/directives/need.py | html_visit | def html_visit(self, node):
"""
Visitor method for Need-node of builder 'html'.
Does only wrap the Need-content into an extra <div> with class=need
"""
self.body.append(self.starttag(node, 'div', '', CLASS='need')) | python | def html_visit(self, node):
"""
Visitor method for Need-node of builder 'html'.
Does only wrap the Need-content into an extra <div> with class=need
"""
self.body.append(self.starttag(node, 'div', '', CLASS='need')) | [
"def",
"html_visit",
"(",
"self",
",",
"node",
")",
":",
"self",
".",
"body",
".",
"append",
"(",
"self",
".",
"starttag",
"(",
"node",
",",
"'div'",
",",
"''",
",",
"CLASS",
"=",
"'need'",
")",
")"
] | Visitor method for Need-node of builder 'html'.
Does only wrap the Need-content into an extra <div> with class=need | [
"Visitor",
"method",
"for",
"Need",
"-",
"node",
"of",
"builder",
"html",
".",
"Does",
"only",
"wrap",
"the",
"Need",
"-",
"content",
"into",
"an",
"extra",
"<div",
">",
"with",
"class",
"=",
"need"
] | train | https://github.com/useblocks/sphinxcontrib-needs/blob/f49af4859a74e9fe76de5b9133c01335ac6ae191/sphinxcontrib/needs/directives/need.py#L662-L667 |
useblocks/sphinxcontrib-needs | sphinxcontrib/needs/directives/need.py | NeedDirective.merge_extra_options | def merge_extra_options(self, needs_info):
"""Add any extra options introduced via options_ext to needs_info"""
extra_keys = set(self.options.keys()).difference(set(needs_info.keys()))
for key in extra_keys:
needs_info[key] = self.options[key]
# Finally add all not used extr... | python | def merge_extra_options(self, needs_info):
"""Add any extra options introduced via options_ext to needs_info"""
extra_keys = set(self.options.keys()).difference(set(needs_info.keys()))
for key in extra_keys:
needs_info[key] = self.options[key]
# Finally add all not used extr... | [
"def",
"merge_extra_options",
"(",
"self",
",",
"needs_info",
")",
":",
"extra_keys",
"=",
"set",
"(",
"self",
".",
"options",
".",
"keys",
"(",
")",
")",
".",
"difference",
"(",
"set",
"(",
"needs_info",
".",
"keys",
"(",
")",
")",
")",
"for",
"key"... | Add any extra options introduced via options_ext to needs_info | [
"Add",
"any",
"extra",
"options",
"introduced",
"via",
"options_ext",
"to",
"needs_info"
] | train | https://github.com/useblocks/sphinxcontrib-needs/blob/f49af4859a74e9fe76de5b9133c01335ac6ae191/sphinxcontrib/needs/directives/need.py#L299-L311 |
useblocks/sphinxcontrib-needs | sphinxcontrib/needs/directives/need.py | NeedDirective.merge_global_options | def merge_global_options(self, needs_info):
"""Add all global defined options to needs_info"""
global_options = getattr(self.env.app.config, 'needs_global_options', None)
if global_options is None:
return
for key, value in global_options.items():
# If key already... | python | def merge_global_options(self, needs_info):
"""Add all global defined options to needs_info"""
global_options = getattr(self.env.app.config, 'needs_global_options', None)
if global_options is None:
return
for key, value in global_options.items():
# If key already... | [
"def",
"merge_global_options",
"(",
"self",
",",
"needs_info",
")",
":",
"global_options",
"=",
"getattr",
"(",
"self",
".",
"env",
".",
"app",
".",
"config",
",",
"'needs_global_options'",
",",
"None",
")",
"if",
"global_options",
"is",
"None",
":",
"return... | Add all global defined options to needs_info | [
"Add",
"all",
"global",
"defined",
"options",
"to",
"needs_info"
] | train | https://github.com/useblocks/sphinxcontrib-needs/blob/f49af4859a74e9fe76de5b9133c01335ac6ae191/sphinxcontrib/needs/directives/need.py#L313-L324 |
useblocks/sphinxcontrib-needs | sphinxcontrib/needs/directives/need.py | NeedDirective._get_full_title | def _get_full_title(self):
"""Determines the title for the need in order of precedence:
directive argument, first sentence of requirement (if
`:title_from_content:` was set, and '' if no title is to be derived."""
if len(self.arguments) > 0: # a title was passed
if 'title_fr... | python | def _get_full_title(self):
"""Determines the title for the need in order of precedence:
directive argument, first sentence of requirement (if
`:title_from_content:` was set, and '' if no title is to be derived."""
if len(self.arguments) > 0: # a title was passed
if 'title_fr... | [
"def",
"_get_full_title",
"(",
"self",
")",
":",
"if",
"len",
"(",
"self",
".",
"arguments",
")",
">",
"0",
":",
"# a title was passed",
"if",
"'title_from_content'",
"in",
"self",
".",
"options",
":",
"self",
".",
"log",
".",
"warning",
"(",
"'Needs: need... | Determines the title for the need in order of precedence:
directive argument, first sentence of requirement (if
`:title_from_content:` was set, and '' if no title is to be derived. | [
"Determines",
"the",
"title",
"for",
"the",
"need",
"in",
"order",
"of",
"precedence",
":",
"directive",
"argument",
"first",
"sentence",
"of",
"requirement",
"(",
"if",
":",
"title_from_content",
":",
"was",
"set",
"and",
"if",
"no",
"title",
"is",
"to",
... | train | https://github.com/useblocks/sphinxcontrib-needs/blob/f49af4859a74e9fe76de5b9133c01335ac6ae191/sphinxcontrib/needs/directives/need.py#L326-L347 |
useblocks/sphinxcontrib-needs | sphinxcontrib/needs/directives/needlist.py | process_needlist | def process_needlist(app, doctree, fromdocname):
"""
Replace all needlist nodes with a list of the collected needs.
Augment each need with a backlink to the original location.
"""
env = app.builder.env
for node in doctree.traverse(Needlist):
if not app.config.needs_include_needs:
... | python | def process_needlist(app, doctree, fromdocname):
"""
Replace all needlist nodes with a list of the collected needs.
Augment each need with a backlink to the original location.
"""
env = app.builder.env
for node in doctree.traverse(Needlist):
if not app.config.needs_include_needs:
... | [
"def",
"process_needlist",
"(",
"app",
",",
"doctree",
",",
"fromdocname",
")",
":",
"env",
"=",
"app",
".",
"builder",
".",
"env",
"for",
"node",
"in",
"doctree",
".",
"traverse",
"(",
"Needlist",
")",
":",
"if",
"not",
"app",
".",
"config",
".",
"n... | Replace all needlist nodes with a list of the collected needs.
Augment each need with a backlink to the original location. | [
"Replace",
"all",
"needlist",
"nodes",
"with",
"a",
"list",
"of",
"the",
"collected",
"needs",
".",
"Augment",
"each",
"need",
"with",
"a",
"backlink",
"to",
"the",
"original",
"location",
"."
] | train | https://github.com/useblocks/sphinxcontrib-needs/blob/f49af4859a74e9fe76de5b9133c01335ac6ae191/sphinxcontrib/needs/directives/needlist.py#L69-L135 |
mfussenegger/cr8 | cr8/misc.py | parse_version | def parse_version(version: str) -> tuple:
"""Parse a string formatted X[.Y.Z] version number into a tuple
>>> parse_version('10.2.3')
(10, 2, 3)
>>> parse_version('12')
(12, 0, 0)
"""
if not version:
return None
parts = version.split('.')
missing = 3 - len(parts)
return... | python | def parse_version(version: str) -> tuple:
"""Parse a string formatted X[.Y.Z] version number into a tuple
>>> parse_version('10.2.3')
(10, 2, 3)
>>> parse_version('12')
(12, 0, 0)
"""
if not version:
return None
parts = version.split('.')
missing = 3 - len(parts)
return... | [
"def",
"parse_version",
"(",
"version",
":",
"str",
")",
"->",
"tuple",
":",
"if",
"not",
"version",
":",
"return",
"None",
"parts",
"=",
"version",
".",
"split",
"(",
"'.'",
")",
"missing",
"=",
"3",
"-",
"len",
"(",
"parts",
")",
"return",
"tuple",... | Parse a string formatted X[.Y.Z] version number into a tuple
>>> parse_version('10.2.3')
(10, 2, 3)
>>> parse_version('12')
(12, 0, 0) | [
"Parse",
"a",
"string",
"formatted",
"X",
"[",
".",
"Y",
".",
"Z",
"]",
"version",
"number",
"into",
"a",
"tuple"
] | train | https://github.com/mfussenegger/cr8/blob/a37d6049f1f9fee2d0556efae2b7b7f8761bffe8/cr8/misc.py#L33-L46 |
mfussenegger/cr8 | cr8/misc.py | parse_table | def parse_table(fq_table: str) -> Tuple[str, str]:
"""Parse a tablename into tuple(<schema>, <table>).
Schema defaults to doc if the table name doesn't contain a schema.
>>> parse_table('x.users')
('x', 'users')
>>> parse_table('users')
('doc', 'users')
"""
parts = fq_table.split('.')... | python | def parse_table(fq_table: str) -> Tuple[str, str]:
"""Parse a tablename into tuple(<schema>, <table>).
Schema defaults to doc if the table name doesn't contain a schema.
>>> parse_table('x.users')
('x', 'users')
>>> parse_table('users')
('doc', 'users')
"""
parts = fq_table.split('.')... | [
"def",
"parse_table",
"(",
"fq_table",
":",
"str",
")",
"->",
"Tuple",
"[",
"str",
",",
"str",
"]",
":",
"parts",
"=",
"fq_table",
".",
"split",
"(",
"'.'",
")",
"if",
"len",
"(",
"parts",
")",
"==",
"1",
":",
"return",
"'doc'",
",",
"parts",
"["... | Parse a tablename into tuple(<schema>, <table>).
Schema defaults to doc if the table name doesn't contain a schema.
>>> parse_table('x.users')
('x', 'users')
>>> parse_table('users')
('doc', 'users') | [
"Parse",
"a",
"tablename",
"into",
"tuple",
"(",
"<schema",
">",
"<table",
">",
")",
"."
] | train | https://github.com/mfussenegger/cr8/blob/a37d6049f1f9fee2d0556efae2b7b7f8761bffe8/cr8/misc.py#L49-L66 |
mfussenegger/cr8 | cr8/misc.py | as_bulk_queries | def as_bulk_queries(queries, bulk_size):
"""Group a iterable of (stmt, args) by stmt into (stmt, bulk_args).
bulk_args will be a list of the args grouped by stmt.
len(bulk_args) will be <= bulk_size
"""
stmt_dict = defaultdict(list)
for stmt, args in queries:
bulk_args = stmt_dict[stmt... | python | def as_bulk_queries(queries, bulk_size):
"""Group a iterable of (stmt, args) by stmt into (stmt, bulk_args).
bulk_args will be a list of the args grouped by stmt.
len(bulk_args) will be <= bulk_size
"""
stmt_dict = defaultdict(list)
for stmt, args in queries:
bulk_args = stmt_dict[stmt... | [
"def",
"as_bulk_queries",
"(",
"queries",
",",
"bulk_size",
")",
":",
"stmt_dict",
"=",
"defaultdict",
"(",
"list",
")",
"for",
"stmt",
",",
"args",
"in",
"queries",
":",
"bulk_args",
"=",
"stmt_dict",
"[",
"stmt",
"]",
"bulk_args",
".",
"append",
"(",
"... | Group a iterable of (stmt, args) by stmt into (stmt, bulk_args).
bulk_args will be a list of the args grouped by stmt.
len(bulk_args) will be <= bulk_size | [
"Group",
"a",
"iterable",
"of",
"(",
"stmt",
"args",
")",
"by",
"stmt",
"into",
"(",
"stmt",
"bulk_args",
")",
"."
] | train | https://github.com/mfussenegger/cr8/blob/a37d6049f1f9fee2d0556efae2b7b7f8761bffe8/cr8/misc.py#L69-L84 |
mfussenegger/cr8 | cr8/misc.py | get_lines | def get_lines(filename: str) -> Iterator[str]:
"""Create an iterator that returns the lines of a utf-8 encoded file."""
if filename.endswith('.gz'):
with gzip.open(filename, 'r') as f:
for line in f:
yield line.decode('utf-8')
else:
with open(filename, 'r', encodi... | python | def get_lines(filename: str) -> Iterator[str]:
"""Create an iterator that returns the lines of a utf-8 encoded file."""
if filename.endswith('.gz'):
with gzip.open(filename, 'r') as f:
for line in f:
yield line.decode('utf-8')
else:
with open(filename, 'r', encodi... | [
"def",
"get_lines",
"(",
"filename",
":",
"str",
")",
"->",
"Iterator",
"[",
"str",
"]",
":",
"if",
"filename",
".",
"endswith",
"(",
"'.gz'",
")",
":",
"with",
"gzip",
".",
"open",
"(",
"filename",
",",
"'r'",
")",
"as",
"f",
":",
"for",
"line",
... | Create an iterator that returns the lines of a utf-8 encoded file. | [
"Create",
"an",
"iterator",
"that",
"returns",
"the",
"lines",
"of",
"a",
"utf",
"-",
"8",
"encoded",
"file",
"."
] | train | https://github.com/mfussenegger/cr8/blob/a37d6049f1f9fee2d0556efae2b7b7f8761bffe8/cr8/misc.py#L87-L96 |
mfussenegger/cr8 | cr8/misc.py | as_statements | def as_statements(lines: Iterator[str]) -> Iterator[str]:
"""Create an iterator that transforms lines into sql statements.
Statements within the lines must end with ";"
The last statement will be included even if it does not end in ';'
>>> list(as_statements(['select * from', '-- comments are filtered... | python | def as_statements(lines: Iterator[str]) -> Iterator[str]:
"""Create an iterator that transforms lines into sql statements.
Statements within the lines must end with ";"
The last statement will be included even if it does not end in ';'
>>> list(as_statements(['select * from', '-- comments are filtered... | [
"def",
"as_statements",
"(",
"lines",
":",
"Iterator",
"[",
"str",
"]",
")",
"->",
"Iterator",
"[",
"str",
"]",
":",
"lines",
"=",
"(",
"l",
".",
"strip",
"(",
")",
"for",
"l",
"in",
"lines",
"if",
"l",
")",
"lines",
"=",
"(",
"l",
"for",
"l",
... | Create an iterator that transforms lines into sql statements.
Statements within the lines must end with ";"
The last statement will be included even if it does not end in ';'
>>> list(as_statements(['select * from', '-- comments are filtered', 't;']))
['select * from t']
>>> list(as_statements(['... | [
"Create",
"an",
"iterator",
"that",
"transforms",
"lines",
"into",
"sql",
"statements",
"."
] | train | https://github.com/mfussenegger/cr8/blob/a37d6049f1f9fee2d0556efae2b7b7f8761bffe8/cr8/misc.py#L99-L120 |
mfussenegger/cr8 | cr8/misc.py | break_iterable | def break_iterable(iterable, pred):
"""Break a iterable on the item that matches the predicate into lists.
The item that matched the predicate is not included in the result.
>>> list(break_iterable([1, 2, 3, 4], lambda x: x == 3))
[[1, 2], [4]]
"""
sublist = []
for i in iterable:
i... | python | def break_iterable(iterable, pred):
"""Break a iterable on the item that matches the predicate into lists.
The item that matched the predicate is not included in the result.
>>> list(break_iterable([1, 2, 3, 4], lambda x: x == 3))
[[1, 2], [4]]
"""
sublist = []
for i in iterable:
i... | [
"def",
"break_iterable",
"(",
"iterable",
",",
"pred",
")",
":",
"sublist",
"=",
"[",
"]",
"for",
"i",
"in",
"iterable",
":",
"if",
"pred",
"(",
"i",
")",
":",
"yield",
"sublist",
"sublist",
"=",
"[",
"]",
"else",
":",
"sublist",
".",
"append",
"("... | Break a iterable on the item that matches the predicate into lists.
The item that matched the predicate is not included in the result.
>>> list(break_iterable([1, 2, 3, 4], lambda x: x == 3))
[[1, 2], [4]] | [
"Break",
"a",
"iterable",
"on",
"the",
"item",
"that",
"matches",
"the",
"predicate",
"into",
"lists",
"."
] | train | https://github.com/mfussenegger/cr8/blob/a37d6049f1f9fee2d0556efae2b7b7f8761bffe8/cr8/misc.py#L123-L138 |
nickmckay/LiPD-utilities | Python/lipd/bag.py | create_bag | def create_bag(dir_bag):
"""
Create a Bag out of given files.
:param str dir_bag: Directory that contains csv, jsonld, and changelog files.
:return obj: Bag
"""
logger_bagit.info("enter create_bag")
# if not dir_bag:
# dir_bag = os.getcwd()
try:
bag = bagit.make_bag(dir_b... | python | def create_bag(dir_bag):
"""
Create a Bag out of given files.
:param str dir_bag: Directory that contains csv, jsonld, and changelog files.
:return obj: Bag
"""
logger_bagit.info("enter create_bag")
# if not dir_bag:
# dir_bag = os.getcwd()
try:
bag = bagit.make_bag(dir_b... | [
"def",
"create_bag",
"(",
"dir_bag",
")",
":",
"logger_bagit",
".",
"info",
"(",
"\"enter create_bag\"",
")",
"# if not dir_bag:",
"# dir_bag = os.getcwd()",
"try",
":",
"bag",
"=",
"bagit",
".",
"make_bag",
"(",
"dir_bag",
",",
"{",
"'Name'",
":",
"'LiPD Pr... | Create a Bag out of given files.
:param str dir_bag: Directory that contains csv, jsonld, and changelog files.
:return obj: Bag | [
"Create",
"a",
"Bag",
"out",
"of",
"given",
"files",
".",
":",
"param",
"str",
"dir_bag",
":",
"Directory",
"that",
"contains",
"csv",
"jsonld",
"and",
"changelog",
"files",
".",
":",
"return",
"obj",
":",
"Bag"
] | train | https://github.com/nickmckay/LiPD-utilities/blob/5dab6bbeffc5effd68e3a6beaca6b76aa928e860/Python/lipd/bag.py#L8-L27 |
nickmckay/LiPD-utilities | Python/lipd/bag.py | open_bag | def open_bag(dir_bag):
"""
Open Bag at the given path
:param str dir_bag: Path to Bag
:return obj: Bag
"""
logger_bagit.info("enter open_bag")
try:
bag = bagit.Bag(dir_bag)
logger_bagit.info("opened bag")
return bag
except Exception as e:
print("Error: fai... | python | def open_bag(dir_bag):
"""
Open Bag at the given path
:param str dir_bag: Path to Bag
:return obj: Bag
"""
logger_bagit.info("enter open_bag")
try:
bag = bagit.Bag(dir_bag)
logger_bagit.info("opened bag")
return bag
except Exception as e:
print("Error: fai... | [
"def",
"open_bag",
"(",
"dir_bag",
")",
":",
"logger_bagit",
".",
"info",
"(",
"\"enter open_bag\"",
")",
"try",
":",
"bag",
"=",
"bagit",
".",
"Bag",
"(",
"dir_bag",
")",
"logger_bagit",
".",
"info",
"(",
"\"opened bag\"",
")",
"return",
"bag",
"except",
... | Open Bag at the given path
:param str dir_bag: Path to Bag
:return obj: Bag | [
"Open",
"Bag",
"at",
"the",
"given",
"path",
":",
"param",
"str",
"dir_bag",
":",
"Path",
"to",
"Bag",
":",
"return",
"obj",
":",
"Bag"
] | train | https://github.com/nickmckay/LiPD-utilities/blob/5dab6bbeffc5effd68e3a6beaca6b76aa928e860/Python/lipd/bag.py#L30-L44 |
nickmckay/LiPD-utilities | Python/lipd/bag.py | validate_md5 | def validate_md5(bag):
"""
Check if Bag is valid
:param obj bag: Bag
:return None:
"""
logger_bagit.info("validate_md5")
if bag.is_valid():
print("Valid md5")
# for path, fixity in bag.entries.items():
# print("path:{}\nmd5:{}\n".format(path, fixity["md5"]))
e... | python | def validate_md5(bag):
"""
Check if Bag is valid
:param obj bag: Bag
:return None:
"""
logger_bagit.info("validate_md5")
if bag.is_valid():
print("Valid md5")
# for path, fixity in bag.entries.items():
# print("path:{}\nmd5:{}\n".format(path, fixity["md5"]))
e... | [
"def",
"validate_md5",
"(",
"bag",
")",
":",
"logger_bagit",
".",
"info",
"(",
"\"validate_md5\"",
")",
"if",
"bag",
".",
"is_valid",
"(",
")",
":",
"print",
"(",
"\"Valid md5\"",
")",
"# for path, fixity in bag.entries.items():",
"# print(\"path:{}\\nmd5:{}\\n\".... | Check if Bag is valid
:param obj bag: Bag
:return None: | [
"Check",
"if",
"Bag",
"is",
"valid",
":",
"param",
"obj",
"bag",
":",
"Bag",
":",
"return",
"None",
":"
] | train | https://github.com/nickmckay/LiPD-utilities/blob/5dab6bbeffc5effd68e3a6beaca6b76aa928e860/Python/lipd/bag.py#L47-L61 |
nickmckay/LiPD-utilities | Python/lipd/bag.py | resolved_flag | def resolved_flag(bag):
"""
Check DOI flag in bag.info to see if doi_resolver has been previously run
:param obj bag: Bag
:return bool: Flag
"""
if 'DOI-Resolved' in bag.info:
logger_bagit.info("bagit resolved_flag: true")
return True
logger_bagit.info("bagit resolved_flag: f... | python | def resolved_flag(bag):
"""
Check DOI flag in bag.info to see if doi_resolver has been previously run
:param obj bag: Bag
:return bool: Flag
"""
if 'DOI-Resolved' in bag.info:
logger_bagit.info("bagit resolved_flag: true")
return True
logger_bagit.info("bagit resolved_flag: f... | [
"def",
"resolved_flag",
"(",
"bag",
")",
":",
"if",
"'DOI-Resolved'",
"in",
"bag",
".",
"info",
":",
"logger_bagit",
".",
"info",
"(",
"\"bagit resolved_flag: true\"",
")",
"return",
"True",
"logger_bagit",
".",
"info",
"(",
"\"bagit resolved_flag: false\"",
")",
... | Check DOI flag in bag.info to see if doi_resolver has been previously run
:param obj bag: Bag
:return bool: Flag | [
"Check",
"DOI",
"flag",
"in",
"bag",
".",
"info",
"to",
"see",
"if",
"doi_resolver",
"has",
"been",
"previously",
"run",
":",
"param",
"obj",
"bag",
":",
"Bag",
":",
"return",
"bool",
":",
"Flag"
] | train | https://github.com/nickmckay/LiPD-utilities/blob/5dab6bbeffc5effd68e3a6beaca6b76aa928e860/Python/lipd/bag.py#L64-L74 |
nickmckay/LiPD-utilities | Python/lipd/bag.py | finish_bag | def finish_bag(dir_bag):
"""
Closing steps for creating a bag
:param obj dir_bag:
:return None:
"""
logger_bagit.info("enter finish_bag")
# Create a bag for the 3 files
new_bag = create_bag(dir_bag)
open_bag(dir_bag)
new_bag.save(manifests=True)
logger_bagit.info("exit finish... | python | def finish_bag(dir_bag):
"""
Closing steps for creating a bag
:param obj dir_bag:
:return None:
"""
logger_bagit.info("enter finish_bag")
# Create a bag for the 3 files
new_bag = create_bag(dir_bag)
open_bag(dir_bag)
new_bag.save(manifests=True)
logger_bagit.info("exit finish... | [
"def",
"finish_bag",
"(",
"dir_bag",
")",
":",
"logger_bagit",
".",
"info",
"(",
"\"enter finish_bag\"",
")",
"# Create a bag for the 3 files",
"new_bag",
"=",
"create_bag",
"(",
"dir_bag",
")",
"open_bag",
"(",
"dir_bag",
")",
"new_bag",
".",
"save",
"(",
"mani... | Closing steps for creating a bag
:param obj dir_bag:
:return None: | [
"Closing",
"steps",
"for",
"creating",
"a",
"bag",
":",
"param",
"obj",
"dir_bag",
":",
":",
"return",
"None",
":"
] | train | https://github.com/nickmckay/LiPD-utilities/blob/5dab6bbeffc5effd68e3a6beaca6b76aa928e860/Python/lipd/bag.py#L77-L89 |
nickmckay/LiPD-utilities | Python/lipd/directory.py | _ask_how_many | def _ask_how_many():
"""
Ask user if they want to load in one file or do a batch process of a whole directory. Default to batch "m" mode.
:return str: Path or none
"""
batch = True
invalid = True
_option = ""
try:
while invalid:
print("\nChoose a loading option:\n1. ... | python | def _ask_how_many():
"""
Ask user if they want to load in one file or do a batch process of a whole directory. Default to batch "m" mode.
:return str: Path or none
"""
batch = True
invalid = True
_option = ""
try:
while invalid:
print("\nChoose a loading option:\n1. ... | [
"def",
"_ask_how_many",
"(",
")",
":",
"batch",
"=",
"True",
"invalid",
"=",
"True",
"_option",
"=",
"\"\"",
"try",
":",
"while",
"invalid",
":",
"print",
"(",
"\"\\nChoose a loading option:\\n1. Select specific file(s)\\n2. Load entire folder\"",
")",
"_option",
"=",... | Ask user if they want to load in one file or do a batch process of a whole directory. Default to batch "m" mode.
:return str: Path or none | [
"Ask",
"user",
"if",
"they",
"want",
"to",
"load",
"in",
"one",
"file",
"or",
"do",
"a",
"batch",
"process",
"of",
"a",
"whole",
"directory",
".",
"Default",
"to",
"batch",
"m",
"mode",
".",
":",
"return",
"str",
":",
"Path",
"or",
"none"
] | train | https://github.com/nickmckay/LiPD-utilities/blob/5dab6bbeffc5effd68e3a6beaca6b76aa928e860/Python/lipd/directory.py#L15-L37 |
nickmckay/LiPD-utilities | Python/lipd/directory.py | browse_dialog_dir | def browse_dialog_dir():
"""
Open up a GUI browse dialog window and let to user pick a target directory.
:return str: Target directory path
"""
_go_to_package()
logger_directory.info("enter browse_dialog")
_path_bytes = subprocess.check_output(['python', 'gui_dir_browse.py'], shell=False)
... | python | def browse_dialog_dir():
"""
Open up a GUI browse dialog window and let to user pick a target directory.
:return str: Target directory path
"""
_go_to_package()
logger_directory.info("enter browse_dialog")
_path_bytes = subprocess.check_output(['python', 'gui_dir_browse.py'], shell=False)
... | [
"def",
"browse_dialog_dir",
"(",
")",
":",
"_go_to_package",
"(",
")",
"logger_directory",
".",
"info",
"(",
"\"enter browse_dialog\"",
")",
"_path_bytes",
"=",
"subprocess",
".",
"check_output",
"(",
"[",
"'python'",
",",
"'gui_dir_browse.py'",
"]",
",",
"shell",... | Open up a GUI browse dialog window and let to user pick a target directory.
:return str: Target directory path | [
"Open",
"up",
"a",
"GUI",
"browse",
"dialog",
"window",
"and",
"let",
"to",
"user",
"pick",
"a",
"target",
"directory",
".",
":",
"return",
"str",
":",
"Target",
"directory",
"path"
] | train | https://github.com/nickmckay/LiPD-utilities/blob/5dab6bbeffc5effd68e3a6beaca6b76aa928e860/Python/lipd/directory.py#L54-L69 |
nickmckay/LiPD-utilities | Python/lipd/directory.py | browse_dialog_file | def browse_dialog_file():
"""
Open up a GUI browse dialog window and let to user select one or more files
:return str _path: Target directory path
:return list _files: List of selected files
"""
logger_directory.info("enter browse_dialog")
# We make files a list, because the user can multi... | python | def browse_dialog_file():
"""
Open up a GUI browse dialog window and let to user select one or more files
:return str _path: Target directory path
:return list _files: List of selected files
"""
logger_directory.info("enter browse_dialog")
# We make files a list, because the user can multi... | [
"def",
"browse_dialog_file",
"(",
")",
":",
"logger_directory",
".",
"info",
"(",
"\"enter browse_dialog\"",
")",
"# We make files a list, because the user can multi-select files.",
"_files",
"=",
"[",
"]",
"_path",
"=",
"\"\"",
"try",
":",
"_go_to_package",
"(",
")",
... | Open up a GUI browse dialog window and let to user select one or more files
:return str _path: Target directory path
:return list _files: List of selected files | [
"Open",
"up",
"a",
"GUI",
"browse",
"dialog",
"window",
"and",
"let",
"to",
"user",
"select",
"one",
"or",
"more",
"files",
":",
"return",
"str",
"_path",
":",
"Target",
"directory",
"path",
":",
"return",
"list",
"_files",
":",
"List",
"of",
"selected",... | train | https://github.com/nickmckay/LiPD-utilities/blob/5dab6bbeffc5effd68e3a6beaca6b76aa928e860/Python/lipd/directory.py#L85-L112 |
nickmckay/LiPD-utilities | Python/lipd/directory.py | check_file_age | def check_file_age(filename, days):
"""
Check if the target file has an older creation date than X amount of time.
i.e. One day: 60*60*24
:param str filename: Target filename
:param int days: Limit in number of days
:return bool: True - older than X time, False - not older than X time
"""
... | python | def check_file_age(filename, days):
"""
Check if the target file has an older creation date than X amount of time.
i.e. One day: 60*60*24
:param str filename: Target filename
:param int days: Limit in number of days
:return bool: True - older than X time, False - not older than X time
"""
... | [
"def",
"check_file_age",
"(",
"filename",
",",
"days",
")",
":",
"logger_directory",
".",
"info",
"(",
"\"enter check_file_age\"",
")",
"# Multiply days given by time for one day.",
"t",
"=",
"days",
"*",
"60",
"*",
"60",
"*",
"24",
"now",
"=",
"time",
".",
"t... | Check if the target file has an older creation date than X amount of time.
i.e. One day: 60*60*24
:param str filename: Target filename
:param int days: Limit in number of days
:return bool: True - older than X time, False - not older than X time | [
"Check",
"if",
"the",
"target",
"file",
"has",
"an",
"older",
"creation",
"date",
"than",
"X",
"amount",
"of",
"time",
".",
"i",
".",
"e",
".",
"One",
"day",
":",
"60",
"*",
"60",
"*",
"24",
":",
"param",
"str",
"filename",
":",
"Target",
"filename... | train | https://github.com/nickmckay/LiPD-utilities/blob/5dab6bbeffc5effd68e3a6beaca6b76aa928e860/Python/lipd/directory.py#L115-L142 |
nickmckay/LiPD-utilities | Python/lipd/directory.py | collect_metadata_files | def collect_metadata_files(cwd, new_files, existing_files):
"""
Collect all files from a given path. Separate by file type, and return one list for each type
If 'files' contains specific
:param str cwd: Directory w/ target files
:param list new_files: Specific new files to load
:param dict exist... | python | def collect_metadata_files(cwd, new_files, existing_files):
"""
Collect all files from a given path. Separate by file type, and return one list for each type
If 'files' contains specific
:param str cwd: Directory w/ target files
:param list new_files: Specific new files to load
:param dict exist... | [
"def",
"collect_metadata_files",
"(",
"cwd",
",",
"new_files",
",",
"existing_files",
")",
":",
"obj",
"=",
"{",
"}",
"try",
":",
"os",
".",
"chdir",
"(",
"cwd",
")",
"# Special case: User uses gui to mult-select 2+ files. You'll be given a list of file paths.",
"if",
... | Collect all files from a given path. Separate by file type, and return one list for each type
If 'files' contains specific
:param str cwd: Directory w/ target files
:param list new_files: Specific new files to load
:param dict existing_files: Files currently loaded, separated by type
:return list: A... | [
"Collect",
"all",
"files",
"from",
"a",
"given",
"path",
".",
"Separate",
"by",
"file",
"type",
"and",
"return",
"one",
"list",
"for",
"each",
"type",
"If",
"files",
"contains",
"specific",
":",
"param",
"str",
"cwd",
":",
"Directory",
"w",
"/",
"target"... | train | https://github.com/nickmckay/LiPD-utilities/blob/5dab6bbeffc5effd68e3a6beaca6b76aa928e860/Python/lipd/directory.py#L155-L189 |
nickmckay/LiPD-utilities | Python/lipd/directory.py | collect_metadata_file | def collect_metadata_file(full_path):
"""
Create the file metadata and add it to the appropriate section by file-type
:param str full_path:
:param dict existing_files:
:return dict existing files:
"""
fne = os.path.basename(full_path)
fn = os.path.splitext(fne)[0]
obj = {"full_path":... | python | def collect_metadata_file(full_path):
"""
Create the file metadata and add it to the appropriate section by file-type
:param str full_path:
:param dict existing_files:
:return dict existing files:
"""
fne = os.path.basename(full_path)
fn = os.path.splitext(fne)[0]
obj = {"full_path":... | [
"def",
"collect_metadata_file",
"(",
"full_path",
")",
":",
"fne",
"=",
"os",
".",
"path",
".",
"basename",
"(",
"full_path",
")",
"fn",
"=",
"os",
".",
"path",
".",
"splitext",
"(",
"fne",
")",
"[",
"0",
"]",
"obj",
"=",
"{",
"\"full_path\"",
":",
... | Create the file metadata and add it to the appropriate section by file-type
:param str full_path:
:param dict existing_files:
:return dict existing files: | [
"Create",
"the",
"file",
"metadata",
"and",
"add",
"it",
"to",
"the",
"appropriate",
"section",
"by",
"file",
"-",
"type",
":",
"param",
"str",
"full_path",
":",
":",
"param",
"dict",
"existing_files",
":",
":",
"return",
"dict",
"existing",
"files",
":"
] | train | https://github.com/nickmckay/LiPD-utilities/blob/5dab6bbeffc5effd68e3a6beaca6b76aa928e860/Python/lipd/directory.py#L192-L202 |
nickmckay/LiPD-utilities | Python/lipd/directory.py | dir_cleanup | def dir_cleanup(dir_bag, dir_data):
"""
Moves JSON and csv files to bag root, then deletes all the metadata bag files. We'll be creating a new bag with
the data files, so we don't need the other text files and such.
:param str dir_bag: Path to root of Bag
:param str dir_data: Path to Bag /data subdi... | python | def dir_cleanup(dir_bag, dir_data):
"""
Moves JSON and csv files to bag root, then deletes all the metadata bag files. We'll be creating a new bag with
the data files, so we don't need the other text files and such.
:param str dir_bag: Path to root of Bag
:param str dir_data: Path to Bag /data subdi... | [
"def",
"dir_cleanup",
"(",
"dir_bag",
",",
"dir_data",
")",
":",
"logger_directory",
".",
"info",
"(",
"\"enter dir_cleanup\"",
")",
"# dir : dir_data -> dir_bag",
"os",
".",
"chdir",
"(",
"dir_bag",
")",
"# Delete files in dir_bag",
"for",
"file",
"in",
"os",
"."... | Moves JSON and csv files to bag root, then deletes all the metadata bag files. We'll be creating a new bag with
the data files, so we don't need the other text files and such.
:param str dir_bag: Path to root of Bag
:param str dir_data: Path to Bag /data subdirectory
:return None: | [
"Moves",
"JSON",
"and",
"csv",
"files",
"to",
"bag",
"root",
"then",
"deletes",
"all",
"the",
"metadata",
"bag",
"files",
".",
"We",
"ll",
"be",
"creating",
"a",
"new",
"bag",
"with",
"the",
"data",
"files",
"so",
"we",
"don",
"t",
"need",
"the",
"ot... | train | https://github.com/nickmckay/LiPD-utilities/blob/5dab6bbeffc5effd68e3a6beaca6b76aa928e860/Python/lipd/directory.py#L205-L229 |
nickmckay/LiPD-utilities | Python/lipd/directory.py | filename_from_path | def filename_from_path(path):
"""
Extract the file name from a given file path.
:param str path: File path
:return str: File name with extension
"""
head, tail = ntpath.split(path)
return head, tail or ntpath.basename(head) | python | def filename_from_path(path):
"""
Extract the file name from a given file path.
:param str path: File path
:return str: File name with extension
"""
head, tail = ntpath.split(path)
return head, tail or ntpath.basename(head) | [
"def",
"filename_from_path",
"(",
"path",
")",
":",
"head",
",",
"tail",
"=",
"ntpath",
".",
"split",
"(",
"path",
")",
"return",
"head",
",",
"tail",
"or",
"ntpath",
".",
"basename",
"(",
"head",
")"
] | Extract the file name from a given file path.
:param str path: File path
:return str: File name with extension | [
"Extract",
"the",
"file",
"name",
"from",
"a",
"given",
"file",
"path",
".",
":",
"param",
"str",
"path",
":",
"File",
"path",
":",
"return",
"str",
":",
"File",
"name",
"with",
"extension"
] | train | https://github.com/nickmckay/LiPD-utilities/blob/5dab6bbeffc5effd68e3a6beaca6b76aa928e860/Python/lipd/directory.py#L232-L239 |
nickmckay/LiPD-utilities | Python/lipd/directory.py | find_files | def find_files():
"""
Search for the directory containing jsonld and csv files. chdir and then quit.
:return none:
"""
_dir = os.getcwd()
_files = os.listdir()
# Look for a jsonld file
for _file in _files:
if _file.endswith(".jsonld"):
return os.getcwd()
# No json... | python | def find_files():
"""
Search for the directory containing jsonld and csv files. chdir and then quit.
:return none:
"""
_dir = os.getcwd()
_files = os.listdir()
# Look for a jsonld file
for _file in _files:
if _file.endswith(".jsonld"):
return os.getcwd()
# No json... | [
"def",
"find_files",
"(",
")",
":",
"_dir",
"=",
"os",
".",
"getcwd",
"(",
")",
"_files",
"=",
"os",
".",
"listdir",
"(",
")",
"# Look for a jsonld file",
"for",
"_file",
"in",
"_files",
":",
"if",
"_file",
".",
"endswith",
"(",
"\".jsonld\"",
")",
":"... | Search for the directory containing jsonld and csv files. chdir and then quit.
:return none: | [
"Search",
"for",
"the",
"directory",
"containing",
"jsonld",
"and",
"csv",
"files",
".",
"chdir",
"and",
"then",
"quit",
".",
":",
"return",
"none",
":"
] | train | https://github.com/nickmckay/LiPD-utilities/blob/5dab6bbeffc5effd68e3a6beaca6b76aa928e860/Python/lipd/directory.py#L242-L263 |
nickmckay/LiPD-utilities | Python/lipd/directory.py | get_filenames_generated | def get_filenames_generated(d, name="", csvs=""):
"""
Get the filenames that the LiPD utilities has generated (per naming standard), as opposed to the filenames that
originated in the LiPD file (that possibly don't follow the naming standard)
:param dict d: Data
:param str name: LiPD dataset name to... | python | def get_filenames_generated(d, name="", csvs=""):
"""
Get the filenames that the LiPD utilities has generated (per naming standard), as opposed to the filenames that
originated in the LiPD file (that possibly don't follow the naming standard)
:param dict d: Data
:param str name: LiPD dataset name to... | [
"def",
"get_filenames_generated",
"(",
"d",
",",
"name",
"=",
"\"\"",
",",
"csvs",
"=",
"\"\"",
")",
":",
"filenames",
"=",
"[",
"]",
"try",
":",
"filenames",
"=",
"d",
".",
"keys",
"(",
")",
"if",
"name",
":",
"filenames",
"=",
"[",
"os",
".",
"... | Get the filenames that the LiPD utilities has generated (per naming standard), as opposed to the filenames that
originated in the LiPD file (that possibly don't follow the naming standard)
:param dict d: Data
:param str name: LiPD dataset name to prefix
:param list csvs: Filenames list to merge with
... | [
"Get",
"the",
"filenames",
"that",
"the",
"LiPD",
"utilities",
"has",
"generated",
"(",
"per",
"naming",
"standard",
")",
"as",
"opposed",
"to",
"the",
"filenames",
"that",
"originated",
"in",
"the",
"LiPD",
"file",
"(",
"that",
"possibly",
"don",
"t",
"fo... | train | https://github.com/nickmckay/LiPD-utilities/blob/5dab6bbeffc5effd68e3a6beaca6b76aa928e860/Python/lipd/directory.py#L266-L285 |
nickmckay/LiPD-utilities | Python/lipd/directory.py | get_filenames_in_lipd | def get_filenames_in_lipd(path, name=""):
"""
List all the files contained in the LiPD archive. Bagit, JSON, and CSV
:param str path: Directory to be listed
:param str name: LiPD dataset name, if you want to prefix it to show file hierarchy
:return list: Filenames found
"""
_filenames = []
... | python | def get_filenames_in_lipd(path, name=""):
"""
List all the files contained in the LiPD archive. Bagit, JSON, and CSV
:param str path: Directory to be listed
:param str name: LiPD dataset name, if you want to prefix it to show file hierarchy
:return list: Filenames found
"""
_filenames = []
... | [
"def",
"get_filenames_in_lipd",
"(",
"path",
",",
"name",
"=",
"\"\"",
")",
":",
"_filenames",
"=",
"[",
"]",
"try",
":",
"# in the top level, list all files and skip the \"data\" directory",
"_top",
"=",
"[",
"os",
".",
"path",
".",
"join",
"(",
"name",
",",
... | List all the files contained in the LiPD archive. Bagit, JSON, and CSV
:param str path: Directory to be listed
:param str name: LiPD dataset name, if you want to prefix it to show file hierarchy
:return list: Filenames found | [
"List",
"all",
"the",
"files",
"contained",
"in",
"the",
"LiPD",
"archive",
".",
"Bagit",
"JSON",
"and",
"CSV",
":",
"param",
"str",
"path",
":",
"Directory",
"to",
"be",
"listed",
":",
"param",
"str",
"name",
":",
"LiPD",
"dataset",
"name",
"if",
"you... | train | https://github.com/nickmckay/LiPD-utilities/blob/5dab6bbeffc5effd68e3a6beaca6b76aa928e860/Python/lipd/directory.py#L288-L305 |
nickmckay/LiPD-utilities | Python/lipd/directory.py | get_src_or_dst | def get_src_or_dst(mode, path_type):
"""
User sets the path to a LiPD source location
:param str mode: "read" or "write" mode
:param str path_type: "directory" or "file"
:return str path: dir path to files
:return list files: files chosen
"""
logger_directory.info("enter set_src_or_dst")... | python | def get_src_or_dst(mode, path_type):
"""
User sets the path to a LiPD source location
:param str mode: "read" or "write" mode
:param str path_type: "directory" or "file"
:return str path: dir path to files
:return list files: files chosen
"""
logger_directory.info("enter set_src_or_dst")... | [
"def",
"get_src_or_dst",
"(",
"mode",
",",
"path_type",
")",
":",
"logger_directory",
".",
"info",
"(",
"\"enter set_src_or_dst\"",
")",
"_path",
"=",
"\"\"",
"_files",
"=",
"\"\"",
"invalid",
"=",
"True",
"count",
"=",
"0",
"# Did you forget to enter a mode?",
... | User sets the path to a LiPD source location
:param str mode: "read" or "write" mode
:param str path_type: "directory" or "file"
:return str path: dir path to files
:return list files: files chosen | [
"User",
"sets",
"the",
"path",
"to",
"a",
"LiPD",
"source",
"location",
":",
"param",
"str",
"mode",
":",
"read",
"or",
"write",
"mode",
":",
"param",
"str",
"path_type",
":",
"directory",
"or",
"file",
":",
"return",
"str",
"path",
":",
"dir",
"path",... | train | https://github.com/nickmckay/LiPD-utilities/blob/5dab6bbeffc5effd68e3a6beaca6b76aa928e860/Python/lipd/directory.py#L308-L344 |
nickmckay/LiPD-utilities | Python/lipd/directory.py | get_src_or_dst_prompt | def get_src_or_dst_prompt(mode):
"""
String together the proper prompt based on the mode
:param str mode: "read" or "write"
:return str prompt: The prompt needed
"""
_words = {"read": "from", "write": "to"}
# print(os.getcwd())
prompt = "Where would you like to {} your file(s) {}?\n" \
... | python | def get_src_or_dst_prompt(mode):
"""
String together the proper prompt based on the mode
:param str mode: "read" or "write"
:return str prompt: The prompt needed
"""
_words = {"read": "from", "write": "to"}
# print(os.getcwd())
prompt = "Where would you like to {} your file(s) {}?\n" \
... | [
"def",
"get_src_or_dst_prompt",
"(",
"mode",
")",
":",
"_words",
"=",
"{",
"\"read\"",
":",
"\"from\"",
",",
"\"write\"",
":",
"\"to\"",
"}",
"# print(os.getcwd())",
"prompt",
"=",
"\"Where would you like to {} your file(s) {}?\\n\"",
"\"1. Desktop ({})\\n\"",
"\"2. Downl... | String together the proper prompt based on the mode
:param str mode: "read" or "write"
:return str prompt: The prompt needed | [
"String",
"together",
"the",
"proper",
"prompt",
"based",
"on",
"the",
"mode",
":",
"param",
"str",
"mode",
":",
"read",
"or",
"write",
":",
"return",
"str",
"prompt",
":",
"The",
"prompt",
"needed"
] | train | https://github.com/nickmckay/LiPD-utilities/blob/5dab6bbeffc5effd68e3a6beaca6b76aa928e860/Python/lipd/directory.py#L347-L363 |
nickmckay/LiPD-utilities | Python/lipd/directory.py | get_src_or_dst_path | def get_src_or_dst_path(prompt, count):
"""
Let the user choose a path, and store the value.
:return str _path: Target directory
:return str count: Counter for attempted prompts
"""
_path = ""
print(prompt)
option = input("Option: ")
print("\n")
if option == '1':
# Set th... | python | def get_src_or_dst_path(prompt, count):
"""
Let the user choose a path, and store the value.
:return str _path: Target directory
:return str count: Counter for attempted prompts
"""
_path = ""
print(prompt)
option = input("Option: ")
print("\n")
if option == '1':
# Set th... | [
"def",
"get_src_or_dst_path",
"(",
"prompt",
",",
"count",
")",
":",
"_path",
"=",
"\"\"",
"print",
"(",
"prompt",
")",
"option",
"=",
"input",
"(",
"\"Option: \"",
")",
"print",
"(",
"\"\\n\"",
")",
"if",
"option",
"==",
"'1'",
":",
"# Set the path to the... | Let the user choose a path, and store the value.
:return str _path: Target directory
:return str count: Counter for attempted prompts | [
"Let",
"the",
"user",
"choose",
"a",
"path",
"and",
"store",
"the",
"value",
".",
":",
"return",
"str",
"_path",
":",
"Target",
"directory",
":",
"return",
"str",
"count",
":",
"Counter",
"for",
"attempted",
"prompts"
] | train | https://github.com/nickmckay/LiPD-utilities/blob/5dab6bbeffc5effd68e3a6beaca6b76aa928e860/Python/lipd/directory.py#L366-L404 |
nickmckay/LiPD-utilities | Python/lipd/directory.py | list_files | def list_files(x, path=""):
"""
Lists file(s) in given path of the X type.
:param str x: File extension that we are interested in.
:param str path: Path, if user would like to check a specific directory outside of the CWD
:return list of str: File name(s) to be worked on
"""
logger_directory... | python | def list_files(x, path=""):
"""
Lists file(s) in given path of the X type.
:param str x: File extension that we are interested in.
:param str path: Path, if user would like to check a specific directory outside of the CWD
:return list of str: File name(s) to be worked on
"""
logger_directory... | [
"def",
"list_files",
"(",
"x",
",",
"path",
"=",
"\"\"",
")",
":",
"logger_directory",
".",
"info",
"(",
"\"enter list_files\"",
")",
"file_list",
"=",
"[",
"]",
"if",
"path",
":",
"# list files from target directory",
"files",
"=",
"os",
".",
"listdir",
"("... | Lists file(s) in given path of the X type.
:param str x: File extension that we are interested in.
:param str path: Path, if user would like to check a specific directory outside of the CWD
:return list of str: File name(s) to be worked on | [
"Lists",
"file",
"(",
"s",
")",
"in",
"given",
"path",
"of",
"the",
"X",
"type",
".",
":",
"param",
"str",
"x",
":",
"File",
"extension",
"that",
"we",
"are",
"interested",
"in",
".",
":",
"param",
"str",
"path",
":",
"Path",
"if",
"user",
"would",... | train | https://github.com/nickmckay/LiPD-utilities/blob/5dab6bbeffc5effd68e3a6beaca6b76aa928e860/Python/lipd/directory.py#L407-L431 |
nickmckay/LiPD-utilities | Python/lipd/directory.py | rm_files_in_dir | def rm_files_in_dir(path):
"""
Removes all files within a directory, but does not delete the directory
:param str path: Target directory
:return none:
"""
for f in os.listdir(path):
try:
os.remove(f)
except PermissionError:
os.chmod(f, 0o777)
t... | python | def rm_files_in_dir(path):
"""
Removes all files within a directory, but does not delete the directory
:param str path: Target directory
:return none:
"""
for f in os.listdir(path):
try:
os.remove(f)
except PermissionError:
os.chmod(f, 0o777)
t... | [
"def",
"rm_files_in_dir",
"(",
"path",
")",
":",
"for",
"f",
"in",
"os",
".",
"listdir",
"(",
"path",
")",
":",
"try",
":",
"os",
".",
"remove",
"(",
"f",
")",
"except",
"PermissionError",
":",
"os",
".",
"chmod",
"(",
"f",
",",
"0o777",
")",
"tr... | Removes all files within a directory, but does not delete the directory
:param str path: Target directory
:return none: | [
"Removes",
"all",
"files",
"within",
"a",
"directory",
"but",
"does",
"not",
"delete",
"the",
"directory",
":",
"param",
"str",
"path",
":",
"Target",
"directory",
":",
"return",
"none",
":"
] | train | https://github.com/nickmckay/LiPD-utilities/blob/5dab6bbeffc5effd68e3a6beaca6b76aa928e860/Python/lipd/directory.py#L434-L449 |
nickmckay/LiPD-utilities | Python/lipd/directory.py | rm_file_if_exists | def rm_file_if_exists(path, filename):
"""
Remove a file if it exists. Useful for when we want to write a file, but it already exists in that locaiton.
:param str filename: Filename
:param str path: Directory
:return none:
"""
_full_path = os.path.join(path, filename)
if os.path.exists(_... | python | def rm_file_if_exists(path, filename):
"""
Remove a file if it exists. Useful for when we want to write a file, but it already exists in that locaiton.
:param str filename: Filename
:param str path: Directory
:return none:
"""
_full_path = os.path.join(path, filename)
if os.path.exists(_... | [
"def",
"rm_file_if_exists",
"(",
"path",
",",
"filename",
")",
":",
"_full_path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"path",
",",
"filename",
")",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"_full_path",
")",
":",
"os",
".",
"remove",
"(",
... | Remove a file if it exists. Useful for when we want to write a file, but it already exists in that locaiton.
:param str filename: Filename
:param str path: Directory
:return none: | [
"Remove",
"a",
"file",
"if",
"it",
"exists",
".",
"Useful",
"for",
"when",
"we",
"want",
"to",
"write",
"a",
"file",
"but",
"it",
"already",
"exists",
"in",
"that",
"locaiton",
".",
":",
"param",
"str",
"filename",
":",
"Filename",
":",
"param",
"str",... | train | https://github.com/nickmckay/LiPD-utilities/blob/5dab6bbeffc5effd68e3a6beaca6b76aa928e860/Python/lipd/directory.py#L452-L462 |
audiolion/django-language-field | languages/regenerate.py | regenerate | def regenerate(location='http://www.iana.org/assignments/language-subtag-registry',
filename=None, default_encoding='utf-8'):
"""
Generate the languages Python module.
"""
paren = re.compile('\([^)]*\)')
# Get the language list.
data = urllib2.urlopen(location)
if ('content-t... | python | def regenerate(location='http://www.iana.org/assignments/language-subtag-registry',
filename=None, default_encoding='utf-8'):
"""
Generate the languages Python module.
"""
paren = re.compile('\([^)]*\)')
# Get the language list.
data = urllib2.urlopen(location)
if ('content-t... | [
"def",
"regenerate",
"(",
"location",
"=",
"'http://www.iana.org/assignments/language-subtag-registry'",
",",
"filename",
"=",
"None",
",",
"default_encoding",
"=",
"'utf-8'",
")",
":",
"paren",
"=",
"re",
".",
"compile",
"(",
"'\\([^)]*\\)'",
")",
"# Get the language... | Generate the languages Python module. | [
"Generate",
"the",
"languages",
"Python",
"module",
"."
] | train | https://github.com/audiolion/django-language-field/blob/7847dab863794fd06d8b445c9dda6b45ce830f8d/languages/regenerate.py#L22-L62 |
mobiusklein/brainpy | brainpy/brainpy.py | give_repr | def give_repr(cls): # pragma: no cover
r"""Patch a class to give it a generic __repr__ method
that works by inspecting the instance dictionary.
Parameters
----------
cls: type
The class to add a generic __repr__ to.
Returns
-------
cls: type
The passed class is returne... | python | def give_repr(cls): # pragma: no cover
r"""Patch a class to give it a generic __repr__ method
that works by inspecting the instance dictionary.
Parameters
----------
cls: type
The class to add a generic __repr__ to.
Returns
-------
cls: type
The passed class is returne... | [
"def",
"give_repr",
"(",
"cls",
")",
":",
"# pragma: no cover",
"def",
"reprer",
"(",
"self",
")",
":",
"attribs",
"=",
"', '",
".",
"join",
"(",
"[",
"\"%s=%r\"",
"%",
"(",
"k",
",",
"v",
")",
"for",
"k",
",",
"v",
"in",
"self",
".",
"__dict__",
... | r"""Patch a class to give it a generic __repr__ method
that works by inspecting the instance dictionary.
Parameters
----------
cls: type
The class to add a generic __repr__ to.
Returns
-------
cls: type
The passed class is returned | [
"r",
"Patch",
"a",
"class",
"to",
"give",
"it",
"a",
"generic",
"__repr__",
"method",
"that",
"works",
"by",
"inspecting",
"the",
"instance",
"dictionary",
"."
] | train | https://github.com/mobiusklein/brainpy/blob/4ccba40af33651a338c0c54bf1a251345c2db8da/brainpy/brainpy.py#L33-L52 |
mobiusklein/brainpy | brainpy/brainpy.py | newton | def newton(power_sum, elementary_symmetric_polynomial, order):
r'''
Given two lists of values, the first list being the `power sum`s of a
polynomial, and the second being expressions of the roots of the
polynomial as found by Viete's Formula, use information from the longer list to
fill out the shor... | python | def newton(power_sum, elementary_symmetric_polynomial, order):
r'''
Given two lists of values, the first list being the `power sum`s of a
polynomial, and the second being expressions of the roots of the
polynomial as found by Viete's Formula, use information from the longer list to
fill out the shor... | [
"def",
"newton",
"(",
"power_sum",
",",
"elementary_symmetric_polynomial",
",",
"order",
")",
":",
"if",
"len",
"(",
"power_sum",
")",
">",
"len",
"(",
"elementary_symmetric_polynomial",
")",
":",
"_update_elementary_symmetric_polynomial",
"(",
"power_sum",
",",
"el... | r'''
Given two lists of values, the first list being the `power sum`s of a
polynomial, and the second being expressions of the roots of the
polynomial as found by Viete's Formula, use information from the longer list to
fill out the shorter list using Newton's Identities.
.. note::
Updates ... | [
"r",
"Given",
"two",
"lists",
"of",
"values",
"the",
"first",
"list",
"being",
"the",
"power",
"sum",
"s",
"of",
"a",
"polynomial",
"and",
"the",
"second",
"being",
"expressions",
"of",
"the",
"roots",
"of",
"the",
"polynomial",
"as",
"found",
"by",
"Vie... | train | https://github.com/mobiusklein/brainpy/blob/4ccba40af33651a338c0c54bf1a251345c2db8da/brainpy/brainpy.py#L75-L99 |
mobiusklein/brainpy | brainpy/brainpy.py | vietes | def vietes(coefficients):
r'''
Given the coefficients of a polynomial of a single variable,
compute an elementary symmetric polynomial of the roots of the
input polynomial by Viete's Formula:
.. math::
\sum_{1\le i_1<i_2<...<i_k \le n} x_{i_1}x_{i_2}...x_{i_k} = (-1)^k\frac{a_{n-k}}{a_n}
... | python | def vietes(coefficients):
r'''
Given the coefficients of a polynomial of a single variable,
compute an elementary symmetric polynomial of the roots of the
input polynomial by Viete's Formula:
.. math::
\sum_{1\le i_1<i_2<...<i_k \le n} x_{i_1}x_{i_2}...x_{i_k} = (-1)^k\frac{a_{n-k}}{a_n}
... | [
"def",
"vietes",
"(",
"coefficients",
")",
":",
"elementary_symmetric_polynomial",
"=",
"[",
"]",
"tail",
"=",
"float",
"(",
"coefficients",
"[",
"-",
"1",
"]",
")",
"size",
"=",
"len",
"(",
"coefficients",
")",
"for",
"i",
"in",
"range",
"(",
"size",
... | r'''
Given the coefficients of a polynomial of a single variable,
compute an elementary symmetric polynomial of the roots of the
input polynomial by Viete's Formula:
.. math::
\sum_{1\le i_1<i_2<...<i_k \le n} x_{i_1}x_{i_2}...x_{i_k} = (-1)^k\frac{a_{n-k}}{a_n}
Parameters
----------
... | [
"r",
"Given",
"the",
"coefficients",
"of",
"a",
"polynomial",
"of",
"a",
"single",
"variable",
"compute",
"an",
"elementary",
"symmetric",
"polynomial",
"of",
"the",
"roots",
"of",
"the",
"input",
"polynomial",
"by",
"Viete",
"s",
"Formula",
":"
] | train | https://github.com/mobiusklein/brainpy/blob/4ccba40af33651a338c0c54bf1a251345c2db8da/brainpy/brainpy.py#L136-L168 |
mobiusklein/brainpy | brainpy/brainpy.py | max_variants | def max_variants(composition):
"""Calculates the maximum number of isotopic variants that could be produced by a
composition.
Parameters
----------
composition : Mapping
Any Mapping type where keys are element symbols and values are integers
Returns
-------
max_n_variants :... | python | def max_variants(composition):
"""Calculates the maximum number of isotopic variants that could be produced by a
composition.
Parameters
----------
composition : Mapping
Any Mapping type where keys are element symbols and values are integers
Returns
-------
max_n_variants :... | [
"def",
"max_variants",
"(",
"composition",
")",
":",
"max_n_variants",
"=",
"0",
"for",
"element",
",",
"count",
"in",
"composition",
".",
"items",
"(",
")",
":",
"if",
"element",
"==",
"\"H+\"",
":",
"continue",
"try",
":",
"max_n_variants",
"+=",
"count"... | Calculates the maximum number of isotopic variants that could be produced by a
composition.
Parameters
----------
composition : Mapping
Any Mapping type where keys are element symbols and values are integers
Returns
-------
max_n_variants : int | [
"Calculates",
"the",
"maximum",
"number",
"of",
"isotopic",
"variants",
"that",
"could",
"be",
"produced",
"by",
"a",
"composition",
"."
] | train | https://github.com/mobiusklein/brainpy/blob/4ccba40af33651a338c0c54bf1a251345c2db8da/brainpy/brainpy.py#L339-L362 |
mobiusklein/brainpy | brainpy/brainpy.py | isotopic_variants | def isotopic_variants(composition, npeaks=None, charge=0, charge_carrier=PROTON):
'''
Compute a peak list representing the theoretical isotopic cluster for `composition`.
Parameters
----------
composition : Mapping
Any Mapping type where keys are element symbols and values are integers
... | python | def isotopic_variants(composition, npeaks=None, charge=0, charge_carrier=PROTON):
'''
Compute a peak list representing the theoretical isotopic cluster for `composition`.
Parameters
----------
composition : Mapping
Any Mapping type where keys are element symbols and values are integers
... | [
"def",
"isotopic_variants",
"(",
"composition",
",",
"npeaks",
"=",
"None",
",",
"charge",
"=",
"0",
",",
"charge_carrier",
"=",
"PROTON",
")",
":",
"if",
"npeaks",
"is",
"None",
":",
"max_n_variants",
"=",
"max_variants",
"(",
"composition",
")",
"npeaks",
... | Compute a peak list representing the theoretical isotopic cluster for `composition`.
Parameters
----------
composition : Mapping
Any Mapping type where keys are element symbols and values are integers
npeaks: int
The number of peaks to include in the isotopic cluster, starting from the ... | [
"Compute",
"a",
"peak",
"list",
"representing",
"the",
"theoretical",
"isotopic",
"cluster",
"for",
"composition",
"."
] | train | https://github.com/mobiusklein/brainpy/blob/4ccba40af33651a338c0c54bf1a251345c2db8da/brainpy/brainpy.py#L579-L611 |
MisterWil/skybellpy | skybellpy/__main__.py | call | def call():
"""Execute command line helper."""
args = get_arguments()
# Set up logging
if args.debug:
log_level = logging.DEBUG
elif args.quiet:
log_level = logging.WARN
else:
log_level = logging.INFO
setup_logging(log_level)
skybell = None
try:
# ... | python | def call():
"""Execute command line helper."""
args = get_arguments()
# Set up logging
if args.debug:
log_level = logging.DEBUG
elif args.quiet:
log_level = logging.WARN
else:
log_level = logging.INFO
setup_logging(log_level)
skybell = None
try:
# ... | [
"def",
"call",
"(",
")",
":",
"args",
"=",
"get_arguments",
"(",
")",
"# Set up logging",
"if",
"args",
".",
"debug",
":",
"log_level",
"=",
"logging",
".",
"DEBUG",
"elif",
"args",
".",
"quiet",
":",
"log_level",
"=",
"logging",
".",
"WARN",
"else",
"... | Execute command line helper. | [
"Execute",
"command",
"line",
"helper",
"."
] | train | https://github.com/MisterWil/skybellpy/blob/ac966d9f590cda7654f6de7eecc94e2103459eef/skybellpy/__main__.py#L140-L235 |
pjmark/NIMPA | niftypet/nimpa/prc/prc.py | trimim | def trimim( fims,
affine=None,
scale=2,
divdim = 8**2,
int_order=0,
fmax = 0.05,
outpath='',
fname='',
fcomment='',
store_avg=False,
store_img_intrmd=False,
store_img=False,
i... | python | def trimim( fims,
affine=None,
scale=2,
divdim = 8**2,
int_order=0,
fmax = 0.05,
outpath='',
fname='',
fcomment='',
store_avg=False,
store_img_intrmd=False,
store_img=False,
i... | [
"def",
"trimim",
"(",
"fims",
",",
"affine",
"=",
"None",
",",
"scale",
"=",
"2",
",",
"divdim",
"=",
"8",
"**",
"2",
",",
"int_order",
"=",
"0",
",",
"fmax",
"=",
"0.05",
",",
"outpath",
"=",
"''",
",",
"fname",
"=",
"''",
",",
"fcomment",
"="... | Trim and upsample PET image(s), e.g., for GPU execution,
PVC correction, ROI sampling, etc.
The input images 'fims' can be passed in multiple ways:
1. as a string of the folder containing NIfTI files
2. as a string of a NIfTI file path (this way a 4D image can be loaded).
3. as a list of NIfTI file ... | [
"Trim",
"and",
"upsample",
"PET",
"image",
"(",
"s",
")",
"e",
".",
"g",
".",
"for",
"GPU",
"execution",
"PVC",
"correction",
"ROI",
"sampling",
"etc",
".",
"The",
"input",
"images",
"fims",
"can",
"be",
"passed",
"in",
"multiple",
"ways",
":",
"1",
... | train | https://github.com/pjmark/NIMPA/blob/3f4231fed2934a1d92e4cd8e9e153b0118e29d86/niftypet/nimpa/prc/prc.py#L46-L347 |
pjmark/NIMPA | niftypet/nimpa/prc/prc.py | psf_general | def psf_general(vx_size=(1,1,1), fwhm=(5, 5, 6), hradius=8, scale=2):
'''
Separable kernels for convolution executed on the GPU device
The outputted kernels are in this order: z, y, x
'''
xSig = (scale*fwhm[0]/vx_size[0]) / (2*(2*np.log(2))**.5)
ySig = (scale*fwhm[1]/vx_size[1]) / (2*(2*np.log(2... | python | def psf_general(vx_size=(1,1,1), fwhm=(5, 5, 6), hradius=8, scale=2):
'''
Separable kernels for convolution executed on the GPU device
The outputted kernels are in this order: z, y, x
'''
xSig = (scale*fwhm[0]/vx_size[0]) / (2*(2*np.log(2))**.5)
ySig = (scale*fwhm[1]/vx_size[1]) / (2*(2*np.log(2... | [
"def",
"psf_general",
"(",
"vx_size",
"=",
"(",
"1",
",",
"1",
",",
"1",
")",
",",
"fwhm",
"=",
"(",
"5",
",",
"5",
",",
"6",
")",
",",
"hradius",
"=",
"8",
",",
"scale",
"=",
"2",
")",
":",
"xSig",
"=",
"(",
"scale",
"*",
"fwhm",
"[",
"0... | Separable kernels for convolution executed on the GPU device
The outputted kernels are in this order: z, y, x | [
"Separable",
"kernels",
"for",
"convolution",
"executed",
"on",
"the",
"GPU",
"device",
"The",
"outputted",
"kernels",
"are",
"in",
"this",
"order",
":",
"z",
"y",
"x"
] | train | https://github.com/pjmark/NIMPA/blob/3f4231fed2934a1d92e4cd8e9e153b0118e29d86/niftypet/nimpa/prc/prc.py#L356-L382 |
pjmark/NIMPA | niftypet/nimpa/prc/prc.py | iyang | def iyang(imgIn, krnl, imgSeg, Cnt, itr=5):
'''partial volume correction using iterative Yang method
imgIn: input image which is blurred due to the PSF of the scanner
krnl: shift invariant kernel of the PSF
imgSeg: segmentation into regions starting with 0 (e.g., background) and then next integer number... | python | def iyang(imgIn, krnl, imgSeg, Cnt, itr=5):
'''partial volume correction using iterative Yang method
imgIn: input image which is blurred due to the PSF of the scanner
krnl: shift invariant kernel of the PSF
imgSeg: segmentation into regions starting with 0 (e.g., background) and then next integer number... | [
"def",
"iyang",
"(",
"imgIn",
",",
"krnl",
",",
"imgSeg",
",",
"Cnt",
",",
"itr",
"=",
"5",
")",
":",
"dim",
"=",
"imgIn",
".",
"shape",
"m",
"=",
"np",
".",
"int32",
"(",
"np",
".",
"max",
"(",
"imgSeg",
")",
")",
"m_a",
"=",
"np",
".",
"z... | partial volume correction using iterative Yang method
imgIn: input image which is blurred due to the PSF of the scanner
krnl: shift invariant kernel of the PSF
imgSeg: segmentation into regions starting with 0 (e.g., background) and then next integer numbers
itr: number of iteration (default 5) | [
"partial",
"volume",
"correction",
"using",
"iterative",
"Yang",
"method",
"imgIn",
":",
"input",
"image",
"which",
"is",
"blurred",
"due",
"to",
"the",
"PSF",
"of",
"the",
"scanner",
"krnl",
":",
"shift",
"invariant",
"kernel",
"of",
"the",
"PSF",
"imgSeg",... | train | https://github.com/pjmark/NIMPA/blob/3f4231fed2934a1d92e4cd8e9e153b0118e29d86/niftypet/nimpa/prc/prc.py#L405-L453 |
pjmark/NIMPA | niftypet/nimpa/prc/prc.py | pvc_iyang | def pvc_iyang(
petin,
mridct,
Cnt,
pvcroi,
krnl,
itr=5,
tool='niftyreg',
faff='',
outpath='',
fcomment='',
store_img=False,
store_rois=False,
):
''' Perform partial volume (PVC) correction of PET data (petin) using M... | python | def pvc_iyang(
petin,
mridct,
Cnt,
pvcroi,
krnl,
itr=5,
tool='niftyreg',
faff='',
outpath='',
fcomment='',
store_img=False,
store_rois=False,
):
''' Perform partial volume (PVC) correction of PET data (petin) using M... | [
"def",
"pvc_iyang",
"(",
"petin",
",",
"mridct",
",",
"Cnt",
",",
"pvcroi",
",",
"krnl",
",",
"itr",
"=",
"5",
",",
"tool",
"=",
"'niftyreg'",
",",
"faff",
"=",
"''",
",",
"outpath",
"=",
"''",
",",
"fcomment",
"=",
"''",
",",
"store_img",
"=",
"... | Perform partial volume (PVC) correction of PET data (petin) using MRI data (mridct).
The PVC method uses iterative Yang method.
GPU based convolution is the key routine of the PVC.
Input:
-------
petin: either a dictionary containing image data, file name and affine transform,
... | [
"Perform",
"partial",
"volume",
"(",
"PVC",
")",
"correction",
"of",
"PET",
"data",
"(",
"petin",
")",
"using",
"MRI",
"data",
"(",
"mridct",
")",
".",
"The",
"PVC",
"method",
"uses",
"iterative",
"Yang",
"method",
".",
"GPU",
"based",
"convolution",
"is... | train | https://github.com/pjmark/NIMPA/blob/3f4231fed2934a1d92e4cd8e9e153b0118e29d86/niftypet/nimpa/prc/prc.py#L460-L664 |
pjmark/NIMPA | niftypet/nimpa/prc/prc.py | ct2mu | def ct2mu(im):
'''HU units to 511keV PET mu-values
https://link.springer.com/content/pdf/10.1007%2Fs00259-002-0796-3.pdf
C. Burger, et al., PET attenuation coefficients from CT images,
'''
# convert nans to -1024 for the HU values only
im[np.isnan(im)] = -1024
# constants
muwat... | python | def ct2mu(im):
'''HU units to 511keV PET mu-values
https://link.springer.com/content/pdf/10.1007%2Fs00259-002-0796-3.pdf
C. Burger, et al., PET attenuation coefficients from CT images,
'''
# convert nans to -1024 for the HU values only
im[np.isnan(im)] = -1024
# constants
muwat... | [
"def",
"ct2mu",
"(",
"im",
")",
":",
"# convert nans to -1024 for the HU values only",
"im",
"[",
"np",
".",
"isnan",
"(",
"im",
")",
"]",
"=",
"-",
"1024",
"# constants",
"muwater",
"=",
"0.096",
"mubone",
"=",
"0.172",
"rhowater",
"=",
"0.184",
"rhobone",
... | HU units to 511keV PET mu-values
https://link.springer.com/content/pdf/10.1007%2Fs00259-002-0796-3.pdf
C. Burger, et al., PET attenuation coefficients from CT images, | [
"HU",
"units",
"to",
"511keV",
"PET",
"mu",
"-",
"values",
"https",
":",
"//",
"link",
".",
"springer",
".",
"com",
"/",
"content",
"/",
"pdf",
"/",
"10",
".",
"1007%2Fs00259",
"-",
"002",
"-",
"0796",
"-",
"3",
".",
"pdf",
"C",
".",
"Burger",
"e... | train | https://github.com/pjmark/NIMPA/blob/3f4231fed2934a1d92e4cd8e9e153b0118e29d86/niftypet/nimpa/prc/prc.py#L669-L687 |
pjmark/NIMPA | niftypet/nimpa/prc/prc.py | centre_mass_img | def centre_mass_img(imdct):
''' Calculate the centre of mass of an image along each axes (x,y,z),
separately.
Arguments:
imdct - the image dictionary with the image and header data.
Output the list of the centre of mass for each axis.
'''
#> initialise centre of mass arr... | python | def centre_mass_img(imdct):
''' Calculate the centre of mass of an image along each axes (x,y,z),
separately.
Arguments:
imdct - the image dictionary with the image and header data.
Output the list of the centre of mass for each axis.
'''
#> initialise centre of mass arr... | [
"def",
"centre_mass_img",
"(",
"imdct",
")",
":",
"#> initialise centre of mass array",
"com",
"=",
"np",
".",
"zeros",
"(",
"3",
",",
"dtype",
"=",
"np",
".",
"float32",
")",
"#> total image sum",
"imsum",
"=",
"np",
".",
"sum",
"(",
"imdct",
"[",
"'im'",... | Calculate the centre of mass of an image along each axes (x,y,z),
separately.
Arguments:
imdct - the image dictionary with the image and header data.
Output the list of the centre of mass for each axis. | [
"Calculate",
"the",
"centre",
"of",
"mass",
"of",
"an",
"image",
"along",
"each",
"axes",
"(",
"x",
"y",
"z",
")",
"separately",
".",
"Arguments",
":",
"imdct",
"-",
"the",
"image",
"dictionary",
"with",
"the",
"image",
"and",
"header",
"data",
".",
"O... | train | https://github.com/pjmark/NIMPA/blob/3f4231fed2934a1d92e4cd8e9e153b0118e29d86/niftypet/nimpa/prc/prc.py#L693-L716 |
pjmark/NIMPA | niftypet/nimpa/prc/prc.py | nii_modify | def nii_modify(
nii,
fimout = '',
outpath = '',
fcomment = '',
voxel_range=[]):
''' Modify the NIfTI image given either as a file path or a dictionary,
obtained by nimpa.getnii(file_path).
'''
if isinstance(nii, basestring) and os.path.isfile(nii):
d... | python | def nii_modify(
nii,
fimout = '',
outpath = '',
fcomment = '',
voxel_range=[]):
''' Modify the NIfTI image given either as a file path or a dictionary,
obtained by nimpa.getnii(file_path).
'''
if isinstance(nii, basestring) and os.path.isfile(nii):
d... | [
"def",
"nii_modify",
"(",
"nii",
",",
"fimout",
"=",
"''",
",",
"outpath",
"=",
"''",
",",
"fcomment",
"=",
"''",
",",
"voxel_range",
"=",
"[",
"]",
")",
":",
"if",
"isinstance",
"(",
"nii",
",",
"basestring",
")",
"and",
"os",
".",
"path",
".",
... | Modify the NIfTI image given either as a file path or a dictionary,
obtained by nimpa.getnii(file_path). | [
"Modify",
"the",
"NIfTI",
"image",
"given",
"either",
"as",
"a",
"file",
"path",
"or",
"a",
"dictionary",
"obtained",
"by",
"nimpa",
".",
"getnii",
"(",
"file_path",
")",
"."
] | train | https://github.com/pjmark/NIMPA/blob/3f4231fed2934a1d92e4cd8e9e153b0118e29d86/niftypet/nimpa/prc/prc.py#L721-L791 |
pjmark/NIMPA | niftypet/nimpa/prc/prc.py | bias_field_correction | def bias_field_correction(
fmr,
fimout = '',
outpath = '',
fcomment = '_N4bias',
executable = '',
exe_options = [],
sitk_image_mask = True,
verbose = False,):
''' Correct for bias field in MR image(s) given in <fmr> as a string
(single file) o... | python | def bias_field_correction(
fmr,
fimout = '',
outpath = '',
fcomment = '_N4bias',
executable = '',
exe_options = [],
sitk_image_mask = True,
verbose = False,):
''' Correct for bias field in MR image(s) given in <fmr> as a string
(single file) o... | [
"def",
"bias_field_correction",
"(",
"fmr",
",",
"fimout",
"=",
"''",
",",
"outpath",
"=",
"''",
",",
"fcomment",
"=",
"'_N4bias'",
",",
"executable",
"=",
"''",
",",
"exe_options",
"=",
"[",
"]",
",",
"sitk_image_mask",
"=",
"True",
",",
"verbose",
"=",... | Correct for bias field in MR image(s) given in <fmr> as a string
(single file) or as a list of strings (multiple files).
Output dictionary with the bias corrected file names.
Options:
- fimout: The name (with path) of the output file. It's
ignored when... | [
"Correct",
"for",
"bias",
"field",
"in",
"MR",
"image",
"(",
"s",
")",
"given",
"in",
"<fmr",
">",
"as",
"a",
"string",
"(",
"single",
"file",
")",
"or",
"as",
"a",
"list",
"of",
"strings",
"(",
"multiple",
"files",
")",
"."
] | train | https://github.com/pjmark/NIMPA/blob/3f4231fed2934a1d92e4cd8e9e153b0118e29d86/niftypet/nimpa/prc/prc.py#L808-L983 |
pjmark/NIMPA | niftypet/nimpa/prc/prc.py | roi_extraction | def roi_extraction(imdic, amyroi, datain, Cnt, use_stored=False):
'''
Extracting ROI values of upsampled PET. If not provided it will be upsampled.
imdic: dictionary of all image parts (image, path to file and affine transformation)
> fpet: file name for quantitative PET
> faff: file name and... | python | def roi_extraction(imdic, amyroi, datain, Cnt, use_stored=False):
'''
Extracting ROI values of upsampled PET. If not provided it will be upsampled.
imdic: dictionary of all image parts (image, path to file and affine transformation)
> fpet: file name for quantitative PET
> faff: file name and... | [
"def",
"roi_extraction",
"(",
"imdic",
",",
"amyroi",
",",
"datain",
",",
"Cnt",
",",
"use_stored",
"=",
"False",
")",
":",
"fpet",
"=",
"imdic",
"[",
"'fpet'",
"]",
"faff",
"=",
"imdic",
"[",
"'faff'",
"]",
"im",
"=",
"imdic",
"[",
"'im'",
"]",
"i... | Extracting ROI values of upsampled PET. If not provided it will be upsampled.
imdic: dictionary of all image parts (image, path to file and affine transformation)
> fpet: file name for quantitative PET
> faff: file name and path to the affine (rigid) transformations, most likely for upscaled PET
... | [
"Extracting",
"ROI",
"values",
"of",
"upsampled",
"PET",
".",
"If",
"not",
"provided",
"it",
"will",
"be",
"upsampled",
".",
"imdic",
":",
"dictionary",
"of",
"all",
"image",
"parts",
"(",
"image",
"path",
"to",
"file",
"and",
"affine",
"transformation",
"... | train | https://github.com/pjmark/NIMPA/blob/3f4231fed2934a1d92e4cd8e9e153b0118e29d86/niftypet/nimpa/prc/prc.py#L1143-L1254 |
pjmark/NIMPA | niftypet/nimpa/prc/imio.py | getnii | def getnii(fim, nan_replace=None, output='image'):
'''Get PET image from NIfTI file.
fim: input file name for the nifty image
nan_replace: the value to be used for replacing the NaNs in the image.
by default no change (None).
output: option for choosing output: image, affine matri... | python | def getnii(fim, nan_replace=None, output='image'):
'''Get PET image from NIfTI file.
fim: input file name for the nifty image
nan_replace: the value to be used for replacing the NaNs in the image.
by default no change (None).
output: option for choosing output: image, affine matri... | [
"def",
"getnii",
"(",
"fim",
",",
"nan_replace",
"=",
"None",
",",
"output",
"=",
"'image'",
")",
":",
"import",
"numbers",
"nim",
"=",
"nib",
".",
"load",
"(",
"fim",
")",
"dim",
"=",
"nim",
".",
"header",
".",
"get",
"(",
"'dim'",
")",
"dimno",
... | Get PET image from NIfTI file.
fim: input file name for the nifty image
nan_replace: the value to be used for replacing the NaNs in the image.
by default no change (None).
output: option for choosing output: image, affine matrix or a dictionary with all info.
----------
Return... | [
"Get",
"PET",
"image",
"from",
"NIfTI",
"file",
".",
"fim",
":",
"input",
"file",
"name",
"for",
"the",
"nifty",
"image",
"nan_replace",
":",
"the",
"value",
"to",
"be",
"used",
"for",
"replacing",
"the",
"NaNs",
"in",
"the",
"image",
".",
"by",
"defau... | train | https://github.com/pjmark/NIMPA/blob/3f4231fed2934a1d92e4cd8e9e153b0118e29d86/niftypet/nimpa/prc/imio.py#L47-L109 |
pjmark/NIMPA | niftypet/nimpa/prc/imio.py | getnii_descr | def getnii_descr(fim):
'''
Extracts the custom description header field to dictionary
'''
nim = nib.load(fim)
hdr = nim.header
rcnlst = hdr['descrip'].item().split(';')
rcndic = {}
if rcnlst[0]=='':
# print 'w> no description in the NIfTI header'
return rcndic
... | python | def getnii_descr(fim):
'''
Extracts the custom description header field to dictionary
'''
nim = nib.load(fim)
hdr = nim.header
rcnlst = hdr['descrip'].item().split(';')
rcndic = {}
if rcnlst[0]=='':
# print 'w> no description in the NIfTI header'
return rcndic
... | [
"def",
"getnii_descr",
"(",
"fim",
")",
":",
"nim",
"=",
"nib",
".",
"load",
"(",
"fim",
")",
"hdr",
"=",
"nim",
".",
"header",
"rcnlst",
"=",
"hdr",
"[",
"'descrip'",
"]",
".",
"item",
"(",
")",
".",
"split",
"(",
"';'",
")",
"rcndic",
"=",
"{... | Extracts the custom description header field to dictionary | [
"Extracts",
"the",
"custom",
"description",
"header",
"field",
"to",
"dictionary"
] | train | https://github.com/pjmark/NIMPA/blob/3f4231fed2934a1d92e4cd8e9e153b0118e29d86/niftypet/nimpa/prc/imio.py#L111-L127 |
pjmark/NIMPA | niftypet/nimpa/prc/imio.py | array2nii | def array2nii(im, A, fnii, descrip='', trnsp=(), flip=(), storage_as=[]):
'''Store the numpy array 'im' to a NIfTI file 'fnii'.
----
Arguments:
'im': image to be stored in NIfTI
'A': affine transformation
'fnii': output NIfTI file name.
'descrip': the descri... | python | def array2nii(im, A, fnii, descrip='', trnsp=(), flip=(), storage_as=[]):
'''Store the numpy array 'im' to a NIfTI file 'fnii'.
----
Arguments:
'im': image to be stored in NIfTI
'A': affine transformation
'fnii': output NIfTI file name.
'descrip': the descri... | [
"def",
"array2nii",
"(",
"im",
",",
"A",
",",
"fnii",
",",
"descrip",
"=",
"''",
",",
"trnsp",
"=",
"(",
")",
",",
"flip",
"=",
"(",
")",
",",
"storage_as",
"=",
"[",
"]",
")",
":",
"if",
"not",
"len",
"(",
"trnsp",
")",
"in",
"[",
"0",
","... | Store the numpy array 'im' to a NIfTI file 'fnii'.
----
Arguments:
'im': image to be stored in NIfTI
'A': affine transformation
'fnii': output NIfTI file name.
'descrip': the description given to the file
'trsnp': transpose/permute the dimensions.
... | [
"Store",
"the",
"numpy",
"array",
"im",
"to",
"a",
"NIfTI",
"file",
"fnii",
".",
"----",
"Arguments",
":",
"im",
":",
"image",
"to",
"be",
"stored",
"in",
"NIfTI",
"A",
":",
"affine",
"transformation",
"fnii",
":",
"output",
"NIfTI",
"file",
"name",
".... | train | https://github.com/pjmark/NIMPA/blob/3f4231fed2934a1d92e4cd8e9e153b0118e29d86/niftypet/nimpa/prc/imio.py#L130-L187 |
pjmark/NIMPA | niftypet/nimpa/prc/imio.py | orientnii | def orientnii(imfile):
'''Get the orientation from NIfTI sform. Not fully functional yet.'''
strorient = ['L-R', 'S-I', 'A-P']
niiorient = []
niixyz = np.zeros(3,dtype=np.int8)
if os.path.isfile(imfile):
nim = nib.load(imfile)
pct = nim.get_data()
A = nim.get_sform()
... | python | def orientnii(imfile):
'''Get the orientation from NIfTI sform. Not fully functional yet.'''
strorient = ['L-R', 'S-I', 'A-P']
niiorient = []
niixyz = np.zeros(3,dtype=np.int8)
if os.path.isfile(imfile):
nim = nib.load(imfile)
pct = nim.get_data()
A = nim.get_sform()
... | [
"def",
"orientnii",
"(",
"imfile",
")",
":",
"strorient",
"=",
"[",
"'L-R'",
",",
"'S-I'",
",",
"'A-P'",
"]",
"niiorient",
"=",
"[",
"]",
"niixyz",
"=",
"np",
".",
"zeros",
"(",
"3",
",",
"dtype",
"=",
"np",
".",
"int8",
")",
"if",
"os",
".",
"... | Get the orientation from NIfTI sform. Not fully functional yet. | [
"Get",
"the",
"orientation",
"from",
"NIfTI",
"sform",
".",
"Not",
"fully",
"functional",
"yet",
"."
] | train | https://github.com/pjmark/NIMPA/blob/3f4231fed2934a1d92e4cd8e9e153b0118e29d86/niftypet/nimpa/prc/imio.py#L191-L203 |
pjmark/NIMPA | niftypet/nimpa/prc/imio.py | nii_ugzip | def nii_ugzip(imfile, outpath=''):
'''Uncompress *.gz file'''
import gzip
with gzip.open(imfile, 'rb') as f:
s = f.read()
# Now store the uncompressed data
if outpath=='':
fout = imfile[:-3]
else:
fout = os.path.join(outpath, os.path.basename(imfile)[:-3])
# store unc... | python | def nii_ugzip(imfile, outpath=''):
'''Uncompress *.gz file'''
import gzip
with gzip.open(imfile, 'rb') as f:
s = f.read()
# Now store the uncompressed data
if outpath=='':
fout = imfile[:-3]
else:
fout = os.path.join(outpath, os.path.basename(imfile)[:-3])
# store unc... | [
"def",
"nii_ugzip",
"(",
"imfile",
",",
"outpath",
"=",
"''",
")",
":",
"import",
"gzip",
"with",
"gzip",
".",
"open",
"(",
"imfile",
",",
"'rb'",
")",
"as",
"f",
":",
"s",
"=",
"f",
".",
"read",
"(",
")",
"# Now store the uncompressed data",
"if",
"... | Uncompress *.gz file | [
"Uncompress",
"*",
".",
"gz",
"file"
] | train | https://github.com/pjmark/NIMPA/blob/3f4231fed2934a1d92e4cd8e9e153b0118e29d86/niftypet/nimpa/prc/imio.py#L205-L218 |
pjmark/NIMPA | niftypet/nimpa/prc/imio.py | nii_gzip | def nii_gzip(imfile, outpath=''):
'''Compress *.gz file'''
import gzip
with open(imfile, 'rb') as f:
d = f.read()
# Now store the compressed data
if outpath=='':
fout = imfile+'.gz'
else:
fout = os.path.join(outpath, os.path.basename(imfile)+'.gz')
# store compressed ... | python | def nii_gzip(imfile, outpath=''):
'''Compress *.gz file'''
import gzip
with open(imfile, 'rb') as f:
d = f.read()
# Now store the compressed data
if outpath=='':
fout = imfile+'.gz'
else:
fout = os.path.join(outpath, os.path.basename(imfile)+'.gz')
# store compressed ... | [
"def",
"nii_gzip",
"(",
"imfile",
",",
"outpath",
"=",
"''",
")",
":",
"import",
"gzip",
"with",
"open",
"(",
"imfile",
",",
"'rb'",
")",
"as",
"f",
":",
"d",
"=",
"f",
".",
"read",
"(",
")",
"# Now store the compressed data",
"if",
"outpath",
"==",
... | Compress *.gz file | [
"Compress",
"*",
".",
"gz",
"file"
] | train | https://github.com/pjmark/NIMPA/blob/3f4231fed2934a1d92e4cd8e9e153b0118e29d86/niftypet/nimpa/prc/imio.py#L220-L233 |
pjmark/NIMPA | niftypet/nimpa/prc/imio.py | pick_t1w | def pick_t1w(mri):
''' Pick the MR T1w from the dictionary for MR->PET registration.
'''
if isinstance(mri, dict):
# check if NIfTI file is given
if 'T1N4' in mri and os.path.isfile(mri['T1N4']):
ft1w = mri['T1N4']
# or another bias corrected
elif 'T1bc' in mri a... | python | def pick_t1w(mri):
''' Pick the MR T1w from the dictionary for MR->PET registration.
'''
if isinstance(mri, dict):
# check if NIfTI file is given
if 'T1N4' in mri and os.path.isfile(mri['T1N4']):
ft1w = mri['T1N4']
# or another bias corrected
elif 'T1bc' in mri a... | [
"def",
"pick_t1w",
"(",
"mri",
")",
":",
"if",
"isinstance",
"(",
"mri",
",",
"dict",
")",
":",
"# check if NIfTI file is given",
"if",
"'T1N4'",
"in",
"mri",
"and",
"os",
".",
"path",
".",
"isfile",
"(",
"mri",
"[",
"'T1N4'",
"]",
")",
":",
"ft1w",
... | Pick the MR T1w from the dictionary for MR->PET registration. | [
"Pick",
"the",
"MR",
"T1w",
"from",
"the",
"dictionary",
"for",
"MR",
"-",
">",
"PET",
"registration",
"."
] | train | https://github.com/pjmark/NIMPA/blob/3f4231fed2934a1d92e4cd8e9e153b0118e29d86/niftypet/nimpa/prc/imio.py#L237-L264 |
pjmark/NIMPA | niftypet/nimpa/prc/imio.py | dcminfo | def dcminfo(dcmvar, verbose=True):
''' Get basic info about the DICOM file/header.
'''
if isinstance(dcmvar, basestring):
if verbose:
print 'i> provided DICOM file:', dcmvar
dhdr = dcm.dcmread(dcmvar)
elif isinstance(dcmvar, dict):
dhdr = dcmvar
elif isinstance(d... | python | def dcminfo(dcmvar, verbose=True):
''' Get basic info about the DICOM file/header.
'''
if isinstance(dcmvar, basestring):
if verbose:
print 'i> provided DICOM file:', dcmvar
dhdr = dcm.dcmread(dcmvar)
elif isinstance(dcmvar, dict):
dhdr = dcmvar
elif isinstance(d... | [
"def",
"dcminfo",
"(",
"dcmvar",
",",
"verbose",
"=",
"True",
")",
":",
"if",
"isinstance",
"(",
"dcmvar",
",",
"basestring",
")",
":",
"if",
"verbose",
":",
"print",
"'i> provided DICOM file:'",
",",
"dcmvar",
"dhdr",
"=",
"dcm",
".",
"dcmread",
"(",
"d... | Get basic info about the DICOM file/header. | [
"Get",
"basic",
"info",
"about",
"the",
"DICOM",
"file",
"/",
"header",
"."
] | train | https://github.com/pjmark/NIMPA/blob/3f4231fed2934a1d92e4cd8e9e153b0118e29d86/niftypet/nimpa/prc/imio.py#L267-L355 |
pjmark/NIMPA | niftypet/nimpa/prc/imio.py | list_dcm_datain | def list_dcm_datain(datain):
''' List all DICOM file paths in the datain dictionary of input data.
'''
if not isinstance(datain, dict):
raise ValueError('The input is not a dictionary!')
dcmlst = []
# list of mu-map DICOM files
if 'mumapDCM' in datain:
dcmump = os.listdir(datai... | python | def list_dcm_datain(datain):
''' List all DICOM file paths in the datain dictionary of input data.
'''
if not isinstance(datain, dict):
raise ValueError('The input is not a dictionary!')
dcmlst = []
# list of mu-map DICOM files
if 'mumapDCM' in datain:
dcmump = os.listdir(datai... | [
"def",
"list_dcm_datain",
"(",
"datain",
")",
":",
"if",
"not",
"isinstance",
"(",
"datain",
",",
"dict",
")",
":",
"raise",
"ValueError",
"(",
"'The input is not a dictionary!'",
")",
"dcmlst",
"=",
"[",
"]",
"# list of mu-map DICOM files",
"if",
"'mumapDCM'",
... | List all DICOM file paths in the datain dictionary of input data. | [
"List",
"all",
"DICOM",
"file",
"paths",
"in",
"the",
"datain",
"dictionary",
"of",
"input",
"data",
"."
] | train | https://github.com/pjmark/NIMPA/blob/3f4231fed2934a1d92e4cd8e9e153b0118e29d86/niftypet/nimpa/prc/imio.py#L358-L411 |
pjmark/NIMPA | niftypet/nimpa/prc/imio.py | dcmanonym | def dcmanonym(
dcmpth,
displayonly=False,
patient='anonymised',
physician='anonymised',
dob='19800101',
verbose=True):
''' Anonymise DICOM file(s)
Arguments:
> dcmpth: it can be passed as a single DICOM file, or
a folder containi... | python | def dcmanonym(
dcmpth,
displayonly=False,
patient='anonymised',
physician='anonymised',
dob='19800101',
verbose=True):
''' Anonymise DICOM file(s)
Arguments:
> dcmpth: it can be passed as a single DICOM file, or
a folder containi... | [
"def",
"dcmanonym",
"(",
"dcmpth",
",",
"displayonly",
"=",
"False",
",",
"patient",
"=",
"'anonymised'",
",",
"physician",
"=",
"'anonymised'",
",",
"dob",
"=",
"'19800101'",
",",
"verbose",
"=",
"True",
")",
":",
"#> check if a single DICOM file",
"if",
"isi... | Anonymise DICOM file(s)
Arguments:
> dcmpth: it can be passed as a single DICOM file, or
a folder containing DICOM files, or a list of DICOM file paths.
> patient: the name of the patient.
> physician:the name of the referring physician.
> dob: patient... | [
"Anonymise",
"DICOM",
"file",
"(",
"s",
")",
"Arguments",
":",
">",
"dcmpth",
":",
"it",
"can",
"be",
"passed",
"as",
"a",
"single",
"DICOM",
"file",
"or",
"a",
"folder",
"containing",
"DICOM",
"files",
"or",
"a",
"list",
"of",
"DICOM",
"file",
"paths"... | train | https://github.com/pjmark/NIMPA/blob/3f4231fed2934a1d92e4cd8e9e153b0118e29d86/niftypet/nimpa/prc/imio.py#L415-L550 |
pjmark/NIMPA | niftypet/nimpa/prc/imio.py | dcmsort | def dcmsort(folder, copy_series=False, verbose=False):
''' Sort out the DICOM files in the folder according to the recorded series.
'''
# list files in the input folder
files = os.listdir(folder)
srs = {}
for f in files:
if os.path.isfile(os.path.join(folder, f)) and f.endswith(dcmext)... | python | def dcmsort(folder, copy_series=False, verbose=False):
''' Sort out the DICOM files in the folder according to the recorded series.
'''
# list files in the input folder
files = os.listdir(folder)
srs = {}
for f in files:
if os.path.isfile(os.path.join(folder, f)) and f.endswith(dcmext)... | [
"def",
"dcmsort",
"(",
"folder",
",",
"copy_series",
"=",
"False",
",",
"verbose",
"=",
"False",
")",
":",
"# list files in the input folder",
"files",
"=",
"os",
".",
"listdir",
"(",
"folder",
")",
"srs",
"=",
"{",
"}",
"for",
"f",
"in",
"files",
":",
... | Sort out the DICOM files in the folder according to the recorded series. | [
"Sort",
"out",
"the",
"DICOM",
"files",
"in",
"the",
"folder",
"according",
"to",
"the",
"recorded",
"series",
"."
] | train | https://github.com/pjmark/NIMPA/blob/3f4231fed2934a1d92e4cd8e9e153b0118e29d86/niftypet/nimpa/prc/imio.py#L557-L625 |
pjmark/NIMPA | niftypet/nimpa/prc/imio.py | niisort | def niisort(
fims,
memlim=True
):
''' Sort all input NIfTI images and check their shape.
Output dictionary of image files and their properties.
Options:
memlim -- when processing large numbers of frames the memory may
not be large enough. memlim causes t... | python | def niisort(
fims,
memlim=True
):
''' Sort all input NIfTI images and check their shape.
Output dictionary of image files and their properties.
Options:
memlim -- when processing large numbers of frames the memory may
not be large enough. memlim causes t... | [
"def",
"niisort",
"(",
"fims",
",",
"memlim",
"=",
"True",
")",
":",
"# number of NIfTI images in folder",
"Nim",
"=",
"0",
"# sorting list (if frame number is present in the form '_frm<dd>', where d is a digit)",
"sortlist",
"=",
"[",
"]",
"for",
"f",
"in",
"fims",
":"... | Sort all input NIfTI images and check their shape.
Output dictionary of image files and their properties.
Options:
memlim -- when processing large numbers of frames the memory may
not be large enough. memlim causes that the output does not contain
all the arrays corr... | [
"Sort",
"all",
"input",
"NIfTI",
"images",
"and",
"check",
"their",
"shape",
".",
"Output",
"dictionary",
"of",
"image",
"files",
"and",
"their",
"properties",
".",
"Options",
":",
"memlim",
"--",
"when",
"processing",
"large",
"numbers",
"of",
"frames",
"th... | train | https://github.com/pjmark/NIMPA/blob/3f4231fed2934a1d92e4cd8e9e153b0118e29d86/niftypet/nimpa/prc/imio.py#L633-L726 |
pjmark/NIMPA | niftypet/nimpa/prc/imio.py | dcm2nii | def dcm2nii(
dcmpth,
fimout = '',
fprefix = 'converted-from-DICOM_',
fcomment = '',
outpath = '',
timestamp = True,
executable = '',
force = False,
):
''' Convert DICOM files in folder (indicated by <dcmpth>) using DCM2NIIX
third-party soft... | python | def dcm2nii(
dcmpth,
fimout = '',
fprefix = 'converted-from-DICOM_',
fcomment = '',
outpath = '',
timestamp = True,
executable = '',
force = False,
):
''' Convert DICOM files in folder (indicated by <dcmpth>) using DCM2NIIX
third-party soft... | [
"def",
"dcm2nii",
"(",
"dcmpth",
",",
"fimout",
"=",
"''",
",",
"fprefix",
"=",
"'converted-from-DICOM_'",
",",
"fcomment",
"=",
"''",
",",
"outpath",
"=",
"''",
",",
"timestamp",
"=",
"True",
",",
"executable",
"=",
"''",
",",
"force",
"=",
"False",
"... | Convert DICOM files in folder (indicated by <dcmpth>) using DCM2NIIX
third-party software. | [
"Convert",
"DICOM",
"files",
"in",
"folder",
"(",
"indicated",
"by",
"<dcmpth",
">",
")",
"using",
"DCM2NIIX",
"third",
"-",
"party",
"software",
"."
] | train | https://github.com/pjmark/NIMPA/blob/3f4231fed2934a1d92e4cd8e9e153b0118e29d86/niftypet/nimpa/prc/imio.py#L730-L792 |
pjmark/NIMPA | niftypet/nimpa/prc/imio.py | dcm2im | def dcm2im(fpth):
''' Get the DICOM files from 'fpth' into an image with the affine transformation.
fpth can be a list of DICOM files or a path (string) to the folder with DICOM files.
'''
# possible DICOM file extensions
ext = ('dcm', 'DCM', 'ima', 'IMA')
# case when given a folder p... | python | def dcm2im(fpth):
''' Get the DICOM files from 'fpth' into an image with the affine transformation.
fpth can be a list of DICOM files or a path (string) to the folder with DICOM files.
'''
# possible DICOM file extensions
ext = ('dcm', 'DCM', 'ima', 'IMA')
# case when given a folder p... | [
"def",
"dcm2im",
"(",
"fpth",
")",
":",
"# possible DICOM file extensions",
"ext",
"=",
"(",
"'dcm'",
",",
"'DCM'",
",",
"'ima'",
",",
"'IMA'",
")",
"# case when given a folder path",
"if",
"isinstance",
"(",
"fpth",
",",
"basestring",
")",
"and",
"os",
".",
... | Get the DICOM files from 'fpth' into an image with the affine transformation.
fpth can be a list of DICOM files or a path (string) to the folder with DICOM files. | [
"Get",
"the",
"DICOM",
"files",
"from",
"fpth",
"into",
"an",
"image",
"with",
"the",
"affine",
"transformation",
".",
"fpth",
"can",
"be",
"a",
"list",
"of",
"DICOM",
"files",
"or",
"a",
"path",
"(",
"string",
")",
"to",
"the",
"folder",
"with",
"DICO... | train | https://github.com/pjmark/NIMPA/blob/3f4231fed2934a1d92e4cd8e9e153b0118e29d86/niftypet/nimpa/prc/imio.py#L798-L929 |
pjmark/NIMPA | cudasetup.py | path_niftypet_local | def path_niftypet_local():
'''Get the path to the local (home) folder for NiftyPET resources.'''
# if using conda put the resources in the folder with the environment name
if 'CONDA_DEFAULT_ENV' in os.environ:
env = os.environ['CONDA_DEFAULT_ENV']
print 'i> conda environment found:', env
... | python | def path_niftypet_local():
'''Get the path to the local (home) folder for NiftyPET resources.'''
# if using conda put the resources in the folder with the environment name
if 'CONDA_DEFAULT_ENV' in os.environ:
env = os.environ['CONDA_DEFAULT_ENV']
print 'i> conda environment found:', env
... | [
"def",
"path_niftypet_local",
"(",
")",
":",
"# if using conda put the resources in the folder with the environment name",
"if",
"'CONDA_DEFAULT_ENV'",
"in",
"os",
".",
"environ",
":",
"env",
"=",
"os",
".",
"environ",
"[",
"'CONDA_DEFAULT_ENV'",
"]",
"print",
"'i> conda ... | Get the path to the local (home) folder for NiftyPET resources. | [
"Get",
"the",
"path",
"to",
"the",
"local",
"(",
"home",
")",
"folder",
"for",
"NiftyPET",
"resources",
"."
] | train | https://github.com/pjmark/NIMPA/blob/3f4231fed2934a1d92e4cd8e9e153b0118e29d86/cudasetup.py#L32-L50 |
pjmark/NIMPA | cudasetup.py | find_cuda | def find_cuda():
'''Locate the CUDA environment on the system.'''
# search the PATH for NVCC
for fldr in os.environ['PATH'].split(os.pathsep):
cuda_path = join(fldr, 'nvcc')
if os.path.exists(cuda_path):
cuda_path = os.path.dirname(os.path.dirname(cuda_path))
break
... | python | def find_cuda():
'''Locate the CUDA environment on the system.'''
# search the PATH for NVCC
for fldr in os.environ['PATH'].split(os.pathsep):
cuda_path = join(fldr, 'nvcc')
if os.path.exists(cuda_path):
cuda_path = os.path.dirname(os.path.dirname(cuda_path))
break
... | [
"def",
"find_cuda",
"(",
")",
":",
"# search the PATH for NVCC",
"for",
"fldr",
"in",
"os",
".",
"environ",
"[",
"'PATH'",
"]",
".",
"split",
"(",
"os",
".",
"pathsep",
")",
":",
"cuda_path",
"=",
"join",
"(",
"fldr",
",",
"'nvcc'",
")",
"if",
"os",
... | Locate the CUDA environment on the system. | [
"Locate",
"the",
"CUDA",
"environment",
"on",
"the",
"system",
"."
] | train | https://github.com/pjmark/NIMPA/blob/3f4231fed2934a1d92e4cd8e9e153b0118e29d86/cudasetup.py#L53-L78 |
pjmark/NIMPA | cudasetup.py | dev_setup | def dev_setup():
'''figure out what GPU devices are available and choose the supported ones.'''
# check first if NiftyPET was already installed and use the choice of GPU
path_resources = path_niftypet_local()
# if so, import the resources and get the constants
if os.path.isfile(os.path.join(path_re... | python | def dev_setup():
'''figure out what GPU devices are available and choose the supported ones.'''
# check first if NiftyPET was already installed and use the choice of GPU
path_resources = path_niftypet_local()
# if so, import the resources and get the constants
if os.path.isfile(os.path.join(path_re... | [
"def",
"dev_setup",
"(",
")",
":",
"# check first if NiftyPET was already installed and use the choice of GPU",
"path_resources",
"=",
"path_niftypet_local",
"(",
")",
"# if so, import the resources and get the constants",
"if",
"os",
".",
"path",
".",
"isfile",
"(",
"os",
".... | figure out what GPU devices are available and choose the supported ones. | [
"figure",
"out",
"what",
"GPU",
"devices",
"are",
"available",
"and",
"choose",
"the",
"supported",
"ones",
"."
] | train | https://github.com/pjmark/NIMPA/blob/3f4231fed2934a1d92e4cd8e9e153b0118e29d86/cudasetup.py#L82-L202 |
pjmark/NIMPA | cudasetup.py | resources_setup | def resources_setup():
'''
This function checks CUDA devices, selects some and installs resources.py
'''
print 'i> installing file <resources.py> into home directory if it does not exist.'
path_current = os.path.dirname( os.path.realpath(__file__) )
# path to the install version of resources.py.... | python | def resources_setup():
'''
This function checks CUDA devices, selects some and installs resources.py
'''
print 'i> installing file <resources.py> into home directory if it does not exist.'
path_current = os.path.dirname( os.path.realpath(__file__) )
# path to the install version of resources.py.... | [
"def",
"resources_setup",
"(",
")",
":",
"print",
"'i> installing file <resources.py> into home directory if it does not exist.'",
"path_current",
"=",
"os",
".",
"path",
".",
"dirname",
"(",
"os",
".",
"path",
".",
"realpath",
"(",
"__file__",
")",
")",
"# path to th... | This function checks CUDA devices, selects some and installs resources.py | [
"This",
"function",
"checks",
"CUDA",
"devices",
"selects",
"some",
"and",
"installs",
"resources",
".",
"py"
] | train | https://github.com/pjmark/NIMPA/blob/3f4231fed2934a1d92e4cd8e9e153b0118e29d86/cudasetup.py#L205-L245 |
Syndace/python-omemo | omemo/promise.py | coroutine | def coroutine(f):
"""
Implementation of a coroutine.
Use as a decorator:
@coroutine
def foo():
result = yield somePromise
The function passed should be a generator yielding instances of the Promise class
(or compatible).
The coroutine waits for the Promise to resolve and sends ... | python | def coroutine(f):
"""
Implementation of a coroutine.
Use as a decorator:
@coroutine
def foo():
result = yield somePromise
The function passed should be a generator yielding instances of the Promise class
(or compatible).
The coroutine waits for the Promise to resolve and sends ... | [
"def",
"coroutine",
"(",
"f",
")",
":",
"@",
"functools",
".",
"wraps",
"(",
"f",
")",
"def",
"_coroutine",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"def",
"_resolver",
"(",
"resolve",
",",
"reject",
")",
":",
"try",
":",
"generator",
... | Implementation of a coroutine.
Use as a decorator:
@coroutine
def foo():
result = yield somePromise
The function passed should be a generator yielding instances of the Promise class
(or compatible).
The coroutine waits for the Promise to resolve and sends the result (or the error)
... | [
"Implementation",
"of",
"a",
"coroutine",
"."
] | train | https://github.com/Syndace/python-omemo/blob/f99be4715a3fad4d3082f5093aceb2c42385b8bd/omemo/promise.py#L164-L225 |
Syndace/python-omemo | omemo/promise.py | no_coroutine | def no_coroutine(f):
"""
This is not a coroutine ;)
Use as a decorator:
@no_coroutine
def foo():
five = yield 5
print(yield "hello")
The function passed should be a generator yielding whatever you feel like.
The yielded values instantly get passed back into the generator.
... | python | def no_coroutine(f):
"""
This is not a coroutine ;)
Use as a decorator:
@no_coroutine
def foo():
five = yield 5
print(yield "hello")
The function passed should be a generator yielding whatever you feel like.
The yielded values instantly get passed back into the generator.
... | [
"def",
"no_coroutine",
"(",
"f",
")",
":",
"@",
"functools",
".",
"wraps",
"(",
"f",
")",
"def",
"_no_coroutine",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"generator",
"=",
"f",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"# Speci... | This is not a coroutine ;)
Use as a decorator:
@no_coroutine
def foo():
five = yield 5
print(yield "hello")
The function passed should be a generator yielding whatever you feel like.
The yielded values instantly get passed back into the generator.
It's basically the same as if ... | [
"This",
"is",
"not",
"a",
"coroutine",
";",
")"
] | train | https://github.com/Syndace/python-omemo/blob/f99be4715a3fad4d3082f5093aceb2c42385b8bd/omemo/promise.py#L227-L276 |
Syndace/python-omemo | omemo/promise.py | maybe_coroutine | def maybe_coroutine(decide):
"""
Either be a coroutine or not.
Use as a decorator:
@maybe_coroutine(lambda maybeAPromise: return isinstance(maybeAPromise, Promise))
def foo(maybeAPromise):
result = yield maybeAPromise
print("hello")
return result
The function passed sho... | python | def maybe_coroutine(decide):
"""
Either be a coroutine or not.
Use as a decorator:
@maybe_coroutine(lambda maybeAPromise: return isinstance(maybeAPromise, Promise))
def foo(maybeAPromise):
result = yield maybeAPromise
print("hello")
return result
The function passed sho... | [
"def",
"maybe_coroutine",
"(",
"decide",
")",
":",
"def",
"_maybe_coroutine",
"(",
"f",
")",
":",
"@",
"functools",
".",
"wraps",
"(",
"f",
")",
"def",
"__maybe_coroutine",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"decide",
"(",
"*"... | Either be a coroutine or not.
Use as a decorator:
@maybe_coroutine(lambda maybeAPromise: return isinstance(maybeAPromise, Promise))
def foo(maybeAPromise):
result = yield maybeAPromise
print("hello")
return result
The function passed should be a generator yielding either only P... | [
"Either",
"be",
"a",
"coroutine",
"or",
"not",
"."
] | train | https://github.com/Syndace/python-omemo/blob/f99be4715a3fad4d3082f5093aceb2c42385b8bd/omemo/promise.py#L278-L321 |
Syndace/python-omemo | omemo/storagewrapper.py | makeCallbackPromise | def makeCallbackPromise(function, *args, **kwargs):
"""
Take a function that reports its result using a callback and return a Promise that
listenes for this callback.
The function must accept a callback as its first parameter.
The callback must take two arguments:
- success : True or False
... | python | def makeCallbackPromise(function, *args, **kwargs):
"""
Take a function that reports its result using a callback and return a Promise that
listenes for this callback.
The function must accept a callback as its first parameter.
The callback must take two arguments:
- success : True or False
... | [
"def",
"makeCallbackPromise",
"(",
"function",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"def",
"_resolver",
"(",
"resolve",
",",
"reject",
")",
":",
"function",
"(",
"lambda",
"success",
",",
"result",
":",
"resolve",
"(",
"result",
")",
"i... | Take a function that reports its result using a callback and return a Promise that
listenes for this callback.
The function must accept a callback as its first parameter.
The callback must take two arguments:
- success : True or False
- result : The result of the operation if success is True or th... | [
"Take",
"a",
"function",
"that",
"reports",
"its",
"result",
"using",
"a",
"callback",
"and",
"return",
"a",
"Promise",
"that",
"listenes",
"for",
"this",
"callback",
"."
] | train | https://github.com/Syndace/python-omemo/blob/f99be4715a3fad4d3082f5093aceb2c42385b8bd/omemo/storagewrapper.py#L6-L24 |
mobiusklein/brainpy | brainpy/composition.py | calculate_mass | def calculate_mass(composition, mass_data=None):
"""Calculates the monoisotopic mass of a composition
Parameters
----------
composition : Mapping
Any Mapping type where keys are element symbols and values are integers
mass_data : dict, optional
A dict with the masses of the chemical... | python | def calculate_mass(composition, mass_data=None):
"""Calculates the monoisotopic mass of a composition
Parameters
----------
composition : Mapping
Any Mapping type where keys are element symbols and values are integers
mass_data : dict, optional
A dict with the masses of the chemical... | [
"def",
"calculate_mass",
"(",
"composition",
",",
"mass_data",
"=",
"None",
")",
":",
"mass",
"=",
"0.0",
"if",
"mass_data",
"is",
"None",
":",
"mass_data",
"=",
"nist_mass",
"for",
"element",
"in",
"composition",
":",
"try",
":",
"mass",
"+=",
"(",
"com... | Calculates the monoisotopic mass of a composition
Parameters
----------
composition : Mapping
Any Mapping type where keys are element symbols and values are integers
mass_data : dict, optional
A dict with the masses of the chemical elements (the default
value is :py:data:`nist_m... | [
"Calculates",
"the",
"monoisotopic",
"mass",
"of",
"a",
"composition"
] | train | https://github.com/mobiusklein/brainpy/blob/4ccba40af33651a338c0c54bf1a251345c2db8da/brainpy/composition.py#L14-L43 |
mobiusklein/brainpy | brainpy/composition.py | parse_formula | def parse_formula(formula):
"""Parse a chemical formula and construct a :class:`PyComposition` object
Parameters
----------
formula : :class:`str`
Returns
-------
:class:`PyComposition`
Raises
------
ValueError
If the formula doesn't match the expected pattern
"""
... | python | def parse_formula(formula):
"""Parse a chemical formula and construct a :class:`PyComposition` object
Parameters
----------
formula : :class:`str`
Returns
-------
:class:`PyComposition`
Raises
------
ValueError
If the formula doesn't match the expected pattern
"""
... | [
"def",
"parse_formula",
"(",
"formula",
")",
":",
"if",
"not",
"formula_pattern",
".",
"match",
"(",
"formula",
")",
":",
"raise",
"ValueError",
"(",
"\"%r does not look like a formula\"",
"%",
"(",
"formula",
",",
")",
")",
"composition",
"=",
"PyComposition",
... | Parse a chemical formula and construct a :class:`PyComposition` object
Parameters
----------
formula : :class:`str`
Returns
-------
:class:`PyComposition`
Raises
------
ValueError
If the formula doesn't match the expected pattern | [
"Parse",
"a",
"chemical",
"formula",
"and",
"construct",
"a",
":",
"class",
":",
"PyComposition",
"object"
] | train | https://github.com/mobiusklein/brainpy/blob/4ccba40af33651a338c0c54bf1a251345c2db8da/brainpy/composition.py#L103-L124 |
MisterWil/skybellpy | skybellpy/__init__.py | Skybell.login | def login(self, username=None, password=None):
"""Execute Skybell login."""
if username is not None:
self._username = username
if password is not None:
self._password = password
if self._username is None or not isinstance(self._username, str):
raise S... | python | def login(self, username=None, password=None):
"""Execute Skybell login."""
if username is not None:
self._username = username
if password is not None:
self._password = password
if self._username is None or not isinstance(self._username, str):
raise S... | [
"def",
"login",
"(",
"self",
",",
"username",
"=",
"None",
",",
"password",
"=",
"None",
")",
":",
"if",
"username",
"is",
"not",
"None",
":",
"self",
".",
"_username",
"=",
"username",
"if",
"password",
"is",
"not",
"None",
":",
"self",
".",
"_passw... | Execute Skybell login. | [
"Execute",
"Skybell",
"login",
"."
] | train | https://github.com/MisterWil/skybellpy/blob/ac966d9f590cda7654f6de7eecc94e2103459eef/skybellpy/__init__.py#L68-L108 |
MisterWil/skybellpy | skybellpy/__init__.py | Skybell.logout | def logout(self):
"""Explicit Skybell logout."""
if self.cache(CONST.ACCESS_TOKEN):
# No explicit logout call as it doesn't seem to matter
# if a logout happens without registering the app which
# we aren't currently doing.
self._session = requests.session... | python | def logout(self):
"""Explicit Skybell logout."""
if self.cache(CONST.ACCESS_TOKEN):
# No explicit logout call as it doesn't seem to matter
# if a logout happens without registering the app which
# we aren't currently doing.
self._session = requests.session... | [
"def",
"logout",
"(",
"self",
")",
":",
"if",
"self",
".",
"cache",
"(",
"CONST",
".",
"ACCESS_TOKEN",
")",
":",
"# No explicit logout call as it doesn't seem to matter",
"# if a logout happens without registering the app which",
"# we aren't currently doing.",
"self",
".",
... | Explicit Skybell logout. | [
"Explicit",
"Skybell",
"logout",
"."
] | train | https://github.com/MisterWil/skybellpy/blob/ac966d9f590cda7654f6de7eecc94e2103459eef/skybellpy/__init__.py#L110-L121 |
MisterWil/skybellpy | skybellpy/__init__.py | Skybell.get_devices | def get_devices(self, refresh=False):
"""Get all devices from Abode."""
if refresh or self._devices is None:
if self._devices is None:
self._devices = {}
_LOGGER.info("Updating all devices...")
response = self.send_request("get", CONST.DEVICES_URL)
... | python | def get_devices(self, refresh=False):
"""Get all devices from Abode."""
if refresh or self._devices is None:
if self._devices is None:
self._devices = {}
_LOGGER.info("Updating all devices...")
response = self.send_request("get", CONST.DEVICES_URL)
... | [
"def",
"get_devices",
"(",
"self",
",",
"refresh",
"=",
"False",
")",
":",
"if",
"refresh",
"or",
"self",
".",
"_devices",
"is",
"None",
":",
"if",
"self",
".",
"_devices",
"is",
"None",
":",
"self",
".",
"_devices",
"=",
"{",
"}",
"_LOGGER",
".",
... | Get all devices from Abode. | [
"Get",
"all",
"devices",
"from",
"Abode",
"."
] | train | https://github.com/MisterWil/skybellpy/blob/ac966d9f590cda7654f6de7eecc94e2103459eef/skybellpy/__init__.py#L123-L146 |
MisterWil/skybellpy | skybellpy/__init__.py | Skybell.send_request | def send_request(self, method, url, headers=None,
json_data=None, retry=True):
"""Send requests to Skybell."""
if not self.cache(CONST.ACCESS_TOKEN) and url != CONST.LOGIN_URL:
self.login()
if not headers:
headers = {}
if self.cache(CONST.AC... | python | def send_request(self, method, url, headers=None,
json_data=None, retry=True):
"""Send requests to Skybell."""
if not self.cache(CONST.ACCESS_TOKEN) and url != CONST.LOGIN_URL:
self.login()
if not headers:
headers = {}
if self.cache(CONST.AC... | [
"def",
"send_request",
"(",
"self",
",",
"method",
",",
"url",
",",
"headers",
"=",
"None",
",",
"json_data",
"=",
"None",
",",
"retry",
"=",
"True",
")",
":",
"if",
"not",
"self",
".",
"cache",
"(",
"CONST",
".",
"ACCESS_TOKEN",
")",
"and",
"url",
... | Send requests to Skybell. | [
"Send",
"requests",
"to",
"Skybell",
"."
] | train | https://github.com/MisterWil/skybellpy/blob/ac966d9f590cda7654f6de7eecc94e2103459eef/skybellpy/__init__.py#L161-L200 |
MisterWil/skybellpy | skybellpy/__init__.py | Skybell.update_cache | def update_cache(self, data):
"""Update a cached value."""
UTILS.update(self._cache, data)
self._save_cache() | python | def update_cache(self, data):
"""Update a cached value."""
UTILS.update(self._cache, data)
self._save_cache() | [
"def",
"update_cache",
"(",
"self",
",",
"data",
")",
":",
"UTILS",
".",
"update",
"(",
"self",
".",
"_cache",
",",
"data",
")",
"self",
".",
"_save_cache",
"(",
")"
] | Update a cached value. | [
"Update",
"a",
"cached",
"value",
"."
] | train | https://github.com/MisterWil/skybellpy/blob/ac966d9f590cda7654f6de7eecc94e2103459eef/skybellpy/__init__.py#L206-L209 |
MisterWil/skybellpy | skybellpy/__init__.py | Skybell.dev_cache | def dev_cache(self, device, key=None):
"""Get a cached value for a device."""
device_cache = self._cache.get(CONST.DEVICES, {}).get(device.device_id)
if device_cache and key:
return device_cache.get(key)
return device_cache | python | def dev_cache(self, device, key=None):
"""Get a cached value for a device."""
device_cache = self._cache.get(CONST.DEVICES, {}).get(device.device_id)
if device_cache and key:
return device_cache.get(key)
return device_cache | [
"def",
"dev_cache",
"(",
"self",
",",
"device",
",",
"key",
"=",
"None",
")",
":",
"device_cache",
"=",
"self",
".",
"_cache",
".",
"get",
"(",
"CONST",
".",
"DEVICES",
",",
"{",
"}",
")",
".",
"get",
"(",
"device",
".",
"device_id",
")",
"if",
"... | Get a cached value for a device. | [
"Get",
"a",
"cached",
"value",
"for",
"a",
"device",
"."
] | train | https://github.com/MisterWil/skybellpy/blob/ac966d9f590cda7654f6de7eecc94e2103459eef/skybellpy/__init__.py#L211-L218 |
MisterWil/skybellpy | skybellpy/__init__.py | Skybell.update_dev_cache | def update_dev_cache(self, device, data):
"""Update cached values for a device."""
self.update_cache(
{
CONST.DEVICES: {
device.device_id: data
}
}) | python | def update_dev_cache(self, device, data):
"""Update cached values for a device."""
self.update_cache(
{
CONST.DEVICES: {
device.device_id: data
}
}) | [
"def",
"update_dev_cache",
"(",
"self",
",",
"device",
",",
"data",
")",
":",
"self",
".",
"update_cache",
"(",
"{",
"CONST",
".",
"DEVICES",
":",
"{",
"device",
".",
"device_id",
":",
"data",
"}",
"}",
")"
] | Update cached values for a device. | [
"Update",
"cached",
"values",
"for",
"a",
"device",
"."
] | train | https://github.com/MisterWil/skybellpy/blob/ac966d9f590cda7654f6de7eecc94e2103459eef/skybellpy/__init__.py#L220-L227 |
MisterWil/skybellpy | skybellpy/__init__.py | Skybell._load_cache | def _load_cache(self):
"""Load existing cache and merge for updating if required."""
if not self._disable_cache:
if os.path.exists(self._cache_path):
_LOGGER.debug("Cache found at: %s", self._cache_path)
if os.path.getsize(self._cache_path) > 0:
... | python | def _load_cache(self):
"""Load existing cache and merge for updating if required."""
if not self._disable_cache:
if os.path.exists(self._cache_path):
_LOGGER.debug("Cache found at: %s", self._cache_path)
if os.path.getsize(self._cache_path) > 0:
... | [
"def",
"_load_cache",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"_disable_cache",
":",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"self",
".",
"_cache_path",
")",
":",
"_LOGGER",
".",
"debug",
"(",
"\"Cache found at: %s\"",
",",
"self",
".",
"... | Load existing cache and merge for updating if required. | [
"Load",
"existing",
"cache",
"and",
"merge",
"for",
"updating",
"if",
"required",
"."
] | train | https://github.com/MisterWil/skybellpy/blob/ac966d9f590cda7654f6de7eecc94e2103459eef/skybellpy/__init__.py#L229-L241 |
Syndace/python-omemo | omemo/sessionmanager.py | SessionManager.__encryptKeyTransportMessage | def __encryptKeyTransportMessage(
self,
bare_jids,
encryption_callback,
bundles = None,
expect_problems = None,
ignore_trust = False
):
"""
bare_jids: iterable<string>
encryption_callback: A function which is called using an instance of cryptog... | python | def __encryptKeyTransportMessage(
self,
bare_jids,
encryption_callback,
bundles = None,
expect_problems = None,
ignore_trust = False
):
"""
bare_jids: iterable<string>
encryption_callback: A function which is called using an instance of cryptog... | [
"def",
"__encryptKeyTransportMessage",
"(",
"self",
",",
"bare_jids",
",",
"encryption_callback",
",",
"bundles",
"=",
"None",
",",
"expect_problems",
"=",
"None",
",",
"ignore_trust",
"=",
"False",
")",
":",
"yield",
"self",
".",
"runInactiveDeviceCleanup",
"(",
... | bare_jids: iterable<string>
encryption_callback: A function which is called using an instance of cryptography.hazmat.primitives.ciphers.CipherContext, which you can use to encrypt any sort of data. You don't have to return anything.
bundles: { [bare_jid: string] => { [device_id: int] => ExtendedPublicBu... | [
"bare_jids",
":",
"iterable<string",
">",
"encryption_callback",
":",
"A",
"function",
"which",
"is",
"called",
"using",
"an",
"instance",
"of",
"cryptography",
".",
"hazmat",
".",
"primitives",
".",
"ciphers",
".",
"CipherContext",
"which",
"you",
"can",
"use",... | train | https://github.com/Syndace/python-omemo/blob/f99be4715a3fad4d3082f5093aceb2c42385b8bd/omemo/sessionmanager.py#L177-L437 |
Syndace/python-omemo | omemo/sessionmanager.py | SessionManager.deleteInactiveDevicesByQuota | def deleteInactiveDevicesByQuota(self, per_jid_max = 15, global_max = 0):
"""
Delete inactive devices by setting a quota. With per_jid_max you can define the
amount of inactive devices that are kept for each jid, with global_max you can
define a global maximum for inactive devices. If an... | python | def deleteInactiveDevicesByQuota(self, per_jid_max = 15, global_max = 0):
"""
Delete inactive devices by setting a quota. With per_jid_max you can define the
amount of inactive devices that are kept for each jid, with global_max you can
define a global maximum for inactive devices. If an... | [
"def",
"deleteInactiveDevicesByQuota",
"(",
"self",
",",
"per_jid_max",
"=",
"15",
",",
"global_max",
"=",
"0",
")",
":",
"if",
"per_jid_max",
"<",
"1",
"and",
"global_max",
"<",
"1",
":",
"return",
"if",
"per_jid_max",
"<",
"1",
":",
"per_jid_max",
"=",
... | Delete inactive devices by setting a quota. With per_jid_max you can define the
amount of inactive devices that are kept for each jid, with global_max you can
define a global maximum for inactive devices. If any of the quotas is reached,
inactive devices are deleted on an LRU basis. This also de... | [
"Delete",
"inactive",
"devices",
"by",
"setting",
"a",
"quota",
".",
"With",
"per_jid_max",
"you",
"can",
"define",
"the",
"amount",
"of",
"inactive",
"devices",
"that",
"are",
"kept",
"for",
"each",
"jid",
"with",
"global_max",
"you",
"can",
"define",
"a",
... | train | https://github.com/Syndace/python-omemo/blob/f99be4715a3fad4d3082f5093aceb2c42385b8bd/omemo/sessionmanager.py#L766-L849 |
Syndace/python-omemo | omemo/sessionmanager.py | SessionManager.deleteInactiveDevicesByAge | def deleteInactiveDevicesByAge(self, age_days):
"""
Delete all inactive devices from the device list storage and cache that are older
then a given number of days. This also deletes the corresponding sessions, so if
a device comes active again and tries to send you an encrypted message yo... | python | def deleteInactiveDevicesByAge(self, age_days):
"""
Delete all inactive devices from the device list storage and cache that are older
then a given number of days. This also deletes the corresponding sessions, so if
a device comes active again and tries to send you an encrypted message yo... | [
"def",
"deleteInactiveDevicesByAge",
"(",
"self",
",",
"age_days",
")",
":",
"if",
"age_days",
"<",
"1",
":",
"return",
"now",
"=",
"time",
".",
"time",
"(",
")",
"bare_jids",
"=",
"yield",
"self",
".",
"_storage",
".",
"listJIDs",
"(",
")",
"for",
"ba... | Delete all inactive devices from the device list storage and cache that are older
then a given number of days. This also deletes the corresponding sessions, so if
a device comes active again and tries to send you an encrypted message you will
not be able to decrypt it. You are not allowed to del... | [
"Delete",
"all",
"inactive",
"devices",
"from",
"the",
"device",
"list",
"storage",
"and",
"cache",
"that",
"are",
"older",
"then",
"a",
"given",
"number",
"of",
"days",
".",
"This",
"also",
"deletes",
"the",
"corresponding",
"sessions",
"so",
"if",
"a",
"... | train | https://github.com/Syndace/python-omemo/blob/f99be4715a3fad4d3082f5093aceb2c42385b8bd/omemo/sessionmanager.py#L852-L889 |
Syndace/python-omemo | omemo/sessionmanager.py | SessionManager.runInactiveDeviceCleanup | def runInactiveDeviceCleanup(self):
"""
Runs both the deleteInactiveDevicesByAge and the deleteInactiveDevicesByQuota
methods with the configuration that was set when calling create.
"""
yield self.deleteInactiveDevicesByQuota(
self.__inactive_per_jid_max,
... | python | def runInactiveDeviceCleanup(self):
"""
Runs both the deleteInactiveDevicesByAge and the deleteInactiveDevicesByQuota
methods with the configuration that was set when calling create.
"""
yield self.deleteInactiveDevicesByQuota(
self.__inactive_per_jid_max,
... | [
"def",
"runInactiveDeviceCleanup",
"(",
"self",
")",
":",
"yield",
"self",
".",
"deleteInactiveDevicesByQuota",
"(",
"self",
".",
"__inactive_per_jid_max",
",",
"self",
".",
"__inactive_global_max",
")",
"yield",
"self",
".",
"deleteInactiveDevicesByAge",
"(",
"self",... | Runs both the deleteInactiveDevicesByAge and the deleteInactiveDevicesByQuota
methods with the configuration that was set when calling create. | [
"Runs",
"both",
"the",
"deleteInactiveDevicesByAge",
"and",
"the",
"deleteInactiveDevicesByQuota",
"methods",
"with",
"the",
"configuration",
"that",
"was",
"set",
"when",
"calling",
"create",
"."
] | train | https://github.com/Syndace/python-omemo/blob/f99be4715a3fad4d3082f5093aceb2c42385b8bd/omemo/sessionmanager.py#L892-L903 |
Syndace/python-omemo | omemo/sessionmanager.py | SessionManager.getTrustForJID | def getTrustForJID(self, bare_jid):
"""
All-in-one trust information for all devices of a bare jid.
The result is structured like this:
{
"active" : { device: int => trust_info }
"inactive" : { device: int => trust_info }
}
where trust_info is ... | python | def getTrustForJID(self, bare_jid):
"""
All-in-one trust information for all devices of a bare jid.
The result is structured like this:
{
"active" : { device: int => trust_info }
"inactive" : { device: int => trust_info }
}
where trust_info is ... | [
"def",
"getTrustForJID",
"(",
"self",
",",
"bare_jid",
")",
":",
"result",
"=",
"{",
"\"active\"",
":",
"{",
"}",
",",
"\"inactive\"",
":",
"{",
"}",
"}",
"devices",
"=",
"yield",
"self",
".",
"__loadActiveDevices",
"(",
"bare_jid",
")",
"for",
"device",... | All-in-one trust information for all devices of a bare jid.
The result is structured like this:
{
"active" : { device: int => trust_info }
"inactive" : { device: int => trust_info }
}
where trust_info is the structure returned by getTrustForDevice. | [
"All",
"-",
"in",
"-",
"one",
"trust",
"information",
"for",
"all",
"devices",
"of",
"a",
"bare",
"jid",
".",
"The",
"result",
"is",
"structured",
"like",
"this",
":"
] | train | https://github.com/Syndace/python-omemo/blob/f99be4715a3fad4d3082f5093aceb2c42385b8bd/omemo/sessionmanager.py#L998-L1026 |
Syndace/python-omemo | omemo/sessionmanager.py | SessionManager.deleteJID | def deleteJID(self, bare_jid):
"""
Delete all data associated with a JID. This includes the list of active/inactive
devices, all sessions with that JID and all information about trusted keys.
"""
yield self.runInactiveDeviceCleanup()
self.__sessions_cache.pop(bare_jid, ... | python | def deleteJID(self, bare_jid):
"""
Delete all data associated with a JID. This includes the list of active/inactive
devices, all sessions with that JID and all information about trusted keys.
"""
yield self.runInactiveDeviceCleanup()
self.__sessions_cache.pop(bare_jid, ... | [
"def",
"deleteJID",
"(",
"self",
",",
"bare_jid",
")",
":",
"yield",
"self",
".",
"runInactiveDeviceCleanup",
"(",
")",
"self",
".",
"__sessions_cache",
".",
"pop",
"(",
"bare_jid",
",",
"None",
")",
"self",
".",
"__devices_cache",
".",
"pop",
"(",
"bare_j... | Delete all data associated with a JID. This includes the list of active/inactive
devices, all sessions with that JID and all information about trusted keys. | [
"Delete",
"all",
"data",
"associated",
"with",
"a",
"JID",
".",
"This",
"includes",
"the",
"list",
"of",
"active",
"/",
"inactive",
"devices",
"all",
"sessions",
"with",
"that",
"JID",
"and",
"all",
"information",
"about",
"trusted",
"keys",
"."
] | train | https://github.com/Syndace/python-omemo/blob/f99be4715a3fad4d3082f5093aceb2c42385b8bd/omemo/sessionmanager.py#L1036-L1048 |
pjmark/NIMPA | resources/resources.py | get_setup | def get_setup(Cnt = {}):
'''Return a dictionary of GPU, mu-map hardware and third party set-up.'''
# the name of the folder for NiftyPET tools
Cnt['DIRTOOLS'] = DIRTOOLS
# additional paramteres for compiling tools with cmake
Cnt['CMAKE_TLS_PAR'] = CMAKE_TLS_PAR
# hardware mu-maps
Cnt[... | python | def get_setup(Cnt = {}):
'''Return a dictionary of GPU, mu-map hardware and third party set-up.'''
# the name of the folder for NiftyPET tools
Cnt['DIRTOOLS'] = DIRTOOLS
# additional paramteres for compiling tools with cmake
Cnt['CMAKE_TLS_PAR'] = CMAKE_TLS_PAR
# hardware mu-maps
Cnt[... | [
"def",
"get_setup",
"(",
"Cnt",
"=",
"{",
"}",
")",
":",
"# the name of the folder for NiftyPET tools",
"Cnt",
"[",
"'DIRTOOLS'",
"]",
"=",
"DIRTOOLS",
"# additional paramteres for compiling tools with cmake",
"Cnt",
"[",
"'CMAKE_TLS_PAR'",
"]",
"=",
"CMAKE_TLS_PAR",
"#... | Return a dictionary of GPU, mu-map hardware and third party set-up. | [
"Return",
"a",
"dictionary",
"of",
"GPU",
"mu",
"-",
"map",
"hardware",
"and",
"third",
"party",
"set",
"-",
"up",
"."
] | train | https://github.com/pjmark/NIMPA/blob/3f4231fed2934a1d92e4cd8e9e153b0118e29d86/resources/resources.py#L247-L278 |
pjmark/NIMPA | resources/resources.py | get_mmr_constants | def get_mmr_constants():
'''
Put all the constants together in a dictionary
'''
Cnt = {
'ISOTOPE':'F18',
'DCYCRR':DCYCRR,
'ALPHA':ALPHA,
'NRNG':NRNG,
'NSRNG':NSRNG,
'NCRS':NCRS,
'NCRSR':NCRSR,
'NBCKT':224,
'NSANGLES':A,
'NS... | python | def get_mmr_constants():
'''
Put all the constants together in a dictionary
'''
Cnt = {
'ISOTOPE':'F18',
'DCYCRR':DCYCRR,
'ALPHA':ALPHA,
'NRNG':NRNG,
'NSRNG':NSRNG,
'NCRS':NCRS,
'NCRSR':NCRSR,
'NBCKT':224,
'NSANGLES':A,
'NS... | [
"def",
"get_mmr_constants",
"(",
")",
":",
"Cnt",
"=",
"{",
"'ISOTOPE'",
":",
"'F18'",
",",
"'DCYCRR'",
":",
"DCYCRR",
",",
"'ALPHA'",
":",
"ALPHA",
",",
"'NRNG'",
":",
"NRNG",
",",
"'NSRNG'",
":",
"NSRNG",
",",
"'NCRS'",
":",
"NCRS",
",",
"'NCRSR'",
... | Put all the constants together in a dictionary | [
"Put",
"all",
"the",
"constants",
"together",
"in",
"a",
"dictionary"
] | train | https://github.com/pjmark/NIMPA/blob/3f4231fed2934a1d92e4cd8e9e153b0118e29d86/resources/resources.py#L281-L376 |
pjmark/NIMPA | install_tools.py | check_version | def check_version(Cnt, chcklst=['RESPATH','REGPATH','DCM2NIIX','HMUDIR']):
''' Check version and existence of all third-party software and input data.
Output a dictionary with bool type of the requested bits in 'chcklst'
'''
# at start, assume that nothing is present yet
output = {}
for itm... | python | def check_version(Cnt, chcklst=['RESPATH','REGPATH','DCM2NIIX','HMUDIR']):
''' Check version and existence of all third-party software and input data.
Output a dictionary with bool type of the requested bits in 'chcklst'
'''
# at start, assume that nothing is present yet
output = {}
for itm... | [
"def",
"check_version",
"(",
"Cnt",
",",
"chcklst",
"=",
"[",
"'RESPATH'",
",",
"'REGPATH'",
",",
"'DCM2NIIX'",
",",
"'HMUDIR'",
"]",
")",
":",
"# at start, assume that nothing is present yet",
"output",
"=",
"{",
"}",
"for",
"itm",
"in",
"chcklst",
":",
"outp... | Check version and existence of all third-party software and input data.
Output a dictionary with bool type of the requested bits in 'chcklst' | [
"Check",
"version",
"and",
"existence",
"of",
"all",
"third",
"-",
"party",
"software",
"and",
"input",
"data",
".",
"Output",
"a",
"dictionary",
"with",
"bool",
"type",
"of",
"the",
"requested",
"bits",
"in",
"chcklst"
] | train | https://github.com/pjmark/NIMPA/blob/3f4231fed2934a1d92e4cd8e9e153b0118e29d86/install_tools.py#L120-L170 |
pjmark/NIMPA | install_tools.py | install_tool | def install_tool(app, Cnt):
''' Install the requested software from the git 'repo'
and check out the version given by 'sha1'.
'''
# get the current working directory
cwd = os.getcwd()
# pick the target installation folder for tools
if 'PATHTOOLS' in Cnt and Cnt['PATHTOOLS']!='':
... | python | def install_tool(app, Cnt):
''' Install the requested software from the git 'repo'
and check out the version given by 'sha1'.
'''
# get the current working directory
cwd = os.getcwd()
# pick the target installation folder for tools
if 'PATHTOOLS' in Cnt and Cnt['PATHTOOLS']!='':
... | [
"def",
"install_tool",
"(",
"app",
",",
"Cnt",
")",
":",
"# get the current working directory",
"cwd",
"=",
"os",
".",
"getcwd",
"(",
")",
"# pick the target installation folder for tools",
"if",
"'PATHTOOLS'",
"in",
"Cnt",
"and",
"Cnt",
"[",
"'PATHTOOLS'",
"]",
"... | Install the requested software from the git 'repo'
and check out the version given by 'sha1'. | [
"Install",
"the",
"requested",
"software",
"from",
"the",
"git",
"repo",
"and",
"check",
"out",
"the",
"version",
"given",
"by",
"sha1",
"."
] | train | https://github.com/pjmark/NIMPA/blob/3f4231fed2934a1d92e4cd8e9e153b0118e29d86/install_tools.py#L215-L340 |
pjmark/NIMPA | install_tools.py | update_resources | def update_resources(Cnt):
'''Update resources.py with the paths to the new installed apps.
'''
# list of path names which will be saved
key_list = ['PATHTOOLS', 'RESPATH', 'REGPATH', 'DCM2NIIX', 'HMUDIR']
# get the local path to NiftyPET resources.py
path_resources = cs.path_niftypet_local()
... | python | def update_resources(Cnt):
'''Update resources.py with the paths to the new installed apps.
'''
# list of path names which will be saved
key_list = ['PATHTOOLS', 'RESPATH', 'REGPATH', 'DCM2NIIX', 'HMUDIR']
# get the local path to NiftyPET resources.py
path_resources = cs.path_niftypet_local()
... | [
"def",
"update_resources",
"(",
"Cnt",
")",
":",
"# list of path names which will be saved",
"key_list",
"=",
"[",
"'PATHTOOLS'",
",",
"'RESPATH'",
",",
"'REGPATH'",
",",
"'DCM2NIIX'",
",",
"'HMUDIR'",
"]",
"# get the local path to NiftyPET resources.py",
"path_resources",
... | Update resources.py with the paths to the new installed apps. | [
"Update",
"resources",
".",
"py",
"with",
"the",
"paths",
"to",
"the",
"new",
"installed",
"apps",
"."
] | train | https://github.com/pjmark/NIMPA/blob/3f4231fed2934a1d92e4cd8e9e153b0118e29d86/install_tools.py#L343-L379 |
Syndace/python-omemo | omemo/storage.py | Storage.loadSessions | def loadSessions(self, callback, bare_jid, device_ids):
"""
Return a dict containing the session for each device id. By default, this method
calls loadSession for each device id.
"""
if self.is_async:
self.__loadSessionsAsync(callback, bare_jid, device_ids, {})
... | python | def loadSessions(self, callback, bare_jid, device_ids):
"""
Return a dict containing the session for each device id. By default, this method
calls loadSession for each device id.
"""
if self.is_async:
self.__loadSessionsAsync(callback, bare_jid, device_ids, {})
... | [
"def",
"loadSessions",
"(",
"self",
",",
"callback",
",",
"bare_jid",
",",
"device_ids",
")",
":",
"if",
"self",
".",
"is_async",
":",
"self",
".",
"__loadSessionsAsync",
"(",
"callback",
",",
"bare_jid",
",",
"device_ids",
",",
"{",
"}",
")",
"else",
":... | Return a dict containing the session for each device id. By default, this method
calls loadSession for each device id. | [
"Return",
"a",
"dict",
"containing",
"the",
"session",
"for",
"each",
"device",
"id",
".",
"By",
"default",
"this",
"method",
"calls",
"loadSession",
"for",
"each",
"device",
"id",
"."
] | train | https://github.com/Syndace/python-omemo/blob/f99be4715a3fad4d3082f5093aceb2c42385b8bd/omemo/storage.py#L88-L97 |
Syndace/python-omemo | omemo/storage.py | Storage.loadTrusts | def loadTrusts(self, callback, bare_jid, device_ids):
"""
Return a dict containing the trust status for each device id. By default, this
method calls loadTrust for each device id.
"""
if self.is_async:
self.__loadTrustsAsync(callback, bare_jid, device_ids, {})
... | python | def loadTrusts(self, callback, bare_jid, device_ids):
"""
Return a dict containing the trust status for each device id. By default, this
method calls loadTrust for each device id.
"""
if self.is_async:
self.__loadTrustsAsync(callback, bare_jid, device_ids, {})
... | [
"def",
"loadTrusts",
"(",
"self",
",",
"callback",
",",
"bare_jid",
",",
"device_ids",
")",
":",
"if",
"self",
".",
"is_async",
":",
"self",
".",
"__loadTrustsAsync",
"(",
"callback",
",",
"bare_jid",
",",
"device_ids",
",",
"{",
"}",
")",
"else",
":",
... | Return a dict containing the trust status for each device id. By default, this
method calls loadTrust for each device id. | [
"Return",
"a",
"dict",
"containing",
"the",
"trust",
"status",
"for",
"each",
"device",
"id",
".",
"By",
"default",
"this",
"method",
"calls",
"loadTrust",
"for",
"each",
"device",
"id",
"."
] | train | https://github.com/Syndace/python-omemo/blob/f99be4715a3fad4d3082f5093aceb2c42385b8bd/omemo/storage.py#L205-L214 |
Syndace/python-omemo | omemo/extendedpublicbundle.py | ExtendedPublicBundle.parse | def parse(cls, backend, ik, spk, spk_signature, otpks):
"""
Use this method when creating a bundle from data you retrieved directly from some
PEP node. This method applies an additional decoding step to the public keys in
the bundle. Pass the same structure as the constructor expects.
... | python | def parse(cls, backend, ik, spk, spk_signature, otpks):
"""
Use this method when creating a bundle from data you retrieved directly from some
PEP node. This method applies an additional decoding step to the public keys in
the bundle. Pass the same structure as the constructor expects.
... | [
"def",
"parse",
"(",
"cls",
",",
"backend",
",",
"ik",
",",
"spk",
",",
"spk_signature",
",",
"otpks",
")",
":",
"ik",
"=",
"backend",
".",
"decodePublicKey",
"(",
"ik",
")",
"[",
"0",
"]",
"spk",
"[",
"\"key\"",
"]",
"=",
"backend",
".",
"decodePu... | Use this method when creating a bundle from data you retrieved directly from some
PEP node. This method applies an additional decoding step to the public keys in
the bundle. Pass the same structure as the constructor expects. | [
"Use",
"this",
"method",
"when",
"creating",
"a",
"bundle",
"from",
"data",
"you",
"retrieved",
"directly",
"from",
"some",
"PEP",
"node",
".",
"This",
"method",
"applies",
"an",
"additional",
"decoding",
"step",
"to",
"the",
"public",
"keys",
"in",
"the",
... | train | https://github.com/Syndace/python-omemo/blob/f99be4715a3fad4d3082f5093aceb2c42385b8bd/omemo/extendedpublicbundle.py#L38-L54 |
Syndace/python-omemo | omemo/extendedpublicbundle.py | ExtendedPublicBundle.serialize | def serialize(self, backend):
"""
Use this method to prepare the data to be uploaded directly to some PEP node. This
method applies an additional encoding step to the public keys in the bundle. The
result is a dictionary with the keys ik, spk, spk_signature and otpks. The values
... | python | def serialize(self, backend):
"""
Use this method to prepare the data to be uploaded directly to some PEP node. This
method applies an additional encoding step to the public keys in the bundle. The
result is a dictionary with the keys ik, spk, spk_signature and otpks. The values
... | [
"def",
"serialize",
"(",
"self",
",",
"backend",
")",
":",
"return",
"{",
"\"ik\"",
":",
"backend",
".",
"encodePublicKey",
"(",
"self",
".",
"ik",
",",
"\"25519\"",
")",
",",
"\"spk\"",
":",
"{",
"\"id\"",
":",
"self",
".",
"spk",
"[",
"\"id\"",
"]"... | Use this method to prepare the data to be uploaded directly to some PEP node. This
method applies an additional encoding step to the public keys in the bundle. The
result is a dictionary with the keys ik, spk, spk_signature and otpks. The values
are structured the same way as the inputs of the c... | [
"Use",
"this",
"method",
"to",
"prepare",
"the",
"data",
"to",
"be",
"uploaded",
"directly",
"to",
"some",
"PEP",
"node",
".",
"This",
"method",
"applies",
"an",
"additional",
"encoding",
"step",
"to",
"the",
"public",
"keys",
"in",
"the",
"bundle",
".",
... | train | https://github.com/Syndace/python-omemo/blob/f99be4715a3fad4d3082f5093aceb2c42385b8bd/omemo/extendedpublicbundle.py#L56-L75 |
pjmark/NIMPA | niftypet/nimpa/prc/regseg.py | imfill | def imfill(immsk):
'''fill the empty patches of image mask 'immsk' '''
for iz in range(immsk.shape[0]):
for iy in range(immsk.shape[1]):
ix0 = np.argmax(immsk[iz,iy,:]>0)
ix1 = immsk.shape[2] - np.argmax(immsk[iz,iy,::-1]>0)
if (ix1-ix0) > immsk.shape[2]-10: continue... | python | def imfill(immsk):
'''fill the empty patches of image mask 'immsk' '''
for iz in range(immsk.shape[0]):
for iy in range(immsk.shape[1]):
ix0 = np.argmax(immsk[iz,iy,:]>0)
ix1 = immsk.shape[2] - np.argmax(immsk[iz,iy,::-1]>0)
if (ix1-ix0) > immsk.shape[2]-10: continue... | [
"def",
"imfill",
"(",
"immsk",
")",
":",
"for",
"iz",
"in",
"range",
"(",
"immsk",
".",
"shape",
"[",
"0",
"]",
")",
":",
"for",
"iy",
"in",
"range",
"(",
"immsk",
".",
"shape",
"[",
"1",
"]",
")",
":",
"ix0",
"=",
"np",
".",
"argmax",
"(",
... | fill the empty patches of image mask 'immsk' | [
"fill",
"the",
"empty",
"patches",
"of",
"image",
"mask",
"immsk"
] | train | https://github.com/pjmark/NIMPA/blob/3f4231fed2934a1d92e4cd8e9e153b0118e29d86/niftypet/nimpa/prc/regseg.py#L22-L31 |
pjmark/NIMPA | niftypet/nimpa/prc/regseg.py | create_mask | def create_mask(
fnii,
fimout = '',
outpath = '',
fill = 1,
dtype_fill = np.uint8,
thrsh = 0.,
fwhm = 0.,):
''' create mask over the whole image or over the threshold area'''
#> output path
if outpath=='' and fimout!='':
opth = ... | python | def create_mask(
fnii,
fimout = '',
outpath = '',
fill = 1,
dtype_fill = np.uint8,
thrsh = 0.,
fwhm = 0.,):
''' create mask over the whole image or over the threshold area'''
#> output path
if outpath=='' and fimout!='':
opth = ... | [
"def",
"create_mask",
"(",
"fnii",
",",
"fimout",
"=",
"''",
",",
"outpath",
"=",
"''",
",",
"fill",
"=",
"1",
",",
"dtype_fill",
"=",
"np",
".",
"uint8",
",",
"thrsh",
"=",
"0.",
",",
"fwhm",
"=",
"0.",
",",
")",
":",
"#> output path",
"if",
"ou... | create mask over the whole image or over the threshold area | [
"create",
"mask",
"over",
"the",
"whole",
"image",
"or",
"over",
"the",
"threshold",
"area"
] | train | https://github.com/pjmark/NIMPA/blob/3f4231fed2934a1d92e4cd8e9e153b0118e29d86/niftypet/nimpa/prc/regseg.py#L38-L103 |
pjmark/NIMPA | niftypet/nimpa/prc/regseg.py | resample_vinci | def resample_vinci(
fref,
fflo,
faff,
intrp = 0,
fimout = '',
fcomment = '',
outpath = '',
pickname = 'ref',
vc = '',
con = '',
vincipy_path = '',
atlas_resample = False,
atlas_ref_make = False,
atlas_ref_del... | python | def resample_vinci(
fref,
fflo,
faff,
intrp = 0,
fimout = '',
fcomment = '',
outpath = '',
pickname = 'ref',
vc = '',
con = '',
vincipy_path = '',
atlas_resample = False,
atlas_ref_make = False,
atlas_ref_del... | [
"def",
"resample_vinci",
"(",
"fref",
",",
"fflo",
",",
"faff",
",",
"intrp",
"=",
"0",
",",
"fimout",
"=",
"''",
",",
"fcomment",
"=",
"''",
",",
"outpath",
"=",
"''",
",",
"pickname",
"=",
"'ref'",
",",
"vc",
"=",
"''",
",",
"con",
"=",
"''",
... | Resample the floating image <fflo> into the geometry of <fref>,
using the Vinci transformation output <faff> (an *.xml file).
Output the NIfTI file path of the resampled/resliced image. | [
"Resample",
"the",
"floating",
"image",
"<fflo",
">",
"into",
"the",
"geometry",
"of",
"<fref",
">",
"using",
"the",
"Vinci",
"transformation",
"output",
"<faff",
">",
"(",
"an",
"*",
".",
"xml",
"file",
")",
".",
"Output",
"the",
"NIfTI",
"file",
"path"... | train | https://github.com/pjmark/NIMPA/blob/3f4231fed2934a1d92e4cd8e9e153b0118e29d86/niftypet/nimpa/prc/regseg.py#L703-L848 |
pjmark/NIMPA | niftypet/nimpa/prc/regseg.py | dice_coeff | def dice_coeff(im1, im2, val=1):
''' Calculate Dice score for parcellation images <im1> and <im2> and ROI value <val>.
Input images can be given as:
1. paths to NIfTI image files or as
2. Numpy arrays.
The ROI value can be given as:
1. a single integer representin... | python | def dice_coeff(im1, im2, val=1):
''' Calculate Dice score for parcellation images <im1> and <im2> and ROI value <val>.
Input images can be given as:
1. paths to NIfTI image files or as
2. Numpy arrays.
The ROI value can be given as:
1. a single integer representin... | [
"def",
"dice_coeff",
"(",
"im1",
",",
"im2",
",",
"val",
"=",
"1",
")",
":",
"if",
"isinstance",
"(",
"im1",
",",
"basestring",
")",
"and",
"isinstance",
"(",
"im2",
",",
"basestring",
")",
"and",
"os",
".",
"path",
".",
"isfile",
"(",
"im1",
")",
... | Calculate Dice score for parcellation images <im1> and <im2> and ROI value <val>.
Input images can be given as:
1. paths to NIfTI image files or as
2. Numpy arrays.
The ROI value can be given as:
1. a single integer representing one ROI out of many in the parcellation... | [
"Calculate",
"Dice",
"score",
"for",
"parcellation",
"images",
"<im1",
">",
"and",
"<im2",
">",
"and",
"ROI",
"value",
"<val",
">",
".",
"Input",
"images",
"can",
"be",
"given",
"as",
":",
"1",
".",
"paths",
"to",
"NIfTI",
"image",
"files",
"or",
"as",... | train | https://github.com/pjmark/NIMPA/blob/3f4231fed2934a1d92e4cd8e9e153b0118e29d86/niftypet/nimpa/prc/regseg.py#L1115-L1160 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.