repo
stringlengths
7
55
path
stringlengths
4
127
func_name
stringlengths
1
88
original_string
stringlengths
75
19.8k
language
stringclasses
1 value
code
stringlengths
75
19.8k
code_tokens
listlengths
20
707
docstring
stringlengths
3
17.3k
docstring_tokens
listlengths
3
222
sha
stringlengths
40
40
url
stringlengths
87
242
partition
stringclasses
1 value
idx
int64
0
252k
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 Monitoring-related operations. Use "%monitoring ' '<command> -h" for help on a specific command.')) list_parser = parser.subcommand( 'list', 'List the metrics or resource types in a monitored project.') list_metric_parser = list_parser.subcommand( 'metrics', 'List the metrics that are available through the Monitoring API.') list_metric_parser.add_argument( '-t', '--type', help='The type of metric(s) to list; can include wildchars.') list_metric_parser.add_argument( '-p', '--project', help='The project on which to execute the request.') list_metric_parser.set_defaults(func=_list_metric_descriptors) list_resource_parser = list_parser.subcommand( 'resource_types', ('List the monitored resource types that are available through the ' 'Monitoring API.')) list_resource_parser.add_argument( '-p', '--project', help='The project on which to execute the request.') list_resource_parser.add_argument( '-t', '--type', help='The resource type(s) to list; can include wildchars.') list_resource_parser.set_defaults(func=_list_resource_descriptors) list_group_parser = list_parser.subcommand( 'groups', ('List the Stackdriver groups in this project.')) list_group_parser.add_argument( '-p', '--project', help='The project on which to execute the request.') list_group_parser.add_argument( '-n', '--name', help='The name of the group(s) to list; can include wildchars.') list_group_parser.set_defaults(func=_list_groups) return datalab.utils.commands.handle_magic_line(line, cell, parser)
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 Monitoring-related operations. Use "%monitoring ' '<command> -h" for help on a specific command.')) list_parser = parser.subcommand( 'list', 'List the metrics or resource types in a monitored project.') list_metric_parser = list_parser.subcommand( 'metrics', 'List the metrics that are available through the Monitoring API.') list_metric_parser.add_argument( '-t', '--type', help='The type of metric(s) to list; can include wildchars.') list_metric_parser.add_argument( '-p', '--project', help='The project on which to execute the request.') list_metric_parser.set_defaults(func=_list_metric_descriptors) list_resource_parser = list_parser.subcommand( 'resource_types', ('List the monitored resource types that are available through the ' 'Monitoring API.')) list_resource_parser.add_argument( '-p', '--project', help='The project on which to execute the request.') list_resource_parser.add_argument( '-t', '--type', help='The resource type(s) to list; can include wildchars.') list_resource_parser.set_defaults(func=_list_resource_descriptors) list_group_parser = list_parser.subcommand( 'groups', ('List the Stackdriver groups in this project.')) list_group_parser.add_argument( '-p', '--project', help='The project on which to execute the request.') list_group_parser.add_argument( '-n', '--name', help='The name of the group(s) to list; can include wildchars.') list_group_parser.set_defaults(func=_list_groups) return datalab.utils.commands.handle_magic_line(line, cell, parser)
[ "def", "monitoring", "(", "line", ",", "cell", "=", "None", ")", ":", "parser", "=", "datalab", ".", "utils", ".", "commands", ".", "CommandParser", "(", "prog", "=", "'monitoring'", ",", "description", "=", "(", "'Execute various Monitoring-related operations. Use \"%monitoring '", "'<command> -h\" for help on a specific command.'", ")", ")", "list_parser", "=", "parser", ".", "subcommand", "(", "'list'", ",", "'List the metrics or resource types in a monitored project.'", ")", "list_metric_parser", "=", "list_parser", ".", "subcommand", "(", "'metrics'", ",", "'List the metrics that are available through the Monitoring API.'", ")", "list_metric_parser", ".", "add_argument", "(", "'-t'", ",", "'--type'", ",", "help", "=", "'The type of metric(s) to list; can include wildchars.'", ")", "list_metric_parser", ".", "add_argument", "(", "'-p'", ",", "'--project'", ",", "help", "=", "'The project on which to execute the request.'", ")", "list_metric_parser", ".", "set_defaults", "(", "func", "=", "_list_metric_descriptors", ")", "list_resource_parser", "=", "list_parser", ".", "subcommand", "(", "'resource_types'", ",", "(", "'List the monitored resource types that are available through the '", "'Monitoring API.'", ")", ")", "list_resource_parser", ".", "add_argument", "(", "'-p'", ",", "'--project'", ",", "help", "=", "'The project on which to execute the request.'", ")", "list_resource_parser", ".", "add_argument", "(", "'-t'", ",", "'--type'", ",", "help", "=", "'The resource type(s) to list; can include wildchars.'", ")", "list_resource_parser", ".", "set_defaults", "(", "func", "=", "_list_resource_descriptors", ")", "list_group_parser", "=", "list_parser", ".", "subcommand", "(", "'groups'", ",", "(", "'List the Stackdriver groups in this project.'", ")", ")", "list_group_parser", ".", "add_argument", "(", "'-p'", ",", "'--project'", ",", "help", "=", "'The project on which to execute the request.'", ")", "list_group_parser", ".", "add_argument", "(", "'-n'", ",", "'--name'", ",", "help", "=", "'The name of the group(s) to list; can include wildchars.'", ")", "list_group_parser", ".", "set_defaults", "(", "func", "=", "_list_groups", ")", "return", "datalab", ".", "utils", ".", "commands", ".", "handle_magic_line", "(", "line", ",", "cell", ",", "parser", ")" ]
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
237,700
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", ".", "HTML", "(", "datalab", ".", "utils", ".", "commands", ".", "HtmlBuilder", ".", "render_table", "(", "data", ",", "fields", ")", ")" ]
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
237,701
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] else: raise Exception('invalid job %s' % job_name) if job is not None: error = '' if job.fatal_error is None else str(job.fatal_error) data = {'exists': True, 'done': job.is_complete, 'error': error} else: data = {'exists': False} except Exception as e: google.datalab.utils.print_exception_with_last_stack(e) data = {'done': True, 'error': str(e)} return IPython.core.display.JSON(data)
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] else: raise Exception('invalid job %s' % job_name) if job is not None: error = '' if job.fatal_error is None else str(job.fatal_error) data = {'exists': True, 'done': job.is_complete, 'error': error} else: data = {'exists': False} except Exception as e: google.datalab.utils.print_exception_with_last_stack(e) data = {'done': True, 'error': str(e)} return IPython.core.display.JSON(data)
[ "def", "_get_job_status", "(", "line", ")", ":", "try", ":", "args", "=", "line", ".", "strip", "(", ")", ".", "split", "(", ")", "job_name", "=", "args", "[", "0", "]", "job", "=", "None", "if", "job_name", "in", "_local_jobs", ":", "job", "=", "_local_jobs", "[", "job_name", "]", "else", ":", "raise", "Exception", "(", "'invalid job %s'", "%", "job_name", ")", "if", "job", "is", "not", "None", ":", "error", "=", "''", "if", "job", ".", "fatal_error", "is", "None", "else", "str", "(", "job", ".", "fatal_error", ")", "data", "=", "{", "'exists'", ":", "True", ",", "'done'", ":", "job", ".", "is_complete", ",", "'error'", ":", "error", "}", "else", ":", "data", "=", "{", "'exists'", ":", "False", "}", "except", "Exception", "as", "e", ":", "google", ".", "datalab", ".", "utils", ".", "print_exception_with_last_stack", "(", "e", ")", "data", "=", "{", "'done'", ":", "True", ",", "'error'", ":", "str", "(", "e", ")", "}", "return", "IPython", ".", "core", ".", "display", ".", "JSON", "(", "data", ")" ]
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
237,702
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
237,703
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. """ if self.exists(): try: self._api.objects_delete(self._bucket, self._key) except Exception as e: raise e if wait_for_deletion: for _ in range(_MAX_POLL_ATTEMPTS): objects = Objects(self._bucket, prefix=self.key, delimiter='/', context=self._context) if any(o.key == self.key for o in objects): time.sleep(_POLLING_SLEEP) continue break else: logging.error('Failed to see object deletion after %d attempts.', _MAX_POLL_ATTEMPTS)
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. """ if self.exists(): try: self._api.objects_delete(self._bucket, self._key) except Exception as e: raise e if wait_for_deletion: for _ in range(_MAX_POLL_ATTEMPTS): objects = Objects(self._bucket, prefix=self.key, delimiter='/', context=self._context) if any(o.key == self.key for o in objects): time.sleep(_POLLING_SLEEP) continue break else: logging.error('Failed to see object deletion after %d attempts.', _MAX_POLL_ATTEMPTS)
[ "def", "delete", "(", "self", ",", "wait_for_deletion", "=", "True", ")", ":", "if", "self", ".", "exists", "(", ")", ":", "try", ":", "self", ".", "_api", ".", "objects_delete", "(", "self", ".", "_bucket", ",", "self", ".", "_key", ")", "except", "Exception", "as", "e", ":", "raise", "e", "if", "wait_for_deletion", ":", "for", "_", "in", "range", "(", "_MAX_POLL_ATTEMPTS", ")", ":", "objects", "=", "Objects", "(", "self", ".", "_bucket", ",", "prefix", "=", "self", ".", "key", ",", "delimiter", "=", "'/'", ",", "context", "=", "self", ".", "_context", ")", "if", "any", "(", "o", ".", "key", "==", "self", ".", "key", "for", "o", "in", "objects", ")", ":", "time", ".", "sleep", "(", "_POLLING_SLEEP", ")", "continue", "break", "else", ":", "logging", ".", "error", "(", "'Failed to see object deletion after %d attempts.'", ",", "_MAX_POLL_ATTEMPTS", ")" ]
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
237,704
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(self._bucket, self._key) except Exception as e: raise e return ObjectMetadata(self._info) if self._info else None
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(self._bucket, self._key) except Exception as e: raise e return ObjectMetadata(self._info) if self._info else None
[ "def", "metadata", "(", "self", ")", ":", "if", "self", ".", "_info", "is", "None", ":", "try", ":", "self", ".", "_info", "=", "self", ".", "_api", ".", "objects_get", "(", "self", ".", "_bucket", ",", "self", ".", "_key", ")", "except", "Exception", "as", "e", ":", "raise", "e", "return", "ObjectMetadata", "(", "self", ".", "_info", ")", "if", "self", ".", "_info", "else", "None" ]
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
237,705
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: Exception if there was an error requesting the object's content. """ try: return self._api.object_download(self._bucket, self._key, start_offset=start_offset, byte_count=byte_count) except Exception as e: raise e
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: Exception if there was an error requesting the object's content. """ try: return self._api.object_download(self._bucket, self._key, start_offset=start_offset, byte_count=byte_count) except Exception as e: raise e
[ "def", "read_stream", "(", "self", ",", "start_offset", "=", "0", ",", "byte_count", "=", "None", ")", ":", "try", ":", "return", "self", ".", "_api", ".", "object_download", "(", "self", ".", "_bucket", ",", "self", ".", "_key", ",", "start_offset", "=", "start_offset", ",", "byte_count", "=", "byte_count", ")", "except", "Exception", "as", "e", ":", "raise", "e" ]
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 content.
[ "Reads", "the", "content", "of", "this", "object", "as", "text", "." ]
d9031901d5bca22fe0d5925d204e6698df9852e1
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/google/datalab/storage/_object.py#L190-L205
train
237,706
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 there was an error requesting the object's content. """ if max_lines is None: return self.read_stream().split('\n') max_to_read = self.metadata.size bytes_to_read = min(100 * max_lines, self.metadata.size) while True: content = self.read_stream(byte_count=bytes_to_read) lines = content.split('\n') if len(lines) > max_lines or bytes_to_read >= max_to_read: break # try 10 times more bytes or max bytes_to_read = min(bytes_to_read * 10, max_to_read) # remove the partial line at last del lines[-1] return lines[0:max_lines]
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 there was an error requesting the object's content. """ if max_lines is None: return self.read_stream().split('\n') max_to_read = self.metadata.size bytes_to_read = min(100 * max_lines, self.metadata.size) while True: content = self.read_stream(byte_count=bytes_to_read) lines = content.split('\n') if len(lines) > max_lines or bytes_to_read >= max_to_read: break # try 10 times more bytes or max bytes_to_read = min(bytes_to_read * 10, max_to_read) # remove the partial line at last del lines[-1] return lines[0:max_lines]
[ "def", "read_lines", "(", "self", ",", "max_lines", "=", "None", ")", ":", "if", "max_lines", "is", "None", ":", "return", "self", ".", "read_stream", "(", ")", ".", "split", "(", "'\\n'", ")", "max_to_read", "=", "self", ".", "metadata", ".", "size", "bytes_to_read", "=", "min", "(", "100", "*", "max_lines", ",", "self", ".", "metadata", ".", "size", ")", "while", "True", ":", "content", "=", "self", ".", "read_stream", "(", "byte_count", "=", "bytes_to_read", ")", "lines", "=", "content", ".", "split", "(", "'\\n'", ")", "if", "len", "(", "lines", ")", ">", "max_lines", "or", "bytes_to_read", ">=", "max_to_read", ":", "break", "# try 10 times more bytes or max", "bytes_to_read", "=", "min", "(", "bytes_to_read", "*", "10", ",", "max_to_read", ")", "# remove the partial line at last", "del", "lines", "[", "-", "1", "]", "return", "lines", "[", "0", ":", "max_lines", "]" ]
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 content.
[ "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
237,707
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 source. strategy: can be "LOCAL" or "BIGQUERY". If local, the sampling happens in local memory, and number of resulting rows matches count. If BigQuery, sampling is done with BigQuery in cloud, and the number of resulting rows will be approximated to count. target: The target file path, can be GCS or local path. Raises: Exception if strategy is "BIGQUERY" but source is not a GCS path. """ # TODO(qimingj) Add unit test # Read data from source into DataFrame. if sys.version_info.major > 2: xrange = range # for python 3 compatibility if strategy == 'BIGQUERY': import datalab.bigquery as bq if not self.path.startswith('gs://'): raise Exception('Cannot use BIGQUERY if data is not in GCS') federated_table = self._create_federated_table(skip_header_rows) row_count = self._get_gcs_csv_row_count(federated_table) query = bq.Query('SELECT * from data', data_sources={'data': federated_table}) sampling = bq.Sampling.random(count * 100 / float(row_count)) sample = query.sample(sampling=sampling) df = sample.to_dataframe() elif strategy == 'LOCAL': local_file = self.path if self.path.startswith('gs://'): local_file = tempfile.mktemp() datalab.utils.gcs_copy_file(self.path, local_file) with open(local_file) as f: row_count = sum(1 for line in f) start_row = 1 if skip_header_rows is True else 0 skip_count = row_count - count - 1 if skip_header_rows is True else row_count - count skip = sorted(random.sample(xrange(start_row, row_count), skip_count)) header_row = 0 if skip_header_rows is True else None df = pd.read_csv(local_file, skiprows=skip, header=header_row, delimiter=self._delimiter) if self.path.startswith('gs://'): os.remove(local_file) else: raise Exception('strategy must be BIGQUERY or LOCAL') # Write to target. if target.startswith('gs://'): with tempfile.NamedTemporaryFile() as f: df.to_csv(f, header=False, index=False) f.flush() datalab.utils.gcs_copy_file(f.name, target) else: with open(target, 'w') as f: df.to_csv(f, header=False, index=False, sep=str(self._delimiter))
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 source. strategy: can be "LOCAL" or "BIGQUERY". If local, the sampling happens in local memory, and number of resulting rows matches count. If BigQuery, sampling is done with BigQuery in cloud, and the number of resulting rows will be approximated to count. target: The target file path, can be GCS or local path. Raises: Exception if strategy is "BIGQUERY" but source is not a GCS path. """ # TODO(qimingj) Add unit test # Read data from source into DataFrame. if sys.version_info.major > 2: xrange = range # for python 3 compatibility if strategy == 'BIGQUERY': import datalab.bigquery as bq if not self.path.startswith('gs://'): raise Exception('Cannot use BIGQUERY if data is not in GCS') federated_table = self._create_federated_table(skip_header_rows) row_count = self._get_gcs_csv_row_count(federated_table) query = bq.Query('SELECT * from data', data_sources={'data': federated_table}) sampling = bq.Sampling.random(count * 100 / float(row_count)) sample = query.sample(sampling=sampling) df = sample.to_dataframe() elif strategy == 'LOCAL': local_file = self.path if self.path.startswith('gs://'): local_file = tempfile.mktemp() datalab.utils.gcs_copy_file(self.path, local_file) with open(local_file) as f: row_count = sum(1 for line in f) start_row = 1 if skip_header_rows is True else 0 skip_count = row_count - count - 1 if skip_header_rows is True else row_count - count skip = sorted(random.sample(xrange(start_row, row_count), skip_count)) header_row = 0 if skip_header_rows is True else None df = pd.read_csv(local_file, skiprows=skip, header=header_row, delimiter=self._delimiter) if self.path.startswith('gs://'): os.remove(local_file) else: raise Exception('strategy must be BIGQUERY or LOCAL') # Write to target. if target.startswith('gs://'): with tempfile.NamedTemporaryFile() as f: df.to_csv(f, header=False, index=False) f.flush() datalab.utils.gcs_copy_file(f.name, target) else: with open(target, 'w') as f: df.to_csv(f, header=False, index=False, sep=str(self._delimiter))
[ "def", "sample_to", "(", "self", ",", "count", ",", "skip_header_rows", ",", "strategy", ",", "target", ")", ":", "# TODO(qimingj) Add unit test", "# Read data from source into DataFrame.", "if", "sys", ".", "version_info", ".", "major", ">", "2", ":", "xrange", "=", "range", "# for python 3 compatibility", "if", "strategy", "==", "'BIGQUERY'", ":", "import", "datalab", ".", "bigquery", "as", "bq", "if", "not", "self", ".", "path", ".", "startswith", "(", "'gs://'", ")", ":", "raise", "Exception", "(", "'Cannot use BIGQUERY if data is not in GCS'", ")", "federated_table", "=", "self", ".", "_create_federated_table", "(", "skip_header_rows", ")", "row_count", "=", "self", ".", "_get_gcs_csv_row_count", "(", "federated_table", ")", "query", "=", "bq", ".", "Query", "(", "'SELECT * from data'", ",", "data_sources", "=", "{", "'data'", ":", "federated_table", "}", ")", "sampling", "=", "bq", ".", "Sampling", ".", "random", "(", "count", "*", "100", "/", "float", "(", "row_count", ")", ")", "sample", "=", "query", ".", "sample", "(", "sampling", "=", "sampling", ")", "df", "=", "sample", ".", "to_dataframe", "(", ")", "elif", "strategy", "==", "'LOCAL'", ":", "local_file", "=", "self", ".", "path", "if", "self", ".", "path", ".", "startswith", "(", "'gs://'", ")", ":", "local_file", "=", "tempfile", ".", "mktemp", "(", ")", "datalab", ".", "utils", ".", "gcs_copy_file", "(", "self", ".", "path", ",", "local_file", ")", "with", "open", "(", "local_file", ")", "as", "f", ":", "row_count", "=", "sum", "(", "1", "for", "line", "in", "f", ")", "start_row", "=", "1", "if", "skip_header_rows", "is", "True", "else", "0", "skip_count", "=", "row_count", "-", "count", "-", "1", "if", "skip_header_rows", "is", "True", "else", "row_count", "-", "count", "skip", "=", "sorted", "(", "random", ".", "sample", "(", "xrange", "(", "start_row", ",", "row_count", ")", ",", "skip_count", ")", ")", "header_row", "=", "0", "if", "skip_header_rows", "is", "True", "else", "None", "df", "=", "pd", ".", "read_csv", "(", "local_file", ",", "skiprows", "=", "skip", ",", "header", "=", "header_row", ",", "delimiter", "=", "self", ".", "_delimiter", ")", "if", "self", ".", "path", ".", "startswith", "(", "'gs://'", ")", ":", "os", ".", "remove", "(", "local_file", ")", "else", ":", "raise", "Exception", "(", "'strategy must be BIGQUERY or LOCAL'", ")", "# Write to target.", "if", "target", ".", "startswith", "(", "'gs://'", ")", ":", "with", "tempfile", ".", "NamedTemporaryFile", "(", ")", "as", "f", ":", "df", ".", "to_csv", "(", "f", ",", "header", "=", "False", ",", "index", "=", "False", ")", "f", ".", "flush", "(", ")", "datalab", ".", "utils", ".", "gcs_copy_file", "(", "f", ".", "name", ",", "target", ")", "else", ":", "with", "open", "(", "target", ",", "'w'", ")", "as", "f", ":", "df", ".", "to_csv", "(", "f", ",", "header", "=", "False", ",", "index", "=", "False", ",", "sep", "=", "str", "(", "self", ".", "_delimiter", ")", ")" ]
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 sampling happens in local memory, and number of resulting rows matches count. If BigQuery, sampling is done with BigQuery in cloud, and the number of resulting rows will be approximated to count. target: The target file path, can be GCS or local path. Raises: Exception if strategy is "BIGQUERY" but source is not a GCS path.
[ "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
237,708
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.FeatureLists from the example. entries: A dictionary of all features parsed thus far and arrays of their values. This is mutated by the function. index: The index of the example to parse from a list of examples. Raises: TypeError: Raises an exception when a feature has inconsistent types across examples. """ features_seen = set() for feature_list, is_feature in zip( [example_features, example_feature_lists], [True, False]): sequence_length = None for feature_name in feature_list: # If this feature has not been seen in previous examples, then # initialize its entry into the entries dictionary. if feature_name not in entries: entries[feature_name] = { 'vals': [], 'counts': [], 'feat_lens': [], 'missing': index } feature_entry = entries[feature_name] feature = feature_list[feature_name] value_type = None value_list = [] if is_feature: # If parsing a tf.Feature, extract the type and values simply. if feature.HasField('float_list'): value_list = feature.float_list.value value_type = self.fs_proto.FLOAT elif feature.HasField('bytes_list'): value_list = feature.bytes_list.value value_type = self.fs_proto.STRING elif feature.HasField('int64_list'): value_list = feature.int64_list.value value_type = self.fs_proto.INT else: # If parsing a tf.FeatureList, get the type and values by iterating # over all Features in the FeatureList. sequence_length = len(feature.feature) if sequence_length != 0 and feature.feature[0].HasField('float_list'): for feat in feature.feature: for value in feat.float_list.value: value_list.append(value) value_type = self.fs_proto.FLOAT elif sequence_length != 0 and feature.feature[0].HasField( 'bytes_list'): for feat in feature.feature: for value in feat.bytes_list.value: value_list.append(value) value_type = self.fs_proto.STRING elif sequence_length != 0 and feature.feature[0].HasField( 'int64_list'): for feat in feature.feature: for value in feat.int64_list.value: value_list.append(value) value_type = self.fs_proto.INT if value_type is not None: if 'type' not in feature_entry: feature_entry['type'] = value_type elif feature_entry['type'] != value_type: raise TypeError('type mismatch for feature ' + feature_name) feature_entry['counts'].append(len(value_list)) feature_entry['vals'].extend(value_list) if sequence_length is not None: feature_entry['feat_lens'].append(sequence_length) if value_list: features_seen.add(feature_name) # For all previously-seen features not found in this example, update the # feature's missing value. for f in entries: fv = entries[f] if f not in features_seen: fv['missing'] += 1
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.FeatureLists from the example. entries: A dictionary of all features parsed thus far and arrays of their values. This is mutated by the function. index: The index of the example to parse from a list of examples. Raises: TypeError: Raises an exception when a feature has inconsistent types across examples. """ features_seen = set() for feature_list, is_feature in zip( [example_features, example_feature_lists], [True, False]): sequence_length = None for feature_name in feature_list: # If this feature has not been seen in previous examples, then # initialize its entry into the entries dictionary. if feature_name not in entries: entries[feature_name] = { 'vals': [], 'counts': [], 'feat_lens': [], 'missing': index } feature_entry = entries[feature_name] feature = feature_list[feature_name] value_type = None value_list = [] if is_feature: # If parsing a tf.Feature, extract the type and values simply. if feature.HasField('float_list'): value_list = feature.float_list.value value_type = self.fs_proto.FLOAT elif feature.HasField('bytes_list'): value_list = feature.bytes_list.value value_type = self.fs_proto.STRING elif feature.HasField('int64_list'): value_list = feature.int64_list.value value_type = self.fs_proto.INT else: # If parsing a tf.FeatureList, get the type and values by iterating # over all Features in the FeatureList. sequence_length = len(feature.feature) if sequence_length != 0 and feature.feature[0].HasField('float_list'): for feat in feature.feature: for value in feat.float_list.value: value_list.append(value) value_type = self.fs_proto.FLOAT elif sequence_length != 0 and feature.feature[0].HasField( 'bytes_list'): for feat in feature.feature: for value in feat.bytes_list.value: value_list.append(value) value_type = self.fs_proto.STRING elif sequence_length != 0 and feature.feature[0].HasField( 'int64_list'): for feat in feature.feature: for value in feat.int64_list.value: value_list.append(value) value_type = self.fs_proto.INT if value_type is not None: if 'type' not in feature_entry: feature_entry['type'] = value_type elif feature_entry['type'] != value_type: raise TypeError('type mismatch for feature ' + feature_name) feature_entry['counts'].append(len(value_list)) feature_entry['vals'].extend(value_list) if sequence_length is not None: feature_entry['feat_lens'].append(sequence_length) if value_list: features_seen.add(feature_name) # For all previously-seen features not found in this example, update the # feature's missing value. for f in entries: fv = entries[f] if f not in features_seen: fv['missing'] += 1
[ "def", "_ParseExample", "(", "self", ",", "example_features", ",", "example_feature_lists", ",", "entries", ",", "index", ")", ":", "features_seen", "=", "set", "(", ")", "for", "feature_list", ",", "is_feature", "in", "zip", "(", "[", "example_features", ",", "example_feature_lists", "]", ",", "[", "True", ",", "False", "]", ")", ":", "sequence_length", "=", "None", "for", "feature_name", "in", "feature_list", ":", "# If this feature has not been seen in previous examples, then", "# initialize its entry into the entries dictionary.", "if", "feature_name", "not", "in", "entries", ":", "entries", "[", "feature_name", "]", "=", "{", "'vals'", ":", "[", "]", ",", "'counts'", ":", "[", "]", ",", "'feat_lens'", ":", "[", "]", ",", "'missing'", ":", "index", "}", "feature_entry", "=", "entries", "[", "feature_name", "]", "feature", "=", "feature_list", "[", "feature_name", "]", "value_type", "=", "None", "value_list", "=", "[", "]", "if", "is_feature", ":", "# If parsing a tf.Feature, extract the type and values simply.", "if", "feature", ".", "HasField", "(", "'float_list'", ")", ":", "value_list", "=", "feature", ".", "float_list", ".", "value", "value_type", "=", "self", ".", "fs_proto", ".", "FLOAT", "elif", "feature", ".", "HasField", "(", "'bytes_list'", ")", ":", "value_list", "=", "feature", ".", "bytes_list", ".", "value", "value_type", "=", "self", ".", "fs_proto", ".", "STRING", "elif", "feature", ".", "HasField", "(", "'int64_list'", ")", ":", "value_list", "=", "feature", ".", "int64_list", ".", "value", "value_type", "=", "self", ".", "fs_proto", ".", "INT", "else", ":", "# If parsing a tf.FeatureList, get the type and values by iterating", "# over all Features in the FeatureList.", "sequence_length", "=", "len", "(", "feature", ".", "feature", ")", "if", "sequence_length", "!=", "0", "and", "feature", ".", "feature", "[", "0", "]", ".", "HasField", "(", "'float_list'", ")", ":", "for", "feat", "in", "feature", ".", "feature", ":", "for", "value", "in", "feat", ".", "float_list", ".", "value", ":", "value_list", ".", "append", "(", "value", ")", "value_type", "=", "self", ".", "fs_proto", ".", "FLOAT", "elif", "sequence_length", "!=", "0", "and", "feature", ".", "feature", "[", "0", "]", ".", "HasField", "(", "'bytes_list'", ")", ":", "for", "feat", "in", "feature", ".", "feature", ":", "for", "value", "in", "feat", ".", "bytes_list", ".", "value", ":", "value_list", ".", "append", "(", "value", ")", "value_type", "=", "self", ".", "fs_proto", ".", "STRING", "elif", "sequence_length", "!=", "0", "and", "feature", ".", "feature", "[", "0", "]", ".", "HasField", "(", "'int64_list'", ")", ":", "for", "feat", "in", "feature", ".", "feature", ":", "for", "value", "in", "feat", ".", "int64_list", ".", "value", ":", "value_list", ".", "append", "(", "value", ")", "value_type", "=", "self", ".", "fs_proto", ".", "INT", "if", "value_type", "is", "not", "None", ":", "if", "'type'", "not", "in", "feature_entry", ":", "feature_entry", "[", "'type'", "]", "=", "value_type", "elif", "feature_entry", "[", "'type'", "]", "!=", "value_type", ":", "raise", "TypeError", "(", "'type mismatch for feature '", "+", "feature_name", ")", "feature_entry", "[", "'counts'", "]", ".", "append", "(", "len", "(", "value_list", ")", ")", "feature_entry", "[", "'vals'", "]", ".", "extend", "(", "value_list", ")", "if", "sequence_length", "is", "not", "None", ":", "feature_entry", "[", "'feat_lens'", "]", ".", "append", "(", "sequence_length", ")", "if", "value_list", ":", "features_seen", ".", "add", "(", "feature_name", ")", "# For all previously-seen features not found in this example, update the", "# feature's missing value.", "for", "f", "in", "entries", ":", "fv", "=", "entries", "[", "f", "]", "if", "f", "not", "in", "features_seen", ":", "fv", "[", "'missing'", "]", "+=", "1" ]
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 of their values. This is mutated by the function. index: The index of the example to parse from a list of examples. Raises: TypeError: Raises an exception when a feature has inconsistent types across examples.
[ "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
237,709
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 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_sequence: True if the input data from 'iterator_from_file' are tf.SequenceExamples, False if tf.Examples. Defaults to false. Returns: A tuple with two elements: - A dictionary of all features parsed thus far and arrays of their values. - The number of examples parsed. """ entries = {} index = 0 for filepath in paths: reader = iterator_from_file(filepath) for record in reader: if is_sequence: sequence_example = tf.train.SequenceExample.FromString(record) self._ParseExample(sequence_example.context.feature, sequence_example.feature_lists.feature_list, entries, index) else: self._ParseExample( tf.train.Example.FromString(record).features.feature, [], entries, index) index += 1 if index == max_entries: return entries, index return entries, index
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 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_sequence: True if the input data from 'iterator_from_file' are tf.SequenceExamples, False if tf.Examples. Defaults to false. Returns: A tuple with two elements: - A dictionary of all features parsed thus far and arrays of their values. - The number of examples parsed. """ entries = {} index = 0 for filepath in paths: reader = iterator_from_file(filepath) for record in reader: if is_sequence: sequence_example = tf.train.SequenceExample.FromString(record) self._ParseExample(sequence_example.context.feature, sequence_example.feature_lists.feature_list, entries, index) else: self._ParseExample( tf.train.Example.FromString(record).features.feature, [], entries, index) index += 1 if index == max_entries: return entries, index return entries, index
[ "def", "_GetEntries", "(", "self", ",", "paths", ",", "max_entries", ",", "iterator_from_file", ",", "is_sequence", "=", "False", ")", ":", "entries", "=", "{", "}", "index", "=", "0", "for", "filepath", "in", "paths", ":", "reader", "=", "iterator_from_file", "(", "filepath", ")", "for", "record", "in", "reader", ":", "if", "is_sequence", ":", "sequence_example", "=", "tf", ".", "train", ".", "SequenceExample", ".", "FromString", "(", "record", ")", "self", ".", "_ParseExample", "(", "sequence_example", ".", "context", ".", "feature", ",", "sequence_example", ".", "feature_lists", ".", "feature_list", ",", "entries", ",", "index", ")", "else", ":", "self", ".", "_ParseExample", "(", "tf", ".", "train", ".", "Example", ".", "FromString", "(", "record", ")", ".", "features", ".", "feature", ",", "[", "]", ",", "entries", ",", "index", ")", "index", "+=", "1", "if", "index", "==", "max_entries", ":", "return", "entries", ",", "index", "return", "entries", ",", "index" ]
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_sequence: True if the input data from 'iterator_from_file' are tf.SequenceExamples, False if tf.Examples. Defaults to false. Returns: A tuple with two elements: - A dictionary of all features parsed thus far and arrays of their values. - The number of examples parsed.
[ "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
237,710
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 the input data from 'path' are tf.SequenceExamples, False if tf.Examples. Defaults to false. iterator_options: Options to pass to the iterator that reads the examples. Defaults to None. Returns: A tuple with two elements: - A dictionary of all features parsed thus far and arrays of their values. - The number of examples parsed. """ return self._GetEntries([path], max_entries, partial( tf.python_io.tf_record_iterator, options=iterator_options), is_sequence)
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 the input data from 'path' are tf.SequenceExamples, False if tf.Examples. Defaults to false. iterator_options: Options to pass to the iterator that reads the examples. Defaults to None. Returns: A tuple with two elements: - A dictionary of all features parsed thus far and arrays of their values. - The number of examples parsed. """ return self._GetEntries([path], max_entries, partial( tf.python_io.tf_record_iterator, options=iterator_options), is_sequence)
[ "def", "_GetTfRecordEntries", "(", "self", ",", "path", ",", "max_entries", ",", "is_sequence", ",", "iterator_options", ")", ":", "return", "self", ".", "_GetEntries", "(", "[", "path", "]", ",", "max_entries", ",", "partial", "(", "tf", ".", "python_io", ".", "tf_record_iterator", ",", "options", "=", "iterator_options", ")", ",", "is_sequence", ")" ]
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. iterator_options: Options to pass to the iterator that reads the examples. Defaults to None. Returns: A tuple with two elements: - A dictionary of all features parsed thus far and arrays of their values. - The number of examples parsed.
[ "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
237,711
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 performing the operation. """ args = {'project': project_id if project_id else self._project_id} data = {'name': bucket} url = Api._ENDPOINT + (Api._BUCKET_PATH % '') return datalab.utils.Http.request(url, args=args, data=data, credentials=self._credentials)
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 performing the operation. """ args = {'project': project_id if project_id else self._project_id} data = {'name': bucket} url = Api._ENDPOINT + (Api._BUCKET_PATH % '') return datalab.utils.Http.request(url, args=args, data=data, credentials=self._credentials)
[ "def", "buckets_insert", "(", "self", ",", "bucket", ",", "project_id", "=", "None", ")", ":", "args", "=", "{", "'project'", ":", "project_id", "if", "project_id", "else", "self", ".", "_project_id", "}", "data", "=", "{", "'name'", ":", "bucket", "}", "url", "=", "Api", ".", "_ENDPOINT", "+", "(", "Api", ".", "_BUCKET_PATH", "%", "''", ")", "return", "datalab", ".", "utils", ".", "Http", ".", "request", "(", "url", ",", "args", "=", "args", ",", "data", "=", "data", ",", "credentials", "=", "self", ".", "_credentials", ")" ]
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
237,712
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._escape_key(key))) datalab.utils.Http.request(url, method='DELETE', credentials=self._credentials, raw_response=True)
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._escape_key(key))) datalab.utils.Http.request(url, method='DELETE', credentials=self._credentials, raw_response=True)
[ "def", "objects_delete", "(", "self", ",", "bucket", ",", "key", ")", ":", "url", "=", "Api", ".", "_ENDPOINT", "+", "(", "Api", ".", "_OBJECT_PATH", "%", "(", "bucket", ",", "Api", ".", "_escape_key", "(", "key", ")", ")", ")", "datalab", ".", "utils", ".", "Http", ".", "request", "(", "url", ",", "method", "=", "'DELETE'", ",", "credentials", "=", "self", ".", "_credentials", ",", "raw_response", "=", "True", ")" ]
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
237,713
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 MetricDescriptor objects that match the filters. """ if self._descriptors is None: self._descriptors = self._client.list_metric_descriptors( filter_string=self._filter_string, type_prefix=self._type_prefix) return [metric for metric in self._descriptors if fnmatch.fnmatch(metric.type, pattern)]
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 MetricDescriptor objects that match the filters. """ if self._descriptors is None: self._descriptors = self._client.list_metric_descriptors( filter_string=self._filter_string, type_prefix=self._type_prefix) return [metric for metric in self._descriptors if fnmatch.fnmatch(metric.type, pattern)]
[ "def", "list", "(", "self", ",", "pattern", "=", "'*'", ")", ":", "if", "self", ".", "_descriptors", "is", "None", ":", "self", ".", "_descriptors", "=", "self", ".", "_client", ".", "list_metric_descriptors", "(", "filter_string", "=", "self", ".", "_filter_string", ",", "type_prefix", "=", "self", ".", "_type_prefix", ")", "return", "[", "metric", "for", "metric", "in", "self", ".", "_descriptors", "if", "fnmatch", ".", "fnmatch", "(", "metric", ".", "type", ",", "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 MetricDescriptor objects that match the filters.
[ "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
237,714
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 themselves may be numeric, the type in the derived schema may not be. Hence it is prudent to make sure the Pandas dataframe is typed correctly. Args: dataframe: The DataFrame. default_type : The default big query type in case the type of the column does not exist in the schema. Defaults to 'STRING'. Returns: A list of dictionaries containing field 'name' and 'type' entries, suitable for use in a BigQuery Tables resource schema. """ type_mapping = { 'i': 'INTEGER', 'b': 'BOOLEAN', 'f': 'FLOAT', 'O': 'STRING', 'S': 'STRING', 'U': 'STRING', 'M': 'TIMESTAMP' } fields = [] for column_name, dtype in dataframe.dtypes.iteritems(): fields.append({'name': column_name, 'type': type_mapping.get(dtype.kind, default_type)}) return fields
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 themselves may be numeric, the type in the derived schema may not be. Hence it is prudent to make sure the Pandas dataframe is typed correctly. Args: dataframe: The DataFrame. default_type : The default big query type in case the type of the column does not exist in the schema. Defaults to 'STRING'. Returns: A list of dictionaries containing field 'name' and 'type' entries, suitable for use in a BigQuery Tables resource schema. """ type_mapping = { 'i': 'INTEGER', 'b': 'BOOLEAN', 'f': 'FLOAT', 'O': 'STRING', 'S': 'STRING', 'U': 'STRING', 'M': 'TIMESTAMP' } fields = [] for column_name, dtype in dataframe.dtypes.iteritems(): fields.append({'name': column_name, 'type': type_mapping.get(dtype.kind, default_type)}) return fields
[ "def", "_from_dataframe", "(", "dataframe", ",", "default_type", "=", "'STRING'", ")", ":", "type_mapping", "=", "{", "'i'", ":", "'INTEGER'", ",", "'b'", ":", "'BOOLEAN'", ",", "'f'", ":", "'FLOAT'", ",", "'O'", ":", "'STRING'", ",", "'S'", ":", "'STRING'", ",", "'U'", ":", "'STRING'", ",", "'M'", ":", "'TIMESTAMP'", "}", "fields", "=", "[", "]", "for", "column_name", ",", "dtype", "in", "dataframe", ".", "dtypes", ".", "iteritems", "(", ")", ":", "fields", ".", "append", "(", "{", "'name'", ":", "column_name", ",", "'type'", ":", "type_mapping", ".", "get", "(", "dtype", ".", "kind", ",", "default_type", ")", "}", ")", "return", "fields" ]
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. Hence it is prudent to make sure the Pandas dataframe is typed correctly. Args: dataframe: The DataFrame. default_type : The default big query type in case the type of the column does not exist in the schema. Defaults to 'STRING'. 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", "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", ".", "Hence", "it", "is", "prudent", "to", "make", "sure", "the", "Pandas", "dataframe", "is", "typed", "correctly", "." ]
d9031901d5bca22fe0d5925d204e6698df9852e1
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/datalab/bigquery/_schema.py#L92-L124
train
237,715
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. Returns: A list of dictionaries containing field 'name' and 'type' entries, suitable for use in a BigQuery Tables resource schema. """ return [Schema._get_field_entry(name, value) for name, value in list(data.items())]
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. Returns: A list of dictionaries containing field 'name' and 'type' entries, suitable for use in a BigQuery Tables resource schema. """ return [Schema._get_field_entry(name, value) for name, value in list(data.items())]
[ "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 containing field 'name' and 'type' entries, suitable for use in a BigQuery Tables resource schema.
[ "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", "." ]
d9031901d5bca22fe0d5925d204e6698df9852e1
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/datalab/bigquery/_schema.py#L164-L176
train
237,716
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_field_entry('Column%d' % (i + 1), value) for i, value in enumerate(data)]
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_field_entry('Column%d' % (i + 1), value) for i, value in enumerate(data)]
[ "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
237,717
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 field 'name' and 'type' entries, suitable for use in a BigQuery Tables resource schema. """ if isinstance(data, dict): return Schema._from_dict_record(data) elif isinstance(data, list): return Schema._from_list_record(data) else: raise Exception('Cannot create a schema from record %s' % str(data))
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 field 'name' and 'type' entries, suitable for use in a BigQuery Tables resource schema. """ if isinstance(data, dict): return Schema._from_dict_record(data) elif isinstance(data, list): return Schema._from_list_record(data) else: raise Exception('Cannot create a schema from record %s' % str(data))
[ "def", "_from_record", "(", "data", ")", ":", "if", "isinstance", "(", "data", ",", "dict", ")", ":", "return", "Schema", ".", "_from_dict_record", "(", "data", ")", "elif", "isinstance", "(", "data", ",", "list", ")", ":", "return", "Schema", ".", "_from_list_record", "(", "data", ")", "else", ":", "raise", "Exception", "(", "'Cannot create a schema from record %s'", "%", "str", "(", "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 field 'name' and 'type' entries, suitable for use in a BigQuery Tables resource schema.
[ "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", "." ]
d9031901d5bca22fe0d5925d204e6698df9852e1
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/datalab/bigquery/_schema.py#L192-L208
train
237,718
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_name in namespace: args.append((namespace[var_name])) else: raise Exception('Undefined variable referenced in command line: %s' % arg) else: args.append(arg) return args
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_name in namespace: args.append((namespace[var_name])) else: raise Exception('Undefined variable referenced in command line: %s' % arg) else: args.append(arg) return args
[ "def", "create_args", "(", "line", ",", "namespace", ")", ":", "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_name", "in", "namespace", ":", "args", ".", "append", "(", "(", "namespace", "[", "var_name", "]", ")", ")", "else", ":", "raise", "Exception", "(", "'Undefined variable referenced in command line: %s'", "%", "arg", ")", "else", ":", "args", ".", "append", "(", "arg", ")", "return", "args" ]
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
237,719
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.parse_args(args) except Exception as e: print(str(e)) return None
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.parse_args(args) except Exception as e: print(str(e)) return None
[ "def", "parse", "(", "self", ",", "line", ",", "namespace", "=", "None", ")", ":", "try", ":", "if", "namespace", "is", "None", ":", "ipy", "=", "IPython", ".", "get_ipython", "(", ")", "namespace", "=", "ipy", ".", "user_ns", "args", "=", "CommandParser", ".", "create_args", "(", "line", ",", "namespace", ")", "return", "self", ".", "parse_args", "(", "args", ")", "except", "Exception", "as", "e", ":", "print", "(", "str", "(", "e", ")", ")", "return", "None" ]
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
237,720
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", ".", "_subcommands", ".", "add_parser", "(", "name", ",", "description", "=", "help", ",", "help", "=", "help", ")" ]
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
237,721
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
237,722
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', 'TIME': 'timeofday', 'DATETIME': 'datetime', 'TIMESTAMP': 'datetime' } cols = [] for col in fields: if schema: f = schema[col] t = 'string' if f.mode == 'REPEATED' else typemap.get(f.data_type, 'string') cols.append({'id': f.name, 'label': f.name, 'type': t}) else: # This will only happen if we had no rows to infer a schema from, so the type # is not really important, except that GCharts will choke if we pass such a schema # to a chart if it is string x string so we default to number. cols.append({'id': col, 'label': col, 'type': 'number'}) return cols
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', 'TIME': 'timeofday', 'DATETIME': 'datetime', 'TIMESTAMP': 'datetime' } cols = [] for col in fields: if schema: f = schema[col] t = 'string' if f.mode == 'REPEATED' else typemap.get(f.data_type, 'string') cols.append({'id': f.name, 'label': f.name, 'type': t}) else: # This will only happen if we had no rows to infer a schema from, so the type # is not really important, except that GCharts will choke if we pass such a schema # to a chart if it is string x string so we default to number. cols.append({'id': col, 'label': col, 'type': 'number'}) return cols
[ "def", "_get_cols", "(", "fields", ",", "schema", ")", ":", "typemap", "=", "{", "'STRING'", ":", "'string'", ",", "'INT64'", ":", "'number'", ",", "'INTEGER'", ":", "'number'", ",", "'FLOAT'", ":", "'number'", ",", "'FLOAT64'", ":", "'number'", ",", "'BOOL'", ":", "'boolean'", ",", "'BOOLEAN'", ":", "'boolean'", ",", "'DATE'", ":", "'date'", ",", "'TIME'", ":", "'timeofday'", ",", "'DATETIME'", ":", "'datetime'", ",", "'TIMESTAMP'", ":", "'datetime'", "}", "cols", "=", "[", "]", "for", "col", "in", "fields", ":", "if", "schema", ":", "f", "=", "schema", "[", "col", "]", "t", "=", "'string'", "if", "f", ".", "mode", "==", "'REPEATED'", "else", "typemap", ".", "get", "(", "f", ".", "data_type", ",", "'string'", ")", "cols", ".", "append", "(", "{", "'id'", ":", "f", ".", "name", ",", "'label'", ":", "f", ".", "name", ",", "'type'", ":", "t", "}", ")", "else", ":", "# This will only happen if we had no rows to infer a schema from, so the type", "# is not really important, except that GCharts will choke if we pass such a schema", "# to a chart if it is string x string so we default to number.", "cols", ".", "append", "(", "{", "'id'", ":", "col", ",", "'label'", ":", "col", ",", "'type'", ":", "'number'", "}", ")", "return", "cols" ]
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
237,723
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", "{", "'cols'", ":", "_get_cols", "(", "fields", ",", "schema", ")", ",", "'rows'", ":", "[", "]", "}", ",", "0" ]
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
237,724
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(fields, schema) gen = source.range(first_row, count) if count >= 0 else source rows = [{'c': [{'v': row[c]} if c in row else {} for c in fields]} for row in gen] return {'cols': _get_cols(fields, schema), 'rows': rows}, source.length
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(fields, schema) gen = source.range(first_row, count) if count >= 0 else source rows = [{'c': [{'v': row[c]} if c in row else {} for c in fields]} for row in gen] return {'cols': _get_cols(fields, schema), 'rows': rows}, source.length
[ "def", "_get_data_from_table", "(", "source", ",", "fields", "=", "'*'", ",", "first_row", "=", "0", ",", "count", "=", "-", "1", ",", "schema", "=", "None", ")", ":", "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", "(", "fields", ",", "schema", ")", "gen", "=", "source", ".", "range", "(", "first_row", ",", "count", ")", "if", "count", ">=", "0", "else", "source", "rows", "=", "[", "{", "'c'", ":", "[", "{", "'v'", ":", "row", "[", "c", "]", "}", "if", "c", "in", "row", "else", "{", "}", "for", "c", "in", "fields", "]", "}", "for", "row", "in", "gen", "]", "return", "{", "'cols'", ":", "_get_cols", "(", "fields", ",", "schema", ")", ",", "'rows'", ":", "rows", "}", ",", "source", ".", "length" ]
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
237,725
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, dict): for k, v in list(config.items()): if isinstance(v, dict) or isinstance(v, list) or isinstance(v, tuple): replace_vars(v, env) elif isinstance(v, basestring): config[k] = expand_var(v, env) elif isinstance(config, list): for i, v in enumerate(config): if isinstance(v, dict) or isinstance(v, list) or isinstance(v, tuple): replace_vars(v, env) elif isinstance(v, basestring): config[i] = expand_var(v, env) elif isinstance(config, tuple): # TODO(gram): figure out how to handle these if the tuple elements are scalar for v in config: if isinstance(v, dict) or isinstance(v, list) or isinstance(v, tuple): replace_vars(v, env)
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, dict): for k, v in list(config.items()): if isinstance(v, dict) or isinstance(v, list) or isinstance(v, tuple): replace_vars(v, env) elif isinstance(v, basestring): config[k] = expand_var(v, env) elif isinstance(config, list): for i, v in enumerate(config): if isinstance(v, dict) or isinstance(v, list) or isinstance(v, tuple): replace_vars(v, env) elif isinstance(v, basestring): config[i] = expand_var(v, env) elif isinstance(config, tuple): # TODO(gram): figure out how to handle these if the tuple elements are scalar for v in config: if isinstance(v, dict) or isinstance(v, list) or isinstance(v, tuple): replace_vars(v, env)
[ "def", "replace_vars", "(", "config", ",", "env", ")", ":", "if", "isinstance", "(", "config", ",", "dict", ")", ":", "for", "k", ",", "v", "in", "list", "(", "config", ".", "items", "(", ")", ")", ":", "if", "isinstance", "(", "v", ",", "dict", ")", "or", "isinstance", "(", "v", ",", "list", ")", "or", "isinstance", "(", "v", ",", "tuple", ")", ":", "replace_vars", "(", "v", ",", "env", ")", "elif", "isinstance", "(", "v", ",", "basestring", ")", ":", "config", "[", "k", "]", "=", "expand_var", "(", "v", ",", "env", ")", "elif", "isinstance", "(", "config", ",", "list", ")", ":", "for", "i", ",", "v", "in", "enumerate", "(", "config", ")", ":", "if", "isinstance", "(", "v", ",", "dict", ")", "or", "isinstance", "(", "v", ",", "list", ")", "or", "isinstance", "(", "v", ",", "tuple", ")", ":", "replace_vars", "(", "v", ",", "env", ")", "elif", "isinstance", "(", "v", ",", "basestring", ")", ":", "config", "[", "i", "]", "=", "expand_var", "(", "v", ",", "env", ")", "elif", "isinstance", "(", "config", ",", "tuple", ")", ":", "# TODO(gram): figure out how to handle these if the tuple elements are scalar", "for", "v", "in", "config", ":", "if", "isinstance", "(", "v", ",", "dict", ")", "or", "isinstance", "(", "v", ",", "list", ")", "or", "isinstance", "(", "v", ",", "tuple", ")", ":", "replace_vars", "(", "v", ",", "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.
[ "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
237,726
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() if len(stripped) == 0: config = {} elif stripped[0] == '{': config = json.loads(config) else: config = yaml.load(config) if as_dict: config = dict(config) # Now we need to walk the config dictionary recursively replacing any '$name' vars. replace_vars(config, env) return config
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() if len(stripped) == 0: config = {} elif stripped[0] == '{': config = json.loads(config) else: config = yaml.load(config) if as_dict: config = dict(config) # Now we need to walk the config dictionary recursively replacing any '$name' vars. replace_vars(config, env) return config
[ "def", "parse_config", "(", "config", ",", "env", ",", "as_dict", "=", "True", ")", ":", "if", "config", "is", "None", ":", "return", "None", "stripped", "=", "config", ".", "strip", "(", ")", "if", "len", "(", "stripped", ")", "==", "0", ":", "config", "=", "{", "}", "elif", "stripped", "[", "0", "]", "==", "'{'", ":", "config", "=", "json", ".", "loads", "(", "config", ")", "else", ":", "config", "=", "yaml", ".", "load", "(", "config", ")", "if", "as_dict", ":", "config", "=", "dict", "(", "config", ")", "# Now we need to walk the config dictionary recursively replacing any '$name' vars.", "replace_vars", "(", "config", ",", "env", ")", "return", "config" ]
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", "supplied", "env", "dictionary", "." ]
d9031901d5bca22fe0d5925d204e6698df9852e1
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/datalab/utils/commands/_utils.py#L313-L333
train
237,727
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: the names of the keys that the config can have. Raises: Exception if the config is not a dict or invalid. """ if optional_keys is None: optional_keys = [] if not isinstance(config, dict): raise Exception('config is not dict type') invalid_keys = set(config) - set(required_keys + optional_keys) if len(invalid_keys) > 0: raise Exception('Invalid config with unexpected keys "%s"' % ', '.join(e for e in invalid_keys)) missing_keys = set(required_keys) - set(config) if len(missing_keys) > 0: raise Exception('Invalid config with missing keys "%s"' % ', '.join(missing_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: the names of the keys that the config can have. Raises: Exception if the config is not a dict or invalid. """ if optional_keys is None: optional_keys = [] if not isinstance(config, dict): raise Exception('config is not dict type') invalid_keys = set(config) - set(required_keys + optional_keys) if len(invalid_keys) > 0: raise Exception('Invalid config with unexpected keys "%s"' % ', '.join(e for e in invalid_keys)) missing_keys = set(required_keys) - set(config) if len(missing_keys) > 0: raise Exception('Invalid config with missing keys "%s"' % ', '.join(missing_keys))
[ "def", "validate_config", "(", "config", ",", "required_keys", ",", "optional_keys", "=", "None", ")", ":", "if", "optional_keys", "is", "None", ":", "optional_keys", "=", "[", "]", "if", "not", "isinstance", "(", "config", ",", "dict", ")", ":", "raise", "Exception", "(", "'config is not dict type'", ")", "invalid_keys", "=", "set", "(", "config", ")", "-", "set", "(", "required_keys", "+", "optional_keys", ")", "if", "len", "(", "invalid_keys", ")", ">", "0", ":", "raise", "Exception", "(", "'Invalid config with unexpected keys \"%s\"'", "%", "', '", ".", "join", "(", "e", "for", "e", "in", "invalid_keys", ")", ")", "missing_keys", "=", "set", "(", "required_keys", ")", "-", "set", "(", "config", ")", "if", "len", "(", "missing_keys", ")", ">", "0", ":", "raise", "Exception", "(", "'Invalid config with missing keys \"%s\"'", "%", "', '", ".", "join", "(", "missing_keys", ")", ")" ]
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: Exception if the config is not a dict or invalid.
[ "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
237,728
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. """ missing_keys = set(required_keys) - set(config) if len(missing_keys) > 0: raise Exception('Invalid config with missing keys "%s"' % ', '.join(missing_keys))
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. """ missing_keys = set(required_keys) - set(config) if len(missing_keys) > 0: raise Exception('Invalid config with missing keys "%s"' % ', '.join(missing_keys))
[ "def", "validate_config_must_have", "(", "config", ",", "required_keys", ")", ":", "missing_keys", "=", "set", "(", "required_keys", ")", "-", "set", "(", "config", ")", "if", "len", "(", "missing_keys", ")", ">", "0", ":", "raise", "Exception", "(", "'Invalid config with missing keys \"%s\"'", "%", "', '", ".", "join", "(", "missing_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.
[ "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
237,729
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 does not have any of them, or multiple of them. """ intersection = set(config).intersection(one_of_keys) if len(intersection) > 1: raise Exception('Only one of the values in "%s" is needed' % ', '.join(intersection)) if len(intersection) == 0: raise Exception('One of the values in "%s" is needed' % ', '.join(one_of_keys))
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 does not have any of them, or multiple of them. """ intersection = set(config).intersection(one_of_keys) if len(intersection) > 1: raise Exception('Only one of the values in "%s" is needed' % ', '.join(intersection)) if len(intersection) == 0: raise Exception('One of the values in "%s" is needed' % ', '.join(one_of_keys))
[ "def", "validate_config_has_one_of", "(", "config", ",", "one_of_keys", ")", ":", "intersection", "=", "set", "(", "config", ")", ".", "intersection", "(", "one_of_keys", ")", "if", "len", "(", "intersection", ")", ">", "1", ":", "raise", "Exception", "(", "'Only one of the values in \"%s\" is needed'", "%", "', '", ".", "join", "(", "intersection", ")", ")", "if", "len", "(", "intersection", ")", "==", "0", ":", "raise", "Exception", "(", "'One of the values in \"%s\" is needed'", "%", "', '", ".", "join", "(", "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 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
237,730
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 value not in possible_values: raise Exception('Invalid config value "%s". Possible values are ' '%s' % (value, ', '.join(e for e in possible_values)))
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 value not in possible_values: raise Exception('Invalid config value "%s". Possible values are ' '%s' % (value, ', '.join(e for e in possible_values)))
[ "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", "(", "e", "for", "e", "in", "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.
[ "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
237,731
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.parse_name(path) if bucket is None: raise Exception('Invalid GCS path "%s"' % path) if require_object and key is None: raise Exception('It appears the GCS path "%s" is a bucket path but not an object path' % path)
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.parse_name(path) if bucket is None: raise Exception('Invalid GCS path "%s"' % path) if require_object and key is None: raise Exception('It appears the GCS path "%s" is a bucket path but not an object path' % path)
[ "def", "validate_gcs_path", "(", "path", ",", "require_object", ")", ":", "bucket", ",", "key", "=", "datalab", ".", "storage", ".", "_bucket", ".", "parse_name", "(", "path", ")", "if", "bucket", "is", "None", ":", "raise", "Exception", "(", "'Invalid GCS path \"%s\"'", "%", "path", ")", "if", "require_object", "and", "key", "is", "None", ":", "raise", "Exception", "(", "'It appears the GCS path \"%s\" is a bucket path but not an object path'", "%", "path", ")" ]
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
237,732
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.ProfileReport(df).html.replace('bootstrap', 'nonexistent'))
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.ProfileReport(df).html.replace('bootstrap', 'nonexistent'))
[ "def", "profile_df", "(", "df", ")", ":", "# 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", ".", "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
237,733
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 package_root = os.path.abspath( os.path.join(os.path.dirname(__file__), '../../')) setup_path = os.path.abspath( os.path.join(os.path.dirname(__file__), 'master_setup.py')) tar_gz_path = os.path.join(staging_package_url, 'staging', 'trainer.tar.gz') print('Building package and uploading to %s' % tar_gz_path) ml.package_and_copy(package_root, setup_path, tar_gz_path) return tar_gz_path
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 package_root = os.path.abspath( os.path.join(os.path.dirname(__file__), '../../')) setup_path = os.path.abspath( os.path.join(os.path.dirname(__file__), 'master_setup.py')) tar_gz_path = os.path.join(staging_package_url, 'staging', 'trainer.tar.gz') print('Building package and uploading to %s' % tar_gz_path) ml.package_and_copy(package_root, setup_path, tar_gz_path) return tar_gz_path
[ "def", "_package_to_staging", "(", "staging_package_url", ")", ":", "import", "google", ".", "datalab", ".", "ml", "as", "ml", "# Find the package root. __file__ is under [package_root]/mltoolbox/_structured_data/this_file", "package_root", "=", "os", ".", "path", ".", "abspath", "(", "os", ".", "path", ".", "join", "(", "os", ".", "path", ".", "dirname", "(", "__file__", ")", ",", "'../../'", ")", ")", "setup_path", "=", "os", ".", "path", ".", "abspath", "(", "os", ".", "path", ".", "join", "(", "os", ".", "path", ".", "dirname", "(", "__file__", ")", ",", "'master_setup.py'", ")", ")", "tar_gz_path", "=", "os", ".", "path", ".", "join", "(", "staging_package_url", ",", "'staging'", ",", "'trainer.tar.gz'", ")", "print", "(", "'Building package and uploading to %s'", "%", "tar_gz_path", ")", "ml", ".", "package_and_copy", "(", "package_root", ",", "setup_path", ",", "tar_gz_path", ")", "return", "tar_gz_path" ]
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
237,734
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", ",", "project_id", "=", "project_id", ")", "job", ".", "wait", "(", ")", "print", "(", "'Analyze: '", "+", "str", "(", "job", ".", "state", ")", ")" ]
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
237,735
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 to use. dataset: only CsvDataSet is supported currently. cloud: If False, runs analysis locally with Pandas. If Ture, runs analysis in the cloud with BigQuery. project_id: Uses BigQuery with this project id. Default is datalab's default project id. Returns: A google.datalab.utils.Job object that can be used to query state from or wait. """ import google.datalab.utils as du with warnings.catch_warnings(): warnings.simplefilter("ignore") fn = lambda: _analyze(output_dir, dataset, cloud, project_id) # noqa return du.LambdaJob(fn, job_id=None)
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 to use. dataset: only CsvDataSet is supported currently. cloud: If False, runs analysis locally with Pandas. If Ture, runs analysis in the cloud with BigQuery. project_id: Uses BigQuery with this project id. Default is datalab's default project id. Returns: A google.datalab.utils.Job object that can be used to query state from or wait. """ import google.datalab.utils as du with warnings.catch_warnings(): warnings.simplefilter("ignore") fn = lambda: _analyze(output_dir, dataset, cloud, project_id) # noqa return du.LambdaJob(fn, job_id=None)
[ "def", "analyze_async", "(", "output_dir", ",", "dataset", ",", "cloud", "=", "False", ",", "project_id", "=", "None", ")", ":", "import", "google", ".", "datalab", ".", "utils", "as", "du", "with", "warnings", ".", "catch_warnings", "(", ")", ":", "warnings", ".", "simplefilter", "(", "\"ignore\"", ")", "fn", "=", "lambda", ":", "_analyze", "(", "output_dir", ",", "dataset", ",", "cloud", ",", "project_id", ")", "# noqa", "return", "du", ".", "LambdaJob", "(", "fn", ",", "job_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 to use. dataset: only CsvDataSet is supported currently. cloud: If False, runs analysis locally with Pandas. If Ture, runs analysis in the cloud with BigQuery. project_id: Uses BigQuery with this project id. Default is datalab's default project id. Returns: A google.datalab.utils.Job object that can be used to query state from or wait.
[ "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
237,736
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_frequency, top_n, layer_sizes, learning_rate, epsilon, job_name, job_name_prefix, config): """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. """ import google.datalab.ml as ml if len(train_dataset.input_files) != 1 or len(eval_dataset.input_files) != 1: raise ValueError('CsvDataSets must be built with a file pattern, not list ' 'of files.') if file_io.file_exists(output_dir): raise ValueError('output_dir already exist. Use a new output path.') if isinstance(features, dict): # Make a features file. if not file_io.file_exists(output_dir): file_io.recursive_create_dir(output_dir) features_file = os.path.join(output_dir, 'features_file.json') file_io.write_string_to_file( features_file, json.dumps(features)) else: features_file = features if not isinstance(config, ml.CloudTrainingConfig): raise ValueError('cloud should be an instance of ' 'google.datalab.ml.CloudTrainingConfig for cloud training.') _assert_gcs_files([output_dir, train_dataset.input_files[0], eval_dataset.input_files[0], features_file, analysis_dir]) args = ['--train-data-paths=%s' % train_dataset.input_files[0], '--eval-data-paths=%s' % eval_dataset.input_files[0], '--preprocess-output-dir=%s' % analysis_dir, '--transforms-file=%s' % features_file, '--model-type=%s' % model_type, '--max-steps=%s' % str(max_steps), '--train-batch-size=%s' % str(train_batch_size), '--eval-batch-size=%s' % str(eval_batch_size), '--min-eval-frequency=%s' % str(min_eval_frequency), '--learning-rate=%s' % str(learning_rate), '--epsilon=%s' % str(epsilon)] if num_epochs: args.append('--num-epochs=%s' % str(num_epochs)) if top_n: args.append('--top-n=%s' % str(top_n)) if layer_sizes: for i in range(len(layer_sizes)): args.append('--layer-size%s=%s' % (i + 1, str(layer_sizes[i]))) job_request = { 'package_uris': [_package_to_staging(output_dir), _TF_GS_URL, _PROTOBUF_GS_URL], 'python_module': 'mltoolbox._structured_data.trainer.task', 'job_dir': output_dir, 'args': args } job_request.update(dict(config._asdict())) if not job_name: job_name = job_name_prefix or 'structured_data_train' job_name += '_' + datetime.datetime.now().strftime('%y%m%d_%H%M%S') job = ml.Job.submit_training(job_request, job_name) print('Job request send. View status of job at') print('https://console.developers.google.com/ml/jobs?project=%s' % _default_project()) return job
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_frequency, top_n, layer_sizes, learning_rate, epsilon, job_name, job_name_prefix, config): """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. """ import google.datalab.ml as ml if len(train_dataset.input_files) != 1 or len(eval_dataset.input_files) != 1: raise ValueError('CsvDataSets must be built with a file pattern, not list ' 'of files.') if file_io.file_exists(output_dir): raise ValueError('output_dir already exist. Use a new output path.') if isinstance(features, dict): # Make a features file. if not file_io.file_exists(output_dir): file_io.recursive_create_dir(output_dir) features_file = os.path.join(output_dir, 'features_file.json') file_io.write_string_to_file( features_file, json.dumps(features)) else: features_file = features if not isinstance(config, ml.CloudTrainingConfig): raise ValueError('cloud should be an instance of ' 'google.datalab.ml.CloudTrainingConfig for cloud training.') _assert_gcs_files([output_dir, train_dataset.input_files[0], eval_dataset.input_files[0], features_file, analysis_dir]) args = ['--train-data-paths=%s' % train_dataset.input_files[0], '--eval-data-paths=%s' % eval_dataset.input_files[0], '--preprocess-output-dir=%s' % analysis_dir, '--transforms-file=%s' % features_file, '--model-type=%s' % model_type, '--max-steps=%s' % str(max_steps), '--train-batch-size=%s' % str(train_batch_size), '--eval-batch-size=%s' % str(eval_batch_size), '--min-eval-frequency=%s' % str(min_eval_frequency), '--learning-rate=%s' % str(learning_rate), '--epsilon=%s' % str(epsilon)] if num_epochs: args.append('--num-epochs=%s' % str(num_epochs)) if top_n: args.append('--top-n=%s' % str(top_n)) if layer_sizes: for i in range(len(layer_sizes)): args.append('--layer-size%s=%s' % (i + 1, str(layer_sizes[i]))) job_request = { 'package_uris': [_package_to_staging(output_dir), _TF_GS_URL, _PROTOBUF_GS_URL], 'python_module': 'mltoolbox._structured_data.trainer.task', 'job_dir': output_dir, 'args': args } job_request.update(dict(config._asdict())) if not job_name: job_name = job_name_prefix or 'structured_data_train' job_name += '_' + datetime.datetime.now().strftime('%y%m%d_%H%M%S') job = ml.Job.submit_training(job_request, job_name) print('Job request send. View status of job at') print('https://console.developers.google.com/ml/jobs?project=%s' % _default_project()) return job
[ "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", ",", "layer_sizes", ",", "learning_rate", ",", "epsilon", ",", "job_name", ",", "job_name_prefix", ",", "config", ")", ":", "import", "google", ".", "datalab", ".", "ml", "as", "ml", "if", "len", "(", "train_dataset", ".", "input_files", ")", "!=", "1", "or", "len", "(", "eval_dataset", ".", "input_files", ")", "!=", "1", ":", "raise", "ValueError", "(", "'CsvDataSets must be built with a file pattern, not list '", "'of files.'", ")", "if", "file_io", ".", "file_exists", "(", "output_dir", ")", ":", "raise", "ValueError", "(", "'output_dir already exist. Use a new output path.'", ")", "if", "isinstance", "(", "features", ",", "dict", ")", ":", "# Make a features file.", "if", "not", "file_io", ".", "file_exists", "(", "output_dir", ")", ":", "file_io", ".", "recursive_create_dir", "(", "output_dir", ")", "features_file", "=", "os", ".", "path", ".", "join", "(", "output_dir", ",", "'features_file.json'", ")", "file_io", ".", "write_string_to_file", "(", "features_file", ",", "json", ".", "dumps", "(", "features", ")", ")", "else", ":", "features_file", "=", "features", "if", "not", "isinstance", "(", "config", ",", "ml", ".", "CloudTrainingConfig", ")", ":", "raise", "ValueError", "(", "'cloud should be an instance of '", "'google.datalab.ml.CloudTrainingConfig for cloud training.'", ")", "_assert_gcs_files", "(", "[", "output_dir", ",", "train_dataset", ".", "input_files", "[", "0", "]", ",", "eval_dataset", ".", "input_files", "[", "0", "]", ",", "features_file", ",", "analysis_dir", "]", ")", "args", "=", "[", "'--train-data-paths=%s'", "%", "train_dataset", ".", "input_files", "[", "0", "]", ",", "'--eval-data-paths=%s'", "%", "eval_dataset", ".", "input_files", "[", "0", "]", ",", "'--preprocess-output-dir=%s'", "%", "analysis_dir", ",", "'--transforms-file=%s'", "%", "features_file", ",", "'--model-type=%s'", "%", "model_type", ",", "'--max-steps=%s'", "%", "str", "(", "max_steps", ")", ",", "'--train-batch-size=%s'", "%", "str", "(", "train_batch_size", ")", ",", "'--eval-batch-size=%s'", "%", "str", "(", "eval_batch_size", ")", ",", "'--min-eval-frequency=%s'", "%", "str", "(", "min_eval_frequency", ")", ",", "'--learning-rate=%s'", "%", "str", "(", "learning_rate", ")", ",", "'--epsilon=%s'", "%", "str", "(", "epsilon", ")", "]", "if", "num_epochs", ":", "args", ".", "append", "(", "'--num-epochs=%s'", "%", "str", "(", "num_epochs", ")", ")", "if", "top_n", ":", "args", ".", "append", "(", "'--top-n=%s'", "%", "str", "(", "top_n", ")", ")", "if", "layer_sizes", ":", "for", "i", "in", "range", "(", "len", "(", "layer_sizes", ")", ")", ":", "args", ".", "append", "(", "'--layer-size%s=%s'", "%", "(", "i", "+", "1", ",", "str", "(", "layer_sizes", "[", "i", "]", ")", ")", ")", "job_request", "=", "{", "'package_uris'", ":", "[", "_package_to_staging", "(", "output_dir", ")", ",", "_TF_GS_URL", ",", "_PROTOBUF_GS_URL", "]", ",", "'python_module'", ":", "'mltoolbox._structured_data.trainer.task'", ",", "'job_dir'", ":", "output_dir", ",", "'args'", ":", "args", "}", "job_request", ".", "update", "(", "dict", "(", "config", ".", "_asdict", "(", ")", ")", ")", "if", "not", "job_name", ":", "job_name", "=", "job_name_prefix", "or", "'structured_data_train'", "job_name", "+=", "'_'", "+", "datetime", ".", "datetime", ".", "now", "(", ")", ".", "strftime", "(", "'%y%m%d_%H%M%S'", ")", "job", "=", "ml", ".", "Job", ".", "submit_training", "(", "job_request", ",", "job_name", ")", "print", "(", "'Job request send. View status of job at'", ")", "print", "(", "'https://console.developers.google.com/ml/jobs?project=%s'", "%", "_default_project", "(", ")", ")", "return", "job" ]
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
237,737
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 model_version: depoyed model version cloud: bool. If False, does local prediction and data and training_dir must be set. If True, does cloud prediction and data, model_name, and model_version must be set. For cloud prediction, the model must be created. This can be done by running two gcloud commands:: 1) gcloud beta ml models create NAME 2) gcloud beta ml versions create VERSION --model NAME --origin gs://BUCKET/training_dir/model or these datalab commands: 1) import google.datalab as datalab model = datalab.ml.ModelVersions(MODEL_NAME) model.deploy(version_name=VERSION, path='gs://BUCKET/training_dir/model') Note that the model must be on GCS. Returns: Pandas DataFrame. """ if cloud: if not model_version or not model_name: raise ValueError('model_version or model_name is not set') if training_dir: raise ValueError('training_dir not needed when cloud is True') with warnings.catch_warnings(): warnings.simplefilter("ignore") return cloud_predict(model_name, model_version, data) else: if not training_dir: raise ValueError('training_dir is not set') if model_version or model_name: raise ValueError('model_name and model_version not needed when cloud is ' 'False.') with warnings.catch_warnings(): warnings.simplefilter("ignore") return local_predict(training_dir, data)
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 model_version: depoyed model version cloud: bool. If False, does local prediction and data and training_dir must be set. If True, does cloud prediction and data, model_name, and model_version must be set. For cloud prediction, the model must be created. This can be done by running two gcloud commands:: 1) gcloud beta ml models create NAME 2) gcloud beta ml versions create VERSION --model NAME --origin gs://BUCKET/training_dir/model or these datalab commands: 1) import google.datalab as datalab model = datalab.ml.ModelVersions(MODEL_NAME) model.deploy(version_name=VERSION, path='gs://BUCKET/training_dir/model') Note that the model must be on GCS. Returns: Pandas DataFrame. """ if cloud: if not model_version or not model_name: raise ValueError('model_version or model_name is not set') if training_dir: raise ValueError('training_dir not needed when cloud is True') with warnings.catch_warnings(): warnings.simplefilter("ignore") return cloud_predict(model_name, model_version, data) else: if not training_dir: raise ValueError('training_dir is not set') if model_version or model_name: raise ValueError('model_name and model_version not needed when cloud is ' 'False.') with warnings.catch_warnings(): warnings.simplefilter("ignore") return local_predict(training_dir, data)
[ "def", "predict", "(", "data", ",", "training_dir", "=", "None", ",", "model_name", "=", "None", ",", "model_version", "=", "None", ",", "cloud", "=", "False", ")", ":", "if", "cloud", ":", "if", "not", "model_version", "or", "not", "model_name", ":", "raise", "ValueError", "(", "'model_version or model_name is not set'", ")", "if", "training_dir", ":", "raise", "ValueError", "(", "'training_dir not needed when cloud is True'", ")", "with", "warnings", ".", "catch_warnings", "(", ")", ":", "warnings", ".", "simplefilter", "(", "\"ignore\"", ")", "return", "cloud_predict", "(", "model_name", ",", "model_version", ",", "data", ")", "else", ":", "if", "not", "training_dir", ":", "raise", "ValueError", "(", "'training_dir is not set'", ")", "if", "model_version", "or", "model_name", ":", "raise", "ValueError", "(", "'model_name and model_version not needed when cloud is '", "'False.'", ")", "with", "warnings", ".", "catch_warnings", "(", ")", ":", "warnings", ".", "simplefilter", "(", "\"ignore\"", ")", "return", "local_predict", "(", "training_dir", ",", "data", ")" ]
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 data and training_dir must be set. If True, does cloud prediction and data, model_name, and model_version must be set. For cloud prediction, the model must be created. This can be done by running two gcloud commands:: 1) gcloud beta ml models create NAME 2) gcloud beta ml versions create VERSION --model NAME --origin gs://BUCKET/training_dir/model or these datalab commands: 1) import google.datalab as datalab model = datalab.ml.ModelVersions(MODEL_NAME) model.deploy(version_name=VERSION, path='gs://BUCKET/training_dir/model') Note that the model must be on GCS. Returns: Pandas DataFrame.
[ "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
237,738
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 schema that was used at training, except the target column should not exist. Args: training_dir: local path to the trained output folder. data: List of csv strings or a Pandas DataFrame that match the model schema. Raises: ValueError: if training_dir does not contain the folder 'model'. FileNotFoundError: if the prediction data is not found. """ # from . import predict as predict_module from .prediction import predict as predict_module # Save the instances to a file, call local batch prediction, and return it tmp_dir = tempfile.mkdtemp() _, input_file_path = tempfile.mkstemp(dir=tmp_dir, suffix='.csv', prefix='input') try: if isinstance(data, pd.DataFrame): data.to_csv(input_file_path, header=False, index=False) else: with open(input_file_path, 'w') as f: for line in data: f.write(line + '\n') model_dir = os.path.join(training_dir, 'model') if not file_io.file_exists(model_dir): raise ValueError('training_dir should contain the folder model') cmd = ['predict.py', '--predict-data=%s' % input_file_path, '--trained-model-dir=%s' % model_dir, '--output-dir=%s' % tmp_dir, '--output-format=csv', '--batch-size=16', '--mode=prediction', '--no-shard-files'] # runner_results = predict_module.predict.main(cmd) runner_results = predict_module.main(cmd) runner_results.wait_until_finish() # Read the header file. schema_file = os.path.join(tmp_dir, 'csv_schema.json') with open(schema_file, 'r') as f: schema = json.loads(f.read()) # Print any errors to the screen. errors_file = glob.glob(os.path.join(tmp_dir, 'errors*')) if errors_file and os.path.getsize(errors_file[0]) > 0: print('Warning: there are errors. See below:') with open(errors_file[0], 'r') as f: text = f.read() print(text) # Read the predictions data. prediction_file = glob.glob(os.path.join(tmp_dir, 'predictions*')) if not prediction_file: raise FileNotFoundError('Prediction results not found') predictions = pd.read_csv(prediction_file[0], header=None, names=[col['name'] for col in schema]) return predictions finally: shutil.rmtree(tmp_dir)
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 schema that was used at training, except the target column should not exist. Args: training_dir: local path to the trained output folder. data: List of csv strings or a Pandas DataFrame that match the model schema. Raises: ValueError: if training_dir does not contain the folder 'model'. FileNotFoundError: if the prediction data is not found. """ # from . import predict as predict_module from .prediction import predict as predict_module # Save the instances to a file, call local batch prediction, and return it tmp_dir = tempfile.mkdtemp() _, input_file_path = tempfile.mkstemp(dir=tmp_dir, suffix='.csv', prefix='input') try: if isinstance(data, pd.DataFrame): data.to_csv(input_file_path, header=False, index=False) else: with open(input_file_path, 'w') as f: for line in data: f.write(line + '\n') model_dir = os.path.join(training_dir, 'model') if not file_io.file_exists(model_dir): raise ValueError('training_dir should contain the folder model') cmd = ['predict.py', '--predict-data=%s' % input_file_path, '--trained-model-dir=%s' % model_dir, '--output-dir=%s' % tmp_dir, '--output-format=csv', '--batch-size=16', '--mode=prediction', '--no-shard-files'] # runner_results = predict_module.predict.main(cmd) runner_results = predict_module.main(cmd) runner_results.wait_until_finish() # Read the header file. schema_file = os.path.join(tmp_dir, 'csv_schema.json') with open(schema_file, 'r') as f: schema = json.loads(f.read()) # Print any errors to the screen. errors_file = glob.glob(os.path.join(tmp_dir, 'errors*')) if errors_file and os.path.getsize(errors_file[0]) > 0: print('Warning: there are errors. See below:') with open(errors_file[0], 'r') as f: text = f.read() print(text) # Read the predictions data. prediction_file = glob.glob(os.path.join(tmp_dir, 'predictions*')) if not prediction_file: raise FileNotFoundError('Prediction results not found') predictions = pd.read_csv(prediction_file[0], header=None, names=[col['name'] for col in schema]) return predictions finally: shutil.rmtree(tmp_dir)
[ "def", "local_predict", "(", "training_dir", ",", "data", ")", ":", "# from . import predict as predict_module", "from", ".", "prediction", "import", "predict", "as", "predict_module", "# Save the instances to a file, call local batch prediction, and return it", "tmp_dir", "=", "tempfile", ".", "mkdtemp", "(", ")", "_", ",", "input_file_path", "=", "tempfile", ".", "mkstemp", "(", "dir", "=", "tmp_dir", ",", "suffix", "=", "'.csv'", ",", "prefix", "=", "'input'", ")", "try", ":", "if", "isinstance", "(", "data", ",", "pd", ".", "DataFrame", ")", ":", "data", ".", "to_csv", "(", "input_file_path", ",", "header", "=", "False", ",", "index", "=", "False", ")", "else", ":", "with", "open", "(", "input_file_path", ",", "'w'", ")", "as", "f", ":", "for", "line", "in", "data", ":", "f", ".", "write", "(", "line", "+", "'\\n'", ")", "model_dir", "=", "os", ".", "path", ".", "join", "(", "training_dir", ",", "'model'", ")", "if", "not", "file_io", ".", "file_exists", "(", "model_dir", ")", ":", "raise", "ValueError", "(", "'training_dir should contain the folder model'", ")", "cmd", "=", "[", "'predict.py'", ",", "'--predict-data=%s'", "%", "input_file_path", ",", "'--trained-model-dir=%s'", "%", "model_dir", ",", "'--output-dir=%s'", "%", "tmp_dir", ",", "'--output-format=csv'", ",", "'--batch-size=16'", ",", "'--mode=prediction'", ",", "'--no-shard-files'", "]", "# runner_results = predict_module.predict.main(cmd)", "runner_results", "=", "predict_module", ".", "main", "(", "cmd", ")", "runner_results", ".", "wait_until_finish", "(", ")", "# Read the header file.", "schema_file", "=", "os", ".", "path", ".", "join", "(", "tmp_dir", ",", "'csv_schema.json'", ")", "with", "open", "(", "schema_file", ",", "'r'", ")", "as", "f", ":", "schema", "=", "json", ".", "loads", "(", "f", ".", "read", "(", ")", ")", "# Print any errors to the screen.", "errors_file", "=", "glob", ".", "glob", "(", "os", ".", "path", ".", "join", "(", "tmp_dir", ",", "'errors*'", ")", ")", "if", "errors_file", "and", "os", ".", "path", ".", "getsize", "(", "errors_file", "[", "0", "]", ")", ">", "0", ":", "print", "(", "'Warning: there are errors. See below:'", ")", "with", "open", "(", "errors_file", "[", "0", "]", ",", "'r'", ")", "as", "f", ":", "text", "=", "f", ".", "read", "(", ")", "print", "(", "text", ")", "# Read the predictions data.", "prediction_file", "=", "glob", ".", "glob", "(", "os", ".", "path", ".", "join", "(", "tmp_dir", ",", "'predictions*'", ")", ")", "if", "not", "prediction_file", ":", "raise", "FileNotFoundError", "(", "'Prediction results not found'", ")", "predictions", "=", "pd", ".", "read_csv", "(", "prediction_file", "[", "0", "]", ",", "header", "=", "None", ",", "names", "=", "[", "col", "[", "'name'", "]", "for", "col", "in", "schema", "]", ")", "return", "predictions", "finally", ":", "shutil", ".", "rmtree", "(", "tmp_dir", ")" ]
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 target column should not exist. Args: training_dir: local path to the trained output folder. data: List of csv strings or a Pandas DataFrame that match the model schema. Raises: ValueError: if training_dir does not contain the folder 'model'. FileNotFoundError: if the prediction data is not found.
[ "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
237,739
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 model_version: depoyed model version data: List of csv strings or a Pandas DataFrame that match the model schema. Before using this, the model must be created. This can be done by running two gcloud commands: 1) gcloud beta ml models create NAME 2) gcloud beta ml versions create VERSION --model NAME \ --origin gs://BUCKET/training_dir/model or these datalab commands: 1) import google.datalab as datalab model = datalab.ml.ModelVersions(MODEL_NAME) model.deploy(version_name=VERSION, path='gs://BUCKET/training_dir/model') Note that the model must be on GCS. """ import google.datalab.ml as ml if isinstance(data, pd.DataFrame): # write the df to csv. string_buffer = io.StringIO() data.to_csv(string_buffer, header=None, index=False) input_data = string_buffer.getvalue().split('\n') # remove empty strings input_data = [line for line in input_data if line] else: input_data = data predictions = ml.ModelVersions(model_name).predict(model_version, input_data) # Convert predictions into a dataframe df = pd.DataFrame(columns=sorted(predictions[0].keys())) for i in range(len(predictions)): for k, v in predictions[i].iteritems(): df.loc[i, k] = v return df
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 model_version: depoyed model version data: List of csv strings or a Pandas DataFrame that match the model schema. Before using this, the model must be created. This can be done by running two gcloud commands: 1) gcloud beta ml models create NAME 2) gcloud beta ml versions create VERSION --model NAME \ --origin gs://BUCKET/training_dir/model or these datalab commands: 1) import google.datalab as datalab model = datalab.ml.ModelVersions(MODEL_NAME) model.deploy(version_name=VERSION, path='gs://BUCKET/training_dir/model') Note that the model must be on GCS. """ import google.datalab.ml as ml if isinstance(data, pd.DataFrame): # write the df to csv. string_buffer = io.StringIO() data.to_csv(string_buffer, header=None, index=False) input_data = string_buffer.getvalue().split('\n') # remove empty strings input_data = [line for line in input_data if line] else: input_data = data predictions = ml.ModelVersions(model_name).predict(model_version, input_data) # Convert predictions into a dataframe df = pd.DataFrame(columns=sorted(predictions[0].keys())) for i in range(len(predictions)): for k, v in predictions[i].iteritems(): df.loc[i, k] = v return df
[ "def", "cloud_predict", "(", "model_name", ",", "model_version", ",", "data", ")", ":", "import", "google", ".", "datalab", ".", "ml", "as", "ml", "if", "isinstance", "(", "data", ",", "pd", ".", "DataFrame", ")", ":", "# write the df to csv.", "string_buffer", "=", "io", ".", "StringIO", "(", ")", "data", ".", "to_csv", "(", "string_buffer", ",", "header", "=", "None", ",", "index", "=", "False", ")", "input_data", "=", "string_buffer", ".", "getvalue", "(", ")", ".", "split", "(", "'\\n'", ")", "# remove empty strings", "input_data", "=", "[", "line", "for", "line", "in", "input_data", "if", "line", "]", "else", ":", "input_data", "=", "data", "predictions", "=", "ml", ".", "ModelVersions", "(", "model_name", ")", ".", "predict", "(", "model_version", ",", "input_data", ")", "# Convert predictions into a dataframe", "df", "=", "pd", ".", "DataFrame", "(", "columns", "=", "sorted", "(", "predictions", "[", "0", "]", ".", "keys", "(", ")", ")", ")", "for", "i", "in", "range", "(", "len", "(", "predictions", ")", ")", ":", "for", "k", ",", "v", "in", "predictions", "[", "i", "]", ".", "iteritems", "(", ")", ":", "df", ".", "loc", "[", "i", ",", "k", "]", "=", "v", "return", "df" ]
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 csv strings or a Pandas DataFrame that match the model schema. Before using this, the model must be created. This can be done by running two gcloud commands: 1) gcloud beta ml models create NAME 2) gcloud beta ml versions create VERSION --model NAME \ --origin gs://BUCKET/training_dir/model or these datalab commands: 1) import google.datalab as datalab model = datalab.ml.ModelVersions(MODEL_NAME) model.deploy(version_name=VERSION, path='gs://BUCKET/training_dir/model') Note that the model must be on GCS.
[ "Use", "Online", "prediction", "." ]
d9031901d5bca22fe0d5925d204e6698df9852e1
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/solutionbox/structured_data/mltoolbox/_structured_data/_package.py#L671-L715
train
237,740
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=training_dir, prediction_input_file=prediction_input_file, output_dir=output_dir, mode=mode, batch_size=batch_size, shard_files=shard_files, output_format=output_format, cloud=cloud) job.wait() print('Batch predict: ' + str(job.state))
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=training_dir, prediction_input_file=prediction_input_file, output_dir=output_dir, mode=mode, batch_size=batch_size, shard_files=shard_files, output_format=output_format, cloud=cloud) job.wait() print('Batch predict: ' + str(job.state))
[ "def", "batch_predict", "(", "training_dir", ",", "prediction_input_file", ",", "output_dir", ",", "mode", ",", "batch_size", "=", "16", ",", "shard_files", "=", "True", ",", "output_format", "=", "'csv'", ",", "cloud", "=", "False", ")", ":", "job", "=", "batch_predict_async", "(", "training_dir", "=", "training_dir", ",", "prediction_input_file", "=", "prediction_input_file", ",", "output_dir", "=", "output_dir", ",", "mode", "=", "mode", ",", "batch_size", "=", "batch_size", ",", "shard_files", "=", "shard_files", ",", "output_format", "=", "output_format", ",", "cloud", "=", "cloud", ")", "job", ".", "wait", "(", ")", "print", "(", "'Batch predict: '", "+", "str", "(", "job", ".", "state", ")", ")" ]
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
237,741
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 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: 'evaluation' or 'prediction'. If 'evaluation', the input data must contain a target column. If 'prediction', the input data must not contain a target column. batch_size: Int. How many instances to run in memory at once. Larger values mean better performace but more memeory consumed. shard_files: If False, the output files are not shardded. output_format: csv or json. Json file are json-newlined. cloud: If ture, does cloud batch prediction. If False, runs batch prediction locally. Returns: A google.datalab.utils.Job object that can be used to query state from or wait. """ import google.datalab.utils as du with warnings.catch_warnings(): warnings.simplefilter("ignore") if cloud: runner_results = cloud_batch_predict(training_dir, prediction_input_file, output_dir, mode, batch_size, shard_files, output_format) job = du.DataflowJob(runner_results) else: runner_results = local_batch_predict(training_dir, prediction_input_file, output_dir, mode, batch_size, shard_files, output_format) job = du.LambdaJob(lambda: runner_results.wait_until_finish(), job_id=None) return job
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 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: 'evaluation' or 'prediction'. If 'evaluation', the input data must contain a target column. If 'prediction', the input data must not contain a target column. batch_size: Int. How many instances to run in memory at once. Larger values mean better performace but more memeory consumed. shard_files: If False, the output files are not shardded. output_format: csv or json. Json file are json-newlined. cloud: If ture, does cloud batch prediction. If False, runs batch prediction locally. Returns: A google.datalab.utils.Job object that can be used to query state from or wait. """ import google.datalab.utils as du with warnings.catch_warnings(): warnings.simplefilter("ignore") if cloud: runner_results = cloud_batch_predict(training_dir, prediction_input_file, output_dir, mode, batch_size, shard_files, output_format) job = du.DataflowJob(runner_results) else: runner_results = local_batch_predict(training_dir, prediction_input_file, output_dir, mode, batch_size, shard_files, output_format) job = du.LambdaJob(lambda: runner_results.wait_until_finish(), job_id=None) return job
[ "def", "batch_predict_async", "(", "training_dir", ",", "prediction_input_file", ",", "output_dir", ",", "mode", ",", "batch_size", "=", "16", ",", "shard_files", "=", "True", ",", "output_format", "=", "'csv'", ",", "cloud", "=", "False", ")", ":", "import", "google", ".", "datalab", ".", "utils", "as", "du", "with", "warnings", ".", "catch_warnings", "(", ")", ":", "warnings", ".", "simplefilter", "(", "\"ignore\"", ")", "if", "cloud", ":", "runner_results", "=", "cloud_batch_predict", "(", "training_dir", ",", "prediction_input_file", ",", "output_dir", ",", "mode", ",", "batch_size", ",", "shard_files", ",", "output_format", ")", "job", "=", "du", ".", "DataflowJob", "(", "runner_results", ")", "else", ":", "runner_results", "=", "local_batch_predict", "(", "training_dir", ",", "prediction_input_file", ",", "output_dir", ",", "mode", ",", "batch_size", ",", "shard_files", ",", "output_format", ")", "job", "=", "du", ".", "LambdaJob", "(", "lambda", ":", "runner_results", ".", "wait_until_finish", "(", ")", ",", "job_id", "=", "None", ")", "return", "job" ]
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: 'evaluation' or 'prediction'. If 'evaluation', the input data must contain a target column. If 'prediction', the input data must not contain a target column. batch_size: Int. How many instances to run in memory at once. Larger values mean better performace but more memeory consumed. shard_files: If False, the output files are not shardded. output_format: csv or json. Json file are json-newlined. cloud: If ture, does cloud batch prediction. If False, runs batch prediction locally. Returns: A google.datalab.utils.Job object that can be used to query state from or wait.
[ "Local", "and", "cloud", "batch", "prediction", "." ]
d9031901d5bca22fe0d5925d204e6698df9852e1
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/solutionbox/structured_data/mltoolbox/_structured_data/_package.py#L742-L777
train
237,742
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 with unicode strings predicted_values, errors = ( pipeline | 'Read CSV Files' >> beam.io.ReadFromText(str(args.predict_data), strip_trailing_newlines=True) | 'Batch Input' >> beam.ParDo(EmitAsBatchDoFn(args.batch_size)) | 'Run TF Graph on Batches' >> beam.ParDo(RunGraphDoFn(args.trained_model_dir)).with_outputs('errors', main='main')) ((predicted_values, errors) | 'Format and Save' >> FormatAndSave(args))
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 with unicode strings predicted_values, errors = ( pipeline | 'Read CSV Files' >> beam.io.ReadFromText(str(args.predict_data), strip_trailing_newlines=True) | 'Batch Input' >> beam.ParDo(EmitAsBatchDoFn(args.batch_size)) | 'Run TF Graph on Batches' >> beam.ParDo(RunGraphDoFn(args.trained_model_dir)).with_outputs('errors', main='main')) ((predicted_values, errors) | 'Format and Save' >> FormatAndSave(args))
[ "def", "make_prediction_pipeline", "(", "pipeline", ",", "args", ")", ":", "# DF bug: DF does not work with unicode strings", "predicted_values", ",", "errors", "=", "(", "pipeline", "|", "'Read CSV Files'", ">>", "beam", ".", "io", ".", "ReadFromText", "(", "str", "(", "args", ".", "predict_data", ")", ",", "strip_trailing_newlines", "=", "True", ")", "|", "'Batch Input'", ">>", "beam", ".", "ParDo", "(", "EmitAsBatchDoFn", "(", "args", ".", "batch_size", ")", ")", "|", "'Run TF Graph on Batches'", ">>", "beam", ".", "ParDo", "(", "RunGraphDoFn", "(", "args", ".", "trained_model_dir", ")", ")", ".", "with_outputs", "(", "'errors'", ",", "main", "=", "'main'", ")", ")", "(", "(", "predicted_values", ",", "errors", ")", "|", "'Format and Save'", ">>", "FormatAndSave", "(", "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
[ "Builds", "the", "prediction", "pipeline", "." ]
d9031901d5bca22fe0d5925d204e6698df9852e1
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/solutionbox/structured_data/mltoolbox/_structured_data/prediction/predict.py#L349-L373
train
237,743
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 = collections.defaultdict(list) for line in element: # Remove trailing newline. if line.endswith('\n'): line = line[:-1] feed_dict[self._input_alias_map.values()[0]].append(line) num_in_batch += 1 # batch_result is list of numpy arrays with batch_size many rows. batch_result = self._session.run(fetches=self._tensor_names, feed_dict=feed_dict) # ex batch_result for batch_size > 1: # (array([value1, value2, ..., value_batch_size]), # array([[a1, b1, c1]], ..., [a_batch_size, b_batch_size, c_batch_size]]), # ...) # ex batch_result for batch_size == 1: # (value, # array([a1, b1, c1]), # ...) # Convert the results into a dict and unbatch the results. if num_in_batch > 1: for result in zip(*batch_result): predictions = {} for name, value in zip(self._aliases, result): predictions[name] = (value.tolist() if getattr(value, 'tolist', None) else value) yield predictions else: predictions = {} for i in range(len(self._aliases)): value = batch_result[i] value = (value.tolist() if getattr(value, 'tolist', None) else value) predictions[self._aliases[i]] = value yield predictions except Exception as e: # pylint: disable=broad-except yield beam.pvalue.TaggedOutput('errors', (str(e), element))
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 = collections.defaultdict(list) for line in element: # Remove trailing newline. if line.endswith('\n'): line = line[:-1] feed_dict[self._input_alias_map.values()[0]].append(line) num_in_batch += 1 # batch_result is list of numpy arrays with batch_size many rows. batch_result = self._session.run(fetches=self._tensor_names, feed_dict=feed_dict) # ex batch_result for batch_size > 1: # (array([value1, value2, ..., value_batch_size]), # array([[a1, b1, c1]], ..., [a_batch_size, b_batch_size, c_batch_size]]), # ...) # ex batch_result for batch_size == 1: # (value, # array([a1, b1, c1]), # ...) # Convert the results into a dict and unbatch the results. if num_in_batch > 1: for result in zip(*batch_result): predictions = {} for name, value in zip(self._aliases, result): predictions[name] = (value.tolist() if getattr(value, 'tolist', None) else value) yield predictions else: predictions = {} for i in range(len(self._aliases)): value = batch_result[i] value = (value.tolist() if getattr(value, 'tolist', None) else value) predictions[self._aliases[i]] = value yield predictions except Exception as e: # pylint: disable=broad-except yield beam.pvalue.TaggedOutput('errors', (str(e), element))
[ "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", ".", "defaultdict", "(", "list", ")", "for", "line", "in", "element", ":", "# Remove trailing newline.", "if", "line", ".", "endswith", "(", "'\\n'", ")", ":", "line", "=", "line", "[", ":", "-", "1", "]", "feed_dict", "[", "self", ".", "_input_alias_map", ".", "values", "(", ")", "[", "0", "]", "]", ".", "append", "(", "line", ")", "num_in_batch", "+=", "1", "# batch_result is list of numpy arrays with batch_size many rows.", "batch_result", "=", "self", ".", "_session", ".", "run", "(", "fetches", "=", "self", ".", "_tensor_names", ",", "feed_dict", "=", "feed_dict", ")", "# ex batch_result for batch_size > 1:", "# (array([value1, value2, ..., value_batch_size]),", "# array([[a1, b1, c1]], ..., [a_batch_size, b_batch_size, c_batch_size]]),", "# ...)", "# ex batch_result for batch_size == 1:", "# (value,", "# array([a1, b1, c1]),", "# ...)", "# Convert the results into a dict and unbatch the results.", "if", "num_in_batch", ">", "1", ":", "for", "result", "in", "zip", "(", "*", "batch_result", ")", ":", "predictions", "=", "{", "}", "for", "name", ",", "value", "in", "zip", "(", "self", ".", "_aliases", ",", "result", ")", ":", "predictions", "[", "name", "]", "=", "(", "value", ".", "tolist", "(", ")", "if", "getattr", "(", "value", ",", "'tolist'", ",", "None", ")", "else", "value", ")", "yield", "predictions", "else", ":", "predictions", "=", "{", "}", "for", "i", "in", "range", "(", "len", "(", "self", ".", "_aliases", ")", ")", ":", "value", "=", "batch_result", "[", "i", "]", "value", "=", "(", "value", ".", "tolist", "(", ")", "if", "getattr", "(", "value", ",", "'tolist'", ",", "None", ")", "else", "value", ")", "predictions", "[", "self", ".", "_aliases", "[", "i", "]", "]", "=", "value", "yield", "predictions", "except", "Exception", "as", "e", ":", "# pylint: disable=broad-except", "yield", "beam", ".", "pvalue", ".", "TaggedOutput", "(", "'errors'", ",", "(", "str", "(", "e", ")", ",", "element", ")", ")" ]
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
237,744
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", "','", ".", "join", "(", "row", ")" ]
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
237,745
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 metric labels. Each row in this dataframe corresponds to the metadata from one time series. """ max_rows = len(self._timeseries_list) if max_rows is None else max_rows headers = [{ 'resource': ts.resource._asdict(), 'metric': ts.metric._asdict()} for ts in self._timeseries_list[:max_rows]] if not headers: return pandas.DataFrame() dataframe = pandas.io.json.json_normalize(headers) # Add a 2 level column header. dataframe.columns = pandas.MultiIndex.from_tuples( [(col, '') if col == 'resource.type' else col.rsplit('.', 1) for col in dataframe.columns]) # Re-order the columns. resource_keys = google.cloud.monitoring._dataframe._sorted_resource_labels( dataframe['resource.labels'].columns) sorted_columns = [('resource.type', '')] sorted_columns += [('resource.labels', key) for key in resource_keys] sorted_columns += sorted(col for col in dataframe.columns if col[0] == 'metric.labels') dataframe = dataframe[sorted_columns] # Sort the data, and clean up index values, and NaNs. dataframe = dataframe.sort_values(sorted_columns) dataframe = dataframe.reset_index(drop=True).fillna('') return dataframe
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 metric labels. Each row in this dataframe corresponds to the metadata from one time series. """ max_rows = len(self._timeseries_list) if max_rows is None else max_rows headers = [{ 'resource': ts.resource._asdict(), 'metric': ts.metric._asdict()} for ts in self._timeseries_list[:max_rows]] if not headers: return pandas.DataFrame() dataframe = pandas.io.json.json_normalize(headers) # Add a 2 level column header. dataframe.columns = pandas.MultiIndex.from_tuples( [(col, '') if col == 'resource.type' else col.rsplit('.', 1) for col in dataframe.columns]) # Re-order the columns. resource_keys = google.cloud.monitoring._dataframe._sorted_resource_labels( dataframe['resource.labels'].columns) sorted_columns = [('resource.type', '')] sorted_columns += [('resource.labels', key) for key in resource_keys] sorted_columns += sorted(col for col in dataframe.columns if col[0] == 'metric.labels') dataframe = dataframe[sorted_columns] # Sort the data, and clean up index values, and NaNs. dataframe = dataframe.sort_values(sorted_columns) dataframe = dataframe.reset_index(drop=True).fillna('') return dataframe
[ "def", "as_dataframe", "(", "self", ",", "max_rows", "=", "None", ")", ":", "max_rows", "=", "len", "(", "self", ".", "_timeseries_list", ")", "if", "max_rows", "is", "None", "else", "max_rows", "headers", "=", "[", "{", "'resource'", ":", "ts", ".", "resource", ".", "_asdict", "(", ")", ",", "'metric'", ":", "ts", ".", "metric", ".", "_asdict", "(", ")", "}", "for", "ts", "in", "self", ".", "_timeseries_list", "[", ":", "max_rows", "]", "]", "if", "not", "headers", ":", "return", "pandas", ".", "DataFrame", "(", ")", "dataframe", "=", "pandas", ".", "io", ".", "json", ".", "json_normalize", "(", "headers", ")", "# Add a 2 level column header.", "dataframe", ".", "columns", "=", "pandas", ".", "MultiIndex", ".", "from_tuples", "(", "[", "(", "col", ",", "''", ")", "if", "col", "==", "'resource.type'", "else", "col", ".", "rsplit", "(", "'.'", ",", "1", ")", "for", "col", "in", "dataframe", ".", "columns", "]", ")", "# Re-order the columns.", "resource_keys", "=", "google", ".", "cloud", ".", "monitoring", ".", "_dataframe", ".", "_sorted_resource_labels", "(", "dataframe", "[", "'resource.labels'", "]", ".", "columns", ")", "sorted_columns", "=", "[", "(", "'resource.type'", ",", "''", ")", "]", "sorted_columns", "+=", "[", "(", "'resource.labels'", ",", "key", ")", "for", "key", "in", "resource_keys", "]", "sorted_columns", "+=", "sorted", "(", "col", "for", "col", "in", "dataframe", ".", "columns", "if", "col", "[", "0", "]", "==", "'metric.labels'", ")", "dataframe", "=", "dataframe", "[", "sorted_columns", "]", "# Sort the data, and clean up index values, and NaNs.", "dataframe", "=", "dataframe", ".", "sort_values", "(", "sorted_columns", ")", "dataframe", "=", "dataframe", ".", "reset_index", "(", "drop", "=", "True", ")", ".", "fillna", "(", "''", ")", "return", "dataframe" ]
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 corresponds to the metadata from one time series.
[ "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
237,746
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_files = file_io.get_matching_files(eval_pattern) return train_files, eval_files
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_files = file_io.get_matching_files(eval_pattern) return train_files, eval_files
[ "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", ".", "path", ".", "join", "(", "data_dir", ",", "'eval*.tfrecord.gz'", ")", "train_files", "=", "file_io", ".", "get_matching_files", "(", "train_pattern", ")", "eval_files", "=", "file_io", ".", "get_matching_files", "(", "eval_pattern", ")", "return", "train_files", ",", "eval_files" ]
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
237,747
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", ",", "'r'", ")", "as", "f", ":", "labels", "=", "f", ".", "read", "(", ")", ".", "rstrip", "(", ")", ".", "split", "(", "'\\n'", ")", "return", "labels" ]
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
237,748
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
237,749
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 [total_loss_update, loss_count_update], loss_op
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 [total_loss_update, loss_count_update], loss_op
[ "def", "loss", "(", "loss_value", ")", ":", "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", "[", "total_loss_update", ",", "loss_count_update", "]", ",", "loss_op" ]
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
237,750
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.Variable(0, False) correct_count_update = tf.assign_add(correct_count, correct) incorrect_count_update = tf.assign_add(incorrect_count, incorrect) accuracy_op = tf.cast(correct_count, tf.float32) / tf.cast( correct_count + incorrect_count, tf.float32) return [correct_count_update, incorrect_count_update], accuracy_op
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.Variable(0, False) correct_count_update = tf.assign_add(correct_count, correct) incorrect_count_update = tf.assign_add(incorrect_count, incorrect) accuracy_op = tf.cast(correct_count, tf.float32) / tf.cast( correct_count + incorrect_count, tf.float32) return [correct_count_update, incorrect_count_update], accuracy_op
[ "def", "accuracy", "(", "logits", ",", "labels", ")", ":", "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", ".", "Variable", "(", "0", ",", "False", ")", "correct_count_update", "=", "tf", ".", "assign_add", "(", "correct_count", ",", "correct", ")", "incorrect_count_update", "=", "tf", ".", "assign_add", "(", "incorrect_count", ",", "incorrect", ")", "accuracy_op", "=", "tf", ".", "cast", "(", "correct_count", ",", "tf", ".", "float32", ")", "/", "tf", ".", "cast", "(", "correct_count", "+", "incorrect_count", ",", "tf", ".", "float32", ")", "return", "[", "correct_count_update", ",", "incorrect_count_update", "]", ",", "accuracy_op" ]
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
237,751
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. Expect only "image_url,label" STRING columns.') else: if (set(['image_url']) != set(names) and set(['image_url', 'label']) != set(names)) or \ any(t != 'STRING' for t in types): raise ValueError('Invalid dataset. Expect only "image_url" or "image_url,label" ' + 'STRING columns.')
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. Expect only "image_url,label" STRING columns.') else: if (set(['image_url']) != set(names) and set(['image_url', 'label']) != set(names)) or \ any(t != 'STRING' for t in types): raise ValueError('Invalid dataset. Expect only "image_url" or "image_url,label" ' + 'STRING columns.')
[ "def", "check_dataset", "(", "dataset", ",", "mode", ")", ":", "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. Expect only \"image_url,label\" STRING columns.'", ")", "else", ":", "if", "(", "set", "(", "[", "'image_url'", "]", ")", "!=", "set", "(", "names", ")", "and", "set", "(", "[", "'image_url'", ",", "'label'", "]", ")", "!=", "set", "(", "names", ")", ")", "or", "any", "(", "t", "!=", "'STRING'", "for", "t", "in", "types", ")", ":", "raise", "ValueError", "(", "'Invalid dataset. Expect only \"image_url\" or \"image_url,label\" '", "+", "'STRING columns.'", ")" ]
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
237,752
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.files): source_list.append(p | 'Read from Csv %d (%s)' % (ii, mode) >> beam.io.ReadFromText(input_path, strip_trailing_newlines=True)) return (source_list | 'Flatten Sources (%s)' % mode >> beam.Flatten() | 'Create Dict from Csv (%s)' % mode >> beam.Map(lambda line: csv.DictReader([line], fieldnames=['image_url', 'label']).next())) elif type(dataset) is BigQueryDataSet: bq_source = (beam.io.BigQuerySource(table=dataset.table) if dataset.table is not None else beam.io.BigQuerySource(query=dataset.query)) return p | 'Read source from BigQuery (%s)' % mode >> beam.io.Read(bq_source) else: raise ValueError('Invalid DataSet. Expect CsvDataSet or BigQueryDataSet')
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.files): source_list.append(p | 'Read from Csv %d (%s)' % (ii, mode) >> beam.io.ReadFromText(input_path, strip_trailing_newlines=True)) return (source_list | 'Flatten Sources (%s)' % mode >> beam.Flatten() | 'Create Dict from Csv (%s)' % mode >> beam.Map(lambda line: csv.DictReader([line], fieldnames=['image_url', 'label']).next())) elif type(dataset) is BigQueryDataSet: bq_source = (beam.io.BigQuerySource(table=dataset.table) if dataset.table is not None else beam.io.BigQuerySource(query=dataset.query)) return p | 'Read source from BigQuery (%s)' % mode >> beam.io.Read(bq_source) else: raise ValueError('Invalid DataSet. Expect CsvDataSet or BigQueryDataSet')
[ "def", "get_sources_from_dataset", "(", "p", ",", "dataset", ",", "mode", ")", ":", "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", ".", "files", ")", ":", "source_list", ".", "append", "(", "p", "|", "'Read from Csv %d (%s)'", "%", "(", "ii", ",", "mode", ")", ">>", "beam", ".", "io", ".", "ReadFromText", "(", "input_path", ",", "strip_trailing_newlines", "=", "True", ")", ")", "return", "(", "source_list", "|", "'Flatten Sources (%s)'", "%", "mode", ">>", "beam", ".", "Flatten", "(", ")", "|", "'Create Dict from Csv (%s)'", "%", "mode", ">>", "beam", ".", "Map", "(", "lambda", "line", ":", "csv", ".", "DictReader", "(", "[", "line", "]", ",", "fieldnames", "=", "[", "'image_url'", ",", "'label'", "]", ")", ".", "next", "(", ")", ")", ")", "elif", "type", "(", "dataset", ")", "is", "BigQueryDataSet", ":", "bq_source", "=", "(", "beam", ".", "io", ".", "BigQuerySource", "(", "table", "=", "dataset", ".", "table", ")", "if", "dataset", ".", "table", "is", "not", "None", "else", "beam", ".", "io", ".", "BigQuerySource", "(", "query", "=", "dataset", ".", "query", ")", ")", "return", "p", "|", "'Read source from BigQuery (%s)'", "%", "mode", ">>", "beam", ".", "io", ".", "Read", "(", "bq_source", ")", "else", ":", "raise", "ValueError", "(", "'Invalid DataSet. Expect CsvDataSet or BigQueryDataSet'", ")" ]
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
237,753
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, but tf_map supresses that index, # thus we have to expand then squeeze. Resize returns float32 in the # range [0, uint8_max] image = tf.expand_dims(image, 0) image = tf.image.resize_bilinear(image, [height, width], align_corners=False) image = tf.squeeze(image, squeeze_dims=[0]) image = tf.cast(image, dtype=tf.uint8) return image
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, but tf_map supresses that index, # thus we have to expand then squeeze. Resize returns float32 in the # range [0, uint8_max] image = tf.expand_dims(image, 0) image = tf.image.resize_bilinear(image, [height, width], align_corners=False) image = tf.squeeze(image, squeeze_dims=[0]) image = tf.cast(image, dtype=tf.uint8) return image
[ "def", "decode_and_resize", "(", "image_str_tensor", ")", ":", "# These constants are set by Inception v3's expectations.", "height", "=", "299", "width", "=", "299", "channels", "=", "3", "image", "=", "tf", ".", "image", ".", "decode_jpeg", "(", "image_str_tensor", ",", "channels", "=", "channels", ")", "# Note resize expects a batch_size, but tf_map supresses that index,", "# thus we have to expand then squeeze. Resize returns float32 in the", "# range [0, uint8_max]", "image", "=", "tf", ".", "expand_dims", "(", "image", ",", "0", ")", "image", "=", "tf", ".", "image", ".", "resize_bilinear", "(", "image", ",", "[", "height", ",", "width", "]", ",", "align_corners", "=", "False", ")", "image", "=", "tf", ".", "squeeze", "(", "image", ",", "squeeze_dims", "=", "[", "0", "]", ")", "image", "=", "tf", ".", "cast", "(", "image", ",", "dtype", "=", "tf", ".", "uint8", ")", "return", "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
237,754
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
237,755
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 'decode_and_resize()' # which is used in prediction graph. This makes sure we don't lose # any quality in prediction, while decreasing the size of the images # submitted to the model over network. image_str_tensor = tf.placeholder(tf.string, shape=[None]) image = tf.map_fn(resize_image, image_str_tensor, back_prop=False) feed_dict = collections.defaultdict(list) feed_dict[image_str_tensor.name] = images with tf.Session() as sess: images_resized = sess.run(image, feed_dict=feed_dict) return images_resized
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 'decode_and_resize()' # which is used in prediction graph. This makes sure we don't lose # any quality in prediction, while decreasing the size of the images # submitted to the model over network. image_str_tensor = tf.placeholder(tf.string, shape=[None]) image = tf.map_fn(resize_image, image_str_tensor, back_prop=False) feed_dict = collections.defaultdict(list) feed_dict[image_str_tensor.name] = images with tf.Session() as sess: images_resized = sess.run(image, feed_dict=feed_dict) return images_resized
[ "def", "load_images", "(", "image_files", ",", "resize", "=", "True", ")", ":", "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 'decode_and_resize()'", "# which is used in prediction graph. This makes sure we don't lose", "# any quality in prediction, while decreasing the size of the images", "# submitted to the model over network.", "image_str_tensor", "=", "tf", ".", "placeholder", "(", "tf", ".", "string", ",", "shape", "=", "[", "None", "]", ")", "image", "=", "tf", ".", "map_fn", "(", "resize_image", ",", "image_str_tensor", ",", "back_prop", "=", "False", ")", "feed_dict", "=", "collections", ".", "defaultdict", "(", "list", ")", "feed_dict", "[", "image_str_tensor", ".", "name", "]", "=", "images", "with", "tf", ".", "Session", "(", ")", "as", "sess", ":", "images_resized", "=", "sess", ".", "run", "(", "image", ",", "feed_dict", "=", "feed_dict", ")", "return", "images_resized" ]
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
237,756
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.display_html('<p style="font-size:28px">%s(%.5f)</p>' % label_and_score, raw=True) IPython.display.display(IPython.display.Image(data=image)) result_dict = [{'image_url': url, 'label': r[0], 'score': r[1]} for url, _, r in results] return pd.DataFrame(result_dict)
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.display_html('<p style="font-size:28px">%s(%.5f)</p>' % label_and_score, raw=True) IPython.display.display(IPython.display.Image(data=image)) result_dict = [{'image_url': url, 'label': r[0], 'score': r[1]} for url, _, r in results] return pd.DataFrame(result_dict)
[ "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", ",", "label_and_score", "in", "results", ":", "IPython", ".", "display", ".", "display_html", "(", "'<p style=\"font-size:28px\">%s(%.5f)</p>'", "%", "label_and_score", ",", "raw", "=", "True", ")", "IPython", ".", "display", ".", "display", "(", "IPython", ".", "display", ".", "Image", "(", "data", "=", "image", ")", ")", "result_dict", "=", "[", "{", "'image_url'", ":", "url", ",", "'label'", ":", "r", "[", "0", "]", ",", "'score'", ":", "r", "[", "1", "]", "}", "for", "url", ",", "_", ",", "r", "in", "results", "]", "return", "pd", ".", "DataFrame", "(", "result_dict", ")" ]
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
237,757
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 setup.py in the same dir for repackaging purpose. setup_py = os.path.join(os.path.dirname(__file__), 'setup.py') staging_package_url = os.path.join(output_path, 'staging', 'image_classification.tar.gz') ml.package_and_copy(package_root, setup_py, staging_package_url) return staging_package_url
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 setup.py in the same dir for repackaging purpose. setup_py = os.path.join(os.path.dirname(__file__), 'setup.py') staging_package_url = os.path.join(output_path, 'staging', 'image_classification.tar.gz') ml.package_and_copy(package_root, setup_py, staging_package_url) return staging_package_url
[ "def", "repackage_to_staging", "(", "output_path", ")", ":", "import", "google", ".", "datalab", ".", "ml", "as", "ml", "# Find the package root. __file__ is under [package_root]/mltoolbox/image/classification.", "package_root", "=", "os", ".", "path", ".", "join", "(", "os", ".", "path", ".", "dirname", "(", "__file__", ")", ",", "'../../../'", ")", "# We deploy setup.py in the same dir for repackaging purpose.", "setup_py", "=", "os", ".", "path", ".", "join", "(", "os", ".", "path", ".", "dirname", "(", "__file__", ")", ",", "'setup.py'", ")", "staging_package_url", "=", "os", ".", "path", ".", "join", "(", "output_path", ",", "'staging'", ",", "'image_classification.tar.gz'", ")", "ml", ".", "package_and_copy", "(", "package_root", ",", "setup_py", ",", "staging_package_url", ")", "return", "staging_package_url" ]
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
237,758
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 = PipelineGenerator._get_operator_definition(task_id, task_details, parameters) task_definitions = task_definitions + task_def dependency_def = PipelineGenerator._get_dependency_definition( task_id, task_details.get('up_stream', [])) up_steam_statements = up_steam_statements + dependency_def schedule_config = pipeline_spec.get('schedule', {}) default_args = PipelineGenerator._get_default_args(schedule_config, pipeline_spec.get('emails', {})) dag_definition = PipelineGenerator._get_dag_definition( name, schedule_config.get('interval', '@once'), schedule_config.get('catchup', False)) return PipelineGenerator._imports + default_args + dag_definition + task_definitions + \ up_steam_statements
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 = PipelineGenerator._get_operator_definition(task_id, task_details, parameters) task_definitions = task_definitions + task_def dependency_def = PipelineGenerator._get_dependency_definition( task_id, task_details.get('up_stream', [])) up_steam_statements = up_steam_statements + dependency_def schedule_config = pipeline_spec.get('schedule', {}) default_args = PipelineGenerator._get_default_args(schedule_config, pipeline_spec.get('emails', {})) dag_definition = PipelineGenerator._get_dag_definition( name, schedule_config.get('interval', '@once'), schedule_config.get('catchup', False)) return PipelineGenerator._imports + default_args + dag_definition + task_definitions + \ up_steam_statements
[ "def", "generate_airflow_spec", "(", "name", ",", "pipeline_spec", ")", ":", "task_definitions", "=", "''", "up_steam_statements", "=", "''", "parameters", "=", "pipeline_spec", ".", "get", "(", "'parameters'", ")", "for", "(", "task_id", ",", "task_details", ")", "in", "sorted", "(", "pipeline_spec", "[", "'tasks'", "]", ".", "items", "(", ")", ")", ":", "task_def", "=", "PipelineGenerator", ".", "_get_operator_definition", "(", "task_id", ",", "task_details", ",", "parameters", ")", "task_definitions", "=", "task_definitions", "+", "task_def", "dependency_def", "=", "PipelineGenerator", ".", "_get_dependency_definition", "(", "task_id", ",", "task_details", ".", "get", "(", "'up_stream'", ",", "[", "]", ")", ")", "up_steam_statements", "=", "up_steam_statements", "+", "dependency_def", "schedule_config", "=", "pipeline_spec", ".", "get", "(", "'schedule'", ",", "{", "}", ")", "default_args", "=", "PipelineGenerator", ".", "_get_default_args", "(", "schedule_config", ",", "pipeline_spec", ".", "get", "(", "'emails'", ",", "{", "}", ")", ")", "dag_definition", "=", "PipelineGenerator", ".", "_get_dag_definition", "(", "name", ",", "schedule_config", ".", "get", "(", "'interval'", ",", "'@once'", ")", ",", "schedule_config", ".", "get", "(", "'catchup'", ",", "False", ")", ")", "return", "PipelineGenerator", ".", "_imports", "+", "default_args", "+", "dag_definition", "+", "task_definitions", "+", "up_steam_statements" ]
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
237,759
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_statements + \ '{0}.set_upstream({1})'.format(task_id, dependency) + '\n' return set_upstream_statements
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_statements + \ '{0}.set_upstream({1})'.format(task_id, dependency) + '\n' return set_upstream_statements
[ "def", "_get_dependency_definition", "(", "task_id", ",", "dependencies", ")", ":", "set_upstream_statements", "=", "''", "for", "dependency", "in", "dependencies", ":", "set_upstream_statements", "=", "set_upstream_statements", "+", "'{0}.set_upstream({1})'", ".", "format", "(", "task_id", ",", "dependency", ")", "+", "'\\n'", "return", "set_upstream_statements" ]
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
237,760
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_operator_prefix_mapping = { 'pydatalab.bq.execute': ('Execute', 'google.datalab.contrib.bigquery.operators._bq_execute_operator'), 'pydatalab.bq.extract': ('Extract', 'google.datalab.contrib.bigquery.operators._bq_extract_operator'), 'pydatalab.bq.load': ('Load', 'google.datalab.contrib.bigquery.operators._bq_load_operator'), 'Bash': ('Bash', 'airflow.operators.bash_operator') } (operator_class_prefix, module) = task_type_to_operator_prefix_mapping.get( task_detail_type, (None, __name__)) format_string = '{0}Operator' operator_class_name = format_string.format(operator_class_prefix) if operator_class_prefix is None: return format_string.format(task_detail_type), module return operator_class_name, module
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_operator_prefix_mapping = { 'pydatalab.bq.execute': ('Execute', 'google.datalab.contrib.bigquery.operators._bq_execute_operator'), 'pydatalab.bq.extract': ('Extract', 'google.datalab.contrib.bigquery.operators._bq_extract_operator'), 'pydatalab.bq.load': ('Load', 'google.datalab.contrib.bigquery.operators._bq_load_operator'), 'Bash': ('Bash', 'airflow.operators.bash_operator') } (operator_class_prefix, module) = task_type_to_operator_prefix_mapping.get( task_detail_type, (None, __name__)) format_string = '{0}Operator' operator_class_name = format_string.format(operator_class_prefix) if operator_class_prefix is None: return format_string.format(task_detail_type), module return operator_class_name, module
[ "def", "_get_operator_class_name", "(", "task_detail_type", ")", ":", "# TODO(rajivpb): Rename this var correctly.", "task_type_to_operator_prefix_mapping", "=", "{", "'pydatalab.bq.execute'", ":", "(", "'Execute'", ",", "'google.datalab.contrib.bigquery.operators._bq_execute_operator'", ")", ",", "'pydatalab.bq.extract'", ":", "(", "'Extract'", ",", "'google.datalab.contrib.bigquery.operators._bq_extract_operator'", ")", ",", "'pydatalab.bq.load'", ":", "(", "'Load'", ",", "'google.datalab.contrib.bigquery.operators._bq_load_operator'", ")", ",", "'Bash'", ":", "(", "'Bash'", ",", "'airflow.operators.bash_operator'", ")", "}", "(", "operator_class_prefix", ",", "module", ")", "=", "task_type_to_operator_prefix_mapping", ".", "get", "(", "task_detail_type", ",", "(", "None", ",", "__name__", ")", ")", "format_string", "=", "'{0}Operator'", "operator_class_name", "=", "format_string", ".", "format", "(", "operator_class_prefix", ")", "if", "operator_class_prefix", "is", "None", ":", "return", "format_string", ".", "format", "(", "task_detail_type", ")", ",", "module", "return", "operator_class_name", ",", "module" ]
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
237,761
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 Datalab, or one that's more friendly. For example, Airflow's BigQueryOperator uses 'bql' for the query string, but we want %%bq users in Datalab to use 'query'. Hence, a few substitutions that are specific to the Airflow operator need to be made. Similarly, we the parameter value could come from the notebook's context. All that happens here. Returns: Dict containing _only_ the keys and values that are required in Airflow operator definition. This requires a substituting existing keys in the dictionary with their Airflow equivalents ( i.e. by adding new keys, and removing the existing ones). """ # We make a clone and then remove 'type' and 'up_stream' since these aren't needed for the # the operator's parameters. operator_task_details = task_details.copy() if 'type' in operator_task_details.keys(): del operator_task_details['type'] if 'up_stream' in operator_task_details.keys(): del operator_task_details['up_stream'] # We special-case certain operators if we do some translation of the parameter names. This is # usually the case when we use syntactic sugar to expose the functionality. # TODO(rajivpb): It should be possible to make this a lookup from the modules mapping via # getattr() or equivalent. Avoid hard-coding these class-names here. if (operator_class_name == 'BigQueryOperator'): return PipelineGenerator._get_bq_execute_params(operator_task_details) if (operator_class_name == 'BigQueryToCloudStorageOperator'): return PipelineGenerator._get_bq_extract_params(operator_task_details) if (operator_class_name == 'GoogleCloudStorageToBigQueryOperator'): return PipelineGenerator._get_bq_load_params(operator_task_details) return operator_task_details
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 Datalab, or one that's more friendly. For example, Airflow's BigQueryOperator uses 'bql' for the query string, but we want %%bq users in Datalab to use 'query'. Hence, a few substitutions that are specific to the Airflow operator need to be made. Similarly, we the parameter value could come from the notebook's context. All that happens here. Returns: Dict containing _only_ the keys and values that are required in Airflow operator definition. This requires a substituting existing keys in the dictionary with their Airflow equivalents ( i.e. by adding new keys, and removing the existing ones). """ # We make a clone and then remove 'type' and 'up_stream' since these aren't needed for the # the operator's parameters. operator_task_details = task_details.copy() if 'type' in operator_task_details.keys(): del operator_task_details['type'] if 'up_stream' in operator_task_details.keys(): del operator_task_details['up_stream'] # We special-case certain operators if we do some translation of the parameter names. This is # usually the case when we use syntactic sugar to expose the functionality. # TODO(rajivpb): It should be possible to make this a lookup from the modules mapping via # getattr() or equivalent. Avoid hard-coding these class-names here. if (operator_class_name == 'BigQueryOperator'): return PipelineGenerator._get_bq_execute_params(operator_task_details) if (operator_class_name == 'BigQueryToCloudStorageOperator'): return PipelineGenerator._get_bq_extract_params(operator_task_details) if (operator_class_name == 'GoogleCloudStorageToBigQueryOperator'): return PipelineGenerator._get_bq_load_params(operator_task_details) return operator_task_details
[ "def", "_get_operator_param_name_and_values", "(", "operator_class_name", ",", "task_details", ")", ":", "# We make a clone and then remove 'type' and 'up_stream' since these aren't needed for the", "# the operator's parameters.", "operator_task_details", "=", "task_details", ".", "copy", "(", ")", "if", "'type'", "in", "operator_task_details", ".", "keys", "(", ")", ":", "del", "operator_task_details", "[", "'type'", "]", "if", "'up_stream'", "in", "operator_task_details", ".", "keys", "(", ")", ":", "del", "operator_task_details", "[", "'up_stream'", "]", "# We special-case certain operators if we do some translation of the parameter names. This is", "# usually the case when we use syntactic sugar to expose the functionality.", "# TODO(rajivpb): It should be possible to make this a lookup from the modules mapping via", "# getattr() or equivalent. Avoid hard-coding these class-names here.", "if", "(", "operator_class_name", "==", "'BigQueryOperator'", ")", ":", "return", "PipelineGenerator", ".", "_get_bq_execute_params", "(", "operator_task_details", ")", "if", "(", "operator_class_name", "==", "'BigQueryToCloudStorageOperator'", ")", ":", "return", "PipelineGenerator", ".", "_get_bq_extract_params", "(", "operator_task_details", ")", "if", "(", "operator_class_name", "==", "'GoogleCloudStorageToBigQueryOperator'", ")", ":", "return", "PipelineGenerator", ".", "_get_bq_load_params", "(", "operator_task_details", ")", "return", "operator_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 Datalab, or one that's more friendly. For example, Airflow's BigQueryOperator uses 'bql' for the query string, but we want %%bq users in Datalab to use 'query'. Hence, a few substitutions that are specific to the Airflow operator need to be made. Similarly, we the parameter value could come from the notebook's context. All that happens here. Returns: Dict containing _only_ the keys and values that are required in Airflow operator definition. This requires a substituting existing keys in the dictionary with their Airflow equivalents ( i.e. by adding new keys, and removing the existing ones).
[ "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", "bql", "for", "the", "query", "string", "but", "we", "want", "%%bq", "users", "in", "Datalab", "to", "use", "query", ".", "Hence", "a", "few", "substitutions", "that", "are", "specific", "to", "the", "Airflow", "operator", "need", "to", "be", "made", "." ]
d9031901d5bca22fe0d5925d204e6698df9852e1
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/google/datalab/contrib/pipeline/_pipeline.py#L201-L236
train
237,762
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 larger than number of rows. """ total = bq.Query('select count(*) from %s' % self._get_source()).execute().result()[0].values()[0] if n > total: raise ValueError('sample larger than population') sampling = bq.Sampling.random(percent=n * 100.0 / float(total)) if self._query is not None: source = self._query else: source = 'SELECT * FROM `%s`' % self._table sample = bq.Query(source).execute(sampling=sampling).result() df = sample.to_dataframe() return df
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 larger than number of rows. """ total = bq.Query('select count(*) from %s' % self._get_source()).execute().result()[0].values()[0] if n > total: raise ValueError('sample larger than population') sampling = bq.Sampling.random(percent=n * 100.0 / float(total)) if self._query is not None: source = self._query else: source = 'SELECT * FROM `%s`' % self._table sample = bq.Query(source).execute(sampling=sampling).result() df = sample.to_dataframe() return df
[ "def", "sample", "(", "self", ",", "n", ")", ":", "total", "=", "bq", ".", "Query", "(", "'select count(*) from %s'", "%", "self", ".", "_get_source", "(", ")", ")", ".", "execute", "(", ")", ".", "result", "(", ")", "[", "0", "]", ".", "values", "(", ")", "[", "0", "]", "if", "n", ">", "total", ":", "raise", "ValueError", "(", "'sample larger than population'", ")", "sampling", "=", "bq", ".", "Sampling", ".", "random", "(", "percent", "=", "n", "*", "100.0", "/", "float", "(", "total", ")", ")", "if", "self", ".", "_query", "is", "not", "None", ":", "source", "=", "self", ".", "_query", "else", ":", "source", "=", "'SELECT * FROM `%s`'", "%", "self", ".", "_table", "sample", "=", "bq", ".", "Query", "(", "source", ")", ".", "execute", "(", "sampling", "=", "sampling", ")", ".", "result", "(", ")", "df", "=", "sample", ".", "to_dataframe", "(", ")", "return", "df" ]
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
237,763
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_file in self.files: self._size += sum(1 for x in tf.python_io.tf_record_iterator(tfexample_file, options=options)) return self._size
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_file in self.files: self._size += sum(1 for x in tf.python_io.tf_record_iterator(tfexample_file, options=options)) return self._size
[ "def", "size", "(", "self", ")", ":", "import", "tensorflow", "as", "tf", "if", "self", ".", "_size", "is", "None", ":", "self", ".", "_size", "=", "0", "options", "=", "tf", ".", "python_io", ".", "TFRecordOptions", "(", "tf", ".", "python_io", ".", "TFRecordCompressionType", ".", "GZIP", ")", "for", "tfexample_file", "in", "self", ".", "files", ":", "self", ".", "_size", "+=", "sum", "(", "1", "for", "x", "in", "tf", ".", "python_io", ".", "tf_record_iterator", "(", "tfexample_file", ",", "options", "=", "options", ")", ")", "return", "self", ".", "_size" ]
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
237,764
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 match the filters. """ if self._group_dict is None: self._group_dict = collections.OrderedDict( (group.id, group) for group in self._client.list_groups()) return [group for group in self._group_dict.values() if fnmatch.fnmatch(group.display_name, pattern)]
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 match the filters. """ if self._group_dict is None: self._group_dict = collections.OrderedDict( (group.id, group) for group in self._client.list_groups()) return [group for group in self._group_dict.values() if fnmatch.fnmatch(group.display_name, pattern)]
[ "def", "list", "(", "self", ",", "pattern", "=", "'*'", ")", ":", "if", "self", ".", "_group_dict", "is", "None", ":", "self", ".", "_group_dict", "=", "collections", ".", "OrderedDict", "(", "(", "group", ".", "id", ",", "group", ")", "for", "group", "in", "self", ".", "_client", ".", "list_groups", "(", ")", ")", "return", "[", "group", "for", "group", "in", "self", ".", "_group_dict", ".", "values", "(", ")", "if", "fnmatch", ".", "fnmatch", "(", "group", ".", "display_name", ",", "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 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
237,765
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_rows: The maximum number of groups to return. If None, return all. Returns: A pandas dataframe containing matching groups. """ data = [] for i, group in enumerate(self.list(pattern)): if max_rows is not None and i >= max_rows: break parent = self._group_dict.get(group.parent_id) parent_display_name = '' if parent is None else parent.display_name data.append([ group.id, group.display_name, group.parent_id, parent_display_name, group.is_cluster, group.filter]) return pandas.DataFrame(data, columns=self._DISPLAY_HEADERS)
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_rows: The maximum number of groups to return. If None, return all. Returns: A pandas dataframe containing matching groups. """ data = [] for i, group in enumerate(self.list(pattern)): if max_rows is not None and i >= max_rows: break parent = self._group_dict.get(group.parent_id) parent_display_name = '' if parent is None else parent.display_name data.append([ group.id, group.display_name, group.parent_id, parent_display_name, group.is_cluster, group.filter]) return pandas.DataFrame(data, columns=self._DISPLAY_HEADERS)
[ "def", "as_dataframe", "(", "self", ",", "pattern", "=", "'*'", ",", "max_rows", "=", "None", ")", ":", "data", "=", "[", "]", "for", "i", ",", "group", "in", "enumerate", "(", "self", ".", "list", "(", "pattern", ")", ")", ":", "if", "max_rows", "is", "not", "None", "and", "i", ">=", "max_rows", ":", "break", "parent", "=", "self", ".", "_group_dict", ".", "get", "(", "group", ".", "parent_id", ")", "parent_display_name", "=", "''", "if", "parent", "is", "None", "else", "parent", ".", "display_name", "data", ".", "append", "(", "[", "group", ".", "id", ",", "group", ".", "display_name", ",", "group", ".", "parent_id", ",", "parent_display_name", ",", "group", ".", "is_cluster", ",", "group", ".", "filter", "]", ")", "return", "pandas", ".", "DataFrame", "(", "data", ",", "columns", "=", "self", ".", "_DISPLAY_HEADERS", ")" ]
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, return all. Returns: A pandas dataframe containing matching groups.
[ "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
237,766
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 '$$'. Args: sql: the raw SQL statement with named placeholders. values: the user-supplied dictionary of name/value pairs to use for placeholder values. code: an array of referenced UDFs found during expansion. resolved_vars: a ref parameter for the variable references completely resolved so far. resolving_vars: a ref parameter for the variable(s) we are currently resolving; if we see a dependency again that is in this set we know we have a circular reference. Returns: The formatted SQL statement with placeholders replaced with their values. Raises: Exception if a placeholder was found in the SQL statement, but did not have a corresponding argument value. """ # Get the set of $var references in this SQL. dependencies = SqlStatement._get_dependencies(sql) for dependency in dependencies: # Now we check each dependency. If it is in complete - i.e., we have an expansion # for it already - we just continue. if dependency in resolved_vars: continue # Look it up in our resolution namespace dictionary. dep = datalab.utils.get_item(values, dependency) # If it is a SQL module, get the main/last query from the module, so users can refer # to $module. Useful especially if final query in module has no DEFINE QUERY <name> part. if isinstance(dep, types.ModuleType): dep = _utils.get_default_query_from_module(dep) # If we can't resolve the $name, give up. if dep is None: raise Exception("Unsatisfied dependency $%s" % dependency) # If it is a SqlStatement, it may have its own $ references in turn; check to make # sure we don't have circular references, and if not, recursively expand it and add # it to the set of complete dependencies. if isinstance(dep, SqlStatement): if resolving_vars is None: resolving_vars = [] elif dependency in resolving_vars: # Circular dependency raise Exception("Circular dependency in $%s" % dependency) resolving_vars.append(dependency) SqlStatement._find_recursive_dependencies(dep._sql, values, code, resolved_vars, resolving_vars) resolving_vars.pop() resolved_vars[dependency] = SqlStatement(dep._sql) else: resolved_vars[dependency] = dep
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 '$$'. Args: sql: the raw SQL statement with named placeholders. values: the user-supplied dictionary of name/value pairs to use for placeholder values. code: an array of referenced UDFs found during expansion. resolved_vars: a ref parameter for the variable references completely resolved so far. resolving_vars: a ref parameter for the variable(s) we are currently resolving; if we see a dependency again that is in this set we know we have a circular reference. Returns: The formatted SQL statement with placeholders replaced with their values. Raises: Exception if a placeholder was found in the SQL statement, but did not have a corresponding argument value. """ # Get the set of $var references in this SQL. dependencies = SqlStatement._get_dependencies(sql) for dependency in dependencies: # Now we check each dependency. If it is in complete - i.e., we have an expansion # for it already - we just continue. if dependency in resolved_vars: continue # Look it up in our resolution namespace dictionary. dep = datalab.utils.get_item(values, dependency) # If it is a SQL module, get the main/last query from the module, so users can refer # to $module. Useful especially if final query in module has no DEFINE QUERY <name> part. if isinstance(dep, types.ModuleType): dep = _utils.get_default_query_from_module(dep) # If we can't resolve the $name, give up. if dep is None: raise Exception("Unsatisfied dependency $%s" % dependency) # If it is a SqlStatement, it may have its own $ references in turn; check to make # sure we don't have circular references, and if not, recursively expand it and add # it to the set of complete dependencies. if isinstance(dep, SqlStatement): if resolving_vars is None: resolving_vars = [] elif dependency in resolving_vars: # Circular dependency raise Exception("Circular dependency in $%s" % dependency) resolving_vars.append(dependency) SqlStatement._find_recursive_dependencies(dep._sql, values, code, resolved_vars, resolving_vars) resolving_vars.pop() resolved_vars[dependency] = SqlStatement(dep._sql) else: resolved_vars[dependency] = dep
[ "def", "_find_recursive_dependencies", "(", "sql", ",", "values", ",", "code", ",", "resolved_vars", ",", "resolving_vars", "=", "None", ")", ":", "# Get the set of $var references in this SQL.", "dependencies", "=", "SqlStatement", ".", "_get_dependencies", "(", "sql", ")", "for", "dependency", "in", "dependencies", ":", "# Now we check each dependency. If it is in complete - i.e., we have an expansion", "# for it already - we just continue.", "if", "dependency", "in", "resolved_vars", ":", "continue", "# Look it up in our resolution namespace dictionary.", "dep", "=", "datalab", ".", "utils", ".", "get_item", "(", "values", ",", "dependency", ")", "# If it is a SQL module, get the main/last query from the module, so users can refer", "# to $module. Useful especially if final query in module has no DEFINE QUERY <name> part.", "if", "isinstance", "(", "dep", ",", "types", ".", "ModuleType", ")", ":", "dep", "=", "_utils", ".", "get_default_query_from_module", "(", "dep", ")", "# If we can't resolve the $name, give up.", "if", "dep", "is", "None", ":", "raise", "Exception", "(", "\"Unsatisfied dependency $%s\"", "%", "dependency", ")", "# If it is a SqlStatement, it may have its own $ references in turn; check to make", "# sure we don't have circular references, and if not, recursively expand it and add", "# it to the set of complete dependencies.", "if", "isinstance", "(", "dep", ",", "SqlStatement", ")", ":", "if", "resolving_vars", "is", "None", ":", "resolving_vars", "=", "[", "]", "elif", "dependency", "in", "resolving_vars", ":", "# Circular dependency", "raise", "Exception", "(", "\"Circular dependency in $%s\"", "%", "dependency", ")", "resolving_vars", ".", "append", "(", "dependency", ")", "SqlStatement", ".", "_find_recursive_dependencies", "(", "dep", ".", "_sql", ",", "values", ",", "code", ",", "resolved_vars", ",", "resolving_vars", ")", "resolving_vars", ".", "pop", "(", ")", "resolved_vars", "[", "dependency", "]", "=", "SqlStatement", "(", "dep", ".", "_sql", ")", "else", ":", "resolved_vars", "[", "dependency", "]", "=", "dep" ]
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-supplied dictionary of name/value pairs to use for placeholder values. code: an array of referenced UDFs found during expansion. resolved_vars: a ref parameter for the variable references completely resolved so far. resolving_vars: a ref parameter for the variable(s) we are currently resolving; if we see a dependency again that is in this set we know we have a circular reference. Returns: The formatted SQL statement with placeholders replaced with their values. Raises: Exception if a placeholder was found in the SQL statement, but did not have a corresponding argument value.
[ "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
237,767
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 dictionary of values to use in variable expansion. Returns: The resolved SQL text with variables expanded. Raises: Exception on failure. """ resolved_vars = {} code = [] SqlStatement._find_recursive_dependencies(sql, args, code=code, resolved_vars=resolved_vars) # Rebuild the SQL string, substituting just '$' for escaped $ occurrences, # variable references substituted with their values, or literal text copied # over as-is. parts = [] for (escape, placeholder, _, literal) in SqlStatement._get_tokens(sql): if escape: parts.append('$') elif placeholder: variable = placeholder[1:] try: value = resolved_vars[variable] except KeyError as e: raise Exception('Invalid sql. Unable to substitute $%s.' % e.args[0]) if isinstance(value, types.ModuleType): value = _utils.get_default_query_from_module(value) if isinstance(value, SqlStatement): sql = value.format(value._sql, resolved_vars) value = '(%s)' % sql elif '_repr_sql_' in dir(value): # pylint: disable=protected-access value = value._repr_sql_() elif isinstance(value, basestring): value = SqlStatement._escape_string(value) elif isinstance(value, list) or isinstance(value, tuple): if isinstance(value, tuple): value = list(value) expansion = '(' for v in value: if len(expansion) > 1: expansion += ', ' if isinstance(v, basestring): expansion += SqlStatement._escape_string(v) else: expansion += str(v) expansion += ')' value = expansion else: value = str(value) parts.append(value) elif literal: parts.append(literal) expanded = ''.join(parts) return expanded
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 dictionary of values to use in variable expansion. Returns: The resolved SQL text with variables expanded. Raises: Exception on failure. """ resolved_vars = {} code = [] SqlStatement._find_recursive_dependencies(sql, args, code=code, resolved_vars=resolved_vars) # Rebuild the SQL string, substituting just '$' for escaped $ occurrences, # variable references substituted with their values, or literal text copied # over as-is. parts = [] for (escape, placeholder, _, literal) in SqlStatement._get_tokens(sql): if escape: parts.append('$') elif placeholder: variable = placeholder[1:] try: value = resolved_vars[variable] except KeyError as e: raise Exception('Invalid sql. Unable to substitute $%s.' % e.args[0]) if isinstance(value, types.ModuleType): value = _utils.get_default_query_from_module(value) if isinstance(value, SqlStatement): sql = value.format(value._sql, resolved_vars) value = '(%s)' % sql elif '_repr_sql_' in dir(value): # pylint: disable=protected-access value = value._repr_sql_() elif isinstance(value, basestring): value = SqlStatement._escape_string(value) elif isinstance(value, list) or isinstance(value, tuple): if isinstance(value, tuple): value = list(value) expansion = '(' for v in value: if len(expansion) > 1: expansion += ', ' if isinstance(v, basestring): expansion += SqlStatement._escape_string(v) else: expansion += str(v) expansion += ')' value = expansion else: value = str(value) parts.append(value) elif literal: parts.append(literal) expanded = ''.join(parts) return expanded
[ "def", "format", "(", "sql", ",", "args", "=", "None", ")", ":", "resolved_vars", "=", "{", "}", "code", "=", "[", "]", "SqlStatement", ".", "_find_recursive_dependencies", "(", "sql", ",", "args", ",", "code", "=", "code", ",", "resolved_vars", "=", "resolved_vars", ")", "# Rebuild the SQL string, substituting just '$' for escaped $ occurrences,", "# variable references substituted with their values, or literal text copied", "# over as-is.", "parts", "=", "[", "]", "for", "(", "escape", ",", "placeholder", ",", "_", ",", "literal", ")", "in", "SqlStatement", ".", "_get_tokens", "(", "sql", ")", ":", "if", "escape", ":", "parts", ".", "append", "(", "'$'", ")", "elif", "placeholder", ":", "variable", "=", "placeholder", "[", "1", ":", "]", "try", ":", "value", "=", "resolved_vars", "[", "variable", "]", "except", "KeyError", "as", "e", ":", "raise", "Exception", "(", "'Invalid sql. Unable to substitute $%s.'", "%", "e", ".", "args", "[", "0", "]", ")", "if", "isinstance", "(", "value", ",", "types", ".", "ModuleType", ")", ":", "value", "=", "_utils", ".", "get_default_query_from_module", "(", "value", ")", "if", "isinstance", "(", "value", ",", "SqlStatement", ")", ":", "sql", "=", "value", ".", "format", "(", "value", ".", "_sql", ",", "resolved_vars", ")", "value", "=", "'(%s)'", "%", "sql", "elif", "'_repr_sql_'", "in", "dir", "(", "value", ")", ":", "# pylint: disable=protected-access", "value", "=", "value", ".", "_repr_sql_", "(", ")", "elif", "isinstance", "(", "value", ",", "basestring", ")", ":", "value", "=", "SqlStatement", ".", "_escape_string", "(", "value", ")", "elif", "isinstance", "(", "value", ",", "list", ")", "or", "isinstance", "(", "value", ",", "tuple", ")", ":", "if", "isinstance", "(", "value", ",", "tuple", ")", ":", "value", "=", "list", "(", "value", ")", "expansion", "=", "'('", "for", "v", "in", "value", ":", "if", "len", "(", "expansion", ")", ">", "1", ":", "expansion", "+=", "', '", "if", "isinstance", "(", "v", ",", "basestring", ")", ":", "expansion", "+=", "SqlStatement", ".", "_escape_string", "(", "v", ")", "else", ":", "expansion", "+=", "str", "(", "v", ")", "expansion", "+=", "')'", "value", "=", "expansion", "else", ":", "value", "=", "str", "(", "value", ")", "parts", ".", "append", "(", "value", ")", "elif", "literal", ":", "parts", ".", "append", "(", "literal", ")", "expanded", "=", "''", ".", "join", "(", "parts", ")", "return", "expanded" ]
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 expansion. Returns: The resolved SQL text with variables expanded. Raises: Exception on failure.
[ "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
237,768
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(variable) elif dollar: raise Exception('Invalid sql; $ with no following $ or identifier: %s.' % sql) return dependencies
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(variable) elif dollar: raise Exception('Invalid sql; $ with no following $ or identifier: %s.' % sql) return dependencies
[ "def", "_get_dependencies", "(", "sql", ")", ":", "dependencies", "=", "[", "]", "for", "(", "_", ",", "placeholder", ",", "dollar", ",", "_", ")", "in", "SqlStatement", ".", "_get_tokens", "(", "sql", ")", ":", "if", "placeholder", ":", "variable", "=", "placeholder", "[", "1", ":", "]", "if", "variable", "not", "in", "dependencies", ":", "dependencies", ".", "append", "(", "variable", ")", "elif", "dollar", ":", "raise", "Exception", "(", "'Invalid sql; $ with no following $ or identifier: %s.'", "%", "sql", ")", "return", "dependencies" ]
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
237,769
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) return _utils.handle_magic_line(line, cell, parser)
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) return _utils.handle_magic_line(line, cell, parser)
[ "def", "pymodule", "(", "line", ",", "cell", "=", "None", ")", ":", "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", ")", "return", "_utils", ".", "handle_magic_line", "(", "line", ",", "cell", ",", "parser", ")" ]
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
237,770
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 is d1 > d2. """ if d1.tzinfo is None or d1.tzinfo.utcoffset(d1) is None: d1 = d1.replace(tzinfo=pytz.UTC) if d2.tzinfo is None or d2.tzinfo.utcoffset(d2) is None: d2 = d2.replace(tzinfo=pytz.UTC) if d1 < d2: return -1 elif d1 > d2: return 1 return 0
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 is d1 > d2. """ if d1.tzinfo is None or d1.tzinfo.utcoffset(d1) is None: d1 = d1.replace(tzinfo=pytz.UTC) if d2.tzinfo is None or d2.tzinfo.utcoffset(d2) is None: d2 = d2.replace(tzinfo=pytz.UTC) if d1 < d2: return -1 elif d1 > d2: return 1 return 0
[ "def", "compare_datetimes", "(", "d1", ",", "d2", ")", ":", "if", "d1", ".", "tzinfo", "is", "None", "or", "d1", ".", "tzinfo", ".", "utcoffset", "(", "d1", ")", "is", "None", ":", "d1", "=", "d1", ".", "replace", "(", "tzinfo", "=", "pytz", ".", "UTC", ")", "if", "d2", ".", "tzinfo", "is", "None", "or", "d2", ".", "tzinfo", ".", "utcoffset", "(", "d2", ")", "is", "None", ":", "d2", "=", "d2", ".", "replace", "(", "tzinfo", "=", "pytz", ".", "UTC", ")", "if", "d1", "<", "d2", ":", "return", "-", "1", "elif", "d1", ">", "d2", ":", "return", "1", "return", "0" ]
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
237,771
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", ".", "getsockname", "(", ")", "s", ".", "close", "(", ")", "return", "port" ]
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
237,772
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 Exception: return False
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 Exception: return False
[ "def", "is_http_running_on", "(", "port", ")", ":", "try", ":", "conn", "=", "httplib", ".", "HTTPConnection", "(", "'127.0.0.1:'", "+", "str", "(", "port", ")", ")", "conn", ".", "connect", "(", ")", "conn", ".", "close", "(", ")", "return", "True", "except", "Exception", ":", "return", "False" ]
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
237,773
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]) except: config_file = os.path.join(get_config_dir(), 'config.json') config = {} if os.path.exists(config_file): with open(config_file) as f: config = json.loads(f.read()) config['project_id'] = project_id with open(config_file, 'w') as f: f.write(json.dumps(config))
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]) except: config_file = os.path.join(get_config_dir(), 'config.json') config = {} if os.path.exists(config_file): with open(config_file) as f: config = json.loads(f.read()) config['project_id'] = project_id with open(config_file, 'w') as f: f.write(json.dumps(config))
[ "def", "save_project_id", "(", "project_id", ")", ":", "# Try gcloud first. If gcloud fails (probably because it does not exist), then", "# write to a config file.", "try", ":", "subprocess", ".", "call", "(", "[", "'gcloud'", ",", "'config'", ",", "'set'", ",", "'project'", ",", "project_id", "]", ")", "except", ":", "config_file", "=", "os", ".", "path", ".", "join", "(", "get_config_dir", "(", ")", ",", "'config.json'", ")", "config", "=", "{", "}", "if", "os", ".", "path", ".", "exists", "(", "config_file", ")", ":", "with", "open", "(", "config_file", ")", "as", "f", ":", "config", "=", "json", ".", "loads", "(", "f", ".", "read", "(", ")", ")", "config", "[", "'project_id'", "]", "=", "project_id", "with", "open", "(", "config_file", ",", "'w'", ")", "as", "f", ":", "f", ".", "write", "(", "json", ".", "dumps", "(", "config", ")", ")" ]
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
237,774
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)'], stdout=subprocess.PIPE) stdout, _ = proc.communicate() value = stdout.strip() if proc.poll() == 0 and value: if isinstance(value, six.string_types): return value else: # Hope it's a utf-8 string encoded in bytes. Otherwise an exception will # be thrown and config.json will be checked. return value.decode() except: pass config_file = os.path.join(get_config_dir(), 'config.json') if os.path.exists(config_file): with open(config_file) as f: config = json.loads(f.read()) if 'project_id' in config and config['project_id']: return str(config['project_id']) if os.getenv('PROJECT_ID') is not None: return os.getenv('PROJECT_ID') return None
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)'], stdout=subprocess.PIPE) stdout, _ = proc.communicate() value = stdout.strip() if proc.poll() == 0 and value: if isinstance(value, six.string_types): return value else: # Hope it's a utf-8 string encoded in bytes. Otherwise an exception will # be thrown and config.json will be checked. return value.decode() except: pass config_file = os.path.join(get_config_dir(), 'config.json') if os.path.exists(config_file): with open(config_file) as f: config = json.loads(f.read()) if 'project_id' in config and config['project_id']: return str(config['project_id']) if os.getenv('PROJECT_ID') is not None: return os.getenv('PROJECT_ID') return None
[ "def", "get_default_project_id", "(", ")", ":", "# Try getting default project id from gcloud. If it fails try config.json.", "try", ":", "proc", "=", "subprocess", ".", "Popen", "(", "[", "'gcloud'", ",", "'config'", ",", "'list'", ",", "'--format'", ",", "'value(core.project)'", "]", ",", "stdout", "=", "subprocess", ".", "PIPE", ")", "stdout", ",", "_", "=", "proc", ".", "communicate", "(", ")", "value", "=", "stdout", ".", "strip", "(", ")", "if", "proc", ".", "poll", "(", ")", "==", "0", "and", "value", ":", "if", "isinstance", "(", "value", ",", "six", ".", "string_types", ")", ":", "return", "value", "else", ":", "# Hope it's a utf-8 string encoded in bytes. Otherwise an exception will", "# be thrown and config.json will be checked.", "return", "value", ".", "decode", "(", ")", "except", ":", "pass", "config_file", "=", "os", ".", "path", ".", "join", "(", "get_config_dir", "(", ")", ",", "'config.json'", ")", "if", "os", ".", "path", ".", "exists", "(", "config_file", ")", ":", "with", "open", "(", "config_file", ")", "as", "f", ":", "config", "=", "json", ".", "loads", "(", "f", ".", "read", "(", ")", ")", "if", "'project_id'", "in", "config", "and", "config", "[", "'project_id'", "]", ":", "return", "str", "(", "config", "[", "'project_id'", "]", ")", "if", "os", ".", "getenv", "(", "'PROJECT_ID'", ")", "is", "not", "None", ":", "return", "os", ".", "getenv", "(", "'PROJECT_ID'", ")", "return", "None" ]
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
237,775
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_context = google.datalab.Context.default() config = {} for key in global_default_context.config: config[key] = global_default_context.config[key] billing_tier_arg = args.get('billing', None) if billing_tier_arg: config['bigquery_billing_tier'] = billing_tier_arg return google.datalab.Context( project_id=global_default_context.project_id, credentials=global_default_context.credentials, config=config)
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_context = google.datalab.Context.default() config = {} for key in global_default_context.config: config[key] = global_default_context.config[key] billing_tier_arg = args.get('billing', None) if billing_tier_arg: config['bigquery_billing_tier'] = billing_tier_arg return google.datalab.Context( project_id=global_default_context.project_id, credentials=global_default_context.credentials, config=config)
[ "def", "_construct_context_for_args", "(", "args", ")", ":", "global_default_context", "=", "google", ".", "datalab", ".", "Context", ".", "default", "(", ")", "config", "=", "{", "}", "for", "key", "in", "global_default_context", ".", "config", ":", "config", "[", "key", "]", "=", "global_default_context", ".", "config", "[", "key", "]", "billing_tier_arg", "=", "args", ".", "get", "(", "'billing'", ",", "None", ")", "if", "billing_tier_arg", ":", "config", "[", "'bigquery_billing_tier'", "]", "=", "billing_tier_arg", "return", "google", ".", "datalab", ".", "Context", "(", "project_id", "=", "global_default_context", ".", "project_id", ",", "credentials", "=", "global_default_context", ".", "credentials", ",", "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
237,776
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): return string if six.PY3: return string.decode(encoding) raise ValueError('Unsupported type %s' % str(type(string)))
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): return string if six.PY3: return string.decode(encoding) raise ValueError('Unsupported type %s' % str(type(string)))
[ "def", "python_portable_string", "(", "string", ",", "encoding", "=", "'utf-8'", ")", ":", "if", "isinstance", "(", "string", ",", "six", ".", "string_types", ")", ":", "return", "string", "if", "six", ".", "PY3", ":", "return", "string", ".", "decode", "(", "encoding", ")", "raise", "ValueError", "(", "'Unsupported type %s'", "%", "str", "(", "type", "(", "string", ")", ")", ")" ]
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
237,777
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 datalab.utils.commands.render_dictionary(data, ['Bucket', 'Created'])
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 datalab.utils.commands.render_dictionary(data, ['Bucket', 'Created'])
[ "def", "_storage_list_buckets", "(", "project", ",", "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", "datalab", ".", "utils", ".", "commands", ".", "render_dictionary", "(", "data", ",", "[", "'Bucket'", ",", "'Created'", "]", ")" ]
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
237,778
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_get_keys(bucket, pattern)] return datalab.utils.commands.render_dictionary(data, ['Name', 'Type', 'Size', 'Updated'])
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_get_keys(bucket, pattern)] return datalab.utils.commands.render_dictionary(data, ['Name', 'Type', 'Size', 'Updated'])
[ "def", "_storage_list_keys", "(", "bucket", ",", "pattern", ")", ":", "data", "=", "[", "{", "'Name'", ":", "item", ".", "metadata", ".", "name", ",", "'Type'", ":", "item", ".", "metadata", ".", "content_type", ",", "'Size'", ":", "item", ".", "metadata", ".", "size", ",", "'Updated'", ":", "item", ".", "metadata", ".", "updated_on", "}", "for", "item", "in", "_storage_get_keys", "(", "bucket", ",", "pattern", ")", "]", "return", "datalab", ".", "utils", ".", "commands", ".", "render_dictionary", "(", "data", ",", "[", "'Name'", ",", "'Type'", ",", "'Size'", ",", "'Updated'", "]", ")" ]
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
237,779
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 retrieval. Returns: A parsed result object. Raises: Exception if there is an error performing the operation. """ url = Api._ENDPOINT +\ (Api._TABLES_PATH % (dataset_name.project_id, dataset_name.dataset_id, '', '')) args = {} if max_results != 0: args['maxResults'] = max_results if page_token is not None: args['pageToken'] = page_token return google.datalab.utils.Http.request(url, args=args, credentials=self.credentials)
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 retrieval. Returns: A parsed result object. Raises: Exception if there is an error performing the operation. """ url = Api._ENDPOINT +\ (Api._TABLES_PATH % (dataset_name.project_id, dataset_name.dataset_id, '', '')) args = {} if max_results != 0: args['maxResults'] = max_results if page_token is not None: args['pageToken'] = page_token return google.datalab.utils.Http.request(url, args=args, credentials=self.credentials)
[ "def", "tables_list", "(", "self", ",", "dataset_name", ",", "max_results", "=", "0", ",", "page_token", "=", "None", ")", ":", "url", "=", "Api", ".", "_ENDPOINT", "+", "(", "Api", ".", "_TABLES_PATH", "%", "(", "dataset_name", ".", "project_id", ",", "dataset_name", ".", "dataset_id", ",", "''", ",", "''", ")", ")", "args", "=", "{", "}", "if", "max_results", "!=", "0", ":", "args", "[", "'maxResults'", "]", "=", "max_results", "if", "page_token", "is", "not", "None", ":", "args", "[", "'pageToken'", "]", "=", "page_token", "return", "google", ".", "datalab", ".", "utils", ".", "Http", ".", "request", "(", "url", ",", "args", "=", "args", ",", "credentials", "=", "self", ".", "credentials", ")" ]
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 if there is an error performing the operation.
[ "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
237,780
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. As tf layer's sum combiner is used, the weights can be just ones. Tokens are not summed together here. """ return tf.SparseTensor( indices=x.indices, values=tf.to_float(tf.ones_like(x.values)), dense_shape=x.dense_shape) return _bow(x)
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. As tf layer's sum combiner is used, the weights can be just ones. Tokens are not summed together here. """ return tf.SparseTensor( indices=x.indices, values=tf.to_float(tf.ones_like(x.values)), dense_shape=x.dense_shape) return _bow(x)
[ "def", "_bag_of_words", "(", "x", ")", ":", "def", "_bow", "(", "x", ")", ":", "\"\"\"Comptue BOW weights.\n\n As tf layer's sum combiner is used, the weights can be just ones. Tokens are\n not summed together here.\n \"\"\"", "return", "tf", ".", "SparseTensor", "(", "indices", "=", "x", ".", "indices", ",", "values", "=", "tf", ".", "to_float", "(", "tf", ".", "ones_like", "(", "x", ".", "values", ")", ")", ",", "dense_shape", "=", "x", ".", "dense_shape", ")", "return", "_bow", "(", "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
237,781
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 keep_target and col['name'] == target_name: continue # Note that numerical key columns do not have a stats entry, hence the use # of get(col['name'], {}) csv_header.append(col['name']) if col['type'].lower() == INTEGER_SCHEMA: dtype = tf.int64 default = int(stats['column_stats'].get(col['name'], {}).get('mean', 0)) elif col['type'].lower() == FLOAT_SCHEMA: dtype = tf.float32 default = float(stats['column_stats'].get(col['name'], {}).get('mean', 0.0)) else: dtype = tf.string default = '' record_defaults.append(tf.constant([default], dtype=dtype)) return csv_header, record_defaults
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 keep_target and col['name'] == target_name: continue # Note that numerical key columns do not have a stats entry, hence the use # of get(col['name'], {}) csv_header.append(col['name']) if col['type'].lower() == INTEGER_SCHEMA: dtype = tf.int64 default = int(stats['column_stats'].get(col['name'], {}).get('mean', 0)) elif col['type'].lower() == FLOAT_SCHEMA: dtype = tf.float32 default = float(stats['column_stats'].get(col['name'], {}).get('mean', 0.0)) else: dtype = tf.string default = '' record_defaults.append(tf.constant([default], dtype=dtype)) return csv_header, record_defaults
[ "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 find target transform'", ")", "csv_header", "=", "[", "]", "record_defaults", "=", "[", "]", "for", "col", "in", "schema", ":", "if", "not", "keep_target", "and", "col", "[", "'name'", "]", "==", "target_name", ":", "continue", "# Note that numerical key columns do not have a stats entry, hence the use", "# of get(col['name'], {})", "csv_header", ".", "append", "(", "col", "[", "'name'", "]", ")", "if", "col", "[", "'type'", "]", ".", "lower", "(", ")", "==", "INTEGER_SCHEMA", ":", "dtype", "=", "tf", ".", "int64", "default", "=", "int", "(", "stats", "[", "'column_stats'", "]", ".", "get", "(", "col", "[", "'name'", "]", ",", "{", "}", ")", ".", "get", "(", "'mean'", ",", "0", ")", ")", "elif", "col", "[", "'type'", "]", ".", "lower", "(", ")", "==", "FLOAT_SCHEMA", ":", "dtype", "=", "tf", ".", "float32", "default", "=", "float", "(", "stats", "[", "'column_stats'", "]", ".", "get", "(", "col", "[", "'name'", "]", ",", "{", "}", ")", ".", "get", "(", "'mean'", ",", "0.0", ")", ")", "else", ":", "dtype", "=", "tf", ".", "string", "default", "=", "''", "record_defaults", ".", "append", "(", "tf", ".", "constant", "(", "[", "default", "]", ",", "dtype", "=", "dtype", ")", ")", "return", "csv_header", ",", "record_defaults" ]
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
237,782
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 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. """ csv_header, record_defaults = csv_header_and_defaults(features, schema, stats, keep_target) placeholder = tf.placeholder(dtype=tf.string, shape=(None,), name='csv_input_placeholder') tensors = tf.decode_csv(placeholder, record_defaults) raw_features = dict(zip(csv_header, tensors)) transform_fn = make_preprocessing_fn(analysis_path, features, keep_target) transformed_tensors = transform_fn(raw_features) transformed_features = {} # Expand the dims of non-sparse tensors for k, v in six.iteritems(transformed_tensors): if isinstance(v, tf.Tensor) and v.get_shape().ndims == 1: transformed_features[k] = tf.expand_dims(v, -1) else: transformed_features[k] = v return input_fn_utils.InputFnOps( transformed_features, None, {"csv_example": placeholder})
python
def build_csv_serving_tensors_for_transform_step(analysis_path, features, schema, stats, keep_target): """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. """ csv_header, record_defaults = csv_header_and_defaults(features, schema, stats, keep_target) placeholder = tf.placeholder(dtype=tf.string, shape=(None,), name='csv_input_placeholder') tensors = tf.decode_csv(placeholder, record_defaults) raw_features = dict(zip(csv_header, tensors)) transform_fn = make_preprocessing_fn(analysis_path, features, keep_target) transformed_tensors = transform_fn(raw_features) transformed_features = {} # Expand the dims of non-sparse tensors for k, v in six.iteritems(transformed_tensors): if isinstance(v, tf.Tensor) and v.get_shape().ndims == 1: transformed_features[k] = tf.expand_dims(v, -1) else: transformed_features[k] = v return input_fn_utils.InputFnOps( transformed_features, None, {"csv_example": placeholder})
[ "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", ",", "keep_target", ")", "placeholder", "=", "tf", ".", "placeholder", "(", "dtype", "=", "tf", ".", "string", ",", "shape", "=", "(", "None", ",", ")", ",", "name", "=", "'csv_input_placeholder'", ")", "tensors", "=", "tf", ".", "decode_csv", "(", "placeholder", ",", "record_defaults", ")", "raw_features", "=", "dict", "(", "zip", "(", "csv_header", ",", "tensors", ")", ")", "transform_fn", "=", "make_preprocessing_fn", "(", "analysis_path", ",", "features", ",", "keep_target", ")", "transformed_tensors", "=", "transform_fn", "(", "raw_features", ")", "transformed_features", "=", "{", "}", "# Expand the dims of non-sparse tensors", "for", "k", ",", "v", "in", "six", ".", "iteritems", "(", "transformed_tensors", ")", ":", "if", "isinstance", "(", "v", ",", "tf", ".", "Tensor", ")", "and", "v", ".", "get_shape", "(", ")", ".", "ndims", "==", "1", ":", "transformed_features", "[", "k", "]", "=", "tf", ".", "expand_dims", "(", "v", ",", "-", "1", ")", "else", ":", "transformed_features", "[", "k", "]", "=", "v", "return", "input_fn_utils", ".", "InputFnOps", "(", "transformed_features", ",", "None", ",", "{", "\"csv_example\"", ":", "placeholder", "}", ")" ]
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
237,783
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 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 long image embedding. """ transformed_features, _, placeholder_dict = build_csv_serving_tensors_for_transform_step( analysis_path=analysis_path, features=features, schema=schema, stats=stats, keep_target=keep_target) transformed_features = image_feature_engineering( features=features, feature_tensors_dict=transformed_features) return input_fn_utils.InputFnOps( transformed_features, None, placeholder_dict)
python
def build_csv_serving_tensors_for_training_step(analysis_path, features, schema, stats, keep_target): """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 long image embedding. """ transformed_features, _, placeholder_dict = build_csv_serving_tensors_for_transform_step( analysis_path=analysis_path, features=features, schema=schema, stats=stats, keep_target=keep_target) transformed_features = image_feature_engineering( features=features, feature_tensors_dict=transformed_features) return input_fn_utils.InputFnOps( transformed_features, None, placeholder_dict)
[ "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", "(", "analysis_path", "=", "analysis_path", ",", "features", "=", "features", ",", "schema", "=", "schema", ",", "stats", "=", "stats", ",", "keep_target", "=", "keep_target", ")", "transformed_features", "=", "image_feature_engineering", "(", "features", "=", "features", ",", "feature_tensors_dict", "=", "transformed_features", ")", "return", "input_fn_utils", ".", "InputFnOps", "(", "transformed_features", ",", "None", ",", "placeholder_dict", ")" ]
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 long image embedding.
[ "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
237,784
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, training_batch_size, num_epochs=None, randomize_input=False, min_after_dequeue=1, reader_num_threads=1, allow_smaller_final_batch=True): """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 size to use. num_epochs: numer of epochs to read from the files. Use None to read forever. randomize_input: If true, the input rows are read out of order. This randomness is limited by the min_after_dequeue value. min_after_dequeue: Minimum number elements in the reading queue after a dequeue, used to ensure a level of mixing of elements. Only used if randomize_input is True. reader_num_threads: The number of threads enqueuing data. allow_smaller_final_batch: If false, fractional batches at the end of training or evaluation are not used. Returns: An input_fn suitable for training that reads raw csv training data and applies transforms. """ def raw_training_input_fn(): """Training input function that reads raw data and applies transforms.""" if isinstance(raw_data_file_pattern, six.string_types): filepath_list = [raw_data_file_pattern] else: filepath_list = raw_data_file_pattern files = [] for path in filepath_list: files.extend(file_io.get_matching_files(path)) filename_queue = tf.train.string_input_producer( files, num_epochs=num_epochs, shuffle=randomize_input) csv_id, csv_lines = tf.TextLineReader().read_up_to(filename_queue, training_batch_size) queue_capacity = (reader_num_threads + 3) * training_batch_size + min_after_dequeue if randomize_input: _, batch_csv_lines = tf.train.shuffle_batch( tensors=[csv_id, csv_lines], batch_size=training_batch_size, capacity=queue_capacity, min_after_dequeue=min_after_dequeue, enqueue_many=True, num_threads=reader_num_threads, allow_smaller_final_batch=allow_smaller_final_batch) else: _, batch_csv_lines = tf.train.batch( tensors=[csv_id, csv_lines], batch_size=training_batch_size, capacity=queue_capacity, enqueue_many=True, num_threads=reader_num_threads, allow_smaller_final_batch=allow_smaller_final_batch) csv_header, record_defaults = csv_header_and_defaults(features, schema, stats, keep_target=True) parsed_tensors = tf.decode_csv(batch_csv_lines, record_defaults, name='csv_to_tensors') raw_features = dict(zip(csv_header, parsed_tensors)) transform_fn = make_preprocessing_fn(analysis_output_dir, features, keep_target=True) transformed_tensors = transform_fn(raw_features) # Expand the dims of non-sparse tensors. This is needed by tf.learn. transformed_features = {} for k, v in six.iteritems(transformed_tensors): if isinstance(v, tf.Tensor) and v.get_shape().ndims == 1: transformed_features[k] = tf.expand_dims(v, -1) else: transformed_features[k] = v # image_feature_engineering does not need to be called as images are not # supported in raw csv for training. # Remove the target tensor, and return it directly target_name = get_target_name(features) if not target_name or target_name not in transformed_features: raise ValueError('Cannot find target transform in features') transformed_target = transformed_features.pop(target_name) return transformed_features, transformed_target return raw_training_input_fn
python
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_dequeue=1, reader_num_threads=1, allow_smaller_final_batch=True): """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 size to use. num_epochs: numer of epochs to read from the files. Use None to read forever. randomize_input: If true, the input rows are read out of order. This randomness is limited by the min_after_dequeue value. min_after_dequeue: Minimum number elements in the reading queue after a dequeue, used to ensure a level of mixing of elements. Only used if randomize_input is True. reader_num_threads: The number of threads enqueuing data. allow_smaller_final_batch: If false, fractional batches at the end of training or evaluation are not used. Returns: An input_fn suitable for training that reads raw csv training data and applies transforms. """ def raw_training_input_fn(): """Training input function that reads raw data and applies transforms.""" if isinstance(raw_data_file_pattern, six.string_types): filepath_list = [raw_data_file_pattern] else: filepath_list = raw_data_file_pattern files = [] for path in filepath_list: files.extend(file_io.get_matching_files(path)) filename_queue = tf.train.string_input_producer( files, num_epochs=num_epochs, shuffle=randomize_input) csv_id, csv_lines = tf.TextLineReader().read_up_to(filename_queue, training_batch_size) queue_capacity = (reader_num_threads + 3) * training_batch_size + min_after_dequeue if randomize_input: _, batch_csv_lines = tf.train.shuffle_batch( tensors=[csv_id, csv_lines], batch_size=training_batch_size, capacity=queue_capacity, min_after_dequeue=min_after_dequeue, enqueue_many=True, num_threads=reader_num_threads, allow_smaller_final_batch=allow_smaller_final_batch) else: _, batch_csv_lines = tf.train.batch( tensors=[csv_id, csv_lines], batch_size=training_batch_size, capacity=queue_capacity, enqueue_many=True, num_threads=reader_num_threads, allow_smaller_final_batch=allow_smaller_final_batch) csv_header, record_defaults = csv_header_and_defaults(features, schema, stats, keep_target=True) parsed_tensors = tf.decode_csv(batch_csv_lines, record_defaults, name='csv_to_tensors') raw_features = dict(zip(csv_header, parsed_tensors)) transform_fn = make_preprocessing_fn(analysis_output_dir, features, keep_target=True) transformed_tensors = transform_fn(raw_features) # Expand the dims of non-sparse tensors. This is needed by tf.learn. transformed_features = {} for k, v in six.iteritems(transformed_tensors): if isinstance(v, tf.Tensor) and v.get_shape().ndims == 1: transformed_features[k] = tf.expand_dims(v, -1) else: transformed_features[k] = v # image_feature_engineering does not need to be called as images are not # supported in raw csv for training. # Remove the target tensor, and return it directly target_name = get_target_name(features) if not target_name or target_name not in transformed_features: raise ValueError('Cannot find target transform in features') transformed_target = transformed_features.pop(target_name) return transformed_features, transformed_target return raw_training_input_fn
[ "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_dequeue", "=", "1", ",", "reader_num_threads", "=", "1", ",", "allow_smaller_final_batch", "=", "True", ")", ":", "def", "raw_training_input_fn", "(", ")", ":", "\"\"\"Training input function that reads raw data and applies transforms.\"\"\"", "if", "isinstance", "(", "raw_data_file_pattern", ",", "six", ".", "string_types", ")", ":", "filepath_list", "=", "[", "raw_data_file_pattern", "]", "else", ":", "filepath_list", "=", "raw_data_file_pattern", "files", "=", "[", "]", "for", "path", "in", "filepath_list", ":", "files", ".", "extend", "(", "file_io", ".", "get_matching_files", "(", "path", ")", ")", "filename_queue", "=", "tf", ".", "train", ".", "string_input_producer", "(", "files", ",", "num_epochs", "=", "num_epochs", ",", "shuffle", "=", "randomize_input", ")", "csv_id", ",", "csv_lines", "=", "tf", ".", "TextLineReader", "(", ")", ".", "read_up_to", "(", "filename_queue", ",", "training_batch_size", ")", "queue_capacity", "=", "(", "reader_num_threads", "+", "3", ")", "*", "training_batch_size", "+", "min_after_dequeue", "if", "randomize_input", ":", "_", ",", "batch_csv_lines", "=", "tf", ".", "train", ".", "shuffle_batch", "(", "tensors", "=", "[", "csv_id", ",", "csv_lines", "]", ",", "batch_size", "=", "training_batch_size", ",", "capacity", "=", "queue_capacity", ",", "min_after_dequeue", "=", "min_after_dequeue", ",", "enqueue_many", "=", "True", ",", "num_threads", "=", "reader_num_threads", ",", "allow_smaller_final_batch", "=", "allow_smaller_final_batch", ")", "else", ":", "_", ",", "batch_csv_lines", "=", "tf", ".", "train", ".", "batch", "(", "tensors", "=", "[", "csv_id", ",", "csv_lines", "]", ",", "batch_size", "=", "training_batch_size", ",", "capacity", "=", "queue_capacity", ",", "enqueue_many", "=", "True", ",", "num_threads", "=", "reader_num_threads", ",", "allow_smaller_final_batch", "=", "allow_smaller_final_batch", ")", "csv_header", ",", "record_defaults", "=", "csv_header_and_defaults", "(", "features", ",", "schema", ",", "stats", ",", "keep_target", "=", "True", ")", "parsed_tensors", "=", "tf", ".", "decode_csv", "(", "batch_csv_lines", ",", "record_defaults", ",", "name", "=", "'csv_to_tensors'", ")", "raw_features", "=", "dict", "(", "zip", "(", "csv_header", ",", "parsed_tensors", ")", ")", "transform_fn", "=", "make_preprocessing_fn", "(", "analysis_output_dir", ",", "features", ",", "keep_target", "=", "True", ")", "transformed_tensors", "=", "transform_fn", "(", "raw_features", ")", "# Expand the dims of non-sparse tensors. This is needed by tf.learn.", "transformed_features", "=", "{", "}", "for", "k", ",", "v", "in", "six", ".", "iteritems", "(", "transformed_tensors", ")", ":", "if", "isinstance", "(", "v", ",", "tf", ".", "Tensor", ")", "and", "v", ".", "get_shape", "(", ")", ".", "ndims", "==", "1", ":", "transformed_features", "[", "k", "]", "=", "tf", ".", "expand_dims", "(", "v", ",", "-", "1", ")", "else", ":", "transformed_features", "[", "k", "]", "=", "v", "# image_feature_engineering does not need to be called as images are not", "# supported in raw csv for training.", "# Remove the target tensor, and return it directly", "target_name", "=", "get_target_name", "(", "features", ")", "if", "not", "target_name", "or", "target_name", "not", "in", "transformed_features", ":", "raise", "ValueError", "(", "'Cannot find target transform in features'", ")", "transformed_target", "=", "transformed_features", ".", "pop", "(", "target_name", ")", "return", "transformed_features", ",", "transformed_target", "return", "raw_training_input_fn" ]
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 size to use. num_epochs: numer of epochs to read from the files. Use None to read forever. randomize_input: If true, the input rows are read out of order. This randomness is limited by the min_after_dequeue value. min_after_dequeue: Minimum number elements in the reading queue after a dequeue, used to ensure a level of mixing of elements. Only used if randomize_input is True. reader_num_threads: The number of threads enqueuing data. allow_smaller_final_batch: If false, fractional batches at the end of training or evaluation are not used. Returns: An input_fn suitable for training that reads raw csv training data and applies transforms.
[ "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
237,785
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_batch_size, num_epochs=None, randomize_input=False, min_after_dequeue=1, reader_num_threads=1, allow_smaller_final_batch=True): """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: numer of epochs to read from the files. Use None to read forever. randomize_input: If true, the input rows are read out of order. This randomness is limited by the min_after_dequeue value. min_after_dequeue: Minimum number elements in the reading queue after a dequeue, used to ensure a level of mixing of elements. Only used if randomize_input is True. reader_num_threads: The number of threads enqueuing data. allow_smaller_final_batch: If false, fractional batches at the end of training or evaluation are not used. Returns: An input_fn suitable for training that reads transformed data in tf record files of tf.example. """ def transformed_training_input_fn(): """Training input function that reads transformed data.""" if isinstance(raw_data_file_pattern, six.string_types): filepath_list = [raw_data_file_pattern] else: filepath_list = raw_data_file_pattern files = [] for path in filepath_list: files.extend(file_io.get_matching_files(path)) filename_queue = tf.train.string_input_producer( files, num_epochs=num_epochs, shuffle=randomize_input) options = tf.python_io.TFRecordOptions( compression_type=tf.python_io.TFRecordCompressionType.GZIP) ex_id, ex_str = tf.TFRecordReader(options=options).read_up_to( filename_queue, training_batch_size) queue_capacity = (reader_num_threads + 3) * training_batch_size + min_after_dequeue if randomize_input: _, batch_ex_str = tf.train.shuffle_batch( tensors=[ex_id, ex_str], batch_size=training_batch_size, capacity=queue_capacity, min_after_dequeue=min_after_dequeue, enqueue_many=True, num_threads=reader_num_threads, allow_smaller_final_batch=allow_smaller_final_batch) else: _, batch_ex_str = tf.train.batch( tensors=[ex_id, ex_str], batch_size=training_batch_size, capacity=queue_capacity, enqueue_many=True, num_threads=reader_num_threads, allow_smaller_final_batch=allow_smaller_final_batch) feature_spec = {} feature_info = get_transformed_feature_info(features, schema) for name, info in six.iteritems(feature_info): if info['size'] is None: feature_spec[name] = tf.VarLenFeature(dtype=info['dtype']) else: feature_spec[name] = tf.FixedLenFeature(shape=[info['size']], dtype=info['dtype']) parsed_tensors = tf.parse_example(batch_ex_str, feature_spec) # Expand the dims of non-sparse tensors. This is needed by tf.learn. transformed_features = {} for k, v in six.iteritems(parsed_tensors): if isinstance(v, tf.Tensor) and v.get_shape().ndims == 1: transformed_features[k] = tf.expand_dims(v, -1) else: # Sparse tensor transformed_features[k] = v transformed_features = image_feature_engineering( features=features, feature_tensors_dict=transformed_features) # Remove the target tensor, and return it directly target_name = get_target_name(features) if not target_name or target_name not in transformed_features: raise ValueError('Cannot find target transform in features') transformed_target = transformed_features.pop(target_name) return transformed_features, transformed_target return transformed_training_input_fn
python
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=1, reader_num_threads=1, allow_smaller_final_batch=True): """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: numer of epochs to read from the files. Use None to read forever. randomize_input: If true, the input rows are read out of order. This randomness is limited by the min_after_dequeue value. min_after_dequeue: Minimum number elements in the reading queue after a dequeue, used to ensure a level of mixing of elements. Only used if randomize_input is True. reader_num_threads: The number of threads enqueuing data. allow_smaller_final_batch: If false, fractional batches at the end of training or evaluation are not used. Returns: An input_fn suitable for training that reads transformed data in tf record files of tf.example. """ def transformed_training_input_fn(): """Training input function that reads transformed data.""" if isinstance(raw_data_file_pattern, six.string_types): filepath_list = [raw_data_file_pattern] else: filepath_list = raw_data_file_pattern files = [] for path in filepath_list: files.extend(file_io.get_matching_files(path)) filename_queue = tf.train.string_input_producer( files, num_epochs=num_epochs, shuffle=randomize_input) options = tf.python_io.TFRecordOptions( compression_type=tf.python_io.TFRecordCompressionType.GZIP) ex_id, ex_str = tf.TFRecordReader(options=options).read_up_to( filename_queue, training_batch_size) queue_capacity = (reader_num_threads + 3) * training_batch_size + min_after_dequeue if randomize_input: _, batch_ex_str = tf.train.shuffle_batch( tensors=[ex_id, ex_str], batch_size=training_batch_size, capacity=queue_capacity, min_after_dequeue=min_after_dequeue, enqueue_many=True, num_threads=reader_num_threads, allow_smaller_final_batch=allow_smaller_final_batch) else: _, batch_ex_str = tf.train.batch( tensors=[ex_id, ex_str], batch_size=training_batch_size, capacity=queue_capacity, enqueue_many=True, num_threads=reader_num_threads, allow_smaller_final_batch=allow_smaller_final_batch) feature_spec = {} feature_info = get_transformed_feature_info(features, schema) for name, info in six.iteritems(feature_info): if info['size'] is None: feature_spec[name] = tf.VarLenFeature(dtype=info['dtype']) else: feature_spec[name] = tf.FixedLenFeature(shape=[info['size']], dtype=info['dtype']) parsed_tensors = tf.parse_example(batch_ex_str, feature_spec) # Expand the dims of non-sparse tensors. This is needed by tf.learn. transformed_features = {} for k, v in six.iteritems(parsed_tensors): if isinstance(v, tf.Tensor) and v.get_shape().ndims == 1: transformed_features[k] = tf.expand_dims(v, -1) else: # Sparse tensor transformed_features[k] = v transformed_features = image_feature_engineering( features=features, feature_tensors_dict=transformed_features) # Remove the target tensor, and return it directly target_name = get_target_name(features) if not target_name or target_name not in transformed_features: raise ValueError('Cannot find target transform in features') transformed_target = transformed_features.pop(target_name) return transformed_features, transformed_target return transformed_training_input_fn
[ "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", "=", "1", ",", "reader_num_threads", "=", "1", ",", "allow_smaller_final_batch", "=", "True", ")", ":", "def", "transformed_training_input_fn", "(", ")", ":", "\"\"\"Training input function that reads transformed data.\"\"\"", "if", "isinstance", "(", "raw_data_file_pattern", ",", "six", ".", "string_types", ")", ":", "filepath_list", "=", "[", "raw_data_file_pattern", "]", "else", ":", "filepath_list", "=", "raw_data_file_pattern", "files", "=", "[", "]", "for", "path", "in", "filepath_list", ":", "files", ".", "extend", "(", "file_io", ".", "get_matching_files", "(", "path", ")", ")", "filename_queue", "=", "tf", ".", "train", ".", "string_input_producer", "(", "files", ",", "num_epochs", "=", "num_epochs", ",", "shuffle", "=", "randomize_input", ")", "options", "=", "tf", ".", "python_io", ".", "TFRecordOptions", "(", "compression_type", "=", "tf", ".", "python_io", ".", "TFRecordCompressionType", ".", "GZIP", ")", "ex_id", ",", "ex_str", "=", "tf", ".", "TFRecordReader", "(", "options", "=", "options", ")", ".", "read_up_to", "(", "filename_queue", ",", "training_batch_size", ")", "queue_capacity", "=", "(", "reader_num_threads", "+", "3", ")", "*", "training_batch_size", "+", "min_after_dequeue", "if", "randomize_input", ":", "_", ",", "batch_ex_str", "=", "tf", ".", "train", ".", "shuffle_batch", "(", "tensors", "=", "[", "ex_id", ",", "ex_str", "]", ",", "batch_size", "=", "training_batch_size", ",", "capacity", "=", "queue_capacity", ",", "min_after_dequeue", "=", "min_after_dequeue", ",", "enqueue_many", "=", "True", ",", "num_threads", "=", "reader_num_threads", ",", "allow_smaller_final_batch", "=", "allow_smaller_final_batch", ")", "else", ":", "_", ",", "batch_ex_str", "=", "tf", ".", "train", ".", "batch", "(", "tensors", "=", "[", "ex_id", ",", "ex_str", "]", ",", "batch_size", "=", "training_batch_size", ",", "capacity", "=", "queue_capacity", ",", "enqueue_many", "=", "True", ",", "num_threads", "=", "reader_num_threads", ",", "allow_smaller_final_batch", "=", "allow_smaller_final_batch", ")", "feature_spec", "=", "{", "}", "feature_info", "=", "get_transformed_feature_info", "(", "features", ",", "schema", ")", "for", "name", ",", "info", "in", "six", ".", "iteritems", "(", "feature_info", ")", ":", "if", "info", "[", "'size'", "]", "is", "None", ":", "feature_spec", "[", "name", "]", "=", "tf", ".", "VarLenFeature", "(", "dtype", "=", "info", "[", "'dtype'", "]", ")", "else", ":", "feature_spec", "[", "name", "]", "=", "tf", ".", "FixedLenFeature", "(", "shape", "=", "[", "info", "[", "'size'", "]", "]", ",", "dtype", "=", "info", "[", "'dtype'", "]", ")", "parsed_tensors", "=", "tf", ".", "parse_example", "(", "batch_ex_str", ",", "feature_spec", ")", "# Expand the dims of non-sparse tensors. This is needed by tf.learn.", "transformed_features", "=", "{", "}", "for", "k", ",", "v", "in", "six", ".", "iteritems", "(", "parsed_tensors", ")", ":", "if", "isinstance", "(", "v", ",", "tf", ".", "Tensor", ")", "and", "v", ".", "get_shape", "(", ")", ".", "ndims", "==", "1", ":", "transformed_features", "[", "k", "]", "=", "tf", ".", "expand_dims", "(", "v", ",", "-", "1", ")", "else", ":", "# Sparse tensor", "transformed_features", "[", "k", "]", "=", "v", "transformed_features", "=", "image_feature_engineering", "(", "features", "=", "features", ",", "feature_tensors_dict", "=", "transformed_features", ")", "# Remove the target tensor, and return it directly", "target_name", "=", "get_target_name", "(", "features", ")", "if", "not", "target_name", "or", "target_name", "not", "in", "transformed_features", ":", "raise", "ValueError", "(", "'Cannot find target transform in features'", ")", "transformed_target", "=", "transformed_features", ".", "pop", "(", "target_name", ")", "return", "transformed_features", ",", "transformed_target", "return", "transformed_training_input_fn" ]
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: numer of epochs to read from the files. Use None to read forever. randomize_input: If true, the input rows are read out of order. This randomness is limited by the min_after_dequeue value. min_after_dequeue: Minimum number elements in the reading queue after a dequeue, used to ensure a level of mixing of elements. Only used if randomize_input is True. reader_num_threads: The number of threads enqueuing data. allow_smaller_final_batch: If false, fractional batches at the end of training or evaluation are not used. Returns: An input_fn suitable for training that reads transformed data in tf record files of tf.example.
[ "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
237,786
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 features and features[name]['transform'] == IMAGE_TRANSFORM: with tf.name_scope(name, 'Wx_plus_b'): hidden = tf.contrib.layers.fully_connected( feature_tensor, IMAGE_HIDDEN_TENSOR_SIZE) engineered_features[name] = hidden else: engineered_features[name] = feature_tensor return engineered_features
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 features and features[name]['transform'] == IMAGE_TRANSFORM: with tf.name_scope(name, 'Wx_plus_b'): hidden = tf.contrib.layers.fully_connected( feature_tensor, IMAGE_HIDDEN_TENSOR_SIZE) engineered_features[name] = hidden else: engineered_features[name] = feature_tensor return engineered_features
[ "def", "image_feature_engineering", "(", "features", ",", "feature_tensors_dict", ")", ":", "engineered_features", "=", "{", "}", "for", "name", ",", "feature_tensor", "in", "six", ".", "iteritems", "(", "feature_tensors_dict", ")", ":", "if", "name", "in", "features", "and", "features", "[", "name", "]", "[", "'transform'", "]", "==", "IMAGE_TRANSFORM", ":", "with", "tf", ".", "name_scope", "(", "name", ",", "'Wx_plus_b'", ")", ":", "hidden", "=", "tf", ".", "contrib", ".", "layers", ".", "fully_connected", "(", "feature_tensor", ",", "IMAGE_HIDDEN_TENSOR_SIZE", ")", "engineered_features", "[", "name", "]", "=", "hidden", "else", ":", "engineered_features", "[", "name", "]", "=", "feature_tensor", "return", "engineered_features" ]
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
237,787
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( f, header=None, names=['vocab', 'count'], dtype=str, # Prevent pd from converting numerical categories. na_filter=False) # Prevent pd from converting 'NA' to a NaN. vocab = vocab_pd['vocab'].tolist() ex_count = vocab_pd['count'].astype(int).tolist() return vocab, ex_count
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( f, header=None, names=['vocab', 'count'], dtype=str, # Prevent pd from converting numerical categories. na_filter=False) # Prevent pd from converting 'NA' to a NaN. vocab = vocab_pd['vocab'].tolist() ex_count = vocab_pd['count'].astype(int).tolist() return vocab, ex_count
[ "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'", ",", "'count'", "]", ",", "dtype", "=", "str", ",", "# Prevent pd from converting numerical categories.", "na_filter", "=", "False", ")", "# Prevent pd from converting 'NA' to a NaN.", "vocab", "=", "vocab_pd", "[", "'vocab'", "]", ".", "tolist", "(", ")", "ex_count", "=", "vocab_pd", "[", "'count'", "]", ".", "astype", "(", "int", ")", ".", "tolist", "(", ")", "return", "vocab", ",", "ex_count" ]
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
237,788
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_source_format, 'sourceUris': self._source, } if self._source_format == 'csv' and self._csv_options: json['csvOptions'] = {} json['csvOptions'].update(self._csv_options._to_query_json()) if self._schema: json['schema'] = {'fields': self._schema._bq_schema} return json
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_source_format, 'sourceUris': self._source, } if self._source_format == 'csv' and self._csv_options: json['csvOptions'] = {} json['csvOptions'].update(self._csv_options._to_query_json()) if self._schema: json['schema'] = {'fields': self._schema._bq_schema} return json
[ "def", "_to_query_json", "(", "self", ")", ":", "json", "=", "{", "'compression'", ":", "'GZIP'", "if", "self", ".", "_compressed", "else", "'NONE'", ",", "'ignoreUnknownValues'", ":", "self", ".", "_ignore_unknown_values", ",", "'maxBadRecords'", ":", "self", ".", "_max_bad_records", ",", "'sourceFormat'", ":", "self", ".", "_bq_source_format", ",", "'sourceUris'", ":", "self", ".", "_source", ",", "}", "if", "self", ".", "_source_format", "==", "'csv'", "and", "self", ".", "_csv_options", ":", "json", "[", "'csvOptions'", "]", "=", "{", "}", "json", "[", "'csvOptions'", "]", ".", "update", "(", "self", ".", "_csv_options", ".", "_to_query_json", "(", ")", ")", "if", "self", ".", "_schema", ":", "json", "[", "'schema'", "]", "=", "{", "'fields'", ":", "self", ".", "_schema", ".", "_bq_schema", "}", "return", "json" ]
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
237,789
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, method="GET", body=None, headers=None, redirections=_httplib2.DEFAULT_MAX_REDIRECTS, connection_type=None): if headers is None: headers = {} headers['user-agent'] = 'GoogleCloudDataLab/1.0' return _orig_request(self, uri, method=method, body=body, headers=headers, redirections=redirections, connection_type=connection_type) _httplib2.Http.request = _request # Similarly for the requests library. def _init_session(self): _orig_init(self) self.headers['User-Agent'] = 'GoogleCloudDataLab/1.0' _requests.Session.__init__ = _init_session # Be more tolerant with magics. If the user specified a cell magic that doesn't # exist and an empty cell body but a line magic with that name exists, run that # instead. Conversely, if the user specified a line magic that doesn't exist but # a cell magic exists with that name, run the cell magic with an empty body. def _run_line_magic(self, magic_name, line): fn = self.find_line_magic(magic_name) if fn is None: cm = self.find_cell_magic(magic_name) if cm: return _run_cell_magic(self, magic_name, line, None) return _orig_run_line_magic(self, magic_name, line) def _run_cell_magic(self, magic_name, line, cell): if cell is None or len(cell) == 0 or cell.isspace(): fn = self.find_line_magic(magic_name) if fn: return _orig_run_line_magic(self, magic_name, line) # IPython will complain if cell is empty string but not if it is None cell = None return _orig_run_cell_magic(self, magic_name, line, cell) _shell.InteractiveShell.run_cell_magic = _run_cell_magic _shell.InteractiveShell.run_line_magic = _run_line_magic # Define global 'project_id' and 'set_project_id' functions to manage the default project ID. We # do this conditionally in a try/catch # to avoid the call to Context.default() when running tests # which mock IPython.get_ipython(). def _get_project_id(): try: return google.datalab.Context.default().project_id except Exception: return None def _set_project_id(project_id): context = google.datalab.Context.default() context.set_project_id(project_id) try: from datalab.context import Context as _old_context _old_context.default().set_project_id(project_id) except ImportError: # If the old library is not loaded, then we don't have to do anything pass try: if 'datalab_project_id' not in _IPython.get_ipython().user_ns: _IPython.get_ipython().user_ns['datalab_project_id'] = _get_project_id _IPython.get_ipython().user_ns['set_datalab_project_id'] = _set_project_id except TypeError: pass
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, method="GET", body=None, headers=None, redirections=_httplib2.DEFAULT_MAX_REDIRECTS, connection_type=None): if headers is None: headers = {} headers['user-agent'] = 'GoogleCloudDataLab/1.0' return _orig_request(self, uri, method=method, body=body, headers=headers, redirections=redirections, connection_type=connection_type) _httplib2.Http.request = _request # Similarly for the requests library. def _init_session(self): _orig_init(self) self.headers['User-Agent'] = 'GoogleCloudDataLab/1.0' _requests.Session.__init__ = _init_session # Be more tolerant with magics. If the user specified a cell magic that doesn't # exist and an empty cell body but a line magic with that name exists, run that # instead. Conversely, if the user specified a line magic that doesn't exist but # a cell magic exists with that name, run the cell magic with an empty body. def _run_line_magic(self, magic_name, line): fn = self.find_line_magic(magic_name) if fn is None: cm = self.find_cell_magic(magic_name) if cm: return _run_cell_magic(self, magic_name, line, None) return _orig_run_line_magic(self, magic_name, line) def _run_cell_magic(self, magic_name, line, cell): if cell is None or len(cell) == 0 or cell.isspace(): fn = self.find_line_magic(magic_name) if fn: return _orig_run_line_magic(self, magic_name, line) # IPython will complain if cell is empty string but not if it is None cell = None return _orig_run_cell_magic(self, magic_name, line, cell) _shell.InteractiveShell.run_cell_magic = _run_cell_magic _shell.InteractiveShell.run_line_magic = _run_line_magic # Define global 'project_id' and 'set_project_id' functions to manage the default project ID. We # do this conditionally in a try/catch # to avoid the call to Context.default() when running tests # which mock IPython.get_ipython(). def _get_project_id(): try: return google.datalab.Context.default().project_id except Exception: return None def _set_project_id(project_id): context = google.datalab.Context.default() context.set_project_id(project_id) try: from datalab.context import Context as _old_context _old_context.default().set_project_id(project_id) except ImportError: # If the old library is not loaded, then we don't have to do anything pass try: if 'datalab_project_id' not in _IPython.get_ipython().user_ns: _IPython.get_ipython().user_ns['datalab_project_id'] = _get_project_id _IPython.get_ipython().user_ns['set_datalab_project_id'] = _set_project_id except TypeError: pass
[ "def", "load_ipython_extension", "(", "shell", ")", ":", "# Inject our user agent on all requests by monkey-patching a wrapper around httplib2.Http.request.", "def", "_request", "(", "self", ",", "uri", ",", "method", "=", "\"GET\"", ",", "body", "=", "None", ",", "headers", "=", "None", ",", "redirections", "=", "_httplib2", ".", "DEFAULT_MAX_REDIRECTS", ",", "connection_type", "=", "None", ")", ":", "if", "headers", "is", "None", ":", "headers", "=", "{", "}", "headers", "[", "'user-agent'", "]", "=", "'GoogleCloudDataLab/1.0'", "return", "_orig_request", "(", "self", ",", "uri", ",", "method", "=", "method", ",", "body", "=", "body", ",", "headers", "=", "headers", ",", "redirections", "=", "redirections", ",", "connection_type", "=", "connection_type", ")", "_httplib2", ".", "Http", ".", "request", "=", "_request", "# Similarly for the requests library.", "def", "_init_session", "(", "self", ")", ":", "_orig_init", "(", "self", ")", "self", ".", "headers", "[", "'User-Agent'", "]", "=", "'GoogleCloudDataLab/1.0'", "_requests", ".", "Session", ".", "__init__", "=", "_init_session", "# Be more tolerant with magics. If the user specified a cell magic that doesn't", "# exist and an empty cell body but a line magic with that name exists, run that", "# instead. Conversely, if the user specified a line magic that doesn't exist but", "# a cell magic exists with that name, run the cell magic with an empty body.", "def", "_run_line_magic", "(", "self", ",", "magic_name", ",", "line", ")", ":", "fn", "=", "self", ".", "find_line_magic", "(", "magic_name", ")", "if", "fn", "is", "None", ":", "cm", "=", "self", ".", "find_cell_magic", "(", "magic_name", ")", "if", "cm", ":", "return", "_run_cell_magic", "(", "self", ",", "magic_name", ",", "line", ",", "None", ")", "return", "_orig_run_line_magic", "(", "self", ",", "magic_name", ",", "line", ")", "def", "_run_cell_magic", "(", "self", ",", "magic_name", ",", "line", ",", "cell", ")", ":", "if", "cell", "is", "None", "or", "len", "(", "cell", ")", "==", "0", "or", "cell", ".", "isspace", "(", ")", ":", "fn", "=", "self", ".", "find_line_magic", "(", "magic_name", ")", "if", "fn", ":", "return", "_orig_run_line_magic", "(", "self", ",", "magic_name", ",", "line", ")", "# IPython will complain if cell is empty string but not if it is None", "cell", "=", "None", "return", "_orig_run_cell_magic", "(", "self", ",", "magic_name", ",", "line", ",", "cell", ")", "_shell", ".", "InteractiveShell", ".", "run_cell_magic", "=", "_run_cell_magic", "_shell", ".", "InteractiveShell", ".", "run_line_magic", "=", "_run_line_magic", "# Define global 'project_id' and 'set_project_id' functions to manage the default project ID. We", "# do this conditionally in a try/catch # to avoid the call to Context.default() when running tests", "# which mock IPython.get_ipython().", "def", "_get_project_id", "(", ")", ":", "try", ":", "return", "google", ".", "datalab", ".", "Context", ".", "default", "(", ")", ".", "project_id", "except", "Exception", ":", "return", "None", "def", "_set_project_id", "(", "project_id", ")", ":", "context", "=", "google", ".", "datalab", ".", "Context", ".", "default", "(", ")", "context", ".", "set_project_id", "(", "project_id", ")", "try", ":", "from", "datalab", ".", "context", "import", "Context", "as", "_old_context", "_old_context", ".", "default", "(", ")", ".", "set_project_id", "(", "project_id", ")", "except", "ImportError", ":", "# If the old library is not loaded, then we don't have to do anything", "pass", "try", ":", "if", "'datalab_project_id'", "not", "in", "_IPython", ".", "get_ipython", "(", ")", ".", "user_ns", ":", "_IPython", ".", "get_ipython", "(", ")", ".", "user_ns", "[", "'datalab_project_id'", "]", "=", "_get_project_id", "_IPython", ".", "get_ipython", "(", ")", ".", "user_ns", "[", "'set_datalab_project_id'", "]", "=", "_set_project_id", "except", "TypeError", ":", "pass" ]
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
237,790
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 arguments. These are all used to override the arg parser. Alternatively args may be a dictionary, in which case it overrides the default values from the arg parser. Returns: A dictionary of argument names and values. """ overrides = None if args is None: tokens = [] elif isinstance(args, basestring): command_line = ' '.join(args.split('\n')) tokens = shlex.split(command_line) elif isinstance(args, dict): overrides = args tokens = [] else: tokens = args args = {} if parser is None else vars(parser.parse_args(tokens)) if overrides: args.update(overrides) # Don't return any args that are None as we don't want to expand to 'None' return {arg: value for arg, value in args.items() if value is not None}
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 arguments. These are all used to override the arg parser. Alternatively args may be a dictionary, in which case it overrides the default values from the arg parser. Returns: A dictionary of argument names and values. """ overrides = None if args is None: tokens = [] elif isinstance(args, basestring): command_line = ' '.join(args.split('\n')) tokens = shlex.split(command_line) elif isinstance(args, dict): overrides = args tokens = [] else: tokens = args args = {} if parser is None else vars(parser.parse_args(tokens)) if overrides: args.update(overrides) # Don't return any args that are None as we don't want to expand to 'None' return {arg: value for arg, value in args.items() if value is not None}
[ "def", "_get_sql_args", "(", "parser", ",", "args", "=", "None", ")", ":", "overrides", "=", "None", "if", "args", "is", "None", ":", "tokens", "=", "[", "]", "elif", "isinstance", "(", "args", ",", "basestring", ")", ":", "command_line", "=", "' '", ".", "join", "(", "args", ".", "split", "(", "'\\n'", ")", ")", "tokens", "=", "shlex", ".", "split", "(", "command_line", ")", "elif", "isinstance", "(", "args", ",", "dict", ")", ":", "overrides", "=", "args", "tokens", "=", "[", "]", "else", ":", "tokens", "=", "args", "args", "=", "{", "}", "if", "parser", "is", "None", "else", "vars", "(", "parser", ".", "parse_args", "(", "tokens", ")", ")", "if", "overrides", ":", "args", ".", "update", "(", "overrides", ")", "# Don't return any args that are None as we don't want to expand to 'None'", "return", "{", "arg", ":", "value", "for", "arg", ",", "value", "in", "args", ".", "items", "(", ")", "if", "value", "is", "not", "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 arguments. These are all used to override the arg parser. Alternatively args may be a dictionary, in which case it overrides the default values from the arg parser. Returns: A dictionary of argument names and values.
[ "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
237,791
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 of command line arguments or a dictionary of values. Returns: A SqlStatement for the query or module, plus a dictionary of variable values to use. """ if isinstance(item, basestring): item = _sql_statement.SqlStatement(item) elif not isinstance(item, _sql_statement.SqlStatement): item = SqlModule.get_default_query_from_module(item) if not item: raise Exception('Expected a SQL statement or module but got %s' % str(item)) env = {} if item.module: env.update(item.module.__dict__) parser = env.get(_utils._SQL_MODULE_ARGPARSE, None) if parser: args = SqlModule._get_sql_args(parser, args=args) else: args = None if isinstance(args, dict): env.update(args) return item, env
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 of command line arguments or a dictionary of values. Returns: A SqlStatement for the query or module, plus a dictionary of variable values to use. """ if isinstance(item, basestring): item = _sql_statement.SqlStatement(item) elif not isinstance(item, _sql_statement.SqlStatement): item = SqlModule.get_default_query_from_module(item) if not item: raise Exception('Expected a SQL statement or module but got %s' % str(item)) env = {} if item.module: env.update(item.module.__dict__) parser = env.get(_utils._SQL_MODULE_ARGPARSE, None) if parser: args = SqlModule._get_sql_args(parser, args=args) else: args = None if isinstance(args, dict): env.update(args) return item, env
[ "def", "get_sql_statement_with_environment", "(", "item", ",", "args", "=", "None", ")", ":", "if", "isinstance", "(", "item", ",", "basestring", ")", ":", "item", "=", "_sql_statement", ".", "SqlStatement", "(", "item", ")", "elif", "not", "isinstance", "(", "item", ",", "_sql_statement", ".", "SqlStatement", ")", ":", "item", "=", "SqlModule", ".", "get_default_query_from_module", "(", "item", ")", "if", "not", "item", ":", "raise", "Exception", "(", "'Expected a SQL statement or module but got %s'", "%", "str", "(", "item", ")", ")", "env", "=", "{", "}", "if", "item", ".", "module", ":", "env", ".", "update", "(", "item", ".", "module", ".", "__dict__", ")", "parser", "=", "env", ".", "get", "(", "_utils", ".", "_SQL_MODULE_ARGPARSE", ",", "None", ")", "if", "parser", ":", "args", "=", "SqlModule", ".", "_get_sql_args", "(", "parser", ",", "args", "=", "args", ")", "else", ":", "args", "=", "None", "if", "isinstance", "(", "args", ",", "dict", ")", ":", "env", ".", "update", "(", "args", ")", "return", "item", ",", "env" ]
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. Returns: A SqlStatement for the query or module, plus a dictionary of variable values to use.
[ "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
237,792
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 parser for the SqlModule associated with the SqlStatement or SqlModule. If a dictionary, it is used to override any default arguments from the argument parser. If the sql argument is a string then args must be None or a dictionary as in this case there is no associated argument parser. Returns: The expanded SQL, list of referenced scripts, and list of referenced external tables. """ sql, args = SqlModule.get_sql_statement_with_environment(sql, args) return _sql_statement.SqlStatement.format(sql._sql, args)
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 parser for the SqlModule associated with the SqlStatement or SqlModule. If a dictionary, it is used to override any default arguments from the argument parser. If the sql argument is a string then args must be None or a dictionary as in this case there is no associated argument parser. Returns: The expanded SQL, list of referenced scripts, and list of referenced external tables. """ sql, args = SqlModule.get_sql_statement_with_environment(sql, args) return _sql_statement.SqlStatement.format(sql._sql, args)
[ "def", "expand", "(", "sql", ",", "args", "=", "None", ")", ":", "sql", ",", "args", "=", "SqlModule", ".", "get_sql_statement_with_environment", "(", "sql", ",", "args", ")", "return", "_sql_statement", ".", "SqlStatement", ".", "format", "(", "sql", ".", "_sql", ",", "args", ")" ]
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 with the SqlStatement or SqlModule. If a dictionary, it is used to override any default arguments from the argument parser. If the sql argument is a string then args must be None or a dictionary as in this case there is no associated argument parser. Returns: The expanded SQL, list of referenced scripts, and list of referenced external tables.
[ "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
237,793
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 contain a project ID and it does not match this, an exception will be thrown. Returns: A DatasetName named tuple for the dataset. Raises: Exception: raised if the name doesn't match the expected formats or a project_id was specified that does not match that in the name. """ _project_id = _dataset_id = None if isinstance(name, basestring): # Try to parse as absolute name first. m = re.match(_ABS_DATASET_NAME_PATTERN, name, re.IGNORECASE) if m is not None: _project_id, _dataset_id = m.groups() else: # Next try to match as a relative name implicitly scoped within current project. m = re.match(_REL_DATASET_NAME_PATTERN, name) if m is not None: groups = m.groups() _dataset_id = groups[0] elif isinstance(name, dict): try: _dataset_id = name['dataset_id'] _project_id = name['project_id'] except KeyError: pass else: # Try treat as an array or tuple if len(name) == 2: # Treat as a tuple or array. _project_id, _dataset_id = name elif len(name) == 1: _dataset_id = name[0] if not _dataset_id: raise Exception('Invalid dataset name: ' + str(name)) if not _project_id: _project_id = project_id return DatasetName(_project_id, _dataset_id)
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 contain a project ID and it does not match this, an exception will be thrown. Returns: A DatasetName named tuple for the dataset. Raises: Exception: raised if the name doesn't match the expected formats or a project_id was specified that does not match that in the name. """ _project_id = _dataset_id = None if isinstance(name, basestring): # Try to parse as absolute name first. m = re.match(_ABS_DATASET_NAME_PATTERN, name, re.IGNORECASE) if m is not None: _project_id, _dataset_id = m.groups() else: # Next try to match as a relative name implicitly scoped within current project. m = re.match(_REL_DATASET_NAME_PATTERN, name) if m is not None: groups = m.groups() _dataset_id = groups[0] elif isinstance(name, dict): try: _dataset_id = name['dataset_id'] _project_id = name['project_id'] except KeyError: pass else: # Try treat as an array or tuple if len(name) == 2: # Treat as a tuple or array. _project_id, _dataset_id = name elif len(name) == 1: _dataset_id = name[0] if not _dataset_id: raise Exception('Invalid dataset name: ' + str(name)) if not _project_id: _project_id = project_id return DatasetName(_project_id, _dataset_id)
[ "def", "parse_dataset_name", "(", "name", ",", "project_id", "=", "None", ")", ":", "_project_id", "=", "_dataset_id", "=", "None", "if", "isinstance", "(", "name", ",", "basestring", ")", ":", "# Try to parse as absolute name first.", "m", "=", "re", ".", "match", "(", "_ABS_DATASET_NAME_PATTERN", ",", "name", ",", "re", ".", "IGNORECASE", ")", "if", "m", "is", "not", "None", ":", "_project_id", ",", "_dataset_id", "=", "m", ".", "groups", "(", ")", "else", ":", "# Next try to match as a relative name implicitly scoped within current project.", "m", "=", "re", ".", "match", "(", "_REL_DATASET_NAME_PATTERN", ",", "name", ")", "if", "m", "is", "not", "None", ":", "groups", "=", "m", ".", "groups", "(", ")", "_dataset_id", "=", "groups", "[", "0", "]", "elif", "isinstance", "(", "name", ",", "dict", ")", ":", "try", ":", "_dataset_id", "=", "name", "[", "'dataset_id'", "]", "_project_id", "=", "name", "[", "'project_id'", "]", "except", "KeyError", ":", "pass", "else", ":", "# Try treat as an array or tuple", "if", "len", "(", "name", ")", "==", "2", ":", "# Treat as a tuple or array.", "_project_id", ",", "_dataset_id", "=", "name", "elif", "len", "(", "name", ")", "==", "1", ":", "_dataset_id", "=", "name", "[", "0", "]", "if", "not", "_dataset_id", ":", "raise", "Exception", "(", "'Invalid dataset name: '", "+", "str", "(", "name", ")", ")", "if", "not", "_project_id", ":", "_project_id", "=", "project_id", "return", "DatasetName", "(", "_project_id", ",", "_dataset_id", ")" ]
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 this, an exception will be thrown. Returns: A DatasetName named tuple for the dataset. Raises: Exception: raised if the name doesn't match the expected formats or a project_id was specified that does not match that in the name.
[ "Parses", "a", "dataset", "name", "into", "its", "individual", "parts", "." ]
d9031901d5bca22fe0d5925d204e6698df9852e1
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/google/datalab/bigquery/_utils.py#L58-L102
train
237,794
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 the name does contain a project ID and it does not match this, an exception will be thrown. dataset_id: the expected dataset ID. If the name does not contain a dataset ID, this will be used; if the name does contain a dataset ID and it does not match this, an exception will be thrown. Returns: A TableName named tuple consisting of the full name and individual name parts. Raises: Exception: raised if the name doesn't match the expected formats, or a project_id and/or dataset_id was provided that does not match that in the name. """ _project_id = _dataset_id = _table_id = _decorator = None if isinstance(name, basestring): # Try to parse as absolute name first. m = re.match(_ABS_TABLE_NAME_PATTERN, name, re.IGNORECASE) if m is not None: _project_id, _dataset_id, _table_id, _decorator = m.groups() else: # Next try to match as a relative name implicitly scoped within current project. m = re.match(_REL_TABLE_NAME_PATTERN, name) if m is not None: groups = m.groups() _project_id, _dataset_id, _table_id, _decorator =\ project_id, groups[0], groups[1], groups[2] else: # Finally try to match as a table name only. m = re.match(_TABLE_NAME_PATTERN, name) if m is not None: groups = m.groups() _project_id, _dataset_id, _table_id, _decorator =\ project_id, dataset_id, groups[0], groups[1] elif isinstance(name, dict): try: _table_id = name['table_id'] _dataset_id = name['dataset_id'] _project_id = name['project_id'] except KeyError: pass else: # Try treat as an array or tuple if len(name) == 4: _project_id, _dataset_id, _table_id, _decorator = name elif len(name) == 3: _project_id, _dataset_id, _table_id = name elif len(name) == 2: _dataset_id, _table_id = name if not _table_id: raise Exception('Invalid table name: ' + str(name)) if not _project_id: _project_id = project_id if not _dataset_id: _dataset_id = dataset_id if not _decorator: _decorator = '' return TableName(_project_id, _dataset_id, _table_id, _decorator)
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 the name does contain a project ID and it does not match this, an exception will be thrown. dataset_id: the expected dataset ID. If the name does not contain a dataset ID, this will be used; if the name does contain a dataset ID and it does not match this, an exception will be thrown. Returns: A TableName named tuple consisting of the full name and individual name parts. Raises: Exception: raised if the name doesn't match the expected formats, or a project_id and/or dataset_id was provided that does not match that in the name. """ _project_id = _dataset_id = _table_id = _decorator = None if isinstance(name, basestring): # Try to parse as absolute name first. m = re.match(_ABS_TABLE_NAME_PATTERN, name, re.IGNORECASE) if m is not None: _project_id, _dataset_id, _table_id, _decorator = m.groups() else: # Next try to match as a relative name implicitly scoped within current project. m = re.match(_REL_TABLE_NAME_PATTERN, name) if m is not None: groups = m.groups() _project_id, _dataset_id, _table_id, _decorator =\ project_id, groups[0], groups[1], groups[2] else: # Finally try to match as a table name only. m = re.match(_TABLE_NAME_PATTERN, name) if m is not None: groups = m.groups() _project_id, _dataset_id, _table_id, _decorator =\ project_id, dataset_id, groups[0], groups[1] elif isinstance(name, dict): try: _table_id = name['table_id'] _dataset_id = name['dataset_id'] _project_id = name['project_id'] except KeyError: pass else: # Try treat as an array or tuple if len(name) == 4: _project_id, _dataset_id, _table_id, _decorator = name elif len(name) == 3: _project_id, _dataset_id, _table_id = name elif len(name) == 2: _dataset_id, _table_id = name if not _table_id: raise Exception('Invalid table name: ' + str(name)) if not _project_id: _project_id = project_id if not _dataset_id: _dataset_id = dataset_id if not _decorator: _decorator = '' return TableName(_project_id, _dataset_id, _table_id, _decorator)
[ "def", "parse_table_name", "(", "name", ",", "project_id", "=", "None", ",", "dataset_id", "=", "None", ")", ":", "_project_id", "=", "_dataset_id", "=", "_table_id", "=", "_decorator", "=", "None", "if", "isinstance", "(", "name", ",", "basestring", ")", ":", "# Try to parse as absolute name first.", "m", "=", "re", ".", "match", "(", "_ABS_TABLE_NAME_PATTERN", ",", "name", ",", "re", ".", "IGNORECASE", ")", "if", "m", "is", "not", "None", ":", "_project_id", ",", "_dataset_id", ",", "_table_id", ",", "_decorator", "=", "m", ".", "groups", "(", ")", "else", ":", "# Next try to match as a relative name implicitly scoped within current project.", "m", "=", "re", ".", "match", "(", "_REL_TABLE_NAME_PATTERN", ",", "name", ")", "if", "m", "is", "not", "None", ":", "groups", "=", "m", ".", "groups", "(", ")", "_project_id", ",", "_dataset_id", ",", "_table_id", ",", "_decorator", "=", "project_id", ",", "groups", "[", "0", "]", ",", "groups", "[", "1", "]", ",", "groups", "[", "2", "]", "else", ":", "# Finally try to match as a table name only.", "m", "=", "re", ".", "match", "(", "_TABLE_NAME_PATTERN", ",", "name", ")", "if", "m", "is", "not", "None", ":", "groups", "=", "m", ".", "groups", "(", ")", "_project_id", ",", "_dataset_id", ",", "_table_id", ",", "_decorator", "=", "project_id", ",", "dataset_id", ",", "groups", "[", "0", "]", ",", "groups", "[", "1", "]", "elif", "isinstance", "(", "name", ",", "dict", ")", ":", "try", ":", "_table_id", "=", "name", "[", "'table_id'", "]", "_dataset_id", "=", "name", "[", "'dataset_id'", "]", "_project_id", "=", "name", "[", "'project_id'", "]", "except", "KeyError", ":", "pass", "else", ":", "# Try treat as an array or tuple", "if", "len", "(", "name", ")", "==", "4", ":", "_project_id", ",", "_dataset_id", ",", "_table_id", ",", "_decorator", "=", "name", "elif", "len", "(", "name", ")", "==", "3", ":", "_project_id", ",", "_dataset_id", ",", "_table_id", "=", "name", "elif", "len", "(", "name", ")", "==", "2", ":", "_dataset_id", ",", "_table_id", "=", "name", "if", "not", "_table_id", ":", "raise", "Exception", "(", "'Invalid table name: '", "+", "str", "(", "name", ")", ")", "if", "not", "_project_id", ":", "_project_id", "=", "project_id", "if", "not", "_dataset_id", ":", "_dataset_id", "=", "dataset_id", "if", "not", "_decorator", ":", "_decorator", "=", "''", "return", "TableName", "(", "_project_id", ",", "_dataset_id", ",", "_table_id", ",", "_decorator", ")" ]
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 this, an exception will be thrown. dataset_id: the expected dataset ID. If the name does not contain a dataset ID, this will be used; if the name does contain a dataset ID and it does not match this, an exception will be thrown. Returns: A TableName named tuple consisting of the full name and individual name parts. Raises: Exception: raised if the name doesn't match the expected formats, or a project_id and/or dataset_id was provided that does not match that in the name.
[ "Parses", "a", "table", "name", "into", "its", "individual", "parts", "." ]
d9031901d5bca22fe0d5925d204e6698df9852e1
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/google/datalab/bigquery/_utils.py#L105-L166
train
237,795
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) instance_copy[column_to_explain] = x predict_input.append(instance_copy) df = _local_predict.get_prediction_results(self._model_dir, predict_input, self._headers, with_source=False) probs = _local_predict.get_probs_for_labels(labels, df) return np.asarray(probs) return _predict_fn
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) instance_copy[column_to_explain] = x predict_input.append(instance_copy) df = _local_predict.get_prediction_results(self._model_dir, predict_input, self._headers, with_source=False) probs = _local_predict.get_probs_for_labels(labels, df) return np.asarray(probs) return _predict_fn
[ "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", "=", "dict", "(", "instance", ")", "instance_copy", "[", "column_to_explain", "]", "=", "x", "predict_input", ".", "append", "(", "instance_copy", ")", "df", "=", "_local_predict", ".", "get_prediction_results", "(", "self", ".", "_model_dir", ",", "predict_input", ",", "self", ".", "_headers", ",", "with_source", "=", "False", ")", "probs", "=", "_local_predict", ".", "get_probs_for_labels", "(", "labels", ",", "df", ")", "return", "np", ".", "asarray", "(", "probs", ")", "return", "_predict_fn" ]
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
237,796
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) instance_copy[column_to_explain] = Image.fromarray(x) predict_input.append(instance_copy) df = _local_predict.get_prediction_results( self._model_dir, predict_input, self._headers, img_cols=self._image_columns, with_source=False) probs = _local_predict.get_probs_for_labels(labels, df) return np.asarray(probs) return _predict_fn
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) instance_copy[column_to_explain] = Image.fromarray(x) predict_input.append(instance_copy) df = _local_predict.get_prediction_results( self._model_dir, predict_input, self._headers, img_cols=self._image_columns, with_source=False) probs = _local_predict.get_probs_for_labels(labels, df) return np.asarray(probs) return _predict_fn
[ "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", "=", "dict", "(", "instance", ")", "instance_copy", "[", "column_to_explain", "]", "=", "Image", ".", "fromarray", "(", "x", ")", "predict_input", ".", "append", "(", "instance_copy", ")", "df", "=", "_local_predict", ".", "get_prediction_results", "(", "self", ".", "_model_dir", ",", "predict_input", ",", "self", ".", "_headers", ",", "img_cols", "=", "self", ".", "_image_columns", ",", "with_source", "=", "False", ")", "probs", "=", "_local_predict", ".", "get_probs_for_labels", "(", "labels", ",", "df", ")", "return", "np", ".", "asarray", "(", "probs", ")", "return", "_predict_fn" ]
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
237,797
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)) col_categories.append('_UNKNOWN') categories.append(col_categories) return categories
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)) col_categories.append('_UNKNOWN') categories.append(col_categories) return categories
[ "def", "_get_unique_categories", "(", "self", ",", "df", ")", ":", "categories", "=", "[", "]", "for", "col", "in", "self", ".", "_categorical_columns", ":", "categocial", "=", "pd", ".", "Categorical", "(", "df", "[", "col", "]", ")", "col_categories", "=", "list", "(", "map", "(", "str", ",", "categocial", ".", "categories", ")", ")", "col_categories", ".", "append", "(", "'_UNKNOWN'", ")", "categories", ".", "append", "(", "col_categories", ")", "return", "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
237,798
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 numpy arrays, with all categorical values converted to indices. It also requires list of names for each category. """ df = df.copy() # Remove non tabular columns (text, image). for col in list(df.columns): if col not in (self._categorical_columns + self._numeric_columns): del df[col] # Convert categorical values into indices. for col_name, col_categories in zip(self._categorical_columns, categories): df[col_name] = df[col_name].apply( lambda x: col_categories.index(str(x)) if str(x) in col_categories else len(col_categories) - 1) # Make sure numeric values are really numeric for numeric_col in self._numeric_columns: df[numeric_col] = df[numeric_col].apply(lambda x: float(x)) return df.as_matrix(self._categorical_columns + self._numeric_columns)
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 numpy arrays, with all categorical values converted to indices. It also requires list of names for each category. """ df = df.copy() # Remove non tabular columns (text, image). for col in list(df.columns): if col not in (self._categorical_columns + self._numeric_columns): del df[col] # Convert categorical values into indices. for col_name, col_categories in zip(self._categorical_columns, categories): df[col_name] = df[col_name].apply( lambda x: col_categories.index(str(x)) if str(x) in col_categories else len(col_categories) - 1) # Make sure numeric values are really numeric for numeric_col in self._numeric_columns: df[numeric_col] = df[numeric_col].apply(lambda x: float(x)) return df.as_matrix(self._categorical_columns + self._numeric_columns)
[ "def", "_preprocess_data_for_tabular_explain", "(", "self", ",", "df", ",", "categories", ")", ":", "df", "=", "df", ".", "copy", "(", ")", "# Remove non tabular columns (text, image).", "for", "col", "in", "list", "(", "df", ".", "columns", ")", ":", "if", "col", "not", "in", "(", "self", ".", "_categorical_columns", "+", "self", ".", "_numeric_columns", ")", ":", "del", "df", "[", "col", "]", "# Convert categorical values into indices.", "for", "col_name", ",", "col_categories", "in", "zip", "(", "self", ".", "_categorical_columns", ",", "categories", ")", ":", "df", "[", "col_name", "]", "=", "df", "[", "col_name", "]", ".", "apply", "(", "lambda", "x", ":", "col_categories", ".", "index", "(", "str", "(", "x", ")", ")", "if", "str", "(", "x", ")", "in", "col_categories", "else", "len", "(", "col_categories", ")", "-", "1", ")", "# Make sure numeric values are really numeric", "for", "numeric_col", "in", "self", ".", "_numeric_columns", ":", "df", "[", "numeric_col", "]", "=", "df", "[", "numeric_col", "]", ".", "apply", "(", "lambda", "x", ":", "float", "(", "x", ")", ")", "return", "df", ".", "as_matrix", "(", "self", ".", "_categorical_columns", "+", "self", ".", "_numeric_columns", ")" ]
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 also requires list of names for each category.
[ "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
237,799