repo
stringlengths 7
55
| path
stringlengths 4
127
| func_name
stringlengths 1
88
| original_string
stringlengths 75
19.8k
| language
stringclasses 1
value | code
stringlengths 75
19.8k
| code_tokens
sequence | docstring
stringlengths 3
17.3k
| docstring_tokens
sequence | sha
stringlengths 40
40
| url
stringlengths 87
242
| partition
stringclasses 1
value |
---|---|---|---|---|---|---|---|---|---|---|---|
Erotemic/utool | utool/_internal/win32_send_keys.py | KeyAction.key_description | def key_description(self):
"Return a description of the key"
vk, scan, flags = self._get_key_info()
desc = ''
if vk:
if vk in CODE_NAMES:
desc = CODE_NAMES[vk]
else:
desc = "VK %d"% vk
else:
desc = "%s"% self.key
return desc | python | def key_description(self):
"Return a description of the key"
vk, scan, flags = self._get_key_info()
desc = ''
if vk:
if vk in CODE_NAMES:
desc = CODE_NAMES[vk]
else:
desc = "VK %d"% vk
else:
desc = "%s"% self.key
return desc | [
"def",
"key_description",
"(",
"self",
")",
":",
"vk",
",",
"scan",
",",
"flags",
"=",
"self",
".",
"_get_key_info",
"(",
")",
"desc",
"=",
"''",
"if",
"vk",
":",
"if",
"vk",
"in",
"CODE_NAMES",
":",
"desc",
"=",
"CODE_NAMES",
"[",
"vk",
"]",
"else",
":",
"desc",
"=",
"\"VK %d\"",
"%",
"vk",
"else",
":",
"desc",
"=",
"\"%s\"",
"%",
"self",
".",
"key",
"return",
"desc"
] | Return a description of the key | [
"Return",
"a",
"description",
"of",
"the",
"key"
] | 3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a | https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/_internal/win32_send_keys.py#L359-L371 | train |
Erotemic/utool | utool/_internal/win32_send_keys.py | VirtualKeyAction._get_key_info | def _get_key_info(self):
"Virtual keys have extended flag set"
# copied more or less verbatim from
# http://www.pinvoke.net/default.aspx/user32.sendinput
if (
(self.key >= 33 and self.key <= 46) or
(self.key >= 91 and self.key <= 93) ):
flags = KEYEVENTF_EXTENDEDKEY;
else:
flags = 0
# This works for %{F4} - ALT + F4
#return self.key, 0, 0
# this works for Tic Tac Toe i.e. +{RIGHT} SHIFT + RIGHT
return self.key, MapVirtualKey(self.key, 0), flags | python | def _get_key_info(self):
"Virtual keys have extended flag set"
# copied more or less verbatim from
# http://www.pinvoke.net/default.aspx/user32.sendinput
if (
(self.key >= 33 and self.key <= 46) or
(self.key >= 91 and self.key <= 93) ):
flags = KEYEVENTF_EXTENDEDKEY;
else:
flags = 0
# This works for %{F4} - ALT + F4
#return self.key, 0, 0
# this works for Tic Tac Toe i.e. +{RIGHT} SHIFT + RIGHT
return self.key, MapVirtualKey(self.key, 0), flags | [
"def",
"_get_key_info",
"(",
"self",
")",
":",
"# copied more or less verbatim from",
"# http://www.pinvoke.net/default.aspx/user32.sendinput",
"if",
"(",
"(",
"self",
".",
"key",
">=",
"33",
"and",
"self",
".",
"key",
"<=",
"46",
")",
"or",
"(",
"self",
".",
"key",
">=",
"91",
"and",
"self",
".",
"key",
"<=",
"93",
")",
")",
":",
"flags",
"=",
"KEYEVENTF_EXTENDEDKEY",
"else",
":",
"flags",
"=",
"0",
"# This works for %{F4} - ALT + F4",
"#return self.key, 0, 0",
"# this works for Tic Tac Toe i.e. +{RIGHT} SHIFT + RIGHT",
"return",
"self",
".",
"key",
",",
"MapVirtualKey",
"(",
"self",
".",
"key",
",",
"0",
")",
",",
"flags"
] | Virtual keys have extended flag set | [
"Virtual",
"keys",
"have",
"extended",
"flag",
"set"
] | 3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a | https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/_internal/win32_send_keys.py#L389-L404 | train |
Erotemic/utool | utool/_internal/win32_send_keys.py | EscapedKeyAction._get_key_info | def _get_key_info(self):
"""EscapedKeyAction doesn't send it as Unicode and the vk and
scan code are generated differently"""
vkey_scan = LoByte(VkKeyScan(self.key))
return (vkey_scan, MapVirtualKey(vkey_scan, 0), 0) | python | def _get_key_info(self):
"""EscapedKeyAction doesn't send it as Unicode and the vk and
scan code are generated differently"""
vkey_scan = LoByte(VkKeyScan(self.key))
return (vkey_scan, MapVirtualKey(vkey_scan, 0), 0) | [
"def",
"_get_key_info",
"(",
"self",
")",
":",
"vkey_scan",
"=",
"LoByte",
"(",
"VkKeyScan",
"(",
"self",
".",
"key",
")",
")",
"return",
"(",
"vkey_scan",
",",
"MapVirtualKey",
"(",
"vkey_scan",
",",
"0",
")",
",",
"0",
")"
] | EscapedKeyAction doesn't send it as Unicode and the vk and
scan code are generated differently | [
"EscapedKeyAction",
"doesn",
"t",
"send",
"it",
"as",
"Unicode",
"and",
"the",
"vk",
"and",
"scan",
"code",
"are",
"generated",
"differently"
] | 3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a | https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/_internal/win32_send_keys.py#L412-L417 | train |
ThreatResponse/aws_ir_plugins | aws_ir_plugins/revokests_key.py | Plugin.setup | def setup(self):
"""Method runs the plugin attaching policies to the user in question"""
self.template = self._generate_inline_policy()
if self.dry_run is not True:
self.client = self._get_client()
username = self._get_username_for_key()
policy_document = self._generate_inline_policy()
self._attach_inline_policy(username, policy_document)
pass | python | def setup(self):
"""Method runs the plugin attaching policies to the user in question"""
self.template = self._generate_inline_policy()
if self.dry_run is not True:
self.client = self._get_client()
username = self._get_username_for_key()
policy_document = self._generate_inline_policy()
self._attach_inline_policy(username, policy_document)
pass | [
"def",
"setup",
"(",
"self",
")",
":",
"self",
".",
"template",
"=",
"self",
".",
"_generate_inline_policy",
"(",
")",
"if",
"self",
".",
"dry_run",
"is",
"not",
"True",
":",
"self",
".",
"client",
"=",
"self",
".",
"_get_client",
"(",
")",
"username",
"=",
"self",
".",
"_get_username_for_key",
"(",
")",
"policy_document",
"=",
"self",
".",
"_generate_inline_policy",
"(",
")",
"self",
".",
"_attach_inline_policy",
"(",
"username",
",",
"policy_document",
")",
"pass"
] | Method runs the plugin attaching policies to the user in question | [
"Method",
"runs",
"the",
"plugin",
"attaching",
"policies",
"to",
"the",
"user",
"in",
"question"
] | b5128ef5cbd91fc0b5d55615f1c14cb036ae7c73 | https://github.com/ThreatResponse/aws_ir_plugins/blob/b5128ef5cbd91fc0b5d55615f1c14cb036ae7c73/aws_ir_plugins/revokests_key.py#L27-L35 | train |
ThreatResponse/aws_ir_plugins | aws_ir_plugins/revokests_key.py | Plugin._get_policies | def _get_policies(self):
"""Returns all the policy names for a given user"""
username = self._get_username_for_key()
policies = self.client.list_user_policies(
UserName=username
)
return policies | python | def _get_policies(self):
"""Returns all the policy names for a given user"""
username = self._get_username_for_key()
policies = self.client.list_user_policies(
UserName=username
)
return policies | [
"def",
"_get_policies",
"(",
"self",
")",
":",
"username",
"=",
"self",
".",
"_get_username_for_key",
"(",
")",
"policies",
"=",
"self",
".",
"client",
".",
"list_user_policies",
"(",
"UserName",
"=",
"username",
")",
"return",
"policies"
] | Returns all the policy names for a given user | [
"Returns",
"all",
"the",
"policy",
"names",
"for",
"a",
"given",
"user"
] | b5128ef5cbd91fc0b5d55615f1c14cb036ae7c73 | https://github.com/ThreatResponse/aws_ir_plugins/blob/b5128ef5cbd91fc0b5d55615f1c14cb036ae7c73/aws_ir_plugins/revokests_key.py#L53-L59 | train |
ThreatResponse/aws_ir_plugins | aws_ir_plugins/revokests_key.py | Plugin._get_username_for_key | def _get_username_for_key(self):
"""Find the user for a given access key"""
response = self.client.get_access_key_last_used(
AccessKeyId=self.compromised_resource['access_key_id']
)
username = response['UserName']
return username | python | def _get_username_for_key(self):
"""Find the user for a given access key"""
response = self.client.get_access_key_last_used(
AccessKeyId=self.compromised_resource['access_key_id']
)
username = response['UserName']
return username | [
"def",
"_get_username_for_key",
"(",
"self",
")",
":",
"response",
"=",
"self",
".",
"client",
".",
"get_access_key_last_used",
"(",
"AccessKeyId",
"=",
"self",
".",
"compromised_resource",
"[",
"'access_key_id'",
"]",
")",
"username",
"=",
"response",
"[",
"'UserName'",
"]",
"return",
"username"
] | Find the user for a given access key | [
"Find",
"the",
"user",
"for",
"a",
"given",
"access",
"key"
] | b5128ef5cbd91fc0b5d55615f1c14cb036ae7c73 | https://github.com/ThreatResponse/aws_ir_plugins/blob/b5128ef5cbd91fc0b5d55615f1c14cb036ae7c73/aws_ir_plugins/revokests_key.py#L66-L72 | train |
ThreatResponse/aws_ir_plugins | aws_ir_plugins/revokests_key.py | Plugin._generate_inline_policy | def _generate_inline_policy(self):
"""Renders a policy from a jinja template"""
template_name = self._locate_file('deny-sts-before-time.json.j2')
template_file = open(template_name)
template_contents = template_file.read()
template_file.close()
jinja_template = Template(template_contents)
policy_document = jinja_template.render(
before_date=self._get_date()
)
return policy_document | python | def _generate_inline_policy(self):
"""Renders a policy from a jinja template"""
template_name = self._locate_file('deny-sts-before-time.json.j2')
template_file = open(template_name)
template_contents = template_file.read()
template_file.close()
jinja_template = Template(template_contents)
policy_document = jinja_template.render(
before_date=self._get_date()
)
return policy_document | [
"def",
"_generate_inline_policy",
"(",
"self",
")",
":",
"template_name",
"=",
"self",
".",
"_locate_file",
"(",
"'deny-sts-before-time.json.j2'",
")",
"template_file",
"=",
"open",
"(",
"template_name",
")",
"template_contents",
"=",
"template_file",
".",
"read",
"(",
")",
"template_file",
".",
"close",
"(",
")",
"jinja_template",
"=",
"Template",
"(",
"template_contents",
")",
"policy_document",
"=",
"jinja_template",
".",
"render",
"(",
"before_date",
"=",
"self",
".",
"_get_date",
"(",
")",
")",
"return",
"policy_document"
] | Renders a policy from a jinja template | [
"Renders",
"a",
"policy",
"from",
"a",
"jinja",
"template"
] | b5128ef5cbd91fc0b5d55615f1c14cb036ae7c73 | https://github.com/ThreatResponse/aws_ir_plugins/blob/b5128ef5cbd91fc0b5d55615f1c14cb036ae7c73/aws_ir_plugins/revokests_key.py#L74-L84 | train |
ThreatResponse/aws_ir_plugins | aws_ir_plugins/revokests_key.py | Plugin._attach_inline_policy | def _attach_inline_policy(self, username, policy_document):
"""Attaches the policy to the user"""
response = self.client.put_user_policy(
UserName=username,
PolicyName="threatresponse-temporal-key-revocation",
PolicyDocument=policy_document
)
logger.info(
'An inline policy has been attached for'
' {u} revoking sts tokens.'.format(u=username)
)
return response | python | def _attach_inline_policy(self, username, policy_document):
"""Attaches the policy to the user"""
response = self.client.put_user_policy(
UserName=username,
PolicyName="threatresponse-temporal-key-revocation",
PolicyDocument=policy_document
)
logger.info(
'An inline policy has been attached for'
' {u} revoking sts tokens.'.format(u=username)
)
return response | [
"def",
"_attach_inline_policy",
"(",
"self",
",",
"username",
",",
"policy_document",
")",
":",
"response",
"=",
"self",
".",
"client",
".",
"put_user_policy",
"(",
"UserName",
"=",
"username",
",",
"PolicyName",
"=",
"\"threatresponse-temporal-key-revocation\"",
",",
"PolicyDocument",
"=",
"policy_document",
")",
"logger",
".",
"info",
"(",
"'An inline policy has been attached for'",
"' {u} revoking sts tokens.'",
".",
"format",
"(",
"u",
"=",
"username",
")",
")",
"return",
"response"
] | Attaches the policy to the user | [
"Attaches",
"the",
"policy",
"to",
"the",
"user"
] | b5128ef5cbd91fc0b5d55615f1c14cb036ae7c73 | https://github.com/ThreatResponse/aws_ir_plugins/blob/b5128ef5cbd91fc0b5d55615f1c14cb036ae7c73/aws_ir_plugins/revokests_key.py#L86-L97 | train |
ThreatResponse/aws_ir_plugins | aws_ir_plugins/revokests_key.py | Plugin._locate_file | def _locate_file(self, pattern, root=os.path.dirname('revokests_key.py')):
"""Locate all files matching supplied filename pattern in and below
supplied root directory.
"""
for path, dirs, files in os.walk(os.path.abspath(root)):
for filename in fnmatch.filter(files, pattern):
return os.path.join(path, filename) | python | def _locate_file(self, pattern, root=os.path.dirname('revokests_key.py')):
"""Locate all files matching supplied filename pattern in and below
supplied root directory.
"""
for path, dirs, files in os.walk(os.path.abspath(root)):
for filename in fnmatch.filter(files, pattern):
return os.path.join(path, filename) | [
"def",
"_locate_file",
"(",
"self",
",",
"pattern",
",",
"root",
"=",
"os",
".",
"path",
".",
"dirname",
"(",
"'revokests_key.py'",
")",
")",
":",
"for",
"path",
",",
"dirs",
",",
"files",
"in",
"os",
".",
"walk",
"(",
"os",
".",
"path",
".",
"abspath",
"(",
"root",
")",
")",
":",
"for",
"filename",
"in",
"fnmatch",
".",
"filter",
"(",
"files",
",",
"pattern",
")",
":",
"return",
"os",
".",
"path",
".",
"join",
"(",
"path",
",",
"filename",
")"
] | Locate all files matching supplied filename pattern in and below
supplied root directory. | [
"Locate",
"all",
"files",
"matching",
"supplied",
"filename",
"pattern",
"in",
"and",
"below"
] | b5128ef5cbd91fc0b5d55615f1c14cb036ae7c73 | https://github.com/ThreatResponse/aws_ir_plugins/blob/b5128ef5cbd91fc0b5d55615f1c14cb036ae7c73/aws_ir_plugins/revokests_key.py#L99-L107 | train |
glormph/msstitch | src/app/readers/tsv.py | generate_tsv_pep_protein_quants | def generate_tsv_pep_protein_quants(fns):
"""Unlike generate_tsv_lines_multifile, this generates tsv lines
from multiple files that may have different headers. Yields
fn, header as well as quant data for each protein quant"""
for fn in fns:
header = get_tsv_header(fn)
for pquant in generate_split_tsv_lines(fn, header):
yield os.path.basename(fn), header, pquant | python | def generate_tsv_pep_protein_quants(fns):
"""Unlike generate_tsv_lines_multifile, this generates tsv lines
from multiple files that may have different headers. Yields
fn, header as well as quant data for each protein quant"""
for fn in fns:
header = get_tsv_header(fn)
for pquant in generate_split_tsv_lines(fn, header):
yield os.path.basename(fn), header, pquant | [
"def",
"generate_tsv_pep_protein_quants",
"(",
"fns",
")",
":",
"for",
"fn",
"in",
"fns",
":",
"header",
"=",
"get_tsv_header",
"(",
"fn",
")",
"for",
"pquant",
"in",
"generate_split_tsv_lines",
"(",
"fn",
",",
"header",
")",
":",
"yield",
"os",
".",
"path",
".",
"basename",
"(",
"fn",
")",
",",
"header",
",",
"pquant"
] | Unlike generate_tsv_lines_multifile, this generates tsv lines
from multiple files that may have different headers. Yields
fn, header as well as quant data for each protein quant | [
"Unlike",
"generate_tsv_lines_multifile",
"this",
"generates",
"tsv",
"lines",
"from",
"multiple",
"files",
"that",
"may",
"have",
"different",
"headers",
".",
"Yields",
"fn",
"header",
"as",
"well",
"as",
"quant",
"data",
"for",
"each",
"protein",
"quant"
] | ded7e5cbd813d7797dc9d42805778266e59ff042 | https://github.com/glormph/msstitch/blob/ded7e5cbd813d7797dc9d42805778266e59ff042/src/app/readers/tsv.py#L22-L29 | train |
glormph/msstitch | src/app/readers/tsv.py | mzmlfn_kronikfeature_generator | def mzmlfn_kronikfeature_generator(mzmlfns, kronikfns):
"""Generates tuples of spectra filename and corresponding output
features from kronik"""
for mzmlfn, kronikfn in zip(mzmlfns, kronikfns):
for quant_el in generate_kronik_feats(kronikfn):
yield os.path.basename(mzmlfn), quant_el | python | def mzmlfn_kronikfeature_generator(mzmlfns, kronikfns):
"""Generates tuples of spectra filename and corresponding output
features from kronik"""
for mzmlfn, kronikfn in zip(mzmlfns, kronikfns):
for quant_el in generate_kronik_feats(kronikfn):
yield os.path.basename(mzmlfn), quant_el | [
"def",
"mzmlfn_kronikfeature_generator",
"(",
"mzmlfns",
",",
"kronikfns",
")",
":",
"for",
"mzmlfn",
",",
"kronikfn",
"in",
"zip",
"(",
"mzmlfns",
",",
"kronikfns",
")",
":",
"for",
"quant_el",
"in",
"generate_kronik_feats",
"(",
"kronikfn",
")",
":",
"yield",
"os",
".",
"path",
".",
"basename",
"(",
"mzmlfn",
")",
",",
"quant_el"
] | Generates tuples of spectra filename and corresponding output
features from kronik | [
"Generates",
"tuples",
"of",
"spectra",
"filename",
"and",
"corresponding",
"output",
"features",
"from",
"kronik"
] | ded7e5cbd813d7797dc9d42805778266e59ff042 | https://github.com/glormph/msstitch/blob/ded7e5cbd813d7797dc9d42805778266e59ff042/src/app/readers/tsv.py#L38-L43 | train |
glormph/msstitch | src/app/readers/tsv.py | generate_split_tsv_lines | def generate_split_tsv_lines(fn, header):
"""Returns dicts with header-keys and psm statistic values"""
for line in generate_tsv_psms_line(fn):
yield {x: y for (x, y) in zip(header, line.strip().split('\t'))} | python | def generate_split_tsv_lines(fn, header):
"""Returns dicts with header-keys and psm statistic values"""
for line in generate_tsv_psms_line(fn):
yield {x: y for (x, y) in zip(header, line.strip().split('\t'))} | [
"def",
"generate_split_tsv_lines",
"(",
"fn",
",",
"header",
")",
":",
"for",
"line",
"in",
"generate_tsv_psms_line",
"(",
"fn",
")",
":",
"yield",
"{",
"x",
":",
"y",
"for",
"(",
"x",
",",
"y",
")",
"in",
"zip",
"(",
"header",
",",
"line",
".",
"strip",
"(",
")",
".",
"split",
"(",
"'\\t'",
")",
")",
"}"
] | Returns dicts with header-keys and psm statistic values | [
"Returns",
"dicts",
"with",
"header",
"-",
"keys",
"and",
"psm",
"statistic",
"values"
] | ded7e5cbd813d7797dc9d42805778266e59ff042 | https://github.com/glormph/msstitch/blob/ded7e5cbd813d7797dc9d42805778266e59ff042/src/app/readers/tsv.py#L55-L58 | train |
glormph/msstitch | src/app/readers/tsv.py | get_proteins_from_psm | def get_proteins_from_psm(line):
"""From a line, return list of proteins reported by Mzid2TSV. When unrolled
lines are given, this returns the single protein from the line."""
proteins = line[mzidtsvdata.HEADER_PROTEIN].split(';')
outproteins = []
for protein in proteins:
prepost_protein = re.sub('\(pre=.*post=.*\)', '', protein).strip()
outproteins.append(prepost_protein)
return outproteins | python | def get_proteins_from_psm(line):
"""From a line, return list of proteins reported by Mzid2TSV. When unrolled
lines are given, this returns the single protein from the line."""
proteins = line[mzidtsvdata.HEADER_PROTEIN].split(';')
outproteins = []
for protein in proteins:
prepost_protein = re.sub('\(pre=.*post=.*\)', '', protein).strip()
outproteins.append(prepost_protein)
return outproteins | [
"def",
"get_proteins_from_psm",
"(",
"line",
")",
":",
"proteins",
"=",
"line",
"[",
"mzidtsvdata",
".",
"HEADER_PROTEIN",
"]",
".",
"split",
"(",
"';'",
")",
"outproteins",
"=",
"[",
"]",
"for",
"protein",
"in",
"proteins",
":",
"prepost_protein",
"=",
"re",
".",
"sub",
"(",
"'\\(pre=.*post=.*\\)'",
",",
"''",
",",
"protein",
")",
".",
"strip",
"(",
")",
"outproteins",
".",
"append",
"(",
"prepost_protein",
")",
"return",
"outproteins"
] | From a line, return list of proteins reported by Mzid2TSV. When unrolled
lines are given, this returns the single protein from the line. | [
"From",
"a",
"line",
"return",
"list",
"of",
"proteins",
"reported",
"by",
"Mzid2TSV",
".",
"When",
"unrolled",
"lines",
"are",
"given",
"this",
"returns",
"the",
"single",
"protein",
"from",
"the",
"line",
"."
] | ded7e5cbd813d7797dc9d42805778266e59ff042 | https://github.com/glormph/msstitch/blob/ded7e5cbd813d7797dc9d42805778266e59ff042/src/app/readers/tsv.py#L74-L82 | train |
Erotemic/utool | utool/util_arg.py | aug_sysargv | def aug_sysargv(cmdstr):
""" DEBUG FUNC modify argv to look like you ran a command """
import shlex
argv = shlex.split(cmdstr)
sys.argv.extend(argv) | python | def aug_sysargv(cmdstr):
""" DEBUG FUNC modify argv to look like you ran a command """
import shlex
argv = shlex.split(cmdstr)
sys.argv.extend(argv) | [
"def",
"aug_sysargv",
"(",
"cmdstr",
")",
":",
"import",
"shlex",
"argv",
"=",
"shlex",
".",
"split",
"(",
"cmdstr",
")",
"sys",
".",
"argv",
".",
"extend",
"(",
"argv",
")"
] | DEBUG FUNC modify argv to look like you ran a command | [
"DEBUG",
"FUNC",
"modify",
"argv",
"to",
"look",
"like",
"you",
"ran",
"a",
"command"
] | 3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a | https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/util_arg.py#L40-L44 | train |
Erotemic/utool | utool/util_arg.py | get_module_verbosity_flags | def get_module_verbosity_flags(*labels):
""" checks for standard flags for enableing module specific verbosity """
verbose_prefix_list = ['--verbose-', '--verb', '--verb-']
veryverbose_prefix_list = ['--veryverbose-', '--veryverb', '--veryverb-']
verbose_flags = tuple(
[prefix + lbl for prefix, lbl in
itertools.product(verbose_prefix_list, labels)])
veryverbose_flags = tuple(
[prefix + lbl for prefix, lbl in
itertools.product(veryverbose_prefix_list, labels)])
veryverbose_module = get_argflag(veryverbose_flags) or VERYVERBOSE
verbose_module = (get_argflag(verbose_flags) or veryverbose_module or VERBOSE)
if veryverbose_module:
verbose_module = 2
return verbose_module, veryverbose_module | python | def get_module_verbosity_flags(*labels):
""" checks for standard flags for enableing module specific verbosity """
verbose_prefix_list = ['--verbose-', '--verb', '--verb-']
veryverbose_prefix_list = ['--veryverbose-', '--veryverb', '--veryverb-']
verbose_flags = tuple(
[prefix + lbl for prefix, lbl in
itertools.product(verbose_prefix_list, labels)])
veryverbose_flags = tuple(
[prefix + lbl for prefix, lbl in
itertools.product(veryverbose_prefix_list, labels)])
veryverbose_module = get_argflag(veryverbose_flags) or VERYVERBOSE
verbose_module = (get_argflag(verbose_flags) or veryverbose_module or VERBOSE)
if veryverbose_module:
verbose_module = 2
return verbose_module, veryverbose_module | [
"def",
"get_module_verbosity_flags",
"(",
"*",
"labels",
")",
":",
"verbose_prefix_list",
"=",
"[",
"'--verbose-'",
",",
"'--verb'",
",",
"'--verb-'",
"]",
"veryverbose_prefix_list",
"=",
"[",
"'--veryverbose-'",
",",
"'--veryverb'",
",",
"'--veryverb-'",
"]",
"verbose_flags",
"=",
"tuple",
"(",
"[",
"prefix",
"+",
"lbl",
"for",
"prefix",
",",
"lbl",
"in",
"itertools",
".",
"product",
"(",
"verbose_prefix_list",
",",
"labels",
")",
"]",
")",
"veryverbose_flags",
"=",
"tuple",
"(",
"[",
"prefix",
"+",
"lbl",
"for",
"prefix",
",",
"lbl",
"in",
"itertools",
".",
"product",
"(",
"veryverbose_prefix_list",
",",
"labels",
")",
"]",
")",
"veryverbose_module",
"=",
"get_argflag",
"(",
"veryverbose_flags",
")",
"or",
"VERYVERBOSE",
"verbose_module",
"=",
"(",
"get_argflag",
"(",
"verbose_flags",
")",
"or",
"veryverbose_module",
"or",
"VERBOSE",
")",
"if",
"veryverbose_module",
":",
"verbose_module",
"=",
"2",
"return",
"verbose_module",
",",
"veryverbose_module"
] | checks for standard flags for enableing module specific verbosity | [
"checks",
"for",
"standard",
"flags",
"for",
"enableing",
"module",
"specific",
"verbosity"
] | 3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a | https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/util_arg.py#L48-L62 | train |
Erotemic/utool | utool/util_arg.py | get_argflag | def get_argflag(argstr_, default=False, help_='', return_specified=None,
need_prefix=True, return_was_specified=False, argv=None,
debug=None,
**kwargs):
"""
Checks if the commandline has a flag or a corresponding noflag
Args:
argstr_ (str, list, or tuple): the flag to look for
default (bool): dont use this (default = False)
help_ (str): a help string (default = '')
return_specified (bool): returns if flag was specified or not (default = False)
Returns:
tuple: (parsed_val, was_specified)
TODO:
depricate return_was_specified
CommandLine:
python -m utool.util_arg --exec-get_argflag --noface --exec-mode
python -m utool.util_arg --exec-get_argflag --foo --exec-mode
python -m utool.util_arg --exec-get_argflag --no-foo --exec-mode
python -m utool.util_arg --exec-get_argflag --foo=True --exec-mode
python -m utool.util_arg --exec-get_argflag --foo=False --exec-mode
Example:
>>> # DISABLE_DOCTEST
>>> from utool.util_arg import * # NOQA
>>> argstr_ = '--foo'
>>> default = False
>>> help_ = ''
>>> return_specified = True
>>> (parsed_val, was_specified) = get_argflag(argstr_, default, help_, return_specified)
>>> result = ('(parsed_val, was_specified) = %s' % (str((parsed_val, was_specified)),))
>>> print(result)
"""
if argv is None:
argv = sys.argv
assert isinstance(default, bool), 'default must be boolean'
argstr_list = meta_util_iter.ensure_iterable(argstr_)
#if VERYVERBOSE:
# print('[util_arg] checking argstr_list=%r' % (argstr_list,))
# arg registration
_register_arg(argstr_list, bool, default, help_)
parsed_val = default
was_specified = False
if debug is None:
debug = DEBUG
# Check environment variables for default as well as argv
import os
#"""
#set UTOOL_NOCNN=True
#export UTOOL_NOCNN True
#"""
#argv_orig = argv[:]
# HACK: make this not happen very time you loop
for key, val in os.environ.items():
key = key.upper()
sentinal = 'UTOOL_'
if key.startswith(sentinal):
flag = '--' + key[len(sentinal):].lower().replace('_', '-')
if val.upper() in ['TRUE', 'ON']:
pass
elif val.upper() in ['FALSE', 'OFF']:
continue
else:
continue
#flag += '=False'
new_argv = [flag]
argv = argv[:] + new_argv
if debug:
print('ENV SPECIFIED COMMAND LINE')
print('argv.extend(new_argv=%r)' % (new_argv,))
for argstr in argstr_list:
#if VERYVERBOSE:
# print('[util_arg] * checking argstr=%r' % (argstr,))
if not (argstr.find('--') == 0 or (argstr.find('-') == 0 and len(argstr) == 2)):
raise AssertionError('Invalid argstr: %r' % (argstr,))
if not need_prefix:
noprefix = argstr.replace('--', '')
if noprefix in argv:
parsed_val = True
was_specified = True
break
#if argstr.find('--no') == 0:
#argstr = argstr.replace('--no', '--')
noarg = argstr.replace('--', '--no')
if argstr in argv:
parsed_val = True
was_specified = True
#if VERYVERBOSE:
# print('[util_arg] * ...WAS_SPECIFIED. AND PARSED')
break
elif noarg in argv:
parsed_val = False
was_specified = True
#if VERYVERBOSE:
# print('[util_arg] * ...WAS_SPECIFIED. AND NOT PARSED')
break
elif argstr + '=True' in argv:
parsed_val = True
was_specified = True
break
elif argstr + '=False' in argv:
parsed_val = False
was_specified = True
break
if return_specified is None:
return_specified = return_was_specified
if return_specified:
return parsed_val, was_specified
else:
return parsed_val | python | def get_argflag(argstr_, default=False, help_='', return_specified=None,
need_prefix=True, return_was_specified=False, argv=None,
debug=None,
**kwargs):
"""
Checks if the commandline has a flag or a corresponding noflag
Args:
argstr_ (str, list, or tuple): the flag to look for
default (bool): dont use this (default = False)
help_ (str): a help string (default = '')
return_specified (bool): returns if flag was specified or not (default = False)
Returns:
tuple: (parsed_val, was_specified)
TODO:
depricate return_was_specified
CommandLine:
python -m utool.util_arg --exec-get_argflag --noface --exec-mode
python -m utool.util_arg --exec-get_argflag --foo --exec-mode
python -m utool.util_arg --exec-get_argflag --no-foo --exec-mode
python -m utool.util_arg --exec-get_argflag --foo=True --exec-mode
python -m utool.util_arg --exec-get_argflag --foo=False --exec-mode
Example:
>>> # DISABLE_DOCTEST
>>> from utool.util_arg import * # NOQA
>>> argstr_ = '--foo'
>>> default = False
>>> help_ = ''
>>> return_specified = True
>>> (parsed_val, was_specified) = get_argflag(argstr_, default, help_, return_specified)
>>> result = ('(parsed_val, was_specified) = %s' % (str((parsed_val, was_specified)),))
>>> print(result)
"""
if argv is None:
argv = sys.argv
assert isinstance(default, bool), 'default must be boolean'
argstr_list = meta_util_iter.ensure_iterable(argstr_)
#if VERYVERBOSE:
# print('[util_arg] checking argstr_list=%r' % (argstr_list,))
# arg registration
_register_arg(argstr_list, bool, default, help_)
parsed_val = default
was_specified = False
if debug is None:
debug = DEBUG
# Check environment variables for default as well as argv
import os
#"""
#set UTOOL_NOCNN=True
#export UTOOL_NOCNN True
#"""
#argv_orig = argv[:]
# HACK: make this not happen very time you loop
for key, val in os.environ.items():
key = key.upper()
sentinal = 'UTOOL_'
if key.startswith(sentinal):
flag = '--' + key[len(sentinal):].lower().replace('_', '-')
if val.upper() in ['TRUE', 'ON']:
pass
elif val.upper() in ['FALSE', 'OFF']:
continue
else:
continue
#flag += '=False'
new_argv = [flag]
argv = argv[:] + new_argv
if debug:
print('ENV SPECIFIED COMMAND LINE')
print('argv.extend(new_argv=%r)' % (new_argv,))
for argstr in argstr_list:
#if VERYVERBOSE:
# print('[util_arg] * checking argstr=%r' % (argstr,))
if not (argstr.find('--') == 0 or (argstr.find('-') == 0 and len(argstr) == 2)):
raise AssertionError('Invalid argstr: %r' % (argstr,))
if not need_prefix:
noprefix = argstr.replace('--', '')
if noprefix in argv:
parsed_val = True
was_specified = True
break
#if argstr.find('--no') == 0:
#argstr = argstr.replace('--no', '--')
noarg = argstr.replace('--', '--no')
if argstr in argv:
parsed_val = True
was_specified = True
#if VERYVERBOSE:
# print('[util_arg] * ...WAS_SPECIFIED. AND PARSED')
break
elif noarg in argv:
parsed_val = False
was_specified = True
#if VERYVERBOSE:
# print('[util_arg] * ...WAS_SPECIFIED. AND NOT PARSED')
break
elif argstr + '=True' in argv:
parsed_val = True
was_specified = True
break
elif argstr + '=False' in argv:
parsed_val = False
was_specified = True
break
if return_specified is None:
return_specified = return_was_specified
if return_specified:
return parsed_val, was_specified
else:
return parsed_val | [
"def",
"get_argflag",
"(",
"argstr_",
",",
"default",
"=",
"False",
",",
"help_",
"=",
"''",
",",
"return_specified",
"=",
"None",
",",
"need_prefix",
"=",
"True",
",",
"return_was_specified",
"=",
"False",
",",
"argv",
"=",
"None",
",",
"debug",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"argv",
"is",
"None",
":",
"argv",
"=",
"sys",
".",
"argv",
"assert",
"isinstance",
"(",
"default",
",",
"bool",
")",
",",
"'default must be boolean'",
"argstr_list",
"=",
"meta_util_iter",
".",
"ensure_iterable",
"(",
"argstr_",
")",
"#if VERYVERBOSE:",
"# print('[util_arg] checking argstr_list=%r' % (argstr_list,))",
"# arg registration",
"_register_arg",
"(",
"argstr_list",
",",
"bool",
",",
"default",
",",
"help_",
")",
"parsed_val",
"=",
"default",
"was_specified",
"=",
"False",
"if",
"debug",
"is",
"None",
":",
"debug",
"=",
"DEBUG",
"# Check environment variables for default as well as argv",
"import",
"os",
"#\"\"\"",
"#set UTOOL_NOCNN=True",
"#export UTOOL_NOCNN True",
"#\"\"\"",
"#argv_orig = argv[:]",
"# HACK: make this not happen very time you loop",
"for",
"key",
",",
"val",
"in",
"os",
".",
"environ",
".",
"items",
"(",
")",
":",
"key",
"=",
"key",
".",
"upper",
"(",
")",
"sentinal",
"=",
"'UTOOL_'",
"if",
"key",
".",
"startswith",
"(",
"sentinal",
")",
":",
"flag",
"=",
"'--'",
"+",
"key",
"[",
"len",
"(",
"sentinal",
")",
":",
"]",
".",
"lower",
"(",
")",
".",
"replace",
"(",
"'_'",
",",
"'-'",
")",
"if",
"val",
".",
"upper",
"(",
")",
"in",
"[",
"'TRUE'",
",",
"'ON'",
"]",
":",
"pass",
"elif",
"val",
".",
"upper",
"(",
")",
"in",
"[",
"'FALSE'",
",",
"'OFF'",
"]",
":",
"continue",
"else",
":",
"continue",
"#flag += '=False'",
"new_argv",
"=",
"[",
"flag",
"]",
"argv",
"=",
"argv",
"[",
":",
"]",
"+",
"new_argv",
"if",
"debug",
":",
"print",
"(",
"'ENV SPECIFIED COMMAND LINE'",
")",
"print",
"(",
"'argv.extend(new_argv=%r)'",
"%",
"(",
"new_argv",
",",
")",
")",
"for",
"argstr",
"in",
"argstr_list",
":",
"#if VERYVERBOSE:",
"# print('[util_arg] * checking argstr=%r' % (argstr,))",
"if",
"not",
"(",
"argstr",
".",
"find",
"(",
"'--'",
")",
"==",
"0",
"or",
"(",
"argstr",
".",
"find",
"(",
"'-'",
")",
"==",
"0",
"and",
"len",
"(",
"argstr",
")",
"==",
"2",
")",
")",
":",
"raise",
"AssertionError",
"(",
"'Invalid argstr: %r'",
"%",
"(",
"argstr",
",",
")",
")",
"if",
"not",
"need_prefix",
":",
"noprefix",
"=",
"argstr",
".",
"replace",
"(",
"'--'",
",",
"''",
")",
"if",
"noprefix",
"in",
"argv",
":",
"parsed_val",
"=",
"True",
"was_specified",
"=",
"True",
"break",
"#if argstr.find('--no') == 0:",
"#argstr = argstr.replace('--no', '--')",
"noarg",
"=",
"argstr",
".",
"replace",
"(",
"'--'",
",",
"'--no'",
")",
"if",
"argstr",
"in",
"argv",
":",
"parsed_val",
"=",
"True",
"was_specified",
"=",
"True",
"#if VERYVERBOSE:",
"# print('[util_arg] * ...WAS_SPECIFIED. AND PARSED')",
"break",
"elif",
"noarg",
"in",
"argv",
":",
"parsed_val",
"=",
"False",
"was_specified",
"=",
"True",
"#if VERYVERBOSE:",
"# print('[util_arg] * ...WAS_SPECIFIED. AND NOT PARSED')",
"break",
"elif",
"argstr",
"+",
"'=True'",
"in",
"argv",
":",
"parsed_val",
"=",
"True",
"was_specified",
"=",
"True",
"break",
"elif",
"argstr",
"+",
"'=False'",
"in",
"argv",
":",
"parsed_val",
"=",
"False",
"was_specified",
"=",
"True",
"break",
"if",
"return_specified",
"is",
"None",
":",
"return_specified",
"=",
"return_was_specified",
"if",
"return_specified",
":",
"return",
"parsed_val",
",",
"was_specified",
"else",
":",
"return",
"parsed_val"
] | Checks if the commandline has a flag or a corresponding noflag
Args:
argstr_ (str, list, or tuple): the flag to look for
default (bool): dont use this (default = False)
help_ (str): a help string (default = '')
return_specified (bool): returns if flag was specified or not (default = False)
Returns:
tuple: (parsed_val, was_specified)
TODO:
depricate return_was_specified
CommandLine:
python -m utool.util_arg --exec-get_argflag --noface --exec-mode
python -m utool.util_arg --exec-get_argflag --foo --exec-mode
python -m utool.util_arg --exec-get_argflag --no-foo --exec-mode
python -m utool.util_arg --exec-get_argflag --foo=True --exec-mode
python -m utool.util_arg --exec-get_argflag --foo=False --exec-mode
Example:
>>> # DISABLE_DOCTEST
>>> from utool.util_arg import * # NOQA
>>> argstr_ = '--foo'
>>> default = False
>>> help_ = ''
>>> return_specified = True
>>> (parsed_val, was_specified) = get_argflag(argstr_, default, help_, return_specified)
>>> result = ('(parsed_val, was_specified) = %s' % (str((parsed_val, was_specified)),))
>>> print(result) | [
"Checks",
"if",
"the",
"commandline",
"has",
"a",
"flag",
"or",
"a",
"corresponding",
"noflag"
] | 3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a | https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/util_arg.py#L135-L253 | train |
Erotemic/utool | utool/util_arg.py | get_arg_dict | def get_arg_dict(argv=None, prefix_list=['--'], type_hints={}):
r"""
Yet another way for parsing args
CommandLine:
python -m utool.util_arg --exec-get_arg_dict
python -m utool.util_arg --test-get_arg_dict
Example:
>>> # ENABLE_DOCTEST
>>> from utool.util_arg import * # NOQA
>>> import utool as ut
>>> import shlex
>>> argv = shlex.split('--test-show_name --name=IBEIS_PZ_0303 --db testdb3 --save "~/latex/crall-candidacy-2015/figures/IBEIS_PZ_0303.jpg" --dpath figures --caption="Shadowed" --figsize=11,3 --no-figtitle -t foo bar baz biz --notitle')
>>> arg_dict = ut.get_arg_dict(argv, prefix_list=['--', '-'], type_hints={'t': list})
>>> result = ut.repr2(arg_dict, nl=1)
>>> # verify results
>>> print(result)
{
'caption': 'Shadowed',
'db': 'testdb3',
'dpath': 'figures',
'figsize': '11,3',
'name': 'IBEIS_PZ_0303',
'no-figtitle': True,
'notitle': True,
'save': '~/latex/crall-candidacy-2015/figures/IBEIS_PZ_0303.jpg',
't': ['foo', 'bar', 'baz', 'biz'],
'test-show_name': True,
}
"""
if argv is None:
argv = sys.argv
arg_dict = {}
def startswith_prefix(arg):
return any([arg.startswith(prefix) for prefix in prefix_list])
def argx_has_value(argv, argx):
# Check if has a value
if argv[argx].find('=') > -1:
return True
if argx + 1 < len(argv) and not startswith_prefix(argv[argx + 1]):
return True
return False
def get_arg_value(argv, argx, argname):
if argv[argx].find('=') > -1:
return '='.join(argv[argx].split('=')[1:])
else:
type_ = type_hints.get(argname, None)
if type_ is None:
return argv[argx + 1]
else:
return parse_arglist_hack(argx, argv=argv)
for argx in range(len(argv)):
arg = argv[argx]
for prefix in prefix_list:
if arg.startswith(prefix):
argname = arg[len(prefix):]
if argx_has_value(argv, argx):
if arg.find('=') > -1:
argname = arg[len(prefix):arg.find('=')]
argvalue = get_arg_value(argv, argx, argname)
arg_dict[argname] = argvalue
else:
arg_dict[argname] = True
break
return arg_dict | python | def get_arg_dict(argv=None, prefix_list=['--'], type_hints={}):
r"""
Yet another way for parsing args
CommandLine:
python -m utool.util_arg --exec-get_arg_dict
python -m utool.util_arg --test-get_arg_dict
Example:
>>> # ENABLE_DOCTEST
>>> from utool.util_arg import * # NOQA
>>> import utool as ut
>>> import shlex
>>> argv = shlex.split('--test-show_name --name=IBEIS_PZ_0303 --db testdb3 --save "~/latex/crall-candidacy-2015/figures/IBEIS_PZ_0303.jpg" --dpath figures --caption="Shadowed" --figsize=11,3 --no-figtitle -t foo bar baz biz --notitle')
>>> arg_dict = ut.get_arg_dict(argv, prefix_list=['--', '-'], type_hints={'t': list})
>>> result = ut.repr2(arg_dict, nl=1)
>>> # verify results
>>> print(result)
{
'caption': 'Shadowed',
'db': 'testdb3',
'dpath': 'figures',
'figsize': '11,3',
'name': 'IBEIS_PZ_0303',
'no-figtitle': True,
'notitle': True,
'save': '~/latex/crall-candidacy-2015/figures/IBEIS_PZ_0303.jpg',
't': ['foo', 'bar', 'baz', 'biz'],
'test-show_name': True,
}
"""
if argv is None:
argv = sys.argv
arg_dict = {}
def startswith_prefix(arg):
return any([arg.startswith(prefix) for prefix in prefix_list])
def argx_has_value(argv, argx):
# Check if has a value
if argv[argx].find('=') > -1:
return True
if argx + 1 < len(argv) and not startswith_prefix(argv[argx + 1]):
return True
return False
def get_arg_value(argv, argx, argname):
if argv[argx].find('=') > -1:
return '='.join(argv[argx].split('=')[1:])
else:
type_ = type_hints.get(argname, None)
if type_ is None:
return argv[argx + 1]
else:
return parse_arglist_hack(argx, argv=argv)
for argx in range(len(argv)):
arg = argv[argx]
for prefix in prefix_list:
if arg.startswith(prefix):
argname = arg[len(prefix):]
if argx_has_value(argv, argx):
if arg.find('=') > -1:
argname = arg[len(prefix):arg.find('=')]
argvalue = get_arg_value(argv, argx, argname)
arg_dict[argname] = argvalue
else:
arg_dict[argname] = True
break
return arg_dict | [
"def",
"get_arg_dict",
"(",
"argv",
"=",
"None",
",",
"prefix_list",
"=",
"[",
"'--'",
"]",
",",
"type_hints",
"=",
"{",
"}",
")",
":",
"if",
"argv",
"is",
"None",
":",
"argv",
"=",
"sys",
".",
"argv",
"arg_dict",
"=",
"{",
"}",
"def",
"startswith_prefix",
"(",
"arg",
")",
":",
"return",
"any",
"(",
"[",
"arg",
".",
"startswith",
"(",
"prefix",
")",
"for",
"prefix",
"in",
"prefix_list",
"]",
")",
"def",
"argx_has_value",
"(",
"argv",
",",
"argx",
")",
":",
"# Check if has a value",
"if",
"argv",
"[",
"argx",
"]",
".",
"find",
"(",
"'='",
")",
">",
"-",
"1",
":",
"return",
"True",
"if",
"argx",
"+",
"1",
"<",
"len",
"(",
"argv",
")",
"and",
"not",
"startswith_prefix",
"(",
"argv",
"[",
"argx",
"+",
"1",
"]",
")",
":",
"return",
"True",
"return",
"False",
"def",
"get_arg_value",
"(",
"argv",
",",
"argx",
",",
"argname",
")",
":",
"if",
"argv",
"[",
"argx",
"]",
".",
"find",
"(",
"'='",
")",
">",
"-",
"1",
":",
"return",
"'='",
".",
"join",
"(",
"argv",
"[",
"argx",
"]",
".",
"split",
"(",
"'='",
")",
"[",
"1",
":",
"]",
")",
"else",
":",
"type_",
"=",
"type_hints",
".",
"get",
"(",
"argname",
",",
"None",
")",
"if",
"type_",
"is",
"None",
":",
"return",
"argv",
"[",
"argx",
"+",
"1",
"]",
"else",
":",
"return",
"parse_arglist_hack",
"(",
"argx",
",",
"argv",
"=",
"argv",
")",
"for",
"argx",
"in",
"range",
"(",
"len",
"(",
"argv",
")",
")",
":",
"arg",
"=",
"argv",
"[",
"argx",
"]",
"for",
"prefix",
"in",
"prefix_list",
":",
"if",
"arg",
".",
"startswith",
"(",
"prefix",
")",
":",
"argname",
"=",
"arg",
"[",
"len",
"(",
"prefix",
")",
":",
"]",
"if",
"argx_has_value",
"(",
"argv",
",",
"argx",
")",
":",
"if",
"arg",
".",
"find",
"(",
"'='",
")",
">",
"-",
"1",
":",
"argname",
"=",
"arg",
"[",
"len",
"(",
"prefix",
")",
":",
"arg",
".",
"find",
"(",
"'='",
")",
"]",
"argvalue",
"=",
"get_arg_value",
"(",
"argv",
",",
"argx",
",",
"argname",
")",
"arg_dict",
"[",
"argname",
"]",
"=",
"argvalue",
"else",
":",
"arg_dict",
"[",
"argname",
"]",
"=",
"True",
"break",
"return",
"arg_dict"
] | r"""
Yet another way for parsing args
CommandLine:
python -m utool.util_arg --exec-get_arg_dict
python -m utool.util_arg --test-get_arg_dict
Example:
>>> # ENABLE_DOCTEST
>>> from utool.util_arg import * # NOQA
>>> import utool as ut
>>> import shlex
>>> argv = shlex.split('--test-show_name --name=IBEIS_PZ_0303 --db testdb3 --save "~/latex/crall-candidacy-2015/figures/IBEIS_PZ_0303.jpg" --dpath figures --caption="Shadowed" --figsize=11,3 --no-figtitle -t foo bar baz biz --notitle')
>>> arg_dict = ut.get_arg_dict(argv, prefix_list=['--', '-'], type_hints={'t': list})
>>> result = ut.repr2(arg_dict, nl=1)
>>> # verify results
>>> print(result)
{
'caption': 'Shadowed',
'db': 'testdb3',
'dpath': 'figures',
'figsize': '11,3',
'name': 'IBEIS_PZ_0303',
'no-figtitle': True,
'notitle': True,
'save': '~/latex/crall-candidacy-2015/figures/IBEIS_PZ_0303.jpg',
't': ['foo', 'bar', 'baz', 'biz'],
'test-show_name': True,
} | [
"r",
"Yet",
"another",
"way",
"for",
"parsing",
"args"
] | 3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a | https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/util_arg.py#L602-L671 | train |
Erotemic/utool | utool/util_arg.py | argv_flag_dec | def argv_flag_dec(*argin, **kwargs):
"""
Decorators which control program flow based on sys.argv
the decorated function does not execute without its corresponding
flag
Kwargs:
default, quiet, indent, default
ReturnKwargs:
alias_flags
"""
kwargs = kwargs.copy()
kwargs['default'] = kwargs.get('default', False)
from utool import util_decor
@util_decor.ignores_exc_tb(outer_wrapper=False)
def wrap_argv_flag_dec(func):
return __argv_flag_dec(func, **kwargs)
assert len(argin) < 2, 'specify 0 or 1 args'
if len(argin) == 1 and util_type.is_funclike(argin[0]):
func = argin[0]
return wrap_argv_flag_dec(func)
else:
return wrap_argv_flag_dec | python | def argv_flag_dec(*argin, **kwargs):
"""
Decorators which control program flow based on sys.argv
the decorated function does not execute without its corresponding
flag
Kwargs:
default, quiet, indent, default
ReturnKwargs:
alias_flags
"""
kwargs = kwargs.copy()
kwargs['default'] = kwargs.get('default', False)
from utool import util_decor
@util_decor.ignores_exc_tb(outer_wrapper=False)
def wrap_argv_flag_dec(func):
return __argv_flag_dec(func, **kwargs)
assert len(argin) < 2, 'specify 0 or 1 args'
if len(argin) == 1 and util_type.is_funclike(argin[0]):
func = argin[0]
return wrap_argv_flag_dec(func)
else:
return wrap_argv_flag_dec | [
"def",
"argv_flag_dec",
"(",
"*",
"argin",
",",
"*",
"*",
"kwargs",
")",
":",
"kwargs",
"=",
"kwargs",
".",
"copy",
"(",
")",
"kwargs",
"[",
"'default'",
"]",
"=",
"kwargs",
".",
"get",
"(",
"'default'",
",",
"False",
")",
"from",
"utool",
"import",
"util_decor",
"@",
"util_decor",
".",
"ignores_exc_tb",
"(",
"outer_wrapper",
"=",
"False",
")",
"def",
"wrap_argv_flag_dec",
"(",
"func",
")",
":",
"return",
"__argv_flag_dec",
"(",
"func",
",",
"*",
"*",
"kwargs",
")",
"assert",
"len",
"(",
"argin",
")",
"<",
"2",
",",
"'specify 0 or 1 args'",
"if",
"len",
"(",
"argin",
")",
"==",
"1",
"and",
"util_type",
".",
"is_funclike",
"(",
"argin",
"[",
"0",
"]",
")",
":",
"func",
"=",
"argin",
"[",
"0",
"]",
"return",
"wrap_argv_flag_dec",
"(",
"func",
")",
"else",
":",
"return",
"wrap_argv_flag_dec"
] | Decorators which control program flow based on sys.argv
the decorated function does not execute without its corresponding
flag
Kwargs:
default, quiet, indent, default
ReturnKwargs:
alias_flags | [
"Decorators",
"which",
"control",
"program",
"flow",
"based",
"on",
"sys",
".",
"argv",
"the",
"decorated",
"function",
"does",
"not",
"execute",
"without",
"its",
"corresponding",
"flag"
] | 3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a | https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/util_arg.py#L853-L878 | train |
Erotemic/utool | utool/util_arg.py | __argv_flag_dec | def __argv_flag_dec(func, default=False, quiet=QUIET, indent=False):
"""
Logic for controlling if a function gets called based on command line
"""
from utool import util_decor
flagname = meta_util_six.get_funcname(func)
if flagname.find('no') == 0:
flagname = flagname[2:]
flags = (
'--' + flagname.replace('_', '-'),
'--' + flagname,
)
@util_decor.ignores_exc_tb(outer_wrapper=False)
def GaurdWrapper(*args, **kwargs):
from utool import util_print
# FIXME: the --print-all is a hack
default_ = kwargs.pop('default', default)
alias_flags = kwargs.pop('alias_flags', [])
is_flagged = (get_argflag(flags, default_) or
get_argflag('--print-all') or
any([get_argflag(_) for _ in alias_flags]))
if flagname in kwargs:
is_flagged = kwargs.pop(flagname)
if is_flagged:
func_label = flags[0].replace('--', '').replace('print-', '')
# print('')
print('\n+ --- ' + func_label + ' ___')
use_indent = indent is not False
if indent is True:
indent_ = '[%s]' % func_label
else:
indent_ = indent
with util_print.Indenter(indent_, enabled=use_indent):
ret = func(*args, **kwargs)
print('L ___ ' + func_label + '___\n')
return ret
else:
PRINT_DISABLED_FLAGDEC = not get_argflag(
'--noinform', help_='does not print disabled flag decorators')
if not quiet and PRINT_DISABLED_FLAGDEC:
#print('\n~~~ %s ~~~' % flag)
print('~~~ %s ~~~' % flags[0])
meta_util_six.set_funcname(GaurdWrapper, meta_util_six.get_funcname(func))
return GaurdWrapper | python | def __argv_flag_dec(func, default=False, quiet=QUIET, indent=False):
"""
Logic for controlling if a function gets called based on command line
"""
from utool import util_decor
flagname = meta_util_six.get_funcname(func)
if flagname.find('no') == 0:
flagname = flagname[2:]
flags = (
'--' + flagname.replace('_', '-'),
'--' + flagname,
)
@util_decor.ignores_exc_tb(outer_wrapper=False)
def GaurdWrapper(*args, **kwargs):
from utool import util_print
# FIXME: the --print-all is a hack
default_ = kwargs.pop('default', default)
alias_flags = kwargs.pop('alias_flags', [])
is_flagged = (get_argflag(flags, default_) or
get_argflag('--print-all') or
any([get_argflag(_) for _ in alias_flags]))
if flagname in kwargs:
is_flagged = kwargs.pop(flagname)
if is_flagged:
func_label = flags[0].replace('--', '').replace('print-', '')
# print('')
print('\n+ --- ' + func_label + ' ___')
use_indent = indent is not False
if indent is True:
indent_ = '[%s]' % func_label
else:
indent_ = indent
with util_print.Indenter(indent_, enabled=use_indent):
ret = func(*args, **kwargs)
print('L ___ ' + func_label + '___\n')
return ret
else:
PRINT_DISABLED_FLAGDEC = not get_argflag(
'--noinform', help_='does not print disabled flag decorators')
if not quiet and PRINT_DISABLED_FLAGDEC:
#print('\n~~~ %s ~~~' % flag)
print('~~~ %s ~~~' % flags[0])
meta_util_six.set_funcname(GaurdWrapper, meta_util_six.get_funcname(func))
return GaurdWrapper | [
"def",
"__argv_flag_dec",
"(",
"func",
",",
"default",
"=",
"False",
",",
"quiet",
"=",
"QUIET",
",",
"indent",
"=",
"False",
")",
":",
"from",
"utool",
"import",
"util_decor",
"flagname",
"=",
"meta_util_six",
".",
"get_funcname",
"(",
"func",
")",
"if",
"flagname",
".",
"find",
"(",
"'no'",
")",
"==",
"0",
":",
"flagname",
"=",
"flagname",
"[",
"2",
":",
"]",
"flags",
"=",
"(",
"'--'",
"+",
"flagname",
".",
"replace",
"(",
"'_'",
",",
"'-'",
")",
",",
"'--'",
"+",
"flagname",
",",
")",
"@",
"util_decor",
".",
"ignores_exc_tb",
"(",
"outer_wrapper",
"=",
"False",
")",
"def",
"GaurdWrapper",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"from",
"utool",
"import",
"util_print",
"# FIXME: the --print-all is a hack",
"default_",
"=",
"kwargs",
".",
"pop",
"(",
"'default'",
",",
"default",
")",
"alias_flags",
"=",
"kwargs",
".",
"pop",
"(",
"'alias_flags'",
",",
"[",
"]",
")",
"is_flagged",
"=",
"(",
"get_argflag",
"(",
"flags",
",",
"default_",
")",
"or",
"get_argflag",
"(",
"'--print-all'",
")",
"or",
"any",
"(",
"[",
"get_argflag",
"(",
"_",
")",
"for",
"_",
"in",
"alias_flags",
"]",
")",
")",
"if",
"flagname",
"in",
"kwargs",
":",
"is_flagged",
"=",
"kwargs",
".",
"pop",
"(",
"flagname",
")",
"if",
"is_flagged",
":",
"func_label",
"=",
"flags",
"[",
"0",
"]",
".",
"replace",
"(",
"'--'",
",",
"''",
")",
".",
"replace",
"(",
"'print-'",
",",
"''",
")",
"# print('')",
"print",
"(",
"'\\n+ --- '",
"+",
"func_label",
"+",
"' ___'",
")",
"use_indent",
"=",
"indent",
"is",
"not",
"False",
"if",
"indent",
"is",
"True",
":",
"indent_",
"=",
"'[%s]'",
"%",
"func_label",
"else",
":",
"indent_",
"=",
"indent",
"with",
"util_print",
".",
"Indenter",
"(",
"indent_",
",",
"enabled",
"=",
"use_indent",
")",
":",
"ret",
"=",
"func",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"print",
"(",
"'L ___ '",
"+",
"func_label",
"+",
"'___\\n'",
")",
"return",
"ret",
"else",
":",
"PRINT_DISABLED_FLAGDEC",
"=",
"not",
"get_argflag",
"(",
"'--noinform'",
",",
"help_",
"=",
"'does not print disabled flag decorators'",
")",
"if",
"not",
"quiet",
"and",
"PRINT_DISABLED_FLAGDEC",
":",
"#print('\\n~~~ %s ~~~' % flag)",
"print",
"(",
"'~~~ %s ~~~'",
"%",
"flags",
"[",
"0",
"]",
")",
"meta_util_six",
".",
"set_funcname",
"(",
"GaurdWrapper",
",",
"meta_util_six",
".",
"get_funcname",
"(",
"func",
")",
")",
"return",
"GaurdWrapper"
] | Logic for controlling if a function gets called based on command line | [
"Logic",
"for",
"controlling",
"if",
"a",
"function",
"gets",
"called",
"based",
"on",
"command",
"line"
] | 3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a | https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/util_arg.py#L885-L930 | train |
Erotemic/utool | utool/util_arg.py | get_argv_tail | def get_argv_tail(scriptname, prefer_main=None, argv=None):
r"""
gets the rest of the arguments after a script has been invoked hack.
accounts for python -m scripts.
Args:
scriptname (str):
CommandLine:
python -m utool.util_arg --test-get_argv_tail
Example:
>>> # ENABLE_DOCTEST
>>> from utool.util_arg import * # NOQA
>>> import utool as ut
>>> from os.path import relpath, dirname
>>> scriptname = 'utool.util_arg'
>>> prefer_main = False
>>> argv=['python', '-m', 'utool.util_arg', '--test-get_argv_tail']
>>> tail = get_argv_tail(scriptname, prefer_main, argv)
>>> # hack
>>> tail[0] = ut.ensure_unixslash(relpath(tail[0], dirname(dirname(ut.__file__))))
>>> result = ut.repr2(tail)
>>> print(result)
['utool/util_arg.py', '--test-get_argv_tail']
Example:
>>> # ENABLE_DOCTEST
>>> from utool.util_arg import * # NOQA
>>> import utool as ut
>>> from os.path import relpath, dirname
>>> scriptname = 'utprof.py'
>>> prefer_main = True
>>> argv=['utprof.py', '-m', 'utool', '--tf', 'get_argv_tail']
>>> tail = get_argv_tail(scriptname, prefer_main, argv)
>>> # hack
>>> tail[0] = ut.ensure_unixslash(relpath(tail[0], dirname(dirname(ut.__file__))))
>>> result = ut.repr2(tail)
>>> print(result)
['utool/__main__.py', '--tf', 'get_argv_tail']
"""
if argv is None:
argv = sys.argv
import utool as ut
modname = ut.get_argval('-m', help_='specify module name to profile', argv=argv)
if modname is not None:
# hack to account for -m scripts
modpath = ut.get_modpath(modname, prefer_main=prefer_main)
argvx = argv.index(modname) + 1
argv_tail = [modpath] + argv[argvx:]
else:
try:
argvx = argv.index(scriptname)
except ValueError:
for argvx, arg in enumerate(argv):
# HACK
if scriptname in arg:
break
argv_tail = argv[(argvx + 1):]
return argv_tail | python | def get_argv_tail(scriptname, prefer_main=None, argv=None):
r"""
gets the rest of the arguments after a script has been invoked hack.
accounts for python -m scripts.
Args:
scriptname (str):
CommandLine:
python -m utool.util_arg --test-get_argv_tail
Example:
>>> # ENABLE_DOCTEST
>>> from utool.util_arg import * # NOQA
>>> import utool as ut
>>> from os.path import relpath, dirname
>>> scriptname = 'utool.util_arg'
>>> prefer_main = False
>>> argv=['python', '-m', 'utool.util_arg', '--test-get_argv_tail']
>>> tail = get_argv_tail(scriptname, prefer_main, argv)
>>> # hack
>>> tail[0] = ut.ensure_unixslash(relpath(tail[0], dirname(dirname(ut.__file__))))
>>> result = ut.repr2(tail)
>>> print(result)
['utool/util_arg.py', '--test-get_argv_tail']
Example:
>>> # ENABLE_DOCTEST
>>> from utool.util_arg import * # NOQA
>>> import utool as ut
>>> from os.path import relpath, dirname
>>> scriptname = 'utprof.py'
>>> prefer_main = True
>>> argv=['utprof.py', '-m', 'utool', '--tf', 'get_argv_tail']
>>> tail = get_argv_tail(scriptname, prefer_main, argv)
>>> # hack
>>> tail[0] = ut.ensure_unixslash(relpath(tail[0], dirname(dirname(ut.__file__))))
>>> result = ut.repr2(tail)
>>> print(result)
['utool/__main__.py', '--tf', 'get_argv_tail']
"""
if argv is None:
argv = sys.argv
import utool as ut
modname = ut.get_argval('-m', help_='specify module name to profile', argv=argv)
if modname is not None:
# hack to account for -m scripts
modpath = ut.get_modpath(modname, prefer_main=prefer_main)
argvx = argv.index(modname) + 1
argv_tail = [modpath] + argv[argvx:]
else:
try:
argvx = argv.index(scriptname)
except ValueError:
for argvx, arg in enumerate(argv):
# HACK
if scriptname in arg:
break
argv_tail = argv[(argvx + 1):]
return argv_tail | [
"def",
"get_argv_tail",
"(",
"scriptname",
",",
"prefer_main",
"=",
"None",
",",
"argv",
"=",
"None",
")",
":",
"if",
"argv",
"is",
"None",
":",
"argv",
"=",
"sys",
".",
"argv",
"import",
"utool",
"as",
"ut",
"modname",
"=",
"ut",
".",
"get_argval",
"(",
"'-m'",
",",
"help_",
"=",
"'specify module name to profile'",
",",
"argv",
"=",
"argv",
")",
"if",
"modname",
"is",
"not",
"None",
":",
"# hack to account for -m scripts",
"modpath",
"=",
"ut",
".",
"get_modpath",
"(",
"modname",
",",
"prefer_main",
"=",
"prefer_main",
")",
"argvx",
"=",
"argv",
".",
"index",
"(",
"modname",
")",
"+",
"1",
"argv_tail",
"=",
"[",
"modpath",
"]",
"+",
"argv",
"[",
"argvx",
":",
"]",
"else",
":",
"try",
":",
"argvx",
"=",
"argv",
".",
"index",
"(",
"scriptname",
")",
"except",
"ValueError",
":",
"for",
"argvx",
",",
"arg",
"in",
"enumerate",
"(",
"argv",
")",
":",
"# HACK",
"if",
"scriptname",
"in",
"arg",
":",
"break",
"argv_tail",
"=",
"argv",
"[",
"(",
"argvx",
"+",
"1",
")",
":",
"]",
"return",
"argv_tail"
] | r"""
gets the rest of the arguments after a script has been invoked hack.
accounts for python -m scripts.
Args:
scriptname (str):
CommandLine:
python -m utool.util_arg --test-get_argv_tail
Example:
>>> # ENABLE_DOCTEST
>>> from utool.util_arg import * # NOQA
>>> import utool as ut
>>> from os.path import relpath, dirname
>>> scriptname = 'utool.util_arg'
>>> prefer_main = False
>>> argv=['python', '-m', 'utool.util_arg', '--test-get_argv_tail']
>>> tail = get_argv_tail(scriptname, prefer_main, argv)
>>> # hack
>>> tail[0] = ut.ensure_unixslash(relpath(tail[0], dirname(dirname(ut.__file__))))
>>> result = ut.repr2(tail)
>>> print(result)
['utool/util_arg.py', '--test-get_argv_tail']
Example:
>>> # ENABLE_DOCTEST
>>> from utool.util_arg import * # NOQA
>>> import utool as ut
>>> from os.path import relpath, dirname
>>> scriptname = 'utprof.py'
>>> prefer_main = True
>>> argv=['utprof.py', '-m', 'utool', '--tf', 'get_argv_tail']
>>> tail = get_argv_tail(scriptname, prefer_main, argv)
>>> # hack
>>> tail[0] = ut.ensure_unixslash(relpath(tail[0], dirname(dirname(ut.__file__))))
>>> result = ut.repr2(tail)
>>> print(result)
['utool/__main__.py', '--tf', 'get_argv_tail'] | [
"r",
"gets",
"the",
"rest",
"of",
"the",
"arguments",
"after",
"a",
"script",
"has",
"been",
"invoked",
"hack",
".",
"accounts",
"for",
"python",
"-",
"m",
"scripts",
"."
] | 3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a | https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/util_arg.py#L1068-L1127 | train |
Erotemic/utool | utool/util_arg.py | get_cmdline_varargs | def get_cmdline_varargs(argv=None):
"""
Returns positional args specified directly after the scriptname
and before any args starting with '-' on the commandline.
"""
if argv is None:
argv = sys.argv
scriptname = argv[0]
if scriptname == '':
# python invoked by iteself
pos_start = 0
pos_end = 0
else:
pos_start = pos_end = 1
for idx in range(pos_start, len(argv)):
if argv[idx].startswith('-'):
pos_end = idx
break
else:
pos_end = len(argv)
cmdline_varargs = argv[pos_start:pos_end]
return cmdline_varargs | python | def get_cmdline_varargs(argv=None):
"""
Returns positional args specified directly after the scriptname
and before any args starting with '-' on the commandline.
"""
if argv is None:
argv = sys.argv
scriptname = argv[0]
if scriptname == '':
# python invoked by iteself
pos_start = 0
pos_end = 0
else:
pos_start = pos_end = 1
for idx in range(pos_start, len(argv)):
if argv[idx].startswith('-'):
pos_end = idx
break
else:
pos_end = len(argv)
cmdline_varargs = argv[pos_start:pos_end]
return cmdline_varargs | [
"def",
"get_cmdline_varargs",
"(",
"argv",
"=",
"None",
")",
":",
"if",
"argv",
"is",
"None",
":",
"argv",
"=",
"sys",
".",
"argv",
"scriptname",
"=",
"argv",
"[",
"0",
"]",
"if",
"scriptname",
"==",
"''",
":",
"# python invoked by iteself",
"pos_start",
"=",
"0",
"pos_end",
"=",
"0",
"else",
":",
"pos_start",
"=",
"pos_end",
"=",
"1",
"for",
"idx",
"in",
"range",
"(",
"pos_start",
",",
"len",
"(",
"argv",
")",
")",
":",
"if",
"argv",
"[",
"idx",
"]",
".",
"startswith",
"(",
"'-'",
")",
":",
"pos_end",
"=",
"idx",
"break",
"else",
":",
"pos_end",
"=",
"len",
"(",
"argv",
")",
"cmdline_varargs",
"=",
"argv",
"[",
"pos_start",
":",
"pos_end",
"]",
"return",
"cmdline_varargs"
] | Returns positional args specified directly after the scriptname
and before any args starting with '-' on the commandline. | [
"Returns",
"positional",
"args",
"specified",
"directly",
"after",
"the",
"scriptname",
"and",
"before",
"any",
"args",
"starting",
"with",
"-",
"on",
"the",
"commandline",
"."
] | 3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a | https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/util_arg.py#L1130-L1151 | train |
Erotemic/utool | utool/util_arg.py | argval | def argval(key, default=None, type=None, smartcast=True, return_exists=False,
argv=None):
"""
alias for get_argval
Example:
>>> # ENABLE_DOCTEST
>>> import utool as ut
>>> import sys
>>> argv = ['--aids=[1,2,3]']
>>> value = ut.argval('--aids', default=[1, 2], argv=argv)
>>> assert isinstance(value, list)
>>> value2 = ut.argval('--aids', smartcast=False, argv=argv)
>>> assert isinstance(value2, str)
>>> value2 = ut.argval('--aids', smartcast=True, argv=argv)
>>> assert isinstance(value2, list)
"""
defaultable_types = (tuple, list, int, float)
if type is None and isinstance(default, defaultable_types):
type = builtins.type(default)
return get_argval(key, type_=type, default=default,
return_was_specified=return_exists, smartcast=smartcast,
argv=argv) | python | def argval(key, default=None, type=None, smartcast=True, return_exists=False,
argv=None):
"""
alias for get_argval
Example:
>>> # ENABLE_DOCTEST
>>> import utool as ut
>>> import sys
>>> argv = ['--aids=[1,2,3]']
>>> value = ut.argval('--aids', default=[1, 2], argv=argv)
>>> assert isinstance(value, list)
>>> value2 = ut.argval('--aids', smartcast=False, argv=argv)
>>> assert isinstance(value2, str)
>>> value2 = ut.argval('--aids', smartcast=True, argv=argv)
>>> assert isinstance(value2, list)
"""
defaultable_types = (tuple, list, int, float)
if type is None and isinstance(default, defaultable_types):
type = builtins.type(default)
return get_argval(key, type_=type, default=default,
return_was_specified=return_exists, smartcast=smartcast,
argv=argv) | [
"def",
"argval",
"(",
"key",
",",
"default",
"=",
"None",
",",
"type",
"=",
"None",
",",
"smartcast",
"=",
"True",
",",
"return_exists",
"=",
"False",
",",
"argv",
"=",
"None",
")",
":",
"defaultable_types",
"=",
"(",
"tuple",
",",
"list",
",",
"int",
",",
"float",
")",
"if",
"type",
"is",
"None",
"and",
"isinstance",
"(",
"default",
",",
"defaultable_types",
")",
":",
"type",
"=",
"builtins",
".",
"type",
"(",
"default",
")",
"return",
"get_argval",
"(",
"key",
",",
"type_",
"=",
"type",
",",
"default",
"=",
"default",
",",
"return_was_specified",
"=",
"return_exists",
",",
"smartcast",
"=",
"smartcast",
",",
"argv",
"=",
"argv",
")"
] | alias for get_argval
Example:
>>> # ENABLE_DOCTEST
>>> import utool as ut
>>> import sys
>>> argv = ['--aids=[1,2,3]']
>>> value = ut.argval('--aids', default=[1, 2], argv=argv)
>>> assert isinstance(value, list)
>>> value2 = ut.argval('--aids', smartcast=False, argv=argv)
>>> assert isinstance(value2, str)
>>> value2 = ut.argval('--aids', smartcast=True, argv=argv)
>>> assert isinstance(value2, list) | [
"alias",
"for",
"get_argval"
] | 3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a | https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/util_arg.py#L1167-L1189 | train |
YuriyGuts/pygoose | pygoose/kg/eda.py | plot_real_feature | def plot_real_feature(df, feature_name, bins=50, figsize=(15, 15)):
"""
Plot the distribution of a real-valued feature conditioned by the target.
Examples:
`plot_real_feature(X, 'emb_mean_euclidean')`
Args:
df: Pandas dataframe containing the target column (named 'target').
feature_name: The name of the feature to plot.
bins: The number of histogram bins for the distribution plot.
figsize: The size of the plotted figure.
"""
ix_negative_target = df[df.target == 0].index
ix_positive_target = df[df.target == 1].index
plt.figure(figsize=figsize)
ax_overall_dist = plt.subplot2grid((3, 2), (0, 0), colspan=2)
ax_target_conditional_dist = plt.subplot2grid((3, 2), (1, 0), colspan=2)
ax_botplot = plt.subplot2grid((3, 2), (2, 0))
ax_violin_plot = plt.subplot2grid((3, 2), (2, 1))
ax_overall_dist.set_title('Distribution of {}'.format(feature_name), fontsize=16)
sns.distplot(
df[feature_name],
bins=50,
ax=ax_overall_dist
)
sns.distplot(
df.loc[ix_positive_target][feature_name],
bins=bins,
ax=ax_target_conditional_dist,
label='Positive Target'
)
sns.distplot(
df.loc[ix_negative_target][feature_name],
bins=bins,
ax=ax_target_conditional_dist,
label='Negative Target'
)
ax_target_conditional_dist.legend(loc='upper right', prop={'size': 14})
sns.boxplot(
y=feature_name,
x='target',
data=df,
ax=ax_botplot
)
sns.violinplot(
y=feature_name,
x='target',
data=df,
ax=ax_violin_plot
)
plt.show() | python | def plot_real_feature(df, feature_name, bins=50, figsize=(15, 15)):
"""
Plot the distribution of a real-valued feature conditioned by the target.
Examples:
`plot_real_feature(X, 'emb_mean_euclidean')`
Args:
df: Pandas dataframe containing the target column (named 'target').
feature_name: The name of the feature to plot.
bins: The number of histogram bins for the distribution plot.
figsize: The size of the plotted figure.
"""
ix_negative_target = df[df.target == 0].index
ix_positive_target = df[df.target == 1].index
plt.figure(figsize=figsize)
ax_overall_dist = plt.subplot2grid((3, 2), (0, 0), colspan=2)
ax_target_conditional_dist = plt.subplot2grid((3, 2), (1, 0), colspan=2)
ax_botplot = plt.subplot2grid((3, 2), (2, 0))
ax_violin_plot = plt.subplot2grid((3, 2), (2, 1))
ax_overall_dist.set_title('Distribution of {}'.format(feature_name), fontsize=16)
sns.distplot(
df[feature_name],
bins=50,
ax=ax_overall_dist
)
sns.distplot(
df.loc[ix_positive_target][feature_name],
bins=bins,
ax=ax_target_conditional_dist,
label='Positive Target'
)
sns.distplot(
df.loc[ix_negative_target][feature_name],
bins=bins,
ax=ax_target_conditional_dist,
label='Negative Target'
)
ax_target_conditional_dist.legend(loc='upper right', prop={'size': 14})
sns.boxplot(
y=feature_name,
x='target',
data=df,
ax=ax_botplot
)
sns.violinplot(
y=feature_name,
x='target',
data=df,
ax=ax_violin_plot
)
plt.show() | [
"def",
"plot_real_feature",
"(",
"df",
",",
"feature_name",
",",
"bins",
"=",
"50",
",",
"figsize",
"=",
"(",
"15",
",",
"15",
")",
")",
":",
"ix_negative_target",
"=",
"df",
"[",
"df",
".",
"target",
"==",
"0",
"]",
".",
"index",
"ix_positive_target",
"=",
"df",
"[",
"df",
".",
"target",
"==",
"1",
"]",
".",
"index",
"plt",
".",
"figure",
"(",
"figsize",
"=",
"figsize",
")",
"ax_overall_dist",
"=",
"plt",
".",
"subplot2grid",
"(",
"(",
"3",
",",
"2",
")",
",",
"(",
"0",
",",
"0",
")",
",",
"colspan",
"=",
"2",
")",
"ax_target_conditional_dist",
"=",
"plt",
".",
"subplot2grid",
"(",
"(",
"3",
",",
"2",
")",
",",
"(",
"1",
",",
"0",
")",
",",
"colspan",
"=",
"2",
")",
"ax_botplot",
"=",
"plt",
".",
"subplot2grid",
"(",
"(",
"3",
",",
"2",
")",
",",
"(",
"2",
",",
"0",
")",
")",
"ax_violin_plot",
"=",
"plt",
".",
"subplot2grid",
"(",
"(",
"3",
",",
"2",
")",
",",
"(",
"2",
",",
"1",
")",
")",
"ax_overall_dist",
".",
"set_title",
"(",
"'Distribution of {}'",
".",
"format",
"(",
"feature_name",
")",
",",
"fontsize",
"=",
"16",
")",
"sns",
".",
"distplot",
"(",
"df",
"[",
"feature_name",
"]",
",",
"bins",
"=",
"50",
",",
"ax",
"=",
"ax_overall_dist",
")",
"sns",
".",
"distplot",
"(",
"df",
".",
"loc",
"[",
"ix_positive_target",
"]",
"[",
"feature_name",
"]",
",",
"bins",
"=",
"bins",
",",
"ax",
"=",
"ax_target_conditional_dist",
",",
"label",
"=",
"'Positive Target'",
")",
"sns",
".",
"distplot",
"(",
"df",
".",
"loc",
"[",
"ix_negative_target",
"]",
"[",
"feature_name",
"]",
",",
"bins",
"=",
"bins",
",",
"ax",
"=",
"ax_target_conditional_dist",
",",
"label",
"=",
"'Negative Target'",
")",
"ax_target_conditional_dist",
".",
"legend",
"(",
"loc",
"=",
"'upper right'",
",",
"prop",
"=",
"{",
"'size'",
":",
"14",
"}",
")",
"sns",
".",
"boxplot",
"(",
"y",
"=",
"feature_name",
",",
"x",
"=",
"'target'",
",",
"data",
"=",
"df",
",",
"ax",
"=",
"ax_botplot",
")",
"sns",
".",
"violinplot",
"(",
"y",
"=",
"feature_name",
",",
"x",
"=",
"'target'",
",",
"data",
"=",
"df",
",",
"ax",
"=",
"ax_violin_plot",
")",
"plt",
".",
"show",
"(",
")"
] | Plot the distribution of a real-valued feature conditioned by the target.
Examples:
`plot_real_feature(X, 'emb_mean_euclidean')`
Args:
df: Pandas dataframe containing the target column (named 'target').
feature_name: The name of the feature to plot.
bins: The number of histogram bins for the distribution plot.
figsize: The size of the plotted figure. | [
"Plot",
"the",
"distribution",
"of",
"a",
"real",
"-",
"valued",
"feature",
"conditioned",
"by",
"the",
"target",
"."
] | 4d9b8827c6d6c4b79949d1cd653393498c0bb3c2 | https://github.com/YuriyGuts/pygoose/blob/4d9b8827c6d6c4b79949d1cd653393498c0bb3c2/pygoose/kg/eda.py#L6-L65 | train |
YuriyGuts/pygoose | pygoose/kg/eda.py | plot_pair | def plot_pair(df, feature_name_1, feature_name_2, kind='scatter', alpha=0.01, **kwargs):
"""
Plot a scatterplot of two features against one another,
and calculate Pearson correlation coefficient.
Examples:
`plot_pair(X, 'emb_mean_euclidean', 'emb_mean_cosine')`
Args:
df:
feature_name_1: The name of the first feature.
feature_name_2: The name of the second feature.
kind: One of the values { 'scatter' | 'reg' | 'resid' | 'kde' | 'hex' }.
alpha: Alpha channel value.
**kwargs: Additional argument to 'sns.jointplot'.
"""
plt.figure()
sns.jointplot(
feature_name_1,
feature_name_2,
df,
alpha=alpha,
kind=kind,
**kwargs
)
plt.show() | python | def plot_pair(df, feature_name_1, feature_name_2, kind='scatter', alpha=0.01, **kwargs):
"""
Plot a scatterplot of two features against one another,
and calculate Pearson correlation coefficient.
Examples:
`plot_pair(X, 'emb_mean_euclidean', 'emb_mean_cosine')`
Args:
df:
feature_name_1: The name of the first feature.
feature_name_2: The name of the second feature.
kind: One of the values { 'scatter' | 'reg' | 'resid' | 'kde' | 'hex' }.
alpha: Alpha channel value.
**kwargs: Additional argument to 'sns.jointplot'.
"""
plt.figure()
sns.jointplot(
feature_name_1,
feature_name_2,
df,
alpha=alpha,
kind=kind,
**kwargs
)
plt.show() | [
"def",
"plot_pair",
"(",
"df",
",",
"feature_name_1",
",",
"feature_name_2",
",",
"kind",
"=",
"'scatter'",
",",
"alpha",
"=",
"0.01",
",",
"*",
"*",
"kwargs",
")",
":",
"plt",
".",
"figure",
"(",
")",
"sns",
".",
"jointplot",
"(",
"feature_name_1",
",",
"feature_name_2",
",",
"df",
",",
"alpha",
"=",
"alpha",
",",
"kind",
"=",
"kind",
",",
"*",
"*",
"kwargs",
")",
"plt",
".",
"show",
"(",
")"
] | Plot a scatterplot of two features against one another,
and calculate Pearson correlation coefficient.
Examples:
`plot_pair(X, 'emb_mean_euclidean', 'emb_mean_cosine')`
Args:
df:
feature_name_1: The name of the first feature.
feature_name_2: The name of the second feature.
kind: One of the values { 'scatter' | 'reg' | 'resid' | 'kde' | 'hex' }.
alpha: Alpha channel value.
**kwargs: Additional argument to 'sns.jointplot'. | [
"Plot",
"a",
"scatterplot",
"of",
"two",
"features",
"against",
"one",
"another",
"and",
"calculate",
"Pearson",
"correlation",
"coefficient",
"."
] | 4d9b8827c6d6c4b79949d1cd653393498c0bb3c2 | https://github.com/YuriyGuts/pygoose/blob/4d9b8827c6d6c4b79949d1cd653393498c0bb3c2/pygoose/kg/eda.py#L68-L94 | train |
YuriyGuts/pygoose | pygoose/kg/eda.py | plot_feature_correlation_heatmap | def plot_feature_correlation_heatmap(df, features, font_size=9, figsize=(15, 15), save_filename=None):
"""
Plot a correlation heatmap between every feature pair.
Args:
df: Pandas dataframe containing the target column (named 'target').
features: The list of features to include in the correlation plot.
font_size: Font size for heatmap cells and axis labels.
figsize: The size of the plot.
save_filename: (Optional) The path of the file to save a high-res version of the plot to.
"""
features = features[:]
features += ['target']
mcorr = df[features].corr()
mask = np.zeros_like(mcorr, dtype=np.bool)
mask[np.triu_indices_from(mask)] = True
cmap = sns.diverging_palette(220, 10, as_cmap=True)
fig = plt.figure(figsize=figsize)
heatmap = sns.heatmap(
mcorr,
mask=mask,
cmap=cmap,
square=True,
annot=True,
fmt='0.2f',
annot_kws={'size': font_size},
)
heatmap.tick_params(axis='both', which='major', labelsize=font_size)
heatmap.tick_params(axis='both', which='minor', labelsize=font_size)
heatmap.set_xticklabels(features, rotation=90)
heatmap.set_yticklabels(reversed(features))
plt.show()
if save_filename is not None:
fig.savefig(save_filename, dpi=300) | python | def plot_feature_correlation_heatmap(df, features, font_size=9, figsize=(15, 15), save_filename=None):
"""
Plot a correlation heatmap between every feature pair.
Args:
df: Pandas dataframe containing the target column (named 'target').
features: The list of features to include in the correlation plot.
font_size: Font size for heatmap cells and axis labels.
figsize: The size of the plot.
save_filename: (Optional) The path of the file to save a high-res version of the plot to.
"""
features = features[:]
features += ['target']
mcorr = df[features].corr()
mask = np.zeros_like(mcorr, dtype=np.bool)
mask[np.triu_indices_from(mask)] = True
cmap = sns.diverging_palette(220, 10, as_cmap=True)
fig = plt.figure(figsize=figsize)
heatmap = sns.heatmap(
mcorr,
mask=mask,
cmap=cmap,
square=True,
annot=True,
fmt='0.2f',
annot_kws={'size': font_size},
)
heatmap.tick_params(axis='both', which='major', labelsize=font_size)
heatmap.tick_params(axis='both', which='minor', labelsize=font_size)
heatmap.set_xticklabels(features, rotation=90)
heatmap.set_yticklabels(reversed(features))
plt.show()
if save_filename is not None:
fig.savefig(save_filename, dpi=300) | [
"def",
"plot_feature_correlation_heatmap",
"(",
"df",
",",
"features",
",",
"font_size",
"=",
"9",
",",
"figsize",
"=",
"(",
"15",
",",
"15",
")",
",",
"save_filename",
"=",
"None",
")",
":",
"features",
"=",
"features",
"[",
":",
"]",
"features",
"+=",
"[",
"'target'",
"]",
"mcorr",
"=",
"df",
"[",
"features",
"]",
".",
"corr",
"(",
")",
"mask",
"=",
"np",
".",
"zeros_like",
"(",
"mcorr",
",",
"dtype",
"=",
"np",
".",
"bool",
")",
"mask",
"[",
"np",
".",
"triu_indices_from",
"(",
"mask",
")",
"]",
"=",
"True",
"cmap",
"=",
"sns",
".",
"diverging_palette",
"(",
"220",
",",
"10",
",",
"as_cmap",
"=",
"True",
")",
"fig",
"=",
"plt",
".",
"figure",
"(",
"figsize",
"=",
"figsize",
")",
"heatmap",
"=",
"sns",
".",
"heatmap",
"(",
"mcorr",
",",
"mask",
"=",
"mask",
",",
"cmap",
"=",
"cmap",
",",
"square",
"=",
"True",
",",
"annot",
"=",
"True",
",",
"fmt",
"=",
"'0.2f'",
",",
"annot_kws",
"=",
"{",
"'size'",
":",
"font_size",
"}",
",",
")",
"heatmap",
".",
"tick_params",
"(",
"axis",
"=",
"'both'",
",",
"which",
"=",
"'major'",
",",
"labelsize",
"=",
"font_size",
")",
"heatmap",
".",
"tick_params",
"(",
"axis",
"=",
"'both'",
",",
"which",
"=",
"'minor'",
",",
"labelsize",
"=",
"font_size",
")",
"heatmap",
".",
"set_xticklabels",
"(",
"features",
",",
"rotation",
"=",
"90",
")",
"heatmap",
".",
"set_yticklabels",
"(",
"reversed",
"(",
"features",
")",
")",
"plt",
".",
"show",
"(",
")",
"if",
"save_filename",
"is",
"not",
"None",
":",
"fig",
".",
"savefig",
"(",
"save_filename",
",",
"dpi",
"=",
"300",
")"
] | Plot a correlation heatmap between every feature pair.
Args:
df: Pandas dataframe containing the target column (named 'target').
features: The list of features to include in the correlation plot.
font_size: Font size for heatmap cells and axis labels.
figsize: The size of the plot.
save_filename: (Optional) The path of the file to save a high-res version of the plot to. | [
"Plot",
"a",
"correlation",
"heatmap",
"between",
"every",
"feature",
"pair",
"."
] | 4d9b8827c6d6c4b79949d1cd653393498c0bb3c2 | https://github.com/YuriyGuts/pygoose/blob/4d9b8827c6d6c4b79949d1cd653393498c0bb3c2/pygoose/kg/eda.py#L97-L138 | train |
YuriyGuts/pygoose | pygoose/kg/eda.py | scatterplot_matrix | def scatterplot_matrix(df, features, downsample_frac=None, figsize=(15, 15)):
"""
Plot a scatterplot matrix for a list of features, colored by target value.
Example: `scatterplot_matrix(X, X.columns.tolist(), downsample_frac=0.01)`
Args:
df: Pandas dataframe containing the target column (named 'target').
features: The list of features to include in the correlation plot.
downsample_frac: Dataframe downsampling rate (0.1 to include 10% of the dataset).
figsize: The size of the plot.
"""
if downsample_frac:
df = df.sample(frac=downsample_frac)
plt.figure(figsize=figsize)
sns.pairplot(df[features], hue='target')
plt.show() | python | def scatterplot_matrix(df, features, downsample_frac=None, figsize=(15, 15)):
"""
Plot a scatterplot matrix for a list of features, colored by target value.
Example: `scatterplot_matrix(X, X.columns.tolist(), downsample_frac=0.01)`
Args:
df: Pandas dataframe containing the target column (named 'target').
features: The list of features to include in the correlation plot.
downsample_frac: Dataframe downsampling rate (0.1 to include 10% of the dataset).
figsize: The size of the plot.
"""
if downsample_frac:
df = df.sample(frac=downsample_frac)
plt.figure(figsize=figsize)
sns.pairplot(df[features], hue='target')
plt.show() | [
"def",
"scatterplot_matrix",
"(",
"df",
",",
"features",
",",
"downsample_frac",
"=",
"None",
",",
"figsize",
"=",
"(",
"15",
",",
"15",
")",
")",
":",
"if",
"downsample_frac",
":",
"df",
"=",
"df",
".",
"sample",
"(",
"frac",
"=",
"downsample_frac",
")",
"plt",
".",
"figure",
"(",
"figsize",
"=",
"figsize",
")",
"sns",
".",
"pairplot",
"(",
"df",
"[",
"features",
"]",
",",
"hue",
"=",
"'target'",
")",
"plt",
".",
"show",
"(",
")"
] | Plot a scatterplot matrix for a list of features, colored by target value.
Example: `scatterplot_matrix(X, X.columns.tolist(), downsample_frac=0.01)`
Args:
df: Pandas dataframe containing the target column (named 'target').
features: The list of features to include in the correlation plot.
downsample_frac: Dataframe downsampling rate (0.1 to include 10% of the dataset).
figsize: The size of the plot. | [
"Plot",
"a",
"scatterplot",
"matrix",
"for",
"a",
"list",
"of",
"features",
"colored",
"by",
"target",
"value",
"."
] | 4d9b8827c6d6c4b79949d1cd653393498c0bb3c2 | https://github.com/YuriyGuts/pygoose/blob/4d9b8827c6d6c4b79949d1cd653393498c0bb3c2/pygoose/kg/eda.py#L141-L159 | train |
LEMS/pylems | lems/parser/LEMS.py | LEMSFileParser.process_nested_tags | def process_nested_tags(self, node, tag = ''):
"""
Process child tags.
@param node: Current node being parsed.
@type node: xml.etree.Element
@raise ParseError: Raised when an unexpected nested tag is found.
"""
##print("---------Processing: %s, %s"%(node.tag,tag))
if tag == '':
t = node.ltag
else:
t = tag.lower()
for child in node.children:
self.xml_node_stack = [child] + self.xml_node_stack
ctagl = child.ltag
if ctagl in self.tag_parse_table and ctagl in self.valid_children[t]:
#print("Processing known type: %s"%ctagl)
self.tag_parse_table[ctagl](child)
else:
#print("Processing unknown type: %s"%ctagl)
self.parse_component_by_typename(child, child.tag)
self.xml_node_stack = self.xml_node_stack[1:] | python | def process_nested_tags(self, node, tag = ''):
"""
Process child tags.
@param node: Current node being parsed.
@type node: xml.etree.Element
@raise ParseError: Raised when an unexpected nested tag is found.
"""
##print("---------Processing: %s, %s"%(node.tag,tag))
if tag == '':
t = node.ltag
else:
t = tag.lower()
for child in node.children:
self.xml_node_stack = [child] + self.xml_node_stack
ctagl = child.ltag
if ctagl in self.tag_parse_table and ctagl in self.valid_children[t]:
#print("Processing known type: %s"%ctagl)
self.tag_parse_table[ctagl](child)
else:
#print("Processing unknown type: %s"%ctagl)
self.parse_component_by_typename(child, child.tag)
self.xml_node_stack = self.xml_node_stack[1:] | [
"def",
"process_nested_tags",
"(",
"self",
",",
"node",
",",
"tag",
"=",
"''",
")",
":",
"##print(\"---------Processing: %s, %s\"%(node.tag,tag))",
"if",
"tag",
"==",
"''",
":",
"t",
"=",
"node",
".",
"ltag",
"else",
":",
"t",
"=",
"tag",
".",
"lower",
"(",
")",
"for",
"child",
"in",
"node",
".",
"children",
":",
"self",
".",
"xml_node_stack",
"=",
"[",
"child",
"]",
"+",
"self",
".",
"xml_node_stack",
"ctagl",
"=",
"child",
".",
"ltag",
"if",
"ctagl",
"in",
"self",
".",
"tag_parse_table",
"and",
"ctagl",
"in",
"self",
".",
"valid_children",
"[",
"t",
"]",
":",
"#print(\"Processing known type: %s\"%ctagl)",
"self",
".",
"tag_parse_table",
"[",
"ctagl",
"]",
"(",
"child",
")",
"else",
":",
"#print(\"Processing unknown type: %s\"%ctagl)",
"self",
".",
"parse_component_by_typename",
"(",
"child",
",",
"child",
".",
"tag",
")",
"self",
".",
"xml_node_stack",
"=",
"self",
".",
"xml_node_stack",
"[",
"1",
":",
"]"
] | Process child tags.
@param node: Current node being parsed.
@type node: xml.etree.Element
@raise ParseError: Raised when an unexpected nested tag is found. | [
"Process",
"child",
"tags",
"."
] | 4eeb719d2f23650fe16c38626663b69b5c83818b | https://github.com/LEMS/pylems/blob/4eeb719d2f23650fe16c38626663b69b5c83818b/lems/parser/LEMS.py#L232-L260 | train |
LEMS/pylems | lems/parser/LEMS.py | LEMSFileParser.parse | def parse(self, xmltext):
"""
Parse a string containing LEMS XML text.
@param xmltext: String containing LEMS XML formatted text.
@type xmltext: str
"""
xml = LEMSXMLNode(xe.XML(xmltext))
if xml.ltag != 'lems' and xml.ltag != 'neuroml':
raise ParseError('<Lems> expected as root element (or even <neuroml>), found: {0}'.format(xml.ltag))
'''
if xml.ltag == 'lems':
if 'description' in xml.lattrib:
self.description = xml.lattrib['description']
'''
self.process_nested_tags(xml) | python | def parse(self, xmltext):
"""
Parse a string containing LEMS XML text.
@param xmltext: String containing LEMS XML formatted text.
@type xmltext: str
"""
xml = LEMSXMLNode(xe.XML(xmltext))
if xml.ltag != 'lems' and xml.ltag != 'neuroml':
raise ParseError('<Lems> expected as root element (or even <neuroml>), found: {0}'.format(xml.ltag))
'''
if xml.ltag == 'lems':
if 'description' in xml.lattrib:
self.description = xml.lattrib['description']
'''
self.process_nested_tags(xml) | [
"def",
"parse",
"(",
"self",
",",
"xmltext",
")",
":",
"xml",
"=",
"LEMSXMLNode",
"(",
"xe",
".",
"XML",
"(",
"xmltext",
")",
")",
"if",
"xml",
".",
"ltag",
"!=",
"'lems'",
"and",
"xml",
".",
"ltag",
"!=",
"'neuroml'",
":",
"raise",
"ParseError",
"(",
"'<Lems> expected as root element (or even <neuroml>), found: {0}'",
".",
"format",
"(",
"xml",
".",
"ltag",
")",
")",
"'''\n if xml.ltag == 'lems':\n if 'description' in xml.lattrib:\n self.description = xml.lattrib['description']\n '''",
"self",
".",
"process_nested_tags",
"(",
"xml",
")"
] | Parse a string containing LEMS XML text.
@param xmltext: String containing LEMS XML formatted text.
@type xmltext: str | [
"Parse",
"a",
"string",
"containing",
"LEMS",
"XML",
"text",
"."
] | 4eeb719d2f23650fe16c38626663b69b5c83818b | https://github.com/LEMS/pylems/blob/4eeb719d2f23650fe16c38626663b69b5c83818b/lems/parser/LEMS.py#L262-L280 | train |
LEMS/pylems | lems/parser/LEMS.py | LEMSFileParser.raise_error | def raise_error(self, message, *params, **key_params):
"""
Raise a parse error.
"""
s = 'Parser error in '
self.xml_node_stack.reverse()
if len(self.xml_node_stack) > 1:
node = self.xml_node_stack[0]
s += '<{0}'.format(node.tag)
if 'name' in node.lattrib:
s += ' name=\"{0}\"'.format(node.lattrib['name'])
if 'id' in node.lattrib:
s += ' id=\"{0}\"'.format(node.lattrib['id'])
s += '>'
for node in self.xml_node_stack[1:]:
s += '.<{0}'.format(node.tag)
if 'name' in node.lattrib:
s += ' name=\"{0}\"'.format(node.lattrib['name'])
if 'id' in node.lattrib:
s += ' id=\"{0}\"'.format(node.lattrib['id'])
s += '>'
s += ':\n ' + message
raise ParseError(s, *params, **key_params)
self.xml_node_stack.reverse() | python | def raise_error(self, message, *params, **key_params):
"""
Raise a parse error.
"""
s = 'Parser error in '
self.xml_node_stack.reverse()
if len(self.xml_node_stack) > 1:
node = self.xml_node_stack[0]
s += '<{0}'.format(node.tag)
if 'name' in node.lattrib:
s += ' name=\"{0}\"'.format(node.lattrib['name'])
if 'id' in node.lattrib:
s += ' id=\"{0}\"'.format(node.lattrib['id'])
s += '>'
for node in self.xml_node_stack[1:]:
s += '.<{0}'.format(node.tag)
if 'name' in node.lattrib:
s += ' name=\"{0}\"'.format(node.lattrib['name'])
if 'id' in node.lattrib:
s += ' id=\"{0}\"'.format(node.lattrib['id'])
s += '>'
s += ':\n ' + message
raise ParseError(s, *params, **key_params)
self.xml_node_stack.reverse() | [
"def",
"raise_error",
"(",
"self",
",",
"message",
",",
"*",
"params",
",",
"*",
"*",
"key_params",
")",
":",
"s",
"=",
"'Parser error in '",
"self",
".",
"xml_node_stack",
".",
"reverse",
"(",
")",
"if",
"len",
"(",
"self",
".",
"xml_node_stack",
")",
">",
"1",
":",
"node",
"=",
"self",
".",
"xml_node_stack",
"[",
"0",
"]",
"s",
"+=",
"'<{0}'",
".",
"format",
"(",
"node",
".",
"tag",
")",
"if",
"'name'",
"in",
"node",
".",
"lattrib",
":",
"s",
"+=",
"' name=\\\"{0}\\\"'",
".",
"format",
"(",
"node",
".",
"lattrib",
"[",
"'name'",
"]",
")",
"if",
"'id'",
"in",
"node",
".",
"lattrib",
":",
"s",
"+=",
"' id=\\\"{0}\\\"'",
".",
"format",
"(",
"node",
".",
"lattrib",
"[",
"'id'",
"]",
")",
"s",
"+=",
"'>'",
"for",
"node",
"in",
"self",
".",
"xml_node_stack",
"[",
"1",
":",
"]",
":",
"s",
"+=",
"'.<{0}'",
".",
"format",
"(",
"node",
".",
"tag",
")",
"if",
"'name'",
"in",
"node",
".",
"lattrib",
":",
"s",
"+=",
"' name=\\\"{0}\\\"'",
".",
"format",
"(",
"node",
".",
"lattrib",
"[",
"'name'",
"]",
")",
"if",
"'id'",
"in",
"node",
".",
"lattrib",
":",
"s",
"+=",
"' id=\\\"{0}\\\"'",
".",
"format",
"(",
"node",
".",
"lattrib",
"[",
"'id'",
"]",
")",
"s",
"+=",
"'>'",
"s",
"+=",
"':\\n '",
"+",
"message",
"raise",
"ParseError",
"(",
"s",
",",
"*",
"params",
",",
"*",
"*",
"key_params",
")",
"self",
".",
"xml_node_stack",
".",
"reverse",
"(",
")"
] | Raise a parse error. | [
"Raise",
"a",
"parse",
"error",
"."
] | 4eeb719d2f23650fe16c38626663b69b5c83818b | https://github.com/LEMS/pylems/blob/4eeb719d2f23650fe16c38626663b69b5c83818b/lems/parser/LEMS.py#L283-L312 | train |
LEMS/pylems | lems/parser/LEMS.py | LEMSFileParser.parse_component_by_typename | def parse_component_by_typename(self, node, type_):
"""
Parses components defined directly by component name.
@param node: Node containing the <Component> element
@type node: xml.etree.Element
@param type_: Type of this component.
@type type_: string
@raise ParseError: Raised when the component does not have an id.
"""
#print('Parsing component {0} by typename {1}'.format(node, type_))
if 'id' in node.lattrib:
id_ = node.lattrib['id']
else:
#self.raise_error('Component must have an id')
id_ = node.tag #make_id()
if 'type' in node.lattrib:
type_ = node.lattrib['type']
else:
type_ = node.tag
component = Component(id_, type_)
if self.current_component:
component.set_parent_id(self.current_component.id)
self.current_component.add_child(component)
else:
self.model.add_component(component)
for key in node.attrib:
if key.lower() not in ['id', 'type']:
component.set_parameter(key, node.attrib[key])
old_component = self.current_component
self.current_component = component
self.process_nested_tags(node, 'component')
self.current_component = old_component | python | def parse_component_by_typename(self, node, type_):
"""
Parses components defined directly by component name.
@param node: Node containing the <Component> element
@type node: xml.etree.Element
@param type_: Type of this component.
@type type_: string
@raise ParseError: Raised when the component does not have an id.
"""
#print('Parsing component {0} by typename {1}'.format(node, type_))
if 'id' in node.lattrib:
id_ = node.lattrib['id']
else:
#self.raise_error('Component must have an id')
id_ = node.tag #make_id()
if 'type' in node.lattrib:
type_ = node.lattrib['type']
else:
type_ = node.tag
component = Component(id_, type_)
if self.current_component:
component.set_parent_id(self.current_component.id)
self.current_component.add_child(component)
else:
self.model.add_component(component)
for key in node.attrib:
if key.lower() not in ['id', 'type']:
component.set_parameter(key, node.attrib[key])
old_component = self.current_component
self.current_component = component
self.process_nested_tags(node, 'component')
self.current_component = old_component | [
"def",
"parse_component_by_typename",
"(",
"self",
",",
"node",
",",
"type_",
")",
":",
"#print('Parsing component {0} by typename {1}'.format(node, type_))",
"if",
"'id'",
"in",
"node",
".",
"lattrib",
":",
"id_",
"=",
"node",
".",
"lattrib",
"[",
"'id'",
"]",
"else",
":",
"#self.raise_error('Component must have an id')",
"id_",
"=",
"node",
".",
"tag",
"#make_id()",
"if",
"'type'",
"in",
"node",
".",
"lattrib",
":",
"type_",
"=",
"node",
".",
"lattrib",
"[",
"'type'",
"]",
"else",
":",
"type_",
"=",
"node",
".",
"tag",
"component",
"=",
"Component",
"(",
"id_",
",",
"type_",
")",
"if",
"self",
".",
"current_component",
":",
"component",
".",
"set_parent_id",
"(",
"self",
".",
"current_component",
".",
"id",
")",
"self",
".",
"current_component",
".",
"add_child",
"(",
"component",
")",
"else",
":",
"self",
".",
"model",
".",
"add_component",
"(",
"component",
")",
"for",
"key",
"in",
"node",
".",
"attrib",
":",
"if",
"key",
".",
"lower",
"(",
")",
"not",
"in",
"[",
"'id'",
",",
"'type'",
"]",
":",
"component",
".",
"set_parameter",
"(",
"key",
",",
"node",
".",
"attrib",
"[",
"key",
"]",
")",
"old_component",
"=",
"self",
".",
"current_component",
"self",
".",
"current_component",
"=",
"component",
"self",
".",
"process_nested_tags",
"(",
"node",
",",
"'component'",
")",
"self",
".",
"current_component",
"=",
"old_component"
] | Parses components defined directly by component name.
@param node: Node containing the <Component> element
@type node: xml.etree.Element
@param type_: Type of this component.
@type type_: string
@raise ParseError: Raised when the component does not have an id. | [
"Parses",
"components",
"defined",
"directly",
"by",
"component",
"name",
"."
] | 4eeb719d2f23650fe16c38626663b69b5c83818b | https://github.com/LEMS/pylems/blob/4eeb719d2f23650fe16c38626663b69b5c83818b/lems/parser/LEMS.py#L446-L486 | train |
glormph/msstitch | src/app/readers/xml.py | generate_tags_multiple_files | def generate_tags_multiple_files(input_files, tag, ignore_tags, ns=None):
"""
Calls xmltag generator for multiple files.
"""
return itertools.chain.from_iterable([generate_xmltags(
fn, tag, ignore_tags, ns) for fn in input_files]) | python | def generate_tags_multiple_files(input_files, tag, ignore_tags, ns=None):
"""
Calls xmltag generator for multiple files.
"""
return itertools.chain.from_iterable([generate_xmltags(
fn, tag, ignore_tags, ns) for fn in input_files]) | [
"def",
"generate_tags_multiple_files",
"(",
"input_files",
",",
"tag",
",",
"ignore_tags",
",",
"ns",
"=",
"None",
")",
":",
"return",
"itertools",
".",
"chain",
".",
"from_iterable",
"(",
"[",
"generate_xmltags",
"(",
"fn",
",",
"tag",
",",
"ignore_tags",
",",
"ns",
")",
"for",
"fn",
"in",
"input_files",
"]",
")"
] | Calls xmltag generator for multiple files. | [
"Calls",
"xmltag",
"generator",
"for",
"multiple",
"files",
"."
] | ded7e5cbd813d7797dc9d42805778266e59ff042 | https://github.com/glormph/msstitch/blob/ded7e5cbd813d7797dc9d42805778266e59ff042/src/app/readers/xml.py#L36-L41 | train |
glormph/msstitch | src/app/readers/xml.py | generate_tags_multiple_files_strings | def generate_tags_multiple_files_strings(input_files, ns, tag, ignore_tags):
"""
Creates stringified xml output of elements with certain tag.
"""
for el in generate_tags_multiple_files(input_files, tag, ignore_tags, ns):
yield formatting.string_and_clear(el, ns) | python | def generate_tags_multiple_files_strings(input_files, ns, tag, ignore_tags):
"""
Creates stringified xml output of elements with certain tag.
"""
for el in generate_tags_multiple_files(input_files, tag, ignore_tags, ns):
yield formatting.string_and_clear(el, ns) | [
"def",
"generate_tags_multiple_files_strings",
"(",
"input_files",
",",
"ns",
",",
"tag",
",",
"ignore_tags",
")",
":",
"for",
"el",
"in",
"generate_tags_multiple_files",
"(",
"input_files",
",",
"tag",
",",
"ignore_tags",
",",
"ns",
")",
":",
"yield",
"formatting",
".",
"string_and_clear",
"(",
"el",
",",
"ns",
")"
] | Creates stringified xml output of elements with certain tag. | [
"Creates",
"stringified",
"xml",
"output",
"of",
"elements",
"with",
"certain",
"tag",
"."
] | ded7e5cbd813d7797dc9d42805778266e59ff042 | https://github.com/glormph/msstitch/blob/ded7e5cbd813d7797dc9d42805778266e59ff042/src/app/readers/xml.py#L44-L49 | train |
glormph/msstitch | src/app/readers/xml.py | generate_xmltags | def generate_xmltags(fn, returntag, ignore_tags, ns=None):
"""
Base generator for percolator xml psm, peptide, protein output,
as well as for mzML, mzIdentML.
ignore_tags are the ones that are cleared when met by parser.
"""
xmlns = create_namespace(ns)
ns_ignore = ['{0}{1}'.format(xmlns, x) for x in ignore_tags]
for ac, el in etree.iterparse(fn):
if el.tag == '{0}{1}'.format(xmlns, returntag):
yield el
elif el.tag in ns_ignore:
formatting.clear_el(el) | python | def generate_xmltags(fn, returntag, ignore_tags, ns=None):
"""
Base generator for percolator xml psm, peptide, protein output,
as well as for mzML, mzIdentML.
ignore_tags are the ones that are cleared when met by parser.
"""
xmlns = create_namespace(ns)
ns_ignore = ['{0}{1}'.format(xmlns, x) for x in ignore_tags]
for ac, el in etree.iterparse(fn):
if el.tag == '{0}{1}'.format(xmlns, returntag):
yield el
elif el.tag in ns_ignore:
formatting.clear_el(el) | [
"def",
"generate_xmltags",
"(",
"fn",
",",
"returntag",
",",
"ignore_tags",
",",
"ns",
"=",
"None",
")",
":",
"xmlns",
"=",
"create_namespace",
"(",
"ns",
")",
"ns_ignore",
"=",
"[",
"'{0}{1}'",
".",
"format",
"(",
"xmlns",
",",
"x",
")",
"for",
"x",
"in",
"ignore_tags",
"]",
"for",
"ac",
",",
"el",
"in",
"etree",
".",
"iterparse",
"(",
"fn",
")",
":",
"if",
"el",
".",
"tag",
"==",
"'{0}{1}'",
".",
"format",
"(",
"xmlns",
",",
"returntag",
")",
":",
"yield",
"el",
"elif",
"el",
".",
"tag",
"in",
"ns_ignore",
":",
"formatting",
".",
"clear_el",
"(",
"el",
")"
] | Base generator for percolator xml psm, peptide, protein output,
as well as for mzML, mzIdentML.
ignore_tags are the ones that are cleared when met by parser. | [
"Base",
"generator",
"for",
"percolator",
"xml",
"psm",
"peptide",
"protein",
"output",
"as",
"well",
"as",
"for",
"mzML",
"mzIdentML",
".",
"ignore_tags",
"are",
"the",
"ones",
"that",
"are",
"cleared",
"when",
"met",
"by",
"parser",
"."
] | ded7e5cbd813d7797dc9d42805778266e59ff042 | https://github.com/glormph/msstitch/blob/ded7e5cbd813d7797dc9d42805778266e59ff042/src/app/readers/xml.py#L52-L64 | train |
LEMS/pylems | lems/model/model.py | Model.add_component_type | def add_component_type(self, component_type):
"""
Adds a component type to the model.
@param component_type: Component type to be added.
@type component_type: lems.model.fundamental.ComponentType
"""
name = component_type.name
# To handle colons in names in LEMS
if ':' in name:
name = name.replace(':', '_')
component_type.name = name
self.component_types[name] = component_type | python | def add_component_type(self, component_type):
"""
Adds a component type to the model.
@param component_type: Component type to be added.
@type component_type: lems.model.fundamental.ComponentType
"""
name = component_type.name
# To handle colons in names in LEMS
if ':' in name:
name = name.replace(':', '_')
component_type.name = name
self.component_types[name] = component_type | [
"def",
"add_component_type",
"(",
"self",
",",
"component_type",
")",
":",
"name",
"=",
"component_type",
".",
"name",
"# To handle colons in names in LEMS",
"if",
"':'",
"in",
"name",
":",
"name",
"=",
"name",
".",
"replace",
"(",
"':'",
",",
"'_'",
")",
"component_type",
".",
"name",
"=",
"name",
"self",
".",
"component_types",
"[",
"name",
"]",
"=",
"component_type"
] | Adds a component type to the model.
@param component_type: Component type to be added.
@type component_type: lems.model.fundamental.ComponentType | [
"Adds",
"a",
"component",
"type",
"to",
"the",
"model",
"."
] | 4eeb719d2f23650fe16c38626663b69b5c83818b | https://github.com/LEMS/pylems/blob/4eeb719d2f23650fe16c38626663b69b5c83818b/lems/model/model.py#L140-L154 | train |
LEMS/pylems | lems/model/model.py | Model.add | def add(self, child):
"""
Adds a typed child object to the model.
@param child: Child object to be added.
"""
if isinstance(child, Include):
self.add_include(child)
elif isinstance(child, Dimension):
self.add_dimension(child)
elif isinstance(child, Unit):
self.add_unit(child)
elif isinstance(child, ComponentType):
self.add_component_type(child)
elif isinstance(child, Component):
self.add_component(child)
elif isinstance(child, FatComponent):
self.add_fat_component(child)
elif isinstance(child, Constant):
self.add_constant(child)
else:
raise ModelError('Unsupported child element') | python | def add(self, child):
"""
Adds a typed child object to the model.
@param child: Child object to be added.
"""
if isinstance(child, Include):
self.add_include(child)
elif isinstance(child, Dimension):
self.add_dimension(child)
elif isinstance(child, Unit):
self.add_unit(child)
elif isinstance(child, ComponentType):
self.add_component_type(child)
elif isinstance(child, Component):
self.add_component(child)
elif isinstance(child, FatComponent):
self.add_fat_component(child)
elif isinstance(child, Constant):
self.add_constant(child)
else:
raise ModelError('Unsupported child element') | [
"def",
"add",
"(",
"self",
",",
"child",
")",
":",
"if",
"isinstance",
"(",
"child",
",",
"Include",
")",
":",
"self",
".",
"add_include",
"(",
"child",
")",
"elif",
"isinstance",
"(",
"child",
",",
"Dimension",
")",
":",
"self",
".",
"add_dimension",
"(",
"child",
")",
"elif",
"isinstance",
"(",
"child",
",",
"Unit",
")",
":",
"self",
".",
"add_unit",
"(",
"child",
")",
"elif",
"isinstance",
"(",
"child",
",",
"ComponentType",
")",
":",
"self",
".",
"add_component_type",
"(",
"child",
")",
"elif",
"isinstance",
"(",
"child",
",",
"Component",
")",
":",
"self",
".",
"add_component",
"(",
"child",
")",
"elif",
"isinstance",
"(",
"child",
",",
"FatComponent",
")",
":",
"self",
".",
"add_fat_component",
"(",
"child",
")",
"elif",
"isinstance",
"(",
"child",
",",
"Constant",
")",
":",
"self",
".",
"add_constant",
"(",
"child",
")",
"else",
":",
"raise",
"ModelError",
"(",
"'Unsupported child element'",
")"
] | Adds a typed child object to the model.
@param child: Child object to be added. | [
"Adds",
"a",
"typed",
"child",
"object",
"to",
"the",
"model",
"."
] | 4eeb719d2f23650fe16c38626663b69b5c83818b | https://github.com/LEMS/pylems/blob/4eeb719d2f23650fe16c38626663b69b5c83818b/lems/model/model.py#L186-L208 | train |
LEMS/pylems | lems/model/model.py | Model.include_file | def include_file(self, path, include_dirs = []):
"""
Includes a file into the current model.
@param path: Path to the file to be included.
@type path: str
@param include_dirs: Optional alternate include search path.
@type include_dirs: list(str)
"""
if self.include_includes:
if self.debug: print("------------------ Including a file: %s"%path)
inc_dirs = include_dirs if include_dirs else self.include_dirs
parser = LEMSFileParser(self, inc_dirs, self.include_includes)
if os.access(path, os.F_OK):
if not path in self.included_files:
parser.parse(open(path).read())
self.included_files.append(path)
return
else:
if self.debug: print("Already included: %s"%path)
return
else:
for inc_dir in inc_dirs:
new_path = (inc_dir + '/' + path)
if os.access(new_path, os.F_OK):
if not new_path in self.included_files:
parser.parse(open(new_path).read())
self.included_files.append(new_path)
return
else:
if self.debug: print("Already included: %s"%path)
return
msg = 'Unable to open ' + path
if self.fail_on_missing_includes:
raise Exception(msg)
elif self.debug:
print(msg) | python | def include_file(self, path, include_dirs = []):
"""
Includes a file into the current model.
@param path: Path to the file to be included.
@type path: str
@param include_dirs: Optional alternate include search path.
@type include_dirs: list(str)
"""
if self.include_includes:
if self.debug: print("------------------ Including a file: %s"%path)
inc_dirs = include_dirs if include_dirs else self.include_dirs
parser = LEMSFileParser(self, inc_dirs, self.include_includes)
if os.access(path, os.F_OK):
if not path in self.included_files:
parser.parse(open(path).read())
self.included_files.append(path)
return
else:
if self.debug: print("Already included: %s"%path)
return
else:
for inc_dir in inc_dirs:
new_path = (inc_dir + '/' + path)
if os.access(new_path, os.F_OK):
if not new_path in self.included_files:
parser.parse(open(new_path).read())
self.included_files.append(new_path)
return
else:
if self.debug: print("Already included: %s"%path)
return
msg = 'Unable to open ' + path
if self.fail_on_missing_includes:
raise Exception(msg)
elif self.debug:
print(msg) | [
"def",
"include_file",
"(",
"self",
",",
"path",
",",
"include_dirs",
"=",
"[",
"]",
")",
":",
"if",
"self",
".",
"include_includes",
":",
"if",
"self",
".",
"debug",
":",
"print",
"(",
"\"------------------ Including a file: %s\"",
"%",
"path",
")",
"inc_dirs",
"=",
"include_dirs",
"if",
"include_dirs",
"else",
"self",
".",
"include_dirs",
"parser",
"=",
"LEMSFileParser",
"(",
"self",
",",
"inc_dirs",
",",
"self",
".",
"include_includes",
")",
"if",
"os",
".",
"access",
"(",
"path",
",",
"os",
".",
"F_OK",
")",
":",
"if",
"not",
"path",
"in",
"self",
".",
"included_files",
":",
"parser",
".",
"parse",
"(",
"open",
"(",
"path",
")",
".",
"read",
"(",
")",
")",
"self",
".",
"included_files",
".",
"append",
"(",
"path",
")",
"return",
"else",
":",
"if",
"self",
".",
"debug",
":",
"print",
"(",
"\"Already included: %s\"",
"%",
"path",
")",
"return",
"else",
":",
"for",
"inc_dir",
"in",
"inc_dirs",
":",
"new_path",
"=",
"(",
"inc_dir",
"+",
"'/'",
"+",
"path",
")",
"if",
"os",
".",
"access",
"(",
"new_path",
",",
"os",
".",
"F_OK",
")",
":",
"if",
"not",
"new_path",
"in",
"self",
".",
"included_files",
":",
"parser",
".",
"parse",
"(",
"open",
"(",
"new_path",
")",
".",
"read",
"(",
")",
")",
"self",
".",
"included_files",
".",
"append",
"(",
"new_path",
")",
"return",
"else",
":",
"if",
"self",
".",
"debug",
":",
"print",
"(",
"\"Already included: %s\"",
"%",
"path",
")",
"return",
"msg",
"=",
"'Unable to open '",
"+",
"path",
"if",
"self",
".",
"fail_on_missing_includes",
":",
"raise",
"Exception",
"(",
"msg",
")",
"elif",
"self",
".",
"debug",
":",
"print",
"(",
"msg",
")"
] | Includes a file into the current model.
@param path: Path to the file to be included.
@type path: str
@param include_dirs: Optional alternate include search path.
@type include_dirs: list(str) | [
"Includes",
"a",
"file",
"into",
"the",
"current",
"model",
"."
] | 4eeb719d2f23650fe16c38626663b69b5c83818b | https://github.com/LEMS/pylems/blob/4eeb719d2f23650fe16c38626663b69b5c83818b/lems/model/model.py#L220-L258 | train |
LEMS/pylems | lems/model/model.py | Model.import_from_file | def import_from_file(self, filepath):
"""
Import a model from a file.
@param filepath: File to be imported.
@type filepath: str
"""
inc_dirs = self.include_directories[:]
inc_dirs.append(dirname(filepath))
parser = LEMSFileParser(self, inc_dirs, self.include_includes)
with open(filepath) as f:
parser.parse(f.read()) | python | def import_from_file(self, filepath):
"""
Import a model from a file.
@param filepath: File to be imported.
@type filepath: str
"""
inc_dirs = self.include_directories[:]
inc_dirs.append(dirname(filepath))
parser = LEMSFileParser(self, inc_dirs, self.include_includes)
with open(filepath) as f:
parser.parse(f.read()) | [
"def",
"import_from_file",
"(",
"self",
",",
"filepath",
")",
":",
"inc_dirs",
"=",
"self",
".",
"include_directories",
"[",
":",
"]",
"inc_dirs",
".",
"append",
"(",
"dirname",
"(",
"filepath",
")",
")",
"parser",
"=",
"LEMSFileParser",
"(",
"self",
",",
"inc_dirs",
",",
"self",
".",
"include_includes",
")",
"with",
"open",
"(",
"filepath",
")",
"as",
"f",
":",
"parser",
".",
"parse",
"(",
"f",
".",
"read",
"(",
")",
")"
] | Import a model from a file.
@param filepath: File to be imported.
@type filepath: str | [
"Import",
"a",
"model",
"from",
"a",
"file",
"."
] | 4eeb719d2f23650fe16c38626663b69b5c83818b | https://github.com/LEMS/pylems/blob/4eeb719d2f23650fe16c38626663b69b5c83818b/lems/model/model.py#L260-L273 | train |
LEMS/pylems | lems/model/model.py | Model.export_to_dom | def export_to_dom(self):
"""
Exports this model to a DOM.
"""
namespaces = 'xmlns="http://www.neuroml.org/lems/%s" ' + \
'xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" ' + \
'xsi:schemaLocation="http://www.neuroml.org/lems/%s %s"'
namespaces = namespaces%(self.target_lems_version,self.target_lems_version,self.schema_location)
xmlstr = '<Lems %s>'%namespaces
for include in self.includes:
xmlstr += include.toxml()
for target in self.targets:
xmlstr += '<Target component="{0}"/>'.format(target)
for dimension in self.dimensions:
xmlstr += dimension.toxml()
for unit in self.units:
xmlstr += unit.toxml()
for constant in self.constants:
xmlstr += constant.toxml()
for component_type in self.component_types:
xmlstr += component_type.toxml()
for component in self.components:
xmlstr += component.toxml()
xmlstr += '</Lems>'
xmldom = minidom.parseString(xmlstr)
return xmldom | python | def export_to_dom(self):
"""
Exports this model to a DOM.
"""
namespaces = 'xmlns="http://www.neuroml.org/lems/%s" ' + \
'xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" ' + \
'xsi:schemaLocation="http://www.neuroml.org/lems/%s %s"'
namespaces = namespaces%(self.target_lems_version,self.target_lems_version,self.schema_location)
xmlstr = '<Lems %s>'%namespaces
for include in self.includes:
xmlstr += include.toxml()
for target in self.targets:
xmlstr += '<Target component="{0}"/>'.format(target)
for dimension in self.dimensions:
xmlstr += dimension.toxml()
for unit in self.units:
xmlstr += unit.toxml()
for constant in self.constants:
xmlstr += constant.toxml()
for component_type in self.component_types:
xmlstr += component_type.toxml()
for component in self.components:
xmlstr += component.toxml()
xmlstr += '</Lems>'
xmldom = minidom.parseString(xmlstr)
return xmldom | [
"def",
"export_to_dom",
"(",
"self",
")",
":",
"namespaces",
"=",
"'xmlns=\"http://www.neuroml.org/lems/%s\" '",
"+",
"'xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" '",
"+",
"'xsi:schemaLocation=\"http://www.neuroml.org/lems/%s %s\"'",
"namespaces",
"=",
"namespaces",
"%",
"(",
"self",
".",
"target_lems_version",
",",
"self",
".",
"target_lems_version",
",",
"self",
".",
"schema_location",
")",
"xmlstr",
"=",
"'<Lems %s>'",
"%",
"namespaces",
"for",
"include",
"in",
"self",
".",
"includes",
":",
"xmlstr",
"+=",
"include",
".",
"toxml",
"(",
")",
"for",
"target",
"in",
"self",
".",
"targets",
":",
"xmlstr",
"+=",
"'<Target component=\"{0}\"/>'",
".",
"format",
"(",
"target",
")",
"for",
"dimension",
"in",
"self",
".",
"dimensions",
":",
"xmlstr",
"+=",
"dimension",
".",
"toxml",
"(",
")",
"for",
"unit",
"in",
"self",
".",
"units",
":",
"xmlstr",
"+=",
"unit",
".",
"toxml",
"(",
")",
"for",
"constant",
"in",
"self",
".",
"constants",
":",
"xmlstr",
"+=",
"constant",
".",
"toxml",
"(",
")",
"for",
"component_type",
"in",
"self",
".",
"component_types",
":",
"xmlstr",
"+=",
"component_type",
".",
"toxml",
"(",
")",
"for",
"component",
"in",
"self",
".",
"components",
":",
"xmlstr",
"+=",
"component",
".",
"toxml",
"(",
")",
"xmlstr",
"+=",
"'</Lems>'",
"xmldom",
"=",
"minidom",
".",
"parseString",
"(",
"xmlstr",
")",
"return",
"xmldom"
] | Exports this model to a DOM. | [
"Exports",
"this",
"model",
"to",
"a",
"DOM",
"."
] | 4eeb719d2f23650fe16c38626663b69b5c83818b | https://github.com/LEMS/pylems/blob/4eeb719d2f23650fe16c38626663b69b5c83818b/lems/model/model.py#L275-L311 | train |
LEMS/pylems | lems/model/model.py | Model.export_to_file | def export_to_file(self, filepath, level_prefix = ' '):
"""
Exports this model to a file.
@param filepath: File to be exported to.
@type filepath: str
"""
xmldom = self.export_to_dom()
xmlstr = xmldom.toprettyxml(level_prefix, '\n',)
f = open(filepath, 'w')
f.write(xmlstr)
f.close() | python | def export_to_file(self, filepath, level_prefix = ' '):
"""
Exports this model to a file.
@param filepath: File to be exported to.
@type filepath: str
"""
xmldom = self.export_to_dom()
xmlstr = xmldom.toprettyxml(level_prefix, '\n',)
f = open(filepath, 'w')
f.write(xmlstr)
f.close() | [
"def",
"export_to_file",
"(",
"self",
",",
"filepath",
",",
"level_prefix",
"=",
"' '",
")",
":",
"xmldom",
"=",
"self",
".",
"export_to_dom",
"(",
")",
"xmlstr",
"=",
"xmldom",
".",
"toprettyxml",
"(",
"level_prefix",
",",
"'\\n'",
",",
")",
"f",
"=",
"open",
"(",
"filepath",
",",
"'w'",
")",
"f",
".",
"write",
"(",
"xmlstr",
")",
"f",
".",
"close",
"(",
")"
] | Exports this model to a file.
@param filepath: File to be exported to.
@type filepath: str | [
"Exports",
"this",
"model",
"to",
"a",
"file",
"."
] | 4eeb719d2f23650fe16c38626663b69b5c83818b | https://github.com/LEMS/pylems/blob/4eeb719d2f23650fe16c38626663b69b5c83818b/lems/model/model.py#L313-L326 | train |
LEMS/pylems | lems/model/model.py | Model.resolve | def resolve(self):
"""
Resolves references in this model.
"""
model = self.copy()
for ct in model.component_types:
model.resolve_component_type(ct)
for c in model.components:
if c.id not in model.fat_components:
model.add(model.fatten_component(c))
for c in ct.constants:
c2 = c.copy()
c2.numeric_value = model.get_numeric_value(c2.value, c2.dimension)
model.add(c2)
return model | python | def resolve(self):
"""
Resolves references in this model.
"""
model = self.copy()
for ct in model.component_types:
model.resolve_component_type(ct)
for c in model.components:
if c.id not in model.fat_components:
model.add(model.fatten_component(c))
for c in ct.constants:
c2 = c.copy()
c2.numeric_value = model.get_numeric_value(c2.value, c2.dimension)
model.add(c2)
return model | [
"def",
"resolve",
"(",
"self",
")",
":",
"model",
"=",
"self",
".",
"copy",
"(",
")",
"for",
"ct",
"in",
"model",
".",
"component_types",
":",
"model",
".",
"resolve_component_type",
"(",
"ct",
")",
"for",
"c",
"in",
"model",
".",
"components",
":",
"if",
"c",
".",
"id",
"not",
"in",
"model",
".",
"fat_components",
":",
"model",
".",
"add",
"(",
"model",
".",
"fatten_component",
"(",
"c",
")",
")",
"for",
"c",
"in",
"ct",
".",
"constants",
":",
"c2",
"=",
"c",
".",
"copy",
"(",
")",
"c2",
".",
"numeric_value",
"=",
"model",
".",
"get_numeric_value",
"(",
"c2",
".",
"value",
",",
"c2",
".",
"dimension",
")",
"model",
".",
"add",
"(",
"c2",
")",
"return",
"model"
] | Resolves references in this model. | [
"Resolves",
"references",
"in",
"this",
"model",
"."
] | 4eeb719d2f23650fe16c38626663b69b5c83818b | https://github.com/LEMS/pylems/blob/4eeb719d2f23650fe16c38626663b69b5c83818b/lems/model/model.py#L328-L347 | train |
LEMS/pylems | lems/model/model.py | Model.resolve_component_type | def resolve_component_type(self, component_type):
"""
Resolves references in the specified component type.
@param component_type: Component type to be resolved.
@type component_type: lems.model.component.ComponentType
"""
# Resolve component type from base types if present.
if component_type.extends:
try:
base_ct = self.component_types[component_type.extends]
except:
raise ModelError("Component type '{0}' trying to extend unknown component type '{1}'",
component_type.name, component_type.extends)
self.resolve_component_type(base_ct)
self.merge_component_types(component_type, base_ct)
component_type.types = set.union(component_type.types, base_ct.types)
component_type.extends = None | python | def resolve_component_type(self, component_type):
"""
Resolves references in the specified component type.
@param component_type: Component type to be resolved.
@type component_type: lems.model.component.ComponentType
"""
# Resolve component type from base types if present.
if component_type.extends:
try:
base_ct = self.component_types[component_type.extends]
except:
raise ModelError("Component type '{0}' trying to extend unknown component type '{1}'",
component_type.name, component_type.extends)
self.resolve_component_type(base_ct)
self.merge_component_types(component_type, base_ct)
component_type.types = set.union(component_type.types, base_ct.types)
component_type.extends = None | [
"def",
"resolve_component_type",
"(",
"self",
",",
"component_type",
")",
":",
"# Resolve component type from base types if present.",
"if",
"component_type",
".",
"extends",
":",
"try",
":",
"base_ct",
"=",
"self",
".",
"component_types",
"[",
"component_type",
".",
"extends",
"]",
"except",
":",
"raise",
"ModelError",
"(",
"\"Component type '{0}' trying to extend unknown component type '{1}'\"",
",",
"component_type",
".",
"name",
",",
"component_type",
".",
"extends",
")",
"self",
".",
"resolve_component_type",
"(",
"base_ct",
")",
"self",
".",
"merge_component_types",
"(",
"component_type",
",",
"base_ct",
")",
"component_type",
".",
"types",
"=",
"set",
".",
"union",
"(",
"component_type",
".",
"types",
",",
"base_ct",
".",
"types",
")",
"component_type",
".",
"extends",
"=",
"None"
] | Resolves references in the specified component type.
@param component_type: Component type to be resolved.
@type component_type: lems.model.component.ComponentType | [
"Resolves",
"references",
"in",
"the",
"specified",
"component",
"type",
"."
] | 4eeb719d2f23650fe16c38626663b69b5c83818b | https://github.com/LEMS/pylems/blob/4eeb719d2f23650fe16c38626663b69b5c83818b/lems/model/model.py#L349-L368 | train |
LEMS/pylems | lems/model/model.py | Model.merge_component_types | def merge_component_types(self, ct, base_ct):
"""
Merge various maps in the given component type from a base
component type.
@param ct: Component type to be resolved.
@type ct: lems.model.component.ComponentType
@param base_ct: Component type to be resolved.
@type base_ct: lems.model.component.ComponentType
"""
#merge_maps(ct.parameters, base_ct.parameters)
for parameter in base_ct.parameters:
if parameter.name in ct.parameters:
p = ct.parameters[parameter.name]
basep = base_ct.parameters[parameter.name]
if p.fixed:
p.value = p.fixed_value
p.dimension = basep.dimension
else:
ct.parameters[parameter.name] = base_ct.parameters[parameter.name]
merge_maps(ct.properties, base_ct.properties)
merge_maps(ct.derived_parameters, base_ct.derived_parameters)
merge_maps(ct.index_parameters, base_ct.index_parameters)
merge_maps(ct.constants, base_ct.constants)
merge_maps(ct.exposures, base_ct.exposures)
merge_maps(ct.requirements, base_ct.requirements)
merge_maps(ct.component_requirements, base_ct.component_requirements)
merge_maps(ct.instance_requirements, base_ct.instance_requirements)
merge_maps(ct.children, base_ct.children)
merge_maps(ct.texts, base_ct.texts)
merge_maps(ct.links, base_ct.links)
merge_maps(ct.paths, base_ct.paths)
merge_maps(ct.event_ports, base_ct.event_ports)
merge_maps(ct.component_references, base_ct.component_references)
merge_maps(ct.attachments, base_ct.attachments)
merge_maps(ct.dynamics.state_variables, base_ct.dynamics.state_variables)
merge_maps(ct.dynamics.derived_variables, base_ct.dynamics.derived_variables)
merge_maps(ct.dynamics.conditional_derived_variables, base_ct.dynamics.conditional_derived_variables)
merge_maps(ct.dynamics.time_derivatives, base_ct.dynamics.time_derivatives)
#merge_lists(ct.dynamics.event_handlers, base_ct.dynamics.event_handlers)
merge_maps(ct.dynamics.kinetic_schemes, base_ct.dynamics.kinetic_schemes)
merge_lists(ct.structure.event_connections, base_ct.structure.event_connections)
merge_lists(ct.structure.child_instances, base_ct.structure.child_instances)
merge_lists(ct.structure.multi_instantiates, base_ct.structure.multi_instantiates)
merge_maps(ct.simulation.runs, base_ct.simulation.runs)
merge_maps(ct.simulation.records, base_ct.simulation.records)
merge_maps(ct.simulation.event_records, base_ct.simulation.event_records)
merge_maps(ct.simulation.data_displays, base_ct.simulation.data_displays)
merge_maps(ct.simulation.data_writers, base_ct.simulation.data_writers)
merge_maps(ct.simulation.event_writers, base_ct.simulation.event_writers) | python | def merge_component_types(self, ct, base_ct):
"""
Merge various maps in the given component type from a base
component type.
@param ct: Component type to be resolved.
@type ct: lems.model.component.ComponentType
@param base_ct: Component type to be resolved.
@type base_ct: lems.model.component.ComponentType
"""
#merge_maps(ct.parameters, base_ct.parameters)
for parameter in base_ct.parameters:
if parameter.name in ct.parameters:
p = ct.parameters[parameter.name]
basep = base_ct.parameters[parameter.name]
if p.fixed:
p.value = p.fixed_value
p.dimension = basep.dimension
else:
ct.parameters[parameter.name] = base_ct.parameters[parameter.name]
merge_maps(ct.properties, base_ct.properties)
merge_maps(ct.derived_parameters, base_ct.derived_parameters)
merge_maps(ct.index_parameters, base_ct.index_parameters)
merge_maps(ct.constants, base_ct.constants)
merge_maps(ct.exposures, base_ct.exposures)
merge_maps(ct.requirements, base_ct.requirements)
merge_maps(ct.component_requirements, base_ct.component_requirements)
merge_maps(ct.instance_requirements, base_ct.instance_requirements)
merge_maps(ct.children, base_ct.children)
merge_maps(ct.texts, base_ct.texts)
merge_maps(ct.links, base_ct.links)
merge_maps(ct.paths, base_ct.paths)
merge_maps(ct.event_ports, base_ct.event_ports)
merge_maps(ct.component_references, base_ct.component_references)
merge_maps(ct.attachments, base_ct.attachments)
merge_maps(ct.dynamics.state_variables, base_ct.dynamics.state_variables)
merge_maps(ct.dynamics.derived_variables, base_ct.dynamics.derived_variables)
merge_maps(ct.dynamics.conditional_derived_variables, base_ct.dynamics.conditional_derived_variables)
merge_maps(ct.dynamics.time_derivatives, base_ct.dynamics.time_derivatives)
#merge_lists(ct.dynamics.event_handlers, base_ct.dynamics.event_handlers)
merge_maps(ct.dynamics.kinetic_schemes, base_ct.dynamics.kinetic_schemes)
merge_lists(ct.structure.event_connections, base_ct.structure.event_connections)
merge_lists(ct.structure.child_instances, base_ct.structure.child_instances)
merge_lists(ct.structure.multi_instantiates, base_ct.structure.multi_instantiates)
merge_maps(ct.simulation.runs, base_ct.simulation.runs)
merge_maps(ct.simulation.records, base_ct.simulation.records)
merge_maps(ct.simulation.event_records, base_ct.simulation.event_records)
merge_maps(ct.simulation.data_displays, base_ct.simulation.data_displays)
merge_maps(ct.simulation.data_writers, base_ct.simulation.data_writers)
merge_maps(ct.simulation.event_writers, base_ct.simulation.event_writers) | [
"def",
"merge_component_types",
"(",
"self",
",",
"ct",
",",
"base_ct",
")",
":",
"#merge_maps(ct.parameters, base_ct.parameters)",
"for",
"parameter",
"in",
"base_ct",
".",
"parameters",
":",
"if",
"parameter",
".",
"name",
"in",
"ct",
".",
"parameters",
":",
"p",
"=",
"ct",
".",
"parameters",
"[",
"parameter",
".",
"name",
"]",
"basep",
"=",
"base_ct",
".",
"parameters",
"[",
"parameter",
".",
"name",
"]",
"if",
"p",
".",
"fixed",
":",
"p",
".",
"value",
"=",
"p",
".",
"fixed_value",
"p",
".",
"dimension",
"=",
"basep",
".",
"dimension",
"else",
":",
"ct",
".",
"parameters",
"[",
"parameter",
".",
"name",
"]",
"=",
"base_ct",
".",
"parameters",
"[",
"parameter",
".",
"name",
"]",
"merge_maps",
"(",
"ct",
".",
"properties",
",",
"base_ct",
".",
"properties",
")",
"merge_maps",
"(",
"ct",
".",
"derived_parameters",
",",
"base_ct",
".",
"derived_parameters",
")",
"merge_maps",
"(",
"ct",
".",
"index_parameters",
",",
"base_ct",
".",
"index_parameters",
")",
"merge_maps",
"(",
"ct",
".",
"constants",
",",
"base_ct",
".",
"constants",
")",
"merge_maps",
"(",
"ct",
".",
"exposures",
",",
"base_ct",
".",
"exposures",
")",
"merge_maps",
"(",
"ct",
".",
"requirements",
",",
"base_ct",
".",
"requirements",
")",
"merge_maps",
"(",
"ct",
".",
"component_requirements",
",",
"base_ct",
".",
"component_requirements",
")",
"merge_maps",
"(",
"ct",
".",
"instance_requirements",
",",
"base_ct",
".",
"instance_requirements",
")",
"merge_maps",
"(",
"ct",
".",
"children",
",",
"base_ct",
".",
"children",
")",
"merge_maps",
"(",
"ct",
".",
"texts",
",",
"base_ct",
".",
"texts",
")",
"merge_maps",
"(",
"ct",
".",
"links",
",",
"base_ct",
".",
"links",
")",
"merge_maps",
"(",
"ct",
".",
"paths",
",",
"base_ct",
".",
"paths",
")",
"merge_maps",
"(",
"ct",
".",
"event_ports",
",",
"base_ct",
".",
"event_ports",
")",
"merge_maps",
"(",
"ct",
".",
"component_references",
",",
"base_ct",
".",
"component_references",
")",
"merge_maps",
"(",
"ct",
".",
"attachments",
",",
"base_ct",
".",
"attachments",
")",
"merge_maps",
"(",
"ct",
".",
"dynamics",
".",
"state_variables",
",",
"base_ct",
".",
"dynamics",
".",
"state_variables",
")",
"merge_maps",
"(",
"ct",
".",
"dynamics",
".",
"derived_variables",
",",
"base_ct",
".",
"dynamics",
".",
"derived_variables",
")",
"merge_maps",
"(",
"ct",
".",
"dynamics",
".",
"conditional_derived_variables",
",",
"base_ct",
".",
"dynamics",
".",
"conditional_derived_variables",
")",
"merge_maps",
"(",
"ct",
".",
"dynamics",
".",
"time_derivatives",
",",
"base_ct",
".",
"dynamics",
".",
"time_derivatives",
")",
"#merge_lists(ct.dynamics.event_handlers, base_ct.dynamics.event_handlers)",
"merge_maps",
"(",
"ct",
".",
"dynamics",
".",
"kinetic_schemes",
",",
"base_ct",
".",
"dynamics",
".",
"kinetic_schemes",
")",
"merge_lists",
"(",
"ct",
".",
"structure",
".",
"event_connections",
",",
"base_ct",
".",
"structure",
".",
"event_connections",
")",
"merge_lists",
"(",
"ct",
".",
"structure",
".",
"child_instances",
",",
"base_ct",
".",
"structure",
".",
"child_instances",
")",
"merge_lists",
"(",
"ct",
".",
"structure",
".",
"multi_instantiates",
",",
"base_ct",
".",
"structure",
".",
"multi_instantiates",
")",
"merge_maps",
"(",
"ct",
".",
"simulation",
".",
"runs",
",",
"base_ct",
".",
"simulation",
".",
"runs",
")",
"merge_maps",
"(",
"ct",
".",
"simulation",
".",
"records",
",",
"base_ct",
".",
"simulation",
".",
"records",
")",
"merge_maps",
"(",
"ct",
".",
"simulation",
".",
"event_records",
",",
"base_ct",
".",
"simulation",
".",
"event_records",
")",
"merge_maps",
"(",
"ct",
".",
"simulation",
".",
"data_displays",
",",
"base_ct",
".",
"simulation",
".",
"data_displays",
")",
"merge_maps",
"(",
"ct",
".",
"simulation",
".",
"data_writers",
",",
"base_ct",
".",
"simulation",
".",
"data_writers",
")",
"merge_maps",
"(",
"ct",
".",
"simulation",
".",
"event_writers",
",",
"base_ct",
".",
"simulation",
".",
"event_writers",
")"
] | Merge various maps in the given component type from a base
component type.
@param ct: Component type to be resolved.
@type ct: lems.model.component.ComponentType
@param base_ct: Component type to be resolved.
@type base_ct: lems.model.component.ComponentType | [
"Merge",
"various",
"maps",
"in",
"the",
"given",
"component",
"type",
"from",
"a",
"base",
"component",
"type",
"."
] | 4eeb719d2f23650fe16c38626663b69b5c83818b | https://github.com/LEMS/pylems/blob/4eeb719d2f23650fe16c38626663b69b5c83818b/lems/model/model.py#L370-L428 | train |
LEMS/pylems | lems/model/model.py | Model.resolve_simulation | def resolve_simulation(self, fc, ct):
"""
Resolve simulation specifications.
"""
for run in ct.simulation.runs:
try:
run2 = Run(fc.component_references[run.component].referenced_component,
run.variable,
fc.parameters[run.increment].numeric_value,
fc.parameters[run.total].numeric_value)
except:
raise ModelError("Unable to resolve simulation run parameters in component '{0}'",
fc.id)
fc.simulation.add(run2)
for record in ct.simulation.records:
try:
record2 = Record(fc.paths[record.quantity].value,
fc.parameters[record.scale].numeric_value if record.scale else 1,
fc.texts[record.color].value if record.color else '#000000')
except:
raise ModelError("Unable to resolve simulation record parameters in component '{0}'",
fc.id)
fc.simulation.add(record2)
for event_record in ct.simulation.event_records:
try:
event_record2 = EventRecord(fc.paths[event_record.quantity].value,
fc.texts[event_record.eventPort].value)
except:
raise ModelError("Unable to resolve simulation event_record parameters in component '{0}'",
fc.id)
fc.simulation.add(event_record2)
for dd in ct.simulation.data_displays:
try:
dd2 = DataDisplay(fc.texts[dd.title].value,
'')
if 'timeScale' in fc.parameters:
dd2.timeScale = fc.parameters['timeScale'].numeric_value
except:
raise ModelError("Unable to resolve simulation display parameters in component '{0}'",
fc.id)
fc.simulation.add(dd2)
for dw in ct.simulation.data_writers:
try:
path = '.'
if fc.texts[dw.path] and fc.texts[dw.path].value:
path = fc.texts[dw.path].value
dw2 = DataWriter(path,
fc.texts[dw.file_name].value)
except:
raise ModelError("Unable to resolve simulation writer parameters in component '{0}'",
fc.id)
fc.simulation.add(dw2)
for ew in ct.simulation.event_writers:
try:
path = '.'
if fc.texts[ew.path] and fc.texts[ew.path].value:
path = fc.texts[ew.path].value
ew2 = EventWriter(path,
fc.texts[ew.file_name].value,
fc.texts[ew.format].value)
except:
raise ModelError("Unable to resolve simulation writer parameters in component '{0}'",
fc.id)
fc.simulation.add(ew2) | python | def resolve_simulation(self, fc, ct):
"""
Resolve simulation specifications.
"""
for run in ct.simulation.runs:
try:
run2 = Run(fc.component_references[run.component].referenced_component,
run.variable,
fc.parameters[run.increment].numeric_value,
fc.parameters[run.total].numeric_value)
except:
raise ModelError("Unable to resolve simulation run parameters in component '{0}'",
fc.id)
fc.simulation.add(run2)
for record in ct.simulation.records:
try:
record2 = Record(fc.paths[record.quantity].value,
fc.parameters[record.scale].numeric_value if record.scale else 1,
fc.texts[record.color].value if record.color else '#000000')
except:
raise ModelError("Unable to resolve simulation record parameters in component '{0}'",
fc.id)
fc.simulation.add(record2)
for event_record in ct.simulation.event_records:
try:
event_record2 = EventRecord(fc.paths[event_record.quantity].value,
fc.texts[event_record.eventPort].value)
except:
raise ModelError("Unable to resolve simulation event_record parameters in component '{0}'",
fc.id)
fc.simulation.add(event_record2)
for dd in ct.simulation.data_displays:
try:
dd2 = DataDisplay(fc.texts[dd.title].value,
'')
if 'timeScale' in fc.parameters:
dd2.timeScale = fc.parameters['timeScale'].numeric_value
except:
raise ModelError("Unable to resolve simulation display parameters in component '{0}'",
fc.id)
fc.simulation.add(dd2)
for dw in ct.simulation.data_writers:
try:
path = '.'
if fc.texts[dw.path] and fc.texts[dw.path].value:
path = fc.texts[dw.path].value
dw2 = DataWriter(path,
fc.texts[dw.file_name].value)
except:
raise ModelError("Unable to resolve simulation writer parameters in component '{0}'",
fc.id)
fc.simulation.add(dw2)
for ew in ct.simulation.event_writers:
try:
path = '.'
if fc.texts[ew.path] and fc.texts[ew.path].value:
path = fc.texts[ew.path].value
ew2 = EventWriter(path,
fc.texts[ew.file_name].value,
fc.texts[ew.format].value)
except:
raise ModelError("Unable to resolve simulation writer parameters in component '{0}'",
fc.id)
fc.simulation.add(ew2) | [
"def",
"resolve_simulation",
"(",
"self",
",",
"fc",
",",
"ct",
")",
":",
"for",
"run",
"in",
"ct",
".",
"simulation",
".",
"runs",
":",
"try",
":",
"run2",
"=",
"Run",
"(",
"fc",
".",
"component_references",
"[",
"run",
".",
"component",
"]",
".",
"referenced_component",
",",
"run",
".",
"variable",
",",
"fc",
".",
"parameters",
"[",
"run",
".",
"increment",
"]",
".",
"numeric_value",
",",
"fc",
".",
"parameters",
"[",
"run",
".",
"total",
"]",
".",
"numeric_value",
")",
"except",
":",
"raise",
"ModelError",
"(",
"\"Unable to resolve simulation run parameters in component '{0}'\"",
",",
"fc",
".",
"id",
")",
"fc",
".",
"simulation",
".",
"add",
"(",
"run2",
")",
"for",
"record",
"in",
"ct",
".",
"simulation",
".",
"records",
":",
"try",
":",
"record2",
"=",
"Record",
"(",
"fc",
".",
"paths",
"[",
"record",
".",
"quantity",
"]",
".",
"value",
",",
"fc",
".",
"parameters",
"[",
"record",
".",
"scale",
"]",
".",
"numeric_value",
"if",
"record",
".",
"scale",
"else",
"1",
",",
"fc",
".",
"texts",
"[",
"record",
".",
"color",
"]",
".",
"value",
"if",
"record",
".",
"color",
"else",
"'#000000'",
")",
"except",
":",
"raise",
"ModelError",
"(",
"\"Unable to resolve simulation record parameters in component '{0}'\"",
",",
"fc",
".",
"id",
")",
"fc",
".",
"simulation",
".",
"add",
"(",
"record2",
")",
"for",
"event_record",
"in",
"ct",
".",
"simulation",
".",
"event_records",
":",
"try",
":",
"event_record2",
"=",
"EventRecord",
"(",
"fc",
".",
"paths",
"[",
"event_record",
".",
"quantity",
"]",
".",
"value",
",",
"fc",
".",
"texts",
"[",
"event_record",
".",
"eventPort",
"]",
".",
"value",
")",
"except",
":",
"raise",
"ModelError",
"(",
"\"Unable to resolve simulation event_record parameters in component '{0}'\"",
",",
"fc",
".",
"id",
")",
"fc",
".",
"simulation",
".",
"add",
"(",
"event_record2",
")",
"for",
"dd",
"in",
"ct",
".",
"simulation",
".",
"data_displays",
":",
"try",
":",
"dd2",
"=",
"DataDisplay",
"(",
"fc",
".",
"texts",
"[",
"dd",
".",
"title",
"]",
".",
"value",
",",
"''",
")",
"if",
"'timeScale'",
"in",
"fc",
".",
"parameters",
":",
"dd2",
".",
"timeScale",
"=",
"fc",
".",
"parameters",
"[",
"'timeScale'",
"]",
".",
"numeric_value",
"except",
":",
"raise",
"ModelError",
"(",
"\"Unable to resolve simulation display parameters in component '{0}'\"",
",",
"fc",
".",
"id",
")",
"fc",
".",
"simulation",
".",
"add",
"(",
"dd2",
")",
"for",
"dw",
"in",
"ct",
".",
"simulation",
".",
"data_writers",
":",
"try",
":",
"path",
"=",
"'.'",
"if",
"fc",
".",
"texts",
"[",
"dw",
".",
"path",
"]",
"and",
"fc",
".",
"texts",
"[",
"dw",
".",
"path",
"]",
".",
"value",
":",
"path",
"=",
"fc",
".",
"texts",
"[",
"dw",
".",
"path",
"]",
".",
"value",
"dw2",
"=",
"DataWriter",
"(",
"path",
",",
"fc",
".",
"texts",
"[",
"dw",
".",
"file_name",
"]",
".",
"value",
")",
"except",
":",
"raise",
"ModelError",
"(",
"\"Unable to resolve simulation writer parameters in component '{0}'\"",
",",
"fc",
".",
"id",
")",
"fc",
".",
"simulation",
".",
"add",
"(",
"dw2",
")",
"for",
"ew",
"in",
"ct",
".",
"simulation",
".",
"event_writers",
":",
"try",
":",
"path",
"=",
"'.'",
"if",
"fc",
".",
"texts",
"[",
"ew",
".",
"path",
"]",
"and",
"fc",
".",
"texts",
"[",
"ew",
".",
"path",
"]",
".",
"value",
":",
"path",
"=",
"fc",
".",
"texts",
"[",
"ew",
".",
"path",
"]",
".",
"value",
"ew2",
"=",
"EventWriter",
"(",
"path",
",",
"fc",
".",
"texts",
"[",
"ew",
".",
"file_name",
"]",
".",
"value",
",",
"fc",
".",
"texts",
"[",
"ew",
".",
"format",
"]",
".",
"value",
")",
"except",
":",
"raise",
"ModelError",
"(",
"\"Unable to resolve simulation writer parameters in component '{0}'\"",
",",
"fc",
".",
"id",
")",
"fc",
".",
"simulation",
".",
"add",
"(",
"ew2",
")"
] | Resolve simulation specifications. | [
"Resolve",
"simulation",
"specifications",
"."
] | 4eeb719d2f23650fe16c38626663b69b5c83818b | https://github.com/LEMS/pylems/blob/4eeb719d2f23650fe16c38626663b69b5c83818b/lems/model/model.py#L728-L799 | train |
LEMS/pylems | lems/model/model.py | Model.get_numeric_value | def get_numeric_value(self, value_str, dimension = None):
"""
Get the numeric value for a parameter value specification.
@param value_str: Value string
@type value_str: str
@param dimension: Dimension of the value
@type dimension: str
"""
n = None
i = len(value_str)
while n is None:
try:
part = value_str[0:i]
nn = float(part)
n = nn
s = value_str[i:]
except ValueError:
i = i-1
number = n
sym = s
numeric_value = None
if sym == '':
numeric_value = number
else:
if sym in self.units:
unit = self.units[sym]
if dimension:
if dimension != unit.dimension and dimension != '*':
raise SimBuildError("Unit symbol '{0}' cannot "
"be used for dimension '{1}'",
sym, dimension)
else:
dimension = unit.dimension
numeric_value = (number * (10 ** unit.power) * unit.scale) + unit.offset
else:
raise SimBuildError("Unknown unit symbol '{0}'. Known: {1}",
sym, self.units)
#print("Have converted %s to value: %s, dimension %s"%(value_str, numeric_value, dimension))
return numeric_value | python | def get_numeric_value(self, value_str, dimension = None):
"""
Get the numeric value for a parameter value specification.
@param value_str: Value string
@type value_str: str
@param dimension: Dimension of the value
@type dimension: str
"""
n = None
i = len(value_str)
while n is None:
try:
part = value_str[0:i]
nn = float(part)
n = nn
s = value_str[i:]
except ValueError:
i = i-1
number = n
sym = s
numeric_value = None
if sym == '':
numeric_value = number
else:
if sym in self.units:
unit = self.units[sym]
if dimension:
if dimension != unit.dimension and dimension != '*':
raise SimBuildError("Unit symbol '{0}' cannot "
"be used for dimension '{1}'",
sym, dimension)
else:
dimension = unit.dimension
numeric_value = (number * (10 ** unit.power) * unit.scale) + unit.offset
else:
raise SimBuildError("Unknown unit symbol '{0}'. Known: {1}",
sym, self.units)
#print("Have converted %s to value: %s, dimension %s"%(value_str, numeric_value, dimension))
return numeric_value | [
"def",
"get_numeric_value",
"(",
"self",
",",
"value_str",
",",
"dimension",
"=",
"None",
")",
":",
"n",
"=",
"None",
"i",
"=",
"len",
"(",
"value_str",
")",
"while",
"n",
"is",
"None",
":",
"try",
":",
"part",
"=",
"value_str",
"[",
"0",
":",
"i",
"]",
"nn",
"=",
"float",
"(",
"part",
")",
"n",
"=",
"nn",
"s",
"=",
"value_str",
"[",
"i",
":",
"]",
"except",
"ValueError",
":",
"i",
"=",
"i",
"-",
"1",
"number",
"=",
"n",
"sym",
"=",
"s",
"numeric_value",
"=",
"None",
"if",
"sym",
"==",
"''",
":",
"numeric_value",
"=",
"number",
"else",
":",
"if",
"sym",
"in",
"self",
".",
"units",
":",
"unit",
"=",
"self",
".",
"units",
"[",
"sym",
"]",
"if",
"dimension",
":",
"if",
"dimension",
"!=",
"unit",
".",
"dimension",
"and",
"dimension",
"!=",
"'*'",
":",
"raise",
"SimBuildError",
"(",
"\"Unit symbol '{0}' cannot \"",
"\"be used for dimension '{1}'\"",
",",
"sym",
",",
"dimension",
")",
"else",
":",
"dimension",
"=",
"unit",
".",
"dimension",
"numeric_value",
"=",
"(",
"number",
"*",
"(",
"10",
"**",
"unit",
".",
"power",
")",
"*",
"unit",
".",
"scale",
")",
"+",
"unit",
".",
"offset",
"else",
":",
"raise",
"SimBuildError",
"(",
"\"Unknown unit symbol '{0}'. Known: {1}\"",
",",
"sym",
",",
"self",
".",
"units",
")",
"#print(\"Have converted %s to value: %s, dimension %s\"%(value_str, numeric_value, dimension)) ",
"return",
"numeric_value"
] | Get the numeric value for a parameter value specification.
@param value_str: Value string
@type value_str: str
@param dimension: Dimension of the value
@type dimension: str | [
"Get",
"the",
"numeric",
"value",
"for",
"a",
"parameter",
"value",
"specification",
"."
] | 4eeb719d2f23650fe16c38626663b69b5c83818b | https://github.com/LEMS/pylems/blob/4eeb719d2f23650fe16c38626663b69b5c83818b/lems/model/model.py#L802-L849 | train |
glormph/msstitch | src/app/drivers/startup.py | start_msstitch | def start_msstitch(exec_drivers, sysargs):
"""Passed all drivers of executable, checks which command is passed to
the executable and then gets the options for a driver, parses them from
command line and runs the driver"""
parser = populate_parser(exec_drivers)
args = parser.parse_args(sysargs[1:])
args.func(**vars(args)) | python | def start_msstitch(exec_drivers, sysargs):
"""Passed all drivers of executable, checks which command is passed to
the executable and then gets the options for a driver, parses them from
command line and runs the driver"""
parser = populate_parser(exec_drivers)
args = parser.parse_args(sysargs[1:])
args.func(**vars(args)) | [
"def",
"start_msstitch",
"(",
"exec_drivers",
",",
"sysargs",
")",
":",
"parser",
"=",
"populate_parser",
"(",
"exec_drivers",
")",
"args",
"=",
"parser",
".",
"parse_args",
"(",
"sysargs",
"[",
"1",
":",
"]",
")",
"args",
".",
"func",
"(",
"*",
"*",
"vars",
"(",
"args",
")",
")"
] | Passed all drivers of executable, checks which command is passed to
the executable and then gets the options for a driver, parses them from
command line and runs the driver | [
"Passed",
"all",
"drivers",
"of",
"executable",
"checks",
"which",
"command",
"is",
"passed",
"to",
"the",
"executable",
"and",
"then",
"gets",
"the",
"options",
"for",
"a",
"driver",
"parses",
"them",
"from",
"command",
"line",
"and",
"runs",
"the",
"driver"
] | ded7e5cbd813d7797dc9d42805778266e59ff042 | https://github.com/glormph/msstitch/blob/ded7e5cbd813d7797dc9d42805778266e59ff042/src/app/drivers/startup.py#L47-L53 | train |
TriOptima/tri.struct | lib/tri/struct/__init__.py | merged | def merged(*dicts, **kwargs):
"""
Merge dictionaries. Later keys overwrite.
.. code-block:: python
merged(dict(a=1), dict(b=2), c=3, d=1)
"""
if not dicts:
return Struct()
result = dict()
for d in dicts:
result.update(d)
result.update(kwargs)
struct_type = type(dicts[0])
return struct_type(**result) | python | def merged(*dicts, **kwargs):
"""
Merge dictionaries. Later keys overwrite.
.. code-block:: python
merged(dict(a=1), dict(b=2), c=3, d=1)
"""
if not dicts:
return Struct()
result = dict()
for d in dicts:
result.update(d)
result.update(kwargs)
struct_type = type(dicts[0])
return struct_type(**result) | [
"def",
"merged",
"(",
"*",
"dicts",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"not",
"dicts",
":",
"return",
"Struct",
"(",
")",
"result",
"=",
"dict",
"(",
")",
"for",
"d",
"in",
"dicts",
":",
"result",
".",
"update",
"(",
"d",
")",
"result",
".",
"update",
"(",
"kwargs",
")",
"struct_type",
"=",
"type",
"(",
"dicts",
"[",
"0",
"]",
")",
"return",
"struct_type",
"(",
"*",
"*",
"result",
")"
] | Merge dictionaries. Later keys overwrite.
.. code-block:: python
merged(dict(a=1), dict(b=2), c=3, d=1) | [
"Merge",
"dictionaries",
".",
"Later",
"keys",
"overwrite",
"."
] | 8886392da9cd77ce662e0781b0ff0bf82b38b56b | https://github.com/TriOptima/tri.struct/blob/8886392da9cd77ce662e0781b0ff0bf82b38b56b/lib/tri/struct/__init__.py#L60-L76 | train |
LEMS/pylems | lems/sim/build.py | order_derived_parameters | def order_derived_parameters(component):
"""
Finds ordering of derived_parameters.
@param component: Component containing derived parameters.
@type component: lems.model.component.Component
@return: Returns ordered list of derived parameters.
@rtype: list(string)
@raise SimBuildError: Raised when a proper ordering of derived
parameters could not be found.
"""
if len(component.derived_parameters) == 0:
return []
ordering = []
dps = []
for dp in component.derived_parameters:
dps.append(dp.name)
maxcount = 5
count = maxcount
while count > 0 and dps != []:
count = count - 1
for dp1 in dps:
#exp_tree = regime.derived_variables[dv1].expression_tree
value = component.derived_parameters[dp1].value
found = False
for dp2 in dps:
if dp1 != dp2 and dp2 in value:
found = True
if not found:
ordering.append(dp1)
del dps[dps.index(dp1)]
count = maxcount
break
if count == 0:
raise SimBuildError(("Unable to find ordering for derived "
"parameter in component '{0}'").format(component))
#return ordering + dvsnoexp
return ordering | python | def order_derived_parameters(component):
"""
Finds ordering of derived_parameters.
@param component: Component containing derived parameters.
@type component: lems.model.component.Component
@return: Returns ordered list of derived parameters.
@rtype: list(string)
@raise SimBuildError: Raised when a proper ordering of derived
parameters could not be found.
"""
if len(component.derived_parameters) == 0:
return []
ordering = []
dps = []
for dp in component.derived_parameters:
dps.append(dp.name)
maxcount = 5
count = maxcount
while count > 0 and dps != []:
count = count - 1
for dp1 in dps:
#exp_tree = regime.derived_variables[dv1].expression_tree
value = component.derived_parameters[dp1].value
found = False
for dp2 in dps:
if dp1 != dp2 and dp2 in value:
found = True
if not found:
ordering.append(dp1)
del dps[dps.index(dp1)]
count = maxcount
break
if count == 0:
raise SimBuildError(("Unable to find ordering for derived "
"parameter in component '{0}'").format(component))
#return ordering + dvsnoexp
return ordering | [
"def",
"order_derived_parameters",
"(",
"component",
")",
":",
"if",
"len",
"(",
"component",
".",
"derived_parameters",
")",
"==",
"0",
":",
"return",
"[",
"]",
"ordering",
"=",
"[",
"]",
"dps",
"=",
"[",
"]",
"for",
"dp",
"in",
"component",
".",
"derived_parameters",
":",
"dps",
".",
"append",
"(",
"dp",
".",
"name",
")",
"maxcount",
"=",
"5",
"count",
"=",
"maxcount",
"while",
"count",
">",
"0",
"and",
"dps",
"!=",
"[",
"]",
":",
"count",
"=",
"count",
"-",
"1",
"for",
"dp1",
"in",
"dps",
":",
"#exp_tree = regime.derived_variables[dv1].expression_tree",
"value",
"=",
"component",
".",
"derived_parameters",
"[",
"dp1",
"]",
".",
"value",
"found",
"=",
"False",
"for",
"dp2",
"in",
"dps",
":",
"if",
"dp1",
"!=",
"dp2",
"and",
"dp2",
"in",
"value",
":",
"found",
"=",
"True",
"if",
"not",
"found",
":",
"ordering",
".",
"append",
"(",
"dp1",
")",
"del",
"dps",
"[",
"dps",
".",
"index",
"(",
"dp1",
")",
"]",
"count",
"=",
"maxcount",
"break",
"if",
"count",
"==",
"0",
":",
"raise",
"SimBuildError",
"(",
"(",
"\"Unable to find ordering for derived \"",
"\"parameter in component '{0}'\"",
")",
".",
"format",
"(",
"component",
")",
")",
"#return ordering + dvsnoexp",
"return",
"ordering"
] | Finds ordering of derived_parameters.
@param component: Component containing derived parameters.
@type component: lems.model.component.Component
@return: Returns ordered list of derived parameters.
@rtype: list(string)
@raise SimBuildError: Raised when a proper ordering of derived
parameters could not be found. | [
"Finds",
"ordering",
"of",
"derived_parameters",
"."
] | 4eeb719d2f23650fe16c38626663b69b5c83818b | https://github.com/LEMS/pylems/blob/4eeb719d2f23650fe16c38626663b69b5c83818b/lems/sim/build.py#L1059-L1107 | train |
LEMS/pylems | lems/sim/build.py | order_derived_variables | def order_derived_variables(regime):
"""
Finds ordering of derived_variables.
@param regime: Dynamics Regime containing derived variables.
@type regime: lems.model.dynamics.regime
@return: Returns ordered list of derived variables.
@rtype: list(string)
@raise SimBuildError: Raised when a proper ordering of derived
variables could not be found.
"""
ordering = []
dvs = []
dvsnoexp = []
maxcount = 5
for dv in regime.derived_variables:
if dv.expression_tree == None:
dvsnoexp.append(dv.name)
else:
dvs.append(dv.name)
for dv in regime.conditional_derived_variables:
if len(dv.cases) == 0:
dvsnoexp.append(dv.name)
else:
dvs.append(dv.name)
count = maxcount
while count > 0 and dvs != []:
count = count - 1
for dv1 in dvs:
if dv1 in regime.derived_variables:
dv = regime.derived_variables[dv1]
else:
dv = regime.conditional_derived_variables[dv1]
found = False
if isinstance(dv, DerivedVariable):
exp_tree = dv.expression_tree
for dv2 in dvs:
if dv1 != dv2 and is_var_in_exp_tree(dv2, exp_tree):
found = True
else:
for case in dv.cases:
for dv2 in dvs:
if dv1 != dv2 and (is_var_in_exp_tree(dv2, case.condition_expression_tree) or
is_var_in_exp_tree(dv2, case.value_expression_tree)):
found = True
if not found:
ordering.append(dv1)
del dvs[dvs.index(dv1)]
count = maxcount
break
if count == 0:
raise SimBuildError(("Unable to find ordering for derived "
"variables in regime '{0}'").format(regime.name))
#return ordering + dvsnoexp
return dvsnoexp + ordering | python | def order_derived_variables(regime):
"""
Finds ordering of derived_variables.
@param regime: Dynamics Regime containing derived variables.
@type regime: lems.model.dynamics.regime
@return: Returns ordered list of derived variables.
@rtype: list(string)
@raise SimBuildError: Raised when a proper ordering of derived
variables could not be found.
"""
ordering = []
dvs = []
dvsnoexp = []
maxcount = 5
for dv in regime.derived_variables:
if dv.expression_tree == None:
dvsnoexp.append(dv.name)
else:
dvs.append(dv.name)
for dv in regime.conditional_derived_variables:
if len(dv.cases) == 0:
dvsnoexp.append(dv.name)
else:
dvs.append(dv.name)
count = maxcount
while count > 0 and dvs != []:
count = count - 1
for dv1 in dvs:
if dv1 in regime.derived_variables:
dv = regime.derived_variables[dv1]
else:
dv = regime.conditional_derived_variables[dv1]
found = False
if isinstance(dv, DerivedVariable):
exp_tree = dv.expression_tree
for dv2 in dvs:
if dv1 != dv2 and is_var_in_exp_tree(dv2, exp_tree):
found = True
else:
for case in dv.cases:
for dv2 in dvs:
if dv1 != dv2 and (is_var_in_exp_tree(dv2, case.condition_expression_tree) or
is_var_in_exp_tree(dv2, case.value_expression_tree)):
found = True
if not found:
ordering.append(dv1)
del dvs[dvs.index(dv1)]
count = maxcount
break
if count == 0:
raise SimBuildError(("Unable to find ordering for derived "
"variables in regime '{0}'").format(regime.name))
#return ordering + dvsnoexp
return dvsnoexp + ordering | [
"def",
"order_derived_variables",
"(",
"regime",
")",
":",
"ordering",
"=",
"[",
"]",
"dvs",
"=",
"[",
"]",
"dvsnoexp",
"=",
"[",
"]",
"maxcount",
"=",
"5",
"for",
"dv",
"in",
"regime",
".",
"derived_variables",
":",
"if",
"dv",
".",
"expression_tree",
"==",
"None",
":",
"dvsnoexp",
".",
"append",
"(",
"dv",
".",
"name",
")",
"else",
":",
"dvs",
".",
"append",
"(",
"dv",
".",
"name",
")",
"for",
"dv",
"in",
"regime",
".",
"conditional_derived_variables",
":",
"if",
"len",
"(",
"dv",
".",
"cases",
")",
"==",
"0",
":",
"dvsnoexp",
".",
"append",
"(",
"dv",
".",
"name",
")",
"else",
":",
"dvs",
".",
"append",
"(",
"dv",
".",
"name",
")",
"count",
"=",
"maxcount",
"while",
"count",
">",
"0",
"and",
"dvs",
"!=",
"[",
"]",
":",
"count",
"=",
"count",
"-",
"1",
"for",
"dv1",
"in",
"dvs",
":",
"if",
"dv1",
"in",
"regime",
".",
"derived_variables",
":",
"dv",
"=",
"regime",
".",
"derived_variables",
"[",
"dv1",
"]",
"else",
":",
"dv",
"=",
"regime",
".",
"conditional_derived_variables",
"[",
"dv1",
"]",
"found",
"=",
"False",
"if",
"isinstance",
"(",
"dv",
",",
"DerivedVariable",
")",
":",
"exp_tree",
"=",
"dv",
".",
"expression_tree",
"for",
"dv2",
"in",
"dvs",
":",
"if",
"dv1",
"!=",
"dv2",
"and",
"is_var_in_exp_tree",
"(",
"dv2",
",",
"exp_tree",
")",
":",
"found",
"=",
"True",
"else",
":",
"for",
"case",
"in",
"dv",
".",
"cases",
":",
"for",
"dv2",
"in",
"dvs",
":",
"if",
"dv1",
"!=",
"dv2",
"and",
"(",
"is_var_in_exp_tree",
"(",
"dv2",
",",
"case",
".",
"condition_expression_tree",
")",
"or",
"is_var_in_exp_tree",
"(",
"dv2",
",",
"case",
".",
"value_expression_tree",
")",
")",
":",
"found",
"=",
"True",
"if",
"not",
"found",
":",
"ordering",
".",
"append",
"(",
"dv1",
")",
"del",
"dvs",
"[",
"dvs",
".",
"index",
"(",
"dv1",
")",
"]",
"count",
"=",
"maxcount",
"break",
"if",
"count",
"==",
"0",
":",
"raise",
"SimBuildError",
"(",
"(",
"\"Unable to find ordering for derived \"",
"\"variables in regime '{0}'\"",
")",
".",
"format",
"(",
"regime",
".",
"name",
")",
")",
"#return ordering + dvsnoexp",
"return",
"dvsnoexp",
"+",
"ordering"
] | Finds ordering of derived_variables.
@param regime: Dynamics Regime containing derived variables.
@type regime: lems.model.dynamics.regime
@return: Returns ordered list of derived variables.
@rtype: list(string)
@raise SimBuildError: Raised when a proper ordering of derived
variables could not be found. | [
"Finds",
"ordering",
"of",
"derived_variables",
"."
] | 4eeb719d2f23650fe16c38626663b69b5c83818b | https://github.com/LEMS/pylems/blob/4eeb719d2f23650fe16c38626663b69b5c83818b/lems/sim/build.py#L1110-L1177 | train |
LEMS/pylems | lems/sim/build.py | SimulationBuilder.build | def build(self):
"""
Build the simulation components from the model.
@return: A runnable simulation object
@rtype: lems.sim.sim.Simulation
"""
self.sim = Simulation()
for component_id in self.model.targets:
if component_id not in self.model.components:
raise SimBuildError("Unable to find target component '{0}'",
component_id)
component = self.model.fat_components[component_id]
runnable = self.build_runnable(component)
self.sim.add_runnable(runnable)
return self.sim | python | def build(self):
"""
Build the simulation components from the model.
@return: A runnable simulation object
@rtype: lems.sim.sim.Simulation
"""
self.sim = Simulation()
for component_id in self.model.targets:
if component_id not in self.model.components:
raise SimBuildError("Unable to find target component '{0}'",
component_id)
component = self.model.fat_components[component_id]
runnable = self.build_runnable(component)
self.sim.add_runnable(runnable)
return self.sim | [
"def",
"build",
"(",
"self",
")",
":",
"self",
".",
"sim",
"=",
"Simulation",
"(",
")",
"for",
"component_id",
"in",
"self",
".",
"model",
".",
"targets",
":",
"if",
"component_id",
"not",
"in",
"self",
".",
"model",
".",
"components",
":",
"raise",
"SimBuildError",
"(",
"\"Unable to find target component '{0}'\"",
",",
"component_id",
")",
"component",
"=",
"self",
".",
"model",
".",
"fat_components",
"[",
"component_id",
"]",
"runnable",
"=",
"self",
".",
"build_runnable",
"(",
"component",
")",
"self",
".",
"sim",
".",
"add_runnable",
"(",
"runnable",
")",
"return",
"self",
".",
"sim"
] | Build the simulation components from the model.
@return: A runnable simulation object
@rtype: lems.sim.sim.Simulation | [
"Build",
"the",
"simulation",
"components",
"from",
"the",
"model",
"."
] | 4eeb719d2f23650fe16c38626663b69b5c83818b | https://github.com/LEMS/pylems/blob/4eeb719d2f23650fe16c38626663b69b5c83818b/lems/sim/build.py#L47-L66 | train |
LEMS/pylems | lems/sim/build.py | SimulationBuilder.build_event_connections | def build_event_connections(self, component, runnable, structure):
"""
Adds event connections to a runnable component based on the structure
specifications in the component model.
@param component: Component model containing structure specifications.
@type component: lems.model.component.FatComponent
@param runnable: Runnable component to which structure is to be added.
@type runnable: lems.sim.runnable.Runnable
@param structure: The structure object to be used to add
structure code in the runnable component.
@type structure: lems.model.structure.Structure
"""
if self.debug: print("\n++++++++ Calling build_event_connections of %s with runnable %s, parent %s"%(component.id, runnable.id, runnable.parent))
# Process event connections
for ec in structure.event_connections:
if self.debug: print(ec.toxml())
source = runnable.parent.resolve_path(ec.from_)
target = runnable.parent.resolve_path(ec.to)
if ec.receiver:
receiver_template = self.build_runnable(ec.receiver,
target)
#receiver = copy.deepcopy(receiver_template)
receiver = receiver_template.copy()
receiver.id = "{0}__{1}__".format(component.id,
receiver_template.id)
if ec.receiver_container:
target.add_attachment(receiver, ec.receiver_container)
target.add_child(receiver_template.id, receiver)
target = receiver
else:
source = runnable.resolve_path(ec.from_)
target = runnable.resolve_path(ec.to)
source_port = ec.source_port
target_port = ec.target_port
if not source_port:
if len(source.event_out_ports) == 1:
source_port = source.event_out_ports[0]
else:
raise SimBuildError(("No source event port "
"uniquely identifiable"
" in '{0}'").format(source.id))
if not target_port:
if len(target.event_in_ports) == 1:
target_port = target.event_in_ports[0]
else:
raise SimBuildError(("No destination event port "
"uniquely identifiable "
"in '{0}'").format(target))
if self.debug: print("register_event_out_callback\n Source: %s, %s (port: %s) \n -> %s, %s (port: %s)"%(source, id(source), source_port, target, id(target), target_port))
source.register_event_out_callback(\
source_port, lambda: target.inc_event_in(target_port)) | python | def build_event_connections(self, component, runnable, structure):
"""
Adds event connections to a runnable component based on the structure
specifications in the component model.
@param component: Component model containing structure specifications.
@type component: lems.model.component.FatComponent
@param runnable: Runnable component to which structure is to be added.
@type runnable: lems.sim.runnable.Runnable
@param structure: The structure object to be used to add
structure code in the runnable component.
@type structure: lems.model.structure.Structure
"""
if self.debug: print("\n++++++++ Calling build_event_connections of %s with runnable %s, parent %s"%(component.id, runnable.id, runnable.parent))
# Process event connections
for ec in structure.event_connections:
if self.debug: print(ec.toxml())
source = runnable.parent.resolve_path(ec.from_)
target = runnable.parent.resolve_path(ec.to)
if ec.receiver:
receiver_template = self.build_runnable(ec.receiver,
target)
#receiver = copy.deepcopy(receiver_template)
receiver = receiver_template.copy()
receiver.id = "{0}__{1}__".format(component.id,
receiver_template.id)
if ec.receiver_container:
target.add_attachment(receiver, ec.receiver_container)
target.add_child(receiver_template.id, receiver)
target = receiver
else:
source = runnable.resolve_path(ec.from_)
target = runnable.resolve_path(ec.to)
source_port = ec.source_port
target_port = ec.target_port
if not source_port:
if len(source.event_out_ports) == 1:
source_port = source.event_out_ports[0]
else:
raise SimBuildError(("No source event port "
"uniquely identifiable"
" in '{0}'").format(source.id))
if not target_port:
if len(target.event_in_ports) == 1:
target_port = target.event_in_ports[0]
else:
raise SimBuildError(("No destination event port "
"uniquely identifiable "
"in '{0}'").format(target))
if self.debug: print("register_event_out_callback\n Source: %s, %s (port: %s) \n -> %s, %s (port: %s)"%(source, id(source), source_port, target, id(target), target_port))
source.register_event_out_callback(\
source_port, lambda: target.inc_event_in(target_port)) | [
"def",
"build_event_connections",
"(",
"self",
",",
"component",
",",
"runnable",
",",
"structure",
")",
":",
"if",
"self",
".",
"debug",
":",
"print",
"(",
"\"\\n++++++++ Calling build_event_connections of %s with runnable %s, parent %s\"",
"%",
"(",
"component",
".",
"id",
",",
"runnable",
".",
"id",
",",
"runnable",
".",
"parent",
")",
")",
"# Process event connections",
"for",
"ec",
"in",
"structure",
".",
"event_connections",
":",
"if",
"self",
".",
"debug",
":",
"print",
"(",
"ec",
".",
"toxml",
"(",
")",
")",
"source",
"=",
"runnable",
".",
"parent",
".",
"resolve_path",
"(",
"ec",
".",
"from_",
")",
"target",
"=",
"runnable",
".",
"parent",
".",
"resolve_path",
"(",
"ec",
".",
"to",
")",
"if",
"ec",
".",
"receiver",
":",
"receiver_template",
"=",
"self",
".",
"build_runnable",
"(",
"ec",
".",
"receiver",
",",
"target",
")",
"#receiver = copy.deepcopy(receiver_template)",
"receiver",
"=",
"receiver_template",
".",
"copy",
"(",
")",
"receiver",
".",
"id",
"=",
"\"{0}__{1}__\"",
".",
"format",
"(",
"component",
".",
"id",
",",
"receiver_template",
".",
"id",
")",
"if",
"ec",
".",
"receiver_container",
":",
"target",
".",
"add_attachment",
"(",
"receiver",
",",
"ec",
".",
"receiver_container",
")",
"target",
".",
"add_child",
"(",
"receiver_template",
".",
"id",
",",
"receiver",
")",
"target",
"=",
"receiver",
"else",
":",
"source",
"=",
"runnable",
".",
"resolve_path",
"(",
"ec",
".",
"from_",
")",
"target",
"=",
"runnable",
".",
"resolve_path",
"(",
"ec",
".",
"to",
")",
"source_port",
"=",
"ec",
".",
"source_port",
"target_port",
"=",
"ec",
".",
"target_port",
"if",
"not",
"source_port",
":",
"if",
"len",
"(",
"source",
".",
"event_out_ports",
")",
"==",
"1",
":",
"source_port",
"=",
"source",
".",
"event_out_ports",
"[",
"0",
"]",
"else",
":",
"raise",
"SimBuildError",
"(",
"(",
"\"No source event port \"",
"\"uniquely identifiable\"",
"\" in '{0}'\"",
")",
".",
"format",
"(",
"source",
".",
"id",
")",
")",
"if",
"not",
"target_port",
":",
"if",
"len",
"(",
"target",
".",
"event_in_ports",
")",
"==",
"1",
":",
"target_port",
"=",
"target",
".",
"event_in_ports",
"[",
"0",
"]",
"else",
":",
"raise",
"SimBuildError",
"(",
"(",
"\"No destination event port \"",
"\"uniquely identifiable \"",
"\"in '{0}'\"",
")",
".",
"format",
"(",
"target",
")",
")",
"if",
"self",
".",
"debug",
":",
"print",
"(",
"\"register_event_out_callback\\n Source: %s, %s (port: %s) \\n -> %s, %s (port: %s)\"",
"%",
"(",
"source",
",",
"id",
"(",
"source",
")",
",",
"source_port",
",",
"target",
",",
"id",
"(",
"target",
")",
",",
"target_port",
")",
")",
"source",
".",
"register_event_out_callback",
"(",
"source_port",
",",
"lambda",
":",
"target",
".",
"inc_event_in",
"(",
"target_port",
")",
")"
] | Adds event connections to a runnable component based on the structure
specifications in the component model.
@param component: Component model containing structure specifications.
@type component: lems.model.component.FatComponent
@param runnable: Runnable component to which structure is to be added.
@type runnable: lems.sim.runnable.Runnable
@param structure: The structure object to be used to add
structure code in the runnable component.
@type structure: lems.model.structure.Structure | [
"Adds",
"event",
"connections",
"to",
"a",
"runnable",
"component",
"based",
"on",
"the",
"structure",
"specifications",
"in",
"the",
"component",
"model",
"."
] | 4eeb719d2f23650fe16c38626663b69b5c83818b | https://github.com/LEMS/pylems/blob/4eeb719d2f23650fe16c38626663b69b5c83818b/lems/sim/build.py#L231-L289 | train |
LEMS/pylems | lems/sim/build.py | SimulationBuilder.build_structure | def build_structure(self, component, runnable, structure):
"""
Adds structure to a runnable component based on the structure
specifications in the component model.
@param component: Component model containing structure specifications.
@type component: lems.model.component.FatComponent
@param runnable: Runnable component to which structure is to be added.
@type runnable: lems.sim.runnable.Runnable
@param structure: The structure object to be used to add
structure code in the runnable component.
@type structure: lems.model.structure.Structure
"""
if self.debug: print("\n++++++++ Calling build_structure of %s with runnable %s, parent %s"%(component.id, runnable.id, runnable.parent))
# Process single-child instantiations
for ch in structure.child_instances:
child_runnable = self.build_runnable(ch.referenced_component, runnable)
runnable.add_child(child_runnable.id, child_runnable)
runnable.add_child_typeref(ch.component, child_runnable)
# Process multi-child instatiantions
for mi in structure.multi_instantiates:
template = self.build_runnable(mi.component,
runnable)
for i in range(mi.number):
#instance = copy.deepcopy(template)
instance = template.copy()
instance.id = "{0}__{1}__{2}".format(component.id,
template.id,
i)
runnable.array.append(instance)
# Process foreach statements
for fe in structure.for_eachs:
self.build_foreach(component, runnable, fe)
self.build_event_connections(component, runnable, structure) | python | def build_structure(self, component, runnable, structure):
"""
Adds structure to a runnable component based on the structure
specifications in the component model.
@param component: Component model containing structure specifications.
@type component: lems.model.component.FatComponent
@param runnable: Runnable component to which structure is to be added.
@type runnable: lems.sim.runnable.Runnable
@param structure: The structure object to be used to add
structure code in the runnable component.
@type structure: lems.model.structure.Structure
"""
if self.debug: print("\n++++++++ Calling build_structure of %s with runnable %s, parent %s"%(component.id, runnable.id, runnable.parent))
# Process single-child instantiations
for ch in structure.child_instances:
child_runnable = self.build_runnable(ch.referenced_component, runnable)
runnable.add_child(child_runnable.id, child_runnable)
runnable.add_child_typeref(ch.component, child_runnable)
# Process multi-child instatiantions
for mi in structure.multi_instantiates:
template = self.build_runnable(mi.component,
runnable)
for i in range(mi.number):
#instance = copy.deepcopy(template)
instance = template.copy()
instance.id = "{0}__{1}__{2}".format(component.id,
template.id,
i)
runnable.array.append(instance)
# Process foreach statements
for fe in structure.for_eachs:
self.build_foreach(component, runnable, fe)
self.build_event_connections(component, runnable, structure) | [
"def",
"build_structure",
"(",
"self",
",",
"component",
",",
"runnable",
",",
"structure",
")",
":",
"if",
"self",
".",
"debug",
":",
"print",
"(",
"\"\\n++++++++ Calling build_structure of %s with runnable %s, parent %s\"",
"%",
"(",
"component",
".",
"id",
",",
"runnable",
".",
"id",
",",
"runnable",
".",
"parent",
")",
")",
"# Process single-child instantiations",
"for",
"ch",
"in",
"structure",
".",
"child_instances",
":",
"child_runnable",
"=",
"self",
".",
"build_runnable",
"(",
"ch",
".",
"referenced_component",
",",
"runnable",
")",
"runnable",
".",
"add_child",
"(",
"child_runnable",
".",
"id",
",",
"child_runnable",
")",
"runnable",
".",
"add_child_typeref",
"(",
"ch",
".",
"component",
",",
"child_runnable",
")",
"# Process multi-child instatiantions",
"for",
"mi",
"in",
"structure",
".",
"multi_instantiates",
":",
"template",
"=",
"self",
".",
"build_runnable",
"(",
"mi",
".",
"component",
",",
"runnable",
")",
"for",
"i",
"in",
"range",
"(",
"mi",
".",
"number",
")",
":",
"#instance = copy.deepcopy(template)",
"instance",
"=",
"template",
".",
"copy",
"(",
")",
"instance",
".",
"id",
"=",
"\"{0}__{1}__{2}\"",
".",
"format",
"(",
"component",
".",
"id",
",",
"template",
".",
"id",
",",
"i",
")",
"runnable",
".",
"array",
".",
"append",
"(",
"instance",
")",
"# Process foreach statements",
"for",
"fe",
"in",
"structure",
".",
"for_eachs",
":",
"self",
".",
"build_foreach",
"(",
"component",
",",
"runnable",
",",
"fe",
")",
"self",
".",
"build_event_connections",
"(",
"component",
",",
"runnable",
",",
"structure",
")"
] | Adds structure to a runnable component based on the structure
specifications in the component model.
@param component: Component model containing structure specifications.
@type component: lems.model.component.FatComponent
@param runnable: Runnable component to which structure is to be added.
@type runnable: lems.sim.runnable.Runnable
@param structure: The structure object to be used to add
structure code in the runnable component.
@type structure: lems.model.structure.Structure | [
"Adds",
"structure",
"to",
"a",
"runnable",
"component",
"based",
"on",
"the",
"structure",
"specifications",
"in",
"the",
"component",
"model",
"."
] | 4eeb719d2f23650fe16c38626663b69b5c83818b | https://github.com/LEMS/pylems/blob/4eeb719d2f23650fe16c38626663b69b5c83818b/lems/sim/build.py#L293-L334 | train |
LEMS/pylems | lems/sim/build.py | SimulationBuilder.build_foreach | def build_foreach(self, component, runnable, foreach, name_mappings = {}):
"""
Iterate over ForEach constructs and process nested elements.
@param component: Component model containing structure specifications.
@type component: lems.model.component.FatComponent
@param runnable: Runnable component to which structure is to be added.
@type runnable: lems.sim.runnable.Runnable
@param foreach: The ForEach structure object to be used to add
structure code in the runnable component.
@type foreach: lems.model.structure.ForEach
"""
if self.debug: print("\n++++++++ Calling build_foreach of %s with runnable %s, parent %s, name_mappings: %s"%(component.id, runnable.id, runnable.parent, name_mappings))
target_array = runnable.resolve_path(foreach.instances)
for target_runnable in target_array:
if self.debug: print("Applying contents of for_each to %s, as %s"%(target_runnable.id, foreach.as_))
name_mappings[foreach.as_] = target_runnable
# Process foreach statements
for fe2 in foreach.for_eachs:
#print fe2.toxml()
target_array2 = runnable.resolve_path(fe2.instances)
for target_runnable2 in target_array2:
name_mappings[fe2.as_] = target_runnable2
self.build_foreach(component, runnable, fe2, name_mappings)
# Process event connections
for ec in foreach.event_connections:
source = name_mappings[ec.from_]
target = name_mappings[ec.to]
source_port = ec.source_port
target_port = ec.target_port
if not source_port:
if len(source.event_out_ports) == 1:
source_port = source.event_out_ports[0]
else:
raise SimBuildError(("No source event port "
"uniquely identifiable"
" in '{0}'").format(source.id))
if not target_port:
if len(target.event_in_ports) == 1:
target_port = target.event_in_ports[0]
else:
raise SimBuildError(("No destination event port "
"uniquely identifiable "
"in '{0}'").format(target))
if self.debug: print("register_event_out_callback\n Source: %s, %s (port: %s) \n -> %s, %s (port: %s)"%(source, id(source), source_port, target, id(target), target_port))
source.register_event_out_callback(\
source_port, lambda: target.inc_event_in(target_port)) | python | def build_foreach(self, component, runnable, foreach, name_mappings = {}):
"""
Iterate over ForEach constructs and process nested elements.
@param component: Component model containing structure specifications.
@type component: lems.model.component.FatComponent
@param runnable: Runnable component to which structure is to be added.
@type runnable: lems.sim.runnable.Runnable
@param foreach: The ForEach structure object to be used to add
structure code in the runnable component.
@type foreach: lems.model.structure.ForEach
"""
if self.debug: print("\n++++++++ Calling build_foreach of %s with runnable %s, parent %s, name_mappings: %s"%(component.id, runnable.id, runnable.parent, name_mappings))
target_array = runnable.resolve_path(foreach.instances)
for target_runnable in target_array:
if self.debug: print("Applying contents of for_each to %s, as %s"%(target_runnable.id, foreach.as_))
name_mappings[foreach.as_] = target_runnable
# Process foreach statements
for fe2 in foreach.for_eachs:
#print fe2.toxml()
target_array2 = runnable.resolve_path(fe2.instances)
for target_runnable2 in target_array2:
name_mappings[fe2.as_] = target_runnable2
self.build_foreach(component, runnable, fe2, name_mappings)
# Process event connections
for ec in foreach.event_connections:
source = name_mappings[ec.from_]
target = name_mappings[ec.to]
source_port = ec.source_port
target_port = ec.target_port
if not source_port:
if len(source.event_out_ports) == 1:
source_port = source.event_out_ports[0]
else:
raise SimBuildError(("No source event port "
"uniquely identifiable"
" in '{0}'").format(source.id))
if not target_port:
if len(target.event_in_ports) == 1:
target_port = target.event_in_ports[0]
else:
raise SimBuildError(("No destination event port "
"uniquely identifiable "
"in '{0}'").format(target))
if self.debug: print("register_event_out_callback\n Source: %s, %s (port: %s) \n -> %s, %s (port: %s)"%(source, id(source), source_port, target, id(target), target_port))
source.register_event_out_callback(\
source_port, lambda: target.inc_event_in(target_port)) | [
"def",
"build_foreach",
"(",
"self",
",",
"component",
",",
"runnable",
",",
"foreach",
",",
"name_mappings",
"=",
"{",
"}",
")",
":",
"if",
"self",
".",
"debug",
":",
"print",
"(",
"\"\\n++++++++ Calling build_foreach of %s with runnable %s, parent %s, name_mappings: %s\"",
"%",
"(",
"component",
".",
"id",
",",
"runnable",
".",
"id",
",",
"runnable",
".",
"parent",
",",
"name_mappings",
")",
")",
"target_array",
"=",
"runnable",
".",
"resolve_path",
"(",
"foreach",
".",
"instances",
")",
"for",
"target_runnable",
"in",
"target_array",
":",
"if",
"self",
".",
"debug",
":",
"print",
"(",
"\"Applying contents of for_each to %s, as %s\"",
"%",
"(",
"target_runnable",
".",
"id",
",",
"foreach",
".",
"as_",
")",
")",
"name_mappings",
"[",
"foreach",
".",
"as_",
"]",
"=",
"target_runnable",
"# Process foreach statements",
"for",
"fe2",
"in",
"foreach",
".",
"for_eachs",
":",
"#print fe2.toxml()",
"target_array2",
"=",
"runnable",
".",
"resolve_path",
"(",
"fe2",
".",
"instances",
")",
"for",
"target_runnable2",
"in",
"target_array2",
":",
"name_mappings",
"[",
"fe2",
".",
"as_",
"]",
"=",
"target_runnable2",
"self",
".",
"build_foreach",
"(",
"component",
",",
"runnable",
",",
"fe2",
",",
"name_mappings",
")",
"# Process event connections",
"for",
"ec",
"in",
"foreach",
".",
"event_connections",
":",
"source",
"=",
"name_mappings",
"[",
"ec",
".",
"from_",
"]",
"target",
"=",
"name_mappings",
"[",
"ec",
".",
"to",
"]",
"source_port",
"=",
"ec",
".",
"source_port",
"target_port",
"=",
"ec",
".",
"target_port",
"if",
"not",
"source_port",
":",
"if",
"len",
"(",
"source",
".",
"event_out_ports",
")",
"==",
"1",
":",
"source_port",
"=",
"source",
".",
"event_out_ports",
"[",
"0",
"]",
"else",
":",
"raise",
"SimBuildError",
"(",
"(",
"\"No source event port \"",
"\"uniquely identifiable\"",
"\" in '{0}'\"",
")",
".",
"format",
"(",
"source",
".",
"id",
")",
")",
"if",
"not",
"target_port",
":",
"if",
"len",
"(",
"target",
".",
"event_in_ports",
")",
"==",
"1",
":",
"target_port",
"=",
"target",
".",
"event_in_ports",
"[",
"0",
"]",
"else",
":",
"raise",
"SimBuildError",
"(",
"(",
"\"No destination event port \"",
"\"uniquely identifiable \"",
"\"in '{0}'\"",
")",
".",
"format",
"(",
"target",
")",
")",
"if",
"self",
".",
"debug",
":",
"print",
"(",
"\"register_event_out_callback\\n Source: %s, %s (port: %s) \\n -> %s, %s (port: %s)\"",
"%",
"(",
"source",
",",
"id",
"(",
"source",
")",
",",
"source_port",
",",
"target",
",",
"id",
"(",
"target",
")",
",",
"target_port",
")",
")",
"source",
".",
"register_event_out_callback",
"(",
"source_port",
",",
"lambda",
":",
"target",
".",
"inc_event_in",
"(",
"target_port",
")",
")"
] | Iterate over ForEach constructs and process nested elements.
@param component: Component model containing structure specifications.
@type component: lems.model.component.FatComponent
@param runnable: Runnable component to which structure is to be added.
@type runnable: lems.sim.runnable.Runnable
@param foreach: The ForEach structure object to be used to add
structure code in the runnable component.
@type foreach: lems.model.structure.ForEach | [
"Iterate",
"over",
"ForEach",
"constructs",
"and",
"process",
"nested",
"elements",
"."
] | 4eeb719d2f23650fe16c38626663b69b5c83818b | https://github.com/LEMS/pylems/blob/4eeb719d2f23650fe16c38626663b69b5c83818b/lems/sim/build.py#L338-L394 | train |
LEMS/pylems | lems/sim/build.py | SimulationBuilder.process_simulation_specs | def process_simulation_specs(self, component, runnable, simulation):
"""
Process simulation-related aspects to a runnable component based on the
dynamics specifications in the component model.
@param component: Component model containing dynamics specifications.
@type component: lems.model.component.FatComponent
@param runnable: Runnable component to which dynamics is to be added.
@type runnable: lems.sim.runnable.Runnable
@param simulation: The simulation-related aspects to be implemented
in the runnable component.
@type simulation: lems.model.simulation.Simulation
@raise SimBuildError: Raised when a time derivative expression refers
to an undefined variable
@raise SimBuildError: Raised when there are invalid time
specifications for the <Run> statement.
@raise SimBuildError: Raised when the component reference for <Run>
cannot be resolved.
"""
# Process runs
for run in simulation.runs:
cid = run.component.id + '_' + component.id
target = self.build_runnable(run.component, runnable, cid)
self.sim.add_runnable(target)
self.current_record_target = target
target.configure_time(run.increment,
run.total) | python | def process_simulation_specs(self, component, runnable, simulation):
"""
Process simulation-related aspects to a runnable component based on the
dynamics specifications in the component model.
@param component: Component model containing dynamics specifications.
@type component: lems.model.component.FatComponent
@param runnable: Runnable component to which dynamics is to be added.
@type runnable: lems.sim.runnable.Runnable
@param simulation: The simulation-related aspects to be implemented
in the runnable component.
@type simulation: lems.model.simulation.Simulation
@raise SimBuildError: Raised when a time derivative expression refers
to an undefined variable
@raise SimBuildError: Raised when there are invalid time
specifications for the <Run> statement.
@raise SimBuildError: Raised when the component reference for <Run>
cannot be resolved.
"""
# Process runs
for run in simulation.runs:
cid = run.component.id + '_' + component.id
target = self.build_runnable(run.component, runnable, cid)
self.sim.add_runnable(target)
self.current_record_target = target
target.configure_time(run.increment,
run.total) | [
"def",
"process_simulation_specs",
"(",
"self",
",",
"component",
",",
"runnable",
",",
"simulation",
")",
":",
"# Process runs",
"for",
"run",
"in",
"simulation",
".",
"runs",
":",
"cid",
"=",
"run",
".",
"component",
".",
"id",
"+",
"'_'",
"+",
"component",
".",
"id",
"target",
"=",
"self",
".",
"build_runnable",
"(",
"run",
".",
"component",
",",
"runnable",
",",
"cid",
")",
"self",
".",
"sim",
".",
"add_runnable",
"(",
"target",
")",
"self",
".",
"current_record_target",
"=",
"target",
"target",
".",
"configure_time",
"(",
"run",
".",
"increment",
",",
"run",
".",
"total",
")"
] | Process simulation-related aspects to a runnable component based on the
dynamics specifications in the component model.
@param component: Component model containing dynamics specifications.
@type component: lems.model.component.FatComponent
@param runnable: Runnable component to which dynamics is to be added.
@type runnable: lems.sim.runnable.Runnable
@param simulation: The simulation-related aspects to be implemented
in the runnable component.
@type simulation: lems.model.simulation.Simulation
@raise SimBuildError: Raised when a time derivative expression refers
to an undefined variable
@raise SimBuildError: Raised when there are invalid time
specifications for the <Run> statement.
@raise SimBuildError: Raised when the component reference for <Run>
cannot be resolved. | [
"Process",
"simulation",
"-",
"related",
"aspects",
"to",
"a",
"runnable",
"component",
"based",
"on",
"the",
"dynamics",
"specifications",
"in",
"the",
"component",
"model",
"."
] | 4eeb719d2f23650fe16c38626663b69b5c83818b | https://github.com/LEMS/pylems/blob/4eeb719d2f23650fe16c38626663b69b5c83818b/lems/sim/build.py#L606-L640 | train |
LEMS/pylems | lems/sim/build.py | SimulationBuilder.build_expression_from_tree | def build_expression_from_tree(self, runnable, regime, tree_node):
"""
Recursively builds a Python expression from a parsed expression tree.
@param runnable: Runnable object to which this expression would be added.
@type runnable: lems.sim.runnable.Runnable
@param regime: Dynamics regime being built.
@type regime: lems.model.dynamics.Regime
@param tree_node: Root node for the tree from which the expression
is to be built.
@type tree_node: lems.parser.expr.ExprNode
@return: Generated Python expression.
@rtype: string
"""
component_type = self.model.component_types[runnable.component.type]
dynamics = component_type.dynamics
if tree_node.type == ExprNode.VALUE:
if tree_node.value[0].isalpha():
if tree_node.value == 't':
return 'self.time_completed'
elif tree_node.value in component_type.requirements:
var_prefix = 'self'
v = tree_node.value
r = runnable
while (v not in r.instance_variables and
v not in r.derived_variables):
var_prefix = '{0}.{1}'.format(var_prefix, 'parent')
r = r.parent
if r == None:
raise SimBuildError("Unable to resolve required "
"variable '{0}'".format(v))
return '{0}.{1}'.format(var_prefix, v)
elif (tree_node.value in dynamics.derived_variables or (regime is not None and tree_node.value in regime.derived_variables)):
return 'self.{0}'.format(tree_node.value)
else:
return 'self.{0}_shadow'.format(tree_node.value)
else:
return tree_node.value
elif tree_node.type == ExprNode.FUNC1:
pattern = '({0}({1}))'
func = self.convert_func(tree_node.func)
if 'random.uniform' in func:
pattern = '({0}(0,{1}))'
return pattern.format(\
func,
self.build_expression_from_tree(runnable,
regime,
tree_node.param))
else:
return '({0}) {1} ({2})'.format(\
self.build_expression_from_tree(runnable,
regime,
tree_node.left),
self.convert_op(tree_node.op),
self.build_expression_from_tree(runnable,
regime,
tree_node.right)) | python | def build_expression_from_tree(self, runnable, regime, tree_node):
"""
Recursively builds a Python expression from a parsed expression tree.
@param runnable: Runnable object to which this expression would be added.
@type runnable: lems.sim.runnable.Runnable
@param regime: Dynamics regime being built.
@type regime: lems.model.dynamics.Regime
@param tree_node: Root node for the tree from which the expression
is to be built.
@type tree_node: lems.parser.expr.ExprNode
@return: Generated Python expression.
@rtype: string
"""
component_type = self.model.component_types[runnable.component.type]
dynamics = component_type.dynamics
if tree_node.type == ExprNode.VALUE:
if tree_node.value[0].isalpha():
if tree_node.value == 't':
return 'self.time_completed'
elif tree_node.value in component_type.requirements:
var_prefix = 'self'
v = tree_node.value
r = runnable
while (v not in r.instance_variables and
v not in r.derived_variables):
var_prefix = '{0}.{1}'.format(var_prefix, 'parent')
r = r.parent
if r == None:
raise SimBuildError("Unable to resolve required "
"variable '{0}'".format(v))
return '{0}.{1}'.format(var_prefix, v)
elif (tree_node.value in dynamics.derived_variables or (regime is not None and tree_node.value in regime.derived_variables)):
return 'self.{0}'.format(tree_node.value)
else:
return 'self.{0}_shadow'.format(tree_node.value)
else:
return tree_node.value
elif tree_node.type == ExprNode.FUNC1:
pattern = '({0}({1}))'
func = self.convert_func(tree_node.func)
if 'random.uniform' in func:
pattern = '({0}(0,{1}))'
return pattern.format(\
func,
self.build_expression_from_tree(runnable,
regime,
tree_node.param))
else:
return '({0}) {1} ({2})'.format(\
self.build_expression_from_tree(runnable,
regime,
tree_node.left),
self.convert_op(tree_node.op),
self.build_expression_from_tree(runnable,
regime,
tree_node.right)) | [
"def",
"build_expression_from_tree",
"(",
"self",
",",
"runnable",
",",
"regime",
",",
"tree_node",
")",
":",
"component_type",
"=",
"self",
".",
"model",
".",
"component_types",
"[",
"runnable",
".",
"component",
".",
"type",
"]",
"dynamics",
"=",
"component_type",
".",
"dynamics",
"if",
"tree_node",
".",
"type",
"==",
"ExprNode",
".",
"VALUE",
":",
"if",
"tree_node",
".",
"value",
"[",
"0",
"]",
".",
"isalpha",
"(",
")",
":",
"if",
"tree_node",
".",
"value",
"==",
"'t'",
":",
"return",
"'self.time_completed'",
"elif",
"tree_node",
".",
"value",
"in",
"component_type",
".",
"requirements",
":",
"var_prefix",
"=",
"'self'",
"v",
"=",
"tree_node",
".",
"value",
"r",
"=",
"runnable",
"while",
"(",
"v",
"not",
"in",
"r",
".",
"instance_variables",
"and",
"v",
"not",
"in",
"r",
".",
"derived_variables",
")",
":",
"var_prefix",
"=",
"'{0}.{1}'",
".",
"format",
"(",
"var_prefix",
",",
"'parent'",
")",
"r",
"=",
"r",
".",
"parent",
"if",
"r",
"==",
"None",
":",
"raise",
"SimBuildError",
"(",
"\"Unable to resolve required \"",
"\"variable '{0}'\"",
".",
"format",
"(",
"v",
")",
")",
"return",
"'{0}.{1}'",
".",
"format",
"(",
"var_prefix",
",",
"v",
")",
"elif",
"(",
"tree_node",
".",
"value",
"in",
"dynamics",
".",
"derived_variables",
"or",
"(",
"regime",
"is",
"not",
"None",
"and",
"tree_node",
".",
"value",
"in",
"regime",
".",
"derived_variables",
")",
")",
":",
"return",
"'self.{0}'",
".",
"format",
"(",
"tree_node",
".",
"value",
")",
"else",
":",
"return",
"'self.{0}_shadow'",
".",
"format",
"(",
"tree_node",
".",
"value",
")",
"else",
":",
"return",
"tree_node",
".",
"value",
"elif",
"tree_node",
".",
"type",
"==",
"ExprNode",
".",
"FUNC1",
":",
"pattern",
"=",
"'({0}({1}))'",
"func",
"=",
"self",
".",
"convert_func",
"(",
"tree_node",
".",
"func",
")",
"if",
"'random.uniform'",
"in",
"func",
":",
"pattern",
"=",
"'({0}(0,{1}))'",
"return",
"pattern",
".",
"format",
"(",
"func",
",",
"self",
".",
"build_expression_from_tree",
"(",
"runnable",
",",
"regime",
",",
"tree_node",
".",
"param",
")",
")",
"else",
":",
"return",
"'({0}) {1} ({2})'",
".",
"format",
"(",
"self",
".",
"build_expression_from_tree",
"(",
"runnable",
",",
"regime",
",",
"tree_node",
".",
"left",
")",
",",
"self",
".",
"convert_op",
"(",
"tree_node",
".",
"op",
")",
",",
"self",
".",
"build_expression_from_tree",
"(",
"runnable",
",",
"regime",
",",
"tree_node",
".",
"right",
")",
")"
] | Recursively builds a Python expression from a parsed expression tree.
@param runnable: Runnable object to which this expression would be added.
@type runnable: lems.sim.runnable.Runnable
@param regime: Dynamics regime being built.
@type regime: lems.model.dynamics.Regime
@param tree_node: Root node for the tree from which the expression
is to be built.
@type tree_node: lems.parser.expr.ExprNode
@return: Generated Python expression.
@rtype: string | [
"Recursively",
"builds",
"a",
"Python",
"expression",
"from",
"a",
"parsed",
"expression",
"tree",
"."
] | 4eeb719d2f23650fe16c38626663b69b5c83818b | https://github.com/LEMS/pylems/blob/4eeb719d2f23650fe16c38626663b69b5c83818b/lems/sim/build.py#L703-L767 | train |
LEMS/pylems | lems/sim/build.py | SimulationBuilder.build_event_handler | def build_event_handler(self, runnable, regime, event_handler):
"""
Build event handler code.
@param event_handler: Event handler object
@type event_handler: lems.model.dynamics.EventHandler
@return: Generated event handler code.
@rtype: list(string)
"""
if isinstance(event_handler, OnCondition):
return self.build_on_condition(runnable, regime, event_handler)
elif isinstance(event_handler, OnEvent):
return self.build_on_event(runnable, regime, event_handler)
elif isinstance(event_handler, OnStart):
return self.build_on_start(runnable, regime, event_handler)
elif isinstance(event_handler, OnEntry):
return self.build_on_entry(runnable, regime, event_handler)
else:
return [] | python | def build_event_handler(self, runnable, regime, event_handler):
"""
Build event handler code.
@param event_handler: Event handler object
@type event_handler: lems.model.dynamics.EventHandler
@return: Generated event handler code.
@rtype: list(string)
"""
if isinstance(event_handler, OnCondition):
return self.build_on_condition(runnable, regime, event_handler)
elif isinstance(event_handler, OnEvent):
return self.build_on_event(runnable, regime, event_handler)
elif isinstance(event_handler, OnStart):
return self.build_on_start(runnable, regime, event_handler)
elif isinstance(event_handler, OnEntry):
return self.build_on_entry(runnable, regime, event_handler)
else:
return [] | [
"def",
"build_event_handler",
"(",
"self",
",",
"runnable",
",",
"regime",
",",
"event_handler",
")",
":",
"if",
"isinstance",
"(",
"event_handler",
",",
"OnCondition",
")",
":",
"return",
"self",
".",
"build_on_condition",
"(",
"runnable",
",",
"regime",
",",
"event_handler",
")",
"elif",
"isinstance",
"(",
"event_handler",
",",
"OnEvent",
")",
":",
"return",
"self",
".",
"build_on_event",
"(",
"runnable",
",",
"regime",
",",
"event_handler",
")",
"elif",
"isinstance",
"(",
"event_handler",
",",
"OnStart",
")",
":",
"return",
"self",
".",
"build_on_start",
"(",
"runnable",
",",
"regime",
",",
"event_handler",
")",
"elif",
"isinstance",
"(",
"event_handler",
",",
"OnEntry",
")",
":",
"return",
"self",
".",
"build_on_entry",
"(",
"runnable",
",",
"regime",
",",
"event_handler",
")",
"else",
":",
"return",
"[",
"]"
] | Build event handler code.
@param event_handler: Event handler object
@type event_handler: lems.model.dynamics.EventHandler
@return: Generated event handler code.
@rtype: list(string) | [
"Build",
"event",
"handler",
"code",
"."
] | 4eeb719d2f23650fe16c38626663b69b5c83818b | https://github.com/LEMS/pylems/blob/4eeb719d2f23650fe16c38626663b69b5c83818b/lems/sim/build.py#L769-L789 | train |
LEMS/pylems | lems/sim/build.py | SimulationBuilder.build_on_condition | def build_on_condition(self, runnable, regime, on_condition):
"""
Build OnCondition event handler code.
@param on_condition: OnCondition event handler object
@type on_condition: lems.model.dynamics.OnCondition
@return: Generated OnCondition code
@rtype: list(string)
"""
on_condition_code = []
on_condition_code += ['if {0}:'.format(\
self.build_expression_from_tree(runnable,
regime,
on_condition.expression_tree))]
for action in on_condition.actions:
code = self.build_action(runnable, regime, action)
for line in code:
on_condition_code += [' ' + line]
return on_condition_code | python | def build_on_condition(self, runnable, regime, on_condition):
"""
Build OnCondition event handler code.
@param on_condition: OnCondition event handler object
@type on_condition: lems.model.dynamics.OnCondition
@return: Generated OnCondition code
@rtype: list(string)
"""
on_condition_code = []
on_condition_code += ['if {0}:'.format(\
self.build_expression_from_tree(runnable,
regime,
on_condition.expression_tree))]
for action in on_condition.actions:
code = self.build_action(runnable, regime, action)
for line in code:
on_condition_code += [' ' + line]
return on_condition_code | [
"def",
"build_on_condition",
"(",
"self",
",",
"runnable",
",",
"regime",
",",
"on_condition",
")",
":",
"on_condition_code",
"=",
"[",
"]",
"on_condition_code",
"+=",
"[",
"'if {0}:'",
".",
"format",
"(",
"self",
".",
"build_expression_from_tree",
"(",
"runnable",
",",
"regime",
",",
"on_condition",
".",
"expression_tree",
")",
")",
"]",
"for",
"action",
"in",
"on_condition",
".",
"actions",
":",
"code",
"=",
"self",
".",
"build_action",
"(",
"runnable",
",",
"regime",
",",
"action",
")",
"for",
"line",
"in",
"code",
":",
"on_condition_code",
"+=",
"[",
"' '",
"+",
"line",
"]",
"return",
"on_condition_code"
] | Build OnCondition event handler code.
@param on_condition: OnCondition event handler object
@type on_condition: lems.model.dynamics.OnCondition
@return: Generated OnCondition code
@rtype: list(string) | [
"Build",
"OnCondition",
"event",
"handler",
"code",
"."
] | 4eeb719d2f23650fe16c38626663b69b5c83818b | https://github.com/LEMS/pylems/blob/4eeb719d2f23650fe16c38626663b69b5c83818b/lems/sim/build.py#L791-L814 | train |
LEMS/pylems | lems/sim/build.py | SimulationBuilder.build_on_event | def build_on_event(self, runnable, regime, on_event):
"""
Build OnEvent event handler code.
@param on_event: OnEvent event handler object
@type on_event: lems.model.dynamics.OnEvent
@return: Generated OnEvent code
@rtype: list(string)
"""
on_event_code = []
if self.debug: on_event_code += ['print("Maybe handling something for %s ("+str(id(self))+")")'%(runnable.id),
'print("EICs ("+str(id(self))+"): "+str(self.event_in_counters))']
on_event_code += ['count = self.event_in_counters[\'{0}\']'.\
format(on_event.port),
'while count > 0:',
' print(" Handling event")' if self.debug else '',
' count -= 1']
for action in on_event.actions:
code = self.build_action(runnable, regime, action)
for line in code:
on_event_code += [' ' + line]
on_event_code += ['self.event_in_counters[\'{0}\'] = 0'.\
format(on_event.port),]
return on_event_code | python | def build_on_event(self, runnable, regime, on_event):
"""
Build OnEvent event handler code.
@param on_event: OnEvent event handler object
@type on_event: lems.model.dynamics.OnEvent
@return: Generated OnEvent code
@rtype: list(string)
"""
on_event_code = []
if self.debug: on_event_code += ['print("Maybe handling something for %s ("+str(id(self))+")")'%(runnable.id),
'print("EICs ("+str(id(self))+"): "+str(self.event_in_counters))']
on_event_code += ['count = self.event_in_counters[\'{0}\']'.\
format(on_event.port),
'while count > 0:',
' print(" Handling event")' if self.debug else '',
' count -= 1']
for action in on_event.actions:
code = self.build_action(runnable, regime, action)
for line in code:
on_event_code += [' ' + line]
on_event_code += ['self.event_in_counters[\'{0}\'] = 0'.\
format(on_event.port),]
return on_event_code | [
"def",
"build_on_event",
"(",
"self",
",",
"runnable",
",",
"regime",
",",
"on_event",
")",
":",
"on_event_code",
"=",
"[",
"]",
"if",
"self",
".",
"debug",
":",
"on_event_code",
"+=",
"[",
"'print(\"Maybe handling something for %s (\"+str(id(self))+\")\")'",
"%",
"(",
"runnable",
".",
"id",
")",
",",
"'print(\"EICs (\"+str(id(self))+\"): \"+str(self.event_in_counters))'",
"]",
"on_event_code",
"+=",
"[",
"'count = self.event_in_counters[\\'{0}\\']'",
".",
"format",
"(",
"on_event",
".",
"port",
")",
",",
"'while count > 0:'",
",",
"' print(\" Handling event\")'",
"if",
"self",
".",
"debug",
"else",
"''",
",",
"' count -= 1'",
"]",
"for",
"action",
"in",
"on_event",
".",
"actions",
":",
"code",
"=",
"self",
".",
"build_action",
"(",
"runnable",
",",
"regime",
",",
"action",
")",
"for",
"line",
"in",
"code",
":",
"on_event_code",
"+=",
"[",
"' '",
"+",
"line",
"]",
"on_event_code",
"+=",
"[",
"'self.event_in_counters[\\'{0}\\'] = 0'",
".",
"format",
"(",
"on_event",
".",
"port",
")",
",",
"]",
"return",
"on_event_code"
] | Build OnEvent event handler code.
@param on_event: OnEvent event handler object
@type on_event: lems.model.dynamics.OnEvent
@return: Generated OnEvent code
@rtype: list(string) | [
"Build",
"OnEvent",
"event",
"handler",
"code",
"."
] | 4eeb719d2f23650fe16c38626663b69b5c83818b | https://github.com/LEMS/pylems/blob/4eeb719d2f23650fe16c38626663b69b5c83818b/lems/sim/build.py#L816-L844 | train |
LEMS/pylems | lems/sim/build.py | SimulationBuilder.build_on_start | def build_on_start(self, runnable, regime, on_start):
"""
Build OnStart start handler code.
@param on_start: OnStart start handler object
@type on_start: lems.model.dynamics.OnStart
@return: Generated OnStart code
@rtype: list(string)
"""
on_start_code = []
for action in on_start.actions:
code = self.build_action(runnable, regime, action)
for line in code:
on_start_code += [line]
return on_start_code | python | def build_on_start(self, runnable, regime, on_start):
"""
Build OnStart start handler code.
@param on_start: OnStart start handler object
@type on_start: lems.model.dynamics.OnStart
@return: Generated OnStart code
@rtype: list(string)
"""
on_start_code = []
for action in on_start.actions:
code = self.build_action(runnable, regime, action)
for line in code:
on_start_code += [line]
return on_start_code | [
"def",
"build_on_start",
"(",
"self",
",",
"runnable",
",",
"regime",
",",
"on_start",
")",
":",
"on_start_code",
"=",
"[",
"]",
"for",
"action",
"in",
"on_start",
".",
"actions",
":",
"code",
"=",
"self",
".",
"build_action",
"(",
"runnable",
",",
"regime",
",",
"action",
")",
"for",
"line",
"in",
"code",
":",
"on_start_code",
"+=",
"[",
"line",
"]",
"return",
"on_start_code"
] | Build OnStart start handler code.
@param on_start: OnStart start handler object
@type on_start: lems.model.dynamics.OnStart
@return: Generated OnStart code
@rtype: list(string) | [
"Build",
"OnStart",
"start",
"handler",
"code",
"."
] | 4eeb719d2f23650fe16c38626663b69b5c83818b | https://github.com/LEMS/pylems/blob/4eeb719d2f23650fe16c38626663b69b5c83818b/lems/sim/build.py#L846-L864 | train |
LEMS/pylems | lems/sim/build.py | SimulationBuilder.build_on_entry | def build_on_entry(self, runnable, regime, on_entry):
"""
Build OnEntry start handler code.
@param on_entry: OnEntry start handler object
@type on_entry: lems.model.dynamics.OnEntry
@return: Generated OnEntry code
@rtype: list(string)
"""
on_entry_code = []
on_entry_code += ['if self.current_regime != self.last_regime:']
on_entry_code += [' self.last_regime = self.current_regime']
for action in on_entry.actions:
code = self.build_action(runnable, regime, action)
for line in code:
on_entry_code += [' ' + line]
return on_entry_code | python | def build_on_entry(self, runnable, regime, on_entry):
"""
Build OnEntry start handler code.
@param on_entry: OnEntry start handler object
@type on_entry: lems.model.dynamics.OnEntry
@return: Generated OnEntry code
@rtype: list(string)
"""
on_entry_code = []
on_entry_code += ['if self.current_regime != self.last_regime:']
on_entry_code += [' self.last_regime = self.current_regime']
for action in on_entry.actions:
code = self.build_action(runnable, regime, action)
for line in code:
on_entry_code += [' ' + line]
return on_entry_code | [
"def",
"build_on_entry",
"(",
"self",
",",
"runnable",
",",
"regime",
",",
"on_entry",
")",
":",
"on_entry_code",
"=",
"[",
"]",
"on_entry_code",
"+=",
"[",
"'if self.current_regime != self.last_regime:'",
"]",
"on_entry_code",
"+=",
"[",
"' self.last_regime = self.current_regime'",
"]",
"for",
"action",
"in",
"on_entry",
".",
"actions",
":",
"code",
"=",
"self",
".",
"build_action",
"(",
"runnable",
",",
"regime",
",",
"action",
")",
"for",
"line",
"in",
"code",
":",
"on_entry_code",
"+=",
"[",
"' '",
"+",
"line",
"]",
"return",
"on_entry_code"
] | Build OnEntry start handler code.
@param on_entry: OnEntry start handler object
@type on_entry: lems.model.dynamics.OnEntry
@return: Generated OnEntry code
@rtype: list(string) | [
"Build",
"OnEntry",
"start",
"handler",
"code",
"."
] | 4eeb719d2f23650fe16c38626663b69b5c83818b | https://github.com/LEMS/pylems/blob/4eeb719d2f23650fe16c38626663b69b5c83818b/lems/sim/build.py#L866-L887 | train |
LEMS/pylems | lems/sim/build.py | SimulationBuilder.build_action | def build_action(self, runnable, regime, action):
"""
Build event handler action code.
@param action: Event handler action object
@type action: lems.model.dynamics.Action
@return: Generated action code
@rtype: string
"""
if isinstance(action, StateAssignment):
return self.build_state_assignment(runnable, regime, action)
if isinstance(action, EventOut):
return self.build_event_out(action)
if isinstance(action, Transition):
return self.build_transition(action)
else:
return ['pass'] | python | def build_action(self, runnable, regime, action):
"""
Build event handler action code.
@param action: Event handler action object
@type action: lems.model.dynamics.Action
@return: Generated action code
@rtype: string
"""
if isinstance(action, StateAssignment):
return self.build_state_assignment(runnable, regime, action)
if isinstance(action, EventOut):
return self.build_event_out(action)
if isinstance(action, Transition):
return self.build_transition(action)
else:
return ['pass'] | [
"def",
"build_action",
"(",
"self",
",",
"runnable",
",",
"regime",
",",
"action",
")",
":",
"if",
"isinstance",
"(",
"action",
",",
"StateAssignment",
")",
":",
"return",
"self",
".",
"build_state_assignment",
"(",
"runnable",
",",
"regime",
",",
"action",
")",
"if",
"isinstance",
"(",
"action",
",",
"EventOut",
")",
":",
"return",
"self",
".",
"build_event_out",
"(",
"action",
")",
"if",
"isinstance",
"(",
"action",
",",
"Transition",
")",
":",
"return",
"self",
".",
"build_transition",
"(",
"action",
")",
"else",
":",
"return",
"[",
"'pass'",
"]"
] | Build event handler action code.
@param action: Event handler action object
@type action: lems.model.dynamics.Action
@return: Generated action code
@rtype: string | [
"Build",
"event",
"handler",
"action",
"code",
"."
] | 4eeb719d2f23650fe16c38626663b69b5c83818b | https://github.com/LEMS/pylems/blob/4eeb719d2f23650fe16c38626663b69b5c83818b/lems/sim/build.py#L889-L907 | train |
LEMS/pylems | lems/sim/build.py | SimulationBuilder.build_state_assignment | def build_state_assignment(self, runnable, regime, state_assignment):
"""
Build state assignment code.
@param state_assignment: State assignment object
@type state_assignment: lems.model.dynamics.StateAssignment
@return: Generated state assignment code
@rtype: string
"""
return ['self.{0} = {1}'.format(\
state_assignment.variable,
self.build_expression_from_tree(runnable,
regime,
state_assignment.expression_tree))] | python | def build_state_assignment(self, runnable, regime, state_assignment):
"""
Build state assignment code.
@param state_assignment: State assignment object
@type state_assignment: lems.model.dynamics.StateAssignment
@return: Generated state assignment code
@rtype: string
"""
return ['self.{0} = {1}'.format(\
state_assignment.variable,
self.build_expression_from_tree(runnable,
regime,
state_assignment.expression_tree))] | [
"def",
"build_state_assignment",
"(",
"self",
",",
"runnable",
",",
"regime",
",",
"state_assignment",
")",
":",
"return",
"[",
"'self.{0} = {1}'",
".",
"format",
"(",
"state_assignment",
".",
"variable",
",",
"self",
".",
"build_expression_from_tree",
"(",
"runnable",
",",
"regime",
",",
"state_assignment",
".",
"expression_tree",
")",
")",
"]"
] | Build state assignment code.
@param state_assignment: State assignment object
@type state_assignment: lems.model.dynamics.StateAssignment
@return: Generated state assignment code
@rtype: string | [
"Build",
"state",
"assignment",
"code",
"."
] | 4eeb719d2f23650fe16c38626663b69b5c83818b | https://github.com/LEMS/pylems/blob/4eeb719d2f23650fe16c38626663b69b5c83818b/lems/sim/build.py#L909-L924 | train |
LEMS/pylems | lems/sim/build.py | SimulationBuilder.build_event_out | def build_event_out(self, event_out):
"""
Build event out code.
@param event_out: event out object
@type event_out: lems.model.dynamics.EventOut
@return: Generated event out code
@rtype: string
"""
event_out_code = ['if "{0}" in self.event_out_callbacks:'.format(event_out.port),
' for c in self.event_out_callbacks[\'{0}\']:'.format(event_out.port),
' c()']
return event_out_code | python | def build_event_out(self, event_out):
"""
Build event out code.
@param event_out: event out object
@type event_out: lems.model.dynamics.EventOut
@return: Generated event out code
@rtype: string
"""
event_out_code = ['if "{0}" in self.event_out_callbacks:'.format(event_out.port),
' for c in self.event_out_callbacks[\'{0}\']:'.format(event_out.port),
' c()']
return event_out_code | [
"def",
"build_event_out",
"(",
"self",
",",
"event_out",
")",
":",
"event_out_code",
"=",
"[",
"'if \"{0}\" in self.event_out_callbacks:'",
".",
"format",
"(",
"event_out",
".",
"port",
")",
",",
"' for c in self.event_out_callbacks[\\'{0}\\']:'",
".",
"format",
"(",
"event_out",
".",
"port",
")",
",",
"' c()'",
"]",
"return",
"event_out_code"
] | Build event out code.
@param event_out: event out object
@type event_out: lems.model.dynamics.EventOut
@return: Generated event out code
@rtype: string | [
"Build",
"event",
"out",
"code",
"."
] | 4eeb719d2f23650fe16c38626663b69b5c83818b | https://github.com/LEMS/pylems/blob/4eeb719d2f23650fe16c38626663b69b5c83818b/lems/sim/build.py#L926-L941 | train |
LEMS/pylems | lems/sim/build.py | SimulationBuilder.build_reduce_code | def build_reduce_code(self, result, select, reduce):
"""
Builds a reduce operation on the selected target range.
"""
select = select.replace('/', '.')
select = select.replace(' ', '')
if reduce == 'add':
reduce_op = '+'
acc_start = 0
else:
reduce_op = '*'
acc_start = 1
#bits = select.split('[*]')
bits = re.split('\[.*\]', select)
seps = re.findall('\[.*\]', select)
code = ['self.{0} = {1}'.format(result, acc_start)]
code += ['self.{0}_shadow = {1}'.format(result, acc_start)]
code += ['try:']
if len(bits) == 1:
target = select
code += [' self.{0} = self.{1}'.format(result, target)]
code += [' self.{0}_shadow = self.{1}'.format(result, target)]
elif len(bits) == 2:
sep = seps[0][1:-1]
if sep == '*':
array = bits[0]
ref = bits[1]
code += [' acc = {0}'.format(acc_start)]
code += [' for o in self.{0}:'.format(array)]
code += [' acc = acc {0} o{1}'.format(reduce_op, ref)]
code += [' self.{0} = acc'.format(result)]
code += [' self.{0}_shadow = acc'.format(result)]
else:
bits2 = sep.split('=')
if len(bits2) > 1:
array = bits[0]
ref = bits[1]
code += [' acc = {0}'.format(acc_start)]
code += [' for o in self.{0}:'.format(array)]
code += [' if o.{0} == {1}:'.format(bits2[0], bits2[1])]
code += [' acc = acc {0} o{1}'.format(reduce_op, ref)]
code += [' self.{0} = acc'.format(result)]
code += [' self.{0}_shadow = acc'.format(result)]
else:
raise SimbuildError("Invalid reduce target - '{0}'".format(select))
else:
raise SimbuildError("Invalid reduce target - '{0}'".format(select))
code += ['except:']
code += [' pass']
return code | python | def build_reduce_code(self, result, select, reduce):
"""
Builds a reduce operation on the selected target range.
"""
select = select.replace('/', '.')
select = select.replace(' ', '')
if reduce == 'add':
reduce_op = '+'
acc_start = 0
else:
reduce_op = '*'
acc_start = 1
#bits = select.split('[*]')
bits = re.split('\[.*\]', select)
seps = re.findall('\[.*\]', select)
code = ['self.{0} = {1}'.format(result, acc_start)]
code += ['self.{0}_shadow = {1}'.format(result, acc_start)]
code += ['try:']
if len(bits) == 1:
target = select
code += [' self.{0} = self.{1}'.format(result, target)]
code += [' self.{0}_shadow = self.{1}'.format(result, target)]
elif len(bits) == 2:
sep = seps[0][1:-1]
if sep == '*':
array = bits[0]
ref = bits[1]
code += [' acc = {0}'.format(acc_start)]
code += [' for o in self.{0}:'.format(array)]
code += [' acc = acc {0} o{1}'.format(reduce_op, ref)]
code += [' self.{0} = acc'.format(result)]
code += [' self.{0}_shadow = acc'.format(result)]
else:
bits2 = sep.split('=')
if len(bits2) > 1:
array = bits[0]
ref = bits[1]
code += [' acc = {0}'.format(acc_start)]
code += [' for o in self.{0}:'.format(array)]
code += [' if o.{0} == {1}:'.format(bits2[0], bits2[1])]
code += [' acc = acc {0} o{1}'.format(reduce_op, ref)]
code += [' self.{0} = acc'.format(result)]
code += [' self.{0}_shadow = acc'.format(result)]
else:
raise SimbuildError("Invalid reduce target - '{0}'".format(select))
else:
raise SimbuildError("Invalid reduce target - '{0}'".format(select))
code += ['except:']
code += [' pass']
return code | [
"def",
"build_reduce_code",
"(",
"self",
",",
"result",
",",
"select",
",",
"reduce",
")",
":",
"select",
"=",
"select",
".",
"replace",
"(",
"'/'",
",",
"'.'",
")",
"select",
"=",
"select",
".",
"replace",
"(",
"' '",
",",
"''",
")",
"if",
"reduce",
"==",
"'add'",
":",
"reduce_op",
"=",
"'+'",
"acc_start",
"=",
"0",
"else",
":",
"reduce_op",
"=",
"'*'",
"acc_start",
"=",
"1",
"#bits = select.split('[*]')",
"bits",
"=",
"re",
".",
"split",
"(",
"'\\[.*\\]'",
",",
"select",
")",
"seps",
"=",
"re",
".",
"findall",
"(",
"'\\[.*\\]'",
",",
"select",
")",
"code",
"=",
"[",
"'self.{0} = {1}'",
".",
"format",
"(",
"result",
",",
"acc_start",
")",
"]",
"code",
"+=",
"[",
"'self.{0}_shadow = {1}'",
".",
"format",
"(",
"result",
",",
"acc_start",
")",
"]",
"code",
"+=",
"[",
"'try:'",
"]",
"if",
"len",
"(",
"bits",
")",
"==",
"1",
":",
"target",
"=",
"select",
"code",
"+=",
"[",
"' self.{0} = self.{1}'",
".",
"format",
"(",
"result",
",",
"target",
")",
"]",
"code",
"+=",
"[",
"' self.{0}_shadow = self.{1}'",
".",
"format",
"(",
"result",
",",
"target",
")",
"]",
"elif",
"len",
"(",
"bits",
")",
"==",
"2",
":",
"sep",
"=",
"seps",
"[",
"0",
"]",
"[",
"1",
":",
"-",
"1",
"]",
"if",
"sep",
"==",
"'*'",
":",
"array",
"=",
"bits",
"[",
"0",
"]",
"ref",
"=",
"bits",
"[",
"1",
"]",
"code",
"+=",
"[",
"' acc = {0}'",
".",
"format",
"(",
"acc_start",
")",
"]",
"code",
"+=",
"[",
"' for o in self.{0}:'",
".",
"format",
"(",
"array",
")",
"]",
"code",
"+=",
"[",
"' acc = acc {0} o{1}'",
".",
"format",
"(",
"reduce_op",
",",
"ref",
")",
"]",
"code",
"+=",
"[",
"' self.{0} = acc'",
".",
"format",
"(",
"result",
")",
"]",
"code",
"+=",
"[",
"' self.{0}_shadow = acc'",
".",
"format",
"(",
"result",
")",
"]",
"else",
":",
"bits2",
"=",
"sep",
".",
"split",
"(",
"'='",
")",
"if",
"len",
"(",
"bits2",
")",
">",
"1",
":",
"array",
"=",
"bits",
"[",
"0",
"]",
"ref",
"=",
"bits",
"[",
"1",
"]",
"code",
"+=",
"[",
"' acc = {0}'",
".",
"format",
"(",
"acc_start",
")",
"]",
"code",
"+=",
"[",
"' for o in self.{0}:'",
".",
"format",
"(",
"array",
")",
"]",
"code",
"+=",
"[",
"' if o.{0} == {1}:'",
".",
"format",
"(",
"bits2",
"[",
"0",
"]",
",",
"bits2",
"[",
"1",
"]",
")",
"]",
"code",
"+=",
"[",
"' acc = acc {0} o{1}'",
".",
"format",
"(",
"reduce_op",
",",
"ref",
")",
"]",
"code",
"+=",
"[",
"' self.{0} = acc'",
".",
"format",
"(",
"result",
")",
"]",
"code",
"+=",
"[",
"' self.{0}_shadow = acc'",
".",
"format",
"(",
"result",
")",
"]",
"else",
":",
"raise",
"SimbuildError",
"(",
"\"Invalid reduce target - '{0}'\"",
".",
"format",
"(",
"select",
")",
")",
"else",
":",
"raise",
"SimbuildError",
"(",
"\"Invalid reduce target - '{0}'\"",
".",
"format",
"(",
"select",
")",
")",
"code",
"+=",
"[",
"'except:'",
"]",
"code",
"+=",
"[",
"' pass'",
"]",
"return",
"code"
] | Builds a reduce operation on the selected target range. | [
"Builds",
"a",
"reduce",
"operation",
"on",
"the",
"selected",
"target",
"range",
"."
] | 4eeb719d2f23650fe16c38626663b69b5c83818b | https://github.com/LEMS/pylems/blob/4eeb719d2f23650fe16c38626663b69b5c83818b/lems/sim/build.py#L956-L1015 | train |
LEMS/pylems | lems/sim/build.py | SimulationBuilder.add_recording_behavior | def add_recording_behavior(self, component, runnable):
"""
Adds recording-related dynamics to a runnable component based on
the dynamics specifications in the component model.
@param component: Component model containing dynamics specifications.
@type component: lems.model.component.FatComponent runnable: Runnable component to which dynamics is to be added.
@type runnable: lems.sim.runnable.Runnable
@raise SimBuildError: Raised when a target for recording could not be
found.
"""
simulation = component.simulation
for rec in simulation.records:
rec.id = runnable.id
self.current_record_target.add_variable_recorder(self.current_data_output, rec) | python | def add_recording_behavior(self, component, runnable):
"""
Adds recording-related dynamics to a runnable component based on
the dynamics specifications in the component model.
@param component: Component model containing dynamics specifications.
@type component: lems.model.component.FatComponent runnable: Runnable component to which dynamics is to be added.
@type runnable: lems.sim.runnable.Runnable
@raise SimBuildError: Raised when a target for recording could not be
found.
"""
simulation = component.simulation
for rec in simulation.records:
rec.id = runnable.id
self.current_record_target.add_variable_recorder(self.current_data_output, rec) | [
"def",
"add_recording_behavior",
"(",
"self",
",",
"component",
",",
"runnable",
")",
":",
"simulation",
"=",
"component",
".",
"simulation",
"for",
"rec",
"in",
"simulation",
".",
"records",
":",
"rec",
".",
"id",
"=",
"runnable",
".",
"id",
"self",
".",
"current_record_target",
".",
"add_variable_recorder",
"(",
"self",
".",
"current_data_output",
",",
"rec",
")"
] | Adds recording-related dynamics to a runnable component based on
the dynamics specifications in the component model.
@param component: Component model containing dynamics specifications.
@type component: lems.model.component.FatComponent runnable: Runnable component to which dynamics is to be added.
@type runnable: lems.sim.runnable.Runnable
@raise SimBuildError: Raised when a target for recording could not be
found. | [
"Adds",
"recording",
"-",
"related",
"dynamics",
"to",
"a",
"runnable",
"component",
"based",
"on",
"the",
"dynamics",
"specifications",
"in",
"the",
"component",
"model",
"."
] | 4eeb719d2f23650fe16c38626663b69b5c83818b | https://github.com/LEMS/pylems/blob/4eeb719d2f23650fe16c38626663b69b5c83818b/lems/sim/build.py#L1038-L1055 | train |
Erotemic/utool | utool/util_inspect.py | check_static_member_vars | def check_static_member_vars(class_, fpath=None, only_init=True):
"""
class_ can either be live object or a classname
# fpath = ut.truepath('~/code/ibeis/ibeis/viz/viz_graph2.py')
# classname = 'AnnotGraphWidget'
"""
#import ast
#import astor
import utool as ut
if isinstance(class_, six.string_types):
classname = class_
if fpath is None:
raise Exception('must specify fpath')
else:
# We were given a live object
if not isinstance(class_, type):
# We were given the class instance not the class
class_instance = class_
class_ = class_instance.__class__
classname = class_.__name__
if fpath is None:
module = ut.get_module_from_class(class_)
fpath = ut.get_modpath(module)
sourcecode = ut.readfrom(fpath)
import redbaron
# Pares a FULL syntax tree that keeps blockcomments
baron = redbaron.RedBaron(sourcecode)
for node in baron:
if node.type == 'class' and node.name == classname:
classnode = node
break
def find_parent_method(node):
par = node.parent_find('def')
if par is not None and par.parent is not None:
if par.parent.type == 'class':
return par
else:
return find_parent_method(par)
# TODO: Find inherited attrs
#classnode.inherit_from
# inhertied_attrs = ['parent']
# inhertied_attrs = []
class_methods = []
for node in classnode:
if node.type == 'def':
if only_init:
if node.name == '__init__':
class_methods.append(node)
else:
class_methods.append(node)
class_vars = []
self_vars = []
for method_node in class_methods:
self_var = method_node.arguments[0].dumps()
self_vars.append(self_var)
for assign in method_node.find_all('assignment'):
# method_node = find_parent_method(assign)
if assign.target.dumps().startswith(self_var + '.'):
class_vars.append(assign.target.value[1].dumps())
static_attrs = ut.unique(class_vars)
return static_attrs
# class_members = ut.unique(class_vars + class_methods + inhertied_attrs)
if False:
self_var = self_vars[0]
# Find everything that is used
complex_cases = []
simple_cases = []
all_self_ref = classnode.find_all(
'name_', value=re.compile('.*' + self_var + '\\.*'))
for x in all_self_ref:
if x.parent.type == 'def_argument':
continue
if x.parent.type == 'atomtrailers':
atom = x.parent
if ut.depth(atom.fst()) <= 3:
simple_cases.append(atom)
else:
complex_cases.append(atom)
#print(ut.depth(atom.value.data))
#print(atom.value)
#print(atom.dumps())
#if len(atom.dumps()) > 200:
# break
accessed_attrs = []
for x in simple_cases:
if x.value[0].dumps() == self_var:
attr = x.value[1].dumps()
accessed_attrs.append(attr)
accessed_attrs = ut.unique(accessed_attrs)
ut.setdiff(accessed_attrs, class_vars) | python | def check_static_member_vars(class_, fpath=None, only_init=True):
"""
class_ can either be live object or a classname
# fpath = ut.truepath('~/code/ibeis/ibeis/viz/viz_graph2.py')
# classname = 'AnnotGraphWidget'
"""
#import ast
#import astor
import utool as ut
if isinstance(class_, six.string_types):
classname = class_
if fpath is None:
raise Exception('must specify fpath')
else:
# We were given a live object
if not isinstance(class_, type):
# We were given the class instance not the class
class_instance = class_
class_ = class_instance.__class__
classname = class_.__name__
if fpath is None:
module = ut.get_module_from_class(class_)
fpath = ut.get_modpath(module)
sourcecode = ut.readfrom(fpath)
import redbaron
# Pares a FULL syntax tree that keeps blockcomments
baron = redbaron.RedBaron(sourcecode)
for node in baron:
if node.type == 'class' and node.name == classname:
classnode = node
break
def find_parent_method(node):
par = node.parent_find('def')
if par is not None and par.parent is not None:
if par.parent.type == 'class':
return par
else:
return find_parent_method(par)
# TODO: Find inherited attrs
#classnode.inherit_from
# inhertied_attrs = ['parent']
# inhertied_attrs = []
class_methods = []
for node in classnode:
if node.type == 'def':
if only_init:
if node.name == '__init__':
class_methods.append(node)
else:
class_methods.append(node)
class_vars = []
self_vars = []
for method_node in class_methods:
self_var = method_node.arguments[0].dumps()
self_vars.append(self_var)
for assign in method_node.find_all('assignment'):
# method_node = find_parent_method(assign)
if assign.target.dumps().startswith(self_var + '.'):
class_vars.append(assign.target.value[1].dumps())
static_attrs = ut.unique(class_vars)
return static_attrs
# class_members = ut.unique(class_vars + class_methods + inhertied_attrs)
if False:
self_var = self_vars[0]
# Find everything that is used
complex_cases = []
simple_cases = []
all_self_ref = classnode.find_all(
'name_', value=re.compile('.*' + self_var + '\\.*'))
for x in all_self_ref:
if x.parent.type == 'def_argument':
continue
if x.parent.type == 'atomtrailers':
atom = x.parent
if ut.depth(atom.fst()) <= 3:
simple_cases.append(atom)
else:
complex_cases.append(atom)
#print(ut.depth(atom.value.data))
#print(atom.value)
#print(atom.dumps())
#if len(atom.dumps()) > 200:
# break
accessed_attrs = []
for x in simple_cases:
if x.value[0].dumps() == self_var:
attr = x.value[1].dumps()
accessed_attrs.append(attr)
accessed_attrs = ut.unique(accessed_attrs)
ut.setdiff(accessed_attrs, class_vars) | [
"def",
"check_static_member_vars",
"(",
"class_",
",",
"fpath",
"=",
"None",
",",
"only_init",
"=",
"True",
")",
":",
"#import ast",
"#import astor",
"import",
"utool",
"as",
"ut",
"if",
"isinstance",
"(",
"class_",
",",
"six",
".",
"string_types",
")",
":",
"classname",
"=",
"class_",
"if",
"fpath",
"is",
"None",
":",
"raise",
"Exception",
"(",
"'must specify fpath'",
")",
"else",
":",
"# We were given a live object",
"if",
"not",
"isinstance",
"(",
"class_",
",",
"type",
")",
":",
"# We were given the class instance not the class",
"class_instance",
"=",
"class_",
"class_",
"=",
"class_instance",
".",
"__class__",
"classname",
"=",
"class_",
".",
"__name__",
"if",
"fpath",
"is",
"None",
":",
"module",
"=",
"ut",
".",
"get_module_from_class",
"(",
"class_",
")",
"fpath",
"=",
"ut",
".",
"get_modpath",
"(",
"module",
")",
"sourcecode",
"=",
"ut",
".",
"readfrom",
"(",
"fpath",
")",
"import",
"redbaron",
"# Pares a FULL syntax tree that keeps blockcomments",
"baron",
"=",
"redbaron",
".",
"RedBaron",
"(",
"sourcecode",
")",
"for",
"node",
"in",
"baron",
":",
"if",
"node",
".",
"type",
"==",
"'class'",
"and",
"node",
".",
"name",
"==",
"classname",
":",
"classnode",
"=",
"node",
"break",
"def",
"find_parent_method",
"(",
"node",
")",
":",
"par",
"=",
"node",
".",
"parent_find",
"(",
"'def'",
")",
"if",
"par",
"is",
"not",
"None",
"and",
"par",
".",
"parent",
"is",
"not",
"None",
":",
"if",
"par",
".",
"parent",
".",
"type",
"==",
"'class'",
":",
"return",
"par",
"else",
":",
"return",
"find_parent_method",
"(",
"par",
")",
"# TODO: Find inherited attrs",
"#classnode.inherit_from",
"# inhertied_attrs = ['parent']",
"# inhertied_attrs = []",
"class_methods",
"=",
"[",
"]",
"for",
"node",
"in",
"classnode",
":",
"if",
"node",
".",
"type",
"==",
"'def'",
":",
"if",
"only_init",
":",
"if",
"node",
".",
"name",
"==",
"'__init__'",
":",
"class_methods",
".",
"append",
"(",
"node",
")",
"else",
":",
"class_methods",
".",
"append",
"(",
"node",
")",
"class_vars",
"=",
"[",
"]",
"self_vars",
"=",
"[",
"]",
"for",
"method_node",
"in",
"class_methods",
":",
"self_var",
"=",
"method_node",
".",
"arguments",
"[",
"0",
"]",
".",
"dumps",
"(",
")",
"self_vars",
".",
"append",
"(",
"self_var",
")",
"for",
"assign",
"in",
"method_node",
".",
"find_all",
"(",
"'assignment'",
")",
":",
"# method_node = find_parent_method(assign)",
"if",
"assign",
".",
"target",
".",
"dumps",
"(",
")",
".",
"startswith",
"(",
"self_var",
"+",
"'.'",
")",
":",
"class_vars",
".",
"append",
"(",
"assign",
".",
"target",
".",
"value",
"[",
"1",
"]",
".",
"dumps",
"(",
")",
")",
"static_attrs",
"=",
"ut",
".",
"unique",
"(",
"class_vars",
")",
"return",
"static_attrs",
"# class_members = ut.unique(class_vars + class_methods + inhertied_attrs)",
"if",
"False",
":",
"self_var",
"=",
"self_vars",
"[",
"0",
"]",
"# Find everything that is used",
"complex_cases",
"=",
"[",
"]",
"simple_cases",
"=",
"[",
"]",
"all_self_ref",
"=",
"classnode",
".",
"find_all",
"(",
"'name_'",
",",
"value",
"=",
"re",
".",
"compile",
"(",
"'.*'",
"+",
"self_var",
"+",
"'\\\\.*'",
")",
")",
"for",
"x",
"in",
"all_self_ref",
":",
"if",
"x",
".",
"parent",
".",
"type",
"==",
"'def_argument'",
":",
"continue",
"if",
"x",
".",
"parent",
".",
"type",
"==",
"'atomtrailers'",
":",
"atom",
"=",
"x",
".",
"parent",
"if",
"ut",
".",
"depth",
"(",
"atom",
".",
"fst",
"(",
")",
")",
"<=",
"3",
":",
"simple_cases",
".",
"append",
"(",
"atom",
")",
"else",
":",
"complex_cases",
".",
"append",
"(",
"atom",
")",
"#print(ut.depth(atom.value.data))",
"#print(atom.value)",
"#print(atom.dumps())",
"#if len(atom.dumps()) > 200:",
"# break",
"accessed_attrs",
"=",
"[",
"]",
"for",
"x",
"in",
"simple_cases",
":",
"if",
"x",
".",
"value",
"[",
"0",
"]",
".",
"dumps",
"(",
")",
"==",
"self_var",
":",
"attr",
"=",
"x",
".",
"value",
"[",
"1",
"]",
".",
"dumps",
"(",
")",
"accessed_attrs",
".",
"append",
"(",
"attr",
")",
"accessed_attrs",
"=",
"ut",
".",
"unique",
"(",
"accessed_attrs",
")",
"ut",
".",
"setdiff",
"(",
"accessed_attrs",
",",
"class_vars",
")"
] | class_ can either be live object or a classname
# fpath = ut.truepath('~/code/ibeis/ibeis/viz/viz_graph2.py')
# classname = 'AnnotGraphWidget' | [
"class_",
"can",
"either",
"be",
"live",
"object",
"or",
"a",
"classname"
] | 3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a | https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/util_inspect.py#L194-L296 | train |
Erotemic/utool | utool/util_inspect.py | get_funcnames_from_modpath | def get_funcnames_from_modpath(modpath, include_methods=True):
"""
Get all functions defined in module
"""
import utool as ut
if True:
import jedi
source = ut.read_from(modpath)
#script = jedi.Script(source=source, source_path=modpath, line=source.count('\n') + 1)
definition_list = jedi.names(source)
funcname_list = [definition.name for definition in definition_list if definition.type == 'function']
if include_methods:
classdef_list = [definition for definition in definition_list if definition.type == 'class']
defined_methods = ut.flatten([definition.defined_names() for definition in classdef_list])
funcname_list += [method.name for method in defined_methods
if method.type == 'function' and not method.name.startswith('_')]
else:
import redbaron
# Pares a FULL syntax tree that keeps blockcomments
sourcecode = ut.read_from(modpath)
baron = redbaron.RedBaron(sourcecode)
funcname_list = [node.name for node in baron.find_all('def', recursive=include_methods)
if not node.name.startswith('_')]
return funcname_list | python | def get_funcnames_from_modpath(modpath, include_methods=True):
"""
Get all functions defined in module
"""
import utool as ut
if True:
import jedi
source = ut.read_from(modpath)
#script = jedi.Script(source=source, source_path=modpath, line=source.count('\n') + 1)
definition_list = jedi.names(source)
funcname_list = [definition.name for definition in definition_list if definition.type == 'function']
if include_methods:
classdef_list = [definition for definition in definition_list if definition.type == 'class']
defined_methods = ut.flatten([definition.defined_names() for definition in classdef_list])
funcname_list += [method.name for method in defined_methods
if method.type == 'function' and not method.name.startswith('_')]
else:
import redbaron
# Pares a FULL syntax tree that keeps blockcomments
sourcecode = ut.read_from(modpath)
baron = redbaron.RedBaron(sourcecode)
funcname_list = [node.name for node in baron.find_all('def', recursive=include_methods)
if not node.name.startswith('_')]
return funcname_list | [
"def",
"get_funcnames_from_modpath",
"(",
"modpath",
",",
"include_methods",
"=",
"True",
")",
":",
"import",
"utool",
"as",
"ut",
"if",
"True",
":",
"import",
"jedi",
"source",
"=",
"ut",
".",
"read_from",
"(",
"modpath",
")",
"#script = jedi.Script(source=source, source_path=modpath, line=source.count('\\n') + 1)",
"definition_list",
"=",
"jedi",
".",
"names",
"(",
"source",
")",
"funcname_list",
"=",
"[",
"definition",
".",
"name",
"for",
"definition",
"in",
"definition_list",
"if",
"definition",
".",
"type",
"==",
"'function'",
"]",
"if",
"include_methods",
":",
"classdef_list",
"=",
"[",
"definition",
"for",
"definition",
"in",
"definition_list",
"if",
"definition",
".",
"type",
"==",
"'class'",
"]",
"defined_methods",
"=",
"ut",
".",
"flatten",
"(",
"[",
"definition",
".",
"defined_names",
"(",
")",
"for",
"definition",
"in",
"classdef_list",
"]",
")",
"funcname_list",
"+=",
"[",
"method",
".",
"name",
"for",
"method",
"in",
"defined_methods",
"if",
"method",
".",
"type",
"==",
"'function'",
"and",
"not",
"method",
".",
"name",
".",
"startswith",
"(",
"'_'",
")",
"]",
"else",
":",
"import",
"redbaron",
"# Pares a FULL syntax tree that keeps blockcomments",
"sourcecode",
"=",
"ut",
".",
"read_from",
"(",
"modpath",
")",
"baron",
"=",
"redbaron",
".",
"RedBaron",
"(",
"sourcecode",
")",
"funcname_list",
"=",
"[",
"node",
".",
"name",
"for",
"node",
"in",
"baron",
".",
"find_all",
"(",
"'def'",
",",
"recursive",
"=",
"include_methods",
")",
"if",
"not",
"node",
".",
"name",
".",
"startswith",
"(",
"'_'",
")",
"]",
"return",
"funcname_list"
] | Get all functions defined in module | [
"Get",
"all",
"functions",
"defined",
"in",
"module"
] | 3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a | https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/util_inspect.py#L311-L334 | train |
Erotemic/utool | utool/util_inspect.py | help_members | def help_members(obj, use_other=False):
r"""
Inspects members of a class
Args:
obj (class or module):
CommandLine:
python -m utool.util_inspect help_members
Example:
>>> # ENABLE_DOCTEST
>>> from utool.util_inspect import * # NOQA
>>> import utool as ut
>>> obj = ut.DynStruct
>>> result = help_members(obj)
>>> print(result)
"""
import utool as ut
attrnames = dir(obj)
attr_list = [getattr(obj, attrname) for attrname in attrnames]
attr_types = ut.lmap(ut.type_str, map(type, attr_list))
unique_types, groupxs = ut.group_indices(attr_types)
type_to_items = ut.dzip(unique_types, ut.apply_grouping(attr_list, groupxs))
type_to_itemname = ut.dzip(unique_types, ut.apply_grouping(attrnames, groupxs))
#if memtypes is None:
# memtypes = list(type_to_items.keys())
memtypes = ['instancemethod'] # , 'method-wrapper']
func_mems = ut.dict_subset(type_to_items, memtypes, [])
func_list = ut.flatten(func_mems.values())
defsig_list = []
num_unbound_args_list = []
num_args_list = []
for func in func_list:
#args = ut.get_func_argspec(func).args
argspec = ut.get_func_argspec(func)
args = argspec.args
unbound_args = get_unbound_args(argspec)
defsig = ut.func_defsig(func)
defsig_list.append(defsig)
num_unbound_args_list.append(len(unbound_args))
num_args_list.append(len(args))
group = ut.hierarchical_group_items(defsig_list, [num_unbound_args_list, num_args_list])
print(repr(obj))
print(ut.repr3(group, strvals=True))
if use_other:
other_mems = ut.delete_keys(type_to_items.copy(), memtypes)
other_mems_attrnames = ut.dict_subset(type_to_itemname, other_mems.keys())
named_other_attrs = ut.dict_union_combine(other_mems_attrnames, other_mems, lambda x, y: list(zip(x, y)))
print(ut.repr4(named_other_attrs, nl=2, strvals=True)) | python | def help_members(obj, use_other=False):
r"""
Inspects members of a class
Args:
obj (class or module):
CommandLine:
python -m utool.util_inspect help_members
Example:
>>> # ENABLE_DOCTEST
>>> from utool.util_inspect import * # NOQA
>>> import utool as ut
>>> obj = ut.DynStruct
>>> result = help_members(obj)
>>> print(result)
"""
import utool as ut
attrnames = dir(obj)
attr_list = [getattr(obj, attrname) for attrname in attrnames]
attr_types = ut.lmap(ut.type_str, map(type, attr_list))
unique_types, groupxs = ut.group_indices(attr_types)
type_to_items = ut.dzip(unique_types, ut.apply_grouping(attr_list, groupxs))
type_to_itemname = ut.dzip(unique_types, ut.apply_grouping(attrnames, groupxs))
#if memtypes is None:
# memtypes = list(type_to_items.keys())
memtypes = ['instancemethod'] # , 'method-wrapper']
func_mems = ut.dict_subset(type_to_items, memtypes, [])
func_list = ut.flatten(func_mems.values())
defsig_list = []
num_unbound_args_list = []
num_args_list = []
for func in func_list:
#args = ut.get_func_argspec(func).args
argspec = ut.get_func_argspec(func)
args = argspec.args
unbound_args = get_unbound_args(argspec)
defsig = ut.func_defsig(func)
defsig_list.append(defsig)
num_unbound_args_list.append(len(unbound_args))
num_args_list.append(len(args))
group = ut.hierarchical_group_items(defsig_list, [num_unbound_args_list, num_args_list])
print(repr(obj))
print(ut.repr3(group, strvals=True))
if use_other:
other_mems = ut.delete_keys(type_to_items.copy(), memtypes)
other_mems_attrnames = ut.dict_subset(type_to_itemname, other_mems.keys())
named_other_attrs = ut.dict_union_combine(other_mems_attrnames, other_mems, lambda x, y: list(zip(x, y)))
print(ut.repr4(named_other_attrs, nl=2, strvals=True)) | [
"def",
"help_members",
"(",
"obj",
",",
"use_other",
"=",
"False",
")",
":",
"import",
"utool",
"as",
"ut",
"attrnames",
"=",
"dir",
"(",
"obj",
")",
"attr_list",
"=",
"[",
"getattr",
"(",
"obj",
",",
"attrname",
")",
"for",
"attrname",
"in",
"attrnames",
"]",
"attr_types",
"=",
"ut",
".",
"lmap",
"(",
"ut",
".",
"type_str",
",",
"map",
"(",
"type",
",",
"attr_list",
")",
")",
"unique_types",
",",
"groupxs",
"=",
"ut",
".",
"group_indices",
"(",
"attr_types",
")",
"type_to_items",
"=",
"ut",
".",
"dzip",
"(",
"unique_types",
",",
"ut",
".",
"apply_grouping",
"(",
"attr_list",
",",
"groupxs",
")",
")",
"type_to_itemname",
"=",
"ut",
".",
"dzip",
"(",
"unique_types",
",",
"ut",
".",
"apply_grouping",
"(",
"attrnames",
",",
"groupxs",
")",
")",
"#if memtypes is None:",
"# memtypes = list(type_to_items.keys())",
"memtypes",
"=",
"[",
"'instancemethod'",
"]",
"# , 'method-wrapper']",
"func_mems",
"=",
"ut",
".",
"dict_subset",
"(",
"type_to_items",
",",
"memtypes",
",",
"[",
"]",
")",
"func_list",
"=",
"ut",
".",
"flatten",
"(",
"func_mems",
".",
"values",
"(",
")",
")",
"defsig_list",
"=",
"[",
"]",
"num_unbound_args_list",
"=",
"[",
"]",
"num_args_list",
"=",
"[",
"]",
"for",
"func",
"in",
"func_list",
":",
"#args = ut.get_func_argspec(func).args",
"argspec",
"=",
"ut",
".",
"get_func_argspec",
"(",
"func",
")",
"args",
"=",
"argspec",
".",
"args",
"unbound_args",
"=",
"get_unbound_args",
"(",
"argspec",
")",
"defsig",
"=",
"ut",
".",
"func_defsig",
"(",
"func",
")",
"defsig_list",
".",
"append",
"(",
"defsig",
")",
"num_unbound_args_list",
".",
"append",
"(",
"len",
"(",
"unbound_args",
")",
")",
"num_args_list",
".",
"append",
"(",
"len",
"(",
"args",
")",
")",
"group",
"=",
"ut",
".",
"hierarchical_group_items",
"(",
"defsig_list",
",",
"[",
"num_unbound_args_list",
",",
"num_args_list",
"]",
")",
"print",
"(",
"repr",
"(",
"obj",
")",
")",
"print",
"(",
"ut",
".",
"repr3",
"(",
"group",
",",
"strvals",
"=",
"True",
")",
")",
"if",
"use_other",
":",
"other_mems",
"=",
"ut",
".",
"delete_keys",
"(",
"type_to_items",
".",
"copy",
"(",
")",
",",
"memtypes",
")",
"other_mems_attrnames",
"=",
"ut",
".",
"dict_subset",
"(",
"type_to_itemname",
",",
"other_mems",
".",
"keys",
"(",
")",
")",
"named_other_attrs",
"=",
"ut",
".",
"dict_union_combine",
"(",
"other_mems_attrnames",
",",
"other_mems",
",",
"lambda",
"x",
",",
"y",
":",
"list",
"(",
"zip",
"(",
"x",
",",
"y",
")",
")",
")",
"print",
"(",
"ut",
".",
"repr4",
"(",
"named_other_attrs",
",",
"nl",
"=",
"2",
",",
"strvals",
"=",
"True",
")",
")"
] | r"""
Inspects members of a class
Args:
obj (class or module):
CommandLine:
python -m utool.util_inspect help_members
Example:
>>> # ENABLE_DOCTEST
>>> from utool.util_inspect import * # NOQA
>>> import utool as ut
>>> obj = ut.DynStruct
>>> result = help_members(obj)
>>> print(result) | [
"r",
"Inspects",
"members",
"of",
"a",
"class"
] | 3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a | https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/util_inspect.py#L569-L621 | train |
Erotemic/utool | utool/util_inspect.py | is_defined_by_module | def is_defined_by_module(item, module, parent=None):
"""
Check if item is directly defined by a module.
This check may be prone to errors.
"""
flag = False
if isinstance(item, types.ModuleType):
if not hasattr(item, '__file__'):
try:
# hack for cv2 and xfeatures2d
import utool as ut
name = ut.get_modname_from_modpath(module.__file__)
flag = name in str(item)
except:
flag = False
else:
item_modpath = os.path.realpath(dirname(item.__file__))
mod_fpath = module.__file__.replace('.pyc', '.py')
if not mod_fpath.endswith('__init__.py'):
flag = False
else:
modpath = os.path.realpath(dirname(mod_fpath))
modpath = modpath.replace('.pyc', '.py')
flag = item_modpath.startswith(modpath)
elif hasattr(item, '_utinfo'):
# Capture case where there is a utool wrapper
orig_func = item._utinfo['orig_func']
flag = is_defined_by_module(orig_func, module, parent)
else:
if isinstance(item, staticmethod):
# static methods are a wrapper around a function
item = item.__func__
try:
func_globals = meta_util_six.get_funcglobals(item)
func_module_name = func_globals['__name__']
if func_module_name == 'line_profiler':
valid_names = dir(module)
if parent is not None:
valid_names += dir(parent)
if item.func_name in valid_names:
# hack to prevent small names
#if len(item.func_name) > 8:
if len(item.func_name) > 6:
flag = True
elif func_module_name == module.__name__:
flag = True
except AttributeError:
if hasattr(item, '__module__'):
flag = item.__module__ == module.__name__
return flag | python | def is_defined_by_module(item, module, parent=None):
"""
Check if item is directly defined by a module.
This check may be prone to errors.
"""
flag = False
if isinstance(item, types.ModuleType):
if not hasattr(item, '__file__'):
try:
# hack for cv2 and xfeatures2d
import utool as ut
name = ut.get_modname_from_modpath(module.__file__)
flag = name in str(item)
except:
flag = False
else:
item_modpath = os.path.realpath(dirname(item.__file__))
mod_fpath = module.__file__.replace('.pyc', '.py')
if not mod_fpath.endswith('__init__.py'):
flag = False
else:
modpath = os.path.realpath(dirname(mod_fpath))
modpath = modpath.replace('.pyc', '.py')
flag = item_modpath.startswith(modpath)
elif hasattr(item, '_utinfo'):
# Capture case where there is a utool wrapper
orig_func = item._utinfo['orig_func']
flag = is_defined_by_module(orig_func, module, parent)
else:
if isinstance(item, staticmethod):
# static methods are a wrapper around a function
item = item.__func__
try:
func_globals = meta_util_six.get_funcglobals(item)
func_module_name = func_globals['__name__']
if func_module_name == 'line_profiler':
valid_names = dir(module)
if parent is not None:
valid_names += dir(parent)
if item.func_name in valid_names:
# hack to prevent small names
#if len(item.func_name) > 8:
if len(item.func_name) > 6:
flag = True
elif func_module_name == module.__name__:
flag = True
except AttributeError:
if hasattr(item, '__module__'):
flag = item.__module__ == module.__name__
return flag | [
"def",
"is_defined_by_module",
"(",
"item",
",",
"module",
",",
"parent",
"=",
"None",
")",
":",
"flag",
"=",
"False",
"if",
"isinstance",
"(",
"item",
",",
"types",
".",
"ModuleType",
")",
":",
"if",
"not",
"hasattr",
"(",
"item",
",",
"'__file__'",
")",
":",
"try",
":",
"# hack for cv2 and xfeatures2d",
"import",
"utool",
"as",
"ut",
"name",
"=",
"ut",
".",
"get_modname_from_modpath",
"(",
"module",
".",
"__file__",
")",
"flag",
"=",
"name",
"in",
"str",
"(",
"item",
")",
"except",
":",
"flag",
"=",
"False",
"else",
":",
"item_modpath",
"=",
"os",
".",
"path",
".",
"realpath",
"(",
"dirname",
"(",
"item",
".",
"__file__",
")",
")",
"mod_fpath",
"=",
"module",
".",
"__file__",
".",
"replace",
"(",
"'.pyc'",
",",
"'.py'",
")",
"if",
"not",
"mod_fpath",
".",
"endswith",
"(",
"'__init__.py'",
")",
":",
"flag",
"=",
"False",
"else",
":",
"modpath",
"=",
"os",
".",
"path",
".",
"realpath",
"(",
"dirname",
"(",
"mod_fpath",
")",
")",
"modpath",
"=",
"modpath",
".",
"replace",
"(",
"'.pyc'",
",",
"'.py'",
")",
"flag",
"=",
"item_modpath",
".",
"startswith",
"(",
"modpath",
")",
"elif",
"hasattr",
"(",
"item",
",",
"'_utinfo'",
")",
":",
"# Capture case where there is a utool wrapper",
"orig_func",
"=",
"item",
".",
"_utinfo",
"[",
"'orig_func'",
"]",
"flag",
"=",
"is_defined_by_module",
"(",
"orig_func",
",",
"module",
",",
"parent",
")",
"else",
":",
"if",
"isinstance",
"(",
"item",
",",
"staticmethod",
")",
":",
"# static methods are a wrapper around a function",
"item",
"=",
"item",
".",
"__func__",
"try",
":",
"func_globals",
"=",
"meta_util_six",
".",
"get_funcglobals",
"(",
"item",
")",
"func_module_name",
"=",
"func_globals",
"[",
"'__name__'",
"]",
"if",
"func_module_name",
"==",
"'line_profiler'",
":",
"valid_names",
"=",
"dir",
"(",
"module",
")",
"if",
"parent",
"is",
"not",
"None",
":",
"valid_names",
"+=",
"dir",
"(",
"parent",
")",
"if",
"item",
".",
"func_name",
"in",
"valid_names",
":",
"# hack to prevent small names",
"#if len(item.func_name) > 8:",
"if",
"len",
"(",
"item",
".",
"func_name",
")",
">",
"6",
":",
"flag",
"=",
"True",
"elif",
"func_module_name",
"==",
"module",
".",
"__name__",
":",
"flag",
"=",
"True",
"except",
"AttributeError",
":",
"if",
"hasattr",
"(",
"item",
",",
"'__module__'",
")",
":",
"flag",
"=",
"item",
".",
"__module__",
"==",
"module",
".",
"__name__",
"return",
"flag"
] | Check if item is directly defined by a module.
This check may be prone to errors. | [
"Check",
"if",
"item",
"is",
"directly",
"defined",
"by",
"a",
"module",
".",
"This",
"check",
"may",
"be",
"prone",
"to",
"errors",
"."
] | 3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a | https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/util_inspect.py#L1052-L1101 | train |
Erotemic/utool | utool/util_inspect.py | is_bateries_included | def is_bateries_included(item):
"""
Returns if a value is a python builtin function
Args:
item (object):
Returns:
bool: flag
References:
http://stackoverflow.com/questions/23149218/check-if-a-python-function-is-builtin
CommandLine:
python -m utool._internal.meta_util_six is_builtin
Example:
>>> # DISABLE_DOCTEST
>>> from utool._internal.meta_util_six import * # NOQA
>>> item = zip
>>> flag = is_bateries_included(item)
>>> result = ('flag = %s' % (str(flag),))
>>> print(result)
"""
flag = False
if hasattr(item, '__call__') and hasattr(item, '__module__'):
if item.__module__ is not None:
module = sys.modules[item.__module__]
if module == builtins:
flag = True
elif hasattr(module, '__file__'):
flag = LIB_PATH == dirname(module.__file__)
return flag | python | def is_bateries_included(item):
"""
Returns if a value is a python builtin function
Args:
item (object):
Returns:
bool: flag
References:
http://stackoverflow.com/questions/23149218/check-if-a-python-function-is-builtin
CommandLine:
python -m utool._internal.meta_util_six is_builtin
Example:
>>> # DISABLE_DOCTEST
>>> from utool._internal.meta_util_six import * # NOQA
>>> item = zip
>>> flag = is_bateries_included(item)
>>> result = ('flag = %s' % (str(flag),))
>>> print(result)
"""
flag = False
if hasattr(item, '__call__') and hasattr(item, '__module__'):
if item.__module__ is not None:
module = sys.modules[item.__module__]
if module == builtins:
flag = True
elif hasattr(module, '__file__'):
flag = LIB_PATH == dirname(module.__file__)
return flag | [
"def",
"is_bateries_included",
"(",
"item",
")",
":",
"flag",
"=",
"False",
"if",
"hasattr",
"(",
"item",
",",
"'__call__'",
")",
"and",
"hasattr",
"(",
"item",
",",
"'__module__'",
")",
":",
"if",
"item",
".",
"__module__",
"is",
"not",
"None",
":",
"module",
"=",
"sys",
".",
"modules",
"[",
"item",
".",
"__module__",
"]",
"if",
"module",
"==",
"builtins",
":",
"flag",
"=",
"True",
"elif",
"hasattr",
"(",
"module",
",",
"'__file__'",
")",
":",
"flag",
"=",
"LIB_PATH",
"==",
"dirname",
"(",
"module",
".",
"__file__",
")",
"return",
"flag"
] | Returns if a value is a python builtin function
Args:
item (object):
Returns:
bool: flag
References:
http://stackoverflow.com/questions/23149218/check-if-a-python-function-is-builtin
CommandLine:
python -m utool._internal.meta_util_six is_builtin
Example:
>>> # DISABLE_DOCTEST
>>> from utool._internal.meta_util_six import * # NOQA
>>> item = zip
>>> flag = is_bateries_included(item)
>>> result = ('flag = %s' % (str(flag),))
>>> print(result) | [
"Returns",
"if",
"a",
"value",
"is",
"a",
"python",
"builtin",
"function"
] | 3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a | https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/util_inspect.py#L1118-L1150 | train |
Erotemic/utool | utool/util_inspect.py | dummy_func | def dummy_func(arg1, arg2, arg3=None, arg4=[1, 2, 3], arg5={}, **kwargs):
"""
test func for kwargs parseing
"""
foo = kwargs.get('foo', None)
bar = kwargs.pop('bar', 4)
foo2 = kwargs['foo2']
foobar = str(foo) + str(bar) + str(foo2)
return foobar | python | def dummy_func(arg1, arg2, arg3=None, arg4=[1, 2, 3], arg5={}, **kwargs):
"""
test func for kwargs parseing
"""
foo = kwargs.get('foo', None)
bar = kwargs.pop('bar', 4)
foo2 = kwargs['foo2']
foobar = str(foo) + str(bar) + str(foo2)
return foobar | [
"def",
"dummy_func",
"(",
"arg1",
",",
"arg2",
",",
"arg3",
"=",
"None",
",",
"arg4",
"=",
"[",
"1",
",",
"2",
",",
"3",
"]",
",",
"arg5",
"=",
"{",
"}",
",",
"*",
"*",
"kwargs",
")",
":",
"foo",
"=",
"kwargs",
".",
"get",
"(",
"'foo'",
",",
"None",
")",
"bar",
"=",
"kwargs",
".",
"pop",
"(",
"'bar'",
",",
"4",
")",
"foo2",
"=",
"kwargs",
"[",
"'foo2'",
"]",
"foobar",
"=",
"str",
"(",
"foo",
")",
"+",
"str",
"(",
"bar",
")",
"+",
"str",
"(",
"foo2",
")",
"return",
"foobar"
] | test func for kwargs parseing | [
"test",
"func",
"for",
"kwargs",
"parseing"
] | 3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a | https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/util_inspect.py#L1261-L1269 | train |
Erotemic/utool | utool/util_inspect.py | get_docstr | def get_docstr(func_or_class):
""" Get the docstring from a live object """
import utool as ut
try:
docstr_ = func_or_class.func_doc
except AttributeError:
docstr_ = func_or_class.__doc__
if docstr_ is None:
docstr_ = ''
docstr = ut.unindent(docstr_)
return docstr | python | def get_docstr(func_or_class):
""" Get the docstring from a live object """
import utool as ut
try:
docstr_ = func_or_class.func_doc
except AttributeError:
docstr_ = func_or_class.__doc__
if docstr_ is None:
docstr_ = ''
docstr = ut.unindent(docstr_)
return docstr | [
"def",
"get_docstr",
"(",
"func_or_class",
")",
":",
"import",
"utool",
"as",
"ut",
"try",
":",
"docstr_",
"=",
"func_or_class",
".",
"func_doc",
"except",
"AttributeError",
":",
"docstr_",
"=",
"func_or_class",
".",
"__doc__",
"if",
"docstr_",
"is",
"None",
":",
"docstr_",
"=",
"''",
"docstr",
"=",
"ut",
".",
"unindent",
"(",
"docstr_",
")",
"return",
"docstr"
] | Get the docstring from a live object | [
"Get",
"the",
"docstring",
"from",
"a",
"live",
"object"
] | 3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a | https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/util_inspect.py#L1354-L1364 | train |
Erotemic/utool | utool/util_inspect.py | find_funcs_called_with_kwargs | def find_funcs_called_with_kwargs(sourcecode, target_kwargs_name='kwargs'):
r"""
Finds functions that are called with the keyword `kwargs` variable
CommandLine:
python3 -m utool.util_inspect find_funcs_called_with_kwargs
Example:
>>> # ENABLE_DOCTEST
>>> import utool as ut
>>> sourcecode = ut.codeblock(
'''
x, y = list(zip(*ut.ichunks(data, 2)))
somecall(arg1, arg2, arg3=4, **kwargs)
import sys
sys.badcall(**kwargs)
def foo():
bar(**kwargs)
ut.holymoly(**kwargs)
baz()
def biz(**kwargs):
foo2(**kwargs)
''')
>>> child_funcnamess = ut.find_funcs_called_with_kwargs(sourcecode)
>>> print('child_funcnamess = %r' % (child_funcnamess,))
>>> assert 'foo2' not in child_funcnamess, 'foo2 should not be found'
>>> assert 'bar' in child_funcnamess, 'bar should be found'
"""
import ast
sourcecode = 'from __future__ import print_function\n' + sourcecode
pt = ast.parse(sourcecode)
child_funcnamess = []
debug = False or VERYVERB_INSPECT
if debug:
print('\nInput:')
print('target_kwargs_name = %r' % (target_kwargs_name,))
print('\nSource:')
print(sourcecode)
import astor
print('\nParse:')
print(astor.dump(pt))
class KwargParseVisitor(ast.NodeVisitor):
"""
TODO: understand ut.update_existing and dict update
ie, know when kwargs is passed to these functions and
then look assume the object that was updated is a dictionary
and check wherever that is passed to kwargs as well.
"""
def visit_FunctionDef(self, node):
if debug:
print('\nVISIT FunctionDef node = %r' % (node,))
print('node.args.kwarg = %r' % (node.args.kwarg,))
if six.PY2:
kwarg_name = node.args.kwarg
else:
if node.args.kwarg is None:
kwarg_name = None
else:
kwarg_name = node.args.kwarg.arg
#import utool as ut
#ut.embed()
if kwarg_name != target_kwargs_name:
# target kwargs is still in scope
ast.NodeVisitor.generic_visit(self, node)
def visit_Call(self, node):
if debug:
print('\nVISIT Call node = %r' % (node,))
#print(ut.repr4(node.__dict__,))
if isinstance(node.func, ast.Attribute):
try:
funcname = node.func.value.id + '.' + node.func.attr
except AttributeError:
funcname = None
elif isinstance(node.func, ast.Name):
funcname = node.func.id
else:
raise NotImplementedError(
'do not know how to parse: node.func = %r' % (node.func,))
if six.PY2:
kwargs = node.kwargs
kwargs_name = None if kwargs is None else kwargs.id
if funcname is not None and kwargs_name == target_kwargs_name:
child_funcnamess.append(funcname)
if debug:
print('funcname = %r' % (funcname,))
print('kwargs_name = %r' % (kwargs_name,))
else:
if node.keywords:
for kwargs in node.keywords:
if kwargs.arg is None:
if hasattr(kwargs.value, 'id'):
kwargs_name = kwargs.value.id
if funcname is not None and kwargs_name == target_kwargs_name:
child_funcnamess.append(funcname)
if debug:
print('funcname = %r' % (funcname,))
print('kwargs_name = %r' % (kwargs_name,))
ast.NodeVisitor.generic_visit(self, node)
try:
KwargParseVisitor().visit(pt)
except Exception:
raise
pass
#import utool as ut
#if ut.SUPER_STRICT:
# raise
return child_funcnamess | python | def find_funcs_called_with_kwargs(sourcecode, target_kwargs_name='kwargs'):
r"""
Finds functions that are called with the keyword `kwargs` variable
CommandLine:
python3 -m utool.util_inspect find_funcs_called_with_kwargs
Example:
>>> # ENABLE_DOCTEST
>>> import utool as ut
>>> sourcecode = ut.codeblock(
'''
x, y = list(zip(*ut.ichunks(data, 2)))
somecall(arg1, arg2, arg3=4, **kwargs)
import sys
sys.badcall(**kwargs)
def foo():
bar(**kwargs)
ut.holymoly(**kwargs)
baz()
def biz(**kwargs):
foo2(**kwargs)
''')
>>> child_funcnamess = ut.find_funcs_called_with_kwargs(sourcecode)
>>> print('child_funcnamess = %r' % (child_funcnamess,))
>>> assert 'foo2' not in child_funcnamess, 'foo2 should not be found'
>>> assert 'bar' in child_funcnamess, 'bar should be found'
"""
import ast
sourcecode = 'from __future__ import print_function\n' + sourcecode
pt = ast.parse(sourcecode)
child_funcnamess = []
debug = False or VERYVERB_INSPECT
if debug:
print('\nInput:')
print('target_kwargs_name = %r' % (target_kwargs_name,))
print('\nSource:')
print(sourcecode)
import astor
print('\nParse:')
print(astor.dump(pt))
class KwargParseVisitor(ast.NodeVisitor):
"""
TODO: understand ut.update_existing and dict update
ie, know when kwargs is passed to these functions and
then look assume the object that was updated is a dictionary
and check wherever that is passed to kwargs as well.
"""
def visit_FunctionDef(self, node):
if debug:
print('\nVISIT FunctionDef node = %r' % (node,))
print('node.args.kwarg = %r' % (node.args.kwarg,))
if six.PY2:
kwarg_name = node.args.kwarg
else:
if node.args.kwarg is None:
kwarg_name = None
else:
kwarg_name = node.args.kwarg.arg
#import utool as ut
#ut.embed()
if kwarg_name != target_kwargs_name:
# target kwargs is still in scope
ast.NodeVisitor.generic_visit(self, node)
def visit_Call(self, node):
if debug:
print('\nVISIT Call node = %r' % (node,))
#print(ut.repr4(node.__dict__,))
if isinstance(node.func, ast.Attribute):
try:
funcname = node.func.value.id + '.' + node.func.attr
except AttributeError:
funcname = None
elif isinstance(node.func, ast.Name):
funcname = node.func.id
else:
raise NotImplementedError(
'do not know how to parse: node.func = %r' % (node.func,))
if six.PY2:
kwargs = node.kwargs
kwargs_name = None if kwargs is None else kwargs.id
if funcname is not None and kwargs_name == target_kwargs_name:
child_funcnamess.append(funcname)
if debug:
print('funcname = %r' % (funcname,))
print('kwargs_name = %r' % (kwargs_name,))
else:
if node.keywords:
for kwargs in node.keywords:
if kwargs.arg is None:
if hasattr(kwargs.value, 'id'):
kwargs_name = kwargs.value.id
if funcname is not None and kwargs_name == target_kwargs_name:
child_funcnamess.append(funcname)
if debug:
print('funcname = %r' % (funcname,))
print('kwargs_name = %r' % (kwargs_name,))
ast.NodeVisitor.generic_visit(self, node)
try:
KwargParseVisitor().visit(pt)
except Exception:
raise
pass
#import utool as ut
#if ut.SUPER_STRICT:
# raise
return child_funcnamess | [
"def",
"find_funcs_called_with_kwargs",
"(",
"sourcecode",
",",
"target_kwargs_name",
"=",
"'kwargs'",
")",
":",
"import",
"ast",
"sourcecode",
"=",
"'from __future__ import print_function\\n'",
"+",
"sourcecode",
"pt",
"=",
"ast",
".",
"parse",
"(",
"sourcecode",
")",
"child_funcnamess",
"=",
"[",
"]",
"debug",
"=",
"False",
"or",
"VERYVERB_INSPECT",
"if",
"debug",
":",
"print",
"(",
"'\\nInput:'",
")",
"print",
"(",
"'target_kwargs_name = %r'",
"%",
"(",
"target_kwargs_name",
",",
")",
")",
"print",
"(",
"'\\nSource:'",
")",
"print",
"(",
"sourcecode",
")",
"import",
"astor",
"print",
"(",
"'\\nParse:'",
")",
"print",
"(",
"astor",
".",
"dump",
"(",
"pt",
")",
")",
"class",
"KwargParseVisitor",
"(",
"ast",
".",
"NodeVisitor",
")",
":",
"\"\"\"\n TODO: understand ut.update_existing and dict update\n ie, know when kwargs is passed to these functions and\n then look assume the object that was updated is a dictionary\n and check wherever that is passed to kwargs as well.\n \"\"\"",
"def",
"visit_FunctionDef",
"(",
"self",
",",
"node",
")",
":",
"if",
"debug",
":",
"print",
"(",
"'\\nVISIT FunctionDef node = %r'",
"%",
"(",
"node",
",",
")",
")",
"print",
"(",
"'node.args.kwarg = %r'",
"%",
"(",
"node",
".",
"args",
".",
"kwarg",
",",
")",
")",
"if",
"six",
".",
"PY2",
":",
"kwarg_name",
"=",
"node",
".",
"args",
".",
"kwarg",
"else",
":",
"if",
"node",
".",
"args",
".",
"kwarg",
"is",
"None",
":",
"kwarg_name",
"=",
"None",
"else",
":",
"kwarg_name",
"=",
"node",
".",
"args",
".",
"kwarg",
".",
"arg",
"#import utool as ut",
"#ut.embed()",
"if",
"kwarg_name",
"!=",
"target_kwargs_name",
":",
"# target kwargs is still in scope",
"ast",
".",
"NodeVisitor",
".",
"generic_visit",
"(",
"self",
",",
"node",
")",
"def",
"visit_Call",
"(",
"self",
",",
"node",
")",
":",
"if",
"debug",
":",
"print",
"(",
"'\\nVISIT Call node = %r'",
"%",
"(",
"node",
",",
")",
")",
"#print(ut.repr4(node.__dict__,))",
"if",
"isinstance",
"(",
"node",
".",
"func",
",",
"ast",
".",
"Attribute",
")",
":",
"try",
":",
"funcname",
"=",
"node",
".",
"func",
".",
"value",
".",
"id",
"+",
"'.'",
"+",
"node",
".",
"func",
".",
"attr",
"except",
"AttributeError",
":",
"funcname",
"=",
"None",
"elif",
"isinstance",
"(",
"node",
".",
"func",
",",
"ast",
".",
"Name",
")",
":",
"funcname",
"=",
"node",
".",
"func",
".",
"id",
"else",
":",
"raise",
"NotImplementedError",
"(",
"'do not know how to parse: node.func = %r'",
"%",
"(",
"node",
".",
"func",
",",
")",
")",
"if",
"six",
".",
"PY2",
":",
"kwargs",
"=",
"node",
".",
"kwargs",
"kwargs_name",
"=",
"None",
"if",
"kwargs",
"is",
"None",
"else",
"kwargs",
".",
"id",
"if",
"funcname",
"is",
"not",
"None",
"and",
"kwargs_name",
"==",
"target_kwargs_name",
":",
"child_funcnamess",
".",
"append",
"(",
"funcname",
")",
"if",
"debug",
":",
"print",
"(",
"'funcname = %r'",
"%",
"(",
"funcname",
",",
")",
")",
"print",
"(",
"'kwargs_name = %r'",
"%",
"(",
"kwargs_name",
",",
")",
")",
"else",
":",
"if",
"node",
".",
"keywords",
":",
"for",
"kwargs",
"in",
"node",
".",
"keywords",
":",
"if",
"kwargs",
".",
"arg",
"is",
"None",
":",
"if",
"hasattr",
"(",
"kwargs",
".",
"value",
",",
"'id'",
")",
":",
"kwargs_name",
"=",
"kwargs",
".",
"value",
".",
"id",
"if",
"funcname",
"is",
"not",
"None",
"and",
"kwargs_name",
"==",
"target_kwargs_name",
":",
"child_funcnamess",
".",
"append",
"(",
"funcname",
")",
"if",
"debug",
":",
"print",
"(",
"'funcname = %r'",
"%",
"(",
"funcname",
",",
")",
")",
"print",
"(",
"'kwargs_name = %r'",
"%",
"(",
"kwargs_name",
",",
")",
")",
"ast",
".",
"NodeVisitor",
".",
"generic_visit",
"(",
"self",
",",
"node",
")",
"try",
":",
"KwargParseVisitor",
"(",
")",
".",
"visit",
"(",
"pt",
")",
"except",
"Exception",
":",
"raise",
"pass",
"#import utool as ut",
"#if ut.SUPER_STRICT:",
"# raise",
"return",
"child_funcnamess"
] | r"""
Finds functions that are called with the keyword `kwargs` variable
CommandLine:
python3 -m utool.util_inspect find_funcs_called_with_kwargs
Example:
>>> # ENABLE_DOCTEST
>>> import utool as ut
>>> sourcecode = ut.codeblock(
'''
x, y = list(zip(*ut.ichunks(data, 2)))
somecall(arg1, arg2, arg3=4, **kwargs)
import sys
sys.badcall(**kwargs)
def foo():
bar(**kwargs)
ut.holymoly(**kwargs)
baz()
def biz(**kwargs):
foo2(**kwargs)
''')
>>> child_funcnamess = ut.find_funcs_called_with_kwargs(sourcecode)
>>> print('child_funcnamess = %r' % (child_funcnamess,))
>>> assert 'foo2' not in child_funcnamess, 'foo2 should not be found'
>>> assert 'bar' in child_funcnamess, 'bar should be found' | [
"r",
"Finds",
"functions",
"that",
"are",
"called",
"with",
"the",
"keyword",
"kwargs",
"variable"
] | 3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a | https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/util_inspect.py#L1683-L1792 | train |
Erotemic/utool | utool/util_inspect.py | get_func_argspec | def get_func_argspec(func):
"""
wrapper around inspect.getargspec but takes into account utool decorators
"""
if hasattr(func, '_utinfo'):
argspec = func._utinfo['orig_argspec']
return argspec
if isinstance(func, property):
func = func.fget
try:
argspec = inspect.getargspec(func)
except Exception:
argspec = inspect.getfullargspec(func)
return argspec | python | def get_func_argspec(func):
"""
wrapper around inspect.getargspec but takes into account utool decorators
"""
if hasattr(func, '_utinfo'):
argspec = func._utinfo['orig_argspec']
return argspec
if isinstance(func, property):
func = func.fget
try:
argspec = inspect.getargspec(func)
except Exception:
argspec = inspect.getfullargspec(func)
return argspec | [
"def",
"get_func_argspec",
"(",
"func",
")",
":",
"if",
"hasattr",
"(",
"func",
",",
"'_utinfo'",
")",
":",
"argspec",
"=",
"func",
".",
"_utinfo",
"[",
"'orig_argspec'",
"]",
"return",
"argspec",
"if",
"isinstance",
"(",
"func",
",",
"property",
")",
":",
"func",
"=",
"func",
".",
"fget",
"try",
":",
"argspec",
"=",
"inspect",
".",
"getargspec",
"(",
"func",
")",
"except",
"Exception",
":",
"argspec",
"=",
"inspect",
".",
"getfullargspec",
"(",
"func",
")",
"return",
"argspec"
] | wrapper around inspect.getargspec but takes into account utool decorators | [
"wrapper",
"around",
"inspect",
".",
"getargspec",
"but",
"takes",
"into",
"account",
"utool",
"decorators"
] | 3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a | https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/util_inspect.py#L2445-L2458 | train |
Erotemic/utool | utool/util_inspect.py | parse_func_kwarg_keys | def parse_func_kwarg_keys(func, with_vals=False):
""" hacky inference of kwargs keys
SeeAlso:
argparse_funckw
recursive_parse_kwargs
parse_kwarg_keys
parse_func_kwarg_keys
get_func_kwargs
"""
sourcecode = get_func_sourcecode(func, strip_docstr=True,
strip_comments=True)
kwkeys = parse_kwarg_keys(sourcecode, with_vals=with_vals)
#ut.get_func_kwargs TODO
return kwkeys | python | def parse_func_kwarg_keys(func, with_vals=False):
""" hacky inference of kwargs keys
SeeAlso:
argparse_funckw
recursive_parse_kwargs
parse_kwarg_keys
parse_func_kwarg_keys
get_func_kwargs
"""
sourcecode = get_func_sourcecode(func, strip_docstr=True,
strip_comments=True)
kwkeys = parse_kwarg_keys(sourcecode, with_vals=with_vals)
#ut.get_func_kwargs TODO
return kwkeys | [
"def",
"parse_func_kwarg_keys",
"(",
"func",
",",
"with_vals",
"=",
"False",
")",
":",
"sourcecode",
"=",
"get_func_sourcecode",
"(",
"func",
",",
"strip_docstr",
"=",
"True",
",",
"strip_comments",
"=",
"True",
")",
"kwkeys",
"=",
"parse_kwarg_keys",
"(",
"sourcecode",
",",
"with_vals",
"=",
"with_vals",
")",
"#ut.get_func_kwargs TODO",
"return",
"kwkeys"
] | hacky inference of kwargs keys
SeeAlso:
argparse_funckw
recursive_parse_kwargs
parse_kwarg_keys
parse_func_kwarg_keys
get_func_kwargs | [
"hacky",
"inference",
"of",
"kwargs",
"keys"
] | 3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a | https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/util_inspect.py#L2740-L2755 | train |
Erotemic/utool | utool/util_inspect.py | get_func_kwargs | def get_func_kwargs(func, recursive=True):
"""
func = ibeis.run_experiment
SeeAlso:
argparse_funckw
recursive_parse_kwargs
parse_kwarg_keys
parse_func_kwarg_keys
get_func_kwargs
"""
import utool as ut
argspec = ut.get_func_argspec(func)
if argspec.defaults is None:
header_kw = {}
else:
header_kw = dict(zip(argspec.args[::-1], argspec.defaults[::-1]))
if argspec.keywords is not None:
header_kw.update(dict(ut.recursive_parse_kwargs(func)))
return header_kw | python | def get_func_kwargs(func, recursive=True):
"""
func = ibeis.run_experiment
SeeAlso:
argparse_funckw
recursive_parse_kwargs
parse_kwarg_keys
parse_func_kwarg_keys
get_func_kwargs
"""
import utool as ut
argspec = ut.get_func_argspec(func)
if argspec.defaults is None:
header_kw = {}
else:
header_kw = dict(zip(argspec.args[::-1], argspec.defaults[::-1]))
if argspec.keywords is not None:
header_kw.update(dict(ut.recursive_parse_kwargs(func)))
return header_kw | [
"def",
"get_func_kwargs",
"(",
"func",
",",
"recursive",
"=",
"True",
")",
":",
"import",
"utool",
"as",
"ut",
"argspec",
"=",
"ut",
".",
"get_func_argspec",
"(",
"func",
")",
"if",
"argspec",
".",
"defaults",
"is",
"None",
":",
"header_kw",
"=",
"{",
"}",
"else",
":",
"header_kw",
"=",
"dict",
"(",
"zip",
"(",
"argspec",
".",
"args",
"[",
":",
":",
"-",
"1",
"]",
",",
"argspec",
".",
"defaults",
"[",
":",
":",
"-",
"1",
"]",
")",
")",
"if",
"argspec",
".",
"keywords",
"is",
"not",
"None",
":",
"header_kw",
".",
"update",
"(",
"dict",
"(",
"ut",
".",
"recursive_parse_kwargs",
"(",
"func",
")",
")",
")",
"return",
"header_kw"
] | func = ibeis.run_experiment
SeeAlso:
argparse_funckw
recursive_parse_kwargs
parse_kwarg_keys
parse_func_kwarg_keys
get_func_kwargs | [
"func",
"=",
"ibeis",
".",
"run_experiment"
] | 3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a | https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/util_inspect.py#L2758-L2777 | train |
Erotemic/utool | utool/util_inspect.py | argparse_funckw | def argparse_funckw(func, defaults={}, **kwargs):
"""
allows kwargs to be specified on the commandline from testfuncs
Args:
func (function):
Kwargs:
lbl, verbose, only_specified, force_keys, type_hint, alias_dict
Returns:
dict: funckw
CommandLine:
python -m utool.util_inspect argparse_funckw
SeeAlso:
exec_funckw
recursive_parse_kwargs
parse_kwarg_keys
Example:
>>> # ENABLE_DOCTEST
>>> from utool.util_inspect import * # NOQA
>>> import utool as ut
>>> func = get_instance_attrnames
>>> funckw = argparse_funckw(func)
>>> result = ('funckw = %s' % (ut.repr3(funckw),))
>>> print(result)
funckw = {
'default': True,
'with_methods': True,
'with_properties': True,
}
"""
import utool as ut
funckw_ = ut.get_funckw(func, recursive=True)
funckw_.update(defaults)
funckw = ut.argparse_dict(funckw_, **kwargs)
return funckw | python | def argparse_funckw(func, defaults={}, **kwargs):
"""
allows kwargs to be specified on the commandline from testfuncs
Args:
func (function):
Kwargs:
lbl, verbose, only_specified, force_keys, type_hint, alias_dict
Returns:
dict: funckw
CommandLine:
python -m utool.util_inspect argparse_funckw
SeeAlso:
exec_funckw
recursive_parse_kwargs
parse_kwarg_keys
Example:
>>> # ENABLE_DOCTEST
>>> from utool.util_inspect import * # NOQA
>>> import utool as ut
>>> func = get_instance_attrnames
>>> funckw = argparse_funckw(func)
>>> result = ('funckw = %s' % (ut.repr3(funckw),))
>>> print(result)
funckw = {
'default': True,
'with_methods': True,
'with_properties': True,
}
"""
import utool as ut
funckw_ = ut.get_funckw(func, recursive=True)
funckw_.update(defaults)
funckw = ut.argparse_dict(funckw_, **kwargs)
return funckw | [
"def",
"argparse_funckw",
"(",
"func",
",",
"defaults",
"=",
"{",
"}",
",",
"*",
"*",
"kwargs",
")",
":",
"import",
"utool",
"as",
"ut",
"funckw_",
"=",
"ut",
".",
"get_funckw",
"(",
"func",
",",
"recursive",
"=",
"True",
")",
"funckw_",
".",
"update",
"(",
"defaults",
")",
"funckw",
"=",
"ut",
".",
"argparse_dict",
"(",
"funckw_",
",",
"*",
"*",
"kwargs",
")",
"return",
"funckw"
] | allows kwargs to be specified on the commandline from testfuncs
Args:
func (function):
Kwargs:
lbl, verbose, only_specified, force_keys, type_hint, alias_dict
Returns:
dict: funckw
CommandLine:
python -m utool.util_inspect argparse_funckw
SeeAlso:
exec_funckw
recursive_parse_kwargs
parse_kwarg_keys
Example:
>>> # ENABLE_DOCTEST
>>> from utool.util_inspect import * # NOQA
>>> import utool as ut
>>> func = get_instance_attrnames
>>> funckw = argparse_funckw(func)
>>> result = ('funckw = %s' % (ut.repr3(funckw),))
>>> print(result)
funckw = {
'default': True,
'with_methods': True,
'with_properties': True,
} | [
"allows",
"kwargs",
"to",
"be",
"specified",
"on",
"the",
"commandline",
"from",
"testfuncs"
] | 3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a | https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/util_inspect.py#L3030-L3069 | train |
Erotemic/utool | utool/Preferences.py | _qt_set_leaf_data | def _qt_set_leaf_data(self, qvar):
""" Sets backend data using QVariants """
if VERBOSE_PREF:
print('')
print('+--- [pref.qt_set_leaf_data]')
print('[pref.qt_set_leaf_data] qvar = %r' % qvar)
print('[pref.qt_set_leaf_data] _intern.name=%r' % self._intern.name)
print('[pref.qt_set_leaf_data] _intern.type_=%r' % self._intern.get_type())
print('[pref.qt_set_leaf_data] type(_intern.value)=%r' % type(self._intern.value))
print('[pref.qt_set_leaf_data] _intern.value=%r' % self._intern.value)
#print('[pref.qt_set_leaf_data] qvar.toString()=%s' % six.text_type(qvar.toString()))
if self._tree.parent is None:
raise Exception('[Pref.qtleaf] Cannot set root preference')
if self.qt_is_editable():
new_val = '[Pref.qtleaf] BadThingsHappenedInPref'
if self._intern.value == PrefNode:
raise Exception('[Pref.qtleaf] Qt can only change leafs')
elif self._intern.value is None:
# None could be a number of types
def cast_order(var, order=[bool, int, float, six.text_type]):
for type_ in order:
try:
ret = type_(var)
return ret
except Exception:
continue
new_val = cast_order(six.text_type(qvar))
self._intern.get_type()
if isinstance(self._intern.value, bool):
#new_val = bool(qvar.toBool())
print('qvar = %r' % (qvar,))
new_val = util_type.smart_cast(qvar, bool)
#new_val = bool(eval(qvar, {}, {}))
print('new_val = %r' % (new_val,))
elif isinstance(self._intern.value, int):
#new_val = int(qvar.toInt()[0])
new_val = int(qvar)
# elif isinstance(self._intern.value, float):
elif self._intern.get_type() in util_type.VALID_FLOAT_TYPES:
#new_val = float(qvar.toDouble()[0])
new_val = float(qvar)
elif isinstance(self._intern.value, six.string_types):
#new_val = six.text_type(qvar.toString())
new_val = six.text_type(qvar)
elif isinstance(self._intern.value, PrefChoice):
#new_val = qvar.toString()
new_val = six.text_type(qvar)
if new_val.upper() == 'NONE':
new_val = None
else:
try:
#new_val = six.text_type(qvar.toString())
type_ = self._intern.get_type()
if type_ is not None:
new_val = type_(six.text_type(qvar))
else:
new_val = six.text_type(qvar)
except Exception:
raise NotImplementedError(
('[Pref.qtleaf] Unknown internal type. '
'type(_intern.value) = %r, '
'_intern.get_type() = %r, ')
% type(self._intern.value), self._intern.get_type())
# Check for a set of None
if isinstance(new_val, six.string_types):
if new_val.lower() == 'none':
new_val = None
elif new_val.lower() == 'true':
new_val = True
elif new_val.lower() == 'false':
new_val = False
# save to disk after modifying data
if VERBOSE_PREF:
print('---')
print('[pref.qt_set_leaf_data] new_val=%r' % new_val)
print('[pref.qt_set_leaf_data] type(new_val)=%r' % type(new_val))
print('L____ [pref.qt_set_leaf_data]')
# TODO Add ability to set a callback function when certain
# preferences are changed.
return self._tree.parent.pref_update(self._intern.name, new_val)
return 'PrefNotEditable' | python | def _qt_set_leaf_data(self, qvar):
""" Sets backend data using QVariants """
if VERBOSE_PREF:
print('')
print('+--- [pref.qt_set_leaf_data]')
print('[pref.qt_set_leaf_data] qvar = %r' % qvar)
print('[pref.qt_set_leaf_data] _intern.name=%r' % self._intern.name)
print('[pref.qt_set_leaf_data] _intern.type_=%r' % self._intern.get_type())
print('[pref.qt_set_leaf_data] type(_intern.value)=%r' % type(self._intern.value))
print('[pref.qt_set_leaf_data] _intern.value=%r' % self._intern.value)
#print('[pref.qt_set_leaf_data] qvar.toString()=%s' % six.text_type(qvar.toString()))
if self._tree.parent is None:
raise Exception('[Pref.qtleaf] Cannot set root preference')
if self.qt_is_editable():
new_val = '[Pref.qtleaf] BadThingsHappenedInPref'
if self._intern.value == PrefNode:
raise Exception('[Pref.qtleaf] Qt can only change leafs')
elif self._intern.value is None:
# None could be a number of types
def cast_order(var, order=[bool, int, float, six.text_type]):
for type_ in order:
try:
ret = type_(var)
return ret
except Exception:
continue
new_val = cast_order(six.text_type(qvar))
self._intern.get_type()
if isinstance(self._intern.value, bool):
#new_val = bool(qvar.toBool())
print('qvar = %r' % (qvar,))
new_val = util_type.smart_cast(qvar, bool)
#new_val = bool(eval(qvar, {}, {}))
print('new_val = %r' % (new_val,))
elif isinstance(self._intern.value, int):
#new_val = int(qvar.toInt()[0])
new_val = int(qvar)
# elif isinstance(self._intern.value, float):
elif self._intern.get_type() in util_type.VALID_FLOAT_TYPES:
#new_val = float(qvar.toDouble()[0])
new_val = float(qvar)
elif isinstance(self._intern.value, six.string_types):
#new_val = six.text_type(qvar.toString())
new_val = six.text_type(qvar)
elif isinstance(self._intern.value, PrefChoice):
#new_val = qvar.toString()
new_val = six.text_type(qvar)
if new_val.upper() == 'NONE':
new_val = None
else:
try:
#new_val = six.text_type(qvar.toString())
type_ = self._intern.get_type()
if type_ is not None:
new_val = type_(six.text_type(qvar))
else:
new_val = six.text_type(qvar)
except Exception:
raise NotImplementedError(
('[Pref.qtleaf] Unknown internal type. '
'type(_intern.value) = %r, '
'_intern.get_type() = %r, ')
% type(self._intern.value), self._intern.get_type())
# Check for a set of None
if isinstance(new_val, six.string_types):
if new_val.lower() == 'none':
new_val = None
elif new_val.lower() == 'true':
new_val = True
elif new_val.lower() == 'false':
new_val = False
# save to disk after modifying data
if VERBOSE_PREF:
print('---')
print('[pref.qt_set_leaf_data] new_val=%r' % new_val)
print('[pref.qt_set_leaf_data] type(new_val)=%r' % type(new_val))
print('L____ [pref.qt_set_leaf_data]')
# TODO Add ability to set a callback function when certain
# preferences are changed.
return self._tree.parent.pref_update(self._intern.name, new_val)
return 'PrefNotEditable' | [
"def",
"_qt_set_leaf_data",
"(",
"self",
",",
"qvar",
")",
":",
"if",
"VERBOSE_PREF",
":",
"print",
"(",
"''",
")",
"print",
"(",
"'+--- [pref.qt_set_leaf_data]'",
")",
"print",
"(",
"'[pref.qt_set_leaf_data] qvar = %r'",
"%",
"qvar",
")",
"print",
"(",
"'[pref.qt_set_leaf_data] _intern.name=%r'",
"%",
"self",
".",
"_intern",
".",
"name",
")",
"print",
"(",
"'[pref.qt_set_leaf_data] _intern.type_=%r'",
"%",
"self",
".",
"_intern",
".",
"get_type",
"(",
")",
")",
"print",
"(",
"'[pref.qt_set_leaf_data] type(_intern.value)=%r'",
"%",
"type",
"(",
"self",
".",
"_intern",
".",
"value",
")",
")",
"print",
"(",
"'[pref.qt_set_leaf_data] _intern.value=%r'",
"%",
"self",
".",
"_intern",
".",
"value",
")",
"#print('[pref.qt_set_leaf_data] qvar.toString()=%s' % six.text_type(qvar.toString()))",
"if",
"self",
".",
"_tree",
".",
"parent",
"is",
"None",
":",
"raise",
"Exception",
"(",
"'[Pref.qtleaf] Cannot set root preference'",
")",
"if",
"self",
".",
"qt_is_editable",
"(",
")",
":",
"new_val",
"=",
"'[Pref.qtleaf] BadThingsHappenedInPref'",
"if",
"self",
".",
"_intern",
".",
"value",
"==",
"PrefNode",
":",
"raise",
"Exception",
"(",
"'[Pref.qtleaf] Qt can only change leafs'",
")",
"elif",
"self",
".",
"_intern",
".",
"value",
"is",
"None",
":",
"# None could be a number of types",
"def",
"cast_order",
"(",
"var",
",",
"order",
"=",
"[",
"bool",
",",
"int",
",",
"float",
",",
"six",
".",
"text_type",
"]",
")",
":",
"for",
"type_",
"in",
"order",
":",
"try",
":",
"ret",
"=",
"type_",
"(",
"var",
")",
"return",
"ret",
"except",
"Exception",
":",
"continue",
"new_val",
"=",
"cast_order",
"(",
"six",
".",
"text_type",
"(",
"qvar",
")",
")",
"self",
".",
"_intern",
".",
"get_type",
"(",
")",
"if",
"isinstance",
"(",
"self",
".",
"_intern",
".",
"value",
",",
"bool",
")",
":",
"#new_val = bool(qvar.toBool())",
"print",
"(",
"'qvar = %r'",
"%",
"(",
"qvar",
",",
")",
")",
"new_val",
"=",
"util_type",
".",
"smart_cast",
"(",
"qvar",
",",
"bool",
")",
"#new_val = bool(eval(qvar, {}, {}))",
"print",
"(",
"'new_val = %r'",
"%",
"(",
"new_val",
",",
")",
")",
"elif",
"isinstance",
"(",
"self",
".",
"_intern",
".",
"value",
",",
"int",
")",
":",
"#new_val = int(qvar.toInt()[0])",
"new_val",
"=",
"int",
"(",
"qvar",
")",
"# elif isinstance(self._intern.value, float):",
"elif",
"self",
".",
"_intern",
".",
"get_type",
"(",
")",
"in",
"util_type",
".",
"VALID_FLOAT_TYPES",
":",
"#new_val = float(qvar.toDouble()[0])",
"new_val",
"=",
"float",
"(",
"qvar",
")",
"elif",
"isinstance",
"(",
"self",
".",
"_intern",
".",
"value",
",",
"six",
".",
"string_types",
")",
":",
"#new_val = six.text_type(qvar.toString())",
"new_val",
"=",
"six",
".",
"text_type",
"(",
"qvar",
")",
"elif",
"isinstance",
"(",
"self",
".",
"_intern",
".",
"value",
",",
"PrefChoice",
")",
":",
"#new_val = qvar.toString()",
"new_val",
"=",
"six",
".",
"text_type",
"(",
"qvar",
")",
"if",
"new_val",
".",
"upper",
"(",
")",
"==",
"'NONE'",
":",
"new_val",
"=",
"None",
"else",
":",
"try",
":",
"#new_val = six.text_type(qvar.toString())",
"type_",
"=",
"self",
".",
"_intern",
".",
"get_type",
"(",
")",
"if",
"type_",
"is",
"not",
"None",
":",
"new_val",
"=",
"type_",
"(",
"six",
".",
"text_type",
"(",
"qvar",
")",
")",
"else",
":",
"new_val",
"=",
"six",
".",
"text_type",
"(",
"qvar",
")",
"except",
"Exception",
":",
"raise",
"NotImplementedError",
"(",
"(",
"'[Pref.qtleaf] Unknown internal type. '",
"'type(_intern.value) = %r, '",
"'_intern.get_type() = %r, '",
")",
"%",
"type",
"(",
"self",
".",
"_intern",
".",
"value",
")",
",",
"self",
".",
"_intern",
".",
"get_type",
"(",
")",
")",
"# Check for a set of None",
"if",
"isinstance",
"(",
"new_val",
",",
"six",
".",
"string_types",
")",
":",
"if",
"new_val",
".",
"lower",
"(",
")",
"==",
"'none'",
":",
"new_val",
"=",
"None",
"elif",
"new_val",
".",
"lower",
"(",
")",
"==",
"'true'",
":",
"new_val",
"=",
"True",
"elif",
"new_val",
".",
"lower",
"(",
")",
"==",
"'false'",
":",
"new_val",
"=",
"False",
"# save to disk after modifying data",
"if",
"VERBOSE_PREF",
":",
"print",
"(",
"'---'",
")",
"print",
"(",
"'[pref.qt_set_leaf_data] new_val=%r'",
"%",
"new_val",
")",
"print",
"(",
"'[pref.qt_set_leaf_data] type(new_val)=%r'",
"%",
"type",
"(",
"new_val",
")",
")",
"print",
"(",
"'L____ [pref.qt_set_leaf_data]'",
")",
"# TODO Add ability to set a callback function when certain",
"# preferences are changed.",
"return",
"self",
".",
"_tree",
".",
"parent",
".",
"pref_update",
"(",
"self",
".",
"_intern",
".",
"name",
",",
"new_val",
")",
"return",
"'PrefNotEditable'"
] | Sets backend data using QVariants | [
"Sets",
"backend",
"data",
"using",
"QVariants"
] | 3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a | https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/Preferences.py#L511-L591 | train |
Erotemic/utool | utool/Preferences.py | Pref.toggle | def toggle(self, key):
""" Toggles a boolean key """
val = self[key]
assert isinstance(val, bool), 'key[%r] = %r is not a bool' % (key, val)
self.pref_update(key, not val) | python | def toggle(self, key):
""" Toggles a boolean key """
val = self[key]
assert isinstance(val, bool), 'key[%r] = %r is not a bool' % (key, val)
self.pref_update(key, not val) | [
"def",
"toggle",
"(",
"self",
",",
"key",
")",
":",
"val",
"=",
"self",
"[",
"key",
"]",
"assert",
"isinstance",
"(",
"val",
",",
"bool",
")",
",",
"'key[%r] = %r is not a bool'",
"%",
"(",
"key",
",",
"val",
")",
"self",
".",
"pref_update",
"(",
"key",
",",
"not",
"val",
")"
] | Toggles a boolean key | [
"Toggles",
"a",
"boolean",
"key"
] | 3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a | https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/Preferences.py#L143-L147 | train |
Erotemic/utool | utool/Preferences.py | Pref.change_combo_val | def change_combo_val(self, new_val):
"""
Checks to see if a selection is a valid index or choice of a combo
preference
"""
choice_obj = self._intern.value
assert isinstance(self._intern.value, PrefChoice), 'must be a choice'
return choice_obj.get_tuple() | python | def change_combo_val(self, new_val):
"""
Checks to see if a selection is a valid index or choice of a combo
preference
"""
choice_obj = self._intern.value
assert isinstance(self._intern.value, PrefChoice), 'must be a choice'
return choice_obj.get_tuple() | [
"def",
"change_combo_val",
"(",
"self",
",",
"new_val",
")",
":",
"choice_obj",
"=",
"self",
".",
"_intern",
".",
"value",
"assert",
"isinstance",
"(",
"self",
".",
"_intern",
".",
"value",
",",
"PrefChoice",
")",
",",
"'must be a choice'",
"return",
"choice_obj",
".",
"get_tuple",
"(",
")"
] | Checks to see if a selection is a valid index or choice of a combo
preference | [
"Checks",
"to",
"see",
"if",
"a",
"selection",
"is",
"a",
"valid",
"index",
"or",
"choice",
"of",
"a",
"combo",
"preference"
] | 3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a | https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/Preferences.py#L149-L156 | train |
Erotemic/utool | utool/Preferences.py | Pref.iteritems | def iteritems(self):
"""
Wow this class is messed up. I had to overwrite items when
moving to python3, just because I haden't called it yet
"""
for (key, val) in six.iteritems(self.__dict__):
if key in self._printable_exclude:
continue
yield (key, val) | python | def iteritems(self):
"""
Wow this class is messed up. I had to overwrite items when
moving to python3, just because I haden't called it yet
"""
for (key, val) in six.iteritems(self.__dict__):
if key in self._printable_exclude:
continue
yield (key, val) | [
"def",
"iteritems",
"(",
"self",
")",
":",
"for",
"(",
"key",
",",
"val",
")",
"in",
"six",
".",
"iteritems",
"(",
"self",
".",
"__dict__",
")",
":",
"if",
"key",
"in",
"self",
".",
"_printable_exclude",
":",
"continue",
"yield",
"(",
"key",
",",
"val",
")"
] | Wow this class is messed up. I had to overwrite items when
moving to python3, just because I haden't called it yet | [
"Wow",
"this",
"class",
"is",
"messed",
"up",
".",
"I",
"had",
"to",
"overwrite",
"items",
"when",
"moving",
"to",
"python3",
"just",
"because",
"I",
"haden",
"t",
"called",
"it",
"yet"
] | 3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a | https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/Preferences.py#L320-L328 | train |
Erotemic/utool | utool/Preferences.py | Pref.to_dict | def to_dict(self, split_structs_bit=False):
""" Converts prefeters to a dictionary.
Children Pref can be optionally separated """
pref_dict = {}
struct_dict = {}
for (key, val) in six.iteritems(self):
if split_structs_bit and isinstance(val, Pref):
struct_dict[key] = val
continue
pref_dict[key] = val
if split_structs_bit:
return (pref_dict, struct_dict)
return pref_dict | python | def to_dict(self, split_structs_bit=False):
""" Converts prefeters to a dictionary.
Children Pref can be optionally separated """
pref_dict = {}
struct_dict = {}
for (key, val) in six.iteritems(self):
if split_structs_bit and isinstance(val, Pref):
struct_dict[key] = val
continue
pref_dict[key] = val
if split_structs_bit:
return (pref_dict, struct_dict)
return pref_dict | [
"def",
"to_dict",
"(",
"self",
",",
"split_structs_bit",
"=",
"False",
")",
":",
"pref_dict",
"=",
"{",
"}",
"struct_dict",
"=",
"{",
"}",
"for",
"(",
"key",
",",
"val",
")",
"in",
"six",
".",
"iteritems",
"(",
"self",
")",
":",
"if",
"split_structs_bit",
"and",
"isinstance",
"(",
"val",
",",
"Pref",
")",
":",
"struct_dict",
"[",
"key",
"]",
"=",
"val",
"continue",
"pref_dict",
"[",
"key",
"]",
"=",
"val",
"if",
"split_structs_bit",
":",
"return",
"(",
"pref_dict",
",",
"struct_dict",
")",
"return",
"pref_dict"
] | Converts prefeters to a dictionary.
Children Pref can be optionally separated | [
"Converts",
"prefeters",
"to",
"a",
"dictionary",
".",
"Children",
"Pref",
"can",
"be",
"optionally",
"separated"
] | 3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a | https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/Preferences.py#L342-L354 | train |
Erotemic/utool | utool/Preferences.py | Pref.save | def save(self):
""" Saves prefs to disk in dict format """
fpath = self.get_fpath()
if fpath in ['', None]:
if self._tree.parent is not None:
if VERBOSE_PREF:
print('[pref.save] Can my parent save me?') # ...to disk
return self._tree.parent.save()
if VERBOSE_PREF:
print('[pref.save] I cannot be saved. I have no parents.')
return False
with open(fpath, 'wb') as f:
print('[pref] Saving to ' + fpath)
pref_dict = self.to_dict()
pickle.dump(pref_dict, f, protocol=2) # Use protocol 2 to support python2 and 3
return True | python | def save(self):
""" Saves prefs to disk in dict format """
fpath = self.get_fpath()
if fpath in ['', None]:
if self._tree.parent is not None:
if VERBOSE_PREF:
print('[pref.save] Can my parent save me?') # ...to disk
return self._tree.parent.save()
if VERBOSE_PREF:
print('[pref.save] I cannot be saved. I have no parents.')
return False
with open(fpath, 'wb') as f:
print('[pref] Saving to ' + fpath)
pref_dict = self.to_dict()
pickle.dump(pref_dict, f, protocol=2) # Use protocol 2 to support python2 and 3
return True | [
"def",
"save",
"(",
"self",
")",
":",
"fpath",
"=",
"self",
".",
"get_fpath",
"(",
")",
"if",
"fpath",
"in",
"[",
"''",
",",
"None",
"]",
":",
"if",
"self",
".",
"_tree",
".",
"parent",
"is",
"not",
"None",
":",
"if",
"VERBOSE_PREF",
":",
"print",
"(",
"'[pref.save] Can my parent save me?'",
")",
"# ...to disk",
"return",
"self",
".",
"_tree",
".",
"parent",
".",
"save",
"(",
")",
"if",
"VERBOSE_PREF",
":",
"print",
"(",
"'[pref.save] I cannot be saved. I have no parents.'",
")",
"return",
"False",
"with",
"open",
"(",
"fpath",
",",
"'wb'",
")",
"as",
"f",
":",
"print",
"(",
"'[pref] Saving to '",
"+",
"fpath",
")",
"pref_dict",
"=",
"self",
".",
"to_dict",
"(",
")",
"pickle",
".",
"dump",
"(",
"pref_dict",
",",
"f",
",",
"protocol",
"=",
"2",
")",
"# Use protocol 2 to support python2 and 3",
"return",
"True"
] | Saves prefs to disk in dict format | [
"Saves",
"prefs",
"to",
"disk",
"in",
"dict",
"format"
] | 3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a | https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/Preferences.py#L358-L373 | train |
Erotemic/utool | utool/Preferences.py | Pref.load | def load(self):
""" Read pref dict stored on disk. Overwriting current values. """
if VERBOSE_PREF:
print('[pref.load()]')
#if not os.path.exists(self._intern.fpath):
# msg = '[pref] fpath=%r does not exist' % (self._intern.fpath)
# return msg
fpath = self.get_fpath()
try:
with open(fpath, 'rb') as f:
if VERBOSE_PREF:
print('load: %r' % fpath)
pref_dict = pickle.load(f)
except EOFError as ex1:
util_dbg.printex(ex1, 'did not load pref fpath=%r correctly' % fpath, iswarning=True)
#warnings.warn(msg)
raise
#return msg
except ImportError as ex2:
util_dbg.printex(ex2, 'did not load pref fpath=%r correctly' % fpath, iswarning=True)
#warnings.warn(msg)
raise
#return msg
if not util_type.is_dict(pref_dict):
raise Exception('Preference file is corrupted')
self.add_dict(pref_dict)
return True | python | def load(self):
""" Read pref dict stored on disk. Overwriting current values. """
if VERBOSE_PREF:
print('[pref.load()]')
#if not os.path.exists(self._intern.fpath):
# msg = '[pref] fpath=%r does not exist' % (self._intern.fpath)
# return msg
fpath = self.get_fpath()
try:
with open(fpath, 'rb') as f:
if VERBOSE_PREF:
print('load: %r' % fpath)
pref_dict = pickle.load(f)
except EOFError as ex1:
util_dbg.printex(ex1, 'did not load pref fpath=%r correctly' % fpath, iswarning=True)
#warnings.warn(msg)
raise
#return msg
except ImportError as ex2:
util_dbg.printex(ex2, 'did not load pref fpath=%r correctly' % fpath, iswarning=True)
#warnings.warn(msg)
raise
#return msg
if not util_type.is_dict(pref_dict):
raise Exception('Preference file is corrupted')
self.add_dict(pref_dict)
return True | [
"def",
"load",
"(",
"self",
")",
":",
"if",
"VERBOSE_PREF",
":",
"print",
"(",
"'[pref.load()]'",
")",
"#if not os.path.exists(self._intern.fpath):",
"# msg = '[pref] fpath=%r does not exist' % (self._intern.fpath)",
"# return msg",
"fpath",
"=",
"self",
".",
"get_fpath",
"(",
")",
"try",
":",
"with",
"open",
"(",
"fpath",
",",
"'rb'",
")",
"as",
"f",
":",
"if",
"VERBOSE_PREF",
":",
"print",
"(",
"'load: %r'",
"%",
"fpath",
")",
"pref_dict",
"=",
"pickle",
".",
"load",
"(",
"f",
")",
"except",
"EOFError",
"as",
"ex1",
":",
"util_dbg",
".",
"printex",
"(",
"ex1",
",",
"'did not load pref fpath=%r correctly'",
"%",
"fpath",
",",
"iswarning",
"=",
"True",
")",
"#warnings.warn(msg)",
"raise",
"#return msg",
"except",
"ImportError",
"as",
"ex2",
":",
"util_dbg",
".",
"printex",
"(",
"ex2",
",",
"'did not load pref fpath=%r correctly'",
"%",
"fpath",
",",
"iswarning",
"=",
"True",
")",
"#warnings.warn(msg)",
"raise",
"#return msg",
"if",
"not",
"util_type",
".",
"is_dict",
"(",
"pref_dict",
")",
":",
"raise",
"Exception",
"(",
"'Preference file is corrupted'",
")",
"self",
".",
"add_dict",
"(",
"pref_dict",
")",
"return",
"True"
] | Read pref dict stored on disk. Overwriting current values. | [
"Read",
"pref",
"dict",
"stored",
"on",
"disk",
".",
"Overwriting",
"current",
"values",
"."
] | 3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a | https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/Preferences.py#L378-L404 | train |
Erotemic/utool | utool/Preferences.py | Pref.full_name | def full_name(self):
""" returns name all the way up the tree """
if self._tree.parent is None:
return self._intern.name
return self._tree.parent.full_name() + '.' + self._intern.name | python | def full_name(self):
""" returns name all the way up the tree """
if self._tree.parent is None:
return self._intern.name
return self._tree.parent.full_name() + '.' + self._intern.name | [
"def",
"full_name",
"(",
"self",
")",
":",
"if",
"self",
".",
"_tree",
".",
"parent",
"is",
"None",
":",
"return",
"self",
".",
"_intern",
".",
"name",
"return",
"self",
".",
"_tree",
".",
"parent",
".",
"full_name",
"(",
")",
"+",
"'.'",
"+",
"self",
".",
"_intern",
".",
"name"
] | returns name all the way up the tree | [
"returns",
"name",
"all",
"the",
"way",
"up",
"the",
"tree"
] | 3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a | https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/Preferences.py#L418-L422 | train |
Erotemic/utool | utool/Preferences.py | Pref.pref_update | def pref_update(self, key, new_val):
""" Changes a preference value and saves it to disk """
print('Update and save pref from: %s=%r, to: %s=%r' %
(key, six.text_type(self[key]), key, six.text_type(new_val)))
self.__setattr__(key, new_val)
return self.save() | python | def pref_update(self, key, new_val):
""" Changes a preference value and saves it to disk """
print('Update and save pref from: %s=%r, to: %s=%r' %
(key, six.text_type(self[key]), key, six.text_type(new_val)))
self.__setattr__(key, new_val)
return self.save() | [
"def",
"pref_update",
"(",
"self",
",",
"key",
",",
"new_val",
")",
":",
"print",
"(",
"'Update and save pref from: %s=%r, to: %s=%r'",
"%",
"(",
"key",
",",
"six",
".",
"text_type",
"(",
"self",
"[",
"key",
"]",
")",
",",
"key",
",",
"six",
".",
"text_type",
"(",
"new_val",
")",
")",
")",
"self",
".",
"__setattr__",
"(",
"key",
",",
"new_val",
")",
"return",
"self",
".",
"save",
"(",
")"
] | Changes a preference value and saves it to disk | [
"Changes",
"a",
"preference",
"value",
"and",
"saves",
"it",
"to",
"disk"
] | 3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a | https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/Preferences.py#L441-L446 | train |
product-definition-center/pdc-client | pdc_client/plugins/permission.py | PermissionPlugin.__get_permissions | def __get_permissions(self, res, **kwargs):
"""
This call returns current login user's permissions.
"""
response = res._(**kwargs)
return response.get('permissions', None) | python | def __get_permissions(self, res, **kwargs):
"""
This call returns current login user's permissions.
"""
response = res._(**kwargs)
return response.get('permissions', None) | [
"def",
"__get_permissions",
"(",
"self",
",",
"res",
",",
"*",
"*",
"kwargs",
")",
":",
"response",
"=",
"res",
".",
"_",
"(",
"*",
"*",
"kwargs",
")",
"return",
"response",
".",
"get",
"(",
"'permissions'",
",",
"None",
")"
] | This call returns current login user's permissions. | [
"This",
"call",
"returns",
"current",
"login",
"user",
"s",
"permissions",
"."
] | 7236fd8b72e675ebb321bbe337289d9fbeb6119f | https://github.com/product-definition-center/pdc-client/blob/7236fd8b72e675ebb321bbe337289d9fbeb6119f/pdc_client/plugins/permission.py#L32-L37 | train |
Erotemic/utool | utool/util_class.py | inject_all_external_modules | def inject_all_external_modules(self, classname=None,
allow_override='override+warn',
strict=True):
"""
dynamically injects registered module methods into a class instance
FIXME: naming convention and use this in all places where this clas is used
"""
#import utool as ut
if classname is None:
classname = self.__class__.__name__
#import utool as ut
#ut.embed()
NEW = True
if NEW:
classkey_list = [key for key in __CLASSTYPE_ATTRIBUTES__
if key[0] == classname]
else:
injected_modules = get_injected_modules(classname)
# the variable must be named CLASS_INJECT_KEY
# and only one class can be specified per module.
classkey_list = [module.CLASS_INJECT_KEY
for module in injected_modules]
for classkey in classkey_list:
inject_instance(
self, classkey=classkey,
allow_override=allow_override, strict=False)
for classkey in classkey_list:
postinject_instance(
self, classkey=classkey) | python | def inject_all_external_modules(self, classname=None,
allow_override='override+warn',
strict=True):
"""
dynamically injects registered module methods into a class instance
FIXME: naming convention and use this in all places where this clas is used
"""
#import utool as ut
if classname is None:
classname = self.__class__.__name__
#import utool as ut
#ut.embed()
NEW = True
if NEW:
classkey_list = [key for key in __CLASSTYPE_ATTRIBUTES__
if key[0] == classname]
else:
injected_modules = get_injected_modules(classname)
# the variable must be named CLASS_INJECT_KEY
# and only one class can be specified per module.
classkey_list = [module.CLASS_INJECT_KEY
for module in injected_modules]
for classkey in classkey_list:
inject_instance(
self, classkey=classkey,
allow_override=allow_override, strict=False)
for classkey in classkey_list:
postinject_instance(
self, classkey=classkey) | [
"def",
"inject_all_external_modules",
"(",
"self",
",",
"classname",
"=",
"None",
",",
"allow_override",
"=",
"'override+warn'",
",",
"strict",
"=",
"True",
")",
":",
"#import utool as ut",
"if",
"classname",
"is",
"None",
":",
"classname",
"=",
"self",
".",
"__class__",
".",
"__name__",
"#import utool as ut",
"#ut.embed()",
"NEW",
"=",
"True",
"if",
"NEW",
":",
"classkey_list",
"=",
"[",
"key",
"for",
"key",
"in",
"__CLASSTYPE_ATTRIBUTES__",
"if",
"key",
"[",
"0",
"]",
"==",
"classname",
"]",
"else",
":",
"injected_modules",
"=",
"get_injected_modules",
"(",
"classname",
")",
"# the variable must be named CLASS_INJECT_KEY",
"# and only one class can be specified per module.",
"classkey_list",
"=",
"[",
"module",
".",
"CLASS_INJECT_KEY",
"for",
"module",
"in",
"injected_modules",
"]",
"for",
"classkey",
"in",
"classkey_list",
":",
"inject_instance",
"(",
"self",
",",
"classkey",
"=",
"classkey",
",",
"allow_override",
"=",
"allow_override",
",",
"strict",
"=",
"False",
")",
"for",
"classkey",
"in",
"classkey_list",
":",
"postinject_instance",
"(",
"self",
",",
"classkey",
"=",
"classkey",
")"
] | dynamically injects registered module methods into a class instance
FIXME: naming convention and use this in all places where this clas is used | [
"dynamically",
"injects",
"registered",
"module",
"methods",
"into",
"a",
"class",
"instance"
] | 3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a | https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/util_class.py#L128-L160 | train |
Erotemic/utool | utool/util_class.py | decorate_class_method | def decorate_class_method(func, classkey=None, skipmain=False):
"""
Will inject all decorated function as methods of classkey
classkey is some identifying string, tuple, or object
func can also be a tuple
"""
#import utool as ut
global __CLASSTYPE_ATTRIBUTES__
assert classkey is not None, 'must specify classkey'
#if not (skipmain and ut.get_caller_modname() == '__main__'):
__CLASSTYPE_ATTRIBUTES__[classkey].append(func)
return func | python | def decorate_class_method(func, classkey=None, skipmain=False):
"""
Will inject all decorated function as methods of classkey
classkey is some identifying string, tuple, or object
func can also be a tuple
"""
#import utool as ut
global __CLASSTYPE_ATTRIBUTES__
assert classkey is not None, 'must specify classkey'
#if not (skipmain and ut.get_caller_modname() == '__main__'):
__CLASSTYPE_ATTRIBUTES__[classkey].append(func)
return func | [
"def",
"decorate_class_method",
"(",
"func",
",",
"classkey",
"=",
"None",
",",
"skipmain",
"=",
"False",
")",
":",
"#import utool as ut",
"global",
"__CLASSTYPE_ATTRIBUTES__",
"assert",
"classkey",
"is",
"not",
"None",
",",
"'must specify classkey'",
"#if not (skipmain and ut.get_caller_modname() == '__main__'):",
"__CLASSTYPE_ATTRIBUTES__",
"[",
"classkey",
"]",
".",
"append",
"(",
"func",
")",
"return",
"func"
] | Will inject all decorated function as methods of classkey
classkey is some identifying string, tuple, or object
func can also be a tuple | [
"Will",
"inject",
"all",
"decorated",
"function",
"as",
"methods",
"of",
"classkey"
] | 3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a | https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/util_class.py#L413-L426 | train |
Erotemic/utool | utool/util_class.py | decorate_postinject | def decorate_postinject(func, classkey=None, skipmain=False):
"""
Will perform func with argument self after inject_instance is called on classkey
classkey is some identifying string, tuple, or object
"""
#import utool as ut
global __CLASSTYPE_POSTINJECT_FUNCS__
assert classkey is not None, 'must specify classkey'
#if not (skipmain and ut.get_caller_modname() == '__main__'):
__CLASSTYPE_POSTINJECT_FUNCS__[classkey].append(func)
return func | python | def decorate_postinject(func, classkey=None, skipmain=False):
"""
Will perform func with argument self after inject_instance is called on classkey
classkey is some identifying string, tuple, or object
"""
#import utool as ut
global __CLASSTYPE_POSTINJECT_FUNCS__
assert classkey is not None, 'must specify classkey'
#if not (skipmain and ut.get_caller_modname() == '__main__'):
__CLASSTYPE_POSTINJECT_FUNCS__[classkey].append(func)
return func | [
"def",
"decorate_postinject",
"(",
"func",
",",
"classkey",
"=",
"None",
",",
"skipmain",
"=",
"False",
")",
":",
"#import utool as ut",
"global",
"__CLASSTYPE_POSTINJECT_FUNCS__",
"assert",
"classkey",
"is",
"not",
"None",
",",
"'must specify classkey'",
"#if not (skipmain and ut.get_caller_modname() == '__main__'):",
"__CLASSTYPE_POSTINJECT_FUNCS__",
"[",
"classkey",
"]",
".",
"append",
"(",
"func",
")",
"return",
"func"
] | Will perform func with argument self after inject_instance is called on classkey
classkey is some identifying string, tuple, or object | [
"Will",
"perform",
"func",
"with",
"argument",
"self",
"after",
"inject_instance",
"is",
"called",
"on",
"classkey"
] | 3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a | https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/util_class.py#L429-L440 | train |
Erotemic/utool | utool/util_class.py | inject_func_as_method | def inject_func_as_method(self, func, method_name=None, class_=None,
allow_override=False, allow_main=False,
verbose=True, override=None, force=False):
""" Injects a function into an object as a method
Wraps func as a bound method of self. Then injects func into self
It is preferable to use make_class_method_decorator and inject_instance
Args:
self (object): class instance
func : some function whos first arugment is a class instance
method_name (str) : default=func.__name__, if specified renames the method
class_ (type) : if func is an unbound method of this class
References:
http://stackoverflow.com/questions/1015307/python-bind-an-unbound-method
"""
if override is not None:
# TODO depcirate allow_override
allow_override = override
if method_name is None:
method_name = get_funcname(func)
if force:
allow_override = True
allow_main = True
old_method = getattr(self, method_name, None)
# Bind function to the class instance
#new_method = types.MethodType(func, self, self.__class__)
new_method = func.__get__(self, self.__class__)
#new_method = profile(func.__get__(self, self.__class__))
if old_method is not None:
old_im_func = get_method_func(old_method)
new_im_func = get_method_func(new_method)
if not allow_main and old_im_func is not None and (
get_funcglobals(old_im_func)['__name__'] != '__main__' and
get_funcglobals(new_im_func)['__name__'] == '__main__'):
if True or VERBOSE_CLASS:
print('[util_class] skipping re-inject of %r from __main__' % method_name)
return
if old_method is new_method or old_im_func is new_im_func:
#if verbose and util_arg.NOT_QUIET:
# print('WARNING: Skipping injecting the same function twice: %r' % new_method)
#print('WARNING: Injecting the same function twice: %r' % new_method)
return
elif allow_override is False:
raise AssertionError(
'Overrides are not allowed. Already have method_name=%r' %
(method_name))
elif allow_override == 'warn':
print(
'WARNING: Overrides are not allowed. Already have method_name=%r. Skipping' %
(method_name))
return
elif allow_override == 'override+warn':
#import utool as ut
#ut.embed()
print('WARNING: Overrides are allowed, but dangerous. method_name=%r.' %
(method_name))
print('old_method = %r, im_func=%s' % (old_method, str(old_im_func)))
print('new_method = %r, im_func=%s' % (new_method, str(new_im_func)))
print(get_funcglobals(old_im_func)['__name__'])
print(get_funcglobals(new_im_func)['__name__'])
# TODO: does this actually decrement the refcount enough?
del old_method
setattr(self, method_name, new_method) | python | def inject_func_as_method(self, func, method_name=None, class_=None,
allow_override=False, allow_main=False,
verbose=True, override=None, force=False):
""" Injects a function into an object as a method
Wraps func as a bound method of self. Then injects func into self
It is preferable to use make_class_method_decorator and inject_instance
Args:
self (object): class instance
func : some function whos first arugment is a class instance
method_name (str) : default=func.__name__, if specified renames the method
class_ (type) : if func is an unbound method of this class
References:
http://stackoverflow.com/questions/1015307/python-bind-an-unbound-method
"""
if override is not None:
# TODO depcirate allow_override
allow_override = override
if method_name is None:
method_name = get_funcname(func)
if force:
allow_override = True
allow_main = True
old_method = getattr(self, method_name, None)
# Bind function to the class instance
#new_method = types.MethodType(func, self, self.__class__)
new_method = func.__get__(self, self.__class__)
#new_method = profile(func.__get__(self, self.__class__))
if old_method is not None:
old_im_func = get_method_func(old_method)
new_im_func = get_method_func(new_method)
if not allow_main and old_im_func is not None and (
get_funcglobals(old_im_func)['__name__'] != '__main__' and
get_funcglobals(new_im_func)['__name__'] == '__main__'):
if True or VERBOSE_CLASS:
print('[util_class] skipping re-inject of %r from __main__' % method_name)
return
if old_method is new_method or old_im_func is new_im_func:
#if verbose and util_arg.NOT_QUIET:
# print('WARNING: Skipping injecting the same function twice: %r' % new_method)
#print('WARNING: Injecting the same function twice: %r' % new_method)
return
elif allow_override is False:
raise AssertionError(
'Overrides are not allowed. Already have method_name=%r' %
(method_name))
elif allow_override == 'warn':
print(
'WARNING: Overrides are not allowed. Already have method_name=%r. Skipping' %
(method_name))
return
elif allow_override == 'override+warn':
#import utool as ut
#ut.embed()
print('WARNING: Overrides are allowed, but dangerous. method_name=%r.' %
(method_name))
print('old_method = %r, im_func=%s' % (old_method, str(old_im_func)))
print('new_method = %r, im_func=%s' % (new_method, str(new_im_func)))
print(get_funcglobals(old_im_func)['__name__'])
print(get_funcglobals(new_im_func)['__name__'])
# TODO: does this actually decrement the refcount enough?
del old_method
setattr(self, method_name, new_method) | [
"def",
"inject_func_as_method",
"(",
"self",
",",
"func",
",",
"method_name",
"=",
"None",
",",
"class_",
"=",
"None",
",",
"allow_override",
"=",
"False",
",",
"allow_main",
"=",
"False",
",",
"verbose",
"=",
"True",
",",
"override",
"=",
"None",
",",
"force",
"=",
"False",
")",
":",
"if",
"override",
"is",
"not",
"None",
":",
"# TODO depcirate allow_override",
"allow_override",
"=",
"override",
"if",
"method_name",
"is",
"None",
":",
"method_name",
"=",
"get_funcname",
"(",
"func",
")",
"if",
"force",
":",
"allow_override",
"=",
"True",
"allow_main",
"=",
"True",
"old_method",
"=",
"getattr",
"(",
"self",
",",
"method_name",
",",
"None",
")",
"# Bind function to the class instance",
"#new_method = types.MethodType(func, self, self.__class__)",
"new_method",
"=",
"func",
".",
"__get__",
"(",
"self",
",",
"self",
".",
"__class__",
")",
"#new_method = profile(func.__get__(self, self.__class__))",
"if",
"old_method",
"is",
"not",
"None",
":",
"old_im_func",
"=",
"get_method_func",
"(",
"old_method",
")",
"new_im_func",
"=",
"get_method_func",
"(",
"new_method",
")",
"if",
"not",
"allow_main",
"and",
"old_im_func",
"is",
"not",
"None",
"and",
"(",
"get_funcglobals",
"(",
"old_im_func",
")",
"[",
"'__name__'",
"]",
"!=",
"'__main__'",
"and",
"get_funcglobals",
"(",
"new_im_func",
")",
"[",
"'__name__'",
"]",
"==",
"'__main__'",
")",
":",
"if",
"True",
"or",
"VERBOSE_CLASS",
":",
"print",
"(",
"'[util_class] skipping re-inject of %r from __main__'",
"%",
"method_name",
")",
"return",
"if",
"old_method",
"is",
"new_method",
"or",
"old_im_func",
"is",
"new_im_func",
":",
"#if verbose and util_arg.NOT_QUIET:",
"# print('WARNING: Skipping injecting the same function twice: %r' % new_method)",
"#print('WARNING: Injecting the same function twice: %r' % new_method)",
"return",
"elif",
"allow_override",
"is",
"False",
":",
"raise",
"AssertionError",
"(",
"'Overrides are not allowed. Already have method_name=%r'",
"%",
"(",
"method_name",
")",
")",
"elif",
"allow_override",
"==",
"'warn'",
":",
"print",
"(",
"'WARNING: Overrides are not allowed. Already have method_name=%r. Skipping'",
"%",
"(",
"method_name",
")",
")",
"return",
"elif",
"allow_override",
"==",
"'override+warn'",
":",
"#import utool as ut",
"#ut.embed()",
"print",
"(",
"'WARNING: Overrides are allowed, but dangerous. method_name=%r.'",
"%",
"(",
"method_name",
")",
")",
"print",
"(",
"'old_method = %r, im_func=%s'",
"%",
"(",
"old_method",
",",
"str",
"(",
"old_im_func",
")",
")",
")",
"print",
"(",
"'new_method = %r, im_func=%s'",
"%",
"(",
"new_method",
",",
"str",
"(",
"new_im_func",
")",
")",
")",
"print",
"(",
"get_funcglobals",
"(",
"old_im_func",
")",
"[",
"'__name__'",
"]",
")",
"print",
"(",
"get_funcglobals",
"(",
"new_im_func",
")",
"[",
"'__name__'",
"]",
")",
"# TODO: does this actually decrement the refcount enough?",
"del",
"old_method",
"setattr",
"(",
"self",
",",
"method_name",
",",
"new_method",
")"
] | Injects a function into an object as a method
Wraps func as a bound method of self. Then injects func into self
It is preferable to use make_class_method_decorator and inject_instance
Args:
self (object): class instance
func : some function whos first arugment is a class instance
method_name (str) : default=func.__name__, if specified renames the method
class_ (type) : if func is an unbound method of this class
References:
http://stackoverflow.com/questions/1015307/python-bind-an-unbound-method | [
"Injects",
"a",
"function",
"into",
"an",
"object",
"as",
"a",
"method"
] | 3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a | https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/util_class.py#L454-L520 | train |
Erotemic/utool | utool/util_class.py | inject_func_as_unbound_method | def inject_func_as_unbound_method(class_, func, method_name=None):
""" This is actually quite simple """
if method_name is None:
method_name = get_funcname(func)
setattr(class_, method_name, func) | python | def inject_func_as_unbound_method(class_, func, method_name=None):
""" This is actually quite simple """
if method_name is None:
method_name = get_funcname(func)
setattr(class_, method_name, func) | [
"def",
"inject_func_as_unbound_method",
"(",
"class_",
",",
"func",
",",
"method_name",
"=",
"None",
")",
":",
"if",
"method_name",
"is",
"None",
":",
"method_name",
"=",
"get_funcname",
"(",
"func",
")",
"setattr",
"(",
"class_",
",",
"method_name",
",",
"func",
")"
] | This is actually quite simple | [
"This",
"is",
"actually",
"quite",
"simple"
] | 3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a | https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/util_class.py#L538-L542 | train |
Erotemic/utool | utool/util_class.py | reloading_meta_metaclass_factory | def reloading_meta_metaclass_factory(BASE_TYPE=type):
""" hack for pyqt """
class ReloadingMetaclass2(BASE_TYPE):
def __init__(metaself, name, bases, dct):
super(ReloadingMetaclass2, metaself).__init__(name, bases, dct)
#print('Making rrr for %r' % (name,))
metaself.rrr = reload_class
return ReloadingMetaclass2 | python | def reloading_meta_metaclass_factory(BASE_TYPE=type):
""" hack for pyqt """
class ReloadingMetaclass2(BASE_TYPE):
def __init__(metaself, name, bases, dct):
super(ReloadingMetaclass2, metaself).__init__(name, bases, dct)
#print('Making rrr for %r' % (name,))
metaself.rrr = reload_class
return ReloadingMetaclass2 | [
"def",
"reloading_meta_metaclass_factory",
"(",
"BASE_TYPE",
"=",
"type",
")",
":",
"class",
"ReloadingMetaclass2",
"(",
"BASE_TYPE",
")",
":",
"def",
"__init__",
"(",
"metaself",
",",
"name",
",",
"bases",
",",
"dct",
")",
":",
"super",
"(",
"ReloadingMetaclass2",
",",
"metaself",
")",
".",
"__init__",
"(",
"name",
",",
"bases",
",",
"dct",
")",
"#print('Making rrr for %r' % (name,))",
"metaself",
".",
"rrr",
"=",
"reload_class",
"return",
"ReloadingMetaclass2"
] | hack for pyqt | [
"hack",
"for",
"pyqt"
] | 3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a | https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/util_class.py#L695-L702 | train |
Erotemic/utool | utool/util_class.py | reload_class | def reload_class(self, verbose=True, reload_module=True):
"""
special class reloading function
This function is often injected as rrr of classes
"""
import utool as ut
verbose = verbose or VERBOSE_CLASS
classname = self.__class__.__name__
try:
modname = self.__class__.__module__
if verbose:
print('[class] reloading ' + classname + ' from ' + modname)
# --HACK--
if hasattr(self, '_on_reload'):
if verbose > 1:
print('[class] calling _on_reload for ' + classname)
self._on_reload()
elif verbose > 1:
print('[class] ' + classname + ' does not have an _on_reload function')
# Do for all inheriting classes
def find_base_clases(_class, find_base_clases=None):
class_list = []
for _baseclass in _class.__bases__:
parents = find_base_clases(_baseclass, find_base_clases)
class_list.extend(parents)
if _class is not object:
class_list.append(_class)
return class_list
head_class = self.__class__
# Determine if parents need reloading
class_list = find_base_clases(head_class, find_base_clases)
# HACK
ignore = {HashComparable2}
class_list = [_class for _class in class_list
if _class not in ignore]
for _class in class_list:
if verbose:
print('[class] reloading parent ' + _class.__name__ +
' from ' + _class.__module__)
if _class.__module__ == '__main__':
# Attempt to find the module that is the main module
# This may be very hacky and potentially break
main_module_ = sys.modules[_class.__module__]
main_modname = ut.get_modname_from_modpath(main_module_.__file__)
module_ = sys.modules[main_modname]
else:
module_ = sys.modules[_class.__module__]
if hasattr(module_, 'rrr'):
if reload_module:
module_.rrr(verbose=verbose)
else:
if reload_module:
import imp
if verbose:
print('[class] reloading ' + _class.__module__ + ' with imp')
try:
imp.reload(module_)
except (ImportError, AttributeError):
print('[class] fallback reloading ' + _class.__module__ +
' with imp')
# one last thing to try. probably used ut.import_module_from_fpath
# when importing this module
imp.load_source(module_.__name__, module_.__file__)
# Reset class attributes
_newclass = getattr(module_, _class.__name__)
reload_class_methods(self, _newclass, verbose=verbose)
# --HACK--
# TODO: handle injected definitions
if hasattr(self, '_initialize_self'):
if verbose > 1:
print('[class] calling _initialize_self for ' + classname)
self._initialize_self()
elif verbose > 1:
print('[class] ' + classname + ' does not have an _initialize_self function')
except Exception as ex:
ut.printex(ex, 'Error Reloading Class', keys=[
'modname', 'module', 'class_', 'class_list', 'self', ])
raise | python | def reload_class(self, verbose=True, reload_module=True):
"""
special class reloading function
This function is often injected as rrr of classes
"""
import utool as ut
verbose = verbose or VERBOSE_CLASS
classname = self.__class__.__name__
try:
modname = self.__class__.__module__
if verbose:
print('[class] reloading ' + classname + ' from ' + modname)
# --HACK--
if hasattr(self, '_on_reload'):
if verbose > 1:
print('[class] calling _on_reload for ' + classname)
self._on_reload()
elif verbose > 1:
print('[class] ' + classname + ' does not have an _on_reload function')
# Do for all inheriting classes
def find_base_clases(_class, find_base_clases=None):
class_list = []
for _baseclass in _class.__bases__:
parents = find_base_clases(_baseclass, find_base_clases)
class_list.extend(parents)
if _class is not object:
class_list.append(_class)
return class_list
head_class = self.__class__
# Determine if parents need reloading
class_list = find_base_clases(head_class, find_base_clases)
# HACK
ignore = {HashComparable2}
class_list = [_class for _class in class_list
if _class not in ignore]
for _class in class_list:
if verbose:
print('[class] reloading parent ' + _class.__name__ +
' from ' + _class.__module__)
if _class.__module__ == '__main__':
# Attempt to find the module that is the main module
# This may be very hacky and potentially break
main_module_ = sys.modules[_class.__module__]
main_modname = ut.get_modname_from_modpath(main_module_.__file__)
module_ = sys.modules[main_modname]
else:
module_ = sys.modules[_class.__module__]
if hasattr(module_, 'rrr'):
if reload_module:
module_.rrr(verbose=verbose)
else:
if reload_module:
import imp
if verbose:
print('[class] reloading ' + _class.__module__ + ' with imp')
try:
imp.reload(module_)
except (ImportError, AttributeError):
print('[class] fallback reloading ' + _class.__module__ +
' with imp')
# one last thing to try. probably used ut.import_module_from_fpath
# when importing this module
imp.load_source(module_.__name__, module_.__file__)
# Reset class attributes
_newclass = getattr(module_, _class.__name__)
reload_class_methods(self, _newclass, verbose=verbose)
# --HACK--
# TODO: handle injected definitions
if hasattr(self, '_initialize_self'):
if verbose > 1:
print('[class] calling _initialize_self for ' + classname)
self._initialize_self()
elif verbose > 1:
print('[class] ' + classname + ' does not have an _initialize_self function')
except Exception as ex:
ut.printex(ex, 'Error Reloading Class', keys=[
'modname', 'module', 'class_', 'class_list', 'self', ])
raise | [
"def",
"reload_class",
"(",
"self",
",",
"verbose",
"=",
"True",
",",
"reload_module",
"=",
"True",
")",
":",
"import",
"utool",
"as",
"ut",
"verbose",
"=",
"verbose",
"or",
"VERBOSE_CLASS",
"classname",
"=",
"self",
".",
"__class__",
".",
"__name__",
"try",
":",
"modname",
"=",
"self",
".",
"__class__",
".",
"__module__",
"if",
"verbose",
":",
"print",
"(",
"'[class] reloading '",
"+",
"classname",
"+",
"' from '",
"+",
"modname",
")",
"# --HACK--",
"if",
"hasattr",
"(",
"self",
",",
"'_on_reload'",
")",
":",
"if",
"verbose",
">",
"1",
":",
"print",
"(",
"'[class] calling _on_reload for '",
"+",
"classname",
")",
"self",
".",
"_on_reload",
"(",
")",
"elif",
"verbose",
">",
"1",
":",
"print",
"(",
"'[class] '",
"+",
"classname",
"+",
"' does not have an _on_reload function'",
")",
"# Do for all inheriting classes",
"def",
"find_base_clases",
"(",
"_class",
",",
"find_base_clases",
"=",
"None",
")",
":",
"class_list",
"=",
"[",
"]",
"for",
"_baseclass",
"in",
"_class",
".",
"__bases__",
":",
"parents",
"=",
"find_base_clases",
"(",
"_baseclass",
",",
"find_base_clases",
")",
"class_list",
".",
"extend",
"(",
"parents",
")",
"if",
"_class",
"is",
"not",
"object",
":",
"class_list",
".",
"append",
"(",
"_class",
")",
"return",
"class_list",
"head_class",
"=",
"self",
".",
"__class__",
"# Determine if parents need reloading",
"class_list",
"=",
"find_base_clases",
"(",
"head_class",
",",
"find_base_clases",
")",
"# HACK",
"ignore",
"=",
"{",
"HashComparable2",
"}",
"class_list",
"=",
"[",
"_class",
"for",
"_class",
"in",
"class_list",
"if",
"_class",
"not",
"in",
"ignore",
"]",
"for",
"_class",
"in",
"class_list",
":",
"if",
"verbose",
":",
"print",
"(",
"'[class] reloading parent '",
"+",
"_class",
".",
"__name__",
"+",
"' from '",
"+",
"_class",
".",
"__module__",
")",
"if",
"_class",
".",
"__module__",
"==",
"'__main__'",
":",
"# Attempt to find the module that is the main module",
"# This may be very hacky and potentially break",
"main_module_",
"=",
"sys",
".",
"modules",
"[",
"_class",
".",
"__module__",
"]",
"main_modname",
"=",
"ut",
".",
"get_modname_from_modpath",
"(",
"main_module_",
".",
"__file__",
")",
"module_",
"=",
"sys",
".",
"modules",
"[",
"main_modname",
"]",
"else",
":",
"module_",
"=",
"sys",
".",
"modules",
"[",
"_class",
".",
"__module__",
"]",
"if",
"hasattr",
"(",
"module_",
",",
"'rrr'",
")",
":",
"if",
"reload_module",
":",
"module_",
".",
"rrr",
"(",
"verbose",
"=",
"verbose",
")",
"else",
":",
"if",
"reload_module",
":",
"import",
"imp",
"if",
"verbose",
":",
"print",
"(",
"'[class] reloading '",
"+",
"_class",
".",
"__module__",
"+",
"' with imp'",
")",
"try",
":",
"imp",
".",
"reload",
"(",
"module_",
")",
"except",
"(",
"ImportError",
",",
"AttributeError",
")",
":",
"print",
"(",
"'[class] fallback reloading '",
"+",
"_class",
".",
"__module__",
"+",
"' with imp'",
")",
"# one last thing to try. probably used ut.import_module_from_fpath",
"# when importing this module",
"imp",
".",
"load_source",
"(",
"module_",
".",
"__name__",
",",
"module_",
".",
"__file__",
")",
"# Reset class attributes",
"_newclass",
"=",
"getattr",
"(",
"module_",
",",
"_class",
".",
"__name__",
")",
"reload_class_methods",
"(",
"self",
",",
"_newclass",
",",
"verbose",
"=",
"verbose",
")",
"# --HACK--",
"# TODO: handle injected definitions",
"if",
"hasattr",
"(",
"self",
",",
"'_initialize_self'",
")",
":",
"if",
"verbose",
">",
"1",
":",
"print",
"(",
"'[class] calling _initialize_self for '",
"+",
"classname",
")",
"self",
".",
"_initialize_self",
"(",
")",
"elif",
"verbose",
">",
"1",
":",
"print",
"(",
"'[class] '",
"+",
"classname",
"+",
"' does not have an _initialize_self function'",
")",
"except",
"Exception",
"as",
"ex",
":",
"ut",
".",
"printex",
"(",
"ex",
",",
"'Error Reloading Class'",
",",
"keys",
"=",
"[",
"'modname'",
",",
"'module'",
",",
"'class_'",
",",
"'class_list'",
",",
"'self'",
",",
"]",
")",
"raise"
] | special class reloading function
This function is often injected as rrr of classes | [
"special",
"class",
"reloading",
"function",
"This",
"function",
"is",
"often",
"injected",
"as",
"rrr",
"of",
"classes"
] | 3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a | https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/util_class.py#L705-L785 | train |
Erotemic/utool | utool/util_class.py | reload_class_methods | def reload_class_methods(self, class_, verbose=True):
"""
rebinds all class methods
Args:
self (object): class instance to reload
class_ (type): type to reload as
Example:
>>> # DISABLE_DOCTEST
>>> from utool.util_class import * # NOQA
>>> self = '?'
>>> class_ = '?'
>>> result = reload_class_methods(self, class_)
>>> print(result)
"""
if verbose:
print('[util_class] Reloading self=%r as class_=%r' % (self, class_))
self.__class__ = class_
for key in dir(class_):
# Get unbound reloaded method
func = getattr(class_, key)
if isinstance(func, types.MethodType):
# inject it into the old instance
inject_func_as_method(self, func, class_=class_,
allow_override=True,
verbose=verbose) | python | def reload_class_methods(self, class_, verbose=True):
"""
rebinds all class methods
Args:
self (object): class instance to reload
class_ (type): type to reload as
Example:
>>> # DISABLE_DOCTEST
>>> from utool.util_class import * # NOQA
>>> self = '?'
>>> class_ = '?'
>>> result = reload_class_methods(self, class_)
>>> print(result)
"""
if verbose:
print('[util_class] Reloading self=%r as class_=%r' % (self, class_))
self.__class__ = class_
for key in dir(class_):
# Get unbound reloaded method
func = getattr(class_, key)
if isinstance(func, types.MethodType):
# inject it into the old instance
inject_func_as_method(self, func, class_=class_,
allow_override=True,
verbose=verbose) | [
"def",
"reload_class_methods",
"(",
"self",
",",
"class_",
",",
"verbose",
"=",
"True",
")",
":",
"if",
"verbose",
":",
"print",
"(",
"'[util_class] Reloading self=%r as class_=%r'",
"%",
"(",
"self",
",",
"class_",
")",
")",
"self",
".",
"__class__",
"=",
"class_",
"for",
"key",
"in",
"dir",
"(",
"class_",
")",
":",
"# Get unbound reloaded method",
"func",
"=",
"getattr",
"(",
"class_",
",",
"key",
")",
"if",
"isinstance",
"(",
"func",
",",
"types",
".",
"MethodType",
")",
":",
"# inject it into the old instance",
"inject_func_as_method",
"(",
"self",
",",
"func",
",",
"class_",
"=",
"class_",
",",
"allow_override",
"=",
"True",
",",
"verbose",
"=",
"verbose",
")"
] | rebinds all class methods
Args:
self (object): class instance to reload
class_ (type): type to reload as
Example:
>>> # DISABLE_DOCTEST
>>> from utool.util_class import * # NOQA
>>> self = '?'
>>> class_ = '?'
>>> result = reload_class_methods(self, class_)
>>> print(result) | [
"rebinds",
"all",
"class",
"methods"
] | 3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a | https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/util_class.py#L788-L814 | train |
Erotemic/utool | utool/util_class.py | remove_private_obfuscation | def remove_private_obfuscation(self):
"""
removes the python obfuscation of class privates so they can be executed as
they appear in class source. Useful when playing with IPython.
"""
classname = self.__class__.__name__
attrlist = [attr for attr in dir(self) if attr.startswith('_' + classname + '__')]
for attr in attrlist:
method = getattr(self, attr)
truename = attr.replace('_' + classname + '__', '__')
setattr(self, truename, method) | python | def remove_private_obfuscation(self):
"""
removes the python obfuscation of class privates so they can be executed as
they appear in class source. Useful when playing with IPython.
"""
classname = self.__class__.__name__
attrlist = [attr for attr in dir(self) if attr.startswith('_' + classname + '__')]
for attr in attrlist:
method = getattr(self, attr)
truename = attr.replace('_' + classname + '__', '__')
setattr(self, truename, method) | [
"def",
"remove_private_obfuscation",
"(",
"self",
")",
":",
"classname",
"=",
"self",
".",
"__class__",
".",
"__name__",
"attrlist",
"=",
"[",
"attr",
"for",
"attr",
"in",
"dir",
"(",
"self",
")",
"if",
"attr",
".",
"startswith",
"(",
"'_'",
"+",
"classname",
"+",
"'__'",
")",
"]",
"for",
"attr",
"in",
"attrlist",
":",
"method",
"=",
"getattr",
"(",
"self",
",",
"attr",
")",
"truename",
"=",
"attr",
".",
"replace",
"(",
"'_'",
"+",
"classname",
"+",
"'__'",
",",
"'__'",
")",
"setattr",
"(",
"self",
",",
"truename",
",",
"method",
")"
] | removes the python obfuscation of class privates so they can be executed as
they appear in class source. Useful when playing with IPython. | [
"removes",
"the",
"python",
"obfuscation",
"of",
"class",
"privates",
"so",
"they",
"can",
"be",
"executed",
"as",
"they",
"appear",
"in",
"class",
"source",
".",
"Useful",
"when",
"playing",
"with",
"IPython",
"."
] | 3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a | https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/util_class.py#L968-L978 | train |
glormph/msstitch | src/app/actions/mslookup/proteinquant.py | create_peptidequant_lookup | def create_peptidequant_lookup(fns, pqdb, poolnames, pepseq_colnr,
ms1_qcolpattern=None, isobqcolpattern=None,
psmnrpattern=None, fdrcolpattern=None,
pepcolpattern=None):
"""Calls lower level function to create a peptide quant lookup"""
patterns = [ms1_qcolpattern, fdrcolpattern, pepcolpattern]
storefuns = [pqdb.store_precursor_quants, pqdb.store_fdr,
pqdb.store_pep]
create_pep_protein_quant_lookup(fns, pqdb, poolnames, pepseq_colnr,
patterns, storefuns,
isobqcolpattern, psmnrpattern) | python | def create_peptidequant_lookup(fns, pqdb, poolnames, pepseq_colnr,
ms1_qcolpattern=None, isobqcolpattern=None,
psmnrpattern=None, fdrcolpattern=None,
pepcolpattern=None):
"""Calls lower level function to create a peptide quant lookup"""
patterns = [ms1_qcolpattern, fdrcolpattern, pepcolpattern]
storefuns = [pqdb.store_precursor_quants, pqdb.store_fdr,
pqdb.store_pep]
create_pep_protein_quant_lookup(fns, pqdb, poolnames, pepseq_colnr,
patterns, storefuns,
isobqcolpattern, psmnrpattern) | [
"def",
"create_peptidequant_lookup",
"(",
"fns",
",",
"pqdb",
",",
"poolnames",
",",
"pepseq_colnr",
",",
"ms1_qcolpattern",
"=",
"None",
",",
"isobqcolpattern",
"=",
"None",
",",
"psmnrpattern",
"=",
"None",
",",
"fdrcolpattern",
"=",
"None",
",",
"pepcolpattern",
"=",
"None",
")",
":",
"patterns",
"=",
"[",
"ms1_qcolpattern",
",",
"fdrcolpattern",
",",
"pepcolpattern",
"]",
"storefuns",
"=",
"[",
"pqdb",
".",
"store_precursor_quants",
",",
"pqdb",
".",
"store_fdr",
",",
"pqdb",
".",
"store_pep",
"]",
"create_pep_protein_quant_lookup",
"(",
"fns",
",",
"pqdb",
",",
"poolnames",
",",
"pepseq_colnr",
",",
"patterns",
",",
"storefuns",
",",
"isobqcolpattern",
",",
"psmnrpattern",
")"
] | Calls lower level function to create a peptide quant lookup | [
"Calls",
"lower",
"level",
"function",
"to",
"create",
"a",
"peptide",
"quant",
"lookup"
] | ded7e5cbd813d7797dc9d42805778266e59ff042 | https://github.com/glormph/msstitch/blob/ded7e5cbd813d7797dc9d42805778266e59ff042/src/app/actions/mslookup/proteinquant.py#L5-L15 | train |
glormph/msstitch | src/app/actions/mslookup/proteinquant.py | create_proteinquant_lookup | def create_proteinquant_lookup(fns, pqdb, poolnames, protacc_colnr,
ms1_qcolpattern=None, isobqcolpattern=None,
psmnrpattern=None, probcolpattern=None,
fdrcolpattern=None, pepcolpattern=None):
"""Calls lower level function to create a protein quant lookup"""
patterns = [ms1_qcolpattern, probcolpattern, fdrcolpattern, pepcolpattern]
storefuns = [pqdb.store_precursor_quants, pqdb.store_probability,
pqdb.store_fdr, pqdb.store_pep]
create_pep_protein_quant_lookup(fns, pqdb, poolnames, protacc_colnr,
patterns, storefuns, isobqcolpattern,
psmnrpattern) | python | def create_proteinquant_lookup(fns, pqdb, poolnames, protacc_colnr,
ms1_qcolpattern=None, isobqcolpattern=None,
psmnrpattern=None, probcolpattern=None,
fdrcolpattern=None, pepcolpattern=None):
"""Calls lower level function to create a protein quant lookup"""
patterns = [ms1_qcolpattern, probcolpattern, fdrcolpattern, pepcolpattern]
storefuns = [pqdb.store_precursor_quants, pqdb.store_probability,
pqdb.store_fdr, pqdb.store_pep]
create_pep_protein_quant_lookup(fns, pqdb, poolnames, protacc_colnr,
patterns, storefuns, isobqcolpattern,
psmnrpattern) | [
"def",
"create_proteinquant_lookup",
"(",
"fns",
",",
"pqdb",
",",
"poolnames",
",",
"protacc_colnr",
",",
"ms1_qcolpattern",
"=",
"None",
",",
"isobqcolpattern",
"=",
"None",
",",
"psmnrpattern",
"=",
"None",
",",
"probcolpattern",
"=",
"None",
",",
"fdrcolpattern",
"=",
"None",
",",
"pepcolpattern",
"=",
"None",
")",
":",
"patterns",
"=",
"[",
"ms1_qcolpattern",
",",
"probcolpattern",
",",
"fdrcolpattern",
",",
"pepcolpattern",
"]",
"storefuns",
"=",
"[",
"pqdb",
".",
"store_precursor_quants",
",",
"pqdb",
".",
"store_probability",
",",
"pqdb",
".",
"store_fdr",
",",
"pqdb",
".",
"store_pep",
"]",
"create_pep_protein_quant_lookup",
"(",
"fns",
",",
"pqdb",
",",
"poolnames",
",",
"protacc_colnr",
",",
"patterns",
",",
"storefuns",
",",
"isobqcolpattern",
",",
"psmnrpattern",
")"
] | Calls lower level function to create a protein quant lookup | [
"Calls",
"lower",
"level",
"function",
"to",
"create",
"a",
"protein",
"quant",
"lookup"
] | ded7e5cbd813d7797dc9d42805778266e59ff042 | https://github.com/glormph/msstitch/blob/ded7e5cbd813d7797dc9d42805778266e59ff042/src/app/actions/mslookup/proteinquant.py#L18-L28 | train |
glormph/msstitch | src/app/actions/mslookup/proteinquant.py | create_pep_protein_quant_lookup | def create_pep_protein_quant_lookup(fns, pqdb, poolnames, featcolnr, patterns,
storefuns, isobqcolpattern=None,
psmnrpattern=None):
"""Does the work when creating peptide and protein quant lookups. This
loops through storing options and parses columns, passing on to the
storing functions"""
tablefn_map = create_tablefn_map(fns, pqdb, poolnames)
feat_map = pqdb.get_feature_map()
for pattern, storefun in zip(patterns, storefuns):
if pattern is None:
continue
colmap = get_colmap(fns, pattern, single_col=True)
if colmap:
store_single_col_data(fns, tablefn_map, feat_map,
storefun, featcolnr, colmap)
if isobqcolpattern is not None:
isocolmap = get_colmap(fns, isobqcolpattern, antipattern=psmnrpattern)
else:
return
if psmnrpattern is not None:
psmcolmap = get_colmap(fns, psmnrpattern)
else:
psmcolmap = False
create_isobaric_quant_lookup(fns, tablefn_map,
feat_map, pqdb,
featcolnr,
isocolmap, psmcolmap) | python | def create_pep_protein_quant_lookup(fns, pqdb, poolnames, featcolnr, patterns,
storefuns, isobqcolpattern=None,
psmnrpattern=None):
"""Does the work when creating peptide and protein quant lookups. This
loops through storing options and parses columns, passing on to the
storing functions"""
tablefn_map = create_tablefn_map(fns, pqdb, poolnames)
feat_map = pqdb.get_feature_map()
for pattern, storefun in zip(patterns, storefuns):
if pattern is None:
continue
colmap = get_colmap(fns, pattern, single_col=True)
if colmap:
store_single_col_data(fns, tablefn_map, feat_map,
storefun, featcolnr, colmap)
if isobqcolpattern is not None:
isocolmap = get_colmap(fns, isobqcolpattern, antipattern=psmnrpattern)
else:
return
if psmnrpattern is not None:
psmcolmap = get_colmap(fns, psmnrpattern)
else:
psmcolmap = False
create_isobaric_quant_lookup(fns, tablefn_map,
feat_map, pqdb,
featcolnr,
isocolmap, psmcolmap) | [
"def",
"create_pep_protein_quant_lookup",
"(",
"fns",
",",
"pqdb",
",",
"poolnames",
",",
"featcolnr",
",",
"patterns",
",",
"storefuns",
",",
"isobqcolpattern",
"=",
"None",
",",
"psmnrpattern",
"=",
"None",
")",
":",
"tablefn_map",
"=",
"create_tablefn_map",
"(",
"fns",
",",
"pqdb",
",",
"poolnames",
")",
"feat_map",
"=",
"pqdb",
".",
"get_feature_map",
"(",
")",
"for",
"pattern",
",",
"storefun",
"in",
"zip",
"(",
"patterns",
",",
"storefuns",
")",
":",
"if",
"pattern",
"is",
"None",
":",
"continue",
"colmap",
"=",
"get_colmap",
"(",
"fns",
",",
"pattern",
",",
"single_col",
"=",
"True",
")",
"if",
"colmap",
":",
"store_single_col_data",
"(",
"fns",
",",
"tablefn_map",
",",
"feat_map",
",",
"storefun",
",",
"featcolnr",
",",
"colmap",
")",
"if",
"isobqcolpattern",
"is",
"not",
"None",
":",
"isocolmap",
"=",
"get_colmap",
"(",
"fns",
",",
"isobqcolpattern",
",",
"antipattern",
"=",
"psmnrpattern",
")",
"else",
":",
"return",
"if",
"psmnrpattern",
"is",
"not",
"None",
":",
"psmcolmap",
"=",
"get_colmap",
"(",
"fns",
",",
"psmnrpattern",
")",
"else",
":",
"psmcolmap",
"=",
"False",
"create_isobaric_quant_lookup",
"(",
"fns",
",",
"tablefn_map",
",",
"feat_map",
",",
"pqdb",
",",
"featcolnr",
",",
"isocolmap",
",",
"psmcolmap",
")"
] | Does the work when creating peptide and protein quant lookups. This
loops through storing options and parses columns, passing on to the
storing functions | [
"Does",
"the",
"work",
"when",
"creating",
"peptide",
"and",
"protein",
"quant",
"lookups",
".",
"This",
"loops",
"through",
"storing",
"options",
"and",
"parses",
"columns",
"passing",
"on",
"to",
"the",
"storing",
"functions"
] | ded7e5cbd813d7797dc9d42805778266e59ff042 | https://github.com/glormph/msstitch/blob/ded7e5cbd813d7797dc9d42805778266e59ff042/src/app/actions/mslookup/proteinquant.py#L31-L57 | train |
glormph/msstitch | src/app/actions/mslookup/proteinquant.py | store_single_col_data | def store_single_col_data(fns, prottable_id_map, pacc_map, pqdbmethod,
protacc_colnr, colmap):
"""General method to store single column data from protein tables
in lookup"""
to_store = []
for fn, header, pquant in tsvreader.generate_tsv_pep_protein_quants(fns):
pacc_id = pacc_map[pquant[header[protacc_colnr]]]
pqdata = (pacc_id, prottable_id_map[fn], pquant[colmap[fn]])
to_store.append(pqdata)
if len(to_store) > 10000:
pqdbmethod(to_store)
to_store = []
pqdbmethod(to_store) | python | def store_single_col_data(fns, prottable_id_map, pacc_map, pqdbmethod,
protacc_colnr, colmap):
"""General method to store single column data from protein tables
in lookup"""
to_store = []
for fn, header, pquant in tsvreader.generate_tsv_pep_protein_quants(fns):
pacc_id = pacc_map[pquant[header[protacc_colnr]]]
pqdata = (pacc_id, prottable_id_map[fn], pquant[colmap[fn]])
to_store.append(pqdata)
if len(to_store) > 10000:
pqdbmethod(to_store)
to_store = []
pqdbmethod(to_store) | [
"def",
"store_single_col_data",
"(",
"fns",
",",
"prottable_id_map",
",",
"pacc_map",
",",
"pqdbmethod",
",",
"protacc_colnr",
",",
"colmap",
")",
":",
"to_store",
"=",
"[",
"]",
"for",
"fn",
",",
"header",
",",
"pquant",
"in",
"tsvreader",
".",
"generate_tsv_pep_protein_quants",
"(",
"fns",
")",
":",
"pacc_id",
"=",
"pacc_map",
"[",
"pquant",
"[",
"header",
"[",
"protacc_colnr",
"]",
"]",
"]",
"pqdata",
"=",
"(",
"pacc_id",
",",
"prottable_id_map",
"[",
"fn",
"]",
",",
"pquant",
"[",
"colmap",
"[",
"fn",
"]",
"]",
")",
"to_store",
".",
"append",
"(",
"pqdata",
")",
"if",
"len",
"(",
"to_store",
")",
">",
"10000",
":",
"pqdbmethod",
"(",
"to_store",
")",
"to_store",
"=",
"[",
"]",
"pqdbmethod",
"(",
"to_store",
")"
] | General method to store single column data from protein tables
in lookup | [
"General",
"method",
"to",
"store",
"single",
"column",
"data",
"from",
"protein",
"tables",
"in",
"lookup"
] | ded7e5cbd813d7797dc9d42805778266e59ff042 | https://github.com/glormph/msstitch/blob/ded7e5cbd813d7797dc9d42805778266e59ff042/src/app/actions/mslookup/proteinquant.py#L87-L99 | train |
glormph/msstitch | src/app/actions/mslookup/proteinquant.py | map_psmnrcol_to_quantcol | def map_psmnrcol_to_quantcol(quantcols, psmcols, tablefn_map):
"""This function yields tuples of table filename, isobaric quant column
and if necessary number-of-PSM column"""
if not psmcols:
for fn in quantcols:
for qcol in quantcols[fn]:
yield (tablefn_map[fn], qcol)
else:
for fn in quantcols:
for qcol, psmcol in zip(quantcols[fn], psmcols[fn]):
yield (tablefn_map[fn], qcol, psmcol) | python | def map_psmnrcol_to_quantcol(quantcols, psmcols, tablefn_map):
"""This function yields tuples of table filename, isobaric quant column
and if necessary number-of-PSM column"""
if not psmcols:
for fn in quantcols:
for qcol in quantcols[fn]:
yield (tablefn_map[fn], qcol)
else:
for fn in quantcols:
for qcol, psmcol in zip(quantcols[fn], psmcols[fn]):
yield (tablefn_map[fn], qcol, psmcol) | [
"def",
"map_psmnrcol_to_quantcol",
"(",
"quantcols",
",",
"psmcols",
",",
"tablefn_map",
")",
":",
"if",
"not",
"psmcols",
":",
"for",
"fn",
"in",
"quantcols",
":",
"for",
"qcol",
"in",
"quantcols",
"[",
"fn",
"]",
":",
"yield",
"(",
"tablefn_map",
"[",
"fn",
"]",
",",
"qcol",
")",
"else",
":",
"for",
"fn",
"in",
"quantcols",
":",
"for",
"qcol",
",",
"psmcol",
"in",
"zip",
"(",
"quantcols",
"[",
"fn",
"]",
",",
"psmcols",
"[",
"fn",
"]",
")",
":",
"yield",
"(",
"tablefn_map",
"[",
"fn",
"]",
",",
"qcol",
",",
"psmcol",
")"
] | This function yields tuples of table filename, isobaric quant column
and if necessary number-of-PSM column | [
"This",
"function",
"yields",
"tuples",
"of",
"table",
"filename",
"isobaric",
"quant",
"column",
"and",
"if",
"necessary",
"number",
"-",
"of",
"-",
"PSM",
"column"
] | ded7e5cbd813d7797dc9d42805778266e59ff042 | https://github.com/glormph/msstitch/blob/ded7e5cbd813d7797dc9d42805778266e59ff042/src/app/actions/mslookup/proteinquant.py#L122-L132 | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.