docstring
stringlengths
52
499
function
stringlengths
67
35.2k
__index_level_0__
int64
52.6k
1.16M
Create Ladybug Datetime from a minute of the year. Args: moy: An integer value 0 <= and < 525600
def from_moy(cls, moy, leap_year=False): if not leap_year: num_of_minutes_until_month = (0, 44640, 84960, 129600, 172800, 217440, 260640, 305280, 349920, 393120, 437760, 480960, 525600) else: ...
435,525
Create a new DateTime after the minutes are added. Args: minute: An integer value for minutes.
def add_minute(self, minute): _moy = self.moy + int(minute) return self.__class__.from_moy(_moy)
435,528
Converts sequence of cartesian coordinates into a sequence of line segments defined by spherical coordinates. Args: xyz = 2d numpy array, each row specifies a point in cartesian coordinates (x,y,z) tracing out a path in 3D space. Returns: r = lengths of ...
def sequential_spherical(xyz): d_xyz = np.diff(xyz,axis=0) r = np.linalg.norm(d_xyz,axis=1) theta = np.arctan2(d_xyz[:,1], d_xyz[:,0]) hyp = d_xyz[:,0]**2 + d_xyz[:,1]**2 phi = np.arctan2(np.sqrt(hyp), d_xyz[:,2]) return (r,theta,phi)
435,843
Simple conversion of spherical to cartesian coordinates Args: r,theta,phi = scalar spherical coordinates Returns: x,y,z = scalar cartesian coordinates
def spherical_to_cartesian(r,theta,phi): x = r * np.sin(phi) * np.cos(theta) y = r * np.sin(phi) * np.sin(theta) z = r * np.cos(phi) return (x,y,z)
435,844
Find (x,y,z) ending coordinate of segment path along section path. Args: targ_length = scalar specifying length of segment path, starting from the begining of the section path xyz = coordinates specifying the section path rcum = cumulative sum of section path lengt...
def find_coord(targ_length,xyz,rcum,theta,phi): # [1] Find spherical coordinates for the line segment containing # the endpoint. # [2] Find endpoint in spherical coords and convert to cartesian i = np.nonzero(rcum <= targ_length)[0][-1] if i == len(theta): return xyz[-1,:]...
435,845
Interpolates along a jagged path in 3D Args: xyz = section path specified in cartesian coordinates nseg = number of segment paths in section path Returns: interp_xyz = interpolated path
def interpolate_jagged(xyz,nseg): # Spherical coordinates specifying the angles of all line # segments that make up the section path (r,theta,phi) = sequential_spherical(xyz) # cumulative length of section path at each coordinate rcum = np.append(0,np.cumsum(r)) # breakpoints for...
435,846
Marks one or more locations on along a section. Could be used to mark the location of a recording or electrical stimulation. Args: h = hocObject to interface with neuron section = reference to section locs = float between 0 and 1, or array of floats optional arguments specify de...
def mark_locations(h,section,locs,markspec='or',**kwargs): # get list of cartesian coordinates specifying section path xyz = get_section_path(h,section) (r,theta,phi) = sequential_spherical(xyz) rcum = np.append(0,np.cumsum(r)) # convert locs into lengths from the beginning of the path if...
435,851
Implements the datalab cell magic for MLWorkbench operations. Args: line: the contents of the ml command line. Returns: The results of executing the cell.
def ml(line, cell=None): parser = google.datalab.utils.commands.CommandParser( prog='%ml', description=textwrap.dedent()) dataset_parser = parser.subcommand( 'dataset', formatter_class=argparse.RawTextHelpFormatter, help='Create or explore datasets.') dataset_sub_commands = datas...
436,032
Create a Metrics instance from csv file pattern. Args: input_csv_pattern: Path to Csv file pattern (with no header). Can be local or GCS path. headers: Csv headers. schema_file: Path to a JSON file containing BigQuery schema. Used if "headers" is None. Returns: a Metrics instance. ...
def from_csv(input_csv_pattern, headers=None, schema_file=None): if headers is not None: names = headers elif schema_file is not None: with _util.open_local_or_gcs(schema_file, mode='r') as f: schema = json.load(f) names = [x['name'] for x in schema] else: raise ValueEr...
436,060
Create a Metrics instance from a bigquery query or table. Returns: a Metrics instance. Args: sql: A BigQuery table name or a query.
def from_bigquery(sql): if isinstance(sql, bq.Query): sql = sql._expanded_sql() parts = sql.split('.') if len(parts) == 1 or len(parts) > 3 or any(' ' in x for x in parts): sql = '(' + sql + ')' # query, not a table name else: sql = '`' + sql + '`' # table name metrics = ...
436,061
Get nearest percentile from regression model evaluation results. Args: percentile: a 0~100 float number. Returns: the percentile float number. Raises: Exception if the CSV headers do not include 'target' or 'predicted', or BigQuery does not return 'target' or 'predicted' column, o...
def percentile_nearest(self, percentile): if self._input_csv_files: df = self._get_data_from_csv_files() if 'target' not in df or 'predicted' not in df: raise ValueError('Cannot find "target" or "predicted" column') df = df[['target', 'predicted']].apply(pd.to_numeric) abs_err...
436,069
Initializes a UDF object from its pieces. Args: name: the name of the javascript function code: function body implementing the logic. return_type: BigQuery data type of the function return. See supported data types in the BigQuery docs params: list of parameter tuples: (name, type) ...
def __init__(self, name, code, return_type, params=None, language='js', imports=None): if not isinstance(return_type, basestring): raise TypeError('Argument return_type should be a string. Instead got: ', type(return_type)) if params and not isinstance(params, list): raise TypeError('Argument p...
436,070
Creates the UDF part of a BigQuery query using its pieces Args: name: the name of the javascript function code: function body implementing the logic. return_type: BigQuery data type of the function return. See supported data types in the BigQuery docs params: dictionary of parameter...
def _build_udf(name, code, return_type, params, language, imports): params = ','.join(['%s %s' % named_param for named_param in params]) imports = ','.join(['library="%s"' % i for i in imports]) if language.lower() == 'sql': udf = 'CREATE TEMPORARY FUNCTION {name} ({params})\n' + \ ...
436,072
Parse a gs:// URL into the bucket and object names. Args: name: a GCS URL of the form gs://bucket or gs://bucket/object Returns: The bucket name (with no gs:// prefix), and the object name if present. If the name could not be parsed returns None for both.
def parse_name(name): bucket = None obj = None m = re.match(_STORAGE_NAME, name) if m: # We want to return the last two groups as first group is the optional 'gs://' bucket = m.group(1) obj = m.group(2) if obj is not None: obj = obj[1:] # Strip '/' else: m = re.match('(' + _OBJEC...
436,073
Initializes an instance of a Bucket object. Args: name: the name of the bucket. info: the information about the bucket if available. context: an optional Context object providing project_id and credentials. If a specific project id or credentials are unspecified, the default ones config...
def __init__(self, name, info=None, context=None): if context is None: context = google.datalab.Context.default() self._context = context self._api = _api.Api(context) self._name = name self._info = info
436,075
Retrieves a Storage Object for the specified key in this bucket. The object need not exist. Args: key: the key of the object within the bucket. Returns: An Object instance representing the specified key.
def object(self, key): return _object.Object(self._name, key, context=self._context)
436,077
Initializes an instance of a BucketList. Args: context: an optional Context object providing project_id and credentials. If a specific project id or credentials are unspecified, the default ones configured at the global level are used.
def __init__(self, context=None): if context is None: context = google.datalab.Context.default() self._context = context self._api = _api.Api(context) self._project_id = context.project_id if context else self._api.project_id
436,080
Checks if the specified bucket exists. Args: name: the name of the bucket to lookup. Returns: True if the bucket exists; False otherwise. Raises: Exception if there was an error requesting information about the bucket.
def contains(self, name): try: self._api.buckets_get(name) except google.datalab.utils.RequestException as e: if e.status == 404: return False raise e except Exception as e: raise e return True
436,081
Parse a gs:// URL into the bucket and item names. Args: name: a GCS URL of the form gs://bucket or gs://bucket/item Returns: The bucket name (with no gs:// prefix), and the item name if present. If the name could not be parsed returns None for both.
def parse_name(name): bucket = None item = None m = re.match(_STORAGE_NAME, name) if m: # We want to return the last two groups as first group is the optional 'gs://' bucket = m.group(1) item = m.group(2) if item is not None: item = item[1:] # Strip '/' else: m = re.match('(' + _...
436,083
Retrieves an Item object for the specified key in this bucket. The item need not exist. Args: key: the key of the item within the bucket. Returns: An Item instance representing the specified key.
def item(self, key): return _item.Item(self._name, key, context=self._context)
436,084
Creates the bucket. Args: project_id: the project in which to create the bucket. Returns: The bucket. Raises: Exception if there was an error creating the bucket.
def create(self, project_id=None): if not self.exists(): if project_id is None: project_id = self._api.project_id try: self._info = self._api.buckets_insert(self._name, project_id=project_id) except Exception as e: raise e return self
436,086
Creates a new bucket. Args: name: a unique name for the new bucket. Returns: The newly created bucket. Raises: Exception if there was an error creating the bucket.
def create(self, name): return Bucket(name, context=self._context).create(self._project_id)
436,087
Initializes an instance of a Airflow object. Args: gcs_dag_bucket: Bucket where Airflow expects dag files to be uploaded. gcs_dag_file_path: File path of the Airflow dag files.
def __init__(self, gcs_dag_bucket, gcs_dag_file_path=None): self._gcs_dag_bucket = gcs_dag_bucket self._gcs_dag_file_path = gcs_dag_file_path or ''
436,093
Returns a list of resource descriptors that match the filters. Args: pattern: An optional pattern to further filter the descriptors. This can include Unix shell-style wildcards. E.g. ``"aws*"``, ``"*cluster*"``. Returns: A list of ResourceDescriptor objects that match the filters.
def list(self, pattern='*'): if self._descriptors is None: self._descriptors = self._client.list_resource_descriptors( filter_string=self._filter_string) return [resource for resource in self._descriptors if fnmatch.fnmatch(resource.type, pattern)]
436,095
Creates a pandas dataframe from the descriptors that match the filters. Args: pattern: An optional pattern to further filter the descriptors. This can include Unix shell-style wildcards. E.g. ``"aws*"``, ``"*cluster*"``. max_rows: The maximum number of descriptors to return. If None, return ...
def as_dataframe(self, pattern='*', max_rows=None): data = [] for i, resource in enumerate(self.list(pattern)): if max_rows is not None and i >= max_rows: break labels = ', '. join([l.key for l in resource.labels]) data.append([resource.type, resource.display_name, labels]) r...
436,096
A helper function to extract user-friendly error messages from service exceptions. Args: message: An error message from an exception. If this is from our HTTP client code, it will actually be a tuple. Returns: A modified version of the message that is less cryptic.
def _extract_gcs_api_response_error(message): try: if len(message) == 3: # Try treat the last part as JSON data = json.loads(message[2]) return data['error']['errors'][0]['message'] except Exception: pass return message
436,098
Implements the gcs cell magic for ipython notebooks. Args: line: the contents of the gcs line. Returns: The results of executing the cell.
def gcs(line, cell=None): parser = google.datalab.utils.commands.CommandParser(prog='%gcs', description=) # TODO(gram): consider adding a move command too. I did try this already using the # objects.patch API to change the object name but that fails with an error: # # Value 'newname' in content does not a...
436,099
Parse command line arguments. Args: argv: list of command line arguments including program name. Returns: The parsed arguments as returned by argparse.ArgumentParser.
def parse_arguments(argv): parser = argparse.ArgumentParser( formatter_class=argparse.RawDescriptionHelpFormatter, description=textwrap.dedent()) source_group = parser.add_mutually_exclusive_group(required=True) source_group.add_argument( '--csv', metavar='FILE', required=False,...
436,114
Parse a csv line into a dict. Args: csv_string: a csv string. May contain missing values "a,,c" column_names: list of column names Returns: Dict of {column_name, value_from_csv}. If there are missing values, value_from_csv will be ''.
def decode_csv(csv_string, column_names): import csv r = next(csv.reader([csv_string])) if len(r) != len(column_names): raise ValueError('csv line %s does not have %d columns' % (csv_string, len(column_names))) return {k: v for k, v in zip(column_names, r)}
436,118
Builds a csv string. Args: data_dict: dict of {column_name: 1 value} column_names: list of column names Returns: A csv string version of data_dict
def encode_csv(data_dict, column_names): import csv import six values = [str(data_dict[x]) for x in column_names] str_buff = six.StringIO() writer = csv.writer(str_buff, lineterminator='') writer.writerow(values) return str_buff.getvalue()
436,119
Makes a serialized tf.example. Args: transformed_json_data: dict of transformed data. info_dict: output of feature_transforms.get_transfrormed_feature_info() Returns: The serialized tf.example version of transformed_json_data.
def serialize_example(transformed_json_data, info_dict): import six import tensorflow as tf def _make_int64_list(x): return tf.train.Feature(int64_list=tf.train.Int64List(value=x)) def _make_bytes_list(x): return tf.train.Feature(bytes_list=tf.train.BytesList(value=x)) def _make_float_list(x): ...
436,120
Run the transformation graph on batched input data Args: element: list of csv strings, representing one batch input to the TF graph. Returns: dict containing the transformed data. Results are un-batched. Sparse tensors are converted to lists.
def process(self, element): import apache_beam as beam import six import tensorflow as tf # This function is invoked by a separate sub-process so setting the logging level # does not affect Datalab's kernel process. tf.logging.set_verbosity(tf.logging.ERROR) try: clean_element = ...
436,127
Parses a row from query results into an equivalent object. Args: schema: the array of fields defining the schema of the data. data: the JSON row from a query result. Returns: The parsed row object.
def parse_row(schema, data): def parse_value(data_type, value): if value is not None: if value == 'null': value = None elif data_type == 'INTEGER': value = int(value) elif data_type == 'FLOAT': value = float(value) elif data_type == 'TI...
436,128
Prediction with a tf savedmodel. Args: model_dir: directory that contains a saved model input_csvlines: list of csv strings Returns: Dict in the form tensor_name:prediction_list. Note that the value is always a list, even if there was only 1 row in input_csvlines.
def _tf_predict(model_dir, input_csvlines): with tf.Graph().as_default(), tf.Session() as sess: input_alias_map, output_alias_map = _tf_load_model(sess, model_dir) csv_tensor_name = list(input_alias_map.values())[0] results = sess.run(fetches=output_alias_map, feed_dict={csv_ten...
436,130
Get a local model's schema and features config. Args: model_dir: local or GCS path of a model. Returns: A tuple of schema (list) and features config (dict).
def get_model_schema_and_features(model_dir): schema_file = os.path.join(model_dir, 'assets.extra', 'schema.json') schema = json.loads(file_io.read_file_to_string(schema_file)) features_file = os.path.join(model_dir, 'assets.extra', 'features.json') features_config = json.loads(file_io.read_file_to_string(fe...
436,134
Initializes an instance of a CloudML Job. Args: name: the name of the job. It can be an operation full name ("projects/[project_id]/jobs/[operation_name]") or just [operation_name]. context: an optional Context object providing project_id and credentials.
def __init__(self, name, context=None): super(Job, self).__init__(name) if context is None: context = datalab.Context.default() self._context = context self._api = discovery.build('ml', 'v1', credentials=self._context.credentials) if not name.startswith('projects/'): name = 'project...
436,141
Initializes an instance of a CloudML Job list that is iteratable ("for job in jobs()"). Args: filter: filter string for retrieving jobs, such as "state=FAILED" context: an optional Context object providing project_id and credentials. api: an optional CloudML API client.
def __init__(self, filter=None): self._filter = filter self._context = datalab.Context.default() self._api = discovery.build('ml', 'v1', credentials=self._context.credentials) self._page_size = 0
436,146
Parse command line arguments. Args: argv: list of command line arguments, including program name. Returns: An argparse Namespace object. Raises: ValueError: for bad parameters
def parse_arguments(argv): parser = argparse.ArgumentParser( formatter_class=argparse.RawDescriptionHelpFormatter, description=textwrap.dedent()) parser.add_argument('--cloud', action='store_true', help='Analysis will use cloud services.') parser.add_argu...
436,149
Use BigQuery to analyze input date. Only one of csv_file_pattern or bigquery_table should be non-None. Args: output_dir: output folder csv_file_pattern: list of csv file paths, may contain wildcards bigquery_table: project_id.dataset_name.table_name schema: schema list features: features confi...
def run_cloud_analysis(output_dir, csv_file_pattern, bigquery_table, schema, features): def _execute_sql(sql, table): import google.datalab.bigquery as bq if isinstance(table, bq.ExternalDataSource): query = bq.Query(sql, data_sources={'csv_table': table}) else: ...
436,150
Defines the default InceptionV3 arg scope. Args: weight_decay: The weight decay to use for regularizing the model. stddev: The standard deviation of the trunctated normal weight initializer. batch_norm_var_collection: The name of the collection for the batch norm variables. Returns: An `arg_...
def inception_v3_arg_scope(weight_decay=0.00004, stddev=0.1, batch_norm_var_collection='moving_vars'): batch_norm_params = { # Decay for the moving averages. 'decay': 0.9997, # epsilon to prevent 0s in variance. 'epsilon': 0.001, #...
436,155
Initializes an instance of a Job. Args: job_id: a unique ID for the job. If None, a UUID will be generated. future: the Future associated with the Job, if any.
def __init__(self, job_id=None, future=None): self._job_id = str(uuid.uuid4()) if job_id is None else job_id self._future = future self._is_complete = False self._errors = None self._fatal_error = None self._result = None self._start_time = datetime.datetime.utcnow() self._end_time ...
436,161
Wait for the job to complete, or a timeout to happen. Args: timeout: how long to wait before giving up (in seconds); default None which means no timeout. Returns: The Job
def wait(self, timeout=None): if self._future: try: # Future.exception() will return rather than raise any exception so we use it. self._future.exception(timeout) except concurrent.futures.TimeoutError: self._timeout() self._refresh_state() else: # fall back ...
436,164
Return when at least one of the specified jobs has completed or timeout expires. Args: jobs: a Job or list of Jobs to wait on. timeout: a timeout in seconds to wait for. None (the default) means no timeout. Returns: A list of the jobs that have now completed or None if there were no jobs.
def wait_any(jobs, timeout=None): return Job._wait(jobs, timeout, concurrent.futures.FIRST_COMPLETED)
436,167
Return when at all of the specified jobs have completed or timeout expires. Args: jobs: a Job or list of Jobs to wait on. timeout: a timeout in seconds to wait for. None (the default) means no timeout. Returns: A list of the jobs that have now completed or None if there were no jobs.
def wait_all(jobs, timeout=None): return Job._wait(jobs, timeout, concurrent.futures.ALL_COMPLETED)
436,168
Parse command line arguments. Args: argv: list of command line arguments, includeing programe name. Returns: An argparse Namespace object. Raises: ValueError: for bad parameters
def parse_arguments(argv): parser = argparse.ArgumentParser( description='Runs Preprocessing on structured data.') parser.add_argument('--output-dir', type=str, required=True, help='Google Cloud Storage which to place outputs.') parser.ad...
436,182
Giving a string a:b.c, returns b.c. Args: bigquery_table: full table name project_id:dataset:table Returns: dataset:table Raises: ValueError: if a, b, or c contain the character ':'.
def parse_table_name(bigquery_table): id_name = bigquery_table.split(':') if len(id_name) != 2: raise ValueError('Bigquery table name should be in the form ' 'project_id:dataset.table_name. Got %s' % bigquery_table) return id_name[1]
436,183
Find min/max values for the numerical columns and writes a json file. Args: table: Reference to FederatedTable (if bigquery_table is false) or a regular Table (otherwise) schema_list: Bigquery schema json object args: the command line args
def run_numerical_analysis(table, schema_list, args): import google.datalab.bigquery as bq # Get list of numerical columns. numerical_columns = [] for col_schema in schema_list: col_type = col_schema['type'].lower() if col_type == 'integer' or col_type == 'float': numerical_columns.append(col_...
436,184
Find vocab values for the categorical columns and writes a csv file. The vocab files are in the from label1 label2 label3 ... Args: table: Reference to FederatedTable (if bigquery_table is false) or a regular Table (otherwise) schema_list: Bigquery schema json object args: the command ...
def run_categorical_analysis(table, schema_list, args): import google.datalab.bigquery as bq # Get list of categorical columns. categorical_columns = [] for col_schema in schema_list: col_type = col_schema['type'].lower() if col_type == 'string': categorical_columns.append(col_schema['name']) ...
436,185
Builds an analysis file for training. Uses BiqQuery tables to do the analysis. Args: args: command line args Raises: ValueError if schema contains unknown types.
def run_analysis(args): import google.datalab.bigquery as bq if args.bigquery_table: table = bq.Table(args.bigquery_table) schema_list = table.schema._bq_schema else: schema_list = json.loads( file_io.read_file_to_string(args.schema_file).decode()) table = bq.ExternalDataSource( ...
436,186
Initializes an instance of a Context object. Args: project_id: the current cloud project. credentials: the credentials to use to authorize requests. config: key/value configurations for cloud operations
def __init__(self, project_id, credentials, config=None): self._project_id = project_id self._credentials = credentials self._config = config if config is not None else Context._get_default_config()
436,188
Create a ConfusionMatrix from a BigQuery table or query. Args: sql: Can be one of: A SQL query string. A Bigquery table string. A Query object defined with '%%bq query --name [query_name]'. The query results or table must include "target", "predicted" columns. Returns:...
def from_bigquery(sql): if isinstance(sql, bq.Query): sql = sql._expanded_sql() parts = sql.split('.') if len(parts) == 1 or len(parts) > 3 or any(' ' in x for x in parts): sql = '(' + sql + ')' # query, not a table name else: sql = '`' + sql + '`' # table name query = bq....
436,193
Plot the confusion matrix. Args: figsize: tuple (x, y) of ints. Sets the size of the figure rotation: the rotation angle of the labels on the x-axis.
def plot(self, figsize=None, rotation=45): fig, ax = plt.subplots(figsize=figsize) plt.imshow(self._cm, interpolation='nearest', cmap=plt.cm.Blues, aspect='auto') plt.title('Confusion matrix') plt.colorbar() tick_marks = np.arange(len(self._labels)) plt.xticks(tick_marks, self._labels, ro...
436,195
Issues a request to Composer to get the environment details. Args: zone: GCP zone of the composer environment environment: name of the Composer environment Returns: A parsed result object. Raises: Exception if there is an error performing the operation.
def get_environment_details(zone, environment): default_context = google.datalab.Context.default() url = (Api._ENDPOINT + (Api._ENVIRONMENTS_PATH_FORMAT % (default_context.project_id, zone, environment))) return google.datalab.utils.Http.req...
436,196
Initializes the Storage helper with context information. Args: context: a Context object providing project_id and credentials.
def __init__(self, context): self._credentials = context.credentials self._project_id = context.project_id
436,197
Issues a request to delete a bucket. Args: bucket: the name of the bucket. Raises: Exception if there is an error performing the operation.
def buckets_delete(self, bucket): url = Api._ENDPOINT + (Api._BUCKET_PATH % bucket) google.datalab.utils.Http.request(url, method='DELETE', credentials=self._credentials, raw_response=True)
436,198
Issues a request to retrieve information about a bucket. Args: bucket: the name of the bucket. projection: the projection of the bucket information to retrieve. Returns: A parsed bucket information dictionary. Raises: Exception if there is an error performing the operation.
def buckets_get(self, bucket, projection='noAcl'): args = {'projection': projection} url = Api._ENDPOINT + (Api._BUCKET_PATH % bucket) return google.datalab.utils.Http.request(url, credentials=self._credentials, args=args)
436,199
Issues a request to retrieve the list of buckets. Args: projection: the projection of the bucket information to retrieve. max_results: an optional maximum number of objects to retrieve. page_token: an optional token to continue the retrieval. project_id: the project whose buckets should be ...
def buckets_list(self, projection='noAcl', max_results=0, page_token=None, project_id=None): if max_results == 0: max_results = Api._MAX_RESULTS args = {'project': project_id if project_id else self._project_id, 'maxResults': max_results} if projection is not None: args['projection'] = pro...
436,200
Reads the contents of an object as text. Args: bucket: the name of the bucket containing the object. key: the key of the object to be read. 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 con...
def object_download(self, bucket, key, start_offset=0, byte_count=None): args = {'alt': 'media'} headers = {} if start_offset > 0 or byte_count is not None: header = 'bytes=%d-' % start_offset if byte_count is not None: header += '%d' % byte_count headers['Range'] = header ...
436,201
Writes text content to the object. Args: bucket: the name of the bucket containing the object. key: the key of the object to be written. content: the text content to be written. content_type: the type of text content. Raises: Exception if the object could not be written to.
def object_upload(self, bucket, key, content, content_type): args = {'uploadType': 'media', 'name': key} headers = {'Content-Type': content_type} url = Api._UPLOAD_ENDPOINT + (Api._OBJECT_PATH % (bucket, '')) return google.datalab.utils.Http.request(url, args=args, data=content, headers=headers, ...
436,202
Updates the metadata associated with an object. Args: bucket: the name of the bucket containing the object. key: the key of the object being updated. info: the metadata to update. Returns: A parsed object information dictionary. Raises: Exception if there is an error performin...
def objects_patch(self, bucket, key, info): url = Api._ENDPOINT + (Api._OBJECT_PATH % (bucket, Api._escape_key(key))) return google.datalab.utils.Http.request(url, method='PATCH', data=info, credentials=self._credentials)
436,204
Check if the user has permissions to read from the given path. Args: gs_path: the GCS path to check if user is permitted to read. Raises: Exception if user has no permissions to read.
def verify_permitted_to_read(gs_path): # TODO(qimingj): Storage APIs need to be modified to allow absence of project # or credential on Objects. When that happens we can move the function # to Objects class. from . import _bucket bucket, prefix = _bucket.parse_name...
436,205
Initializes an instance of a Job. Args: job_id: the BigQuery job ID corresponding to this job. context: a Context object providing project_id and credentials.
def __init__(self, job_id, context): super(Job, self).__init__(job_id, context)
436,224
Implements the monitoring cell magic for ipython notebooks. Args: line: the contents of the storage line. Returns: The results of executing the cell.
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 res...
436,227
create html representation of status of a job (long running operation). Args: job_name: the full name of the job. job_type: type of job. Can be 'local' or 'cloud'. refresh_interval: how often should the client refresh status. html_on_running: additional html that the job view needs to include on job ...
def html_job_status(job_name, job_type, refresh_interval, html_on_running, html_on_success): _HTML_TEMPLATE = div_id = _html.Html.next_id() return IPython.core.display.HTML(_HTML_TEMPLATE % (div_id, div_id, job_name, job_type, refresh_interval, html_on_running, html_on_succe...
436,232
Initializes an instance of an Object. Args: bucket: the name of the bucket containing the object. key: the key of the object. info: the information about the object if available. context: an optional Context object providing project_id and credentials. If a specific project id or ...
def __init__(self, bucket, key, info=None, context=None): if context is None: context = google.datalab.Context.default() self._context = context self._api = _api.Api(context) self._bucket = bucket self._key = key self._info = info
436,237
Deletes this object from its bucket. Args: wait_for_deletion: If True, we poll until this object no longer appears in objects.list operations for this bucket before returning. Raises: Exception if there was an error deleting the object.
def delete(self, wait_for_deletion=True): if self.exists(): try: self._api.objects_delete(self._bucket, self._key) except Exception as e: raise e if wait_for_deletion: for _ in range(_MAX_POLL_ATTEMPTS): objects = Objects(self._bucket, prefix=self.key, delimi...
436,239
Reads the content of this object as text. Args: start_offset: the start offset of bytes to read. byte_count: the number of bytes to read. If None, it reads to the end. Returns: The text content within the object. Raises: Exception if there was an error requesting the object's conten...
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
436,241
Reads the content of this object as text, and return a list of lines up to some max. Args: max_lines: max number of lines to return. If None, return all lines. Returns: The text content of the object as a list of lines. Raises: Exception if there was an error requesting the object's conte...
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'...
436,242
Initializes an instance of a Csv instance. Args: path: path of the Csv file. delimiter: the separator used to parse a Csv line.
def __init__(self, path, delimiter=b','): self._path = path self._delimiter = delimiter
436,244
Initializes an instance of an Iterator. Args: retriever: a function that can retrieve the next page of items.
def __init__(self, retriever): self._page_token = None self._first_page = True self._retriever = retriever self._count = 0
436,251
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.
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)
436,258
Updates the metadata associated with an object. Args: source_bucket: the name of the bucket containing the source object. source_key: the key of the source object being copied. target_bucket: the name of the bucket that will contain the copied object. target_key: the key of the copied objec...
def objects_copy(self, source_bucket, source_key, target_bucket, target_key): url = Api._ENDPOINT + (Api._OBJECT_COPY_PATH % (source_bucket, Api._escape_key(source_key), target_bucket, Api._escape_key(target_key))) return datalab.utils.Http.request(url, m...
436,259
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.
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)
436,260
Issues a request to retrieve information about an object. Args: bucket: the name of the bucket. key: the key of the object within the bucket. projection: the projection of the object to retrieve. Returns: A parsed object information dictionary. Raises: Exception if there is an...
def objects_get(self, bucket, key, projection='noAcl'): args = {} if projection is not None: args['projection'] = projection url = Api._ENDPOINT + (Api._OBJECT_PATH % (bucket, Api._escape_key(key))) return datalab.utils.Http.request(url, args=args, credentials=self._credentials)
436,261
Check if the user has permissions to read from the given path. Args: gs_path: the GCS path to check if user is permitted to read. Raises: Exception if user has no permissions to read.
def verify_permitted_to_read(gs_path): # TODO(qimingj): Storage APIs need to be modified to allow absence of project # or credential on Items. When that happens we can move the function # to Items class. from . import _bucket bucket, prefix = _bucket.parse_name(gs_...
436,262
Initializes a QueryJob object. Args: job_id: the ID of the query job. table_name: the name of the table where the query results will be stored. sql: the SQL statement that was executed for the query. context: the Context object providing project_id and credentials that was used wh...
def __init__(self, job_id, table_name, sql, context): super(QueryJob, self).__init__(job_id, context) self._sql = sql self._table = _query_results_table.QueryResultsTable(table_name, context, self, is_temporary=True) self._bytes_processed = N...
436,263
Wait for the job to complete, or a timeout to happen. This is more efficient than the version in the base Job class, in that we can use a call that blocks for the poll duration rather than a sleep. That means we shouldn't block unnecessarily long and can also poll less. Args: timeout: how ...
def wait(self, timeout=None): poll = 30 while not self._is_complete: try: query_result = self._api.jobs_query_results(self._job_id, project_id=self._context.project_id, page_size=0, ...
436,264
Returns a list of metric descriptors that match the filters. Args: pattern: An optional pattern to further filter the descriptors. This can include Unix shell-style wildcards. E.g. ``"compute*"``, ``"*cpu/load_??m"``. Returns: A list of MetricDescriptor objects that match the f...
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)]
436,266
Creates a pandas dataframe from the 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"``. max_rows: The maximum number of descriptors to return...
def as_dataframe(self, pattern='*', max_rows=None): data = [] for i, metric in enumerate(self.list(pattern)): if max_rows is not None and i >= max_rows: break labels = ', '. join([l.key for l in metric.labels]) data.append([ metric.type, metric.display_name, metric.metri...
436,267
Given a %%sql module return the default (last) query for the module. Args: module: the %%sql module. Returns: The default query associated with this module.
def get_default_query_from_module(module): if isinstance(module, types.ModuleType): return module.__dict__.get(_SQL_MODULE_LAST, None) return None
436,268
Initializes an instance of a Job. Args: fn: the lambda function to execute asyncronously job_id: an optional ID for the job. If None, a UUID will be generated.
def __init__(self, fn, job_id, *args, **kwargs): super(LambdaJob, self).__init__(job_id) self._future = _async.async.executor.submit(fn, *args, **kwargs)
436,270
Infer a BigQuery table schema from a dictionary. If the dictionary has entries that are in turn OrderedDicts these will be turned into RECORD types. Ideally this will be an OrderedDict but it is not required. Args: data: The dict to infer a schema from. Returns: A list of dictionaries conta...
def _from_dict_record(data): return [Schema._get_field_entry(name, value) for name, value in list(data.items())]
436,272
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.
def _from_list_record(data): return [Schema._get_field_entry('Column%d' % (i + 1), value) for i, value in enumerate(data)]
436,273
Infer a BigQuery table schema from a list of fields or a dictionary. The typeof the elements is used. For a list, the field names are simply 'Column1', 'Column2', etc. Args: data: The list of fields or dictionary. Returns: A list of dictionaries containing field 'name' and 'type' entries, suita...
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))
436,274
Initializes a Schema from its raw JSON representation, a Pandas Dataframe, or a list. Args: definition: a definition of the schema as a list of dictionaries with 'name' and 'type' entries and possibly 'mode' and 'description' entries. Only used if no data argument was provided. 'mode' can...
def __init__(self, definition=None): super(Schema, self).__init__() self._map = {} self._bq_schema = definition self._populate_fields(definition)
436,276
Get the index of a field in the flattened list given its (fully-qualified) name. Args: name: the fully-qualified name of the field. Returns: The index of the field, if found; else -1.
def find(self, name): for i in range(0, len(self)): if self[i].name == name: return i return -1
436,279
Return a dictionary list formatted as a HTML table. Args: data: the dictionary list headers: the keys in the dictionary to use as table columns, in order.
def render_dictionary(data, headers=None): return IPython.core.display.HTML(_html.HtmlBuilder.render_table(data, headers))
436,287
Return text formatted as a HTML Args: text: the text to render preformatted: whether the text should be rendered as preformatted
def render_text(text, preformatted=False): return IPython.core.display.HTML(_html.HtmlBuilder.render_text(text, preformatted))
436,288
If v is a variable reference (for example: '$myvar'), replace it using the supplied env dictionary. Args: v: the variable to replace if needed. env: user supplied dictionary. Raises: Exception if v is a variable reference but it is not found in env.
def expand_var(v, env): if len(v) == 0: return v # Using len() and v[0] instead of startswith makes this Unicode-safe. if v[0] == '$': v = v[1:] if len(v) and v[0] != '$': if v in env: v = env[v] else: raise Exception('Cannot expand variable $%s' % v) return v
436,295
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.
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): ...
436,296
Validate a config dictionary to make sure it includes all required keys and does not include any unexpected keys. Args: config: the config to validate. required_keys: the names of the keys that the config must have. optional_keys: the names of the keys that the config can have. Raises: Excep...
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('Inval...
436,298
Validate a config dictionary to make sure it has all of the specified keys Args: config: the config to validate. required_keys: the list of possible keys that config must include. Raises: Exception if the config does not have any of them.
def validate_config_must_have(config, required_keys): missing_keys = set(required_keys) - set(config) if len(missing_keys) > 0: raise Exception('Invalid config with missing keys "%s"' % ', '.join(missing_keys))
436,299
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.
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' % ',...
436,300
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.
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)))
436,301
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
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)
436,303
Generate a profile of data in a dataframe. Args: df: the Pandas dataframe.
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'))
436,305
Check files starts wtih gs://. Args: files: string to file path, or list of file paths.
def _assert_gcs_files(files): if sys.version_info.major > 2: string_type = (str, bytes) # for python 3 compatibility else: string_type = basestring # noqa if isinstance(files, string_type): files = [files] for f in files: if f is not None and not f.startswith('gs://'): raise ValueE...
436,307
Repackage this package from local installed location and copy it to GCS. Args: staging_package_url: GCS 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( ...
436,308
Helper function. Wait for a process to finish if it exists, and then try to kill a list of processes. Used by local_train Args: pid_to_wait: the process to wait for. pids_to_kill: a list of processes to kill after the process of pid_to_wait finishes.
def _wait_and_kill(pid_to_wait, pids_to_kill): # cloud workers don't have psutil import psutil if psutil.pid_exists(pid_to_wait): psutil.Process(pid=pid_to_wait).wait() for pid_to_kill in pids_to_kill: if psutil.pid_exists(pid_to_kill): p = psutil.Process(pid=pid_to_kill) p.kill() ...
436,309
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.
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_...
436,315