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
listlengths
20
707
docstring
stringlengths
3
17.3k
docstring_tokens
listlengths
3
222
sha
stringlengths
40
40
url
stringlengths
87
242
partition
stringclasses
1 value
idx
int64
0
252k
tobami/littlechef
littlechef/chef.py
_remove_remote_data_bags
def _remove_remote_data_bags(): """Remove remote data bags, so it won't leak any sensitive information""" data_bags_path = os.path.join(env.node_work_path, 'data_bags') if exists(data_bags_path): sudo("rm -rf {0}".format(data_bags_path))
python
def _remove_remote_data_bags(): """Remove remote data bags, so it won't leak any sensitive information""" data_bags_path = os.path.join(env.node_work_path, 'data_bags') if exists(data_bags_path): sudo("rm -rf {0}".format(data_bags_path))
[ "def", "_remove_remote_data_bags", "(", ")", ":", "data_bags_path", "=", "os", ".", "path", ".", "join", "(", "env", ".", "node_work_path", ",", "'data_bags'", ")", "if", "exists", "(", "data_bags_path", ")", ":", "sudo", "(", "\"rm -rf {0}\"", ".", "format", "(", "data_bags_path", ")", ")" ]
Remove remote data bags, so it won't leak any sensitive information
[ "Remove", "remote", "data", "bags", "so", "it", "won", "t", "leak", "any", "sensitive", "information" ]
aab8c94081b38100a69cc100bc4278ae7419c58e
https://github.com/tobami/littlechef/blob/aab8c94081b38100a69cc100bc4278ae7419c58e/littlechef/chef.py#L397-L401
train
238,000
tobami/littlechef
littlechef/chef.py
_configure_node
def _configure_node(): """Exectutes chef-solo to apply roles and recipes to a node""" print("") msg = "Cooking..." if env.parallel: msg = "[{0}]: {1}".format(env.host_string, msg) print(msg) # Backup last report with settings(hide('stdout', 'warnings', 'running'), warn_only=True): sudo("mv {0} {0}.1".format(LOGFILE)) # Build chef-solo command cmd = "RUBYOPT=-Ku chef-solo" if whyrun: cmd += " --why-run" cmd += ' -l {0} -j /etc/chef/node.json'.format(env.loglevel) if ENABLE_LOGS: cmd += ' | tee {0}'.format(LOGFILE) if env.loglevel == "debug": print("Executing Chef Solo with the following command:\n" "{0}".format(cmd)) with settings(hide('warnings', 'running'), warn_only=True): output = sudo(cmd) if (output.failed or "FATAL: Stacktrace dumped" in output or ("Chef Run complete" not in output and "Report handlers complete" not in output)): if 'chef-solo: command not found' in output: print( colors.red( "\nFAILED: Chef Solo is not installed on this node")) print( "Type 'fix node:{0} deploy_chef' to install it".format( env.host)) abort("") else: print(colors.red( "\nFAILED: chef-solo could not finish configuring the node\n")) import sys sys.exit(1) else: msg = "\n" if env.parallel: msg += "[{0}]: ".format(env.host_string) msg += "SUCCESS: Node correctly configured" print(colors.green(msg))
python
def _configure_node(): """Exectutes chef-solo to apply roles and recipes to a node""" print("") msg = "Cooking..." if env.parallel: msg = "[{0}]: {1}".format(env.host_string, msg) print(msg) # Backup last report with settings(hide('stdout', 'warnings', 'running'), warn_only=True): sudo("mv {0} {0}.1".format(LOGFILE)) # Build chef-solo command cmd = "RUBYOPT=-Ku chef-solo" if whyrun: cmd += " --why-run" cmd += ' -l {0} -j /etc/chef/node.json'.format(env.loglevel) if ENABLE_LOGS: cmd += ' | tee {0}'.format(LOGFILE) if env.loglevel == "debug": print("Executing Chef Solo with the following command:\n" "{0}".format(cmd)) with settings(hide('warnings', 'running'), warn_only=True): output = sudo(cmd) if (output.failed or "FATAL: Stacktrace dumped" in output or ("Chef Run complete" not in output and "Report handlers complete" not in output)): if 'chef-solo: command not found' in output: print( colors.red( "\nFAILED: Chef Solo is not installed on this node")) print( "Type 'fix node:{0} deploy_chef' to install it".format( env.host)) abort("") else: print(colors.red( "\nFAILED: chef-solo could not finish configuring the node\n")) import sys sys.exit(1) else: msg = "\n" if env.parallel: msg += "[{0}]: ".format(env.host_string) msg += "SUCCESS: Node correctly configured" print(colors.green(msg))
[ "def", "_configure_node", "(", ")", ":", "print", "(", "\"\"", ")", "msg", "=", "\"Cooking...\"", "if", "env", ".", "parallel", ":", "msg", "=", "\"[{0}]: {1}\"", ".", "format", "(", "env", ".", "host_string", ",", "msg", ")", "print", "(", "msg", ")", "# Backup last report", "with", "settings", "(", "hide", "(", "'stdout'", ",", "'warnings'", ",", "'running'", ")", ",", "warn_only", "=", "True", ")", ":", "sudo", "(", "\"mv {0} {0}.1\"", ".", "format", "(", "LOGFILE", ")", ")", "# Build chef-solo command", "cmd", "=", "\"RUBYOPT=-Ku chef-solo\"", "if", "whyrun", ":", "cmd", "+=", "\" --why-run\"", "cmd", "+=", "' -l {0} -j /etc/chef/node.json'", ".", "format", "(", "env", ".", "loglevel", ")", "if", "ENABLE_LOGS", ":", "cmd", "+=", "' | tee {0}'", ".", "format", "(", "LOGFILE", ")", "if", "env", ".", "loglevel", "==", "\"debug\"", ":", "print", "(", "\"Executing Chef Solo with the following command:\\n\"", "\"{0}\"", ".", "format", "(", "cmd", ")", ")", "with", "settings", "(", "hide", "(", "'warnings'", ",", "'running'", ")", ",", "warn_only", "=", "True", ")", ":", "output", "=", "sudo", "(", "cmd", ")", "if", "(", "output", ".", "failed", "or", "\"FATAL: Stacktrace dumped\"", "in", "output", "or", "(", "\"Chef Run complete\"", "not", "in", "output", "and", "\"Report handlers complete\"", "not", "in", "output", ")", ")", ":", "if", "'chef-solo: command not found'", "in", "output", ":", "print", "(", "colors", ".", "red", "(", "\"\\nFAILED: Chef Solo is not installed on this node\"", ")", ")", "print", "(", "\"Type 'fix node:{0} deploy_chef' to install it\"", ".", "format", "(", "env", ".", "host", ")", ")", "abort", "(", "\"\"", ")", "else", ":", "print", "(", "colors", ".", "red", "(", "\"\\nFAILED: chef-solo could not finish configuring the node\\n\"", ")", ")", "import", "sys", "sys", ".", "exit", "(", "1", ")", "else", ":", "msg", "=", "\"\\n\"", "if", "env", ".", "parallel", ":", "msg", "+=", "\"[{0}]: \"", ".", "format", "(", "env", ".", "host_string", ")", "msg", "+=", "\"SUCCESS: Node correctly configured\"", "print", "(", "colors", ".", "green", "(", "msg", ")", ")" ]
Exectutes chef-solo to apply roles and recipes to a node
[ "Exectutes", "chef", "-", "solo", "to", "apply", "roles", "and", "recipes", "to", "a", "node" ]
aab8c94081b38100a69cc100bc4278ae7419c58e
https://github.com/tobami/littlechef/blob/aab8c94081b38100a69cc100bc4278ae7419c58e/littlechef/chef.py#L431-L474
train
238,001
tobami/littlechef
littlechef/lib.py
_resolve_hostname
def _resolve_hostname(name): """Returns resolved hostname using the ssh config""" if env.ssh_config is None: return name elif not os.path.exists(os.path.join("nodes", name + ".json")): resolved_name = env.ssh_config.lookup(name)['hostname'] if os.path.exists(os.path.join("nodes", resolved_name + ".json")): name = resolved_name return name
python
def _resolve_hostname(name): """Returns resolved hostname using the ssh config""" if env.ssh_config is None: return name elif not os.path.exists(os.path.join("nodes", name + ".json")): resolved_name = env.ssh_config.lookup(name)['hostname'] if os.path.exists(os.path.join("nodes", resolved_name + ".json")): name = resolved_name return name
[ "def", "_resolve_hostname", "(", "name", ")", ":", "if", "env", ".", "ssh_config", "is", "None", ":", "return", "name", "elif", "not", "os", ".", "path", ".", "exists", "(", "os", ".", "path", ".", "join", "(", "\"nodes\"", ",", "name", "+", "\".json\"", ")", ")", ":", "resolved_name", "=", "env", ".", "ssh_config", ".", "lookup", "(", "name", ")", "[", "'hostname'", "]", "if", "os", ".", "path", ".", "exists", "(", "os", ".", "path", ".", "join", "(", "\"nodes\"", ",", "resolved_name", "+", "\".json\"", ")", ")", ":", "name", "=", "resolved_name", "return", "name" ]
Returns resolved hostname using the ssh config
[ "Returns", "resolved", "hostname", "using", "the", "ssh", "config" ]
aab8c94081b38100a69cc100bc4278ae7419c58e
https://github.com/tobami/littlechef/blob/aab8c94081b38100a69cc100bc4278ae7419c58e/littlechef/lib.py#L31-L39
train
238,002
tobami/littlechef
littlechef/lib.py
get_environment
def get_environment(name): """Returns a JSON environment file as a dictionary""" if name == "_default": return env_from_template(name) filename = os.path.join("environments", name + ".json") try: with open(filename) as f: try: return json.loads(f.read()) except ValueError as e: msg = 'LittleChef found the following error in' msg += ' "{0}":\n {1}'.format(filename, str(e)) abort(msg) except IOError: raise FileNotFoundError('File {0} not found'.format(filename))
python
def get_environment(name): """Returns a JSON environment file as a dictionary""" if name == "_default": return env_from_template(name) filename = os.path.join("environments", name + ".json") try: with open(filename) as f: try: return json.loads(f.read()) except ValueError as e: msg = 'LittleChef found the following error in' msg += ' "{0}":\n {1}'.format(filename, str(e)) abort(msg) except IOError: raise FileNotFoundError('File {0} not found'.format(filename))
[ "def", "get_environment", "(", "name", ")", ":", "if", "name", "==", "\"_default\"", ":", "return", "env_from_template", "(", "name", ")", "filename", "=", "os", ".", "path", ".", "join", "(", "\"environments\"", ",", "name", "+", "\".json\"", ")", "try", ":", "with", "open", "(", "filename", ")", "as", "f", ":", "try", ":", "return", "json", ".", "loads", "(", "f", ".", "read", "(", ")", ")", "except", "ValueError", "as", "e", ":", "msg", "=", "'LittleChef found the following error in'", "msg", "+=", "' \"{0}\":\\n {1}'", ".", "format", "(", "filename", ",", "str", "(", "e", ")", ")", "abort", "(", "msg", ")", "except", "IOError", ":", "raise", "FileNotFoundError", "(", "'File {0} not found'", ".", "format", "(", "filename", ")", ")" ]
Returns a JSON environment file as a dictionary
[ "Returns", "a", "JSON", "environment", "file", "as", "a", "dictionary" ]
aab8c94081b38100a69cc100bc4278ae7419c58e
https://github.com/tobami/littlechef/blob/aab8c94081b38100a69cc100bc4278ae7419c58e/littlechef/lib.py#L62-L76
train
238,003
tobami/littlechef
littlechef/lib.py
get_environments
def get_environments(): """Gets all environments found in the 'environments' directory""" envs = [] for root, subfolders, files in os.walk('environments'): for filename in files: if filename.endswith(".json"): path = os.path.join( root[len('environments'):], filename[:-len('.json')]) envs.append(get_environment(path)) return sorted(envs, key=lambda x: x['name'])
python
def get_environments(): """Gets all environments found in the 'environments' directory""" envs = [] for root, subfolders, files in os.walk('environments'): for filename in files: if filename.endswith(".json"): path = os.path.join( root[len('environments'):], filename[:-len('.json')]) envs.append(get_environment(path)) return sorted(envs, key=lambda x: x['name'])
[ "def", "get_environments", "(", ")", ":", "envs", "=", "[", "]", "for", "root", ",", "subfolders", ",", "files", "in", "os", ".", "walk", "(", "'environments'", ")", ":", "for", "filename", "in", "files", ":", "if", "filename", ".", "endswith", "(", "\".json\"", ")", ":", "path", "=", "os", ".", "path", ".", "join", "(", "root", "[", "len", "(", "'environments'", ")", ":", "]", ",", "filename", "[", ":", "-", "len", "(", "'.json'", ")", "]", ")", "envs", ".", "append", "(", "get_environment", "(", "path", ")", ")", "return", "sorted", "(", "envs", ",", "key", "=", "lambda", "x", ":", "x", "[", "'name'", "]", ")" ]
Gets all environments found in the 'environments' directory
[ "Gets", "all", "environments", "found", "in", "the", "environments", "directory" ]
aab8c94081b38100a69cc100bc4278ae7419c58e
https://github.com/tobami/littlechef/blob/aab8c94081b38100a69cc100bc4278ae7419c58e/littlechef/lib.py#L79-L88
train
238,004
tobami/littlechef
littlechef/lib.py
get_node
def get_node(name, merged=False): """Returns a JSON node file as a dictionary""" if merged: node_path = os.path.join("data_bags", "node", name.replace('.', '_') + ".json") else: node_path = os.path.join("nodes", name + ".json") if os.path.exists(node_path): # Read node.json with open(node_path, 'r') as f: try: node = json.loads(f.read()) except ValueError as e: msg = 'LittleChef found the following error in' msg += ' "{0}":\n {1}'.format(node_path, str(e)) abort(msg) else: print "Creating new node file '{0}.json'".format(name) node = {'run_list': []} # Add node name so that we can tell to which node it is node['name'] = name if not node.get('chef_environment'): node['chef_environment'] = '_default' return node
python
def get_node(name, merged=False): """Returns a JSON node file as a dictionary""" if merged: node_path = os.path.join("data_bags", "node", name.replace('.', '_') + ".json") else: node_path = os.path.join("nodes", name + ".json") if os.path.exists(node_path): # Read node.json with open(node_path, 'r') as f: try: node = json.loads(f.read()) except ValueError as e: msg = 'LittleChef found the following error in' msg += ' "{0}":\n {1}'.format(node_path, str(e)) abort(msg) else: print "Creating new node file '{0}.json'".format(name) node = {'run_list': []} # Add node name so that we can tell to which node it is node['name'] = name if not node.get('chef_environment'): node['chef_environment'] = '_default' return node
[ "def", "get_node", "(", "name", ",", "merged", "=", "False", ")", ":", "if", "merged", ":", "node_path", "=", "os", ".", "path", ".", "join", "(", "\"data_bags\"", ",", "\"node\"", ",", "name", ".", "replace", "(", "'.'", ",", "'_'", ")", "+", "\".json\"", ")", "else", ":", "node_path", "=", "os", ".", "path", ".", "join", "(", "\"nodes\"", ",", "name", "+", "\".json\"", ")", "if", "os", ".", "path", ".", "exists", "(", "node_path", ")", ":", "# Read node.json", "with", "open", "(", "node_path", ",", "'r'", ")", "as", "f", ":", "try", ":", "node", "=", "json", ".", "loads", "(", "f", ".", "read", "(", ")", ")", "except", "ValueError", "as", "e", ":", "msg", "=", "'LittleChef found the following error in'", "msg", "+=", "' \"{0}\":\\n {1}'", ".", "format", "(", "node_path", ",", "str", "(", "e", ")", ")", "abort", "(", "msg", ")", "else", ":", "print", "\"Creating new node file '{0}.json'\"", ".", "format", "(", "name", ")", "node", "=", "{", "'run_list'", ":", "[", "]", "}", "# Add node name so that we can tell to which node it is", "node", "[", "'name'", "]", "=", "name", "if", "not", "node", ".", "get", "(", "'chef_environment'", ")", ":", "node", "[", "'chef_environment'", "]", "=", "'_default'", "return", "node" ]
Returns a JSON node file as a dictionary
[ "Returns", "a", "JSON", "node", "file", "as", "a", "dictionary" ]
aab8c94081b38100a69cc100bc4278ae7419c58e
https://github.com/tobami/littlechef/blob/aab8c94081b38100a69cc100bc4278ae7419c58e/littlechef/lib.py#L91-L113
train
238,005
tobami/littlechef
littlechef/lib.py
get_nodes_with_role
def get_nodes_with_role(role_name, environment=None): """Get all nodes which include a given role, prefix-searches are also supported """ prefix_search = role_name.endswith("*") if prefix_search: role_name = role_name.rstrip("*") for n in get_nodes(environment): roles = get_roles_in_node(n, recursive=True) if prefix_search: if any(role.startswith(role_name) for role in roles): yield n else: if role_name in roles: yield n
python
def get_nodes_with_role(role_name, environment=None): """Get all nodes which include a given role, prefix-searches are also supported """ prefix_search = role_name.endswith("*") if prefix_search: role_name = role_name.rstrip("*") for n in get_nodes(environment): roles = get_roles_in_node(n, recursive=True) if prefix_search: if any(role.startswith(role_name) for role in roles): yield n else: if role_name in roles: yield n
[ "def", "get_nodes_with_role", "(", "role_name", ",", "environment", "=", "None", ")", ":", "prefix_search", "=", "role_name", ".", "endswith", "(", "\"*\"", ")", "if", "prefix_search", ":", "role_name", "=", "role_name", ".", "rstrip", "(", "\"*\"", ")", "for", "n", "in", "get_nodes", "(", "environment", ")", ":", "roles", "=", "get_roles_in_node", "(", "n", ",", "recursive", "=", "True", ")", "if", "prefix_search", ":", "if", "any", "(", "role", ".", "startswith", "(", "role_name", ")", "for", "role", "in", "roles", ")", ":", "yield", "n", "else", ":", "if", "role_name", "in", "roles", ":", "yield", "n" ]
Get all nodes which include a given role, prefix-searches are also supported
[ "Get", "all", "nodes", "which", "include", "a", "given", "role", "prefix", "-", "searches", "are", "also", "supported" ]
aab8c94081b38100a69cc100bc4278ae7419c58e
https://github.com/tobami/littlechef/blob/aab8c94081b38100a69cc100bc4278ae7419c58e/littlechef/lib.py#L132-L147
train
238,006
tobami/littlechef
littlechef/lib.py
get_nodes_with_tag
def get_nodes_with_tag(tag, environment=None, include_guests=False): """Get all nodes which include a given tag""" nodes = get_nodes(environment) nodes_mapping = dict((n['name'], n) for n in nodes) for n in nodes: if tag in n.get('tags', []): # Remove from node mapping so it doesn't get added twice by # guest walking below try: del nodes_mapping[n['fqdn']] except KeyError: pass yield n # Walk guest if it is a host if include_guests and n.get('virtualization', {}).get('role') == 'host': for guest in n['virtualization'].get('guests', []): try: yield nodes_mapping[guest['fqdn']] except KeyError: # we ignore guests which are not in the same # chef environments than their hosts for now pass
python
def get_nodes_with_tag(tag, environment=None, include_guests=False): """Get all nodes which include a given tag""" nodes = get_nodes(environment) nodes_mapping = dict((n['name'], n) for n in nodes) for n in nodes: if tag in n.get('tags', []): # Remove from node mapping so it doesn't get added twice by # guest walking below try: del nodes_mapping[n['fqdn']] except KeyError: pass yield n # Walk guest if it is a host if include_guests and n.get('virtualization', {}).get('role') == 'host': for guest in n['virtualization'].get('guests', []): try: yield nodes_mapping[guest['fqdn']] except KeyError: # we ignore guests which are not in the same # chef environments than their hosts for now pass
[ "def", "get_nodes_with_tag", "(", "tag", ",", "environment", "=", "None", ",", "include_guests", "=", "False", ")", ":", "nodes", "=", "get_nodes", "(", "environment", ")", "nodes_mapping", "=", "dict", "(", "(", "n", "[", "'name'", "]", ",", "n", ")", "for", "n", "in", "nodes", ")", "for", "n", "in", "nodes", ":", "if", "tag", "in", "n", ".", "get", "(", "'tags'", ",", "[", "]", ")", ":", "# Remove from node mapping so it doesn't get added twice by", "# guest walking below", "try", ":", "del", "nodes_mapping", "[", "n", "[", "'fqdn'", "]", "]", "except", "KeyError", ":", "pass", "yield", "n", "# Walk guest if it is a host", "if", "include_guests", "and", "n", ".", "get", "(", "'virtualization'", ",", "{", "}", ")", ".", "get", "(", "'role'", ")", "==", "'host'", ":", "for", "guest", "in", "n", "[", "'virtualization'", "]", ".", "get", "(", "'guests'", ",", "[", "]", ")", ":", "try", ":", "yield", "nodes_mapping", "[", "guest", "[", "'fqdn'", "]", "]", "except", "KeyError", ":", "# we ignore guests which are not in the same", "# chef environments than their hosts for now", "pass" ]
Get all nodes which include a given tag
[ "Get", "all", "nodes", "which", "include", "a", "given", "tag" ]
aab8c94081b38100a69cc100bc4278ae7419c58e
https://github.com/tobami/littlechef/blob/aab8c94081b38100a69cc100bc4278ae7419c58e/littlechef/lib.py#L150-L171
train
238,007
tobami/littlechef
littlechef/lib.py
get_nodes_with_recipe
def get_nodes_with_recipe(recipe_name, environment=None): """Get all nodes which include a given recipe, prefix-searches are also supported """ prefix_search = recipe_name.endswith("*") if prefix_search: recipe_name = recipe_name.rstrip("*") for n in get_nodes(environment): recipes = get_recipes_in_node(n) for role in get_roles_in_node(n, recursive=True): recipes.extend(get_recipes_in_role(role)) if prefix_search: if any(recipe.startswith(recipe_name) for recipe in recipes): yield n else: if recipe_name in recipes: yield n
python
def get_nodes_with_recipe(recipe_name, environment=None): """Get all nodes which include a given recipe, prefix-searches are also supported """ prefix_search = recipe_name.endswith("*") if prefix_search: recipe_name = recipe_name.rstrip("*") for n in get_nodes(environment): recipes = get_recipes_in_node(n) for role in get_roles_in_node(n, recursive=True): recipes.extend(get_recipes_in_role(role)) if prefix_search: if any(recipe.startswith(recipe_name) for recipe in recipes): yield n else: if recipe_name in recipes: yield n
[ "def", "get_nodes_with_recipe", "(", "recipe_name", ",", "environment", "=", "None", ")", ":", "prefix_search", "=", "recipe_name", ".", "endswith", "(", "\"*\"", ")", "if", "prefix_search", ":", "recipe_name", "=", "recipe_name", ".", "rstrip", "(", "\"*\"", ")", "for", "n", "in", "get_nodes", "(", "environment", ")", ":", "recipes", "=", "get_recipes_in_node", "(", "n", ")", "for", "role", "in", "get_roles_in_node", "(", "n", ",", "recursive", "=", "True", ")", ":", "recipes", ".", "extend", "(", "get_recipes_in_role", "(", "role", ")", ")", "if", "prefix_search", ":", "if", "any", "(", "recipe", ".", "startswith", "(", "recipe_name", ")", "for", "recipe", "in", "recipes", ")", ":", "yield", "n", "else", ":", "if", "recipe_name", "in", "recipes", ":", "yield", "n" ]
Get all nodes which include a given recipe, prefix-searches are also supported
[ "Get", "all", "nodes", "which", "include", "a", "given", "recipe", "prefix", "-", "searches", "are", "also", "supported" ]
aab8c94081b38100a69cc100bc4278ae7419c58e
https://github.com/tobami/littlechef/blob/aab8c94081b38100a69cc100bc4278ae7419c58e/littlechef/lib.py#L174-L191
train
238,008
tobami/littlechef
littlechef/lib.py
print_node
def print_node(node, detailed=False): """Pretty prints the given node""" nodename = node['name'] print(colors.yellow("\n" + nodename)) # Roles if detailed: for role in get_roles_in_node(node): print_role(_get_role(role), detailed=False) else: print(' Roles: {0}'.format(", ".join(get_roles_in_node(node)))) # Recipes if detailed: for recipe in get_recipes_in_node(node): print " Recipe:", recipe print " attributes: {0}".format(node.get(recipe, "")) else: print(' Recipes: {0}'.format(", ".join(get_recipes_in_node(node)))) # Node attributes print " Node attributes:" for attribute in node.keys(): if attribute == "run_list" or attribute == "name": continue print " {0}: {1}".format(attribute, node[attribute])
python
def print_node(node, detailed=False): """Pretty prints the given node""" nodename = node['name'] print(colors.yellow("\n" + nodename)) # Roles if detailed: for role in get_roles_in_node(node): print_role(_get_role(role), detailed=False) else: print(' Roles: {0}'.format(", ".join(get_roles_in_node(node)))) # Recipes if detailed: for recipe in get_recipes_in_node(node): print " Recipe:", recipe print " attributes: {0}".format(node.get(recipe, "")) else: print(' Recipes: {0}'.format(", ".join(get_recipes_in_node(node)))) # Node attributes print " Node attributes:" for attribute in node.keys(): if attribute == "run_list" or attribute == "name": continue print " {0}: {1}".format(attribute, node[attribute])
[ "def", "print_node", "(", "node", ",", "detailed", "=", "False", ")", ":", "nodename", "=", "node", "[", "'name'", "]", "print", "(", "colors", ".", "yellow", "(", "\"\\n\"", "+", "nodename", ")", ")", "# Roles", "if", "detailed", ":", "for", "role", "in", "get_roles_in_node", "(", "node", ")", ":", "print_role", "(", "_get_role", "(", "role", ")", ",", "detailed", "=", "False", ")", "else", ":", "print", "(", "' Roles: {0}'", ".", "format", "(", "\", \"", ".", "join", "(", "get_roles_in_node", "(", "node", ")", ")", ")", ")", "# Recipes", "if", "detailed", ":", "for", "recipe", "in", "get_recipes_in_node", "(", "node", ")", ":", "print", "\" Recipe:\"", ",", "recipe", "print", "\" attributes: {0}\"", ".", "format", "(", "node", ".", "get", "(", "recipe", ",", "\"\"", ")", ")", "else", ":", "print", "(", "' Recipes: {0}'", ".", "format", "(", "\", \"", ".", "join", "(", "get_recipes_in_node", "(", "node", ")", ")", ")", ")", "# Node attributes", "print", "\" Node attributes:\"", "for", "attribute", "in", "node", ".", "keys", "(", ")", ":", "if", "attribute", "==", "\"run_list\"", "or", "attribute", "==", "\"name\"", ":", "continue", "print", "\" {0}: {1}\"", ".", "format", "(", "attribute", ",", "node", "[", "attribute", "]", ")" ]
Pretty prints the given node
[ "Pretty", "prints", "the", "given", "node" ]
aab8c94081b38100a69cc100bc4278ae7419c58e
https://github.com/tobami/littlechef/blob/aab8c94081b38100a69cc100bc4278ae7419c58e/littlechef/lib.py#L194-L216
train
238,009
tobami/littlechef
littlechef/lib.py
print_nodes
def print_nodes(nodes, detailed=False): """Prints all the given nodes""" found = 0 for node in nodes: found += 1 print_node(node, detailed=detailed) print("\nFound {0} node{1}".format(found, "s" if found != 1 else ""))
python
def print_nodes(nodes, detailed=False): """Prints all the given nodes""" found = 0 for node in nodes: found += 1 print_node(node, detailed=detailed) print("\nFound {0} node{1}".format(found, "s" if found != 1 else ""))
[ "def", "print_nodes", "(", "nodes", ",", "detailed", "=", "False", ")", ":", "found", "=", "0", "for", "node", "in", "nodes", ":", "found", "+=", "1", "print_node", "(", "node", ",", "detailed", "=", "detailed", ")", "print", "(", "\"\\nFound {0} node{1}\"", ".", "format", "(", "found", ",", "\"s\"", "if", "found", "!=", "1", "else", "\"\"", ")", ")" ]
Prints all the given nodes
[ "Prints", "all", "the", "given", "nodes" ]
aab8c94081b38100a69cc100bc4278ae7419c58e
https://github.com/tobami/littlechef/blob/aab8c94081b38100a69cc100bc4278ae7419c58e/littlechef/lib.py#L219-L225
train
238,010
tobami/littlechef
littlechef/lib.py
_generate_metadata
def _generate_metadata(path, cookbook_path, name): """Checks whether metadata.rb has changed and regenerate metadata.json""" global knife_installed if not knife_installed: return metadata_path_rb = os.path.join(path, 'metadata.rb') metadata_path_json = os.path.join(path, 'metadata.json') if (os.path.exists(metadata_path_rb) and (not os.path.exists(metadata_path_json) or os.stat(metadata_path_rb).st_mtime > os.stat(metadata_path_json).st_mtime)): error_msg = "Warning: metadata.json for {0}".format(name) error_msg += " in {0} is older that metadata.rb".format(cookbook_path) error_msg += ", cookbook attributes could be out of date\n\n" try: proc = subprocess.Popen( ['knife', 'cookbook', 'metadata', '-o', cookbook_path, name], stdout=subprocess.PIPE, stderr=subprocess.PIPE) resp, error = proc.communicate() if ('ERROR:' in resp or 'FATAL:' in resp or 'Generating metadata for' not in resp): if("No user specified, pass via -u or specifiy 'node_name'" in error): error_msg += "You need to have an up-to-date (>=0.10.x)" error_msg += " version of knife installed locally in order" error_msg += " to generate metadata.json.\nError " else: error_msg += "Unkown error " error_msg += "while executing knife to generate " error_msg += "metadata.json for {0}".format(path) print(error_msg) print resp if env.loglevel == 'debug': print "\n".join(resp.split("\n")[:2]) except OSError: knife_installed = False error_msg += "If you locally install Chef's knife tool, LittleChef" error_msg += " will regenerate metadata.json files automatically\n" print(error_msg) else: print("Generated metadata.json for {0}\n".format(path))
python
def _generate_metadata(path, cookbook_path, name): """Checks whether metadata.rb has changed and regenerate metadata.json""" global knife_installed if not knife_installed: return metadata_path_rb = os.path.join(path, 'metadata.rb') metadata_path_json = os.path.join(path, 'metadata.json') if (os.path.exists(metadata_path_rb) and (not os.path.exists(metadata_path_json) or os.stat(metadata_path_rb).st_mtime > os.stat(metadata_path_json).st_mtime)): error_msg = "Warning: metadata.json for {0}".format(name) error_msg += " in {0} is older that metadata.rb".format(cookbook_path) error_msg += ", cookbook attributes could be out of date\n\n" try: proc = subprocess.Popen( ['knife', 'cookbook', 'metadata', '-o', cookbook_path, name], stdout=subprocess.PIPE, stderr=subprocess.PIPE) resp, error = proc.communicate() if ('ERROR:' in resp or 'FATAL:' in resp or 'Generating metadata for' not in resp): if("No user specified, pass via -u or specifiy 'node_name'" in error): error_msg += "You need to have an up-to-date (>=0.10.x)" error_msg += " version of knife installed locally in order" error_msg += " to generate metadata.json.\nError " else: error_msg += "Unkown error " error_msg += "while executing knife to generate " error_msg += "metadata.json for {0}".format(path) print(error_msg) print resp if env.loglevel == 'debug': print "\n".join(resp.split("\n")[:2]) except OSError: knife_installed = False error_msg += "If you locally install Chef's knife tool, LittleChef" error_msg += " will regenerate metadata.json files automatically\n" print(error_msg) else: print("Generated metadata.json for {0}\n".format(path))
[ "def", "_generate_metadata", "(", "path", ",", "cookbook_path", ",", "name", ")", ":", "global", "knife_installed", "if", "not", "knife_installed", ":", "return", "metadata_path_rb", "=", "os", ".", "path", ".", "join", "(", "path", ",", "'metadata.rb'", ")", "metadata_path_json", "=", "os", ".", "path", ".", "join", "(", "path", ",", "'metadata.json'", ")", "if", "(", "os", ".", "path", ".", "exists", "(", "metadata_path_rb", ")", "and", "(", "not", "os", ".", "path", ".", "exists", "(", "metadata_path_json", ")", "or", "os", ".", "stat", "(", "metadata_path_rb", ")", ".", "st_mtime", ">", "os", ".", "stat", "(", "metadata_path_json", ")", ".", "st_mtime", ")", ")", ":", "error_msg", "=", "\"Warning: metadata.json for {0}\"", ".", "format", "(", "name", ")", "error_msg", "+=", "\" in {0} is older that metadata.rb\"", ".", "format", "(", "cookbook_path", ")", "error_msg", "+=", "\", cookbook attributes could be out of date\\n\\n\"", "try", ":", "proc", "=", "subprocess", ".", "Popen", "(", "[", "'knife'", ",", "'cookbook'", ",", "'metadata'", ",", "'-o'", ",", "cookbook_path", ",", "name", "]", ",", "stdout", "=", "subprocess", ".", "PIPE", ",", "stderr", "=", "subprocess", ".", "PIPE", ")", "resp", ",", "error", "=", "proc", ".", "communicate", "(", ")", "if", "(", "'ERROR:'", "in", "resp", "or", "'FATAL:'", "in", "resp", "or", "'Generating metadata for'", "not", "in", "resp", ")", ":", "if", "(", "\"No user specified, pass via -u or specifiy 'node_name'\"", "in", "error", ")", ":", "error_msg", "+=", "\"You need to have an up-to-date (>=0.10.x)\"", "error_msg", "+=", "\" version of knife installed locally in order\"", "error_msg", "+=", "\" to generate metadata.json.\\nError \"", "else", ":", "error_msg", "+=", "\"Unkown error \"", "error_msg", "+=", "\"while executing knife to generate \"", "error_msg", "+=", "\"metadata.json for {0}\"", ".", "format", "(", "path", ")", "print", "(", "error_msg", ")", "print", "resp", "if", "env", ".", "loglevel", "==", "'debug'", ":", "print", "\"\\n\"", ".", "join", "(", "resp", ".", "split", "(", "\"\\n\"", ")", "[", ":", "2", "]", ")", "except", "OSError", ":", "knife_installed", "=", "False", "error_msg", "+=", "\"If you locally install Chef's knife tool, LittleChef\"", "error_msg", "+=", "\" will regenerate metadata.json files automatically\\n\"", "print", "(", "error_msg", ")", "else", ":", "print", "(", "\"Generated metadata.json for {0}\\n\"", ".", "format", "(", "path", ")", ")" ]
Checks whether metadata.rb has changed and regenerate metadata.json
[ "Checks", "whether", "metadata", ".", "rb", "has", "changed", "and", "regenerate", "metadata", ".", "json" ]
aab8c94081b38100a69cc100bc4278ae7419c58e
https://github.com/tobami/littlechef/blob/aab8c94081b38100a69cc100bc4278ae7419c58e/littlechef/lib.py#L228-L268
train
238,011
tobami/littlechef
littlechef/lib.py
get_recipes_in_cookbook
def get_recipes_in_cookbook(name): """Gets the name of all recipes present in a cookbook Returns a list of dictionaries """ recipes = {} path = None cookbook_exists = False metadata_exists = False for cookbook_path in cookbook_paths: path = os.path.join(cookbook_path, name) path_exists = os.path.exists(path) # cookbook exists if present in any of the cookbook paths cookbook_exists = cookbook_exists or path_exists if not path_exists: continue _generate_metadata(path, cookbook_path, name) # Now try to open metadata.json try: with open(os.path.join(path, 'metadata.json'), 'r') as f: try: cookbook = json.loads(f.read()) except ValueError as e: msg = "Little Chef found the following error in your" msg += " {0} file:\n {1}".format( os.path.join(path, 'metadata.json'), e) abort(msg) # Add each recipe defined in the cookbook metadata_exists = True recipe_defaults = { 'description': '', 'version': cookbook.get('version'), 'dependencies': cookbook.get('dependencies', {}).keys(), 'attributes': cookbook.get('attributes', {}) } for recipe in cookbook.get('recipes', []): recipes[recipe] = dict( recipe_defaults, name=recipe, description=cookbook['recipes'][recipe] ) # Cookbook metadata.json was found, don't try next cookbook path # because metadata.json in site-cookbooks has preference break except IOError: # metadata.json was not found, try next cookbook_path pass if not cookbook_exists: abort('Unable to find cookbook "{0}"'.format(name)) elif not metadata_exists: abort('Cookbook "{0}" has no metadata.json'.format(name)) # Add recipes found in the 'recipes' directory but not listed # in the metadata for cookbook_path in cookbook_paths: recipes_dir = os.path.join(cookbook_path, name, 'recipes') if not os.path.isdir(recipes_dir): continue for basename in os.listdir(recipes_dir): fname, ext = os.path.splitext(basename) if ext != '.rb': continue if fname != 'default': recipe = '%s::%s' % (name, fname) else: recipe = name if recipe not in recipes: recipes[recipe] = dict(recipe_defaults, name=recipe) # When a recipe has no default recipe (libraries?), # add one so that it is listed if not recipes: recipes[name] = dict( recipe_defaults, name=name, description='This cookbook has no default recipe' ) return recipes.values()
python
def get_recipes_in_cookbook(name): """Gets the name of all recipes present in a cookbook Returns a list of dictionaries """ recipes = {} path = None cookbook_exists = False metadata_exists = False for cookbook_path in cookbook_paths: path = os.path.join(cookbook_path, name) path_exists = os.path.exists(path) # cookbook exists if present in any of the cookbook paths cookbook_exists = cookbook_exists or path_exists if not path_exists: continue _generate_metadata(path, cookbook_path, name) # Now try to open metadata.json try: with open(os.path.join(path, 'metadata.json'), 'r') as f: try: cookbook = json.loads(f.read()) except ValueError as e: msg = "Little Chef found the following error in your" msg += " {0} file:\n {1}".format( os.path.join(path, 'metadata.json'), e) abort(msg) # Add each recipe defined in the cookbook metadata_exists = True recipe_defaults = { 'description': '', 'version': cookbook.get('version'), 'dependencies': cookbook.get('dependencies', {}).keys(), 'attributes': cookbook.get('attributes', {}) } for recipe in cookbook.get('recipes', []): recipes[recipe] = dict( recipe_defaults, name=recipe, description=cookbook['recipes'][recipe] ) # Cookbook metadata.json was found, don't try next cookbook path # because metadata.json in site-cookbooks has preference break except IOError: # metadata.json was not found, try next cookbook_path pass if not cookbook_exists: abort('Unable to find cookbook "{0}"'.format(name)) elif not metadata_exists: abort('Cookbook "{0}" has no metadata.json'.format(name)) # Add recipes found in the 'recipes' directory but not listed # in the metadata for cookbook_path in cookbook_paths: recipes_dir = os.path.join(cookbook_path, name, 'recipes') if not os.path.isdir(recipes_dir): continue for basename in os.listdir(recipes_dir): fname, ext = os.path.splitext(basename) if ext != '.rb': continue if fname != 'default': recipe = '%s::%s' % (name, fname) else: recipe = name if recipe not in recipes: recipes[recipe] = dict(recipe_defaults, name=recipe) # When a recipe has no default recipe (libraries?), # add one so that it is listed if not recipes: recipes[name] = dict( recipe_defaults, name=name, description='This cookbook has no default recipe' ) return recipes.values()
[ "def", "get_recipes_in_cookbook", "(", "name", ")", ":", "recipes", "=", "{", "}", "path", "=", "None", "cookbook_exists", "=", "False", "metadata_exists", "=", "False", "for", "cookbook_path", "in", "cookbook_paths", ":", "path", "=", "os", ".", "path", ".", "join", "(", "cookbook_path", ",", "name", ")", "path_exists", "=", "os", ".", "path", ".", "exists", "(", "path", ")", "# cookbook exists if present in any of the cookbook paths", "cookbook_exists", "=", "cookbook_exists", "or", "path_exists", "if", "not", "path_exists", ":", "continue", "_generate_metadata", "(", "path", ",", "cookbook_path", ",", "name", ")", "# Now try to open metadata.json", "try", ":", "with", "open", "(", "os", ".", "path", ".", "join", "(", "path", ",", "'metadata.json'", ")", ",", "'r'", ")", "as", "f", ":", "try", ":", "cookbook", "=", "json", ".", "loads", "(", "f", ".", "read", "(", ")", ")", "except", "ValueError", "as", "e", ":", "msg", "=", "\"Little Chef found the following error in your\"", "msg", "+=", "\" {0} file:\\n {1}\"", ".", "format", "(", "os", ".", "path", ".", "join", "(", "path", ",", "'metadata.json'", ")", ",", "e", ")", "abort", "(", "msg", ")", "# Add each recipe defined in the cookbook", "metadata_exists", "=", "True", "recipe_defaults", "=", "{", "'description'", ":", "''", ",", "'version'", ":", "cookbook", ".", "get", "(", "'version'", ")", ",", "'dependencies'", ":", "cookbook", ".", "get", "(", "'dependencies'", ",", "{", "}", ")", ".", "keys", "(", ")", ",", "'attributes'", ":", "cookbook", ".", "get", "(", "'attributes'", ",", "{", "}", ")", "}", "for", "recipe", "in", "cookbook", ".", "get", "(", "'recipes'", ",", "[", "]", ")", ":", "recipes", "[", "recipe", "]", "=", "dict", "(", "recipe_defaults", ",", "name", "=", "recipe", ",", "description", "=", "cookbook", "[", "'recipes'", "]", "[", "recipe", "]", ")", "# Cookbook metadata.json was found, don't try next cookbook path", "# because metadata.json in site-cookbooks has preference", "break", "except", "IOError", ":", "# metadata.json was not found, try next cookbook_path", "pass", "if", "not", "cookbook_exists", ":", "abort", "(", "'Unable to find cookbook \"{0}\"'", ".", "format", "(", "name", ")", ")", "elif", "not", "metadata_exists", ":", "abort", "(", "'Cookbook \"{0}\" has no metadata.json'", ".", "format", "(", "name", ")", ")", "# Add recipes found in the 'recipes' directory but not listed", "# in the metadata", "for", "cookbook_path", "in", "cookbook_paths", ":", "recipes_dir", "=", "os", ".", "path", ".", "join", "(", "cookbook_path", ",", "name", ",", "'recipes'", ")", "if", "not", "os", ".", "path", ".", "isdir", "(", "recipes_dir", ")", ":", "continue", "for", "basename", "in", "os", ".", "listdir", "(", "recipes_dir", ")", ":", "fname", ",", "ext", "=", "os", ".", "path", ".", "splitext", "(", "basename", ")", "if", "ext", "!=", "'.rb'", ":", "continue", "if", "fname", "!=", "'default'", ":", "recipe", "=", "'%s::%s'", "%", "(", "name", ",", "fname", ")", "else", ":", "recipe", "=", "name", "if", "recipe", "not", "in", "recipes", ":", "recipes", "[", "recipe", "]", "=", "dict", "(", "recipe_defaults", ",", "name", "=", "recipe", ")", "# When a recipe has no default recipe (libraries?),", "# add one so that it is listed", "if", "not", "recipes", ":", "recipes", "[", "name", "]", "=", "dict", "(", "recipe_defaults", ",", "name", "=", "name", ",", "description", "=", "'This cookbook has no default recipe'", ")", "return", "recipes", ".", "values", "(", ")" ]
Gets the name of all recipes present in a cookbook Returns a list of dictionaries
[ "Gets", "the", "name", "of", "all", "recipes", "present", "in", "a", "cookbook", "Returns", "a", "list", "of", "dictionaries" ]
aab8c94081b38100a69cc100bc4278ae7419c58e
https://github.com/tobami/littlechef/blob/aab8c94081b38100a69cc100bc4278ae7419c58e/littlechef/lib.py#L271-L348
train
238,012
tobami/littlechef
littlechef/lib.py
get_recipes_in_node
def get_recipes_in_node(node): """Gets the name of all recipes present in the run_list of a node""" recipes = [] for elem in node.get('run_list', []): if elem.startswith("recipe"): recipe = elem.split('[')[1].split(']')[0] recipes.append(recipe) return recipes
python
def get_recipes_in_node(node): """Gets the name of all recipes present in the run_list of a node""" recipes = [] for elem in node.get('run_list', []): if elem.startswith("recipe"): recipe = elem.split('[')[1].split(']')[0] recipes.append(recipe) return recipes
[ "def", "get_recipes_in_node", "(", "node", ")", ":", "recipes", "=", "[", "]", "for", "elem", "in", "node", ".", "get", "(", "'run_list'", ",", "[", "]", ")", ":", "if", "elem", ".", "startswith", "(", "\"recipe\"", ")", ":", "recipe", "=", "elem", ".", "split", "(", "'['", ")", "[", "1", "]", ".", "split", "(", "']'", ")", "[", "0", "]", "recipes", ".", "append", "(", "recipe", ")", "return", "recipes" ]
Gets the name of all recipes present in the run_list of a node
[ "Gets", "the", "name", "of", "all", "recipes", "present", "in", "the", "run_list", "of", "a", "node" ]
aab8c94081b38100a69cc100bc4278ae7419c58e
https://github.com/tobami/littlechef/blob/aab8c94081b38100a69cc100bc4278ae7419c58e/littlechef/lib.py#L357-L364
train
238,013
tobami/littlechef
littlechef/lib.py
get_recipes
def get_recipes(): """Gets all recipes found in the cookbook directories""" dirnames = set() for path in cookbook_paths: dirnames.update([d for d in os.listdir(path) if os.path.isdir( os.path.join(path, d)) and not d.startswith('.')]) recipes = [] for dirname in dirnames: recipes.extend(get_recipes_in_cookbook(dirname)) return sorted(recipes, key=lambda x: x['name'])
python
def get_recipes(): """Gets all recipes found in the cookbook directories""" dirnames = set() for path in cookbook_paths: dirnames.update([d for d in os.listdir(path) if os.path.isdir( os.path.join(path, d)) and not d.startswith('.')]) recipes = [] for dirname in dirnames: recipes.extend(get_recipes_in_cookbook(dirname)) return sorted(recipes, key=lambda x: x['name'])
[ "def", "get_recipes", "(", ")", ":", "dirnames", "=", "set", "(", ")", "for", "path", "in", "cookbook_paths", ":", "dirnames", ".", "update", "(", "[", "d", "for", "d", "in", "os", ".", "listdir", "(", "path", ")", "if", "os", ".", "path", ".", "isdir", "(", "os", ".", "path", ".", "join", "(", "path", ",", "d", ")", ")", "and", "not", "d", ".", "startswith", "(", "'.'", ")", "]", ")", "recipes", "=", "[", "]", "for", "dirname", "in", "dirnames", ":", "recipes", ".", "extend", "(", "get_recipes_in_cookbook", "(", "dirname", ")", ")", "return", "sorted", "(", "recipes", ",", "key", "=", "lambda", "x", ":", "x", "[", "'name'", "]", ")" ]
Gets all recipes found in the cookbook directories
[ "Gets", "all", "recipes", "found", "in", "the", "cookbook", "directories" ]
aab8c94081b38100a69cc100bc4278ae7419c58e
https://github.com/tobami/littlechef/blob/aab8c94081b38100a69cc100bc4278ae7419c58e/littlechef/lib.py#L367-L376
train
238,014
tobami/littlechef
littlechef/lib.py
print_recipe
def print_recipe(recipe): """Pretty prints the given recipe""" print(colors.yellow("\n{0}".format(recipe['name']))) print " description: {0}".format(recipe['description']) print " version: {0}".format(recipe['version']) print " dependencies: {0}".format(", ".join(recipe['dependencies'])) print " attributes: {0}".format(", ".join(recipe['attributes']))
python
def print_recipe(recipe): """Pretty prints the given recipe""" print(colors.yellow("\n{0}".format(recipe['name']))) print " description: {0}".format(recipe['description']) print " version: {0}".format(recipe['version']) print " dependencies: {0}".format(", ".join(recipe['dependencies'])) print " attributes: {0}".format(", ".join(recipe['attributes']))
[ "def", "print_recipe", "(", "recipe", ")", ":", "print", "(", "colors", ".", "yellow", "(", "\"\\n{0}\"", ".", "format", "(", "recipe", "[", "'name'", "]", ")", ")", ")", "print", "\" description: {0}\"", ".", "format", "(", "recipe", "[", "'description'", "]", ")", "print", "\" version: {0}\"", ".", "format", "(", "recipe", "[", "'version'", "]", ")", "print", "\" dependencies: {0}\"", ".", "format", "(", "\", \"", ".", "join", "(", "recipe", "[", "'dependencies'", "]", ")", ")", "print", "\" attributes: {0}\"", ".", "format", "(", "\", \"", ".", "join", "(", "recipe", "[", "'attributes'", "]", ")", ")" ]
Pretty prints the given recipe
[ "Pretty", "prints", "the", "given", "recipe" ]
aab8c94081b38100a69cc100bc4278ae7419c58e
https://github.com/tobami/littlechef/blob/aab8c94081b38100a69cc100bc4278ae7419c58e/littlechef/lib.py#L379-L385
train
238,015
tobami/littlechef
littlechef/lib.py
_get_role
def _get_role(rolename): """Reads and parses a file containing a role""" path = os.path.join('roles', rolename + '.json') if not os.path.exists(path): abort("Couldn't read role file {0}".format(path)) with open(path, 'r') as f: try: role = json.loads(f.read()) except ValueError as e: msg = "Little Chef found the following error in your" msg += " {0}.json file:\n {1}".format(rolename, str(e)) abort(msg) role['fullname'] = rolename return role
python
def _get_role(rolename): """Reads and parses a file containing a role""" path = os.path.join('roles', rolename + '.json') if not os.path.exists(path): abort("Couldn't read role file {0}".format(path)) with open(path, 'r') as f: try: role = json.loads(f.read()) except ValueError as e: msg = "Little Chef found the following error in your" msg += " {0}.json file:\n {1}".format(rolename, str(e)) abort(msg) role['fullname'] = rolename return role
[ "def", "_get_role", "(", "rolename", ")", ":", "path", "=", "os", ".", "path", ".", "join", "(", "'roles'", ",", "rolename", "+", "'.json'", ")", "if", "not", "os", ".", "path", ".", "exists", "(", "path", ")", ":", "abort", "(", "\"Couldn't read role file {0}\"", ".", "format", "(", "path", ")", ")", "with", "open", "(", "path", ",", "'r'", ")", "as", "f", ":", "try", ":", "role", "=", "json", ".", "loads", "(", "f", ".", "read", "(", ")", ")", "except", "ValueError", "as", "e", ":", "msg", "=", "\"Little Chef found the following error in your\"", "msg", "+=", "\" {0}.json file:\\n {1}\"", ".", "format", "(", "rolename", ",", "str", "(", "e", ")", ")", "abort", "(", "msg", ")", "role", "[", "'fullname'", "]", "=", "rolename", "return", "role" ]
Reads and parses a file containing a role
[ "Reads", "and", "parses", "a", "file", "containing", "a", "role" ]
aab8c94081b38100a69cc100bc4278ae7419c58e
https://github.com/tobami/littlechef/blob/aab8c94081b38100a69cc100bc4278ae7419c58e/littlechef/lib.py#L413-L426
train
238,016
tobami/littlechef
littlechef/lib.py
get_roles
def get_roles(): """Gets all roles found in the 'roles' directory""" roles = [] for root, subfolders, files in os.walk('roles'): for filename in files: if filename.endswith(".json"): path = os.path.join( root[len('roles'):], filename[:-len('.json')]) roles.append(_get_role(path)) return sorted(roles, key=lambda x: x['fullname'])
python
def get_roles(): """Gets all roles found in the 'roles' directory""" roles = [] for root, subfolders, files in os.walk('roles'): for filename in files: if filename.endswith(".json"): path = os.path.join( root[len('roles'):], filename[:-len('.json')]) roles.append(_get_role(path)) return sorted(roles, key=lambda x: x['fullname'])
[ "def", "get_roles", "(", ")", ":", "roles", "=", "[", "]", "for", "root", ",", "subfolders", ",", "files", "in", "os", ".", "walk", "(", "'roles'", ")", ":", "for", "filename", "in", "files", ":", "if", "filename", ".", "endswith", "(", "\".json\"", ")", ":", "path", "=", "os", ".", "path", ".", "join", "(", "root", "[", "len", "(", "'roles'", ")", ":", "]", ",", "filename", "[", ":", "-", "len", "(", "'.json'", ")", "]", ")", "roles", ".", "append", "(", "_get_role", "(", "path", ")", ")", "return", "sorted", "(", "roles", ",", "key", "=", "lambda", "x", ":", "x", "[", "'fullname'", "]", ")" ]
Gets all roles found in the 'roles' directory
[ "Gets", "all", "roles", "found", "in", "the", "roles", "directory" ]
aab8c94081b38100a69cc100bc4278ae7419c58e
https://github.com/tobami/littlechef/blob/aab8c94081b38100a69cc100bc4278ae7419c58e/littlechef/lib.py#L429-L438
train
238,017
tobami/littlechef
littlechef/lib.py
print_role
def print_role(role, detailed=True): """Pretty prints the given role""" if detailed: print(colors.yellow(role.get('fullname'))) else: print(" Role: {0}".format(role.get('fullname'))) if detailed: print(" description: {0}".format(role.get('description'))) if 'default_attributes' in role: print(" default_attributes:") _pprint(role['default_attributes']) if 'override_attributes' in role: print(" override_attributes:") _pprint(role['override_attributes']) if detailed: print(" run_list: {0}".format(role.get('run_list'))) print("")
python
def print_role(role, detailed=True): """Pretty prints the given role""" if detailed: print(colors.yellow(role.get('fullname'))) else: print(" Role: {0}".format(role.get('fullname'))) if detailed: print(" description: {0}".format(role.get('description'))) if 'default_attributes' in role: print(" default_attributes:") _pprint(role['default_attributes']) if 'override_attributes' in role: print(" override_attributes:") _pprint(role['override_attributes']) if detailed: print(" run_list: {0}".format(role.get('run_list'))) print("")
[ "def", "print_role", "(", "role", ",", "detailed", "=", "True", ")", ":", "if", "detailed", ":", "print", "(", "colors", ".", "yellow", "(", "role", ".", "get", "(", "'fullname'", ")", ")", ")", "else", ":", "print", "(", "\" Role: {0}\"", ".", "format", "(", "role", ".", "get", "(", "'fullname'", ")", ")", ")", "if", "detailed", ":", "print", "(", "\" description: {0}\"", ".", "format", "(", "role", ".", "get", "(", "'description'", ")", ")", ")", "if", "'default_attributes'", "in", "role", ":", "print", "(", "\" default_attributes:\"", ")", "_pprint", "(", "role", "[", "'default_attributes'", "]", ")", "if", "'override_attributes'", "in", "role", ":", "print", "(", "\" override_attributes:\"", ")", "_pprint", "(", "role", "[", "'override_attributes'", "]", ")", "if", "detailed", ":", "print", "(", "\" run_list: {0}\"", ".", "format", "(", "role", ".", "get", "(", "'run_list'", ")", ")", ")", "print", "(", "\"\"", ")" ]
Pretty prints the given role
[ "Pretty", "prints", "the", "given", "role" ]
aab8c94081b38100a69cc100bc4278ae7419c58e
https://github.com/tobami/littlechef/blob/aab8c94081b38100a69cc100bc4278ae7419c58e/littlechef/lib.py#L441-L457
train
238,018
tobami/littlechef
littlechef/lib.py
import_plugin
def import_plugin(name): """Imports plugin python module""" path = os.path.join("plugins", name + ".py") try: with open(path, 'rb') as f: try: plugin = imp.load_module( "p_" + name, f, name + '.py', ('.py', 'rb', imp.PY_SOURCE) ) except SyntaxError as e: error = "Found plugin '{0}', but it seems".format(name) error += " to have a syntax error: {0}".format(str(e)) abort(error) except IOError: abort("Sorry, could not find '{0}.py' in the plugin directory".format( name)) return plugin
python
def import_plugin(name): """Imports plugin python module""" path = os.path.join("plugins", name + ".py") try: with open(path, 'rb') as f: try: plugin = imp.load_module( "p_" + name, f, name + '.py', ('.py', 'rb', imp.PY_SOURCE) ) except SyntaxError as e: error = "Found plugin '{0}', but it seems".format(name) error += " to have a syntax error: {0}".format(str(e)) abort(error) except IOError: abort("Sorry, could not find '{0}.py' in the plugin directory".format( name)) return plugin
[ "def", "import_plugin", "(", "name", ")", ":", "path", "=", "os", ".", "path", ".", "join", "(", "\"plugins\"", ",", "name", "+", "\".py\"", ")", "try", ":", "with", "open", "(", "path", ",", "'rb'", ")", "as", "f", ":", "try", ":", "plugin", "=", "imp", ".", "load_module", "(", "\"p_\"", "+", "name", ",", "f", ",", "name", "+", "'.py'", ",", "(", "'.py'", ",", "'rb'", ",", "imp", ".", "PY_SOURCE", ")", ")", "except", "SyntaxError", "as", "e", ":", "error", "=", "\"Found plugin '{0}', but it seems\"", ".", "format", "(", "name", ")", "error", "+=", "\" to have a syntax error: {0}\"", ".", "format", "(", "str", "(", "e", ")", ")", "abort", "(", "error", ")", "except", "IOError", ":", "abort", "(", "\"Sorry, could not find '{0}.py' in the plugin directory\"", ".", "format", "(", "name", ")", ")", "return", "plugin" ]
Imports plugin python module
[ "Imports", "plugin", "python", "module" ]
aab8c94081b38100a69cc100bc4278ae7419c58e
https://github.com/tobami/littlechef/blob/aab8c94081b38100a69cc100bc4278ae7419c58e/littlechef/lib.py#L482-L499
train
238,019
tobami/littlechef
littlechef/lib.py
get_cookbook_path
def get_cookbook_path(cookbook_name): """Returns path to the cookbook for the given cookbook name""" for cookbook_path in cookbook_paths: path = os.path.join(cookbook_path, cookbook_name) if os.path.exists(path): return path raise IOError('Can\'t find cookbook with name "{0}"'.format(cookbook_name))
python
def get_cookbook_path(cookbook_name): """Returns path to the cookbook for the given cookbook name""" for cookbook_path in cookbook_paths: path = os.path.join(cookbook_path, cookbook_name) if os.path.exists(path): return path raise IOError('Can\'t find cookbook with name "{0}"'.format(cookbook_name))
[ "def", "get_cookbook_path", "(", "cookbook_name", ")", ":", "for", "cookbook_path", "in", "cookbook_paths", ":", "path", "=", "os", ".", "path", ".", "join", "(", "cookbook_path", ",", "cookbook_name", ")", "if", "os", ".", "path", ".", "exists", "(", "path", ")", ":", "return", "path", "raise", "IOError", "(", "'Can\\'t find cookbook with name \"{0}\"'", ".", "format", "(", "cookbook_name", ")", ")" ]
Returns path to the cookbook for the given cookbook name
[ "Returns", "path", "to", "the", "cookbook", "for", "the", "given", "cookbook", "name" ]
aab8c94081b38100a69cc100bc4278ae7419c58e
https://github.com/tobami/littlechef/blob/aab8c94081b38100a69cc100bc4278ae7419c58e/littlechef/lib.py#L502-L508
train
238,020
tobami/littlechef
littlechef/lib.py
global_confirm
def global_confirm(question, default=True): """Shows a confirmation that applies to all hosts by temporarily disabling parallel execution in Fabric """ if env.abort_on_prompts: return True original_parallel = env.parallel env.parallel = False result = confirm(question, default) env.parallel = original_parallel return result
python
def global_confirm(question, default=True): """Shows a confirmation that applies to all hosts by temporarily disabling parallel execution in Fabric """ if env.abort_on_prompts: return True original_parallel = env.parallel env.parallel = False result = confirm(question, default) env.parallel = original_parallel return result
[ "def", "global_confirm", "(", "question", ",", "default", "=", "True", ")", ":", "if", "env", ".", "abort_on_prompts", ":", "return", "True", "original_parallel", "=", "env", ".", "parallel", "env", ".", "parallel", "=", "False", "result", "=", "confirm", "(", "question", ",", "default", ")", "env", ".", "parallel", "=", "original_parallel", "return", "result" ]
Shows a confirmation that applies to all hosts by temporarily disabling parallel execution in Fabric
[ "Shows", "a", "confirmation", "that", "applies", "to", "all", "hosts", "by", "temporarily", "disabling", "parallel", "execution", "in", "Fabric" ]
aab8c94081b38100a69cc100bc4278ae7419c58e
https://github.com/tobami/littlechef/blob/aab8c94081b38100a69cc100bc4278ae7419c58e/littlechef/lib.py#L511-L521
train
238,021
tobami/littlechef
littlechef/lib.py
_pprint
def _pprint(dic): """Prints a dictionary with one indentation level""" for key, value in dic.items(): print(" {0}: {1}".format(key, value))
python
def _pprint(dic): """Prints a dictionary with one indentation level""" for key, value in dic.items(): print(" {0}: {1}".format(key, value))
[ "def", "_pprint", "(", "dic", ")", ":", "for", "key", ",", "value", "in", "dic", ".", "items", "(", ")", ":", "print", "(", "\" {0}: {1}\"", ".", "format", "(", "key", ",", "value", ")", ")" ]
Prints a dictionary with one indentation level
[ "Prints", "a", "dictionary", "with", "one", "indentation", "level" ]
aab8c94081b38100a69cc100bc4278ae7419c58e
https://github.com/tobami/littlechef/blob/aab8c94081b38100a69cc100bc4278ae7419c58e/littlechef/lib.py#L524-L527
train
238,022
tobami/littlechef
littlechef/lib.py
get_margin
def get_margin(length): """Add enough tabs to align in two columns""" if length > 23: margin_left = "\t" chars = 1 elif length > 15: margin_left = "\t\t" chars = 2 elif length > 7: margin_left = "\t\t\t" chars = 3 else: margin_left = "\t\t\t\t" chars = 4 return margin_left
python
def get_margin(length): """Add enough tabs to align in two columns""" if length > 23: margin_left = "\t" chars = 1 elif length > 15: margin_left = "\t\t" chars = 2 elif length > 7: margin_left = "\t\t\t" chars = 3 else: margin_left = "\t\t\t\t" chars = 4 return margin_left
[ "def", "get_margin", "(", "length", ")", ":", "if", "length", ">", "23", ":", "margin_left", "=", "\"\\t\"", "chars", "=", "1", "elif", "length", ">", "15", ":", "margin_left", "=", "\"\\t\\t\"", "chars", "=", "2", "elif", "length", ">", "7", ":", "margin_left", "=", "\"\\t\\t\\t\"", "chars", "=", "3", "else", ":", "margin_left", "=", "\"\\t\\t\\t\\t\"", "chars", "=", "4", "return", "margin_left" ]
Add enough tabs to align in two columns
[ "Add", "enough", "tabs", "to", "align", "in", "two", "columns" ]
aab8c94081b38100a69cc100bc4278ae7419c58e
https://github.com/tobami/littlechef/blob/aab8c94081b38100a69cc100bc4278ae7419c58e/littlechef/lib.py#L535-L549
train
238,023
tobami/littlechef
littlechef/solo.py
configure
def configure(current_node=None): """Deploy chef-solo specific files""" current_node = current_node or {} # Ensure that the /tmp/chef-solo/cache directory exist cache_dir = "{0}/cache".format(env.node_work_path) # First remote call, could go wrong try: cache_exists = exists(cache_dir) except EOFError as e: abort("Could not login to node, got: {0}".format(e)) if not cache_exists: with settings(hide('running', 'stdout'), warn_only=True): output = sudo('mkdir -p {0}'.format(cache_dir)) if output.failed: error = "Could not create {0} dir. ".format(env.node_work_path) error += "Do you have sudo rights?" abort(error) # Change ownership of /tmp/chef-solo/ so that we can rsync with hide('running', 'stdout'): with settings(warn_only=True): output = sudo( 'chown -R {0} {1}'.format(env.user, env.node_work_path)) if output.failed: error = "Could not modify {0} dir. ".format(env.node_work_path) error += "Do you have sudo rights?" abort(error) # Set up chef solo configuration logging_path = os.path.dirname(LOGFILE) if not exists(logging_path): sudo('mkdir -p {0}'.format(logging_path)) if not exists('/etc/chef'): sudo('mkdir -p /etc/chef') # Set parameters and upload solo.rb template reversed_cookbook_paths = cookbook_paths[:] reversed_cookbook_paths.reverse() cookbook_paths_list = '[{0}]'.format(', '.join( ['"{0}/{1}"'.format(env.node_work_path, x) for x in reversed_cookbook_paths])) data = { 'node_work_path': env.node_work_path, 'cookbook_paths_list': cookbook_paths_list, 'environment': current_node.get('chef_environment', '_default'), 'verbose': "true" if env.verbose else "false", 'http_proxy': env.http_proxy, 'https_proxy': env.https_proxy } with settings(hide('everything')): try: upload_template('solo.rb.j2', '/etc/chef/solo.rb', context=data, use_sudo=True, backup=False, template_dir=BASEDIR, use_jinja=True, mode=0400) except SystemExit: error = ("Failed to upload '/etc/chef/solo.rb'\nThis " "can happen when the deployment user does not have a " "home directory, which is needed as a temporary location") abort(error) with hide('stdout'): sudo('chown root:$(id -g -n root) {0}'.format('/etc/chef/solo.rb'))
python
def configure(current_node=None): """Deploy chef-solo specific files""" current_node = current_node or {} # Ensure that the /tmp/chef-solo/cache directory exist cache_dir = "{0}/cache".format(env.node_work_path) # First remote call, could go wrong try: cache_exists = exists(cache_dir) except EOFError as e: abort("Could not login to node, got: {0}".format(e)) if not cache_exists: with settings(hide('running', 'stdout'), warn_only=True): output = sudo('mkdir -p {0}'.format(cache_dir)) if output.failed: error = "Could not create {0} dir. ".format(env.node_work_path) error += "Do you have sudo rights?" abort(error) # Change ownership of /tmp/chef-solo/ so that we can rsync with hide('running', 'stdout'): with settings(warn_only=True): output = sudo( 'chown -R {0} {1}'.format(env.user, env.node_work_path)) if output.failed: error = "Could not modify {0} dir. ".format(env.node_work_path) error += "Do you have sudo rights?" abort(error) # Set up chef solo configuration logging_path = os.path.dirname(LOGFILE) if not exists(logging_path): sudo('mkdir -p {0}'.format(logging_path)) if not exists('/etc/chef'): sudo('mkdir -p /etc/chef') # Set parameters and upload solo.rb template reversed_cookbook_paths = cookbook_paths[:] reversed_cookbook_paths.reverse() cookbook_paths_list = '[{0}]'.format(', '.join( ['"{0}/{1}"'.format(env.node_work_path, x) for x in reversed_cookbook_paths])) data = { 'node_work_path': env.node_work_path, 'cookbook_paths_list': cookbook_paths_list, 'environment': current_node.get('chef_environment', '_default'), 'verbose': "true" if env.verbose else "false", 'http_proxy': env.http_proxy, 'https_proxy': env.https_proxy } with settings(hide('everything')): try: upload_template('solo.rb.j2', '/etc/chef/solo.rb', context=data, use_sudo=True, backup=False, template_dir=BASEDIR, use_jinja=True, mode=0400) except SystemExit: error = ("Failed to upload '/etc/chef/solo.rb'\nThis " "can happen when the deployment user does not have a " "home directory, which is needed as a temporary location") abort(error) with hide('stdout'): sudo('chown root:$(id -g -n root) {0}'.format('/etc/chef/solo.rb'))
[ "def", "configure", "(", "current_node", "=", "None", ")", ":", "current_node", "=", "current_node", "or", "{", "}", "# Ensure that the /tmp/chef-solo/cache directory exist", "cache_dir", "=", "\"{0}/cache\"", ".", "format", "(", "env", ".", "node_work_path", ")", "# First remote call, could go wrong", "try", ":", "cache_exists", "=", "exists", "(", "cache_dir", ")", "except", "EOFError", "as", "e", ":", "abort", "(", "\"Could not login to node, got: {0}\"", ".", "format", "(", "e", ")", ")", "if", "not", "cache_exists", ":", "with", "settings", "(", "hide", "(", "'running'", ",", "'stdout'", ")", ",", "warn_only", "=", "True", ")", ":", "output", "=", "sudo", "(", "'mkdir -p {0}'", ".", "format", "(", "cache_dir", ")", ")", "if", "output", ".", "failed", ":", "error", "=", "\"Could not create {0} dir. \"", ".", "format", "(", "env", ".", "node_work_path", ")", "error", "+=", "\"Do you have sudo rights?\"", "abort", "(", "error", ")", "# Change ownership of /tmp/chef-solo/ so that we can rsync", "with", "hide", "(", "'running'", ",", "'stdout'", ")", ":", "with", "settings", "(", "warn_only", "=", "True", ")", ":", "output", "=", "sudo", "(", "'chown -R {0} {1}'", ".", "format", "(", "env", ".", "user", ",", "env", ".", "node_work_path", ")", ")", "if", "output", ".", "failed", ":", "error", "=", "\"Could not modify {0} dir. \"", ".", "format", "(", "env", ".", "node_work_path", ")", "error", "+=", "\"Do you have sudo rights?\"", "abort", "(", "error", ")", "# Set up chef solo configuration", "logging_path", "=", "os", ".", "path", ".", "dirname", "(", "LOGFILE", ")", "if", "not", "exists", "(", "logging_path", ")", ":", "sudo", "(", "'mkdir -p {0}'", ".", "format", "(", "logging_path", ")", ")", "if", "not", "exists", "(", "'/etc/chef'", ")", ":", "sudo", "(", "'mkdir -p /etc/chef'", ")", "# Set parameters and upload solo.rb template", "reversed_cookbook_paths", "=", "cookbook_paths", "[", ":", "]", "reversed_cookbook_paths", ".", "reverse", "(", ")", "cookbook_paths_list", "=", "'[{0}]'", ".", "format", "(", "', '", ".", "join", "(", "[", "'\"{0}/{1}\"'", ".", "format", "(", "env", ".", "node_work_path", ",", "x", ")", "for", "x", "in", "reversed_cookbook_paths", "]", ")", ")", "data", "=", "{", "'node_work_path'", ":", "env", ".", "node_work_path", ",", "'cookbook_paths_list'", ":", "cookbook_paths_list", ",", "'environment'", ":", "current_node", ".", "get", "(", "'chef_environment'", ",", "'_default'", ")", ",", "'verbose'", ":", "\"true\"", "if", "env", ".", "verbose", "else", "\"false\"", ",", "'http_proxy'", ":", "env", ".", "http_proxy", ",", "'https_proxy'", ":", "env", ".", "https_proxy", "}", "with", "settings", "(", "hide", "(", "'everything'", ")", ")", ":", "try", ":", "upload_template", "(", "'solo.rb.j2'", ",", "'/etc/chef/solo.rb'", ",", "context", "=", "data", ",", "use_sudo", "=", "True", ",", "backup", "=", "False", ",", "template_dir", "=", "BASEDIR", ",", "use_jinja", "=", "True", ",", "mode", "=", "0400", ")", "except", "SystemExit", ":", "error", "=", "(", "\"Failed to upload '/etc/chef/solo.rb'\\nThis \"", "\"can happen when the deployment user does not have a \"", "\"home directory, which is needed as a temporary location\"", ")", "abort", "(", "error", ")", "with", "hide", "(", "'stdout'", ")", ":", "sudo", "(", "'chown root:$(id -g -n root) {0}'", ".", "format", "(", "'/etc/chef/solo.rb'", ")", ")" ]
Deploy chef-solo specific files
[ "Deploy", "chef", "-", "solo", "specific", "files" ]
aab8c94081b38100a69cc100bc4278ae7419c58e
https://github.com/tobami/littlechef/blob/aab8c94081b38100a69cc100bc4278ae7419c58e/littlechef/solo.py#L42-L99
train
238,024
tobami/littlechef
plugins/save_xen_info.py
execute
def execute(node): """Uses ohai to get virtualization information which is then saved to then node file """ with hide('everything'): virt = json.loads(sudo('ohai virtualization')) if not len(virt) or virt[0][1] != "host": # It may work for virtualization solutions other than Xen print("This node is not a Xen host, doing nothing") return node['virtualization'] = { 'role': 'host', 'system': 'xen', 'vms': [], } # VMs with hide('everything'): vm_list = sudo("xm list") for vm in vm_list.split("\n")[2:]: data = vm.split() if len(data) != 6: break node['virtualization']['vms'].append({ 'fqdn': data[0], 'RAM': data[2], 'cpus': data[3]}) print("Found {0} VMs for this Xen host".format( len(node['virtualization']['vms']))) # Save node file and remove the returned temp file del node['name'] os.remove(chef.save_config(node, True))
python
def execute(node): """Uses ohai to get virtualization information which is then saved to then node file """ with hide('everything'): virt = json.loads(sudo('ohai virtualization')) if not len(virt) or virt[0][1] != "host": # It may work for virtualization solutions other than Xen print("This node is not a Xen host, doing nothing") return node['virtualization'] = { 'role': 'host', 'system': 'xen', 'vms': [], } # VMs with hide('everything'): vm_list = sudo("xm list") for vm in vm_list.split("\n")[2:]: data = vm.split() if len(data) != 6: break node['virtualization']['vms'].append({ 'fqdn': data[0], 'RAM': data[2], 'cpus': data[3]}) print("Found {0} VMs for this Xen host".format( len(node['virtualization']['vms']))) # Save node file and remove the returned temp file del node['name'] os.remove(chef.save_config(node, True))
[ "def", "execute", "(", "node", ")", ":", "with", "hide", "(", "'everything'", ")", ":", "virt", "=", "json", ".", "loads", "(", "sudo", "(", "'ohai virtualization'", ")", ")", "if", "not", "len", "(", "virt", ")", "or", "virt", "[", "0", "]", "[", "1", "]", "!=", "\"host\"", ":", "# It may work for virtualization solutions other than Xen", "print", "(", "\"This node is not a Xen host, doing nothing\"", ")", "return", "node", "[", "'virtualization'", "]", "=", "{", "'role'", ":", "'host'", ",", "'system'", ":", "'xen'", ",", "'vms'", ":", "[", "]", ",", "}", "# VMs", "with", "hide", "(", "'everything'", ")", ":", "vm_list", "=", "sudo", "(", "\"xm list\"", ")", "for", "vm", "in", "vm_list", ".", "split", "(", "\"\\n\"", ")", "[", "2", ":", "]", ":", "data", "=", "vm", ".", "split", "(", ")", "if", "len", "(", "data", ")", "!=", "6", ":", "break", "node", "[", "'virtualization'", "]", "[", "'vms'", "]", ".", "append", "(", "{", "'fqdn'", ":", "data", "[", "0", "]", ",", "'RAM'", ":", "data", "[", "2", "]", ",", "'cpus'", ":", "data", "[", "3", "]", "}", ")", "print", "(", "\"Found {0} VMs for this Xen host\"", ".", "format", "(", "len", "(", "node", "[", "'virtualization'", "]", "[", "'vms'", "]", ")", ")", ")", "# Save node file and remove the returned temp file", "del", "node", "[", "'name'", "]", "os", ".", "remove", "(", "chef", ".", "save_config", "(", "node", ",", "True", ")", ")" ]
Uses ohai to get virtualization information which is then saved to then node file
[ "Uses", "ohai", "to", "get", "virtualization", "information", "which", "is", "then", "saved", "to", "then", "node", "file" ]
aab8c94081b38100a69cc100bc4278ae7419c58e
https://github.com/tobami/littlechef/blob/aab8c94081b38100a69cc100bc4278ae7419c58e/plugins/save_xen_info.py#L11-L40
train
238,025
tobami/littlechef
littlechef/runner.py
nodes_with_role
def nodes_with_role(rolename): """Configures a list of nodes that have the given role in their run list""" nodes = [n['name'] for n in lib.get_nodes_with_role(rolename, env.chef_environment)] if not len(nodes): print("No nodes found with role '{0}'".format(rolename)) sys.exit(0) return node(*nodes)
python
def nodes_with_role(rolename): """Configures a list of nodes that have the given role in their run list""" nodes = [n['name'] for n in lib.get_nodes_with_role(rolename, env.chef_environment)] if not len(nodes): print("No nodes found with role '{0}'".format(rolename)) sys.exit(0) return node(*nodes)
[ "def", "nodes_with_role", "(", "rolename", ")", ":", "nodes", "=", "[", "n", "[", "'name'", "]", "for", "n", "in", "lib", ".", "get_nodes_with_role", "(", "rolename", ",", "env", ".", "chef_environment", ")", "]", "if", "not", "len", "(", "nodes", ")", ":", "print", "(", "\"No nodes found with role '{0}'\"", ".", "format", "(", "rolename", ")", ")", "sys", ".", "exit", "(", "0", ")", "return", "node", "(", "*", "nodes", ")" ]
Configures a list of nodes that have the given role in their run list
[ "Configures", "a", "list", "of", "nodes", "that", "have", "the", "given", "role", "in", "their", "run", "list" ]
aab8c94081b38100a69cc100bc4278ae7419c58e
https://github.com/tobami/littlechef/blob/aab8c94081b38100a69cc100bc4278ae7419c58e/littlechef/runner.py#L92-L99
train
238,026
tobami/littlechef
littlechef/runner.py
nodes_with_recipe
def nodes_with_recipe(recipename): """Configures a list of nodes that have the given recipe in their run list """ nodes = [n['name'] for n in lib.get_nodes_with_recipe(recipename, env.chef_environment)] if not len(nodes): print("No nodes found with recipe '{0}'".format(recipename)) sys.exit(0) return node(*nodes)
python
def nodes_with_recipe(recipename): """Configures a list of nodes that have the given recipe in their run list """ nodes = [n['name'] for n in lib.get_nodes_with_recipe(recipename, env.chef_environment)] if not len(nodes): print("No nodes found with recipe '{0}'".format(recipename)) sys.exit(0) return node(*nodes)
[ "def", "nodes_with_recipe", "(", "recipename", ")", ":", "nodes", "=", "[", "n", "[", "'name'", "]", "for", "n", "in", "lib", ".", "get_nodes_with_recipe", "(", "recipename", ",", "env", ".", "chef_environment", ")", "]", "if", "not", "len", "(", "nodes", ")", ":", "print", "(", "\"No nodes found with recipe '{0}'\"", ".", "format", "(", "recipename", ")", ")", "sys", ".", "exit", "(", "0", ")", "return", "node", "(", "*", "nodes", ")" ]
Configures a list of nodes that have the given recipe in their run list
[ "Configures", "a", "list", "of", "nodes", "that", "have", "the", "given", "recipe", "in", "their", "run", "list" ]
aab8c94081b38100a69cc100bc4278ae7419c58e
https://github.com/tobami/littlechef/blob/aab8c94081b38100a69cc100bc4278ae7419c58e/littlechef/runner.py#L102-L110
train
238,027
tobami/littlechef
littlechef/runner.py
node
def node(*nodes): """Selects and configures a list of nodes. 'all' configures all nodes""" chef.build_node_data_bag() if not len(nodes) or nodes[0] == '': abort('No node was given') elif nodes[0] == 'all': # Fetch all nodes and add them to env.hosts for node in lib.get_nodes(env.chef_environment): env.hosts.append(node['name']) if not len(env.hosts): abort('No nodes found in /nodes/') message = "Are you sure you want to configure all nodes ({0})".format( len(env.hosts)) if env.chef_environment: message += " in the {0} environment".format(env.chef_environment) message += "?" if not __testing__: if not lib.global_confirm(message): abort('Aborted by user') else: # A list of nodes was given env.hosts = list(nodes) env.all_hosts = list(env.hosts) # Shouldn't be needed # Check whether another command was given in addition to "node:" if not(littlechef.__cooking__ and 'node:' not in sys.argv[-1] and 'nodes_with_role:' not in sys.argv[-1] and 'nodes_with_recipe:' not in sys.argv[-1] and 'nodes_with_tag:' not in sys.argv[-1]): # If user didn't type recipe:X, role:Y or deploy_chef, # configure the nodes with settings(): execute(_node_runner) chef.remove_local_node_data_bag()
python
def node(*nodes): """Selects and configures a list of nodes. 'all' configures all nodes""" chef.build_node_data_bag() if not len(nodes) or nodes[0] == '': abort('No node was given') elif nodes[0] == 'all': # Fetch all nodes and add them to env.hosts for node in lib.get_nodes(env.chef_environment): env.hosts.append(node['name']) if not len(env.hosts): abort('No nodes found in /nodes/') message = "Are you sure you want to configure all nodes ({0})".format( len(env.hosts)) if env.chef_environment: message += " in the {0} environment".format(env.chef_environment) message += "?" if not __testing__: if not lib.global_confirm(message): abort('Aborted by user') else: # A list of nodes was given env.hosts = list(nodes) env.all_hosts = list(env.hosts) # Shouldn't be needed # Check whether another command was given in addition to "node:" if not(littlechef.__cooking__ and 'node:' not in sys.argv[-1] and 'nodes_with_role:' not in sys.argv[-1] and 'nodes_with_recipe:' not in sys.argv[-1] and 'nodes_with_tag:' not in sys.argv[-1]): # If user didn't type recipe:X, role:Y or deploy_chef, # configure the nodes with settings(): execute(_node_runner) chef.remove_local_node_data_bag()
[ "def", "node", "(", "*", "nodes", ")", ":", "chef", ".", "build_node_data_bag", "(", ")", "if", "not", "len", "(", "nodes", ")", "or", "nodes", "[", "0", "]", "==", "''", ":", "abort", "(", "'No node was given'", ")", "elif", "nodes", "[", "0", "]", "==", "'all'", ":", "# Fetch all nodes and add them to env.hosts", "for", "node", "in", "lib", ".", "get_nodes", "(", "env", ".", "chef_environment", ")", ":", "env", ".", "hosts", ".", "append", "(", "node", "[", "'name'", "]", ")", "if", "not", "len", "(", "env", ".", "hosts", ")", ":", "abort", "(", "'No nodes found in /nodes/'", ")", "message", "=", "\"Are you sure you want to configure all nodes ({0})\"", ".", "format", "(", "len", "(", "env", ".", "hosts", ")", ")", "if", "env", ".", "chef_environment", ":", "message", "+=", "\" in the {0} environment\"", ".", "format", "(", "env", ".", "chef_environment", ")", "message", "+=", "\"?\"", "if", "not", "__testing__", ":", "if", "not", "lib", ".", "global_confirm", "(", "message", ")", ":", "abort", "(", "'Aborted by user'", ")", "else", ":", "# A list of nodes was given", "env", ".", "hosts", "=", "list", "(", "nodes", ")", "env", ".", "all_hosts", "=", "list", "(", "env", ".", "hosts", ")", "# Shouldn't be needed", "# Check whether another command was given in addition to \"node:\"", "if", "not", "(", "littlechef", ".", "__cooking__", "and", "'node:'", "not", "in", "sys", ".", "argv", "[", "-", "1", "]", "and", "'nodes_with_role:'", "not", "in", "sys", ".", "argv", "[", "-", "1", "]", "and", "'nodes_with_recipe:'", "not", "in", "sys", ".", "argv", "[", "-", "1", "]", "and", "'nodes_with_tag:'", "not", "in", "sys", ".", "argv", "[", "-", "1", "]", ")", ":", "# If user didn't type recipe:X, role:Y or deploy_chef,", "# configure the nodes", "with", "settings", "(", ")", ":", "execute", "(", "_node_runner", ")", "chef", ".", "remove_local_node_data_bag", "(", ")" ]
Selects and configures a list of nodes. 'all' configures all nodes
[ "Selects", "and", "configures", "a", "list", "of", "nodes", ".", "all", "configures", "all", "nodes" ]
aab8c94081b38100a69cc100bc4278ae7419c58e
https://github.com/tobami/littlechef/blob/aab8c94081b38100a69cc100bc4278ae7419c58e/littlechef/runner.py#L124-L158
train
238,028
tobami/littlechef
littlechef/runner.py
_node_runner
def _node_runner(): """This is only used by node so that we can execute in parallel""" env.host_string = lib.get_env_host_string() node = lib.get_node(env.host_string) _configure_fabric_for_platform(node.get("platform")) if __testing__: print "TEST: would now configure {0}".format(env.host_string) else: lib.print_header("Configuring {0}".format(env.host_string)) if env.autodeploy_chef and not chef.chef_test(): deploy_chef(ask="no") chef.sync_node(node)
python
def _node_runner(): """This is only used by node so that we can execute in parallel""" env.host_string = lib.get_env_host_string() node = lib.get_node(env.host_string) _configure_fabric_for_platform(node.get("platform")) if __testing__: print "TEST: would now configure {0}".format(env.host_string) else: lib.print_header("Configuring {0}".format(env.host_string)) if env.autodeploy_chef and not chef.chef_test(): deploy_chef(ask="no") chef.sync_node(node)
[ "def", "_node_runner", "(", ")", ":", "env", ".", "host_string", "=", "lib", ".", "get_env_host_string", "(", ")", "node", "=", "lib", ".", "get_node", "(", "env", ".", "host_string", ")", "_configure_fabric_for_platform", "(", "node", ".", "get", "(", "\"platform\"", ")", ")", "if", "__testing__", ":", "print", "\"TEST: would now configure {0}\"", ".", "format", "(", "env", ".", "host_string", ")", "else", ":", "lib", ".", "print_header", "(", "\"Configuring {0}\"", ".", "format", "(", "env", ".", "host_string", ")", ")", "if", "env", ".", "autodeploy_chef", "and", "not", "chef", ".", "chef_test", "(", ")", ":", "deploy_chef", "(", "ask", "=", "\"no\"", ")", "chef", ".", "sync_node", "(", "node", ")" ]
This is only used by node so that we can execute in parallel
[ "This", "is", "only", "used", "by", "node", "so", "that", "we", "can", "execute", "in", "parallel" ]
aab8c94081b38100a69cc100bc4278ae7419c58e
https://github.com/tobami/littlechef/blob/aab8c94081b38100a69cc100bc4278ae7419c58e/littlechef/runner.py#L167-L180
train
238,029
tobami/littlechef
littlechef/runner.py
deploy_chef
def deploy_chef(ask="yes", version="11"): """Install chef-solo on a node""" env.host_string = lib.get_env_host_string() if ask == "no" or littlechef.noninteractive: print("Deploying Chef using omnibus installer version: ...".format(version)) else: message = ('\nAre you sure you want to install Chef version:' '{0} on node {1}?'.format(version, env.host_string)) if not confirm(message): abort('Aborted by user') lib.print_header("Configuring Chef Solo on {0}".format(env.host_string)) if not __testing__: solo.install(version) solo.configure() # Build a basic node file if there isn't one already # with some properties from ohai with settings(hide('stdout'), warn_only=True): output = sudo('ohai -l warn') if output.succeeded: try: ohai = json.loads(output) except ValueError: abort("Could not parse ohai's output" ":\n {0}".format(output)) node = {"run_list": []} for attribute in ["ipaddress", "platform", "platform_family", "platform_version"]: if ohai.get(attribute): node[attribute] = ohai[attribute] chef.save_config(node)
python
def deploy_chef(ask="yes", version="11"): """Install chef-solo on a node""" env.host_string = lib.get_env_host_string() if ask == "no" or littlechef.noninteractive: print("Deploying Chef using omnibus installer version: ...".format(version)) else: message = ('\nAre you sure you want to install Chef version:' '{0} on node {1}?'.format(version, env.host_string)) if not confirm(message): abort('Aborted by user') lib.print_header("Configuring Chef Solo on {0}".format(env.host_string)) if not __testing__: solo.install(version) solo.configure() # Build a basic node file if there isn't one already # with some properties from ohai with settings(hide('stdout'), warn_only=True): output = sudo('ohai -l warn') if output.succeeded: try: ohai = json.loads(output) except ValueError: abort("Could not parse ohai's output" ":\n {0}".format(output)) node = {"run_list": []} for attribute in ["ipaddress", "platform", "platform_family", "platform_version"]: if ohai.get(attribute): node[attribute] = ohai[attribute] chef.save_config(node)
[ "def", "deploy_chef", "(", "ask", "=", "\"yes\"", ",", "version", "=", "\"11\"", ")", ":", "env", ".", "host_string", "=", "lib", ".", "get_env_host_string", "(", ")", "if", "ask", "==", "\"no\"", "or", "littlechef", ".", "noninteractive", ":", "print", "(", "\"Deploying Chef using omnibus installer version: ...\"", ".", "format", "(", "version", ")", ")", "else", ":", "message", "=", "(", "'\\nAre you sure you want to install Chef version:'", "'{0} on node {1}?'", ".", "format", "(", "version", ",", "env", ".", "host_string", ")", ")", "if", "not", "confirm", "(", "message", ")", ":", "abort", "(", "'Aborted by user'", ")", "lib", ".", "print_header", "(", "\"Configuring Chef Solo on {0}\"", ".", "format", "(", "env", ".", "host_string", ")", ")", "if", "not", "__testing__", ":", "solo", ".", "install", "(", "version", ")", "solo", ".", "configure", "(", ")", "# Build a basic node file if there isn't one already", "# with some properties from ohai", "with", "settings", "(", "hide", "(", "'stdout'", ")", ",", "warn_only", "=", "True", ")", ":", "output", "=", "sudo", "(", "'ohai -l warn'", ")", "if", "output", ".", "succeeded", ":", "try", ":", "ohai", "=", "json", ".", "loads", "(", "output", ")", "except", "ValueError", ":", "abort", "(", "\"Could not parse ohai's output\"", "\":\\n {0}\"", ".", "format", "(", "output", ")", ")", "node", "=", "{", "\"run_list\"", ":", "[", "]", "}", "for", "attribute", "in", "[", "\"ipaddress\"", ",", "\"platform\"", ",", "\"platform_family\"", ",", "\"platform_version\"", "]", ":", "if", "ohai", ".", "get", "(", "attribute", ")", ":", "node", "[", "attribute", "]", "=", "ohai", "[", "attribute", "]", "chef", ".", "save_config", "(", "node", ")" ]
Install chef-solo on a node
[ "Install", "chef", "-", "solo", "on", "a", "node" ]
aab8c94081b38100a69cc100bc4278ae7419c58e
https://github.com/tobami/littlechef/blob/aab8c94081b38100a69cc100bc4278ae7419c58e/littlechef/runner.py#L183-L215
train
238,030
tobami/littlechef
littlechef/runner.py
plugin
def plugin(name): """Executes the selected plugin Plugins are expected to be found in the kitchen's 'plugins' directory """ env.host_string = lib.get_env_host_string() plug = lib.import_plugin(name) lib.print_header("Executing plugin '{0}' on " "{1}".format(name, env.host_string)) node = lib.get_node(env.host_string) if node == {'run_list': []}: node['name'] = env.host_string plug.execute(node) print("Finished executing plugin")
python
def plugin(name): """Executes the selected plugin Plugins are expected to be found in the kitchen's 'plugins' directory """ env.host_string = lib.get_env_host_string() plug = lib.import_plugin(name) lib.print_header("Executing plugin '{0}' on " "{1}".format(name, env.host_string)) node = lib.get_node(env.host_string) if node == {'run_list': []}: node['name'] = env.host_string plug.execute(node) print("Finished executing plugin")
[ "def", "plugin", "(", "name", ")", ":", "env", ".", "host_string", "=", "lib", ".", "get_env_host_string", "(", ")", "plug", "=", "lib", ".", "import_plugin", "(", "name", ")", "lib", ".", "print_header", "(", "\"Executing plugin '{0}' on \"", "\"{1}\"", ".", "format", "(", "name", ",", "env", ".", "host_string", ")", ")", "node", "=", "lib", ".", "get_node", "(", "env", ".", "host_string", ")", "if", "node", "==", "{", "'run_list'", ":", "[", "]", "}", ":", "node", "[", "'name'", "]", "=", "env", ".", "host_string", "plug", ".", "execute", "(", "node", ")", "print", "(", "\"Finished executing plugin\"", ")" ]
Executes the selected plugin Plugins are expected to be found in the kitchen's 'plugins' directory
[ "Executes", "the", "selected", "plugin", "Plugins", "are", "expected", "to", "be", "found", "in", "the", "kitchen", "s", "plugins", "directory" ]
aab8c94081b38100a69cc100bc4278ae7419c58e
https://github.com/tobami/littlechef/blob/aab8c94081b38100a69cc100bc4278ae7419c58e/littlechef/runner.py#L269-L282
train
238,031
tobami/littlechef
littlechef/runner.py
list_envs
def list_envs(): """List all environments""" for env in lib.get_environments(): margin_left = lib.get_margin(len(env['name'])) print("{0}{1}{2}".format( env['name'], margin_left, env.get('description', '(no description)')))
python
def list_envs(): """List all environments""" for env in lib.get_environments(): margin_left = lib.get_margin(len(env['name'])) print("{0}{1}{2}".format( env['name'], margin_left, env.get('description', '(no description)')))
[ "def", "list_envs", "(", ")", ":", "for", "env", "in", "lib", ".", "get_environments", "(", ")", ":", "margin_left", "=", "lib", ".", "get_margin", "(", "len", "(", "env", "[", "'name'", "]", ")", ")", "print", "(", "\"{0}{1}{2}\"", ".", "format", "(", "env", "[", "'name'", "]", ",", "margin_left", ",", "env", ".", "get", "(", "'description'", ",", "'(no description)'", ")", ")", ")" ]
List all environments
[ "List", "all", "environments" ]
aab8c94081b38100a69cc100bc4278ae7419c58e
https://github.com/tobami/littlechef/blob/aab8c94081b38100a69cc100bc4278ae7419c58e/littlechef/runner.py#L310-L316
train
238,032
tobami/littlechef
littlechef/runner.py
list_nodes_with_tag
def list_nodes_with_tag(tag): """Show all nodes which have assigned a given tag""" lib.print_nodes(lib.get_nodes_with_tag(tag, env.chef_environment, littlechef.include_guests))
python
def list_nodes_with_tag(tag): """Show all nodes which have assigned a given tag""" lib.print_nodes(lib.get_nodes_with_tag(tag, env.chef_environment, littlechef.include_guests))
[ "def", "list_nodes_with_tag", "(", "tag", ")", ":", "lib", ".", "print_nodes", "(", "lib", ".", "get_nodes_with_tag", "(", "tag", ",", "env", ".", "chef_environment", ",", "littlechef", ".", "include_guests", ")", ")" ]
Show all nodes which have assigned a given tag
[ "Show", "all", "nodes", "which", "have", "assigned", "a", "given", "tag" ]
aab8c94081b38100a69cc100bc4278ae7419c58e
https://github.com/tobami/littlechef/blob/aab8c94081b38100a69cc100bc4278ae7419c58e/littlechef/runner.py#L320-L323
train
238,033
tobami/littlechef
littlechef/runner.py
list_recipes
def list_recipes(): """Show a list of all available recipes""" for recipe in lib.get_recipes(): margin_left = lib.get_margin(len(recipe['name'])) print("{0}{1}{2}".format( recipe['name'], margin_left, recipe['description']))
python
def list_recipes(): """Show a list of all available recipes""" for recipe in lib.get_recipes(): margin_left = lib.get_margin(len(recipe['name'])) print("{0}{1}{2}".format( recipe['name'], margin_left, recipe['description']))
[ "def", "list_recipes", "(", ")", ":", "for", "recipe", "in", "lib", ".", "get_recipes", "(", ")", ":", "margin_left", "=", "lib", ".", "get_margin", "(", "len", "(", "recipe", "[", "'name'", "]", ")", ")", "print", "(", "\"{0}{1}{2}\"", ".", "format", "(", "recipe", "[", "'name'", "]", ",", "margin_left", ",", "recipe", "[", "'description'", "]", ")", ")" ]
Show a list of all available recipes
[ "Show", "a", "list", "of", "all", "available", "recipes" ]
aab8c94081b38100a69cc100bc4278ae7419c58e
https://github.com/tobami/littlechef/blob/aab8c94081b38100a69cc100bc4278ae7419c58e/littlechef/runner.py#L327-L332
train
238,034
tobami/littlechef
littlechef/runner.py
list_roles
def list_roles(): """Show a list of all available roles""" for role in lib.get_roles(): margin_left = lib.get_margin(len(role['fullname'])) print("{0}{1}{2}".format( role['fullname'], margin_left, role.get('description', '(no description)')))
python
def list_roles(): """Show a list of all available roles""" for role in lib.get_roles(): margin_left = lib.get_margin(len(role['fullname'])) print("{0}{1}{2}".format( role['fullname'], margin_left, role.get('description', '(no description)')))
[ "def", "list_roles", "(", ")", ":", "for", "role", "in", "lib", ".", "get_roles", "(", ")", ":", "margin_left", "=", "lib", ".", "get_margin", "(", "len", "(", "role", "[", "'fullname'", "]", ")", ")", "print", "(", "\"{0}{1}{2}\"", ".", "format", "(", "role", "[", "'fullname'", "]", ",", "margin_left", ",", "role", ".", "get", "(", "'description'", ",", "'(no description)'", ")", ")", ")" ]
Show a list of all available roles
[ "Show", "a", "list", "of", "all", "available", "roles" ]
aab8c94081b38100a69cc100bc4278ae7419c58e
https://github.com/tobami/littlechef/blob/aab8c94081b38100a69cc100bc4278ae7419c58e/littlechef/runner.py#L343-L349
train
238,035
tobami/littlechef
littlechef/runner.py
_check_appliances
def _check_appliances(): """Looks around and return True or False based on whether we are in a kitchen """ filenames = os.listdir(os.getcwd()) missing = [] for dirname in ['nodes', 'environments', 'roles', 'cookbooks', 'data_bags']: if (dirname not in filenames) or (not os.path.isdir(dirname)): missing.append(dirname) return (not bool(missing)), missing
python
def _check_appliances(): """Looks around and return True or False based on whether we are in a kitchen """ filenames = os.listdir(os.getcwd()) missing = [] for dirname in ['nodes', 'environments', 'roles', 'cookbooks', 'data_bags']: if (dirname not in filenames) or (not os.path.isdir(dirname)): missing.append(dirname) return (not bool(missing)), missing
[ "def", "_check_appliances", "(", ")", ":", "filenames", "=", "os", ".", "listdir", "(", "os", ".", "getcwd", "(", ")", ")", "missing", "=", "[", "]", "for", "dirname", "in", "[", "'nodes'", ",", "'environments'", ",", "'roles'", ",", "'cookbooks'", ",", "'data_bags'", "]", ":", "if", "(", "dirname", "not", "in", "filenames", ")", "or", "(", "not", "os", ".", "path", ".", "isdir", "(", "dirname", ")", ")", ":", "missing", ".", "append", "(", "dirname", ")", "return", "(", "not", "bool", "(", "missing", ")", ")", ",", "missing" ]
Looks around and return True or False based on whether we are in a kitchen
[ "Looks", "around", "and", "return", "True", "or", "False", "based", "on", "whether", "we", "are", "in", "a", "kitchen" ]
aab8c94081b38100a69cc100bc4278ae7419c58e
https://github.com/tobami/littlechef/blob/aab8c94081b38100a69cc100bc4278ae7419c58e/littlechef/runner.py#L365-L374
train
238,036
jbittel/django-mama-cas
mama_cas/models.py
TicketManager.create_ticket_str
def create_ticket_str(self, prefix=None): """ Generate a sufficiently opaque ticket string to ensure the ticket is not guessable. If a prefix is provided, prepend it to the string. """ if not prefix: prefix = self.model.TICKET_PREFIX return "%s-%d-%s" % (prefix, int(time.time()), get_random_string(length=self.model.TICKET_RAND_LEN))
python
def create_ticket_str(self, prefix=None): """ Generate a sufficiently opaque ticket string to ensure the ticket is not guessable. If a prefix is provided, prepend it to the string. """ if not prefix: prefix = self.model.TICKET_PREFIX return "%s-%d-%s" % (prefix, int(time.time()), get_random_string(length=self.model.TICKET_RAND_LEN))
[ "def", "create_ticket_str", "(", "self", ",", "prefix", "=", "None", ")", ":", "if", "not", "prefix", ":", "prefix", "=", "self", ".", "model", ".", "TICKET_PREFIX", "return", "\"%s-%d-%s\"", "%", "(", "prefix", ",", "int", "(", "time", ".", "time", "(", ")", ")", ",", "get_random_string", "(", "length", "=", "self", ".", "model", ".", "TICKET_RAND_LEN", ")", ")" ]
Generate a sufficiently opaque ticket string to ensure the ticket is not guessable. If a prefix is provided, prepend it to the string.
[ "Generate", "a", "sufficiently", "opaque", "ticket", "string", "to", "ensure", "the", "ticket", "is", "not", "guessable", ".", "If", "a", "prefix", "is", "provided", "prepend", "it", "to", "the", "string", "." ]
03935d97442b46d8127ab9e1cd8deb96953fe156
https://github.com/jbittel/django-mama-cas/blob/03935d97442b46d8127ab9e1cd8deb96953fe156/mama_cas/models.py#L58-L66
train
238,037
jbittel/django-mama-cas
mama_cas/models.py
TicketManager.validate_ticket
def validate_ticket(self, ticket, service, renew=False, require_https=False): """ Given a ticket string and service identifier, validate the corresponding ``Ticket``. If validation succeeds, return the ``Ticket``. If validation fails, raise an appropriate error. If ``renew`` is ``True``, ``ServiceTicket`` validation will only succeed if the ticket was issued from the presentation of the user's primary credentials. If ``require_https`` is ``True``, ``ServiceTicket`` validation will only succeed if the service URL scheme is HTTPS. """ if not ticket: raise InvalidRequest("No ticket string provided") if not self.model.TICKET_RE.match(ticket): raise InvalidTicket("Ticket string %s is invalid" % ticket) try: t = self.get(ticket=ticket) except self.model.DoesNotExist: raise InvalidTicket("Ticket %s does not exist" % ticket) if t.is_consumed(): raise InvalidTicket("%s %s has already been used" % (t.name, ticket)) if t.is_expired(): raise InvalidTicket("%s %s has expired" % (t.name, ticket)) if not service: raise InvalidRequest("No service identifier provided") if require_https and not is_scheme_https(service): raise InvalidService("Service %s is not HTTPS" % service) if not service_allowed(service): raise InvalidService("Service %s is not a valid %s URL" % (service, t.name)) try: if not match_service(t.service, service): raise InvalidService("%s %s for service %s is invalid for " "service %s" % (t.name, ticket, t.service, service)) except AttributeError: pass try: if renew and not t.is_primary(): raise InvalidTicket("%s %s was not issued via primary " "credentials" % (t.name, ticket)) except AttributeError: pass logger.debug("Validated %s %s" % (t.name, ticket)) return t
python
def validate_ticket(self, ticket, service, renew=False, require_https=False): """ Given a ticket string and service identifier, validate the corresponding ``Ticket``. If validation succeeds, return the ``Ticket``. If validation fails, raise an appropriate error. If ``renew`` is ``True``, ``ServiceTicket`` validation will only succeed if the ticket was issued from the presentation of the user's primary credentials. If ``require_https`` is ``True``, ``ServiceTicket`` validation will only succeed if the service URL scheme is HTTPS. """ if not ticket: raise InvalidRequest("No ticket string provided") if not self.model.TICKET_RE.match(ticket): raise InvalidTicket("Ticket string %s is invalid" % ticket) try: t = self.get(ticket=ticket) except self.model.DoesNotExist: raise InvalidTicket("Ticket %s does not exist" % ticket) if t.is_consumed(): raise InvalidTicket("%s %s has already been used" % (t.name, ticket)) if t.is_expired(): raise InvalidTicket("%s %s has expired" % (t.name, ticket)) if not service: raise InvalidRequest("No service identifier provided") if require_https and not is_scheme_https(service): raise InvalidService("Service %s is not HTTPS" % service) if not service_allowed(service): raise InvalidService("Service %s is not a valid %s URL" % (service, t.name)) try: if not match_service(t.service, service): raise InvalidService("%s %s for service %s is invalid for " "service %s" % (t.name, ticket, t.service, service)) except AttributeError: pass try: if renew and not t.is_primary(): raise InvalidTicket("%s %s was not issued via primary " "credentials" % (t.name, ticket)) except AttributeError: pass logger.debug("Validated %s %s" % (t.name, ticket)) return t
[ "def", "validate_ticket", "(", "self", ",", "ticket", ",", "service", ",", "renew", "=", "False", ",", "require_https", "=", "False", ")", ":", "if", "not", "ticket", ":", "raise", "InvalidRequest", "(", "\"No ticket string provided\"", ")", "if", "not", "self", ".", "model", ".", "TICKET_RE", ".", "match", "(", "ticket", ")", ":", "raise", "InvalidTicket", "(", "\"Ticket string %s is invalid\"", "%", "ticket", ")", "try", ":", "t", "=", "self", ".", "get", "(", "ticket", "=", "ticket", ")", "except", "self", ".", "model", ".", "DoesNotExist", ":", "raise", "InvalidTicket", "(", "\"Ticket %s does not exist\"", "%", "ticket", ")", "if", "t", ".", "is_consumed", "(", ")", ":", "raise", "InvalidTicket", "(", "\"%s %s has already been used\"", "%", "(", "t", ".", "name", ",", "ticket", ")", ")", "if", "t", ".", "is_expired", "(", ")", ":", "raise", "InvalidTicket", "(", "\"%s %s has expired\"", "%", "(", "t", ".", "name", ",", "ticket", ")", ")", "if", "not", "service", ":", "raise", "InvalidRequest", "(", "\"No service identifier provided\"", ")", "if", "require_https", "and", "not", "is_scheme_https", "(", "service", ")", ":", "raise", "InvalidService", "(", "\"Service %s is not HTTPS\"", "%", "service", ")", "if", "not", "service_allowed", "(", "service", ")", ":", "raise", "InvalidService", "(", "\"Service %s is not a valid %s URL\"", "%", "(", "service", ",", "t", ".", "name", ")", ")", "try", ":", "if", "not", "match_service", "(", "t", ".", "service", ",", "service", ")", ":", "raise", "InvalidService", "(", "\"%s %s for service %s is invalid for \"", "\"service %s\"", "%", "(", "t", ".", "name", ",", "ticket", ",", "t", ".", "service", ",", "service", ")", ")", "except", "AttributeError", ":", "pass", "try", ":", "if", "renew", "and", "not", "t", ".", "is_primary", "(", ")", ":", "raise", "InvalidTicket", "(", "\"%s %s was not issued via primary \"", "\"credentials\"", "%", "(", "t", ".", "name", ",", "ticket", ")", ")", "except", "AttributeError", ":", "pass", "logger", ".", "debug", "(", "\"Validated %s %s\"", "%", "(", "t", ".", "name", ",", "ticket", ")", ")", "return", "t" ]
Given a ticket string and service identifier, validate the corresponding ``Ticket``. If validation succeeds, return the ``Ticket``. If validation fails, raise an appropriate error. If ``renew`` is ``True``, ``ServiceTicket`` validation will only succeed if the ticket was issued from the presentation of the user's primary credentials. If ``require_https`` is ``True``, ``ServiceTicket`` validation will only succeed if the service URL scheme is HTTPS.
[ "Given", "a", "ticket", "string", "and", "service", "identifier", "validate", "the", "corresponding", "Ticket", ".", "If", "validation", "succeeds", "return", "the", "Ticket", ".", "If", "validation", "fails", "raise", "an", "appropriate", "error", "." ]
03935d97442b46d8127ab9e1cd8deb96953fe156
https://github.com/jbittel/django-mama-cas/blob/03935d97442b46d8127ab9e1cd8deb96953fe156/mama_cas/models.py#L68-L123
train
238,038
jbittel/django-mama-cas
mama_cas/models.py
TicketManager.delete_invalid_tickets
def delete_invalid_tickets(self): """ Delete consumed or expired ``Ticket``s that are not referenced by other ``Ticket``s. Invalid tickets are no longer valid for authentication and can be safely deleted. A custom management command is provided that executes this method on all applicable models by running ``manage.py cleanupcas``. """ for ticket in self.filter(Q(consumed__isnull=False) | Q(expires__lte=now())).order_by('-expires'): try: ticket.delete() except models.ProtectedError: pass
python
def delete_invalid_tickets(self): """ Delete consumed or expired ``Ticket``s that are not referenced by other ``Ticket``s. Invalid tickets are no longer valid for authentication and can be safely deleted. A custom management command is provided that executes this method on all applicable models by running ``manage.py cleanupcas``. """ for ticket in self.filter(Q(consumed__isnull=False) | Q(expires__lte=now())).order_by('-expires'): try: ticket.delete() except models.ProtectedError: pass
[ "def", "delete_invalid_tickets", "(", "self", ")", ":", "for", "ticket", "in", "self", ".", "filter", "(", "Q", "(", "consumed__isnull", "=", "False", ")", "|", "Q", "(", "expires__lte", "=", "now", "(", ")", ")", ")", ".", "order_by", "(", "'-expires'", ")", ":", "try", ":", "ticket", ".", "delete", "(", ")", "except", "models", ".", "ProtectedError", ":", "pass" ]
Delete consumed or expired ``Ticket``s that are not referenced by other ``Ticket``s. Invalid tickets are no longer valid for authentication and can be safely deleted. A custom management command is provided that executes this method on all applicable models by running ``manage.py cleanupcas``.
[ "Delete", "consumed", "or", "expired", "Ticket", "s", "that", "are", "not", "referenced", "by", "other", "Ticket", "s", ".", "Invalid", "tickets", "are", "no", "longer", "valid", "for", "authentication", "and", "can", "be", "safely", "deleted", "." ]
03935d97442b46d8127ab9e1cd8deb96953fe156
https://github.com/jbittel/django-mama-cas/blob/03935d97442b46d8127ab9e1cd8deb96953fe156/mama_cas/models.py#L125-L139
train
238,039
jbittel/django-mama-cas
mama_cas/models.py
TicketManager.consume_tickets
def consume_tickets(self, user): """ Consume all valid ``Ticket``s for a specified user. This is run when the user logs out to ensure all issued tickets are no longer valid for future authentication attempts. """ for ticket in self.filter(user=user, consumed__isnull=True, expires__gt=now()): ticket.consume()
python
def consume_tickets(self, user): """ Consume all valid ``Ticket``s for a specified user. This is run when the user logs out to ensure all issued tickets are no longer valid for future authentication attempts. """ for ticket in self.filter(user=user, consumed__isnull=True, expires__gt=now()): ticket.consume()
[ "def", "consume_tickets", "(", "self", ",", "user", ")", ":", "for", "ticket", "in", "self", ".", "filter", "(", "user", "=", "user", ",", "consumed__isnull", "=", "True", ",", "expires__gt", "=", "now", "(", ")", ")", ":", "ticket", ".", "consume", "(", ")" ]
Consume all valid ``Ticket``s for a specified user. This is run when the user logs out to ensure all issued tickets are no longer valid for future authentication attempts.
[ "Consume", "all", "valid", "Ticket", "s", "for", "a", "specified", "user", ".", "This", "is", "run", "when", "the", "user", "logs", "out", "to", "ensure", "all", "issued", "tickets", "are", "no", "longer", "valid", "for", "future", "authentication", "attempts", "." ]
03935d97442b46d8127ab9e1cd8deb96953fe156
https://github.com/jbittel/django-mama-cas/blob/03935d97442b46d8127ab9e1cd8deb96953fe156/mama_cas/models.py#L141-L149
train
238,040
jbittel/django-mama-cas
mama_cas/models.py
ServiceTicketManager.request_sign_out
def request_sign_out(self, user): """ Send a single logout request to each service accessed by a specified user. This is called at logout when single logout is enabled. If requests-futures is installed, asynchronous requests will be sent. Otherwise, synchronous requests will be sent. """ session = Session() for ticket in self.filter(user=user, consumed__gte=user.last_login): ticket.request_sign_out(session=session)
python
def request_sign_out(self, user): """ Send a single logout request to each service accessed by a specified user. This is called at logout when single logout is enabled. If requests-futures is installed, asynchronous requests will be sent. Otherwise, synchronous requests will be sent. """ session = Session() for ticket in self.filter(user=user, consumed__gte=user.last_login): ticket.request_sign_out(session=session)
[ "def", "request_sign_out", "(", "self", ",", "user", ")", ":", "session", "=", "Session", "(", ")", "for", "ticket", "in", "self", ".", "filter", "(", "user", "=", "user", ",", "consumed__gte", "=", "user", ".", "last_login", ")", ":", "ticket", ".", "request_sign_out", "(", "session", "=", "session", ")" ]
Send a single logout request to each service accessed by a specified user. This is called at logout when single logout is enabled. If requests-futures is installed, asynchronous requests will be sent. Otherwise, synchronous requests will be sent.
[ "Send", "a", "single", "logout", "request", "to", "each", "service", "accessed", "by", "a", "specified", "user", ".", "This", "is", "called", "at", "logout", "when", "single", "logout", "is", "enabled", "." ]
03935d97442b46d8127ab9e1cd8deb96953fe156
https://github.com/jbittel/django-mama-cas/blob/03935d97442b46d8127ab9e1cd8deb96953fe156/mama_cas/models.py#L207-L218
train
238,041
jbittel/django-mama-cas
mama_cas/models.py
ServiceTicket.request_sign_out
def request_sign_out(self, session=requests): """ Send a POST request to the ``ServiceTicket``s logout URL to request sign-out. """ if logout_allowed(self.service): request = SingleSignOutRequest(context={'ticket': self}) url = get_logout_url(self.service) or self.service session.post(url, data={'logoutRequest': request.render_content()}) logger.info("Single sign-out request sent to %s" % url)
python
def request_sign_out(self, session=requests): """ Send a POST request to the ``ServiceTicket``s logout URL to request sign-out. """ if logout_allowed(self.service): request = SingleSignOutRequest(context={'ticket': self}) url = get_logout_url(self.service) or self.service session.post(url, data={'logoutRequest': request.render_content()}) logger.info("Single sign-out request sent to %s" % url)
[ "def", "request_sign_out", "(", "self", ",", "session", "=", "requests", ")", ":", "if", "logout_allowed", "(", "self", ".", "service", ")", ":", "request", "=", "SingleSignOutRequest", "(", "context", "=", "{", "'ticket'", ":", "self", "}", ")", "url", "=", "get_logout_url", "(", "self", ".", "service", ")", "or", "self", ".", "service", "session", ".", "post", "(", "url", ",", "data", "=", "{", "'logoutRequest'", ":", "request", ".", "render_content", "(", ")", "}", ")", "logger", ".", "info", "(", "\"Single sign-out request sent to %s\"", "%", "url", ")" ]
Send a POST request to the ``ServiceTicket``s logout URL to request sign-out.
[ "Send", "a", "POST", "request", "to", "the", "ServiceTicket", "s", "logout", "URL", "to", "request", "sign", "-", "out", "." ]
03935d97442b46d8127ab9e1cd8deb96953fe156
https://github.com/jbittel/django-mama-cas/blob/03935d97442b46d8127ab9e1cd8deb96953fe156/mama_cas/models.py#L248-L257
train
238,042
jbittel/django-mama-cas
mama_cas/models.py
ProxyGrantingTicketManager.validate_callback
def validate_callback(self, service, pgturl, pgtid, pgtiou): """Verify the provided proxy callback URL.""" if not proxy_allowed(service): raise UnauthorizedServiceProxy("%s is not authorized to use proxy authentication" % service) if not is_scheme_https(pgturl): raise InvalidProxyCallback("Proxy callback %s is not HTTPS" % pgturl) if not proxy_callback_allowed(service, pgturl): raise InvalidProxyCallback("%s is not an authorized proxy callback URL" % pgturl) # Verify that the SSL certificate is valid verify = os.environ.get('REQUESTS_CA_BUNDLE', True) try: requests.get(pgturl, verify=verify, timeout=5) except requests.exceptions.SSLError: raise InvalidProxyCallback("SSL certificate validation failed for proxy callback %s" % pgturl) except requests.exceptions.RequestException as e: raise InvalidProxyCallback(e) # Callback certificate appears valid, so send the ticket strings pgturl = add_query_params(pgturl, {'pgtId': pgtid, 'pgtIou': pgtiou}) try: response = requests.get(pgturl, verify=verify, timeout=5) except requests.exceptions.RequestException as e: raise InvalidProxyCallback(e) try: response.raise_for_status() except requests.exceptions.HTTPError as e: raise InvalidProxyCallback("Proxy callback %s returned %s" % (pgturl, e))
python
def validate_callback(self, service, pgturl, pgtid, pgtiou): """Verify the provided proxy callback URL.""" if not proxy_allowed(service): raise UnauthorizedServiceProxy("%s is not authorized to use proxy authentication" % service) if not is_scheme_https(pgturl): raise InvalidProxyCallback("Proxy callback %s is not HTTPS" % pgturl) if not proxy_callback_allowed(service, pgturl): raise InvalidProxyCallback("%s is not an authorized proxy callback URL" % pgturl) # Verify that the SSL certificate is valid verify = os.environ.get('REQUESTS_CA_BUNDLE', True) try: requests.get(pgturl, verify=verify, timeout=5) except requests.exceptions.SSLError: raise InvalidProxyCallback("SSL certificate validation failed for proxy callback %s" % pgturl) except requests.exceptions.RequestException as e: raise InvalidProxyCallback(e) # Callback certificate appears valid, so send the ticket strings pgturl = add_query_params(pgturl, {'pgtId': pgtid, 'pgtIou': pgtiou}) try: response = requests.get(pgturl, verify=verify, timeout=5) except requests.exceptions.RequestException as e: raise InvalidProxyCallback(e) try: response.raise_for_status() except requests.exceptions.HTTPError as e: raise InvalidProxyCallback("Proxy callback %s returned %s" % (pgturl, e))
[ "def", "validate_callback", "(", "self", ",", "service", ",", "pgturl", ",", "pgtid", ",", "pgtiou", ")", ":", "if", "not", "proxy_allowed", "(", "service", ")", ":", "raise", "UnauthorizedServiceProxy", "(", "\"%s is not authorized to use proxy authentication\"", "%", "service", ")", "if", "not", "is_scheme_https", "(", "pgturl", ")", ":", "raise", "InvalidProxyCallback", "(", "\"Proxy callback %s is not HTTPS\"", "%", "pgturl", ")", "if", "not", "proxy_callback_allowed", "(", "service", ",", "pgturl", ")", ":", "raise", "InvalidProxyCallback", "(", "\"%s is not an authorized proxy callback URL\"", "%", "pgturl", ")", "# Verify that the SSL certificate is valid", "verify", "=", "os", ".", "environ", ".", "get", "(", "'REQUESTS_CA_BUNDLE'", ",", "True", ")", "try", ":", "requests", ".", "get", "(", "pgturl", ",", "verify", "=", "verify", ",", "timeout", "=", "5", ")", "except", "requests", ".", "exceptions", ".", "SSLError", ":", "raise", "InvalidProxyCallback", "(", "\"SSL certificate validation failed for proxy callback %s\"", "%", "pgturl", ")", "except", "requests", ".", "exceptions", ".", "RequestException", "as", "e", ":", "raise", "InvalidProxyCallback", "(", "e", ")", "# Callback certificate appears valid, so send the ticket strings", "pgturl", "=", "add_query_params", "(", "pgturl", ",", "{", "'pgtId'", ":", "pgtid", ",", "'pgtIou'", ":", "pgtiou", "}", ")", "try", ":", "response", "=", "requests", ".", "get", "(", "pgturl", ",", "verify", "=", "verify", ",", "timeout", "=", "5", ")", "except", "requests", ".", "exceptions", ".", "RequestException", "as", "e", ":", "raise", "InvalidProxyCallback", "(", "e", ")", "try", ":", "response", ".", "raise_for_status", "(", ")", "except", "requests", ".", "exceptions", ".", "HTTPError", "as", "e", ":", "raise", "InvalidProxyCallback", "(", "\"Proxy callback %s returned %s\"", "%", "(", "pgturl", ",", "e", ")", ")" ]
Verify the provided proxy callback URL.
[ "Verify", "the", "provided", "proxy", "callback", "URL", "." ]
03935d97442b46d8127ab9e1cd8deb96953fe156
https://github.com/jbittel/django-mama-cas/blob/03935d97442b46d8127ab9e1cd8deb96953fe156/mama_cas/models.py#L299-L329
train
238,043
jbittel/django-mama-cas
mama_cas/services/__init__.py
_get_backends
def _get_backends(): """Retrieve the list of configured service backends.""" backends = [] backend_paths = getattr( settings, 'MAMA_CAS_SERVICE_BACKENDS', ['mama_cas.services.backends.SettingsBackend'] ) for backend_path in backend_paths: backend = import_string(backend_path)() backends.append(backend) return backends
python
def _get_backends(): """Retrieve the list of configured service backends.""" backends = [] backend_paths = getattr( settings, 'MAMA_CAS_SERVICE_BACKENDS', ['mama_cas.services.backends.SettingsBackend'] ) for backend_path in backend_paths: backend = import_string(backend_path)() backends.append(backend) return backends
[ "def", "_get_backends", "(", ")", ":", "backends", "=", "[", "]", "backend_paths", "=", "getattr", "(", "settings", ",", "'MAMA_CAS_SERVICE_BACKENDS'", ",", "[", "'mama_cas.services.backends.SettingsBackend'", "]", ")", "for", "backend_path", "in", "backend_paths", ":", "backend", "=", "import_string", "(", "backend_path", ")", "(", ")", "backends", ".", "append", "(", "backend", ")", "return", "backends" ]
Retrieve the list of configured service backends.
[ "Retrieve", "the", "list", "of", "configured", "service", "backends", "." ]
03935d97442b46d8127ab9e1cd8deb96953fe156
https://github.com/jbittel/django-mama-cas/blob/03935d97442b46d8127ab9e1cd8deb96953fe156/mama_cas/services/__init__.py#L8-L18
train
238,044
jbittel/django-mama-cas
mama_cas/services/__init__.py
_is_allowed
def _is_allowed(attr, *args): """ Test if a given attribute is allowed according to the current set of configured service backends. """ for backend in _get_backends(): try: if getattr(backend, attr)(*args): return True except AttributeError: raise NotImplementedError("%s.%s.%s() not implemented" % ( backend.__class__.__module__, backend.__class__.__name__, attr) ) return False
python
def _is_allowed(attr, *args): """ Test if a given attribute is allowed according to the current set of configured service backends. """ for backend in _get_backends(): try: if getattr(backend, attr)(*args): return True except AttributeError: raise NotImplementedError("%s.%s.%s() not implemented" % ( backend.__class__.__module__, backend.__class__.__name__, attr) ) return False
[ "def", "_is_allowed", "(", "attr", ",", "*", "args", ")", ":", "for", "backend", "in", "_get_backends", "(", ")", ":", "try", ":", "if", "getattr", "(", "backend", ",", "attr", ")", "(", "*", "args", ")", ":", "return", "True", "except", "AttributeError", ":", "raise", "NotImplementedError", "(", "\"%s.%s.%s() not implemented\"", "%", "(", "backend", ".", "__class__", ".", "__module__", ",", "backend", ".", "__class__", ".", "__name__", ",", "attr", ")", ")", "return", "False" ]
Test if a given attribute is allowed according to the current set of configured service backends.
[ "Test", "if", "a", "given", "attribute", "is", "allowed", "according", "to", "the", "current", "set", "of", "configured", "service", "backends", "." ]
03935d97442b46d8127ab9e1cd8deb96953fe156
https://github.com/jbittel/django-mama-cas/blob/03935d97442b46d8127ab9e1cd8deb96953fe156/mama_cas/services/__init__.py#L21-L34
train
238,045
jbittel/django-mama-cas
mama_cas/services/__init__.py
_is_valid_service_url
def _is_valid_service_url(url): """Access services list from ``MAMA_CAS_VALID_SERVICES``.""" valid_services = getattr(settings, 'MAMA_CAS_VALID_SERVICES', ()) if not valid_services: return True warnings.warn( 'The MAMA_CAS_VALID_SERVICES setting is deprecated. Services ' 'should be configured using MAMA_CAS_SERVICES.', DeprecationWarning) for service in [re.compile(s) for s in valid_services]: if service.match(url): return True return False
python
def _is_valid_service_url(url): """Access services list from ``MAMA_CAS_VALID_SERVICES``.""" valid_services = getattr(settings, 'MAMA_CAS_VALID_SERVICES', ()) if not valid_services: return True warnings.warn( 'The MAMA_CAS_VALID_SERVICES setting is deprecated. Services ' 'should be configured using MAMA_CAS_SERVICES.', DeprecationWarning) for service in [re.compile(s) for s in valid_services]: if service.match(url): return True return False
[ "def", "_is_valid_service_url", "(", "url", ")", ":", "valid_services", "=", "getattr", "(", "settings", ",", "'MAMA_CAS_VALID_SERVICES'", ",", "(", ")", ")", "if", "not", "valid_services", ":", "return", "True", "warnings", ".", "warn", "(", "'The MAMA_CAS_VALID_SERVICES setting is deprecated. Services '", "'should be configured using MAMA_CAS_SERVICES.'", ",", "DeprecationWarning", ")", "for", "service", "in", "[", "re", ".", "compile", "(", "s", ")", "for", "s", "in", "valid_services", "]", ":", "if", "service", ".", "match", "(", "url", ")", ":", "return", "True", "return", "False" ]
Access services list from ``MAMA_CAS_VALID_SERVICES``.
[ "Access", "services", "list", "from", "MAMA_CAS_VALID_SERVICES", "." ]
03935d97442b46d8127ab9e1cd8deb96953fe156
https://github.com/jbittel/django-mama-cas/blob/03935d97442b46d8127ab9e1cd8deb96953fe156/mama_cas/services/__init__.py#L37-L48
train
238,046
jbittel/django-mama-cas
mama_cas/services/__init__.py
get_backend_path
def get_backend_path(service): """Return the dotted path of the matching backend.""" for backend in _get_backends(): try: if backend.service_allowed(service): return "%s.%s" % (backend.__class__.__module__, backend.__class__.__name__) except AttributeError: raise NotImplementedError("%s.%s.service_allowed() not implemented" % ( backend.__class__.__module__, backend.__class__.__name__) ) return None
python
def get_backend_path(service): """Return the dotted path of the matching backend.""" for backend in _get_backends(): try: if backend.service_allowed(service): return "%s.%s" % (backend.__class__.__module__, backend.__class__.__name__) except AttributeError: raise NotImplementedError("%s.%s.service_allowed() not implemented" % ( backend.__class__.__module__, backend.__class__.__name__) ) return None
[ "def", "get_backend_path", "(", "service", ")", ":", "for", "backend", "in", "_get_backends", "(", ")", ":", "try", ":", "if", "backend", ".", "service_allowed", "(", "service", ")", ":", "return", "\"%s.%s\"", "%", "(", "backend", ".", "__class__", ".", "__module__", ",", "backend", ".", "__class__", ".", "__name__", ")", "except", "AttributeError", ":", "raise", "NotImplementedError", "(", "\"%s.%s.service_allowed() not implemented\"", "%", "(", "backend", ".", "__class__", ".", "__module__", ",", "backend", ".", "__class__", ".", "__name__", ")", ")", "return", "None" ]
Return the dotted path of the matching backend.
[ "Return", "the", "dotted", "path", "of", "the", "matching", "backend", "." ]
03935d97442b46d8127ab9e1cd8deb96953fe156
https://github.com/jbittel/django-mama-cas/blob/03935d97442b46d8127ab9e1cd8deb96953fe156/mama_cas/services/__init__.py#L51-L61
train
238,047
jbittel/django-mama-cas
mama_cas/services/__init__.py
get_callbacks
def get_callbacks(service): """Get configured callbacks list for a given service identifier.""" callbacks = list(getattr(settings, 'MAMA_CAS_ATTRIBUTE_CALLBACKS', [])) if callbacks: warnings.warn( 'The MAMA_CAS_ATTRIBUTE_CALLBACKS setting is deprecated. Service callbacks ' 'should be configured using MAMA_CAS_SERVICES.', DeprecationWarning) for backend in _get_backends(): try: callbacks.extend(backend.get_callbacks(service)) except AttributeError: raise NotImplementedError("%s.%s.get_callbacks() not implemented" % ( backend.__class__.__module__, backend.__class__.__name__) ) return callbacks
python
def get_callbacks(service): """Get configured callbacks list for a given service identifier.""" callbacks = list(getattr(settings, 'MAMA_CAS_ATTRIBUTE_CALLBACKS', [])) if callbacks: warnings.warn( 'The MAMA_CAS_ATTRIBUTE_CALLBACKS setting is deprecated. Service callbacks ' 'should be configured using MAMA_CAS_SERVICES.', DeprecationWarning) for backend in _get_backends(): try: callbacks.extend(backend.get_callbacks(service)) except AttributeError: raise NotImplementedError("%s.%s.get_callbacks() not implemented" % ( backend.__class__.__module__, backend.__class__.__name__) ) return callbacks
[ "def", "get_callbacks", "(", "service", ")", ":", "callbacks", "=", "list", "(", "getattr", "(", "settings", ",", "'MAMA_CAS_ATTRIBUTE_CALLBACKS'", ",", "[", "]", ")", ")", "if", "callbacks", ":", "warnings", ".", "warn", "(", "'The MAMA_CAS_ATTRIBUTE_CALLBACKS setting is deprecated. Service callbacks '", "'should be configured using MAMA_CAS_SERVICES.'", ",", "DeprecationWarning", ")", "for", "backend", "in", "_get_backends", "(", ")", ":", "try", ":", "callbacks", ".", "extend", "(", "backend", ".", "get_callbacks", "(", "service", ")", ")", "except", "AttributeError", ":", "raise", "NotImplementedError", "(", "\"%s.%s.get_callbacks() not implemented\"", "%", "(", "backend", ".", "__class__", ".", "__module__", ",", "backend", ".", "__class__", ".", "__name__", ")", ")", "return", "callbacks" ]
Get configured callbacks list for a given service identifier.
[ "Get", "configured", "callbacks", "list", "for", "a", "given", "service", "identifier", "." ]
03935d97442b46d8127ab9e1cd8deb96953fe156
https://github.com/jbittel/django-mama-cas/blob/03935d97442b46d8127ab9e1cd8deb96953fe156/mama_cas/services/__init__.py#L64-L79
train
238,048
jbittel/django-mama-cas
mama_cas/services/__init__.py
get_logout_url
def get_logout_url(service): """Get the configured logout URL for a given service identifier, if any.""" for backend in _get_backends(): try: return backend.get_logout_url(service) except AttributeError: raise NotImplementedError("%s.%s.get_logout_url() not implemented" % ( backend.__class__.__module__, backend.__class__.__name__) ) return None
python
def get_logout_url(service): """Get the configured logout URL for a given service identifier, if any.""" for backend in _get_backends(): try: return backend.get_logout_url(service) except AttributeError: raise NotImplementedError("%s.%s.get_logout_url() not implemented" % ( backend.__class__.__module__, backend.__class__.__name__) ) return None
[ "def", "get_logout_url", "(", "service", ")", ":", "for", "backend", "in", "_get_backends", "(", ")", ":", "try", ":", "return", "backend", ".", "get_logout_url", "(", "service", ")", "except", "AttributeError", ":", "raise", "NotImplementedError", "(", "\"%s.%s.get_logout_url() not implemented\"", "%", "(", "backend", ".", "__class__", ".", "__module__", ",", "backend", ".", "__class__", ".", "__name__", ")", ")", "return", "None" ]
Get the configured logout URL for a given service identifier, if any.
[ "Get", "the", "configured", "logout", "URL", "for", "a", "given", "service", "identifier", "if", "any", "." ]
03935d97442b46d8127ab9e1cd8deb96953fe156
https://github.com/jbittel/django-mama-cas/blob/03935d97442b46d8127ab9e1cd8deb96953fe156/mama_cas/services/__init__.py#L82-L91
train
238,049
jbittel/django-mama-cas
mama_cas/services/__init__.py
logout_allowed
def logout_allowed(service): """Check if a given service identifier should be sent a logout request.""" if hasattr(settings, 'MAMA_CAS_SERVICES'): return _is_allowed('logout_allowed', service) if hasattr(settings, 'MAMA_CAS_ENABLE_SINGLE_SIGN_OUT'): warnings.warn( 'The MAMA_CAS_ENABLE_SINGLE_SIGN_OUT setting is deprecated. SLO ' 'should be configured using MAMA_CAS_SERVICES.', DeprecationWarning) return getattr(settings, 'MAMA_CAS_ENABLE_SINGLE_SIGN_OUT', False)
python
def logout_allowed(service): """Check if a given service identifier should be sent a logout request.""" if hasattr(settings, 'MAMA_CAS_SERVICES'): return _is_allowed('logout_allowed', service) if hasattr(settings, 'MAMA_CAS_ENABLE_SINGLE_SIGN_OUT'): warnings.warn( 'The MAMA_CAS_ENABLE_SINGLE_SIGN_OUT setting is deprecated. SLO ' 'should be configured using MAMA_CAS_SERVICES.', DeprecationWarning) return getattr(settings, 'MAMA_CAS_ENABLE_SINGLE_SIGN_OUT', False)
[ "def", "logout_allowed", "(", "service", ")", ":", "if", "hasattr", "(", "settings", ",", "'MAMA_CAS_SERVICES'", ")", ":", "return", "_is_allowed", "(", "'logout_allowed'", ",", "service", ")", "if", "hasattr", "(", "settings", ",", "'MAMA_CAS_ENABLE_SINGLE_SIGN_OUT'", ")", ":", "warnings", ".", "warn", "(", "'The MAMA_CAS_ENABLE_SINGLE_SIGN_OUT setting is deprecated. SLO '", "'should be configured using MAMA_CAS_SERVICES.'", ",", "DeprecationWarning", ")", "return", "getattr", "(", "settings", ",", "'MAMA_CAS_ENABLE_SINGLE_SIGN_OUT'", ",", "False", ")" ]
Check if a given service identifier should be sent a logout request.
[ "Check", "if", "a", "given", "service", "identifier", "should", "be", "sent", "a", "logout", "request", "." ]
03935d97442b46d8127ab9e1cd8deb96953fe156
https://github.com/jbittel/django-mama-cas/blob/03935d97442b46d8127ab9e1cd8deb96953fe156/mama_cas/services/__init__.py#L94-L103
train
238,050
jbittel/django-mama-cas
mama_cas/services/__init__.py
proxy_callback_allowed
def proxy_callback_allowed(service, pgturl): """Check if a given proxy callback is allowed for the given service identifier.""" if hasattr(settings, 'MAMA_CAS_SERVICES'): return _is_allowed('proxy_callback_allowed', service, pgturl) return _is_valid_service_url(service)
python
def proxy_callback_allowed(service, pgturl): """Check if a given proxy callback is allowed for the given service identifier.""" if hasattr(settings, 'MAMA_CAS_SERVICES'): return _is_allowed('proxy_callback_allowed', service, pgturl) return _is_valid_service_url(service)
[ "def", "proxy_callback_allowed", "(", "service", ",", "pgturl", ")", ":", "if", "hasattr", "(", "settings", ",", "'MAMA_CAS_SERVICES'", ")", ":", "return", "_is_allowed", "(", "'proxy_callback_allowed'", ",", "service", ",", "pgturl", ")", "return", "_is_valid_service_url", "(", "service", ")" ]
Check if a given proxy callback is allowed for the given service identifier.
[ "Check", "if", "a", "given", "proxy", "callback", "is", "allowed", "for", "the", "given", "service", "identifier", "." ]
03935d97442b46d8127ab9e1cd8deb96953fe156
https://github.com/jbittel/django-mama-cas/blob/03935d97442b46d8127ab9e1cd8deb96953fe156/mama_cas/services/__init__.py#L111-L115
train
238,051
jbittel/django-mama-cas
mama_cas/forms.py
LoginForm.clean
def clean(self): """ Pass the provided username and password to the active authentication backends and verify the user account is not disabled. If authentication succeeds, the ``User`` object is assigned to the form so it can be accessed in the view. """ username = self.cleaned_data.get('username') password = self.cleaned_data.get('password') if username and password: try: self.user = authenticate(request=self.request, username=username, password=password) except Exception: logger.exception("Error authenticating %s" % username) error_msg = _('Internal error while authenticating user') raise forms.ValidationError(error_msg) if self.user is None: logger.warning("Failed authentication for %s" % username) error_msg = _('The username or password is not correct') raise forms.ValidationError(error_msg) else: if not self.user.is_active: logger.warning("User account %s is disabled" % username) error_msg = _('This user account is disabled') raise forms.ValidationError(error_msg) return self.cleaned_data
python
def clean(self): """ Pass the provided username and password to the active authentication backends and verify the user account is not disabled. If authentication succeeds, the ``User`` object is assigned to the form so it can be accessed in the view. """ username = self.cleaned_data.get('username') password = self.cleaned_data.get('password') if username and password: try: self.user = authenticate(request=self.request, username=username, password=password) except Exception: logger.exception("Error authenticating %s" % username) error_msg = _('Internal error while authenticating user') raise forms.ValidationError(error_msg) if self.user is None: logger.warning("Failed authentication for %s" % username) error_msg = _('The username or password is not correct') raise forms.ValidationError(error_msg) else: if not self.user.is_active: logger.warning("User account %s is disabled" % username) error_msg = _('This user account is disabled') raise forms.ValidationError(error_msg) return self.cleaned_data
[ "def", "clean", "(", "self", ")", ":", "username", "=", "self", ".", "cleaned_data", ".", "get", "(", "'username'", ")", "password", "=", "self", ".", "cleaned_data", ".", "get", "(", "'password'", ")", "if", "username", "and", "password", ":", "try", ":", "self", ".", "user", "=", "authenticate", "(", "request", "=", "self", ".", "request", ",", "username", "=", "username", ",", "password", "=", "password", ")", "except", "Exception", ":", "logger", ".", "exception", "(", "\"Error authenticating %s\"", "%", "username", ")", "error_msg", "=", "_", "(", "'Internal error while authenticating user'", ")", "raise", "forms", ".", "ValidationError", "(", "error_msg", ")", "if", "self", ".", "user", "is", "None", ":", "logger", ".", "warning", "(", "\"Failed authentication for %s\"", "%", "username", ")", "error_msg", "=", "_", "(", "'The username or password is not correct'", ")", "raise", "forms", ".", "ValidationError", "(", "error_msg", ")", "else", ":", "if", "not", "self", ".", "user", ".", "is_active", ":", "logger", ".", "warning", "(", "\"User account %s is disabled\"", "%", "username", ")", "error_msg", "=", "_", "(", "'This user account is disabled'", ")", "raise", "forms", ".", "ValidationError", "(", "error_msg", ")", "return", "self", ".", "cleaned_data" ]
Pass the provided username and password to the active authentication backends and verify the user account is not disabled. If authentication succeeds, the ``User`` object is assigned to the form so it can be accessed in the view.
[ "Pass", "the", "provided", "username", "and", "password", "to", "the", "active", "authentication", "backends", "and", "verify", "the", "user", "account", "is", "not", "disabled", ".", "If", "authentication", "succeeds", "the", "User", "object", "is", "assigned", "to", "the", "form", "so", "it", "can", "be", "accessed", "in", "the", "view", "." ]
03935d97442b46d8127ab9e1cd8deb96953fe156
https://github.com/jbittel/django-mama-cas/blob/03935d97442b46d8127ab9e1cd8deb96953fe156/mama_cas/forms.py#L34-L62
train
238,052
jbittel/django-mama-cas
mama_cas/request.py
CasRequestBase.ns
def ns(self, prefix, tag): """ Given a prefix and an XML tag, output the qualified name for proper namespace handling on output. """ return etree.QName(self.prefixes[prefix], tag)
python
def ns(self, prefix, tag): """ Given a prefix and an XML tag, output the qualified name for proper namespace handling on output. """ return etree.QName(self.prefixes[prefix], tag)
[ "def", "ns", "(", "self", ",", "prefix", ",", "tag", ")", ":", "return", "etree", ".", "QName", "(", "self", ".", "prefixes", "[", "prefix", "]", ",", "tag", ")" ]
Given a prefix and an XML tag, output the qualified name for proper namespace handling on output.
[ "Given", "a", "prefix", "and", "an", "XML", "tag", "output", "the", "qualified", "name", "for", "proper", "namespace", "handling", "on", "output", "." ]
03935d97442b46d8127ab9e1cd8deb96953fe156
https://github.com/jbittel/django-mama-cas/blob/03935d97442b46d8127ab9e1cd8deb96953fe156/mama_cas/request.py#L19-L24
train
238,053
jbittel/django-mama-cas
mama_cas/cas.py
validate_service_ticket
def validate_service_ticket(service, ticket, pgturl=None, renew=False, require_https=False): """ Validate a service ticket string. Return a triplet containing a ``ServiceTicket`` and an optional ``ProxyGrantingTicket``, or a ``ValidationError`` if ticket validation failed. """ logger.debug("Service validation request received for %s" % ticket) # Check for proxy tickets passed to /serviceValidate if ticket and ticket.startswith(ProxyTicket.TICKET_PREFIX): raise InvalidTicketSpec('Proxy tickets cannot be validated with /serviceValidate') st = ServiceTicket.objects.validate_ticket(ticket, service, renew=renew, require_https=require_https) attributes = get_attributes(st.user, st.service) if pgturl is not None: logger.debug("Proxy-granting ticket request received for %s" % pgturl) pgt = ProxyGrantingTicket.objects.create_ticket(service, pgturl, user=st.user, granted_by_st=st) else: pgt = None return st, attributes, pgt
python
def validate_service_ticket(service, ticket, pgturl=None, renew=False, require_https=False): """ Validate a service ticket string. Return a triplet containing a ``ServiceTicket`` and an optional ``ProxyGrantingTicket``, or a ``ValidationError`` if ticket validation failed. """ logger.debug("Service validation request received for %s" % ticket) # Check for proxy tickets passed to /serviceValidate if ticket and ticket.startswith(ProxyTicket.TICKET_PREFIX): raise InvalidTicketSpec('Proxy tickets cannot be validated with /serviceValidate') st = ServiceTicket.objects.validate_ticket(ticket, service, renew=renew, require_https=require_https) attributes = get_attributes(st.user, st.service) if pgturl is not None: logger.debug("Proxy-granting ticket request received for %s" % pgturl) pgt = ProxyGrantingTicket.objects.create_ticket(service, pgturl, user=st.user, granted_by_st=st) else: pgt = None return st, attributes, pgt
[ "def", "validate_service_ticket", "(", "service", ",", "ticket", ",", "pgturl", "=", "None", ",", "renew", "=", "False", ",", "require_https", "=", "False", ")", ":", "logger", ".", "debug", "(", "\"Service validation request received for %s\"", "%", "ticket", ")", "# Check for proxy tickets passed to /serviceValidate", "if", "ticket", "and", "ticket", ".", "startswith", "(", "ProxyTicket", ".", "TICKET_PREFIX", ")", ":", "raise", "InvalidTicketSpec", "(", "'Proxy tickets cannot be validated with /serviceValidate'", ")", "st", "=", "ServiceTicket", ".", "objects", ".", "validate_ticket", "(", "ticket", ",", "service", ",", "renew", "=", "renew", ",", "require_https", "=", "require_https", ")", "attributes", "=", "get_attributes", "(", "st", ".", "user", ",", "st", ".", "service", ")", "if", "pgturl", "is", "not", "None", ":", "logger", ".", "debug", "(", "\"Proxy-granting ticket request received for %s\"", "%", "pgturl", ")", "pgt", "=", "ProxyGrantingTicket", ".", "objects", ".", "create_ticket", "(", "service", ",", "pgturl", ",", "user", "=", "st", ".", "user", ",", "granted_by_st", "=", "st", ")", "else", ":", "pgt", "=", "None", "return", "st", ",", "attributes", ",", "pgt" ]
Validate a service ticket string. Return a triplet containing a ``ServiceTicket`` and an optional ``ProxyGrantingTicket``, or a ``ValidationError`` if ticket validation failed.
[ "Validate", "a", "service", "ticket", "string", ".", "Return", "a", "triplet", "containing", "a", "ServiceTicket", "and", "an", "optional", "ProxyGrantingTicket", "or", "a", "ValidationError", "if", "ticket", "validation", "failed", "." ]
03935d97442b46d8127ab9e1cd8deb96953fe156
https://github.com/jbittel/django-mama-cas/blob/03935d97442b46d8127ab9e1cd8deb96953fe156/mama_cas/cas.py#L18-L38
train
238,054
jbittel/django-mama-cas
mama_cas/cas.py
validate_proxy_ticket
def validate_proxy_ticket(service, ticket, pgturl=None): """ Validate a proxy ticket string. Return a 4-tuple containing a ``ProxyTicket``, an optional ``ProxyGrantingTicket`` and a list of proxies through which authentication proceeded, or a ``ValidationError`` if ticket validation failed. """ logger.debug("Proxy validation request received for %s" % ticket) pt = ProxyTicket.objects.validate_ticket(ticket, service) attributes = get_attributes(pt.user, pt.service) # Build a list of all services that proxied authentication, # in reverse order of which they were traversed proxies = [pt.service] prior_pt = pt.granted_by_pgt.granted_by_pt while prior_pt: proxies.append(prior_pt.service) prior_pt = prior_pt.granted_by_pgt.granted_by_pt if pgturl is not None: logger.debug("Proxy-granting ticket request received for %s" % pgturl) pgt = ProxyGrantingTicket.objects.create_ticket(service, pgturl, user=pt.user, granted_by_pt=pt) else: pgt = None return pt, attributes, pgt, proxies
python
def validate_proxy_ticket(service, ticket, pgturl=None): """ Validate a proxy ticket string. Return a 4-tuple containing a ``ProxyTicket``, an optional ``ProxyGrantingTicket`` and a list of proxies through which authentication proceeded, or a ``ValidationError`` if ticket validation failed. """ logger.debug("Proxy validation request received for %s" % ticket) pt = ProxyTicket.objects.validate_ticket(ticket, service) attributes = get_attributes(pt.user, pt.service) # Build a list of all services that proxied authentication, # in reverse order of which they were traversed proxies = [pt.service] prior_pt = pt.granted_by_pgt.granted_by_pt while prior_pt: proxies.append(prior_pt.service) prior_pt = prior_pt.granted_by_pgt.granted_by_pt if pgturl is not None: logger.debug("Proxy-granting ticket request received for %s" % pgturl) pgt = ProxyGrantingTicket.objects.create_ticket(service, pgturl, user=pt.user, granted_by_pt=pt) else: pgt = None return pt, attributes, pgt, proxies
[ "def", "validate_proxy_ticket", "(", "service", ",", "ticket", ",", "pgturl", "=", "None", ")", ":", "logger", ".", "debug", "(", "\"Proxy validation request received for %s\"", "%", "ticket", ")", "pt", "=", "ProxyTicket", ".", "objects", ".", "validate_ticket", "(", "ticket", ",", "service", ")", "attributes", "=", "get_attributes", "(", "pt", ".", "user", ",", "pt", ".", "service", ")", "# Build a list of all services that proxied authentication,", "# in reverse order of which they were traversed", "proxies", "=", "[", "pt", ".", "service", "]", "prior_pt", "=", "pt", ".", "granted_by_pgt", ".", "granted_by_pt", "while", "prior_pt", ":", "proxies", ".", "append", "(", "prior_pt", ".", "service", ")", "prior_pt", "=", "prior_pt", ".", "granted_by_pgt", ".", "granted_by_pt", "if", "pgturl", "is", "not", "None", ":", "logger", ".", "debug", "(", "\"Proxy-granting ticket request received for %s\"", "%", "pgturl", ")", "pgt", "=", "ProxyGrantingTicket", ".", "objects", ".", "create_ticket", "(", "service", ",", "pgturl", ",", "user", "=", "pt", ".", "user", ",", "granted_by_pt", "=", "pt", ")", "else", ":", "pgt", "=", "None", "return", "pt", ",", "attributes", ",", "pgt", ",", "proxies" ]
Validate a proxy ticket string. Return a 4-tuple containing a ``ProxyTicket``, an optional ``ProxyGrantingTicket`` and a list of proxies through which authentication proceeded, or a ``ValidationError`` if ticket validation failed.
[ "Validate", "a", "proxy", "ticket", "string", ".", "Return", "a", "4", "-", "tuple", "containing", "a", "ProxyTicket", "an", "optional", "ProxyGrantingTicket", "and", "a", "list", "of", "proxies", "through", "which", "authentication", "proceeded", "or", "a", "ValidationError", "if", "ticket", "validation", "failed", "." ]
03935d97442b46d8127ab9e1cd8deb96953fe156
https://github.com/jbittel/django-mama-cas/blob/03935d97442b46d8127ab9e1cd8deb96953fe156/mama_cas/cas.py#L41-L66
train
238,055
jbittel/django-mama-cas
mama_cas/cas.py
validate_proxy_granting_ticket
def validate_proxy_granting_ticket(pgt, target_service): """ Validate a proxy granting ticket string. Return an ordered pair containing a ``ProxyTicket``, or a ``ValidationError`` if ticket validation failed. """ logger.debug("Proxy ticket request received for %s using %s" % (target_service, pgt)) pgt = ProxyGrantingTicket.objects.validate_ticket(pgt, target_service) pt = ProxyTicket.objects.create_ticket(service=target_service, user=pgt.user, granted_by_pgt=pgt) return pt
python
def validate_proxy_granting_ticket(pgt, target_service): """ Validate a proxy granting ticket string. Return an ordered pair containing a ``ProxyTicket``, or a ``ValidationError`` if ticket validation failed. """ logger.debug("Proxy ticket request received for %s using %s" % (target_service, pgt)) pgt = ProxyGrantingTicket.objects.validate_ticket(pgt, target_service) pt = ProxyTicket.objects.create_ticket(service=target_service, user=pgt.user, granted_by_pgt=pgt) return pt
[ "def", "validate_proxy_granting_ticket", "(", "pgt", ",", "target_service", ")", ":", "logger", ".", "debug", "(", "\"Proxy ticket request received for %s using %s\"", "%", "(", "target_service", ",", "pgt", ")", ")", "pgt", "=", "ProxyGrantingTicket", ".", "objects", ".", "validate_ticket", "(", "pgt", ",", "target_service", ")", "pt", "=", "ProxyTicket", ".", "objects", ".", "create_ticket", "(", "service", "=", "target_service", ",", "user", "=", "pgt", ".", "user", ",", "granted_by_pgt", "=", "pgt", ")", "return", "pt" ]
Validate a proxy granting ticket string. Return an ordered pair containing a ``ProxyTicket``, or a ``ValidationError`` if ticket validation failed.
[ "Validate", "a", "proxy", "granting", "ticket", "string", ".", "Return", "an", "ordered", "pair", "containing", "a", "ProxyTicket", "or", "a", "ValidationError", "if", "ticket", "validation", "failed", "." ]
03935d97442b46d8127ab9e1cd8deb96953fe156
https://github.com/jbittel/django-mama-cas/blob/03935d97442b46d8127ab9e1cd8deb96953fe156/mama_cas/cas.py#L69-L79
train
238,056
jbittel/django-mama-cas
mama_cas/cas.py
get_attributes
def get_attributes(user, service): """ Return a dictionary of user attributes from the set of configured callback functions. """ attributes = {} for path in get_callbacks(service): callback = import_string(path) attributes.update(callback(user, service)) return attributes
python
def get_attributes(user, service): """ Return a dictionary of user attributes from the set of configured callback functions. """ attributes = {} for path in get_callbacks(service): callback = import_string(path) attributes.update(callback(user, service)) return attributes
[ "def", "get_attributes", "(", "user", ",", "service", ")", ":", "attributes", "=", "{", "}", "for", "path", "in", "get_callbacks", "(", "service", ")", ":", "callback", "=", "import_string", "(", "path", ")", "attributes", ".", "update", "(", "callback", "(", "user", ",", "service", ")", ")", "return", "attributes" ]
Return a dictionary of user attributes from the set of configured callback functions.
[ "Return", "a", "dictionary", "of", "user", "attributes", "from", "the", "set", "of", "configured", "callback", "functions", "." ]
03935d97442b46d8127ab9e1cd8deb96953fe156
https://github.com/jbittel/django-mama-cas/blob/03935d97442b46d8127ab9e1cd8deb96953fe156/mama_cas/cas.py#L82-L91
train
238,057
jbittel/django-mama-cas
mama_cas/cas.py
logout_user
def logout_user(request): """End a single sign-on session for the current user.""" logger.debug("Logout request received for %s" % request.user) if is_authenticated(request.user): ServiceTicket.objects.consume_tickets(request.user) ProxyTicket.objects.consume_tickets(request.user) ProxyGrantingTicket.objects.consume_tickets(request.user) ServiceTicket.objects.request_sign_out(request.user) logger.info("Single sign-on session ended for %s" % request.user) logout(request) messages.success(request, _('You have been successfully logged out'))
python
def logout_user(request): """End a single sign-on session for the current user.""" logger.debug("Logout request received for %s" % request.user) if is_authenticated(request.user): ServiceTicket.objects.consume_tickets(request.user) ProxyTicket.objects.consume_tickets(request.user) ProxyGrantingTicket.objects.consume_tickets(request.user) ServiceTicket.objects.request_sign_out(request.user) logger.info("Single sign-on session ended for %s" % request.user) logout(request) messages.success(request, _('You have been successfully logged out'))
[ "def", "logout_user", "(", "request", ")", ":", "logger", ".", "debug", "(", "\"Logout request received for %s\"", "%", "request", ".", "user", ")", "if", "is_authenticated", "(", "request", ".", "user", ")", ":", "ServiceTicket", ".", "objects", ".", "consume_tickets", "(", "request", ".", "user", ")", "ProxyTicket", ".", "objects", ".", "consume_tickets", "(", "request", ".", "user", ")", "ProxyGrantingTicket", ".", "objects", ".", "consume_tickets", "(", "request", ".", "user", ")", "ServiceTicket", ".", "objects", ".", "request_sign_out", "(", "request", ".", "user", ")", "logger", ".", "info", "(", "\"Single sign-on session ended for %s\"", "%", "request", ".", "user", ")", "logout", "(", "request", ")", "messages", ".", "success", "(", "request", ",", "_", "(", "'You have been successfully logged out'", ")", ")" ]
End a single sign-on session for the current user.
[ "End", "a", "single", "sign", "-", "on", "session", "for", "the", "current", "user", "." ]
03935d97442b46d8127ab9e1cd8deb96953fe156
https://github.com/jbittel/django-mama-cas/blob/03935d97442b46d8127ab9e1cd8deb96953fe156/mama_cas/cas.py#L94-L106
train
238,058
jbittel/django-mama-cas
mama_cas/callbacks.py
user_name_attributes
def user_name_attributes(user, service): """Return all available user name related fields and methods.""" attributes = {} attributes['username'] = user.get_username() attributes['full_name'] = user.get_full_name() attributes['short_name'] = user.get_short_name() return attributes
python
def user_name_attributes(user, service): """Return all available user name related fields and methods.""" attributes = {} attributes['username'] = user.get_username() attributes['full_name'] = user.get_full_name() attributes['short_name'] = user.get_short_name() return attributes
[ "def", "user_name_attributes", "(", "user", ",", "service", ")", ":", "attributes", "=", "{", "}", "attributes", "[", "'username'", "]", "=", "user", ".", "get_username", "(", ")", "attributes", "[", "'full_name'", "]", "=", "user", ".", "get_full_name", "(", ")", "attributes", "[", "'short_name'", "]", "=", "user", ".", "get_short_name", "(", ")", "return", "attributes" ]
Return all available user name related fields and methods.
[ "Return", "all", "available", "user", "name", "related", "fields", "and", "methods", "." ]
03935d97442b46d8127ab9e1cd8deb96953fe156
https://github.com/jbittel/django-mama-cas/blob/03935d97442b46d8127ab9e1cd8deb96953fe156/mama_cas/callbacks.py#L1-L7
train
238,059
jbittel/django-mama-cas
mama_cas/callbacks.py
user_model_attributes
def user_model_attributes(user, service): """ Return all fields on the user object that are not in the list of fields to ignore. """ ignore_fields = ['id', 'password'] attributes = {} for field in user._meta.fields: if field.name not in ignore_fields: attributes[field.name] = getattr(user, field.name) return attributes
python
def user_model_attributes(user, service): """ Return all fields on the user object that are not in the list of fields to ignore. """ ignore_fields = ['id', 'password'] attributes = {} for field in user._meta.fields: if field.name not in ignore_fields: attributes[field.name] = getattr(user, field.name) return attributes
[ "def", "user_model_attributes", "(", "user", ",", "service", ")", ":", "ignore_fields", "=", "[", "'id'", ",", "'password'", "]", "attributes", "=", "{", "}", "for", "field", "in", "user", ".", "_meta", ".", "fields", ":", "if", "field", ".", "name", "not", "in", "ignore_fields", ":", "attributes", "[", "field", ".", "name", "]", "=", "getattr", "(", "user", ",", "field", ".", "name", ")", "return", "attributes" ]
Return all fields on the user object that are not in the list of fields to ignore.
[ "Return", "all", "fields", "on", "the", "user", "object", "that", "are", "not", "in", "the", "list", "of", "fields", "to", "ignore", "." ]
03935d97442b46d8127ab9e1cd8deb96953fe156
https://github.com/jbittel/django-mama-cas/blob/03935d97442b46d8127ab9e1cd8deb96953fe156/mama_cas/callbacks.py#L10-L20
train
238,060
jbittel/django-mama-cas
mama_cas/utils.py
add_query_params
def add_query_params(url, params): """ Inject additional query parameters into an existing URL. If parameters already exist with the same name, they will be overwritten. Parameters with empty values are ignored. Return the modified URL as a string. """ def encode(s): return force_bytes(s, settings.DEFAULT_CHARSET) params = dict([(encode(k), encode(v)) for k, v in params.items() if v]) parts = list(urlparse(url)) query = dict(parse_qsl(parts[4])) query.update(params) parts[4] = urlencode(query) return urlunparse(parts)
python
def add_query_params(url, params): """ Inject additional query parameters into an existing URL. If parameters already exist with the same name, they will be overwritten. Parameters with empty values are ignored. Return the modified URL as a string. """ def encode(s): return force_bytes(s, settings.DEFAULT_CHARSET) params = dict([(encode(k), encode(v)) for k, v in params.items() if v]) parts = list(urlparse(url)) query = dict(parse_qsl(parts[4])) query.update(params) parts[4] = urlencode(query) return urlunparse(parts)
[ "def", "add_query_params", "(", "url", ",", "params", ")", ":", "def", "encode", "(", "s", ")", ":", "return", "force_bytes", "(", "s", ",", "settings", ".", "DEFAULT_CHARSET", ")", "params", "=", "dict", "(", "[", "(", "encode", "(", "k", ")", ",", "encode", "(", "v", ")", ")", "for", "k", ",", "v", "in", "params", ".", "items", "(", ")", "if", "v", "]", ")", "parts", "=", "list", "(", "urlparse", "(", "url", ")", ")", "query", "=", "dict", "(", "parse_qsl", "(", "parts", "[", "4", "]", ")", ")", "query", ".", "update", "(", "params", ")", "parts", "[", "4", "]", "=", "urlencode", "(", "query", ")", "return", "urlunparse", "(", "parts", ")" ]
Inject additional query parameters into an existing URL. If parameters already exist with the same name, they will be overwritten. Parameters with empty values are ignored. Return the modified URL as a string.
[ "Inject", "additional", "query", "parameters", "into", "an", "existing", "URL", ".", "If", "parameters", "already", "exist", "with", "the", "same", "name", "they", "will", "be", "overwritten", ".", "Parameters", "with", "empty", "values", "are", "ignored", ".", "Return", "the", "modified", "URL", "as", "a", "string", "." ]
03935d97442b46d8127ab9e1cd8deb96953fe156
https://github.com/jbittel/django-mama-cas/blob/03935d97442b46d8127ab9e1cd8deb96953fe156/mama_cas/utils.py#L23-L38
train
238,061
jbittel/django-mama-cas
mama_cas/utils.py
match_service
def match_service(service1, service2): """ Compare two service URLs. Return ``True`` if the scheme, hostname, optional port and path match. """ s1, s2 = urlparse(service1), urlparse(service2) try: return (s1.scheme, s1.netloc, s1.path) == (s2.scheme, s2.netloc, s2.path) except ValueError: return False
python
def match_service(service1, service2): """ Compare two service URLs. Return ``True`` if the scheme, hostname, optional port and path match. """ s1, s2 = urlparse(service1), urlparse(service2) try: return (s1.scheme, s1.netloc, s1.path) == (s2.scheme, s2.netloc, s2.path) except ValueError: return False
[ "def", "match_service", "(", "service1", ",", "service2", ")", ":", "s1", ",", "s2", "=", "urlparse", "(", "service1", ")", ",", "urlparse", "(", "service2", ")", "try", ":", "return", "(", "s1", ".", "scheme", ",", "s1", ".", "netloc", ",", "s1", ".", "path", ")", "==", "(", "s2", ".", "scheme", ",", "s2", ".", "netloc", ",", "s2", ".", "path", ")", "except", "ValueError", ":", "return", "False" ]
Compare two service URLs. Return ``True`` if the scheme, hostname, optional port and path match.
[ "Compare", "two", "service", "URLs", ".", "Return", "True", "if", "the", "scheme", "hostname", "optional", "port", "and", "path", "match", "." ]
03935d97442b46d8127ab9e1cd8deb96953fe156
https://github.com/jbittel/django-mama-cas/blob/03935d97442b46d8127ab9e1cd8deb96953fe156/mama_cas/utils.py#L58-L67
train
238,062
jbittel/django-mama-cas
mama_cas/utils.py
redirect
def redirect(to, *args, **kwargs): """ Similar to the Django ``redirect`` shortcut but with altered functionality. If an optional ``params`` argument is provided, the dictionary items will be injected as query parameters on the redirection URL. """ params = kwargs.pop('params', {}) try: to = reverse(to, args=args, kwargs=kwargs) except NoReverseMatch: if '/' not in to and '.' not in to: to = reverse('cas_login') elif not service_allowed(to): raise PermissionDenied() if params: to = add_query_params(to, params) logger.debug("Redirecting to %s" % to) return HttpResponseRedirect(to)
python
def redirect(to, *args, **kwargs): """ Similar to the Django ``redirect`` shortcut but with altered functionality. If an optional ``params`` argument is provided, the dictionary items will be injected as query parameters on the redirection URL. """ params = kwargs.pop('params', {}) try: to = reverse(to, args=args, kwargs=kwargs) except NoReverseMatch: if '/' not in to and '.' not in to: to = reverse('cas_login') elif not service_allowed(to): raise PermissionDenied() if params: to = add_query_params(to, params) logger.debug("Redirecting to %s" % to) return HttpResponseRedirect(to)
[ "def", "redirect", "(", "to", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "params", "=", "kwargs", ".", "pop", "(", "'params'", ",", "{", "}", ")", "try", ":", "to", "=", "reverse", "(", "to", ",", "args", "=", "args", ",", "kwargs", "=", "kwargs", ")", "except", "NoReverseMatch", ":", "if", "'/'", "not", "in", "to", "and", "'.'", "not", "in", "to", ":", "to", "=", "reverse", "(", "'cas_login'", ")", "elif", "not", "service_allowed", "(", "to", ")", ":", "raise", "PermissionDenied", "(", ")", "if", "params", ":", "to", "=", "add_query_params", "(", "to", ",", "params", ")", "logger", ".", "debug", "(", "\"Redirecting to %s\"", "%", "to", ")", "return", "HttpResponseRedirect", "(", "to", ")" ]
Similar to the Django ``redirect`` shortcut but with altered functionality. If an optional ``params`` argument is provided, the dictionary items will be injected as query parameters on the redirection URL.
[ "Similar", "to", "the", "Django", "redirect", "shortcut", "but", "with", "altered", "functionality", ".", "If", "an", "optional", "params", "argument", "is", "provided", "the", "dictionary", "items", "will", "be", "injected", "as", "query", "parameters", "on", "the", "redirection", "URL", "." ]
03935d97442b46d8127ab9e1cd8deb96953fe156
https://github.com/jbittel/django-mama-cas/blob/03935d97442b46d8127ab9e1cd8deb96953fe156/mama_cas/utils.py#L70-L91
train
238,063
jbittel/django-mama-cas
mama_cas/services/backends.py
ServiceConfig.get_config
def get_config(self, service, setting): """ Access the configuration for a given service and setting. If the service is not found, return a default value. """ try: return self.get_service(service)[setting] except KeyError: return getattr(self, setting + '_DEFAULT')
python
def get_config(self, service, setting): """ Access the configuration for a given service and setting. If the service is not found, return a default value. """ try: return self.get_service(service)[setting] except KeyError: return getattr(self, setting + '_DEFAULT')
[ "def", "get_config", "(", "self", ",", "service", ",", "setting", ")", ":", "try", ":", "return", "self", ".", "get_service", "(", "service", ")", "[", "setting", "]", "except", "KeyError", ":", "return", "getattr", "(", "self", ",", "setting", "+", "'_DEFAULT'", ")" ]
Access the configuration for a given service and setting. If the service is not found, return a default value.
[ "Access", "the", "configuration", "for", "a", "given", "service", "and", "setting", ".", "If", "the", "service", "is", "not", "found", "return", "a", "default", "value", "." ]
03935d97442b46d8127ab9e1cd8deb96953fe156
https://github.com/jbittel/django-mama-cas/blob/03935d97442b46d8127ab9e1cd8deb96953fe156/mama_cas/services/backends.py#L47-L55
train
238,064
jbittel/django-mama-cas
mama_cas/response.py
SamlValidationResponse.get_status
def get_status(self, status_value, message=None): """ Build a Status XML block for a SAML 1.1 Response. """ status = etree.Element('Status') status_code = etree.SubElement(status, 'StatusCode') status_code.set('Value', 'samlp:' + status_value) if message: status_message = etree.SubElement(status, 'StatusMessage') status_message.text = message return status
python
def get_status(self, status_value, message=None): """ Build a Status XML block for a SAML 1.1 Response. """ status = etree.Element('Status') status_code = etree.SubElement(status, 'StatusCode') status_code.set('Value', 'samlp:' + status_value) if message: status_message = etree.SubElement(status, 'StatusMessage') status_message.text = message return status
[ "def", "get_status", "(", "self", ",", "status_value", ",", "message", "=", "None", ")", ":", "status", "=", "etree", ".", "Element", "(", "'Status'", ")", "status_code", "=", "etree", ".", "SubElement", "(", "status", ",", "'StatusCode'", ")", "status_code", ".", "set", "(", "'Value'", ",", "'samlp:'", "+", "status_value", ")", "if", "message", ":", "status_message", "=", "etree", ".", "SubElement", "(", "status", ",", "'StatusMessage'", ")", "status_message", ".", "text", "=", "message", "return", "status" ]
Build a Status XML block for a SAML 1.1 Response.
[ "Build", "a", "Status", "XML", "block", "for", "a", "SAML", "1", ".", "1", "Response", "." ]
03935d97442b46d8127ab9e1cd8deb96953fe156
https://github.com/jbittel/django-mama-cas/blob/03935d97442b46d8127ab9e1cd8deb96953fe156/mama_cas/response.py#L185-L195
train
238,065
jbittel/django-mama-cas
mama_cas/response.py
SamlValidationResponse.get_assertion
def get_assertion(self, ticket, attributes): """ Build a SAML 1.1 Assertion XML block. """ assertion = etree.Element('Assertion') assertion.set('xmlns', 'urn:oasis:names:tc:SAML:1.0:assertion') assertion.set('AssertionID', self.generate_id()) assertion.set('IssueInstant', self.instant()) assertion.set('Issuer', 'localhost') assertion.set('MajorVersion', '1') assertion.set('MinorVersion', '1') assertion.append(self.get_conditions(ticket.service)) subject = self.get_subject(ticket.user.get_username()) if attributes: assertion.append(self.get_attribute_statement(subject, attributes)) assertion.append(self.get_authentication_statement(subject, ticket)) return assertion
python
def get_assertion(self, ticket, attributes): """ Build a SAML 1.1 Assertion XML block. """ assertion = etree.Element('Assertion') assertion.set('xmlns', 'urn:oasis:names:tc:SAML:1.0:assertion') assertion.set('AssertionID', self.generate_id()) assertion.set('IssueInstant', self.instant()) assertion.set('Issuer', 'localhost') assertion.set('MajorVersion', '1') assertion.set('MinorVersion', '1') assertion.append(self.get_conditions(ticket.service)) subject = self.get_subject(ticket.user.get_username()) if attributes: assertion.append(self.get_attribute_statement(subject, attributes)) assertion.append(self.get_authentication_statement(subject, ticket)) return assertion
[ "def", "get_assertion", "(", "self", ",", "ticket", ",", "attributes", ")", ":", "assertion", "=", "etree", ".", "Element", "(", "'Assertion'", ")", "assertion", ".", "set", "(", "'xmlns'", ",", "'urn:oasis:names:tc:SAML:1.0:assertion'", ")", "assertion", ".", "set", "(", "'AssertionID'", ",", "self", ".", "generate_id", "(", ")", ")", "assertion", ".", "set", "(", "'IssueInstant'", ",", "self", ".", "instant", "(", ")", ")", "assertion", ".", "set", "(", "'Issuer'", ",", "'localhost'", ")", "assertion", ".", "set", "(", "'MajorVersion'", ",", "'1'", ")", "assertion", ".", "set", "(", "'MinorVersion'", ",", "'1'", ")", "assertion", ".", "append", "(", "self", ".", "get_conditions", "(", "ticket", ".", "service", ")", ")", "subject", "=", "self", ".", "get_subject", "(", "ticket", ".", "user", ".", "get_username", "(", ")", ")", "if", "attributes", ":", "assertion", ".", "append", "(", "self", ".", "get_attribute_statement", "(", "subject", ",", "attributes", ")", ")", "assertion", ".", "append", "(", "self", ".", "get_authentication_statement", "(", "subject", ",", "ticket", ")", ")", "return", "assertion" ]
Build a SAML 1.1 Assertion XML block.
[ "Build", "a", "SAML", "1", ".", "1", "Assertion", "XML", "block", "." ]
03935d97442b46d8127ab9e1cd8deb96953fe156
https://github.com/jbittel/django-mama-cas/blob/03935d97442b46d8127ab9e1cd8deb96953fe156/mama_cas/response.py#L197-L214
train
238,066
jbittel/django-mama-cas
mama_cas/response.py
SamlValidationResponse.get_conditions
def get_conditions(self, service_id): """ Build a Conditions XML block for a SAML 1.1 Assertion. """ conditions = etree.Element('Conditions') conditions.set('NotBefore', self.instant()) conditions.set('NotOnOrAfter', self.instant(offset=30)) restriction = etree.SubElement(conditions, 'AudienceRestrictionCondition') audience = etree.SubElement(restriction, 'Audience') audience.text = service_id return conditions
python
def get_conditions(self, service_id): """ Build a Conditions XML block for a SAML 1.1 Assertion. """ conditions = etree.Element('Conditions') conditions.set('NotBefore', self.instant()) conditions.set('NotOnOrAfter', self.instant(offset=30)) restriction = etree.SubElement(conditions, 'AudienceRestrictionCondition') audience = etree.SubElement(restriction, 'Audience') audience.text = service_id return conditions
[ "def", "get_conditions", "(", "self", ",", "service_id", ")", ":", "conditions", "=", "etree", ".", "Element", "(", "'Conditions'", ")", "conditions", ".", "set", "(", "'NotBefore'", ",", "self", ".", "instant", "(", ")", ")", "conditions", ".", "set", "(", "'NotOnOrAfter'", ",", "self", ".", "instant", "(", "offset", "=", "30", ")", ")", "restriction", "=", "etree", ".", "SubElement", "(", "conditions", ",", "'AudienceRestrictionCondition'", ")", "audience", "=", "etree", ".", "SubElement", "(", "restriction", ",", "'Audience'", ")", "audience", ".", "text", "=", "service_id", "return", "conditions" ]
Build a Conditions XML block for a SAML 1.1 Assertion.
[ "Build", "a", "Conditions", "XML", "block", "for", "a", "SAML", "1", ".", "1", "Assertion", "." ]
03935d97442b46d8127ab9e1cd8deb96953fe156
https://github.com/jbittel/django-mama-cas/blob/03935d97442b46d8127ab9e1cd8deb96953fe156/mama_cas/response.py#L216-L226
train
238,067
jbittel/django-mama-cas
mama_cas/response.py
SamlValidationResponse.get_attribute_statement
def get_attribute_statement(self, subject, attributes): """ Build an AttributeStatement XML block for a SAML 1.1 Assertion. """ attribute_statement = etree.Element('AttributeStatement') attribute_statement.append(subject) for name, value in attributes.items(): attribute = etree.SubElement(attribute_statement, 'Attribute') attribute.set('AttributeName', name) attribute.set('AttributeNamespace', self.namespace) if isinstance(value, list): for v in value: attribute_value = etree.SubElement(attribute, 'AttributeValue') attribute_value.text = force_text(v) else: attribute_value = etree.SubElement(attribute, 'AttributeValue') attribute_value.text = force_text(value) return attribute_statement
python
def get_attribute_statement(self, subject, attributes): """ Build an AttributeStatement XML block for a SAML 1.1 Assertion. """ attribute_statement = etree.Element('AttributeStatement') attribute_statement.append(subject) for name, value in attributes.items(): attribute = etree.SubElement(attribute_statement, 'Attribute') attribute.set('AttributeName', name) attribute.set('AttributeNamespace', self.namespace) if isinstance(value, list): for v in value: attribute_value = etree.SubElement(attribute, 'AttributeValue') attribute_value.text = force_text(v) else: attribute_value = etree.SubElement(attribute, 'AttributeValue') attribute_value.text = force_text(value) return attribute_statement
[ "def", "get_attribute_statement", "(", "self", ",", "subject", ",", "attributes", ")", ":", "attribute_statement", "=", "etree", ".", "Element", "(", "'AttributeStatement'", ")", "attribute_statement", ".", "append", "(", "subject", ")", "for", "name", ",", "value", "in", "attributes", ".", "items", "(", ")", ":", "attribute", "=", "etree", ".", "SubElement", "(", "attribute_statement", ",", "'Attribute'", ")", "attribute", ".", "set", "(", "'AttributeName'", ",", "name", ")", "attribute", ".", "set", "(", "'AttributeNamespace'", ",", "self", ".", "namespace", ")", "if", "isinstance", "(", "value", ",", "list", ")", ":", "for", "v", "in", "value", ":", "attribute_value", "=", "etree", ".", "SubElement", "(", "attribute", ",", "'AttributeValue'", ")", "attribute_value", ".", "text", "=", "force_text", "(", "v", ")", "else", ":", "attribute_value", "=", "etree", ".", "SubElement", "(", "attribute", ",", "'AttributeValue'", ")", "attribute_value", ".", "text", "=", "force_text", "(", "value", ")", "return", "attribute_statement" ]
Build an AttributeStatement XML block for a SAML 1.1 Assertion.
[ "Build", "an", "AttributeStatement", "XML", "block", "for", "a", "SAML", "1", ".", "1", "Assertion", "." ]
03935d97442b46d8127ab9e1cd8deb96953fe156
https://github.com/jbittel/django-mama-cas/blob/03935d97442b46d8127ab9e1cd8deb96953fe156/mama_cas/response.py#L228-L245
train
238,068
jbittel/django-mama-cas
mama_cas/response.py
SamlValidationResponse.get_authentication_statement
def get_authentication_statement(self, subject, ticket): """ Build an AuthenticationStatement XML block for a SAML 1.1 Assertion. """ authentication_statement = etree.Element('AuthenticationStatement') authentication_statement.set('AuthenticationInstant', self.instant(instant=ticket.consumed)) authentication_statement.set('AuthenticationMethod', self.authn_method_password) authentication_statement.append(subject) return authentication_statement
python
def get_authentication_statement(self, subject, ticket): """ Build an AuthenticationStatement XML block for a SAML 1.1 Assertion. """ authentication_statement = etree.Element('AuthenticationStatement') authentication_statement.set('AuthenticationInstant', self.instant(instant=ticket.consumed)) authentication_statement.set('AuthenticationMethod', self.authn_method_password) authentication_statement.append(subject) return authentication_statement
[ "def", "get_authentication_statement", "(", "self", ",", "subject", ",", "ticket", ")", ":", "authentication_statement", "=", "etree", ".", "Element", "(", "'AuthenticationStatement'", ")", "authentication_statement", ".", "set", "(", "'AuthenticationInstant'", ",", "self", ".", "instant", "(", "instant", "=", "ticket", ".", "consumed", ")", ")", "authentication_statement", ".", "set", "(", "'AuthenticationMethod'", ",", "self", ".", "authn_method_password", ")", "authentication_statement", ".", "append", "(", "subject", ")", "return", "authentication_statement" ]
Build an AuthenticationStatement XML block for a SAML 1.1 Assertion.
[ "Build", "an", "AuthenticationStatement", "XML", "block", "for", "a", "SAML", "1", ".", "1", "Assertion", "." ]
03935d97442b46d8127ab9e1cd8deb96953fe156
https://github.com/jbittel/django-mama-cas/blob/03935d97442b46d8127ab9e1cd8deb96953fe156/mama_cas/response.py#L247-L258
train
238,069
jbittel/django-mama-cas
mama_cas/response.py
SamlValidationResponse.get_subject
def get_subject(self, identifier): """ Build a Subject XML block for a SAML 1.1 AuthenticationStatement or AttributeStatement. """ subject = etree.Element('Subject') name = etree.SubElement(subject, 'NameIdentifier') name.text = identifier subject_confirmation = etree.SubElement(subject, 'SubjectConfirmation') method = etree.SubElement(subject_confirmation, 'ConfirmationMethod') method.text = self.confirmation_method return subject
python
def get_subject(self, identifier): """ Build a Subject XML block for a SAML 1.1 AuthenticationStatement or AttributeStatement. """ subject = etree.Element('Subject') name = etree.SubElement(subject, 'NameIdentifier') name.text = identifier subject_confirmation = etree.SubElement(subject, 'SubjectConfirmation') method = etree.SubElement(subject_confirmation, 'ConfirmationMethod') method.text = self.confirmation_method return subject
[ "def", "get_subject", "(", "self", ",", "identifier", ")", ":", "subject", "=", "etree", ".", "Element", "(", "'Subject'", ")", "name", "=", "etree", ".", "SubElement", "(", "subject", ",", "'NameIdentifier'", ")", "name", ".", "text", "=", "identifier", "subject_confirmation", "=", "etree", ".", "SubElement", "(", "subject", ",", "'SubjectConfirmation'", ")", "method", "=", "etree", ".", "SubElement", "(", "subject_confirmation", ",", "'ConfirmationMethod'", ")", "method", ".", "text", "=", "self", ".", "confirmation_method", "return", "subject" ]
Build a Subject XML block for a SAML 1.1 AuthenticationStatement or AttributeStatement.
[ "Build", "a", "Subject", "XML", "block", "for", "a", "SAML", "1", ".", "1", "AuthenticationStatement", "or", "AttributeStatement", "." ]
03935d97442b46d8127ab9e1cd8deb96953fe156
https://github.com/jbittel/django-mama-cas/blob/03935d97442b46d8127ab9e1cd8deb96953fe156/mama_cas/response.py#L260-L271
train
238,070
sarugaku/vistir
src/vistir/compat.py
is_bytes
def is_bytes(string): """Check if a string is a bytes instance :param Union[str, bytes] string: A string that may be string or bytes like :return: Whether the provided string is a bytes type or not :rtype: bool """ if six.PY3 and isinstance(string, (bytes, memoryview, bytearray)): # noqa return True elif six.PY2 and isinstance(string, (buffer, bytearray)): # noqa return True return False
python
def is_bytes(string): """Check if a string is a bytes instance :param Union[str, bytes] string: A string that may be string or bytes like :return: Whether the provided string is a bytes type or not :rtype: bool """ if six.PY3 and isinstance(string, (bytes, memoryview, bytearray)): # noqa return True elif six.PY2 and isinstance(string, (buffer, bytearray)): # noqa return True return False
[ "def", "is_bytes", "(", "string", ")", ":", "if", "six", ".", "PY3", "and", "isinstance", "(", "string", ",", "(", "bytes", ",", "memoryview", ",", "bytearray", ")", ")", ":", "# noqa", "return", "True", "elif", "six", ".", "PY2", "and", "isinstance", "(", "string", ",", "(", "buffer", ",", "bytearray", ")", ")", ":", "# noqa", "return", "True", "return", "False" ]
Check if a string is a bytes instance :param Union[str, bytes] string: A string that may be string or bytes like :return: Whether the provided string is a bytes type or not :rtype: bool
[ "Check", "if", "a", "string", "is", "a", "bytes", "instance" ]
96c008ee62a43608d1e70797f74634cb66a004c1
https://github.com/sarugaku/vistir/blob/96c008ee62a43608d1e70797f74634cb66a004c1/src/vistir/compat.py#L205-L216
train
238,071
sarugaku/vistir
src/vistir/misc.py
partialclass
def partialclass(cls, *args, **kwargs): """Returns a partially instantiated class :return: A partial class instance :rtype: cls >>> source = partialclass(Source, url="https://pypi.org/simple") >>> source <class '__main__.Source'> >>> source(name="pypi") >>> source.__dict__ mappingproxy({'__module__': '__main__', '__dict__': <attribute '__dict__' of 'Source' objects>, '__weakref__': <attribute '__weakref__' of 'Source' objects>, '__doc__': None, '__init__': functools.partialmethod(<function Source.__init__ at 0x7f23af429bf8>, , url='https://pypi.org/simple')}) >>> new_source = source(name="pypi") >>> new_source <__main__.Source object at 0x7f23af189b38> >>> new_source.__dict__ {'url': 'https://pypi.org/simple', 'verify_ssl': True, 'name': 'pypi'} """ name_attrs = [ n for n in (getattr(cls, name, str(cls)) for name in ("__name__", "__qualname__")) if n is not None ] name_attrs = name_attrs[0] type_ = type( name_attrs, (cls,), {"__init__": partialmethod(cls.__init__, *args, **kwargs)} ) # Swiped from attrs.make_class try: type_.__module__ = sys._getframe(1).f_globals.get("__name__", "__main__") except (AttributeError, ValueError): # pragma: no cover pass # pragma: no cover return type_
python
def partialclass(cls, *args, **kwargs): """Returns a partially instantiated class :return: A partial class instance :rtype: cls >>> source = partialclass(Source, url="https://pypi.org/simple") >>> source <class '__main__.Source'> >>> source(name="pypi") >>> source.__dict__ mappingproxy({'__module__': '__main__', '__dict__': <attribute '__dict__' of 'Source' objects>, '__weakref__': <attribute '__weakref__' of 'Source' objects>, '__doc__': None, '__init__': functools.partialmethod(<function Source.__init__ at 0x7f23af429bf8>, , url='https://pypi.org/simple')}) >>> new_source = source(name="pypi") >>> new_source <__main__.Source object at 0x7f23af189b38> >>> new_source.__dict__ {'url': 'https://pypi.org/simple', 'verify_ssl': True, 'name': 'pypi'} """ name_attrs = [ n for n in (getattr(cls, name, str(cls)) for name in ("__name__", "__qualname__")) if n is not None ] name_attrs = name_attrs[0] type_ = type( name_attrs, (cls,), {"__init__": partialmethod(cls.__init__, *args, **kwargs)} ) # Swiped from attrs.make_class try: type_.__module__ = sys._getframe(1).f_globals.get("__name__", "__main__") except (AttributeError, ValueError): # pragma: no cover pass # pragma: no cover return type_
[ "def", "partialclass", "(", "cls", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "name_attrs", "=", "[", "n", "for", "n", "in", "(", "getattr", "(", "cls", ",", "name", ",", "str", "(", "cls", ")", ")", "for", "name", "in", "(", "\"__name__\"", ",", "\"__qualname__\"", ")", ")", "if", "n", "is", "not", "None", "]", "name_attrs", "=", "name_attrs", "[", "0", "]", "type_", "=", "type", "(", "name_attrs", ",", "(", "cls", ",", ")", ",", "{", "\"__init__\"", ":", "partialmethod", "(", "cls", ".", "__init__", ",", "*", "args", ",", "*", "*", "kwargs", ")", "}", ")", "# Swiped from attrs.make_class", "try", ":", "type_", ".", "__module__", "=", "sys", ".", "_getframe", "(", "1", ")", ".", "f_globals", ".", "get", "(", "\"__name__\"", ",", "\"__main__\"", ")", "except", "(", "AttributeError", ",", "ValueError", ")", ":", "# pragma: no cover", "pass", "# pragma: no cover", "return", "type_" ]
Returns a partially instantiated class :return: A partial class instance :rtype: cls >>> source = partialclass(Source, url="https://pypi.org/simple") >>> source <class '__main__.Source'> >>> source(name="pypi") >>> source.__dict__ mappingproxy({'__module__': '__main__', '__dict__': <attribute '__dict__' of 'Source' objects>, '__weakref__': <attribute '__weakref__' of 'Source' objects>, '__doc__': None, '__init__': functools.partialmethod(<function Source.__init__ at 0x7f23af429bf8>, , url='https://pypi.org/simple')}) >>> new_source = source(name="pypi") >>> new_source <__main__.Source object at 0x7f23af189b38> >>> new_source.__dict__ {'url': 'https://pypi.org/simple', 'verify_ssl': True, 'name': 'pypi'}
[ "Returns", "a", "partially", "instantiated", "class" ]
96c008ee62a43608d1e70797f74634cb66a004c1
https://github.com/sarugaku/vistir/blob/96c008ee62a43608d1e70797f74634cb66a004c1/src/vistir/misc.py#L371-L404
train
238,072
sarugaku/vistir
src/vistir/misc.py
replace_with_text_stream
def replace_with_text_stream(stream_name): """Given a stream name, replace the target stream with a text-converted equivalent :param str stream_name: The name of a target stream, such as **stdout** or **stderr** :return: None """ new_stream = TEXT_STREAMS.get(stream_name) if new_stream is not None: new_stream = new_stream() setattr(sys, stream_name, new_stream) return None
python
def replace_with_text_stream(stream_name): """Given a stream name, replace the target stream with a text-converted equivalent :param str stream_name: The name of a target stream, such as **stdout** or **stderr** :return: None """ new_stream = TEXT_STREAMS.get(stream_name) if new_stream is not None: new_stream = new_stream() setattr(sys, stream_name, new_stream) return None
[ "def", "replace_with_text_stream", "(", "stream_name", ")", ":", "new_stream", "=", "TEXT_STREAMS", ".", "get", "(", "stream_name", ")", "if", "new_stream", "is", "not", "None", ":", "new_stream", "=", "new_stream", "(", ")", "setattr", "(", "sys", ",", "stream_name", ",", "new_stream", ")", "return", "None" ]
Given a stream name, replace the target stream with a text-converted equivalent :param str stream_name: The name of a target stream, such as **stdout** or **stderr** :return: None
[ "Given", "a", "stream", "name", "replace", "the", "target", "stream", "with", "a", "text", "-", "converted", "equivalent" ]
96c008ee62a43608d1e70797f74634cb66a004c1
https://github.com/sarugaku/vistir/blob/96c008ee62a43608d1e70797f74634cb66a004c1/src/vistir/misc.py#L913-L923
train
238,073
sarugaku/vistir
src/vistir/backports/tempfile.py
_sanitize_params
def _sanitize_params(prefix, suffix, dir): """Common parameter processing for most APIs in this module.""" output_type = _infer_return_type(prefix, suffix, dir) if suffix is None: suffix = output_type() if prefix is None: if output_type is str: prefix = "tmp" else: prefix = os.fsencode("tmp") if dir is None: if output_type is str: dir = gettempdir() else: dir = fs_encode(gettempdir()) return prefix, suffix, dir, output_type
python
def _sanitize_params(prefix, suffix, dir): """Common parameter processing for most APIs in this module.""" output_type = _infer_return_type(prefix, suffix, dir) if suffix is None: suffix = output_type() if prefix is None: if output_type is str: prefix = "tmp" else: prefix = os.fsencode("tmp") if dir is None: if output_type is str: dir = gettempdir() else: dir = fs_encode(gettempdir()) return prefix, suffix, dir, output_type
[ "def", "_sanitize_params", "(", "prefix", ",", "suffix", ",", "dir", ")", ":", "output_type", "=", "_infer_return_type", "(", "prefix", ",", "suffix", ",", "dir", ")", "if", "suffix", "is", "None", ":", "suffix", "=", "output_type", "(", ")", "if", "prefix", "is", "None", ":", "if", "output_type", "is", "str", ":", "prefix", "=", "\"tmp\"", "else", ":", "prefix", "=", "os", ".", "fsencode", "(", "\"tmp\"", ")", "if", "dir", "is", "None", ":", "if", "output_type", "is", "str", ":", "dir", "=", "gettempdir", "(", ")", "else", ":", "dir", "=", "fs_encode", "(", "gettempdir", "(", ")", ")", "return", "prefix", ",", "suffix", ",", "dir", ",", "output_type" ]
Common parameter processing for most APIs in this module.
[ "Common", "parameter", "processing", "for", "most", "APIs", "in", "this", "module", "." ]
96c008ee62a43608d1e70797f74634cb66a004c1
https://github.com/sarugaku/vistir/blob/96c008ee62a43608d1e70797f74634cb66a004c1/src/vistir/backports/tempfile.py#L55-L70
train
238,074
danielholmstrom/dictalchemy
dictalchemy/utils.py
fromdict
def fromdict(model, data, exclude=None, exclude_underscore=None, allow_pk=None, follow=None, include=None, only=None): """Update a model from a dict Works almost identically as :meth:`dictalchemy.utils.asdict`. However, it will not create missing instances or update collections. This method updates the following properties on a model: * Simple columns * Synonyms * Simple 1-m relationships :param data: dict of data :param exclude: list of properties that should be excluded :param exclude_underscore: If True underscore properties will be excluded,\ if set to None model.dictalchemy_exclude_underscore will be used. :param allow_pk: If True any column that refers to the primary key will \ be excluded. Defaults model.dictalchemy_fromdict_allow_pk or \ dictable.constants.fromdict_allow_pk. If set to True a primary \ key can still be excluded with the `exclude` parameter. :param follow: Dict of relations that should be followed, the key is the \ arguments passed to the relation. Relations only works on simple \ relations, not on lists. :param include: List of properties that should be included. This list \ will override anything in the exclude list. It will not override \ allow_pk. :param only: List of the only properties that should be set. This \ will not override `allow_pk` or `follow`. :raises: :class:`dictalchemy.errors.DictalchemyError` If a primary key is \ in data and allow_pk is False :returns: The model """ follow = arg_to_dict(follow) info = inspect(model) columns = [c.key for c in info.mapper.column_attrs] synonyms = [c.key for c in info.mapper.synonyms] relations = [c.key for c in info.mapper.relationships] primary_keys = [c.key for c in info.mapper.primary_key] if allow_pk is None: allow_pk = getattr(model, 'dictalchemy_fromdict_allow_pk', constants.default_fromdict_allow_pk) if only: valid_keys = only else: exclude = exclude or [] exclude += getattr(model, 'dictalchemy_exclude', constants.default_exclude) or [] if exclude_underscore is None: exclude_underscore = getattr(model, 'dictalchemy_exclude_underscore', constants.default_exclude_underscore) if exclude_underscore: # Exclude all properties starting with underscore exclude += [k.key for k in info.mapper.attrs if k.key[0] == '_'] include = (include or []) + (getattr(model, 'dictalchemy_fromdict_include', getattr(model, 'dictalchemy_include', None)) or []) valid_keys = [k for k in columns + synonyms if k not in exclude] + include # Keys that will be updated update_keys = set(valid_keys) & set(data.keys()) # Check for primary keys data_primary_key= update_keys & set(primary_keys) if len(data_primary_key) and not allow_pk: msg = ("Primary keys({0}) cannot be updated by fromdict." "Set 'dictalchemy_fromdict_allow_pk' to True in your Model" " or pass 'allow_pk=True'.").format(','.join(data_primary_key)) raise errors.DictalchemyError(msg) # Update columns and synonyms for k in update_keys: setattr(model, k, data[k]) # Update simple relations for (k, args) in follow.iteritems(): if k not in data: continue if k not in relations: raise errors.MissingRelationError(k) rel = getattr(model, k) if hasattr(rel, 'fromdict'): rel.fromdict(data[k], **args) return model
python
def fromdict(model, data, exclude=None, exclude_underscore=None, allow_pk=None, follow=None, include=None, only=None): """Update a model from a dict Works almost identically as :meth:`dictalchemy.utils.asdict`. However, it will not create missing instances or update collections. This method updates the following properties on a model: * Simple columns * Synonyms * Simple 1-m relationships :param data: dict of data :param exclude: list of properties that should be excluded :param exclude_underscore: If True underscore properties will be excluded,\ if set to None model.dictalchemy_exclude_underscore will be used. :param allow_pk: If True any column that refers to the primary key will \ be excluded. Defaults model.dictalchemy_fromdict_allow_pk or \ dictable.constants.fromdict_allow_pk. If set to True a primary \ key can still be excluded with the `exclude` parameter. :param follow: Dict of relations that should be followed, the key is the \ arguments passed to the relation. Relations only works on simple \ relations, not on lists. :param include: List of properties that should be included. This list \ will override anything in the exclude list. It will not override \ allow_pk. :param only: List of the only properties that should be set. This \ will not override `allow_pk` or `follow`. :raises: :class:`dictalchemy.errors.DictalchemyError` If a primary key is \ in data and allow_pk is False :returns: The model """ follow = arg_to_dict(follow) info = inspect(model) columns = [c.key for c in info.mapper.column_attrs] synonyms = [c.key for c in info.mapper.synonyms] relations = [c.key for c in info.mapper.relationships] primary_keys = [c.key for c in info.mapper.primary_key] if allow_pk is None: allow_pk = getattr(model, 'dictalchemy_fromdict_allow_pk', constants.default_fromdict_allow_pk) if only: valid_keys = only else: exclude = exclude or [] exclude += getattr(model, 'dictalchemy_exclude', constants.default_exclude) or [] if exclude_underscore is None: exclude_underscore = getattr(model, 'dictalchemy_exclude_underscore', constants.default_exclude_underscore) if exclude_underscore: # Exclude all properties starting with underscore exclude += [k.key for k in info.mapper.attrs if k.key[0] == '_'] include = (include or []) + (getattr(model, 'dictalchemy_fromdict_include', getattr(model, 'dictalchemy_include', None)) or []) valid_keys = [k for k in columns + synonyms if k not in exclude] + include # Keys that will be updated update_keys = set(valid_keys) & set(data.keys()) # Check for primary keys data_primary_key= update_keys & set(primary_keys) if len(data_primary_key) and not allow_pk: msg = ("Primary keys({0}) cannot be updated by fromdict." "Set 'dictalchemy_fromdict_allow_pk' to True in your Model" " or pass 'allow_pk=True'.").format(','.join(data_primary_key)) raise errors.DictalchemyError(msg) # Update columns and synonyms for k in update_keys: setattr(model, k, data[k]) # Update simple relations for (k, args) in follow.iteritems(): if k not in data: continue if k not in relations: raise errors.MissingRelationError(k) rel = getattr(model, k) if hasattr(rel, 'fromdict'): rel.fromdict(data[k], **args) return model
[ "def", "fromdict", "(", "model", ",", "data", ",", "exclude", "=", "None", ",", "exclude_underscore", "=", "None", ",", "allow_pk", "=", "None", ",", "follow", "=", "None", ",", "include", "=", "None", ",", "only", "=", "None", ")", ":", "follow", "=", "arg_to_dict", "(", "follow", ")", "info", "=", "inspect", "(", "model", ")", "columns", "=", "[", "c", ".", "key", "for", "c", "in", "info", ".", "mapper", ".", "column_attrs", "]", "synonyms", "=", "[", "c", ".", "key", "for", "c", "in", "info", ".", "mapper", ".", "synonyms", "]", "relations", "=", "[", "c", ".", "key", "for", "c", "in", "info", ".", "mapper", ".", "relationships", "]", "primary_keys", "=", "[", "c", ".", "key", "for", "c", "in", "info", ".", "mapper", ".", "primary_key", "]", "if", "allow_pk", "is", "None", ":", "allow_pk", "=", "getattr", "(", "model", ",", "'dictalchemy_fromdict_allow_pk'", ",", "constants", ".", "default_fromdict_allow_pk", ")", "if", "only", ":", "valid_keys", "=", "only", "else", ":", "exclude", "=", "exclude", "or", "[", "]", "exclude", "+=", "getattr", "(", "model", ",", "'dictalchemy_exclude'", ",", "constants", ".", "default_exclude", ")", "or", "[", "]", "if", "exclude_underscore", "is", "None", ":", "exclude_underscore", "=", "getattr", "(", "model", ",", "'dictalchemy_exclude_underscore'", ",", "constants", ".", "default_exclude_underscore", ")", "if", "exclude_underscore", ":", "# Exclude all properties starting with underscore", "exclude", "+=", "[", "k", ".", "key", "for", "k", "in", "info", ".", "mapper", ".", "attrs", "if", "k", ".", "key", "[", "0", "]", "==", "'_'", "]", "include", "=", "(", "include", "or", "[", "]", ")", "+", "(", "getattr", "(", "model", ",", "'dictalchemy_fromdict_include'", ",", "getattr", "(", "model", ",", "'dictalchemy_include'", ",", "None", ")", ")", "or", "[", "]", ")", "valid_keys", "=", "[", "k", "for", "k", "in", "columns", "+", "synonyms", "if", "k", "not", "in", "exclude", "]", "+", "include", "# Keys that will be updated", "update_keys", "=", "set", "(", "valid_keys", ")", "&", "set", "(", "data", ".", "keys", "(", ")", ")", "# Check for primary keys", "data_primary_key", "=", "update_keys", "&", "set", "(", "primary_keys", ")", "if", "len", "(", "data_primary_key", ")", "and", "not", "allow_pk", ":", "msg", "=", "(", "\"Primary keys({0}) cannot be updated by fromdict.\"", "\"Set 'dictalchemy_fromdict_allow_pk' to True in your Model\"", "\" or pass 'allow_pk=True'.\"", ")", ".", "format", "(", "','", ".", "join", "(", "data_primary_key", ")", ")", "raise", "errors", ".", "DictalchemyError", "(", "msg", ")", "# Update columns and synonyms", "for", "k", "in", "update_keys", ":", "setattr", "(", "model", ",", "k", ",", "data", "[", "k", "]", ")", "# Update simple relations", "for", "(", "k", ",", "args", ")", "in", "follow", ".", "iteritems", "(", ")", ":", "if", "k", "not", "in", "data", ":", "continue", "if", "k", "not", "in", "relations", ":", "raise", "errors", ".", "MissingRelationError", "(", "k", ")", "rel", "=", "getattr", "(", "model", ",", "k", ")", "if", "hasattr", "(", "rel", ",", "'fromdict'", ")", ":", "rel", ".", "fromdict", "(", "data", "[", "k", "]", ",", "*", "*", "args", ")", "return", "model" ]
Update a model from a dict Works almost identically as :meth:`dictalchemy.utils.asdict`. However, it will not create missing instances or update collections. This method updates the following properties on a model: * Simple columns * Synonyms * Simple 1-m relationships :param data: dict of data :param exclude: list of properties that should be excluded :param exclude_underscore: If True underscore properties will be excluded,\ if set to None model.dictalchemy_exclude_underscore will be used. :param allow_pk: If True any column that refers to the primary key will \ be excluded. Defaults model.dictalchemy_fromdict_allow_pk or \ dictable.constants.fromdict_allow_pk. If set to True a primary \ key can still be excluded with the `exclude` parameter. :param follow: Dict of relations that should be followed, the key is the \ arguments passed to the relation. Relations only works on simple \ relations, not on lists. :param include: List of properties that should be included. This list \ will override anything in the exclude list. It will not override \ allow_pk. :param only: List of the only properties that should be set. This \ will not override `allow_pk` or `follow`. :raises: :class:`dictalchemy.errors.DictalchemyError` If a primary key is \ in data and allow_pk is False :returns: The model
[ "Update", "a", "model", "from", "a", "dict" ]
038b8822b0ed66feef78a80b3af8f3a09f795b5a
https://github.com/danielholmstrom/dictalchemy/blob/038b8822b0ed66feef78a80b3af8f3a09f795b5a/dictalchemy/utils.py#L186-L283
train
238,075
danielholmstrom/dictalchemy
dictalchemy/utils.py
make_class_dictable
def make_class_dictable( cls, exclude=constants.default_exclude, exclude_underscore=constants.default_exclude_underscore, fromdict_allow_pk=constants.default_fromdict_allow_pk, include=None, asdict_include=None, fromdict_include=None): """Make a class dictable Useful for when the Base class is already defined, for example when using Flask-SQLAlchemy. Warning: This method will overwrite existing attributes if they exists. :param exclude: Will be set as dictalchemy_exclude on the class :param exclude_underscore: Will be set as dictalchemy_exclude_underscore \ on the class :param fromdict_allow_pk: Will be set as dictalchemy_fromdict_allow_pk\ on the class :param include: Will be set as dictalchemy_include on the class. :param asdict_include: Will be set as `dictalchemy_asdict_include` on the \ class. If not None it will override `dictalchemy_include`. :param fromdict_include: Will be set as `dictalchemy_fromdict_include` on \ the class. If not None it will override `dictalchemy_include`. :returns: The class """ setattr(cls, 'dictalchemy_exclude', exclude) setattr(cls, 'dictalchemy_exclude_underscore', exclude_underscore) setattr(cls, 'dictalchemy_fromdict_allow_pk', fromdict_allow_pk) setattr(cls, 'asdict', asdict) setattr(cls, 'fromdict', fromdict) setattr(cls, '__iter__', iter) setattr(cls, 'dictalchemy_include', include) setattr(cls, 'dictalchemy_asdict_include', asdict_include) setattr(cls, 'dictalchemy_fromdict_include', fromdict_include) return cls
python
def make_class_dictable( cls, exclude=constants.default_exclude, exclude_underscore=constants.default_exclude_underscore, fromdict_allow_pk=constants.default_fromdict_allow_pk, include=None, asdict_include=None, fromdict_include=None): """Make a class dictable Useful for when the Base class is already defined, for example when using Flask-SQLAlchemy. Warning: This method will overwrite existing attributes if they exists. :param exclude: Will be set as dictalchemy_exclude on the class :param exclude_underscore: Will be set as dictalchemy_exclude_underscore \ on the class :param fromdict_allow_pk: Will be set as dictalchemy_fromdict_allow_pk\ on the class :param include: Will be set as dictalchemy_include on the class. :param asdict_include: Will be set as `dictalchemy_asdict_include` on the \ class. If not None it will override `dictalchemy_include`. :param fromdict_include: Will be set as `dictalchemy_fromdict_include` on \ the class. If not None it will override `dictalchemy_include`. :returns: The class """ setattr(cls, 'dictalchemy_exclude', exclude) setattr(cls, 'dictalchemy_exclude_underscore', exclude_underscore) setattr(cls, 'dictalchemy_fromdict_allow_pk', fromdict_allow_pk) setattr(cls, 'asdict', asdict) setattr(cls, 'fromdict', fromdict) setattr(cls, '__iter__', iter) setattr(cls, 'dictalchemy_include', include) setattr(cls, 'dictalchemy_asdict_include', asdict_include) setattr(cls, 'dictalchemy_fromdict_include', fromdict_include) return cls
[ "def", "make_class_dictable", "(", "cls", ",", "exclude", "=", "constants", ".", "default_exclude", ",", "exclude_underscore", "=", "constants", ".", "default_exclude_underscore", ",", "fromdict_allow_pk", "=", "constants", ".", "default_fromdict_allow_pk", ",", "include", "=", "None", ",", "asdict_include", "=", "None", ",", "fromdict_include", "=", "None", ")", ":", "setattr", "(", "cls", ",", "'dictalchemy_exclude'", ",", "exclude", ")", "setattr", "(", "cls", ",", "'dictalchemy_exclude_underscore'", ",", "exclude_underscore", ")", "setattr", "(", "cls", ",", "'dictalchemy_fromdict_allow_pk'", ",", "fromdict_allow_pk", ")", "setattr", "(", "cls", ",", "'asdict'", ",", "asdict", ")", "setattr", "(", "cls", ",", "'fromdict'", ",", "fromdict", ")", "setattr", "(", "cls", ",", "'__iter__'", ",", "iter", ")", "setattr", "(", "cls", ",", "'dictalchemy_include'", ",", "include", ")", "setattr", "(", "cls", ",", "'dictalchemy_asdict_include'", ",", "asdict_include", ")", "setattr", "(", "cls", ",", "'dictalchemy_fromdict_include'", ",", "fromdict_include", ")", "return", "cls" ]
Make a class dictable Useful for when the Base class is already defined, for example when using Flask-SQLAlchemy. Warning: This method will overwrite existing attributes if they exists. :param exclude: Will be set as dictalchemy_exclude on the class :param exclude_underscore: Will be set as dictalchemy_exclude_underscore \ on the class :param fromdict_allow_pk: Will be set as dictalchemy_fromdict_allow_pk\ on the class :param include: Will be set as dictalchemy_include on the class. :param asdict_include: Will be set as `dictalchemy_asdict_include` on the \ class. If not None it will override `dictalchemy_include`. :param fromdict_include: Will be set as `dictalchemy_fromdict_include` on \ the class. If not None it will override `dictalchemy_include`. :returns: The class
[ "Make", "a", "class", "dictable" ]
038b8822b0ed66feef78a80b3af8f3a09f795b5a
https://github.com/danielholmstrom/dictalchemy/blob/038b8822b0ed66feef78a80b3af8f3a09f795b5a/dictalchemy/utils.py#L295-L333
train
238,076
simon-anders/htseq
python2/HTSeq/__init__.py
parse_GFF_attribute_string
def parse_GFF_attribute_string(attrStr, extra_return_first_value=False): """Parses a GFF attribute string and returns it as a dictionary. If 'extra_return_first_value' is set, a pair is returned: the dictionary and the value of the first attribute. This might be useful if this is the ID. """ if attrStr.endswith("\n"): attrStr = attrStr[:-1] d = {} first_val = "_unnamed_" for (i, attr) in itertools.izip( itertools.count(), _HTSeq.quotesafe_split(attrStr)): if _re_attr_empty.match(attr): continue if attr.count('"') not in (0, 2): raise ValueError( "The attribute string seems to contain mismatched quotes.") mo = _re_attr_main.match(attr) if not mo: raise ValueError("Failure parsing GFF attribute line") val = mo.group(2) if val.startswith('"') and val.endswith('"'): val = val[1:-1] d[intern(mo.group(1))] = intern(val) if extra_return_first_value and i == 0: first_val = val if extra_return_first_value: return (d, first_val) else: return d
python
def parse_GFF_attribute_string(attrStr, extra_return_first_value=False): """Parses a GFF attribute string and returns it as a dictionary. If 'extra_return_first_value' is set, a pair is returned: the dictionary and the value of the first attribute. This might be useful if this is the ID. """ if attrStr.endswith("\n"): attrStr = attrStr[:-1] d = {} first_val = "_unnamed_" for (i, attr) in itertools.izip( itertools.count(), _HTSeq.quotesafe_split(attrStr)): if _re_attr_empty.match(attr): continue if attr.count('"') not in (0, 2): raise ValueError( "The attribute string seems to contain mismatched quotes.") mo = _re_attr_main.match(attr) if not mo: raise ValueError("Failure parsing GFF attribute line") val = mo.group(2) if val.startswith('"') and val.endswith('"'): val = val[1:-1] d[intern(mo.group(1))] = intern(val) if extra_return_first_value and i == 0: first_val = val if extra_return_first_value: return (d, first_val) else: return d
[ "def", "parse_GFF_attribute_string", "(", "attrStr", ",", "extra_return_first_value", "=", "False", ")", ":", "if", "attrStr", ".", "endswith", "(", "\"\\n\"", ")", ":", "attrStr", "=", "attrStr", "[", ":", "-", "1", "]", "d", "=", "{", "}", "first_val", "=", "\"_unnamed_\"", "for", "(", "i", ",", "attr", ")", "in", "itertools", ".", "izip", "(", "itertools", ".", "count", "(", ")", ",", "_HTSeq", ".", "quotesafe_split", "(", "attrStr", ")", ")", ":", "if", "_re_attr_empty", ".", "match", "(", "attr", ")", ":", "continue", "if", "attr", ".", "count", "(", "'\"'", ")", "not", "in", "(", "0", ",", "2", ")", ":", "raise", "ValueError", "(", "\"The attribute string seems to contain mismatched quotes.\"", ")", "mo", "=", "_re_attr_main", ".", "match", "(", "attr", ")", "if", "not", "mo", ":", "raise", "ValueError", "(", "\"Failure parsing GFF attribute line\"", ")", "val", "=", "mo", ".", "group", "(", "2", ")", "if", "val", ".", "startswith", "(", "'\"'", ")", "and", "val", ".", "endswith", "(", "'\"'", ")", ":", "val", "=", "val", "[", "1", ":", "-", "1", "]", "d", "[", "intern", "(", "mo", ".", "group", "(", "1", ")", ")", "]", "=", "intern", "(", "val", ")", "if", "extra_return_first_value", "and", "i", "==", "0", ":", "first_val", "=", "val", "if", "extra_return_first_value", ":", "return", "(", "d", ",", "first_val", ")", "else", ":", "return", "d" ]
Parses a GFF attribute string and returns it as a dictionary. If 'extra_return_first_value' is set, a pair is returned: the dictionary and the value of the first attribute. This might be useful if this is the ID.
[ "Parses", "a", "GFF", "attribute", "string", "and", "returns", "it", "as", "a", "dictionary", "." ]
6f7d66e757e610228c33ebf2bb5dc8cc5051c7f0
https://github.com/simon-anders/htseq/blob/6f7d66e757e610228c33ebf2bb5dc8cc5051c7f0/python2/HTSeq/__init__.py#L144-L175
train
238,077
simon-anders/htseq
python2/HTSeq/__init__.py
pair_SAM_alignments
def pair_SAM_alignments( alignments, bundle=False, primary_only=False): '''Iterate over SAM aligments, name-sorted paired-end Args: alignments (iterator of SAM/BAM alignments): the alignments to wrap bundle (bool): if True, bundle all alignments from one read pair into a single yield. If False (default), each pair of alignments is yielded separately. primary_only (bool): for each read, consider only the primary line (SAM flag 0x900 = 0). The SAM specification requires one and only one of those for each read. Yields: 2-tuples with each pair of alignments or, if bundle==True, each bundled list of alignments. ''' mate_missing_count = [0] def process_list(almnt_list): '''Transform a list of alignment with the same read name into pairs Args: almnt_list (list): alignments to process Yields: each pair of alignments. This function is needed because each line of a BAM file is not a read but an alignment. For uniquely mapped and unmapped reads, those two are the same. For multimapped reads, however, there can be more than one alignment for each read. Also, it is normal for a mapper to uniquely map one read and multimap its mate. This function goes down the list of alignments for a given read name and tries to find the first mate. So if read 1 is uniquely mapped but read 2 is mapped 4 times, only (read 1, read 2 - first occurrence) will yield; the other 3 alignments of read 2 are ignored. ''' while len(almnt_list) > 0: a1 = almnt_list.pop(0) # Find its mate for a2 in almnt_list: if a1.pe_which == a2.pe_which: continue if a1.aligned != a2.mate_aligned or a1.mate_aligned != a2.aligned: continue if not (a1.aligned and a2.aligned): break if a1.iv.chrom == a2.mate_start.chrom and a1.iv.start == a2.mate_start.pos and \ a2.iv.chrom == a1.mate_start.chrom and a2.iv.start == a1.mate_start.pos: break else: if a1.mate_aligned: mate_missing_count[0] += 1 if mate_missing_count[0] == 1: warnings.warn( "Read " + a1.read.name + " claims to have an aligned mate " + "which could not be found in an adjacent line.") a2 = None if a2 is not None: almnt_list.remove(a2) if a1.pe_which == "first": yield (a1, a2) else: assert a1.pe_which == "second" yield (a2, a1) almnt_list = [] current_name = None for almnt in alignments: if not almnt.paired_end: raise ValueError( "'pair_alignments' needs a sequence of paired-end alignments") if almnt.pe_which == "unknown": raise ValueError( "Paired-end read found with 'unknown' 'pe_which' status.") # FIXME: almnt.not_primary_alignment currently means secondary if primary_only and (almnt.not_primary_alignment or almnt.supplementary): continue if almnt.read.name == current_name: almnt_list.append(almnt) else: if bundle: yield list(process_list(almnt_list)) else: for p in process_list(almnt_list): yield p current_name = almnt.read.name almnt_list = [almnt] if bundle: yield list(process_list(almnt_list)) else: for p in process_list(almnt_list): yield p if mate_missing_count[0] > 1: warnings.warn("%d reads with missing mate encountered." % mate_missing_count[0])
python
def pair_SAM_alignments( alignments, bundle=False, primary_only=False): '''Iterate over SAM aligments, name-sorted paired-end Args: alignments (iterator of SAM/BAM alignments): the alignments to wrap bundle (bool): if True, bundle all alignments from one read pair into a single yield. If False (default), each pair of alignments is yielded separately. primary_only (bool): for each read, consider only the primary line (SAM flag 0x900 = 0). The SAM specification requires one and only one of those for each read. Yields: 2-tuples with each pair of alignments or, if bundle==True, each bundled list of alignments. ''' mate_missing_count = [0] def process_list(almnt_list): '''Transform a list of alignment with the same read name into pairs Args: almnt_list (list): alignments to process Yields: each pair of alignments. This function is needed because each line of a BAM file is not a read but an alignment. For uniquely mapped and unmapped reads, those two are the same. For multimapped reads, however, there can be more than one alignment for each read. Also, it is normal for a mapper to uniquely map one read and multimap its mate. This function goes down the list of alignments for a given read name and tries to find the first mate. So if read 1 is uniquely mapped but read 2 is mapped 4 times, only (read 1, read 2 - first occurrence) will yield; the other 3 alignments of read 2 are ignored. ''' while len(almnt_list) > 0: a1 = almnt_list.pop(0) # Find its mate for a2 in almnt_list: if a1.pe_which == a2.pe_which: continue if a1.aligned != a2.mate_aligned or a1.mate_aligned != a2.aligned: continue if not (a1.aligned and a2.aligned): break if a1.iv.chrom == a2.mate_start.chrom and a1.iv.start == a2.mate_start.pos and \ a2.iv.chrom == a1.mate_start.chrom and a2.iv.start == a1.mate_start.pos: break else: if a1.mate_aligned: mate_missing_count[0] += 1 if mate_missing_count[0] == 1: warnings.warn( "Read " + a1.read.name + " claims to have an aligned mate " + "which could not be found in an adjacent line.") a2 = None if a2 is not None: almnt_list.remove(a2) if a1.pe_which == "first": yield (a1, a2) else: assert a1.pe_which == "second" yield (a2, a1) almnt_list = [] current_name = None for almnt in alignments: if not almnt.paired_end: raise ValueError( "'pair_alignments' needs a sequence of paired-end alignments") if almnt.pe_which == "unknown": raise ValueError( "Paired-end read found with 'unknown' 'pe_which' status.") # FIXME: almnt.not_primary_alignment currently means secondary if primary_only and (almnt.not_primary_alignment or almnt.supplementary): continue if almnt.read.name == current_name: almnt_list.append(almnt) else: if bundle: yield list(process_list(almnt_list)) else: for p in process_list(almnt_list): yield p current_name = almnt.read.name almnt_list = [almnt] if bundle: yield list(process_list(almnt_list)) else: for p in process_list(almnt_list): yield p if mate_missing_count[0] > 1: warnings.warn("%d reads with missing mate encountered." % mate_missing_count[0])
[ "def", "pair_SAM_alignments", "(", "alignments", ",", "bundle", "=", "False", ",", "primary_only", "=", "False", ")", ":", "mate_missing_count", "=", "[", "0", "]", "def", "process_list", "(", "almnt_list", ")", ":", "'''Transform a list of alignment with the same read name into pairs\n\n Args:\n almnt_list (list): alignments to process\n\n Yields:\n each pair of alignments.\n\n This function is needed because each line of a BAM file is not a read\n but an alignment. For uniquely mapped and unmapped reads, those two are\n the same. For multimapped reads, however, there can be more than one\n alignment for each read. Also, it is normal for a mapper to uniquely\n map one read and multimap its mate.\n\n This function goes down the list of alignments for a given read name\n and tries to find the first mate. So if read 1 is uniquely mapped but\n read 2 is mapped 4 times, only (read 1, read 2 - first occurrence) will\n yield; the other 3 alignments of read 2 are ignored.\n '''", "while", "len", "(", "almnt_list", ")", ">", "0", ":", "a1", "=", "almnt_list", ".", "pop", "(", "0", ")", "# Find its mate", "for", "a2", "in", "almnt_list", ":", "if", "a1", ".", "pe_which", "==", "a2", ".", "pe_which", ":", "continue", "if", "a1", ".", "aligned", "!=", "a2", ".", "mate_aligned", "or", "a1", ".", "mate_aligned", "!=", "a2", ".", "aligned", ":", "continue", "if", "not", "(", "a1", ".", "aligned", "and", "a2", ".", "aligned", ")", ":", "break", "if", "a1", ".", "iv", ".", "chrom", "==", "a2", ".", "mate_start", ".", "chrom", "and", "a1", ".", "iv", ".", "start", "==", "a2", ".", "mate_start", ".", "pos", "and", "a2", ".", "iv", ".", "chrom", "==", "a1", ".", "mate_start", ".", "chrom", "and", "a2", ".", "iv", ".", "start", "==", "a1", ".", "mate_start", ".", "pos", ":", "break", "else", ":", "if", "a1", ".", "mate_aligned", ":", "mate_missing_count", "[", "0", "]", "+=", "1", "if", "mate_missing_count", "[", "0", "]", "==", "1", ":", "warnings", ".", "warn", "(", "\"Read \"", "+", "a1", ".", "read", ".", "name", "+", "\" claims to have an aligned mate \"", "+", "\"which could not be found in an adjacent line.\"", ")", "a2", "=", "None", "if", "a2", "is", "not", "None", ":", "almnt_list", ".", "remove", "(", "a2", ")", "if", "a1", ".", "pe_which", "==", "\"first\"", ":", "yield", "(", "a1", ",", "a2", ")", "else", ":", "assert", "a1", ".", "pe_which", "==", "\"second\"", "yield", "(", "a2", ",", "a1", ")", "almnt_list", "=", "[", "]", "current_name", "=", "None", "for", "almnt", "in", "alignments", ":", "if", "not", "almnt", ".", "paired_end", ":", "raise", "ValueError", "(", "\"'pair_alignments' needs a sequence of paired-end alignments\"", ")", "if", "almnt", ".", "pe_which", "==", "\"unknown\"", ":", "raise", "ValueError", "(", "\"Paired-end read found with 'unknown' 'pe_which' status.\"", ")", "# FIXME: almnt.not_primary_alignment currently means secondary", "if", "primary_only", "and", "(", "almnt", ".", "not_primary_alignment", "or", "almnt", ".", "supplementary", ")", ":", "continue", "if", "almnt", ".", "read", ".", "name", "==", "current_name", ":", "almnt_list", ".", "append", "(", "almnt", ")", "else", ":", "if", "bundle", ":", "yield", "list", "(", "process_list", "(", "almnt_list", ")", ")", "else", ":", "for", "p", "in", "process_list", "(", "almnt_list", ")", ":", "yield", "p", "current_name", "=", "almnt", ".", "read", ".", "name", "almnt_list", "=", "[", "almnt", "]", "if", "bundle", ":", "yield", "list", "(", "process_list", "(", "almnt_list", ")", ")", "else", ":", "for", "p", "in", "process_list", "(", "almnt_list", ")", ":", "yield", "p", "if", "mate_missing_count", "[", "0", "]", ">", "1", ":", "warnings", ".", "warn", "(", "\"%d reads with missing mate encountered.\"", "%", "mate_missing_count", "[", "0", "]", ")" ]
Iterate over SAM aligments, name-sorted paired-end Args: alignments (iterator of SAM/BAM alignments): the alignments to wrap bundle (bool): if True, bundle all alignments from one read pair into a single yield. If False (default), each pair of alignments is yielded separately. primary_only (bool): for each read, consider only the primary line (SAM flag 0x900 = 0). The SAM specification requires one and only one of those for each read. Yields: 2-tuples with each pair of alignments or, if bundle==True, each bundled list of alignments.
[ "Iterate", "over", "SAM", "aligments", "name", "-", "sorted", "paired", "-", "end" ]
6f7d66e757e610228c33ebf2bb5dc8cc5051c7f0
https://github.com/simon-anders/htseq/blob/6f7d66e757e610228c33ebf2bb5dc8cc5051c7f0/python2/HTSeq/__init__.py#L634-L736
train
238,078
simon-anders/htseq
python3/HTSeq/__init__.py
pair_SAM_alignments_with_buffer
def pair_SAM_alignments_with_buffer( alignments, max_buffer_size=30000000, primary_only=False): '''Iterate over SAM aligments with buffer, position-sorted paired-end Args: alignments (iterator of SAM/BAM alignments): the alignments to wrap max_buffer_size (int): maxmal numer of alignments to keep in memory. primary_only (bool): for each read, consider only the primary line (SAM flag 0x900 = 0). The SAM specification requires one and only one of those for each read. Yields: 2-tuples with each pair of alignments. ''' almnt_buffer = {} ambiguous_pairing_counter = 0 for almnt in alignments: if not almnt.paired_end: raise ValueError( "Sequence of paired-end alignments expected, but got single-end alignment.") if almnt.pe_which == "unknown": raise ValueError( "Cannot process paired-end alignment found with 'unknown' 'pe_which' status.") # FIXME: almnt.not_primary_alignment currently means secondary if primary_only and (almnt.not_primary_alignment or almnt.supplementary): continue matekey = ( almnt.read.name, "second" if almnt.pe_which == "first" else "first", almnt.mate_start.chrom if almnt.mate_aligned else None, almnt.mate_start.pos if almnt.mate_aligned else None, almnt.iv.chrom if almnt.aligned else None, almnt.iv.start if almnt.aligned else None, -almnt.inferred_insert_size if almnt.aligned and almnt.mate_aligned else None) if matekey in almnt_buffer: if len(almnt_buffer[matekey]) == 1: mate = almnt_buffer[matekey][0] del almnt_buffer[matekey] else: mate = almnt_buffer[matekey].pop(0) if ambiguous_pairing_counter == 0: ambiguous_pairing_first_occurance = matekey ambiguous_pairing_counter += 1 if almnt.pe_which == "first": yield (almnt, mate) else: yield (mate, almnt) else: almntkey = ( almnt.read.name, almnt.pe_which, almnt.iv.chrom if almnt.aligned else None, almnt.iv.start if almnt.aligned else None, almnt.mate_start.chrom if almnt.mate_aligned else None, almnt.mate_start.pos if almnt.mate_aligned else None, almnt.inferred_insert_size if almnt.aligned and almnt.mate_aligned else None) if almntkey not in almnt_buffer: almnt_buffer[almntkey] = [almnt] else: almnt_buffer[almntkey].append(almnt) if len(almnt_buffer) > max_buffer_size: raise ValueError( "Maximum alignment buffer size exceeded while pairing SAM alignments.") if len(almnt_buffer) > 0: warnings.warn( "Mate records missing for %d records; first such record: %s." % (len(almnt_buffer), str(list(almnt_buffer.values())[0][0]))) for almnt_list in list(almnt_buffer.values()): for almnt in almnt_list: if almnt.pe_which == "first": yield (almnt, None) else: yield (None, almnt) if ambiguous_pairing_counter > 0: warnings.warn( "Mate pairing was ambiguous for %d records; mate key for first such record: %s." % (ambiguous_pairing_counter, str(ambiguous_pairing_first_occurance)))
python
def pair_SAM_alignments_with_buffer( alignments, max_buffer_size=30000000, primary_only=False): '''Iterate over SAM aligments with buffer, position-sorted paired-end Args: alignments (iterator of SAM/BAM alignments): the alignments to wrap max_buffer_size (int): maxmal numer of alignments to keep in memory. primary_only (bool): for each read, consider only the primary line (SAM flag 0x900 = 0). The SAM specification requires one and only one of those for each read. Yields: 2-tuples with each pair of alignments. ''' almnt_buffer = {} ambiguous_pairing_counter = 0 for almnt in alignments: if not almnt.paired_end: raise ValueError( "Sequence of paired-end alignments expected, but got single-end alignment.") if almnt.pe_which == "unknown": raise ValueError( "Cannot process paired-end alignment found with 'unknown' 'pe_which' status.") # FIXME: almnt.not_primary_alignment currently means secondary if primary_only and (almnt.not_primary_alignment or almnt.supplementary): continue matekey = ( almnt.read.name, "second" if almnt.pe_which == "first" else "first", almnt.mate_start.chrom if almnt.mate_aligned else None, almnt.mate_start.pos if almnt.mate_aligned else None, almnt.iv.chrom if almnt.aligned else None, almnt.iv.start if almnt.aligned else None, -almnt.inferred_insert_size if almnt.aligned and almnt.mate_aligned else None) if matekey in almnt_buffer: if len(almnt_buffer[matekey]) == 1: mate = almnt_buffer[matekey][0] del almnt_buffer[matekey] else: mate = almnt_buffer[matekey].pop(0) if ambiguous_pairing_counter == 0: ambiguous_pairing_first_occurance = matekey ambiguous_pairing_counter += 1 if almnt.pe_which == "first": yield (almnt, mate) else: yield (mate, almnt) else: almntkey = ( almnt.read.name, almnt.pe_which, almnt.iv.chrom if almnt.aligned else None, almnt.iv.start if almnt.aligned else None, almnt.mate_start.chrom if almnt.mate_aligned else None, almnt.mate_start.pos if almnt.mate_aligned else None, almnt.inferred_insert_size if almnt.aligned and almnt.mate_aligned else None) if almntkey not in almnt_buffer: almnt_buffer[almntkey] = [almnt] else: almnt_buffer[almntkey].append(almnt) if len(almnt_buffer) > max_buffer_size: raise ValueError( "Maximum alignment buffer size exceeded while pairing SAM alignments.") if len(almnt_buffer) > 0: warnings.warn( "Mate records missing for %d records; first such record: %s." % (len(almnt_buffer), str(list(almnt_buffer.values())[0][0]))) for almnt_list in list(almnt_buffer.values()): for almnt in almnt_list: if almnt.pe_which == "first": yield (almnt, None) else: yield (None, almnt) if ambiguous_pairing_counter > 0: warnings.warn( "Mate pairing was ambiguous for %d records; mate key for first such record: %s." % (ambiguous_pairing_counter, str(ambiguous_pairing_first_occurance)))
[ "def", "pair_SAM_alignments_with_buffer", "(", "alignments", ",", "max_buffer_size", "=", "30000000", ",", "primary_only", "=", "False", ")", ":", "almnt_buffer", "=", "{", "}", "ambiguous_pairing_counter", "=", "0", "for", "almnt", "in", "alignments", ":", "if", "not", "almnt", ".", "paired_end", ":", "raise", "ValueError", "(", "\"Sequence of paired-end alignments expected, but got single-end alignment.\"", ")", "if", "almnt", ".", "pe_which", "==", "\"unknown\"", ":", "raise", "ValueError", "(", "\"Cannot process paired-end alignment found with 'unknown' 'pe_which' status.\"", ")", "# FIXME: almnt.not_primary_alignment currently means secondary", "if", "primary_only", "and", "(", "almnt", ".", "not_primary_alignment", "or", "almnt", ".", "supplementary", ")", ":", "continue", "matekey", "=", "(", "almnt", ".", "read", ".", "name", ",", "\"second\"", "if", "almnt", ".", "pe_which", "==", "\"first\"", "else", "\"first\"", ",", "almnt", ".", "mate_start", ".", "chrom", "if", "almnt", ".", "mate_aligned", "else", "None", ",", "almnt", ".", "mate_start", ".", "pos", "if", "almnt", ".", "mate_aligned", "else", "None", ",", "almnt", ".", "iv", ".", "chrom", "if", "almnt", ".", "aligned", "else", "None", ",", "almnt", ".", "iv", ".", "start", "if", "almnt", ".", "aligned", "else", "None", ",", "-", "almnt", ".", "inferred_insert_size", "if", "almnt", ".", "aligned", "and", "almnt", ".", "mate_aligned", "else", "None", ")", "if", "matekey", "in", "almnt_buffer", ":", "if", "len", "(", "almnt_buffer", "[", "matekey", "]", ")", "==", "1", ":", "mate", "=", "almnt_buffer", "[", "matekey", "]", "[", "0", "]", "del", "almnt_buffer", "[", "matekey", "]", "else", ":", "mate", "=", "almnt_buffer", "[", "matekey", "]", ".", "pop", "(", "0", ")", "if", "ambiguous_pairing_counter", "==", "0", ":", "ambiguous_pairing_first_occurance", "=", "matekey", "ambiguous_pairing_counter", "+=", "1", "if", "almnt", ".", "pe_which", "==", "\"first\"", ":", "yield", "(", "almnt", ",", "mate", ")", "else", ":", "yield", "(", "mate", ",", "almnt", ")", "else", ":", "almntkey", "=", "(", "almnt", ".", "read", ".", "name", ",", "almnt", ".", "pe_which", ",", "almnt", ".", "iv", ".", "chrom", "if", "almnt", ".", "aligned", "else", "None", ",", "almnt", ".", "iv", ".", "start", "if", "almnt", ".", "aligned", "else", "None", ",", "almnt", ".", "mate_start", ".", "chrom", "if", "almnt", ".", "mate_aligned", "else", "None", ",", "almnt", ".", "mate_start", ".", "pos", "if", "almnt", ".", "mate_aligned", "else", "None", ",", "almnt", ".", "inferred_insert_size", "if", "almnt", ".", "aligned", "and", "almnt", ".", "mate_aligned", "else", "None", ")", "if", "almntkey", "not", "in", "almnt_buffer", ":", "almnt_buffer", "[", "almntkey", "]", "=", "[", "almnt", "]", "else", ":", "almnt_buffer", "[", "almntkey", "]", ".", "append", "(", "almnt", ")", "if", "len", "(", "almnt_buffer", ")", ">", "max_buffer_size", ":", "raise", "ValueError", "(", "\"Maximum alignment buffer size exceeded while pairing SAM alignments.\"", ")", "if", "len", "(", "almnt_buffer", ")", ">", "0", ":", "warnings", ".", "warn", "(", "\"Mate records missing for %d records; first such record: %s.\"", "%", "(", "len", "(", "almnt_buffer", ")", ",", "str", "(", "list", "(", "almnt_buffer", ".", "values", "(", ")", ")", "[", "0", "]", "[", "0", "]", ")", ")", ")", "for", "almnt_list", "in", "list", "(", "almnt_buffer", ".", "values", "(", ")", ")", ":", "for", "almnt", "in", "almnt_list", ":", "if", "almnt", ".", "pe_which", "==", "\"first\"", ":", "yield", "(", "almnt", ",", "None", ")", "else", ":", "yield", "(", "None", ",", "almnt", ")", "if", "ambiguous_pairing_counter", ">", "0", ":", "warnings", ".", "warn", "(", "\"Mate pairing was ambiguous for %d records; mate key for first such record: %s.\"", "%", "(", "ambiguous_pairing_counter", ",", "str", "(", "ambiguous_pairing_first_occurance", ")", ")", ")" ]
Iterate over SAM aligments with buffer, position-sorted paired-end Args: alignments (iterator of SAM/BAM alignments): the alignments to wrap max_buffer_size (int): maxmal numer of alignments to keep in memory. primary_only (bool): for each read, consider only the primary line (SAM flag 0x900 = 0). The SAM specification requires one and only one of those for each read. Yields: 2-tuples with each pair of alignments.
[ "Iterate", "over", "SAM", "aligments", "with", "buffer", "position", "-", "sorted", "paired", "-", "end" ]
6f7d66e757e610228c33ebf2bb5dc8cc5051c7f0
https://github.com/simon-anders/htseq/blob/6f7d66e757e610228c33ebf2bb5dc8cc5051c7f0/python3/HTSeq/__init__.py#L742-L824
train
238,079
sqreen/PyMiniRacer
py_mini_racer/extension/v8_build.py
ensure_v8_src
def ensure_v8_src(): """ Ensure that v8 src are presents and up-to-date """ path = local_path('v8') if not os.path.isdir(path): fetch_v8(path) else: update_v8(path) checkout_v8_version(local_path("v8/v8"), V8_VERSION) dependencies_sync(path)
python
def ensure_v8_src(): """ Ensure that v8 src are presents and up-to-date """ path = local_path('v8') if not os.path.isdir(path): fetch_v8(path) else: update_v8(path) checkout_v8_version(local_path("v8/v8"), V8_VERSION) dependencies_sync(path)
[ "def", "ensure_v8_src", "(", ")", ":", "path", "=", "local_path", "(", "'v8'", ")", "if", "not", "os", ".", "path", ".", "isdir", "(", "path", ")", ":", "fetch_v8", "(", "path", ")", "else", ":", "update_v8", "(", "path", ")", "checkout_v8_version", "(", "local_path", "(", "\"v8/v8\"", ")", ",", "V8_VERSION", ")", "dependencies_sync", "(", "path", ")" ]
Ensure that v8 src are presents and up-to-date
[ "Ensure", "that", "v8", "src", "are", "presents", "and", "up", "-", "to", "-", "date" ]
86747cddb13895ccaba990704ad68e5e059587f9
https://github.com/sqreen/PyMiniRacer/blob/86747cddb13895ccaba990704ad68e5e059587f9/py_mini_racer/extension/v8_build.py#L57-L68
train
238,080
sqreen/PyMiniRacer
wheel_pymalloc.py
get_filenames
def get_filenames(directory): """Get all the file to copy""" for filename in os.listdir(directory): if re.search(r"cp\d{2}mu?-manylinux1_\S+\.whl", filename): yield filename
python
def get_filenames(directory): """Get all the file to copy""" for filename in os.listdir(directory): if re.search(r"cp\d{2}mu?-manylinux1_\S+\.whl", filename): yield filename
[ "def", "get_filenames", "(", "directory", ")", ":", "for", "filename", "in", "os", ".", "listdir", "(", "directory", ")", ":", "if", "re", ".", "search", "(", "r\"cp\\d{2}mu?-manylinux1_\\S+\\.whl\"", ",", "filename", ")", ":", "yield", "filename" ]
Get all the file to copy
[ "Get", "all", "the", "file", "to", "copy" ]
86747cddb13895ccaba990704ad68e5e059587f9
https://github.com/sqreen/PyMiniRacer/blob/86747cddb13895ccaba990704ad68e5e059587f9/wheel_pymalloc.py#L11-L15
train
238,081
sqreen/PyMiniRacer
wheel_pymalloc.py
copy_file
def copy_file(filename): """Copy the file and put the correct tag""" print("Updating file %s" % filename) out_dir = os.path.abspath(DIRECTORY) tags = filename[:-4].split("-") tags[-2] = tags[-2].replace("m", "") new_name = "-".join(tags) + ".whl" wheel_flag = "-".join(tags[2:]) with InWheelCtx(os.path.join(DIRECTORY, filename)) as ctx: info_fname = os.path.join(_dist_info_dir(ctx.path), 'WHEEL') infos = pkginfo.read_pkg_info(info_fname) print("Changing Tag %s to %s" % (infos["Tag"], wheel_flag)) del infos['Tag'] infos.add_header('Tag', wheel_flag) pkginfo.write_pkg_info(info_fname, infos) ctx.out_wheel = os.path.join(out_dir, new_name) print("Saving new wheel into %s" % ctx.out_wheel)
python
def copy_file(filename): """Copy the file and put the correct tag""" print("Updating file %s" % filename) out_dir = os.path.abspath(DIRECTORY) tags = filename[:-4].split("-") tags[-2] = tags[-2].replace("m", "") new_name = "-".join(tags) + ".whl" wheel_flag = "-".join(tags[2:]) with InWheelCtx(os.path.join(DIRECTORY, filename)) as ctx: info_fname = os.path.join(_dist_info_dir(ctx.path), 'WHEEL') infos = pkginfo.read_pkg_info(info_fname) print("Changing Tag %s to %s" % (infos["Tag"], wheel_flag)) del infos['Tag'] infos.add_header('Tag', wheel_flag) pkginfo.write_pkg_info(info_fname, infos) ctx.out_wheel = os.path.join(out_dir, new_name) print("Saving new wheel into %s" % ctx.out_wheel)
[ "def", "copy_file", "(", "filename", ")", ":", "print", "(", "\"Updating file %s\"", "%", "filename", ")", "out_dir", "=", "os", ".", "path", ".", "abspath", "(", "DIRECTORY", ")", "tags", "=", "filename", "[", ":", "-", "4", "]", ".", "split", "(", "\"-\"", ")", "tags", "[", "-", "2", "]", "=", "tags", "[", "-", "2", "]", ".", "replace", "(", "\"m\"", ",", "\"\"", ")", "new_name", "=", "\"-\"", ".", "join", "(", "tags", ")", "+", "\".whl\"", "wheel_flag", "=", "\"-\"", ".", "join", "(", "tags", "[", "2", ":", "]", ")", "with", "InWheelCtx", "(", "os", ".", "path", ".", "join", "(", "DIRECTORY", ",", "filename", ")", ")", "as", "ctx", ":", "info_fname", "=", "os", ".", "path", ".", "join", "(", "_dist_info_dir", "(", "ctx", ".", "path", ")", ",", "'WHEEL'", ")", "infos", "=", "pkginfo", ".", "read_pkg_info", "(", "info_fname", ")", "print", "(", "\"Changing Tag %s to %s\"", "%", "(", "infos", "[", "\"Tag\"", "]", ",", "wheel_flag", ")", ")", "del", "infos", "[", "'Tag'", "]", "infos", ".", "add_header", "(", "'Tag'", ",", "wheel_flag", ")", "pkginfo", ".", "write_pkg_info", "(", "info_fname", ",", "infos", ")", "ctx", ".", "out_wheel", "=", "os", ".", "path", ".", "join", "(", "out_dir", ",", "new_name", ")", "print", "(", "\"Saving new wheel into %s\"", "%", "ctx", ".", "out_wheel", ")" ]
Copy the file and put the correct tag
[ "Copy", "the", "file", "and", "put", "the", "correct", "tag" ]
86747cddb13895ccaba990704ad68e5e059587f9
https://github.com/sqreen/PyMiniRacer/blob/86747cddb13895ccaba990704ad68e5e059587f9/wheel_pymalloc.py#L17-L40
train
238,082
sqreen/PyMiniRacer
py_mini_racer/py_mini_racer.py
is_unicode
def is_unicode(value): """ Check if a value is a valid unicode string, compatible with python 2 and python 3 >>> is_unicode(u'foo') True >>> is_unicode(u'✌') True >>> is_unicode(b'foo') False >>> is_unicode(42) False >>> is_unicode(('abc',)) False """ python_version = sys.version_info[0] if python_version == 2: return isinstance(value, unicode) elif python_version == 3: return isinstance(value, str) else: raise NotImplementedError()
python
def is_unicode(value): """ Check if a value is a valid unicode string, compatible with python 2 and python 3 >>> is_unicode(u'foo') True >>> is_unicode(u'✌') True >>> is_unicode(b'foo') False >>> is_unicode(42) False >>> is_unicode(('abc',)) False """ python_version = sys.version_info[0] if python_version == 2: return isinstance(value, unicode) elif python_version == 3: return isinstance(value, str) else: raise NotImplementedError()
[ "def", "is_unicode", "(", "value", ")", ":", "python_version", "=", "sys", ".", "version_info", "[", "0", "]", "if", "python_version", "==", "2", ":", "return", "isinstance", "(", "value", ",", "unicode", ")", "elif", "python_version", "==", "3", ":", "return", "isinstance", "(", "value", ",", "str", ")", "else", ":", "raise", "NotImplementedError", "(", ")" ]
Check if a value is a valid unicode string, compatible with python 2 and python 3 >>> is_unicode(u'foo') True >>> is_unicode(u'✌') True >>> is_unicode(b'foo') False >>> is_unicode(42) False >>> is_unicode(('abc',)) False
[ "Check", "if", "a", "value", "is", "a", "valid", "unicode", "string", "compatible", "with", "python", "2", "and", "python", "3" ]
86747cddb13895ccaba990704ad68e5e059587f9
https://github.com/sqreen/PyMiniRacer/blob/86747cddb13895ccaba990704ad68e5e059587f9/py_mini_racer/py_mini_racer.py#L59-L80
train
238,083
sqreen/PyMiniRacer
py_mini_racer/py_mini_racer.py
MiniRacer.execute
def execute(self, js_str, timeout=0, max_memory=0): """ Exec the given JS value """ wrapped = "(function(){return (%s)})()" % js_str return self.eval(wrapped, timeout, max_memory)
python
def execute(self, js_str, timeout=0, max_memory=0): """ Exec the given JS value """ wrapped = "(function(){return (%s)})()" % js_str return self.eval(wrapped, timeout, max_memory)
[ "def", "execute", "(", "self", ",", "js_str", ",", "timeout", "=", "0", ",", "max_memory", "=", "0", ")", ":", "wrapped", "=", "\"(function(){return (%s)})()\"", "%", "js_str", "return", "self", ".", "eval", "(", "wrapped", ",", "timeout", ",", "max_memory", ")" ]
Exec the given JS value
[ "Exec", "the", "given", "JS", "value" ]
86747cddb13895ccaba990704ad68e5e059587f9
https://github.com/sqreen/PyMiniRacer/blob/86747cddb13895ccaba990704ad68e5e059587f9/py_mini_racer/py_mini_racer.py#L136-L140
train
238,084
sqreen/PyMiniRacer
py_mini_racer/py_mini_racer.py
MiniRacer.eval
def eval(self, js_str, timeout=0, max_memory=0): """ Eval the JavaScript string """ if is_unicode(js_str): bytes_val = js_str.encode("utf8") else: bytes_val = js_str res = None self.lock.acquire() try: res = self.ext.mr_eval_context(self.ctx, bytes_val, len(bytes_val), ctypes.c_ulong(timeout), ctypes.c_size_t(max_memory)) if bool(res) is False: raise JSConversionException() python_value = res.contents.to_python() return python_value finally: self.lock.release() if res is not None: self.free(res)
python
def eval(self, js_str, timeout=0, max_memory=0): """ Eval the JavaScript string """ if is_unicode(js_str): bytes_val = js_str.encode("utf8") else: bytes_val = js_str res = None self.lock.acquire() try: res = self.ext.mr_eval_context(self.ctx, bytes_val, len(bytes_val), ctypes.c_ulong(timeout), ctypes.c_size_t(max_memory)) if bool(res) is False: raise JSConversionException() python_value = res.contents.to_python() return python_value finally: self.lock.release() if res is not None: self.free(res)
[ "def", "eval", "(", "self", ",", "js_str", ",", "timeout", "=", "0", ",", "max_memory", "=", "0", ")", ":", "if", "is_unicode", "(", "js_str", ")", ":", "bytes_val", "=", "js_str", ".", "encode", "(", "\"utf8\"", ")", "else", ":", "bytes_val", "=", "js_str", "res", "=", "None", "self", ".", "lock", ".", "acquire", "(", ")", "try", ":", "res", "=", "self", ".", "ext", ".", "mr_eval_context", "(", "self", ".", "ctx", ",", "bytes_val", ",", "len", "(", "bytes_val", ")", ",", "ctypes", ".", "c_ulong", "(", "timeout", ")", ",", "ctypes", ".", "c_size_t", "(", "max_memory", ")", ")", "if", "bool", "(", "res", ")", "is", "False", ":", "raise", "JSConversionException", "(", ")", "python_value", "=", "res", ".", "contents", ".", "to_python", "(", ")", "return", "python_value", "finally", ":", "self", ".", "lock", ".", "release", "(", ")", "if", "res", "is", "not", "None", ":", "self", ".", "free", "(", "res", ")" ]
Eval the JavaScript string
[ "Eval", "the", "JavaScript", "string" ]
86747cddb13895ccaba990704ad68e5e059587f9
https://github.com/sqreen/PyMiniRacer/blob/86747cddb13895ccaba990704ad68e5e059587f9/py_mini_racer/py_mini_racer.py#L142-L166
train
238,085
sqreen/PyMiniRacer
py_mini_racer/py_mini_racer.py
MiniRacer.call
def call(self, identifier, *args, **kwargs): """ Call the named function with provided arguments You can pass a custom JSON encoder by passing it in the encoder keyword only argument. """ encoder = kwargs.get('encoder', None) timeout = kwargs.get('timeout', 0) max_memory = kwargs.get('max_memory', 0) json_args = json.dumps(args, separators=(',', ':'), cls=encoder) js = "{identifier}.apply(this, {json_args})" return self.eval(js.format(identifier=identifier, json_args=json_args), timeout, max_memory)
python
def call(self, identifier, *args, **kwargs): """ Call the named function with provided arguments You can pass a custom JSON encoder by passing it in the encoder keyword only argument. """ encoder = kwargs.get('encoder', None) timeout = kwargs.get('timeout', 0) max_memory = kwargs.get('max_memory', 0) json_args = json.dumps(args, separators=(',', ':'), cls=encoder) js = "{identifier}.apply(this, {json_args})" return self.eval(js.format(identifier=identifier, json_args=json_args), timeout, max_memory)
[ "def", "call", "(", "self", ",", "identifier", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "encoder", "=", "kwargs", ".", "get", "(", "'encoder'", ",", "None", ")", "timeout", "=", "kwargs", ".", "get", "(", "'timeout'", ",", "0", ")", "max_memory", "=", "kwargs", ".", "get", "(", "'max_memory'", ",", "0", ")", "json_args", "=", "json", ".", "dumps", "(", "args", ",", "separators", "=", "(", "','", ",", "':'", ")", ",", "cls", "=", "encoder", ")", "js", "=", "\"{identifier}.apply(this, {json_args})\"", "return", "self", ".", "eval", "(", "js", ".", "format", "(", "identifier", "=", "identifier", ",", "json_args", "=", "json_args", ")", ",", "timeout", ",", "max_memory", ")" ]
Call the named function with provided arguments You can pass a custom JSON encoder by passing it in the encoder keyword only argument.
[ "Call", "the", "named", "function", "with", "provided", "arguments", "You", "can", "pass", "a", "custom", "JSON", "encoder", "by", "passing", "it", "in", "the", "encoder", "keyword", "only", "argument", "." ]
86747cddb13895ccaba990704ad68e5e059587f9
https://github.com/sqreen/PyMiniRacer/blob/86747cddb13895ccaba990704ad68e5e059587f9/py_mini_racer/py_mini_racer.py#L168-L180
train
238,086
sqreen/PyMiniRacer
py_mini_racer/py_mini_racer.py
MiniRacer.heap_stats
def heap_stats(self): """ Return heap statistics """ self.lock.acquire() res = self.ext.mr_heap_stats(self.ctx) self.lock.release() python_value = res.contents.to_python() self.free(res) return python_value
python
def heap_stats(self): """ Return heap statistics """ self.lock.acquire() res = self.ext.mr_heap_stats(self.ctx) self.lock.release() python_value = res.contents.to_python() self.free(res) return python_value
[ "def", "heap_stats", "(", "self", ")", ":", "self", ".", "lock", ".", "acquire", "(", ")", "res", "=", "self", ".", "ext", ".", "mr_heap_stats", "(", "self", ".", "ctx", ")", "self", ".", "lock", ".", "release", "(", ")", "python_value", "=", "res", ".", "contents", ".", "to_python", "(", ")", "self", ".", "free", "(", "res", ")", "return", "python_value" ]
Return heap statistics
[ "Return", "heap", "statistics" ]
86747cddb13895ccaba990704ad68e5e059587f9
https://github.com/sqreen/PyMiniRacer/blob/86747cddb13895ccaba990704ad68e5e059587f9/py_mini_racer/py_mini_racer.py#L182-L191
train
238,087
sqreen/PyMiniRacer
py_mini_racer/py_mini_racer.py
MiniRacer.heap_snapshot
def heap_snapshot(self): """ Return heap snapshot """ self.lock.acquire() res = self.ext.mr_heap_snapshot(self.ctx) self.lock.release() python_value = res.contents.to_python() self.free(res) return python_value
python
def heap_snapshot(self): """ Return heap snapshot """ self.lock.acquire() res = self.ext.mr_heap_snapshot(self.ctx) self.lock.release() python_value = res.contents.to_python() self.free(res) return python_value
[ "def", "heap_snapshot", "(", "self", ")", ":", "self", ".", "lock", ".", "acquire", "(", ")", "res", "=", "self", ".", "ext", ".", "mr_heap_snapshot", "(", "self", ".", "ctx", ")", "self", ".", "lock", ".", "release", "(", ")", "python_value", "=", "res", ".", "contents", ".", "to_python", "(", ")", "self", ".", "free", "(", "res", ")", "return", "python_value" ]
Return heap snapshot
[ "Return", "heap", "snapshot" ]
86747cddb13895ccaba990704ad68e5e059587f9
https://github.com/sqreen/PyMiniRacer/blob/86747cddb13895ccaba990704ad68e5e059587f9/py_mini_racer/py_mini_racer.py#L196-L205
train
238,088
sqreen/PyMiniRacer
py_mini_racer/py_mini_racer.py
PythonValue.to_python
def to_python(self): """ Return an object as native Python """ result = None if self.type == PythonTypes.null: result = None elif self.type == PythonTypes.bool: result = self.value == 1 elif self.type == PythonTypes.integer: if self.value is None: result = 0 else: result = ctypes.c_int32(self.value).value elif self.type == PythonTypes.double: result = self._double_value() elif self.type == PythonTypes.str_utf8: buf = ctypes.c_char_p(self.value) ptr = ctypes.cast(buf, ctypes.POINTER(ctypes.c_char)) result = ptr[0:self.len].decode("utf8") elif self.type == PythonTypes.array: if self.len == 0: return [] ary = [] ary_addr = ctypes.c_void_p.from_address(self.value) ptr_to_ary = ctypes.pointer(ary_addr) for i in range(self.len): pval = PythonValue.from_address(ptr_to_ary[i]) ary.append(pval.to_python()) result = ary elif self.type == PythonTypes.hash: if self.len == 0: return {} res = {} hash_ary_addr = ctypes.c_void_p.from_address(self.value) ptr_to_hash = ctypes.pointer(hash_ary_addr) for i in range(self.len): pkey = PythonValue.from_address(ptr_to_hash[i*2]) pval = PythonValue.from_address(ptr_to_hash[i*2+1]) res[pkey.to_python()] = pval.to_python() result = res elif self.type == PythonTypes.function: result = JSFunction() elif self.type == PythonTypes.parse_exception: msg = ctypes.c_char_p(self.value).value raise JSParseException(msg) elif self.type == PythonTypes.execute_exception: msg = ctypes.c_char_p(self.value).value raise JSEvalException(msg.decode('utf-8', errors='replace')) elif self.type == PythonTypes.oom_exception: msg = ctypes.c_char_p(self.value).value raise JSOOMException(msg) elif self.type == PythonTypes.timeout_exception: msg = ctypes.c_char_p(self.value).value raise JSTimeoutException(msg) elif self.type == PythonTypes.date: timestamp = self._double_value() # JS timestamp are milliseconds, in python we are in seconds result = datetime.datetime.utcfromtimestamp(timestamp / 1000.) else: raise WrongReturnTypeException("unknown type %d" % self.type) return result
python
def to_python(self): """ Return an object as native Python """ result = None if self.type == PythonTypes.null: result = None elif self.type == PythonTypes.bool: result = self.value == 1 elif self.type == PythonTypes.integer: if self.value is None: result = 0 else: result = ctypes.c_int32(self.value).value elif self.type == PythonTypes.double: result = self._double_value() elif self.type == PythonTypes.str_utf8: buf = ctypes.c_char_p(self.value) ptr = ctypes.cast(buf, ctypes.POINTER(ctypes.c_char)) result = ptr[0:self.len].decode("utf8") elif self.type == PythonTypes.array: if self.len == 0: return [] ary = [] ary_addr = ctypes.c_void_p.from_address(self.value) ptr_to_ary = ctypes.pointer(ary_addr) for i in range(self.len): pval = PythonValue.from_address(ptr_to_ary[i]) ary.append(pval.to_python()) result = ary elif self.type == PythonTypes.hash: if self.len == 0: return {} res = {} hash_ary_addr = ctypes.c_void_p.from_address(self.value) ptr_to_hash = ctypes.pointer(hash_ary_addr) for i in range(self.len): pkey = PythonValue.from_address(ptr_to_hash[i*2]) pval = PythonValue.from_address(ptr_to_hash[i*2+1]) res[pkey.to_python()] = pval.to_python() result = res elif self.type == PythonTypes.function: result = JSFunction() elif self.type == PythonTypes.parse_exception: msg = ctypes.c_char_p(self.value).value raise JSParseException(msg) elif self.type == PythonTypes.execute_exception: msg = ctypes.c_char_p(self.value).value raise JSEvalException(msg.decode('utf-8', errors='replace')) elif self.type == PythonTypes.oom_exception: msg = ctypes.c_char_p(self.value).value raise JSOOMException(msg) elif self.type == PythonTypes.timeout_exception: msg = ctypes.c_char_p(self.value).value raise JSTimeoutException(msg) elif self.type == PythonTypes.date: timestamp = self._double_value() # JS timestamp are milliseconds, in python we are in seconds result = datetime.datetime.utcfromtimestamp(timestamp / 1000.) else: raise WrongReturnTypeException("unknown type %d" % self.type) return result
[ "def", "to_python", "(", "self", ")", ":", "result", "=", "None", "if", "self", ".", "type", "==", "PythonTypes", ".", "null", ":", "result", "=", "None", "elif", "self", ".", "type", "==", "PythonTypes", ".", "bool", ":", "result", "=", "self", ".", "value", "==", "1", "elif", "self", ".", "type", "==", "PythonTypes", ".", "integer", ":", "if", "self", ".", "value", "is", "None", ":", "result", "=", "0", "else", ":", "result", "=", "ctypes", ".", "c_int32", "(", "self", ".", "value", ")", ".", "value", "elif", "self", ".", "type", "==", "PythonTypes", ".", "double", ":", "result", "=", "self", ".", "_double_value", "(", ")", "elif", "self", ".", "type", "==", "PythonTypes", ".", "str_utf8", ":", "buf", "=", "ctypes", ".", "c_char_p", "(", "self", ".", "value", ")", "ptr", "=", "ctypes", ".", "cast", "(", "buf", ",", "ctypes", ".", "POINTER", "(", "ctypes", ".", "c_char", ")", ")", "result", "=", "ptr", "[", "0", ":", "self", ".", "len", "]", ".", "decode", "(", "\"utf8\"", ")", "elif", "self", ".", "type", "==", "PythonTypes", ".", "array", ":", "if", "self", ".", "len", "==", "0", ":", "return", "[", "]", "ary", "=", "[", "]", "ary_addr", "=", "ctypes", ".", "c_void_p", ".", "from_address", "(", "self", ".", "value", ")", "ptr_to_ary", "=", "ctypes", ".", "pointer", "(", "ary_addr", ")", "for", "i", "in", "range", "(", "self", ".", "len", ")", ":", "pval", "=", "PythonValue", ".", "from_address", "(", "ptr_to_ary", "[", "i", "]", ")", "ary", ".", "append", "(", "pval", ".", "to_python", "(", ")", ")", "result", "=", "ary", "elif", "self", ".", "type", "==", "PythonTypes", ".", "hash", ":", "if", "self", ".", "len", "==", "0", ":", "return", "{", "}", "res", "=", "{", "}", "hash_ary_addr", "=", "ctypes", ".", "c_void_p", ".", "from_address", "(", "self", ".", "value", ")", "ptr_to_hash", "=", "ctypes", ".", "pointer", "(", "hash_ary_addr", ")", "for", "i", "in", "range", "(", "self", ".", "len", ")", ":", "pkey", "=", "PythonValue", ".", "from_address", "(", "ptr_to_hash", "[", "i", "*", "2", "]", ")", "pval", "=", "PythonValue", ".", "from_address", "(", "ptr_to_hash", "[", "i", "*", "2", "+", "1", "]", ")", "res", "[", "pkey", ".", "to_python", "(", ")", "]", "=", "pval", ".", "to_python", "(", ")", "result", "=", "res", "elif", "self", ".", "type", "==", "PythonTypes", ".", "function", ":", "result", "=", "JSFunction", "(", ")", "elif", "self", ".", "type", "==", "PythonTypes", ".", "parse_exception", ":", "msg", "=", "ctypes", ".", "c_char_p", "(", "self", ".", "value", ")", ".", "value", "raise", "JSParseException", "(", "msg", ")", "elif", "self", ".", "type", "==", "PythonTypes", ".", "execute_exception", ":", "msg", "=", "ctypes", ".", "c_char_p", "(", "self", ".", "value", ")", ".", "value", "raise", "JSEvalException", "(", "msg", ".", "decode", "(", "'utf-8'", ",", "errors", "=", "'replace'", ")", ")", "elif", "self", ".", "type", "==", "PythonTypes", ".", "oom_exception", ":", "msg", "=", "ctypes", ".", "c_char_p", "(", "self", ".", "value", ")", ".", "value", "raise", "JSOOMException", "(", "msg", ")", "elif", "self", ".", "type", "==", "PythonTypes", ".", "timeout_exception", ":", "msg", "=", "ctypes", ".", "c_char_p", "(", "self", ".", "value", ")", ".", "value", "raise", "JSTimeoutException", "(", "msg", ")", "elif", "self", ".", "type", "==", "PythonTypes", ".", "date", ":", "timestamp", "=", "self", ".", "_double_value", "(", ")", "# JS timestamp are milliseconds, in python we are in seconds", "result", "=", "datetime", ".", "datetime", ".", "utcfromtimestamp", "(", "timestamp", "/", "1000.", ")", "else", ":", "raise", "WrongReturnTypeException", "(", "\"unknown type %d\"", "%", "self", ".", "type", ")", "return", "result" ]
Return an object as native Python
[ "Return", "an", "object", "as", "native", "Python" ]
86747cddb13895ccaba990704ad68e5e059587f9
https://github.com/sqreen/PyMiniRacer/blob/86747cddb13895ccaba990704ad68e5e059587f9/py_mini_racer/py_mini_racer.py#L248-L308
train
238,089
sqreen/PyMiniRacer
setup.py
libv8_object
def libv8_object(object_name): """ Return a path for object_name which is OS independent """ filename = join(V8_LIB_DIRECTORY, 'out.gn/x64.release/obj/{}'.format(object_name)) if not isfile(filename): filename = join(local_path('vendor/v8/out.gn/libv8/obj/{}'.format(object_name))) if not isfile(filename): filename = join(V8_LIB_DIRECTORY, 'out.gn/x64.release/obj/{}'.format(object_name)) return filename
python
def libv8_object(object_name): """ Return a path for object_name which is OS independent """ filename = join(V8_LIB_DIRECTORY, 'out.gn/x64.release/obj/{}'.format(object_name)) if not isfile(filename): filename = join(local_path('vendor/v8/out.gn/libv8/obj/{}'.format(object_name))) if not isfile(filename): filename = join(V8_LIB_DIRECTORY, 'out.gn/x64.release/obj/{}'.format(object_name)) return filename
[ "def", "libv8_object", "(", "object_name", ")", ":", "filename", "=", "join", "(", "V8_LIB_DIRECTORY", ",", "'out.gn/x64.release/obj/{}'", ".", "format", "(", "object_name", ")", ")", "if", "not", "isfile", "(", "filename", ")", ":", "filename", "=", "join", "(", "local_path", "(", "'vendor/v8/out.gn/libv8/obj/{}'", ".", "format", "(", "object_name", ")", ")", ")", "if", "not", "isfile", "(", "filename", ")", ":", "filename", "=", "join", "(", "V8_LIB_DIRECTORY", ",", "'out.gn/x64.release/obj/{}'", ".", "format", "(", "object_name", ")", ")", "return", "filename" ]
Return a path for object_name which is OS independent
[ "Return", "a", "path", "for", "object_name", "which", "is", "OS", "independent" ]
86747cddb13895ccaba990704ad68e5e059587f9
https://github.com/sqreen/PyMiniRacer/blob/86747cddb13895ccaba990704ad68e5e059587f9/setup.py#L88-L100
train
238,090
sqreen/PyMiniRacer
setup.py
get_static_lib_paths
def get_static_lib_paths(): """ Return the required static libraries path """ libs = [] is_linux = sys.platform.startswith('linux') if is_linux: libs += ['-Wl,--start-group'] libs += get_raw_static_lib_path() if is_linux: libs += ['-Wl,--end-group'] return libs
python
def get_static_lib_paths(): """ Return the required static libraries path """ libs = [] is_linux = sys.platform.startswith('linux') if is_linux: libs += ['-Wl,--start-group'] libs += get_raw_static_lib_path() if is_linux: libs += ['-Wl,--end-group'] return libs
[ "def", "get_static_lib_paths", "(", ")", ":", "libs", "=", "[", "]", "is_linux", "=", "sys", ".", "platform", ".", "startswith", "(", "'linux'", ")", "if", "is_linux", ":", "libs", "+=", "[", "'-Wl,--start-group'", "]", "libs", "+=", "get_raw_static_lib_path", "(", ")", "if", "is_linux", ":", "libs", "+=", "[", "'-Wl,--end-group'", "]", "return", "libs" ]
Return the required static libraries path
[ "Return", "the", "required", "static", "libraries", "path" ]
86747cddb13895ccaba990704ad68e5e059587f9
https://github.com/sqreen/PyMiniRacer/blob/86747cddb13895ccaba990704ad68e5e059587f9/setup.py#L110-L120
train
238,091
ajbosco/dag-factory
dagfactory/dagbuilder.py
DagBuilder.get_dag_params
def get_dag_params(self) -> Dict[str, Any]: """ Merges default config with dag config, sets dag_id, and extropolates dag_start_date :returns: dict of dag parameters """ try: dag_params: Dict[str, Any] = utils.merge_configs(self.dag_config, self.default_config) except Exception as e: raise Exception(f"Failed to merge config with default config, err: {e}") dag_params["dag_id"]: str = self.dag_name try: # ensure that default_args dictionary contains key "start_date" with "datetime" value in specified timezone dag_params["default_args"]["start_date"]: datetime = utils.get_start_date( date_value=dag_params["default_args"]["start_date"], timezone=dag_params["default_args"].get("timezone", "UTC"), ) except KeyError as e: raise Exception(f"{self.dag_name} config is missing start_date, err: {e}") return dag_params
python
def get_dag_params(self) -> Dict[str, Any]: """ Merges default config with dag config, sets dag_id, and extropolates dag_start_date :returns: dict of dag parameters """ try: dag_params: Dict[str, Any] = utils.merge_configs(self.dag_config, self.default_config) except Exception as e: raise Exception(f"Failed to merge config with default config, err: {e}") dag_params["dag_id"]: str = self.dag_name try: # ensure that default_args dictionary contains key "start_date" with "datetime" value in specified timezone dag_params["default_args"]["start_date"]: datetime = utils.get_start_date( date_value=dag_params["default_args"]["start_date"], timezone=dag_params["default_args"].get("timezone", "UTC"), ) except KeyError as e: raise Exception(f"{self.dag_name} config is missing start_date, err: {e}") return dag_params
[ "def", "get_dag_params", "(", "self", ")", "->", "Dict", "[", "str", ",", "Any", "]", ":", "try", ":", "dag_params", ":", "Dict", "[", "str", ",", "Any", "]", "=", "utils", ".", "merge_configs", "(", "self", ".", "dag_config", ",", "self", ".", "default_config", ")", "except", "Exception", "as", "e", ":", "raise", "Exception", "(", "f\"Failed to merge config with default config, err: {e}\"", ")", "dag_params", "[", "\"dag_id\"", "]", ":", "str", "=", "self", ".", "dag_name", "try", ":", "# ensure that default_args dictionary contains key \"start_date\" with \"datetime\" value in specified timezone", "dag_params", "[", "\"default_args\"", "]", "[", "\"start_date\"", "]", ":", "datetime", "=", "utils", ".", "get_start_date", "(", "date_value", "=", "dag_params", "[", "\"default_args\"", "]", "[", "\"start_date\"", "]", ",", "timezone", "=", "dag_params", "[", "\"default_args\"", "]", ".", "get", "(", "\"timezone\"", ",", "\"UTC\"", ")", ",", ")", "except", "KeyError", "as", "e", ":", "raise", "Exception", "(", "f\"{self.dag_name} config is missing start_date, err: {e}\"", ")", "return", "dag_params" ]
Merges default config with dag config, sets dag_id, and extropolates dag_start_date :returns: dict of dag parameters
[ "Merges", "default", "config", "with", "dag", "config", "sets", "dag_id", "and", "extropolates", "dag_start_date" ]
cc7cfe74e62f82859fe38d527e95311a2805723b
https://github.com/ajbosco/dag-factory/blob/cc7cfe74e62f82859fe38d527e95311a2805723b/dagfactory/dagbuilder.py#L24-L43
train
238,092
ajbosco/dag-factory
dagfactory/dagbuilder.py
DagBuilder.make_task
def make_task(operator: str, task_params: Dict[str, Any]) -> BaseOperator: """ Takes an operator and params and creates an instance of that operator. :returns: instance of operator object """ try: # class is a Callable https://stackoverflow.com/a/34578836/3679900 operator_obj: Callable[..., BaseOperator] = import_string(operator) except Exception as e: raise Exception(f"Failed to import operator: {operator}. err: {e}") try: task: BaseOperator = operator_obj(**task_params) except Exception as e: raise Exception(f"Failed to create {operator_obj} task. err: {e}") return task
python
def make_task(operator: str, task_params: Dict[str, Any]) -> BaseOperator: """ Takes an operator and params and creates an instance of that operator. :returns: instance of operator object """ try: # class is a Callable https://stackoverflow.com/a/34578836/3679900 operator_obj: Callable[..., BaseOperator] = import_string(operator) except Exception as e: raise Exception(f"Failed to import operator: {operator}. err: {e}") try: task: BaseOperator = operator_obj(**task_params) except Exception as e: raise Exception(f"Failed to create {operator_obj} task. err: {e}") return task
[ "def", "make_task", "(", "operator", ":", "str", ",", "task_params", ":", "Dict", "[", "str", ",", "Any", "]", ")", "->", "BaseOperator", ":", "try", ":", "# class is a Callable https://stackoverflow.com/a/34578836/3679900", "operator_obj", ":", "Callable", "[", "...", ",", "BaseOperator", "]", "=", "import_string", "(", "operator", ")", "except", "Exception", "as", "e", ":", "raise", "Exception", "(", "f\"Failed to import operator: {operator}. err: {e}\"", ")", "try", ":", "task", ":", "BaseOperator", "=", "operator_obj", "(", "*", "*", "task_params", ")", "except", "Exception", "as", "e", ":", "raise", "Exception", "(", "f\"Failed to create {operator_obj} task. err: {e}\"", ")", "return", "task" ]
Takes an operator and params and creates an instance of that operator. :returns: instance of operator object
[ "Takes", "an", "operator", "and", "params", "and", "creates", "an", "instance", "of", "that", "operator", "." ]
cc7cfe74e62f82859fe38d527e95311a2805723b
https://github.com/ajbosco/dag-factory/blob/cc7cfe74e62f82859fe38d527e95311a2805723b/dagfactory/dagbuilder.py#L46-L61
train
238,093
ajbosco/dag-factory
dagfactory/dagbuilder.py
DagBuilder.build
def build(self) -> Dict[str, Union[str, DAG]]: """ Generates a DAG from the DAG parameters. :returns: dict with dag_id and DAG object :type: Dict[str, Union[str, DAG]] """ dag_params: Dict[str, Any] = self.get_dag_params() dag: DAG = DAG( dag_id=dag_params["dag_id"], schedule_interval=dag_params["schedule_interval"], description=dag_params.get("description", ""), max_active_runs=dag_params.get( "max_active_runs", configuration.conf.getint("core", "max_active_runs_per_dag"), ), default_args=dag_params.get("default_args", {}), ) tasks: Dict[str, Dict[str, Any]] = dag_params["tasks"] # create dictionary to track tasks and set dependencies tasks_dict: Dict[str, BaseOperator] = {} for task_name, task_conf in tasks.items(): task_conf["task_id"]: str = task_name operator: str = task_conf["operator"] task_conf["dag"]: DAG = dag params: Dict[str, Any] = {k: v for k, v in task_conf.items() if k not in SYSTEM_PARAMS} task: BaseOperator = DagBuilder.make_task(operator=operator, task_params=params) tasks_dict[task.task_id]: BaseOperator = task # set task dependencies after creating tasks for task_name, task_conf in tasks.items(): if task_conf.get("dependencies"): source_task: BaseOperator = tasks_dict[task_name] for dep in task_conf["dependencies"]: dep_task: BaseOperator = tasks_dict[dep] source_task.set_upstream(dep_task) return {"dag_id": dag_params["dag_id"], "dag": dag}
python
def build(self) -> Dict[str, Union[str, DAG]]: """ Generates a DAG from the DAG parameters. :returns: dict with dag_id and DAG object :type: Dict[str, Union[str, DAG]] """ dag_params: Dict[str, Any] = self.get_dag_params() dag: DAG = DAG( dag_id=dag_params["dag_id"], schedule_interval=dag_params["schedule_interval"], description=dag_params.get("description", ""), max_active_runs=dag_params.get( "max_active_runs", configuration.conf.getint("core", "max_active_runs_per_dag"), ), default_args=dag_params.get("default_args", {}), ) tasks: Dict[str, Dict[str, Any]] = dag_params["tasks"] # create dictionary to track tasks and set dependencies tasks_dict: Dict[str, BaseOperator] = {} for task_name, task_conf in tasks.items(): task_conf["task_id"]: str = task_name operator: str = task_conf["operator"] task_conf["dag"]: DAG = dag params: Dict[str, Any] = {k: v for k, v in task_conf.items() if k not in SYSTEM_PARAMS} task: BaseOperator = DagBuilder.make_task(operator=operator, task_params=params) tasks_dict[task.task_id]: BaseOperator = task # set task dependencies after creating tasks for task_name, task_conf in tasks.items(): if task_conf.get("dependencies"): source_task: BaseOperator = tasks_dict[task_name] for dep in task_conf["dependencies"]: dep_task: BaseOperator = tasks_dict[dep] source_task.set_upstream(dep_task) return {"dag_id": dag_params["dag_id"], "dag": dag}
[ "def", "build", "(", "self", ")", "->", "Dict", "[", "str", ",", "Union", "[", "str", ",", "DAG", "]", "]", ":", "dag_params", ":", "Dict", "[", "str", ",", "Any", "]", "=", "self", ".", "get_dag_params", "(", ")", "dag", ":", "DAG", "=", "DAG", "(", "dag_id", "=", "dag_params", "[", "\"dag_id\"", "]", ",", "schedule_interval", "=", "dag_params", "[", "\"schedule_interval\"", "]", ",", "description", "=", "dag_params", ".", "get", "(", "\"description\"", ",", "\"\"", ")", ",", "max_active_runs", "=", "dag_params", ".", "get", "(", "\"max_active_runs\"", ",", "configuration", ".", "conf", ".", "getint", "(", "\"core\"", ",", "\"max_active_runs_per_dag\"", ")", ",", ")", ",", "default_args", "=", "dag_params", ".", "get", "(", "\"default_args\"", ",", "{", "}", ")", ",", ")", "tasks", ":", "Dict", "[", "str", ",", "Dict", "[", "str", ",", "Any", "]", "]", "=", "dag_params", "[", "\"tasks\"", "]", "# create dictionary to track tasks and set dependencies", "tasks_dict", ":", "Dict", "[", "str", ",", "BaseOperator", "]", "=", "{", "}", "for", "task_name", ",", "task_conf", "in", "tasks", ".", "items", "(", ")", ":", "task_conf", "[", "\"task_id\"", "]", ":", "str", "=", "task_name", "operator", ":", "str", "=", "task_conf", "[", "\"operator\"", "]", "task_conf", "[", "\"dag\"", "]", ":", "DAG", "=", "dag", "params", ":", "Dict", "[", "str", ",", "Any", "]", "=", "{", "k", ":", "v", "for", "k", ",", "v", "in", "task_conf", ".", "items", "(", ")", "if", "k", "not", "in", "SYSTEM_PARAMS", "}", "task", ":", "BaseOperator", "=", "DagBuilder", ".", "make_task", "(", "operator", "=", "operator", ",", "task_params", "=", "params", ")", "tasks_dict", "[", "task", ".", "task_id", "]", ":", "BaseOperator", "=", "task", "# set task dependencies after creating tasks", "for", "task_name", ",", "task_conf", "in", "tasks", ".", "items", "(", ")", ":", "if", "task_conf", ".", "get", "(", "\"dependencies\"", ")", ":", "source_task", ":", "BaseOperator", "=", "tasks_dict", "[", "task_name", "]", "for", "dep", "in", "task_conf", "[", "\"dependencies\"", "]", ":", "dep_task", ":", "BaseOperator", "=", "tasks_dict", "[", "dep", "]", "source_task", ".", "set_upstream", "(", "dep_task", ")", "return", "{", "\"dag_id\"", ":", "dag_params", "[", "\"dag_id\"", "]", ",", "\"dag\"", ":", "dag", "}" ]
Generates a DAG from the DAG parameters. :returns: dict with dag_id and DAG object :type: Dict[str, Union[str, DAG]]
[ "Generates", "a", "DAG", "from", "the", "DAG", "parameters", "." ]
cc7cfe74e62f82859fe38d527e95311a2805723b
https://github.com/ajbosco/dag-factory/blob/cc7cfe74e62f82859fe38d527e95311a2805723b/dagfactory/dagbuilder.py#L63-L101
train
238,094
ajbosco/dag-factory
dagfactory/utils.py
merge_configs
def merge_configs(config: Dict[str, Any], default_config: Dict[str, Any]) -> Dict[str, Any]: """ Merges a `default` config with DAG config. Used to set default values for a group of DAGs. :param config: config to merge in default values :type config: Dict[str, Any] :param default_config: config to merge default values from :type default_config: Dict[str, Any] :returns: dict with merged configs :type: Dict[str, Any] """ for key in default_config: if key in config: if isinstance(config[key], dict) and isinstance(default_config[key], dict): merge_configs(config[key], default_config[key]) else: config[key]: Any = default_config[key] return config
python
def merge_configs(config: Dict[str, Any], default_config: Dict[str, Any]) -> Dict[str, Any]: """ Merges a `default` config with DAG config. Used to set default values for a group of DAGs. :param config: config to merge in default values :type config: Dict[str, Any] :param default_config: config to merge default values from :type default_config: Dict[str, Any] :returns: dict with merged configs :type: Dict[str, Any] """ for key in default_config: if key in config: if isinstance(config[key], dict) and isinstance(default_config[key], dict): merge_configs(config[key], default_config[key]) else: config[key]: Any = default_config[key] return config
[ "def", "merge_configs", "(", "config", ":", "Dict", "[", "str", ",", "Any", "]", ",", "default_config", ":", "Dict", "[", "str", ",", "Any", "]", ")", "->", "Dict", "[", "str", ",", "Any", "]", ":", "for", "key", "in", "default_config", ":", "if", "key", "in", "config", ":", "if", "isinstance", "(", "config", "[", "key", "]", ",", "dict", ")", "and", "isinstance", "(", "default_config", "[", "key", "]", ",", "dict", ")", ":", "merge_configs", "(", "config", "[", "key", "]", ",", "default_config", "[", "key", "]", ")", "else", ":", "config", "[", "key", "]", ":", "Any", "=", "default_config", "[", "key", "]", "return", "config" ]
Merges a `default` config with DAG config. Used to set default values for a group of DAGs. :param config: config to merge in default values :type config: Dict[str, Any] :param default_config: config to merge default values from :type default_config: Dict[str, Any] :returns: dict with merged configs :type: Dict[str, Any]
[ "Merges", "a", "default", "config", "with", "DAG", "config", ".", "Used", "to", "set", "default", "values", "for", "a", "group", "of", "DAGs", "." ]
cc7cfe74e62f82859fe38d527e95311a2805723b
https://github.com/ajbosco/dag-factory/blob/cc7cfe74e62f82859fe38d527e95311a2805723b/dagfactory/utils.py#L68-L86
train
238,095
ajbosco/dag-factory
dagfactory/dagfactory.py
DagFactory._load_config
def _load_config(config_filepath: str) -> Dict[str, Any]: """ Loads YAML config file to dictionary :returns: dict from YAML config file """ try: config: Dict[str, Any] = yaml.load(stream=open(config_filepath, "r")) except Exception as e: raise Exception(f"Invalid DAG Factory config file; err: {e}") return config
python
def _load_config(config_filepath: str) -> Dict[str, Any]: """ Loads YAML config file to dictionary :returns: dict from YAML config file """ try: config: Dict[str, Any] = yaml.load(stream=open(config_filepath, "r")) except Exception as e: raise Exception(f"Invalid DAG Factory config file; err: {e}") return config
[ "def", "_load_config", "(", "config_filepath", ":", "str", ")", "->", "Dict", "[", "str", ",", "Any", "]", ":", "try", ":", "config", ":", "Dict", "[", "str", ",", "Any", "]", "=", "yaml", ".", "load", "(", "stream", "=", "open", "(", "config_filepath", ",", "\"r\"", ")", ")", "except", "Exception", "as", "e", ":", "raise", "Exception", "(", "f\"Invalid DAG Factory config file; err: {e}\"", ")", "return", "config" ]
Loads YAML config file to dictionary :returns: dict from YAML config file
[ "Loads", "YAML", "config", "file", "to", "dictionary" ]
cc7cfe74e62f82859fe38d527e95311a2805723b
https://github.com/ajbosco/dag-factory/blob/cc7cfe74e62f82859fe38d527e95311a2805723b/dagfactory/dagfactory.py#L30-L40
train
238,096
ajbosco/dag-factory
dagfactory/dagfactory.py
DagFactory.get_dag_configs
def get_dag_configs(self) -> Dict[str, Dict[str, Any]]: """ Returns configuration for each the DAG in factory :returns: dict with configuration for dags """ return {dag: self.config[dag] for dag in self.config.keys() if dag != "default"}
python
def get_dag_configs(self) -> Dict[str, Dict[str, Any]]: """ Returns configuration for each the DAG in factory :returns: dict with configuration for dags """ return {dag: self.config[dag] for dag in self.config.keys() if dag != "default"}
[ "def", "get_dag_configs", "(", "self", ")", "->", "Dict", "[", "str", ",", "Dict", "[", "str", ",", "Any", "]", "]", ":", "return", "{", "dag", ":", "self", ".", "config", "[", "dag", "]", "for", "dag", "in", "self", ".", "config", ".", "keys", "(", ")", "if", "dag", "!=", "\"default\"", "}" ]
Returns configuration for each the DAG in factory :returns: dict with configuration for dags
[ "Returns", "configuration", "for", "each", "the", "DAG", "in", "factory" ]
cc7cfe74e62f82859fe38d527e95311a2805723b
https://github.com/ajbosco/dag-factory/blob/cc7cfe74e62f82859fe38d527e95311a2805723b/dagfactory/dagfactory.py#L42-L48
train
238,097
ajbosco/dag-factory
dagfactory/dagfactory.py
DagFactory.generate_dags
def generate_dags(self, globals: Dict[str, Any]) -> None: """ Generates DAGs from YAML config :param globals: The globals() from the file used to generate DAGs. The dag_id must be passed into globals() for Airflow to import """ dag_configs: Dict[str, Dict[str, Any]] = self.get_dag_configs() default_config: Dict[str, Any] = self.get_default_config() for dag_name, dag_config in dag_configs.items(): dag_builder: DagBuilder = DagBuilder(dag_name=dag_name, dag_config=dag_config, default_config=default_config) try: dag: Dict[str, Union[str, DAG]] = dag_builder.build() except Exception as e: raise Exception( f"Failed to generate dag {dag_name}. make sure config is properly populated. err:{e}" ) globals[dag["dag_id"]]: DAG = dag["dag"]
python
def generate_dags(self, globals: Dict[str, Any]) -> None: """ Generates DAGs from YAML config :param globals: The globals() from the file used to generate DAGs. The dag_id must be passed into globals() for Airflow to import """ dag_configs: Dict[str, Dict[str, Any]] = self.get_dag_configs() default_config: Dict[str, Any] = self.get_default_config() for dag_name, dag_config in dag_configs.items(): dag_builder: DagBuilder = DagBuilder(dag_name=dag_name, dag_config=dag_config, default_config=default_config) try: dag: Dict[str, Union[str, DAG]] = dag_builder.build() except Exception as e: raise Exception( f"Failed to generate dag {dag_name}. make sure config is properly populated. err:{e}" ) globals[dag["dag_id"]]: DAG = dag["dag"]
[ "def", "generate_dags", "(", "self", ",", "globals", ":", "Dict", "[", "str", ",", "Any", "]", ")", "->", "None", ":", "dag_configs", ":", "Dict", "[", "str", ",", "Dict", "[", "str", ",", "Any", "]", "]", "=", "self", ".", "get_dag_configs", "(", ")", "default_config", ":", "Dict", "[", "str", ",", "Any", "]", "=", "self", ".", "get_default_config", "(", ")", "for", "dag_name", ",", "dag_config", "in", "dag_configs", ".", "items", "(", ")", ":", "dag_builder", ":", "DagBuilder", "=", "DagBuilder", "(", "dag_name", "=", "dag_name", ",", "dag_config", "=", "dag_config", ",", "default_config", "=", "default_config", ")", "try", ":", "dag", ":", "Dict", "[", "str", ",", "Union", "[", "str", ",", "DAG", "]", "]", "=", "dag_builder", ".", "build", "(", ")", "except", "Exception", "as", "e", ":", "raise", "Exception", "(", "f\"Failed to generate dag {dag_name}. make sure config is properly populated. err:{e}\"", ")", "globals", "[", "dag", "[", "\"dag_id\"", "]", "]", ":", "DAG", "=", "dag", "[", "\"dag\"", "]" ]
Generates DAGs from YAML config :param globals: The globals() from the file used to generate DAGs. The dag_id must be passed into globals() for Airflow to import
[ "Generates", "DAGs", "from", "YAML", "config" ]
cc7cfe74e62f82859fe38d527e95311a2805723b
https://github.com/ajbosco/dag-factory/blob/cc7cfe74e62f82859fe38d527e95311a2805723b/dagfactory/dagfactory.py#L58-L78
train
238,098
fronzbot/blinkpy
blinkpy/sync_module.py
BlinkSyncModule.attributes
def attributes(self): """Return sync attributes.""" attr = { 'name': self.name, 'id': self.sync_id, 'network_id': self.network_id, 'serial': self.serial, 'status': self.status, 'region': self.region, 'region_id': self.region_id, } return attr
python
def attributes(self): """Return sync attributes.""" attr = { 'name': self.name, 'id': self.sync_id, 'network_id': self.network_id, 'serial': self.serial, 'status': self.status, 'region': self.region, 'region_id': self.region_id, } return attr
[ "def", "attributes", "(", "self", ")", ":", "attr", "=", "{", "'name'", ":", "self", ".", "name", ",", "'id'", ":", "self", ".", "sync_id", ",", "'network_id'", ":", "self", ".", "network_id", ",", "'serial'", ":", "self", ".", "serial", ",", "'status'", ":", "self", ".", "status", ",", "'region'", ":", "self", ".", "region", ",", "'region_id'", ":", "self", ".", "region_id", ",", "}", "return", "attr" ]
Return sync attributes.
[ "Return", "sync", "attributes", "." ]
bfdc1e47bdd84903f1aca653605846f3c99bcfac
https://github.com/fronzbot/blinkpy/blob/bfdc1e47bdd84903f1aca653605846f3c99bcfac/blinkpy/sync_module.py#L41-L52
train
238,099