repository_name
stringlengths
7
55
func_path_in_repository
stringlengths
4
223
func_name
stringlengths
1
134
whole_func_string
stringlengths
75
104k
language
stringclasses
1 value
func_code_string
stringlengths
75
104k
func_code_tokens
listlengths
19
28.4k
func_documentation_string
stringlengths
1
46.9k
func_documentation_tokens
listlengths
1
1.97k
split_name
stringclasses
1 value
func_code_url
stringlengths
87
315
belbio/bel
bel/utils.py
download_file
def download_file(url): """Download file""" response = requests.get(url, stream=True) fp = tempfile.NamedTemporaryFile() for chunk in response.iter_content(chunk_size=1024): if chunk: # filter out keep-alive new chunks fp.write(chunk) # log.info(f'Download file - tmp file: {fp...
python
def download_file(url): """Download file""" response = requests.get(url, stream=True) fp = tempfile.NamedTemporaryFile() for chunk in response.iter_content(chunk_size=1024): if chunk: # filter out keep-alive new chunks fp.write(chunk) # log.info(f'Download file - tmp file: {fp...
[ "def", "download_file", "(", "url", ")", ":", "response", "=", "requests", ".", "get", "(", "url", ",", "stream", "=", "True", ")", "fp", "=", "tempfile", ".", "NamedTemporaryFile", "(", ")", "for", "chunk", "in", "response", ".", "iter_content", "(", ...
Download file
[ "Download", "file" ]
train
https://github.com/belbio/bel/blob/60333e8815625b942b4836903f3b618cf44b3771/bel/utils.py#L67-L77
belbio/bel
bel/utils.py
first_true
def first_true(iterable, default=False, pred=None): """Returns the first true value in the iterable. If no true value is found, returns *default* If *pred* is not None, returns the first item for which pred(item) is true. """ # first_true([a,b,c], x) --> a or b or c or x # first_true([a,b...
python
def first_true(iterable, default=False, pred=None): """Returns the first true value in the iterable. If no true value is found, returns *default* If *pred* is not None, returns the first item for which pred(item) is true. """ # first_true([a,b,c], x) --> a or b or c or x # first_true([a,b...
[ "def", "first_true", "(", "iterable", ",", "default", "=", "False", ",", "pred", "=", "None", ")", ":", "# first_true([a,b,c], x) --> a or b or c or x", "# first_true([a,b], x, f) --> a if f(a) else b if f(b) else x", "return", "next", "(", "filter", "(", "pred", ",", "...
Returns the first true value in the iterable. If no true value is found, returns *default* If *pred* is not None, returns the first item for which pred(item) is true.
[ "Returns", "the", "first", "true", "value", "in", "the", "iterable", "." ]
train
https://github.com/belbio/bel/blob/60333e8815625b942b4836903f3b618cf44b3771/bel/utils.py#L90-L101
belbio/bel
bel/utils.py
_create_hash_from_doc
def _create_hash_from_doc(doc: Mapping[str, Any]) -> str: """Create hash Id from edge record Args: edge (Mapping[str, Any]): edge record to create hash from Returns: str: Murmur3 128 bit hash """ doc_string = json.dumps(doc, sort_keys=True) return _create_hash(doc_string)
python
def _create_hash_from_doc(doc: Mapping[str, Any]) -> str: """Create hash Id from edge record Args: edge (Mapping[str, Any]): edge record to create hash from Returns: str: Murmur3 128 bit hash """ doc_string = json.dumps(doc, sort_keys=True) return _create_hash(doc_string)
[ "def", "_create_hash_from_doc", "(", "doc", ":", "Mapping", "[", "str", ",", "Any", "]", ")", "->", "str", ":", "doc_string", "=", "json", ".", "dumps", "(", "doc", ",", "sort_keys", "=", "True", ")", "return", "_create_hash", "(", "doc_string", ")" ]
Create hash Id from edge record Args: edge (Mapping[str, Any]): edge record to create hash from Returns: str: Murmur3 128 bit hash
[ "Create", "hash", "Id", "from", "edge", "record" ]
train
https://github.com/belbio/bel/blob/60333e8815625b942b4836903f3b618cf44b3771/bel/utils.py#L104-L115
belbio/bel
bel/utils.py
Timer.elapsed
def elapsed(self): """ Return the current elapsed time since start If the `elapsed` property is called in the context manager scope, the elapsed time bewteen start and property access is returned. However, if it is accessed outside of the context manager scope, it returns the ela...
python
def elapsed(self): """ Return the current elapsed time since start If the `elapsed` property is called in the context manager scope, the elapsed time bewteen start and property access is returned. However, if it is accessed outside of the context manager scope, it returns the ela...
[ "def", "elapsed", "(", "self", ")", ":", "if", "self", ".", "end", "is", "None", ":", "# if elapsed is called in the context manager scope", "return", "(", "self", "(", ")", "-", "self", ".", "start", ")", "*", "self", ".", "factor", "else", ":", "# if ela...
Return the current elapsed time since start If the `elapsed` property is called in the context manager scope, the elapsed time bewteen start and property access is returned. However, if it is accessed outside of the context manager scope, it returns the elapsed time bewteen entering and ...
[ "Return", "the", "current", "elapsed", "time", "since", "start", "If", "the", "elapsed", "property", "is", "called", "in", "the", "context", "manager", "scope", "the", "elapsed", "time", "bewteen", "start", "and", "property", "access", "is", "returned", ".", ...
train
https://github.com/belbio/bel/blob/60333e8815625b942b4836903f3b618cf44b3771/bel/utils.py#L245-L259
belbio/bel
bel/edge/pipeline.py
load_edges_into_db
def load_edges_into_db( nanopub_id: str, nanopub_url: str, edges: list = [], edges_coll_name: str = edges_coll_name, nodes_coll_name: str = nodes_coll_name, ): """Load edges into Edgestore""" start_time = datetime.datetime.now() # Clean out edges for nanopub in edgestore query = f"...
python
def load_edges_into_db( nanopub_id: str, nanopub_url: str, edges: list = [], edges_coll_name: str = edges_coll_name, nodes_coll_name: str = nodes_coll_name, ): """Load edges into Edgestore""" start_time = datetime.datetime.now() # Clean out edges for nanopub in edgestore query = f"...
[ "def", "load_edges_into_db", "(", "nanopub_id", ":", "str", ",", "nanopub_url", ":", "str", ",", "edges", ":", "list", "=", "[", "]", ",", "edges_coll_name", ":", "str", "=", "edges_coll_name", ",", "nodes_coll_name", ":", "str", "=", "nodes_coll_name", ",",...
Load edges into Edgestore
[ "Load", "edges", "into", "Edgestore" ]
train
https://github.com/belbio/bel/blob/60333e8815625b942b4836903f3b618cf44b3771/bel/edge/pipeline.py#L141-L215
belbio/bel
bel/edge/pipeline.py
edge_iterator
def edge_iterator(edges=[], edges_fn=None): """Yield documents from edge for loading into ArangoDB""" for edge in itertools.chain(edges, files.read_edges(edges_fn)): subj = copy.deepcopy(edge["edge"]["subject"]) subj_id = str(utils._create_hash_from_doc(subj)) subj["_key"] = subj_id ...
python
def edge_iterator(edges=[], edges_fn=None): """Yield documents from edge for loading into ArangoDB""" for edge in itertools.chain(edges, files.read_edges(edges_fn)): subj = copy.deepcopy(edge["edge"]["subject"]) subj_id = str(utils._create_hash_from_doc(subj)) subj["_key"] = subj_id ...
[ "def", "edge_iterator", "(", "edges", "=", "[", "]", ",", "edges_fn", "=", "None", ")", ":", "for", "edge", "in", "itertools", ".", "chain", "(", "edges", ",", "files", ".", "read_edges", "(", "edges_fn", ")", ")", ":", "subj", "=", "copy", ".", "d...
Yield documents from edge for loading into ArangoDB
[ "Yield", "documents", "from", "edge", "for", "loading", "into", "ArangoDB" ]
train
https://github.com/belbio/bel/blob/60333e8815625b942b4836903f3b618cf44b3771/bel/edge/pipeline.py#L218-L256
belbio/bel
bel/nanopub/nanopubstore.py
update_nanopubstore_start_dt
def update_nanopubstore_start_dt(url: str, start_dt: str): """Add nanopubstore start_dt to belapi.state_mgmt collection Args: url: url of nanopubstore start_dt: datetime of last query against nanopubstore for new ID's """ hostname = urllib.parse.urlsplit(url)[1] start_dates_doc = ...
python
def update_nanopubstore_start_dt(url: str, start_dt: str): """Add nanopubstore start_dt to belapi.state_mgmt collection Args: url: url of nanopubstore start_dt: datetime of last query against nanopubstore for new ID's """ hostname = urllib.parse.urlsplit(url)[1] start_dates_doc = ...
[ "def", "update_nanopubstore_start_dt", "(", "url", ":", "str", ",", "start_dt", ":", "str", ")", ":", "hostname", "=", "urllib", ".", "parse", ".", "urlsplit", "(", "url", ")", "[", "1", "]", "start_dates_doc", "=", "state_mgmt", ".", "get", "(", "start_...
Add nanopubstore start_dt to belapi.state_mgmt collection Args: url: url of nanopubstore start_dt: datetime of last query against nanopubstore for new ID's
[ "Add", "nanopubstore", "start_dt", "to", "belapi", ".", "state_mgmt", "collection" ]
train
https://github.com/belbio/bel/blob/60333e8815625b942b4836903f3b618cf44b3771/bel/nanopub/nanopubstore.py#L23-L50
belbio/bel
bel/nanopub/nanopubstore.py
get_nanopubstore_start_dt
def get_nanopubstore_start_dt(url: str): """Get last start_dt recorded for getting new nanopub ID's""" hostname = urllib.parse.urlsplit(url)[1] start_dates_doc = state_mgmt.get(start_dates_doc_key) if start_dates_doc and start_dates_doc.get("start_dates"): date = [ dt["start_dt"] ...
python
def get_nanopubstore_start_dt(url: str): """Get last start_dt recorded for getting new nanopub ID's""" hostname = urllib.parse.urlsplit(url)[1] start_dates_doc = state_mgmt.get(start_dates_doc_key) if start_dates_doc and start_dates_doc.get("start_dates"): date = [ dt["start_dt"] ...
[ "def", "get_nanopubstore_start_dt", "(", "url", ":", "str", ")", ":", "hostname", "=", "urllib", ".", "parse", ".", "urlsplit", "(", "url", ")", "[", "1", "]", "start_dates_doc", "=", "state_mgmt", ".", "get", "(", "start_dates_doc_key", ")", "if", "start_...
Get last start_dt recorded for getting new nanopub ID's
[ "Get", "last", "start_dt", "recorded", "for", "getting", "new", "nanopub", "ID", "s" ]
train
https://github.com/belbio/bel/blob/60333e8815625b942b4836903f3b618cf44b3771/bel/nanopub/nanopubstore.py#L53-L69
belbio/bel
bel/nanopub/nanopubstore.py
get_nanopub_urls
def get_nanopub_urls(ns_root_url: str = None, start_dt: str = None) -> dict: """Get modified and deleted nanopub urls Limited by last datetime retrieved (start_dt). Modified includes new and updated nanopubs Returns: dict: {'modified': [], 'deleted': []} """ if not ns_root_url: ns...
python
def get_nanopub_urls(ns_root_url: str = None, start_dt: str = None) -> dict: """Get modified and deleted nanopub urls Limited by last datetime retrieved (start_dt). Modified includes new and updated nanopubs Returns: dict: {'modified': [], 'deleted': []} """ if not ns_root_url: ns...
[ "def", "get_nanopub_urls", "(", "ns_root_url", ":", "str", "=", "None", ",", "start_dt", ":", "str", "=", "None", ")", "->", "dict", ":", "if", "not", "ns_root_url", ":", "ns_root_url", "=", "config", "[", "\"bel_api\"", "]", "[", "\"servers\"", "]", "["...
Get modified and deleted nanopub urls Limited by last datetime retrieved (start_dt). Modified includes new and updated nanopubs Returns: dict: {'modified': [], 'deleted': []}
[ "Get", "modified", "and", "deleted", "nanopub", "urls" ]
train
https://github.com/belbio/bel/blob/60333e8815625b942b4836903f3b618cf44b3771/bel/nanopub/nanopubstore.py#L72-L115
belbio/bel
bel/nanopub/nanopubstore.py
get_nanopub
def get_nanopub(url): """Get Nanopub from nanopubstore given url""" r = bel.utils.get_url(url, cache=False) if r and r.json(): return r.json() else: return {}
python
def get_nanopub(url): """Get Nanopub from nanopubstore given url""" r = bel.utils.get_url(url, cache=False) if r and r.json(): return r.json() else: return {}
[ "def", "get_nanopub", "(", "url", ")", ":", "r", "=", "bel", ".", "utils", ".", "get_url", "(", "url", ",", "cache", "=", "False", ")", "if", "r", "and", "r", ".", "json", "(", ")", ":", "return", "r", ".", "json", "(", ")", "else", ":", "ret...
Get Nanopub from nanopubstore given url
[ "Get", "Nanopub", "from", "nanopubstore", "given", "url" ]
train
https://github.com/belbio/bel/blob/60333e8815625b942b4836903f3b618cf44b3771/bel/nanopub/nanopubstore.py#L118-L125
belbio/bel
bel/scripts.py
pipeline
def pipeline( ctx, input_fn, db_save, db_delete, output_fn, rules, species, namespace_targets, version, api, config_fn, ): """BEL Pipeline - BEL Nanopubs into BEL Edges This will process BEL Nanopubs into BEL Edges by validating, orthologizing (if requested), can...
python
def pipeline( ctx, input_fn, db_save, db_delete, output_fn, rules, species, namespace_targets, version, api, config_fn, ): """BEL Pipeline - BEL Nanopubs into BEL Edges This will process BEL Nanopubs into BEL Edges by validating, orthologizing (if requested), can...
[ "def", "pipeline", "(", "ctx", ",", "input_fn", ",", "db_save", ",", "db_delete", ",", "output_fn", ",", "rules", ",", "species", ",", "namespace_targets", ",", "version", ",", "api", ",", "config_fn", ",", ")", ":", "if", "config_fn", ":", "config", "="...
BEL Pipeline - BEL Nanopubs into BEL Edges This will process BEL Nanopubs into BEL Edges by validating, orthologizing (if requested), canonicalizing, and then computing the BEL Edges based on the given rule_set. \b input_fn: If input fn has *.gz, will read as a gzip file If input fn ha...
[ "BEL", "Pipeline", "-", "BEL", "Nanopubs", "into", "BEL", "Edges" ]
train
https://github.com/belbio/bel/blob/60333e8815625b942b4836903f3b618cf44b3771/bel/scripts.py#L86-L210
belbio/bel
bel/scripts.py
nanopub_validate
def nanopub_validate(ctx, input_fn, output_fn, api, config_fn): """Validate nanopubs""" if config_fn: config = bel.db.Config.merge_config(ctx.config, override_config_fn=config_fn) else: config = ctx.config api = utils.first_true( [api, config["bel_api"]["servers"].get("api_url"...
python
def nanopub_validate(ctx, input_fn, output_fn, api, config_fn): """Validate nanopubs""" if config_fn: config = bel.db.Config.merge_config(ctx.config, override_config_fn=config_fn) else: config = ctx.config api = utils.first_true( [api, config["bel_api"]["servers"].get("api_url"...
[ "def", "nanopub_validate", "(", "ctx", ",", "input_fn", ",", "output_fn", ",", "api", ",", "config_fn", ")", ":", "if", "config_fn", ":", "config", "=", "bel", ".", "db", ".", "Config", ".", "merge_config", "(", "ctx", ".", "config", ",", "override_confi...
Validate nanopubs
[ "Validate", "nanopubs" ]
train
https://github.com/belbio/bel/blob/60333e8815625b942b4836903f3b618cf44b3771/bel/scripts.py#L227-L239
belbio/bel
bel/scripts.py
convert_belscript
def convert_belscript(ctx, input_fn, output_fn): """Convert belscript to nanopubs_bel format This will convert the OpenBEL BELScript file format to nanopub_bel-1.0.0 format. \b input_fn: If input fn has *.gz, will read as a gzip file \b output_fn: If output fn has *.gz, wi...
python
def convert_belscript(ctx, input_fn, output_fn): """Convert belscript to nanopubs_bel format This will convert the OpenBEL BELScript file format to nanopub_bel-1.0.0 format. \b input_fn: If input fn has *.gz, will read as a gzip file \b output_fn: If output fn has *.gz, wi...
[ "def", "convert_belscript", "(", "ctx", ",", "input_fn", ",", "output_fn", ")", ":", "try", ":", "(", "out_fh", ",", "yaml_flag", ",", "jsonl_flag", ",", "json_flag", ",", ")", "=", "bel", ".", "nanopub", ".", "files", ".", "create_nanopubs_fh", "(", "ou...
Convert belscript to nanopubs_bel format This will convert the OpenBEL BELScript file format to nanopub_bel-1.0.0 format. \b input_fn: If input fn has *.gz, will read as a gzip file \b output_fn: If output fn has *.gz, will written as a gzip file If output fn has *.jso...
[ "Convert", "belscript", "to", "nanopubs_bel", "format" ]
train
https://github.com/belbio/bel/blob/60333e8815625b942b4836903f3b618cf44b3771/bel/scripts.py#L252-L302
belbio/bel
bel/scripts.py
reformat
def reformat(ctx, input_fn, output_fn): """Reformat between JSON, YAML, JSONLines formats \b input_fn: If input fn has *.gz, will read as a gzip file \b output_fn: If output fn has *.gz, will written as a gzip file If output fn has *.jsonl*, will written as a JSONLines file...
python
def reformat(ctx, input_fn, output_fn): """Reformat between JSON, YAML, JSONLines formats \b input_fn: If input fn has *.gz, will read as a gzip file \b output_fn: If output fn has *.gz, will written as a gzip file If output fn has *.jsonl*, will written as a JSONLines file...
[ "def", "reformat", "(", "ctx", ",", "input_fn", ",", "output_fn", ")", ":", "try", ":", "(", "out_fh", ",", "yaml_flag", ",", "jsonl_flag", ",", "json_flag", ",", ")", "=", "bel", ".", "nanopub", ".", "files", ".", "create_nanopubs_fh", "(", "output_fn",...
Reformat between JSON, YAML, JSONLines formats \b input_fn: If input fn has *.gz, will read as a gzip file \b output_fn: If output fn has *.gz, will written as a gzip file If output fn has *.jsonl*, will written as a JSONLines file IF output fn has *.json*, will be writ...
[ "Reformat", "between", "JSON", "YAML", "JSONLines", "formats" ]
train
https://github.com/belbio/bel/blob/60333e8815625b942b4836903f3b618cf44b3771/bel/scripts.py#L309-L355
belbio/bel
bel/scripts.py
nanopub_stats
def nanopub_stats(ctx, input_fn): """Collect statistics on nanopub file input_fn can be json, jsonl or yaml and additionally gzipped """ counts = { "nanopubs": 0, "assertions": {"total": 0, "subject_only": 0, "nested": 0, "relations": {}}, } for np in bnf.read_nanopubs(input_f...
python
def nanopub_stats(ctx, input_fn): """Collect statistics on nanopub file input_fn can be json, jsonl or yaml and additionally gzipped """ counts = { "nanopubs": 0, "assertions": {"total": 0, "subject_only": 0, "nested": 0, "relations": {}}, } for np in bnf.read_nanopubs(input_f...
[ "def", "nanopub_stats", "(", "ctx", ",", "input_fn", ")", ":", "counts", "=", "{", "\"nanopubs\"", ":", "0", ",", "\"assertions\"", ":", "{", "\"total\"", ":", "0", ",", "\"subject_only\"", ":", "0", ",", "\"nested\"", ":", "0", ",", "\"relations\"", ":"...
Collect statistics on nanopub file input_fn can be json, jsonl or yaml and additionally gzipped
[ "Collect", "statistics", "on", "nanopub", "file" ]
train
https://github.com/belbio/bel/blob/60333e8815625b942b4836903f3b618cf44b3771/bel/scripts.py#L361-L395
belbio/bel
bel/scripts.py
canonicalize
def canonicalize(ctx, statement, namespace_targets, version, api, config_fn): """Canonicalize statement Target namespaces can be provided in the following manner: bel stmt canonicalize "<BELStmt>" --namespace_targets '{"HGNC": ["EG", "SP"], "CHEMBL": ["CHEBI"]}' the value of target_namespa...
python
def canonicalize(ctx, statement, namespace_targets, version, api, config_fn): """Canonicalize statement Target namespaces can be provided in the following manner: bel stmt canonicalize "<BELStmt>" --namespace_targets '{"HGNC": ["EG", "SP"], "CHEMBL": ["CHEBI"]}' the value of target_namespa...
[ "def", "canonicalize", "(", "ctx", ",", "statement", ",", "namespace_targets", ",", "version", ",", "api", ",", "config_fn", ")", ":", "if", "config_fn", ":", "config", "=", "bel", ".", "db", ".", "Config", ".", "merge_config", "(", "ctx", ".", "config",...
Canonicalize statement Target namespaces can be provided in the following manner: bel stmt canonicalize "<BELStmt>" --namespace_targets '{"HGNC": ["EG", "SP"], "CHEMBL": ["CHEBI"]}' the value of target_namespaces must be JSON and embedded in single quotes reserving double quotes fo...
[ "Canonicalize", "statement" ]
train
https://github.com/belbio/bel/blob/60333e8815625b942b4836903f3b618cf44b3771/bel/scripts.py#L464-L508
belbio/bel
bel/scripts.py
edges
def edges(ctx, statement, rules, species, namespace_targets, version, api, config_fn): """Create BEL Edges from BEL Statement""" if config_fn: config = bel.db.Config.merge_config(ctx.config, override_config_fn=config_fn) else: config = ctx.config # Configuration - will return the first...
python
def edges(ctx, statement, rules, species, namespace_targets, version, api, config_fn): """Create BEL Edges from BEL Statement""" if config_fn: config = bel.db.Config.merge_config(ctx.config, override_config_fn=config_fn) else: config = ctx.config # Configuration - will return the first...
[ "def", "edges", "(", "ctx", ",", "statement", ",", "rules", ",", "species", ",", "namespace_targets", ",", "version", ",", "api", ",", "config_fn", ")", ":", "if", "config_fn", ":", "config", "=", "bel", ".", "db", ".", "Config", ".", "merge_config", "...
Create BEL Edges from BEL Statement
[ "Create", "BEL", "Edges", "from", "BEL", "Statement" ]
train
https://github.com/belbio/bel/blob/60333e8815625b942b4836903f3b618cf44b3771/bel/scripts.py#L582-L637
belbio/bel
bel/scripts.py
elasticsearch
def elasticsearch(delete, index_name): """Setup Elasticsearch namespace indexes This will by default only create the indexes and run the namespace index mapping if the indexes don't exist. The --delete option will force removal of the index if it exists. The index_name should be aliased to the in...
python
def elasticsearch(delete, index_name): """Setup Elasticsearch namespace indexes This will by default only create the indexes and run the namespace index mapping if the indexes don't exist. The --delete option will force removal of the index if it exists. The index_name should be aliased to the in...
[ "def", "elasticsearch", "(", "delete", ",", "index_name", ")", ":", "if", "delete", ":", "bel", ".", "db", ".", "elasticsearch", ".", "get_client", "(", "delete", "=", "True", ")", "else", ":", "bel", ".", "db", ".", "elasticsearch", ".", "get_client", ...
Setup Elasticsearch namespace indexes This will by default only create the indexes and run the namespace index mapping if the indexes don't exist. The --delete option will force removal of the index if it exists. The index_name should be aliased to the index 'terms' when it's ready
[ "Setup", "Elasticsearch", "namespace", "indexes" ]
train
https://github.com/belbio/bel/blob/60333e8815625b942b4836903f3b618cf44b3771/bel/scripts.py#L655-L667
belbio/bel
bel/scripts.py
arangodb
def arangodb(delete, db_name): """Setup ArangoDB database db_name: Either 'belns' or 'edgestore' - must be one or the other This will create the database, collections and indexes on the collection if it doesn't exist. The --delete option will force removal of the database if it exists.""" if del...
python
def arangodb(delete, db_name): """Setup ArangoDB database db_name: Either 'belns' or 'edgestore' - must be one or the other This will create the database, collections and indexes on the collection if it doesn't exist. The --delete option will force removal of the database if it exists.""" if del...
[ "def", "arangodb", "(", "delete", ",", "db_name", ")", ":", "if", "delete", ":", "client", "=", "bel", ".", "db", ".", "arangodb", ".", "get_client", "(", ")", "bel", ".", "db", ".", "arangodb", ".", "delete_database", "(", "client", ",", "db_name", ...
Setup ArangoDB database db_name: Either 'belns' or 'edgestore' - must be one or the other This will create the database, collections and indexes on the collection if it doesn't exist. The --delete option will force removal of the database if it exists.
[ "Setup", "ArangoDB", "database" ]
train
https://github.com/belbio/bel/blob/60333e8815625b942b4836903f3b618cf44b3771/bel/scripts.py#L675-L691
belbio/bel
bel/nanopub/nanopubs.py
validate_to_schema
def validate_to_schema(nanopub, schema) -> Tuple[bool, List[Tuple[str, str]]]: """Validate nanopub against jsonschema for nanopub Args: nanopub (Mapping[str, Any]): nanopub dict schema (Mapping[str, Any]): nanopub schema Returns: Tuple[bool, List[str]]: bool: Is valid? ...
python
def validate_to_schema(nanopub, schema) -> Tuple[bool, List[Tuple[str, str]]]: """Validate nanopub against jsonschema for nanopub Args: nanopub (Mapping[str, Any]): nanopub dict schema (Mapping[str, Any]): nanopub schema Returns: Tuple[bool, List[str]]: bool: Is valid? ...
[ "def", "validate_to_schema", "(", "nanopub", ",", "schema", ")", "->", "Tuple", "[", "bool", ",", "List", "[", "Tuple", "[", "str", ",", "str", "]", "]", "]", ":", "v", "=", "jsonschema", ".", "Draft4Validator", "(", "schema", ")", "messages", "=", "...
Validate nanopub against jsonschema for nanopub Args: nanopub (Mapping[str, Any]): nanopub dict schema (Mapping[str, Any]): nanopub schema Returns: Tuple[bool, List[str]]: bool: Is valid? Yes = True, No = False List[Tuple[str, str]]: Validation issues, empty if...
[ "Validate", "nanopub", "against", "jsonschema", "for", "nanopub" ]
train
https://github.com/belbio/bel/blob/60333e8815625b942b4836903f3b618cf44b3771/bel/nanopub/nanopubs.py#L141-L167
belbio/bel
bel/nanopub/nanopubs.py
hash_nanopub
def hash_nanopub(nanopub: Mapping[str, Any]) -> str: """Create CityHash64 from nanopub for duplicate check TODO - check that this hash value is consistent between C# and Python running on laptop and server Build string to hash Collect flat array of (all values.strip()): nanopub.type.name ...
python
def hash_nanopub(nanopub: Mapping[str, Any]) -> str: """Create CityHash64 from nanopub for duplicate check TODO - check that this hash value is consistent between C# and Python running on laptop and server Build string to hash Collect flat array of (all values.strip()): nanopub.type.name ...
[ "def", "hash_nanopub", "(", "nanopub", ":", "Mapping", "[", "str", ",", "Any", "]", ")", "->", "str", ":", "hash_list", "=", "[", "]", "# Type", "hash_list", ".", "append", "(", "nanopub", "[", "\"nanopub\"", "]", "[", "\"type\"", "]", ".", "get", "(...
Create CityHash64 from nanopub for duplicate check TODO - check that this hash value is consistent between C# and Python running on laptop and server Build string to hash Collect flat array of (all values.strip()): nanopub.type.name nanopub.type.version One of: na...
[ "Create", "CityHash64", "from", "nanopub", "for", "duplicate", "check" ]
train
https://github.com/belbio/bel/blob/60333e8815625b942b4836903f3b618cf44b3771/bel/nanopub/nanopubs.py#L171-L256
belbio/bel
bel/nanopub/nanopubs.py
Nanopub.validate
def validate( self, nanopub: Mapping[str, Any] ) -> Tuple[bool, List[Tuple[str, str]]]: """Validates using the nanopub schema Args: nanopub (Mapping[str, Any]): nanopub dict Returns: Tuple[bool, List[Tuple[str, str]]]: bool: Is valid? Yes = ...
python
def validate( self, nanopub: Mapping[str, Any] ) -> Tuple[bool, List[Tuple[str, str]]]: """Validates using the nanopub schema Args: nanopub (Mapping[str, Any]): nanopub dict Returns: Tuple[bool, List[Tuple[str, str]]]: bool: Is valid? Yes = ...
[ "def", "validate", "(", "self", ",", "nanopub", ":", "Mapping", "[", "str", ",", "Any", "]", ")", "->", "Tuple", "[", "bool", ",", "List", "[", "Tuple", "[", "str", ",", "str", "]", "]", "]", ":", "# Validate nanopub", "(", "is_valid", ",", "messag...
Validates using the nanopub schema Args: nanopub (Mapping[str, Any]): nanopub dict Returns: Tuple[bool, List[Tuple[str, str]]]: bool: Is valid? Yes = True, No = False List[Tuple[str, str]]: Validation issues, empty if valid, tuple is ('ERROR|WAR...
[ "Validates", "using", "the", "nanopub", "schema" ]
train
https://github.com/belbio/bel/blob/60333e8815625b942b4836903f3b618cf44b3771/bel/nanopub/nanopubs.py#L30-L83
belbio/bel
bel/nanopub/nanopubs.py
Nanopub.validate_context
def validate_context( self, context: Mapping[str, Any] ) -> Tuple[bool, List[Tuple[str, str]]]: """ Validate context Args: context (Mapping[str, Any]): context dictionary of type, id and label Returns: Tuple[bool, List[Tuple[str, str]]]: bool...
python
def validate_context( self, context: Mapping[str, Any] ) -> Tuple[bool, List[Tuple[str, str]]]: """ Validate context Args: context (Mapping[str, Any]): context dictionary of type, id and label Returns: Tuple[bool, List[Tuple[str, str]]]: bool...
[ "def", "validate_context", "(", "self", ",", "context", ":", "Mapping", "[", "str", ",", "Any", "]", ")", "->", "Tuple", "[", "bool", ",", "List", "[", "Tuple", "[", "str", ",", "str", "]", "]", "]", ":", "url", "=", "f'{self.endpoint}/terms/{context[\...
Validate context Args: context (Mapping[str, Any]): context dictionary of type, id and label Returns: Tuple[bool, List[Tuple[str, str]]]: bool: Is valid? Yes = True, No = False List[Tuple[str, str]]: Validation issues, empty if valid, tuple is (...
[ "Validate", "context" ]
train
https://github.com/belbio/bel/blob/60333e8815625b942b4836903f3b618cf44b3771/bel/nanopub/nanopubs.py#L85-L106
belbio/bel
bel/nanopub/nanopubs.py
Nanopub.bel_edges
def bel_edges( self, nanopub: Mapping[str, Any], namespace_targets: Mapping[str, List[str]] = {}, rules: List[str] = [], orthologize_target: str = None, ) -> List[Mapping[str, Any]]: """Create BEL Edges from BEL nanopub Args: nanopub (Mapping[str,...
python
def bel_edges( self, nanopub: Mapping[str, Any], namespace_targets: Mapping[str, List[str]] = {}, rules: List[str] = [], orthologize_target: str = None, ) -> List[Mapping[str, Any]]: """Create BEL Edges from BEL nanopub Args: nanopub (Mapping[str,...
[ "def", "bel_edges", "(", "self", ",", "nanopub", ":", "Mapping", "[", "str", ",", "Any", "]", ",", "namespace_targets", ":", "Mapping", "[", "str", ",", "List", "[", "str", "]", "]", "=", "{", "}", ",", "rules", ":", "List", "[", "str", "]", "=",...
Create BEL Edges from BEL nanopub Args: nanopub (Mapping[str, Any]): bel nanopub namespace_targets (Mapping[str, List[str]]): what namespaces to canonicalize rules (List[str]): which computed edge rules to process, default is all, look at BEL Specification yam...
[ "Create", "BEL", "Edges", "from", "BEL", "nanopub" ]
train
https://github.com/belbio/bel/blob/60333e8815625b942b4836903f3b618cf44b3771/bel/nanopub/nanopubs.py#L108-L138
RockFeng0/rtsf-http
httpdriver/cli.py
main_hrun
def main_hrun(): """ parse command line options and run commands.""" parser = argparse.ArgumentParser(description="Tools for http(s) test. Base on rtsf.") parser.add_argument( '--log-level', default='INFO', help="Specify logging level, default is INFO.") p...
python
def main_hrun(): """ parse command line options and run commands.""" parser = argparse.ArgumentParser(description="Tools for http(s) test. Base on rtsf.") parser.add_argument( '--log-level', default='INFO', help="Specify logging level, default is INFO.") p...
[ "def", "main_hrun", "(", ")", ":", "parser", "=", "argparse", ".", "ArgumentParser", "(", "description", "=", "\"Tools for http(s) test. Base on rtsf.\"", ")", "parser", ".", "add_argument", "(", "'--log-level'", ",", "default", "=", "'INFO'", ",", "help", "=", ...
parse command line options and run commands.
[ "parse", "command", "line", "options", "and", "run", "commands", "." ]
train
https://github.com/RockFeng0/rtsf-http/blob/3280cc9a01b0c92c52d699b0ebc29e55e62611a0/httpdriver/cli.py#L28-L51
malja/zroya
setup.py
find_pyd_file
def find_pyd_file(): """ Return path to .pyd after successful build command. :return: Path to .pyd file or None. """ if not os.path.isdir("./build"): raise NotADirectoryError for path, dirs, files in os.walk("./build"): for file_name in files: file_name_parts = os.p...
python
def find_pyd_file(): """ Return path to .pyd after successful build command. :return: Path to .pyd file or None. """ if not os.path.isdir("./build"): raise NotADirectoryError for path, dirs, files in os.walk("./build"): for file_name in files: file_name_parts = os.p...
[ "def", "find_pyd_file", "(", ")", ":", "if", "not", "os", ".", "path", ".", "isdir", "(", "\"./build\"", ")", ":", "raise", "NotADirectoryError", "for", "path", ",", "dirs", ",", "files", "in", "os", ".", "walk", "(", "\"./build\"", ")", ":", "for", ...
Return path to .pyd after successful build command. :return: Path to .pyd file or None.
[ "Return", "path", "to", ".", "pyd", "after", "successful", "build", "command", ".", ":", "return", ":", "Path", "to", ".", "pyd", "file", "or", "None", "." ]
train
https://github.com/malja/zroya/blob/41830133a54528e9cd9ef43d9637a576ac849c11/setup.py#L53-L67
urschrei/simplification
simplification/util.py
_void_array_to_nested_list
def _void_array_to_nested_list(res, _func, _args): """ Dereference the FFI result to a list of coordinates """ try: shape = res.coords.len, 2 ptr = cast(res.coords.data, POINTER(c_double)) array = np.ctypeslib.as_array(ptr, shape) return array.tolist() finally: drop_a...
python
def _void_array_to_nested_list(res, _func, _args): """ Dereference the FFI result to a list of coordinates """ try: shape = res.coords.len, 2 ptr = cast(res.coords.data, POINTER(c_double)) array = np.ctypeslib.as_array(ptr, shape) return array.tolist() finally: drop_a...
[ "def", "_void_array_to_nested_list", "(", "res", ",", "_func", ",", "_args", ")", ":", "try", ":", "shape", "=", "res", ".", "coords", ".", "len", ",", "2", "ptr", "=", "cast", "(", "res", ".", "coords", ".", "data", ",", "POINTER", "(", "c_double", ...
Dereference the FFI result to a list of coordinates
[ "Dereference", "the", "FFI", "result", "to", "a", "list", "of", "coordinates" ]
train
https://github.com/urschrei/simplification/blob/58491fc08cffa2fab5fe19d17c2ceb9d442530c3/simplification/util.py#L92-L100
MacHu-GWU/dataIO-project
dataIO/js.py
is_json_file
def is_json_file(abspath): """Parse file extension. - *.json: uncompressed, utf-8 encode json file - *.gz: compressed, utf-8 encode json file """ abspath = abspath.lower() fname, ext = os.path.splitext(abspath) if ext in [".json", ".js"]: is_json = True elif ext == ".gz": ...
python
def is_json_file(abspath): """Parse file extension. - *.json: uncompressed, utf-8 encode json file - *.gz: compressed, utf-8 encode json file """ abspath = abspath.lower() fname, ext = os.path.splitext(abspath) if ext in [".json", ".js"]: is_json = True elif ext == ".gz": ...
[ "def", "is_json_file", "(", "abspath", ")", ":", "abspath", "=", "abspath", ".", "lower", "(", ")", "fname", ",", "ext", "=", "os", ".", "path", ".", "splitext", "(", "abspath", ")", "if", "ext", "in", "[", "\".json\"", ",", "\".js\"", "]", ":", "i...
Parse file extension. - *.json: uncompressed, utf-8 encode json file - *.gz: compressed, utf-8 encode json file
[ "Parse", "file", "extension", "." ]
train
https://github.com/MacHu-GWU/dataIO-project/blob/7e1cc192b5e53426eed6dbd742918619b8fd60ab/dataIO/js.py#L49-L68
MacHu-GWU/dataIO-project
dataIO/js.py
lower_ext
def lower_ext(abspath): """Convert file extension to lowercase. """ fname, ext = os.path.splitext(abspath) return fname + ext.lower()
python
def lower_ext(abspath): """Convert file extension to lowercase. """ fname, ext = os.path.splitext(abspath) return fname + ext.lower()
[ "def", "lower_ext", "(", "abspath", ")", ":", "fname", ",", "ext", "=", "os", ".", "path", ".", "splitext", "(", "abspath", ")", "return", "fname", "+", "ext", ".", "lower", "(", ")" ]
Convert file extension to lowercase.
[ "Convert", "file", "extension", "to", "lowercase", "." ]
train
https://github.com/MacHu-GWU/dataIO-project/blob/7e1cc192b5e53426eed6dbd742918619b8fd60ab/dataIO/js.py#L71-L75
MacHu-GWU/dataIO-project
dataIO/js.py
load
def load(abspath, default=None, enable_verbose=True): """Load Json from file. If file are not exists, returns ``default``. :param abspath: file path. use absolute path as much as you can. extension has to be ``.json`` or ``.gz`` (for compressed Json). :type abspath: string :param default: defa...
python
def load(abspath, default=None, enable_verbose=True): """Load Json from file. If file are not exists, returns ``default``. :param abspath: file path. use absolute path as much as you can. extension has to be ``.json`` or ``.gz`` (for compressed Json). :type abspath: string :param default: defa...
[ "def", "load", "(", "abspath", ",", "default", "=", "None", ",", "enable_verbose", "=", "True", ")", ":", "if", "default", "is", "None", ":", "default", "=", "dict", "(", ")", "prt", "(", "\"\\nLoad from '%s' ...\"", "%", "abspath", ",", "enable_verbose", ...
Load Json from file. If file are not exists, returns ``default``. :param abspath: file path. use absolute path as much as you can. extension has to be ``.json`` or ``.gz`` (for compressed Json). :type abspath: string :param default: default ``dict()``, if ``abspath`` not exists, return the ...
[ "Load", "Json", "from", "file", ".", "If", "file", "are", "not", "exists", "returns", "default", "." ]
train
https://github.com/MacHu-GWU/dataIO-project/blob/7e1cc192b5e53426eed6dbd742918619b8fd60ab/dataIO/js.py#L78-L132
MacHu-GWU/dataIO-project
dataIO/js.py
dump
def dump(data, abspath, indent_format=False, float_precision=None, ensure_ascii=True, overwrite=False, enable_verbose=True): """Dump Json serializable object to file. Provides multiple choice to customize the behavior. :param data: Serializable python object. ...
python
def dump(data, abspath, indent_format=False, float_precision=None, ensure_ascii=True, overwrite=False, enable_verbose=True): """Dump Json serializable object to file. Provides multiple choice to customize the behavior. :param data: Serializable python object. ...
[ "def", "dump", "(", "data", ",", "abspath", ",", "indent_format", "=", "False", ",", "float_precision", "=", "None", ",", "ensure_ascii", "=", "True", ",", "overwrite", "=", "False", ",", "enable_verbose", "=", "True", ")", ":", "prt", "(", "\"\\nDump to '...
Dump Json serializable object to file. Provides multiple choice to customize the behavior. :param data: Serializable python object. :type data: dict or list :param abspath: ``save as`` path, file extension has to be ``.json`` or ``.gz`` (for compressed Json) :type abspath: string :par...
[ "Dump", "Json", "serializable", "object", "to", "file", ".", "Provides", "multiple", "choice", "to", "customize", "the", "behavior", "." ]
train
https://github.com/MacHu-GWU/dataIO-project/blob/7e1cc192b5e53426eed6dbd742918619b8fd60ab/dataIO/js.py#L135-L235
MacHu-GWU/dataIO-project
dataIO/js.py
safe_dump
def safe_dump(data, abspath, indent_format=False, float_precision=None, ensure_ascii=True, enable_verbose=True): """A stable version of :func:`dump`, this method will silently overwrite existing file. There's a issue with :func:`dump`: If your progra...
python
def safe_dump(data, abspath, indent_format=False, float_precision=None, ensure_ascii=True, enable_verbose=True): """A stable version of :func:`dump`, this method will silently overwrite existing file. There's a issue with :func:`dump`: If your progra...
[ "def", "safe_dump", "(", "data", ",", "abspath", ",", "indent_format", "=", "False", ",", "float_precision", "=", "None", ",", "ensure_ascii", "=", "True", ",", "enable_verbose", "=", "True", ")", ":", "abspath", "=", "lower_ext", "(", "str", "(", "abspath...
A stable version of :func:`dump`, this method will silently overwrite existing file. There's a issue with :func:`dump`: If your program is interrupted while writing, you got an incomplete file, and you also lose the original file. So this method write json to a temporary file first, then rename to wh...
[ "A", "stable", "version", "of", ":", "func", ":", "dump", "this", "method", "will", "silently", "overwrite", "existing", "file", "." ]
train
https://github.com/MacHu-GWU/dataIO-project/blob/7e1cc192b5e53426eed6dbd742918619b8fd60ab/dataIO/js.py#L238-L266
MacHu-GWU/dataIO-project
dataIO/js.py
pretty_dumps
def pretty_dumps(data): """Return json string in pretty format. **中文文档** 将字典转化成格式化后的字符串。 """ try: return json.dumps(data, sort_keys=True, indent=4, ensure_ascii=False) except: return json.dumps(data, sort_keys=True, indent=4, ensure_ascii=True)
python
def pretty_dumps(data): """Return json string in pretty format. **中文文档** 将字典转化成格式化后的字符串。 """ try: return json.dumps(data, sort_keys=True, indent=4, ensure_ascii=False) except: return json.dumps(data, sort_keys=True, indent=4, ensure_ascii=True)
[ "def", "pretty_dumps", "(", "data", ")", ":", "try", ":", "return", "json", ".", "dumps", "(", "data", ",", "sort_keys", "=", "True", ",", "indent", "=", "4", ",", "ensure_ascii", "=", "False", ")", "except", ":", "return", "json", ".", "dumps", "(",...
Return json string in pretty format. **中文文档** 将字典转化成格式化后的字符串。
[ "Return", "json", "string", "in", "pretty", "format", "." ]
train
https://github.com/MacHu-GWU/dataIO-project/blob/7e1cc192b5e53426eed6dbd742918619b8fd60ab/dataIO/js.py#L269-L279
RI-imaging/nrefocus
nrefocus/pad.py
_get_pad_left_right
def _get_pad_left_right(small, large): """ Compute left and right padding values. Here we use the convention that if the padding size is odd, we pad the odd part to the right and the even part to the left. Parameters ---------- small : int Old size of original 1D array large : ...
python
def _get_pad_left_right(small, large): """ Compute left and right padding values. Here we use the convention that if the padding size is odd, we pad the odd part to the right and the even part to the left. Parameters ---------- small : int Old size of original 1D array large : ...
[ "def", "_get_pad_left_right", "(", "small", ",", "large", ")", ":", "assert", "small", "<", "large", ",", "\"Can only pad when new size larger than old size\"", "padsize", "=", "large", "-", "small", "if", "padsize", "%", "2", "!=", "0", ":", "leftpad", "=", "...
Compute left and right padding values. Here we use the convention that if the padding size is odd, we pad the odd part to the right and the even part to the left. Parameters ---------- small : int Old size of original 1D array large : int New size off padded 1D array R...
[ "Compute", "left", "and", "right", "padding", "values", "." ]
train
https://github.com/RI-imaging/nrefocus/blob/ad09aeecace609ab8f9effcb662d2b7d50826080/nrefocus/pad.py#L12-L40
RI-imaging/nrefocus
nrefocus/pad.py
pad_add
def pad_add(av, size=None, stlen=10): """ Perform linear padding for complex array The input array `av` is padded with a linear ramp starting at the edges and going outwards to an average value computed from a band of thickness `stlen` at the outer boundary of the array. Pads will only be appended...
python
def pad_add(av, size=None, stlen=10): """ Perform linear padding for complex array The input array `av` is padded with a linear ramp starting at the edges and going outwards to an average value computed from a band of thickness `stlen` at the outer boundary of the array. Pads will only be appended...
[ "def", "pad_add", "(", "av", ",", "size", "=", "None", ",", "stlen", "=", "10", ")", ":", "if", "size", "is", "None", ":", "size", "=", "list", "(", ")", "for", "s", "in", "av", ".", "shape", ":", "size", ".", "append", "(", "int", "(", "2", ...
Perform linear padding for complex array The input array `av` is padded with a linear ramp starting at the edges and going outwards to an average value computed from a band of thickness `stlen` at the outer boundary of the array. Pads will only be appended, not prepended to the array. If the inpu...
[ "Perform", "linear", "padding", "for", "complex", "array" ]
train
https://github.com/RI-imaging/nrefocus/blob/ad09aeecace609ab8f9effcb662d2b7d50826080/nrefocus/pad.py#L43-L86
RI-imaging/nrefocus
nrefocus/pad.py
_pad_add_1d
def _pad_add_1d(av, size, stlen): """ 2D component of `pad_add` """ assert len(size) == 1 padx = _get_pad_left_right(av.shape[0], size[0]) mask = np.zeros(av.shape, dtype=bool) mask[stlen:-stlen] = True border = av[~mask] if av.dtype.name.count("complex"): padval = np.average(n...
python
def _pad_add_1d(av, size, stlen): """ 2D component of `pad_add` """ assert len(size) == 1 padx = _get_pad_left_right(av.shape[0], size[0]) mask = np.zeros(av.shape, dtype=bool) mask[stlen:-stlen] = True border = av[~mask] if av.dtype.name.count("complex"): padval = np.average(n...
[ "def", "_pad_add_1d", "(", "av", ",", "size", ",", "stlen", ")", ":", "assert", "len", "(", "size", ")", "==", "1", "padx", "=", "_get_pad_left_right", "(", "av", ".", "shape", "[", "0", "]", ",", "size", "[", "0", "]", ")", "mask", "=", "np", ...
2D component of `pad_add`
[ "2D", "component", "of", "pad_add" ]
train
https://github.com/RI-imaging/nrefocus/blob/ad09aeecace609ab8f9effcb662d2b7d50826080/nrefocus/pad.py#L89-L114
RI-imaging/nrefocus
nrefocus/pad.py
pad_rem
def pad_rem(pv, size=None): """ Removes linear padding from array This is a convenience function that does the opposite of `pad_add`. Parameters ---------- pv : 1D or 2D ndarray The array from which the padding will be removed. size : tuple of length 1 (1D) or 2 (2D), optional ...
python
def pad_rem(pv, size=None): """ Removes linear padding from array This is a convenience function that does the opposite of `pad_add`. Parameters ---------- pv : 1D or 2D ndarray The array from which the padding will be removed. size : tuple of length 1 (1D) or 2 (2D), optional ...
[ "def", "pad_rem", "(", "pv", ",", "size", "=", "None", ")", ":", "if", "size", "is", "None", ":", "size", "=", "list", "(", ")", "for", "s", "in", "pv", ".", "shape", ":", "assert", "s", "%", "2", "==", "0", ",", "\"Uneven size; specify correct siz...
Removes linear padding from array This is a convenience function that does the opposite of `pad_add`. Parameters ---------- pv : 1D or 2D ndarray The array from which the padding will be removed. size : tuple of length 1 (1D) or 2 (2D), optional The final size of the un-padded ...
[ "Removes", "linear", "padding", "from", "array" ]
train
https://github.com/RI-imaging/nrefocus/blob/ad09aeecace609ab8f9effcb662d2b7d50826080/nrefocus/pad.py#L147-L182
anteater/anteater
anteater/src/virus_total.py
VirusTotal.rate_limit
def rate_limit(self): """ Simple rate limit function using redis """ rate_limited_msg = False while True: is_rate_limited = self.limit.is_rate_limited(uuid) if is_rate_limited: time.sleep(0.3) # save hammering redis if not...
python
def rate_limit(self): """ Simple rate limit function using redis """ rate_limited_msg = False while True: is_rate_limited = self.limit.is_rate_limited(uuid) if is_rate_limited: time.sleep(0.3) # save hammering redis if not...
[ "def", "rate_limit", "(", "self", ")", ":", "rate_limited_msg", "=", "False", "while", "True", ":", "is_rate_limited", "=", "self", ".", "limit", ".", "is_rate_limited", "(", "uuid", ")", "if", "is_rate_limited", ":", "time", ".", "sleep", "(", "0.3", ")",...
Simple rate limit function using redis
[ "Simple", "rate", "limit", "function", "using", "redis" ]
train
https://github.com/anteater/anteater/blob/a980adbed8563ef92494f565acd371e91f50f155/anteater/src/virus_total.py#L60-L77
anteater/anteater
anteater/src/virus_total.py
VirusTotal.scan_file
def scan_file(self, filename, apikey): """ Sends a file to virus total for assessment """ url = self.base_url + "file/scan" params = {'apikey': apikey} scanfile = {"file": open(filename, 'rb')} response = requests.post(url, files=scanfile, params=params) r...
python
def scan_file(self, filename, apikey): """ Sends a file to virus total for assessment """ url = self.base_url + "file/scan" params = {'apikey': apikey} scanfile = {"file": open(filename, 'rb')} response = requests.post(url, files=scanfile, params=params) r...
[ "def", "scan_file", "(", "self", ",", "filename", ",", "apikey", ")", ":", "url", "=", "self", ".", "base_url", "+", "\"file/scan\"", "params", "=", "{", "'apikey'", ":", "apikey", "}", "scanfile", "=", "{", "\"file\"", ":", "open", "(", "filename", ",...
Sends a file to virus total for assessment
[ "Sends", "a", "file", "to", "virus", "total", "for", "assessment" ]
train
https://github.com/anteater/anteater/blob/a980adbed8563ef92494f565acd371e91f50f155/anteater/src/virus_total.py#L79-L95
anteater/anteater
anteater/src/virus_total.py
VirusTotal.rescan_file
def rescan_file(self, filename, sha256hash, apikey): """ just send the hash, check the date """ url = self.base_url + "file/rescan" params = { 'apikey': apikey, 'resource': sha256hash } rate_limit_clear = self.rate_limit() if rate_...
python
def rescan_file(self, filename, sha256hash, apikey): """ just send the hash, check the date """ url = self.base_url + "file/rescan" params = { 'apikey': apikey, 'resource': sha256hash } rate_limit_clear = self.rate_limit() if rate_...
[ "def", "rescan_file", "(", "self", ",", "filename", ",", "sha256hash", ",", "apikey", ")", ":", "url", "=", "self", ".", "base_url", "+", "\"file/rescan\"", "params", "=", "{", "'apikey'", ":", "apikey", ",", "'resource'", ":", "sha256hash", "}", "rate_lim...
just send the hash, check the date
[ "just", "send", "the", "hash", "check", "the", "date" ]
train
https://github.com/anteater/anteater/blob/a980adbed8563ef92494f565acd371e91f50f155/anteater/src/virus_total.py#L97-L116
anteater/anteater
anteater/src/virus_total.py
VirusTotal.binary_report
def binary_report(self, sha256sum, apikey): """ retrieve report from file scan """ url = self.base_url + "file/report" params = {"apikey": apikey, "resource": sha256sum} rate_limit_clear = self.rate_limit() if rate_limit_clear: response = requests.pos...
python
def binary_report(self, sha256sum, apikey): """ retrieve report from file scan """ url = self.base_url + "file/report" params = {"apikey": apikey, "resource": sha256sum} rate_limit_clear = self.rate_limit() if rate_limit_clear: response = requests.pos...
[ "def", "binary_report", "(", "self", ",", "sha256sum", ",", "apikey", ")", ":", "url", "=", "self", ".", "base_url", "+", "\"file/report\"", "params", "=", "{", "\"apikey\"", ":", "apikey", ",", "\"resource\"", ":", "sha256sum", "}", "rate_limit_clear", "=",...
retrieve report from file scan
[ "retrieve", "report", "from", "file", "scan" ]
train
https://github.com/anteater/anteater/blob/a980adbed8563ef92494f565acd371e91f50f155/anteater/src/virus_total.py#L118-L136
anteater/anteater
anteater/src/virus_total.py
VirusTotal.send_ip
def send_ip(self, ipaddr, apikey): """ Send IP address for list of past malicous domain associations """ url = self.base_url + "ip-address/report" parameters = {"ip": ipaddr, "apikey": apikey} rate_limit_clear = self.rate_limit() if rate_limit_clear: r...
python
def send_ip(self, ipaddr, apikey): """ Send IP address for list of past malicous domain associations """ url = self.base_url + "ip-address/report" parameters = {"ip": ipaddr, "apikey": apikey} rate_limit_clear = self.rate_limit() if rate_limit_clear: r...
[ "def", "send_ip", "(", "self", ",", "ipaddr", ",", "apikey", ")", ":", "url", "=", "self", ".", "base_url", "+", "\"ip-address/report\"", "parameters", "=", "{", "\"ip\"", ":", "ipaddr", ",", "\"apikey\"", ":", "apikey", "}", "rate_limit_clear", "=", "self...
Send IP address for list of past malicous domain associations
[ "Send", "IP", "address", "for", "list", "of", "past", "malicous", "domain", "associations" ]
train
https://github.com/anteater/anteater/blob/a980adbed8563ef92494f565acd371e91f50f155/anteater/src/virus_total.py#L138-L154
anteater/anteater
anteater/src/virus_total.py
VirusTotal.url_report
def url_report(self, scan_url, apikey): """ Send URLS for list of past malicous associations """ url = self.base_url + "url/report" params = {"apikey": apikey, 'resource': scan_url} rate_limit_clear = self.rate_limit() if rate_limit_clear: response = r...
python
def url_report(self, scan_url, apikey): """ Send URLS for list of past malicous associations """ url = self.base_url + "url/report" params = {"apikey": apikey, 'resource': scan_url} rate_limit_clear = self.rate_limit() if rate_limit_clear: response = r...
[ "def", "url_report", "(", "self", ",", "scan_url", ",", "apikey", ")", ":", "url", "=", "self", ".", "base_url", "+", "\"url/report\"", "params", "=", "{", "\"apikey\"", ":", "apikey", ",", "'resource'", ":", "scan_url", "}", "rate_limit_clear", "=", "self...
Send URLS for list of past malicous associations
[ "Send", "URLS", "for", "list", "of", "past", "malicous", "associations" ]
train
https://github.com/anteater/anteater/blob/a980adbed8563ef92494f565acd371e91f50f155/anteater/src/virus_total.py#L156-L172
rapidpro/expressions
python/setup.py
_read_requirements
def _read_requirements(filename, extra_packages): """Returns a list of package requirements read from the file.""" requirements_file = open(filename).read() hard_requirements = [] for line in requirements_file.splitlines(): if _is_requirement(line): if line.find(';') > -1: ...
python
def _read_requirements(filename, extra_packages): """Returns a list of package requirements read from the file.""" requirements_file = open(filename).read() hard_requirements = [] for line in requirements_file.splitlines(): if _is_requirement(line): if line.find(';') > -1: ...
[ "def", "_read_requirements", "(", "filename", ",", "extra_packages", ")", ":", "requirements_file", "=", "open", "(", "filename", ")", ".", "read", "(", ")", "hard_requirements", "=", "[", "]", "for", "line", "in", "requirements_file", ".", "splitlines", "(", ...
Returns a list of package requirements read from the file.
[ "Returns", "a", "list", "of", "package", "requirements", "read", "from", "the", "file", "." ]
train
https://github.com/rapidpro/expressions/blob/b03d91ec58fc328960bce90ecb5fa49dcf467627/python/setup.py#L14-L26
rapidpro/expressions
python/temba_expressions/functions/custom.py
field
def field(ctx, text, index, delimiter=' '): """ Reference a field in string separated by a delimiter """ splits = text.split(delimiter) # remove our delimiters and whitespace splits = [f for f in splits if f != delimiter and len(f.strip()) > 0] index = conversions.to_integer(index, ctx) ...
python
def field(ctx, text, index, delimiter=' '): """ Reference a field in string separated by a delimiter """ splits = text.split(delimiter) # remove our delimiters and whitespace splits = [f for f in splits if f != delimiter and len(f.strip()) > 0] index = conversions.to_integer(index, ctx) ...
[ "def", "field", "(", "ctx", ",", "text", ",", "index", ",", "delimiter", "=", "' '", ")", ":", "splits", "=", "text", ".", "split", "(", "delimiter", ")", "# remove our delimiters and whitespace", "splits", "=", "[", "f", "for", "f", "in", "splits", "if"...
Reference a field in string separated by a delimiter
[ "Reference", "a", "field", "in", "string", "separated", "by", "a", "delimiter" ]
train
https://github.com/rapidpro/expressions/blob/b03d91ec58fc328960bce90ecb5fa49dcf467627/python/temba_expressions/functions/custom.py#L10-L26
rapidpro/expressions
python/temba_expressions/functions/custom.py
epoch
def epoch(ctx, datetime): """ Converts the given date to the number of seconds since January 1st, 1970 UTC """ return conversions.to_decimal(str(conversions.to_datetime(datetime, ctx).timestamp()), ctx)
python
def epoch(ctx, datetime): """ Converts the given date to the number of seconds since January 1st, 1970 UTC """ return conversions.to_decimal(str(conversions.to_datetime(datetime, ctx).timestamp()), ctx)
[ "def", "epoch", "(", "ctx", ",", "datetime", ")", ":", "return", "conversions", ".", "to_decimal", "(", "str", "(", "conversions", ".", "to_datetime", "(", "datetime", ",", "ctx", ")", ".", "timestamp", "(", ")", ")", ",", "ctx", ")" ]
Converts the given date to the number of seconds since January 1st, 1970 UTC
[ "Converts", "the", "given", "date", "to", "the", "number", "of", "seconds", "since", "January", "1st", "1970", "UTC" ]
train
https://github.com/rapidpro/expressions/blob/b03d91ec58fc328960bce90ecb5fa49dcf467627/python/temba_expressions/functions/custom.py#L44-L48
rapidpro/expressions
python/temba_expressions/functions/custom.py
read_digits
def read_digits(ctx, text): """ Formats digits in text for reading in TTS """ def chunk(value, chunk_size): return [value[i: i + chunk_size] for i in range(0, len(value), chunk_size)] text = conversions.to_string(text, ctx).strip() if not text: return '' # trim off the plus...
python
def read_digits(ctx, text): """ Formats digits in text for reading in TTS """ def chunk(value, chunk_size): return [value[i: i + chunk_size] for i in range(0, len(value), chunk_size)] text = conversions.to_string(text, ctx).strip() if not text: return '' # trim off the plus...
[ "def", "read_digits", "(", "ctx", ",", "text", ")", ":", "def", "chunk", "(", "value", ",", "chunk_size", ")", ":", "return", "[", "value", "[", "i", ":", "i", "+", "chunk_size", "]", "for", "i", "in", "range", "(", "0", ",", "len", "(", "value",...
Formats digits in text for reading in TTS
[ "Formats", "digits", "in", "text", "for", "reading", "in", "TTS" ]
train
https://github.com/rapidpro/expressions/blob/b03d91ec58fc328960bce90ecb5fa49dcf467627/python/temba_expressions/functions/custom.py#L51-L86
rapidpro/expressions
python/temba_expressions/functions/custom.py
remove_first_word
def remove_first_word(ctx, text): """ Removes the first word from the given text string """ text = conversions.to_string(text, ctx).lstrip() first = first_word(ctx, text) return text[len(first):].lstrip() if first else ''
python
def remove_first_word(ctx, text): """ Removes the first word from the given text string """ text = conversions.to_string(text, ctx).lstrip() first = first_word(ctx, text) return text[len(first):].lstrip() if first else ''
[ "def", "remove_first_word", "(", "ctx", ",", "text", ")", ":", "text", "=", "conversions", ".", "to_string", "(", "text", ",", "ctx", ")", ".", "lstrip", "(", ")", "first", "=", "first_word", "(", "ctx", ",", "text", ")", "return", "text", "[", "len"...
Removes the first word from the given text string
[ "Removes", "the", "first", "word", "from", "the", "given", "text", "string" ]
train
https://github.com/rapidpro/expressions/blob/b03d91ec58fc328960bce90ecb5fa49dcf467627/python/temba_expressions/functions/custom.py#L89-L95
rapidpro/expressions
python/temba_expressions/functions/custom.py
word
def word(ctx, text, number, by_spaces=False): """ Extracts the nth word from the given text string """ return word_slice(ctx, text, number, conversions.to_integer(number, ctx) + 1, by_spaces)
python
def word(ctx, text, number, by_spaces=False): """ Extracts the nth word from the given text string """ return word_slice(ctx, text, number, conversions.to_integer(number, ctx) + 1, by_spaces)
[ "def", "word", "(", "ctx", ",", "text", ",", "number", ",", "by_spaces", "=", "False", ")", ":", "return", "word_slice", "(", "ctx", ",", "text", ",", "number", ",", "conversions", ".", "to_integer", "(", "number", ",", "ctx", ")", "+", "1", ",", "...
Extracts the nth word from the given text string
[ "Extracts", "the", "nth", "word", "from", "the", "given", "text", "string" ]
train
https://github.com/rapidpro/expressions/blob/b03d91ec58fc328960bce90ecb5fa49dcf467627/python/temba_expressions/functions/custom.py#L98-L102
rapidpro/expressions
python/temba_expressions/functions/custom.py
word_count
def word_count(ctx, text, by_spaces=False): """ Returns the number of words in the given text string """ text = conversions.to_string(text, ctx) by_spaces = conversions.to_boolean(by_spaces, ctx) return len(__get_words(text, by_spaces))
python
def word_count(ctx, text, by_spaces=False): """ Returns the number of words in the given text string """ text = conversions.to_string(text, ctx) by_spaces = conversions.to_boolean(by_spaces, ctx) return len(__get_words(text, by_spaces))
[ "def", "word_count", "(", "ctx", ",", "text", ",", "by_spaces", "=", "False", ")", ":", "text", "=", "conversions", ".", "to_string", "(", "text", ",", "ctx", ")", "by_spaces", "=", "conversions", ".", "to_boolean", "(", "by_spaces", ",", "ctx", ")", "...
Returns the number of words in the given text string
[ "Returns", "the", "number", "of", "words", "in", "the", "given", "text", "string" ]
train
https://github.com/rapidpro/expressions/blob/b03d91ec58fc328960bce90ecb5fa49dcf467627/python/temba_expressions/functions/custom.py#L105-L111
rapidpro/expressions
python/temba_expressions/functions/custom.py
word_slice
def word_slice(ctx, text, start, stop=0, by_spaces=False): """ Extracts a substring spanning from start up to but not-including stop """ text = conversions.to_string(text, ctx) start = conversions.to_integer(start, ctx) stop = conversions.to_integer(stop, ctx) by_spaces = conversions.to_bool...
python
def word_slice(ctx, text, start, stop=0, by_spaces=False): """ Extracts a substring spanning from start up to but not-including stop """ text = conversions.to_string(text, ctx) start = conversions.to_integer(start, ctx) stop = conversions.to_integer(stop, ctx) by_spaces = conversions.to_bool...
[ "def", "word_slice", "(", "ctx", ",", "text", ",", "start", ",", "stop", "=", "0", ",", "by_spaces", "=", "False", ")", ":", "text", "=", "conversions", ".", "to_string", "(", "text", ",", "ctx", ")", "start", "=", "conversions", ".", "to_integer", "...
Extracts a substring spanning from start up to but not-including stop
[ "Extracts", "a", "substring", "spanning", "from", "start", "up", "to", "but", "not", "-", "including", "stop" ]
train
https://github.com/rapidpro/expressions/blob/b03d91ec58fc328960bce90ecb5fa49dcf467627/python/temba_expressions/functions/custom.py#L114-L138
rapidpro/expressions
python/temba_expressions/functions/custom.py
format_date
def format_date(ctx, text): """ Takes a single parameter (date as string) and returns it in the format defined by the org """ dt = conversions.to_datetime(text, ctx) return dt.astimezone(ctx.timezone).strftime(ctx.get_date_format(True))
python
def format_date(ctx, text): """ Takes a single parameter (date as string) and returns it in the format defined by the org """ dt = conversions.to_datetime(text, ctx) return dt.astimezone(ctx.timezone).strftime(ctx.get_date_format(True))
[ "def", "format_date", "(", "ctx", ",", "text", ")", ":", "dt", "=", "conversions", ".", "to_datetime", "(", "text", ",", "ctx", ")", "return", "dt", ".", "astimezone", "(", "ctx", ".", "timezone", ")", ".", "strftime", "(", "ctx", ".", "get_date_format...
Takes a single parameter (date as string) and returns it in the format defined by the org
[ "Takes", "a", "single", "parameter", "(", "date", "as", "string", ")", "and", "returns", "it", "in", "the", "format", "defined", "by", "the", "org" ]
train
https://github.com/rapidpro/expressions/blob/b03d91ec58fc328960bce90ecb5fa49dcf467627/python/temba_expressions/functions/custom.py#L141-L146
rapidpro/expressions
python/temba_expressions/functions/custom.py
format_location
def format_location(ctx, text): """ Takes a single parameter (administrative boundary as a string) and returns the name of the leaf boundary """ text = conversions.to_string(text, ctx) return text.split(">")[-1].strip()
python
def format_location(ctx, text): """ Takes a single parameter (administrative boundary as a string) and returns the name of the leaf boundary """ text = conversions.to_string(text, ctx) return text.split(">")[-1].strip()
[ "def", "format_location", "(", "ctx", ",", "text", ")", ":", "text", "=", "conversions", ".", "to_string", "(", "text", ",", "ctx", ")", "return", "text", ".", "split", "(", "\">\"", ")", "[", "-", "1", "]", ".", "strip", "(", ")" ]
Takes a single parameter (administrative boundary as a string) and returns the name of the leaf boundary
[ "Takes", "a", "single", "parameter", "(", "administrative", "boundary", "as", "a", "string", ")", "and", "returns", "the", "name", "of", "the", "leaf", "boundary" ]
train
https://github.com/rapidpro/expressions/blob/b03d91ec58fc328960bce90ecb5fa49dcf467627/python/temba_expressions/functions/custom.py#L149-L154
rapidpro/expressions
python/temba_expressions/functions/custom.py
regex_group
def regex_group(ctx, text, pattern, group_num): """ Tries to match the text with the given pattern and returns the value of matching group """ text = conversions.to_string(text, ctx) pattern = conversions.to_string(pattern, ctx) group_num = conversions.to_integer(group_num, ctx) expression ...
python
def regex_group(ctx, text, pattern, group_num): """ Tries to match the text with the given pattern and returns the value of matching group """ text = conversions.to_string(text, ctx) pattern = conversions.to_string(pattern, ctx) group_num = conversions.to_integer(group_num, ctx) expression ...
[ "def", "regex_group", "(", "ctx", ",", "text", ",", "pattern", ",", "group_num", ")", ":", "text", "=", "conversions", ".", "to_string", "(", "text", ",", "ctx", ")", "pattern", "=", "conversions", ".", "to_string", "(", "pattern", ",", "ctx", ")", "gr...
Tries to match the text with the given pattern and returns the value of matching group
[ "Tries", "to", "match", "the", "text", "with", "the", "given", "pattern", "and", "returns", "the", "value", "of", "matching", "group" ]
train
https://github.com/rapidpro/expressions/blob/b03d91ec58fc328960bce90ecb5fa49dcf467627/python/temba_expressions/functions/custom.py#L157-L174
rapidpro/expressions
python/temba_expressions/functions/custom.py
__get_words
def __get_words(text, by_spaces): """ Helper function which splits the given text string into words. If by_spaces is false, then text like '01-02-2014' will be split into 3 separate words. For backwards compatibility, this is the default for all expression functions. :param text: the text to split ...
python
def __get_words(text, by_spaces): """ Helper function which splits the given text string into words. If by_spaces is false, then text like '01-02-2014' will be split into 3 separate words. For backwards compatibility, this is the default for all expression functions. :param text: the text to split ...
[ "def", "__get_words", "(", "text", ",", "by_spaces", ")", ":", "if", "by_spaces", ":", "splits", "=", "regex", ".", "split", "(", "r'\\s+'", ",", "text", ",", "flags", "=", "regex", ".", "MULTILINE", "|", "regex", ".", "UNICODE", "|", "regex", ".", "...
Helper function which splits the given text string into words. If by_spaces is false, then text like '01-02-2014' will be split into 3 separate words. For backwards compatibility, this is the default for all expression functions. :param text: the text to split :param by_spaces: whether words should be s...
[ "Helper", "function", "which", "splits", "the", "given", "text", "string", "into", "words", ".", "If", "by_spaces", "is", "false", "then", "text", "like", "01", "-", "02", "-", "2014", "will", "be", "split", "into", "3", "separate", "words", ".", "For", ...
train
https://github.com/rapidpro/expressions/blob/b03d91ec58fc328960bce90ecb5fa49dcf467627/python/temba_expressions/functions/custom.py#L179-L191
rapidpro/expressions
python/temba_expressions/utils.py
decimal_round
def decimal_round(number, num_digits, rounding=ROUND_HALF_UP): """ Rounding for decimals with support for negative digits """ exp = Decimal(10) ** -num_digits if num_digits >= 0: return number.quantize(exp, rounding) else: return exp * (number / exp).to_integral_value(rounding)
python
def decimal_round(number, num_digits, rounding=ROUND_HALF_UP): """ Rounding for decimals with support for negative digits """ exp = Decimal(10) ** -num_digits if num_digits >= 0: return number.quantize(exp, rounding) else: return exp * (number / exp).to_integral_value(rounding)
[ "def", "decimal_round", "(", "number", ",", "num_digits", ",", "rounding", "=", "ROUND_HALF_UP", ")", ":", "exp", "=", "Decimal", "(", "10", ")", "**", "-", "num_digits", "if", "num_digits", ">=", "0", ":", "return", "number", ".", "quantize", "(", "exp"...
Rounding for decimals with support for negative digits
[ "Rounding", "for", "decimals", "with", "support", "for", "negative", "digits" ]
train
https://github.com/rapidpro/expressions/blob/b03d91ec58fc328960bce90ecb5fa49dcf467627/python/temba_expressions/utils.py#L22-L31
rapidpro/expressions
python/temba_expressions/utils.py
parse_json_date
def parse_json_date(value): """ Parses an ISO8601 formatted datetime from a string value """ if not value: return None return datetime.datetime.strptime(value, JSON_DATETIME_FORMAT).replace(tzinfo=pytz.UTC)
python
def parse_json_date(value): """ Parses an ISO8601 formatted datetime from a string value """ if not value: return None return datetime.datetime.strptime(value, JSON_DATETIME_FORMAT).replace(tzinfo=pytz.UTC)
[ "def", "parse_json_date", "(", "value", ")", ":", "if", "not", "value", ":", "return", "None", "return", "datetime", ".", "datetime", ".", "strptime", "(", "value", ",", "JSON_DATETIME_FORMAT", ")", ".", "replace", "(", "tzinfo", "=", "pytz", ".", "UTC", ...
Parses an ISO8601 formatted datetime from a string value
[ "Parses", "an", "ISO8601", "formatted", "datetime", "from", "a", "string", "value" ]
train
https://github.com/rapidpro/expressions/blob/b03d91ec58fc328960bce90ecb5fa49dcf467627/python/temba_expressions/utils.py#L50-L57
rapidpro/expressions
python/temba_expressions/utils.py
format_json_date
def format_json_date(value): """ Formats a datetime as ISO8601 in UTC with millisecond precision, e.g. "2014-10-03T09:41:12.790Z" """ if not value: return None # %f will include 6 microsecond digits micro_precision = value.astimezone(pytz.UTC).strftime(JSON_DATETIME_FORMAT) # only ...
python
def format_json_date(value): """ Formats a datetime as ISO8601 in UTC with millisecond precision, e.g. "2014-10-03T09:41:12.790Z" """ if not value: return None # %f will include 6 microsecond digits micro_precision = value.astimezone(pytz.UTC).strftime(JSON_DATETIME_FORMAT) # only ...
[ "def", "format_json_date", "(", "value", ")", ":", "if", "not", "value", ":", "return", "None", "# %f will include 6 microsecond digits", "micro_precision", "=", "value", ".", "astimezone", "(", "pytz", ".", "UTC", ")", ".", "strftime", "(", "JSON_DATETIME_FORMAT"...
Formats a datetime as ISO8601 in UTC with millisecond precision, e.g. "2014-10-03T09:41:12.790Z"
[ "Formats", "a", "datetime", "as", "ISO8601", "in", "UTC", "with", "millisecond", "precision", "e", ".", "g", ".", "2014", "-", "10", "-", "03T09", ":", "41", ":", "12", ".", "790Z" ]
train
https://github.com/rapidpro/expressions/blob/b03d91ec58fc328960bce90ecb5fa49dcf467627/python/temba_expressions/utils.py#L60-L71
rapidpro/expressions
python/temba_expressions/functions/excel.py
clean
def clean(ctx, text): """ Removes all non-printable characters from a text string """ text = conversions.to_string(text, ctx) return ''.join([c for c in text if ord(c) >= 32])
python
def clean(ctx, text): """ Removes all non-printable characters from a text string """ text = conversions.to_string(text, ctx) return ''.join([c for c in text if ord(c) >= 32])
[ "def", "clean", "(", "ctx", ",", "text", ")", ":", "text", "=", "conversions", ".", "to_string", "(", "text", ",", "ctx", ")", "return", "''", ".", "join", "(", "[", "c", "for", "c", "in", "text", "if", "ord", "(", "c", ")", ">=", "32", "]", ...
Removes all non-printable characters from a text string
[ "Removes", "all", "non", "-", "printable", "characters", "from", "a", "text", "string" ]
train
https://github.com/rapidpro/expressions/blob/b03d91ec58fc328960bce90ecb5fa49dcf467627/python/temba_expressions/functions/excel.py#L22-L27
rapidpro/expressions
python/temba_expressions/functions/excel.py
concatenate
def concatenate(ctx, *text): """ Joins text strings into one text string """ result = '' for arg in text: result += conversions.to_string(arg, ctx) return result
python
def concatenate(ctx, *text): """ Joins text strings into one text string """ result = '' for arg in text: result += conversions.to_string(arg, ctx) return result
[ "def", "concatenate", "(", "ctx", ",", "*", "text", ")", ":", "result", "=", "''", "for", "arg", "in", "text", ":", "result", "+=", "conversions", ".", "to_string", "(", "arg", ",", "ctx", ")", "return", "result" ]
Joins text strings into one text string
[ "Joins", "text", "strings", "into", "one", "text", "string" ]
train
https://github.com/rapidpro/expressions/blob/b03d91ec58fc328960bce90ecb5fa49dcf467627/python/temba_expressions/functions/excel.py#L37-L44
rapidpro/expressions
python/temba_expressions/functions/excel.py
fixed
def fixed(ctx, number, decimals=2, no_commas=False): """ Formats the given number in decimal format using a period and commas """ value = _round(ctx, number, decimals) format_str = '{:f}' if no_commas else '{:,f}' return format_str.format(value)
python
def fixed(ctx, number, decimals=2, no_commas=False): """ Formats the given number in decimal format using a period and commas """ value = _round(ctx, number, decimals) format_str = '{:f}' if no_commas else '{:,f}' return format_str.format(value)
[ "def", "fixed", "(", "ctx", ",", "number", ",", "decimals", "=", "2", ",", "no_commas", "=", "False", ")", ":", "value", "=", "_round", "(", "ctx", ",", "number", ",", "decimals", ")", "format_str", "=", "'{:f}'", "if", "no_commas", "else", "'{:,f}'", ...
Formats the given number in decimal format using a period and commas
[ "Formats", "the", "given", "number", "in", "decimal", "format", "using", "a", "period", "and", "commas" ]
train
https://github.com/rapidpro/expressions/blob/b03d91ec58fc328960bce90ecb5fa49dcf467627/python/temba_expressions/functions/excel.py#L47-L53
rapidpro/expressions
python/temba_expressions/functions/excel.py
left
def left(ctx, text, num_chars): """ Returns the first characters in a text string """ num_chars = conversions.to_integer(num_chars, ctx) if num_chars < 0: raise ValueError("Number of chars can't be negative") return conversions.to_string(text, ctx)[0:num_chars]
python
def left(ctx, text, num_chars): """ Returns the first characters in a text string """ num_chars = conversions.to_integer(num_chars, ctx) if num_chars < 0: raise ValueError("Number of chars can't be negative") return conversions.to_string(text, ctx)[0:num_chars]
[ "def", "left", "(", "ctx", ",", "text", ",", "num_chars", ")", ":", "num_chars", "=", "conversions", ".", "to_integer", "(", "num_chars", ",", "ctx", ")", "if", "num_chars", "<", "0", ":", "raise", "ValueError", "(", "\"Number of chars can't be negative\"", ...
Returns the first characters in a text string
[ "Returns", "the", "first", "characters", "in", "a", "text", "string" ]
train
https://github.com/rapidpro/expressions/blob/b03d91ec58fc328960bce90ecb5fa49dcf467627/python/temba_expressions/functions/excel.py#L56-L63
rapidpro/expressions
python/temba_expressions/functions/excel.py
rept
def rept(ctx, text, number_times): """ Repeats text a given number of times """ if number_times < 0: raise ValueError("Number of times can't be negative") return conversions.to_string(text, ctx) * conversions.to_integer(number_times, ctx)
python
def rept(ctx, text, number_times): """ Repeats text a given number of times """ if number_times < 0: raise ValueError("Number of times can't be negative") return conversions.to_string(text, ctx) * conversions.to_integer(number_times, ctx)
[ "def", "rept", "(", "ctx", ",", "text", ",", "number_times", ")", ":", "if", "number_times", "<", "0", ":", "raise", "ValueError", "(", "\"Number of times can't be negative\"", ")", "return", "conversions", ".", "to_string", "(", "text", ",", "ctx", ")", "*"...
Repeats text a given number of times
[ "Repeats", "text", "a", "given", "number", "of", "times" ]
train
https://github.com/rapidpro/expressions/blob/b03d91ec58fc328960bce90ecb5fa49dcf467627/python/temba_expressions/functions/excel.py#L87-L93
rapidpro/expressions
python/temba_expressions/functions/excel.py
right
def right(ctx, text, num_chars): """ Returns the last characters in a text string """ num_chars = conversions.to_integer(num_chars, ctx) if num_chars < 0: raise ValueError("Number of chars can't be negative") elif num_chars == 0: return '' else: return conversions.to_...
python
def right(ctx, text, num_chars): """ Returns the last characters in a text string """ num_chars = conversions.to_integer(num_chars, ctx) if num_chars < 0: raise ValueError("Number of chars can't be negative") elif num_chars == 0: return '' else: return conversions.to_...
[ "def", "right", "(", "ctx", ",", "text", ",", "num_chars", ")", ":", "num_chars", "=", "conversions", ".", "to_integer", "(", "num_chars", ",", "ctx", ")", "if", "num_chars", "<", "0", ":", "raise", "ValueError", "(", "\"Number of chars can't be negative\"", ...
Returns the last characters in a text string
[ "Returns", "the", "last", "characters", "in", "a", "text", "string" ]
train
https://github.com/rapidpro/expressions/blob/b03d91ec58fc328960bce90ecb5fa49dcf467627/python/temba_expressions/functions/excel.py#L96-L106
rapidpro/expressions
python/temba_expressions/functions/excel.py
substitute
def substitute(ctx, text, old_text, new_text, instance_num=-1): """ Substitutes new_text for old_text in a text string """ text = conversions.to_string(text, ctx) old_text = conversions.to_string(old_text, ctx) new_text = conversions.to_string(new_text, ctx) if instance_num < 0: ret...
python
def substitute(ctx, text, old_text, new_text, instance_num=-1): """ Substitutes new_text for old_text in a text string """ text = conversions.to_string(text, ctx) old_text = conversions.to_string(old_text, ctx) new_text = conversions.to_string(new_text, ctx) if instance_num < 0: ret...
[ "def", "substitute", "(", "ctx", ",", "text", ",", "old_text", ",", "new_text", ",", "instance_num", "=", "-", "1", ")", ":", "text", "=", "conversions", ".", "to_string", "(", "text", ",", "ctx", ")", "old_text", "=", "conversions", ".", "to_string", ...
Substitutes new_text for old_text in a text string
[ "Substitutes", "new_text", "for", "old_text", "in", "a", "text", "string" ]
train
https://github.com/rapidpro/expressions/blob/b03d91ec58fc328960bce90ecb5fa49dcf467627/python/temba_expressions/functions/excel.py#L109-L127
rapidpro/expressions
python/temba_expressions/functions/excel.py
_unicode
def _unicode(ctx, text): """ Returns a numeric code for the first character in a text string """ text = conversions.to_string(text, ctx) if len(text) == 0: raise ValueError("Text can't be empty") return ord(text[0])
python
def _unicode(ctx, text): """ Returns a numeric code for the first character in a text string """ text = conversions.to_string(text, ctx) if len(text) == 0: raise ValueError("Text can't be empty") return ord(text[0])
[ "def", "_unicode", "(", "ctx", ",", "text", ")", ":", "text", "=", "conversions", ".", "to_string", "(", "text", ",", "ctx", ")", "if", "len", "(", "text", ")", "==", "0", ":", "raise", "ValueError", "(", "\"Text can't be empty\"", ")", "return", "ord"...
Returns a numeric code for the first character in a text string
[ "Returns", "a", "numeric", "code", "for", "the", "first", "character", "in", "a", "text", "string" ]
train
https://github.com/rapidpro/expressions/blob/b03d91ec58fc328960bce90ecb5fa49dcf467627/python/temba_expressions/functions/excel.py#L137-L144
rapidpro/expressions
python/temba_expressions/functions/excel.py
date
def date(ctx, year, month, day): """ Defines a date value """ return _date(conversions.to_integer(year, ctx), conversions.to_integer(month, ctx), conversions.to_integer(day, ctx))
python
def date(ctx, year, month, day): """ Defines a date value """ return _date(conversions.to_integer(year, ctx), conversions.to_integer(month, ctx), conversions.to_integer(day, ctx))
[ "def", "date", "(", "ctx", ",", "year", ",", "month", ",", "day", ")", ":", "return", "_date", "(", "conversions", ".", "to_integer", "(", "year", ",", "ctx", ")", ",", "conversions", ".", "to_integer", "(", "month", ",", "ctx", ")", ",", "conversion...
Defines a date value
[ "Defines", "a", "date", "value" ]
train
https://github.com/rapidpro/expressions/blob/b03d91ec58fc328960bce90ecb5fa49dcf467627/python/temba_expressions/functions/excel.py#L157-L161
rapidpro/expressions
python/temba_expressions/functions/excel.py
datedif
def datedif(ctx, start_date, end_date, unit): """ Calculates the number of days, months, or years between two dates. """ start_date = conversions.to_date(start_date, ctx) end_date = conversions.to_date(end_date, ctx) unit = conversions.to_string(unit, ctx).lower() if start_date > end_date: ...
python
def datedif(ctx, start_date, end_date, unit): """ Calculates the number of days, months, or years between two dates. """ start_date = conversions.to_date(start_date, ctx) end_date = conversions.to_date(end_date, ctx) unit = conversions.to_string(unit, ctx).lower() if start_date > end_date: ...
[ "def", "datedif", "(", "ctx", ",", "start_date", ",", "end_date", ",", "unit", ")", ":", "start_date", "=", "conversions", ".", "to_date", "(", "start_date", ",", "ctx", ")", "end_date", "=", "conversions", ".", "to_date", "(", "end_date", ",", "ctx", ")...
Calculates the number of days, months, or years between two dates.
[ "Calculates", "the", "number", "of", "days", "months", "or", "years", "between", "two", "dates", "." ]
train
https://github.com/rapidpro/expressions/blob/b03d91ec58fc328960bce90ecb5fa49dcf467627/python/temba_expressions/functions/excel.py#L164-L189
rapidpro/expressions
python/temba_expressions/functions/excel.py
edate
def edate(ctx, date, months): """ Moves a date by the given number of months """ return conversions.to_date_or_datetime(date, ctx) + relativedelta(months=conversions.to_integer(months, ctx))
python
def edate(ctx, date, months): """ Moves a date by the given number of months """ return conversions.to_date_or_datetime(date, ctx) + relativedelta(months=conversions.to_integer(months, ctx))
[ "def", "edate", "(", "ctx", ",", "date", ",", "months", ")", ":", "return", "conversions", ".", "to_date_or_datetime", "(", "date", ",", "ctx", ")", "+", "relativedelta", "(", "months", "=", "conversions", ".", "to_integer", "(", "months", ",", "ctx", ")...
Moves a date by the given number of months
[ "Moves", "a", "date", "by", "the", "given", "number", "of", "months" ]
train
https://github.com/rapidpro/expressions/blob/b03d91ec58fc328960bce90ecb5fa49dcf467627/python/temba_expressions/functions/excel.py#L213-L217
rapidpro/expressions
python/temba_expressions/functions/excel.py
time
def time(ctx, hours, minutes, seconds): """ Defines a time value """ return _time(conversions.to_integer(hours, ctx), conversions.to_integer(minutes, ctx), conversions.to_integer(seconds, ctx))
python
def time(ctx, hours, minutes, seconds): """ Defines a time value """ return _time(conversions.to_integer(hours, ctx), conversions.to_integer(minutes, ctx), conversions.to_integer(seconds, ctx))
[ "def", "time", "(", "ctx", ",", "hours", ",", "minutes", ",", "seconds", ")", ":", "return", "_time", "(", "conversions", ".", "to_integer", "(", "hours", ",", "ctx", ")", ",", "conversions", ".", "to_integer", "(", "minutes", ",", "ctx", ")", ",", "...
Defines a time value
[ "Defines", "a", "time", "value" ]
train
https://github.com/rapidpro/expressions/blob/b03d91ec58fc328960bce90ecb5fa49dcf467627/python/temba_expressions/functions/excel.py#L255-L259
rapidpro/expressions
python/temba_expressions/functions/excel.py
_abs
def _abs(ctx, number): """ Returns the absolute value of a number """ return conversions.to_decimal(abs(conversions.to_decimal(number, ctx)), ctx)
python
def _abs(ctx, number): """ Returns the absolute value of a number """ return conversions.to_decimal(abs(conversions.to_decimal(number, ctx)), ctx)
[ "def", "_abs", "(", "ctx", ",", "number", ")", ":", "return", "conversions", ".", "to_decimal", "(", "abs", "(", "conversions", ".", "to_decimal", "(", "number", ",", "ctx", ")", ")", ",", "ctx", ")" ]
Returns the absolute value of a number
[ "Returns", "the", "absolute", "value", "of", "a", "number" ]
train
https://github.com/rapidpro/expressions/blob/b03d91ec58fc328960bce90ecb5fa49dcf467627/python/temba_expressions/functions/excel.py#L293-L297
rapidpro/expressions
python/temba_expressions/functions/excel.py
_int
def _int(ctx, number): """ Rounds a number down to the nearest integer """ return conversions.to_integer(conversions.to_decimal(number, ctx).to_integral_value(ROUND_FLOOR), ctx)
python
def _int(ctx, number): """ Rounds a number down to the nearest integer """ return conversions.to_integer(conversions.to_decimal(number, ctx).to_integral_value(ROUND_FLOOR), ctx)
[ "def", "_int", "(", "ctx", ",", "number", ")", ":", "return", "conversions", ".", "to_integer", "(", "conversions", ".", "to_decimal", "(", "number", ",", "ctx", ")", ".", "to_integral_value", "(", "ROUND_FLOOR", ")", ",", "ctx", ")" ]
Rounds a number down to the nearest integer
[ "Rounds", "a", "number", "down", "to", "the", "nearest", "integer" ]
train
https://github.com/rapidpro/expressions/blob/b03d91ec58fc328960bce90ecb5fa49dcf467627/python/temba_expressions/functions/excel.py#L314-L318
rapidpro/expressions
python/temba_expressions/functions/excel.py
_max
def _max(ctx, *number): """ Returns the maximum value of all arguments """ if len(number) == 0: raise ValueError("Wrong number of arguments") result = conversions.to_decimal(number[0], ctx) for arg in number[1:]: arg = conversions.to_decimal(arg, ctx) if arg > result: ...
python
def _max(ctx, *number): """ Returns the maximum value of all arguments """ if len(number) == 0: raise ValueError("Wrong number of arguments") result = conversions.to_decimal(number[0], ctx) for arg in number[1:]: arg = conversions.to_decimal(arg, ctx) if arg > result: ...
[ "def", "_max", "(", "ctx", ",", "*", "number", ")", ":", "if", "len", "(", "number", ")", "==", "0", ":", "raise", "ValueError", "(", "\"Wrong number of arguments\"", ")", "result", "=", "conversions", ".", "to_decimal", "(", "number", "[", "0", "]", "...
Returns the maximum value of all arguments
[ "Returns", "the", "maximum", "value", "of", "all", "arguments" ]
train
https://github.com/rapidpro/expressions/blob/b03d91ec58fc328960bce90ecb5fa49dcf467627/python/temba_expressions/functions/excel.py#L321-L333
rapidpro/expressions
python/temba_expressions/functions/excel.py
mod
def mod(ctx, number, divisor): """ Returns the remainder after number is divided by divisor """ number = conversions.to_decimal(number, ctx) divisor = conversions.to_decimal(divisor, ctx) return number - divisor * _int(ctx, number / divisor)
python
def mod(ctx, number, divisor): """ Returns the remainder after number is divided by divisor """ number = conversions.to_decimal(number, ctx) divisor = conversions.to_decimal(divisor, ctx) return number - divisor * _int(ctx, number / divisor)
[ "def", "mod", "(", "ctx", ",", "number", ",", "divisor", ")", ":", "number", "=", "conversions", ".", "to_decimal", "(", "number", ",", "ctx", ")", "divisor", "=", "conversions", ".", "to_decimal", "(", "divisor", ",", "ctx", ")", "return", "number", "...
Returns the remainder after number is divided by divisor
[ "Returns", "the", "remainder", "after", "number", "is", "divided", "by", "divisor" ]
train
https://github.com/rapidpro/expressions/blob/b03d91ec58fc328960bce90ecb5fa49dcf467627/python/temba_expressions/functions/excel.py#L351-L357
rapidpro/expressions
python/temba_expressions/functions/excel.py
_power
def _power(ctx, number, power): """ Returns the result of a number raised to a power """ return decimal_pow(conversions.to_decimal(number, ctx), conversions.to_decimal(power, ctx))
python
def _power(ctx, number, power): """ Returns the result of a number raised to a power """ return decimal_pow(conversions.to_decimal(number, ctx), conversions.to_decimal(power, ctx))
[ "def", "_power", "(", "ctx", ",", "number", ",", "power", ")", ":", "return", "decimal_pow", "(", "conversions", ".", "to_decimal", "(", "number", ",", "ctx", ")", ",", "conversions", ".", "to_decimal", "(", "power", ",", "ctx", ")", ")" ]
Returns the result of a number raised to a power
[ "Returns", "the", "result", "of", "a", "number", "raised", "to", "a", "power" ]
train
https://github.com/rapidpro/expressions/blob/b03d91ec58fc328960bce90ecb5fa49dcf467627/python/temba_expressions/functions/excel.py#L360-L364
rapidpro/expressions
python/temba_expressions/functions/excel.py
randbetween
def randbetween(ctx, bottom, top): """ Returns a random integer number between the numbers you specify """ bottom = conversions.to_integer(bottom, ctx) top = conversions.to_integer(top, ctx) return random.randint(bottom, top)
python
def randbetween(ctx, bottom, top): """ Returns a random integer number between the numbers you specify """ bottom = conversions.to_integer(bottom, ctx) top = conversions.to_integer(top, ctx) return random.randint(bottom, top)
[ "def", "randbetween", "(", "ctx", ",", "bottom", ",", "top", ")", ":", "bottom", "=", "conversions", ".", "to_integer", "(", "bottom", ",", "ctx", ")", "top", "=", "conversions", ".", "to_integer", "(", "top", ",", "ctx", ")", "return", "random", ".", ...
Returns a random integer number between the numbers you specify
[ "Returns", "a", "random", "integer", "number", "between", "the", "numbers", "you", "specify" ]
train
https://github.com/rapidpro/expressions/blob/b03d91ec58fc328960bce90ecb5fa49dcf467627/python/temba_expressions/functions/excel.py#L374-L380
rapidpro/expressions
python/temba_expressions/functions/excel.py
_round
def _round(ctx, number, num_digits): """ Rounds a number to a specified number of digits """ number = conversions.to_decimal(number, ctx) num_digits = conversions.to_integer(num_digits, ctx) return decimal_round(number, num_digits, ROUND_HALF_UP)
python
def _round(ctx, number, num_digits): """ Rounds a number to a specified number of digits """ number = conversions.to_decimal(number, ctx) num_digits = conversions.to_integer(num_digits, ctx) return decimal_round(number, num_digits, ROUND_HALF_UP)
[ "def", "_round", "(", "ctx", ",", "number", ",", "num_digits", ")", ":", "number", "=", "conversions", ".", "to_decimal", "(", "number", ",", "ctx", ")", "num_digits", "=", "conversions", ".", "to_integer", "(", "num_digits", ",", "ctx", ")", "return", "...
Rounds a number to a specified number of digits
[ "Rounds", "a", "number", "to", "a", "specified", "number", "of", "digits" ]
train
https://github.com/rapidpro/expressions/blob/b03d91ec58fc328960bce90ecb5fa49dcf467627/python/temba_expressions/functions/excel.py#L383-L390
rapidpro/expressions
python/temba_expressions/functions/excel.py
rounddown
def rounddown(ctx, number, num_digits): """ Rounds a number down, toward zero """ number = conversions.to_decimal(number, ctx) num_digits = conversions.to_integer(num_digits, ctx) return decimal_round(number, num_digits, ROUND_DOWN)
python
def rounddown(ctx, number, num_digits): """ Rounds a number down, toward zero """ number = conversions.to_decimal(number, ctx) num_digits = conversions.to_integer(num_digits, ctx) return decimal_round(number, num_digits, ROUND_DOWN)
[ "def", "rounddown", "(", "ctx", ",", "number", ",", "num_digits", ")", ":", "number", "=", "conversions", ".", "to_decimal", "(", "number", ",", "ctx", ")", "num_digits", "=", "conversions", ".", "to_integer", "(", "num_digits", ",", "ctx", ")", "return", ...
Rounds a number down, toward zero
[ "Rounds", "a", "number", "down", "toward", "zero" ]
train
https://github.com/rapidpro/expressions/blob/b03d91ec58fc328960bce90ecb5fa49dcf467627/python/temba_expressions/functions/excel.py#L393-L400
rapidpro/expressions
python/temba_expressions/functions/excel.py
roundup
def roundup(ctx, number, num_digits): """ Rounds a number up, away from zero """ number = conversions.to_decimal(number, ctx) num_digits = conversions.to_integer(num_digits, ctx) return decimal_round(number, num_digits, ROUND_UP)
python
def roundup(ctx, number, num_digits): """ Rounds a number up, away from zero """ number = conversions.to_decimal(number, ctx) num_digits = conversions.to_integer(num_digits, ctx) return decimal_round(number, num_digits, ROUND_UP)
[ "def", "roundup", "(", "ctx", ",", "number", ",", "num_digits", ")", ":", "number", "=", "conversions", ".", "to_decimal", "(", "number", ",", "ctx", ")", "num_digits", "=", "conversions", ".", "to_integer", "(", "num_digits", ",", "ctx", ")", "return", ...
Rounds a number up, away from zero
[ "Rounds", "a", "number", "up", "away", "from", "zero" ]
train
https://github.com/rapidpro/expressions/blob/b03d91ec58fc328960bce90ecb5fa49dcf467627/python/temba_expressions/functions/excel.py#L403-L410
rapidpro/expressions
python/temba_expressions/functions/excel.py
_sum
def _sum(ctx, *number): """ Returns the sum of all arguments """ if len(number) == 0: raise ValueError("Wrong number of arguments") result = Decimal(0) for arg in number: result += conversions.to_decimal(arg, ctx) return result
python
def _sum(ctx, *number): """ Returns the sum of all arguments """ if len(number) == 0: raise ValueError("Wrong number of arguments") result = Decimal(0) for arg in number: result += conversions.to_decimal(arg, ctx) return result
[ "def", "_sum", "(", "ctx", ",", "*", "number", ")", ":", "if", "len", "(", "number", ")", "==", "0", ":", "raise", "ValueError", "(", "\"Wrong number of arguments\"", ")", "result", "=", "Decimal", "(", "0", ")", "for", "arg", "in", "number", ":", "r...
Returns the sum of all arguments
[ "Returns", "the", "sum", "of", "all", "arguments" ]
train
https://github.com/rapidpro/expressions/blob/b03d91ec58fc328960bce90ecb5fa49dcf467627/python/temba_expressions/functions/excel.py#L413-L423
rapidpro/expressions
python/temba_expressions/functions/excel.py
trunc
def trunc(ctx, number): """ Truncates a number to an integer by removing the fractional part of the number """ return conversions.to_integer(conversions.to_decimal(number, ctx).to_integral_value(ROUND_DOWN), ctx)
python
def trunc(ctx, number): """ Truncates a number to an integer by removing the fractional part of the number """ return conversions.to_integer(conversions.to_decimal(number, ctx).to_integral_value(ROUND_DOWN), ctx)
[ "def", "trunc", "(", "ctx", ",", "number", ")", ":", "return", "conversions", ".", "to_integer", "(", "conversions", ".", "to_decimal", "(", "number", ",", "ctx", ")", ".", "to_integral_value", "(", "ROUND_DOWN", ")", ",", "ctx", ")" ]
Truncates a number to an integer by removing the fractional part of the number
[ "Truncates", "a", "number", "to", "an", "integer", "by", "removing", "the", "fractional", "part", "of", "the", "number" ]
train
https://github.com/rapidpro/expressions/blob/b03d91ec58fc328960bce90ecb5fa49dcf467627/python/temba_expressions/functions/excel.py#L426-L430
rapidpro/expressions
python/temba_expressions/functions/excel.py
_and
def _and(ctx, *logical): """ Returns TRUE if and only if all its arguments evaluate to TRUE """ for arg in logical: if not conversions.to_boolean(arg, ctx): return False return True
python
def _and(ctx, *logical): """ Returns TRUE if and only if all its arguments evaluate to TRUE """ for arg in logical: if not conversions.to_boolean(arg, ctx): return False return True
[ "def", "_and", "(", "ctx", ",", "*", "logical", ")", ":", "for", "arg", "in", "logical", ":", "if", "not", "conversions", ".", "to_boolean", "(", "arg", ",", "ctx", ")", ":", "return", "False", "return", "True" ]
Returns TRUE if and only if all its arguments evaluate to TRUE
[ "Returns", "TRUE", "if", "and", "only", "if", "all", "its", "arguments", "evaluate", "to", "TRUE" ]
train
https://github.com/rapidpro/expressions/blob/b03d91ec58fc328960bce90ecb5fa49dcf467627/python/temba_expressions/functions/excel.py#L435-L442
rapidpro/expressions
python/temba_expressions/functions/excel.py
_if
def _if(ctx, logical_test, value_if_true=0, value_if_false=False): """ Returns one value if the condition evaluates to TRUE, and another value if it evaluates to FALSE """ return value_if_true if conversions.to_boolean(logical_test, ctx) else value_if_false
python
def _if(ctx, logical_test, value_if_true=0, value_if_false=False): """ Returns one value if the condition evaluates to TRUE, and another value if it evaluates to FALSE """ return value_if_true if conversions.to_boolean(logical_test, ctx) else value_if_false
[ "def", "_if", "(", "ctx", ",", "logical_test", ",", "value_if_true", "=", "0", ",", "value_if_false", "=", "False", ")", ":", "return", "value_if_true", "if", "conversions", ".", "to_boolean", "(", "logical_test", ",", "ctx", ")", "else", "value_if_false" ]
Returns one value if the condition evaluates to TRUE, and another value if it evaluates to FALSE
[ "Returns", "one", "value", "if", "the", "condition", "evaluates", "to", "TRUE", "and", "another", "value", "if", "it", "evaluates", "to", "FALSE" ]
train
https://github.com/rapidpro/expressions/blob/b03d91ec58fc328960bce90ecb5fa49dcf467627/python/temba_expressions/functions/excel.py#L452-L456
rapidpro/expressions
python/temba_expressions/functions/excel.py
_or
def _or(ctx, *logical): """ Returns TRUE if any argument is TRUE """ for arg in logical: if conversions.to_boolean(arg, ctx): return True return False
python
def _or(ctx, *logical): """ Returns TRUE if any argument is TRUE """ for arg in logical: if conversions.to_boolean(arg, ctx): return True return False
[ "def", "_or", "(", "ctx", ",", "*", "logical", ")", ":", "for", "arg", "in", "logical", ":", "if", "conversions", ".", "to_boolean", "(", "arg", ",", "ctx", ")", ":", "return", "True", "return", "False" ]
Returns TRUE if any argument is TRUE
[ "Returns", "TRUE", "if", "any", "argument", "is", "TRUE" ]
train
https://github.com/rapidpro/expressions/blob/b03d91ec58fc328960bce90ecb5fa49dcf467627/python/temba_expressions/functions/excel.py#L459-L466
rainwoodman/kdcount
kdcount/correlate.py
compute_sum_values
def compute_sum_values(i, j, data1, data2): """ Return the sum1_ij and sum2_ij values given the input indices and data instances. Notes ----- This is called in `Binning.update_sums` to compute the `sum1` and `sum2` contributions for indices `(i,j)` Parameters ---------- i,j : a...
python
def compute_sum_values(i, j, data1, data2): """ Return the sum1_ij and sum2_ij values given the input indices and data instances. Notes ----- This is called in `Binning.update_sums` to compute the `sum1` and `sum2` contributions for indices `(i,j)` Parameters ---------- i,j : a...
[ "def", "compute_sum_values", "(", "i", ",", "j", ",", "data1", ",", "data2", ")", ":", "sum1_ij", "=", "1.", "for", "idx", ",", "d", "in", "zip", "(", "[", "i", ",", "j", "]", ",", "[", "data1", ",", "data2", "]", ")", ":", "if", "isinstance", ...
Return the sum1_ij and sum2_ij values given the input indices and data instances. Notes ----- This is called in `Binning.update_sums` to compute the `sum1` and `sum2` contributions for indices `(i,j)` Parameters ---------- i,j : array_like the bin indices for these pairs da...
[ "Return", "the", "sum1_ij", "and", "sum2_ij", "values", "given", "the", "input", "indices", "and", "data", "instances", "." ]
train
https://github.com/rainwoodman/kdcount/blob/483548f6d27a4f245cd5d98880b5f4edd6cc8dc1/kdcount/correlate.py#L46-L77
rainwoodman/kdcount
kdcount/correlate.py
Binning._setup
def _setup(self): """ Set the binning info we need from the `edges` """ dtype = [('inv', 'f8'), ('min', 'f8'), ('max', 'f8'),('N', 'i4'), ('spacing','object')] dtype = numpy.dtype(dtype) self._info = numpy.empty(self.Ndim, dtype=dtype) self.min = self...
python
def _setup(self): """ Set the binning info we need from the `edges` """ dtype = [('inv', 'f8'), ('min', 'f8'), ('max', 'f8'),('N', 'i4'), ('spacing','object')] dtype = numpy.dtype(dtype) self._info = numpy.empty(self.Ndim, dtype=dtype) self.min = self...
[ "def", "_setup", "(", "self", ")", ":", "dtype", "=", "[", "(", "'inv'", ",", "'f8'", ")", ",", "(", "'min'", ",", "'f8'", ")", ",", "(", "'max'", ",", "'f8'", ")", ",", "(", "'N'", ",", "'i4'", ")", ",", "(", "'spacing'", ",", "'object'", ")...
Set the binning info we need from the `edges`
[ "Set", "the", "binning", "info", "we", "need", "from", "the", "edges" ]
train
https://github.com/rainwoodman/kdcount/blob/483548f6d27a4f245cd5d98880b5f4edd6cc8dc1/kdcount/correlate.py#L135-L169
rainwoodman/kdcount
kdcount/correlate.py
Binning.linear
def linear(self, **paircoords): """ Linearize bin indices. This function is called by subclasses. Refer to the source code of :py:class:`RBinning` for an example. Parameters ---------- args : list a list of bin index, (xi, yi, zi, ..) Ret...
python
def linear(self, **paircoords): """ Linearize bin indices. This function is called by subclasses. Refer to the source code of :py:class:`RBinning` for an example. Parameters ---------- args : list a list of bin index, (xi, yi, zi, ..) Ret...
[ "def", "linear", "(", "self", ",", "*", "*", "paircoords", ")", ":", "N", "=", "len", "(", "paircoords", "[", "list", "(", "paircoords", ".", "keys", "(", ")", ")", "[", "0", "]", "]", ")", "integer", "=", "numpy", ".", "empty", "(", "N", ",", ...
Linearize bin indices. This function is called by subclasses. Refer to the source code of :py:class:`RBinning` for an example. Parameters ---------- args : list a list of bin index, (xi, yi, zi, ..) Returns ------- linearlized bin index
[ "Linearize", "bin", "indices", "." ]
train
https://github.com/rainwoodman/kdcount/blob/483548f6d27a4f245cd5d98880b5f4edd6cc8dc1/kdcount/correlate.py#L172-L208
rainwoodman/kdcount
kdcount/correlate.py
Binning.update_sums
def update_sums(self, r, i, j, data1, data2, sum1, sum2, N=None, centers_sum=None): """ The main function that digitizes the pair counts, calls bincount for the appropriate `sum1` and `sum2` values, and adds them to the input arrays, will modify sum1, sum2, N, and centers_sum in...
python
def update_sums(self, r, i, j, data1, data2, sum1, sum2, N=None, centers_sum=None): """ The main function that digitizes the pair counts, calls bincount for the appropriate `sum1` and `sum2` values, and adds them to the input arrays, will modify sum1, sum2, N, and centers_sum in...
[ "def", "update_sums", "(", "self", ",", "r", ",", "i", ",", "j", ",", "data1", ",", "data2", ",", "sum1", ",", "sum2", ",", "N", "=", "None", ",", "centers_sum", "=", "None", ")", ":", "# the summation values for this (r,i,j)", "sum1_ij", ",", "sum2_ij",...
The main function that digitizes the pair counts, calls bincount for the appropriate `sum1` and `sum2` values, and adds them to the input arrays, will modify sum1, sum2, N, and centers_sum inplace.
[ "The", "main", "function", "that", "digitizes", "the", "pair", "counts", "calls", "bincount", "for", "the", "appropriate", "sum1", "and", "sum2", "values", "and", "adds", "them", "to", "the", "input", "arrays" ]
train
https://github.com/rainwoodman/kdcount/blob/483548f6d27a4f245cd5d98880b5f4edd6cc8dc1/kdcount/correlate.py#L238-L291
rainwoodman/kdcount
kdcount/correlate.py
Binning.sum_shapes
def sum_shapes(self, data1, data2): """ Return the shapes of the summation arrays, given the input data and shape of the bins """ # the linear shape (put extra dimensions first) linearshape = [-1] + list(self.shape) # determine the full shape subshapes = ...
python
def sum_shapes(self, data1, data2): """ Return the shapes of the summation arrays, given the input data and shape of the bins """ # the linear shape (put extra dimensions first) linearshape = [-1] + list(self.shape) # determine the full shape subshapes = ...
[ "def", "sum_shapes", "(", "self", ",", "data1", ",", "data2", ")", ":", "# the linear shape (put extra dimensions first)", "linearshape", "=", "[", "-", "1", "]", "+", "list", "(", "self", ".", "shape", ")", "# determine the full shape", "subshapes", "=", "[", ...
Return the shapes of the summation arrays, given the input data and shape of the bins
[ "Return", "the", "shapes", "of", "the", "summation", "arrays", "given", "the", "input", "data", "and", "shape", "of", "the", "bins" ]
train
https://github.com/rainwoodman/kdcount/blob/483548f6d27a4f245cd5d98880b5f4edd6cc8dc1/kdcount/correlate.py#L293-L315
rainwoodman/kdcount
kdcount/correlate.py
Binning._update_mean_coords
def _update_mean_coords(self, dig, N, centers_sum, **paircoords): """ Update the mean coordinate sums """ if N is None or centers_sum is None: return N.flat[:] += utils.bincount(dig, 1., minlength=N.size) for i, dim in enumerate(self.dims): size = centers_sum...
python
def _update_mean_coords(self, dig, N, centers_sum, **paircoords): """ Update the mean coordinate sums """ if N is None or centers_sum is None: return N.flat[:] += utils.bincount(dig, 1., minlength=N.size) for i, dim in enumerate(self.dims): size = centers_sum...
[ "def", "_update_mean_coords", "(", "self", ",", "dig", ",", "N", ",", "centers_sum", ",", "*", "*", "paircoords", ")", ":", "if", "N", "is", "None", "or", "centers_sum", "is", "None", ":", "return", "N", ".", "flat", "[", ":", "]", "+=", "utils", "...
Update the mean coordinate sums
[ "Update", "the", "mean", "coordinate", "sums" ]
train
https://github.com/rainwoodman/kdcount/blob/483548f6d27a4f245cd5d98880b5f4edd6cc8dc1/kdcount/correlate.py#L317-L326
rainwoodman/kdcount
kdcount/correlate.py
paircount_queue.work
def work(self, i): """ Internal function that performs the pair-counting """ n1, n2 = self.p[i] # initialize the total arrays for this process sum1 = numpy.zeros_like(self.sum1g) sum2 = 1. if not self.pts_only: sum2 = numpy.zeros_like(self.sum2g) ...
python
def work(self, i): """ Internal function that performs the pair-counting """ n1, n2 = self.p[i] # initialize the total arrays for this process sum1 = numpy.zeros_like(self.sum1g) sum2 = 1. if not self.pts_only: sum2 = numpy.zeros_like(self.sum2g) ...
[ "def", "work", "(", "self", ",", "i", ")", ":", "n1", ",", "n2", "=", "self", ".", "p", "[", "i", "]", "# initialize the total arrays for this process", "sum1", "=", "numpy", ".", "zeros_like", "(", "self", ".", "sum1g", ")", "sum2", "=", "1.", "if", ...
Internal function that performs the pair-counting
[ "Internal", "function", "that", "performs", "the", "pair", "-", "counting" ]
train
https://github.com/rainwoodman/kdcount/blob/483548f6d27a4f245cd5d98880b5f4edd6cc8dc1/kdcount/correlate.py#L739-L778
rainwoodman/kdcount
kdcount/correlate.py
paircount_queue.reduce
def reduce(self, sum1, sum2, *args): """ The internal reduce function that sums the results from various processors """ self.sum1g[...] += sum1 if not self.pts_only: self.sum2g[...] += sum2 if self.compute_mean_coords: N, centers_sum = args ...
python
def reduce(self, sum1, sum2, *args): """ The internal reduce function that sums the results from various processors """ self.sum1g[...] += sum1 if not self.pts_only: self.sum2g[...] += sum2 if self.compute_mean_coords: N, centers_sum = args ...
[ "def", "reduce", "(", "self", ",", "sum1", ",", "sum2", ",", "*", "args", ")", ":", "self", ".", "sum1g", "[", "...", "]", "+=", "sum1", "if", "not", "self", ".", "pts_only", ":", "self", ".", "sum2g", "[", "...", "]", "+=", "sum2", "if", "self...
The internal reduce function that sums the results from various processors
[ "The", "internal", "reduce", "function", "that", "sums", "the", "results", "from", "various", "processors" ]
train
https://github.com/rainwoodman/kdcount/blob/483548f6d27a4f245cd5d98880b5f4edd6cc8dc1/kdcount/correlate.py#L780-L792
hammerlab/stanity
stanity/psis.py
psisloo
def psisloo(log_lik, **kwargs): r"""PSIS leave-one-out log predictive densities. Computes the log predictive densities given posterior samples of the log likelihood terms :math:`p(y_i|\theta^s)` in input parameter `log_lik`. Returns a sum of the leave-one-out log predictive densities `loo`, individ...
python
def psisloo(log_lik, **kwargs): r"""PSIS leave-one-out log predictive densities. Computes the log predictive densities given posterior samples of the log likelihood terms :math:`p(y_i|\theta^s)` in input parameter `log_lik`. Returns a sum of the leave-one-out log predictive densities `loo`, individ...
[ "def", "psisloo", "(", "log_lik", ",", "*", "*", "kwargs", ")", ":", "# ensure overwrite flag in passed arguments", "kwargs", "[", "'overwrite_lw'", "]", "=", "True", "# log raw weights from log_lik", "lw", "=", "-", "log_lik", "# compute Pareto smoothed log weights given...
r"""PSIS leave-one-out log predictive densities. Computes the log predictive densities given posterior samples of the log likelihood terms :math:`p(y_i|\theta^s)` in input parameter `log_lik`. Returns a sum of the leave-one-out log predictive densities `loo`, individual leave-one-out log predictive den...
[ "r", "PSIS", "leave", "-", "one", "-", "out", "log", "predictive", "densities", "." ]
train
https://github.com/hammerlab/stanity/blob/6c36abc207c4ce94f78968501dab839a56f35a41/stanity/psis.py#L69-L110
hammerlab/stanity
stanity/psis.py
psislw
def psislw(lw, Reff=1.0, overwrite_lw=False): """Pareto smoothed importance sampling (PSIS). Parameters ---------- lw : ndarray Array of size n x m containing m sets of n log weights. It is also possible to provide one dimensional array of length n. Reff : scalar, optional ...
python
def psislw(lw, Reff=1.0, overwrite_lw=False): """Pareto smoothed importance sampling (PSIS). Parameters ---------- lw : ndarray Array of size n x m containing m sets of n log weights. It is also possible to provide one dimensional array of length n. Reff : scalar, optional ...
[ "def", "psislw", "(", "lw", ",", "Reff", "=", "1.0", ",", "overwrite_lw", "=", "False", ")", ":", "if", "lw", ".", "ndim", "==", "2", ":", "n", ",", "m", "=", "lw", ".", "shape", "elif", "lw", ".", "ndim", "==", "1", ":", "n", "=", "len", "...
Pareto smoothed importance sampling (PSIS). Parameters ---------- lw : ndarray Array of size n x m containing m sets of n log weights. It is also possible to provide one dimensional array of length n. Reff : scalar, optional relative MCMC efficiency ``N_eff / N`` overwrite...
[ "Pareto", "smoothed", "importance", "sampling", "(", "PSIS", ")", "." ]
train
https://github.com/hammerlab/stanity/blob/6c36abc207c4ce94f78968501dab839a56f35a41/stanity/psis.py#L113-L209
hammerlab/stanity
stanity/psis.py
gpdfitnew
def gpdfitnew(x, sort=True, sort_in_place=False, return_quadrature=False): """Estimate the paramaters for the Generalized Pareto Distribution (GPD) Returns empirical Bayes estimate for the parameters of the two-parameter generalized Parato distribution given the data. Parameters ---------- x :...
python
def gpdfitnew(x, sort=True, sort_in_place=False, return_quadrature=False): """Estimate the paramaters for the Generalized Pareto Distribution (GPD) Returns empirical Bayes estimate for the parameters of the two-parameter generalized Parato distribution given the data. Parameters ---------- x :...
[ "def", "gpdfitnew", "(", "x", ",", "sort", "=", "True", ",", "sort_in_place", "=", "False", ",", "return_quadrature", "=", "False", ")", ":", "if", "x", ".", "ndim", "!=", "1", "or", "len", "(", "x", ")", "<=", "1", ":", "raise", "ValueError", "(",...
Estimate the paramaters for the Generalized Pareto Distribution (GPD) Returns empirical Bayes estimate for the parameters of the two-parameter generalized Parato distribution given the data. Parameters ---------- x : ndarray One dimensional data array sort : bool or ndarray, optional ...
[ "Estimate", "the", "paramaters", "for", "the", "Generalized", "Pareto", "Distribution", "(", "GPD", ")" ]
train
https://github.com/hammerlab/stanity/blob/6c36abc207c4ce94f78968501dab839a56f35a41/stanity/psis.py#L212-L332
hammerlab/stanity
stanity/psis.py
gpinv
def gpinv(p, k, sigma): """Inverse Generalised Pareto distribution function.""" x = np.empty(p.shape) x.fill(np.nan) if sigma <= 0: return x ok = (p > 0) & (p < 1) if np.all(ok): if np.abs(k) < np.finfo(float).eps: np.negative(p, out=x) np.log1p(x, out=x) ...
python
def gpinv(p, k, sigma): """Inverse Generalised Pareto distribution function.""" x = np.empty(p.shape) x.fill(np.nan) if sigma <= 0: return x ok = (p > 0) & (p < 1) if np.all(ok): if np.abs(k) < np.finfo(float).eps: np.negative(p, out=x) np.log1p(x, out=x) ...
[ "def", "gpinv", "(", "p", ",", "k", ",", "sigma", ")", ":", "x", "=", "np", ".", "empty", "(", "p", ".", "shape", ")", "x", ".", "fill", "(", "np", ".", "nan", ")", "if", "sigma", "<=", "0", ":", "return", "x", "ok", "=", "(", "p", ">", ...
Inverse Generalised Pareto distribution function.
[ "Inverse", "Generalised", "Pareto", "distribution", "function", "." ]
train
https://github.com/hammerlab/stanity/blob/6c36abc207c4ce94f78968501dab839a56f35a41/stanity/psis.py#L335-L377
hammerlab/stanity
stanity/psis.py
sumlogs
def sumlogs(x, axis=None, out=None): """Sum of vector where numbers are represented by their logarithms. Calculates ``np.log(np.sum(np.exp(x), axis=axis))`` in such a fashion that it works even when elements have large magnitude. """ maxx = x.max(axis=axis, keepdims=True) xnorm = x - maxx ...
python
def sumlogs(x, axis=None, out=None): """Sum of vector where numbers are represented by their logarithms. Calculates ``np.log(np.sum(np.exp(x), axis=axis))`` in such a fashion that it works even when elements have large magnitude. """ maxx = x.max(axis=axis, keepdims=True) xnorm = x - maxx ...
[ "def", "sumlogs", "(", "x", ",", "axis", "=", "None", ",", "out", "=", "None", ")", ":", "maxx", "=", "x", ".", "max", "(", "axis", "=", "axis", ",", "keepdims", "=", "True", ")", "xnorm", "=", "x", "-", "maxx", "np", ".", "exp", "(", "xnorm"...
Sum of vector where numbers are represented by their logarithms. Calculates ``np.log(np.sum(np.exp(x), axis=axis))`` in such a fashion that it works even when elements have large magnitude.
[ "Sum", "of", "vector", "where", "numbers", "are", "represented", "by", "their", "logarithms", "." ]
train
https://github.com/hammerlab/stanity/blob/6c36abc207c4ce94f78968501dab839a56f35a41/stanity/psis.py#L380-L396
rapidpro/expressions
python/temba_expressions/functions/__init__.py
FunctionManager.add_library
def add_library(self, library): """ Adds functions from a library module :param library: the library module :return: """ for fn in library.__dict__.copy().values(): # ignore imported methods and anything beginning __ if inspect.isfunction(fn) and i...
python
def add_library(self, library): """ Adds functions from a library module :param library: the library module :return: """ for fn in library.__dict__.copy().values(): # ignore imported methods and anything beginning __ if inspect.isfunction(fn) and i...
[ "def", "add_library", "(", "self", ",", "library", ")", ":", "for", "fn", "in", "library", ".", "__dict__", ".", "copy", "(", ")", ".", "values", "(", ")", ":", "# ignore imported methods and anything beginning __", "if", "inspect", ".", "isfunction", "(", "...
Adds functions from a library module :param library: the library module :return:
[ "Adds", "functions", "from", "a", "library", "module", ":", "param", "library", ":", "the", "library", "module", ":", "return", ":" ]
train
https://github.com/rapidpro/expressions/blob/b03d91ec58fc328960bce90ecb5fa49dcf467627/python/temba_expressions/functions/__init__.py#L9-L24
rapidpro/expressions
python/temba_expressions/functions/__init__.py
FunctionManager.invoke_function
def invoke_function(self, ctx, name, arguments): """ Invokes the given function :param ctx: the evaluation context :param name: the function name (case insensitive) :param arguments: the arguments to be passed to the function :return: the function return value """...
python
def invoke_function(self, ctx, name, arguments): """ Invokes the given function :param ctx: the evaluation context :param name: the function name (case insensitive) :param arguments: the arguments to be passed to the function :return: the function return value """...
[ "def", "invoke_function", "(", "self", ",", "ctx", ",", "name", ",", "arguments", ")", ":", "from", "temba_expressions", "import", "EvaluationError", ",", "conversions", "# find function with given name", "func", "=", "self", ".", "get_function", "(", "name", ")",...
Invokes the given function :param ctx: the evaluation context :param name: the function name (case insensitive) :param arguments: the arguments to be passed to the function :return: the function return value
[ "Invokes", "the", "given", "function", ":", "param", "ctx", ":", "the", "evaluation", "context", ":", "param", "name", ":", "the", "function", "name", "(", "case", "insensitive", ")", ":", "param", "arguments", ":", "the", "arguments", "to", "be", "passed"...
train
https://github.com/rapidpro/expressions/blob/b03d91ec58fc328960bce90ecb5fa49dcf467627/python/temba_expressions/functions/__init__.py#L29-L81
rapidpro/expressions
python/temba_expressions/functions/__init__.py
FunctionManager.build_listing
def build_listing(self): """ Builds a listing of all functions sorted A-Z, with their names and descriptions """ def func_entry(name, func): args, varargs, defaults = self._get_arg_spec(func) # add regular arguments params = [{'name': str(a), 'optiona...
python
def build_listing(self): """ Builds a listing of all functions sorted A-Z, with their names and descriptions """ def func_entry(name, func): args, varargs, defaults = self._get_arg_spec(func) # add regular arguments params = [{'name': str(a), 'optiona...
[ "def", "build_listing", "(", "self", ")", ":", "def", "func_entry", "(", "name", ",", "func", ")", ":", "args", ",", "varargs", ",", "defaults", "=", "self", ".", "_get_arg_spec", "(", "func", ")", "# add regular arguments", "params", "=", "[", "{", "'na...
Builds a listing of all functions sorted A-Z, with their names and descriptions
[ "Builds", "a", "listing", "of", "all", "functions", "sorted", "A", "-", "Z", "with", "their", "names", "and", "descriptions" ]
train
https://github.com/rapidpro/expressions/blob/b03d91ec58fc328960bce90ecb5fa49dcf467627/python/temba_expressions/functions/__init__.py#L83-L102