repo
stringlengths
7
55
path
stringlengths
4
223
func_name
stringlengths
1
134
original_string
stringlengths
75
104k
language
stringclasses
1 value
code
stringlengths
75
104k
code_tokens
listlengths
19
28.4k
docstring
stringlengths
1
46.9k
docstring_tokens
listlengths
1
1.97k
sha
stringlengths
40
40
url
stringlengths
87
315
partition
stringclasses
1 value
cons3rt/pycons3rt
pycons3rt/aliasip.py
alias_ip_address
def alias_ip_address(ip_address, interface, aws=False): """Adds an IP alias to a specific interface Adds an ip address as an alias to the specified interface on Linux systems. :param ip_address: (str) IP address to set as an alias :param interface: (str) The interface number or full device name, i...
python
def alias_ip_address(ip_address, interface, aws=False): """Adds an IP alias to a specific interface Adds an ip address as an alias to the specified interface on Linux systems. :param ip_address: (str) IP address to set as an alias :param interface: (str) The interface number or full device name, i...
[ "def", "alias_ip_address", "(", "ip_address", ",", "interface", ",", "aws", "=", "False", ")", ":", "log", "=", "logging", ".", "getLogger", "(", "mod_logger", "+", "'.alias_ip_address'", ")", "# Validate args", "if", "not", "isinstance", "(", "ip_address", ",...
Adds an IP alias to a specific interface Adds an ip address as an alias to the specified interface on Linux systems. :param ip_address: (str) IP address to set as an alias :param interface: (str) The interface number or full device name, if an int is provided assumes the device name is eth<i> ...
[ "Adds", "an", "IP", "alias", "to", "a", "specific", "interface" ]
f004ab3a35c5bff2f698131fef3b2a8ed5a7596d
https://github.com/cons3rt/pycons3rt/blob/f004ab3a35c5bff2f698131fef3b2a8ed5a7596d/pycons3rt/aliasip.py#L106-L263
train
cons3rt/pycons3rt
pycons3rt/aliasip.py
set_source_ip_for_interface
def set_source_ip_for_interface(source_ip_address, desired_source_ip_address, device_num=0): """Configures the source IP address for a Linux interface :param source_ip_address: (str) Source IP address to change :param desired_source_ip_address: (str) IP address to configure as the source in outgoing packet...
python
def set_source_ip_for_interface(source_ip_address, desired_source_ip_address, device_num=0): """Configures the source IP address for a Linux interface :param source_ip_address: (str) Source IP address to change :param desired_source_ip_address: (str) IP address to configure as the source in outgoing packet...
[ "def", "set_source_ip_for_interface", "(", "source_ip_address", ",", "desired_source_ip_address", ",", "device_num", "=", "0", ")", ":", "log", "=", "logging", ".", "getLogger", "(", "mod_logger", "+", "'.set_source_ip_for_interface'", ")", "if", "not", "isinstance", ...
Configures the source IP address for a Linux interface :param source_ip_address: (str) Source IP address to change :param desired_source_ip_address: (str) IP address to configure as the source in outgoing packets :param device_num: (int) Integer interface device number to configure :return: None :r...
[ "Configures", "the", "source", "IP", "address", "for", "a", "Linux", "interface" ]
f004ab3a35c5bff2f698131fef3b2a8ed5a7596d
https://github.com/cons3rt/pycons3rt/blob/f004ab3a35c5bff2f698131fef3b2a8ed5a7596d/pycons3rt/aliasip.py#L266-L328
train
ktsstudio/tornkts
tornkts/handlers/object_handler.py
ObjectHandler.save_logic
def save_logic(self, some_object): """ Перед сохранением в методе save вызывается этот метод :param some_object: сохраненный объект """ some_object.validate_model() some_object.save() self.send_success_response(data=some_object.to_dict())
python
def save_logic(self, some_object): """ Перед сохранением в методе save вызывается этот метод :param some_object: сохраненный объект """ some_object.validate_model() some_object.save() self.send_success_response(data=some_object.to_dict())
[ "def", "save_logic", "(", "self", ",", "some_object", ")", ":", "some_object", ".", "validate_model", "(", ")", "some_object", ".", "save", "(", ")", "self", ".", "send_success_response", "(", "data", "=", "some_object", ".", "to_dict", "(", ")", ")" ]
Перед сохранением в методе save вызывается этот метод :param some_object: сохраненный объект
[ "Перед", "сохранением", "в", "методе", "save", "вызывается", "этот", "метод", ":", "param", "some_object", ":", "сохраненный", "объект" ]
db47e4550426282960a7e4486dcc4399c8d52e02
https://github.com/ktsstudio/tornkts/blob/db47e4550426282960a7e4486dcc4399c8d52e02/tornkts/handlers/object_handler.py#L80-L87
train
novopl/peltak
src/peltak/core/shell.py
fmt
def fmt(msg, *args, **kw): # type: (str, *Any, **Any) -> str """ Generate shell color opcodes from a pretty coloring syntax. """ global is_tty if len(args) or len(kw): msg = msg.format(*args, **kw) opcode_subst = '\x1b[\\1m' if is_tty else '' return re.sub(r'<(\d{1,2})>', opcode_subst,...
python
def fmt(msg, *args, **kw): # type: (str, *Any, **Any) -> str """ Generate shell color opcodes from a pretty coloring syntax. """ global is_tty if len(args) or len(kw): msg = msg.format(*args, **kw) opcode_subst = '\x1b[\\1m' if is_tty else '' return re.sub(r'<(\d{1,2})>', opcode_subst,...
[ "def", "fmt", "(", "msg", ",", "*", "args", ",", "*", "*", "kw", ")", ":", "# type: (str, *Any, **Any) -> str", "global", "is_tty", "if", "len", "(", "args", ")", "or", "len", "(", "kw", ")", ":", "msg", "=", "msg", ".", "format", "(", "*", "args",...
Generate shell color opcodes from a pretty coloring syntax.
[ "Generate", "shell", "color", "opcodes", "from", "a", "pretty", "coloring", "syntax", "." ]
b627acc019e3665875fe76cdca0a14773b69beaa
https://github.com/novopl/peltak/blob/b627acc019e3665875fe76cdca0a14773b69beaa/src/peltak/core/shell.py#L55-L64
train
novopl/peltak
src/peltak/core/shell.py
cprint
def cprint(msg, *args, **kw): # type: (str, *Any, **Any) -> None """ Print colored message to stdout. """ if len(args) or len(kw): msg = msg.format(*args, **kw) print(fmt('{}<0>'.format(msg)))
python
def cprint(msg, *args, **kw): # type: (str, *Any, **Any) -> None """ Print colored message to stdout. """ if len(args) or len(kw): msg = msg.format(*args, **kw) print(fmt('{}<0>'.format(msg)))
[ "def", "cprint", "(", "msg", ",", "*", "args", ",", "*", "*", "kw", ")", ":", "# type: (str, *Any, **Any) -> None", "if", "len", "(", "args", ")", "or", "len", "(", "kw", ")", ":", "msg", "=", "msg", ".", "format", "(", "*", "args", ",", "*", "*"...
Print colored message to stdout.
[ "Print", "colored", "message", "to", "stdout", "." ]
b627acc019e3665875fe76cdca0a14773b69beaa
https://github.com/novopl/peltak/blob/b627acc019e3665875fe76cdca0a14773b69beaa/src/peltak/core/shell.py#L67-L73
train
novopl/peltak
src/peltak/core/shell.py
run
def run(cmd, capture=False, shell=True, env=None, exit_on_error=None, never_pretend=False): # type: (str, bool, bool, Dict[str, str], bool) -> ExecResult """ Run a shell command. Args: cmd (str): The shell command to execute. shell (bool):...
python
def run(cmd, capture=False, shell=True, env=None, exit_on_error=None, never_pretend=False): # type: (str, bool, bool, Dict[str, str], bool) -> ExecResult """ Run a shell command. Args: cmd (str): The shell command to execute. shell (bool):...
[ "def", "run", "(", "cmd", ",", "capture", "=", "False", ",", "shell", "=", "True", ",", "env", "=", "None", ",", "exit_on_error", "=", "None", ",", "never_pretend", "=", "False", ")", ":", "# type: (str, bool, bool, Dict[str, str], bool) -> ExecResult", "if", ...
Run a shell command. Args: cmd (str): The shell command to execute. shell (bool): Same as in `subprocess.Popen`. capture (bool): If set to True, it will capture the standard input/error instead of just piping it to the caller stdout/stderr. ...
[ "Run", "a", "shell", "command", "." ]
b627acc019e3665875fe76cdca0a14773b69beaa
https://github.com/novopl/peltak/blob/b627acc019e3665875fe76cdca0a14773b69beaa/src/peltak/core/shell.py#L76-L164
train
bitesofcode/pyramid_restful
pyramid_restful/utils.py
get_payload
def get_payload(request): """ Extracts the request's payload information. This method will merge the URL parameter information and the JSON body of the request together to generate a dictionary of key<->value pairings. This method assumes that the JSON body being provided is also a key-valu...
python
def get_payload(request): """ Extracts the request's payload information. This method will merge the URL parameter information and the JSON body of the request together to generate a dictionary of key<->value pairings. This method assumes that the JSON body being provided is also a key-valu...
[ "def", "get_payload", "(", "request", ")", ":", "# always extract values from the URL", "payload", "=", "dict", "(", "request", ".", "params", ".", "mixed", "(", ")", ")", "# provide override capability from the JSON body", "try", ":", "json_data", "=", "request", "...
Extracts the request's payload information. This method will merge the URL parameter information and the JSON body of the request together to generate a dictionary of key<->value pairings. This method assumes that the JSON body being provided is also a key-value map, if it is not, then an HTTPBadRe...
[ "Extracts", "the", "request", "s", "payload", "information", ".", "This", "method", "will", "merge", "the", "URL", "parameter", "information", "and", "the", "JSON", "body", "of", "the", "request", "together", "to", "generate", "a", "dictionary", "of", "key<", ...
0f1eccb2c61b9bd6add03b461d4e4d7901c957da
https://github.com/bitesofcode/pyramid_restful/blob/0f1eccb2c61b9bd6add03b461d4e4d7901c957da/pyramid_restful/utils.py#L4-L37
train
cons3rt/pycons3rt
pycons3rt/assetmailer.py
main
def main(): """Handles external calling for this module Execute this python module and provide the args shown below to external call this module to send email messages! :return: None """ log = logging.getLogger(mod_logger + '.main') parser = argparse.ArgumentParser(description='This module...
python
def main(): """Handles external calling for this module Execute this python module and provide the args shown below to external call this module to send email messages! :return: None """ log = logging.getLogger(mod_logger + '.main') parser = argparse.ArgumentParser(description='This module...
[ "def", "main", "(", ")", ":", "log", "=", "logging", ".", "getLogger", "(", "mod_logger", "+", "'.main'", ")", "parser", "=", "argparse", ".", "ArgumentParser", "(", "description", "=", "'This module allows sending email messages.'", ")", "parser", ".", "add_arg...
Handles external calling for this module Execute this python module and provide the args shown below to external call this module to send email messages! :return: None
[ "Handles", "external", "calling", "for", "this", "module" ]
f004ab3a35c5bff2f698131fef3b2a8ed5a7596d
https://github.com/cons3rt/pycons3rt/blob/f004ab3a35c5bff2f698131fef3b2a8ed5a7596d/pycons3rt/assetmailer.py#L178-L212
train
cons3rt/pycons3rt
pycons3rt/assetmailer.py
AssetMailer.send_cons3rt_agent_logs
def send_cons3rt_agent_logs(self): """Send the cons3rt agent log file :return: """ log = logging.getLogger(self.cls_logger + '.send_cons3rt_agent_logs') if self.cons3rt_agent_log_dir is None: log.warn('There is not CONS3RT agent log directory on this system') ...
python
def send_cons3rt_agent_logs(self): """Send the cons3rt agent log file :return: """ log = logging.getLogger(self.cls_logger + '.send_cons3rt_agent_logs') if self.cons3rt_agent_log_dir is None: log.warn('There is not CONS3RT agent log directory on this system') ...
[ "def", "send_cons3rt_agent_logs", "(", "self", ")", ":", "log", "=", "logging", ".", "getLogger", "(", "self", ".", "cls_logger", "+", "'.send_cons3rt_agent_logs'", ")", "if", "self", ".", "cons3rt_agent_log_dir", "is", "None", ":", "log", ".", "warn", "(", ...
Send the cons3rt agent log file :return:
[ "Send", "the", "cons3rt", "agent", "log", "file" ]
f004ab3a35c5bff2f698131fef3b2a8ed5a7596d
https://github.com/cons3rt/pycons3rt/blob/f004ab3a35c5bff2f698131fef3b2a8ed5a7596d/pycons3rt/assetmailer.py#L63-L87
train
cons3rt/pycons3rt
pycons3rt/assetmailer.py
AssetMailer.send_text_file
def send_text_file(self, text_file, sender=None, recipient=None): """Sends an email with the contents of the provided text file :return: None """ log = logging.getLogger(self.cls_logger + '.send_text_file') if not isinstance(text_file, basestring): msg = 'arg text_f...
python
def send_text_file(self, text_file, sender=None, recipient=None): """Sends an email with the contents of the provided text file :return: None """ log = logging.getLogger(self.cls_logger + '.send_text_file') if not isinstance(text_file, basestring): msg = 'arg text_f...
[ "def", "send_text_file", "(", "self", ",", "text_file", ",", "sender", "=", "None", ",", "recipient", "=", "None", ")", ":", "log", "=", "logging", ".", "getLogger", "(", "self", ".", "cls_logger", "+", "'.send_text_file'", ")", "if", "not", "isinstance", ...
Sends an email with the contents of the provided text file :return: None
[ "Sends", "an", "email", "with", "the", "contents", "of", "the", "provided", "text", "file" ]
f004ab3a35c5bff2f698131fef3b2a8ed5a7596d
https://github.com/cons3rt/pycons3rt/blob/f004ab3a35c5bff2f698131fef3b2a8ed5a7596d/pycons3rt/assetmailer.py#L89-L175
train
kajala/django-jutil
jutil/command.py
get_date_range_by_name
def get_date_range_by_name(name: str, today: datetime=None, tz=None) -> (datetime, datetime): """ :param name: yesterday, last_month :param today: Optional current datetime. Default is now(). :param tz: Optional timezone. Default is UTC. :return: datetime (begin, end) """ if today is None: ...
python
def get_date_range_by_name(name: str, today: datetime=None, tz=None) -> (datetime, datetime): """ :param name: yesterday, last_month :param today: Optional current datetime. Default is now(). :param tz: Optional timezone. Default is UTC. :return: datetime (begin, end) """ if today is None: ...
[ "def", "get_date_range_by_name", "(", "name", ":", "str", ",", "today", ":", "datetime", "=", "None", ",", "tz", "=", "None", ")", "->", "(", "datetime", ",", "datetime", ")", ":", "if", "today", "is", "None", ":", "today", "=", "datetime", ".", "utc...
:param name: yesterday, last_month :param today: Optional current datetime. Default is now(). :param tz: Optional timezone. Default is UTC. :return: datetime (begin, end)
[ ":", "param", "name", ":", "yesterday", "last_month", ":", "param", "today", ":", "Optional", "current", "datetime", ".", "Default", "is", "now", "()", ".", ":", "param", "tz", ":", "Optional", "timezone", ".", "Default", "is", "UTC", ".", ":", "return",...
2abd93ebad51042744eaeb1ee1074ed0eb55ad0c
https://github.com/kajala/django-jutil/blob/2abd93ebad51042744eaeb1ee1074ed0eb55ad0c/jutil/command.py#L50-L86
train
kajala/django-jutil
jutil/command.py
parse_date_range_arguments
def parse_date_range_arguments(options: dict, default_range='last_month') -> (datetime, datetime, list): """ :param options: :param default_range: Default datetime range to return if no other selected :return: begin, end, [(begin1,end1), (begin2,end2), ...] """ begin, end = get_date_range_by_nam...
python
def parse_date_range_arguments(options: dict, default_range='last_month') -> (datetime, datetime, list): """ :param options: :param default_range: Default datetime range to return if no other selected :return: begin, end, [(begin1,end1), (begin2,end2), ...] """ begin, end = get_date_range_by_nam...
[ "def", "parse_date_range_arguments", "(", "options", ":", "dict", ",", "default_range", "=", "'last_month'", ")", "->", "(", "datetime", ",", "datetime", ",", "list", ")", ":", "begin", ",", "end", "=", "get_date_range_by_name", "(", "default_range", ")", "for...
:param options: :param default_range: Default datetime range to return if no other selected :return: begin, end, [(begin1,end1), (begin2,end2), ...]
[ ":", "param", "options", ":", ":", "param", "default_range", ":", "Default", "datetime", "range", "to", "return", "if", "no", "other", "selected", ":", "return", ":", "begin", "end", "[", "(", "begin1", "end1", ")", "(", "begin2", "end2", ")", "...", "...
2abd93ebad51042744eaeb1ee1074ed0eb55ad0c
https://github.com/kajala/django-jutil/blob/2abd93ebad51042744eaeb1ee1074ed0eb55ad0c/jutil/command.py#L89-L123
train
Vital-Fernandez/dazer
bin/lib/Astro_Libraries/Abundances_Class.py
Chemical_Analysis_pyneb.load_elements
def load_elements(self): #Set atomic data #atomicData.setDataFile('he_i_rec_Pal12-Pal13.fits') atomicData.setDataFile('s_iii_coll_HRS12.dat') #Default: 's_iii_atom_PKW09.dat' 'S3: All energy and A values: Podobedova, Kelleher, and Wiese 2009, J. Phys. Chem. Ref. Data, Vol.' ...
python
def load_elements(self): #Set atomic data #atomicData.setDataFile('he_i_rec_Pal12-Pal13.fits') atomicData.setDataFile('s_iii_coll_HRS12.dat') #Default: 's_iii_atom_PKW09.dat' 'S3: All energy and A values: Podobedova, Kelleher, and Wiese 2009, J. Phys. Chem. Ref. Data, Vol.' ...
[ "def", "load_elements", "(", "self", ")", ":", "#Set atomic data ", "#atomicData.setDataFile('he_i_rec_Pal12-Pal13.fits')", "atomicData", ".", "setDataFile", "(", "'s_iii_coll_HRS12.dat'", ")", "#Default: 's_iii_atom_PKW09.dat' ", "'S3: collision strengths: Tayal & Gupta 1999, ApJ, 526...
S3: All energy and A values: Podobedova, Kelleher, and Wiese 2009, J. Phys. Chem. Ref. Data, Vol.
[ "S3", ":", "All", "energy", "and", "A", "values", ":", "Podobedova", "Kelleher", "and", "Wiese", "2009", "J", ".", "Phys", ".", "Chem", ".", "Ref", ".", "Data", "Vol", "." ]
3c9ae8ae6d40ea33f22cc20dc11365d6d6e65244
https://github.com/Vital-Fernandez/dazer/blob/3c9ae8ae6d40ea33f22cc20dc11365d6d6e65244/bin/lib/Astro_Libraries/Abundances_Class.py#L23-L87
train
cons3rt/pycons3rt
pycons3rt/pygit.py
git_clone
def git_clone(url, clone_dir, branch='master', username=None, password=None, max_retries=10, retry_sec=30, git_cmd=None): """Clones a git url :param url: (str) Git URL in https or ssh :param clone_dir: (str) Path to the desired destination dir :param branch: (str) branch to clone :par...
python
def git_clone(url, clone_dir, branch='master', username=None, password=None, max_retries=10, retry_sec=30, git_cmd=None): """Clones a git url :param url: (str) Git URL in https or ssh :param clone_dir: (str) Path to the desired destination dir :param branch: (str) branch to clone :par...
[ "def", "git_clone", "(", "url", ",", "clone_dir", ",", "branch", "=", "'master'", ",", "username", "=", "None", ",", "password", "=", "None", ",", "max_retries", "=", "10", ",", "retry_sec", "=", "30", ",", "git_cmd", "=", "None", ")", ":", "log", "=...
Clones a git url :param url: (str) Git URL in https or ssh :param clone_dir: (str) Path to the desired destination dir :param branch: (str) branch to clone :param username: (str) username for the git repo :param password: (str) password for the git repo :param max_retries: (int) the number of a...
[ "Clones", "a", "git", "url" ]
f004ab3a35c5bff2f698131fef3b2a8ed5a7596d
https://github.com/cons3rt/pycons3rt/blob/f004ab3a35c5bff2f698131fef3b2a8ed5a7596d/pycons3rt/pygit.py#L30-L134
train
cons3rt/pycons3rt
pycons3rt/pygit.py
encode_password
def encode_password(password): """Performs URL encoding for passwords :param password: (str) password to encode :return: (str) encoded password """ log = logging.getLogger(mod_logger + '.password_encoder') log.debug('Encoding password: {p}'.format(p=password)) encoded_password = '' for ...
python
def encode_password(password): """Performs URL encoding for passwords :param password: (str) password to encode :return: (str) encoded password """ log = logging.getLogger(mod_logger + '.password_encoder') log.debug('Encoding password: {p}'.format(p=password)) encoded_password = '' for ...
[ "def", "encode_password", "(", "password", ")", ":", "log", "=", "logging", ".", "getLogger", "(", "mod_logger", "+", "'.password_encoder'", ")", "log", ".", "debug", "(", "'Encoding password: {p}'", ".", "format", "(", "p", "=", "password", ")", ")", "encod...
Performs URL encoding for passwords :param password: (str) password to encode :return: (str) encoded password
[ "Performs", "URL", "encoding", "for", "passwords" ]
f004ab3a35c5bff2f698131fef3b2a8ed5a7596d
https://github.com/cons3rt/pycons3rt/blob/f004ab3a35c5bff2f698131fef3b2a8ed5a7596d/pycons3rt/pygit.py#L137-L149
train
cons3rt/pycons3rt
pycons3rt/pygit.py
encode_character
def encode_character(char): """Returns URL encoding for a single character :param char (str) Single character to encode :returns (str) URL-encoded character """ if char == '!': return '%21' elif char == '"': return '%22' elif char == '#': return '%23' elif char == '$': return '%24' ...
python
def encode_character(char): """Returns URL encoding for a single character :param char (str) Single character to encode :returns (str) URL-encoded character """ if char == '!': return '%21' elif char == '"': return '%22' elif char == '#': return '%23' elif char == '$': return '%24' ...
[ "def", "encode_character", "(", "char", ")", ":", "if", "char", "==", "'!'", ":", "return", "'%21'", "elif", "char", "==", "'\"'", ":", "return", "'%22'", "elif", "char", "==", "'#'", ":", "return", "'%23'", "elif", "char", "==", "'$'", ":", "return", ...
Returns URL encoding for a single character :param char (str) Single character to encode :returns (str) URL-encoded character
[ "Returns", "URL", "encoding", "for", "a", "single", "character" ]
f004ab3a35c5bff2f698131fef3b2a8ed5a7596d
https://github.com/cons3rt/pycons3rt/blob/f004ab3a35c5bff2f698131fef3b2a8ed5a7596d/pycons3rt/pygit.py#L152-L191
train
isogeo/isogeo-api-py-minsdk
isogeo_pysdk/samples/results_parser.py
search_tags_as_filters
def search_tags_as_filters(tags): """Get different tags as dicts ready to use as dropdown lists.""" # set dicts actions = {} contacts = {} formats = {} inspire = {} keywords = {} licenses = {} md_types = dict() owners = defaultdict(str) srs = {} unused = {} # 0/1 valu...
python
def search_tags_as_filters(tags): """Get different tags as dicts ready to use as dropdown lists.""" # set dicts actions = {} contacts = {} formats = {} inspire = {} keywords = {} licenses = {} md_types = dict() owners = defaultdict(str) srs = {} unused = {} # 0/1 valu...
[ "def", "search_tags_as_filters", "(", "tags", ")", ":", "# set dicts", "actions", "=", "{", "}", "contacts", "=", "{", "}", "formats", "=", "{", "}", "inspire", "=", "{", "}", "keywords", "=", "{", "}", "licenses", "=", "{", "}", "md_types", "=", "di...
Get different tags as dicts ready to use as dropdown lists.
[ "Get", "different", "tags", "as", "dicts", "ready", "to", "use", "as", "dropdown", "lists", "." ]
57a604be92c7767b26abd247012cc1a584b386a0
https://github.com/isogeo/isogeo-api-py-minsdk/blob/57a604be92c7767b26abd247012cc1a584b386a0/isogeo_pysdk/samples/results_parser.py#L28-L141
train
ktsstudio/tornkts
tornkts/modules/verification/verification_model.py
Verification.generate
def generate(self, verified, keygen): """ :param verified: телефон или email (verified_entity) :param keygen: функция генерации ключа :return: """ return Verification( verified_entity=verified, key=keygen(), verified=False )
python
def generate(self, verified, keygen): """ :param verified: телефон или email (verified_entity) :param keygen: функция генерации ключа :return: """ return Verification( verified_entity=verified, key=keygen(), verified=False )
[ "def", "generate", "(", "self", ",", "verified", ",", "keygen", ")", ":", "return", "Verification", "(", "verified_entity", "=", "verified", ",", "key", "=", "keygen", "(", ")", ",", "verified", "=", "False", ")" ]
:param verified: телефон или email (verified_entity) :param keygen: функция генерации ключа :return:
[ ":", "param", "verified", ":", "телефон", "или", "email", "(", "verified_entity", ")", ":", "param", "keygen", ":", "функция", "генерации", "ключа", ":", "return", ":" ]
db47e4550426282960a7e4486dcc4399c8d52e02
https://github.com/ktsstudio/tornkts/blob/db47e4550426282960a7e4486dcc4399c8d52e02/tornkts/modules/verification/verification_model.py#L12-L22
train
kajala/django-jutil
jutil/validators.py
iban_bank_info
def iban_bank_info(v: str) -> (str, str): """ Returns BIC code and bank name from IBAN number. :param v: IBAN account number :return: (BIC code, bank name) or ('', '') if not found / unsupported country """ v = iban_filter(v) if v[:2] == 'FI': return fi_iban_bank_info(v) else: ...
python
def iban_bank_info(v: str) -> (str, str): """ Returns BIC code and bank name from IBAN number. :param v: IBAN account number :return: (BIC code, bank name) or ('', '') if not found / unsupported country """ v = iban_filter(v) if v[:2] == 'FI': return fi_iban_bank_info(v) else: ...
[ "def", "iban_bank_info", "(", "v", ":", "str", ")", "->", "(", "str", ",", "str", ")", ":", "v", "=", "iban_filter", "(", "v", ")", "if", "v", "[", ":", "2", "]", "==", "'FI'", ":", "return", "fi_iban_bank_info", "(", "v", ")", "else", ":", "re...
Returns BIC code and bank name from IBAN number. :param v: IBAN account number :return: (BIC code, bank name) or ('', '') if not found / unsupported country
[ "Returns", "BIC", "code", "and", "bank", "name", "from", "IBAN", "number", ".", ":", "param", "v", ":", "IBAN", "account", "number", ":", "return", ":", "(", "BIC", "code", "bank", "name", ")", "or", "(", ")", "if", "not", "found", "/", "unsupported"...
2abd93ebad51042744eaeb1ee1074ed0eb55ad0c
https://github.com/kajala/django-jutil/blob/2abd93ebad51042744eaeb1ee1074ed0eb55ad0c/jutil/validators.py#L116-L126
train
kajala/django-jutil
jutil/validators.py
fi_payment_reference_number
def fi_payment_reference_number(num: str): """ Appends Finland reference number checksum to existing number. :param num: At least 3 digits :return: Number plus checksum """ assert isinstance(num, str) num = STRIP_WHITESPACE.sub('', num) num = re.sub(r'^0+', '', num) assert len(num) >...
python
def fi_payment_reference_number(num: str): """ Appends Finland reference number checksum to existing number. :param num: At least 3 digits :return: Number plus checksum """ assert isinstance(num, str) num = STRIP_WHITESPACE.sub('', num) num = re.sub(r'^0+', '', num) assert len(num) >...
[ "def", "fi_payment_reference_number", "(", "num", ":", "str", ")", ":", "assert", "isinstance", "(", "num", ",", "str", ")", "num", "=", "STRIP_WHITESPACE", ".", "sub", "(", "''", ",", "num", ")", "num", "=", "re", ".", "sub", "(", "r'^0+'", ",", "''...
Appends Finland reference number checksum to existing number. :param num: At least 3 digits :return: Number plus checksum
[ "Appends", "Finland", "reference", "number", "checksum", "to", "existing", "number", ".", ":", "param", "num", ":", "At", "least", "3", "digits", ":", "return", ":", "Number", "plus", "checksum" ]
2abd93ebad51042744eaeb1ee1074ed0eb55ad0c
https://github.com/kajala/django-jutil/blob/2abd93ebad51042744eaeb1ee1074ed0eb55ad0c/jutil/validators.py#L154-L169
train
kajala/django-jutil
jutil/validators.py
iso_payment_reference_validator
def iso_payment_reference_validator(v: str): """ Validates ISO reference number checksum. :param v: Reference number """ num = '' v = STRIP_WHITESPACE.sub('', v) for ch in v[4:] + v[0:4]: x = ord(ch) if ord('0') <= x <= ord('9'): num += ch else: ...
python
def iso_payment_reference_validator(v: str): """ Validates ISO reference number checksum. :param v: Reference number """ num = '' v = STRIP_WHITESPACE.sub('', v) for ch in v[4:] + v[0:4]: x = ord(ch) if ord('0') <= x <= ord('9'): num += ch else: ...
[ "def", "iso_payment_reference_validator", "(", "v", ":", "str", ")", ":", "num", "=", "''", "v", "=", "STRIP_WHITESPACE", ".", "sub", "(", "''", ",", "v", ")", "for", "ch", "in", "v", "[", "4", ":", "]", "+", "v", "[", "0", ":", "4", "]", ":", ...
Validates ISO reference number checksum. :param v: Reference number
[ "Validates", "ISO", "reference", "number", "checksum", ".", ":", "param", "v", ":", "Reference", "number" ]
2abd93ebad51042744eaeb1ee1074ed0eb55ad0c
https://github.com/kajala/django-jutil/blob/2abd93ebad51042744eaeb1ee1074ed0eb55ad0c/jutil/validators.py#L178-L196
train
kajala/django-jutil
jutil/validators.py
fi_iban_bank_info
def fi_iban_bank_info(v: str) -> (str, str): """ Returns BIC code and bank name from FI IBAN number. :param v: IBAN account number :return: (BIC code, bank name) or ('', '') if not found """ from jutil.bank_const_fi import FI_BIC_BY_ACCOUNT_NUMBER, FI_BANK_NAME_BY_BIC v = iban_filter(v) ...
python
def fi_iban_bank_info(v: str) -> (str, str): """ Returns BIC code and bank name from FI IBAN number. :param v: IBAN account number :return: (BIC code, bank name) or ('', '') if not found """ from jutil.bank_const_fi import FI_BIC_BY_ACCOUNT_NUMBER, FI_BANK_NAME_BY_BIC v = iban_filter(v) ...
[ "def", "fi_iban_bank_info", "(", "v", ":", "str", ")", "->", "(", "str", ",", "str", ")", ":", "from", "jutil", ".", "bank_const_fi", "import", "FI_BIC_BY_ACCOUNT_NUMBER", ",", "FI_BANK_NAME_BY_BIC", "v", "=", "iban_filter", "(", "v", ")", "bic", "=", "FI_...
Returns BIC code and bank name from FI IBAN number. :param v: IBAN account number :return: (BIC code, bank name) or ('', '') if not found
[ "Returns", "BIC", "code", "and", "bank", "name", "from", "FI", "IBAN", "number", ".", ":", "param", "v", ":", "IBAN", "account", "number", ":", "return", ":", "(", "BIC", "code", "bank", "name", ")", "or", "(", ")", "if", "not", "found" ]
2abd93ebad51042744eaeb1ee1074ed0eb55ad0c
https://github.com/kajala/django-jutil/blob/2abd93ebad51042744eaeb1ee1074ed0eb55ad0c/jutil/validators.py#L203-L212
train
kajala/django-jutil
jutil/validators.py
se_clearing_code_bank_info
def se_clearing_code_bank_info(clearing: str) -> (str, int): """ Returns Sweden bank info by clearning code. :param clearing: 4-digit clearing code :return: (Bank name, account digit count) or ('', None) if not found """ from jutil.bank_const_se import SE_BANK_CLEARING_LIST for name, begin, ...
python
def se_clearing_code_bank_info(clearing: str) -> (str, int): """ Returns Sweden bank info by clearning code. :param clearing: 4-digit clearing code :return: (Bank name, account digit count) or ('', None) if not found """ from jutil.bank_const_se import SE_BANK_CLEARING_LIST for name, begin, ...
[ "def", "se_clearing_code_bank_info", "(", "clearing", ":", "str", ")", "->", "(", "str", ",", "int", ")", ":", "from", "jutil", ".", "bank_const_se", "import", "SE_BANK_CLEARING_LIST", "for", "name", ",", "begin", ",", "end", ",", "acc_digits", "in", "SE_BAN...
Returns Sweden bank info by clearning code. :param clearing: 4-digit clearing code :return: (Bank name, account digit count) or ('', None) if not found
[ "Returns", "Sweden", "bank", "info", "by", "clearning", "code", ".", ":", "param", "clearing", ":", "4", "-", "digit", "clearing", "code", ":", "return", ":", "(", "Bank", "name", "account", "digit", "count", ")", "or", "(", "None", ")", "if", "not", ...
2abd93ebad51042744eaeb1ee1074ed0eb55ad0c
https://github.com/kajala/django-jutil/blob/2abd93ebad51042744eaeb1ee1074ed0eb55ad0c/jutil/validators.py#L323-L333
train
Vital-Fernandez/dazer
bin/lib/Astro_Libraries/spectrum_fitting/plot_tools.py
_histplot_bins
def _histplot_bins(column, bins=100): """Helper to get bins for histplot.""" col_min = np.min(column) col_max = np.max(column) return range(col_min, col_max + 2, max((col_max - col_min) // bins, 1))
python
def _histplot_bins(column, bins=100): """Helper to get bins for histplot.""" col_min = np.min(column) col_max = np.max(column) return range(col_min, col_max + 2, max((col_max - col_min) // bins, 1))
[ "def", "_histplot_bins", "(", "column", ",", "bins", "=", "100", ")", ":", "col_min", "=", "np", ".", "min", "(", "column", ")", "col_max", "=", "np", ".", "max", "(", "column", ")", "return", "range", "(", "col_min", ",", "col_max", "+", "2", ",",...
Helper to get bins for histplot.
[ "Helper", "to", "get", "bins", "for", "histplot", "." ]
3c9ae8ae6d40ea33f22cc20dc11365d6d6e65244
https://github.com/Vital-Fernandez/dazer/blob/3c9ae8ae6d40ea33f22cc20dc11365d6d6e65244/bin/lib/Astro_Libraries/spectrum_fitting/plot_tools.py#L27-L31
train
jaredLunde/vital-tools
vital/tools/http.py
http_date
def http_date(value): """ Formats the @value in required HTTP style @value: :class:datetime.datetime, #int, #float, #str time-like object -> #str HTTP-style formatted date (c)2014, Marcel Hellkamp """ if isinstance(value, datetime.datetime): value = value.utctimetuple() ...
python
def http_date(value): """ Formats the @value in required HTTP style @value: :class:datetime.datetime, #int, #float, #str time-like object -> #str HTTP-style formatted date (c)2014, Marcel Hellkamp """ if isinstance(value, datetime.datetime): value = value.utctimetuple() ...
[ "def", "http_date", "(", "value", ")", ":", "if", "isinstance", "(", "value", ",", "datetime", ".", "datetime", ")", ":", "value", "=", "value", ".", "utctimetuple", "(", ")", "elif", "isinstance", "(", "value", ",", "(", "int", ",", "float", ")", ")...
Formats the @value in required HTTP style @value: :class:datetime.datetime, #int, #float, #str time-like object -> #str HTTP-style formatted date (c)2014, Marcel Hellkamp
[ "Formats", "the", "@value", "in", "required", "HTTP", "style" ]
ea924c9bbb6ec22aa66f8095f018b1ee0099ac04
https://github.com/jaredLunde/vital-tools/blob/ea924c9bbb6ec22aa66f8095f018b1ee0099ac04/vital/tools/http.py#L25-L40
train
jaredLunde/vital-tools
vital/tools/http.py
parse_auth
def parse_auth(header): """ Parse rfc2617 HTTP authentication header string (basic) and return (user,pass) tuple or None (c)2014, Marcel Hellkamp """ try: method, data = header.split(None, 1) if method.lower() == 'basic': data = base64.b64decode(uniorbytes(data, b...
python
def parse_auth(header): """ Parse rfc2617 HTTP authentication header string (basic) and return (user,pass) tuple or None (c)2014, Marcel Hellkamp """ try: method, data = header.split(None, 1) if method.lower() == 'basic': data = base64.b64decode(uniorbytes(data, b...
[ "def", "parse_auth", "(", "header", ")", ":", "try", ":", "method", ",", "data", "=", "header", ".", "split", "(", "None", ",", "1", ")", "if", "method", ".", "lower", "(", ")", "==", "'basic'", ":", "data", "=", "base64", ".", "b64decode", "(", ...
Parse rfc2617 HTTP authentication header string (basic) and return (user,pass) tuple or None (c)2014, Marcel Hellkamp
[ "Parse", "rfc2617", "HTTP", "authentication", "header", "string", "(", "basic", ")", "and", "return", "(", "user", "pass", ")", "tuple", "or", "None", "(", "c", ")", "2014", "Marcel", "Hellkamp" ]
ea924c9bbb6ec22aa66f8095f018b1ee0099ac04
https://github.com/jaredLunde/vital-tools/blob/ea924c9bbb6ec22aa66f8095f018b1ee0099ac04/vital/tools/http.py#L54-L66
train
azaghal/django-pydenticon
django_pydenticon/views.py
image
def image(request, data): """ Generates identicon image based on passed data. Arguments: data - Data which should be used for generating an identicon. This data will be used in order to create a digest which is used for generating the identicon. If the data passed is a hex digest already...
python
def image(request, data): """ Generates identicon image based on passed data. Arguments: data - Data which should be used for generating an identicon. This data will be used in order to create a digest which is used for generating the identicon. If the data passed is a hex digest already...
[ "def", "image", "(", "request", ",", "data", ")", ":", "# Get image width, height, padding, and format from GET parameters, or", "# fall-back to default values from settings.", "try", ":", "width", "=", "int", "(", "request", ".", "GET", ".", "get", "(", "\"w\"", ",", ...
Generates identicon image based on passed data. Arguments: data - Data which should be used for generating an identicon. This data will be used in order to create a digest which is used for generating the identicon. If the data passed is a hex digest already, the digest will be used as-is....
[ "Generates", "identicon", "image", "based", "on", "passed", "data", "." ]
dd21a87693505614eb5ce1da6ff1b6146d341b2c
https://github.com/azaghal/django-pydenticon/blob/dd21a87693505614eb5ce1da6ff1b6146d341b2c/django_pydenticon/views.py#L14-L85
train
novopl/peltak
src/peltak/extra/gitflow/commands/hotfix.py
rename
def rename(name): # type: (str) -> None """ Give the currently developed hotfix a new name. """ from peltak.extra.gitflow import logic if name is None: name = click.prompt('Hotfix name') logic.hotfix.rename(name)
python
def rename(name): # type: (str) -> None """ Give the currently developed hotfix a new name. """ from peltak.extra.gitflow import logic if name is None: name = click.prompt('Hotfix name') logic.hotfix.rename(name)
[ "def", "rename", "(", "name", ")", ":", "# type: (str) -> None", "from", "peltak", ".", "extra", ".", "gitflow", "import", "logic", "if", "name", "is", "None", ":", "name", "=", "click", ".", "prompt", "(", "'Hotfix name'", ")", "logic", ".", "hotfix", "...
Give the currently developed hotfix a new name.
[ "Give", "the", "currently", "developed", "hotfix", "a", "new", "name", "." ]
b627acc019e3665875fe76cdca0a14773b69beaa
https://github.com/novopl/peltak/blob/b627acc019e3665875fe76cdca0a14773b69beaa/src/peltak/extra/gitflow/commands/hotfix.py#L53-L61
train
jaredLunde/vital-tools
vital/cache/decorators.py
local_lru
def local_lru(obj): """ Property that maps to a key in a local dict-like attribute. self._cache must be an OrderedDict self._cache_size must be defined as LRU size .. class Foo(object): def __init__(self, cache_size=5000): self._cache = OrderedDict() ...
python
def local_lru(obj): """ Property that maps to a key in a local dict-like attribute. self._cache must be an OrderedDict self._cache_size must be defined as LRU size .. class Foo(object): def __init__(self, cache_size=5000): self._cache = OrderedDict() ...
[ "def", "local_lru", "(", "obj", ")", ":", "@", "wraps", "(", "obj", ")", "def", "memoizer", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "instance", "=", "args", "[", "0", "]", "lru_size", "=", "instance", ".", "_cache_size", "if", "lru_siz...
Property that maps to a key in a local dict-like attribute. self._cache must be an OrderedDict self._cache_size must be defined as LRU size .. class Foo(object): def __init__(self, cache_size=5000): self._cache = OrderedDict() self._cache_size...
[ "Property", "that", "maps", "to", "a", "key", "in", "a", "local", "dict", "-", "like", "attribute", ".", "self", ".", "_cache", "must", "be", "an", "OrderedDict", "self", ".", "_cache_size", "must", "be", "defined", "as", "LRU", "size", "..", "class", ...
ea924c9bbb6ec22aa66f8095f018b1ee0099ac04
https://github.com/jaredLunde/vital-tools/blob/ea924c9bbb6ec22aa66f8095f018b1ee0099ac04/vital/cache/decorators.py#L42-L74
train
jaredLunde/vital-tools
vital/cache/decorators.py
typed_lru
def typed_lru(maxsize, types=None): """ :func:functools.lru_cache wrapper which allows you to prevent object types outside of @types from being cached. The main use case for this is preventing unhashable type errors when you still want to cache some results. .. from vita...
python
def typed_lru(maxsize, types=None): """ :func:functools.lru_cache wrapper which allows you to prevent object types outside of @types from being cached. The main use case for this is preventing unhashable type errors when you still want to cache some results. .. from vita...
[ "def", "typed_lru", "(", "maxsize", ",", "types", "=", "None", ")", ":", "types", "=", "types", "or", "collections", ".", "Hashable", "def", "lru", "(", "obj", ")", ":", "@", "lru_cache", "(", "maxsize", ")", "def", "_lru_cache", "(", "*", "args", ",...
:func:functools.lru_cache wrapper which allows you to prevent object types outside of @types from being cached. The main use case for this is preventing unhashable type errors when you still want to cache some results. .. from vital.cache import typed_lru @typed...
[ ":", "func", ":", "functools", ".", "lru_cache", "wrapper", "which", "allows", "you", "to", "prevent", "object", "types", "outside", "of", "@types", "from", "being", "cached", "." ]
ea924c9bbb6ec22aa66f8095f018b1ee0099ac04
https://github.com/jaredLunde/vital-tools/blob/ea924c9bbb6ec22aa66f8095f018b1ee0099ac04/vital/cache/decorators.py#L77-L124
train
jaredLunde/vital-tools
vital/cache/decorators.py
local_expiring_lru
def local_expiring_lru(obj): """ Property that maps to a key in a local dict-like attribute. self._cache must be an OrderedDict self._cache_size must be defined as LRU size self._cache_ttl is the expiration time in seconds .. class Foo(object): def __init__(self,...
python
def local_expiring_lru(obj): """ Property that maps to a key in a local dict-like attribute. self._cache must be an OrderedDict self._cache_size must be defined as LRU size self._cache_ttl is the expiration time in seconds .. class Foo(object): def __init__(self,...
[ "def", "local_expiring_lru", "(", "obj", ")", ":", "@", "wraps", "(", "obj", ")", "def", "memoizer", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "instance", "=", "args", "[", "0", "]", "lru_size", "=", "instance", ".", "_cache_size", "cache_...
Property that maps to a key in a local dict-like attribute. self._cache must be an OrderedDict self._cache_size must be defined as LRU size self._cache_ttl is the expiration time in seconds .. class Foo(object): def __init__(self, cache_size=5000, cache_ttl=600): ...
[ "Property", "that", "maps", "to", "a", "key", "in", "a", "local", "dict", "-", "like", "attribute", ".", "self", ".", "_cache", "must", "be", "an", "OrderedDict", "self", ".", "_cache_size", "must", "be", "defined", "as", "LRU", "size", "self", ".", "_...
ea924c9bbb6ec22aa66f8095f018b1ee0099ac04
https://github.com/jaredLunde/vital-tools/blob/ea924c9bbb6ec22aa66f8095f018b1ee0099ac04/vital/cache/decorators.py#L127-L172
train
novopl/peltak
src/peltak/core/context.py
GlobalContext.get
def get(self, name, *default): # type: (str, Any) -> Any """ Get context value with the given name and optional default. Args: name (str): The name of the context value. *default (Any): If given and the key doesn't not exist, this will be ...
python
def get(self, name, *default): # type: (str, Any) -> Any """ Get context value with the given name and optional default. Args: name (str): The name of the context value. *default (Any): If given and the key doesn't not exist, this will be ...
[ "def", "get", "(", "self", ",", "name", ",", "*", "default", ")", ":", "# type: (str, Any) -> Any", "curr", "=", "self", ".", "values", "for", "part", "in", "name", ".", "split", "(", "'.'", ")", ":", "if", "part", "in", "curr", ":", "curr", "=", "...
Get context value with the given name and optional default. Args: name (str): The name of the context value. *default (Any): If given and the key doesn't not exist, this will be returned instead. If it's not given and the context value doe...
[ "Get", "context", "value", "with", "the", "given", "name", "and", "optional", "default", "." ]
b627acc019e3665875fe76cdca0a14773b69beaa
https://github.com/novopl/peltak/blob/b627acc019e3665875fe76cdca0a14773b69beaa/src/peltak/core/context.py#L57-L90
train
novopl/peltak
src/peltak/core/context.py
GlobalContext.set
def set(self, name, value): """ Set context value. Args: name (str): The name of the context value to change. value (Any): The new value for the selected context value """ curr = self.values parts = name.split('.') ...
python
def set(self, name, value): """ Set context value. Args: name (str): The name of the context value to change. value (Any): The new value for the selected context value """ curr = self.values parts = name.split('.') ...
[ "def", "set", "(", "self", ",", "name", ",", "value", ")", ":", "curr", "=", "self", ".", "values", "parts", "=", "name", ".", "split", "(", "'.'", ")", "for", "i", ",", "part", "in", "enumerate", "(", "parts", "[", ":", "-", "1", "]", ")", "...
Set context value. Args: name (str): The name of the context value to change. value (Any): The new value for the selected context value
[ "Set", "context", "value", "." ]
b627acc019e3665875fe76cdca0a14773b69beaa
https://github.com/novopl/peltak/blob/b627acc019e3665875fe76cdca0a14773b69beaa/src/peltak/core/context.py#L92-L113
train
cons3rt/pycons3rt
pycons3rt/pyjavakeys.py
alias_exists
def alias_exists(alias, keystore_path=None, keystore_password='changeit'): """Checks if an alias already exists in a keystore :param alias: :param keystore_path: :param keystore_password: :return: (bool) True when the alias already exists in the keystore :raises: OSError """ log = loggi...
python
def alias_exists(alias, keystore_path=None, keystore_password='changeit'): """Checks if an alias already exists in a keystore :param alias: :param keystore_path: :param keystore_password: :return: (bool) True when the alias already exists in the keystore :raises: OSError """ log = loggi...
[ "def", "alias_exists", "(", "alias", ",", "keystore_path", "=", "None", ",", "keystore_password", "=", "'changeit'", ")", ":", "log", "=", "logging", ".", "getLogger", "(", "mod_logger", "+", "'.alias_exists'", ")", "if", "not", "isinstance", "(", "alias", "...
Checks if an alias already exists in a keystore :param alias: :param keystore_path: :param keystore_password: :return: (bool) True when the alias already exists in the keystore :raises: OSError
[ "Checks", "if", "an", "alias", "already", "exists", "in", "a", "keystore" ]
f004ab3a35c5bff2f698131fef3b2a8ed5a7596d
https://github.com/cons3rt/pycons3rt/blob/f004ab3a35c5bff2f698131fef3b2a8ed5a7596d/pycons3rt/pyjavakeys.py#L34-L103
train
MarcAureleCoste/sqla-filters
src/sqla_filters/nodes/base/base.py
TreeNode.filter
def filter(self, query: Query, entity: type) -> Tuple[Query, Any]: """Define the filter function that every node must to implement. :param query: The sqlalchemy query. :type query: Query :param entity: The entity model. :type entity: type :return: The filtered query. ...
python
def filter(self, query: Query, entity: type) -> Tuple[Query, Any]: """Define the filter function that every node must to implement. :param query: The sqlalchemy query. :type query: Query :param entity: The entity model. :type entity: type :return: The filtered query. ...
[ "def", "filter", "(", "self", ",", "query", ":", "Query", ",", "entity", ":", "type", ")", "->", "Tuple", "[", "Query", ",", "Any", "]", ":", "raise", "NotImplementedError", "(", "'You must implement this.'", ")" ]
Define the filter function that every node must to implement. :param query: The sqlalchemy query. :type query: Query :param entity: The entity model. :type entity: type :return: The filtered query. :rtype: Tuple[Query, Any]
[ "Define", "the", "filter", "function", "that", "every", "node", "must", "to", "implement", "." ]
a9596f660a11d275bf0e831ecd9e502b0af2a087
https://github.com/MarcAureleCoste/sqla-filters/blob/a9596f660a11d275bf0e831ecd9e502b0af2a087/src/sqla_filters/nodes/base/base.py#L50-L62
train
MarcAureleCoste/sqla-filters
src/sqla_filters/nodes/base/base.py
BaseOperationalNode._extract_relations
def _extract_relations(self, attribute: str) -> Tuple[List[str], str]: """Split and return the list of relation(s) and the attribute. :param attribute: :type attribute: str :return: A tuple where the first element is the list of related entities and the second is the attrib...
python
def _extract_relations(self, attribute: str) -> Tuple[List[str], str]: """Split and return the list of relation(s) and the attribute. :param attribute: :type attribute: str :return: A tuple where the first element is the list of related entities and the second is the attrib...
[ "def", "_extract_relations", "(", "self", ",", "attribute", ":", "str", ")", "->", "Tuple", "[", "List", "[", "str", "]", ",", "str", "]", ":", "splitted", "=", "attribute", ".", "split", "(", "self", ".", "_attr_sep", ")", "return", "(", "splitted", ...
Split and return the list of relation(s) and the attribute. :param attribute: :type attribute: str :return: A tuple where the first element is the list of related entities and the second is the attribute. :rtype: Tuple[List[str], str]
[ "Split", "and", "return", "the", "list", "of", "relation", "(", "s", ")", "and", "the", "attribute", "." ]
a9596f660a11d275bf0e831ecd9e502b0af2a087
https://github.com/MarcAureleCoste/sqla-filters/blob/a9596f660a11d275bf0e831ecd9e502b0af2a087/src/sqla_filters/nodes/base/base.py#L104-L115
train
MarcAureleCoste/sqla-filters
src/sqla_filters/nodes/base/base.py
BaseOperationalNode._get_relation
def _get_relation(self, related_model: type, relations: List[str]) -> Tuple[Optional[List[type]], Optional[type]]: """Transform the list of relation to list of class. :param related_mode: The model of the query. :type related_mode: type :param relations: The relation list get from the ...
python
def _get_relation(self, related_model: type, relations: List[str]) -> Tuple[Optional[List[type]], Optional[type]]: """Transform the list of relation to list of class. :param related_mode: The model of the query. :type related_mode: type :param relations: The relation list get from the ...
[ "def", "_get_relation", "(", "self", ",", "related_model", ":", "type", ",", "relations", ":", "List", "[", "str", "]", ")", "->", "Tuple", "[", "Optional", "[", "List", "[", "type", "]", "]", ",", "Optional", "[", "type", "]", "]", ":", "relations_l...
Transform the list of relation to list of class. :param related_mode: The model of the query. :type related_mode: type :param relations: The relation list get from the `_extract_relations`. :type relations: List[str] :return: Tuple with the list of relations (class) and the se...
[ "Transform", "the", "list", "of", "relation", "to", "list", "of", "class", "." ]
a9596f660a11d275bf0e831ecd9e502b0af2a087
https://github.com/MarcAureleCoste/sqla-filters/blob/a9596f660a11d275bf0e831ecd9e502b0af2a087/src/sqla_filters/nodes/base/base.py#L117-L137
train
MarcAureleCoste/sqla-filters
src/sqla_filters/nodes/base/base.py
BaseOperationalNode._join_tables
def _join_tables(self, query: Query, join_models: Optional[List[type]]) -> Query: """Method to make the join when relation is found. :param query: The sqlalchemy query. :type query: Query :param join_models: The list of joined models get from the method `_get_relation`. ...
python
def _join_tables(self, query: Query, join_models: Optional[List[type]]) -> Query: """Method to make the join when relation is found. :param query: The sqlalchemy query. :type query: Query :param join_models: The list of joined models get from the method `_get_relation`. ...
[ "def", "_join_tables", "(", "self", ",", "query", ":", "Query", ",", "join_models", ":", "Optional", "[", "List", "[", "type", "]", "]", ")", "->", "Query", ":", "joined_query", "=", "query", "# Create the list of already joined entities", "joined_tables", "=", ...
Method to make the join when relation is found. :param query: The sqlalchemy query. :type query: Query :param join_models: The list of joined models get from the method `_get_relation`. :type join_models: Optional[List[type]] :return: The new Query with the joined ...
[ "Method", "to", "make", "the", "join", "when", "relation", "is", "found", "." ]
a9596f660a11d275bf0e831ecd9e502b0af2a087
https://github.com/MarcAureleCoste/sqla-filters/blob/a9596f660a11d275bf0e831ecd9e502b0af2a087/src/sqla_filters/nodes/base/base.py#L139-L160
train
MarcAureleCoste/sqla-filters
src/sqla_filters/nodes/base/base.py
BaseLogicalNode.filter
def filter(self, query: Query, entity: type) -> Tuple[Query, Any]: """Apply the `_method` to all childs of the node. :param query: The sqlachemy query. :type query: Query :param entity: The entity model of the query. :type entity: type :return: A tuple with in ...
python
def filter(self, query: Query, entity: type) -> Tuple[Query, Any]: """Apply the `_method` to all childs of the node. :param query: The sqlachemy query. :type query: Query :param entity: The entity model of the query. :type entity: type :return: A tuple with in ...
[ "def", "filter", "(", "self", ",", "query", ":", "Query", ",", "entity", ":", "type", ")", "->", "Tuple", "[", "Query", ",", "Any", "]", ":", "new_query", "=", "query", "c_filter_list", "=", "[", "]", "for", "child", "in", "self", ".", "_childs", "...
Apply the `_method` to all childs of the node. :param query: The sqlachemy query. :type query: Query :param entity: The entity model of the query. :type entity: type :return: A tuple with in first place the updated query and in second place the list of filt...
[ "Apply", "the", "_method", "to", "all", "childs", "of", "the", "node", ".", ":", "param", "query", ":", "The", "sqlachemy", "query", ".", ":", "type", "query", ":", "Query" ]
a9596f660a11d275bf0e831ecd9e502b0af2a087
https://github.com/MarcAureleCoste/sqla-filters/blob/a9596f660a11d275bf0e831ecd9e502b0af2a087/src/sqla_filters/nodes/base/base.py#L207-L228
train
kajala/django-jutil
jutil/sms.py
send_sms
def send_sms(phone: str, message: str, sender: str='', **kw): """ Sends SMS via Kajala Group SMS API. Contact info@kajala.com for access. :param phone: Phone number :param message: Message to be esnd :param sender: Sender (max 11 characters) :param kw: Variable key-value pairs to be sent to SMS ...
python
def send_sms(phone: str, message: str, sender: str='', **kw): """ Sends SMS via Kajala Group SMS API. Contact info@kajala.com for access. :param phone: Phone number :param message: Message to be esnd :param sender: Sender (max 11 characters) :param kw: Variable key-value pairs to be sent to SMS ...
[ "def", "send_sms", "(", "phone", ":", "str", ",", "message", ":", "str", ",", "sender", ":", "str", "=", "''", ",", "*", "*", "kw", ")", ":", "if", "not", "hasattr", "(", "settings", ",", "'SMS_TOKEN'", ")", ":", "raise", "Exception", "(", "'Invali...
Sends SMS via Kajala Group SMS API. Contact info@kajala.com for access. :param phone: Phone number :param message: Message to be esnd :param sender: Sender (max 11 characters) :param kw: Variable key-value pairs to be sent to SMS API :return: Response from requests.post
[ "Sends", "SMS", "via", "Kajala", "Group", "SMS", "API", ".", "Contact", "info" ]
2abd93ebad51042744eaeb1ee1074ed0eb55ad0c
https://github.com/kajala/django-jutil/blob/2abd93ebad51042744eaeb1ee1074ed0eb55ad0c/jutil/sms.py#L6-L32
train
isogeo/isogeo-api-py-minsdk
isogeo_pysdk/samples/dev_perfs_sync_async.py
_meta_get_resource_sync
def _meta_get_resource_sync(md_uuid): """Just a meta func to get execution time""" isogeo.resource(id_resource=md_uuid) elapsed = default_timer() - START_TIME time_completed_at = "{:5.2f}s".format(elapsed) print("{0:<30} {1:>20}".format(md_uuid, time_completed_at)) return
python
def _meta_get_resource_sync(md_uuid): """Just a meta func to get execution time""" isogeo.resource(id_resource=md_uuid) elapsed = default_timer() - START_TIME time_completed_at = "{:5.2f}s".format(elapsed) print("{0:<30} {1:>20}".format(md_uuid, time_completed_at)) return
[ "def", "_meta_get_resource_sync", "(", "md_uuid", ")", ":", "isogeo", ".", "resource", "(", "id_resource", "=", "md_uuid", ")", "elapsed", "=", "default_timer", "(", ")", "-", "START_TIME", "time_completed_at", "=", "\"{:5.2f}s\"", ".", "format", "(", "elapsed",...
Just a meta func to get execution time
[ "Just", "a", "meta", "func", "to", "get", "execution", "time" ]
57a604be92c7767b26abd247012cc1a584b386a0
https://github.com/isogeo/isogeo-api-py-minsdk/blob/57a604be92c7767b26abd247012cc1a584b386a0/isogeo_pysdk/samples/dev_perfs_sync_async.py#L35-L43
train
Varkal/chuda
chuda/commands.py
Command.setup
def setup(self, app): ''' Setup properties from parent app on the command ''' self.logger = app.logger self.shell.logger = self.logger if not self.command_name: raise EmptyCommandNameException() self.app = app self.arguments_declaration = sel...
python
def setup(self, app): ''' Setup properties from parent app on the command ''' self.logger = app.logger self.shell.logger = self.logger if not self.command_name: raise EmptyCommandNameException() self.app = app self.arguments_declaration = sel...
[ "def", "setup", "(", "self", ",", "app", ")", ":", "self", ".", "logger", "=", "app", ".", "logger", "self", ".", "shell", ".", "logger", "=", "self", ".", "logger", "if", "not", "self", ".", "command_name", ":", "raise", "EmptyCommandNameException", "...
Setup properties from parent app on the command
[ "Setup", "properties", "from", "parent", "app", "on", "the", "command" ]
0d93b716dede35231c21be97bcc19a656655983f
https://github.com/Varkal/chuda/blob/0d93b716dede35231c21be97bcc19a656655983f/chuda/commands.py#L92-L109
train
kajala/django-jutil
jutil/middleware.py
LogExceptionMiddleware.process_exception
def process_exception(self, request, e): """ Logs exception error message and sends email to ADMINS if hostname is not testserver and DEBUG=False. :param request: HttpRequest :param e: Exception """ from jutil.email import send_email assert isinstance(request, Ht...
python
def process_exception(self, request, e): """ Logs exception error message and sends email to ADMINS if hostname is not testserver and DEBUG=False. :param request: HttpRequest :param e: Exception """ from jutil.email import send_email assert isinstance(request, Ht...
[ "def", "process_exception", "(", "self", ",", "request", ",", "e", ")", ":", "from", "jutil", ".", "email", "import", "send_email", "assert", "isinstance", "(", "request", ",", "HttpRequest", ")", "full_path", "=", "request", ".", "get_full_path", "(", ")", ...
Logs exception error message and sends email to ADMINS if hostname is not testserver and DEBUG=False. :param request: HttpRequest :param e: Exception
[ "Logs", "exception", "error", "message", "and", "sends", "email", "to", "ADMINS", "if", "hostname", "is", "not", "testserver", "and", "DEBUG", "=", "False", ".", ":", "param", "request", ":", "HttpRequest", ":", "param", "e", ":", "Exception" ]
2abd93ebad51042744eaeb1ee1074ed0eb55ad0c
https://github.com/kajala/django-jutil/blob/2abd93ebad51042744eaeb1ee1074ed0eb55ad0c/jutil/middleware.py#L47-L63
train
cfobel/pygtk3-helpers
pygtk3_helpers/delegates.py
get_first_builder_window
def get_first_builder_window(builder): """Get the first toplevel widget in a Gtk.Builder hierarchy. This is mostly used for guessing purposes, and an explicit naming is always going to be a better situation. """ for obj in builder.get_objects(): if isinstance(obj, Gtk.Window): #...
python
def get_first_builder_window(builder): """Get the first toplevel widget in a Gtk.Builder hierarchy. This is mostly used for guessing purposes, and an explicit naming is always going to be a better situation. """ for obj in builder.get_objects(): if isinstance(obj, Gtk.Window): #...
[ "def", "get_first_builder_window", "(", "builder", ")", ":", "for", "obj", "in", "builder", ".", "get_objects", "(", ")", ":", "if", "isinstance", "(", "obj", ",", "Gtk", ".", "Window", ")", ":", "# first window", "return", "obj" ]
Get the first toplevel widget in a Gtk.Builder hierarchy. This is mostly used for guessing purposes, and an explicit naming is always going to be a better situation.
[ "Get", "the", "first", "toplevel", "widget", "in", "a", "Gtk", ".", "Builder", "hierarchy", "." ]
ae793cb34a5c1bbe40cc83bb8a6084f0eeed2519
https://github.com/cfobel/pygtk3-helpers/blob/ae793cb34a5c1bbe40cc83bb8a6084f0eeed2519/pygtk3_helpers/delegates.py#L20-L29
train
cfobel/pygtk3-helpers
pygtk3_helpers/delegates.py
BaseDelegate.add_slave
def add_slave(self, slave, container_name="widget"): """Add a slave delegate """ cont = getattr(self, container_name, None) if cont is None: raise AttributeError( 'Container name must be a member of the delegate') cont.add(slave.widget) self.sl...
python
def add_slave(self, slave, container_name="widget"): """Add a slave delegate """ cont = getattr(self, container_name, None) if cont is None: raise AttributeError( 'Container name must be a member of the delegate') cont.add(slave.widget) self.sl...
[ "def", "add_slave", "(", "self", ",", "slave", ",", "container_name", "=", "\"widget\"", ")", ":", "cont", "=", "getattr", "(", "self", ",", "container_name", ",", "None", ")", "if", "cont", "is", "None", ":", "raise", "AttributeError", "(", "'Container na...
Add a slave delegate
[ "Add", "a", "slave", "delegate" ]
ae793cb34a5c1bbe40cc83bb8a6084f0eeed2519
https://github.com/cfobel/pygtk3-helpers/blob/ae793cb34a5c1bbe40cc83bb8a6084f0eeed2519/pygtk3_helpers/delegates.py#L103-L112
train
cfobel/pygtk3-helpers
pygtk3_helpers/delegates.py
SlaveView.get_builder_toplevel
def get_builder_toplevel(self, builder): """Get the toplevel widget from a Gtk.Builder file. The slave view implementation first searches for the widget named as self.toplevel_name (which defaults to "main". If this is missing, the first toplevel widget is discovered in the Builder file...
python
def get_builder_toplevel(self, builder): """Get the toplevel widget from a Gtk.Builder file. The slave view implementation first searches for the widget named as self.toplevel_name (which defaults to "main". If this is missing, the first toplevel widget is discovered in the Builder file...
[ "def", "get_builder_toplevel", "(", "self", ",", "builder", ")", ":", "toplevel", "=", "builder", ".", "get_object", "(", "self", ".", "toplevel_name", ")", "if", "toplevel", "is", "None", ":", "toplevel", "=", "get_first_builder_window", "(", "builder", ")", ...
Get the toplevel widget from a Gtk.Builder file. The slave view implementation first searches for the widget named as self.toplevel_name (which defaults to "main". If this is missing, the first toplevel widget is discovered in the Builder file, and it's immediate child is used as the to...
[ "Get", "the", "toplevel", "widget", "from", "a", "Gtk", ".", "Builder", "file", "." ]
ae793cb34a5c1bbe40cc83bb8a6084f0eeed2519
https://github.com/cfobel/pygtk3-helpers/blob/ae793cb34a5c1bbe40cc83bb8a6084f0eeed2519/pygtk3_helpers/delegates.py#L231-L246
train
cfobel/pygtk3-helpers
pygtk3_helpers/delegates.py
SlaveView.show_and_run
def show_and_run(self): """Show the main widget in a window and run the gtk loop""" if not self._ui_ready: self.prepare_ui() self.display_widget = Gtk.Window() self.display_widget.add(self.widget) self.display_widget.show() self.display_widget.connect('destroy...
python
def show_and_run(self): """Show the main widget in a window and run the gtk loop""" if not self._ui_ready: self.prepare_ui() self.display_widget = Gtk.Window() self.display_widget.add(self.widget) self.display_widget.show() self.display_widget.connect('destroy...
[ "def", "show_and_run", "(", "self", ")", ":", "if", "not", "self", ".", "_ui_ready", ":", "self", ".", "prepare_ui", "(", ")", "self", ".", "display_widget", "=", "Gtk", ".", "Window", "(", ")", "self", ".", "display_widget", ".", "add", "(", "self", ...
Show the main widget in a window and run the gtk loop
[ "Show", "the", "main", "widget", "in", "a", "window", "and", "run", "the", "gtk", "loop" ]
ae793cb34a5c1bbe40cc83bb8a6084f0eeed2519
https://github.com/cfobel/pygtk3-helpers/blob/ae793cb34a5c1bbe40cc83bb8a6084f0eeed2519/pygtk3_helpers/delegates.py#L251-L259
train
cfobel/pygtk3-helpers
pygtk3_helpers/delegates.py
ToplevelView.get_builder_toplevel
def get_builder_toplevel(self, builder): """Get the toplevel widget from a Gtk.Builder file. The main view implementation first searches for the widget named as self.toplevel_name (which defaults to "main". If this is missing, or not a Gtk.Window, the first toplevel window found in the ...
python
def get_builder_toplevel(self, builder): """Get the toplevel widget from a Gtk.Builder file. The main view implementation first searches for the widget named as self.toplevel_name (which defaults to "main". If this is missing, or not a Gtk.Window, the first toplevel window found in the ...
[ "def", "get_builder_toplevel", "(", "self", ",", "builder", ")", ":", "toplevel", "=", "builder", ".", "get_object", "(", "self", ".", "toplevel_name", ")", "if", "not", "GObject", ".", "type_is_a", "(", "toplevel", ",", "Gtk", ".", "Window", ")", ":", "...
Get the toplevel widget from a Gtk.Builder file. The main view implementation first searches for the widget named as self.toplevel_name (which defaults to "main". If this is missing, or not a Gtk.Window, the first toplevel window found in the Gtk.Builder is used.
[ "Get", "the", "toplevel", "widget", "from", "a", "Gtk", ".", "Builder", "file", "." ]
ae793cb34a5c1bbe40cc83bb8a6084f0eeed2519
https://github.com/cfobel/pygtk3-helpers/blob/ae793cb34a5c1bbe40cc83bb8a6084f0eeed2519/pygtk3_helpers/delegates.py#L265-L278
train
InformaticsMatters/pipelines-utils
src/python/pipelines_utils/utils.py
round_sig
def round_sig(x, sig): """Round the number to the specified number of significant figures""" return round(x, sig - int(floor(log10(abs(x)))) - 1)
python
def round_sig(x, sig): """Round the number to the specified number of significant figures""" return round(x, sig - int(floor(log10(abs(x)))) - 1)
[ "def", "round_sig", "(", "x", ",", "sig", ")", ":", "return", "round", "(", "x", ",", "sig", "-", "int", "(", "floor", "(", "log10", "(", "abs", "(", "x", ")", ")", ")", ")", "-", "1", ")" ]
Round the number to the specified number of significant figures
[ "Round", "the", "number", "to", "the", "specified", "number", "of", "significant", "figures" ]
058aa6eceeff28c4ae402f6f58c58720bff0298e
https://github.com/InformaticsMatters/pipelines-utils/blob/058aa6eceeff28c4ae402f6f58c58720bff0298e/src/python/pipelines_utils/utils.py#L30-L32
train
InformaticsMatters/pipelines-utils
src/python/pipelines_utils/utils.py
open_file
def open_file(filename, as_text=False): """Open the file gunzipping it if it ends with .gz. If as_text the file is opened in text mode, otherwise the file's opened in binary mode.""" if filename.lower().endswith('.gz'): if as_text: return gzip.open(filename, 'rt') else: ...
python
def open_file(filename, as_text=False): """Open the file gunzipping it if it ends with .gz. If as_text the file is opened in text mode, otherwise the file's opened in binary mode.""" if filename.lower().endswith('.gz'): if as_text: return gzip.open(filename, 'rt') else: ...
[ "def", "open_file", "(", "filename", ",", "as_text", "=", "False", ")", ":", "if", "filename", ".", "lower", "(", ")", ".", "endswith", "(", "'.gz'", ")", ":", "if", "as_text", ":", "return", "gzip", ".", "open", "(", "filename", ",", "'rt'", ")", ...
Open the file gunzipping it if it ends with .gz. If as_text the file is opened in text mode, otherwise the file's opened in binary mode.
[ "Open", "the", "file", "gunzipping", "it", "if", "it", "ends", "with", ".", "gz", ".", "If", "as_text", "the", "file", "is", "opened", "in", "text", "mode", "otherwise", "the", "file", "s", "opened", "in", "binary", "mode", "." ]
058aa6eceeff28c4ae402f6f58c58720bff0298e
https://github.com/InformaticsMatters/pipelines-utils/blob/058aa6eceeff28c4ae402f6f58c58720bff0298e/src/python/pipelines_utils/utils.py#L35-L48
train
InformaticsMatters/pipelines-utils
src/python/pipelines_utils/utils.py
create_simple_writer
def create_simple_writer(outputDef, defaultOutput, outputFormat, fieldNames, compress=True, valueClassMappings=None, datasetMetaProps=None, fieldMetaProps=None): """Create a simple writer suitable for writing flat data e.g. as BasicObject or TSV.""" if not ...
python
def create_simple_writer(outputDef, defaultOutput, outputFormat, fieldNames, compress=True, valueClassMappings=None, datasetMetaProps=None, fieldMetaProps=None): """Create a simple writer suitable for writing flat data e.g. as BasicObject or TSV.""" if not ...
[ "def", "create_simple_writer", "(", "outputDef", ",", "defaultOutput", ",", "outputFormat", ",", "fieldNames", ",", "compress", "=", "True", ",", "valueClassMappings", "=", "None", ",", "datasetMetaProps", "=", "None", ",", "fieldMetaProps", "=", "None", ")", ":...
Create a simple writer suitable for writing flat data e.g. as BasicObject or TSV.
[ "Create", "a", "simple", "writer", "suitable", "for", "writing", "flat", "data", "e", ".", "g", ".", "as", "BasicObject", "or", "TSV", "." ]
058aa6eceeff28c4ae402f6f58c58720bff0298e
https://github.com/InformaticsMatters/pipelines-utils/blob/058aa6eceeff28c4ae402f6f58c58720bff0298e/src/python/pipelines_utils/utils.py#L51-L71
train
InformaticsMatters/pipelines-utils
src/python/pipelines_utils/utils.py
write_squonk_datasetmetadata
def write_squonk_datasetmetadata(outputBase, thinOutput, valueClassMappings, datasetMetaProps, fieldMetaProps): """This is a temp hack to write the minimal metadata that Squonk needs. Will needs to be replaced with something that allows something more complete to be written. :param outputBase: Base name fo...
python
def write_squonk_datasetmetadata(outputBase, thinOutput, valueClassMappings, datasetMetaProps, fieldMetaProps): """This is a temp hack to write the minimal metadata that Squonk needs. Will needs to be replaced with something that allows something more complete to be written. :param outputBase: Base name fo...
[ "def", "write_squonk_datasetmetadata", "(", "outputBase", ",", "thinOutput", ",", "valueClassMappings", ",", "datasetMetaProps", ",", "fieldMetaProps", ")", ":", "meta", "=", "{", "}", "props", "=", "{", "}", "# TODO add created property - how to handle date formats?", ...
This is a temp hack to write the minimal metadata that Squonk needs. Will needs to be replaced with something that allows something more complete to be written. :param outputBase: Base name for the file to write to :param thinOutput: Write only new data, not structures. Result type will be BasicObject ...
[ "This", "is", "a", "temp", "hack", "to", "write", "the", "minimal", "metadata", "that", "Squonk", "needs", ".", "Will", "needs", "to", "be", "replaced", "with", "something", "that", "allows", "something", "more", "complete", "to", "be", "written", "." ]
058aa6eceeff28c4ae402f6f58c58720bff0298e
https://github.com/InformaticsMatters/pipelines-utils/blob/058aa6eceeff28c4ae402f6f58c58720bff0298e/src/python/pipelines_utils/utils.py#L90-L124
train
InformaticsMatters/pipelines-utils
src/python/pipelines_utils/utils.py
write_metrics
def write_metrics(baseName, values): """Write the metrics data :param baseName: The base name of the output files. e.g. extensions will be appended to this base name :param values dictionary of values to write """ m = open(baseName + '_metrics.txt', 'w') for key in values:...
python
def write_metrics(baseName, values): """Write the metrics data :param baseName: The base name of the output files. e.g. extensions will be appended to this base name :param values dictionary of values to write """ m = open(baseName + '_metrics.txt', 'w') for key in values:...
[ "def", "write_metrics", "(", "baseName", ",", "values", ")", ":", "m", "=", "open", "(", "baseName", "+", "'_metrics.txt'", ",", "'w'", ")", "for", "key", "in", "values", ":", "m", ".", "write", "(", "key", "+", "'='", "+", "str", "(", "values", "[...
Write the metrics data :param baseName: The base name of the output files. e.g. extensions will be appended to this base name :param values dictionary of values to write
[ "Write", "the", "metrics", "data" ]
058aa6eceeff28c4ae402f6f58c58720bff0298e
https://github.com/InformaticsMatters/pipelines-utils/blob/058aa6eceeff28c4ae402f6f58c58720bff0298e/src/python/pipelines_utils/utils.py#L127-L138
train
InformaticsMatters/pipelines-utils
src/python/pipelines_utils/utils.py
generate_molecule_object_dict
def generate_molecule_object_dict(source, format, values): """Generate a dictionary that represents a Squonk MoleculeObject when written as JSON :param source: Molecules in molfile or smiles format :param format: The format of the molecule. Either 'mol' or 'smiles' :param values: Optional dict of v...
python
def generate_molecule_object_dict(source, format, values): """Generate a dictionary that represents a Squonk MoleculeObject when written as JSON :param source: Molecules in molfile or smiles format :param format: The format of the molecule. Either 'mol' or 'smiles' :param values: Optional dict of v...
[ "def", "generate_molecule_object_dict", "(", "source", ",", "format", ",", "values", ")", ":", "m", "=", "{", "\"uuid\"", ":", "str", "(", "uuid", ".", "uuid4", "(", ")", ")", ",", "\"source\"", ":", "source", ",", "\"format\"", ":", "format", "}", "if...
Generate a dictionary that represents a Squonk MoleculeObject when written as JSON :param source: Molecules in molfile or smiles format :param format: The format of the molecule. Either 'mol' or 'smiles' :param values: Optional dict of values (properties) for the MoleculeObject
[ "Generate", "a", "dictionary", "that", "represents", "a", "Squonk", "MoleculeObject", "when", "written", "as", "JSON" ]
058aa6eceeff28c4ae402f6f58c58720bff0298e
https://github.com/InformaticsMatters/pipelines-utils/blob/058aa6eceeff28c4ae402f6f58c58720bff0298e/src/python/pipelines_utils/utils.py#L141-L152
train
InformaticsMatters/pipelines-utils
src/python/pipelines_utils/utils.py
get_undecorated_calling_module
def get_undecorated_calling_module(): """Returns the module name of the caller's calling module. If a.py makes a call to b() in b.py, b() can get the name of the calling module (i.e. a) by calling get_undecorated_calling_module(). The module also includes its full path. As the name suggests, this ...
python
def get_undecorated_calling_module(): """Returns the module name of the caller's calling module. If a.py makes a call to b() in b.py, b() can get the name of the calling module (i.e. a) by calling get_undecorated_calling_module(). The module also includes its full path. As the name suggests, this ...
[ "def", "get_undecorated_calling_module", "(", ")", ":", "frame", "=", "inspect", ".", "stack", "(", ")", "[", "2", "]", "module", "=", "inspect", ".", "getmodule", "(", "frame", "[", "0", "]", ")", "# Return the module's file and its path", "# and omit the exten...
Returns the module name of the caller's calling module. If a.py makes a call to b() in b.py, b() can get the name of the calling module (i.e. a) by calling get_undecorated_calling_module(). The module also includes its full path. As the name suggests, this does not work for decorated functions.
[ "Returns", "the", "module", "name", "of", "the", "caller", "s", "calling", "module", ".", "If", "a", ".", "py", "makes", "a", "call", "to", "b", "()", "in", "b", ".", "py", "b", "()", "can", "get", "the", "name", "of", "the", "calling", "module", ...
058aa6eceeff28c4ae402f6f58c58720bff0298e
https://github.com/InformaticsMatters/pipelines-utils/blob/058aa6eceeff28c4ae402f6f58c58720bff0298e/src/python/pipelines_utils/utils.py#L155-L169
train
cons3rt/pycons3rt
pycons3rt/nexus.py
query_nexus
def query_nexus(query_url, timeout_sec, basic_auth=None): """Queries Nexus for an artifact :param query_url: (str) Query URL :param timeout_sec: (int) query timeout :param basic_auth (HTTPBasicAuth) object or none :return: requests.Response object :raises: RuntimeError """ log = logging...
python
def query_nexus(query_url, timeout_sec, basic_auth=None): """Queries Nexus for an artifact :param query_url: (str) Query URL :param timeout_sec: (int) query timeout :param basic_auth (HTTPBasicAuth) object or none :return: requests.Response object :raises: RuntimeError """ log = logging...
[ "def", "query_nexus", "(", "query_url", ",", "timeout_sec", ",", "basic_auth", "=", "None", ")", ":", "log", "=", "logging", ".", "getLogger", "(", "mod_logger", "+", "'.query_nexus'", ")", "# Attempt to query Nexus", "retry_sec", "=", "5", "max_retries", "=", ...
Queries Nexus for an artifact :param query_url: (str) Query URL :param timeout_sec: (int) query timeout :param basic_auth (HTTPBasicAuth) object or none :return: requests.Response object :raises: RuntimeError
[ "Queries", "Nexus", "for", "an", "artifact" ]
f004ab3a35c5bff2f698131fef3b2a8ed5a7596d
https://github.com/cons3rt/pycons3rt/blob/f004ab3a35c5bff2f698131fef3b2a8ed5a7596d/pycons3rt/nexus.py#L39-L93
train
cons3rt/pycons3rt
pycons3rt/nexus.py
get_artifact
def get_artifact(suppress_status=False, nexus_url=sample_nexus_url, timeout_sec=600, overwrite=True, username=None, password=None, **kwargs): """Retrieves an artifact from Nexus :param suppress_status: (bool) Set to True to suppress printing download status :param nexus_url: (str) URL of t...
python
def get_artifact(suppress_status=False, nexus_url=sample_nexus_url, timeout_sec=600, overwrite=True, username=None, password=None, **kwargs): """Retrieves an artifact from Nexus :param suppress_status: (bool) Set to True to suppress printing download status :param nexus_url: (str) URL of t...
[ "def", "get_artifact", "(", "suppress_status", "=", "False", ",", "nexus_url", "=", "sample_nexus_url", ",", "timeout_sec", "=", "600", ",", "overwrite", "=", "True", ",", "username", "=", "None", ",", "password", "=", "None", ",", "*", "*", "kwargs", ")",...
Retrieves an artifact from Nexus :param suppress_status: (bool) Set to True to suppress printing download status :param nexus_url: (str) URL of the Nexus Server :param timeout_sec: (int) Number of seconds to wait before timing out the artifact retrieval. :param overwrite: (bool) True overwrites...
[ "Retrieves", "an", "artifact", "from", "Nexus" ]
f004ab3a35c5bff2f698131fef3b2a8ed5a7596d
https://github.com/cons3rt/pycons3rt/blob/f004ab3a35c5bff2f698131fef3b2a8ed5a7596d/pycons3rt/nexus.py#L96-L299
train
cons3rt/pycons3rt
pycons3rt/nexus.py
get_artifact_nexus3
def get_artifact_nexus3(suppress_status=False, nexus_base_url=sample_nexus_base_url, repository=None, timeout_sec=600, overwrite=True, username=None, password=None, **kwargs): """Retrieves an artifact from the Nexus 3 ReST API :param suppress_status: (bool) Set to True to suppress print...
python
def get_artifact_nexus3(suppress_status=False, nexus_base_url=sample_nexus_base_url, repository=None, timeout_sec=600, overwrite=True, username=None, password=None, **kwargs): """Retrieves an artifact from the Nexus 3 ReST API :param suppress_status: (bool) Set to True to suppress print...
[ "def", "get_artifact_nexus3", "(", "suppress_status", "=", "False", ",", "nexus_base_url", "=", "sample_nexus_base_url", ",", "repository", "=", "None", ",", "timeout_sec", "=", "600", ",", "overwrite", "=", "True", ",", "username", "=", "None", ",", "password",...
Retrieves an artifact from the Nexus 3 ReST API :param suppress_status: (bool) Set to True to suppress printing download status :param nexus_base_url: (str) Base URL of the Nexus Server (domain name portion only, see sample) :param repository: (str) Repository to query (e.g. snapshots) if not provided, wil...
[ "Retrieves", "an", "artifact", "from", "the", "Nexus", "3", "ReST", "API" ]
f004ab3a35c5bff2f698131fef3b2a8ed5a7596d
https://github.com/cons3rt/pycons3rt/blob/f004ab3a35c5bff2f698131fef3b2a8ed5a7596d/pycons3rt/nexus.py#L302-L553
train
cons3rt/pycons3rt
pycons3rt/nexus.py
main
def main(): """Handles calling this module as a script :return: None """ log = logging.getLogger(mod_logger + '.main') parser = argparse.ArgumentParser(description='This Python module retrieves artifacts from Nexus.') parser.add_argument('-u', '--url', help='Nexus Server URL', required=False) ...
python
def main(): """Handles calling this module as a script :return: None """ log = logging.getLogger(mod_logger + '.main') parser = argparse.ArgumentParser(description='This Python module retrieves artifacts from Nexus.') parser.add_argument('-u', '--url', help='Nexus Server URL', required=False) ...
[ "def", "main", "(", ")", ":", "log", "=", "logging", ".", "getLogger", "(", "mod_logger", "+", "'.main'", ")", "parser", "=", "argparse", ".", "ArgumentParser", "(", "description", "=", "'This Python module retrieves artifacts from Nexus.'", ")", "parser", ".", ...
Handles calling this module as a script :return: None
[ "Handles", "calling", "this", "module", "as", "a", "script" ]
f004ab3a35c5bff2f698131fef3b2a8ed5a7596d
https://github.com/cons3rt/pycons3rt/blob/f004ab3a35c5bff2f698131fef3b2a8ed5a7596d/pycons3rt/nexus.py#L556-L591
train
Josef-Friedrich/phrydy
phrydy/doc.py
get_doc
def get_doc(additional_doc=False, field_prefix='$', field_suffix=':', indent=4): """Return a formated string containing documentation about the audio fields. """ if additional_doc: f = fields.copy() f.update(additional_doc) else: f = fields...
python
def get_doc(additional_doc=False, field_prefix='$', field_suffix=':', indent=4): """Return a formated string containing documentation about the audio fields. """ if additional_doc: f = fields.copy() f.update(additional_doc) else: f = fields...
[ "def", "get_doc", "(", "additional_doc", "=", "False", ",", "field_prefix", "=", "'$'", ",", "field_suffix", "=", "':'", ",", "indent", "=", "4", ")", ":", "if", "additional_doc", ":", "f", "=", "fields", ".", "copy", "(", ")", "f", ".", "update", "(...
Return a formated string containing documentation about the audio fields.
[ "Return", "a", "formated", "string", "containing", "documentation", "about", "the", "audio", "fields", "." ]
aa13755155977b4776e49f79984f9968ac1d74dc
https://github.com/Josef-Friedrich/phrydy/blob/aa13755155977b4776e49f79984f9968ac1d74dc/phrydy/doc.py#L413-L440
train
novopl/peltak
src/peltak/extra/docker/client.py
RegistryClient.list_images
def list_images(self): # type: () -> List[str] """ List images stored in the registry. Returns: list[str]: List of image names. """ r = self.get(self.registry_url + '/v2/_catalog', auth=self.auth) return r.json()['repositories']
python
def list_images(self): # type: () -> List[str] """ List images stored in the registry. Returns: list[str]: List of image names. """ r = self.get(self.registry_url + '/v2/_catalog', auth=self.auth) return r.json()['repositories']
[ "def", "list_images", "(", "self", ")", ":", "# type: () -> List[str]", "r", "=", "self", ".", "get", "(", "self", ".", "registry_url", "+", "'/v2/_catalog'", ",", "auth", "=", "self", ".", "auth", ")", "return", "r", ".", "json", "(", ")", "[", "'repo...
List images stored in the registry. Returns: list[str]: List of image names.
[ "List", "images", "stored", "in", "the", "registry", "." ]
b627acc019e3665875fe76cdca0a14773b69beaa
https://github.com/novopl/peltak/blob/b627acc019e3665875fe76cdca0a14773b69beaa/src/peltak/extra/docker/client.py#L53-L61
train
novopl/peltak
src/peltak/extra/docker/client.py
RegistryClient.list_tags
def list_tags(self, image_name): # type: (str) -> Iterator[str] """ List all tags for the given image stored in the registry. Args: image_name (str): The name of the image to query. The image must be present on the registry for this call to return any...
python
def list_tags(self, image_name): # type: (str) -> Iterator[str] """ List all tags for the given image stored in the registry. Args: image_name (str): The name of the image to query. The image must be present on the registry for this call to return any...
[ "def", "list_tags", "(", "self", ",", "image_name", ")", ":", "# type: (str) -> Iterator[str]", "tags_url", "=", "self", ".", "registry_url", "+", "'/v2/{}/tags/list'", "r", "=", "self", ".", "get", "(", "tags_url", ".", "format", "(", "image_name", ")", ",", ...
List all tags for the given image stored in the registry. Args: image_name (str): The name of the image to query. The image must be present on the registry for this call to return any values. Returns: list[str]: List of tags for that image.
[ "List", "all", "tags", "for", "the", "given", "image", "stored", "in", "the", "registry", "." ]
b627acc019e3665875fe76cdca0a14773b69beaa
https://github.com/novopl/peltak/blob/b627acc019e3665875fe76cdca0a14773b69beaa/src/peltak/extra/docker/client.py#L63-L82
train
cons3rt/pycons3rt
pycons3rt/asset.py
validate_asset_structure
def validate_asset_structure(asset_dir_path): """Checks asset structure validity :param asset_dir_path: (str) path to the directory containing the asset :return: (str) Asset name :raises: Cons3rtAssetStructureError """ log = logging.getLogger(mod_logger + '.validate_asset_structure') log.i...
python
def validate_asset_structure(asset_dir_path): """Checks asset structure validity :param asset_dir_path: (str) path to the directory containing the asset :return: (str) Asset name :raises: Cons3rtAssetStructureError """ log = logging.getLogger(mod_logger + '.validate_asset_structure') log.i...
[ "def", "validate_asset_structure", "(", "asset_dir_path", ")", ":", "log", "=", "logging", ".", "getLogger", "(", "mod_logger", "+", "'.validate_asset_structure'", ")", "log", ".", "info", "(", "'Validating asset directory: {d}'", ".", "format", "(", "d", "=", "as...
Checks asset structure validity :param asset_dir_path: (str) path to the directory containing the asset :return: (str) Asset name :raises: Cons3rtAssetStructureError
[ "Checks", "asset", "structure", "validity" ]
f004ab3a35c5bff2f698131fef3b2a8ed5a7596d
https://github.com/cons3rt/pycons3rt/blob/f004ab3a35c5bff2f698131fef3b2a8ed5a7596d/pycons3rt/asset.py#L122-L253
train
cons3rt/pycons3rt
pycons3rt/asset.py
make_asset_zip
def make_asset_zip(asset_dir_path, destination_directory=None): """Given an asset directory path, creates an asset zip file in the provided destination directory :param asset_dir_path: (str) path to the directory containing the asset :param destination_directory: (str) path to the destination directory...
python
def make_asset_zip(asset_dir_path, destination_directory=None): """Given an asset directory path, creates an asset zip file in the provided destination directory :param asset_dir_path: (str) path to the directory containing the asset :param destination_directory: (str) path to the destination directory...
[ "def", "make_asset_zip", "(", "asset_dir_path", ",", "destination_directory", "=", "None", ")", ":", "log", "=", "logging", ".", "getLogger", "(", "mod_logger", "+", "'.make_asset_zip'", ")", "log", ".", "info", "(", "'Attempting to create an asset zip from directory:...
Given an asset directory path, creates an asset zip file in the provided destination directory :param asset_dir_path: (str) path to the directory containing the asset :param destination_directory: (str) path to the destination directory for the asset :return: (str) Path to the asset zip fil...
[ "Given", "an", "asset", "directory", "path", "creates", "an", "asset", "zip", "file", "in", "the", "provided", "destination", "directory" ]
f004ab3a35c5bff2f698131fef3b2a8ed5a7596d
https://github.com/cons3rt/pycons3rt/blob/f004ab3a35c5bff2f698131fef3b2a8ed5a7596d/pycons3rt/asset.py#L256-L345
train
cons3rt/pycons3rt
pycons3rt/asset.py
validate
def validate(asset_dir): """Command line call to validate an asset structure :param asset_dir: (full path to the asset dir) :return: (int) """ try: asset_name = validate_asset_structure(asset_dir_path=asset_dir) except Cons3rtAssetStructureError: _, ex, trace = sys.exc_info() ...
python
def validate(asset_dir): """Command line call to validate an asset structure :param asset_dir: (full path to the asset dir) :return: (int) """ try: asset_name = validate_asset_structure(asset_dir_path=asset_dir) except Cons3rtAssetStructureError: _, ex, trace = sys.exc_info() ...
[ "def", "validate", "(", "asset_dir", ")", ":", "try", ":", "asset_name", "=", "validate_asset_structure", "(", "asset_dir_path", "=", "asset_dir", ")", "except", "Cons3rtAssetStructureError", ":", "_", ",", "ex", ",", "trace", "=", "sys", ".", "exc_info", "(",...
Command line call to validate an asset structure :param asset_dir: (full path to the asset dir) :return: (int)
[ "Command", "line", "call", "to", "validate", "an", "asset", "structure" ]
f004ab3a35c5bff2f698131fef3b2a8ed5a7596d
https://github.com/cons3rt/pycons3rt/blob/f004ab3a35c5bff2f698131fef3b2a8ed5a7596d/pycons3rt/asset.py#L348-L362
train
cons3rt/pycons3rt
pycons3rt/asset.py
create
def create(asset_dir, dest_dir): """Command line call to create an asset zip :param asset_dir: (full path to the asset dir) :param dest_dir: (full path to the destination directory) :return: (int) """ val = validate(asset_dir=asset_dir) if val != 0: return 1 try: asset_z...
python
def create(asset_dir, dest_dir): """Command line call to create an asset zip :param asset_dir: (full path to the asset dir) :param dest_dir: (full path to the destination directory) :return: (int) """ val = validate(asset_dir=asset_dir) if val != 0: return 1 try: asset_z...
[ "def", "create", "(", "asset_dir", ",", "dest_dir", ")", ":", "val", "=", "validate", "(", "asset_dir", "=", "asset_dir", ")", "if", "val", "!=", "0", ":", "return", "1", "try", ":", "asset_zip", "=", "make_asset_zip", "(", "asset_dir_path", "=", "asset_...
Command line call to create an asset zip :param asset_dir: (full path to the asset dir) :param dest_dir: (full path to the destination directory) :return: (int)
[ "Command", "line", "call", "to", "create", "an", "asset", "zip" ]
f004ab3a35c5bff2f698131fef3b2a8ed5a7596d
https://github.com/cons3rt/pycons3rt/blob/f004ab3a35c5bff2f698131fef3b2a8ed5a7596d/pycons3rt/asset.py#L365-L383
train
kajala/django-jutil
jutil/model.py
get_object_or_none
def get_object_or_none(cls, **kwargs): """ Returns model instance or None if not found. :param cls: Class or queryset :param kwargs: Filters for get() call :return: Object or None """ from django.shortcuts import _get_queryset qs = _get_queryset(cls) try: return qs.get(**kwar...
python
def get_object_or_none(cls, **kwargs): """ Returns model instance or None if not found. :param cls: Class or queryset :param kwargs: Filters for get() call :return: Object or None """ from django.shortcuts import _get_queryset qs = _get_queryset(cls) try: return qs.get(**kwar...
[ "def", "get_object_or_none", "(", "cls", ",", "*", "*", "kwargs", ")", ":", "from", "django", ".", "shortcuts", "import", "_get_queryset", "qs", "=", "_get_queryset", "(", "cls", ")", "try", ":", "return", "qs", ".", "get", "(", "*", "*", "kwargs", ")"...
Returns model instance or None if not found. :param cls: Class or queryset :param kwargs: Filters for get() call :return: Object or None
[ "Returns", "model", "instance", "or", "None", "if", "not", "found", ".", ":", "param", "cls", ":", "Class", "or", "queryset", ":", "param", "kwargs", ":", "Filters", "for", "get", "()", "call", ":", "return", ":", "Object", "or", "None" ]
2abd93ebad51042744eaeb1ee1074ed0eb55ad0c
https://github.com/kajala/django-jutil/blob/2abd93ebad51042744eaeb1ee1074ed0eb55ad0c/jutil/model.py#L5-L17
train
kajala/django-jutil
jutil/model.py
get_model_field_label_and_value
def get_model_field_label_and_value(instance, field_name) -> (str, str): """ Returns model field label and value. :param instance: Model instance :param field_name: Model attribute name :return: (label, value) tuple """ label = field_name value = str(getattr(instance, field_name)) fo...
python
def get_model_field_label_and_value(instance, field_name) -> (str, str): """ Returns model field label and value. :param instance: Model instance :param field_name: Model attribute name :return: (label, value) tuple """ label = field_name value = str(getattr(instance, field_name)) fo...
[ "def", "get_model_field_label_and_value", "(", "instance", ",", "field_name", ")", "->", "(", "str", ",", "str", ")", ":", "label", "=", "field_name", "value", "=", "str", "(", "getattr", "(", "instance", ",", "field_name", ")", ")", "for", "f", "in", "i...
Returns model field label and value. :param instance: Model instance :param field_name: Model attribute name :return: (label, value) tuple
[ "Returns", "model", "field", "label", "and", "value", ".", ":", "param", "instance", ":", "Model", "instance", ":", "param", "field_name", ":", "Model", "attribute", "name", ":", "return", ":", "(", "label", "value", ")", "tuple" ]
2abd93ebad51042744eaeb1ee1074ed0eb55ad0c
https://github.com/kajala/django-jutil/blob/2abd93ebad51042744eaeb1ee1074ed0eb55ad0c/jutil/model.py#L20-L35
train
kajala/django-jutil
jutil/model.py
clone_model
def clone_model(instance, cls, commit: bool=True, exclude_fields: tuple=('id',), base_class_suffix: str='_ptr', **kw): """ Assigns model fields to new object. Ignores exclude_fields list and attributes ending with pointer suffix (default '_ptr') :param instance: Instance to copy :param cls: Class na...
python
def clone_model(instance, cls, commit: bool=True, exclude_fields: tuple=('id',), base_class_suffix: str='_ptr', **kw): """ Assigns model fields to new object. Ignores exclude_fields list and attributes ending with pointer suffix (default '_ptr') :param instance: Instance to copy :param cls: Class na...
[ "def", "clone_model", "(", "instance", ",", "cls", ",", "commit", ":", "bool", "=", "True", ",", "exclude_fields", ":", "tuple", "=", "(", "'id'", ",", ")", ",", "base_class_suffix", ":", "str", "=", "'_ptr'", ",", "*", "*", "kw", ")", ":", "keys", ...
Assigns model fields to new object. Ignores exclude_fields list and attributes ending with pointer suffix (default '_ptr') :param instance: Instance to copy :param cls: Class name :param commit: Save or not :param exclude_fields: List of fields to exclude :param base_class_suffix: End of name fo...
[ "Assigns", "model", "fields", "to", "new", "object", ".", "Ignores", "exclude_fields", "list", "and", "attributes", "ending", "with", "pointer", "suffix", "(", "default", "_ptr", ")", ":", "param", "instance", ":", "Instance", "to", "copy", ":", "param", "cl...
2abd93ebad51042744eaeb1ee1074ed0eb55ad0c
https://github.com/kajala/django-jutil/blob/2abd93ebad51042744eaeb1ee1074ed0eb55ad0c/jutil/model.py#L38-L58
train
praekeltfoundation/seed-identity-store
identities/views.py
IdentitySearchList.get_queryset
def get_queryset(self): """ This view should return a list of all the Identities for the supplied query parameters. The query parameters should be in the form: {"address_type": "address"} e.g. {"msisdn": "+27123"} {"email": "foo@bar.com"} A specia...
python
def get_queryset(self): """ This view should return a list of all the Identities for the supplied query parameters. The query parameters should be in the form: {"address_type": "address"} e.g. {"msisdn": "+27123"} {"email": "foo@bar.com"} A specia...
[ "def", "get_queryset", "(", "self", ")", ":", "query_params", "=", "list", "(", "self", ".", "request", ".", "query_params", ".", "keys", "(", ")", ")", "# variable that stores criteria to filter identities by", "filter_criteria", "=", "{", "}", "# variable that sto...
This view should return a list of all the Identities for the supplied query parameters. The query parameters should be in the form: {"address_type": "address"} e.g. {"msisdn": "+27123"} {"email": "foo@bar.com"} A special query paramater "include_inactive" can als...
[ "This", "view", "should", "return", "a", "list", "of", "all", "the", "Identities", "for", "the", "supplied", "query", "parameters", ".", "The", "query", "parameters", "should", "be", "in", "the", "form", ":", "{", "address_type", ":", "address", "}", "e", ...
194e5756b5a74ebce9798c390de958cf5305b105
https://github.com/praekeltfoundation/seed-identity-store/blob/194e5756b5a74ebce9798c390de958cf5305b105/identities/views.py#L131-L210
train
praekeltfoundation/seed-identity-store
identities/views.py
IdentityAddresses.get_queryset
def get_queryset(self): """ This view should return a list of all the addresses the identity has for the supplied query parameters. Currently only supports address_type and default params Always excludes addresses with optedout = True """ identity_id = self.kwargs...
python
def get_queryset(self): """ This view should return a list of all the addresses the identity has for the supplied query parameters. Currently only supports address_type and default params Always excludes addresses with optedout = True """ identity_id = self.kwargs...
[ "def", "get_queryset", "(", "self", ")", ":", "identity_id", "=", "self", ".", "kwargs", "[", "\"identity_id\"", "]", "address_type", "=", "self", ".", "kwargs", "[", "\"address_type\"", "]", "use_ct", "=", "\"use_communicate_through\"", "in", "self", ".", "re...
This view should return a list of all the addresses the identity has for the supplied query parameters. Currently only supports address_type and default params Always excludes addresses with optedout = True
[ "This", "view", "should", "return", "a", "list", "of", "all", "the", "addresses", "the", "identity", "has", "for", "the", "supplied", "query", "parameters", ".", "Currently", "only", "supports", "address_type", "and", "default", "params", "Always", "excludes", ...
194e5756b5a74ebce9798c390de958cf5305b105
https://github.com/praekeltfoundation/seed-identity-store/blob/194e5756b5a74ebce9798c390de958cf5305b105/identities/views.py#L279-L299
train
isogeo/isogeo-api-py-minsdk
isogeo_pysdk/checker.py
IsogeoChecker.check_internet_connection
def check_internet_connection(self, remote_server: str = "api.isogeo.com") -> bool: """Test if an internet connection is operational. Src: http://stackoverflow.com/a/20913928/2556577. :param str remote_server: remote server used to check """ try: # see if we can reso...
python
def check_internet_connection(self, remote_server: str = "api.isogeo.com") -> bool: """Test if an internet connection is operational. Src: http://stackoverflow.com/a/20913928/2556577. :param str remote_server: remote server used to check """ try: # see if we can reso...
[ "def", "check_internet_connection", "(", "self", ",", "remote_server", ":", "str", "=", "\"api.isogeo.com\"", ")", "->", "bool", ":", "try", ":", "# see if we can resolve the host name -- tells us if there is", "# a DNS listening", "host", "=", "socket", ".", "gethostbyna...
Test if an internet connection is operational. Src: http://stackoverflow.com/a/20913928/2556577. :param str remote_server: remote server used to check
[ "Test", "if", "an", "internet", "connection", "is", "operational", ".", "Src", ":", "http", ":", "//", "stackoverflow", ".", "com", "/", "a", "/", "20913928", "/", "2556577", "." ]
57a604be92c7767b26abd247012cc1a584b386a0
https://github.com/isogeo/isogeo-api-py-minsdk/blob/57a604be92c7767b26abd247012cc1a584b386a0/isogeo_pysdk/checker.py#L109-L125
train
isogeo/isogeo-api-py-minsdk
isogeo_pysdk/checker.py
IsogeoChecker.check_bearer_validity
def check_bearer_validity(self, token: dict, connect_mtd) -> dict: """Check API Bearer token validity. Isogeo ID delivers authentication bearers which are valid during a certain time. So this method checks the validity of the token with a 30 mn anticipation limit, and renews it if neces...
python
def check_bearer_validity(self, token: dict, connect_mtd) -> dict: """Check API Bearer token validity. Isogeo ID delivers authentication bearers which are valid during a certain time. So this method checks the validity of the token with a 30 mn anticipation limit, and renews it if neces...
[ "def", "check_bearer_validity", "(", "self", ",", "token", ":", "dict", ",", "connect_mtd", ")", "->", "dict", ":", "warnings", ".", "warn", "(", "\"Method is now executed as a decorator within the main SDK class. Will be removed in future versions.\"", ",", "DeprecationWarni...
Check API Bearer token validity. Isogeo ID delivers authentication bearers which are valid during a certain time. So this method checks the validity of the token with a 30 mn anticipation limit, and renews it if necessary. See: http://tools.ietf.org/html/rfc6750#section-2 FI: 2...
[ "Check", "API", "Bearer", "token", "validity", "." ]
57a604be92c7767b26abd247012cc1a584b386a0
https://github.com/isogeo/isogeo-api-py-minsdk/blob/57a604be92c7767b26abd247012cc1a584b386a0/isogeo_pysdk/checker.py#L127-L154
train
isogeo/isogeo-api-py-minsdk
isogeo_pysdk/checker.py
IsogeoChecker.check_api_response
def check_api_response(self, response): """Check API response and raise exceptions if needed. :param requests.models.Response response: request response to check """ # check response if response.status_code == 200: return True elif response.status_code >= 400...
python
def check_api_response(self, response): """Check API response and raise exceptions if needed. :param requests.models.Response response: request response to check """ # check response if response.status_code == 200: return True elif response.status_code >= 400...
[ "def", "check_api_response", "(", "self", ",", "response", ")", ":", "# check response", "if", "response", ".", "status_code", "==", "200", ":", "return", "True", "elif", "response", ".", "status_code", ">=", "400", ":", "logging", ".", "error", "(", "\"{}: ...
Check API response and raise exceptions if needed. :param requests.models.Response response: request response to check
[ "Check", "API", "response", "and", "raise", "exceptions", "if", "needed", "." ]
57a604be92c7767b26abd247012cc1a584b386a0
https://github.com/isogeo/isogeo-api-py-minsdk/blob/57a604be92c7767b26abd247012cc1a584b386a0/isogeo_pysdk/checker.py#L156-L173
train
isogeo/isogeo-api-py-minsdk
isogeo_pysdk/checker.py
IsogeoChecker.check_request_parameters
def check_request_parameters(self, parameters: dict = dict): """Check parameters passed to avoid errors and help debug. :param dict response: search request parameters """ # -- SEMANTIC QUERY --------------------------------------------------- li_args = parameters.get("q").split...
python
def check_request_parameters(self, parameters: dict = dict): """Check parameters passed to avoid errors and help debug. :param dict response: search request parameters """ # -- SEMANTIC QUERY --------------------------------------------------- li_args = parameters.get("q").split...
[ "def", "check_request_parameters", "(", "self", ",", "parameters", ":", "dict", "=", "dict", ")", ":", "# -- SEMANTIC QUERY ---------------------------------------------------", "li_args", "=", "parameters", ".", "get", "(", "\"q\"", ")", ".", "split", "(", ")", "lo...
Check parameters passed to avoid errors and help debug. :param dict response: search request parameters
[ "Check", "parameters", "passed", "to", "avoid", "errors", "and", "help", "debug", "." ]
57a604be92c7767b26abd247012cc1a584b386a0
https://github.com/isogeo/isogeo-api-py-minsdk/blob/57a604be92c7767b26abd247012cc1a584b386a0/isogeo_pysdk/checker.py#L175-L281
train
isogeo/isogeo-api-py-minsdk
isogeo_pysdk/checker.py
IsogeoChecker.check_is_uuid
def check_is_uuid(self, uuid_str: str): """Check if it's an Isogeo UUID handling specific form. :param str uuid_str: UUID string to check """ # check uuid type if not isinstance(uuid_str, str): raise TypeError("'uuid_str' expected a str value.") else: ...
python
def check_is_uuid(self, uuid_str: str): """Check if it's an Isogeo UUID handling specific form. :param str uuid_str: UUID string to check """ # check uuid type if not isinstance(uuid_str, str): raise TypeError("'uuid_str' expected a str value.") else: ...
[ "def", "check_is_uuid", "(", "self", ",", "uuid_str", ":", "str", ")", ":", "# check uuid type", "if", "not", "isinstance", "(", "uuid_str", ",", "str", ")", ":", "raise", "TypeError", "(", "\"'uuid_str' expected a str value.\"", ")", "else", ":", "pass", "# h...
Check if it's an Isogeo UUID handling specific form. :param str uuid_str: UUID string to check
[ "Check", "if", "it", "s", "an", "Isogeo", "UUID", "handling", "specific", "form", "." ]
57a604be92c7767b26abd247012cc1a584b386a0
https://github.com/isogeo/isogeo-api-py-minsdk/blob/57a604be92c7767b26abd247012cc1a584b386a0/isogeo_pysdk/checker.py#L283-L306
train
isogeo/isogeo-api-py-minsdk
isogeo_pysdk/checker.py
IsogeoChecker.check_edit_tab
def check_edit_tab(self, tab: str, md_type: str): """Check if asked tab is part of Isogeo web form and reliable with metadata type. :param str tab: tab to check. Must be one one of EDIT_TABS attribute :param str md_type: metadata type. Must be one one of FILTER_TYPES """ ...
python
def check_edit_tab(self, tab: str, md_type: str): """Check if asked tab is part of Isogeo web form and reliable with metadata type. :param str tab: tab to check. Must be one one of EDIT_TABS attribute :param str md_type: metadata type. Must be one one of FILTER_TYPES """ ...
[ "def", "check_edit_tab", "(", "self", ",", "tab", ":", "str", ",", "md_type", ":", "str", ")", ":", "# check parameters types", "if", "not", "isinstance", "(", "tab", ",", "str", ")", ":", "raise", "TypeError", "(", "\"'tab' expected a str value.\"", ")", "e...
Check if asked tab is part of Isogeo web form and reliable with metadata type. :param str tab: tab to check. Must be one one of EDIT_TABS attribute :param str md_type: metadata type. Must be one one of FILTER_TYPES
[ "Check", "if", "asked", "tab", "is", "part", "of", "Isogeo", "web", "form", "and", "reliable", "with", "metadata", "type", "." ]
57a604be92c7767b26abd247012cc1a584b386a0
https://github.com/isogeo/isogeo-api-py-minsdk/blob/57a604be92c7767b26abd247012cc1a584b386a0/isogeo_pysdk/checker.py#L308-L349
train
isogeo/isogeo-api-py-minsdk
isogeo_pysdk/checker.py
IsogeoChecker._check_filter_specific_md
def _check_filter_specific_md(self, specific_md: list): """Check if specific_md parameter is valid. :param list specific_md: list of specific metadata UUID to check """ if isinstance(specific_md, list): if len(specific_md) > 0: # checking UUIDs and poping bad...
python
def _check_filter_specific_md(self, specific_md: list): """Check if specific_md parameter is valid. :param list specific_md: list of specific metadata UUID to check """ if isinstance(specific_md, list): if len(specific_md) > 0: # checking UUIDs and poping bad...
[ "def", "_check_filter_specific_md", "(", "self", ",", "specific_md", ":", "list", ")", ":", "if", "isinstance", "(", "specific_md", ",", "list", ")", ":", "if", "len", "(", "specific_md", ")", ">", "0", ":", "# checking UUIDs and poping bad ones", "for", "md",...
Check if specific_md parameter is valid. :param list specific_md: list of specific metadata UUID to check
[ "Check", "if", "specific_md", "parameter", "is", "valid", "." ]
57a604be92c7767b26abd247012cc1a584b386a0
https://github.com/isogeo/isogeo-api-py-minsdk/blob/57a604be92c7767b26abd247012cc1a584b386a0/isogeo_pysdk/checker.py#L352-L370
train
isogeo/isogeo-api-py-minsdk
isogeo_pysdk/checker.py
IsogeoChecker._check_filter_specific_tag
def _check_filter_specific_tag(self, specific_tag: list): """Check if specific_tag parameter is valid. :param list specific_tag: list of specific tag to check """ if isinstance(specific_tag, list): if len(specific_tag) > 0: specific_tag = ",".join(specific_ta...
python
def _check_filter_specific_tag(self, specific_tag: list): """Check if specific_tag parameter is valid. :param list specific_tag: list of specific tag to check """ if isinstance(specific_tag, list): if len(specific_tag) > 0: specific_tag = ",".join(specific_ta...
[ "def", "_check_filter_specific_tag", "(", "self", ",", "specific_tag", ":", "list", ")", ":", "if", "isinstance", "(", "specific_tag", ",", "list", ")", ":", "if", "len", "(", "specific_tag", ")", ">", "0", ":", "specific_tag", "=", "\",\"", ".", "join", ...
Check if specific_tag parameter is valid. :param list specific_tag: list of specific tag to check
[ "Check", "if", "specific_tag", "parameter", "is", "valid", "." ]
57a604be92c7767b26abd247012cc1a584b386a0
https://github.com/isogeo/isogeo-api-py-minsdk/blob/57a604be92c7767b26abd247012cc1a584b386a0/isogeo_pysdk/checker.py#L372-L384
train
isogeo/isogeo-api-py-minsdk
isogeo_pysdk/checker.py
IsogeoChecker._check_filter_includes
def _check_filter_includes(self, includes: list, resource: str = "metadata"): """Check if specific_resources parameter is valid. :param list includes: sub resources to check :param str resource: resource type to check sub resources. Must be one of: metadata | keyword. """ ...
python
def _check_filter_includes(self, includes: list, resource: str = "metadata"): """Check if specific_resources parameter is valid. :param list includes: sub resources to check :param str resource: resource type to check sub resources. Must be one of: metadata | keyword. """ ...
[ "def", "_check_filter_includes", "(", "self", ",", "includes", ":", "list", ",", "resource", ":", "str", "=", "\"metadata\"", ")", ":", "# check resource parameter", "if", "resource", "==", "\"metadata\"", ":", "ref_subresources", "=", "_SUBRESOURCES_MD", "elif", ...
Check if specific_resources parameter is valid. :param list includes: sub resources to check :param str resource: resource type to check sub resources. Must be one of: metadata | keyword.
[ "Check", "if", "specific_resources", "parameter", "is", "valid", "." ]
57a604be92c7767b26abd247012cc1a584b386a0
https://github.com/isogeo/isogeo-api-py-minsdk/blob/57a604be92c7767b26abd247012cc1a584b386a0/isogeo_pysdk/checker.py#L386-L411
train
isogeo/isogeo-api-py-minsdk
isogeo_pysdk/checker.py
IsogeoChecker._check_subresource
def _check_subresource(self, subresource: str): """Check if specific_resources parameter is valid. :param str resource: subresource to check. """ warnings.warn( "subresource in URL is deprecated." " Use _include mecanism instead.", DeprecationWarning, ) ...
python
def _check_subresource(self, subresource: str): """Check if specific_resources parameter is valid. :param str resource: subresource to check. """ warnings.warn( "subresource in URL is deprecated." " Use _include mecanism instead.", DeprecationWarning, ) ...
[ "def", "_check_subresource", "(", "self", ",", "subresource", ":", "str", ")", ":", "warnings", ".", "warn", "(", "\"subresource in URL is deprecated.\"", "\" Use _include mecanism instead.\"", ",", "DeprecationWarning", ",", ")", "l_subresources", "=", "(", "\"conditio...
Check if specific_resources parameter is valid. :param str resource: subresource to check.
[ "Check", "if", "specific_resources", "parameter", "is", "valid", "." ]
57a604be92c7767b26abd247012cc1a584b386a0
https://github.com/isogeo/isogeo-api-py-minsdk/blob/57a604be92c7767b26abd247012cc1a584b386a0/isogeo_pysdk/checker.py#L413-L460
train
isogeo/isogeo-api-py-minsdk
isogeo_pysdk/checker.py
IsogeoChecker._convert_md_type
def _convert_md_type(self, type_to_convert: str): """Metadata types are not consistent in Isogeo API. A vector dataset is defined as vector-dataset in query filter but as vectorDataset in resource (metadata) details. see: https://github.com/isogeo/isogeo-api-py-minsdk/issues/29 ...
python
def _convert_md_type(self, type_to_convert: str): """Metadata types are not consistent in Isogeo API. A vector dataset is defined as vector-dataset in query filter but as vectorDataset in resource (metadata) details. see: https://github.com/isogeo/isogeo-api-py-minsdk/issues/29 ...
[ "def", "_convert_md_type", "(", "self", ",", "type_to_convert", ":", "str", ")", ":", "if", "type_to_convert", "in", "FILTER_TYPES", ":", "return", "FILTER_TYPES", ".", "get", "(", "type_to_convert", ")", "elif", "type_to_convert", "in", "FILTER_TYPES", ".", "va...
Metadata types are not consistent in Isogeo API. A vector dataset is defined as vector-dataset in query filter but as vectorDataset in resource (metadata) details. see: https://github.com/isogeo/isogeo-api-py-minsdk/issues/29
[ "Metadata", "types", "are", "not", "consistent", "in", "Isogeo", "API", ".", "A", "vector", "dataset", "is", "defined", "as", "vector", "-", "dataset", "in", "query", "filter", "but", "as", "vectorDataset", "in", "resource", "(", "metadata", ")", "details", ...
57a604be92c7767b26abd247012cc1a584b386a0
https://github.com/isogeo/isogeo-api-py-minsdk/blob/57a604be92c7767b26abd247012cc1a584b386a0/isogeo_pysdk/checker.py#L462-L476
train
novopl/peltak
src/peltak/commands/version.py
version_cli
def version_cli(ctx, porcelain): # type: (click.Context, bool) -> None """ Show project version. Has sub commands. For this command to work you must specify where the project version is stored. You can do that with version_file conf variable. peltak supports multiple ways to store the project versi...
python
def version_cli(ctx, porcelain): # type: (click.Context, bool) -> None """ Show project version. Has sub commands. For this command to work you must specify where the project version is stored. You can do that with version_file conf variable. peltak supports multiple ways to store the project versi...
[ "def", "version_cli", "(", "ctx", ",", "porcelain", ")", ":", "# type: (click.Context, bool) -> None", "if", "ctx", ".", "invoked_subcommand", ":", "return", "from", "peltak", ".", "core", "import", "log", "from", "peltak", ".", "core", "import", "versioning", "...
Show project version. Has sub commands. For this command to work you must specify where the project version is stored. You can do that with version_file conf variable. peltak supports multiple ways to store the project version. Right now you can store it in a python file using built-in __version__ vari...
[ "Show", "project", "version", ".", "Has", "sub", "commands", "." ]
b627acc019e3665875fe76cdca0a14773b69beaa
https://github.com/novopl/peltak/blob/b627acc019e3665875fe76cdca0a14773b69beaa/src/peltak/commands/version.py#L25-L64
train
novopl/peltak
src/peltak/commands/version.py
bump_version
def bump_version(component='patch', exact=None): # type: (str, str) -> None """ Bump current project version without committing anything. No tags are created either. Examples: \b $ peltak version bump patch # Bump patch version component $ peltak version bump minor...
python
def bump_version(component='patch', exact=None): # type: (str, str) -> None """ Bump current project version without committing anything. No tags are created either. Examples: \b $ peltak version bump patch # Bump patch version component $ peltak version bump minor...
[ "def", "bump_version", "(", "component", "=", "'patch'", ",", "exact", "=", "None", ")", ":", "# type: (str, str) -> None", "from", "peltak", ".", "core", "import", "log", "from", "peltak", ".", "core", "import", "versioning", "old_ver", ",", "new_ver", "=", ...
Bump current project version without committing anything. No tags are created either. Examples: \b $ peltak version bump patch # Bump patch version component $ peltak version bump minor # Bump minor version component $ peltak version bump major ...
[ "Bump", "current", "project", "version", "without", "committing", "anything", "." ]
b627acc019e3665875fe76cdca0a14773b69beaa
https://github.com/novopl/peltak/blob/b627acc019e3665875fe76cdca0a14773b69beaa/src/peltak/commands/version.py#L76-L99
train
nathankw/pulsarpy
pulsarpy/models.py
Meta.get_logfile_name
def get_logfile_name(tag): """ Creates a name for a log file that is meant to be used in a call to ``logging.FileHandler``. The log file name will incldue the path to the log directory given by the `p.LOG_DIR` constant. The format of the file name is: 'log_$HOST_$TAG.txt', where ...
python
def get_logfile_name(tag): """ Creates a name for a log file that is meant to be used in a call to ``logging.FileHandler``. The log file name will incldue the path to the log directory given by the `p.LOG_DIR` constant. The format of the file name is: 'log_$HOST_$TAG.txt', where ...
[ "def", "get_logfile_name", "(", "tag", ")", ":", "if", "not", "os", ".", "path", ".", "exists", "(", "p", ".", "LOG_DIR", ")", ":", "os", ".", "mkdir", "(", "p", ".", "LOG_DIR", ")", "filename", "=", "\"log_\"", "+", "p", ".", "HOST", "+", "\"_\"...
Creates a name for a log file that is meant to be used in a call to ``logging.FileHandler``. The log file name will incldue the path to the log directory given by the `p.LOG_DIR` constant. The format of the file name is: 'log_$HOST_$TAG.txt', where $HOST is the hostname part of the URL given by...
[ "Creates", "a", "name", "for", "a", "log", "file", "that", "is", "meant", "to", "be", "used", "in", "a", "call", "to", "logging", ".", "FileHandler", ".", "The", "log", "file", "name", "will", "incldue", "the", "path", "to", "the", "log", "directory", ...
359b040c0f2383b88c0b5548715fefd35f5f634c
https://github.com/nathankw/pulsarpy/blob/359b040c0f2383b88c0b5548715fefd35f5f634c/pulsarpy/models.py#L114-L131
train
nathankw/pulsarpy
pulsarpy/models.py
Model._get
def _get(self, rec_id=None, upstream=None): """ Fetches a record by the record's ID or upstream_identifier. Raises: `pulsarpy.models.RecordNotFound`: A record could not be found. """ if rec_id: self.record_url = self.__class__.get_record_url(rec_id) ...
python
def _get(self, rec_id=None, upstream=None): """ Fetches a record by the record's ID or upstream_identifier. Raises: `pulsarpy.models.RecordNotFound`: A record could not be found. """ if rec_id: self.record_url = self.__class__.get_record_url(rec_id) ...
[ "def", "_get", "(", "self", ",", "rec_id", "=", "None", ",", "upstream", "=", "None", ")", ":", "if", "rec_id", ":", "self", ".", "record_url", "=", "self", ".", "__class__", ".", "get_record_url", "(", "rec_id", ")", "self", ".", "debug_logger", ".", ...
Fetches a record by the record's ID or upstream_identifier. Raises: `pulsarpy.models.RecordNotFound`: A record could not be found.
[ "Fetches", "a", "record", "by", "the", "record", "s", "ID", "or", "upstream_identifier", "." ]
359b040c0f2383b88c0b5548715fefd35f5f634c
https://github.com/nathankw/pulsarpy/blob/359b040c0f2383b88c0b5548715fefd35f5f634c/pulsarpy/models.py#L296-L315
train
nathankw/pulsarpy
pulsarpy/models.py
Model.replace_name_with_id
def replace_name_with_id(cls, name): """ Used to replace a foreign key reference using a name with an ID. Works by searching the record in Pulsar and expects to find exactly one hit. First, will check if the foreign key reference is an integer value and if so, returns that as it is presu...
python
def replace_name_with_id(cls, name): """ Used to replace a foreign key reference using a name with an ID. Works by searching the record in Pulsar and expects to find exactly one hit. First, will check if the foreign key reference is an integer value and if so, returns that as it is presu...
[ "def", "replace_name_with_id", "(", "cls", ",", "name", ")", ":", "try", ":", "int", "(", "name", ")", "return", "name", "#Already a presumed ID.", "except", "ValueError", ":", "pass", "#Not an int, so maybe a combination of MODEL_ABBR and Primary Key, i.e. B-8.", "if", ...
Used to replace a foreign key reference using a name with an ID. Works by searching the record in Pulsar and expects to find exactly one hit. First, will check if the foreign key reference is an integer value and if so, returns that as it is presumed to be the foreign key. Raises: `...
[ "Used", "to", "replace", "a", "foreign", "key", "reference", "using", "a", "name", "with", "an", "ID", ".", "Works", "by", "searching", "the", "record", "in", "Pulsar", "and", "expects", "to", "find", "exactly", "one", "hit", ".", "First", "will", "check...
359b040c0f2383b88c0b5548715fefd35f5f634c
https://github.com/nathankw/pulsarpy/blob/359b040c0f2383b88c0b5548715fefd35f5f634c/pulsarpy/models.py#L330-L354
train
nathankw/pulsarpy
pulsarpy/models.py
Model.add_model_name_to_payload
def add_model_name_to_payload(cls, payload): """ Checks whether the model name in question is in the payload. If not, the entire payload is set as a value of a key by the name of the model. This method is useful when some server-side Rails API calls expect the parameters to include the ...
python
def add_model_name_to_payload(cls, payload): """ Checks whether the model name in question is in the payload. If not, the entire payload is set as a value of a key by the name of the model. This method is useful when some server-side Rails API calls expect the parameters to include the ...
[ "def", "add_model_name_to_payload", "(", "cls", ",", "payload", ")", ":", "if", "not", "cls", ".", "MODEL_NAME", "in", "payload", ":", "payload", "=", "{", "cls", ".", "MODEL_NAME", ":", "payload", "}", "return", "payload" ]
Checks whether the model name in question is in the payload. If not, the entire payload is set as a value of a key by the name of the model. This method is useful when some server-side Rails API calls expect the parameters to include the parameterized model name. For example, server-side endpoi...
[ "Checks", "whether", "the", "model", "name", "in", "question", "is", "in", "the", "payload", ".", "If", "not", "the", "entire", "payload", "is", "set", "as", "a", "value", "of", "a", "key", "by", "the", "name", "of", "the", "model", ".", "This", "met...
359b040c0f2383b88c0b5548715fefd35f5f634c
https://github.com/nathankw/pulsarpy/blob/359b040c0f2383b88c0b5548715fefd35f5f634c/pulsarpy/models.py#L358-L381
train
nathankw/pulsarpy
pulsarpy/models.py
Model.delete
def delete(self): """Deletes the record. """ res = requests.delete(url=self.record_url, headers=HEADERS, verify=False) #self.write_response_html_to_file(res,"bob_delete.html") if res.status_code == 204: #No content. Can't render json: return {} ret...
python
def delete(self): """Deletes the record. """ res = requests.delete(url=self.record_url, headers=HEADERS, verify=False) #self.write_response_html_to_file(res,"bob_delete.html") if res.status_code == 204: #No content. Can't render json: return {} ret...
[ "def", "delete", "(", "self", ")", ":", "res", "=", "requests", ".", "delete", "(", "url", "=", "self", ".", "record_url", ",", "headers", "=", "HEADERS", ",", "verify", "=", "False", ")", "#self.write_response_html_to_file(res,\"bob_delete.html\")", "if", "re...
Deletes the record.
[ "Deletes", "the", "record", "." ]
359b040c0f2383b88c0b5548715fefd35f5f634c
https://github.com/nathankw/pulsarpy/blob/359b040c0f2383b88c0b5548715fefd35f5f634c/pulsarpy/models.py#L413-L421
train
nathankw/pulsarpy
pulsarpy/models.py
Model.find_by
def find_by(cls, payload, require=False): """ Searches the model in question by AND joining the query parameters. Implements a Railsy way of looking for a record using a method by the same name and passing in the query as a dict. as well. Only the first hit is returned, and there is no ...
python
def find_by(cls, payload, require=False): """ Searches the model in question by AND joining the query parameters. Implements a Railsy way of looking for a record using a method by the same name and passing in the query as a dict. as well. Only the first hit is returned, and there is no ...
[ "def", "find_by", "(", "cls", ",", "payload", ",", "require", "=", "False", ")", ":", "if", "not", "isinstance", "(", "payload", ",", "dict", ")", ":", "raise", "ValueError", "(", "\"The 'payload' parameter must be provided a dictionary object.\"", ")", "url", "...
Searches the model in question by AND joining the query parameters. Implements a Railsy way of looking for a record using a method by the same name and passing in the query as a dict. as well. Only the first hit is returned, and there is no particular ordering specified in the server-side API m...
[ "Searches", "the", "model", "in", "question", "by", "AND", "joining", "the", "query", "parameters", "." ]
359b040c0f2383b88c0b5548715fefd35f5f634c
https://github.com/nathankw/pulsarpy/blob/359b040c0f2383b88c0b5548715fefd35f5f634c/pulsarpy/models.py#L424-L463
train
nathankw/pulsarpy
pulsarpy/models.py
Model.find_by_or
def find_by_or(cls, payload): """ Searches the model in question by OR joining the query parameters. Implements a Railsy way of looking for a record using a method by the same name and passing in the query as a string (for the OR operator joining to be specified). Only the firs...
python
def find_by_or(cls, payload): """ Searches the model in question by OR joining the query parameters. Implements a Railsy way of looking for a record using a method by the same name and passing in the query as a string (for the OR operator joining to be specified). Only the firs...
[ "def", "find_by_or", "(", "cls", ",", "payload", ")", ":", "if", "not", "isinstance", "(", "payload", ",", "dict", ")", ":", "raise", "ValueError", "(", "\"The 'payload' parameter must be provided a dictionary object.\"", ")", "url", "=", "os", ".", "path", ".",...
Searches the model in question by OR joining the query parameters. Implements a Railsy way of looking for a record using a method by the same name and passing in the query as a string (for the OR operator joining to be specified). Only the first hit is returned, and there is not particular ord...
[ "Searches", "the", "model", "in", "question", "by", "OR", "joining", "the", "query", "parameters", "." ]
359b040c0f2383b88c0b5548715fefd35f5f634c
https://github.com/nathankw/pulsarpy/blob/359b040c0f2383b88c0b5548715fefd35f5f634c/pulsarpy/models.py#L466-L497
train
nathankw/pulsarpy
pulsarpy/models.py
Model.index
def index(cls): """Fetches all records. Returns: `dict`. The JSON formatted response. Raises: `requests.exceptions.HTTPError`: The status code is not ok. """ res = requests.get(cls.URL, headers=HEADERS, verify=False) res.raise_for_status() ...
python
def index(cls): """Fetches all records. Returns: `dict`. The JSON formatted response. Raises: `requests.exceptions.HTTPError`: The status code is not ok. """ res = requests.get(cls.URL, headers=HEADERS, verify=False) res.raise_for_status() ...
[ "def", "index", "(", "cls", ")", ":", "res", "=", "requests", ".", "get", "(", "cls", ".", "URL", ",", "headers", "=", "HEADERS", ",", "verify", "=", "False", ")", "res", ".", "raise_for_status", "(", ")", "return", "res", ".", "json", "(", ")" ]
Fetches all records. Returns: `dict`. The JSON formatted response. Raises: `requests.exceptions.HTTPError`: The status code is not ok.
[ "Fetches", "all", "records", "." ]
359b040c0f2383b88c0b5548715fefd35f5f634c
https://github.com/nathankw/pulsarpy/blob/359b040c0f2383b88c0b5548715fefd35f5f634c/pulsarpy/models.py#L500-L511
train
nathankw/pulsarpy
pulsarpy/models.py
Model.patch
def patch(self, payload, append_to_arrays=True): """ Patches current record and udpates the current instance's 'attrs' attribute to reflect the new changes. Args: payload - hash. This will be JSON-formatted prior to sending the request. Returns: `dict`. ...
python
def patch(self, payload, append_to_arrays=True): """ Patches current record and udpates the current instance's 'attrs' attribute to reflect the new changes. Args: payload - hash. This will be JSON-formatted prior to sending the request. Returns: `dict`. ...
[ "def", "patch", "(", "self", ",", "payload", ",", "append_to_arrays", "=", "True", ")", ":", "if", "not", "isinstance", "(", "payload", ",", "dict", ")", ":", "raise", "ValueError", "(", "\"The 'payload' parameter must be provided a dictionary object.\"", ")", "pa...
Patches current record and udpates the current instance's 'attrs' attribute to reflect the new changes. Args: payload - hash. This will be JSON-formatted prior to sending the request. Returns: `dict`. The JSON formatted response. Raises: `requests.e...
[ "Patches", "current", "record", "and", "udpates", "the", "current", "instance", "s", "attrs", "attribute", "to", "reflect", "the", "new", "changes", "." ]
359b040c0f2383b88c0b5548715fefd35f5f634c
https://github.com/nathankw/pulsarpy/blob/359b040c0f2383b88c0b5548715fefd35f5f634c/pulsarpy/models.py#L513-L545
train
nathankw/pulsarpy
pulsarpy/models.py
Model.set_id_in_fkeys
def set_id_in_fkeys(cls, payload): """ Looks for any keys in the payload that end with either _id or _ids, signaling a foreign key field. For each foreign key field, checks whether the value is using the name of the record or the actual primary ID of the record (which may include the mod...
python
def set_id_in_fkeys(cls, payload): """ Looks for any keys in the payload that end with either _id or _ids, signaling a foreign key field. For each foreign key field, checks whether the value is using the name of the record or the actual primary ID of the record (which may include the mod...
[ "def", "set_id_in_fkeys", "(", "cls", ",", "payload", ")", ":", "for", "key", "in", "payload", ":", "val", "=", "payload", "[", "key", "]", "if", "not", "val", ":", "continue", "if", "key", ".", "endswith", "(", "\"_id\"", ")", ":", "model", "=", "...
Looks for any keys in the payload that end with either _id or _ids, signaling a foreign key field. For each foreign key field, checks whether the value is using the name of the record or the actual primary ID of the record (which may include the model abbreviation, i.e. B-1). If the former case,...
[ "Looks", "for", "any", "keys", "in", "the", "payload", "that", "end", "with", "either", "_id", "or", "_ids", "signaling", "a", "foreign", "key", "field", ".", "For", "each", "foreign", "key", "field", "checks", "whether", "the", "value", "is", "using", "...
359b040c0f2383b88c0b5548715fefd35f5f634c
https://github.com/nathankw/pulsarpy/blob/359b040c0f2383b88c0b5548715fefd35f5f634c/pulsarpy/models.py#L548-L577
train
nathankw/pulsarpy
pulsarpy/models.py
Model.post
def post(cls, payload): """Posts the data to the specified record. Args: payload: `dict`. This will be JSON-formatted prior to sending the request. Returns: `dict`. The JSON formatted response. Raises: `Requests.exceptions.HTTPError`: The status cod...
python
def post(cls, payload): """Posts the data to the specified record. Args: payload: `dict`. This will be JSON-formatted prior to sending the request. Returns: `dict`. The JSON formatted response. Raises: `Requests.exceptions.HTTPError`: The status cod...
[ "def", "post", "(", "cls", ",", "payload", ")", ":", "if", "not", "isinstance", "(", "payload", ",", "dict", ")", ":", "raise", "ValueError", "(", "\"The 'payload' parameter must be provided a dictionary object.\"", ")", "payload", "=", "cls", ".", "set_id_in_fkey...
Posts the data to the specified record. Args: payload: `dict`. This will be JSON-formatted prior to sending the request. Returns: `dict`. The JSON formatted response. Raises: `Requests.exceptions.HTTPError`: The status code is not ok. `RecordNot...
[ "Posts", "the", "data", "to", "the", "specified", "record", "." ]
359b040c0f2383b88c0b5548715fefd35f5f634c
https://github.com/nathankw/pulsarpy/blob/359b040c0f2383b88c0b5548715fefd35f5f634c/pulsarpy/models.py#L585-L619
train
nathankw/pulsarpy
pulsarpy/models.py
Model.log_error
def log_error(cls, msg): """ Logs the provided error message to both the error logger and the debug logger logging instances. Args: msg: `str`. The error message to log. """ cls.error_logger.error(msg) cls.debug_logger.debug(msg)
python
def log_error(cls, msg): """ Logs the provided error message to both the error logger and the debug logger logging instances. Args: msg: `str`. The error message to log. """ cls.error_logger.error(msg) cls.debug_logger.debug(msg)
[ "def", "log_error", "(", "cls", ",", "msg", ")", ":", "cls", ".", "error_logger", ".", "error", "(", "msg", ")", "cls", ".", "debug_logger", ".", "debug", "(", "msg", ")" ]
Logs the provided error message to both the error logger and the debug logger logging instances. Args: msg: `str`. The error message to log.
[ "Logs", "the", "provided", "error", "message", "to", "both", "the", "error", "logger", "and", "the", "debug", "logger", "logging", "instances", "." ]
359b040c0f2383b88c0b5548715fefd35f5f634c
https://github.com/nathankw/pulsarpy/blob/359b040c0f2383b88c0b5548715fefd35f5f634c/pulsarpy/models.py#L622-L631
train
nathankw/pulsarpy
pulsarpy/models.py
Model.write_response_html_to_file
def write_response_html_to_file(response,filename): """ An aid in troubleshooting internal application errors, i.e. <Response [500]>, to be mainly beneficial when developing the server-side API. This method will write the response HTML for viewing the error details in the browesr. ...
python
def write_response_html_to_file(response,filename): """ An aid in troubleshooting internal application errors, i.e. <Response [500]>, to be mainly beneficial when developing the server-side API. This method will write the response HTML for viewing the error details in the browesr. ...
[ "def", "write_response_html_to_file", "(", "response", ",", "filename", ")", ":", "fout", "=", "open", "(", "filename", ",", "'w'", ")", "if", "not", "str", "(", "response", ".", "status_code", ")", ".", "startswith", "(", "\"2\"", ")", ":", "Model", "."...
An aid in troubleshooting internal application errors, i.e. <Response [500]>, to be mainly beneficial when developing the server-side API. This method will write the response HTML for viewing the error details in the browesr. Args: response: `requests.models.Response` instance. ...
[ "An", "aid", "in", "troubleshooting", "internal", "application", "errors", "i", ".", "e", ".", "<Response", "[", "500", "]", ">", "to", "be", "mainly", "beneficial", "when", "developing", "the", "server", "-", "side", "API", ".", "This", "method", "will", ...
359b040c0f2383b88c0b5548715fefd35f5f634c
https://github.com/nathankw/pulsarpy/blob/359b040c0f2383b88c0b5548715fefd35f5f634c/pulsarpy/models.py#L634-L648
train
nathankw/pulsarpy
pulsarpy/models.py
Biosample.parent_ids
def parent_ids(self): """ Returns an array of parent Biosample IDs. If the current Biosample has a part_of relationship, the Biosampled referenced there will be returned. Otherwise, if the current Biosample was generated from a pool of Biosamples (pooled_from_biosample_ids), then those w...
python
def parent_ids(self): """ Returns an array of parent Biosample IDs. If the current Biosample has a part_of relationship, the Biosampled referenced there will be returned. Otherwise, if the current Biosample was generated from a pool of Biosamples (pooled_from_biosample_ids), then those w...
[ "def", "parent_ids", "(", "self", ")", ":", "action", "=", "os", ".", "path", ".", "join", "(", "self", ".", "record_url", ",", "\"parent_ids\"", ")", "res", "=", "requests", ".", "get", "(", "url", "=", "action", ",", "headers", "=", "HEADERS", ",",...
Returns an array of parent Biosample IDs. If the current Biosample has a part_of relationship, the Biosampled referenced there will be returned. Otherwise, if the current Biosample was generated from a pool of Biosamples (pooled_from_biosample_ids), then those will be returned. Otherwise, the re...
[ "Returns", "an", "array", "of", "parent", "Biosample", "IDs", ".", "If", "the", "current", "Biosample", "has", "a", "part_of", "relationship", "the", "Biosampled", "referenced", "there", "will", "be", "returned", ".", "Otherwise", "if", "the", "current", "Bios...
359b040c0f2383b88c0b5548715fefd35f5f634c
https://github.com/nathankw/pulsarpy/blob/359b040c0f2383b88c0b5548715fefd35f5f634c/pulsarpy/models.py#L696-L706
train
nathankw/pulsarpy
pulsarpy/models.py
Biosample.find_first_wt_parent
def find_first_wt_parent(self, with_ip=False): """ Recursively looks at the part_of parent ancestry line (ignoring pooled_from parents) and returns a parent Biosample ID if its wild_type attribute is True. Args: with_ip: `bool`. True means to restrict the search to the firs...
python
def find_first_wt_parent(self, with_ip=False): """ Recursively looks at the part_of parent ancestry line (ignoring pooled_from parents) and returns a parent Biosample ID if its wild_type attribute is True. Args: with_ip: `bool`. True means to restrict the search to the firs...
[ "def", "find_first_wt_parent", "(", "self", ",", "with_ip", "=", "False", ")", ":", "parent_id", "=", "self", ".", "part_of_id", "if", "not", "parent_id", ":", "return", "False", "parent", "=", "Biosample", "(", "parent_id", ")", "if", "parent", ".", "wild...
Recursively looks at the part_of parent ancestry line (ignoring pooled_from parents) and returns a parent Biosample ID if its wild_type attribute is True. Args: with_ip: `bool`. True means to restrict the search to the first parental Wild Type that also has an Immunoblot l...
[ "Recursively", "looks", "at", "the", "part_of", "parent", "ancestry", "line", "(", "ignoring", "pooled_from", "parents", ")", "and", "returns", "a", "parent", "Biosample", "ID", "if", "its", "wild_type", "attribute", "is", "True", "." ]
359b040c0f2383b88c0b5548715fefd35f5f634c
https://github.com/nathankw/pulsarpy/blob/359b040c0f2383b88c0b5548715fefd35f5f634c/pulsarpy/models.py#L708-L734
train
nathankw/pulsarpy
pulsarpy/models.py
Document.upload
def upload(cls, path, document_type, is_protocol, description=""): """ Args: path: `str`. The path to the document to upload. document_type: `str`. DocumentType identified by the value of its name attribute. is_protocol: `bool`. description: `str`. ...
python
def upload(cls, path, document_type, is_protocol, description=""): """ Args: path: `str`. The path to the document to upload. document_type: `str`. DocumentType identified by the value of its name attribute. is_protocol: `bool`. description: `str`. ...
[ "def", "upload", "(", "cls", ",", "path", ",", "document_type", ",", "is_protocol", ",", "description", "=", "\"\"", ")", ":", "file_name", "=", "os", ".", "path", ".", "basename", "(", "path", ")", "mime_type", "=", "mimetypes", ".", "guess_type", "(", ...
Args: path: `str`. The path to the document to upload. document_type: `str`. DocumentType identified by the value of its name attribute. is_protocol: `bool`. description: `str`.
[ "Args", ":", "path", ":", "str", ".", "The", "path", "to", "the", "document", "to", "upload", ".", "document_type", ":", "str", ".", "DocumentType", "identified", "by", "the", "value", "of", "its", "name", "attribute", ".", "is_protocol", ":", "bool", "....
359b040c0f2383b88c0b5548715fefd35f5f634c
https://github.com/nathankw/pulsarpy/blob/359b040c0f2383b88c0b5548715fefd35f5f634c/pulsarpy/models.py#L838-L858
train