repo stringlengths 7 55 | path stringlengths 4 127 | func_name stringlengths 1 88 | original_string stringlengths 75 19.8k | language stringclasses 1
value | code stringlengths 75 19.8k | code_tokens list | docstring stringlengths 3 17.3k | docstring_tokens list | sha stringlengths 40 40 | url stringlengths 87 242 | partition stringclasses 1
value |
|---|---|---|---|---|---|---|---|---|---|---|---|
unixsurfer/anycast_healthchecker | anycast_healthchecker/utils.py | valid_ip_prefix | def valid_ip_prefix(ip_prefix):
"""Perform a sanity check on ip_prefix.
Arguments:
ip_prefix (str): The IP-Prefix to validate
Returns:
True if ip_prefix is a valid IPv4 address with prefix length 32 or a
valid IPv6 address with prefix length 128, otherwise False
"""
try:
... | python | def valid_ip_prefix(ip_prefix):
"""Perform a sanity check on ip_prefix.
Arguments:
ip_prefix (str): The IP-Prefix to validate
Returns:
True if ip_prefix is a valid IPv4 address with prefix length 32 or a
valid IPv6 address with prefix length 128, otherwise False
"""
try:
... | [
"def",
"valid_ip_prefix",
"(",
"ip_prefix",
")",
":",
"try",
":",
"ip_prefix",
"=",
"ipaddress",
".",
"ip_network",
"(",
"ip_prefix",
")",
"except",
"ValueError",
":",
"return",
"False",
"else",
":",
"if",
"ip_prefix",
".",
"version",
"==",
"4",
"and",
"ip... | Perform a sanity check on ip_prefix.
Arguments:
ip_prefix (str): The IP-Prefix to validate
Returns:
True if ip_prefix is a valid IPv4 address with prefix length 32 or a
valid IPv6 address with prefix length 128, otherwise False | [
"Perform",
"a",
"sanity",
"check",
"on",
"ip_prefix",
"."
] | 3ab9c1d65d550eb30621ced2434252f61d1fdd33 | https://github.com/unixsurfer/anycast_healthchecker/blob/3ab9c1d65d550eb30621ced2434252f61d1fdd33/anycast_healthchecker/utils.py#L82-L102 | train |
unixsurfer/anycast_healthchecker | anycast_healthchecker/utils.py | get_ip_prefixes_from_config | def get_ip_prefixes_from_config(config, services, ip_version):
"""Build a set of IP prefixes found in service configuration files.
Arguments:
config (obg): A configparser object which holds our configuration.
services (list): A list of section names which are the name of the
service che... | python | def get_ip_prefixes_from_config(config, services, ip_version):
"""Build a set of IP prefixes found in service configuration files.
Arguments:
config (obg): A configparser object which holds our configuration.
services (list): A list of section names which are the name of the
service che... | [
"def",
"get_ip_prefixes_from_config",
"(",
"config",
",",
"services",
",",
"ip_version",
")",
":",
"ip_prefixes",
"=",
"set",
"(",
")",
"for",
"service",
"in",
"services",
":",
"ip_prefix",
"=",
"ipaddress",
".",
"ip_network",
"(",
"config",
".",
"get",
"(",... | Build a set of IP prefixes found in service configuration files.
Arguments:
config (obg): A configparser object which holds our configuration.
services (list): A list of section names which are the name of the
service checks.
ip_version (int): IP protocol version
Returns:
... | [
"Build",
"a",
"set",
"of",
"IP",
"prefixes",
"found",
"in",
"service",
"configuration",
"files",
"."
] | 3ab9c1d65d550eb30621ced2434252f61d1fdd33 | https://github.com/unixsurfer/anycast_healthchecker/blob/3ab9c1d65d550eb30621ced2434252f61d1fdd33/anycast_healthchecker/utils.py#L125-L145 | train |
unixsurfer/anycast_healthchecker | anycast_healthchecker/utils.py | ip_prefixes_sanity_check | def ip_prefixes_sanity_check(config, bird_configuration):
"""Sanity check on IP prefixes.
Arguments:
config (obg): A configparser object which holds our configuration.
bird_configuration (dict): A dictionary, which holds Bird configuration
per IP protocol version.
"""
for ip_ve... | python | def ip_prefixes_sanity_check(config, bird_configuration):
"""Sanity check on IP prefixes.
Arguments:
config (obg): A configparser object which holds our configuration.
bird_configuration (dict): A dictionary, which holds Bird configuration
per IP protocol version.
"""
for ip_ve... | [
"def",
"ip_prefixes_sanity_check",
"(",
"config",
",",
"bird_configuration",
")",
":",
"for",
"ip_version",
"in",
"bird_configuration",
":",
"modify_ip_prefixes",
"(",
"config",
",",
"bird_configuration",
"[",
"ip_version",
"]",
"[",
"'config_file'",
"]",
",",
"bird... | Sanity check on IP prefixes.
Arguments:
config (obg): A configparser object which holds our configuration.
bird_configuration (dict): A dictionary, which holds Bird configuration
per IP protocol version. | [
"Sanity",
"check",
"on",
"IP",
"prefixes",
"."
] | 3ab9c1d65d550eb30621ced2434252f61d1fdd33 | https://github.com/unixsurfer/anycast_healthchecker/blob/3ab9c1d65d550eb30621ced2434252f61d1fdd33/anycast_healthchecker/utils.py#L148-L165 | train |
unixsurfer/anycast_healthchecker | anycast_healthchecker/utils.py | modify_ip_prefixes | def modify_ip_prefixes(
config,
config_file,
variable_name,
dummy_ip_prefix,
reconfigure_cmd,
keep_changes,
changes_counter,
ip_version):
"""Modify IP prefixes in Bird configuration.
Depending on the configuration either removes or reports IP pref... | python | def modify_ip_prefixes(
config,
config_file,
variable_name,
dummy_ip_prefix,
reconfigure_cmd,
keep_changes,
changes_counter,
ip_version):
"""Modify IP prefixes in Bird configuration.
Depending on the configuration either removes or reports IP pref... | [
"def",
"modify_ip_prefixes",
"(",
"config",
",",
"config_file",
",",
"variable_name",
",",
"dummy_ip_prefix",
",",
"reconfigure_cmd",
",",
"keep_changes",
",",
"changes_counter",
",",
"ip_version",
")",
":",
"log",
"=",
"logging",
".",
"getLogger",
"(",
"PROGRAM_N... | Modify IP prefixes in Bird configuration.
Depending on the configuration either removes or reports IP prefixes found
in Bird configuration for which we don't have a service check associated
with them. Moreover, it adds the dummy IP prefix if it isn't present and
ensures that the correct variable name i... | [
"Modify",
"IP",
"prefixes",
"in",
"Bird",
"configuration",
"."
] | 3ab9c1d65d550eb30621ced2434252f61d1fdd33 | https://github.com/unixsurfer/anycast_healthchecker/blob/3ab9c1d65d550eb30621ced2434252f61d1fdd33/anycast_healthchecker/utils.py#L168-L268 | train |
unixsurfer/anycast_healthchecker | anycast_healthchecker/utils.py | load_configuration | def load_configuration(config_file, config_dir, service_file):
"""Build configuration objects.
If all sanity checks against daemon and service check settings are passed
then it builds a ConfigParser object which holds all our configuration
and a dictionary data structure which holds Bird configuration ... | python | def load_configuration(config_file, config_dir, service_file):
"""Build configuration objects.
If all sanity checks against daemon and service check settings are passed
then it builds a ConfigParser object which holds all our configuration
and a dictionary data structure which holds Bird configuration ... | [
"def",
"load_configuration",
"(",
"config_file",
",",
"config_dir",
",",
"service_file",
")",
":",
"config_files",
"=",
"[",
"config_file",
"]",
"config",
"=",
"configparser",
".",
"ConfigParser",
"(",
")",
"config",
".",
"read_dict",
"(",
"DEFAULT_OPTIONS",
")"... | Build configuration objects.
If all sanity checks against daemon and service check settings are passed
then it builds a ConfigParser object which holds all our configuration
and a dictionary data structure which holds Bird configuration per IP
protocol version.
Arguments:
config_file (str)... | [
"Build",
"configuration",
"objects",
"."
] | 3ab9c1d65d550eb30621ced2434252f61d1fdd33 | https://github.com/unixsurfer/anycast_healthchecker/blob/3ab9c1d65d550eb30621ced2434252f61d1fdd33/anycast_healthchecker/utils.py#L271-L323 | train |
unixsurfer/anycast_healthchecker | anycast_healthchecker/utils.py | configuration_check | def configuration_check(config):
"""Perform a sanity check on configuration.
First it performs a sanity check against settings for daemon
and then against settings for each service check.
Arguments:
config (obj): A configparser object which holds our configuration.
Returns:
None i... | python | def configuration_check(config):
"""Perform a sanity check on configuration.
First it performs a sanity check against settings for daemon
and then against settings for each service check.
Arguments:
config (obj): A configparser object which holds our configuration.
Returns:
None i... | [
"def",
"configuration_check",
"(",
"config",
")",
":",
"log_level",
"=",
"config",
".",
"get",
"(",
"'daemon'",
",",
"'loglevel'",
")",
"num_level",
"=",
"getattr",
"(",
"logging",
",",
"log_level",
".",
"upper",
"(",
")",
",",
"None",
")",
"pidfile",
"=... | Perform a sanity check on configuration.
First it performs a sanity check against settings for daemon
and then against settings for each service check.
Arguments:
config (obj): A configparser object which holds our configuration.
Returns:
None if all checks are successfully passed oth... | [
"Perform",
"a",
"sanity",
"check",
"on",
"configuration",
"."
] | 3ab9c1d65d550eb30621ced2434252f61d1fdd33 | https://github.com/unixsurfer/anycast_healthchecker/blob/3ab9c1d65d550eb30621ced2434252f61d1fdd33/anycast_healthchecker/utils.py#L326-L372 | train |
unixsurfer/anycast_healthchecker | anycast_healthchecker/utils.py | build_bird_configuration | def build_bird_configuration(config):
"""Build bird configuration structure.
First it performs a sanity check against bird settings and then builds a
dictionary structure with bird configuration per IP version.
Arguments:
config (obj): A configparser object which holds our configuration.
... | python | def build_bird_configuration(config):
"""Build bird configuration structure.
First it performs a sanity check against bird settings and then builds a
dictionary structure with bird configuration per IP version.
Arguments:
config (obj): A configparser object which holds our configuration.
... | [
"def",
"build_bird_configuration",
"(",
"config",
")",
":",
"bird_configuration",
"=",
"{",
"}",
"if",
"config",
".",
"getboolean",
"(",
"'daemon'",
",",
"'ipv4'",
")",
":",
"if",
"os",
".",
"path",
".",
"islink",
"(",
"config",
".",
"get",
"(",
"'daemon... | Build bird configuration structure.
First it performs a sanity check against bird settings and then builds a
dictionary structure with bird configuration per IP version.
Arguments:
config (obj): A configparser object which holds our configuration.
Returns:
A dictionary
Raises:
... | [
"Build",
"bird",
"configuration",
"structure",
"."
] | 3ab9c1d65d550eb30621ced2434252f61d1fdd33 | https://github.com/unixsurfer/anycast_healthchecker/blob/3ab9c1d65d550eb30621ced2434252f61d1fdd33/anycast_healthchecker/utils.py#L457-L519 | train |
unixsurfer/anycast_healthchecker | anycast_healthchecker/utils.py | get_variable_name_from_bird | def get_variable_name_from_bird(bird_conf):
"""Return the variable name set in Bird configuration.
The variable name in Bird configuration is set with the keyword 'define',
here is an example:
define ACAST_PS_ADVERTISE =
and we exract the string between the word 'define' and the equals sign.
... | python | def get_variable_name_from_bird(bird_conf):
"""Return the variable name set in Bird configuration.
The variable name in Bird configuration is set with the keyword 'define',
here is an example:
define ACAST_PS_ADVERTISE =
and we exract the string between the word 'define' and the equals sign.
... | [
"def",
"get_variable_name_from_bird",
"(",
"bird_conf",
")",
":",
"bird_variable_pattern",
"=",
"re",
".",
"compile",
"(",
"r",
",",
"re",
".",
"VERBOSE",
")",
"with",
"open",
"(",
"bird_conf",
",",
"'r'",
")",
"as",
"content",
":",
"for",
"line",
"in",
... | Return the variable name set in Bird configuration.
The variable name in Bird configuration is set with the keyword 'define',
here is an example:
define ACAST_PS_ADVERTISE =
and we exract the string between the word 'define' and the equals sign.
Arguments:
bird_conf (str): The absolu... | [
"Return",
"the",
"variable",
"name",
"set",
"in",
"Bird",
"configuration",
"."
] | 3ab9c1d65d550eb30621ced2434252f61d1fdd33 | https://github.com/unixsurfer/anycast_healthchecker/blob/3ab9c1d65d550eb30621ced2434252f61d1fdd33/anycast_healthchecker/utils.py#L522-L555 | train |
unixsurfer/anycast_healthchecker | anycast_healthchecker/utils.py | create_bird_config_files | def create_bird_config_files(bird_configuration):
"""Create bird configuration files per IP version.
Creates bird configuration files if they don't exist. It also creates the
directories where we store the history of changes, if this functionality is
enabled.
Arguments:
bird_configuration ... | python | def create_bird_config_files(bird_configuration):
"""Create bird configuration files per IP version.
Creates bird configuration files if they don't exist. It also creates the
directories where we store the history of changes, if this functionality is
enabled.
Arguments:
bird_configuration ... | [
"def",
"create_bird_config_files",
"(",
"bird_configuration",
")",
":",
"for",
"ip_version",
"in",
"bird_configuration",
":",
"config_file",
"=",
"bird_configuration",
"[",
"ip_version",
"]",
"[",
"'config_file'",
"]",
"try",
":",
"touch",
"(",
"config_file",
")",
... | Create bird configuration files per IP version.
Creates bird configuration files if they don't exist. It also creates the
directories where we store the history of changes, if this functionality is
enabled.
Arguments:
bird_configuration (dict): A dictionary with settings for bird.
Returns... | [
"Create",
"bird",
"configuration",
"files",
"per",
"IP",
"version",
"."
] | 3ab9c1d65d550eb30621ced2434252f61d1fdd33 | https://github.com/unixsurfer/anycast_healthchecker/blob/3ab9c1d65d550eb30621ced2434252f61d1fdd33/anycast_healthchecker/utils.py#L558-L595 | train |
unixsurfer/anycast_healthchecker | anycast_healthchecker/utils.py | running | def running(processid):
"""Check the validity of a process ID.
Arguments:
processid (int): Process ID number.
Returns:
True if process ID is found otherwise False.
"""
try:
# From kill(2)
# If sig is 0 (the null signal), error checking is performed but no
... | python | def running(processid):
"""Check the validity of a process ID.
Arguments:
processid (int): Process ID number.
Returns:
True if process ID is found otherwise False.
"""
try:
# From kill(2)
# If sig is 0 (the null signal), error checking is performed but no
... | [
"def",
"running",
"(",
"processid",
")",
":",
"try",
":",
"os",
".",
"kill",
"(",
"processid",
",",
"0",
")",
"except",
"OverflowError",
"as",
"exc",
":",
"print",
"(",
"\"checking validity of pid ({p}) failed with: {e}\"",
".",
"format",
"(",
"p",
"=",
"pro... | Check the validity of a process ID.
Arguments:
processid (int): Process ID number.
Returns:
True if process ID is found otherwise False. | [
"Check",
"the",
"validity",
"of",
"a",
"process",
"ID",
"."
] | 3ab9c1d65d550eb30621ced2434252f61d1fdd33 | https://github.com/unixsurfer/anycast_healthchecker/blob/3ab9c1d65d550eb30621ced2434252f61d1fdd33/anycast_healthchecker/utils.py#L598-L621 | train |
unixsurfer/anycast_healthchecker | anycast_healthchecker/utils.py | get_ip_prefixes_from_bird | def get_ip_prefixes_from_bird(filename):
"""Build a list of IP prefixes found in Bird configuration.
Arguments:
filename (str): The absolute path of the Bird configuration file.
Notes:
It can only parse a file with the following format
define ACAST_PS_ADVERTISE =
... | python | def get_ip_prefixes_from_bird(filename):
"""Build a list of IP prefixes found in Bird configuration.
Arguments:
filename (str): The absolute path of the Bird configuration file.
Notes:
It can only parse a file with the following format
define ACAST_PS_ADVERTISE =
... | [
"def",
"get_ip_prefixes_from_bird",
"(",
"filename",
")",
":",
"prefixes",
"=",
"[",
"]",
"with",
"open",
"(",
"filename",
",",
"'r'",
")",
"as",
"bird_conf",
":",
"lines",
"=",
"bird_conf",
".",
"read",
"(",
")",
"for",
"line",
"in",
"lines",
".",
"sp... | Build a list of IP prefixes found in Bird configuration.
Arguments:
filename (str): The absolute path of the Bird configuration file.
Notes:
It can only parse a file with the following format
define ACAST_PS_ADVERTISE =
[
10.189.200.155/32,
... | [
"Build",
"a",
"list",
"of",
"IP",
"prefixes",
"found",
"in",
"Bird",
"configuration",
"."
] | 3ab9c1d65d550eb30621ced2434252f61d1fdd33 | https://github.com/unixsurfer/anycast_healthchecker/blob/3ab9c1d65d550eb30621ced2434252f61d1fdd33/anycast_healthchecker/utils.py#L624-L652 | train |
unixsurfer/anycast_healthchecker | anycast_healthchecker/utils.py | reconfigure_bird | def reconfigure_bird(cmd):
"""Reconfigure BIRD daemon.
Arguments:
cmd (string): A command to trigger a reconfiguration of Bird daemon
Notes:
Runs 'birdc configure' to reconfigure BIRD. Some useful information on
how birdc tool works:
-- Returns a non-zero exit code only... | python | def reconfigure_bird(cmd):
"""Reconfigure BIRD daemon.
Arguments:
cmd (string): A command to trigger a reconfiguration of Bird daemon
Notes:
Runs 'birdc configure' to reconfigure BIRD. Some useful information on
how birdc tool works:
-- Returns a non-zero exit code only... | [
"def",
"reconfigure_bird",
"(",
"cmd",
")",
":",
"log",
"=",
"logging",
".",
"getLogger",
"(",
"PROGRAM_NAME",
")",
"cmd",
"=",
"shlex",
".",
"split",
"(",
"cmd",
")",
"log",
".",
"info",
"(",
"\"reconfiguring BIRD by running %s\"",
",",
"' '",
".",
"join"... | Reconfigure BIRD daemon.
Arguments:
cmd (string): A command to trigger a reconfiguration of Bird daemon
Notes:
Runs 'birdc configure' to reconfigure BIRD. Some useful information on
how birdc tool works:
-- Returns a non-zero exit code only when it can't access BIRD
... | [
"Reconfigure",
"BIRD",
"daemon",
"."
] | 3ab9c1d65d550eb30621ced2434252f61d1fdd33 | https://github.com/unixsurfer/anycast_healthchecker/blob/3ab9c1d65d550eb30621ced2434252f61d1fdd33/anycast_healthchecker/utils.py#L725-L778 | train |
unixsurfer/anycast_healthchecker | anycast_healthchecker/utils.py | write_temp_bird_conf | def write_temp_bird_conf(dummy_ip_prefix,
config_file,
variable_name,
prefixes):
"""Write in a temporary file the list of IP-Prefixes.
A failure to create and write the temporary file will exit main program.
Arguments:
dumm... | python | def write_temp_bird_conf(dummy_ip_prefix,
config_file,
variable_name,
prefixes):
"""Write in a temporary file the list of IP-Prefixes.
A failure to create and write the temporary file will exit main program.
Arguments:
dumm... | [
"def",
"write_temp_bird_conf",
"(",
"dummy_ip_prefix",
",",
"config_file",
",",
"variable_name",
",",
"prefixes",
")",
":",
"log",
"=",
"logging",
".",
"getLogger",
"(",
"PROGRAM_NAME",
")",
"comment",
"=",
"(",
"\"# {i} is a dummy IP Prefix. It should NOT be used and \... | Write in a temporary file the list of IP-Prefixes.
A failure to create and write the temporary file will exit main program.
Arguments:
dummy_ip_prefix (str): The dummy IP prefix, which must be always
config_file (str): The file name of bird configuration
variable_name (str): The name o... | [
"Write",
"in",
"a",
"temporary",
"file",
"the",
"list",
"of",
"IP",
"-",
"Prefixes",
"."
] | 3ab9c1d65d550eb30621ced2434252f61d1fdd33 | https://github.com/unixsurfer/anycast_healthchecker/blob/3ab9c1d65d550eb30621ced2434252f61d1fdd33/anycast_healthchecker/utils.py#L781-L827 | train |
unixsurfer/anycast_healthchecker | anycast_healthchecker/utils.py | archive_bird_conf | def archive_bird_conf(config_file, changes_counter):
"""Keep a history of Bird configuration files.
Arguments:
config_file (str): file name of bird configuration
changes_counter (int): number of configuration files to keep in the
history
"""
log = logging.getLogger(PROGRAM_NAME)... | python | def archive_bird_conf(config_file, changes_counter):
"""Keep a history of Bird configuration files.
Arguments:
config_file (str): file name of bird configuration
changes_counter (int): number of configuration files to keep in the
history
"""
log = logging.getLogger(PROGRAM_NAME)... | [
"def",
"archive_bird_conf",
"(",
"config_file",
",",
"changes_counter",
")",
":",
"log",
"=",
"logging",
".",
"getLogger",
"(",
"PROGRAM_NAME",
")",
"history_dir",
"=",
"os",
".",
"path",
".",
"join",
"(",
"os",
".",
"path",
".",
"dirname",
"(",
"config_fi... | Keep a history of Bird configuration files.
Arguments:
config_file (str): file name of bird configuration
changes_counter (int): number of configuration files to keep in the
history | [
"Keep",
"a",
"history",
"of",
"Bird",
"configuration",
"files",
"."
] | 3ab9c1d65d550eb30621ced2434252f61d1fdd33 | https://github.com/unixsurfer/anycast_healthchecker/blob/3ab9c1d65d550eb30621ced2434252f61d1fdd33/anycast_healthchecker/utils.py#L830-L861 | train |
unixsurfer/anycast_healthchecker | anycast_healthchecker/utils.py | update_pidfile | def update_pidfile(pidfile):
"""Update pidfile.
Notice:
We should call this function only after we have successfully acquired
a lock and never before. It exits main program if it fails to parse
and/or write pidfile.
Arguments:
pidfile (str): pidfile to update
"""
t... | python | def update_pidfile(pidfile):
"""Update pidfile.
Notice:
We should call this function only after we have successfully acquired
a lock and never before. It exits main program if it fails to parse
and/or write pidfile.
Arguments:
pidfile (str): pidfile to update
"""
t... | [
"def",
"update_pidfile",
"(",
"pidfile",
")",
":",
"try",
":",
"with",
"open",
"(",
"pidfile",
",",
"mode",
"=",
"'r'",
")",
"as",
"_file",
":",
"pid",
"=",
"_file",
".",
"read",
"(",
"1024",
")",
".",
"rstrip",
"(",
")",
"try",
":",
"pid",
"=",
... | Update pidfile.
Notice:
We should call this function only after we have successfully acquired
a lock and never before. It exits main program if it fails to parse
and/or write pidfile.
Arguments:
pidfile (str): pidfile to update | [
"Update",
"pidfile",
"."
] | 3ab9c1d65d550eb30621ced2434252f61d1fdd33 | https://github.com/unixsurfer/anycast_healthchecker/blob/3ab9c1d65d550eb30621ced2434252f61d1fdd33/anycast_healthchecker/utils.py#L864-L904 | train |
unixsurfer/anycast_healthchecker | anycast_healthchecker/utils.py | write_pid | def write_pid(pidfile):
"""Write processID to the pidfile.
Notice:
It exits main program if it fails to write pidfile.
Arguments:
pidfile (str): pidfile to update
"""
pid = str(os.getpid())
try:
with open(pidfile, mode='w') as _file:
print("writing processI... | python | def write_pid(pidfile):
"""Write processID to the pidfile.
Notice:
It exits main program if it fails to write pidfile.
Arguments:
pidfile (str): pidfile to update
"""
pid = str(os.getpid())
try:
with open(pidfile, mode='w') as _file:
print("writing processI... | [
"def",
"write_pid",
"(",
"pidfile",
")",
":",
"pid",
"=",
"str",
"(",
"os",
".",
"getpid",
"(",
")",
")",
"try",
":",
"with",
"open",
"(",
"pidfile",
",",
"mode",
"=",
"'w'",
")",
"as",
"_file",
":",
"print",
"(",
"\"writing processID {p} to pidfile\""... | Write processID to the pidfile.
Notice:
It exits main program if it fails to write pidfile.
Arguments:
pidfile (str): pidfile to update | [
"Write",
"processID",
"to",
"the",
"pidfile",
"."
] | 3ab9c1d65d550eb30621ced2434252f61d1fdd33 | https://github.com/unixsurfer/anycast_healthchecker/blob/3ab9c1d65d550eb30621ced2434252f61d1fdd33/anycast_healthchecker/utils.py#L907-L923 | train |
unixsurfer/anycast_healthchecker | anycast_healthchecker/utils.py | shutdown | def shutdown(pidfile, signalnb=None, frame=None):
"""Clean up pidfile upon shutdown.
Notice:
We should register this function as signal handler for the following
termination signals:
SIGHUP
SIGTERM
SIGABRT
SIGINT
Arguments:
pidfile (s... | python | def shutdown(pidfile, signalnb=None, frame=None):
"""Clean up pidfile upon shutdown.
Notice:
We should register this function as signal handler for the following
termination signals:
SIGHUP
SIGTERM
SIGABRT
SIGINT
Arguments:
pidfile (s... | [
"def",
"shutdown",
"(",
"pidfile",
",",
"signalnb",
"=",
"None",
",",
"frame",
"=",
"None",
")",
":",
"log",
"=",
"logging",
".",
"getLogger",
"(",
"PROGRAM_NAME",
")",
"log",
".",
"info",
"(",
"\"received %s at %s\"",
",",
"signalnb",
",",
"frame",
")",... | Clean up pidfile upon shutdown.
Notice:
We should register this function as signal handler for the following
termination signals:
SIGHUP
SIGTERM
SIGABRT
SIGINT
Arguments:
pidfile (str): pidfile to remove
signalnb (int): The ID of ... | [
"Clean",
"up",
"pidfile",
"upon",
"shutdown",
"."
] | 3ab9c1d65d550eb30621ced2434252f61d1fdd33 | https://github.com/unixsurfer/anycast_healthchecker/blob/3ab9c1d65d550eb30621ced2434252f61d1fdd33/anycast_healthchecker/utils.py#L926-L949 | train |
unixsurfer/anycast_healthchecker | anycast_healthchecker/utils.py | setup_logger | def setup_logger(config):
"""Configure the logging environment.
Notice:
By default logging will go to STDOUT and messages for unhandled
exceptions or crashes will go to STDERR. If log_file and/or log_server
is set then we don't log to STDOUT. Messages for unhandled exceptions
or... | python | def setup_logger(config):
"""Configure the logging environment.
Notice:
By default logging will go to STDOUT and messages for unhandled
exceptions or crashes will go to STDERR. If log_file and/or log_server
is set then we don't log to STDOUT. Messages for unhandled exceptions
or... | [
"def",
"setup_logger",
"(",
"config",
")",
":",
"logger",
"=",
"logging",
".",
"getLogger",
"(",
"PROGRAM_NAME",
")",
"num_level",
"=",
"getattr",
"(",
"logging",
",",
"config",
".",
"get",
"(",
"'daemon'",
",",
"'loglevel'",
")",
".",
"upper",
"(",
")",... | Configure the logging environment.
Notice:
By default logging will go to STDOUT and messages for unhandled
exceptions or crashes will go to STDERR. If log_file and/or log_server
is set then we don't log to STDOUT. Messages for unhandled exceptions
or crashes can only go to either ST... | [
"Configure",
"the",
"logging",
"environment",
"."
] | 3ab9c1d65d550eb30621ced2434252f61d1fdd33 | https://github.com/unixsurfer/anycast_healthchecker/blob/3ab9c1d65d550eb30621ced2434252f61d1fdd33/anycast_healthchecker/utils.py#L952-L1059 | train |
unixsurfer/anycast_healthchecker | anycast_healthchecker/utils.py | run_custom_bird_reconfigure | def run_custom_bird_reconfigure(operation):
"""Reconfigure BIRD daemon by running a custom command.
It adds one argument to the command, either "up" or "down".
If command times out then we kill it. In order to avoid leaving any orphan
processes, that may have been started by the command, we start a new... | python | def run_custom_bird_reconfigure(operation):
"""Reconfigure BIRD daemon by running a custom command.
It adds one argument to the command, either "up" or "down".
If command times out then we kill it. In order to avoid leaving any orphan
processes, that may have been started by the command, we start a new... | [
"def",
"run_custom_bird_reconfigure",
"(",
"operation",
")",
":",
"log",
"=",
"logging",
".",
"getLogger",
"(",
"PROGRAM_NAME",
")",
"if",
"isinstance",
"(",
"operation",
",",
"AddOperation",
")",
":",
"status",
"=",
"'up'",
"else",
":",
"status",
"=",
"'dow... | Reconfigure BIRD daemon by running a custom command.
It adds one argument to the command, either "up" or "down".
If command times out then we kill it. In order to avoid leaving any orphan
processes, that may have been started by the command, we start a new
session when we invoke the command and then we... | [
"Reconfigure",
"BIRD",
"daemon",
"by",
"running",
"a",
"custom",
"command",
"."
] | 3ab9c1d65d550eb30621ced2434252f61d1fdd33 | https://github.com/unixsurfer/anycast_healthchecker/blob/3ab9c1d65d550eb30621ced2434252f61d1fdd33/anycast_healthchecker/utils.py#L1206-L1248 | train |
unixsurfer/anycast_healthchecker | anycast_healthchecker/utils.py | AddOperation.update | def update(self, prefixes):
"""Add a value to the list.
Arguments:
prefixes(list): A list to add the value
"""
if self.ip_prefix not in prefixes:
prefixes.append(self.ip_prefix)
self.log.info("announcing %s for %s", self.ip_prefix, self.name)
... | python | def update(self, prefixes):
"""Add a value to the list.
Arguments:
prefixes(list): A list to add the value
"""
if self.ip_prefix not in prefixes:
prefixes.append(self.ip_prefix)
self.log.info("announcing %s for %s", self.ip_prefix, self.name)
... | [
"def",
"update",
"(",
"self",
",",
"prefixes",
")",
":",
"if",
"self",
".",
"ip_prefix",
"not",
"in",
"prefixes",
":",
"prefixes",
".",
"append",
"(",
"self",
".",
"ip_prefix",
")",
"self",
".",
"log",
".",
"info",
"(",
"\"announcing %s for %s\"",
",",
... | Add a value to the list.
Arguments:
prefixes(list): A list to add the value | [
"Add",
"a",
"value",
"to",
"the",
"list",
"."
] | 3ab9c1d65d550eb30621ced2434252f61d1fdd33 | https://github.com/unixsurfer/anycast_healthchecker/blob/3ab9c1d65d550eb30621ced2434252f61d1fdd33/anycast_healthchecker/utils.py#L690-L701 | train |
unixsurfer/anycast_healthchecker | anycast_healthchecker/utils.py | CustomLogger.write | def write(self, string):
"""Erase newline from a string and write to the logger."""
string = string.rstrip()
if string: # Don't log empty lines
self.logger.critical(string) | python | def write(self, string):
"""Erase newline from a string and write to the logger."""
string = string.rstrip()
if string: # Don't log empty lines
self.logger.critical(string) | [
"def",
"write",
"(",
"self",
",",
"string",
")",
":",
"string",
"=",
"string",
".",
"rstrip",
"(",
")",
"if",
"string",
":",
"self",
".",
"logger",
".",
"critical",
"(",
"string",
")"
] | Erase newline from a string and write to the logger. | [
"Erase",
"newline",
"from",
"a",
"string",
"and",
"write",
"to",
"the",
"logger",
"."
] | 3ab9c1d65d550eb30621ced2434252f61d1fdd33 | https://github.com/unixsurfer/anycast_healthchecker/blob/3ab9c1d65d550eb30621ced2434252f61d1fdd33/anycast_healthchecker/utils.py#L1097-L1101 | train |
unixsurfer/anycast_healthchecker | anycast_healthchecker/utils.py | CustomJsonFormatter.process_log_record | def process_log_record(self, log_record):
"""Add customer record keys and rename threadName key."""
log_record["version"] = __version__
log_record["program"] = PROGRAM_NAME
log_record["service_name"] = log_record.pop('threadName', None)
# return jsonlogger.JsonFormatter.process_l... | python | def process_log_record(self, log_record):
"""Add customer record keys and rename threadName key."""
log_record["version"] = __version__
log_record["program"] = PROGRAM_NAME
log_record["service_name"] = log_record.pop('threadName', None)
# return jsonlogger.JsonFormatter.process_l... | [
"def",
"process_log_record",
"(",
"self",
",",
"log_record",
")",
":",
"log_record",
"[",
"\"version\"",
"]",
"=",
"__version__",
"log_record",
"[",
"\"program\"",
"]",
"=",
"PROGRAM_NAME",
"log_record",
"[",
"\"service_name\"",
"]",
"=",
"log_record",
".",
"pop... | Add customer record keys and rename threadName key. | [
"Add",
"customer",
"record",
"keys",
"and",
"rename",
"threadName",
"key",
"."
] | 3ab9c1d65d550eb30621ced2434252f61d1fdd33 | https://github.com/unixsurfer/anycast_healthchecker/blob/3ab9c1d65d550eb30621ced2434252f61d1fdd33/anycast_healthchecker/utils.py#L1176-L1183 | train |
sashahart/vex | vex/main.py | get_vexrc | def get_vexrc(options, environ):
"""Get a representation of the contents of the config file.
:returns:
a Vexrc instance.
"""
# Complain if user specified nonexistent file with --config.
# But we don't want to complain just because ~/.vexrc doesn't exist.
if options.config and not os.pat... | python | def get_vexrc(options, environ):
"""Get a representation of the contents of the config file.
:returns:
a Vexrc instance.
"""
# Complain if user specified nonexistent file with --config.
# But we don't want to complain just because ~/.vexrc doesn't exist.
if options.config and not os.pat... | [
"def",
"get_vexrc",
"(",
"options",
",",
"environ",
")",
":",
"if",
"options",
".",
"config",
"and",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"options",
".",
"config",
")",
":",
"raise",
"exceptions",
".",
"InvalidVexrc",
"(",
"\"nonexistent config: {... | Get a representation of the contents of the config file.
:returns:
a Vexrc instance. | [
"Get",
"a",
"representation",
"of",
"the",
"contents",
"of",
"the",
"config",
"file",
"."
] | b7680c40897b8cbe6aae55ec9812b4fb11738192 | https://github.com/sashahart/vex/blob/b7680c40897b8cbe6aae55ec9812b4fb11738192/vex/main.py#L15-L27 | train |
sashahart/vex | vex/main.py | get_cwd | def get_cwd(options):
"""Discover what directory the command should run in.
"""
if not options.cwd:
return None
if not os.path.exists(options.cwd):
raise exceptions.InvalidCwd(
"can't --cwd to invalid path {0!r}".format(options.cwd))
return options.cwd | python | def get_cwd(options):
"""Discover what directory the command should run in.
"""
if not options.cwd:
return None
if not os.path.exists(options.cwd):
raise exceptions.InvalidCwd(
"can't --cwd to invalid path {0!r}".format(options.cwd))
return options.cwd | [
"def",
"get_cwd",
"(",
"options",
")",
":",
"if",
"not",
"options",
".",
"cwd",
":",
"return",
"None",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"options",
".",
"cwd",
")",
":",
"raise",
"exceptions",
".",
"InvalidCwd",
"(",
"\"can't --cwd to... | Discover what directory the command should run in. | [
"Discover",
"what",
"directory",
"the",
"command",
"should",
"run",
"in",
"."
] | b7680c40897b8cbe6aae55ec9812b4fb11738192 | https://github.com/sashahart/vex/blob/b7680c40897b8cbe6aae55ec9812b4fb11738192/vex/main.py#L30-L38 | train |
sashahart/vex | vex/main.py | get_virtualenv_path | def get_virtualenv_path(ve_base, ve_name):
"""Check a virtualenv path, raising exceptions to explain problems.
"""
if not ve_base:
raise exceptions.NoVirtualenvsDirectory(
"could not figure out a virtualenvs directory. "
"make sure $HOME is set, or $WORKON_HOME,"
... | python | def get_virtualenv_path(ve_base, ve_name):
"""Check a virtualenv path, raising exceptions to explain problems.
"""
if not ve_base:
raise exceptions.NoVirtualenvsDirectory(
"could not figure out a virtualenvs directory. "
"make sure $HOME is set, or $WORKON_HOME,"
... | [
"def",
"get_virtualenv_path",
"(",
"ve_base",
",",
"ve_name",
")",
":",
"if",
"not",
"ve_base",
":",
"raise",
"exceptions",
".",
"NoVirtualenvsDirectory",
"(",
"\"could not figure out a virtualenvs directory. \"",
"\"make sure $HOME is set, or $WORKON_HOME,\"",
"\" or set virtu... | Check a virtualenv path, raising exceptions to explain problems. | [
"Check",
"a",
"virtualenv",
"path",
"raising",
"exceptions",
"to",
"explain",
"problems",
"."
] | b7680c40897b8cbe6aae55ec9812b4fb11738192 | https://github.com/sashahart/vex/blob/b7680c40897b8cbe6aae55ec9812b4fb11738192/vex/main.py#L53-L88 | train |
sashahart/vex | vex/main.py | get_command | def get_command(options, vexrc, environ):
"""Get a command to run.
:returns:
a list of strings representing a command to be passed to Popen.
"""
command = options.rest
if not command:
command = vexrc.get_shell(environ)
if command and command[0].startswith('--'):
raise ex... | python | def get_command(options, vexrc, environ):
"""Get a command to run.
:returns:
a list of strings representing a command to be passed to Popen.
"""
command = options.rest
if not command:
command = vexrc.get_shell(environ)
if command and command[0].startswith('--'):
raise ex... | [
"def",
"get_command",
"(",
"options",
",",
"vexrc",
",",
"environ",
")",
":",
"command",
"=",
"options",
".",
"rest",
"if",
"not",
"command",
":",
"command",
"=",
"vexrc",
".",
"get_shell",
"(",
"environ",
")",
"if",
"command",
"and",
"command",
"[",
"... | Get a command to run.
:returns:
a list of strings representing a command to be passed to Popen. | [
"Get",
"a",
"command",
"to",
"run",
"."
] | b7680c40897b8cbe6aae55ec9812b4fb11738192 | https://github.com/sashahart/vex/blob/b7680c40897b8cbe6aae55ec9812b4fb11738192/vex/main.py#L91-L106 | train |
sashahart/vex | vex/main.py | main | def main():
"""The main command-line entry point, with system interactions.
"""
argv = sys.argv[1:]
returncode = 1
try:
returncode = _main(os.environ, argv)
except exceptions.InvalidArgument as error:
if error.message:
sys.stderr.write("Error: " + error.message + '\n'... | python | def main():
"""The main command-line entry point, with system interactions.
"""
argv = sys.argv[1:]
returncode = 1
try:
returncode = _main(os.environ, argv)
except exceptions.InvalidArgument as error:
if error.message:
sys.stderr.write("Error: " + error.message + '\n'... | [
"def",
"main",
"(",
")",
":",
"argv",
"=",
"sys",
".",
"argv",
"[",
"1",
":",
"]",
"returncode",
"=",
"1",
"try",
":",
"returncode",
"=",
"_main",
"(",
"os",
".",
"environ",
",",
"argv",
")",
"except",
"exceptions",
".",
"InvalidArgument",
"as",
"e... | The main command-line entry point, with system interactions. | [
"The",
"main",
"command",
"-",
"line",
"entry",
"point",
"with",
"system",
"interactions",
"."
] | b7680c40897b8cbe6aae55ec9812b4fb11738192 | https://github.com/sashahart/vex/blob/b7680c40897b8cbe6aae55ec9812b4fb11738192/vex/main.py#L185-L197 | train |
unixsurfer/anycast_healthchecker | contrib/nagios/check_anycast_healthchecker.py | get_processid | def get_processid(config):
"""Return process id of anycast-healthchecker.
Arguments:
config (obj): A configparser object with the configuration of
anycast-healthchecker.
Returns:
The process id found in the pid file
Raises:
ValueError in the following cases
- p... | python | def get_processid(config):
"""Return process id of anycast-healthchecker.
Arguments:
config (obj): A configparser object with the configuration of
anycast-healthchecker.
Returns:
The process id found in the pid file
Raises:
ValueError in the following cases
- p... | [
"def",
"get_processid",
"(",
"config",
")",
":",
"pidfile",
"=",
"config",
".",
"get",
"(",
"'daemon'",
",",
"'pidfile'",
",",
"fallback",
"=",
"None",
")",
"if",
"pidfile",
"is",
"None",
":",
"raise",
"ValueError",
"(",
"\"Configuration doesn't have pidfile o... | Return process id of anycast-healthchecker.
Arguments:
config (obj): A configparser object with the configuration of
anycast-healthchecker.
Returns:
The process id found in the pid file
Raises:
ValueError in the following cases
- pidfile option is missing from the ... | [
"Return",
"process",
"id",
"of",
"anycast",
"-",
"healthchecker",
"."
] | 3ab9c1d65d550eb30621ced2434252f61d1fdd33 | https://github.com/unixsurfer/anycast_healthchecker/blob/3ab9c1d65d550eb30621ced2434252f61d1fdd33/contrib/nagios/check_anycast_healthchecker.py#L22-L63 | train |
unixsurfer/anycast_healthchecker | contrib/nagios/check_anycast_healthchecker.py | parse_services | def parse_services(config, services):
"""Parse configuration to return number of enabled service checks.
Arguments:
config (obj): A configparser object with the configuration of
anycast-healthchecker.
services (list): A list of section names which holds configuration
for each se... | python | def parse_services(config, services):
"""Parse configuration to return number of enabled service checks.
Arguments:
config (obj): A configparser object with the configuration of
anycast-healthchecker.
services (list): A list of section names which holds configuration
for each se... | [
"def",
"parse_services",
"(",
"config",
",",
"services",
")",
":",
"enabled",
"=",
"0",
"for",
"service",
"in",
"services",
":",
"check_disabled",
"=",
"config",
".",
"getboolean",
"(",
"service",
",",
"'check_disabled'",
")",
"if",
"not",
"check_disabled",
... | Parse configuration to return number of enabled service checks.
Arguments:
config (obj): A configparser object with the configuration of
anycast-healthchecker.
services (list): A list of section names which holds configuration
for each service check
Returns:
A number (i... | [
"Parse",
"configuration",
"to",
"return",
"number",
"of",
"enabled",
"service",
"checks",
"."
] | 3ab9c1d65d550eb30621ced2434252f61d1fdd33 | https://github.com/unixsurfer/anycast_healthchecker/blob/3ab9c1d65d550eb30621ced2434252f61d1fdd33/contrib/nagios/check_anycast_healthchecker.py#L90-L109 | train |
unixsurfer/anycast_healthchecker | contrib/nagios/check_anycast_healthchecker.py | main | def main():
"""Run check.
anycast-healthchecker is a multi-threaded software and for each
service check it holds a thread. If a thread dies then the service
is not monitored anymore and the route for the IP associated with service
it wont be withdrawn in case service goes down in the meantime.
... | python | def main():
"""Run check.
anycast-healthchecker is a multi-threaded software and for each
service check it holds a thread. If a thread dies then the service
is not monitored anymore and the route for the IP associated with service
it wont be withdrawn in case service goes down in the meantime.
... | [
"def",
"main",
"(",
")",
":",
"arguments",
"=",
"docopt",
"(",
"__doc__",
")",
"config_file",
"=",
"'/etc/anycast-healthchecker.conf'",
"config_dir",
"=",
"'/etc/anycast-healthchecker.d'",
"config",
"=",
"configparser",
".",
"ConfigParser",
"(",
")",
"config_files",
... | Run check.
anycast-healthchecker is a multi-threaded software and for each
service check it holds a thread. If a thread dies then the service
is not monitored anymore and the route for the IP associated with service
it wont be withdrawn in case service goes down in the meantime. | [
"Run",
"check",
"."
] | 3ab9c1d65d550eb30621ced2434252f61d1fdd33 | https://github.com/unixsurfer/anycast_healthchecker/blob/3ab9c1d65d550eb30621ced2434252f61d1fdd33/contrib/nagios/check_anycast_healthchecker.py#L112-L184 | train |
sashahart/vex | vex/shell_config.py | scary_path | def scary_path(path):
"""Whitelist the WORKON_HOME strings we're willing to substitute in
to strings that we provide for user's shell to evaluate.
If it smells at all bad, return True.
"""
if not path:
return True
assert isinstance(path, bytes)
return not NOT_SCARY.match(path) | python | def scary_path(path):
"""Whitelist the WORKON_HOME strings we're willing to substitute in
to strings that we provide for user's shell to evaluate.
If it smells at all bad, return True.
"""
if not path:
return True
assert isinstance(path, bytes)
return not NOT_SCARY.match(path) | [
"def",
"scary_path",
"(",
"path",
")",
":",
"if",
"not",
"path",
":",
"return",
"True",
"assert",
"isinstance",
"(",
"path",
",",
"bytes",
")",
"return",
"not",
"NOT_SCARY",
".",
"match",
"(",
"path",
")"
] | Whitelist the WORKON_HOME strings we're willing to substitute in
to strings that we provide for user's shell to evaluate.
If it smells at all bad, return True. | [
"Whitelist",
"the",
"WORKON_HOME",
"strings",
"we",
"re",
"willing",
"to",
"substitute",
"in",
"to",
"strings",
"that",
"we",
"provide",
"for",
"user",
"s",
"shell",
"to",
"evaluate",
"."
] | b7680c40897b8cbe6aae55ec9812b4fb11738192 | https://github.com/sashahart/vex/blob/b7680c40897b8cbe6aae55ec9812b4fb11738192/vex/shell_config.py#L22-L31 | train |
sashahart/vex | vex/shell_config.py | shell_config_for | def shell_config_for(shell, vexrc, environ):
"""return completion config for the named shell.
"""
here = os.path.dirname(os.path.abspath(__file__))
path = os.path.join(here, 'shell_configs', shell)
try:
with open(path, 'rb') as inp:
data = inp.read()
except FileNotFoundError ... | python | def shell_config_for(shell, vexrc, environ):
"""return completion config for the named shell.
"""
here = os.path.dirname(os.path.abspath(__file__))
path = os.path.join(here, 'shell_configs', shell)
try:
with open(path, 'rb') as inp:
data = inp.read()
except FileNotFoundError ... | [
"def",
"shell_config_for",
"(",
"shell",
",",
"vexrc",
",",
"environ",
")",
":",
"here",
"=",
"os",
".",
"path",
".",
"dirname",
"(",
"os",
".",
"path",
".",
"abspath",
"(",
"__file__",
")",
")",
"path",
"=",
"os",
".",
"path",
".",
"join",
"(",
... | return completion config for the named shell. | [
"return",
"completion",
"config",
"for",
"the",
"named",
"shell",
"."
] | b7680c40897b8cbe6aae55ec9812b4fb11738192 | https://github.com/sashahart/vex/blob/b7680c40897b8cbe6aae55ec9812b4fb11738192/vex/shell_config.py#L34-L49 | train |
unixsurfer/anycast_healthchecker | anycast_healthchecker/servicecheck.py | ServiceCheck._run_check | def _run_check(self):
"""Execute a check command.
Returns:
True if the exit code of the command is 0 otherwise False.
"""
cmd = shlex.split(self.config['check_cmd'])
self.log.info("running %s", ' '.join(cmd))
proc = subprocess.Popen(cmd, stdout=subprocess.PI... | python | def _run_check(self):
"""Execute a check command.
Returns:
True if the exit code of the command is 0 otherwise False.
"""
cmd = shlex.split(self.config['check_cmd'])
self.log.info("running %s", ' '.join(cmd))
proc = subprocess.Popen(cmd, stdout=subprocess.PI... | [
"def",
"_run_check",
"(",
"self",
")",
":",
"cmd",
"=",
"shlex",
".",
"split",
"(",
"self",
".",
"config",
"[",
"'check_cmd'",
"]",
")",
"self",
".",
"log",
".",
"info",
"(",
"\"running %s\"",
",",
"' '",
".",
"join",
"(",
"cmd",
")",
")",
"proc",
... | Execute a check command.
Returns:
True if the exit code of the command is 0 otherwise False. | [
"Execute",
"a",
"check",
"command",
"."
] | 3ab9c1d65d550eb30621ced2434252f61d1fdd33 | https://github.com/unixsurfer/anycast_healthchecker/blob/3ab9c1d65d550eb30621ced2434252f61d1fdd33/anycast_healthchecker/servicecheck.py#L88-L123 | train |
unixsurfer/anycast_healthchecker | anycast_healthchecker/servicecheck.py | ServiceCheck._ip_assigned | def _ip_assigned(self):
"""Check if IP prefix is assigned to loopback interface.
Returns:
True if IP prefix found assigned otherwise False.
"""
output = []
cmd = [
'/sbin/ip',
'address',
'show',
'dev',
self... | python | def _ip_assigned(self):
"""Check if IP prefix is assigned to loopback interface.
Returns:
True if IP prefix found assigned otherwise False.
"""
output = []
cmd = [
'/sbin/ip',
'address',
'show',
'dev',
self... | [
"def",
"_ip_assigned",
"(",
"self",
")",
":",
"output",
"=",
"[",
"]",
"cmd",
"=",
"[",
"'/sbin/ip'",
",",
"'address'",
",",
"'show'",
",",
"'dev'",
",",
"self",
".",
"config",
"[",
"'interface'",
"]",
",",
"'to'",
",",
"self",
".",
"ip_with_prefixlen"... | Check if IP prefix is assigned to loopback interface.
Returns:
True if IP prefix found assigned otherwise False. | [
"Check",
"if",
"IP",
"prefix",
"is",
"assigned",
"to",
"loopback",
"interface",
"."
] | 3ab9c1d65d550eb30621ced2434252f61d1fdd33 | https://github.com/unixsurfer/anycast_healthchecker/blob/3ab9c1d65d550eb30621ced2434252f61d1fdd33/anycast_healthchecker/servicecheck.py#L125-L193 | train |
unixsurfer/anycast_healthchecker | anycast_healthchecker/servicecheck.py | ServiceCheck._check_disabled | def _check_disabled(self):
"""Check if health check is disabled.
It logs a message if health check is disabled and it also adds an item
to the action queue based on 'on_disabled' setting.
Returns:
True if check is disabled otherwise False.
"""
if self.confi... | python | def _check_disabled(self):
"""Check if health check is disabled.
It logs a message if health check is disabled and it also adds an item
to the action queue based on 'on_disabled' setting.
Returns:
True if check is disabled otherwise False.
"""
if self.confi... | [
"def",
"_check_disabled",
"(",
"self",
")",
":",
"if",
"self",
".",
"config",
"[",
"'check_disabled'",
"]",
":",
"if",
"self",
".",
"config",
"[",
"'on_disabled'",
"]",
"==",
"'withdraw'",
":",
"self",
".",
"log",
".",
"info",
"(",
"\"Check is disabled and... | Check if health check is disabled.
It logs a message if health check is disabled and it also adds an item
to the action queue based on 'on_disabled' setting.
Returns:
True if check is disabled otherwise False. | [
"Check",
"if",
"health",
"check",
"is",
"disabled",
"."
] | 3ab9c1d65d550eb30621ced2434252f61d1fdd33 | https://github.com/unixsurfer/anycast_healthchecker/blob/3ab9c1d65d550eb30621ced2434252f61d1fdd33/anycast_healthchecker/servicecheck.py#L195-L220 | train |
unixsurfer/anycast_healthchecker | anycast_healthchecker/servicecheck.py | ServiceCheck.run | def run(self):
"""Wrap _run method."""
# Catch all possible exceptions raised by the running thread
# and let parent process know about it.
try:
self._run()
except Exception: # pylint: disable=broad-except
self.action.put(
ServiceCheckDied... | python | def run(self):
"""Wrap _run method."""
# Catch all possible exceptions raised by the running thread
# and let parent process know about it.
try:
self._run()
except Exception: # pylint: disable=broad-except
self.action.put(
ServiceCheckDied... | [
"def",
"run",
"(",
"self",
")",
":",
"try",
":",
"self",
".",
"_run",
"(",
")",
"except",
"Exception",
":",
"self",
".",
"action",
".",
"put",
"(",
"ServiceCheckDiedError",
"(",
"self",
".",
"name",
",",
"traceback",
".",
"format_exc",
"(",
")",
")",... | Wrap _run method. | [
"Wrap",
"_run",
"method",
"."
] | 3ab9c1d65d550eb30621ced2434252f61d1fdd33 | https://github.com/unixsurfer/anycast_healthchecker/blob/3ab9c1d65d550eb30621ced2434252f61d1fdd33/anycast_healthchecker/servicecheck.py#L222-L231 | train |
unixsurfer/anycast_healthchecker | anycast_healthchecker/main.py | main | def main():
"""Parse CLI and starts main program."""
args = docopt(__doc__, version=__version__)
if args['--print']:
for section in DEFAULT_OPTIONS:
print("[{}]".format(section))
for key, value in DEFAULT_OPTIONS[section].items():
print("{k} = {v}".format(k=ke... | python | def main():
"""Parse CLI and starts main program."""
args = docopt(__doc__, version=__version__)
if args['--print']:
for section in DEFAULT_OPTIONS:
print("[{}]".format(section))
for key, value in DEFAULT_OPTIONS[section].items():
print("{k} = {v}".format(k=ke... | [
"def",
"main",
"(",
")",
":",
"args",
"=",
"docopt",
"(",
"__doc__",
",",
"version",
"=",
"__version__",
")",
"if",
"args",
"[",
"'--print'",
"]",
":",
"for",
"section",
"in",
"DEFAULT_OPTIONS",
":",
"print",
"(",
"\"[{}]\"",
".",
"format",
"(",
"secti... | Parse CLI and starts main program. | [
"Parse",
"CLI",
"and",
"starts",
"main",
"program",
"."
] | 3ab9c1d65d550eb30621ced2434252f61d1fdd33 | https://github.com/unixsurfer/anycast_healthchecker/blob/3ab9c1d65d550eb30621ced2434252f61d1fdd33/anycast_healthchecker/main.py#L38-L98 | train |
sashahart/vex | vex/run.py | get_environ | def get_environ(environ, defaults, ve_path):
"""Make an environment to run with.
"""
# Copy the parent environment, add in defaults from .vexrc.
env = environ.copy()
env.update(defaults)
# Leaving in existing PYTHONHOME can cause some errors
if 'PYTHONHOME' in env:
del env['PYTHONHO... | python | def get_environ(environ, defaults, ve_path):
"""Make an environment to run with.
"""
# Copy the parent environment, add in defaults from .vexrc.
env = environ.copy()
env.update(defaults)
# Leaving in existing PYTHONHOME can cause some errors
if 'PYTHONHOME' in env:
del env['PYTHONHO... | [
"def",
"get_environ",
"(",
"environ",
",",
"defaults",
",",
"ve_path",
")",
":",
"env",
"=",
"environ",
".",
"copy",
"(",
")",
"env",
".",
"update",
"(",
"defaults",
")",
"if",
"'PYTHONHOME'",
"in",
"env",
":",
"del",
"env",
"[",
"'PYTHONHOME'",
"]",
... | Make an environment to run with. | [
"Make",
"an",
"environment",
"to",
"run",
"with",
"."
] | b7680c40897b8cbe6aae55ec9812b4fb11738192 | https://github.com/sashahart/vex/blob/b7680c40897b8cbe6aae55ec9812b4fb11738192/vex/run.py#L10-L64 | train |
sashahart/vex | vex/config.py | extract_key_value | def extract_key_value(line, environ):
"""Return key, value from given line if present, else return None.
"""
segments = line.split("=", 1)
if len(segments) < 2:
return None
key, value = segments
# foo passes through as-is (with spaces stripped)
# '{foo}' passes through literally
... | python | def extract_key_value(line, environ):
"""Return key, value from given line if present, else return None.
"""
segments = line.split("=", 1)
if len(segments) < 2:
return None
key, value = segments
# foo passes through as-is (with spaces stripped)
# '{foo}' passes through literally
... | [
"def",
"extract_key_value",
"(",
"line",
",",
"environ",
")",
":",
"segments",
"=",
"line",
".",
"split",
"(",
"\"=\"",
",",
"1",
")",
"if",
"len",
"(",
"segments",
")",
"<",
"2",
":",
"return",
"None",
"key",
",",
"value",
"=",
"segments",
"value",
... | Return key, value from given line if present, else return None. | [
"Return",
"key",
"value",
"from",
"given",
"line",
"if",
"present",
"else",
"return",
"None",
"."
] | b7680c40897b8cbe6aae55ec9812b4fb11738192 | https://github.com/sashahart/vex/blob/b7680c40897b8cbe6aae55ec9812b4fb11738192/vex/config.py#L129-L147 | train |
sashahart/vex | vex/config.py | Vexrc.from_file | def from_file(cls, path, environ):
"""Make a Vexrc instance from given file in given environ.
"""
instance = cls()
instance.read(path, environ)
return instance | python | def from_file(cls, path, environ):
"""Make a Vexrc instance from given file in given environ.
"""
instance = cls()
instance.read(path, environ)
return instance | [
"def",
"from_file",
"(",
"cls",
",",
"path",
",",
"environ",
")",
":",
"instance",
"=",
"cls",
"(",
")",
"instance",
".",
"read",
"(",
"path",
",",
"environ",
")",
"return",
"instance"
] | Make a Vexrc instance from given file in given environ. | [
"Make",
"a",
"Vexrc",
"instance",
"from",
"given",
"file",
"in",
"given",
"environ",
"."
] | b7680c40897b8cbe6aae55ec9812b4fb11738192 | https://github.com/sashahart/vex/blob/b7680c40897b8cbe6aae55ec9812b4fb11738192/vex/config.py#L54-L59 | train |
sashahart/vex | vex/config.py | Vexrc.read | def read(self, path, environ):
"""Read data from file into this vexrc instance.
"""
try:
inp = open(path, 'rb')
except FileNotFoundError as error:
if error.errno != 2:
raise
return None
parsing = parse_vexrc(inp, environ)
... | python | def read(self, path, environ):
"""Read data from file into this vexrc instance.
"""
try:
inp = open(path, 'rb')
except FileNotFoundError as error:
if error.errno != 2:
raise
return None
parsing = parse_vexrc(inp, environ)
... | [
"def",
"read",
"(",
"self",
",",
"path",
",",
"environ",
")",
":",
"try",
":",
"inp",
"=",
"open",
"(",
"path",
",",
"'rb'",
")",
"except",
"FileNotFoundError",
"as",
"error",
":",
"if",
"error",
".",
"errno",
"!=",
"2",
":",
"raise",
"return",
"No... | Read data from file into this vexrc instance. | [
"Read",
"data",
"from",
"file",
"into",
"this",
"vexrc",
"instance",
"."
] | b7680c40897b8cbe6aae55ec9812b4fb11738192 | https://github.com/sashahart/vex/blob/b7680c40897b8cbe6aae55ec9812b4fb11738192/vex/config.py#L61-L76 | train |
sashahart/vex | vex/config.py | Vexrc.get_ve_base | def get_ve_base(self, environ):
"""Find a directory to look for virtualenvs in.
"""
# set ve_base to a path we can look for virtualenvs:
# 1. .vexrc
# 2. WORKON_HOME (as defined for virtualenvwrapper's benefit)
# 3. $HOME/.virtualenvs
# (unless we got --path, then... | python | def get_ve_base(self, environ):
"""Find a directory to look for virtualenvs in.
"""
# set ve_base to a path we can look for virtualenvs:
# 1. .vexrc
# 2. WORKON_HOME (as defined for virtualenvwrapper's benefit)
# 3. $HOME/.virtualenvs
# (unless we got --path, then... | [
"def",
"get_ve_base",
"(",
"self",
",",
"environ",
")",
":",
"ve_base_value",
"=",
"self",
".",
"headings",
"[",
"self",
".",
"default_heading",
"]",
".",
"get",
"(",
"'virtualenvs'",
")",
"if",
"ve_base_value",
":",
"ve_base",
"=",
"os",
".",
"path",
".... | Find a directory to look for virtualenvs in. | [
"Find",
"a",
"directory",
"to",
"look",
"for",
"virtualenvs",
"in",
"."
] | b7680c40897b8cbe6aae55ec9812b4fb11738192 | https://github.com/sashahart/vex/blob/b7680c40897b8cbe6aae55ec9812b4fb11738192/vex/config.py#L78-L108 | train |
sashahart/vex | vex/config.py | Vexrc.get_shell | def get_shell(self, environ):
"""Find a command to run.
"""
command = self.headings[self.default_heading].get('shell')
if not command and os.name != 'nt':
command = environ.get('SHELL', '')
command = shlex.split(command) if command else None
return command | python | def get_shell(self, environ):
"""Find a command to run.
"""
command = self.headings[self.default_heading].get('shell')
if not command and os.name != 'nt':
command = environ.get('SHELL', '')
command = shlex.split(command) if command else None
return command | [
"def",
"get_shell",
"(",
"self",
",",
"environ",
")",
":",
"command",
"=",
"self",
".",
"headings",
"[",
"self",
".",
"default_heading",
"]",
".",
"get",
"(",
"'shell'",
")",
"if",
"not",
"command",
"and",
"os",
".",
"name",
"!=",
"'nt'",
":",
"comma... | Find a command to run. | [
"Find",
"a",
"command",
"to",
"run",
"."
] | b7680c40897b8cbe6aae55ec9812b4fb11738192 | https://github.com/sashahart/vex/blob/b7680c40897b8cbe6aae55ec9812b4fb11738192/vex/config.py#L110-L117 | train |
rndusr/torf | torf/_torrent.py | Torrent.name | def name(self):
"""
Name of the torrent
Default to last item in :attr:`path` or ``None`` if :attr:`path` is
``None``.
Setting this property sets or removes ``name`` in :attr:`metainfo`\
``['info']``.
"""
if 'name' not in self.metainfo['info'] and self.pa... | python | def name(self):
"""
Name of the torrent
Default to last item in :attr:`path` or ``None`` if :attr:`path` is
``None``.
Setting this property sets or removes ``name`` in :attr:`metainfo`\
``['info']``.
"""
if 'name' not in self.metainfo['info'] and self.pa... | [
"def",
"name",
"(",
"self",
")",
":",
"if",
"'name'",
"not",
"in",
"self",
".",
"metainfo",
"[",
"'info'",
"]",
"and",
"self",
".",
"path",
"is",
"not",
"None",
":",
"self",
".",
"metainfo",
"[",
"'info'",
"]",
"[",
"'name'",
"]",
"=",
"os",
".",... | Name of the torrent
Default to last item in :attr:`path` or ``None`` if :attr:`path` is
``None``.
Setting this property sets or removes ``name`` in :attr:`metainfo`\
``['info']``. | [
"Name",
"of",
"the",
"torrent"
] | df0363232daacd3f8c91aafddaa0623b8c28cbd2 | https://github.com/rndusr/torf/blob/df0363232daacd3f8c91aafddaa0623b8c28cbd2/torf/_torrent.py#L323-L335 | train |
rndusr/torf | torf/_torrent.py | Torrent.trackers | def trackers(self):
"""
List of tiers of announce URLs or ``None`` for no trackers
A tier is either a single announce URL (:class:`str`) or an
:class:`~collections.abc.Iterable` (e.g. :class:`list`) of announce
URLs.
Setting this property sets or removes ``announce`` an... | python | def trackers(self):
"""
List of tiers of announce URLs or ``None`` for no trackers
A tier is either a single announce URL (:class:`str`) or an
:class:`~collections.abc.Iterable` (e.g. :class:`list`) of announce
URLs.
Setting this property sets or removes ``announce`` an... | [
"def",
"trackers",
"(",
"self",
")",
":",
"announce_list",
"=",
"self",
".",
"metainfo",
".",
"get",
"(",
"'announce-list'",
",",
"None",
")",
"if",
"not",
"announce_list",
":",
"announce",
"=",
"self",
".",
"metainfo",
".",
"get",
"(",
"'announce'",
","... | List of tiers of announce URLs or ``None`` for no trackers
A tier is either a single announce URL (:class:`str`) or an
:class:`~collections.abc.Iterable` (e.g. :class:`list`) of announce
URLs.
Setting this property sets or removes ``announce`` and ``announce-list``
in :attr:`me... | [
"List",
"of",
"tiers",
"of",
"announce",
"URLs",
"or",
"None",
"for",
"no",
"trackers"
] | df0363232daacd3f8c91aafddaa0623b8c28cbd2 | https://github.com/rndusr/torf/blob/df0363232daacd3f8c91aafddaa0623b8c28cbd2/torf/_torrent.py#L345-L365 | train |
rndusr/torf | torf/_torrent.py | Torrent.infohash | def infohash(self):
"""SHA1 info hash"""
self.validate()
info = self.convert()[b'info']
return sha1(bencode(info)).hexdigest() | python | def infohash(self):
"""SHA1 info hash"""
self.validate()
info = self.convert()[b'info']
return sha1(bencode(info)).hexdigest() | [
"def",
"infohash",
"(",
"self",
")",
":",
"self",
".",
"validate",
"(",
")",
"info",
"=",
"self",
".",
"convert",
"(",
")",
"[",
"b'info'",
"]",
"return",
"sha1",
"(",
"bencode",
"(",
"info",
")",
")",
".",
"hexdigest",
"(",
")"
] | SHA1 info hash | [
"SHA1",
"info",
"hash"
] | df0363232daacd3f8c91aafddaa0623b8c28cbd2 | https://github.com/rndusr/torf/blob/df0363232daacd3f8c91aafddaa0623b8c28cbd2/torf/_torrent.py#L548-L552 | train |
rndusr/torf | torf/_torrent.py | Torrent.infohash_base32 | def infohash_base32(self):
"""Base32 encoded SHA1 info hash"""
self.validate()
info = self.convert()[b'info']
return b32encode(sha1(bencode(info)).digest()) | python | def infohash_base32(self):
"""Base32 encoded SHA1 info hash"""
self.validate()
info = self.convert()[b'info']
return b32encode(sha1(bencode(info)).digest()) | [
"def",
"infohash_base32",
"(",
"self",
")",
":",
"self",
".",
"validate",
"(",
")",
"info",
"=",
"self",
".",
"convert",
"(",
")",
"[",
"b'info'",
"]",
"return",
"b32encode",
"(",
"sha1",
"(",
"bencode",
"(",
"info",
")",
")",
".",
"digest",
"(",
"... | Base32 encoded SHA1 info hash | [
"Base32",
"encoded",
"SHA1",
"info",
"hash"
] | df0363232daacd3f8c91aafddaa0623b8c28cbd2 | https://github.com/rndusr/torf/blob/df0363232daacd3f8c91aafddaa0623b8c28cbd2/torf/_torrent.py#L555-L559 | train |
rndusr/torf | torf/_torrent.py | Torrent.generate | def generate(self, callback=None, interval=0):
"""
Hash pieces and report progress to `callback`
This method sets ``pieces`` in :attr:`metainfo`\ ``['info']`` when all
pieces are hashed successfully.
:param callable callback: Callable with signature ``(torrent, filepath,
... | python | def generate(self, callback=None, interval=0):
"""
Hash pieces and report progress to `callback`
This method sets ``pieces`` in :attr:`metainfo`\ ``['info']`` when all
pieces are hashed successfully.
:param callable callback: Callable with signature ``(torrent, filepath,
... | [
"def",
"generate",
"(",
"self",
",",
"callback",
"=",
"None",
",",
"interval",
"=",
"0",
")",
":",
"if",
"self",
".",
"path",
"is",
"None",
":",
"raise",
"RuntimeError",
"(",
"'generate() called with no path specified'",
")",
"elif",
"self",
".",
"size",
"... | Hash pieces and report progress to `callback`
This method sets ``pieces`` in :attr:`metainfo`\ ``['info']`` when all
pieces are hashed successfully.
:param callable callback: Callable with signature ``(torrent, filepath,
pieces_done, pieces_total)``; if `callback` returns anything ... | [
"Hash",
"pieces",
"and",
"report",
"progress",
"to",
"callback"
] | df0363232daacd3f8c91aafddaa0623b8c28cbd2 | https://github.com/rndusr/torf/blob/df0363232daacd3f8c91aafddaa0623b8c28cbd2/torf/_torrent.py#L593-L641 | train |
rndusr/torf | torf/_torrent.py | Torrent.magnet | def magnet(self, name=True, size=True, trackers=True, tracker=False, validate=True):
"""
BTIH Magnet URI
:param bool name: Whether to include the name
:param bool size: Whether to include the size
:param bool trackers: Whether to include all trackers
:param bool tracker:... | python | def magnet(self, name=True, size=True, trackers=True, tracker=False, validate=True):
"""
BTIH Magnet URI
:param bool name: Whether to include the name
:param bool size: Whether to include the size
:param bool trackers: Whether to include all trackers
:param bool tracker:... | [
"def",
"magnet",
"(",
"self",
",",
"name",
"=",
"True",
",",
"size",
"=",
"True",
",",
"trackers",
"=",
"True",
",",
"tracker",
"=",
"False",
",",
"validate",
"=",
"True",
")",
":",
"if",
"validate",
":",
"self",
".",
"validate",
"(",
")",
"parts",... | BTIH Magnet URI
:param bool name: Whether to include the name
:param bool size: Whether to include the size
:param bool trackers: Whether to include all trackers
:param bool tracker: Whether to include only the first tracker of the
first tier (overrides `trackers`)
:... | [
"BTIH",
"Magnet",
"URI"
] | df0363232daacd3f8c91aafddaa0623b8c28cbd2 | https://github.com/rndusr/torf/blob/df0363232daacd3f8c91aafddaa0623b8c28cbd2/torf/_torrent.py#L867-L895 | train |
rndusr/torf | torf/_torrent.py | Torrent.read_stream | def read_stream(cls, stream, validate=True):
"""
Read torrent metainfo from file-like object
:param stream: Readable file-like object (e.g. :class:`io.BytesIO`)
:param bool validate: Whether to run :meth:`validate` on the new Torrent
object
:raises ReadError: if rea... | python | def read_stream(cls, stream, validate=True):
"""
Read torrent metainfo from file-like object
:param stream: Readable file-like object (e.g. :class:`io.BytesIO`)
:param bool validate: Whether to run :meth:`validate` on the new Torrent
object
:raises ReadError: if rea... | [
"def",
"read_stream",
"(",
"cls",
",",
"stream",
",",
"validate",
"=",
"True",
")",
":",
"try",
":",
"content",
"=",
"stream",
".",
"read",
"(",
"cls",
".",
"MAX_TORRENT_FILE_SIZE",
")",
"except",
"OSError",
"as",
"e",
":",
"raise",
"error",
".",
"Read... | Read torrent metainfo from file-like object
:param stream: Readable file-like object (e.g. :class:`io.BytesIO`)
:param bool validate: Whether to run :meth:`validate` on the new Torrent
object
:raises ReadError: if reading from `stream` fails
:raises ParseError: if `stream` ... | [
"Read",
"torrent",
"metainfo",
"from",
"file",
"-",
"like",
"object"
] | df0363232daacd3f8c91aafddaa0623b8c28cbd2 | https://github.com/rndusr/torf/blob/df0363232daacd3f8c91aafddaa0623b8c28cbd2/torf/_torrent.py#L903-L963 | train |
rndusr/torf | torf/_torrent.py | Torrent.read | def read(cls, filepath, validate=True):
"""
Read torrent metainfo from file
:param filepath: Path of the torrent file
:param bool validate: Whether to run :meth:`validate` on the new Torrent
object
:raises ReadError: if reading from `filepath` fails
:raises ... | python | def read(cls, filepath, validate=True):
"""
Read torrent metainfo from file
:param filepath: Path of the torrent file
:param bool validate: Whether to run :meth:`validate` on the new Torrent
object
:raises ReadError: if reading from `filepath` fails
:raises ... | [
"def",
"read",
"(",
"cls",
",",
"filepath",
",",
"validate",
"=",
"True",
")",
":",
"try",
":",
"with",
"open",
"(",
"filepath",
",",
"'rb'",
")",
"as",
"fh",
":",
"return",
"cls",
".",
"read_stream",
"(",
"fh",
")",
"except",
"(",
"OSError",
",",
... | Read torrent metainfo from file
:param filepath: Path of the torrent file
:param bool validate: Whether to run :meth:`validate` on the new Torrent
object
:raises ReadError: if reading from `filepath` fails
:raises ParseError: if `filepath` does not contain a valid bencoded ... | [
"Read",
"torrent",
"metainfo",
"from",
"file"
] | df0363232daacd3f8c91aafddaa0623b8c28cbd2 | https://github.com/rndusr/torf/blob/df0363232daacd3f8c91aafddaa0623b8c28cbd2/torf/_torrent.py#L966-L988 | train |
rndusr/torf | torf/_torrent.py | Torrent.copy | def copy(self):
"""
Return a new object with the same metainfo
Internally, this simply copies the internal metainfo dictionary with
:func:`copy.deepcopy` and gives it to the new instance.
"""
from copy import deepcopy
cp = type(self)()
cp._metainfo = deep... | python | def copy(self):
"""
Return a new object with the same metainfo
Internally, this simply copies the internal metainfo dictionary with
:func:`copy.deepcopy` and gives it to the new instance.
"""
from copy import deepcopy
cp = type(self)()
cp._metainfo = deep... | [
"def",
"copy",
"(",
"self",
")",
":",
"from",
"copy",
"import",
"deepcopy",
"cp",
"=",
"type",
"(",
"self",
")",
"(",
")",
"cp",
".",
"_metainfo",
"=",
"deepcopy",
"(",
"self",
".",
"_metainfo",
")",
"return",
"cp"
] | Return a new object with the same metainfo
Internally, this simply copies the internal metainfo dictionary with
:func:`copy.deepcopy` and gives it to the new instance. | [
"Return",
"a",
"new",
"object",
"with",
"the",
"same",
"metainfo"
] | df0363232daacd3f8c91aafddaa0623b8c28cbd2 | https://github.com/rndusr/torf/blob/df0363232daacd3f8c91aafddaa0623b8c28cbd2/torf/_torrent.py#L990-L1000 | train |
rndusr/torf | torf/_utils.py | validated_url | def validated_url(url):
"""Return url if valid, raise URLError otherwise"""
try:
u = urlparse(url)
u.port # Trigger 'invalid port' exception
except Exception:
raise error.URLError(url)
else:
if not u.scheme or not u.netloc:
raise error.URLError(url)
r... | python | def validated_url(url):
"""Return url if valid, raise URLError otherwise"""
try:
u = urlparse(url)
u.port # Trigger 'invalid port' exception
except Exception:
raise error.URLError(url)
else:
if not u.scheme or not u.netloc:
raise error.URLError(url)
r... | [
"def",
"validated_url",
"(",
"url",
")",
":",
"try",
":",
"u",
"=",
"urlparse",
"(",
"url",
")",
"u",
".",
"port",
"except",
"Exception",
":",
"raise",
"error",
".",
"URLError",
"(",
"url",
")",
"else",
":",
"if",
"not",
"u",
".",
"scheme",
"or",
... | Return url if valid, raise URLError otherwise | [
"Return",
"url",
"if",
"valid",
"raise",
"URLError",
"otherwise"
] | df0363232daacd3f8c91aafddaa0623b8c28cbd2 | https://github.com/rndusr/torf/blob/df0363232daacd3f8c91aafddaa0623b8c28cbd2/torf/_utils.py#L38-L48 | train |
rndusr/torf | torf/_utils.py | read_chunks | def read_chunks(filepath, chunk_size):
"""Generator that yields chunks from file"""
try:
with open(filepath, 'rb') as f:
while True:
chunk = f.read(chunk_size)
if chunk:
yield chunk
else:
break # EOF
... | python | def read_chunks(filepath, chunk_size):
"""Generator that yields chunks from file"""
try:
with open(filepath, 'rb') as f:
while True:
chunk = f.read(chunk_size)
if chunk:
yield chunk
else:
break # EOF
... | [
"def",
"read_chunks",
"(",
"filepath",
",",
"chunk_size",
")",
":",
"try",
":",
"with",
"open",
"(",
"filepath",
",",
"'rb'",
")",
"as",
"f",
":",
"while",
"True",
":",
"chunk",
"=",
"f",
".",
"read",
"(",
"chunk_size",
")",
"if",
"chunk",
":",
"yi... | Generator that yields chunks from file | [
"Generator",
"that",
"yields",
"chunks",
"from",
"file"
] | df0363232daacd3f8c91aafddaa0623b8c28cbd2 | https://github.com/rndusr/torf/blob/df0363232daacd3f8c91aafddaa0623b8c28cbd2/torf/_utils.py#L51-L62 | train |
rndusr/torf | torf/_utils.py | calc_piece_size | def calc_piece_size(total_size, max_pieces, min_piece_size, max_piece_size):
"""Calculate piece size"""
ps = 1 << max(0, math.ceil(math.log(total_size / max_pieces, 2)))
if ps < min_piece_size:
ps = min_piece_size
if ps > max_piece_size:
ps = max_piece_size
return ps | python | def calc_piece_size(total_size, max_pieces, min_piece_size, max_piece_size):
"""Calculate piece size"""
ps = 1 << max(0, math.ceil(math.log(total_size / max_pieces, 2)))
if ps < min_piece_size:
ps = min_piece_size
if ps > max_piece_size:
ps = max_piece_size
return ps | [
"def",
"calc_piece_size",
"(",
"total_size",
",",
"max_pieces",
",",
"min_piece_size",
",",
"max_piece_size",
")",
":",
"ps",
"=",
"1",
"<<",
"max",
"(",
"0",
",",
"math",
".",
"ceil",
"(",
"math",
".",
"log",
"(",
"total_size",
"/",
"max_pieces",
",",
... | Calculate piece size | [
"Calculate",
"piece",
"size"
] | df0363232daacd3f8c91aafddaa0623b8c28cbd2 | https://github.com/rndusr/torf/blob/df0363232daacd3f8c91aafddaa0623b8c28cbd2/torf/_utils.py#L65-L72 | train |
rndusr/torf | torf/_utils.py | is_power_of_2 | def is_power_of_2(num):
"""Return whether `num` is a power of two"""
log = math.log2(num)
return int(log) == float(log) | python | def is_power_of_2(num):
"""Return whether `num` is a power of two"""
log = math.log2(num)
return int(log) == float(log) | [
"def",
"is_power_of_2",
"(",
"num",
")",
":",
"log",
"=",
"math",
".",
"log2",
"(",
"num",
")",
"return",
"int",
"(",
"log",
")",
"==",
"float",
"(",
"log",
")"
] | Return whether `num` is a power of two | [
"Return",
"whether",
"num",
"is",
"a",
"power",
"of",
"two"
] | df0363232daacd3f8c91aafddaa0623b8c28cbd2 | https://github.com/rndusr/torf/blob/df0363232daacd3f8c91aafddaa0623b8c28cbd2/torf/_utils.py#L75-L78 | train |
rndusr/torf | torf/_utils.py | is_hidden | def is_hidden(path):
"""Whether file or directory is hidden"""
for name in path.split(os.sep):
if name != '.' and name != '..' and name and name[0] == '.':
return True
return False | python | def is_hidden(path):
"""Whether file or directory is hidden"""
for name in path.split(os.sep):
if name != '.' and name != '..' and name and name[0] == '.':
return True
return False | [
"def",
"is_hidden",
"(",
"path",
")",
":",
"for",
"name",
"in",
"path",
".",
"split",
"(",
"os",
".",
"sep",
")",
":",
"if",
"name",
"!=",
"'.'",
"and",
"name",
"!=",
"'..'",
"and",
"name",
"and",
"name",
"[",
"0",
"]",
"==",
"'.'",
":",
"retur... | Whether file or directory is hidden | [
"Whether",
"file",
"or",
"directory",
"is",
"hidden"
] | df0363232daacd3f8c91aafddaa0623b8c28cbd2 | https://github.com/rndusr/torf/blob/df0363232daacd3f8c91aafddaa0623b8c28cbd2/torf/_utils.py#L81-L86 | train |
rndusr/torf | torf/_utils.py | filepaths | def filepaths(path, exclude=(), hidden=True, empty=True):
"""
Return list of absolute, sorted file paths
path: Path to file or directory
exclude: List of file name patterns to exclude
hidden: Whether to include hidden files
empty: Whether to include empty files
Raise PathNotFoundError if p... | python | def filepaths(path, exclude=(), hidden=True, empty=True):
"""
Return list of absolute, sorted file paths
path: Path to file or directory
exclude: List of file name patterns to exclude
hidden: Whether to include hidden files
empty: Whether to include empty files
Raise PathNotFoundError if p... | [
"def",
"filepaths",
"(",
"path",
",",
"exclude",
"=",
"(",
")",
",",
"hidden",
"=",
"True",
",",
"empty",
"=",
"True",
")",
":",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"path",
")",
":",
"raise",
"error",
".",
"PathNotFoundError",
"(",
... | Return list of absolute, sorted file paths
path: Path to file or directory
exclude: List of file name patterns to exclude
hidden: Whether to include hidden files
empty: Whether to include empty files
Raise PathNotFoundError if path doesn't exist. | [
"Return",
"list",
"of",
"absolute",
"sorted",
"file",
"paths"
] | df0363232daacd3f8c91aafddaa0623b8c28cbd2 | https://github.com/rndusr/torf/blob/df0363232daacd3f8c91aafddaa0623b8c28cbd2/torf/_utils.py#L96-L136 | train |
rndusr/torf | torf/_utils.py | assert_type | def assert_type(lst_or_dct, keys, exp_types, must_exist=True, check=None):
"""
Raise MetainfoError is not of a particular type
lst_or_dct: list or dict instance
keys: Sequence of keys so that `lst_or_dct[key[0]][key[1]]...` resolves to a
value
exp_types: Sequence of types that the value s... | python | def assert_type(lst_or_dct, keys, exp_types, must_exist=True, check=None):
"""
Raise MetainfoError is not of a particular type
lst_or_dct: list or dict instance
keys: Sequence of keys so that `lst_or_dct[key[0]][key[1]]...` resolves to a
value
exp_types: Sequence of types that the value s... | [
"def",
"assert_type",
"(",
"lst_or_dct",
",",
"keys",
",",
"exp_types",
",",
"must_exist",
"=",
"True",
",",
"check",
"=",
"None",
")",
":",
"keys",
"=",
"list",
"(",
"keys",
")",
"keychain",
"=",
"[",
"]",
"while",
"len",
"(",
"keys",
"[",
":",
"-... | Raise MetainfoError is not of a particular type
lst_or_dct: list or dict instance
keys: Sequence of keys so that `lst_or_dct[key[0]][key[1]]...` resolves to a
value
exp_types: Sequence of types that the value specified by `keys` must be an
instance of
must_exist: Whether to rai... | [
"Raise",
"MetainfoError",
"is",
"not",
"of",
"a",
"particular",
"type"
] | df0363232daacd3f8c91aafddaa0623b8c28cbd2 | https://github.com/rndusr/torf/blob/df0363232daacd3f8c91aafddaa0623b8c28cbd2/torf/_utils.py#L149-L188 | train |
reincubate/ricloud | ricloud/utils.py | error_message_and_exit | def error_message_and_exit(message, error_result):
"""Prints error messages in blue, the failed task result and quits."""
if message:
error_message(message)
puts(json.dumps(error_result, indent=2))
sys.exit(1) | python | def error_message_and_exit(message, error_result):
"""Prints error messages in blue, the failed task result and quits."""
if message:
error_message(message)
puts(json.dumps(error_result, indent=2))
sys.exit(1) | [
"def",
"error_message_and_exit",
"(",
"message",
",",
"error_result",
")",
":",
"if",
"message",
":",
"error_message",
"(",
"message",
")",
"puts",
"(",
"json",
".",
"dumps",
"(",
"error_result",
",",
"indent",
"=",
"2",
")",
")",
"sys",
".",
"exit",
"("... | Prints error messages in blue, the failed task result and quits. | [
"Prints",
"error",
"messages",
"in",
"blue",
"the",
"failed",
"task",
"result",
"and",
"quits",
"."
] | e46bce4529fbdca34a4190c18c7219e937e2b697 | https://github.com/reincubate/ricloud/blob/e46bce4529fbdca34a4190c18c7219e937e2b697/ricloud/utils.py#L82-L87 | train |
reincubate/ricloud | ricloud/utils.py | print_prompt_values | def print_prompt_values(values, message=None, sub_attr=None):
"""Prints prompt title and choices with a bit of formatting."""
if message:
prompt_message(message)
for index, entry in enumerate(values):
if sub_attr:
line = '{:2d}: {}'.format(index, getattr(utf8(entry), sub_attr))
... | python | def print_prompt_values(values, message=None, sub_attr=None):
"""Prints prompt title and choices with a bit of formatting."""
if message:
prompt_message(message)
for index, entry in enumerate(values):
if sub_attr:
line = '{:2d}: {}'.format(index, getattr(utf8(entry), sub_attr))
... | [
"def",
"print_prompt_values",
"(",
"values",
",",
"message",
"=",
"None",
",",
"sub_attr",
"=",
"None",
")",
":",
"if",
"message",
":",
"prompt_message",
"(",
"message",
")",
"for",
"index",
",",
"entry",
"in",
"enumerate",
"(",
"values",
")",
":",
"if",... | Prints prompt title and choices with a bit of formatting. | [
"Prints",
"prompt",
"title",
"and",
"choices",
"with",
"a",
"bit",
"of",
"formatting",
"."
] | e46bce4529fbdca34a4190c18c7219e937e2b697 | https://github.com/reincubate/ricloud/blob/e46bce4529fbdca34a4190c18c7219e937e2b697/ricloud/utils.py#L90-L102 | train |
reincubate/ricloud | ricloud/utils.py | prompt_for_input | def prompt_for_input(message, input_type=None):
"""Prints prompt instruction and does basic input parsing."""
while True:
output = prompt.query(message)
if input_type:
try:
output = input_type(output)
except ValueError:
error_message('Inva... | python | def prompt_for_input(message, input_type=None):
"""Prints prompt instruction and does basic input parsing."""
while True:
output = prompt.query(message)
if input_type:
try:
output = input_type(output)
except ValueError:
error_message('Inva... | [
"def",
"prompt_for_input",
"(",
"message",
",",
"input_type",
"=",
"None",
")",
":",
"while",
"True",
":",
"output",
"=",
"prompt",
".",
"query",
"(",
"message",
")",
"if",
"input_type",
":",
"try",
":",
"output",
"=",
"input_type",
"(",
"output",
")",
... | Prints prompt instruction and does basic input parsing. | [
"Prints",
"prompt",
"instruction",
"and",
"does",
"basic",
"input",
"parsing",
"."
] | e46bce4529fbdca34a4190c18c7219e937e2b697 | https://github.com/reincubate/ricloud/blob/e46bce4529fbdca34a4190c18c7219e937e2b697/ricloud/utils.py#L105-L119 | train |
reincubate/ricloud | ricloud/utils.py | prompt_for_choice | def prompt_for_choice(values, message, input_type=int, output_type=None):
"""Prints prompt with a list of choices to choose from."""
output = None
while not output:
index = prompt_for_input(message, input_type=input_type)
try:
output = utf8(values[index])
except IndexErr... | python | def prompt_for_choice(values, message, input_type=int, output_type=None):
"""Prints prompt with a list of choices to choose from."""
output = None
while not output:
index = prompt_for_input(message, input_type=input_type)
try:
output = utf8(values[index])
except IndexErr... | [
"def",
"prompt_for_choice",
"(",
"values",
",",
"message",
",",
"input_type",
"=",
"int",
",",
"output_type",
"=",
"None",
")",
":",
"output",
"=",
"None",
"while",
"not",
"output",
":",
"index",
"=",
"prompt_for_input",
"(",
"message",
",",
"input_type",
... | Prints prompt with a list of choices to choose from. | [
"Prints",
"prompt",
"with",
"a",
"list",
"of",
"choices",
"to",
"choose",
"from",
"."
] | e46bce4529fbdca34a4190c18c7219e937e2b697 | https://github.com/reincubate/ricloud/blob/e46bce4529fbdca34a4190c18c7219e937e2b697/ricloud/utils.py#L122-L137 | train |
reincubate/ricloud | ricloud/object_store.py | ObjectStore._retrieve_result | def _retrieve_result(endpoints, token_header):
"""Prepare the request list and execute them concurrently."""
request_list = [
(url, token_header)
for (task_id, url) in endpoints
]
responses = concurrent_get(request_list)
# Quick sanity check
asse... | python | def _retrieve_result(endpoints, token_header):
"""Prepare the request list and execute them concurrently."""
request_list = [
(url, token_header)
for (task_id, url) in endpoints
]
responses = concurrent_get(request_list)
# Quick sanity check
asse... | [
"def",
"_retrieve_result",
"(",
"endpoints",
",",
"token_header",
")",
":",
"request_list",
"=",
"[",
"(",
"url",
",",
"token_header",
")",
"for",
"(",
"task_id",
",",
"url",
")",
"in",
"endpoints",
"]",
"responses",
"=",
"concurrent_get",
"(",
"request_list... | Prepare the request list and execute them concurrently. | [
"Prepare",
"the",
"request",
"list",
"and",
"execute",
"them",
"concurrently",
"."
] | e46bce4529fbdca34a4190c18c7219e937e2b697 | https://github.com/reincubate/ricloud/blob/e46bce4529fbdca34a4190c18c7219e937e2b697/ricloud/object_store.py#L62-L78 | train |
reincubate/ricloud | ricloud/asmaster_api.py | AsmasterApi._build_endpoint | def _build_endpoint(self, endpoint_name):
"""Generate an enpoint url from a setting name.
Args:
endpoint_name(str): setting name for the enpoint to build
Returns:
(str) url enpoint
"""
endpoint_relative = settings.get('asmaster_endpoints', endpoint_name)... | python | def _build_endpoint(self, endpoint_name):
"""Generate an enpoint url from a setting name.
Args:
endpoint_name(str): setting name for the enpoint to build
Returns:
(str) url enpoint
"""
endpoint_relative = settings.get('asmaster_endpoints', endpoint_name)... | [
"def",
"_build_endpoint",
"(",
"self",
",",
"endpoint_name",
")",
":",
"endpoint_relative",
"=",
"settings",
".",
"get",
"(",
"'asmaster_endpoints'",
",",
"endpoint_name",
")",
"return",
"'%s%s'",
"%",
"(",
"self",
".",
"host",
",",
"endpoint_relative",
")"
] | Generate an enpoint url from a setting name.
Args:
endpoint_name(str): setting name for the enpoint to build
Returns:
(str) url enpoint | [
"Generate",
"an",
"enpoint",
"url",
"from",
"a",
"setting",
"name",
"."
] | e46bce4529fbdca34a4190c18c7219e937e2b697 | https://github.com/reincubate/ricloud/blob/e46bce4529fbdca34a4190c18c7219e937e2b697/ricloud/asmaster_api.py#L33-L43 | train |
reincubate/ricloud | ricloud/asmaster_api.py | AsmasterApi._set_allowed_services_and_actions | def _set_allowed_services_and_actions(self, services):
"""Expect services to be a list of service dictionaries, each with `name` and `actions` keys."""
for service in services:
self.services[service['name']] = {}
for action in service['actions']:
name = action.po... | python | def _set_allowed_services_and_actions(self, services):
"""Expect services to be a list of service dictionaries, each with `name` and `actions` keys."""
for service in services:
self.services[service['name']] = {}
for action in service['actions']:
name = action.po... | [
"def",
"_set_allowed_services_and_actions",
"(",
"self",
",",
"services",
")",
":",
"for",
"service",
"in",
"services",
":",
"self",
".",
"services",
"[",
"service",
"[",
"'name'",
"]",
"]",
"=",
"{",
"}",
"for",
"action",
"in",
"service",
"[",
"'actions'"... | Expect services to be a list of service dictionaries, each with `name` and `actions` keys. | [
"Expect",
"services",
"to",
"be",
"a",
"list",
"of",
"service",
"dictionaries",
"each",
"with",
"name",
"and",
"actions",
"keys",
"."
] | e46bce4529fbdca34a4190c18c7219e937e2b697 | https://github.com/reincubate/ricloud/blob/e46bce4529fbdca34a4190c18c7219e937e2b697/ricloud/asmaster_api.py#L59-L66 | train |
reincubate/ricloud | ricloud/asmaster_api.py | AsmasterApi.list_subscriptions | def list_subscriptions(self, service):
"""Asks for a list of all subscribed accounts and devices, along with their statuses."""
data = {
'service': service,
}
return self._perform_post_request(self.list_subscriptions_endpoint, data, self.token_header) | python | def list_subscriptions(self, service):
"""Asks for a list of all subscribed accounts and devices, along with their statuses."""
data = {
'service': service,
}
return self._perform_post_request(self.list_subscriptions_endpoint, data, self.token_header) | [
"def",
"list_subscriptions",
"(",
"self",
",",
"service",
")",
":",
"data",
"=",
"{",
"'service'",
":",
"service",
",",
"}",
"return",
"self",
".",
"_perform_post_request",
"(",
"self",
".",
"list_subscriptions_endpoint",
",",
"data",
",",
"self",
".",
"toke... | Asks for a list of all subscribed accounts and devices, along with their statuses. | [
"Asks",
"for",
"a",
"list",
"of",
"all",
"subscribed",
"accounts",
"and",
"devices",
"along",
"with",
"their",
"statuses",
"."
] | e46bce4529fbdca34a4190c18c7219e937e2b697 | https://github.com/reincubate/ricloud/blob/e46bce4529fbdca34a4190c18c7219e937e2b697/ricloud/asmaster_api.py#L84-L89 | train |
reincubate/ricloud | ricloud/asmaster_api.py | AsmasterApi.subscribe_account | def subscribe_account(self, username, password, service):
"""Subscribe an account for a service.
"""
data = {
'service': service,
'username': username,
'password': password,
}
return self._perform_post_request(self.subscribe_account_endpoint, ... | python | def subscribe_account(self, username, password, service):
"""Subscribe an account for a service.
"""
data = {
'service': service,
'username': username,
'password': password,
}
return self._perform_post_request(self.subscribe_account_endpoint, ... | [
"def",
"subscribe_account",
"(",
"self",
",",
"username",
",",
"password",
",",
"service",
")",
":",
"data",
"=",
"{",
"'service'",
":",
"service",
",",
"'username'",
":",
"username",
",",
"'password'",
":",
"password",
",",
"}",
"return",
"self",
".",
"... | Subscribe an account for a service. | [
"Subscribe",
"an",
"account",
"for",
"a",
"service",
"."
] | e46bce4529fbdca34a4190c18c7219e937e2b697 | https://github.com/reincubate/ricloud/blob/e46bce4529fbdca34a4190c18c7219e937e2b697/ricloud/asmaster_api.py#L91-L100 | train |
reincubate/ricloud | ricloud/asmaster_listener.py | AsmasterDownloadFileHandler.file_id_to_file_name | def file_id_to_file_name(file_id):
"""Sometimes file ids are not the file names on the device, but are instead generated
by the API. These are not guaranteed to be valid file names so need hashing.
"""
if len(file_id) == 40 and re.match("^[a-f0-9]+$", file_id):
return file_id... | python | def file_id_to_file_name(file_id):
"""Sometimes file ids are not the file names on the device, but are instead generated
by the API. These are not guaranteed to be valid file names so need hashing.
"""
if len(file_id) == 40 and re.match("^[a-f0-9]+$", file_id):
return file_id... | [
"def",
"file_id_to_file_name",
"(",
"file_id",
")",
":",
"if",
"len",
"(",
"file_id",
")",
"==",
"40",
"and",
"re",
".",
"match",
"(",
"\"^[a-f0-9]+$\"",
",",
"file_id",
")",
":",
"return",
"file_id",
"return",
"\"re_{}\"",
".",
"format",
"(",
"hashlib",
... | Sometimes file ids are not the file names on the device, but are instead generated
by the API. These are not guaranteed to be valid file names so need hashing. | [
"Sometimes",
"file",
"ids",
"are",
"not",
"the",
"file",
"names",
"on",
"the",
"device",
"but",
"are",
"instead",
"generated",
"by",
"the",
"API",
".",
"These",
"are",
"not",
"guaranteed",
"to",
"be",
"valid",
"file",
"names",
"so",
"need",
"hashing",
".... | e46bce4529fbdca34a4190c18c7219e937e2b697 | https://github.com/reincubate/ricloud/blob/e46bce4529fbdca34a4190c18c7219e937e2b697/ricloud/asmaster_listener.py#L216-L223 | train |
reincubate/ricloud | ricloud/clients/base.py | sync | def sync(func):
"""Decorator to make a task synchronous."""
sync_timeout = 3600 # Match standard synchronous timeout.
def wraps(*args, **kwargs):
task = func(*args, **kwargs)
task.wait_for_result(timeout=sync_timeout)
result = json.loads(task.result)
return result
retu... | python | def sync(func):
"""Decorator to make a task synchronous."""
sync_timeout = 3600 # Match standard synchronous timeout.
def wraps(*args, **kwargs):
task = func(*args, **kwargs)
task.wait_for_result(timeout=sync_timeout)
result = json.loads(task.result)
return result
retu... | [
"def",
"sync",
"(",
"func",
")",
":",
"sync_timeout",
"=",
"3600",
"def",
"wraps",
"(",
"*",
"args",
",",
"**",
"kwargs",
")",
":",
"task",
"=",
"func",
"(",
"*",
"args",
",",
"**",
"kwargs",
")",
"task",
".",
"wait_for_result",
"(",
"timeout",
"="... | Decorator to make a task synchronous. | [
"Decorator",
"to",
"make",
"a",
"task",
"synchronous",
"."
] | e46bce4529fbdca34a4190c18c7219e937e2b697 | https://github.com/reincubate/ricloud/blob/e46bce4529fbdca34a4190c18c7219e937e2b697/ricloud/clients/base.py#L4-L14 | train |
reincubate/ricloud | ricloud/samples/live_sample.py | SampleLiveICloudApplication.fetch_data | def fetch_data(self):
"""Prompt for a data type choice and execute the `fetch_data` task.
The results are saved to a file in json format.
"""
choices = self.available_data
choices.insert(0, 'All')
selected_data_type = utils.select_item(
choices,
'... | python | def fetch_data(self):
"""Prompt for a data type choice and execute the `fetch_data` task.
The results are saved to a file in json format.
"""
choices = self.available_data
choices.insert(0, 'All')
selected_data_type = utils.select_item(
choices,
'... | [
"def",
"fetch_data",
"(",
"self",
")",
":",
"choices",
"=",
"self",
".",
"available_data",
"choices",
".",
"insert",
"(",
"0",
",",
"'All'",
")",
"selected_data_type",
"=",
"utils",
".",
"select_item",
"(",
"choices",
",",
"'Please select what data to fetch:'",
... | Prompt for a data type choice and execute the `fetch_data` task.
The results are saved to a file in json format. | [
"Prompt",
"for",
"a",
"data",
"type",
"choice",
"and",
"execute",
"the",
"fetch_data",
"task",
".",
"The",
"results",
"are",
"saved",
"to",
"a",
"file",
"in",
"json",
"format",
"."
] | e46bce4529fbdca34a4190c18c7219e937e2b697 | https://github.com/reincubate/ricloud/blob/e46bce4529fbdca34a4190c18c7219e937e2b697/ricloud/samples/live_sample.py#L22-L58 | train |
reincubate/ricloud | ricloud/samples/icloud_sample.py | SampleICloudApplication.log_in | def log_in(self):
"""Perform the `log_in` task to setup the API session for future data requests."""
if not self.password:
# Password wasn't give, ask for it now
self.password = getpass.getpass('Password: ')
utils.pending_message('Performing login...')
login_res... | python | def log_in(self):
"""Perform the `log_in` task to setup the API session for future data requests."""
if not self.password:
# Password wasn't give, ask for it now
self.password = getpass.getpass('Password: ')
utils.pending_message('Performing login...')
login_res... | [
"def",
"log_in",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"password",
":",
"self",
".",
"password",
"=",
"getpass",
".",
"getpass",
"(",
"'Password: '",
")",
"utils",
".",
"pending_message",
"(",
"'Performing login...'",
")",
"login_result",
"=",
"... | Perform the `log_in` task to setup the API session for future data requests. | [
"Perform",
"the",
"log_in",
"task",
"to",
"setup",
"the",
"API",
"session",
"for",
"future",
"data",
"requests",
"."
] | e46bce4529fbdca34a4190c18c7219e937e2b697 | https://github.com/reincubate/ricloud/blob/e46bce4529fbdca34a4190c18c7219e937e2b697/ricloud/samples/icloud_sample.py#L43-L59 | train |
reincubate/ricloud | ricloud/samples/icloud_sample.py | SampleICloudApplication.get_devices | def get_devices(self):
"""Execute the `get_devices` task and store the results in `self.devices`."""
utils.pending_message('Fetching device list...')
get_devices_task = self.client.devices(
account=self.account
)
# We wait for device list info as this sample relies ... | python | def get_devices(self):
"""Execute the `get_devices` task and store the results in `self.devices`."""
utils.pending_message('Fetching device list...')
get_devices_task = self.client.devices(
account=self.account
)
# We wait for device list info as this sample relies ... | [
"def",
"get_devices",
"(",
"self",
")",
":",
"utils",
".",
"pending_message",
"(",
"'Fetching device list...'",
")",
"get_devices_task",
"=",
"self",
".",
"client",
".",
"devices",
"(",
"account",
"=",
"self",
".",
"account",
")",
"get_devices_task",
".",
"wai... | Execute the `get_devices` task and store the results in `self.devices`. | [
"Execute",
"the",
"get_devices",
"task",
"and",
"store",
"the",
"results",
"in",
"self",
".",
"devices",
"."
] | e46bce4529fbdca34a4190c18c7219e937e2b697 | https://github.com/reincubate/ricloud/blob/e46bce4529fbdca34a4190c18c7219e937e2b697/ricloud/samples/icloud_sample.py#L113-L127 | train |
reincubate/ricloud | ricloud/samples/icloud_sample.py | SampleICloudApplication.download_files | def download_files(self, files):
"""This method uses the `download_file` task to retrieve binary files
such as attachments, images and videos.
Notice that this method does not wait for the tasks it creates to return
a result synchronously.
"""
utils.pending_message(
... | python | def download_files(self, files):
"""This method uses the `download_file` task to retrieve binary files
such as attachments, images and videos.
Notice that this method does not wait for the tasks it creates to return
a result synchronously.
"""
utils.pending_message(
... | [
"def",
"download_files",
"(",
"self",
",",
"files",
")",
":",
"utils",
".",
"pending_message",
"(",
"\"Downloading {nfiles} file{plural}...\"",
".",
"format",
"(",
"nfiles",
"=",
"len",
"(",
"files",
")",
",",
"plural",
"=",
"'s'",
"if",
"len",
"(",
"files",... | This method uses the `download_file` task to retrieve binary files
such as attachments, images and videos.
Notice that this method does not wait for the tasks it creates to return
a result synchronously. | [
"This",
"method",
"uses",
"the",
"download_file",
"task",
"to",
"retrieve",
"binary",
"files",
"such",
"as",
"attachments",
"images",
"and",
"videos",
"."
] | e46bce4529fbdca34a4190c18c7219e937e2b697 | https://github.com/reincubate/ricloud/blob/e46bce4529fbdca34a4190c18c7219e937e2b697/ricloud/samples/icloud_sample.py#L183-L226 | train |
reincubate/ricloud | ricloud/api.py | Api.register_account | def register_account(self, username, service):
"""Register an account against a service.
The account that we're querying must be referenced during any
future task requests - so we know which account to link the task
too.
"""
data = {
'service': service,
... | python | def register_account(self, username, service):
"""Register an account against a service.
The account that we're querying must be referenced during any
future task requests - so we know which account to link the task
too.
"""
data = {
'service': service,
... | [
"def",
"register_account",
"(",
"self",
",",
"username",
",",
"service",
")",
":",
"data",
"=",
"{",
"'service'",
":",
"service",
",",
"'username'",
":",
"username",
",",
"}",
"return",
"self",
".",
"_perform_post_request",
"(",
"self",
".",
"register_accoun... | Register an account against a service.
The account that we're querying must be referenced during any
future task requests - so we know which account to link the task
too. | [
"Register",
"an",
"account",
"against",
"a",
"service",
".",
"The",
"account",
"that",
"we",
"re",
"querying",
"must",
"be",
"referenced",
"during",
"any",
"future",
"task",
"requests",
"-",
"so",
"we",
"know",
"which",
"account",
"to",
"link",
"the",
"tas... | e46bce4529fbdca34a4190c18c7219e937e2b697 | https://github.com/reincubate/ricloud/blob/e46bce4529fbdca34a4190c18c7219e937e2b697/ricloud/api.py#L79-L90 | train |
reincubate/ricloud | ricloud/api.py | Api.perform_task | def perform_task(self, service, task_name, account, payload, callback=None):
"""Submit a task to the API.
The task is executed asyncronously, and a Task object is returned.
"""
data = {
'service': service,
'action': task_name,
'account': account,
... | python | def perform_task(self, service, task_name, account, payload, callback=None):
"""Submit a task to the API.
The task is executed asyncronously, and a Task object is returned.
"""
data = {
'service': service,
'action': task_name,
'account': account,
... | [
"def",
"perform_task",
"(",
"self",
",",
"service",
",",
"task_name",
",",
"account",
",",
"payload",
",",
"callback",
"=",
"None",
")",
":",
"data",
"=",
"{",
"'service'",
":",
"service",
",",
"'action'",
":",
"task_name",
",",
"'account'",
":",
"accoun... | Submit a task to the API.
The task is executed asyncronously, and a Task object is returned. | [
"Submit",
"a",
"task",
"to",
"the",
"API",
".",
"The",
"task",
"is",
"executed",
"asyncronously",
"and",
"a",
"Task",
"object",
"is",
"returned",
"."
] | e46bce4529fbdca34a4190c18c7219e937e2b697 | https://github.com/reincubate/ricloud/blob/e46bce4529fbdca34a4190c18c7219e937e2b697/ricloud/api.py#L92-L108 | train |
reincubate/ricloud | ricloud/api.py | Api.task_status | def task_status(self, task_id):
"""Find the status of a task."""
data = {
'task_ids': task_id,
}
return self._perform_post_request(self.task_status_endpoint, data, self.token_header) | python | def task_status(self, task_id):
"""Find the status of a task."""
data = {
'task_ids': task_id,
}
return self._perform_post_request(self.task_status_endpoint, data, self.token_header) | [
"def",
"task_status",
"(",
"self",
",",
"task_id",
")",
":",
"data",
"=",
"{",
"'task_ids'",
":",
"task_id",
",",
"}",
"return",
"self",
".",
"_perform_post_request",
"(",
"self",
".",
"task_status_endpoint",
",",
"data",
",",
"self",
".",
"token_header",
... | Find the status of a task. | [
"Find",
"the",
"status",
"of",
"a",
"task",
"."
] | e46bce4529fbdca34a4190c18c7219e937e2b697 | https://github.com/reincubate/ricloud/blob/e46bce4529fbdca34a4190c18c7219e937e2b697/ricloud/api.py#L110-L115 | train |
reincubate/ricloud | ricloud/api.py | Api.result_consumed | def result_consumed(self, task_id):
"""Report the result as successfully consumed."""
logger.debug('Sending result consumed message.')
data = {
'task_ids': task_id,
}
return self._perform_post_request(self.results_consumed_endpoint, data, self.token_header) | python | def result_consumed(self, task_id):
"""Report the result as successfully consumed."""
logger.debug('Sending result consumed message.')
data = {
'task_ids': task_id,
}
return self._perform_post_request(self.results_consumed_endpoint, data, self.token_header) | [
"def",
"result_consumed",
"(",
"self",
",",
"task_id",
")",
":",
"logger",
".",
"debug",
"(",
"'Sending result consumed message.'",
")",
"data",
"=",
"{",
"'task_ids'",
":",
"task_id",
",",
"}",
"return",
"self",
".",
"_perform_post_request",
"(",
"self",
".",... | Report the result as successfully consumed. | [
"Report",
"the",
"result",
"as",
"successfully",
"consumed",
"."
] | e46bce4529fbdca34a4190c18c7219e937e2b697 | https://github.com/reincubate/ricloud/blob/e46bce4529fbdca34a4190c18c7219e937e2b697/ricloud/api.py#L117-L123 | train |
nitmir/django-cas-server | cas_server/models.py | NewVersionWarning.send_mails | def send_mails(cls):
"""
For each new django-cas-server version, if the current instance is not up to date
send one mail to ``settings.ADMINS``.
"""
if settings.CAS_NEW_VERSION_EMAIL_WARNING and settings.ADMINS:
try:
obj = cls.objects.get()
... | python | def send_mails(cls):
"""
For each new django-cas-server version, if the current instance is not up to date
send one mail to ``settings.ADMINS``.
"""
if settings.CAS_NEW_VERSION_EMAIL_WARNING and settings.ADMINS:
try:
obj = cls.objects.get()
... | [
"def",
"send_mails",
"(",
"cls",
")",
":",
"if",
"settings",
".",
"CAS_NEW_VERSION_EMAIL_WARNING",
"and",
"settings",
".",
"ADMINS",
":",
"try",
":",
"obj",
"=",
"cls",
".",
"objects",
".",
"get",
"(",
")",
"except",
"cls",
".",
"DoesNotExist",
":",
"obj... | For each new django-cas-server version, if the current instance is not up to date
send one mail to ``settings.ADMINS``. | [
"For",
"each",
"new",
"django",
"-",
"cas",
"-",
"server",
"version",
"if",
"the",
"current",
"instance",
"is",
"not",
"up",
"to",
"date",
"send",
"one",
"mail",
"to",
"settings",
".",
"ADMINS",
"."
] | d106181b94c444f1946269da5c20f6c904840ad3 | https://github.com/nitmir/django-cas-server/blob/d106181b94c444f1946269da5c20f6c904840ad3/cas_server/models.py#L1072-L1117 | train |
nitmir/django-cas-server | cas_server/cas.py | CASClientBase.get_proxy_url | def get_proxy_url(self, pgt):
"""Returns proxy url, given the proxy granting ticket"""
params = urllib_parse.urlencode({'pgt': pgt, 'targetService': self.service_url})
return "%s/proxy?%s" % (self.server_url, params) | python | def get_proxy_url(self, pgt):
"""Returns proxy url, given the proxy granting ticket"""
params = urllib_parse.urlencode({'pgt': pgt, 'targetService': self.service_url})
return "%s/proxy?%s" % (self.server_url, params) | [
"def",
"get_proxy_url",
"(",
"self",
",",
"pgt",
")",
":",
"params",
"=",
"urllib_parse",
".",
"urlencode",
"(",
"{",
"'pgt'",
":",
"pgt",
",",
"'targetService'",
":",
"self",
".",
"service_url",
"}",
")",
"return",
"\"%s/proxy?%s\"",
"%",
"(",
"self",
"... | Returns proxy url, given the proxy granting ticket | [
"Returns",
"proxy",
"url",
"given",
"the",
"proxy",
"granting",
"ticket"
] | d106181b94c444f1946269da5c20f6c904840ad3 | https://github.com/nitmir/django-cas-server/blob/d106181b94c444f1946269da5c20f6c904840ad3/cas_server/cas.py#L112-L115 | train |
nitmir/django-cas-server | cas_server/auth.py | LdapAuthUser.get_conn | def get_conn(cls):
"""Return a connection object to the ldap database"""
conn = cls._conn
if conn is None or conn.closed:
conn = ldap3.Connection(
settings.CAS_LDAP_SERVER,
settings.CAS_LDAP_USER,
settings.CAS_LDAP_PASSWORD,
... | python | def get_conn(cls):
"""Return a connection object to the ldap database"""
conn = cls._conn
if conn is None or conn.closed:
conn = ldap3.Connection(
settings.CAS_LDAP_SERVER,
settings.CAS_LDAP_USER,
settings.CAS_LDAP_PASSWORD,
... | [
"def",
"get_conn",
"(",
"cls",
")",
":",
"conn",
"=",
"cls",
".",
"_conn",
"if",
"conn",
"is",
"None",
"or",
"conn",
".",
"closed",
":",
"conn",
"=",
"ldap3",
".",
"Connection",
"(",
"settings",
".",
"CAS_LDAP_SERVER",
",",
"settings",
".",
"CAS_LDAP_U... | Return a connection object to the ldap database | [
"Return",
"a",
"connection",
"object",
"to",
"the",
"ldap",
"database"
] | d106181b94c444f1946269da5c20f6c904840ad3 | https://github.com/nitmir/django-cas-server/blob/d106181b94c444f1946269da5c20f6c904840ad3/cas_server/auth.py#L272-L284 | train |
nitmir/django-cas-server | cas_server/utils.py | json_encode | def json_encode(obj):
"""Encode a python object to json"""
try:
return json_encode.encoder.encode(obj)
except AttributeError:
json_encode.encoder = DjangoJSONEncoder(default=six.text_type)
return json_encode(obj) | python | def json_encode(obj):
"""Encode a python object to json"""
try:
return json_encode.encoder.encode(obj)
except AttributeError:
json_encode.encoder = DjangoJSONEncoder(default=six.text_type)
return json_encode(obj) | [
"def",
"json_encode",
"(",
"obj",
")",
":",
"try",
":",
"return",
"json_encode",
".",
"encoder",
".",
"encode",
"(",
"obj",
")",
"except",
"AttributeError",
":",
"json_encode",
".",
"encoder",
"=",
"DjangoJSONEncoder",
"(",
"default",
"=",
"six",
".",
"tex... | Encode a python object to json | [
"Encode",
"a",
"python",
"object",
"to",
"json"
] | d106181b94c444f1946269da5c20f6c904840ad3 | https://github.com/nitmir/django-cas-server/blob/d106181b94c444f1946269da5c20f6c904840ad3/cas_server/utils.py#L50-L56 | train |
nitmir/django-cas-server | cas_server/utils.py | context | def context(params):
"""
Function that add somes variable to the context before template rendering
:param dict params: The context dictionary used to render templates.
:return: The ``params`` dictionary with the key ``settings`` set to
:obj:`django.conf.settings`.
:rtype... | python | def context(params):
"""
Function that add somes variable to the context before template rendering
:param dict params: The context dictionary used to render templates.
:return: The ``params`` dictionary with the key ``settings`` set to
:obj:`django.conf.settings`.
:rtype... | [
"def",
"context",
"(",
"params",
")",
":",
"params",
"[",
"\"settings\"",
"]",
"=",
"settings",
"params",
"[",
"\"message_levels\"",
"]",
"=",
"DEFAULT_MESSAGE_LEVELS",
"if",
"settings",
".",
"CAS_NEW_VERSION_HTML_WARNING",
":",
"LAST_VERSION",
"=",
"last_version",
... | Function that add somes variable to the context before template rendering
:param dict params: The context dictionary used to render templates.
:return: The ``params`` dictionary with the key ``settings`` set to
:obj:`django.conf.settings`.
:rtype: dict | [
"Function",
"that",
"add",
"somes",
"variable",
"to",
"the",
"context",
"before",
"template",
"rendering"
] | d106181b94c444f1946269da5c20f6c904840ad3 | https://github.com/nitmir/django-cas-server/blob/d106181b94c444f1946269da5c20f6c904840ad3/cas_server/utils.py#L59-L100 | train |
nitmir/django-cas-server | cas_server/utils.py | json_response | def json_response(request, data):
"""
Wrapper dumping `data` to a json and sending it to the user with an HttpResponse
:param django.http.HttpRequest request: The request object used to generate this response.
:param dict data: The python dictionnary to return as a json
:return: The... | python | def json_response(request, data):
"""
Wrapper dumping `data` to a json and sending it to the user with an HttpResponse
:param django.http.HttpRequest request: The request object used to generate this response.
:param dict data: The python dictionnary to return as a json
:return: The... | [
"def",
"json_response",
"(",
"request",
",",
"data",
")",
":",
"data",
"[",
"\"messages\"",
"]",
"=",
"[",
"]",
"for",
"msg",
"in",
"messages",
".",
"get_messages",
"(",
"request",
")",
":",
"data",
"[",
"\"messages\"",
"]",
".",
"append",
"(",
"{",
... | Wrapper dumping `data` to a json and sending it to the user with an HttpResponse
:param django.http.HttpRequest request: The request object used to generate this response.
:param dict data: The python dictionnary to return as a json
:return: The content of ``data`` serialized in json
:r... | [
"Wrapper",
"dumping",
"data",
"to",
"a",
"json",
"and",
"sending",
"it",
"to",
"the",
"user",
"with",
"an",
"HttpResponse"
] | d106181b94c444f1946269da5c20f6c904840ad3 | https://github.com/nitmir/django-cas-server/blob/d106181b94c444f1946269da5c20f6c904840ad3/cas_server/utils.py#L103-L115 | train |
nitmir/django-cas-server | cas_server/utils.py | import_attr | def import_attr(path):
"""
transform a python dotted path to the attr
:param path: A dotted path to a python object or a python object
:type path: :obj:`unicode` or :obj:`str` or anything
:return: The python object pointed by the dotted path or the python object unchanged
"""
... | python | def import_attr(path):
"""
transform a python dotted path to the attr
:param path: A dotted path to a python object or a python object
:type path: :obj:`unicode` or :obj:`str` or anything
:return: The python object pointed by the dotted path or the python object unchanged
"""
... | [
"def",
"import_attr",
"(",
"path",
")",
":",
"if",
"isinstance",
"(",
"path",
",",
"six",
".",
"binary_type",
")",
":",
"path",
"=",
"path",
".",
"decode",
"(",
"\"utf-8\"",
")",
"if",
"not",
"isinstance",
"(",
"path",
",",
"six",
".",
"text_type",
"... | transform a python dotted path to the attr
:param path: A dotted path to a python object or a python object
:type path: :obj:`unicode` or :obj:`str` or anything
:return: The python object pointed by the dotted path or the python object unchanged | [
"transform",
"a",
"python",
"dotted",
"path",
"to",
"the",
"attr"
] | d106181b94c444f1946269da5c20f6c904840ad3 | https://github.com/nitmir/django-cas-server/blob/d106181b94c444f1946269da5c20f6c904840ad3/cas_server/utils.py#L118-L140 | train |
nitmir/django-cas-server | cas_server/utils.py | redirect_params | def redirect_params(url_name, params=None):
"""
Redirect to ``url_name`` with ``params`` as querystring
:param unicode url_name: a URL pattern name
:param params: Some parameter to append to the reversed URL
:type params: :obj:`dict` or :obj:`NoneType<types.NoneType>`
:retur... | python | def redirect_params(url_name, params=None):
"""
Redirect to ``url_name`` with ``params`` as querystring
:param unicode url_name: a URL pattern name
:param params: Some parameter to append to the reversed URL
:type params: :obj:`dict` or :obj:`NoneType<types.NoneType>`
:retur... | [
"def",
"redirect_params",
"(",
"url_name",
",",
"params",
"=",
"None",
")",
":",
"url",
"=",
"reverse",
"(",
"url_name",
")",
"params",
"=",
"urlencode",
"(",
"params",
"if",
"params",
"else",
"{",
"}",
")",
"return",
"HttpResponseRedirect",
"(",
"url",
... | Redirect to ``url_name`` with ``params`` as querystring
:param unicode url_name: a URL pattern name
:param params: Some parameter to append to the reversed URL
:type params: :obj:`dict` or :obj:`NoneType<types.NoneType>`
:return: A redirection to the URL with name ``url_name`` with ``pa... | [
"Redirect",
"to",
"url_name",
"with",
"params",
"as",
"querystring"
] | d106181b94c444f1946269da5c20f6c904840ad3 | https://github.com/nitmir/django-cas-server/blob/d106181b94c444f1946269da5c20f6c904840ad3/cas_server/utils.py#L143-L155 | train |
nitmir/django-cas-server | cas_server/utils.py | reverse_params | def reverse_params(url_name, params=None, **kwargs):
"""
compute the reverse url of ``url_name`` and add to it parameters from ``params``
as querystring
:param unicode url_name: a URL pattern name
:param params: Some parameter to append to the reversed URL
:type params: :obj... | python | def reverse_params(url_name, params=None, **kwargs):
"""
compute the reverse url of ``url_name`` and add to it parameters from ``params``
as querystring
:param unicode url_name: a URL pattern name
:param params: Some parameter to append to the reversed URL
:type params: :obj... | [
"def",
"reverse_params",
"(",
"url_name",
",",
"params",
"=",
"None",
",",
"**",
"kwargs",
")",
":",
"url",
"=",
"reverse",
"(",
"url_name",
",",
"**",
"kwargs",
")",
"params",
"=",
"urlencode",
"(",
"params",
"if",
"params",
"else",
"{",
"}",
")",
"... | compute the reverse url of ``url_name`` and add to it parameters from ``params``
as querystring
:param unicode url_name: a URL pattern name
:param params: Some parameter to append to the reversed URL
:type params: :obj:`dict` or :obj:`NoneType<types.NoneType>`
:param **kwargs: a... | [
"compute",
"the",
"reverse",
"url",
"of",
"url_name",
"and",
"add",
"to",
"it",
"parameters",
"from",
"params",
"as",
"querystring"
] | d106181b94c444f1946269da5c20f6c904840ad3 | https://github.com/nitmir/django-cas-server/blob/d106181b94c444f1946269da5c20f6c904840ad3/cas_server/utils.py#L158-L175 | train |
nitmir/django-cas-server | cas_server/utils.py | set_cookie | def set_cookie(response, key, value, max_age):
"""
Set the cookie ``key`` on ``response`` with value ``value`` valid for ``max_age`` secondes
:param django.http.HttpResponse response: a django response where to set the cookie
:param unicode key: the cookie key
:param unicode value: ... | python | def set_cookie(response, key, value, max_age):
"""
Set the cookie ``key`` on ``response`` with value ``value`` valid for ``max_age`` secondes
:param django.http.HttpResponse response: a django response where to set the cookie
:param unicode key: the cookie key
:param unicode value: ... | [
"def",
"set_cookie",
"(",
"response",
",",
"key",
",",
"value",
",",
"max_age",
")",
":",
"expires",
"=",
"datetime",
".",
"strftime",
"(",
"datetime",
".",
"utcnow",
"(",
")",
"+",
"timedelta",
"(",
"seconds",
"=",
"max_age",
")",
",",
"\"%a, %d-%b-%Y %... | Set the cookie ``key`` on ``response`` with value ``value`` valid for ``max_age`` secondes
:param django.http.HttpResponse response: a django response where to set the cookie
:param unicode key: the cookie key
:param unicode value: the cookie value
:param int max_age: the maximum validi... | [
"Set",
"the",
"cookie",
"key",
"on",
"response",
"with",
"value",
"value",
"valid",
"for",
"max_age",
"secondes"
] | d106181b94c444f1946269da5c20f6c904840ad3 | https://github.com/nitmir/django-cas-server/blob/d106181b94c444f1946269da5c20f6c904840ad3/cas_server/utils.py#L197-L217 | train |
nitmir/django-cas-server | cas_server/utils.py | get_current_url | def get_current_url(request, ignore_params=None):
"""
Giving a django request, return the current http url, possibly ignoring some GET parameters
:param django.http.HttpRequest request: The current request object.
:param set ignore_params: An optional set of GET parameters to ignore
... | python | def get_current_url(request, ignore_params=None):
"""
Giving a django request, return the current http url, possibly ignoring some GET parameters
:param django.http.HttpRequest request: The current request object.
:param set ignore_params: An optional set of GET parameters to ignore
... | [
"def",
"get_current_url",
"(",
"request",
",",
"ignore_params",
"=",
"None",
")",
":",
"if",
"ignore_params",
"is",
"None",
":",
"ignore_params",
"=",
"set",
"(",
")",
"protocol",
"=",
"u'https'",
"if",
"request",
".",
"is_secure",
"(",
")",
"else",
"u\"ht... | Giving a django request, return the current http url, possibly ignoring some GET parameters
:param django.http.HttpRequest request: The current request object.
:param set ignore_params: An optional set of GET parameters to ignore
:return: The URL of the current page, possibly omitting some para... | [
"Giving",
"a",
"django",
"request",
"return",
"the",
"current",
"http",
"url",
"possibly",
"ignoring",
"some",
"GET",
"parameters"
] | d106181b94c444f1946269da5c20f6c904840ad3 | https://github.com/nitmir/django-cas-server/blob/d106181b94c444f1946269da5c20f6c904840ad3/cas_server/utils.py#L220-L238 | train |
nitmir/django-cas-server | cas_server/utils.py | update_url | def update_url(url, params):
"""
update parameters using ``params`` in the ``url`` query string
:param url: An URL possibily with a querystring
:type url: :obj:`unicode` or :obj:`str`
:param dict params: A dictionary of parameters for updating the url querystring
:return: Th... | python | def update_url(url, params):
"""
update parameters using ``params`` in the ``url`` query string
:param url: An URL possibily with a querystring
:type url: :obj:`unicode` or :obj:`str`
:param dict params: A dictionary of parameters for updating the url querystring
:return: Th... | [
"def",
"update_url",
"(",
"url",
",",
"params",
")",
":",
"if",
"not",
"isinstance",
"(",
"url",
",",
"bytes",
")",
":",
"url",
"=",
"url",
".",
"encode",
"(",
"'utf-8'",
")",
"for",
"key",
",",
"value",
"in",
"list",
"(",
"params",
".",
"items",
... | update parameters using ``params`` in the ``url`` query string
:param url: An URL possibily with a querystring
:type url: :obj:`unicode` or :obj:`str`
:param dict params: A dictionary of parameters for updating the url querystring
:return: The URL with an updated querystring
:rt... | [
"update",
"parameters",
"using",
"params",
"in",
"the",
"url",
"query",
"string"
] | d106181b94c444f1946269da5c20f6c904840ad3 | https://github.com/nitmir/django-cas-server/blob/d106181b94c444f1946269da5c20f6c904840ad3/cas_server/utils.py#L241-L270 | train |
nitmir/django-cas-server | cas_server/utils.py | unpack_nested_exception | def unpack_nested_exception(error):
"""
If exception are stacked, return the first one
:param error: A python exception with possible exception embeded within
:return: A python exception with no exception embeded within
"""
i = 0
while True:
if error.args[i:]:
... | python | def unpack_nested_exception(error):
"""
If exception are stacked, return the first one
:param error: A python exception with possible exception embeded within
:return: A python exception with no exception embeded within
"""
i = 0
while True:
if error.args[i:]:
... | [
"def",
"unpack_nested_exception",
"(",
"error",
")",
":",
"i",
"=",
"0",
"while",
"True",
":",
"if",
"error",
".",
"args",
"[",
"i",
":",
"]",
":",
"if",
"isinstance",
"(",
"error",
".",
"args",
"[",
"i",
"]",
",",
"Exception",
")",
":",
"error",
... | If exception are stacked, return the first one
:param error: A python exception with possible exception embeded within
:return: A python exception with no exception embeded within | [
"If",
"exception",
"are",
"stacked",
"return",
"the",
"first",
"one"
] | d106181b94c444f1946269da5c20f6c904840ad3 | https://github.com/nitmir/django-cas-server/blob/d106181b94c444f1946269da5c20f6c904840ad3/cas_server/utils.py#L273-L290 | train |
nitmir/django-cas-server | cas_server/utils.py | _gen_ticket | def _gen_ticket(prefix=None, lg=settings.CAS_TICKET_LEN):
"""
Generate a ticket with prefix ``prefix`` and length ``lg``
:param unicode prefix: An optional prefix (probably ST, PT, PGT or PGTIOU)
:param int lg: The length of the generated ticket (with the prefix)
:return: A randomll... | python | def _gen_ticket(prefix=None, lg=settings.CAS_TICKET_LEN):
"""
Generate a ticket with prefix ``prefix`` and length ``lg``
:param unicode prefix: An optional prefix (probably ST, PT, PGT or PGTIOU)
:param int lg: The length of the generated ticket (with the prefix)
:return: A randomll... | [
"def",
"_gen_ticket",
"(",
"prefix",
"=",
"None",
",",
"lg",
"=",
"settings",
".",
"CAS_TICKET_LEN",
")",
":",
"random_part",
"=",
"u''",
".",
"join",
"(",
"random",
".",
"choice",
"(",
"string",
".",
"ascii_letters",
"+",
"string",
".",
"digits",
")",
... | Generate a ticket with prefix ``prefix`` and length ``lg``
:param unicode prefix: An optional prefix (probably ST, PT, PGT or PGTIOU)
:param int lg: The length of the generated ticket (with the prefix)
:return: A randomlly generated ticket of length ``lg``
:rtype: unicode | [
"Generate",
"a",
"ticket",
"with",
"prefix",
"prefix",
"and",
"length",
"lg"
] | d106181b94c444f1946269da5c20f6c904840ad3 | https://github.com/nitmir/django-cas-server/blob/d106181b94c444f1946269da5c20f6c904840ad3/cas_server/utils.py#L293-L310 | train |
nitmir/django-cas-server | cas_server/utils.py | crypt_salt_is_valid | def crypt_salt_is_valid(salt):
"""
Validate a salt as crypt salt
:param str salt: a password salt
:return: ``True`` if ``salt`` is a valid crypt salt on this system, ``False`` otherwise
:rtype: bool
"""
if len(salt) < 2:
return False
else:
if salt[0] == '... | python | def crypt_salt_is_valid(salt):
"""
Validate a salt as crypt salt
:param str salt: a password salt
:return: ``True`` if ``salt`` is a valid crypt salt on this system, ``False`` otherwise
:rtype: bool
"""
if len(salt) < 2:
return False
else:
if salt[0] == '... | [
"def",
"crypt_salt_is_valid",
"(",
"salt",
")",
":",
"if",
"len",
"(",
"salt",
")",
"<",
"2",
":",
"return",
"False",
"else",
":",
"if",
"salt",
"[",
"0",
"]",
"==",
"'$'",
":",
"if",
"salt",
"[",
"1",
"]",
"==",
"'$'",
":",
"return",
"False",
... | Validate a salt as crypt salt
:param str salt: a password salt
:return: ``True`` if ``salt`` is a valid crypt salt on this system, ``False`` otherwise
:rtype: bool | [
"Validate",
"a",
"salt",
"as",
"crypt",
"salt"
] | d106181b94c444f1946269da5c20f6c904840ad3 | https://github.com/nitmir/django-cas-server/blob/d106181b94c444f1946269da5c20f6c904840ad3/cas_server/utils.py#L393-L417 | train |
nitmir/django-cas-server | cas_server/utils.py | check_password | def check_password(method, password, hashed_password, charset):
"""
Check that ``password`` match `hashed_password` using ``method``,
assuming the encoding is ``charset``.
:param str method: on of ``"crypt"``, ``"ldap"``, ``"hex_md5"``, ``"hex_sha1"``,
``"hex_sha224"``, ``"hex_s... | python | def check_password(method, password, hashed_password, charset):
"""
Check that ``password`` match `hashed_password` using ``method``,
assuming the encoding is ``charset``.
:param str method: on of ``"crypt"``, ``"ldap"``, ``"hex_md5"``, ``"hex_sha1"``,
``"hex_sha224"``, ``"hex_s... | [
"def",
"check_password",
"(",
"method",
",",
"password",
",",
"hashed_password",
",",
"charset",
")",
":",
"if",
"not",
"isinstance",
"(",
"password",
",",
"six",
".",
"binary_type",
")",
":",
"password",
"=",
"password",
".",
"encode",
"(",
"charset",
")"... | Check that ``password`` match `hashed_password` using ``method``,
assuming the encoding is ``charset``.
:param str method: on of ``"crypt"``, ``"ldap"``, ``"hex_md5"``, ``"hex_sha1"``,
``"hex_sha224"``, ``"hex_sha256"``, ``"hex_sha384"``, ``"hex_sha512"``, ``"plain"``
:param passwor... | [
"Check",
"that",
"password",
"match",
"hashed_password",
"using",
"method",
"assuming",
"the",
"encoding",
"is",
"charset",
"."
] | d106181b94c444f1946269da5c20f6c904840ad3 | https://github.com/nitmir/django-cas-server/blob/d106181b94c444f1946269da5c20f6c904840ad3/cas_server/utils.py#L607-L658 | train |
nitmir/django-cas-server | cas_server/utils.py | last_version | def last_version():
"""
Fetch the last version from pypi and return it. On successful fetch from pypi, the response
is cached 24h, on error, it is cached 10 min.
:return: the last django-cas-server version
:rtype: unicode
"""
try:
last_update, version, success = last... | python | def last_version():
"""
Fetch the last version from pypi and return it. On successful fetch from pypi, the response
is cached 24h, on error, it is cached 10 min.
:return: the last django-cas-server version
:rtype: unicode
"""
try:
last_update, version, success = last... | [
"def",
"last_version",
"(",
")",
":",
"try",
":",
"last_update",
",",
"version",
",",
"success",
"=",
"last_version",
".",
"_cache",
"except",
"AttributeError",
":",
"last_update",
"=",
"0",
"version",
"=",
"None",
"success",
"=",
"False",
"cache_delta",
"="... | Fetch the last version from pypi and return it. On successful fetch from pypi, the response
is cached 24h, on error, it is cached 10 min.
:return: the last django-cas-server version
:rtype: unicode | [
"Fetch",
"the",
"last",
"version",
"from",
"pypi",
"and",
"return",
"it",
".",
"On",
"successful",
"fetch",
"from",
"pypi",
"the",
"response",
"is",
"cached",
"24h",
"on",
"error",
"it",
"is",
"cached",
"10",
"min",
"."
] | d106181b94c444f1946269da5c20f6c904840ad3 | https://github.com/nitmir/django-cas-server/blob/d106181b94c444f1946269da5c20f6c904840ad3/cas_server/utils.py#L673-L705 | train |
nitmir/django-cas-server | cas_server/utils.py | regexpr_validator | def regexpr_validator(value):
"""
Test that ``value`` is a valid regular expression
:param unicode value: A regular expression to test
:raises ValidationError: if ``value`` is not a valid regular expression
"""
try:
re.compile(value)
except re.error:
raise Valida... | python | def regexpr_validator(value):
"""
Test that ``value`` is a valid regular expression
:param unicode value: A regular expression to test
:raises ValidationError: if ``value`` is not a valid regular expression
"""
try:
re.compile(value)
except re.error:
raise Valida... | [
"def",
"regexpr_validator",
"(",
"value",
")",
":",
"try",
":",
"re",
".",
"compile",
"(",
"value",
")",
"except",
"re",
".",
"error",
":",
"raise",
"ValidationError",
"(",
"_",
"(",
"'\"%(value)s\" is not a valid regular expression'",
")",
",",
"params",
"=",... | Test that ``value`` is a valid regular expression
:param unicode value: A regular expression to test
:raises ValidationError: if ``value`` is not a valid regular expression | [
"Test",
"that",
"value",
"is",
"a",
"valid",
"regular",
"expression"
] | d106181b94c444f1946269da5c20f6c904840ad3 | https://github.com/nitmir/django-cas-server/blob/d106181b94c444f1946269da5c20f6c904840ad3/cas_server/utils.py#L736-L749 | train |
nitmir/django-cas-server | cas_server/utils.py | LdapHashUserPassword.hash | def hash(cls, scheme, password, salt=None, charset="utf8"):
"""
Hash ``password`` with ``scheme`` using ``salt``.
This three variable beeing encoded in ``charset``.
:param bytes scheme: A valid scheme
:param bytes password: A byte string to hash using ``scheme``
... | python | def hash(cls, scheme, password, salt=None, charset="utf8"):
"""
Hash ``password`` with ``scheme`` using ``salt``.
This three variable beeing encoded in ``charset``.
:param bytes scheme: A valid scheme
:param bytes password: A byte string to hash using ``scheme``
... | [
"def",
"hash",
"(",
"cls",
",",
"scheme",
",",
"password",
",",
"salt",
"=",
"None",
",",
"charset",
"=",
"\"utf8\"",
")",
":",
"scheme",
"=",
"scheme",
".",
"upper",
"(",
")",
"cls",
".",
"_test_scheme",
"(",
"scheme",
")",
"if",
"salt",
"is",
"No... | Hash ``password`` with ``scheme`` using ``salt``.
This three variable beeing encoded in ``charset``.
:param bytes scheme: A valid scheme
:param bytes password: A byte string to hash using ``scheme``
:param bytes salt: An optional salt to use if ``scheme`` requires any
... | [
"Hash",
"password",
"with",
"scheme",
"using",
"salt",
".",
"This",
"three",
"variable",
"beeing",
"encoded",
"in",
"charset",
"."
] | d106181b94c444f1946269da5c20f6c904840ad3 | https://github.com/nitmir/django-cas-server/blob/d106181b94c444f1946269da5c20f6c904840ad3/cas_server/utils.py#L530-L562 | train |
nitmir/django-cas-server | cas_server/utils.py | LdapHashUserPassword.get_salt | def get_salt(cls, hashed_passord):
"""
Return the salt of ``hashed_passord`` possibly empty
:param bytes hashed_passord: A hashed password
:return: The salt used by the hashed password (empty if no salt is used)
:rtype: bytes
:raises BadHash: if no va... | python | def get_salt(cls, hashed_passord):
"""
Return the salt of ``hashed_passord`` possibly empty
:param bytes hashed_passord: A hashed password
:return: The salt used by the hashed password (empty if no salt is used)
:rtype: bytes
:raises BadHash: if no va... | [
"def",
"get_salt",
"(",
"cls",
",",
"hashed_passord",
")",
":",
"scheme",
"=",
"cls",
".",
"get_scheme",
"(",
"hashed_passord",
")",
"cls",
".",
"_test_scheme",
"(",
"scheme",
")",
"if",
"scheme",
"in",
"cls",
".",
"schemes_nosalt",
":",
"return",
"b\"\"",... | Return the salt of ``hashed_passord`` possibly empty
:param bytes hashed_passord: A hashed password
:return: The salt used by the hashed password (empty if no salt is used)
:rtype: bytes
:raises BadHash: if no valid scheme is found within ``hashed_passord`` or if the
... | [
"Return",
"the",
"salt",
"of",
"hashed_passord",
"possibly",
"empty"
] | d106181b94c444f1946269da5c20f6c904840ad3 | https://github.com/nitmir/django-cas-server/blob/d106181b94c444f1946269da5c20f6c904840ad3/cas_server/utils.py#L581-L604 | train |
nitmir/django-cas-server | docs/_ext/djangodocs.py | visit_snippet_latex | def visit_snippet_latex(self, node):
"""
Latex document generator visit handler
"""
code = node.rawsource.rstrip('\n')
lang = self.hlsettingstack[-1][0]
linenos = code.count('\n') >= self.hlsettingstack[-1][1] - 1
fname = node['filename']
highlight_args = node.get('highlight_args', {})
... | python | def visit_snippet_latex(self, node):
"""
Latex document generator visit handler
"""
code = node.rawsource.rstrip('\n')
lang = self.hlsettingstack[-1][0]
linenos = code.count('\n') >= self.hlsettingstack[-1][1] - 1
fname = node['filename']
highlight_args = node.get('highlight_args', {})
... | [
"def",
"visit_snippet_latex",
"(",
"self",
",",
"node",
")",
":",
"code",
"=",
"node",
".",
"rawsource",
".",
"rstrip",
"(",
"'\\n'",
")",
"lang",
"=",
"self",
".",
"hlsettingstack",
"[",
"-",
"1",
"]",
"[",
"0",
"]",
"linenos",
"=",
"code",
".",
"... | Latex document generator visit handler | [
"Latex",
"document",
"generator",
"visit",
"handler"
] | d106181b94c444f1946269da5c20f6c904840ad3 | https://github.com/nitmir/django-cas-server/blob/d106181b94c444f1946269da5c20f6c904840ad3/docs/_ext/djangodocs.py#L121-L166 | train |
nitmir/django-cas-server | cas_server/views.py | LogoutMixin.logout | def logout(self, all_session=False):
"""
effectively destroy a CAS session
:param boolean all_session: If ``True`` destroy all the user sessions, otherwise
destroy the current user session.
:return: The number of destroyed sessions
:rtype: int
... | python | def logout(self, all_session=False):
"""
effectively destroy a CAS session
:param boolean all_session: If ``True`` destroy all the user sessions, otherwise
destroy the current user session.
:return: The number of destroyed sessions
:rtype: int
... | [
"def",
"logout",
"(",
"self",
",",
"all_session",
"=",
"False",
")",
":",
"session_nb",
"=",
"0",
"username",
"=",
"self",
".",
"request",
".",
"session",
".",
"get",
"(",
"\"username\"",
")",
"if",
"username",
":",
"if",
"all_session",
":",
"logger",
... | effectively destroy a CAS session
:param boolean all_session: If ``True`` destroy all the user sessions, otherwise
destroy the current user session.
:return: The number of destroyed sessions
:rtype: int | [
"effectively",
"destroy",
"a",
"CAS",
"session"
] | d106181b94c444f1946269da5c20f6c904840ad3 | https://github.com/nitmir/django-cas-server/blob/d106181b94c444f1946269da5c20f6c904840ad3/cas_server/views.py#L53-L108 | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.