repo
stringlengths
7
55
path
stringlengths
4
127
func_name
stringlengths
1
88
original_string
stringlengths
75
19.8k
language
stringclasses
1 value
code
stringlengths
75
19.8k
code_tokens
list
docstring
stringlengths
3
17.3k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
87
242
partition
stringclasses
1 value
googledatalab/pydatalab
datalab/stackdriver/commands/_monitoring.py
monitoring
def monitoring(line, cell=None): """Implements the monitoring 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='monitoring', description=( 'Execute various Monitorin...
python
def monitoring(line, cell=None): """Implements the monitoring 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='monitoring', description=( 'Execute various Monitorin...
[ "def", "monitoring", "(", "line", ",", "cell", "=", "None", ")", ":", "parser", "=", "datalab", ".", "utils", ".", "commands", ".", "CommandParser", "(", "prog", "=", "'monitoring'", ",", "description", "=", "(", "'Execute various Monitoring-related operations. ...
Implements the monitoring cell magic for ipython notebooks. Args: line: the contents of the storage line. Returns: The results of executing the cell.
[ "Implements", "the", "monitoring", "cell", "magic", "for", "ipython", "notebooks", "." ]
d9031901d5bca22fe0d5925d204e6698df9852e1
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/datalab/stackdriver/commands/_monitoring.py#L27-L73
train
googledatalab/pydatalab
datalab/stackdriver/commands/_monitoring.py
_render_dataframe
def _render_dataframe(dataframe): """Helper to render a dataframe as an HTML table.""" data = dataframe.to_dict(orient='records') fields = dataframe.columns.tolist() return IPython.core.display.HTML( datalab.utils.commands.HtmlBuilder.render_table(data, fields))
python
def _render_dataframe(dataframe): """Helper to render a dataframe as an HTML table.""" data = dataframe.to_dict(orient='records') fields = dataframe.columns.tolist() return IPython.core.display.HTML( datalab.utils.commands.HtmlBuilder.render_table(data, fields))
[ "def", "_render_dataframe", "(", "dataframe", ")", ":", "data", "=", "dataframe", ".", "to_dict", "(", "orient", "=", "'records'", ")", "fields", "=", "dataframe", ".", "columns", ".", "tolist", "(", ")", "return", "IPython", ".", "core", ".", "display", ...
Helper to render a dataframe as an HTML table.
[ "Helper", "to", "render", "a", "dataframe", "as", "an", "HTML", "table", "." ]
d9031901d5bca22fe0d5925d204e6698df9852e1
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/datalab/stackdriver/commands/_monitoring.py#L103-L108
train
googledatalab/pydatalab
google/datalab/utils/commands/_job.py
_get_job_status
def _get_job_status(line): """magic used as an endpoint for client to get job status. %_get_job_status <name> Returns: A JSON object of the job status. """ try: args = line.strip().split() job_name = args[0] job = None if job_name in _local_jobs: job = _local_jobs[job_name] ...
python
def _get_job_status(line): """magic used as an endpoint for client to get job status. %_get_job_status <name> Returns: A JSON object of the job status. """ try: args = line.strip().split() job_name = args[0] job = None if job_name in _local_jobs: job = _local_jobs[job_name] ...
[ "def", "_get_job_status", "(", "line", ")", ":", "try", ":", "args", "=", "line", ".", "strip", "(", ")", ".", "split", "(", ")", "job_name", "=", "args", "[", "0", "]", "job", "=", "None", "if", "job_name", "in", "_local_jobs", ":", "job", "=", ...
magic used as an endpoint for client to get job status. %_get_job_status <name> Returns: A JSON object of the job status.
[ "magic", "used", "as", "an", "endpoint", "for", "client", "to", "get", "job", "status", "." ]
d9031901d5bca22fe0d5925d204e6698df9852e1
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/google/datalab/utils/commands/_job.py#L61-L89
train
googledatalab/pydatalab
google/datalab/storage/_object.py
ObjectMetadata.updated_on
def updated_on(self): """The updated timestamp of the object as a datetime.datetime.""" s = self._info.get('updated', None) return dateutil.parser.parse(s) if s else None
python
def updated_on(self): """The updated timestamp of the object as a datetime.datetime.""" s = self._info.get('updated', None) return dateutil.parser.parse(s) if s else None
[ "def", "updated_on", "(", "self", ")", ":", "s", "=", "self", ".", "_info", ".", "get", "(", "'updated'", ",", "None", ")", "return", "dateutil", ".", "parser", ".", "parse", "(", "s", ")", "if", "s", "else", "None" ]
The updated timestamp of the object as a datetime.datetime.
[ "The", "updated", "timestamp", "of", "the", "object", "as", "a", "datetime", ".", "datetime", "." ]
d9031901d5bca22fe0d5925d204e6698df9852e1
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/google/datalab/storage/_object.py#L69-L72
train
googledatalab/pydatalab
google/datalab/storage/_object.py
Object.delete
def delete(self, wait_for_deletion=True): """Deletes this object from its bucket. Args: wait_for_deletion: If True, we poll until this object no longer appears in objects.list operations for this bucket before returning. Raises: Exception if there was an error deleting the object. ...
python
def delete(self, wait_for_deletion=True): """Deletes this object from its bucket. Args: wait_for_deletion: If True, we poll until this object no longer appears in objects.list operations for this bucket before returning. Raises: Exception if there was an error deleting the object. ...
[ "def", "delete", "(", "self", ",", "wait_for_deletion", "=", "True", ")", ":", "if", "self", ".", "exists", "(", ")", ":", "try", ":", "self", ".", "_api", ".", "objects_delete", "(", "self", ".", "_bucket", ",", "self", ".", "_key", ")", "except", ...
Deletes this object from its bucket. Args: wait_for_deletion: If True, we poll until this object no longer appears in objects.list operations for this bucket before returning. Raises: Exception if there was an error deleting the object.
[ "Deletes", "this", "object", "from", "its", "bucket", "." ]
d9031901d5bca22fe0d5925d204e6698df9852e1
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/google/datalab/storage/_object.py#L147-L172
train
googledatalab/pydatalab
google/datalab/storage/_object.py
Object.metadata
def metadata(self): """Retrieves metadata about the object. Returns: An ObjectMetadata instance with information about this object. Raises: Exception if there was an error requesting the object's metadata. """ if self._info is None: try: self._info = self._api.objects_get(...
python
def metadata(self): """Retrieves metadata about the object. Returns: An ObjectMetadata instance with information about this object. Raises: Exception if there was an error requesting the object's metadata. """ if self._info is None: try: self._info = self._api.objects_get(...
[ "def", "metadata", "(", "self", ")", ":", "if", "self", ".", "_info", "is", "None", ":", "try", ":", "self", ".", "_info", "=", "self", ".", "_api", ".", "objects_get", "(", "self", ".", "_bucket", ",", "self", ".", "_key", ")", "except", "Exceptio...
Retrieves metadata about the object. Returns: An ObjectMetadata instance with information about this object. Raises: Exception if there was an error requesting the object's metadata.
[ "Retrieves", "metadata", "about", "the", "object", "." ]
d9031901d5bca22fe0d5925d204e6698df9852e1
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/google/datalab/storage/_object.py#L175-L188
train
googledatalab/pydatalab
google/datalab/storage/_object.py
Object.read_stream
def read_stream(self, start_offset=0, byte_count=None): """Reads the content of this object as text. Args: start_offset: the start offset of bytes to read. byte_count: the number of bytes to read. If None, it reads to the end. Returns: The text content within the object. Raises: ...
python
def read_stream(self, start_offset=0, byte_count=None): """Reads the content of this object as text. Args: start_offset: the start offset of bytes to read. byte_count: the number of bytes to read. If None, it reads to the end. Returns: The text content within the object. Raises: ...
[ "def", "read_stream", "(", "self", ",", "start_offset", "=", "0", ",", "byte_count", "=", "None", ")", ":", "try", ":", "return", "self", ".", "_api", ".", "object_download", "(", "self", ".", "_bucket", ",", "self", ".", "_key", ",", "start_offset", "...
Reads the content of this object as text. Args: start_offset: the start offset of bytes to read. byte_count: the number of bytes to read. If None, it reads to the end. Returns: The text content within the object. Raises: Exception if there was an error requesting the object's conten...
[ "Reads", "the", "content", "of", "this", "object", "as", "text", "." ]
d9031901d5bca22fe0d5925d204e6698df9852e1
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/google/datalab/storage/_object.py#L190-L205
train
googledatalab/pydatalab
google/datalab/storage/_object.py
Object.read_lines
def read_lines(self, max_lines=None): """Reads the content of this object as text, and return a list of lines up to some max. Args: max_lines: max number of lines to return. If None, return all lines. Returns: The text content of the object as a list of lines. Raises: Exception if the...
python
def read_lines(self, max_lines=None): """Reads the content of this object as text, and return a list of lines up to some max. Args: max_lines: max number of lines to return. If None, return all lines. Returns: The text content of the object as a list of lines. Raises: Exception if the...
[ "def", "read_lines", "(", "self", ",", "max_lines", "=", "None", ")", ":", "if", "max_lines", "is", "None", ":", "return", "self", ".", "read_stream", "(", ")", ".", "split", "(", "'\\n'", ")", "max_to_read", "=", "self", ".", "metadata", ".", "size", ...
Reads the content of this object as text, and return a list of lines up to some max. Args: max_lines: max number of lines to return. If None, return all lines. Returns: The text content of the object as a list of lines. Raises: Exception if there was an error requesting the object's conte...
[ "Reads", "the", "content", "of", "this", "object", "as", "text", "and", "return", "a", "list", "of", "lines", "up", "to", "some", "max", "." ]
d9031901d5bca22fe0d5925d204e6698df9852e1
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/google/datalab/storage/_object.py#L217-L243
train
googledatalab/pydatalab
datalab/data/_csv.py
Csv.sample_to
def sample_to(self, count, skip_header_rows, strategy, target): """Sample rows from GCS or local file and save results to target file. Args: count: number of rows to sample. If strategy is "BIGQUERY", it is used as approximate number. skip_header_rows: whether to skip first row when reading from so...
python
def sample_to(self, count, skip_header_rows, strategy, target): """Sample rows from GCS or local file and save results to target file. Args: count: number of rows to sample. If strategy is "BIGQUERY", it is used as approximate number. skip_header_rows: whether to skip first row when reading from so...
[ "def", "sample_to", "(", "self", ",", "count", ",", "skip_header_rows", ",", "strategy", ",", "target", ")", ":", "if", "sys", ".", "version_info", ".", "major", ">", "2", ":", "xrange", "=", "range", "if", "strategy", "==", "'BIGQUERY'", ":", "import", ...
Sample rows from GCS or local file and save results to target file. Args: count: number of rows to sample. If strategy is "BIGQUERY", it is used as approximate number. skip_header_rows: whether to skip first row when reading from source. strategy: can be "LOCAL" or "BIGQUERY". If local, the sampl...
[ "Sample", "rows", "from", "GCS", "or", "local", "file", "and", "save", "results", "to", "target", "file", "." ]
d9031901d5bca22fe0d5925d204e6698df9852e1
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/datalab/data/_csv.py#L129-L183
train
googledatalab/pydatalab
google/datalab/utils/facets/base_feature_statistics_generator.py
BaseFeatureStatisticsGenerator._ParseExample
def _ParseExample(self, example_features, example_feature_lists, entries, index): """Parses data from an example, populating a dictionary of feature values. Args: example_features: A map of strings to tf.Features from the example. example_feature_lists: A map of strings to tf.Fe...
python
def _ParseExample(self, example_features, example_feature_lists, entries, index): """Parses data from an example, populating a dictionary of feature values. Args: example_features: A map of strings to tf.Features from the example. example_feature_lists: A map of strings to tf.Fe...
[ "def", "_ParseExample", "(", "self", ",", "example_features", ",", "example_feature_lists", ",", "entries", ",", "index", ")", ":", "features_seen", "=", "set", "(", ")", "for", "feature_list", ",", "is_feature", "in", "zip", "(", "[", "example_features", ",",...
Parses data from an example, populating a dictionary of feature values. Args: example_features: A map of strings to tf.Features from the example. example_feature_lists: A map of strings to tf.FeatureLists from the example. entries: A dictionary of all features parsed thus far and arrays o...
[ "Parses", "data", "from", "an", "example", "populating", "a", "dictionary", "of", "feature", "values", "." ]
d9031901d5bca22fe0d5925d204e6698df9852e1
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/google/datalab/utils/facets/base_feature_statistics_generator.py#L74-L160
train
googledatalab/pydatalab
google/datalab/utils/facets/base_feature_statistics_generator.py
BaseFeatureStatisticsGenerator._GetEntries
def _GetEntries(self, paths, max_entries, iterator_from_file, is_sequence=False): """Extracts examples into a dictionary of feature values. Args: paths: A list of the paths to the files to parse. max_entries: The maximum number...
python
def _GetEntries(self, paths, max_entries, iterator_from_file, is_sequence=False): """Extracts examples into a dictionary of feature values. Args: paths: A list of the paths to the files to parse. max_entries: The maximum number...
[ "def", "_GetEntries", "(", "self", ",", "paths", ",", "max_entries", ",", "iterator_from_file", ",", "is_sequence", "=", "False", ")", ":", "entries", "=", "{", "}", "index", "=", "0", "for", "filepath", "in", "paths", ":", "reader", "=", "iterator_from_fi...
Extracts examples into a dictionary of feature values. Args: paths: A list of the paths to the files to parse. max_entries: The maximum number of examples to load. iterator_from_file: A method that takes a file path string and returns an iterator to the examples in that file. is_s...
[ "Extracts", "examples", "into", "a", "dictionary", "of", "feature", "values", "." ]
d9031901d5bca22fe0d5925d204e6698df9852e1
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/google/datalab/utils/facets/base_feature_statistics_generator.py#L162-L200
train
googledatalab/pydatalab
google/datalab/utils/facets/base_feature_statistics_generator.py
BaseFeatureStatisticsGenerator._GetTfRecordEntries
def _GetTfRecordEntries(self, path, max_entries, is_sequence, iterator_options): """Extracts TFRecord examples into a dictionary of feature values. Args: path: The path to the TFRecord file(s). max_entries: The maximum number of examples to load. is_sequence: True if...
python
def _GetTfRecordEntries(self, path, max_entries, is_sequence, iterator_options): """Extracts TFRecord examples into a dictionary of feature values. Args: path: The path to the TFRecord file(s). max_entries: The maximum number of examples to load. is_sequence: True if...
[ "def", "_GetTfRecordEntries", "(", "self", ",", "path", ",", "max_entries", ",", "is_sequence", ",", "iterator_options", ")", ":", "return", "self", ".", "_GetEntries", "(", "[", "path", "]", ",", "max_entries", ",", "partial", "(", "tf", ".", "python_io", ...
Extracts TFRecord examples into a dictionary of feature values. Args: path: The path to the TFRecord file(s). max_entries: The maximum number of examples to load. is_sequence: True if the input data from 'path' are tf.SequenceExamples, False if tf.Examples. Defaults to false. ite...
[ "Extracts", "TFRecord", "examples", "into", "a", "dictionary", "of", "feature", "values", "." ]
d9031901d5bca22fe0d5925d204e6698df9852e1
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/google/datalab/utils/facets/base_feature_statistics_generator.py#L202-L223
train
googledatalab/pydatalab
datalab/storage/_api.py
Api.buckets_insert
def buckets_insert(self, bucket, project_id=None): """Issues a request to create a new bucket. Args: bucket: the name of the bucket. project_id: the project to use when inserting the bucket. Returns: A parsed bucket information dictionary. Raises: Exception if there is an error ...
python
def buckets_insert(self, bucket, project_id=None): """Issues a request to create a new bucket. Args: bucket: the name of the bucket. project_id: the project to use when inserting the bucket. Returns: A parsed bucket information dictionary. Raises: Exception if there is an error ...
[ "def", "buckets_insert", "(", "self", ",", "bucket", ",", "project_id", "=", "None", ")", ":", "args", "=", "{", "'project'", ":", "project_id", "if", "project_id", "else", "self", ".", "_project_id", "}", "data", "=", "{", "'name'", ":", "bucket", "}", ...
Issues a request to create a new bucket. Args: bucket: the name of the bucket. project_id: the project to use when inserting the bucket. Returns: A parsed bucket information dictionary. Raises: Exception if there is an error performing the operation.
[ "Issues", "a", "request", "to", "create", "a", "new", "bucket", "." ]
d9031901d5bca22fe0d5925d204e6698df9852e1
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/datalab/storage/_api.py#L54-L69
train
googledatalab/pydatalab
datalab/storage/_api.py
Api.objects_delete
def objects_delete(self, bucket, key): """Deletes the specified object. Args: bucket: the name of the bucket. key: the key of the object within the bucket. Raises: Exception if there is an error performing the operation. """ url = Api._ENDPOINT + (Api._OBJECT_PATH % (bucket, Api._...
python
def objects_delete(self, bucket, key): """Deletes the specified object. Args: bucket: the name of the bucket. key: the key of the object within the bucket. Raises: Exception if there is an error performing the operation. """ url = Api._ENDPOINT + (Api._OBJECT_PATH % (bucket, Api._...
[ "def", "objects_delete", "(", "self", ",", "bucket", ",", "key", ")", ":", "url", "=", "Api", ".", "_ENDPOINT", "+", "(", "Api", ".", "_OBJECT_PATH", "%", "(", "bucket", ",", "Api", ".", "_escape_key", "(", "key", ")", ")", ")", "datalab", ".", "ut...
Deletes the specified object. Args: bucket: the name of the bucket. key: the key of the object within the bucket. Raises: Exception if there is an error performing the operation.
[ "Deletes", "the", "specified", "object", "." ]
d9031901d5bca22fe0d5925d204e6698df9852e1
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/datalab/storage/_api.py#L182-L193
train
googledatalab/pydatalab
google/datalab/stackdriver/monitoring/_metric.py
MetricDescriptors.list
def list(self, pattern='*'): """Returns a list of metric descriptors that match the filters. Args: pattern: An optional pattern to further filter the descriptors. This can include Unix shell-style wildcards. E.g. ``"compute*"``, ``"*cpu/load_??m"``. Returns: A list of Metri...
python
def list(self, pattern='*'): """Returns a list of metric descriptors that match the filters. Args: pattern: An optional pattern to further filter the descriptors. This can include Unix shell-style wildcards. E.g. ``"compute*"``, ``"*cpu/load_??m"``. Returns: A list of Metri...
[ "def", "list", "(", "self", ",", "pattern", "=", "'*'", ")", ":", "if", "self", ".", "_descriptors", "is", "None", ":", "self", ".", "_descriptors", "=", "self", ".", "_client", ".", "list_metric_descriptors", "(", "filter_string", "=", "self", ".", "_fi...
Returns a list of metric descriptors that match the filters. Args: pattern: An optional pattern to further filter the descriptors. This can include Unix shell-style wildcards. E.g. ``"compute*"``, ``"*cpu/load_??m"``. Returns: A list of MetricDescriptor objects that match the f...
[ "Returns", "a", "list", "of", "metric", "descriptors", "that", "match", "the", "filters", "." ]
d9031901d5bca22fe0d5925d204e6698df9852e1
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/google/datalab/stackdriver/monitoring/_metric.py#L45-L60
train
googledatalab/pydatalab
datalab/bigquery/_schema.py
Schema._from_dataframe
def _from_dataframe(dataframe, default_type='STRING'): """ Infer a BigQuery table schema from a Pandas dataframe. Note that if you don't explicitly set the types of the columns in the dataframe, they may be of a type that forces coercion to STRING, so even though the fields in the dataframe themse...
python
def _from_dataframe(dataframe, default_type='STRING'): """ Infer a BigQuery table schema from a Pandas dataframe. Note that if you don't explicitly set the types of the columns in the dataframe, they may be of a type that forces coercion to STRING, so even though the fields in the dataframe themse...
[ "def", "_from_dataframe", "(", "dataframe", ",", "default_type", "=", "'STRING'", ")", ":", "type_mapping", "=", "{", "'i'", ":", "'INTEGER'", ",", "'b'", ":", "'BOOLEAN'", ",", "'f'", ":", "'FLOAT'", ",", "'O'", ":", "'STRING'", ",", "'S'", ":", "'STRIN...
Infer a BigQuery table schema from a Pandas dataframe. Note that if you don't explicitly set the types of the columns in the dataframe, they may be of a type that forces coercion to STRING, so even though the fields in the dataframe themselves may be numeric, the type in the derived schema may not be....
[ "Infer", "a", "BigQuery", "table", "schema", "from", "a", "Pandas", "dataframe", ".", "Note", "that", "if", "you", "don", "t", "explicitly", "set", "the", "types", "of", "the", "columns", "in", "the", "dataframe", "they", "may", "be", "of", "a", "type", ...
d9031901d5bca22fe0d5925d204e6698df9852e1
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/datalab/bigquery/_schema.py#L92-L124
train
googledatalab/pydatalab
datalab/bigquery/_schema.py
Schema._from_dict_record
def _from_dict_record(data): """ Infer a BigQuery table schema from a dictionary. If the dictionary has entries that are in turn OrderedDicts these will be turned into RECORD types. Ideally this will be an OrderedDict but it is not required. Args: data: The dict to infer a schema from. Re...
python
def _from_dict_record(data): """ Infer a BigQuery table schema from a dictionary. If the dictionary has entries that are in turn OrderedDicts these will be turned into RECORD types. Ideally this will be an OrderedDict but it is not required. Args: data: The dict to infer a schema from. Re...
[ "def", "_from_dict_record", "(", "data", ")", ":", "return", "[", "Schema", ".", "_get_field_entry", "(", "name", ",", "value", ")", "for", "name", ",", "value", "in", "list", "(", "data", ".", "items", "(", ")", ")", "]" ]
Infer a BigQuery table schema from a dictionary. If the dictionary has entries that are in turn OrderedDicts these will be turned into RECORD types. Ideally this will be an OrderedDict but it is not required. Args: data: The dict to infer a schema from. Returns: A list of dictionaries conta...
[ "Infer", "a", "BigQuery", "table", "schema", "from", "a", "dictionary", ".", "If", "the", "dictionary", "has", "entries", "that", "are", "in", "turn", "OrderedDicts", "these", "will", "be", "turned", "into", "RECORD", "types", ".", "Ideally", "this", "will",...
d9031901d5bca22fe0d5925d204e6698df9852e1
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/datalab/bigquery/_schema.py#L164-L176
train
googledatalab/pydatalab
datalab/bigquery/_schema.py
Schema._from_list_record
def _from_list_record(data): """ Infer a BigQuery table schema from a list of values. Args: data: The list of values. Returns: A list of dictionaries containing field 'name' and 'type' entries, suitable for use in a BigQuery Tables resource schema. """ return [Schema._get_...
python
def _from_list_record(data): """ Infer a BigQuery table schema from a list of values. Args: data: The list of values. Returns: A list of dictionaries containing field 'name' and 'type' entries, suitable for use in a BigQuery Tables resource schema. """ return [Schema._get_...
[ "def", "_from_list_record", "(", "data", ")", ":", "return", "[", "Schema", ".", "_get_field_entry", "(", "'Column%d'", "%", "(", "i", "+", "1", ")", ",", "value", ")", "for", "i", ",", "value", "in", "enumerate", "(", "data", ")", "]" ]
Infer a BigQuery table schema from a list of values. Args: data: The list of values. Returns: A list of dictionaries containing field 'name' and 'type' entries, suitable for use in a BigQuery Tables resource schema.
[ "Infer", "a", "BigQuery", "table", "schema", "from", "a", "list", "of", "values", "." ]
d9031901d5bca22fe0d5925d204e6698df9852e1
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/datalab/bigquery/_schema.py#L179-L189
train
googledatalab/pydatalab
datalab/bigquery/_schema.py
Schema._from_record
def _from_record(data): """ Infer a BigQuery table schema from a list of fields or a dictionary. The typeof the elements is used. For a list, the field names are simply 'Column1', 'Column2', etc. Args: data: The list of fields or dictionary. Returns: A list of dictionaries containing fi...
python
def _from_record(data): """ Infer a BigQuery table schema from a list of fields or a dictionary. The typeof the elements is used. For a list, the field names are simply 'Column1', 'Column2', etc. Args: data: The list of fields or dictionary. Returns: A list of dictionaries containing fi...
[ "def", "_from_record", "(", "data", ")", ":", "if", "isinstance", "(", "data", ",", "dict", ")", ":", "return", "Schema", ".", "_from_dict_record", "(", "data", ")", "elif", "isinstance", "(", "data", ",", "list", ")", ":", "return", "Schema", ".", "_f...
Infer a BigQuery table schema from a list of fields or a dictionary. The typeof the elements is used. For a list, the field names are simply 'Column1', 'Column2', etc. Args: data: The list of fields or dictionary. Returns: A list of dictionaries containing field 'name' and 'type' entries, suita...
[ "Infer", "a", "BigQuery", "table", "schema", "from", "a", "list", "of", "fields", "or", "a", "dictionary", ".", "The", "typeof", "the", "elements", "is", "used", ".", "For", "a", "list", "the", "field", "names", "are", "simply", "Column1", "Column2", "et...
d9031901d5bca22fe0d5925d204e6698df9852e1
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/datalab/bigquery/_schema.py#L192-L208
train
googledatalab/pydatalab
datalab/utils/commands/_commands.py
CommandParser.create_args
def create_args(line, namespace): """ Expand any meta-variable references in the argument list. """ args = [] # Using shlex.split handles quotes args and escape characters. for arg in shlex.split(line): if not arg: continue if arg[0] == '$': var_name = arg[1:] if var...
python
def create_args(line, namespace): """ Expand any meta-variable references in the argument list. """ args = [] # Using shlex.split handles quotes args and escape characters. for arg in shlex.split(line): if not arg: continue if arg[0] == '$': var_name = arg[1:] if var...
[ "def", "create_args", "(", "line", ",", "namespace", ")", ":", "args", "=", "[", "]", "for", "arg", "in", "shlex", ".", "split", "(", "line", ")", ":", "if", "not", "arg", ":", "continue", "if", "arg", "[", "0", "]", "==", "'$'", ":", "var_name",...
Expand any meta-variable references in the argument list.
[ "Expand", "any", "meta", "-", "variable", "references", "in", "the", "argument", "list", "." ]
d9031901d5bca22fe0d5925d204e6698df9852e1
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/datalab/utils/commands/_commands.py#L49-L64
train
googledatalab/pydatalab
datalab/utils/commands/_commands.py
CommandParser.parse
def parse(self, line, namespace=None): """Parses a line into a dictionary of arguments, expanding meta-variables from a namespace. """ try: if namespace is None: ipy = IPython.get_ipython() namespace = ipy.user_ns args = CommandParser.create_args(line, namespace) return self.pa...
python
def parse(self, line, namespace=None): """Parses a line into a dictionary of arguments, expanding meta-variables from a namespace. """ try: if namespace is None: ipy = IPython.get_ipython() namespace = ipy.user_ns args = CommandParser.create_args(line, namespace) return self.pa...
[ "def", "parse", "(", "self", ",", "line", ",", "namespace", "=", "None", ")", ":", "try", ":", "if", "namespace", "is", "None", ":", "ipy", "=", "IPython", ".", "get_ipython", "(", ")", "namespace", "=", "ipy", ".", "user_ns", "args", "=", "CommandPa...
Parses a line into a dictionary of arguments, expanding meta-variables from a namespace.
[ "Parses", "a", "line", "into", "a", "dictionary", "of", "arguments", "expanding", "meta", "-", "variables", "from", "a", "namespace", "." ]
d9031901d5bca22fe0d5925d204e6698df9852e1
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/datalab/utils/commands/_commands.py#L66-L76
train
googledatalab/pydatalab
datalab/utils/commands/_commands.py
CommandParser.subcommand
def subcommand(self, name, help): """Creates a parser for a sub-command. """ if self._subcommands is None: self._subcommands = self.add_subparsers(help='commands') return self._subcommands.add_parser(name, description=help, help=help)
python
def subcommand(self, name, help): """Creates a parser for a sub-command. """ if self._subcommands is None: self._subcommands = self.add_subparsers(help='commands') return self._subcommands.add_parser(name, description=help, help=help)
[ "def", "subcommand", "(", "self", ",", "name", ",", "help", ")", ":", "if", "self", ".", "_subcommands", "is", "None", ":", "self", ".", "_subcommands", "=", "self", ".", "add_subparsers", "(", "help", "=", "'commands'", ")", "return", "self", ".", "_s...
Creates a parser for a sub-command.
[ "Creates", "a", "parser", "for", "a", "sub", "-", "command", "." ]
d9031901d5bca22fe0d5925d204e6698df9852e1
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/datalab/utils/commands/_commands.py#L78-L82
train
googledatalab/pydatalab
datalab/utils/commands/_utils.py
render_text
def render_text(text, preformatted=False): """ Return text formatted as a HTML Args: text: the text to render preformatted: whether the text should be rendered as preformatted """ return IPython.core.display.HTML(_html.HtmlBuilder.render_text(text, preformatted))
python
def render_text(text, preformatted=False): """ Return text formatted as a HTML Args: text: the text to render preformatted: whether the text should be rendered as preformatted """ return IPython.core.display.HTML(_html.HtmlBuilder.render_text(text, preformatted))
[ "def", "render_text", "(", "text", ",", "preformatted", "=", "False", ")", ":", "return", "IPython", ".", "core", ".", "display", ".", "HTML", "(", "_html", ".", "HtmlBuilder", ".", "render_text", "(", "text", ",", "preformatted", ")", ")" ]
Return text formatted as a HTML Args: text: the text to render preformatted: whether the text should be rendered as preformatted
[ "Return", "text", "formatted", "as", "a", "HTML" ]
d9031901d5bca22fe0d5925d204e6698df9852e1
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/datalab/utils/commands/_utils.py#L73-L80
train
googledatalab/pydatalab
datalab/utils/commands/_utils.py
_get_cols
def _get_cols(fields, schema): """ Get column metadata for Google Charts based on field list and schema. """ typemap = { 'STRING': 'string', 'INT64': 'number', 'INTEGER': 'number', 'FLOAT': 'number', 'FLOAT64': 'number', 'BOOL': 'boolean', 'BOOLEAN': 'boolean', 'DATE': 'date', 'T...
python
def _get_cols(fields, schema): """ Get column metadata for Google Charts based on field list and schema. """ typemap = { 'STRING': 'string', 'INT64': 'number', 'INTEGER': 'number', 'FLOAT': 'number', 'FLOAT64': 'number', 'BOOL': 'boolean', 'BOOLEAN': 'boolean', 'DATE': 'date', 'T...
[ "def", "_get_cols", "(", "fields", ",", "schema", ")", ":", "typemap", "=", "{", "'STRING'", ":", "'string'", ",", "'INT64'", ":", "'number'", ",", "'INTEGER'", ":", "'number'", ",", "'FLOAT'", ":", "'number'", ",", "'FLOAT64'", ":", "'number'", ",", "'B...
Get column metadata for Google Charts based on field list and schema.
[ "Get", "column", "metadata", "for", "Google", "Charts", "based", "on", "field", "list", "and", "schema", "." ]
d9031901d5bca22fe0d5925d204e6698df9852e1
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/datalab/utils/commands/_utils.py#L99-L125
train
googledatalab/pydatalab
datalab/utils/commands/_utils.py
_get_data_from_empty_list
def _get_data_from_empty_list(source, fields='*', first_row=0, count=-1, schema=None): """ Helper function for _get_data that handles empty lists. """ fields = get_field_list(fields, schema) return {'cols': _get_cols(fields, schema), 'rows': []}, 0
python
def _get_data_from_empty_list(source, fields='*', first_row=0, count=-1, schema=None): """ Helper function for _get_data that handles empty lists. """ fields = get_field_list(fields, schema) return {'cols': _get_cols(fields, schema), 'rows': []}, 0
[ "def", "_get_data_from_empty_list", "(", "source", ",", "fields", "=", "'*'", ",", "first_row", "=", "0", ",", "count", "=", "-", "1", ",", "schema", "=", "None", ")", ":", "fields", "=", "get_field_list", "(", "fields", ",", "schema", ")", "return", "...
Helper function for _get_data that handles empty lists.
[ "Helper", "function", "for", "_get_data", "that", "handles", "empty", "lists", "." ]
d9031901d5bca22fe0d5925d204e6698df9852e1
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/datalab/utils/commands/_utils.py#L128-L131
train
googledatalab/pydatalab
datalab/utils/commands/_utils.py
_get_data_from_table
def _get_data_from_table(source, fields='*', first_row=0, count=-1, schema=None): """ Helper function for _get_data that handles BQ Tables. """ if not source.exists(): return _get_data_from_empty_list(source, fields, first_row, count) if schema is None: schema = source.schema fields = get_field_list(fie...
python
def _get_data_from_table(source, fields='*', first_row=0, count=-1, schema=None): """ Helper function for _get_data that handles BQ Tables. """ if not source.exists(): return _get_data_from_empty_list(source, fields, first_row, count) if schema is None: schema = source.schema fields = get_field_list(fie...
[ "def", "_get_data_from_table", "(", "source", ",", "fields", "=", "'*'", ",", "first_row", "=", "0", ",", "count", "=", "-", "1", ",", "schema", "=", "None", ")", ":", "if", "not", "source", ".", "exists", "(", ")", ":", "return", "_get_data_from_empty...
Helper function for _get_data that handles BQ Tables.
[ "Helper", "function", "for", "_get_data", "that", "handles", "BQ", "Tables", "." ]
d9031901d5bca22fe0d5925d204e6698df9852e1
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/datalab/utils/commands/_utils.py#L176-L185
train
googledatalab/pydatalab
datalab/utils/commands/_utils.py
replace_vars
def replace_vars(config, env): """ Replace variable references in config using the supplied env dictionary. Args: config: the config to parse. Can be a tuple, list or dict. env: user supplied dictionary. Raises: Exception if any variable references are not found in env. """ if isinstance(config,...
python
def replace_vars(config, env): """ Replace variable references in config using the supplied env dictionary. Args: config: the config to parse. Can be a tuple, list or dict. env: user supplied dictionary. Raises: Exception if any variable references are not found in env. """ if isinstance(config,...
[ "def", "replace_vars", "(", "config", ",", "env", ")", ":", "if", "isinstance", "(", "config", ",", "dict", ")", ":", "for", "k", ",", "v", "in", "list", "(", "config", ".", "items", "(", ")", ")", ":", "if", "isinstance", "(", "v", ",", "dict", ...
Replace variable references in config using the supplied env dictionary. Args: config: the config to parse. Can be a tuple, list or dict. env: user supplied dictionary. Raises: Exception if any variable references are not found in env.
[ "Replace", "variable", "references", "in", "config", "using", "the", "supplied", "env", "dictionary", "." ]
d9031901d5bca22fe0d5925d204e6698df9852e1
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/datalab/utils/commands/_utils.py#L284-L310
train
googledatalab/pydatalab
datalab/utils/commands/_utils.py
parse_config
def parse_config(config, env, as_dict=True): """ Parse a config from a magic cell body. This could be JSON or YAML. We turn it into a Python dictionary then recursively replace any variable references using the supplied env dictionary. """ if config is None: return None stripped = config.strip(...
python
def parse_config(config, env, as_dict=True): """ Parse a config from a magic cell body. This could be JSON or YAML. We turn it into a Python dictionary then recursively replace any variable references using the supplied env dictionary. """ if config is None: return None stripped = config.strip(...
[ "def", "parse_config", "(", "config", ",", "env", ",", "as_dict", "=", "True", ")", ":", "if", "config", "is", "None", ":", "return", "None", "stripped", "=", "config", ".", "strip", "(", ")", "if", "len", "(", "stripped", ")", "==", "0", ":", "con...
Parse a config from a magic cell body. This could be JSON or YAML. We turn it into a Python dictionary then recursively replace any variable references using the supplied env dictionary.
[ "Parse", "a", "config", "from", "a", "magic", "cell", "body", ".", "This", "could", "be", "JSON", "or", "YAML", ".", "We", "turn", "it", "into", "a", "Python", "dictionary", "then", "recursively", "replace", "any", "variable", "references", "using", "the",...
d9031901d5bca22fe0d5925d204e6698df9852e1
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/datalab/utils/commands/_utils.py#L313-L333
train
googledatalab/pydatalab
datalab/utils/commands/_utils.py
validate_config
def validate_config(config, required_keys, optional_keys=None): """ Validate a config dictionary to make sure it includes all required keys and does not include any unexpected keys. Args: config: the config to validate. required_keys: the names of the keys that the config must have. optional_keys...
python
def validate_config(config, required_keys, optional_keys=None): """ Validate a config dictionary to make sure it includes all required keys and does not include any unexpected keys. Args: config: the config to validate. required_keys: the names of the keys that the config must have. optional_keys...
[ "def", "validate_config", "(", "config", ",", "required_keys", ",", "optional_keys", "=", "None", ")", ":", "if", "optional_keys", "is", "None", ":", "optional_keys", "=", "[", "]", "if", "not", "isinstance", "(", "config", ",", "dict", ")", ":", "raise", ...
Validate a config dictionary to make sure it includes all required keys and does not include any unexpected keys. Args: config: the config to validate. required_keys: the names of the keys that the config must have. optional_keys: the names of the keys that the config can have. Raises: Excep...
[ "Validate", "a", "config", "dictionary", "to", "make", "sure", "it", "includes", "all", "required", "keys", "and", "does", "not", "include", "any", "unexpected", "keys", "." ]
d9031901d5bca22fe0d5925d204e6698df9852e1
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/datalab/utils/commands/_utils.py#L336-L357
train
googledatalab/pydatalab
datalab/utils/commands/_utils.py
validate_config_must_have
def validate_config_must_have(config, required_keys): """ Validate a config dictionary to make sure it has all of the specified keys Args: config: the config to validate. required_keys: the list of possible keys that config must include. Raises: Exception if the config does not have any of them. "...
python
def validate_config_must_have(config, required_keys): """ Validate a config dictionary to make sure it has all of the specified keys Args: config: the config to validate. required_keys: the list of possible keys that config must include. Raises: Exception if the config does not have any of them. "...
[ "def", "validate_config_must_have", "(", "config", ",", "required_keys", ")", ":", "missing_keys", "=", "set", "(", "required_keys", ")", "-", "set", "(", "config", ")", "if", "len", "(", "missing_keys", ")", ">", "0", ":", "raise", "Exception", "(", "'Inv...
Validate a config dictionary to make sure it has all of the specified keys Args: config: the config to validate. required_keys: the list of possible keys that config must include. Raises: Exception if the config does not have any of them.
[ "Validate", "a", "config", "dictionary", "to", "make", "sure", "it", "has", "all", "of", "the", "specified", "keys" ]
d9031901d5bca22fe0d5925d204e6698df9852e1
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/datalab/utils/commands/_utils.py#L360-L372
train
googledatalab/pydatalab
datalab/utils/commands/_utils.py
validate_config_has_one_of
def validate_config_has_one_of(config, one_of_keys): """ Validate a config dictionary to make sure it has one and only one key in one_of_keys. Args: config: the config to validate. one_of_keys: the list of possible keys that config can have one and only one. Raises: Exception if the config doe...
python
def validate_config_has_one_of(config, one_of_keys): """ Validate a config dictionary to make sure it has one and only one key in one_of_keys. Args: config: the config to validate. one_of_keys: the list of possible keys that config can have one and only one. Raises: Exception if the config doe...
[ "def", "validate_config_has_one_of", "(", "config", ",", "one_of_keys", ")", ":", "intersection", "=", "set", "(", "config", ")", ".", "intersection", "(", "one_of_keys", ")", "if", "len", "(", "intersection", ")", ">", "1", ":", "raise", "Exception", "(", ...
Validate a config dictionary to make sure it has one and only one key in one_of_keys. Args: config: the config to validate. one_of_keys: the list of possible keys that config can have one and only one. Raises: Exception if the config does not have any of them, or multiple of them.
[ "Validate", "a", "config", "dictionary", "to", "make", "sure", "it", "has", "one", "and", "only", "one", "key", "in", "one_of_keys", "." ]
d9031901d5bca22fe0d5925d204e6698df9852e1
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/datalab/utils/commands/_utils.py#L375-L390
train
googledatalab/pydatalab
datalab/utils/commands/_utils.py
validate_config_value
def validate_config_value(value, possible_values): """ Validate a config value to make sure it is one of the possible values. Args: value: the config value to validate. possible_values: the possible values the value can be Raises: Exception if the value is not one of possible values. """ if valu...
python
def validate_config_value(value, possible_values): """ Validate a config value to make sure it is one of the possible values. Args: value: the config value to validate. possible_values: the possible values the value can be Raises: Exception if the value is not one of possible values. """ if valu...
[ "def", "validate_config_value", "(", "value", ",", "possible_values", ")", ":", "if", "value", "not", "in", "possible_values", ":", "raise", "Exception", "(", "'Invalid config value \"%s\". Possible values are '", "'%s'", "%", "(", "value", ",", "', '", ".", "join",...
Validate a config value to make sure it is one of the possible values. Args: value: the config value to validate. possible_values: the possible values the value can be Raises: Exception if the value is not one of possible values.
[ "Validate", "a", "config", "value", "to", "make", "sure", "it", "is", "one", "of", "the", "possible", "values", "." ]
d9031901d5bca22fe0d5925d204e6698df9852e1
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/datalab/utils/commands/_utils.py#L393-L405
train
googledatalab/pydatalab
datalab/utils/commands/_utils.py
validate_gcs_path
def validate_gcs_path(path, require_object): """ Check whether a given path is a valid GCS path. Args: path: the config to check. require_object: if True, the path has to be an object path but not bucket path. Raises: Exception if the path is invalid """ bucket, key = datalab.storage._bucket.par...
python
def validate_gcs_path(path, require_object): """ Check whether a given path is a valid GCS path. Args: path: the config to check. require_object: if True, the path has to be an object path but not bucket path. Raises: Exception if the path is invalid """ bucket, key = datalab.storage._bucket.par...
[ "def", "validate_gcs_path", "(", "path", ",", "require_object", ")", ":", "bucket", ",", "key", "=", "datalab", ".", "storage", ".", "_bucket", ".", "parse_name", "(", "path", ")", "if", "bucket", "is", "None", ":", "raise", "Exception", "(", "'Invalid GCS...
Check whether a given path is a valid GCS path. Args: path: the config to check. require_object: if True, the path has to be an object path but not bucket path. Raises: Exception if the path is invalid
[ "Check", "whether", "a", "given", "path", "is", "a", "valid", "GCS", "path", "." ]
d9031901d5bca22fe0d5925d204e6698df9852e1
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/datalab/utils/commands/_utils.py#L421-L435
train
googledatalab/pydatalab
datalab/utils/commands/_utils.py
profile_df
def profile_df(df): """ Generate a profile of data in a dataframe. Args: df: the Pandas dataframe. """ # The bootstrap CSS messes up the Datalab display so we tweak it to not have an effect. # TODO(gram): strip it out rather than this kludge. return IPython.core.display.HTML( pandas_profiling.Pro...
python
def profile_df(df): """ Generate a profile of data in a dataframe. Args: df: the Pandas dataframe. """ # The bootstrap CSS messes up the Datalab display so we tweak it to not have an effect. # TODO(gram): strip it out rather than this kludge. return IPython.core.display.HTML( pandas_profiling.Pro...
[ "def", "profile_df", "(", "df", ")", ":", "return", "IPython", ".", "core", ".", "display", ".", "HTML", "(", "pandas_profiling", ".", "ProfileReport", "(", "df", ")", ".", "html", ".", "replace", "(", "'bootstrap'", ",", "'nonexistent'", ")", ")" ]
Generate a profile of data in a dataframe. Args: df: the Pandas dataframe.
[ "Generate", "a", "profile", "of", "data", "in", "a", "dataframe", "." ]
d9031901d5bca22fe0d5925d204e6698df9852e1
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/datalab/utils/commands/_utils.py#L675-L684
train
googledatalab/pydatalab
solutionbox/structured_data/mltoolbox/_structured_data/_package.py
_package_to_staging
def _package_to_staging(staging_package_url): """Repackage this package from local installed location and copy it to GCS. Args: staging_package_url: GCS path. """ import google.datalab.ml as ml # Find the package root. __file__ is under [package_root]/mltoolbox/_structured_data/this_file ...
python
def _package_to_staging(staging_package_url): """Repackage this package from local installed location and copy it to GCS. Args: staging_package_url: GCS path. """ import google.datalab.ml as ml # Find the package root. __file__ is under [package_root]/mltoolbox/_structured_data/this_file ...
[ "def", "_package_to_staging", "(", "staging_package_url", ")", ":", "import", "google", ".", "datalab", ".", "ml", "as", "ml", "package_root", "=", "os", ".", "path", ".", "abspath", "(", "os", ".", "path", ".", "join", "(", "os", ".", "path", ".", "di...
Repackage this package from local installed location and copy it to GCS. Args: staging_package_url: GCS path.
[ "Repackage", "this", "package", "from", "local", "installed", "location", "and", "copy", "it", "to", "GCS", "." ]
d9031901d5bca22fe0d5925d204e6698df9852e1
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/solutionbox/structured_data/mltoolbox/_structured_data/_package.py#L87-L105
train
googledatalab/pydatalab
solutionbox/structured_data/mltoolbox/_structured_data/_package.py
analyze
def analyze(output_dir, dataset, cloud=False, project_id=None): """Blocking version of analyze_async. See documentation of analyze_async.""" job = analyze_async( output_dir=output_dir, dataset=dataset, cloud=cloud, project_id=project_id) job.wait() print('Analyze: ' + str(job.state))
python
def analyze(output_dir, dataset, cloud=False, project_id=None): """Blocking version of analyze_async. See documentation of analyze_async.""" job = analyze_async( output_dir=output_dir, dataset=dataset, cloud=cloud, project_id=project_id) job.wait() print('Analyze: ' + str(job.state))
[ "def", "analyze", "(", "output_dir", ",", "dataset", ",", "cloud", "=", "False", ",", "project_id", "=", "None", ")", ":", "job", "=", "analyze_async", "(", "output_dir", "=", "output_dir", ",", "dataset", "=", "dataset", ",", "cloud", "=", "cloud", ",",...
Blocking version of analyze_async. See documentation of analyze_async.
[ "Blocking", "version", "of", "analyze_async", ".", "See", "documentation", "of", "analyze_async", "." ]
d9031901d5bca22fe0d5925d204e6698df9852e1
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/solutionbox/structured_data/mltoolbox/_structured_data/_package.py#L136-L144
train
googledatalab/pydatalab
solutionbox/structured_data/mltoolbox/_structured_data/_package.py
analyze_async
def analyze_async(output_dir, dataset, cloud=False, project_id=None): """Analyze data locally or in the cloud with BigQuery. Produce analysis used by training. This can take a while, even for small datasets. For small datasets, it may be faster to use local_analysis. Args: output_dir: The output directory...
python
def analyze_async(output_dir, dataset, cloud=False, project_id=None): """Analyze data locally or in the cloud with BigQuery. Produce analysis used by training. This can take a while, even for small datasets. For small datasets, it may be faster to use local_analysis. Args: output_dir: The output directory...
[ "def", "analyze_async", "(", "output_dir", ",", "dataset", ",", "cloud", "=", "False", ",", "project_id", "=", "None", ")", ":", "import", "google", ".", "datalab", ".", "utils", "as", "du", "with", "warnings", ".", "catch_warnings", "(", ")", ":", "warn...
Analyze data locally or in the cloud with BigQuery. Produce analysis used by training. This can take a while, even for small datasets. For small datasets, it may be faster to use local_analysis. Args: output_dir: The output directory to use. dataset: only CsvDataSet is supported currently. cloud: If...
[ "Analyze", "data", "locally", "or", "in", "the", "cloud", "with", "BigQuery", "." ]
d9031901d5bca22fe0d5925d204e6698df9852e1
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/solutionbox/structured_data/mltoolbox/_structured_data/_package.py#L147-L168
train
googledatalab/pydatalab
solutionbox/structured_data/mltoolbox/_structured_data/_package.py
cloud_train
def cloud_train(train_dataset, eval_dataset, analysis_dir, output_dir, features, model_type, max_steps, num_epochs, train_batch_size, eval_batch_size, min_eval_...
python
def cloud_train(train_dataset, eval_dataset, analysis_dir, output_dir, features, model_type, max_steps, num_epochs, train_batch_size, eval_batch_size, min_eval_...
[ "def", "cloud_train", "(", "train_dataset", ",", "eval_dataset", ",", "analysis_dir", ",", "output_dir", ",", "features", ",", "model_type", ",", "max_steps", ",", "num_epochs", ",", "train_batch_size", ",", "eval_batch_size", ",", "min_eval_frequency", ",", "top_n"...
Train model using CloudML. See local_train() for a description of the args. Args: config: A CloudTrainingConfig object. job_name: Training job name. A default will be picked if None.
[ "Train", "model", "using", "CloudML", "." ]
d9031901d5bca22fe0d5925d204e6698df9852e1
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/solutionbox/structured_data/mltoolbox/_structured_data/_package.py#L456-L543
train
googledatalab/pydatalab
solutionbox/structured_data/mltoolbox/_structured_data/_package.py
predict
def predict(data, training_dir=None, model_name=None, model_version=None, cloud=False): """Runs prediction locally or on the cloud. Args: data: List of csv strings or a Pandas DataFrame that match the model schema. training_dir: local path to the trained output folder. model_name: deployed model name ...
python
def predict(data, training_dir=None, model_name=None, model_version=None, cloud=False): """Runs prediction locally or on the cloud. Args: data: List of csv strings or a Pandas DataFrame that match the model schema. training_dir: local path to the trained output folder. model_name: deployed model name ...
[ "def", "predict", "(", "data", ",", "training_dir", "=", "None", ",", "model_name", "=", "None", ",", "model_version", "=", "None", ",", "cloud", "=", "False", ")", ":", "if", "cloud", ":", "if", "not", "model_version", "or", "not", "model_name", ":", ...
Runs prediction locally or on the cloud. Args: data: List of csv strings or a Pandas DataFrame that match the model schema. training_dir: local path to the trained output folder. model_name: deployed model name model_version: depoyed model version cloud: bool. If False, does local prediction and ...
[ "Runs", "prediction", "locally", "or", "on", "the", "cloud", "." ]
d9031901d5bca22fe0d5925d204e6698df9852e1
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/solutionbox/structured_data/mltoolbox/_structured_data/_package.py#L550-L592
train
googledatalab/pydatalab
solutionbox/structured_data/mltoolbox/_structured_data/_package.py
local_predict
def local_predict(training_dir, data): """Runs local prediction on the prediction graph. Runs local prediction and returns the result in a Pandas DataFrame. For running prediction on a large dataset or saving the results, run local_batch_prediction or batch_prediction. Input data should fully match the schem...
python
def local_predict(training_dir, data): """Runs local prediction on the prediction graph. Runs local prediction and returns the result in a Pandas DataFrame. For running prediction on a large dataset or saving the results, run local_batch_prediction or batch_prediction. Input data should fully match the schem...
[ "def", "local_predict", "(", "training_dir", ",", "data", ")", ":", "from", ".", "prediction", "import", "predict", "as", "predict_module", "tmp_dir", "=", "tempfile", ".", "mkdtemp", "(", ")", "_", ",", "input_file_path", "=", "tempfile", ".", "mkstemp", "(...
Runs local prediction on the prediction graph. Runs local prediction and returns the result in a Pandas DataFrame. For running prediction on a large dataset or saving the results, run local_batch_prediction or batch_prediction. Input data should fully match the schema that was used at training, except the targ...
[ "Runs", "local", "prediction", "on", "the", "prediction", "graph", "." ]
d9031901d5bca22fe0d5925d204e6698df9852e1
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/solutionbox/structured_data/mltoolbox/_structured_data/_package.py#L595-L668
train
googledatalab/pydatalab
solutionbox/structured_data/mltoolbox/_structured_data/_package.py
cloud_predict
def cloud_predict(model_name, model_version, data): """Use Online prediction. Runs online prediction in the cloud and prints the results to the screen. For running prediction on a large dataset or saving the results, run local_batch_prediction or batch_prediction. Args: model_name: deployed model name ...
python
def cloud_predict(model_name, model_version, data): """Use Online prediction. Runs online prediction in the cloud and prints the results to the screen. For running prediction on a large dataset or saving the results, run local_batch_prediction or batch_prediction. Args: model_name: deployed model name ...
[ "def", "cloud_predict", "(", "model_name", ",", "model_version", ",", "data", ")", ":", "import", "google", ".", "datalab", ".", "ml", "as", "ml", "if", "isinstance", "(", "data", ",", "pd", ".", "DataFrame", ")", ":", "string_buffer", "=", "io", ".", ...
Use Online prediction. Runs online prediction in the cloud and prints the results to the screen. For running prediction on a large dataset or saving the results, run local_batch_prediction or batch_prediction. Args: model_name: deployed model name model_version: depoyed model version data: List of...
[ "Use", "Online", "prediction", "." ]
d9031901d5bca22fe0d5925d204e6698df9852e1
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/solutionbox/structured_data/mltoolbox/_structured_data/_package.py#L671-L715
train
googledatalab/pydatalab
solutionbox/structured_data/mltoolbox/_structured_data/_package.py
batch_predict
def batch_predict(training_dir, prediction_input_file, output_dir, mode, batch_size=16, shard_files=True, output_format='csv', cloud=False): """Blocking versoin of batch_predict. See documentation of batch_prediction_async. """ job = batch_predict_async( training_dir=t...
python
def batch_predict(training_dir, prediction_input_file, output_dir, mode, batch_size=16, shard_files=True, output_format='csv', cloud=False): """Blocking versoin of batch_predict. See documentation of batch_prediction_async. """ job = batch_predict_async( training_dir=t...
[ "def", "batch_predict", "(", "training_dir", ",", "prediction_input_file", ",", "output_dir", ",", "mode", ",", "batch_size", "=", "16", ",", "shard_files", "=", "True", ",", "output_format", "=", "'csv'", ",", "cloud", "=", "False", ")", ":", "job", "=", ...
Blocking versoin of batch_predict. See documentation of batch_prediction_async.
[ "Blocking", "versoin", "of", "batch_predict", "." ]
d9031901d5bca22fe0d5925d204e6698df9852e1
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/solutionbox/structured_data/mltoolbox/_structured_data/_package.py#L722-L739
train
googledatalab/pydatalab
solutionbox/structured_data/mltoolbox/_structured_data/_package.py
batch_predict_async
def batch_predict_async(training_dir, prediction_input_file, output_dir, mode, batch_size=16, shard_files=True, output_format='csv', cloud=False): """Local and cloud batch prediction. Args: training_dir: The output folder of training. prediction_input_file: csv file pattern to a fil...
python
def batch_predict_async(training_dir, prediction_input_file, output_dir, mode, batch_size=16, shard_files=True, output_format='csv', cloud=False): """Local and cloud batch prediction. Args: training_dir: The output folder of training. prediction_input_file: csv file pattern to a fil...
[ "def", "batch_predict_async", "(", "training_dir", ",", "prediction_input_file", ",", "output_dir", ",", "mode", ",", "batch_size", "=", "16", ",", "shard_files", "=", "True", ",", "output_format", "=", "'csv'", ",", "cloud", "=", "False", ")", ":", "import", ...
Local and cloud batch prediction. Args: training_dir: The output folder of training. prediction_input_file: csv file pattern to a file. File must be on GCS if running cloud prediction output_dir: output location to save the results. Must be a GSC path if running cloud prediction. mode...
[ "Local", "and", "cloud", "batch", "prediction", "." ]
d9031901d5bca22fe0d5925d204e6698df9852e1
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/solutionbox/structured_data/mltoolbox/_structured_data/_package.py#L742-L777
train
googledatalab/pydatalab
solutionbox/structured_data/mltoolbox/_structured_data/prediction/predict.py
make_prediction_pipeline
def make_prediction_pipeline(pipeline, args): """Builds the prediction pipeline. Reads the csv files, prepends a ',' if the target column is missing, run prediction, and then prints the formated results to a file. Args: pipeline: the pipeline args: command line args """ # DF bug: DF does not work...
python
def make_prediction_pipeline(pipeline, args): """Builds the prediction pipeline. Reads the csv files, prepends a ',' if the target column is missing, run prediction, and then prints the formated results to a file. Args: pipeline: the pipeline args: command line args """ # DF bug: DF does not work...
[ "def", "make_prediction_pipeline", "(", "pipeline", ",", "args", ")", ":", "predicted_values", ",", "errors", "=", "(", "pipeline", "|", "'Read CSV Files'", ">>", "beam", ".", "io", ".", "ReadFromText", "(", "str", "(", "args", ".", "predict_data", ")", ",",...
Builds the prediction pipeline. Reads the csv files, prepends a ',' if the target column is missing, run prediction, and then prints the formated results to a file. Args: pipeline: the pipeline args: command line args
[ "Builds", "the", "prediction", "pipeline", "." ]
d9031901d5bca22fe0d5925d204e6698df9852e1
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/solutionbox/structured_data/mltoolbox/_structured_data/prediction/predict.py#L349-L373
train
googledatalab/pydatalab
solutionbox/structured_data/mltoolbox/_structured_data/prediction/predict.py
RunGraphDoFn.process
def process(self, element): """Run batch prediciton on a TF graph. Args: element: list of strings, representing one batch input to the TF graph. """ import collections import apache_beam as beam num_in_batch = 0 try: assert self._session is not None feed_dict = collectio...
python
def process(self, element): """Run batch prediciton on a TF graph. Args: element: list of strings, representing one batch input to the TF graph. """ import collections import apache_beam as beam num_in_batch = 0 try: assert self._session is not None feed_dict = collectio...
[ "def", "process", "(", "self", ",", "element", ")", ":", "import", "collections", "import", "apache_beam", "as", "beam", "num_in_batch", "=", "0", "try", ":", "assert", "self", ".", "_session", "is", "not", "None", "feed_dict", "=", "collections", ".", "de...
Run batch prediciton on a TF graph. Args: element: list of strings, representing one batch input to the TF graph.
[ "Run", "batch", "prediciton", "on", "a", "TF", "graph", "." ]
d9031901d5bca22fe0d5925d204e6698df9852e1
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/solutionbox/structured_data/mltoolbox/_structured_data/prediction/predict.py#L165-L218
train
googledatalab/pydatalab
solutionbox/structured_data/mltoolbox/_structured_data/prediction/predict.py
CSVCoder.encode
def encode(self, tf_graph_predictions): """Encodes the graph json prediction into csv. Args: tf_graph_predictions: python dict. Returns: csv string. """ row = [] for col in self._header: row.append(str(tf_graph_predictions[col])) return ','.join(row)
python
def encode(self, tf_graph_predictions): """Encodes the graph json prediction into csv. Args: tf_graph_predictions: python dict. Returns: csv string. """ row = [] for col in self._header: row.append(str(tf_graph_predictions[col])) return ','.join(row)
[ "def", "encode", "(", "self", ",", "tf_graph_predictions", ")", ":", "row", "=", "[", "]", "for", "col", "in", "self", ".", "_header", ":", "row", ".", "append", "(", "str", "(", "tf_graph_predictions", "[", "col", "]", ")", ")", "return", "','", "."...
Encodes the graph json prediction into csv. Args: tf_graph_predictions: python dict. Returns: csv string.
[ "Encodes", "the", "graph", "json", "prediction", "into", "csv", "." ]
d9031901d5bca22fe0d5925d204e6698df9852e1
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/solutionbox/structured_data/mltoolbox/_structured_data/prediction/predict.py#L251-L264
train
googledatalab/pydatalab
google/datalab/stackdriver/monitoring/_query_metadata.py
QueryMetadata.as_dataframe
def as_dataframe(self, max_rows=None): """Creates a pandas dataframe from the query metadata. Args: max_rows: The maximum number of timeseries metadata to return. If None, return all. Returns: A pandas dataframe containing the resource type, resource labels and me...
python
def as_dataframe(self, max_rows=None): """Creates a pandas dataframe from the query metadata. Args: max_rows: The maximum number of timeseries metadata to return. If None, return all. Returns: A pandas dataframe containing the resource type, resource labels and me...
[ "def", "as_dataframe", "(", "self", ",", "max_rows", "=", "None", ")", ":", "max_rows", "=", "len", "(", "self", ".", "_timeseries_list", ")", "if", "max_rows", "is", "None", "else", "max_rows", "headers", "=", "[", "{", "'resource'", ":", "ts", ".", "...
Creates a pandas dataframe from the query metadata. Args: max_rows: The maximum number of timeseries metadata to return. If None, return all. Returns: A pandas dataframe containing the resource type, resource labels and metric labels. Each row in this dataframe correspo...
[ "Creates", "a", "pandas", "dataframe", "from", "the", "query", "metadata", "." ]
d9031901d5bca22fe0d5925d204e6698df9852e1
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/google/datalab/stackdriver/monitoring/_query_metadata.py#L53-L92
train
googledatalab/pydatalab
solutionbox/image_classification/mltoolbox/image/classification/_util.py
get_train_eval_files
def get_train_eval_files(input_dir): """Get preprocessed training and eval files.""" data_dir = _get_latest_data_dir(input_dir) train_pattern = os.path.join(data_dir, 'train*.tfrecord.gz') eval_pattern = os.path.join(data_dir, 'eval*.tfrecord.gz') train_files = file_io.get_matching_files(train_pattern) eval...
python
def get_train_eval_files(input_dir): """Get preprocessed training and eval files.""" data_dir = _get_latest_data_dir(input_dir) train_pattern = os.path.join(data_dir, 'train*.tfrecord.gz') eval_pattern = os.path.join(data_dir, 'eval*.tfrecord.gz') train_files = file_io.get_matching_files(train_pattern) eval...
[ "def", "get_train_eval_files", "(", "input_dir", ")", ":", "data_dir", "=", "_get_latest_data_dir", "(", "input_dir", ")", "train_pattern", "=", "os", ".", "path", ".", "join", "(", "data_dir", ",", "'train*.tfrecord.gz'", ")", "eval_pattern", "=", "os", ".", ...
Get preprocessed training and eval files.
[ "Get", "preprocessed", "training", "and", "eval", "files", "." ]
d9031901d5bca22fe0d5925d204e6698df9852e1
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/solutionbox/image_classification/mltoolbox/image/classification/_util.py#L53-L60
train
googledatalab/pydatalab
solutionbox/image_classification/mltoolbox/image/classification/_util.py
get_labels
def get_labels(input_dir): """Get a list of labels from preprocessed output dir.""" data_dir = _get_latest_data_dir(input_dir) labels_file = os.path.join(data_dir, 'labels') with file_io.FileIO(labels_file, 'r') as f: labels = f.read().rstrip().split('\n') return labels
python
def get_labels(input_dir): """Get a list of labels from preprocessed output dir.""" data_dir = _get_latest_data_dir(input_dir) labels_file = os.path.join(data_dir, 'labels') with file_io.FileIO(labels_file, 'r') as f: labels = f.read().rstrip().split('\n') return labels
[ "def", "get_labels", "(", "input_dir", ")", ":", "data_dir", "=", "_get_latest_data_dir", "(", "input_dir", ")", "labels_file", "=", "os", ".", "path", ".", "join", "(", "data_dir", ",", "'labels'", ")", "with", "file_io", ".", "FileIO", "(", "labels_file", ...
Get a list of labels from preprocessed output dir.
[ "Get", "a", "list", "of", "labels", "from", "preprocessed", "output", "dir", "." ]
d9031901d5bca22fe0d5925d204e6698df9852e1
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/solutionbox/image_classification/mltoolbox/image/classification/_util.py#L63-L69
train
googledatalab/pydatalab
solutionbox/image_classification/mltoolbox/image/classification/_util.py
override_if_not_in_args
def override_if_not_in_args(flag, argument, args): """Checks if flags is in args, and if not it adds the flag to args.""" if flag not in args: args.extend([flag, argument])
python
def override_if_not_in_args(flag, argument, args): """Checks if flags is in args, and if not it adds the flag to args.""" if flag not in args: args.extend([flag, argument])
[ "def", "override_if_not_in_args", "(", "flag", ",", "argument", ",", "args", ")", ":", "if", "flag", "not", "in", "args", ":", "args", ".", "extend", "(", "[", "flag", ",", "argument", "]", ")" ]
Checks if flags is in args, and if not it adds the flag to args.
[ "Checks", "if", "flags", "is", "in", "args", "and", "if", "not", "it", "adds", "the", "flag", "to", "args", "." ]
d9031901d5bca22fe0d5925d204e6698df9852e1
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/solutionbox/image_classification/mltoolbox/image/classification/_util.py#L120-L123
train
googledatalab/pydatalab
solutionbox/image_classification/mltoolbox/image/classification/_util.py
loss
def loss(loss_value): """Calculates aggregated mean loss.""" total_loss = tf.Variable(0.0, False) loss_count = tf.Variable(0, False) total_loss_update = tf.assign_add(total_loss, loss_value) loss_count_update = tf.assign_add(loss_count, 1) loss_op = total_loss / tf.cast(loss_count, tf.float32) return [tot...
python
def loss(loss_value): """Calculates aggregated mean loss.""" total_loss = tf.Variable(0.0, False) loss_count = tf.Variable(0, False) total_loss_update = tf.assign_add(total_loss, loss_value) loss_count_update = tf.assign_add(loss_count, 1) loss_op = total_loss / tf.cast(loss_count, tf.float32) return [tot...
[ "def", "loss", "(", "loss_value", ")", ":", "total_loss", "=", "tf", ".", "Variable", "(", "0.0", ",", "False", ")", "loss_count", "=", "tf", ".", "Variable", "(", "0", ",", "False", ")", "total_loss_update", "=", "tf", ".", "assign_add", "(", "total_l...
Calculates aggregated mean loss.
[ "Calculates", "aggregated", "mean", "loss", "." ]
d9031901d5bca22fe0d5925d204e6698df9852e1
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/solutionbox/image_classification/mltoolbox/image/classification/_util.py#L126-L133
train
googledatalab/pydatalab
solutionbox/image_classification/mltoolbox/image/classification/_util.py
accuracy
def accuracy(logits, labels): """Calculates aggregated accuracy.""" is_correct = tf.nn.in_top_k(logits, labels, 1) correct = tf.reduce_sum(tf.cast(is_correct, tf.int32)) incorrect = tf.reduce_sum(tf.cast(tf.logical_not(is_correct), tf.int32)) correct_count = tf.Variable(0, False) incorrect_count = tf.Variab...
python
def accuracy(logits, labels): """Calculates aggregated accuracy.""" is_correct = tf.nn.in_top_k(logits, labels, 1) correct = tf.reduce_sum(tf.cast(is_correct, tf.int32)) incorrect = tf.reduce_sum(tf.cast(tf.logical_not(is_correct), tf.int32)) correct_count = tf.Variable(0, False) incorrect_count = tf.Variab...
[ "def", "accuracy", "(", "logits", ",", "labels", ")", ":", "is_correct", "=", "tf", ".", "nn", ".", "in_top_k", "(", "logits", ",", "labels", ",", "1", ")", "correct", "=", "tf", ".", "reduce_sum", "(", "tf", ".", "cast", "(", "is_correct", ",", "t...
Calculates aggregated accuracy.
[ "Calculates", "aggregated", "accuracy", "." ]
d9031901d5bca22fe0d5925d204e6698df9852e1
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/solutionbox/image_classification/mltoolbox/image/classification/_util.py#L136-L147
train
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", "." ]
d9031901d5bca22fe0d5925d204e6698df9852e1
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/solutionbox/image_classification/mltoolbox/image/classification/_util.py#L150-L162
train
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", "." ]
d9031901d5bca22fe0d5925d204e6698df9852e1
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/solutionbox/image_classification/mltoolbox/image/classification/_util.py#L165-L189
train
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", ")", ":", "height", "=", "299", "width", "=", "299", "channels", "=", "3", "image", "=", "tf", ".", "image", ".", "decode_jpeg", "(", "image_str_tensor", ",", "channels", "=", "channels", ")", "image", "...
Decodes jpeg string, resizes it and returns a uint8 tensor.
[ "Decodes", "jpeg", "string", "resizes", "it", "and", "returns", "a", "uint8", "tensor", "." ]
d9031901d5bca22fe0d5925d204e6698df9852e1
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/solutionbox/image_classification/mltoolbox/image/classification/_util.py#L192-L208
train
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", "." ]
d9031901d5bca22fe0d5925d204e6698df9852e1
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/solutionbox/image_classification/mltoolbox/image/classification/_util.py#L211-L216
train
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", "." ]
d9031901d5bca22fe0d5925d204e6698df9852e1
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/solutionbox/image_classification/mltoolbox/image/classification/_util.py#L219-L239
train
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", "." ]
d9031901d5bca22fe0d5925d204e6698df9852e1
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/solutionbox/image_classification/mltoolbox/image/classification/_util.py#L242-L254
train
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", "package_root", "=", "os", ".", "path", ".", "join", "(", "os", ".", "path", ".", "dirname", "(", "__file__", ")", ",", "'../../../'",...
Repackage it from local installed location and copy it to GCS.
[ "Repackage", "it", "from", "local", "installed", "location", "and", "copy", "it", "to", "GCS", "." ]
d9031901d5bca22fe0d5925d204e6698df9852e1
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/solutionbox/image_classification/mltoolbox/image/classification/_util.py#L257-L268
train
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", "." ]
d9031901d5bca22fe0d5925d204e6698df9852e1
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/google/datalab/contrib/pipeline/_pipeline.py#L48-L68
train
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", "." ]
d9031901d5bca22fe0d5925d204e6698df9852e1
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/google/datalab/contrib/pipeline/_pipeline.py#L167-L175
train
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", ")", ":", "task_type_to_operator_prefix_mapping", "=", "{", "'pydatalab.bq.execute'", ":", "(", "'Execute'", ",", "'google.datalab.contrib.bigquery.operators._bq_execute_operator'", ")", ",", "'pydatalab.bq.extract'", ":...
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"...
d9031901d5bca22fe0d5925d204e6698df9852e1
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/google/datalab/contrib/pipeline/_pipeline.py#L178-L198
train
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", ")", ":", "operator_task_details", "=", "task_details", ".", "copy", "(", ")", "if", "'type'", "in", "operator_task_details", ".", "keys", "(", ")", ":", "del", "operator_...
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...
d9031901d5bca22fe0d5925d204e6698df9852e1
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/google/datalab/contrib/pipeline/_pipeline.py#L201-L236
train
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", "." ]
d9031901d5bca22fe0d5925d204e6698df9852e1
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/google/datalab/ml/_dataset.py#L196-L218
train
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", "." ]
d9031901d5bca22fe0d5925d204e6698df9852e1
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/google/datalab/ml/_dataset.py#L252-L265
train
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", "." ]
d9031901d5bca22fe0d5925d204e6698df9852e1
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/google/datalab/stackdriver/monitoring/_group.py#L45-L61
train
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", "." ]
d9031901d5bca22fe0d5925d204e6698df9852e1
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/google/datalab/stackdriver/monitoring/_group.py#L63-L85
train
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", ")", ":", "dependencies", "=", "SqlStatement", ".", "_get_dependencies", "(", "sql", ")", "for", "dependency", "in", "depende...
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", "." ]
d9031901d5bca22fe0d5925d204e6698df9852e1
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/datalab/data/_sql_statement.py#L69-L120
train
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", "." ]
d9031901d5bca22fe0d5925d204e6698df9852e1
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/datalab/data/_sql_statement.py#L127-L193
train
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", "." ]
d9031901d5bca22fe0d5925d204e6698df9852e1
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/datalab/data/_sql_statement.py#L202-L212
train
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", "." ]
d9031901d5bca22fe0d5925d204e6698df9852e1
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/datalab/utils/commands/_modules.py#L31-L38
train
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", "." ]
d9031901d5bca22fe0d5925d204e6698df9852e1
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/google/datalab/utils/_utils.py#L75-L95
train
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", "." ]
d9031901d5bca22fe0d5925d204e6698df9852e1
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/google/datalab/utils/_utils.py#L98-L108
train
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", "." ]
d9031901d5bca22fe0d5925d204e6698df9852e1
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/google/datalab/utils/_utils.py#L111-L125
train
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", ":", "subprocess", ".", "call", "(", "[", "'gcloud'", ",", "'config'", ",", "'set'", ",", "'project'", ",", "project_id", "]", ")", "except", ":", "config_file", "=", "os", ".", "path", ".", ...
Save project id to config file. Args: project_id: the project_id to save.
[ "Save", "project", "id", "to", "config", "file", "." ]
d9031901d5bca22fe0d5925d204e6698df9852e1
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/google/datalab/utils/_utils.py#L222-L240
train
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", ":", "proc", "=", "subprocess", ".", "Popen", "(", "[", "'gcloud'", ",", "'config'", ",", "'list'", ",", "'--format'", ",", "'value(core.project)'", "]", ",", "stdout", "=", "subprocess", ".", "PIPE", ...
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", "." ]
d9031901d5bca22fe0d5925d204e6698df9852e1
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/google/datalab/utils/_utils.py#L243-L273
train
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", "." ]
d9031901d5bca22fe0d5925d204e6698df9852e1
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/google/datalab/utils/_utils.py#L276-L297
train
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", "." ]
d9031901d5bca22fe0d5925d204e6698df9852e1
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/google/datalab/utils/_utils.py#L300-L314
train
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", "." ]
d9031901d5bca22fe0d5925d204e6698df9852e1
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/datalab/storage/commands/_storage.py#L276-L281
train
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", "." ]
d9031901d5bca22fe0d5925d204e6698df9852e1
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/datalab/storage/commands/_storage.py#L294-L301
train
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", "." ]
d9031901d5bca22fe0d5925d204e6698df9852e1
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/google/datalab/bigquery/_api.py#L354-L375
train
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", ")", ":", "return", "tf", ".", "SparseTensor", "(", "indices", "=", "x", ".", "indices", ",", "values", "=", "tf", ".", "to_float", "(", "tf", ".", "ones_like", "(", "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.
[ "Computes", "bag", "of", "words", "weights" ]
d9031901d5bca22fe0d5925d204e6698df9852e1
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/solutionbox/ml_workbench/tensorflow/trainer/feature_transforms.py#L203-L221
train
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", "." ]
d9031901d5bca22fe0d5925d204e6698df9852e1
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/solutionbox/ml_workbench/tensorflow/trainer/feature_transforms.py#L503-L531
train
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", "." ]
d9031901d5bca22fe0d5925d204e6698df9852e1
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/solutionbox/ml_workbench/tensorflow/trainer/feature_transforms.py#L534-L567
train
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", "." ]
d9031901d5bca22fe0d5925d204e6698df9852e1
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/solutionbox/ml_workbench/tensorflow/trainer/feature_transforms.py#L570-L595
train
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", "." ]
d9031901d5bca22fe0d5925d204e6698df9852e1
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/solutionbox/ml_workbench/tensorflow/trainer/feature_transforms.py#L598-L698
train
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", "." ]
d9031901d5bca22fe0d5925d204e6698df9852e1
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/solutionbox/ml_workbench/tensorflow/trainer/feature_transforms.py#L701-L806
train
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", "." ]
d9031901d5bca22fe0d5925d204e6698df9852e1
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/solutionbox/ml_workbench/tensorflow/trainer/feature_transforms.py#L809-L826
train
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", "." ]
d9031901d5bca22fe0d5925d204e6698df9852e1
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/solutionbox/ml_workbench/tensorflow/trainer/feature_transforms.py#L837-L857
train
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", "." ]
d9031901d5bca22fe0d5925d204e6698df9852e1
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/google/datalab/bigquery/_external_data_source.py#L70-L84
train
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", ")", ":", "def", "_request", "(", "self", ",", "uri", ",", "method", "=", "\"GET\"", ",", "body", "=", "None", ",", "headers", "=", "None", ",", "redirections", "=", "_httplib2", ".", "DEFAULT_MAX_REDIRECTS", ...
Called when the extension is loaded. Args: shell - (NotebookWebApplication): handle to the Notebook interactive shell instance.
[ "Called", "when", "the", "extension", "is", "loaded", "." ]
d9031901d5bca22fe0d5925d204e6698df9852e1
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/google/datalab/kernel/__init__.py#L44-L122
train
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", "." ]
d9031901d5bca22fe0d5925d204e6698df9852e1
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/datalab/data/_sql_module.py#L33-L62
train
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", "." ]
d9031901d5bca22fe0d5925d204e6698df9852e1
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/datalab/data/_sql_module.py#L77-L107
train
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", "." ]
d9031901d5bca22fe0d5925d204e6698df9852e1
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/datalab/data/_sql_module.py#L110-L124
train
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", ")", ":", "m", "=", "re", ".", "match", "(", "_ABS_DATASET_NAME_PATTERN", ...
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", "." ]
d9031901d5bca22fe0d5925d204e6698df9852e1
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/google/datalab/bigquery/_utils.py#L58-L102
train
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", "." ]
d9031901d5bca22fe0d5925d204e6698df9852e1
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/google/datalab/bigquery/_utils.py#L105-L166
train
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", "." ]
d9031901d5bca22fe0d5925d204e6698df9852e1
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/google/datalab/contrib/mlworkbench/_prediction_explainer.py#L56-L71
train
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", "." ]
d9031901d5bca22fe0d5925d204e6698df9852e1
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/google/datalab/contrib/mlworkbench/_prediction_explainer.py#L73-L90
train
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", "." ]
d9031901d5bca22fe0d5925d204e6698df9852e1
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/google/datalab/contrib/mlworkbench/_prediction_explainer.py#L92-L101
train
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", "(", ")", "for", "col", "in", "list", "(", "df", ".", "columns", ")", ":", "if", "col", "not", "in", "(", "self", ".", ...
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", "." ]
d9031901d5bca22fe0d5925d204e6698df9852e1
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/google/datalab/contrib/mlworkbench/_prediction_explainer.py#L103-L128
train