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
solutionbox/image_classification/mltoolbox/image/classification/_util.py
check_dataset
def check_dataset(dataset, mode): """Validate we have a good dataset.""" names = [x['name'] for x in dataset.schema] types = [x['type'] for x in dataset.schema] if mode == 'train': if (set(['image_url', 'label']) != set(names) or any(t != 'STRING' for t in types)): raise ValueError('Invalid dataset. ...
python
def check_dataset(dataset, mode): """Validate we have a good dataset.""" names = [x['name'] for x in dataset.schema] types = [x['type'] for x in dataset.schema] if mode == 'train': if (set(['image_url', 'label']) != set(names) or any(t != 'STRING' for t in types)): raise ValueError('Invalid dataset. ...
[ "def", "check_dataset", "(", "dataset", ",", "mode", ")", ":", "names", "=", "[", "x", "[", "'name'", "]", "for", "x", "in", "dataset", ".", "schema", "]", "types", "=", "[", "x", "[", "'type'", "]", "for", "x", "in", "dataset", ".", "schema", "]...
Validate we have a good dataset.
[ "Validate", "we", "have", "a", "good", "dataset", "." ]
train
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/solutionbox/image_classification/mltoolbox/image/classification/_util.py#L150-L162
googledatalab/pydatalab
solutionbox/image_classification/mltoolbox/image/classification/_util.py
get_sources_from_dataset
def get_sources_from_dataset(p, dataset, mode): """get pcollection from dataset.""" import apache_beam as beam import csv from google.datalab.ml import CsvDataSet, BigQueryDataSet check_dataset(dataset, mode) if type(dataset) is CsvDataSet: source_list = [] for ii, input_path in enumerate(dataset....
python
def get_sources_from_dataset(p, dataset, mode): """get pcollection from dataset.""" import apache_beam as beam import csv from google.datalab.ml import CsvDataSet, BigQueryDataSet check_dataset(dataset, mode) if type(dataset) is CsvDataSet: source_list = [] for ii, input_path in enumerate(dataset....
[ "def", "get_sources_from_dataset", "(", "p", ",", "dataset", ",", "mode", ")", ":", "import", "apache_beam", "as", "beam", "import", "csv", "from", "google", ".", "datalab", ".", "ml", "import", "CsvDataSet", ",", "BigQueryDataSet", "check_dataset", "(", "data...
get pcollection from dataset.
[ "get", "pcollection", "from", "dataset", "." ]
train
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/solutionbox/image_classification/mltoolbox/image/classification/_util.py#L165-L189
googledatalab/pydatalab
solutionbox/image_classification/mltoolbox/image/classification/_util.py
decode_and_resize
def decode_and_resize(image_str_tensor): """Decodes jpeg string, resizes it and returns a uint8 tensor.""" # These constants are set by Inception v3's expectations. height = 299 width = 299 channels = 3 image = tf.image.decode_jpeg(image_str_tensor, channels=channels) # Note resize expects a batch_size,...
python
def decode_and_resize(image_str_tensor): """Decodes jpeg string, resizes it and returns a uint8 tensor.""" # These constants are set by Inception v3's expectations. height = 299 width = 299 channels = 3 image = tf.image.decode_jpeg(image_str_tensor, channels=channels) # Note resize expects a batch_size,...
[ "def", "decode_and_resize", "(", "image_str_tensor", ")", ":", "# These constants are set by Inception v3's expectations.", "height", "=", "299", "width", "=", "299", "channels", "=", "3", "image", "=", "tf", ".", "image", ".", "decode_jpeg", "(", "image_str_tensor", ...
Decodes jpeg string, resizes it and returns a uint8 tensor.
[ "Decodes", "jpeg", "string", "resizes", "it", "and", "returns", "a", "uint8", "tensor", "." ]
train
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/solutionbox/image_classification/mltoolbox/image/classification/_util.py#L192-L208
googledatalab/pydatalab
solutionbox/image_classification/mltoolbox/image/classification/_util.py
resize_image
def resize_image(image_str_tensor): """Decodes jpeg string, resizes it and re-encode it to jpeg.""" image = decode_and_resize(image_str_tensor) image = tf.image.encode_jpeg(image, quality=100) return image
python
def resize_image(image_str_tensor): """Decodes jpeg string, resizes it and re-encode it to jpeg.""" image = decode_and_resize(image_str_tensor) image = tf.image.encode_jpeg(image, quality=100) return image
[ "def", "resize_image", "(", "image_str_tensor", ")", ":", "image", "=", "decode_and_resize", "(", "image_str_tensor", ")", "image", "=", "tf", ".", "image", ".", "encode_jpeg", "(", "image", ",", "quality", "=", "100", ")", "return", "image" ]
Decodes jpeg string, resizes it and re-encode it to jpeg.
[ "Decodes", "jpeg", "string", "resizes", "it", "and", "re", "-", "encode", "it", "to", "jpeg", "." ]
train
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/solutionbox/image_classification/mltoolbox/image/classification/_util.py#L211-L216
googledatalab/pydatalab
solutionbox/image_classification/mltoolbox/image/classification/_util.py
load_images
def load_images(image_files, resize=True): """Load images from files and optionally resize it.""" images = [] for image_file in image_files: with file_io.FileIO(image_file, 'r') as ff: images.append(ff.read()) if resize is False: return images # To resize, run a tf session so we can reuse 'dec...
python
def load_images(image_files, resize=True): """Load images from files and optionally resize it.""" images = [] for image_file in image_files: with file_io.FileIO(image_file, 'r') as ff: images.append(ff.read()) if resize is False: return images # To resize, run a tf session so we can reuse 'dec...
[ "def", "load_images", "(", "image_files", ",", "resize", "=", "True", ")", ":", "images", "=", "[", "]", "for", "image_file", "in", "image_files", ":", "with", "file_io", ".", "FileIO", "(", "image_file", ",", "'r'", ")", "as", "ff", ":", "images", "."...
Load images from files and optionally resize it.
[ "Load", "images", "from", "files", "and", "optionally", "resize", "it", "." ]
train
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/solutionbox/image_classification/mltoolbox/image/classification/_util.py#L219-L239
googledatalab/pydatalab
solutionbox/image_classification/mltoolbox/image/classification/_util.py
process_prediction_results
def process_prediction_results(results, show_image): """Create DataFrames out of prediction results, and display images in IPython if requested.""" import pandas as pd if (is_in_IPython() and show_image is True): import IPython for image_url, image, label_and_score in results: IPython.display.disp...
python
def process_prediction_results(results, show_image): """Create DataFrames out of prediction results, and display images in IPython if requested.""" import pandas as pd if (is_in_IPython() and show_image is True): import IPython for image_url, image, label_and_score in results: IPython.display.disp...
[ "def", "process_prediction_results", "(", "results", ",", "show_image", ")", ":", "import", "pandas", "as", "pd", "if", "(", "is_in_IPython", "(", ")", "and", "show_image", "is", "True", ")", ":", "import", "IPython", "for", "image_url", ",", "image", ",", ...
Create DataFrames out of prediction results, and display images in IPython if requested.
[ "Create", "DataFrames", "out", "of", "prediction", "results", "and", "display", "images", "in", "IPython", "if", "requested", "." ]
train
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/solutionbox/image_classification/mltoolbox/image/classification/_util.py#L242-L254
googledatalab/pydatalab
solutionbox/image_classification/mltoolbox/image/classification/_util.py
repackage_to_staging
def repackage_to_staging(output_path): """Repackage it from local installed location and copy it to GCS.""" import google.datalab.ml as ml # Find the package root. __file__ is under [package_root]/mltoolbox/image/classification. package_root = os.path.join(os.path.dirname(__file__), '../../../') # We deploy...
python
def repackage_to_staging(output_path): """Repackage it from local installed location and copy it to GCS.""" import google.datalab.ml as ml # Find the package root. __file__ is under [package_root]/mltoolbox/image/classification. package_root = os.path.join(os.path.dirname(__file__), '../../../') # We deploy...
[ "def", "repackage_to_staging", "(", "output_path", ")", ":", "import", "google", ".", "datalab", ".", "ml", "as", "ml", "# Find the package root. __file__ is under [package_root]/mltoolbox/image/classification.", "package_root", "=", "os", ".", "path", ".", "join", "(", ...
Repackage it from local installed location and copy it to GCS.
[ "Repackage", "it", "from", "local", "installed", "location", "and", "copy", "it", "to", "GCS", "." ]
train
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/solutionbox/image_classification/mltoolbox/image/classification/_util.py#L257-L268
googledatalab/pydatalab
google/datalab/contrib/pipeline/_pipeline.py
PipelineGenerator.generate_airflow_spec
def generate_airflow_spec(name, pipeline_spec): """ Gets the airflow python spec for the Pipeline object. """ task_definitions = '' up_steam_statements = '' parameters = pipeline_spec.get('parameters') for (task_id, task_details) in sorted(pipeline_spec['tasks'].items()): task_def = Pipeli...
python
def generate_airflow_spec(name, pipeline_spec): """ Gets the airflow python spec for the Pipeline object. """ task_definitions = '' up_steam_statements = '' parameters = pipeline_spec.get('parameters') for (task_id, task_details) in sorted(pipeline_spec['tasks'].items()): task_def = Pipeli...
[ "def", "generate_airflow_spec", "(", "name", ",", "pipeline_spec", ")", ":", "task_definitions", "=", "''", "up_steam_statements", "=", "''", "parameters", "=", "pipeline_spec", ".", "get", "(", "'parameters'", ")", "for", "(", "task_id", ",", "task_details", ")...
Gets the airflow python spec for the Pipeline object.
[ "Gets", "the", "airflow", "python", "spec", "for", "the", "Pipeline", "object", "." ]
train
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/google/datalab/contrib/pipeline/_pipeline.py#L48-L68
googledatalab/pydatalab
google/datalab/contrib/pipeline/_pipeline.py
PipelineGenerator._get_operator_definition
def _get_operator_definition(task_id, task_details, parameters): """ Internal helper that gets the definition of the airflow operator for the task with the python parameters. All the parameters are also expanded with the airflow macros. :param parameters: """ operator_type = task_details['type']...
python
def _get_operator_definition(task_id, task_details, parameters): """ Internal helper that gets the definition of the airflow operator for the task with the python parameters. All the parameters are also expanded with the airflow macros. :param parameters: """ operator_type = task_details['type']...
[ "def", "_get_operator_definition", "(", "task_id", ",", "task_details", ",", "parameters", ")", ":", "operator_type", "=", "task_details", "[", "'type'", "]", "full_param_string", "=", "'task_id=\\'{0}_id\\''", ".", "format", "(", "task_id", ")", "operator_class_name"...
Internal helper that gets the definition of the airflow operator for the task with the python parameters. All the parameters are also expanded with the airflow macros. :param parameters:
[ "Internal", "helper", "that", "gets", "the", "definition", "of", "the", "airflow", "operator", "for", "the", "task", "with", "the", "python", "parameters", ".", "All", "the", "parameters", "are", "also", "expanded", "with", "the", "airflow", "macros", ".", "...
train
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/google/datalab/contrib/pipeline/_pipeline.py#L120-L149
googledatalab/pydatalab
google/datalab/contrib/pipeline/_pipeline.py
PipelineGenerator._get_dependency_definition
def _get_dependency_definition(task_id, dependencies): """ Internal helper collects all the dependencies of the task, and returns the Airflow equivalent python sytax for specifying them. """ set_upstream_statements = '' for dependency in dependencies: set_upstream_statements = set_upstream_s...
python
def _get_dependency_definition(task_id, dependencies): """ Internal helper collects all the dependencies of the task, and returns the Airflow equivalent python sytax for specifying them. """ set_upstream_statements = '' for dependency in dependencies: set_upstream_statements = set_upstream_s...
[ "def", "_get_dependency_definition", "(", "task_id", ",", "dependencies", ")", ":", "set_upstream_statements", "=", "''", "for", "dependency", "in", "dependencies", ":", "set_upstream_statements", "=", "set_upstream_statements", "+", "'{0}.set_upstream({1})'", ".", "forma...
Internal helper collects all the dependencies of the task, and returns the Airflow equivalent python sytax for specifying them.
[ "Internal", "helper", "collects", "all", "the", "dependencies", "of", "the", "task", "and", "returns", "the", "Airflow", "equivalent", "python", "sytax", "for", "specifying", "them", "." ]
train
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/google/datalab/contrib/pipeline/_pipeline.py#L167-L175
googledatalab/pydatalab
google/datalab/contrib/pipeline/_pipeline.py
PipelineGenerator._get_operator_class_name
def _get_operator_class_name(task_detail_type): """ Internal helper gets the name of the Airflow operator class. We maintain this in a map, so this method really returns the enum name, concatenated with the string "Operator". """ # TODO(rajivpb): Rename this var correctly. task_type_to_opera...
python
def _get_operator_class_name(task_detail_type): """ Internal helper gets the name of the Airflow operator class. We maintain this in a map, so this method really returns the enum name, concatenated with the string "Operator". """ # TODO(rajivpb): Rename this var correctly. task_type_to_opera...
[ "def", "_get_operator_class_name", "(", "task_detail_type", ")", ":", "# TODO(rajivpb): Rename this var correctly.", "task_type_to_operator_prefix_mapping", "=", "{", "'pydatalab.bq.execute'", ":", "(", "'Execute'", ",", "'google.datalab.contrib.bigquery.operators._bq_execute_operator'...
Internal helper gets the name of the Airflow operator class. We maintain this in a map, so this method really returns the enum name, concatenated with the string "Operator".
[ "Internal", "helper", "gets", "the", "name", "of", "the", "Airflow", "operator", "class", ".", "We", "maintain", "this", "in", "a", "map", "so", "this", "method", "really", "returns", "the", "enum", "name", "concatenated", "with", "the", "string", "Operator"...
train
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/google/datalab/contrib/pipeline/_pipeline.py#L178-L198
googledatalab/pydatalab
google/datalab/contrib/pipeline/_pipeline.py
PipelineGenerator._get_operator_param_name_and_values
def _get_operator_param_name_and_values(operator_class_name, task_details): """ Internal helper gets the name of the python parameter for the Airflow operator class. In some cases, we do not expose the airflow parameter name in its native form, but choose to expose a name that's more standard for Datala...
python
def _get_operator_param_name_and_values(operator_class_name, task_details): """ Internal helper gets the name of the python parameter for the Airflow operator class. In some cases, we do not expose the airflow parameter name in its native form, but choose to expose a name that's more standard for Datala...
[ "def", "_get_operator_param_name_and_values", "(", "operator_class_name", ",", "task_details", ")", ":", "# We make a clone and then remove 'type' and 'up_stream' since these aren't needed for the", "# the operator's parameters.", "operator_task_details", "=", "task_details", ".", "copy"...
Internal helper gets the name of the python parameter for the Airflow operator class. In some cases, we do not expose the airflow parameter name in its native form, but choose to expose a name that's more standard for Datalab, or one that's more friendly. For example, Airflow's BigQueryOperator uses '...
[ "Internal", "helper", "gets", "the", "name", "of", "the", "python", "parameter", "for", "the", "Airflow", "operator", "class", ".", "In", "some", "cases", "we", "do", "not", "expose", "the", "airflow", "parameter", "name", "in", "its", "native", "form", "b...
train
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/google/datalab/contrib/pipeline/_pipeline.py#L201-L236
googledatalab/pydatalab
google/datalab/ml/_dataset.py
CsvDataSet.size
def size(self): """The size of the schema. If the underlying data source changes, it may be outdated. """ if self._size is None: self._size = 0 for csv_file in self.files: self._size += sum(1 if line else 0 for line in _util.open_local_or_gcs(csv_file, 'r')) return self._size
python
def size(self): """The size of the schema. If the underlying data source changes, it may be outdated. """ if self._size is None: self._size = 0 for csv_file in self.files: self._size += sum(1 if line else 0 for line in _util.open_local_or_gcs(csv_file, 'r')) return self._size
[ "def", "size", "(", "self", ")", ":", "if", "self", ".", "_size", "is", "None", ":", "self", ".", "_size", "=", "0", "for", "csv_file", "in", "self", ".", "files", ":", "self", ".", "_size", "+=", "sum", "(", "1", "if", "line", "else", "0", "fo...
The size of the schema. If the underlying data source changes, it may be outdated.
[ "The", "size", "of", "the", "schema", ".", "If", "the", "underlying", "data", "source", "changes", "it", "may", "be", "outdated", "." ]
train
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/google/datalab/ml/_dataset.py#L95-L103
googledatalab/pydatalab
google/datalab/ml/_dataset.py
CsvDataSet.sample
def sample(self, n): """ Samples data into a Pandas DataFrame. Args: n: number of sampled counts. Returns: A dataframe containing sampled data. Raises: Exception if n is larger than number of rows. """ row_total_count = 0 row_counts = [] for file in self.files: w...
python
def sample(self, n): """ Samples data into a Pandas DataFrame. Args: n: number of sampled counts. Returns: A dataframe containing sampled data. Raises: Exception if n is larger than number of rows. """ row_total_count = 0 row_counts = [] for file in self.files: w...
[ "def", "sample", "(", "self", ",", "n", ")", ":", "row_total_count", "=", "0", "row_counts", "=", "[", "]", "for", "file", "in", "self", ".", "files", ":", "with", "_util", ".", "open_local_or_gcs", "(", "file", ",", "'r'", ")", "as", "f", ":", "nu...
Samples data into a Pandas DataFrame. Args: n: number of sampled counts. Returns: A dataframe containing sampled data. Raises: Exception if n is larger than number of rows.
[ "Samples", "data", "into", "a", "Pandas", "DataFrame", ".", "Args", ":", "n", ":", "number", "of", "sampled", "counts", ".", "Returns", ":", "A", "dataframe", "containing", "sampled", "data", ".", "Raises", ":", "Exception", "if", "n", "is", "larger", "t...
train
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/google/datalab/ml/_dataset.py#L105-L145
googledatalab/pydatalab
google/datalab/ml/_dataset.py
BigQueryDataSet.size
def size(self): """The size of the schema. If the underlying data source changes, it may be outdated. """ if self._size is None: self._size = bq.Query('SELECT COUNT(*) FROM %s' % self._get_source()).execute().result()[0].values()[0] return self._size
python
def size(self): """The size of the schema. If the underlying data source changes, it may be outdated. """ if self._size is None: self._size = bq.Query('SELECT COUNT(*) FROM %s' % self._get_source()).execute().result()[0].values()[0] return self._size
[ "def", "size", "(", "self", ")", ":", "if", "self", ".", "_size", "is", "None", ":", "self", ".", "_size", "=", "bq", ".", "Query", "(", "'SELECT COUNT(*) FROM %s'", "%", "self", ".", "_get_source", "(", ")", ")", ".", "execute", "(", ")", ".", "re...
The size of the schema. If the underlying data source changes, it may be outdated.
[ "The", "size", "of", "the", "schema", ".", "If", "the", "underlying", "data", "source", "changes", "it", "may", "be", "outdated", "." ]
train
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/google/datalab/ml/_dataset.py#L188-L194
googledatalab/pydatalab
google/datalab/ml/_dataset.py
BigQueryDataSet.sample
def sample(self, n): """Samples data into a Pandas DataFrame. Note that it calls BigQuery so it will incur cost. Args: n: number of sampled counts. Note that the number of counts returned is approximated. Returns: A dataframe containing sampled data. Raises: Exception if n is l...
python
def sample(self, n): """Samples data into a Pandas DataFrame. Note that it calls BigQuery so it will incur cost. Args: n: number of sampled counts. Note that the number of counts returned is approximated. Returns: A dataframe containing sampled data. Raises: Exception if n is l...
[ "def", "sample", "(", "self", ",", "n", ")", ":", "total", "=", "bq", ".", "Query", "(", "'select count(*) from %s'", "%", "self", ".", "_get_source", "(", ")", ")", ".", "execute", "(", ")", ".", "result", "(", ")", "[", "0", "]", ".", "values", ...
Samples data into a Pandas DataFrame. Note that it calls BigQuery so it will incur cost. Args: n: number of sampled counts. Note that the number of counts returned is approximated. Returns: A dataframe containing sampled data. Raises: Exception if n is larger than number of rows.
[ "Samples", "data", "into", "a", "Pandas", "DataFrame", ".", "Note", "that", "it", "calls", "BigQuery", "so", "it", "will", "incur", "cost", "." ]
train
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/google/datalab/ml/_dataset.py#L196-L218
googledatalab/pydatalab
google/datalab/ml/_dataset.py
TransformedDataSet.size
def size(self): """The number of instances in the data. If the underlying data source changes, it may be outdated. """ import tensorflow as tf if self._size is None: self._size = 0 options = tf.python_io.TFRecordOptions(tf.python_io.TFRecordCompressionType.GZIP) for tfexample_f...
python
def size(self): """The number of instances in the data. If the underlying data source changes, it may be outdated. """ import tensorflow as tf if self._size is None: self._size = 0 options = tf.python_io.TFRecordOptions(tf.python_io.TFRecordCompressionType.GZIP) for tfexample_f...
[ "def", "size", "(", "self", ")", ":", "import", "tensorflow", "as", "tf", "if", "self", ".", "_size", "is", "None", ":", "self", ".", "_size", "=", "0", "options", "=", "tf", ".", "python_io", ".", "TFRecordOptions", "(", "tf", ".", "python_io", ".",...
The number of instances in the data. If the underlying data source changes, it may be outdated.
[ "The", "number", "of", "instances", "in", "the", "data", ".", "If", "the", "underlying", "data", "source", "changes", "it", "may", "be", "outdated", "." ]
train
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/google/datalab/ml/_dataset.py#L252-L265
googledatalab/pydatalab
google/datalab/stackdriver/monitoring/_group.py
Groups.list
def list(self, pattern='*'): """Returns a list of groups that match the filters. Args: pattern: An optional pattern to filter the groups based on their display name. This can include Unix shell-style wildcards. E.g. ``"Production*"``. Returns: A list of Group objects that m...
python
def list(self, pattern='*'): """Returns a list of groups that match the filters. Args: pattern: An optional pattern to filter the groups based on their display name. This can include Unix shell-style wildcards. E.g. ``"Production*"``. Returns: A list of Group objects that m...
[ "def", "list", "(", "self", ",", "pattern", "=", "'*'", ")", ":", "if", "self", ".", "_group_dict", "is", "None", ":", "self", ".", "_group_dict", "=", "collections", ".", "OrderedDict", "(", "(", "group", ".", "id", ",", "group", ")", "for", "group"...
Returns a list of groups that match the filters. Args: pattern: An optional pattern to filter the groups based on their display name. This can include Unix shell-style wildcards. E.g. ``"Production*"``. Returns: A list of Group objects that match the filters.
[ "Returns", "a", "list", "of", "groups", "that", "match", "the", "filters", "." ]
train
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/google/datalab/stackdriver/monitoring/_group.py#L45-L61
googledatalab/pydatalab
google/datalab/stackdriver/monitoring/_group.py
Groups.as_dataframe
def as_dataframe(self, pattern='*', max_rows=None): """Creates a pandas dataframe from the groups that match the filters. Args: pattern: An optional pattern to further filter the groups. This can include Unix shell-style wildcards. E.g. ``"Production *"``, ``"*-backend"``. max_r...
python
def as_dataframe(self, pattern='*', max_rows=None): """Creates a pandas dataframe from the groups that match the filters. Args: pattern: An optional pattern to further filter the groups. This can include Unix shell-style wildcards. E.g. ``"Production *"``, ``"*-backend"``. max_r...
[ "def", "as_dataframe", "(", "self", ",", "pattern", "=", "'*'", ",", "max_rows", "=", "None", ")", ":", "data", "=", "[", "]", "for", "i", ",", "group", "in", "enumerate", "(", "self", ".", "list", "(", "pattern", ")", ")", ":", "if", "max_rows", ...
Creates a pandas dataframe from the groups that match the filters. Args: pattern: An optional pattern to further filter the groups. This can include Unix shell-style wildcards. E.g. ``"Production *"``, ``"*-backend"``. max_rows: The maximum number of groups to return. If None, retur...
[ "Creates", "a", "pandas", "dataframe", "from", "the", "groups", "that", "match", "the", "filters", "." ]
train
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/google/datalab/stackdriver/monitoring/_group.py#L63-L85
googledatalab/pydatalab
datalab/data/_sql_statement.py
SqlStatement._find_recursive_dependencies
def _find_recursive_dependencies(sql, values, code, resolved_vars, resolving_vars=None): """ Recursive helper method for expanding variables including transitive dependencies. Placeholders in SQL are represented as $<name>. If '$' must appear within the SQL statement literally, then it can be escaped as '$...
python
def _find_recursive_dependencies(sql, values, code, resolved_vars, resolving_vars=None): """ Recursive helper method for expanding variables including transitive dependencies. Placeholders in SQL are represented as $<name>. If '$' must appear within the SQL statement literally, then it can be escaped as '$...
[ "def", "_find_recursive_dependencies", "(", "sql", ",", "values", ",", "code", ",", "resolved_vars", ",", "resolving_vars", "=", "None", ")", ":", "# Get the set of $var references in this SQL.", "dependencies", "=", "SqlStatement", ".", "_get_dependencies", "(", "sql",...
Recursive helper method for expanding variables including transitive dependencies. Placeholders in SQL are represented as $<name>. If '$' must appear within the SQL statement literally, then it can be escaped as '$$'. Args: sql: the raw SQL statement with named placeholders. values: the user-s...
[ "Recursive", "helper", "method", "for", "expanding", "variables", "including", "transitive", "dependencies", "." ]
train
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/datalab/data/_sql_statement.py#L69-L120
googledatalab/pydatalab
datalab/data/_sql_statement.py
SqlStatement.format
def format(sql, args=None): """ Resolve variable references in a query within an environment. This computes and resolves the transitive dependencies in the query and raises an exception if that fails due to either undefined or circular references. Args: sql: query to format. args: a dictio...
python
def format(sql, args=None): """ Resolve variable references in a query within an environment. This computes and resolves the transitive dependencies in the query and raises an exception if that fails due to either undefined or circular references. Args: sql: query to format. args: a dictio...
[ "def", "format", "(", "sql", ",", "args", "=", "None", ")", ":", "resolved_vars", "=", "{", "}", "code", "=", "[", "]", "SqlStatement", ".", "_find_recursive_dependencies", "(", "sql", ",", "args", ",", "code", "=", "code", ",", "resolved_vars", "=", "...
Resolve variable references in a query within an environment. This computes and resolves the transitive dependencies in the query and raises an exception if that fails due to either undefined or circular references. Args: sql: query to format. args: a dictionary of values to use in variable ex...
[ "Resolve", "variable", "references", "in", "a", "query", "within", "an", "environment", "." ]
train
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/datalab/data/_sql_statement.py#L127-L193
googledatalab/pydatalab
datalab/data/_sql_statement.py
SqlStatement._get_dependencies
def _get_dependencies(sql): """ Return the list of variables referenced in this SQL. """ dependencies = [] for (_, placeholder, dollar, _) in SqlStatement._get_tokens(sql): if placeholder: variable = placeholder[1:] if variable not in dependencies: dependencies.append(variabl...
python
def _get_dependencies(sql): """ Return the list of variables referenced in this SQL. """ dependencies = [] for (_, placeholder, dollar, _) in SqlStatement._get_tokens(sql): if placeholder: variable = placeholder[1:] if variable not in dependencies: dependencies.append(variabl...
[ "def", "_get_dependencies", "(", "sql", ")", ":", "dependencies", "=", "[", "]", "for", "(", "_", ",", "placeholder", ",", "dollar", ",", "_", ")", "in", "SqlStatement", ".", "_get_tokens", "(", "sql", ")", ":", "if", "placeholder", ":", "variable", "=...
Return the list of variables referenced in this SQL.
[ "Return", "the", "list", "of", "variables", "referenced", "in", "this", "SQL", "." ]
train
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/datalab/data/_sql_statement.py#L202-L212
googledatalab/pydatalab
datalab/utils/commands/_modules.py
pymodule
def pymodule(line, cell=None): """Creates and subsequently auto-imports a python module. """ parser = _commands.CommandParser.create('pymodule') parser.add_argument('-n', '--name', help='the name of the python module to create and import') parser.set_defaults(func=_pymodule_cell) retur...
python
def pymodule(line, cell=None): """Creates and subsequently auto-imports a python module. """ parser = _commands.CommandParser.create('pymodule') parser.add_argument('-n', '--name', help='the name of the python module to create and import') parser.set_defaults(func=_pymodule_cell) retur...
[ "def", "pymodule", "(", "line", ",", "cell", "=", "None", ")", ":", "parser", "=", "_commands", ".", "CommandParser", ".", "create", "(", "'pymodule'", ")", "parser", ".", "add_argument", "(", "'-n'", ",", "'--name'", ",", "help", "=", "'the name of the py...
Creates and subsequently auto-imports a python module.
[ "Creates", "and", "subsequently", "auto", "-", "imports", "a", "python", "module", "." ]
train
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/datalab/utils/commands/_modules.py#L31-L38
googledatalab/pydatalab
datalab/context/_context.py
Context.set_project_id
def set_project_id(self, project_id): """ Set the project_id for the context. """ self._project_id = project_id if self == Context._global_context: try: from google.datalab import Context as new_context new_context.default().set_project_id(project_id) except ImportError: ...
python
def set_project_id(self, project_id): """ Set the project_id for the context. """ self._project_id = project_id if self == Context._global_context: try: from google.datalab import Context as new_context new_context.default().set_project_id(project_id) except ImportError: ...
[ "def", "set_project_id", "(", "self", ",", "project_id", ")", ":", "self", ".", "_project_id", "=", "project_id", "if", "self", "==", "Context", ".", "_global_context", ":", "try", ":", "from", "google", ".", "datalab", "import", "Context", "as", "new_contex...
Set the project_id for the context.
[ "Set", "the", "project_id", "for", "the", "context", "." ]
train
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/datalab/context/_context.py#L65-L74
googledatalab/pydatalab
datalab/context/_context.py
Context.default
def default(): """Retrieves a default Context object, creating it if necessary. The default Context is a global shared instance used every time the default context is retrieved. Attempting to use a Context with no project_id will raise an exception, so on first use set_project_id must be c...
python
def default(): """Retrieves a default Context object, creating it if necessary. The default Context is a global shared instance used every time the default context is retrieved. Attempting to use a Context with no project_id will raise an exception, so on first use set_project_id must be c...
[ "def", "default", "(", ")", ":", "credentials", "=", "_utils", ".", "get_credentials", "(", ")", "if", "Context", ".", "_global_context", "is", "None", ":", "project", "=", "_project", ".", "Projects", ".", "get_default_id", "(", "credentials", ")", "Context...
Retrieves a default Context object, creating it if necessary. The default Context is a global shared instance used every time the default context is retrieved. Attempting to use a Context with no project_id will raise an exception, so on first use set_project_id must be called. Returns: ...
[ "Retrieves", "a", "default", "Context", "object", "creating", "it", "if", "necessary", "." ]
train
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/datalab/context/_context.py#L86-L105
googledatalab/pydatalab
google/datalab/utils/_utils.py
compare_datetimes
def compare_datetimes(d1, d2): """ Compares two datetimes safely, whether they are timezone-naive or timezone-aware. If either datetime is naive it is converted to an aware datetime assuming UTC. Args: d1: first datetime. d2: second datetime. Returns: -1 if d1 < d2, 0 if they are the same, or +1 ...
python
def compare_datetimes(d1, d2): """ Compares two datetimes safely, whether they are timezone-naive or timezone-aware. If either datetime is naive it is converted to an aware datetime assuming UTC. Args: d1: first datetime. d2: second datetime. Returns: -1 if d1 < d2, 0 if they are the same, or +1 ...
[ "def", "compare_datetimes", "(", "d1", ",", "d2", ")", ":", "if", "d1", ".", "tzinfo", "is", "None", "or", "d1", ".", "tzinfo", ".", "utcoffset", "(", "d1", ")", "is", "None", ":", "d1", "=", "d1", ".", "replace", "(", "tzinfo", "=", "pytz", ".",...
Compares two datetimes safely, whether they are timezone-naive or timezone-aware. If either datetime is naive it is converted to an aware datetime assuming UTC. Args: d1: first datetime. d2: second datetime. Returns: -1 if d1 < d2, 0 if they are the same, or +1 is d1 > d2.
[ "Compares", "two", "datetimes", "safely", "whether", "they", "are", "timezone", "-", "naive", "or", "timezone", "-", "aware", "." ]
train
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/google/datalab/utils/_utils.py#L75-L95
googledatalab/pydatalab
google/datalab/utils/_utils.py
pick_unused_port
def pick_unused_port(): """ get an unused port on the VM. Returns: An unused port. """ s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.bind(('localhost', 0)) addr, port = s.getsockname() s.close() return port
python
def pick_unused_port(): """ get an unused port on the VM. Returns: An unused port. """ s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.bind(('localhost', 0)) addr, port = s.getsockname() s.close() return port
[ "def", "pick_unused_port", "(", ")", ":", "s", "=", "socket", ".", "socket", "(", "socket", ".", "AF_INET", ",", "socket", ".", "SOCK_STREAM", ")", "s", ".", "bind", "(", "(", "'localhost'", ",", "0", ")", ")", "addr", ",", "port", "=", "s", ".", ...
get an unused port on the VM. Returns: An unused port.
[ "get", "an", "unused", "port", "on", "the", "VM", "." ]
train
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/google/datalab/utils/_utils.py#L98-L108
googledatalab/pydatalab
google/datalab/utils/_utils.py
is_http_running_on
def is_http_running_on(port): """ Check if an http server runs on a given port. Args: The port to check. Returns: True if it is used by an http server. False otherwise. """ try: conn = httplib.HTTPConnection('127.0.0.1:' + str(port)) conn.connect() conn.close() return True except Ex...
python
def is_http_running_on(port): """ Check if an http server runs on a given port. Args: The port to check. Returns: True if it is used by an http server. False otherwise. """ try: conn = httplib.HTTPConnection('127.0.0.1:' + str(port)) conn.connect() conn.close() return True except Ex...
[ "def", "is_http_running_on", "(", "port", ")", ":", "try", ":", "conn", "=", "httplib", ".", "HTTPConnection", "(", "'127.0.0.1:'", "+", "str", "(", "port", ")", ")", "conn", ".", "connect", "(", ")", "conn", ".", "close", "(", ")", "return", "True", ...
Check if an http server runs on a given port. Args: The port to check. Returns: True if it is used by an http server. False otherwise.
[ "Check", "if", "an", "http", "server", "runs", "on", "a", "given", "port", "." ]
train
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/google/datalab/utils/_utils.py#L111-L125
googledatalab/pydatalab
google/datalab/utils/_utils.py
save_project_id
def save_project_id(project_id): """ Save project id to config file. Args: project_id: the project_id to save. """ # Try gcloud first. If gcloud fails (probably because it does not exist), then # write to a config file. try: subprocess.call(['gcloud', 'config', 'set', 'project', project_id]) exce...
python
def save_project_id(project_id): """ Save project id to config file. Args: project_id: the project_id to save. """ # Try gcloud first. If gcloud fails (probably because it does not exist), then # write to a config file. try: subprocess.call(['gcloud', 'config', 'set', 'project', project_id]) exce...
[ "def", "save_project_id", "(", "project_id", ")", ":", "# Try gcloud first. If gcloud fails (probably because it does not exist), then", "# write to a config file.", "try", ":", "subprocess", ".", "call", "(", "[", "'gcloud'", ",", "'config'", ",", "'set'", ",", "'project'"...
Save project id to config file. Args: project_id: the project_id to save.
[ "Save", "project", "id", "to", "config", "file", "." ]
train
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/google/datalab/utils/_utils.py#L222-L240
googledatalab/pydatalab
google/datalab/utils/_utils.py
get_default_project_id
def get_default_project_id(): """ Get default project id from config or environment var. Returns: the project id if available, or None. """ # Try getting default project id from gcloud. If it fails try config.json. try: proc = subprocess.Popen(['gcloud', 'config', 'list', '--format', 'value(core.project)...
python
def get_default_project_id(): """ Get default project id from config or environment var. Returns: the project id if available, or None. """ # Try getting default project id from gcloud. If it fails try config.json. try: proc = subprocess.Popen(['gcloud', 'config', 'list', '--format', 'value(core.project)...
[ "def", "get_default_project_id", "(", ")", ":", "# Try getting default project id from gcloud. If it fails try config.json.", "try", ":", "proc", "=", "subprocess", ".", "Popen", "(", "[", "'gcloud'", ",", "'config'", ",", "'list'", ",", "'--format'", ",", "'value(core....
Get default project id from config or environment var. Returns: the project id if available, or None.
[ "Get", "default", "project", "id", "from", "config", "or", "environment", "var", "." ]
train
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/google/datalab/utils/_utils.py#L243-L273
googledatalab/pydatalab
google/datalab/utils/_utils.py
_construct_context_for_args
def _construct_context_for_args(args): """Construct a new Context for the parsed arguments. Args: args: the dictionary of magic arguments. Returns: A new Context based on the current default context, but with any explicitly specified arguments overriding the default's config. """ global_default...
python
def _construct_context_for_args(args): """Construct a new Context for the parsed arguments. Args: args: the dictionary of magic arguments. Returns: A new Context based on the current default context, but with any explicitly specified arguments overriding the default's config. """ global_default...
[ "def", "_construct_context_for_args", "(", "args", ")", ":", "global_default_context", "=", "google", ".", "datalab", ".", "Context", ".", "default", "(", ")", "config", "=", "{", "}", "for", "key", "in", "global_default_context", ".", "config", ":", "config",...
Construct a new Context for the parsed arguments. Args: args: the dictionary of magic arguments. Returns: A new Context based on the current default context, but with any explicitly specified arguments overriding the default's config.
[ "Construct", "a", "new", "Context", "for", "the", "parsed", "arguments", "." ]
train
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/google/datalab/utils/_utils.py#L276-L297
googledatalab/pydatalab
google/datalab/utils/_utils.py
python_portable_string
def python_portable_string(string, encoding='utf-8'): """Converts bytes into a string type. Valid string types are retuned without modification. So in Python 2, type str and unicode are not converted. In Python 3, type bytes is converted to type str (unicode) """ if isinstance(string, six.string_types): ...
python
def python_portable_string(string, encoding='utf-8'): """Converts bytes into a string type. Valid string types are retuned without modification. So in Python 2, type str and unicode are not converted. In Python 3, type bytes is converted to type str (unicode) """ if isinstance(string, six.string_types): ...
[ "def", "python_portable_string", "(", "string", ",", "encoding", "=", "'utf-8'", ")", ":", "if", "isinstance", "(", "string", ",", "six", ".", "string_types", ")", ":", "return", "string", "if", "six", ".", "PY3", ":", "return", "string", ".", "decode", ...
Converts bytes into a string type. Valid string types are retuned without modification. So in Python 2, type str and unicode are not converted. In Python 3, type bytes is converted to type str (unicode)
[ "Converts", "bytes", "into", "a", "string", "type", "." ]
train
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/google/datalab/utils/_utils.py#L300-L314
googledatalab/pydatalab
datalab/storage/commands/_storage.py
_extract_storage_api_response_error
def _extract_storage_api_response_error(message): """ A helper function to extract user-friendly error messages from service exceptions. Args: message: An error message from an exception. If this is from our HTTP client code, it will actually be a tuple. Returns: A modified version of the messag...
python
def _extract_storage_api_response_error(message): """ A helper function to extract user-friendly error messages from service exceptions. Args: message: An error message from an exception. If this is from our HTTP client code, it will actually be a tuple. Returns: A modified version of the messag...
[ "def", "_extract_storage_api_response_error", "(", "message", ")", ":", "try", ":", "if", "len", "(", "message", ")", "==", "3", ":", "# Try treat the last part as JSON", "data", "=", "json", ".", "loads", "(", "message", "[", "2", "]", ")", "return", "data"...
A helper function to extract user-friendly error messages from service exceptions. Args: message: An error message from an exception. If this is from our HTTP client code, it will actually be a tuple. Returns: A modified version of the message that is less cryptic.
[ "A", "helper", "function", "to", "extract", "user", "-", "friendly", "error", "messages", "from", "service", "exceptions", "." ]
train
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/datalab/storage/commands/_storage.py#L34-L51
googledatalab/pydatalab
datalab/storage/commands/_storage.py
storage
def storage(line, cell=None): """Implements the storage cell magic for ipython notebooks. Args: line: the contents of the storage line. Returns: The results of executing the cell. """ parser = datalab.utils.commands.CommandParser(prog='storage', description=""" Execute various storage-related operati...
python
def storage(line, cell=None): """Implements the storage cell magic for ipython notebooks. Args: line: the contents of the storage line. Returns: The results of executing the cell. """ parser = datalab.utils.commands.CommandParser(prog='storage', description=""" Execute various storage-related operati...
[ "def", "storage", "(", "line", ",", "cell", "=", "None", ")", ":", "parser", "=", "datalab", ".", "utils", ".", "commands", ".", "CommandParser", "(", "prog", "=", "'storage'", ",", "description", "=", "\"\"\"\nExecute various storage-related operations. Use \"%st...
Implements the storage cell magic for ipython notebooks. Args: line: the contents of the storage line. Returns: The results of executing the cell.
[ "Implements", "the", "storage", "cell", "magic", "for", "ipython", "notebooks", "." ]
train
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/datalab/storage/commands/_storage.py#L55-L134
googledatalab/pydatalab
datalab/storage/commands/_storage.py
_expand_list
def _expand_list(names): """ Do a wildchar name expansion of object names in a list and return expanded list. The items are expected to exist as this is used for copy sources or delete targets. Currently we support wildchars in the key name only. """ if names is None: names = [] elif isinstance(na...
python
def _expand_list(names): """ Do a wildchar name expansion of object names in a list and return expanded list. The items are expected to exist as this is used for copy sources or delete targets. Currently we support wildchars in the key name only. """ if names is None: names = [] elif isinstance(na...
[ "def", "_expand_list", "(", "names", ")", ":", "if", "names", "is", "None", ":", "names", "=", "[", "]", "elif", "isinstance", "(", "names", ",", "basestring", ")", ":", "names", "=", "[", "names", "]", "results", "=", "[", "]", "# The expanded list.",...
Do a wildchar name expansion of object names in a list and return expanded list. The items are expected to exist as this is used for copy sources or delete targets. Currently we support wildchars in the key name only.
[ "Do", "a", "wildchar", "name", "expansion", "of", "object", "names", "in", "a", "list", "and", "return", "expanded", "list", "." ]
train
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/datalab/storage/commands/_storage.py#L144-L196
googledatalab/pydatalab
datalab/storage/commands/_storage.py
_storage_create
def _storage_create(args, _): """ Create one or more buckets. """ buckets = datalab.storage.Buckets(project_id=args['project']) errs = [] for name in args['bucket']: try: bucket, key = datalab.storage._bucket.parse_name(name) if bucket and not key: buckets.create(bucket) else: ...
python
def _storage_create(args, _): """ Create one or more buckets. """ buckets = datalab.storage.Buckets(project_id=args['project']) errs = [] for name in args['bucket']: try: bucket, key = datalab.storage._bucket.parse_name(name) if bucket and not key: buckets.create(bucket) else: ...
[ "def", "_storage_create", "(", "args", ",", "_", ")", ":", "buckets", "=", "datalab", ".", "storage", ".", "Buckets", "(", "project_id", "=", "args", "[", "'project'", "]", ")", "errs", "=", "[", "]", "for", "name", "in", "args", "[", "'bucket'", "]"...
Create one or more buckets.
[ "Create", "one", "or", "more", "buckets", "." ]
train
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/datalab/storage/commands/_storage.py#L229-L244
googledatalab/pydatalab
datalab/storage/commands/_storage.py
_storage_delete
def _storage_delete(args, _): """ Delete one or more buckets or objects. """ items = _expand_list(args['bucket']) items.extend(_expand_list(args['object'])) errs = [] for item in items: try: bucket, key = datalab.storage._bucket.parse_name(item) if bucket and key: gcs_item = datalab.st...
python
def _storage_delete(args, _): """ Delete one or more buckets or objects. """ items = _expand_list(args['bucket']) items.extend(_expand_list(args['object'])) errs = [] for item in items: try: bucket, key = datalab.storage._bucket.parse_name(item) if bucket and key: gcs_item = datalab.st...
[ "def", "_storage_delete", "(", "args", ",", "_", ")", ":", "items", "=", "_expand_list", "(", "args", "[", "'bucket'", "]", ")", "items", ".", "extend", "(", "_expand_list", "(", "args", "[", "'object'", "]", ")", ")", "errs", "=", "[", "]", "for", ...
Delete one or more buckets or objects.
[ "Delete", "one", "or", "more", "buckets", "or", "objects", "." ]
train
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/datalab/storage/commands/_storage.py#L247-L273
googledatalab/pydatalab
datalab/storage/commands/_storage.py
_storage_list_buckets
def _storage_list_buckets(project, pattern): """ List all storage buckets that match a pattern. """ data = [{'Bucket': 'gs://' + bucket.name, 'Created': bucket.metadata.created_on} for bucket in datalab.storage.Buckets(project_id=project) if fnmatch.fnmatch(bucket.name, pattern)] return datala...
python
def _storage_list_buckets(project, pattern): """ List all storage buckets that match a pattern. """ data = [{'Bucket': 'gs://' + bucket.name, 'Created': bucket.metadata.created_on} for bucket in datalab.storage.Buckets(project_id=project) if fnmatch.fnmatch(bucket.name, pattern)] return datala...
[ "def", "_storage_list_buckets", "(", "project", ",", "pattern", ")", ":", "data", "=", "[", "{", "'Bucket'", ":", "'gs://'", "+", "bucket", ".", "name", ",", "'Created'", ":", "bucket", ".", "metadata", ".", "created_on", "}", "for", "bucket", "in", "dat...
List all storage buckets that match a pattern.
[ "List", "all", "storage", "buckets", "that", "match", "a", "pattern", "." ]
train
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/datalab/storage/commands/_storage.py#L276-L281
googledatalab/pydatalab
datalab/storage/commands/_storage.py
_storage_get_keys
def _storage_get_keys(bucket, pattern): """ Get names of all storage keys in a specified bucket that match a pattern. """ return [item for item in list(bucket.items()) if fnmatch.fnmatch(item.metadata.name, pattern)]
python
def _storage_get_keys(bucket, pattern): """ Get names of all storage keys in a specified bucket that match a pattern. """ return [item for item in list(bucket.items()) if fnmatch.fnmatch(item.metadata.name, pattern)]
[ "def", "_storage_get_keys", "(", "bucket", ",", "pattern", ")", ":", "return", "[", "item", "for", "item", "in", "list", "(", "bucket", ".", "items", "(", ")", ")", "if", "fnmatch", ".", "fnmatch", "(", "item", ".", "metadata", ".", "name", ",", "pat...
Get names of all storage keys in a specified bucket that match a pattern.
[ "Get", "names", "of", "all", "storage", "keys", "in", "a", "specified", "bucket", "that", "match", "a", "pattern", "." ]
train
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/datalab/storage/commands/_storage.py#L284-L286
googledatalab/pydatalab
datalab/storage/commands/_storage.py
_storage_get_key_names
def _storage_get_key_names(bucket, pattern): """ Get names of all storage keys in a specified bucket that match a pattern. """ return [item.metadata.name for item in _storage_get_keys(bucket, pattern)]
python
def _storage_get_key_names(bucket, pattern): """ Get names of all storage keys in a specified bucket that match a pattern. """ return [item.metadata.name for item in _storage_get_keys(bucket, pattern)]
[ "def", "_storage_get_key_names", "(", "bucket", ",", "pattern", ")", ":", "return", "[", "item", ".", "metadata", ".", "name", "for", "item", "in", "_storage_get_keys", "(", "bucket", ",", "pattern", ")", "]" ]
Get names of all storage keys in a specified bucket that match a pattern.
[ "Get", "names", "of", "all", "storage", "keys", "in", "a", "specified", "bucket", "that", "match", "a", "pattern", "." ]
train
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/datalab/storage/commands/_storage.py#L289-L291
googledatalab/pydatalab
datalab/storage/commands/_storage.py
_storage_list_keys
def _storage_list_keys(bucket, pattern): """ List all storage keys in a specified bucket that match a pattern. """ data = [{'Name': item.metadata.name, 'Type': item.metadata.content_type, 'Size': item.metadata.size, 'Updated': item.metadata.updated_on} for item in _storage...
python
def _storage_list_keys(bucket, pattern): """ List all storage keys in a specified bucket that match a pattern. """ data = [{'Name': item.metadata.name, 'Type': item.metadata.content_type, 'Size': item.metadata.size, 'Updated': item.metadata.updated_on} for item in _storage...
[ "def", "_storage_list_keys", "(", "bucket", ",", "pattern", ")", ":", "data", "=", "[", "{", "'Name'", ":", "item", ".", "metadata", ".", "name", ",", "'Type'", ":", "item", ".", "metadata", ".", "content_type", ",", "'Size'", ":", "item", ".", "metada...
List all storage keys in a specified bucket that match a pattern.
[ "List", "all", "storage", "keys", "in", "a", "specified", "bucket", "that", "match", "a", "pattern", "." ]
train
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/datalab/storage/commands/_storage.py#L294-L301
googledatalab/pydatalab
datalab/storage/commands/_storage.py
_storage_list
def _storage_list(args, _): """ List the buckets or the contents of a bucket. This command is a bit different in that we allow wildchars in the bucket name and will list the buckets that match. """ target = args['object'] if args['object'] else args['bucket'] project = args['project'] if target is None: ...
python
def _storage_list(args, _): """ List the buckets or the contents of a bucket. This command is a bit different in that we allow wildchars in the bucket name and will list the buckets that match. """ target = args['object'] if args['object'] else args['bucket'] project = args['project'] if target is None: ...
[ "def", "_storage_list", "(", "args", ",", "_", ")", ":", "target", "=", "args", "[", "'object'", "]", "if", "args", "[", "'object'", "]", "else", "args", "[", "'bucket'", "]", "project", "=", "args", "[", "'project'", "]", "if", "target", "is", "None...
List the buckets or the contents of a bucket. This command is a bit different in that we allow wildchars in the bucket name and will list the buckets that match.
[ "List", "the", "buckets", "or", "the", "contents", "of", "a", "bucket", "." ]
train
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/datalab/storage/commands/_storage.py#L304-L341
googledatalab/pydatalab
google/datalab/bigquery/_api.py
Api.jobs_insert_query
def jobs_insert_query(self, sql, table_name=None, append=False, overwrite=False, dry_run=False, use_cache=True, batch=True, allow_large_results=False, table_definitions=None, query_params=None): """Issues a request to insert a query job. Args: sql: the SQL ...
python
def jobs_insert_query(self, sql, table_name=None, append=False, overwrite=False, dry_run=False, use_cache=True, batch=True, allow_large_results=False, table_definitions=None, query_params=None): """Issues a request to insert a query job. Args: sql: the SQL ...
[ "def", "jobs_insert_query", "(", "self", ",", "sql", ",", "table_name", "=", "None", ",", "append", "=", "False", ",", "overwrite", "=", "False", ",", "dry_run", "=", "False", ",", "use_cache", "=", "True", ",", "batch", "=", "True", ",", "allow_large_re...
Issues a request to insert a query job. Args: sql: the SQL string representing the query to execute. table_name: None for an anonymous table, or a name parts tuple for a long-lived table. append: if True, append to the table if it is non-empty; else the request will fail if table is non...
[ "Issues", "a", "request", "to", "insert", "a", "query", "job", "." ]
train
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/google/datalab/bigquery/_api.py#L134-L202
googledatalab/pydatalab
google/datalab/bigquery/_api.py
Api.jobs_query_results
def jobs_query_results(self, job_id, project_id, page_size, timeout, start_index=0): """Issues a request to the jobs/getQueryResults method. Args: job_id: the id of job from a previously executed query. project_id: the project id to use to fetch the results; use None for the default project. ...
python
def jobs_query_results(self, job_id, project_id, page_size, timeout, start_index=0): """Issues a request to the jobs/getQueryResults method. Args: job_id: the id of job from a previously executed query. project_id: the project id to use to fetch the results; use None for the default project. ...
[ "def", "jobs_query_results", "(", "self", ",", "job_id", ",", "project_id", ",", "page_size", ",", "timeout", ",", "start_index", "=", "0", ")", ":", "if", "timeout", "is", "None", ":", "timeout", "=", "Api", ".", "_DEFAULT_TIMEOUT", "if", "project_id", "i...
Issues a request to the jobs/getQueryResults method. Args: job_id: the id of job from a previously executed query. project_id: the project id to use to fetch the results; use None for the default project. page_size: limit to the number of rows to fetch. timeout: duration (in milliseconds) t...
[ "Issues", "a", "request", "to", "the", "jobs", "/", "getQueryResults", "method", "." ]
train
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/google/datalab/bigquery/_api.py#L204-L230
googledatalab/pydatalab
google/datalab/bigquery/_api.py
Api.tables_list
def tables_list(self, dataset_name, max_results=0, page_token=None): """Issues a request to retrieve a list of tables. Args: dataset_name: the name of the dataset to enumerate. max_results: an optional maximum number of tables to retrieve. page_token: an optional token to continue the retriev...
python
def tables_list(self, dataset_name, max_results=0, page_token=None): """Issues a request to retrieve a list of tables. Args: dataset_name: the name of the dataset to enumerate. max_results: an optional maximum number of tables to retrieve. page_token: an optional token to continue the retriev...
[ "def", "tables_list", "(", "self", ",", "dataset_name", ",", "max_results", "=", "0", ",", "page_token", "=", "None", ")", ":", "url", "=", "Api", ".", "_ENDPOINT", "+", "(", "Api", ".", "_TABLES_PATH", "%", "(", "dataset_name", ".", "project_id", ",", ...
Issues a request to retrieve a list of tables. Args: dataset_name: the name of the dataset to enumerate. max_results: an optional maximum number of tables to retrieve. page_token: an optional token to continue the retrieval. Returns: A parsed result object. Raises: Exception i...
[ "Issues", "a", "request", "to", "retrieve", "a", "list", "of", "tables", "." ]
train
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/google/datalab/bigquery/_api.py#L354-L375
googledatalab/pydatalab
solutionbox/ml_workbench/tensorflow/trainer/feature_transforms.py
_scale
def _scale(x, min_x_value, max_x_value, output_min, output_max): """Scale a column to [output_min, output_max]. Assumes the columns's range is [min_x_value, max_x_value]. If this is not true at training or prediction time, the output value of this scale could be outside the range [output_min, output_max]. R...
python
def _scale(x, min_x_value, max_x_value, output_min, output_max): """Scale a column to [output_min, output_max]. Assumes the columns's range is [min_x_value, max_x_value]. If this is not true at training or prediction time, the output value of this scale could be outside the range [output_min, output_max]. R...
[ "def", "_scale", "(", "x", ",", "min_x_value", ",", "max_x_value", ",", "output_min", ",", "output_max", ")", ":", "if", "round", "(", "min_x_value", "-", "max_x_value", ",", "7", ")", "==", "0", ":", "# There is something wrong with the data.", "# Why round to ...
Scale a column to [output_min, output_max]. Assumes the columns's range is [min_x_value, max_x_value]. If this is not true at training or prediction time, the output value of this scale could be outside the range [output_min, output_max]. Raises: ValueError: if min_x_value = max_x_value, as the column is ...
[ "Scale", "a", "column", "to", "[", "output_min", "output_max", "]", "." ]
train
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/solutionbox/ml_workbench/tensorflow/trainer/feature_transforms.py#L84-L108
googledatalab/pydatalab
solutionbox/ml_workbench/tensorflow/trainer/feature_transforms.py
_string_to_int
def _string_to_int(x, vocab): """Given a vocabulary and a string tensor `x`, maps `x` into an int tensor. Args: x: A `Column` representing a string value. vocab: list of strings. Returns: A `Column` where each string value is mapped to an integer representing its index in the vocab. Out of vocab ...
python
def _string_to_int(x, vocab): """Given a vocabulary and a string tensor `x`, maps `x` into an int tensor. Args: x: A `Column` representing a string value. vocab: list of strings. Returns: A `Column` where each string value is mapped to an integer representing its index in the vocab. Out of vocab ...
[ "def", "_string_to_int", "(", "x", ",", "vocab", ")", ":", "def", "_map_to_int", "(", "x", ")", ":", "\"\"\"Maps string tensor into indexes using vocab.\n\n Args:\n x : a Tensor/SparseTensor of string.\n Returns:\n a Tensor/SparseTensor of indexes (int) of the same shape ...
Given a vocabulary and a string tensor `x`, maps `x` into an int tensor. Args: x: A `Column` representing a string value. vocab: list of strings. Returns: A `Column` where each string value is mapped to an integer representing its index in the vocab. Out of vocab values are mapped to len(vocab).
[ "Given", "a", "vocabulary", "and", "a", "string", "tensor", "x", "maps", "x", "into", "an", "int", "tensor", ".", "Args", ":", "x", ":", "A", "Column", "representing", "a", "string", "value", ".", "vocab", ":", "list", "of", "strings", "." ]
train
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/solutionbox/ml_workbench/tensorflow/trainer/feature_transforms.py#L111-L135
googledatalab/pydatalab
solutionbox/ml_workbench/tensorflow/trainer/feature_transforms.py
_tfidf
def _tfidf(x, reduced_term_freq, vocab_size, corpus_size): """Maps the terms in x to their (1/doc_length) * inverse document frequency. Args: x: A `Column` representing int64 values (most likely that are the result of calling string_to_int on a tokenized string). reduced_term_freq: A dense tensor of...
python
def _tfidf(x, reduced_term_freq, vocab_size, corpus_size): """Maps the terms in x to their (1/doc_length) * inverse document frequency. Args: x: A `Column` representing int64 values (most likely that are the result of calling string_to_int on a tokenized string). reduced_term_freq: A dense tensor of...
[ "def", "_tfidf", "(", "x", ",", "reduced_term_freq", ",", "vocab_size", ",", "corpus_size", ")", ":", "def", "_map_to_vocab_range", "(", "x", ")", ":", "\"\"\"Enforces that the vocab_ids in x are positive.\"\"\"", "return", "tf", ".", "SparseTensor", "(", "indices", ...
Maps the terms in x to their (1/doc_length) * inverse document frequency. Args: x: A `Column` representing int64 values (most likely that are the result of calling string_to_int on a tokenized string). reduced_term_freq: A dense tensor of shape (vocab_size,) that represents the count of the nu...
[ "Maps", "the", "terms", "in", "x", "to", "their", "(", "1", "/", "doc_length", ")", "*", "inverse", "document", "frequency", ".", "Args", ":", "x", ":", "A", "Column", "representing", "int64", "values", "(", "most", "likely", "that", "are", "the", "res...
train
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/solutionbox/ml_workbench/tensorflow/trainer/feature_transforms.py#L140-L198
googledatalab/pydatalab
solutionbox/ml_workbench/tensorflow/trainer/feature_transforms.py
_bag_of_words
def _bag_of_words(x): """Computes bag of words weights Note the return type is a float sparse tensor, not a int sparse tensor. This is so that the output types batch tfidf, and any downstream transformation in tf layers during training can be applied to both. """ def _bow(x): """Comptue BOW weights. ...
python
def _bag_of_words(x): """Computes bag of words weights Note the return type is a float sparse tensor, not a int sparse tensor. This is so that the output types batch tfidf, and any downstream transformation in tf layers during training can be applied to both. """ def _bow(x): """Comptue BOW weights. ...
[ "def", "_bag_of_words", "(", "x", ")", ":", "def", "_bow", "(", "x", ")", ":", "\"\"\"Comptue BOW weights.\n\n As tf layer's sum combiner is used, the weights can be just ones. Tokens are\n not summed together here.\n \"\"\"", "return", "tf", ".", "SparseTensor", "(", "i...
Computes bag of words weights Note the return type is a float sparse tensor, not a int sparse tensor. This is so that the output types batch tfidf, and any downstream transformation in tf layers during training can be applied to both.
[ "Computes", "bag", "of", "words", "weights" ]
train
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/solutionbox/ml_workbench/tensorflow/trainer/feature_transforms.py#L203-L221
googledatalab/pydatalab
solutionbox/ml_workbench/tensorflow/trainer/feature_transforms.py
_make_image_to_vec_tito
def _make_image_to_vec_tito(feature_name, tmp_dir=None, checkpoint=None): """Creates a tensor-in-tensor-out function that produces embeddings from image bytes. Image to embedding is implemented with Tensorflow's inception v3 model and a pretrained checkpoint. It returns 1x2048 'PreLogits' embeddings for each ima...
python
def _make_image_to_vec_tito(feature_name, tmp_dir=None, checkpoint=None): """Creates a tensor-in-tensor-out function that produces embeddings from image bytes. Image to embedding is implemented with Tensorflow's inception v3 model and a pretrained checkpoint. It returns 1x2048 'PreLogits' embeddings for each ima...
[ "def", "_make_image_to_vec_tito", "(", "feature_name", ",", "tmp_dir", "=", "None", ",", "checkpoint", "=", "None", ")", ":", "def", "_image_to_vec", "(", "image_str_tensor", ")", ":", "def", "_decode_and_resize", "(", "image_tensor", ")", ":", "\"\"\"Decodes jpeg...
Creates a tensor-in-tensor-out function that produces embeddings from image bytes. Image to embedding is implemented with Tensorflow's inception v3 model and a pretrained checkpoint. It returns 1x2048 'PreLogits' embeddings for each image. Args: feature_name: The name of the feature. Used only to identify t...
[ "Creates", "a", "tensor", "-", "in", "-", "tensor", "-", "out", "function", "that", "produces", "embeddings", "from", "image", "bytes", "." ]
train
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/solutionbox/ml_workbench/tensorflow/trainer/feature_transforms.py#L224-L336
googledatalab/pydatalab
solutionbox/ml_workbench/tensorflow/trainer/feature_transforms.py
make_preprocessing_fn
def make_preprocessing_fn(output_dir, features, keep_target): """Makes a preprocessing function. Args: output_dir: folder path that contains the vocab and stats files. features: the features dict Returns: a function that takes a dict of input tensors """ def preprocessing_fn(inputs): """Prep...
python
def make_preprocessing_fn(output_dir, features, keep_target): """Makes a preprocessing function. Args: output_dir: folder path that contains the vocab and stats files. features: the features dict Returns: a function that takes a dict of input tensors """ def preprocessing_fn(inputs): """Prep...
[ "def", "make_preprocessing_fn", "(", "output_dir", ",", "features", ",", "keep_target", ")", ":", "def", "preprocessing_fn", "(", "inputs", ")", ":", "\"\"\"Preprocessing function.\n\n Args:\n inputs: dictionary of raw input tensors\n\n Returns:\n A dictionary of tran...
Makes a preprocessing function. Args: output_dir: folder path that contains the vocab and stats files. features: the features dict Returns: a function that takes a dict of input tensors
[ "Makes", "a", "preprocessing", "function", "." ]
train
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/solutionbox/ml_workbench/tensorflow/trainer/feature_transforms.py#L344-L432
googledatalab/pydatalab
solutionbox/ml_workbench/tensorflow/trainer/feature_transforms.py
get_transformed_feature_info
def get_transformed_feature_info(features, schema): """Returns information about the transformed features. Returns: Dict in the from {transformed_feature_name: {dtype: tf type, size: int or None}}. If the size is None, then the tensor is a sparse tensor. """ info = collections.defaultdict(dict) ...
python
def get_transformed_feature_info(features, schema): """Returns information about the transformed features. Returns: Dict in the from {transformed_feature_name: {dtype: tf type, size: int or None}}. If the size is None, then the tensor is a sparse tensor. """ info = collections.defaultdict(dict) ...
[ "def", "get_transformed_feature_info", "(", "features", ",", "schema", ")", ":", "info", "=", "collections", ".", "defaultdict", "(", "dict", ")", "for", "name", ",", "transform", "in", "six", ".", "iteritems", "(", "features", ")", ":", "transform_name", "=...
Returns information about the transformed features. Returns: Dict in the from {transformed_feature_name: {dtype: tf type, size: int or None}}. If the size is None, then the tensor is a sparse tensor.
[ "Returns", "information", "about", "the", "transformed", "features", "." ]
train
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/solutionbox/ml_workbench/tensorflow/trainer/feature_transforms.py#L435-L500
googledatalab/pydatalab
solutionbox/ml_workbench/tensorflow/trainer/feature_transforms.py
csv_header_and_defaults
def csv_header_and_defaults(features, schema, stats, keep_target): """Gets csv header and default lists.""" target_name = get_target_name(features) if keep_target and not target_name: raise ValueError('Cannot find target transform') csv_header = [] record_defaults = [] for col in schema: if not ke...
python
def csv_header_and_defaults(features, schema, stats, keep_target): """Gets csv header and default lists.""" target_name = get_target_name(features) if keep_target and not target_name: raise ValueError('Cannot find target transform') csv_header = [] record_defaults = [] for col in schema: if not ke...
[ "def", "csv_header_and_defaults", "(", "features", ",", "schema", ",", "stats", ",", "keep_target", ")", ":", "target_name", "=", "get_target_name", "(", "features", ")", "if", "keep_target", "and", "not", "target_name", ":", "raise", "ValueError", "(", "'Cannot...
Gets csv header and default lists.
[ "Gets", "csv", "header", "and", "default", "lists", "." ]
train
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/solutionbox/ml_workbench/tensorflow/trainer/feature_transforms.py#L503-L531
googledatalab/pydatalab
solutionbox/ml_workbench/tensorflow/trainer/feature_transforms.py
build_csv_serving_tensors_for_transform_step
def build_csv_serving_tensors_for_transform_step(analysis_path, features, schema, stats, keep_target): """Builds a serving...
python
def build_csv_serving_tensors_for_transform_step(analysis_path, features, schema, stats, keep_target): """Builds a serving...
[ "def", "build_csv_serving_tensors_for_transform_step", "(", "analysis_path", ",", "features", ",", "schema", ",", "stats", ",", "keep_target", ")", ":", "csv_header", ",", "record_defaults", "=", "csv_header_and_defaults", "(", "features", ",", "schema", ",", "stats",...
Builds a serving function starting from raw csv. This should only be used by transform.py (the transform step), and the For image columns, the image should be a base64 string encoding the image. The output of this function will transform that image to a 2048 long vector using the inception model.
[ "Builds", "a", "serving", "function", "starting", "from", "raw", "csv", "." ]
train
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/solutionbox/ml_workbench/tensorflow/trainer/feature_transforms.py#L534-L567
googledatalab/pydatalab
solutionbox/ml_workbench/tensorflow/trainer/feature_transforms.py
build_csv_serving_tensors_for_training_step
def build_csv_serving_tensors_for_training_step(analysis_path, features, schema, stats, keep_target): """Builds a serving func...
python
def build_csv_serving_tensors_for_training_step(analysis_path, features, schema, stats, keep_target): """Builds a serving func...
[ "def", "build_csv_serving_tensors_for_training_step", "(", "analysis_path", ",", "features", ",", "schema", ",", "stats", ",", "keep_target", ")", ":", "transformed_features", ",", "_", ",", "placeholder_dict", "=", "build_csv_serving_tensors_for_transform_step", "(", "an...
Builds a serving function starting from raw csv, used at model export time. For image columns, the image should be a base64 string encoding the image. The output of this function will transform that image to a 2048 long vector using the inception model and then a fully connected net is attached to the 2048 lon...
[ "Builds", "a", "serving", "function", "starting", "from", "raw", "csv", "used", "at", "model", "export", "time", "." ]
train
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/solutionbox/ml_workbench/tensorflow/trainer/feature_transforms.py#L570-L595
googledatalab/pydatalab
solutionbox/ml_workbench/tensorflow/trainer/feature_transforms.py
build_csv_transforming_training_input_fn
def build_csv_transforming_training_input_fn(schema, features, stats, analysis_output_dir, raw_data_file_pattern, ...
python
def build_csv_transforming_training_input_fn(schema, features, stats, analysis_output_dir, raw_data_file_pattern, ...
[ "def", "build_csv_transforming_training_input_fn", "(", "schema", ",", "features", ",", "stats", ",", "analysis_output_dir", ",", "raw_data_file_pattern", ",", "training_batch_size", ",", "num_epochs", "=", "None", ",", "randomize_input", "=", "False", ",", "min_after_d...
Creates training input_fn that reads raw csv data and applies transforms. Args: schema: schema list features: features dict stats: stats dict analysis_output_dir: output folder from analysis raw_data_file_pattern: file path, or list of files training_batch_size: An int specifying the batch si...
[ "Creates", "training", "input_fn", "that", "reads", "raw", "csv", "data", "and", "applies", "transforms", "." ]
train
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/solutionbox/ml_workbench/tensorflow/trainer/feature_transforms.py#L598-L698
googledatalab/pydatalab
solutionbox/ml_workbench/tensorflow/trainer/feature_transforms.py
build_tfexample_transfored_training_input_fn
def build_tfexample_transfored_training_input_fn(schema, features, analysis_output_dir, raw_data_file_pattern, training_batc...
python
def build_tfexample_transfored_training_input_fn(schema, features, analysis_output_dir, raw_data_file_pattern, training_batc...
[ "def", "build_tfexample_transfored_training_input_fn", "(", "schema", ",", "features", ",", "analysis_output_dir", ",", "raw_data_file_pattern", ",", "training_batch_size", ",", "num_epochs", "=", "None", ",", "randomize_input", "=", "False", ",", "min_after_dequeue", "="...
Creates training input_fn that reads transformed tf.example files. Args: schema: schema list features: features dict analysis_output_dir: output folder from analysis raw_data_file_pattern: file path, or list of files training_batch_size: An int specifying the batch size to use. num_epochs: nu...
[ "Creates", "training", "input_fn", "that", "reads", "transformed", "tf", ".", "example", "files", "." ]
train
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/solutionbox/ml_workbench/tensorflow/trainer/feature_transforms.py#L701-L806
googledatalab/pydatalab
solutionbox/ml_workbench/tensorflow/trainer/feature_transforms.py
image_feature_engineering
def image_feature_engineering(features, feature_tensors_dict): """Add a hidden layer on image features. Args: features: features dict feature_tensors_dict: dict of feature-name: tensor """ engineered_features = {} for name, feature_tensor in six.iteritems(feature_tensors_dict): if name in feature...
python
def image_feature_engineering(features, feature_tensors_dict): """Add a hidden layer on image features. Args: features: features dict feature_tensors_dict: dict of feature-name: tensor """ engineered_features = {} for name, feature_tensor in six.iteritems(feature_tensors_dict): if name in feature...
[ "def", "image_feature_engineering", "(", "features", ",", "feature_tensors_dict", ")", ":", "engineered_features", "=", "{", "}", "for", "name", ",", "feature_tensor", "in", "six", ".", "iteritems", "(", "feature_tensors_dict", ")", ":", "if", "name", "in", "fea...
Add a hidden layer on image features. Args: features: features dict feature_tensors_dict: dict of feature-name: tensor
[ "Add", "a", "hidden", "layer", "on", "image", "features", "." ]
train
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/solutionbox/ml_workbench/tensorflow/trainer/feature_transforms.py#L809-L826
googledatalab/pydatalab
solutionbox/ml_workbench/tensorflow/trainer/feature_transforms.py
read_vocab_file
def read_vocab_file(file_path): """Reads a vocab file to memeory. Args: file_path: Each line of the vocab is in the form "token,example_count" Returns: Two lists, one for the vocab, and one for just the example counts. """ with file_io.FileIO(file_path, 'r') as f: vocab_pd = pd.read_csv( ...
python
def read_vocab_file(file_path): """Reads a vocab file to memeory. Args: file_path: Each line of the vocab is in the form "token,example_count" Returns: Two lists, one for the vocab, and one for just the example counts. """ with file_io.FileIO(file_path, 'r') as f: vocab_pd = pd.read_csv( ...
[ "def", "read_vocab_file", "(", "file_path", ")", ":", "with", "file_io", ".", "FileIO", "(", "file_path", ",", "'r'", ")", "as", "f", ":", "vocab_pd", "=", "pd", ".", "read_csv", "(", "f", ",", "header", "=", "None", ",", "names", "=", "[", "'vocab'"...
Reads a vocab file to memeory. Args: file_path: Each line of the vocab is in the form "token,example_count" Returns: Two lists, one for the vocab, and one for just the example counts.
[ "Reads", "a", "vocab", "file", "to", "memeory", "." ]
train
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/solutionbox/ml_workbench/tensorflow/trainer/feature_transforms.py#L837-L857
googledatalab/pydatalab
google/datalab/bigquery/_external_data_source.py
ExternalDataSource._to_query_json
def _to_query_json(self): """ Return the table as a dictionary to be used as JSON in a query job. """ json = { 'compression': 'GZIP' if self._compressed else 'NONE', 'ignoreUnknownValues': self._ignore_unknown_values, 'maxBadRecords': self._max_bad_records, 'sourceFormat': self._bq_sourc...
python
def _to_query_json(self): """ Return the table as a dictionary to be used as JSON in a query job. """ json = { 'compression': 'GZIP' if self._compressed else 'NONE', 'ignoreUnknownValues': self._ignore_unknown_values, 'maxBadRecords': self._max_bad_records, 'sourceFormat': self._bq_sourc...
[ "def", "_to_query_json", "(", "self", ")", ":", "json", "=", "{", "'compression'", ":", "'GZIP'", "if", "self", ".", "_compressed", "else", "'NONE'", ",", "'ignoreUnknownValues'", ":", "self", ".", "_ignore_unknown_values", ",", "'maxBadRecords'", ":", "self", ...
Return the table as a dictionary to be used as JSON in a query job.
[ "Return", "the", "table", "as", "a", "dictionary", "to", "be", "used", "as", "JSON", "in", "a", "query", "job", "." ]
train
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/google/datalab/bigquery/_external_data_source.py#L70-L84
googledatalab/pydatalab
google/datalab/kernel/__init__.py
load_ipython_extension
def load_ipython_extension(shell): """ Called when the extension is loaded. Args: shell - (NotebookWebApplication): handle to the Notebook interactive shell instance. """ # Inject our user agent on all requests by monkey-patching a wrapper around httplib2.Http.request. def _request(self, uri, metho...
python
def load_ipython_extension(shell): """ Called when the extension is loaded. Args: shell - (NotebookWebApplication): handle to the Notebook interactive shell instance. """ # Inject our user agent on all requests by monkey-patching a wrapper around httplib2.Http.request. def _request(self, uri, metho...
[ "def", "load_ipython_extension", "(", "shell", ")", ":", "# Inject our user agent on all requests by monkey-patching a wrapper around httplib2.Http.request.", "def", "_request", "(", "self", ",", "uri", ",", "method", "=", "\"GET\"", ",", "body", "=", "None", ",", "header...
Called when the extension is loaded. Args: shell - (NotebookWebApplication): handle to the Notebook interactive shell instance.
[ "Called", "when", "the", "extension", "is", "loaded", "." ]
train
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/google/datalab/kernel/__init__.py#L44-L122
googledatalab/pydatalab
datalab/data/_sql_module.py
SqlModule._get_sql_args
def _get_sql_args(parser, args=None): """ Parse a set of %%sql arguments or get the default value of the arguments. Args: parser: the argument parser to use. args: the argument flags. May be a string or a list. If omitted the empty string is used so we can get the default values for the a...
python
def _get_sql_args(parser, args=None): """ Parse a set of %%sql arguments or get the default value of the arguments. Args: parser: the argument parser to use. args: the argument flags. May be a string or a list. If omitted the empty string is used so we can get the default values for the a...
[ "def", "_get_sql_args", "(", "parser", ",", "args", "=", "None", ")", ":", "overrides", "=", "None", "if", "args", "is", "None", ":", "tokens", "=", "[", "]", "elif", "isinstance", "(", "args", ",", "basestring", ")", ":", "command_line", "=", "' '", ...
Parse a set of %%sql arguments or get the default value of the arguments. Args: parser: the argument parser to use. args: the argument flags. May be a string or a list. If omitted the empty string is used so we can get the default values for the arguments. These are all used to override the ...
[ "Parse", "a", "set", "of", "%%sql", "arguments", "or", "get", "the", "default", "value", "of", "the", "arguments", "." ]
train
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/datalab/data/_sql_module.py#L33-L62
googledatalab/pydatalab
datalab/data/_sql_module.py
SqlModule.get_sql_statement_with_environment
def get_sql_statement_with_environment(item, args=None): """ Given a SQLStatement, string or module plus command line args or a dictionary, return a SqlStatement and final dictionary for variable resolution. Args: item: a SqlStatement, %%sql module, or string containing a query. args: a string...
python
def get_sql_statement_with_environment(item, args=None): """ Given a SQLStatement, string or module plus command line args or a dictionary, return a SqlStatement and final dictionary for variable resolution. Args: item: a SqlStatement, %%sql module, or string containing a query. args: a string...
[ "def", "get_sql_statement_with_environment", "(", "item", ",", "args", "=", "None", ")", ":", "if", "isinstance", "(", "item", ",", "basestring", ")", ":", "item", "=", "_sql_statement", ".", "SqlStatement", "(", "item", ")", "elif", "not", "isinstance", "("...
Given a SQLStatement, string or module plus command line args or a dictionary, return a SqlStatement and final dictionary for variable resolution. Args: item: a SqlStatement, %%sql module, or string containing a query. args: a string of command line arguments or a dictionary of values. Return...
[ "Given", "a", "SQLStatement", "string", "or", "module", "plus", "command", "line", "args", "or", "a", "dictionary", "return", "a", "SqlStatement", "and", "final", "dictionary", "for", "variable", "resolution", "." ]
train
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/datalab/data/_sql_module.py#L77-L107
googledatalab/pydatalab
datalab/data/_sql_module.py
SqlModule.expand
def expand(sql, args=None): """ Expand a SqlStatement, query string or SqlModule with a set of arguments. Args: sql: a SqlStatement, %%sql module, or string containing a query. args: a string of command line arguments or a dictionary of values. If a string, it is passed to the argument pa...
python
def expand(sql, args=None): """ Expand a SqlStatement, query string or SqlModule with a set of arguments. Args: sql: a SqlStatement, %%sql module, or string containing a query. args: a string of command line arguments or a dictionary of values. If a string, it is passed to the argument pa...
[ "def", "expand", "(", "sql", ",", "args", "=", "None", ")", ":", "sql", ",", "args", "=", "SqlModule", ".", "get_sql_statement_with_environment", "(", "sql", ",", "args", ")", "return", "_sql_statement", ".", "SqlStatement", ".", "format", "(", "sql", ".",...
Expand a SqlStatement, query string or SqlModule with a set of arguments. Args: sql: a SqlStatement, %%sql module, or string containing a query. args: a string of command line arguments or a dictionary of values. If a string, it is passed to the argument parser for the SqlModule associated wi...
[ "Expand", "a", "SqlStatement", "query", "string", "or", "SqlModule", "with", "a", "set", "of", "arguments", "." ]
train
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/datalab/data/_sql_module.py#L110-L124
googledatalab/pydatalab
google/datalab/bigquery/_utils.py
parse_dataset_name
def parse_dataset_name(name, project_id=None): """Parses a dataset name into its individual parts. Args: name: the name to parse, or a tuple, dictionary or array containing the parts. project_id: the expected project ID. If the name does not contain a project ID, this will be used; if the name does...
python
def parse_dataset_name(name, project_id=None): """Parses a dataset name into its individual parts. Args: name: the name to parse, or a tuple, dictionary or array containing the parts. project_id: the expected project ID. If the name does not contain a project ID, this will be used; if the name does...
[ "def", "parse_dataset_name", "(", "name", ",", "project_id", "=", "None", ")", ":", "_project_id", "=", "_dataset_id", "=", "None", "if", "isinstance", "(", "name", ",", "basestring", ")", ":", "# Try to parse as absolute name first.", "m", "=", "re", ".", "ma...
Parses a dataset name into its individual parts. Args: name: the name to parse, or a tuple, dictionary or array containing the parts. project_id: the expected project ID. If the name does not contain a project ID, this will be used; if the name does contain a project ID and it does not match ...
[ "Parses", "a", "dataset", "name", "into", "its", "individual", "parts", "." ]
train
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/google/datalab/bigquery/_utils.py#L58-L102
googledatalab/pydatalab
google/datalab/bigquery/_utils.py
parse_table_name
def parse_table_name(name, project_id=None, dataset_id=None): """Parses a table name into its individual parts. Args: name: the name to parse, or a tuple, dictionary or array containing the parts. project_id: the expected project ID. If the name does not contain a project ID, this will be used; if ...
python
def parse_table_name(name, project_id=None, dataset_id=None): """Parses a table name into its individual parts. Args: name: the name to parse, or a tuple, dictionary or array containing the parts. project_id: the expected project ID. If the name does not contain a project ID, this will be used; if ...
[ "def", "parse_table_name", "(", "name", ",", "project_id", "=", "None", ",", "dataset_id", "=", "None", ")", ":", "_project_id", "=", "_dataset_id", "=", "_table_id", "=", "_decorator", "=", "None", "if", "isinstance", "(", "name", ",", "basestring", ")", ...
Parses a table name into its individual parts. Args: name: the name to parse, or a tuple, dictionary or array containing the parts. project_id: the expected project ID. If the name does not contain a project ID, this will be used; if the name does contain a project ID and it does not match th...
[ "Parses", "a", "table", "name", "into", "its", "individual", "parts", "." ]
train
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/google/datalab/bigquery/_utils.py#L105-L166
googledatalab/pydatalab
google/datalab/utils/commands/_chart.py
chart
def chart(line, cell=None): """ Generate charts with Google Charts. Use %chart --help for more details. """ parser = _commands.CommandParser(prog='%chart', description=""" Generate an inline chart using Google Charts using the data in a Table, Query, dataframe, or list. Numerous types of charts are supported. Optio...
python
def chart(line, cell=None): """ Generate charts with Google Charts. Use %chart --help for more details. """ parser = _commands.CommandParser(prog='%chart', description=""" Generate an inline chart using Google Charts using the data in a Table, Query, dataframe, or list. Numerous types of charts are supported. Optio...
[ "def", "chart", "(", "line", ",", "cell", "=", "None", ")", ":", "parser", "=", "_commands", ".", "CommandParser", "(", "prog", "=", "'%chart'", ",", "description", "=", "\"\"\"\nGenerate an inline chart using Google Charts using the data in a Table, Query, dataframe, or ...
Generate charts with Google Charts. Use %chart --help for more details.
[ "Generate", "charts", "with", "Google", "Charts", ".", "Use", "%chart", "--", "help", "for", "more", "details", "." ]
train
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/google/datalab/utils/commands/_chart.py#L29-L49
googledatalab/pydatalab
google/datalab/contrib/mlworkbench/_prediction_explainer.py
PredictionExplainer._make_text_predict_fn
def _make_text_predict_fn(self, labels, instance, column_to_explain): """Create a predict_fn that can be used by LIME text explainer. """ def _predict_fn(perturbed_text): predict_input = [] for x in perturbed_text: instance_copy = dict(instance) i...
python
def _make_text_predict_fn(self, labels, instance, column_to_explain): """Create a predict_fn that can be used by LIME text explainer. """ def _predict_fn(perturbed_text): predict_input = [] for x in perturbed_text: instance_copy = dict(instance) i...
[ "def", "_make_text_predict_fn", "(", "self", ",", "labels", ",", "instance", ",", "column_to_explain", ")", ":", "def", "_predict_fn", "(", "perturbed_text", ")", ":", "predict_input", "=", "[", "]", "for", "x", "in", "perturbed_text", ":", "instance_copy", "=...
Create a predict_fn that can be used by LIME text explainer.
[ "Create", "a", "predict_fn", "that", "can", "be", "used", "by", "LIME", "text", "explainer", "." ]
train
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/google/datalab/contrib/mlworkbench/_prediction_explainer.py#L56-L71
googledatalab/pydatalab
google/datalab/contrib/mlworkbench/_prediction_explainer.py
PredictionExplainer._make_image_predict_fn
def _make_image_predict_fn(self, labels, instance, column_to_explain): """Create a predict_fn that can be used by LIME image explainer. """ def _predict_fn(perturbed_image): predict_input = [] for x in perturbed_image: instance_copy = dict(instance) ...
python
def _make_image_predict_fn(self, labels, instance, column_to_explain): """Create a predict_fn that can be used by LIME image explainer. """ def _predict_fn(perturbed_image): predict_input = [] for x in perturbed_image: instance_copy = dict(instance) ...
[ "def", "_make_image_predict_fn", "(", "self", ",", "labels", ",", "instance", ",", "column_to_explain", ")", ":", "def", "_predict_fn", "(", "perturbed_image", ")", ":", "predict_input", "=", "[", "]", "for", "x", "in", "perturbed_image", ":", "instance_copy", ...
Create a predict_fn that can be used by LIME image explainer.
[ "Create", "a", "predict_fn", "that", "can", "be", "used", "by", "LIME", "image", "explainer", "." ]
train
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/google/datalab/contrib/mlworkbench/_prediction_explainer.py#L73-L90
googledatalab/pydatalab
google/datalab/contrib/mlworkbench/_prediction_explainer.py
PredictionExplainer._get_unique_categories
def _get_unique_categories(self, df): """Get all categories for each categorical columns from training data.""" categories = [] for col in self._categorical_columns: categocial = pd.Categorical(df[col]) col_categories = list(map(str, categocial.categories)) c...
python
def _get_unique_categories(self, df): """Get all categories for each categorical columns from training data.""" categories = [] for col in self._categorical_columns: categocial = pd.Categorical(df[col]) col_categories = list(map(str, categocial.categories)) c...
[ "def", "_get_unique_categories", "(", "self", ",", "df", ")", ":", "categories", "=", "[", "]", "for", "col", "in", "self", ".", "_categorical_columns", ":", "categocial", "=", "pd", ".", "Categorical", "(", "df", "[", "col", "]", ")", "col_categories", ...
Get all categories for each categorical columns from training data.
[ "Get", "all", "categories", "for", "each", "categorical", "columns", "from", "training", "data", "." ]
train
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/google/datalab/contrib/mlworkbench/_prediction_explainer.py#L92-L101
googledatalab/pydatalab
google/datalab/contrib/mlworkbench/_prediction_explainer.py
PredictionExplainer._preprocess_data_for_tabular_explain
def _preprocess_data_for_tabular_explain(self, df, categories): """Get preprocessed training set in numpy array, and categorical names from raw training data. LIME tabular explainer requires a training set to know the distribution of numeric and categorical values. The training set has to be nu...
python
def _preprocess_data_for_tabular_explain(self, df, categories): """Get preprocessed training set in numpy array, and categorical names from raw training data. LIME tabular explainer requires a training set to know the distribution of numeric and categorical values. The training set has to be nu...
[ "def", "_preprocess_data_for_tabular_explain", "(", "self", ",", "df", ",", "categories", ")", ":", "df", "=", "df", ".", "copy", "(", ")", "# Remove non tabular columns (text, image).", "for", "col", "in", "list", "(", "df", ".", "columns", ")", ":", "if", ...
Get preprocessed training set in numpy array, and categorical names from raw training data. LIME tabular explainer requires a training set to know the distribution of numeric and categorical values. The training set has to be numpy arrays, with all categorical values converted to indices. It al...
[ "Get", "preprocessed", "training", "set", "in", "numpy", "array", "and", "categorical", "names", "from", "raw", "training", "data", "." ]
train
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/google/datalab/contrib/mlworkbench/_prediction_explainer.py#L103-L128
googledatalab/pydatalab
google/datalab/contrib/mlworkbench/_prediction_explainer.py
PredictionExplainer._make_tabular_predict_fn
def _make_tabular_predict_fn(self, labels, instance, categories): """Create a predict_fn that can be used by LIME tabular explainer. """ def _predict_fn(np_instance): df = pd.DataFrame( np_instance, columns=(self._categorical_columns + self._numeric_columns)...
python
def _make_tabular_predict_fn(self, labels, instance, categories): """Create a predict_fn that can be used by LIME tabular explainer. """ def _predict_fn(np_instance): df = pd.DataFrame( np_instance, columns=(self._categorical_columns + self._numeric_columns)...
[ "def", "_make_tabular_predict_fn", "(", "self", ",", "labels", ",", "instance", ",", "categories", ")", ":", "def", "_predict_fn", "(", "np_instance", ")", ":", "df", "=", "pd", ".", "DataFrame", "(", "np_instance", ",", "columns", "=", "(", "self", ".", ...
Create a predict_fn that can be used by LIME tabular explainer.
[ "Create", "a", "predict_fn", "that", "can", "be", "used", "by", "LIME", "tabular", "explainer", "." ]
train
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/google/datalab/contrib/mlworkbench/_prediction_explainer.py#L130-L155
googledatalab/pydatalab
google/datalab/contrib/mlworkbench/_prediction_explainer.py
PredictionExplainer.explain_tabular
def explain_tabular(self, trainset, labels, instance, num_features=5, kernel_width=3): """Explain categorical and numeric features for a prediction. It analyze the prediction by LIME, and returns a report of the most impactful tabular features contributing to certain labels. Args: ...
python
def explain_tabular(self, trainset, labels, instance, num_features=5, kernel_width=3): """Explain categorical and numeric features for a prediction. It analyze the prediction by LIME, and returns a report of the most impactful tabular features contributing to certain labels. Args: ...
[ "def", "explain_tabular", "(", "self", ",", "trainset", ",", "labels", ",", "instance", ",", "num_features", "=", "5", ",", "kernel_width", "=", "3", ")", ":", "from", "lime", ".", "lime_tabular", "import", "LimeTabularExplainer", "if", "isinstance", "(", "i...
Explain categorical and numeric features for a prediction. It analyze the prediction by LIME, and returns a report of the most impactful tabular features contributing to certain labels. Args: trainset: a DataFrame representing the training features that LIME can use to decide ...
[ "Explain", "categorical", "and", "numeric", "features", "for", "a", "prediction", "." ]
train
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/google/datalab/contrib/mlworkbench/_prediction_explainer.py#L157-L199
googledatalab/pydatalab
google/datalab/contrib/mlworkbench/_prediction_explainer.py
PredictionExplainer.explain_text
def explain_text(self, labels, instance, column_name=None, num_features=10, num_samples=5000): """Explain a text field of a prediction. It analyze the prediction by LIME, and returns a report of which words are most impactful in contributing to certain labels. Args: labels: a...
python
def explain_text(self, labels, instance, column_name=None, num_features=10, num_samples=5000): """Explain a text field of a prediction. It analyze the prediction by LIME, and returns a report of which words are most impactful in contributing to certain labels. Args: labels: a...
[ "def", "explain_text", "(", "self", ",", "labels", ",", "instance", ",", "column_name", "=", "None", ",", "num_features", "=", "10", ",", "num_samples", "=", "5000", ")", ":", "from", "lime", ".", "lime_text", "import", "LimeTextExplainer", "if", "len", "(...
Explain a text field of a prediction. It analyze the prediction by LIME, and returns a report of which words are most impactful in contributing to certain labels. Args: labels: a list of labels to explain. instance: the prediction instance. It needs to conform to model's in...
[ "Explain", "a", "text", "field", "of", "a", "prediction", "." ]
train
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/google/datalab/contrib/mlworkbench/_prediction_explainer.py#L201-L244
googledatalab/pydatalab
google/datalab/contrib/mlworkbench/_prediction_explainer.py
PredictionExplainer.explain_image
def explain_image(self, labels, instance, column_name=None, num_features=100000, num_samples=300, batch_size=200, hide_color=0): """Explain an image of a prediction. It analyze the prediction by LIME, and returns a report of which words are most impactful in contributing t...
python
def explain_image(self, labels, instance, column_name=None, num_features=100000, num_samples=300, batch_size=200, hide_color=0): """Explain an image of a prediction. It analyze the prediction by LIME, and returns a report of which words are most impactful in contributing t...
[ "def", "explain_image", "(", "self", ",", "labels", ",", "instance", ",", "column_name", "=", "None", ",", "num_features", "=", "100000", ",", "num_samples", "=", "300", ",", "batch_size", "=", "200", ",", "hide_color", "=", "0", ")", ":", "from", "lime"...
Explain an image of a prediction. It analyze the prediction by LIME, and returns a report of which words are most impactful in contributing to certain labels. Args: labels: a list of labels to explain. instance: the prediction instance. It needs to conform to model's input....
[ "Explain", "an", "image", "of", "a", "prediction", "." ]
train
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/google/datalab/contrib/mlworkbench/_prediction_explainer.py#L246-L299
googledatalab/pydatalab
google/datalab/contrib/mlworkbench/_prediction_explainer.py
PredictionExplainer._image_gradients
def _image_gradients(self, input_csvlines, label, image_column_name): """Compute gradients from prob of label to image. Used by integrated gradients (probe).""" with tf.Graph().as_default() as g, tf.Session() as sess: logging_level = tf.logging.get_verbosity() try: ...
python
def _image_gradients(self, input_csvlines, label, image_column_name): """Compute gradients from prob of label to image. Used by integrated gradients (probe).""" with tf.Graph().as_default() as g, tf.Session() as sess: logging_level = tf.logging.get_verbosity() try: ...
[ "def", "_image_gradients", "(", "self", ",", "input_csvlines", ",", "label", ",", "image_column_name", ")", ":", "with", "tf", ".", "Graph", "(", ")", ".", "as_default", "(", ")", "as", "g", ",", "tf", ".", "Session", "(", ")", "as", "sess", ":", "lo...
Compute gradients from prob of label to image. Used by integrated gradients (probe).
[ "Compute", "gradients", "from", "prob", "of", "label", "to", "image", ".", "Used", "by", "integrated", "gradients", "(", "probe", ")", "." ]
train
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/google/datalab/contrib/mlworkbench/_prediction_explainer.py#L301-L332
googledatalab/pydatalab
google/datalab/contrib/mlworkbench/_prediction_explainer.py
PredictionExplainer.probe_image
def probe_image(self, labels, instance, column_name=None, num_scaled_images=50, top_percent=10): """ Get pixel importance of the image. It performs pixel sensitivity analysis by showing only the most important pixels to a certain label in the image. It uses integrated gradie...
python
def probe_image(self, labels, instance, column_name=None, num_scaled_images=50, top_percent=10): """ Get pixel importance of the image. It performs pixel sensitivity analysis by showing only the most important pixels to a certain label in the image. It uses integrated gradie...
[ "def", "probe_image", "(", "self", ",", "labels", ",", "instance", ",", "column_name", "=", "None", ",", "num_scaled_images", "=", "50", ",", "top_percent", "=", "10", ")", ":", "if", "len", "(", "self", ".", "_image_columns", ")", ">", "1", "and", "no...
Get pixel importance of the image. It performs pixel sensitivity analysis by showing only the most important pixels to a certain label in the image. It uses integrated gradients to measure the importance of each pixel. Args: labels: labels to compute gradients from. ...
[ "Get", "pixel", "importance", "of", "the", "image", "." ]
train
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/google/datalab/contrib/mlworkbench/_prediction_explainer.py#L334-L414
googledatalab/pydatalab
google/datalab/ml/_cloud_models.py
Models.get_model_details
def get_model_details(self, model_name): """Get details of the specified model from CloudML Service. Args: model_name: the name of the model. It can be a model full name ("projects/[project_id]/models/[model_name]") or just [model_name]. Returns: a dictionary of the model details. """...
python
def get_model_details(self, model_name): """Get details of the specified model from CloudML Service. Args: model_name: the name of the model. It can be a model full name ("projects/[project_id]/models/[model_name]") or just [model_name]. Returns: a dictionary of the model details. """...
[ "def", "get_model_details", "(", "self", ",", "model_name", ")", ":", "full_name", "=", "model_name", "if", "not", "model_name", ".", "startswith", "(", "'projects/'", ")", ":", "full_name", "=", "(", "'projects/%s/models/%s'", "%", "(", "self", ".", "_project...
Get details of the specified model from CloudML Service. Args: model_name: the name of the model. It can be a model full name ("projects/[project_id]/models/[model_name]") or just [model_name]. Returns: a dictionary of the model details.
[ "Get", "details", "of", "the", "specified", "model", "from", "CloudML", "Service", "." ]
train
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/google/datalab/ml/_cloud_models.py#L53-L64
googledatalab/pydatalab
google/datalab/ml/_cloud_models.py
Models.create
def create(self, model_name): """Create a model. Args: model_name: the short name of the model, such as "iris". Returns: If successful, returns informaiton of the model, such as {u'regions': [u'us-central1'], u'name': u'projects/myproject/models/mymodel'} Raises: If the model cr...
python
def create(self, model_name): """Create a model. Args: model_name: the short name of the model, such as "iris". Returns: If successful, returns informaiton of the model, such as {u'regions': [u'us-central1'], u'name': u'projects/myproject/models/mymodel'} Raises: If the model cr...
[ "def", "create", "(", "self", ",", "model_name", ")", ":", "body", "=", "{", "'name'", ":", "model_name", "}", "parent", "=", "'projects/'", "+", "self", ".", "_project_id", "# Model creation is instant. If anything goes wrong, Exception will be thrown.", "return", "s...
Create a model. Args: model_name: the short name of the model, such as "iris". Returns: If successful, returns informaiton of the model, such as {u'regions': [u'us-central1'], u'name': u'projects/myproject/models/mymodel'} Raises: If the model creation failed.
[ "Create", "a", "model", "." ]
train
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/google/datalab/ml/_cloud_models.py#L66-L80
googledatalab/pydatalab
google/datalab/ml/_cloud_models.py
Models.delete
def delete(self, model_name): """Delete a model. Args: model_name: the name of the model. It can be a model full name ("projects/[project_id]/models/[model_name]") or just [model_name]. """ full_name = model_name if not model_name.startswith('projects/'): full_name = ('project...
python
def delete(self, model_name): """Delete a model. Args: model_name: the name of the model. It can be a model full name ("projects/[project_id]/models/[model_name]") or just [model_name]. """ full_name = model_name if not model_name.startswith('projects/'): full_name = ('project...
[ "def", "delete", "(", "self", ",", "model_name", ")", ":", "full_name", "=", "model_name", "if", "not", "model_name", ".", "startswith", "(", "'projects/'", ")", ":", "full_name", "=", "(", "'projects/%s/models/%s'", "%", "(", "self", ".", "_project_id", ","...
Delete a model. Args: model_name: the name of the model. It can be a model full name ("projects/[project_id]/models/[model_name]") or just [model_name].
[ "Delete", "a", "model", "." ]
train
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/google/datalab/ml/_cloud_models.py#L82-L95
googledatalab/pydatalab
google/datalab/ml/_cloud_models.py
Models.list
def list(self, count=10): """List models under the current project in a table view. Args: count: upper limit of the number of models to list. Raises: Exception if it is called in a non-IPython environment. """ import IPython data = [] # Add range(count) to loop so it will stop e...
python
def list(self, count=10): """List models under the current project in a table view. Args: count: upper limit of the number of models to list. Raises: Exception if it is called in a non-IPython environment. """ import IPython data = [] # Add range(count) to loop so it will stop e...
[ "def", "list", "(", "self", ",", "count", "=", "10", ")", ":", "import", "IPython", "data", "=", "[", "]", "# Add range(count) to loop so it will stop either it reaches count, or iteration", "# on self is exhausted. \"self\" is iterable (see __iter__() method).", "for", "_", ...
List models under the current project in a table view. Args: count: upper limit of the number of models to list. Raises: Exception if it is called in a non-IPython environment.
[ "List", "models", "under", "the", "current", "project", "in", "a", "table", "view", "." ]
train
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/google/datalab/ml/_cloud_models.py#L97-L117
googledatalab/pydatalab
google/datalab/ml/_cloud_models.py
Models.describe
def describe(self, model_name): """Print information of a specified model. Args: model_name: the name of the model to print details on. """ model_yaml = yaml.safe_dump(self.get_model_details(model_name), default_flow_style=False) print(model_yaml)
python
def describe(self, model_name): """Print information of a specified model. Args: model_name: the name of the model to print details on. """ model_yaml = yaml.safe_dump(self.get_model_details(model_name), default_flow_style=False) print(model_yaml)
[ "def", "describe", "(", "self", ",", "model_name", ")", ":", "model_yaml", "=", "yaml", ".", "safe_dump", "(", "self", ".", "get_model_details", "(", "model_name", ")", ",", "default_flow_style", "=", "False", ")", "print", "(", "model_yaml", ")" ]
Print information of a specified model. Args: model_name: the name of the model to print details on.
[ "Print", "information", "of", "a", "specified", "model", "." ]
train
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/google/datalab/ml/_cloud_models.py#L119-L126
googledatalab/pydatalab
google/datalab/ml/_cloud_models.py
ModelVersions.get_version_details
def get_version_details(self, version_name): """Get details of a version. Args: version: the name of the version in short form, such as "v1". Returns: a dictionary containing the version details. """ name = ('%s/versions/%s' % (self._full_model_name, version_name)) return self._api.projec...
python
def get_version_details(self, version_name): """Get details of a version. Args: version: the name of the version in short form, such as "v1". Returns: a dictionary containing the version details. """ name = ('%s/versions/%s' % (self._full_model_name, version_name)) return self._api.projec...
[ "def", "get_version_details", "(", "self", ",", "version_name", ")", ":", "name", "=", "(", "'%s/versions/%s'", "%", "(", "self", ".", "_full_model_name", ",", "version_name", ")", ")", "return", "self", ".", "_api", ".", "projects", "(", ")", ".", "models...
Get details of a version. Args: version: the name of the version in short form, such as "v1". Returns: a dictionary containing the version details.
[ "Get", "details", "of", "a", "version", "." ]
train
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/google/datalab/ml/_cloud_models.py#L166-L174
googledatalab/pydatalab
google/datalab/ml/_cloud_models.py
ModelVersions.deploy
def deploy(self, version_name, path, runtime_version=None): """Deploy a model version to the cloud. Args: version_name: the name of the version in short form, such as "v1". path: the Google Cloud Storage path (gs://...) which contains the model files. runtime_version: the ML Engine runtime ve...
python
def deploy(self, version_name, path, runtime_version=None): """Deploy a model version to the cloud. Args: version_name: the name of the version in short form, such as "v1". path: the Google Cloud Storage path (gs://...) which contains the model files. runtime_version: the ML Engine runtime ve...
[ "def", "deploy", "(", "self", ",", "version_name", ",", "path", ",", "runtime_version", "=", "None", ")", ":", "if", "not", "path", ".", "startswith", "(", "'gs://'", ")", ":", "raise", "Exception", "(", "'Invalid path. Only Google Cloud Storage path (gs://...) is...
Deploy a model version to the cloud. Args: version_name: the name of the version in short form, such as "v1". path: the Google Cloud Storage path (gs://...) which contains the model files. runtime_version: the ML Engine runtime version as a string, example '1.2'. See https://cloud.googl...
[ "Deploy", "a", "model", "version", "to", "the", "cloud", "." ]
train
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/google/datalab/ml/_cloud_models.py#L176-L222
googledatalab/pydatalab
google/datalab/ml/_cloud_models.py
ModelVersions.delete
def delete(self, version_name): """Delete a version of model. Args: version_name: the name of the version in short form, such as "v1". """ name = ('%s/versions/%s' % (self._full_model_name, version_name)) response = self._api.projects().models().versions().delete(name=name).execute() if '...
python
def delete(self, version_name): """Delete a version of model. Args: version_name: the name of the version in short form, such as "v1". """ name = ('%s/versions/%s' % (self._full_model_name, version_name)) response = self._api.projects().models().versions().delete(name=name).execute() if '...
[ "def", "delete", "(", "self", ",", "version_name", ")", ":", "name", "=", "(", "'%s/versions/%s'", "%", "(", "self", ".", "_full_model_name", ",", "version_name", ")", ")", "response", "=", "self", ".", "_api", ".", "projects", "(", ")", ".", "models", ...
Delete a version of model. Args: version_name: the name of the version in short form, such as "v1".
[ "Delete", "a", "version", "of", "model", "." ]
train
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/google/datalab/ml/_cloud_models.py#L224-L234
googledatalab/pydatalab
google/datalab/ml/_cloud_models.py
ModelVersions.predict
def predict(self, version_name, data): """Get prediction results from features instances. Args: version_name: the name of the version used for prediction. data: typically a list of instance to be submitted for prediction. The format of the instance depends on the model. For example, struc...
python
def predict(self, version_name, data): """Get prediction results from features instances. Args: version_name: the name of the version used for prediction. data: typically a list of instance to be submitted for prediction. The format of the instance depends on the model. For example, struc...
[ "def", "predict", "(", "self", ",", "version_name", ",", "data", ")", ":", "full_version_name", "=", "(", "'%s/versions/%s'", "%", "(", "self", ".", "_full_model_name", ",", "version_name", ")", ")", "request", "=", "self", ".", "_api", ".", "projects", "(...
Get prediction results from features instances. Args: version_name: the name of the version used for prediction. data: typically a list of instance to be submitted for prediction. The format of the instance depends on the model. For example, structured data model may require a csv l...
[ "Get", "prediction", "results", "from", "features", "instances", "." ]
train
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/google/datalab/ml/_cloud_models.py#L236-L261
googledatalab/pydatalab
google/datalab/ml/_cloud_models.py
ModelVersions.describe
def describe(self, version_name): """Print information of a specified model. Args: version: the name of the version in short form, such as "v1". """ version_yaml = yaml.safe_dump(self.get_version_details(version_name), default_flow_style=False) print(version_...
python
def describe(self, version_name): """Print information of a specified model. Args: version: the name of the version in short form, such as "v1". """ version_yaml = yaml.safe_dump(self.get_version_details(version_name), default_flow_style=False) print(version_...
[ "def", "describe", "(", "self", ",", "version_name", ")", ":", "version_yaml", "=", "yaml", ".", "safe_dump", "(", "self", ".", "get_version_details", "(", "version_name", ")", ",", "default_flow_style", "=", "False", ")", "print", "(", "version_yaml", ")" ]
Print information of a specified model. Args: version: the name of the version in short form, such as "v1".
[ "Print", "information", "of", "a", "specified", "model", "." ]
train
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/google/datalab/ml/_cloud_models.py#L263-L271
googledatalab/pydatalab
google/datalab/ml/_cloud_models.py
ModelVersions.list
def list(self): """List versions under the current model in a table view. Raises: Exception if it is called in a non-IPython environment. """ import IPython # "self" is iterable (see __iter__() method). data = [{'name': version['name'].split()[-1], 'deploymentUri': version['...
python
def list(self): """List versions under the current model in a table view. Raises: Exception if it is called in a non-IPython environment. """ import IPython # "self" is iterable (see __iter__() method). data = [{'name': version['name'].split()[-1], 'deploymentUri': version['...
[ "def", "list", "(", "self", ")", ":", "import", "IPython", "# \"self\" is iterable (see __iter__() method).", "data", "=", "[", "{", "'name'", ":", "version", "[", "'name'", "]", ".", "split", "(", ")", "[", "-", "1", "]", ",", "'deploymentUri'", ":", "ver...
List versions under the current model in a table view. Raises: Exception if it is called in a non-IPython environment.
[ "List", "versions", "under", "the", "current", "model", "in", "a", "table", "view", "." ]
train
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/google/datalab/ml/_cloud_models.py#L273-L286
googledatalab/pydatalab
google/datalab/bigquery/_query_job.py
QueryJob.result
def result(self): """ Get the table used for the results of the query. If the query is incomplete, this blocks. Raises: Exception if we timed out waiting for results or the query failed. """ self.wait() if self.failed: raise Exception('Query failed: %s' % str(self.errors)) return se...
python
def result(self): """ Get the table used for the results of the query. If the query is incomplete, this blocks. Raises: Exception if we timed out waiting for results or the query failed. """ self.wait() if self.failed: raise Exception('Query failed: %s' % str(self.errors)) return se...
[ "def", "result", "(", "self", ")", ":", "self", ".", "wait", "(", ")", "if", "self", ".", "failed", ":", "raise", "Exception", "(", "'Query failed: %s'", "%", "str", "(", "self", ".", "errors", ")", ")", "return", "self", ".", "_table" ]
Get the table used for the results of the query. If the query is incomplete, this blocks. Raises: Exception if we timed out waiting for results or the query failed.
[ "Get", "the", "table", "used", "for", "the", "results", "of", "the", "query", ".", "If", "the", "query", "is", "incomplete", "this", "blocks", "." ]
train
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/google/datalab/bigquery/_query_job.py#L101-L110
googledatalab/pydatalab
solutionbox/ml_workbench/xgboost/trainer/feature_transforms.py
make_preprocessing_fn
def make_preprocessing_fn(output_dir, features, keep_target): """Makes a preprocessing function. Args: output_dir: folder path that contains the vocab and stats files. features: the features dict Returns: a function that takes a dict of input tensors """ def preprocessing_fn(inputs): """Prep...
python
def make_preprocessing_fn(output_dir, features, keep_target): """Makes a preprocessing function. Args: output_dir: folder path that contains the vocab and stats files. features: the features dict Returns: a function that takes a dict of input tensors """ def preprocessing_fn(inputs): """Prep...
[ "def", "make_preprocessing_fn", "(", "output_dir", ",", "features", ",", "keep_target", ")", ":", "def", "preprocessing_fn", "(", "inputs", ")", ":", "\"\"\"Preprocessing function.\n\n Args:\n inputs: dictionary of raw input tensors\n\n Returns:\n A dictionary of tran...
Makes a preprocessing function. Args: output_dir: folder path that contains the vocab and stats files. features: the features dict Returns: a function that takes a dict of input tensors
[ "Makes", "a", "preprocessing", "function", "." ]
train
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/solutionbox/ml_workbench/xgboost/trainer/feature_transforms.py#L252-L314
googledatalab/pydatalab
solutionbox/ml_workbench/xgboost/trainer/feature_transforms.py
get_transformed_feature_indices
def get_transformed_feature_indices(features, stats): """Returns information about the transformed features. Returns: List in the from [(transformed_feature_name, {size: int, index_start: int})] """ feature_indices = [] index_start = 1 for name, transform in sorted(six.iteritems(features)): tr...
python
def get_transformed_feature_indices(features, stats): """Returns information about the transformed features. Returns: List in the from [(transformed_feature_name, {size: int, index_start: int})] """ feature_indices = [] index_start = 1 for name, transform in sorted(six.iteritems(features)): tr...
[ "def", "get_transformed_feature_indices", "(", "features", ",", "stats", ")", ":", "feature_indices", "=", "[", "]", "index_start", "=", "1", "for", "name", ",", "transform", "in", "sorted", "(", "six", ".", "iteritems", "(", "features", ")", ")", ":", "tr...
Returns information about the transformed features. Returns: List in the from [(transformed_feature_name, {size: int, index_start: int})]
[ "Returns", "information", "about", "the", "transformed", "features", "." ]
train
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/solutionbox/ml_workbench/xgboost/trainer/feature_transforms.py#L415-L444
googledatalab/pydatalab
solutionbox/ml_workbench/xgboost/trainer/feature_transforms.py
create_feature_map
def create_feature_map(features, feature_indices, output_dir): """Returns feature_map about the transformed features. feature_map includes information such as: 1, cat1=0 2, cat1=1 3, numeric1 ... Returns: List in the from [(index, feature_description)] """ feature_map = [] for name,...
python
def create_feature_map(features, feature_indices, output_dir): """Returns feature_map about the transformed features. feature_map includes information such as: 1, cat1=0 2, cat1=1 3, numeric1 ... Returns: List in the from [(index, feature_description)] """ feature_map = [] for name,...
[ "def", "create_feature_map", "(", "features", ",", "feature_indices", ",", "output_dir", ")", ":", "feature_map", "=", "[", "]", "for", "name", ",", "info", "in", "feature_indices", ":", "transform_name", "=", "features", "[", "name", "]", "[", "'transform'", ...
Returns feature_map about the transformed features. feature_map includes information such as: 1, cat1=0 2, cat1=1 3, numeric1 ... Returns: List in the from [(index, feature_description)]
[ "Returns", "feature_map", "about", "the", "transformed", "features", "." ]
train
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/solutionbox/ml_workbench/xgboost/trainer/feature_transforms.py#L447-L477
googledatalab/pydatalab
datalab/bigquery/_view.py
View.create
def create(self, query): """ Creates the view with the specified query. Args: query: the query to use to for the View; either a string containing a SQL query or a Query object. Returns: The View instance. Raises: Exception if the view couldn't be created or already exists an...
python
def create(self, query): """ Creates the view with the specified query. Args: query: the query to use to for the View; either a string containing a SQL query or a Query object. Returns: The View instance. Raises: Exception if the view couldn't be created or already exists an...
[ "def", "create", "(", "self", ",", "query", ")", ":", "if", "isinstance", "(", "query", ",", "_query", ".", "Query", ")", ":", "query", "=", "query", ".", "sql", "try", ":", "response", "=", "self", ".", "_table", ".", "_api", ".", "tables_insert", ...
Creates the view with the specified query. Args: query: the query to use to for the View; either a string containing a SQL query or a Query object. Returns: The View instance. Raises: Exception if the view couldn't be created or already exists and overwrite was False.
[ "Creates", "the", "view", "with", "the", "specified", "query", "." ]
train
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/datalab/bigquery/_view.py#L91-L110
googledatalab/pydatalab
datalab/bigquery/_view.py
View.sample
def sample(self, fields=None, count=5, sampling=None, use_cache=True, dialect=None, billing_tier=None): """Retrieves a sampling of data from the view. Args: fields: an optional list of field names to retrieve. count: an optional count of rows to retrieve which is used if a specific ...
python
def sample(self, fields=None, count=5, sampling=None, use_cache=True, dialect=None, billing_tier=None): """Retrieves a sampling of data from the view. Args: fields: an optional list of field names to retrieve. count: an optional count of rows to retrieve which is used if a specific ...
[ "def", "sample", "(", "self", ",", "fields", "=", "None", ",", "count", "=", "5", ",", "sampling", "=", "None", ",", "use_cache", "=", "True", ",", "dialect", "=", "None", ",", "billing_tier", "=", "None", ")", ":", "return", "self", ".", "_table", ...
Retrieves a sampling of data from the view. Args: 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 apply to the view. use_cache: wheth...
[ "Retrieves", "a", "sampling", "of", "data", "from", "the", "view", "." ]
train
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/datalab/bigquery/_view.py#L112-L136
googledatalab/pydatalab
datalab/bigquery/_view.py
View.update
def update(self, friendly_name=None, description=None, query=None): """ Selectively updates View information. Any parameters that are None (the default) are not applied in the update. Args: friendly_name: if not None, the new friendly name. description: if not None, the new description. ...
python
def update(self, friendly_name=None, description=None, query=None): """ Selectively updates View information. Any parameters that are None (the default) are not applied in the update. Args: friendly_name: if not None, the new friendly name. description: if not None, the new description. ...
[ "def", "update", "(", "self", ",", "friendly_name", "=", "None", ",", "description", "=", "None", ",", "query", "=", "None", ")", ":", "self", ".", "_table", ".", "_load_info", "(", ")", "if", "query", "is", "not", "None", ":", "if", "isinstance", "(...
Selectively updates View information. Any parameters that are None (the default) are not applied in the update. Args: friendly_name: if not None, the new friendly name. description: if not None, the new description. query: if not None, a new query string for the View.
[ "Selectively", "updates", "View", "information", "." ]
train
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/datalab/bigquery/_view.py#L149-L164
googledatalab/pydatalab
datalab/bigquery/_view.py
View.results
def results(self, use_cache=True, dialect=None, billing_tier=None): """Materialize the view synchronously. If you require more control over the execution, use execute() or execute_async(). Args: use_cache: whether to use cached results or not. dialect : {'legacy', 'standard'}, default 'legacy'...
python
def results(self, use_cache=True, dialect=None, billing_tier=None): """Materialize the view synchronously. If you require more control over the execution, use execute() or execute_async(). Args: use_cache: whether to use cached results or not. dialect : {'legacy', 'standard'}, default 'legacy'...
[ "def", "results", "(", "self", ",", "use_cache", "=", "True", ",", "dialect", "=", "None", ",", "billing_tier", "=", "None", ")", ":", "return", "self", ".", "_materialization", ".", "results", "(", "use_cache", "=", "use_cache", ",", "dialect", "=", "di...
Materialize the view synchronously. If you require more control over the execution, use execute() or execute_async(). Args: use_cache: whether to use cached results or not. dialect : {'legacy', 'standard'}, default 'legacy' 'legacy' : Use BigQuery's legacy SQL dialect. 'standar...
[ "Materialize", "the", "view", "synchronously", "." ]
train
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/datalab/bigquery/_view.py#L166-L187
googledatalab/pydatalab
datalab/bigquery/_view.py
View.execute_async
def execute_async(self, table_name=None, table_mode='create', use_cache=True, priority='high', allow_large_results=False, dialect=None, billing_tier=None): """Materialize the View asynchronously. Args: table_name: the result table name; if None, then a temporary table will be used. ...
python
def execute_async(self, table_name=None, table_mode='create', use_cache=True, priority='high', allow_large_results=False, dialect=None, billing_tier=None): """Materialize the View asynchronously. Args: table_name: the result table name; if None, then a temporary table will be used. ...
[ "def", "execute_async", "(", "self", ",", "table_name", "=", "None", ",", "table_mode", "=", "'create'", ",", "use_cache", "=", "True", ",", "priority", "=", "'high'", ",", "allow_large_results", "=", "False", ",", "dialect", "=", "None", ",", "billing_tier"...
Materialize the View asynchronously. Args: table_name: the result table name; if None, then a temporary table will be used. table_mode: one of 'create', 'overwrite' or 'append'. If 'create' (the default), the request will fail if the table exists. use_cache: whether to use past query re...
[ "Materialize", "the", "View", "asynchronously", "." ]
train
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/datalab/bigquery/_view.py#L189-L219
googledatalab/pydatalab
google/datalab/utils/commands/_utils.py
get_notebook_item
def get_notebook_item(name): """ Get an item from the IPython environment. """ env = notebook_environment() return google.datalab.utils.get_item(env, name)
python
def get_notebook_item(name): """ Get an item from the IPython environment. """ env = notebook_environment() return google.datalab.utils.get_item(env, name)
[ "def", "get_notebook_item", "(", "name", ")", ":", "env", "=", "notebook_environment", "(", ")", "return", "google", ".", "datalab", ".", "utils", ".", "get_item", "(", "env", ",", "name", ")" ]
Get an item from the IPython environment.
[ "Get", "an", "item", "from", "the", "IPython", "environment", "." ]
train
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/google/datalab/utils/commands/_utils.py#L50-L53
googledatalab/pydatalab
google/datalab/utils/commands/_utils.py
get_field_list
def get_field_list(fields, schema): """ Convert a field list spec into a real list of field names. For tables, we return only the top-level non-RECORD fields as Google charts can't handle nested data. """ # If the fields weren't supplied get them from the schema. if schema: all_fields = [f['nam...
python
def get_field_list(fields, schema): """ Convert a field list spec into a real list of field names. For tables, we return only the top-level non-RECORD fields as Google charts can't handle nested data. """ # If the fields weren't supplied get them from the schema. if schema: all_fields = [f['nam...
[ "def", "get_field_list", "(", "fields", ",", "schema", ")", ":", "# If the fields weren't supplied get them from the schema.", "if", "schema", ":", "all_fields", "=", "[", "f", "[", "'name'", "]", "for", "f", "in", "schema", ".", "_bq_schema", "if", "f", "[", ...
Convert a field list spec into a real list of field names. For tables, we return only the top-level non-RECORD fields as Google charts can't handle nested data.
[ "Convert", "a", "field", "list", "spec", "into", "a", "real", "list", "of", "field", "names", "." ]
train
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/google/datalab/utils/commands/_utils.py#L80-L106
googledatalab/pydatalab
google/datalab/utils/commands/_utils.py
_get_data_from_list_of_dicts
def _get_data_from_list_of_dicts(source, fields='*', first_row=0, count=-1, schema=None): """ Helper function for _get_data that handles lists of dicts. """ if schema is None: schema = google.datalab.bigquery.Schema.from_data(source) fields = get_field_list(fields, schema) gen = source[first_row:first_row +...
python
def _get_data_from_list_of_dicts(source, fields='*', first_row=0, count=-1, schema=None): """ Helper function for _get_data that handles lists of dicts. """ if schema is None: schema = google.datalab.bigquery.Schema.from_data(source) fields = get_field_list(fields, schema) gen = source[first_row:first_row +...
[ "def", "_get_data_from_list_of_dicts", "(", "source", ",", "fields", "=", "'*'", ",", "first_row", "=", "0", ",", "count", "=", "-", "1", ",", "schema", "=", "None", ")", ":", "if", "schema", "is", "None", ":", "schema", "=", "google", ".", "datalab", ...
Helper function for _get_data that handles lists of dicts.
[ "Helper", "function", "for", "_get_data", "that", "handles", "lists", "of", "dicts", "." ]
train
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/google/datalab/utils/commands/_utils.py#L144-L151