repository_name
stringlengths
7
55
func_path_in_repository
stringlengths
4
223
func_name
stringlengths
1
134
whole_func_string
stringlengths
75
104k
language
stringclasses
1 value
func_code_string
stringlengths
75
104k
func_code_tokens
listlengths
19
28.4k
func_documentation_string
stringlengths
1
46.9k
func_documentation_tokens
listlengths
1
1.97k
split_name
stringclasses
1 value
func_code_url
stringlengths
87
315
googledatalab/pydatalab
google/datalab/bigquery/commands/_bigquery.py
_extract_cell
def _extract_cell(args, cell_body): """Implements the BigQuery extract magic used to extract query or table data to GCS. The supported syntax is: %bq extract <args> Args: args: the arguments following '%bigquery extract'. """ env = google.datalab.utils.commands.notebook_environment() config = g...
python
def _extract_cell(args, cell_body): """Implements the BigQuery extract magic used to extract query or table data to GCS. The supported syntax is: %bq extract <args> Args: args: the arguments following '%bigquery extract'. """ env = google.datalab.utils.commands.notebook_environment() config = g...
[ "def", "_extract_cell", "(", "args", ",", "cell_body", ")", ":", "env", "=", "google", ".", "datalab", ".", "utils", ".", "commands", ".", "notebook_environment", "(", ")", "config", "=", "google", ".", "datalab", ".", "utils", ".", "commands", ".", "par...
Implements the BigQuery extract magic used to extract query or table data to GCS. The supported syntax is: %bq extract <args> Args: args: the arguments following '%bigquery extract'.
[ "Implements", "the", "BigQuery", "extract", "magic", "used", "to", "extract", "query", "or", "table", "data", "to", "GCS", "." ]
train
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/google/datalab/bigquery/commands/_bigquery.py#L757-L802
googledatalab/pydatalab
google/datalab/bigquery/commands/_bigquery.py
_load_cell
def _load_cell(args, cell_body): """Implements the BigQuery load magic used to load data from GCS to a table. The supported syntax is: %bq load <optional args> Args: args: the arguments following '%bq load'. cell_body: optional contents of the cell interpreted as YAML or JSON. Returns: A ...
python
def _load_cell(args, cell_body): """Implements the BigQuery load magic used to load data from GCS to a table. The supported syntax is: %bq load <optional args> Args: args: the arguments following '%bq load'. cell_body: optional contents of the cell interpreted as YAML or JSON. Returns: A ...
[ "def", "_load_cell", "(", "args", ",", "cell_body", ")", ":", "env", "=", "google", ".", "datalab", ".", "utils", ".", "commands", ".", "notebook_environment", "(", ")", "config", "=", "google", ".", "datalab", ".", "utils", ".", "commands", ".", "parse_...
Implements the BigQuery load magic used to load data from GCS to a table. The supported syntax is: %bq load <optional args> Args: args: the arguments following '%bq load'. cell_body: optional contents of the cell interpreted as YAML or JSON. Returns: A message about whether the load succeed...
[ "Implements", "the", "BigQuery", "load", "magic", "used", "to", "load", "data", "from", "GCS", "to", "a", "table", "." ]
train
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/google/datalab/bigquery/commands/_bigquery.py#L805-L855
googledatalab/pydatalab
google/datalab/bigquery/commands/_bigquery.py
_pipeline_cell
def _pipeline_cell(args, cell_body): """Implements the pipeline subcommand in the %%bq magic. Args: args: the arguments following '%%bq pipeline'. cell_body: Cell contents. """ name = args.get('name') if name is None: raise Exception('Pipeline name was not specified.') impor...
python
def _pipeline_cell(args, cell_body): """Implements the pipeline subcommand in the %%bq magic. Args: args: the arguments following '%%bq pipeline'. cell_body: Cell contents. """ name = args.get('name') if name is None: raise Exception('Pipeline name was not specified.') impor...
[ "def", "_pipeline_cell", "(", "args", ",", "cell_body", ")", ":", "name", "=", "args", ".", "get", "(", "'name'", ")", "if", "name", "is", "None", ":", "raise", "Exception", "(", "'Pipeline name was not specified.'", ")", "import", "google", ".", "datalab", ...
Implements the pipeline subcommand in the %%bq magic. Args: args: the arguments following '%%bq pipeline'. cell_body: Cell contents.
[ "Implements", "the", "pipeline", "subcommand", "in", "the", "%%bq", "magic", ".", "Args", ":", "args", ":", "the", "arguments", "following", "%%bq", "pipeline", ".", "cell_body", ":", "Cell", "contents", "." ]
train
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/google/datalab/bigquery/commands/_bigquery.py#L913-L962
googledatalab/pydatalab
google/datalab/bigquery/commands/_bigquery.py
_create_bigquery_parser
def _create_bigquery_parser(): """ Create the parser for the %bq magics. Note that because we use the func default handler dispatch mechanism of argparse, our handlers can take only one argument which is the parsed args. So we must create closures for the handlers that bind the cell contents and thus must recr...
python
def _create_bigquery_parser(): """ Create the parser for the %bq magics. Note that because we use the func default handler dispatch mechanism of argparse, our handlers can take only one argument which is the parsed args. So we must create closures for the handlers that bind the cell contents and thus must recr...
[ "def", "_create_bigquery_parser", "(", ")", ":", "parser", "=", "google", ".", "datalab", ".", "utils", ".", "commands", ".", "CommandParser", "(", "prog", "=", "'%bq'", ",", "description", "=", "\"\"\"\nExecute various BigQuery-related operations. Use \"%bq <command> -...
Create the parser for the %bq magics. Note that because we use the func default handler dispatch mechanism of argparse, our handlers can take only one argument which is the parsed args. So we must create closures for the handlers that bind the cell contents and thus must recreate this parser for each cell upon...
[ "Create", "the", "parser", "for", "the", "%bq", "magics", "." ]
train
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/google/datalab/bigquery/commands/_bigquery.py#L972-L1021
googledatalab/pydatalab
google/datalab/bigquery/commands/_bigquery.py
bq
def bq(line, cell=None): """Implements the bq cell magic for ipython notebooks. The supported syntax is: %%bq <command> [<args>] <cell> or: %bq <command> [<args>] Use %bq --help for a list of commands, or %bq <command> --help for help on a specific command. """ return google.datalab.utils...
python
def bq(line, cell=None): """Implements the bq cell magic for ipython notebooks. The supported syntax is: %%bq <command> [<args>] <cell> or: %bq <command> [<args>] Use %bq --help for a list of commands, or %bq <command> --help for help on a specific command. """ return google.datalab.utils...
[ "def", "bq", "(", "line", ",", "cell", "=", "None", ")", ":", "return", "google", ".", "datalab", ".", "utils", ".", "commands", ".", "handle_magic_line", "(", "line", ",", "cell", ",", "_bigquery_parser", ")" ]
Implements the bq cell magic for ipython notebooks. The supported syntax is: %%bq <command> [<args>] <cell> or: %bq <command> [<args>] Use %bq --help for a list of commands, or %bq <command> --help for help on a specific command.
[ "Implements", "the", "bq", "cell", "magic", "for", "ipython", "notebooks", "." ]
train
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/google/datalab/bigquery/commands/_bigquery.py#L1028-L1043
googledatalab/pydatalab
google/datalab/bigquery/commands/_bigquery.py
_table_viewer
def _table_viewer(table, rows_per_page=25, fields=None): """ Return a table viewer. This includes a static rendering of the first page of the table, that gets replaced by the charting code in environments where Javascript is executable and BQ is available. Args: table: the table to view. rows_per...
python
def _table_viewer(table, rows_per_page=25, fields=None): """ Return a table viewer. This includes a static rendering of the first page of the table, that gets replaced by the charting code in environments where Javascript is executable and BQ is available. Args: table: the table to view. rows_per...
[ "def", "_table_viewer", "(", "table", ",", "rows_per_page", "=", "25", ",", "fields", "=", "None", ")", ":", "# TODO(gram): rework this to use google.datalab.utils.commands.chart_html", "if", "not", "table", ".", "exists", "(", ")", ":", "raise", "Exception", "(", ...
Return a table viewer. This includes a static rendering of the first page of the table, that gets replaced by the charting code in environments where Javascript is executable and BQ is available. Args: table: the table to view. rows_per_page: how many rows to display at one time. fields: an arra...
[ "Return", "a", "table", "viewer", "." ]
train
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/google/datalab/bigquery/commands/_bigquery.py#L1074-L1186
googledatalab/pydatalab
datalab/bigquery/_udf.py
UDF._build_js
def _build_js(inputs, outputs, name, implementation, support_code): """Creates a BigQuery SQL UDF javascript object. Args: inputs: a list of (name, type) tuples representing the schema of input. outputs: a list of (name, type) tuples representing the schema of the output. name: the name of th...
python
def _build_js(inputs, outputs, name, implementation, support_code): """Creates a BigQuery SQL UDF javascript object. Args: inputs: a list of (name, type) tuples representing the schema of input. outputs: a list of (name, type) tuples representing the schema of the output. name: the name of th...
[ "def", "_build_js", "(", "inputs", ",", "outputs", ",", "name", ",", "implementation", ",", "support_code", ")", ":", "# Construct a comma-separated list of input field names", "# For example, field1,field2,...", "input_fields", "=", "json", ".", "dumps", "(", "[", "f",...
Creates a BigQuery SQL UDF javascript object. Args: inputs: a list of (name, type) tuples representing the schema of input. outputs: a list of (name, type) tuples representing the schema of the output. name: the name of the function implementation: a javascript function defining the UDF log...
[ "Creates", "a", "BigQuery", "SQL", "UDF", "javascript", "object", "." ]
train
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/datalab/bigquery/_udf.py#L59-L84
googledatalab/pydatalab
datalab/bigquery/_sampling.py
Sampling.sampling_query
def sampling_query(sql, fields=None, count=5, sampling=None): """Returns a sampling query for the SQL object. Args: sql: the SQL object to sample fields: an optional list of field names to retrieve. count: an optional count of rows to retrieve which is used if a specific sampling is...
python
def sampling_query(sql, fields=None, count=5, sampling=None): """Returns a sampling query for the SQL object. Args: sql: the SQL object to sample fields: an optional list of field names to retrieve. count: an optional count of rows to retrieve which is used if a specific sampling is...
[ "def", "sampling_query", "(", "sql", ",", "fields", "=", "None", ",", "count", "=", "5", ",", "sampling", "=", "None", ")", ":", "if", "sampling", "is", "None", ":", "sampling", "=", "Sampling", ".", "default", "(", "count", "=", "count", ",", "field...
Returns a sampling query for the SQL object. Args: sql: the SQL object to sample fields: an optional list of field names to retrieve. count: an optional count of rows to retrieve which is used if a specific sampling is not specified. sampling: an optional sampling strategy to appl...
[ "Returns", "a", "sampling", "query", "for", "the", "SQL", "object", "." ]
train
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/datalab/bigquery/_sampling.py#L74-L88
googledatalab/pydatalab
google/datalab/ml/_fasets.py
FacetsOverview._remove_nonascii
def _remove_nonascii(self, df): """Make copy and remove non-ascii characters from it.""" df_copy = df.copy(deep=True) for col in df_copy.columns: if (df_copy[col].dtype == np.dtype('O')): df_copy[col] = df[col].apply( lambda x: re.sub(r'[^\x00-\x7f]', r'', x) if isinstance(x, six.st...
python
def _remove_nonascii(self, df): """Make copy and remove non-ascii characters from it.""" df_copy = df.copy(deep=True) for col in df_copy.columns: if (df_copy[col].dtype == np.dtype('O')): df_copy[col] = df[col].apply( lambda x: re.sub(r'[^\x00-\x7f]', r'', x) if isinstance(x, six.st...
[ "def", "_remove_nonascii", "(", "self", ",", "df", ")", ":", "df_copy", "=", "df", ".", "copy", "(", "deep", "=", "True", ")", "for", "col", "in", "df_copy", ".", "columns", ":", "if", "(", "df_copy", "[", "col", "]", ".", "dtype", "==", "np", "....
Make copy and remove non-ascii characters from it.
[ "Make", "copy", "and", "remove", "non", "-", "ascii", "characters", "from", "it", "." ]
train
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/google/datalab/ml/_fasets.py#L27-L36
googledatalab/pydatalab
google/datalab/ml/_fasets.py
FacetsOverview.plot
def plot(self, data): """ Plots an overview in a list of dataframes Args: data: a dictionary with key the name, and value the dataframe. """ import IPython if not isinstance(data, dict) or not all(isinstance(v, pd.DataFrame) for v in data.values()): raise ValueError('Expect a dictiona...
python
def plot(self, data): """ Plots an overview in a list of dataframes Args: data: a dictionary with key the name, and value the dataframe. """ import IPython if not isinstance(data, dict) or not all(isinstance(v, pd.DataFrame) for v in data.values()): raise ValueError('Expect a dictiona...
[ "def", "plot", "(", "self", ",", "data", ")", ":", "import", "IPython", "if", "not", "isinstance", "(", "data", ",", "dict", ")", "or", "not", "all", "(", "isinstance", "(", "v", ",", "pd", ".", "DataFrame", ")", "for", "v", "in", "data", ".", "v...
Plots an overview in a list of dataframes Args: data: a dictionary with key the name, and value the dataframe.
[ "Plots", "an", "overview", "in", "a", "list", "of", "dataframes" ]
train
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/google/datalab/ml/_fasets.py#L38-L62
googledatalab/pydatalab
google/datalab/ml/_fasets.py
FacetsDiveview.plot
def plot(self, data, height=1000, render_large_data=False): """ Plots a detail view of data. Args: data: a Pandas dataframe. height: the height of the output. """ import IPython if not isinstance(data, pd.DataFrame): raise ValueError('Expect a DataFrame.') if (len(data) > 1...
python
def plot(self, data, height=1000, render_large_data=False): """ Plots a detail view of data. Args: data: a Pandas dataframe. height: the height of the output. """ import IPython if not isinstance(data, pd.DataFrame): raise ValueError('Expect a DataFrame.') if (len(data) > 1...
[ "def", "plot", "(", "self", ",", "data", ",", "height", "=", "1000", ",", "render_large_data", "=", "False", ")", ":", "import", "IPython", "if", "not", "isinstance", "(", "data", ",", "pd", ".", "DataFrame", ")", ":", "raise", "ValueError", "(", "'Exp...
Plots a detail view of data. Args: data: a Pandas dataframe. height: the height of the output.
[ "Plots", "a", "detail", "view", "of", "data", "." ]
train
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/google/datalab/ml/_fasets.py#L68-L95
googledatalab/pydatalab
google/datalab/utils/facets/base_generic_feature_statistics_generator.py
BaseGenericFeatureStatisticsGenerator.ProtoFromDataFrames
def ProtoFromDataFrames(self, dataframes): """Creates a feature statistics proto from a set of pandas dataframes. Args: dataframes: A list of dicts describing tables for each dataset for the proto. Each entry contains a 'table' field of the dataframe of the data and a 'name...
python
def ProtoFromDataFrames(self, dataframes): """Creates a feature statistics proto from a set of pandas dataframes. Args: dataframes: A list of dicts describing tables for each dataset for the proto. Each entry contains a 'table' field of the dataframe of the data and a 'name...
[ "def", "ProtoFromDataFrames", "(", "self", ",", "dataframes", ")", ":", "datasets", "=", "[", "]", "for", "dataframe", "in", "dataframes", ":", "table", "=", "dataframe", "[", "'table'", "]", "table_entries", "=", "{", "}", "for", "col", "in", "table", "...
Creates a feature statistics proto from a set of pandas dataframes. Args: dataframes: A list of dicts describing tables for each dataset for the proto. Each entry contains a 'table' field of the dataframe of the data and a 'name' field to identify the dataset in the proto. ...
[ "Creates", "a", "feature", "statistics", "proto", "from", "a", "set", "of", "pandas", "dataframes", ".", "Args", ":", "dataframes", ":", "A", "list", "of", "dicts", "describing", "tables", "for", "each", "dataset", "for", "the", "proto", ".", "Each", "entr...
train
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/google/datalab/utils/facets/base_generic_feature_statistics_generator.py#L35-L56
googledatalab/pydatalab
google/datalab/utils/facets/base_generic_feature_statistics_generator.py
BaseGenericFeatureStatisticsGenerator.DtypeToType
def DtypeToType(self, dtype): """Converts a Numpy dtype to the FeatureNameStatistics.Type proto enum.""" if dtype.char in np.typecodes['AllFloat']: return self.fs_proto.FLOAT elif (dtype.char in np.typecodes['AllInteger'] or dtype == np.bool or np.issubdtype(dtype, np.datetime64) or ...
python
def DtypeToType(self, dtype): """Converts a Numpy dtype to the FeatureNameStatistics.Type proto enum.""" if dtype.char in np.typecodes['AllFloat']: return self.fs_proto.FLOAT elif (dtype.char in np.typecodes['AllInteger'] or dtype == np.bool or np.issubdtype(dtype, np.datetime64) or ...
[ "def", "DtypeToType", "(", "self", ",", "dtype", ")", ":", "if", "dtype", ".", "char", "in", "np", ".", "typecodes", "[", "'AllFloat'", "]", ":", "return", "self", ".", "fs_proto", ".", "FLOAT", "elif", "(", "dtype", ".", "char", "in", "np", ".", "...
Converts a Numpy dtype to the FeatureNameStatistics.Type proto enum.
[ "Converts", "a", "Numpy", "dtype", "to", "the", "FeatureNameStatistics", ".", "Type", "proto", "enum", "." ]
train
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/google/datalab/utils/facets/base_generic_feature_statistics_generator.py#L58-L67
googledatalab/pydatalab
google/datalab/utils/facets/base_generic_feature_statistics_generator.py
BaseGenericFeatureStatisticsGenerator.DtypeToNumberConverter
def DtypeToNumberConverter(self, dtype): """Converts a Numpy dtype to a converter method if applicable. The converter method takes in a numpy array of objects of the provided dtype and returns a numpy array of the numbers backing that object for statistical analysis. Returns None if no...
python
def DtypeToNumberConverter(self, dtype): """Converts a Numpy dtype to a converter method if applicable. The converter method takes in a numpy array of objects of the provided dtype and returns a numpy array of the numbers backing that object for statistical analysis. Returns None if no...
[ "def", "DtypeToNumberConverter", "(", "self", ",", "dtype", ")", ":", "if", "np", ".", "issubdtype", "(", "dtype", ",", "np", ".", "datetime64", ")", ":", "def", "DatetimesToNumbers", "(", "dt_list", ")", ":", "return", "np", ".", "array", "(", "[", "p...
Converts a Numpy dtype to a converter method if applicable. The converter method takes in a numpy array of objects of the provided dtype and returns a numpy array of the numbers backing that object for statistical analysis. Returns None if no converter is necessary. Args: dtype: ...
[ "Converts", "a", "Numpy", "dtype", "to", "a", "converter", "method", "if", "applicable", ".", "The", "converter", "method", "takes", "in", "a", "numpy", "array", "of", "objects", "of", "the", "provided", "dtype", "and", "returns", "a", "numpy", "array", "o...
train
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/google/datalab/utils/facets/base_generic_feature_statistics_generator.py#L69-L94
googledatalab/pydatalab
google/datalab/utils/facets/base_generic_feature_statistics_generator.py
BaseGenericFeatureStatisticsGenerator.NdarrayToEntry
def NdarrayToEntry(self, x): """Converts an ndarray to the Entry format.""" row_counts = [] for row in x: try: rc = np.count_nonzero(~np.isnan(row)) if rc != 0: row_counts.append(rc) except TypeError: try: row_counts.append(row.size) except Att...
python
def NdarrayToEntry(self, x): """Converts an ndarray to the Entry format.""" row_counts = [] for row in x: try: rc = np.count_nonzero(~np.isnan(row)) if rc != 0: row_counts.append(rc) except TypeError: try: row_counts.append(row.size) except Att...
[ "def", "NdarrayToEntry", "(", "self", ",", "x", ")", ":", "row_counts", "=", "[", "]", "for", "row", "in", "x", ":", "try", ":", "rc", "=", "np", ".", "count_nonzero", "(", "~", "np", ".", "isnan", "(", "row", ")", ")", "if", "rc", "!=", "0", ...
Converts an ndarray to the Entry format.
[ "Converts", "an", "ndarray", "to", "the", "Entry", "format", "." ]
train
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/google/datalab/utils/facets/base_generic_feature_statistics_generator.py#L96-L137
googledatalab/pydatalab
google/datalab/utils/facets/base_generic_feature_statistics_generator.py
BaseGenericFeatureStatisticsGenerator.GetDatasetsProto
def GetDatasetsProto(self, datasets, features=None): """Generates the feature stats proto from dictionaries of feature values. Args: datasets: An array of dictionaries, one per dataset, each one containing: - 'entries': The dictionary of features in the dataset from the parsed exampl...
python
def GetDatasetsProto(self, datasets, features=None): """Generates the feature stats proto from dictionaries of feature values. Args: datasets: An array of dictionaries, one per dataset, each one containing: - 'entries': The dictionary of features in the dataset from the parsed exampl...
[ "def", "GetDatasetsProto", "(", "self", ",", "datasets", ",", "features", "=", "None", ")", ":", "features_seen", "=", "set", "(", ")", "whitelist_features", "=", "set", "(", "features", ")", "if", "features", "else", "None", "all_datasets", "=", "self", "...
Generates the feature stats proto from dictionaries of feature values. Args: datasets: An array of dictionaries, one per dataset, each one containing: - 'entries': The dictionary of features in the dataset from the parsed examples. - 'size': The number of examples parsed for th...
[ "Generates", "the", "feature", "stats", "proto", "from", "dictionaries", "of", "feature", "values", ".", "Args", ":", "datasets", ":", "An", "array", "of", "dictionaries", "one", "per", "dataset", "each", "one", "containing", ":", "-", "entries", ":", "The",...
train
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/google/datalab/utils/facets/base_generic_feature_statistics_generator.py#L139-L286
googledatalab/pydatalab
google/datalab/utils/facets/base_generic_feature_statistics_generator.py
BaseGenericFeatureStatisticsGenerator._PopulateQuantilesHistogram
def _PopulateQuantilesHistogram(self, hist, nums): """Fills in the histogram with quantile information from the provided array. Args: hist: A Histogram proto message to fill in. nums: A list of numbers to create a quantiles histogram from. """ if not nums: return num_quantile_bucke...
python
def _PopulateQuantilesHistogram(self, hist, nums): """Fills in the histogram with quantile information from the provided array. Args: hist: A Histogram proto message to fill in. nums: A list of numbers to create a quantiles histogram from. """ if not nums: return num_quantile_bucke...
[ "def", "_PopulateQuantilesHistogram", "(", "self", ",", "hist", ",", "nums", ")", ":", "if", "not", "nums", ":", "return", "num_quantile_buckets", "=", "10", "quantiles_to_get", "=", "[", "x", "*", "100", "/", "num_quantile_buckets", "for", "x", "in", "range...
Fills in the histogram with quantile information from the provided array. Args: hist: A Histogram proto message to fill in. nums: A list of numbers to create a quantiles histogram from.
[ "Fills", "in", "the", "histogram", "with", "quantile", "information", "from", "the", "provided", "array", ".", "Args", ":", "hist", ":", "A", "Histogram", "proto", "message", "to", "fill", "in", ".", "nums", ":", "A", "list", "of", "numbers", "to", "crea...
train
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/google/datalab/utils/facets/base_generic_feature_statistics_generator.py#L288-L305
googledatalab/pydatalab
solutionbox/structured_data/mltoolbox/_structured_data/trainer/util.py
serving_from_csv_input
def serving_from_csv_input(train_config, args, keep_target): """Read the input features from a placeholder csv string tensor.""" examples = tf.placeholder( dtype=tf.string, shape=(None,), name='csv_input_string') features = parse_example_tensor(examples=examples, ...
python
def serving_from_csv_input(train_config, args, keep_target): """Read the input features from a placeholder csv string tensor.""" examples = tf.placeholder( dtype=tf.string, shape=(None,), name='csv_input_string') features = parse_example_tensor(examples=examples, ...
[ "def", "serving_from_csv_input", "(", "train_config", ",", "args", ",", "keep_target", ")", ":", "examples", "=", "tf", ".", "placeholder", "(", "dtype", "=", "tf", ".", "string", ",", "shape", "=", "(", "None", ",", ")", ",", "name", "=", "'csv_input_st...
Read the input features from a placeholder csv string tensor.
[ "Read", "the", "input", "features", "from", "a", "placeholder", "csv", "string", "tensor", "." ]
train
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/solutionbox/structured_data/mltoolbox/_structured_data/trainer/util.py#L90-L115
googledatalab/pydatalab
solutionbox/structured_data/mltoolbox/_structured_data/trainer/util.py
parse_example_tensor
def parse_example_tensor(examples, train_config, keep_target): """Read the csv files. Args: examples: string tensor train_config: training config keep_target: if true, the target column is expected to exist and it is returned in the features dict. Returns: Dict of feature_name to tensor....
python
def parse_example_tensor(examples, train_config, keep_target): """Read the csv files. Args: examples: string tensor train_config: training config keep_target: if true, the target column is expected to exist and it is returned in the features dict. Returns: Dict of feature_name to tensor....
[ "def", "parse_example_tensor", "(", "examples", ",", "train_config", ",", "keep_target", ")", ":", "csv_header", "=", "[", "]", "if", "keep_target", ":", "csv_header", "=", "train_config", "[", "'csv_header'", "]", "else", ":", "csv_header", "=", "[", "name", ...
Read the csv files. Args: examples: string tensor train_config: training config keep_target: if true, the target column is expected to exist and it is returned in the features dict. Returns: Dict of feature_name to tensor. Target feature is in the dict.
[ "Read", "the", "csv", "files", "." ]
train
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/solutionbox/structured_data/mltoolbox/_structured_data/trainer/util.py#L281-L312
googledatalab/pydatalab
solutionbox/structured_data/mltoolbox/_structured_data/trainer/util.py
read_examples
def read_examples(input_files, batch_size, shuffle, num_epochs=None): """Creates readers and queues for reading example protos.""" files = [] for e in input_files: for path in e.split(','): files.extend(file_io.get_matching_files(path)) thread_count = multiprocessing.cpu_count() # The minimum numbe...
python
def read_examples(input_files, batch_size, shuffle, num_epochs=None): """Creates readers and queues for reading example protos.""" files = [] for e in input_files: for path in e.split(','): files.extend(file_io.get_matching_files(path)) thread_count = multiprocessing.cpu_count() # The minimum numbe...
[ "def", "read_examples", "(", "input_files", ",", "batch_size", ",", "shuffle", ",", "num_epochs", "=", "None", ")", ":", "files", "=", "[", "]", "for", "e", "in", "input_files", ":", "for", "path", "in", "e", ".", "split", "(", "','", ")", ":", "file...
Creates readers and queues for reading example protos.
[ "Creates", "readers", "and", "queues", "for", "reading", "example", "protos", "." ]
train
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/solutionbox/structured_data/mltoolbox/_structured_data/trainer/util.py#L315-L359
googledatalab/pydatalab
solutionbox/structured_data/mltoolbox/_structured_data/trainer/util.py
get_estimator
def get_estimator(output_dir, train_config, args): """Returns a tf learn estimator. We only support {DNN, Linear}Regressor and {DNN, Linear}Classifier. This is controlled by the values of model_type in the args. Args: output_dir: Modes are saved into outputdir/train train_config: our training config ...
python
def get_estimator(output_dir, train_config, args): """Returns a tf learn estimator. We only support {DNN, Linear}Regressor and {DNN, Linear}Classifier. This is controlled by the values of model_type in the args. Args: output_dir: Modes are saved into outputdir/train train_config: our training config ...
[ "def", "get_estimator", "(", "output_dir", ",", "train_config", ",", "args", ")", ":", "# Check the requested mode fits the preprocessed data.", "target_name", "=", "train_config", "[", "'target_column'", "]", "if", "is_classification_model", "(", "args", ".", "model_type...
Returns a tf learn estimator. We only support {DNN, Linear}Regressor and {DNN, Linear}Classifier. This is controlled by the values of model_type in the args. Args: output_dir: Modes are saved into outputdir/train train_config: our training config args: command line parameters Returns: TF lean...
[ "Returns", "a", "tf", "learn", "estimator", "." ]
train
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/solutionbox/structured_data/mltoolbox/_structured_data/trainer/util.py#L367-L445
googledatalab/pydatalab
solutionbox/structured_data/mltoolbox/_structured_data/trainer/util.py
preprocess_input
def preprocess_input(features, target, train_config, preprocess_output_dir, model_type): """Perform some transformations after reading in the input tensors. Args: features: dict of feature_name to tensor target: tensor train_config: our training config object preprocess_output_...
python
def preprocess_input(features, target, train_config, preprocess_output_dir, model_type): """Perform some transformations after reading in the input tensors. Args: features: dict of feature_name to tensor target: tensor train_config: our training config object preprocess_output_...
[ "def", "preprocess_input", "(", "features", ",", "target", ",", "train_config", ",", "preprocess_output_dir", ",", "model_type", ")", ":", "target_name", "=", "train_config", "[", "'target_column'", "]", "key_name", "=", "train_config", "[", "'key_column'", "]", "...
Perform some transformations after reading in the input tensors. Args: features: dict of feature_name to tensor target: tensor train_config: our training config object preprocess_output_dir: folder should contain the vocab files. model_type: the tf model type. Raises: ValueError: if wrong ...
[ "Perform", "some", "transformations", "after", "reading", "in", "the", "input", "tensors", "." ]
train
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/solutionbox/structured_data/mltoolbox/_structured_data/trainer/util.py#L448-L542
googledatalab/pydatalab
solutionbox/structured_data/mltoolbox/_structured_data/trainer/util.py
_scale_tensor
def _scale_tensor(tensor, range_min, range_max, scale_min, scale_max): """Scale a tensor to scale_min to scale_max. Args: tensor: input tensor. Should be a numerical tensor. range_min: min expected value for this feature/tensor. range_max: max expected Value. scale_min: new expected min value. ...
python
def _scale_tensor(tensor, range_min, range_max, scale_min, scale_max): """Scale a tensor to scale_min to scale_max. Args: tensor: input tensor. Should be a numerical tensor. range_min: min expected value for this feature/tensor. range_max: max expected Value. scale_min: new expected min value. ...
[ "def", "_scale_tensor", "(", "tensor", ",", "range_min", ",", "range_max", ",", "scale_min", ",", "scale_max", ")", ":", "if", "range_min", "==", "range_max", ":", "return", "tensor", "float_tensor", "=", "tf", ".", "to_float", "(", "tensor", ")", "scaled_te...
Scale a tensor to scale_min to scale_max. Args: tensor: input tensor. Should be a numerical tensor. range_min: min expected value for this feature/tensor. range_max: max expected Value. scale_min: new expected min value. scale_max: new expected max value. Returns: scaled tensor.
[ "Scale", "a", "tensor", "to", "scale_min", "to", "scale_max", "." ]
train
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/solutionbox/structured_data/mltoolbox/_structured_data/trainer/util.py#L545-L567
googledatalab/pydatalab
solutionbox/structured_data/mltoolbox/_structured_data/trainer/util.py
_tflearn_features
def _tflearn_features(train_config, args): """Builds the tf.learn feature list. All numerical features are just given real_valued_column because all the preprocessing transformations are done in preprocess_input. Categoriacl features are processed here depending if the vocab map (from string to int) was appl...
python
def _tflearn_features(train_config, args): """Builds the tf.learn feature list. All numerical features are just given real_valued_column because all the preprocessing transformations are done in preprocess_input. Categoriacl features are processed here depending if the vocab map (from string to int) was appl...
[ "def", "_tflearn_features", "(", "train_config", ",", "args", ")", ":", "feature_columns", "=", "[", "]", "target_name", "=", "train_config", "[", "'target_column'", "]", "key_name", "=", "train_config", "[", "'key_column'", "]", "for", "name", "in", "train_conf...
Builds the tf.learn feature list. All numerical features are just given real_valued_column because all the preprocessing transformations are done in preprocess_input. Categoriacl features are processed here depending if the vocab map (from string to int) was applied in preprocess_input. Args: train_conf...
[ "Builds", "the", "tf", ".", "learn", "feature", "list", "." ]
train
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/solutionbox/structured_data/mltoolbox/_structured_data/trainer/util.py#L570-L647
googledatalab/pydatalab
solutionbox/structured_data/mltoolbox/_structured_data/trainer/util.py
get_vocabulary
def get_vocabulary(preprocess_output_dir, name): """Loads the vocabulary file as a list of strings. Args: preprocess_output_dir: Should contain the file CATEGORICAL_ANALYSIS % name. name: name of the csv column. Returns: List of strings. Raises: ValueError: if file is missing. """ vocab_f...
python
def get_vocabulary(preprocess_output_dir, name): """Loads the vocabulary file as a list of strings. Args: preprocess_output_dir: Should contain the file CATEGORICAL_ANALYSIS % name. name: name of the csv column. Returns: List of strings. Raises: ValueError: if file is missing. """ vocab_f...
[ "def", "get_vocabulary", "(", "preprocess_output_dir", ",", "name", ")", ":", "vocab_file", "=", "os", ".", "path", ".", "join", "(", "preprocess_output_dir", ",", "CATEGORICAL_ANALYSIS", "%", "name", ")", "if", "not", "file_io", ".", "file_exists", "(", "voca...
Loads the vocabulary file as a list of strings. Args: preprocess_output_dir: Should contain the file CATEGORICAL_ANALYSIS % name. name: name of the csv column. Returns: List of strings. Raises: ValueError: if file is missing.
[ "Loads", "the", "vocabulary", "file", "as", "a", "list", "of", "strings", "." ]
train
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/solutionbox/structured_data/mltoolbox/_structured_data/trainer/util.py#L655-L677
googledatalab/pydatalab
solutionbox/structured_data/mltoolbox/_structured_data/trainer/util.py
merge_metadata
def merge_metadata(preprocess_output_dir, transforms_file): """Merge schema, analysis, and transforms files into one python object. Args: preprocess_output_dir: the output folder of preprocessing. Should contain the schema, and the numerical and categorical analysis files. transforms_file: ...
python
def merge_metadata(preprocess_output_dir, transforms_file): """Merge schema, analysis, and transforms files into one python object. Args: preprocess_output_dir: the output folder of preprocessing. Should contain the schema, and the numerical and categorical analysis files. transforms_file: ...
[ "def", "merge_metadata", "(", "preprocess_output_dir", ",", "transforms_file", ")", ":", "numerical_anlysis_file", "=", "os", ".", "path", ".", "join", "(", "preprocess_output_dir", ",", "NUMERICAL_ANALYSIS", ")", "schema_file", "=", "os", ".", "path", ".", "join"...
Merge schema, analysis, and transforms files into one python object. Args: preprocess_output_dir: the output folder of preprocessing. Should contain the schema, and the numerical and categorical analysis files. transforms_file: the training transforms file. Returns: A dict in the form ...
[ "Merge", "schema", "analysis", "and", "transforms", "files", "into", "one", "python", "object", "." ]
train
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/solutionbox/structured_data/mltoolbox/_structured_data/trainer/util.py#L680-L808
googledatalab/pydatalab
solutionbox/structured_data/mltoolbox/_structured_data/trainer/util.py
validate_metadata
def validate_metadata(train_config): """Perform some checks that the trainig config is correct. Args: train_config: train config as produced by merge_metadata() Raises: ValueError: if columns look wrong. """ # Make sure we have a default for every column if len(train_config['csv_header']) != len(...
python
def validate_metadata(train_config): """Perform some checks that the trainig config is correct. Args: train_config: train config as produced by merge_metadata() Raises: ValueError: if columns look wrong. """ # Make sure we have a default for every column if len(train_config['csv_header']) != len(...
[ "def", "validate_metadata", "(", "train_config", ")", ":", "# Make sure we have a default for every column", "if", "len", "(", "train_config", "[", "'csv_header'", "]", ")", "!=", "len", "(", "train_config", "[", "'csv_defaults'", "]", ")", ":", "raise", "ValueError...
Perform some checks that the trainig config is correct. Args: train_config: train config as produced by merge_metadata() Raises: ValueError: if columns look wrong.
[ "Perform", "some", "checks", "that", "the", "trainig", "config", "is", "correct", "." ]
train
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/solutionbox/structured_data/mltoolbox/_structured_data/trainer/util.py#L811-L838
googledatalab/pydatalab
datalab/context/_project.py
Projects.get_default_id
def get_default_id(credentials=None): """ Get default project id. Returns: the default project id if there is one, or None. """ project_id = _utils.get_project_id() if project_id is None: projects, _ = Projects(credentials)._retrieve_projects(None, 2) if len(projects) == 1: proj...
python
def get_default_id(credentials=None): """ Get default project id. Returns: the default project id if there is one, or None. """ project_id = _utils.get_project_id() if project_id is None: projects, _ = Projects(credentials)._retrieve_projects(None, 2) if len(projects) == 1: proj...
[ "def", "get_default_id", "(", "credentials", "=", "None", ")", ":", "project_id", "=", "_utils", ".", "get_project_id", "(", ")", "if", "project_id", "is", "None", ":", "projects", ",", "_", "=", "Projects", "(", "credentials", ")", ".", "_retrieve_projects"...
Get default project id. Returns: the default project id if there is one, or None.
[ "Get", "default", "project", "id", "." ]
train
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/datalab/context/_project.py#L97-L107
jpvanhal/flask-split
flask_split/core.py
init_app
def init_app(state): """ Prepare the Flask application for Flask-Split. :param state: :class:`BlueprintSetupState` instance """ app = state.app app.config.setdefault('SPLIT_ALLOW_MULTIPLE_EXPERIMENTS', False) app.config.setdefault('SPLIT_DB_FAILOVER', False) app.config.setdefault('SPLI...
python
def init_app(state): """ Prepare the Flask application for Flask-Split. :param state: :class:`BlueprintSetupState` instance """ app = state.app app.config.setdefault('SPLIT_ALLOW_MULTIPLE_EXPERIMENTS', False) app.config.setdefault('SPLIT_DB_FAILOVER', False) app.config.setdefault('SPLI...
[ "def", "init_app", "(", "state", ")", ":", "app", "=", "state", ".", "app", "app", ".", "config", ".", "setdefault", "(", "'SPLIT_ALLOW_MULTIPLE_EXPERIMENTS'", ",", "False", ")", "app", ".", "config", ".", "setdefault", "(", "'SPLIT_DB_FAILOVER'", ",", "Fals...
Prepare the Flask application for Flask-Split. :param state: :class:`BlueprintSetupState` instance
[ "Prepare", "the", "Flask", "application", "for", "Flask", "-", "Split", "." ]
train
https://github.com/jpvanhal/flask-split/blob/52bc9df49b5ce8b0ec436ba09b361a4b0b1793ba/flask_split/core.py#L23-L61
jpvanhal/flask-split
flask_split/core.py
finished
def finished(experiment_name, reset=True): """ Track a conversion. :param experiment_name: Name of the experiment. :param reset: If set to `True` current user's session is reset so that they may start the test again in the future. If set to `False` the user will always see the alternat...
python
def finished(experiment_name, reset=True): """ Track a conversion. :param experiment_name: Name of the experiment. :param reset: If set to `True` current user's session is reset so that they may start the test again in the future. If set to `False` the user will always see the alternat...
[ "def", "finished", "(", "experiment_name", ",", "reset", "=", "True", ")", ":", "if", "_exclude_visitor", "(", ")", ":", "return", "redis", "=", "_get_redis_connection", "(", ")", "try", ":", "experiment", "=", "Experiment", ".", "find", "(", "redis", ",",...
Track a conversion. :param experiment_name: Name of the experiment. :param reset: If set to `True` current user's session is reset so that they may start the test again in the future. If set to `False` the user will always see the alternative they started with. Defaults to `True`.
[ "Track", "a", "conversion", "." ]
train
https://github.com/jpvanhal/flask-split/blob/52bc9df49b5ce8b0ec436ba09b361a4b0b1793ba/flask_split/core.py#L108-L142
jpvanhal/flask-split
flask_split/core.py
_is_robot
def _is_robot(): """ Return `True` if the current visitor is a robot or spider, or `False` otherwise. This function works by comparing the request's user agent with a regular expression. The regular expression can be configured with the ``SPLIT_ROBOT_REGEX`` setting. """ robot_regex = ...
python
def _is_robot(): """ Return `True` if the current visitor is a robot or spider, or `False` otherwise. This function works by comparing the request's user agent with a regular expression. The regular expression can be configured with the ``SPLIT_ROBOT_REGEX`` setting. """ robot_regex = ...
[ "def", "_is_robot", "(", ")", ":", "robot_regex", "=", "current_app", ".", "config", "[", "'SPLIT_ROBOT_REGEX'", "]", "user_agent", "=", "request", ".", "headers", ".", "get", "(", "'User-Agent'", ",", "''", ")", "return", "re", ".", "search", "(", "robot_...
Return `True` if the current visitor is a robot or spider, or `False` otherwise. This function works by comparing the request's user agent with a regular expression. The regular expression can be configured with the ``SPLIT_ROBOT_REGEX`` setting.
[ "Return", "True", "if", "the", "current", "visitor", "is", "a", "robot", "or", "spider", "or", "False", "otherwise", "." ]
train
https://github.com/jpvanhal/flask-split/blob/52bc9df49b5ce8b0ec436ba09b361a4b0b1793ba/flask_split/core.py#L206-L217
jpvanhal/flask-split
flask_split/models.py
Experiment.start_time
def start_time(self): """The start time of this experiment.""" t = self.redis.hget('experiment_start_times', self.name) if t: return datetime.strptime(t, '%Y-%m-%dT%H:%M:%S')
python
def start_time(self): """The start time of this experiment.""" t = self.redis.hget('experiment_start_times', self.name) if t: return datetime.strptime(t, '%Y-%m-%dT%H:%M:%S')
[ "def", "start_time", "(", "self", ")", ":", "t", "=", "self", ".", "redis", ".", "hget", "(", "'experiment_start_times'", ",", "self", ".", "name", ")", "if", "t", ":", "return", "datetime", ".", "strptime", "(", "t", ",", "'%Y-%m-%dT%H:%M:%S'", ")" ]
The start time of this experiment.
[ "The", "start", "time", "of", "this", "experiment", "." ]
train
https://github.com/jpvanhal/flask-split/blob/52bc9df49b5ce8b0ec436ba09b361a4b0b1793ba/flask_split/models.py#L163-L167
jpvanhal/flask-split
flask_split/models.py
Experiment.reset
def reset(self): """Delete all data for this experiment.""" for alternative in self.alternatives: alternative.reset() self.reset_winner() self.increment_version()
python
def reset(self): """Delete all data for this experiment.""" for alternative in self.alternatives: alternative.reset() self.reset_winner() self.increment_version()
[ "def", "reset", "(", "self", ")", ":", "for", "alternative", "in", "self", ".", "alternatives", ":", "alternative", ".", "reset", "(", ")", "self", ".", "reset_winner", "(", ")", "self", ".", "increment_version", "(", ")" ]
Delete all data for this experiment.
[ "Delete", "all", "data", "for", "this", "experiment", "." ]
train
https://github.com/jpvanhal/flask-split/blob/52bc9df49b5ce8b0ec436ba09b361a4b0b1793ba/flask_split/models.py#L211-L216
jpvanhal/flask-split
flask_split/models.py
Experiment.delete
def delete(self): """Delete this experiment and all its data.""" for alternative in self.alternatives: alternative.delete() self.reset_winner() self.redis.srem('experiments', self.name) self.redis.delete(self.name) self.increment_version()
python
def delete(self): """Delete this experiment and all its data.""" for alternative in self.alternatives: alternative.delete() self.reset_winner() self.redis.srem('experiments', self.name) self.redis.delete(self.name) self.increment_version()
[ "def", "delete", "(", "self", ")", ":", "for", "alternative", "in", "self", ".", "alternatives", ":", "alternative", ".", "delete", "(", ")", "self", ".", "reset_winner", "(", ")", "self", ".", "redis", ".", "srem", "(", "'experiments'", ",", "self", "...
Delete this experiment and all its data.
[ "Delete", "this", "experiment", "and", "all", "its", "data", "." ]
train
https://github.com/jpvanhal/flask-split/blob/52bc9df49b5ce8b0ec436ba09b361a4b0b1793ba/flask_split/models.py#L218-L225
jpvanhal/flask-split
flask_split/utils.py
_get_redis_connection
def _get_redis_connection(): """ Return a Redis connection based on the Flask application's configuration. The connection parameters are retrieved from `REDIS_URL` configuration variable. :return: an instance of :class:`redis.Connection` """ url = current_app.config.get('REDIS_URL', 'redis...
python
def _get_redis_connection(): """ Return a Redis connection based on the Flask application's configuration. The connection parameters are retrieved from `REDIS_URL` configuration variable. :return: an instance of :class:`redis.Connection` """ url = current_app.config.get('REDIS_URL', 'redis...
[ "def", "_get_redis_connection", "(", ")", ":", "url", "=", "current_app", ".", "config", ".", "get", "(", "'REDIS_URL'", ",", "'redis://localhost:6379'", ")", "return", "redis", ".", "from_url", "(", "url", ",", "decode_responses", "=", "True", ")" ]
Return a Redis connection based on the Flask application's configuration. The connection parameters are retrieved from `REDIS_URL` configuration variable. :return: an instance of :class:`redis.Connection`
[ "Return", "a", "Redis", "connection", "based", "on", "the", "Flask", "application", "s", "configuration", "." ]
train
https://github.com/jpvanhal/flask-split/blob/52bc9df49b5ce8b0ec436ba09b361a4b0b1793ba/flask_split/utils.py#L24-L34
jpvanhal/flask-split
flask_split/views.py
set_experiment_winner
def set_experiment_winner(experiment): """Mark an alternative as the winner of the experiment.""" redis = _get_redis_connection() experiment = Experiment.find(redis, experiment) if experiment: alternative_name = request.form.get('alternative') alternative = Alternative(redis, alternative...
python
def set_experiment_winner(experiment): """Mark an alternative as the winner of the experiment.""" redis = _get_redis_connection() experiment = Experiment.find(redis, experiment) if experiment: alternative_name = request.form.get('alternative') alternative = Alternative(redis, alternative...
[ "def", "set_experiment_winner", "(", "experiment", ")", ":", "redis", "=", "_get_redis_connection", "(", ")", "experiment", "=", "Experiment", ".", "find", "(", "redis", ",", "experiment", ")", "if", "experiment", ":", "alternative_name", "=", "request", ".", ...
Mark an alternative as the winner of the experiment.
[ "Mark", "an", "alternative", "as", "the", "winner", "of", "the", "experiment", "." ]
train
https://github.com/jpvanhal/flask-split/blob/52bc9df49b5ce8b0ec436ba09b361a4b0b1793ba/flask_split/views.py#L44-L53
jpvanhal/flask-split
flask_split/views.py
reset_experiment
def reset_experiment(experiment): """Delete all data for an experiment.""" redis = _get_redis_connection() experiment = Experiment.find(redis, experiment) if experiment: experiment.reset() return redirect(url_for('.index'))
python
def reset_experiment(experiment): """Delete all data for an experiment.""" redis = _get_redis_connection() experiment = Experiment.find(redis, experiment) if experiment: experiment.reset() return redirect(url_for('.index'))
[ "def", "reset_experiment", "(", "experiment", ")", ":", "redis", "=", "_get_redis_connection", "(", ")", "experiment", "=", "Experiment", ".", "find", "(", "redis", ",", "experiment", ")", "if", "experiment", ":", "experiment", ".", "reset", "(", ")", "retur...
Delete all data for an experiment.
[ "Delete", "all", "data", "for", "an", "experiment", "." ]
train
https://github.com/jpvanhal/flask-split/blob/52bc9df49b5ce8b0ec436ba09b361a4b0b1793ba/flask_split/views.py#L57-L63
jpvanhal/flask-split
flask_split/views.py
delete_experiment
def delete_experiment(experiment): """Delete an experiment and all its data.""" redis = _get_redis_connection() experiment = Experiment.find(redis, experiment) if experiment: experiment.delete() return redirect(url_for('.index'))
python
def delete_experiment(experiment): """Delete an experiment and all its data.""" redis = _get_redis_connection() experiment = Experiment.find(redis, experiment) if experiment: experiment.delete() return redirect(url_for('.index'))
[ "def", "delete_experiment", "(", "experiment", ")", ":", "redis", "=", "_get_redis_connection", "(", ")", "experiment", "=", "Experiment", ".", "find", "(", "redis", ",", "experiment", ")", "if", "experiment", ":", "experiment", ".", "delete", "(", ")", "ret...
Delete an experiment and all its data.
[ "Delete", "an", "experiment", "and", "all", "its", "data", "." ]
train
https://github.com/jpvanhal/flask-split/blob/52bc9df49b5ce8b0ec436ba09b361a4b0b1793ba/flask_split/views.py#L67-L73
tobami/littlechef
littlechef/chef.py
save_config
def save_config(node, force=False): """Saves node configuration if no nodes/hostname.json exists, or force=True, it creates one it also saves to tmp_node.json """ filepath = os.path.join("nodes", env.host_string + ".json") tmp_filename = 'tmp_{0}.json'.format(env.host_string) files_to_creat...
python
def save_config(node, force=False): """Saves node configuration if no nodes/hostname.json exists, or force=True, it creates one it also saves to tmp_node.json """ filepath = os.path.join("nodes", env.host_string + ".json") tmp_filename = 'tmp_{0}.json'.format(env.host_string) files_to_creat...
[ "def", "save_config", "(", "node", ",", "force", "=", "False", ")", ":", "filepath", "=", "os", ".", "path", ".", "join", "(", "\"nodes\"", ",", "env", ".", "host_string", "+", "\".json\"", ")", "tmp_filename", "=", "'tmp_{0}.json'", ".", "format", "(", ...
Saves node configuration if no nodes/hostname.json exists, or force=True, it creates one it also saves to tmp_node.json
[ "Saves", "node", "configuration", "if", "no", "nodes", "/", "hostname", ".", "json", "exists", "or", "force", "=", "True", "it", "creates", "one", "it", "also", "saves", "to", "tmp_node", ".", "json" ]
train
https://github.com/tobami/littlechef/blob/aab8c94081b38100a69cc100bc4278ae7419c58e/littlechef/chef.py#L36-L52
tobami/littlechef
littlechef/chef.py
_get_ipaddress
def _get_ipaddress(node): """Adds the ipaddress attribute to the given node object if not already present and it is correctly given by ohai Returns True if ipaddress is added, False otherwise """ if "ipaddress" not in node: with settings(hide('stdout'), warn_only=True): output =...
python
def _get_ipaddress(node): """Adds the ipaddress attribute to the given node object if not already present and it is correctly given by ohai Returns True if ipaddress is added, False otherwise """ if "ipaddress" not in node: with settings(hide('stdout'), warn_only=True): output =...
[ "def", "_get_ipaddress", "(", "node", ")", ":", "if", "\"ipaddress\"", "not", "in", "node", ":", "with", "settings", "(", "hide", "(", "'stdout'", ")", ",", "warn_only", "=", "True", ")", ":", "output", "=", "sudo", "(", "'ohai -l warn ipaddress'", ")", ...
Adds the ipaddress attribute to the given node object if not already present and it is correctly given by ohai Returns True if ipaddress is added, False otherwise
[ "Adds", "the", "ipaddress", "attribute", "to", "the", "given", "node", "object", "if", "not", "already", "present", "and", "it", "is", "correctly", "given", "by", "ohai", "Returns", "True", "if", "ipaddress", "is", "added", "False", "otherwise" ]
train
https://github.com/tobami/littlechef/blob/aab8c94081b38100a69cc100bc4278ae7419c58e/littlechef/chef.py#L55-L71
tobami/littlechef
littlechef/chef.py
sync_node
def sync_node(node): """Builds, synchronizes and configures a node. It also injects the ipaddress to the node's config file if not already existent. """ if node.get('dummy') or 'dummy' in node.get('tags', []): lib.print_header("Skipping dummy: {0}".format(env.host)) return False ...
python
def sync_node(node): """Builds, synchronizes and configures a node. It also injects the ipaddress to the node's config file if not already existent. """ if node.get('dummy') or 'dummy' in node.get('tags', []): lib.print_header("Skipping dummy: {0}".format(env.host)) return False ...
[ "def", "sync_node", "(", "node", ")", ":", "if", "node", ".", "get", "(", "'dummy'", ")", "or", "'dummy'", "in", "node", ".", "get", "(", "'tags'", ",", "[", "]", ")", ":", "lib", ".", "print_header", "(", "\"Skipping dummy: {0}\"", ".", "format", "(...
Builds, synchronizes and configures a node. It also injects the ipaddress to the node's config file if not already existent.
[ "Builds", "synchronizes", "and", "configures", "a", "node", ".", "It", "also", "injects", "the", "ipaddress", "to", "the", "node", "s", "config", "file", "if", "not", "already", "existent", "." ]
train
https://github.com/tobami/littlechef/blob/aab8c94081b38100a69cc100bc4278ae7419c58e/littlechef/chef.py#L86-L110
tobami/littlechef
littlechef/chef.py
_synchronize_node
def _synchronize_node(configfile, node): """Performs the Synchronize step of a Chef run: Uploads all cookbooks, all roles and all databags to a node and add the patch for data bags Returns the node object of the node which is about to be configured, or None if this node object cannot be found. ...
python
def _synchronize_node(configfile, node): """Performs the Synchronize step of a Chef run: Uploads all cookbooks, all roles and all databags to a node and add the patch for data bags Returns the node object of the node which is about to be configured, or None if this node object cannot be found. ...
[ "def", "_synchronize_node", "(", "configfile", ",", "node", ")", ":", "msg", "=", "\"Synchronizing nodes, environments, roles, cookbooks and data bags...\"", "if", "env", ".", "parallel", ":", "msg", "=", "\"[{0}]: {1}\"", ".", "format", "(", "env", ".", "host_string"...
Performs the Synchronize step of a Chef run: Uploads all cookbooks, all roles and all databags to a node and add the patch for data bags Returns the node object of the node which is about to be configured, or None if this node object cannot be found.
[ "Performs", "the", "Synchronize", "step", "of", "a", "Chef", "run", ":", "Uploads", "all", "cookbooks", "all", "roles", "and", "all", "databags", "to", "a", "node", "and", "add", "the", "patch", "for", "data", "bags" ]
train
https://github.com/tobami/littlechef/blob/aab8c94081b38100a69cc100bc4278ae7419c58e/littlechef/chef.py#L113-L189
tobami/littlechef
littlechef/chef.py
build_dct
def build_dct(dic, keys, value): """Builds a dictionary with arbitrary depth out of a key list""" key = keys.pop(0) if len(keys): dic.setdefault(key, {}) build_dct(dic[key], keys, value) else: # Transform cookbook default attribute strings into proper booleans if value ==...
python
def build_dct(dic, keys, value): """Builds a dictionary with arbitrary depth out of a key list""" key = keys.pop(0) if len(keys): dic.setdefault(key, {}) build_dct(dic[key], keys, value) else: # Transform cookbook default attribute strings into proper booleans if value ==...
[ "def", "build_dct", "(", "dic", ",", "keys", ",", "value", ")", ":", "key", "=", "keys", ".", "pop", "(", "0", ")", "if", "len", "(", "keys", ")", ":", "dic", ".", "setdefault", "(", "key", ",", "{", "}", ")", "build_dct", "(", "dic", "[", "k...
Builds a dictionary with arbitrary depth out of a key list
[ "Builds", "a", "dictionary", "with", "arbitrary", "depth", "out", "of", "a", "key", "list" ]
train
https://github.com/tobami/littlechef/blob/aab8c94081b38100a69cc100bc4278ae7419c58e/littlechef/chef.py#L192-L205
tobami/littlechef
littlechef/chef.py
update_dct
def update_dct(dic1, dic2): """Merges two dictionaries recursively dic2 will have preference over dic1 """ for key, val in dic2.items(): if isinstance(val, dict): dic1.setdefault(key, {}) update_dct(dic1[key], val) else: dic1[key] = val
python
def update_dct(dic1, dic2): """Merges two dictionaries recursively dic2 will have preference over dic1 """ for key, val in dic2.items(): if isinstance(val, dict): dic1.setdefault(key, {}) update_dct(dic1[key], val) else: dic1[key] = val
[ "def", "update_dct", "(", "dic1", ",", "dic2", ")", ":", "for", "key", ",", "val", "in", "dic2", ".", "items", "(", ")", ":", "if", "isinstance", "(", "val", ",", "dict", ")", ":", "dic1", ".", "setdefault", "(", "key", ",", "{", "}", ")", "upd...
Merges two dictionaries recursively dic2 will have preference over dic1
[ "Merges", "two", "dictionaries", "recursively", "dic2", "will", "have", "preference", "over", "dic1" ]
train
https://github.com/tobami/littlechef/blob/aab8c94081b38100a69cc100bc4278ae7419c58e/littlechef/chef.py#L208-L218
tobami/littlechef
littlechef/chef.py
_add_automatic_attributes
def _add_automatic_attributes(node): """Adds some of Chef's automatic attributes: http://wiki.opscode.com/display/chef/Recipes#Recipes -CommonAutomaticAttributes """ node['fqdn'] = node['name'] node['hostname'] = node['fqdn'].split('.')[0] node['domain'] = ".".join(node['fqdn'].spli...
python
def _add_automatic_attributes(node): """Adds some of Chef's automatic attributes: http://wiki.opscode.com/display/chef/Recipes#Recipes -CommonAutomaticAttributes """ node['fqdn'] = node['name'] node['hostname'] = node['fqdn'].split('.')[0] node['domain'] = ".".join(node['fqdn'].spli...
[ "def", "_add_automatic_attributes", "(", "node", ")", ":", "node", "[", "'fqdn'", "]", "=", "node", "[", "'name'", "]", "node", "[", "'hostname'", "]", "=", "node", "[", "'fqdn'", "]", ".", "split", "(", "'.'", ")", "[", "0", "]", "node", "[", "'do...
Adds some of Chef's automatic attributes: http://wiki.opscode.com/display/chef/Recipes#Recipes -CommonAutomaticAttributes
[ "Adds", "some", "of", "Chef", "s", "automatic", "attributes", ":", "http", ":", "//", "wiki", ".", "opscode", ".", "com", "/", "display", "/", "chef", "/", "Recipes#Recipes", "-", "CommonAutomaticAttributes" ]
train
https://github.com/tobami/littlechef/blob/aab8c94081b38100a69cc100bc4278ae7419c58e/littlechef/chef.py#L221-L229
tobami/littlechef
littlechef/chef.py
_add_merged_attributes
def _add_merged_attributes(node, all_recipes, all_roles): """Merges attributes from cookbooks, node and roles Chef Attribute precedence: http://docs.opscode.com/essentials_cookbook_attribute_files.html#attribute-precedence LittleChef implements, in precedence order: - Cookbook default -...
python
def _add_merged_attributes(node, all_recipes, all_roles): """Merges attributes from cookbooks, node and roles Chef Attribute precedence: http://docs.opscode.com/essentials_cookbook_attribute_files.html#attribute-precedence LittleChef implements, in precedence order: - Cookbook default -...
[ "def", "_add_merged_attributes", "(", "node", ",", "all_recipes", ",", "all_roles", ")", ":", "# Get cookbooks from extended recipes", "attributes", "=", "{", "}", "for", "recipe", "in", "node", "[", "'recipes'", "]", ":", "# Find this recipe", "found", "=", "Fals...
Merges attributes from cookbooks, node and roles Chef Attribute precedence: http://docs.opscode.com/essentials_cookbook_attribute_files.html#attribute-precedence LittleChef implements, in precedence order: - Cookbook default - Environment default - Role default - Node normal...
[ "Merges", "attributes", "from", "cookbooks", "node", "and", "roles" ]
train
https://github.com/tobami/littlechef/blob/aab8c94081b38100a69cc100bc4278ae7419c58e/littlechef/chef.py#L232-L300
tobami/littlechef
littlechef/chef.py
build_node_data_bag
def build_node_data_bag(): """Builds one 'node' data bag item per file found in the 'nodes' directory Automatic attributes for a node item: 'id': It adds data bag 'id', same as filename but with underscores 'name': same as the filename 'fqdn': same as the filename (LittleChef filenames ...
python
def build_node_data_bag(): """Builds one 'node' data bag item per file found in the 'nodes' directory Automatic attributes for a node item: 'id': It adds data bag 'id', same as filename but with underscores 'name': same as the filename 'fqdn': same as the filename (LittleChef filenames ...
[ "def", "build_node_data_bag", "(", ")", ":", "nodes", "=", "lib", ".", "get_nodes", "(", ")", "node_data_bag_path", "=", "os", ".", "path", ".", "join", "(", "'data_bags'", ",", "'node'", ")", "# In case there are leftovers", "remove_local_node_data_bag", "(", "...
Builds one 'node' data bag item per file found in the 'nodes' directory Automatic attributes for a node item: 'id': It adds data bag 'id', same as filename but with underscores 'name': same as the filename 'fqdn': same as the filename (LittleChef filenames should be fqdns) 'hostname...
[ "Builds", "one", "node", "data", "bag", "item", "per", "file", "found", "in", "the", "nodes", "directory" ]
train
https://github.com/tobami/littlechef/blob/aab8c94081b38100a69cc100bc4278ae7419c58e/littlechef/chef.py#L303-L352
tobami/littlechef
littlechef/chef.py
remove_local_node_data_bag
def remove_local_node_data_bag(): """Removes generated 'node' data_bag locally""" node_data_bag_path = os.path.join('data_bags', 'node') if os.path.exists(node_data_bag_path): shutil.rmtree(node_data_bag_path)
python
def remove_local_node_data_bag(): """Removes generated 'node' data_bag locally""" node_data_bag_path = os.path.join('data_bags', 'node') if os.path.exists(node_data_bag_path): shutil.rmtree(node_data_bag_path)
[ "def", "remove_local_node_data_bag", "(", ")", ":", "node_data_bag_path", "=", "os", ".", "path", ".", "join", "(", "'data_bags'", ",", "'node'", ")", "if", "os", ".", "path", ".", "exists", "(", "node_data_bag_path", ")", ":", "shutil", ".", "rmtree", "("...
Removes generated 'node' data_bag locally
[ "Removes", "generated", "node", "data_bag", "locally" ]
train
https://github.com/tobami/littlechef/blob/aab8c94081b38100a69cc100bc4278ae7419c58e/littlechef/chef.py#L355-L359
tobami/littlechef
littlechef/chef.py
ensure_berksfile_cookbooks_are_installed
def ensure_berksfile_cookbooks_are_installed(): """Run 'berks vendor' to berksfile cookbooks directory""" msg = "Vendoring cookbooks from Berksfile {0} to directory {1}..." print(msg.format(env.berksfile, env.berksfile_cookbooks_directory)) run_vendor = True cookbooks_dir = env.berksfile_cookbooks_...
python
def ensure_berksfile_cookbooks_are_installed(): """Run 'berks vendor' to berksfile cookbooks directory""" msg = "Vendoring cookbooks from Berksfile {0} to directory {1}..." print(msg.format(env.berksfile, env.berksfile_cookbooks_directory)) run_vendor = True cookbooks_dir = env.berksfile_cookbooks_...
[ "def", "ensure_berksfile_cookbooks_are_installed", "(", ")", ":", "msg", "=", "\"Vendoring cookbooks from Berksfile {0} to directory {1}...\"", "print", "(", "msg", ".", "format", "(", "env", ".", "berksfile", ",", "env", ".", "berksfile_cookbooks_directory", ")", ")", ...
Run 'berks vendor' to berksfile cookbooks directory
[ "Run", "berks", "vendor", "to", "berksfile", "cookbooks", "directory" ]
train
https://github.com/tobami/littlechef/blob/aab8c94081b38100a69cc100bc4278ae7419c58e/littlechef/chef.py#L362-L388
tobami/littlechef
littlechef/chef.py
_remove_remote_node_data_bag
def _remove_remote_node_data_bag(): """Removes generated 'node' data_bag from the remote node""" node_data_bag_path = os.path.join(env.node_work_path, 'data_bags', 'node') if exists(node_data_bag_path): sudo("rm -rf {0}".format(node_data_bag_path))
python
def _remove_remote_node_data_bag(): """Removes generated 'node' data_bag from the remote node""" node_data_bag_path = os.path.join(env.node_work_path, 'data_bags', 'node') if exists(node_data_bag_path): sudo("rm -rf {0}".format(node_data_bag_path))
[ "def", "_remove_remote_node_data_bag", "(", ")", ":", "node_data_bag_path", "=", "os", ".", "path", ".", "join", "(", "env", ".", "node_work_path", ",", "'data_bags'", ",", "'node'", ")", "if", "exists", "(", "node_data_bag_path", ")", ":", "sudo", "(", "\"r...
Removes generated 'node' data_bag from the remote node
[ "Removes", "generated", "node", "data_bag", "from", "the", "remote", "node" ]
train
https://github.com/tobami/littlechef/blob/aab8c94081b38100a69cc100bc4278ae7419c58e/littlechef/chef.py#L391-L395
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"...
Remove remote data bags, so it won't leak any sensitive information
[ "Remove", "remote", "data", "bags", "so", "it", "won", "t", "leak", "any", "sensitive", "information" ]
train
https://github.com/tobami/littlechef/blob/aab8c94081b38100a69cc100bc4278ae7419c58e/littlechef/chef.py#L397-L401
tobami/littlechef
littlechef/chef.py
_add_environment_lib
def _add_environment_lib(): """Adds the chef_solo_envs cookbook, which provides a library that adds environment attribute compatibility for chef-solo v10 NOTE: Chef 10 only """ # Create extra cookbook dir lib_path = os.path.join(env.node_work_path, cookbook_paths[0], ...
python
def _add_environment_lib(): """Adds the chef_solo_envs cookbook, which provides a library that adds environment attribute compatibility for chef-solo v10 NOTE: Chef 10 only """ # Create extra cookbook dir lib_path = os.path.join(env.node_work_path, cookbook_paths[0], ...
[ "def", "_add_environment_lib", "(", ")", ":", "# Create extra cookbook dir", "lib_path", "=", "os", ".", "path", ".", "join", "(", "env", ".", "node_work_path", ",", "cookbook_paths", "[", "0", "]", ",", "'chef_solo_envs'", ",", "'libraries'", ")", "with", "hi...
Adds the chef_solo_envs cookbook, which provides a library that adds environment attribute compatibility for chef-solo v10 NOTE: Chef 10 only
[ "Adds", "the", "chef_solo_envs", "cookbook", "which", "provides", "a", "library", "that", "adds", "environment", "attribute", "compatibility", "for", "chef", "-", "solo", "v10", "NOTE", ":", "Chef", "10", "only" ]
train
https://github.com/tobami/littlechef/blob/aab8c94081b38100a69cc100bc4278ae7419c58e/littlechef/chef.py#L415-L428
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): ...
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): ...
[ "def", "_configure_node", "(", ")", ":", "print", "(", "\"\"", ")", "msg", "=", "\"Cooking...\"", "if", "env", ".", "parallel", ":", "msg", "=", "\"[{0}]: {1}\"", ".", "format", "(", "env", ".", "host_string", ",", "msg", ")", "print", "(", "msg", ")",...
Exectutes chef-solo to apply roles and recipes to a node
[ "Exectutes", "chef", "-", "solo", "to", "apply", "roles", "and", "recipes", "to", "a", "node" ]
train
https://github.com/tobami/littlechef/blob/aab8c94081b38100a69cc100bc4278ae7419c58e/littlechef/chef.py#L431-L474
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", res...
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", res...
[ "def", "_resolve_hostname", "(", "name", ")", ":", "if", "env", ".", "ssh_config", "is", "None", ":", "return", "name", "elif", "not", "os", ".", "path", ".", "exists", "(", "os", ".", "path", ".", "join", "(", "\"nodes\"", ",", "name", "+", "\".json...
Returns resolved hostname using the ssh config
[ "Returns", "resolved", "hostname", "using", "the", "ssh", "config" ]
train
https://github.com/tobami/littlechef/blob/aab8c94081b38100a69cc100bc4278ae7419c58e/littlechef/lib.py#L31-L39
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()) ...
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()) ...
[ "def", "get_environment", "(", "name", ")", ":", "if", "name", "==", "\"_default\"", ":", "return", "env_from_template", "(", "name", ")", "filename", "=", "os", ".", "path", ".", "join", "(", "\"environments\"", ",", "name", "+", "\".json\"", ")", "try", ...
Returns a JSON environment file as a dictionary
[ "Returns", "a", "JSON", "environment", "file", "as", "a", "dictionary" ]
train
https://github.com/tobami/littlechef/blob/aab8c94081b38100a69cc100bc4278ae7419c58e/littlechef/lib.py#L62-L76
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('environment...
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('environment...
[ "def", "get_environments", "(", ")", ":", "envs", "=", "[", "]", "for", "root", ",", "subfolders", ",", "files", "in", "os", ".", "walk", "(", "'environments'", ")", ":", "for", "filename", "in", "files", ":", "if", "filename", ".", "endswith", "(", ...
Gets all environments found in the 'environments' directory
[ "Gets", "all", "environments", "found", "in", "the", "environments", "directory" ]
train
https://github.com/tobami/littlechef/blob/aab8c94081b38100a69cc100bc4278ae7419c58e/littlechef/lib.py#L79-L88
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 ...
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 ...
[ "def", "get_node", "(", "name", ",", "merged", "=", "False", ")", ":", "if", "merged", ":", "node_path", "=", "os", ".", "path", ".", "join", "(", "\"data_bags\"", ",", "\"node\"", ",", "name", ".", "replace", "(", "'.'", ",", "'_'", ")", "+", "\"....
Returns a JSON node file as a dictionary
[ "Returns", "a", "JSON", "node", "file", "as", "a", "dictionary" ]
train
https://github.com/tobami/littlechef/blob/aab8c94081b38100a69cc100bc4278ae7419c58e/littlechef/lib.py#L91-L113
tobami/littlechef
littlechef/lib.py
get_nodes
def get_nodes(environment=None): """Gets all nodes found in the nodes/ directory""" if not os.path.exists('nodes'): return [] nodes = [] for filename in sorted( [f for f in os.listdir('nodes') if (not os.path.isdir(f) and f.endswith(".json") and not f.st...
python
def get_nodes(environment=None): """Gets all nodes found in the nodes/ directory""" if not os.path.exists('nodes'): return [] nodes = [] for filename in sorted( [f for f in os.listdir('nodes') if (not os.path.isdir(f) and f.endswith(".json") and not f.st...
[ "def", "get_nodes", "(", "environment", "=", "None", ")", ":", "if", "not", "os", ".", "path", ".", "exists", "(", "'nodes'", ")", ":", "return", "[", "]", "nodes", "=", "[", "]", "for", "filename", "in", "sorted", "(", "[", "f", "for", "f", "in"...
Gets all nodes found in the nodes/ directory
[ "Gets", "all", "nodes", "found", "in", "the", "nodes", "/", "directory" ]
train
https://github.com/tobami/littlechef/blob/aab8c94081b38100a69cc100bc4278ae7419c58e/littlechef/lib.py#L116-L129
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_role...
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_role...
[ "def", "get_nodes_with_role", "(", "role_name", ",", "environment", "=", "None", ")", ":", "prefix_search", "=", "role_name", ".", "endswith", "(", "\"*\"", ")", "if", "prefix_search", ":", "role_name", "=", "role_name", ".", "rstrip", "(", "\"*\"", ")", "fo...
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" ]
train
https://github.com/tobami/littlechef/blob/aab8c94081b38100a69cc100bc4278ae7419c58e/littlechef/lib.py#L132-L147
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 ...
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 ...
[ "def", "get_nodes_with_tag", "(", "tag", ",", "environment", "=", "None", ",", "include_guests", "=", "False", ")", ":", "nodes", "=", "get_nodes", "(", "environment", ")", "nodes_mapping", "=", "dict", "(", "(", "n", "[", "'name'", "]", ",", "n", ")", ...
Get all nodes which include a given tag
[ "Get", "all", "nodes", "which", "include", "a", "given", "tag" ]
train
https://github.com/tobami/littlechef/blob/aab8c94081b38100a69cc100bc4278ae7419c58e/littlechef/lib.py#L150-L171
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): reci...
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): reci...
[ "def", "get_nodes_with_recipe", "(", "recipe_name", ",", "environment", "=", "None", ")", ":", "prefix_search", "=", "recipe_name", ".", "endswith", "(", "\"*\"", ")", "if", "prefix_search", ":", "recipe_name", "=", "recipe_name", ".", "rstrip", "(", "\"*\"", ...
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" ]
train
https://github.com/tobami/littlechef/blob/aab8c94081b38100a69cc100bc4278ae7419c58e/littlechef/lib.py#L174-L191
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}'.form...
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}'.form...
[ "def", "print_node", "(", "node", ",", "detailed", "=", "False", ")", ":", "nodename", "=", "node", "[", "'name'", "]", "print", "(", "colors", ".", "yellow", "(", "\"\\n\"", "+", "nodename", ")", ")", "# Roles", "if", "detailed", ":", "for", "role", ...
Pretty prints the given node
[ "Pretty", "prints", "the", "given", "node" ]
train
https://github.com/tobami/littlechef/blob/aab8c94081b38100a69cc100bc4278ae7419c58e/littlechef/lib.py#L194-L216
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}...
Prints all the given nodes
[ "Prints", "all", "the", "given", "nodes" ]
train
https://github.com/tobami/littlechef/blob/aab8c94081b38100a69cc100bc4278ae7419c58e/littlechef/lib.py#L219-L225
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') ...
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') ...
[ "def", "_generate_metadata", "(", "path", ",", "cookbook_path", ",", "name", ")", ":", "global", "knife_installed", "if", "not", "knife_installed", ":", "return", "metadata_path_rb", "=", "os", ".", "path", ".", "join", "(", "path", ",", "'metadata.rb'", ")", ...
Checks whether metadata.rb has changed and regenerate metadata.json
[ "Checks", "whether", "metadata", ".", "rb", "has", "changed", "and", "regenerate", "metadata", ".", "json" ]
train
https://github.com/tobami/littlechef/blob/aab8c94081b38100a69cc100bc4278ae7419c58e/littlechef/lib.py#L228-L268
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) ...
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) ...
[ "def", "get_recipes_in_cookbook", "(", "name", ")", ":", "recipes", "=", "{", "}", "path", "=", "None", "cookbook_exists", "=", "False", "metadata_exists", "=", "False", "for", "cookbook_path", "in", "cookbook_paths", ":", "path", "=", "os", ".", "path", "."...
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" ]
train
https://github.com/tobami/littlechef/blob/aab8c94081b38100a69cc100bc4278ae7419c58e/littlechef/lib.py#L271-L348
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", ...
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" ]
train
https://github.com/tobami/littlechef/blob/aab8c94081b38100a69cc100bc4278ae7419c58e/littlechef/lib.py#L357-L364
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 d...
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 d...
[ "def", "get_recipes", "(", ")", ":", "dirnames", "=", "set", "(", ")", "for", "path", "in", "cookbook_paths", ":", "dirnames", ".", "update", "(", "[", "d", "for", "d", "in", "os", ".", "listdir", "(", "path", ")", "if", "os", ".", "path", ".", "...
Gets all recipes found in the cookbook directories
[ "Gets", "all", "recipes", "found", "in", "the", "cookbook", "directories" ]
train
https://github.com/tobami/littlechef/blob/aab8c94081b38100a69cc100bc4278ae7419c58e/littlechef/lib.py#L367-L376
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'])) ...
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'])) ...
[ "def", "print_recipe", "(", "recipe", ")", ":", "print", "(", "colors", ".", "yellow", "(", "\"\\n{0}\"", ".", "format", "(", "recipe", "[", "'name'", "]", ")", ")", ")", "print", "\" description: {0}\"", ".", "format", "(", "recipe", "[", "'description'...
Pretty prints the given recipe
[ "Pretty", "prints", "the", "given", "recipe" ]
train
https://github.com/tobami/littlechef/blob/aab8c94081b38100a69cc100bc4278ae7419c58e/littlechef/lib.py#L379-L385
tobami/littlechef
littlechef/lib.py
get_roles_in_node
def get_roles_in_node(node, recursive=False, depth=0): """Returns a list of roles found in the run_list of a node * recursive: True feches roles recursively * depth: Keeps track of recursion depth """ LIMIT = 5 roles = [] for elem in node.get('run_list', []): if elem.startswith("rol...
python
def get_roles_in_node(node, recursive=False, depth=0): """Returns a list of roles found in the run_list of a node * recursive: True feches roles recursively * depth: Keeps track of recursion depth """ LIMIT = 5 roles = [] for elem in node.get('run_list', []): if elem.startswith("rol...
[ "def", "get_roles_in_node", "(", "node", ",", "recursive", "=", "False", ",", "depth", "=", "0", ")", ":", "LIMIT", "=", "5", "roles", "=", "[", "]", "for", "elem", "in", "node", ".", "get", "(", "'run_list'", ",", "[", "]", ")", ":", "if", "elem...
Returns a list of roles found in the run_list of a node * recursive: True feches roles recursively * depth: Keeps track of recursion depth
[ "Returns", "a", "list", "of", "roles", "found", "in", "the", "run_list", "of", "a", "node", "*", "recursive", ":", "True", "feches", "roles", "recursively", "*", "depth", ":", "Keeps", "track", "of", "recursion", "depth" ]
train
https://github.com/tobami/littlechef/blob/aab8c94081b38100a69cc100bc4278ae7419c58e/littlechef/lib.py#L393-L410
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 ...
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 ...
[ "def", "_get_role", "(", "rolename", ")", ":", "path", "=", "os", ".", "path", ".", "join", "(", "'roles'", ",", "rolename", "+", "'.json'", ")", "if", "not", "os", ".", "path", ".", "exists", "(", "path", ")", ":", "abort", "(", "\"Couldn't read rol...
Reads and parses a file containing a role
[ "Reads", "and", "parses", "a", "file", "containing", "a", "role" ]
train
https://github.com/tobami/littlechef/blob/aab8c94081b38100a69cc100bc4278ae7419c58e/littlechef/lib.py#L413-L426
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')]) ...
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')]) ...
[ "def", "get_roles", "(", ")", ":", "roles", "=", "[", "]", "for", "root", ",", "subfolders", ",", "files", "in", "os", ".", "walk", "(", "'roles'", ")", ":", "for", "filename", "in", "files", ":", "if", "filename", ".", "endswith", "(", "\".json\"", ...
Gets all roles found in the 'roles' directory
[ "Gets", "all", "roles", "found", "in", "the", "roles", "directory" ]
train
https://github.com/tobami/littlechef/blob/aab8c94081b38100a69cc100bc4278ae7419c58e/littlechef/lib.py#L429-L438
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_attri...
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_attri...
[ "def", "print_role", "(", "role", ",", "detailed", "=", "True", ")", ":", "if", "detailed", ":", "print", "(", "colors", ".", "yellow", "(", "role", ".", "get", "(", "'fullname'", ")", ")", ")", "else", ":", "print", "(", "\" Role: {0}\"", ".", "for...
Pretty prints the given role
[ "Pretty", "prints", "the", "given", "role" ]
train
https://github.com/tobami/littlechef/blob/aab8c94081b38100a69cc100bc4278ae7419c58e/littlechef/lib.py#L441-L457
tobami/littlechef
littlechef/lib.py
get_plugins
def get_plugins(): """Gets available plugins by looking into the plugins/ directory""" if os.path.exists('plugins'): for filename in sorted([f for f in os.listdir('plugins') if not os.path.isdir(f) and f.endswith(".py")]): plugin_name = filename[:-3] try: ...
python
def get_plugins(): """Gets available plugins by looking into the plugins/ directory""" if os.path.exists('plugins'): for filename in sorted([f for f in os.listdir('plugins') if not os.path.isdir(f) and f.endswith(".py")]): plugin_name = filename[:-3] try: ...
[ "def", "get_plugins", "(", ")", ":", "if", "os", ".", "path", ".", "exists", "(", "'plugins'", ")", ":", "for", "filename", "in", "sorted", "(", "[", "f", "for", "f", "in", "os", ".", "listdir", "(", "'plugins'", ")", "if", "not", "os", ".", "pat...
Gets available plugins by looking into the plugins/ directory
[ "Gets", "available", "plugins", "by", "looking", "into", "the", "plugins", "/", "directory" ]
train
https://github.com/tobami/littlechef/blob/aab8c94081b38100a69cc100bc4278ae7419c58e/littlechef/lib.py#L467-L479
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) ...
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) ...
[ "def", "import_plugin", "(", "name", ")", ":", "path", "=", "os", ".", "path", ".", "join", "(", "\"plugins\"", ",", "name", "+", "\".py\"", ")", "try", ":", "with", "open", "(", "path", ",", "'rb'", ")", "as", "f", ":", "try", ":", "plugin", "="...
Imports plugin python module
[ "Imports", "plugin", "python", "module" ]
train
https://github.com/tobami/littlechef/blob/aab8c94081b38100a69cc100bc4278ae7419c58e/littlechef/lib.py#L482-L499
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}"'.fo...
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}"'.fo...
[ "def", "get_cookbook_path", "(", "cookbook_name", ")", ":", "for", "cookbook_path", "in", "cookbook_paths", ":", "path", "=", "os", ".", "path", ".", "join", "(", "cookbook_path", ",", "cookbook_name", ")", "if", "os", ".", "path", ".", "exists", "(", "pat...
Returns path to the cookbook for the given cookbook name
[ "Returns", "path", "to", "the", "cookbook", "for", "the", "given", "cookbook", "name" ]
train
https://github.com/tobami/littlechef/blob/aab8c94081b38100a69cc100bc4278ae7419c58e/littlechef/lib.py#L502-L508
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) e...
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) e...
[ "def", "global_confirm", "(", "question", ",", "default", "=", "True", ")", ":", "if", "env", ".", "abort_on_prompts", ":", "return", "True", "original_parallel", "=", "env", ".", "parallel", "env", ".", "parallel", "=", "False", "result", "=", "confirm", ...
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" ]
train
https://github.com/tobami/littlechef/blob/aab8c94081b38100a69cc100bc4278ae7419c58e/littlechef/lib.py#L511-L521
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" ]
train
https://github.com/tobami/littlechef/blob/aab8c94081b38100a69cc100bc4278ae7419c58e/littlechef/lib.py#L524-L527
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"...
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"...
[ "def", "get_margin", "(", "length", ")", ":", "if", "length", ">", "23", ":", "margin_left", "=", "\"\\t\"", "chars", "=", "1", "elif", "length", ">", "15", ":", "margin_left", "=", "\"\\t\\t\"", "chars", "=", "2", "elif", "length", ">", "7", ":", "m...
Add enough tabs to align in two columns
[ "Add", "enough", "tabs", "to", "align", "in", "two", "columns" ]
train
https://github.com/tobami/littlechef/blob/aab8c94081b38100a69cc100bc4278ae7419c58e/littlechef/lib.py#L535-L549
tobami/littlechef
littlechef/solo.py
install
def install(version): """Install Chef using the omnibus installer""" url = "https://www.chef.io/chef/install.sh" with hide('stdout', 'running'): local("""python -c "import urllib; print urllib.urlopen('{0}').read()"' ' > /tmp/install.sh""".format(url)) put('/tmp/install.sh', '/...
python
def install(version): """Install Chef using the omnibus installer""" url = "https://www.chef.io/chef/install.sh" with hide('stdout', 'running'): local("""python -c "import urllib; print urllib.urlopen('{0}').read()"' ' > /tmp/install.sh""".format(url)) put('/tmp/install.sh', '/...
[ "def", "install", "(", "version", ")", ":", "url", "=", "\"https://www.chef.io/chef/install.sh\"", "with", "hide", "(", "'stdout'", ",", "'running'", ")", ":", "local", "(", "\"\"\"python -c \"import urllib; print urllib.urlopen('{0}').read()\"'\n ' > /tmp/install....
Install Chef using the omnibus installer
[ "Install", "Chef", "using", "the", "omnibus", "installer" ]
train
https://github.com/tobami/littlechef/blob/aab8c94081b38100a69cc100bc4278ae7419c58e/littlechef/solo.py#L29-L39
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) ...
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) ...
[ "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", ")", "...
Deploy chef-solo specific files
[ "Deploy", "chef", "-", "solo", "specific", "files" ]
train
https://github.com/tobami/littlechef/blob/aab8c94081b38100a69cc100bc4278ae7419c58e/littlechef/solo.py#L42-L99
tobami/littlechef
plugins/save_ip.py
parse_ip
def parse_ip(text): """Extract an IPv4 IP from a text string Uses an IP Address Regex: http://www.regular-expressions.info/examples.html """ ip_matches = re.findall(r'\b\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\b', text) ip = ip_matches[0] if ip_matches else None return ip
python
def parse_ip(text): """Extract an IPv4 IP from a text string Uses an IP Address Regex: http://www.regular-expressions.info/examples.html """ ip_matches = re.findall(r'\b\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\b', text) ip = ip_matches[0] if ip_matches else None return ip
[ "def", "parse_ip", "(", "text", ")", ":", "ip_matches", "=", "re", ".", "findall", "(", "r'\\b\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\b'", ",", "text", ")", "ip", "=", "ip_matches", "[", "0", "]", "if", "ip_matches", "else", "None", "return", "ip" ]
Extract an IPv4 IP from a text string Uses an IP Address Regex: http://www.regular-expressions.info/examples.html
[ "Extract", "an", "IPv4", "IP", "from", "a", "text", "string", "Uses", "an", "IP", "Address", "Regex", ":", "http", ":", "//", "www", ".", "regular", "-", "expressions", ".", "info", "/", "examples", ".", "html" ]
train
https://github.com/tobami/littlechef/blob/aab8c94081b38100a69cc100bc4278ae7419c58e/plugins/save_ip.py#L11-L18
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 ...
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 ...
[ "def", "execute", "(", "node", ")", ":", "with", "hide", "(", "'everything'", ")", ":", "virt", "=", "json", ".", "loads", "(", "sudo", "(", "'ohai virtualization'", ")", ")", "if", "not", "len", "(", "virt", ")", "or", "virt", "[", "0", "]", "[", ...
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" ]
train
https://github.com/tobami/littlechef/blob/aab8c94081b38100a69cc100bc4278ae7419c58e/plugins/save_xen_info.py#L11-L40
tobami/littlechef
littlechef/runner.py
new_kitchen
def new_kitchen(): """Create LittleChef directory structure (Kitchen)""" def _mkdir(d, content=""): if not os.path.exists(d): os.mkdir(d) # Add a README so that it can be added to version control readme_path = os.path.join(d, 'README') if not os.path.exist...
python
def new_kitchen(): """Create LittleChef directory structure (Kitchen)""" def _mkdir(d, content=""): if not os.path.exists(d): os.mkdir(d) # Add a README so that it can be added to version control readme_path = os.path.join(d, 'README') if not os.path.exist...
[ "def", "new_kitchen", "(", ")", ":", "def", "_mkdir", "(", "d", ",", "content", "=", "\"\"", ")", ":", "if", "not", "os", ".", "path", ".", "exists", "(", "d", ")", ":", "os", ".", "mkdir", "(", "d", ")", "# Add a README so that it can be added to vers...
Create LittleChef directory structure (Kitchen)
[ "Create", "LittleChef", "directory", "structure", "(", "Kitchen", ")" ]
train
https://github.com/tobami/littlechef/blob/aab8c94081b38100a69cc100bc4278ae7419c58e/littlechef/runner.py#L51-L89
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)...
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)...
[ "def", "nodes_with_role", "(", "rolename", ")", ":", "nodes", "=", "[", "n", "[", "'name'", "]", "for", "n", "in", "lib", ".", "get_nodes_with_role", "(", "rolename", ",", "env", ".", "chef_environment", ")", "]", "if", "not", "len", "(", "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" ]
train
https://github.com/tobami/littlechef/blob/aab8c94081b38100a69cc100bc4278ae7419c58e/littlechef/runner.py#L92-L99
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)) ...
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)) ...
[ "def", "nodes_with_recipe", "(", "recipename", ")", ":", "nodes", "=", "[", "n", "[", "'name'", "]", "for", "n", "in", "lib", ".", "get_nodes_with_recipe", "(", "recipename", ",", "env", ".", "chef_environment", ")", "]", "if", "not", "len", "(", "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" ]
train
https://github.com/tobami/littlechef/blob/aab8c94081b38100a69cc100bc4278ae7419c58e/littlechef/runner.py#L102-L110
tobami/littlechef
littlechef/runner.py
nodes_with_tag
def nodes_with_tag(tag): """Sets a list of nodes that have the given tag assigned and calls node()""" nodes = lib.get_nodes_with_tag(tag, env.chef_environment, littlechef.include_guests) nodes = [n['name'] for n in nodes] if not len(nodes): print("No nodes foun...
python
def nodes_with_tag(tag): """Sets a list of nodes that have the given tag assigned and calls node()""" nodes = lib.get_nodes_with_tag(tag, env.chef_environment, littlechef.include_guests) nodes = [n['name'] for n in nodes] if not len(nodes): print("No nodes foun...
[ "def", "nodes_with_tag", "(", "tag", ")", ":", "nodes", "=", "lib", ".", "get_nodes_with_tag", "(", "tag", ",", "env", ".", "chef_environment", ",", "littlechef", ".", "include_guests", ")", "nodes", "=", "[", "n", "[", "'name'", "]", "for", "n", "in", ...
Sets a list of nodes that have the given tag assigned and calls node()
[ "Sets", "a", "list", "of", "nodes", "that", "have", "the", "given", "tag", "assigned", "and", "calls", "node", "()" ]
train
https://github.com/tobami/littlechef/blob/aab8c94081b38100a69cc100bc4278ae7419c58e/littlechef/runner.py#L113-L121
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....
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....
[ "def", "node", "(", "*", "nodes", ")", ":", "chef", ".", "build_node_data_bag", "(", ")", "if", "not", "len", "(", "nodes", ")", "or", "nodes", "[", "0", "]", "==", "''", ":", "abort", "(", "'No node was given'", ")", "elif", "nodes", "[", "0", "]"...
Selects and configures a list of nodes. 'all' configures all nodes
[ "Selects", "and", "configures", "a", "list", "of", "nodes", ".", "all", "configures", "all", "nodes" ]
train
https://github.com/tobami/littlechef/blob/aab8c94081b38100a69cc100bc4278ae7419c58e/littlechef/runner.py#L124-L158
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...
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...
[ "def", "_node_runner", "(", ")", ":", "env", ".", "host_string", "=", "lib", ".", "get_env_host_string", "(", ")", "node", "=", "lib", ".", "get_node", "(", "env", ".", "host_string", ")", "_configure_fabric_for_platform", "(", "node", ".", "get", "(", "\"...
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" ]
train
https://github.com/tobami/littlechef/blob/aab8c94081b38100a69cc100bc4278ae7419c58e/littlechef/runner.py#L167-L180
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 i...
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 i...
[ "def", "deploy_chef", "(", "ask", "=", "\"yes\"", ",", "version", "=", "\"11\"", ")", ":", "env", ".", "host_string", "=", "lib", ".", "get_env_host_string", "(", ")", "if", "ask", "==", "\"no\"", "or", "littlechef", ".", "noninteractive", ":", "print", ...
Install chef-solo on a node
[ "Install", "chef", "-", "solo", "on", "a", "node" ]
train
https://github.com/tobami/littlechef/blob/aab8c94081b38100a69cc100bc4278ae7419c58e/littlechef/runner.py#L183-L215
tobami/littlechef
littlechef/runner.py
recipe
def recipe(recipe): """Apply the given recipe to a node Sets the run_list to the given recipe If no nodes/hostname.json file exists, it creates one """ env.host_string = lib.get_env_host_string() lib.print_header( "Applying recipe '{0}' on node {1}".format(recipe, env.host_string)) ...
python
def recipe(recipe): """Apply the given recipe to a node Sets the run_list to the given recipe If no nodes/hostname.json file exists, it creates one """ env.host_string = lib.get_env_host_string() lib.print_header( "Applying recipe '{0}' on node {1}".format(recipe, env.host_string)) ...
[ "def", "recipe", "(", "recipe", ")", ":", "env", ".", "host_string", "=", "lib", ".", "get_env_host_string", "(", ")", "lib", ".", "print_header", "(", "\"Applying recipe '{0}' on node {1}\"", ".", "format", "(", "recipe", ",", "env", ".", "host_string", ")", ...
Apply the given recipe to a node Sets the run_list to the given recipe If no nodes/hostname.json file exists, it creates one
[ "Apply", "the", "given", "recipe", "to", "a", "node", "Sets", "the", "run_list", "to", "the", "given", "recipe", "If", "no", "nodes", "/", "hostname", ".", "json", "file", "exists", "it", "creates", "one" ]
train
https://github.com/tobami/littlechef/blob/aab8c94081b38100a69cc100bc4278ae7419c58e/littlechef/runner.py#L218-L234
tobami/littlechef
littlechef/runner.py
ssh
def ssh(name): """Executes the given command""" env.host_string = lib.get_env_host_string() print("\nExecuting the command '{0}' on node {1}...".format( name, env.host_string)) # Execute remotely using either the sudo or the run fabric functions with settings(hide("warnings"), warn_only=Tr...
python
def ssh(name): """Executes the given command""" env.host_string = lib.get_env_host_string() print("\nExecuting the command '{0}' on node {1}...".format( name, env.host_string)) # Execute remotely using either the sudo or the run fabric functions with settings(hide("warnings"), warn_only=Tr...
[ "def", "ssh", "(", "name", ")", ":", "env", ".", "host_string", "=", "lib", ".", "get_env_host_string", "(", ")", "print", "(", "\"\\nExecuting the command '{0}' on node {1}...\"", ".", "format", "(", "name", ",", "env", ".", "host_string", ")", ")", "# Execut...
Executes the given command
[ "Executes", "the", "given", "command" ]
train
https://github.com/tobami/littlechef/blob/aab8c94081b38100a69cc100bc4278ae7419c58e/littlechef/runner.py#L256-L266
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_s...
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_s...
[ "def", "plugin", "(", "name", ")", ":", "env", ".", "host_string", "=", "lib", ".", "get_env_host_string", "(", ")", "plug", "=", "lib", ".", "import_plugin", "(", "name", ")", "lib", ".", "print_header", "(", "\"Executing plugin '{0}' on \"", "\"{1}\"", "."...
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" ]
train
https://github.com/tobami/littlechef/blob/aab8c94081b38100a69cc100bc4278ae7419c58e/littlechef/runner.py#L269-L282
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", "(...
List all environments
[ "List", "all", "environments" ]
train
https://github.com/tobami/littlechef/blob/aab8c94081b38100a69cc100bc4278ae7419c58e/littlechef/runner.py#L310-L316
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" ]
train
https://github.com/tobami/littlechef/blob/aab8c94081b38100a69cc100bc4278ae7419c58e/littlechef/runner.py#L320-L323
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", ...
Show a list of all available recipes
[ "Show", "a", "list", "of", "all", "available", "recipes" ]
train
https://github.com/tobami/littlechef/blob/aab8c94081b38100a69cc100bc4278ae7419c58e/littlechef/runner.py#L327-L332
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", "(...
Show a list of all available roles
[ "Show", "a", "list", "of", "all", "available", "roles" ]
train
https://github.com/tobami/littlechef/blob/aab8c94081b38100a69cc100bc4278ae7419c58e/littlechef/runner.py#L343-L349
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(dir...
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(dir...
[ "def", "_check_appliances", "(", ")", ":", "filenames", "=", "os", ".", "listdir", "(", "os", ".", "getcwd", "(", ")", ")", "missing", "=", "[", "]", "for", "dirname", "in", "[", "'nodes'", ",", "'environments'", ",", "'roles'", ",", "'cookbooks'", ","...
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" ]
train
https://github.com/tobami/littlechef/blob/aab8c94081b38100a69cc100bc4278ae7419c58e/littlechef/runner.py#L365-L374
tobami/littlechef
littlechef/runner.py
_readconfig
def _readconfig(): """Configures environment variables""" config = ConfigParser.SafeConfigParser() try: found = config.read(littlechef.CONFIGFILE) except ConfigParser.ParsingError as e: abort(str(e)) if not len(found): try: found = config.read(['config.cfg', 'auth...
python
def _readconfig(): """Configures environment variables""" config = ConfigParser.SafeConfigParser() try: found = config.read(littlechef.CONFIGFILE) except ConfigParser.ParsingError as e: abort(str(e)) if not len(found): try: found = config.read(['config.cfg', 'auth...
[ "def", "_readconfig", "(", ")", ":", "config", "=", "ConfigParser", ".", "SafeConfigParser", "(", ")", "try", ":", "found", "=", "config", ".", "read", "(", "littlechef", ".", "CONFIGFILE", ")", "except", "ConfigParser", ".", "ParsingError", "as", "e", ":"...
Configures environment variables
[ "Configures", "environment", "variables" ]
train
https://github.com/tobami/littlechef/blob/aab8c94081b38100a69cc100bc4278ae7419c58e/littlechef/runner.py#L377-L552
jbittel/django-mama-cas
mama_cas/views.py
LoginView.get
def get(self, request, *args, **kwargs): """ (2.1) As a credential requestor, /login accepts three optional parameters: 1. ``service``: the identifier of the application the client is accessing. We assume this identifier to be a URL. 2. ``renew``: requires a client to...
python
def get(self, request, *args, **kwargs): """ (2.1) As a credential requestor, /login accepts three optional parameters: 1. ``service``: the identifier of the application the client is accessing. We assume this identifier to be a URL. 2. ``renew``: requires a client to...
[ "def", "get", "(", "self", ",", "request", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "service", "=", "request", ".", "GET", ".", "get", "(", "'service'", ")", "renew", "=", "to_bool", "(", "request", ".", "GET", ".", "get", "(", "'rene...
(2.1) As a credential requestor, /login accepts three optional parameters: 1. ``service``: the identifier of the application the client is accessing. We assume this identifier to be a URL. 2. ``renew``: requires a client to present credentials regardless of any existing si...
[ "(", "2", ".", "1", ")", "As", "a", "credential", "requestor", "/", "login", "accepts", "three", "optional", "parameters", ":" ]
train
https://github.com/jbittel/django-mama-cas/blob/03935d97442b46d8127ab9e1cd8deb96953fe156/mama_cas/views.py#L68-L108
jbittel/django-mama-cas
mama_cas/views.py
LoginView.form_valid
def form_valid(self, form): """ (2.2) As a credential acceptor, /login requires two parameters: 1. ``username``: the username provided by the client 2. ``password``: the password provided by the client If authentication is successful, the single sign-on session is creat...
python
def form_valid(self, form): """ (2.2) As a credential acceptor, /login requires two parameters: 1. ``username``: the username provided by the client 2. ``password``: the password provided by the client If authentication is successful, the single sign-on session is creat...
[ "def", "form_valid", "(", "self", ",", "form", ")", ":", "login", "(", "self", ".", "request", ",", "form", ".", "user", ")", "logger", ".", "info", "(", "\"Single sign-on session started for %s\"", "%", "form", ".", "user", ")", "if", "form", ".", "clea...
(2.2) As a credential acceptor, /login requires two parameters: 1. ``username``: the username provided by the client 2. ``password``: the password provided by the client If authentication is successful, the single sign-on session is created. If a service is provided, a ``ServiceTicket`...
[ "(", "2", ".", "2", ")", "As", "a", "credential", "acceptor", "/", "login", "requires", "two", "parameters", ":" ]
train
https://github.com/jbittel/django-mama-cas/blob/03935d97442b46d8127ab9e1cd8deb96953fe156/mama_cas/views.py#L117-L150