idx
int64
0
252k
question
stringlengths
48
5.28k
target
stringlengths
5
1.23k
237,800
def _make_tabular_predict_fn ( self , labels , instance , categories ) : def _predict_fn ( np_instance ) : df = pd . DataFrame ( np_instance , columns = ( self . _categorical_columns + self . _numeric_columns ) ) for col_name , col_categories in zip ( self . _categorical_columns , categories ) : df [ col_name ] = df [ ...
Create a predict_fn that can be used by LIME tabular explainer .
237,801
def explain_tabular ( self , trainset , labels , instance , num_features = 5 , kernel_width = 3 ) : from lime . lime_tabular import LimeTabularExplainer if isinstance ( instance , six . string_types ) : instance = next ( csv . DictReader ( [ instance ] , fieldnames = self . _headers ) ) categories = self . _get_unique_...
Explain categorical and numeric features for a prediction .
237,802
def explain_text ( self , labels , instance , column_name = None , num_features = 10 , num_samples = 5000 ) : from lime . lime_text import LimeTextExplainer if len ( self . _text_columns ) > 1 and not column_name : raise ValueError ( 'There are multiple text columns in the input of the model. ' + 'Please specify "colum...
Explain a text field of a prediction .
237,803
def explain_image ( self , labels , instance , column_name = None , num_features = 100000 , num_samples = 300 , batch_size = 200 , hide_color = 0 ) : from lime . lime_image import LimeImageExplainer if len ( self . _image_columns ) > 1 and not column_name : raise ValueError ( 'There are multiple image columns in the in...
Explain an image of a prediction .
237,804
def probe_image ( self , labels , instance , column_name = None , num_scaled_images = 50 , top_percent = 10 ) : if len ( self . _image_columns ) > 1 and not column_name : raise ValueError ( 'There are multiple image columns in the input of the model. ' + 'Please specify "column_name".' ) elif column_name and column_nam...
Get pixel importance of the image .
237,805
def get_model_details ( self , model_name ) : full_name = model_name if not model_name . startswith ( 'projects/' ) : full_name = ( 'projects/%s/models/%s' % ( self . _project_id , model_name ) ) return self . _api . projects ( ) . models ( ) . get ( name = full_name ) . execute ( )
Get details of the specified model from CloudML Service .
237,806
def create ( self , model_name ) : body = { 'name' : model_name } parent = 'projects/' + self . _project_id return self . _api . projects ( ) . models ( ) . create ( body = body , parent = parent ) . execute ( )
Create a model .
237,807
def list ( self , count = 10 ) : import IPython data = [ ] for _ , model in zip ( range ( count ) , self . get_iterator ( ) ) : element = { 'name' : model [ 'name' ] } if 'defaultVersion' in model : version_short_name = model [ 'defaultVersion' ] [ 'name' ] . split ( '/' ) [ - 1 ] element [ 'defaultVersion' ] = version...
List models under the current project in a table view .
237,808
def get_version_details ( self , version_name ) : name = ( '%s/versions/%s' % ( self . _full_model_name , version_name ) ) return self . _api . projects ( ) . models ( ) . versions ( ) . get ( name = name ) . execute ( )
Get details of a version .
237,809
def deploy ( self , version_name , path , runtime_version = None ) : if not path . startswith ( 'gs://' ) : raise Exception ( 'Invalid path. Only Google Cloud Storage path (gs://...) is accepted.' ) if not datalab . storage . Object . from_url ( os . path . join ( path , 'export.meta' ) ) . exists ( ) and not datalab ....
Deploy a model version to the cloud .
237,810
def delete ( self , version_name ) : name = ( '%s/versions/%s' % ( self . _full_model_name , version_name ) ) response = self . _api . projects ( ) . models ( ) . versions ( ) . delete ( name = name ) . execute ( ) if 'name' not in response : raise Exception ( 'Invalid response from service. "name" is not found.' ) _ut...
Delete a version of model .
237,811
def predict ( self , version_name , data ) : full_version_name = ( '%s/versions/%s' % ( self . _full_model_name , version_name ) ) request = self . _api . projects ( ) . predict ( body = { 'instances' : data } , name = full_version_name ) request . headers [ 'user-agent' ] = 'GoogleCloudDataLab/1.0' result = request . ...
Get prediction results from features instances .
237,812
def list ( self ) : import IPython data = [ { 'name' : version [ 'name' ] . split ( ) [ - 1 ] , 'deploymentUri' : version [ 'deploymentUri' ] , 'createTime' : version [ 'createTime' ] } for version in self . get_iterator ( ) ] IPython . display . display ( datalab . utils . commands . render_dictionary ( data , [ 'name...
List versions under the current model in a table view .
237,813
def create_feature_map ( features , feature_indices , output_dir ) : feature_map = [ ] for name , info in feature_indices : transform_name = features [ name ] [ 'transform' ] source_column = features [ name ] [ 'source_column' ] if transform_name in [ IDENTITY_TRANSFORM , SCALE_TRANSFORM ] : feature_map . append ( ( in...
Returns feature_map about the transformed features .
237,814
def create ( self , query ) : if isinstance ( query , _query . Query ) : query = query . sql try : response = self . _table . _api . tables_insert ( self . _table . name , query = query ) except Exception as e : raise e if 'selfLink' in response : return self raise Exception ( "View %s could not be created as it alread...
Creates the view with the specified query .
237,815
def sample ( self , fields = None , count = 5 , sampling = None , use_cache = True , dialect = None , billing_tier = None ) : return self . _table . sample ( fields = fields , count = count , sampling = sampling , use_cache = use_cache , dialect = dialect , billing_tier = billing_tier )
Retrieves a sampling of data from the view .
237,816
def update ( self , friendly_name = None , description = None , query = None ) : self . _table . _load_info ( ) if query is not None : if isinstance ( query , _query . Query ) : query = query . sql self . _table . _info [ 'view' ] = { 'query' : query } self . _table . update ( friendly_name = friendly_name , descriptio...
Selectively updates View information .
237,817
def results ( self , use_cache = True , dialect = None , billing_tier = None ) : return self . _materialization . results ( use_cache = use_cache , dialect = dialect , billing_tier = billing_tier )
Materialize the view synchronously .
237,818
def execute_async ( self , table_name = None , table_mode = 'create' , use_cache = True , priority = 'high' , allow_large_results = False , dialect = None , billing_tier = None ) : return self . _materialization . execute_async ( table_name = table_name , table_mode = table_mode , use_cache = use_cache , priority = pri...
Materialize the View asynchronously .
237,819
def get_notebook_item ( name ) : env = notebook_environment ( ) return google . datalab . utils . get_item ( env , name )
Get an item from the IPython environment .
237,820
def _get_data_from_list_of_dicts ( source , fields = '*' , first_row = 0 , count = - 1 , schema = None ) : if schema is None : schema = google . datalab . bigquery . Schema . from_data ( source ) fields = get_field_list ( fields , schema ) gen = source [ first_row : first_row + count ] if count >= 0 else source rows = ...
Helper function for _get_data that handles lists of dicts .
237,821
def _get_data_from_list_of_lists ( source , fields = '*' , first_row = 0 , count = - 1 , schema = None ) : if schema is None : schema = google . datalab . bigquery . Schema . from_data ( source ) fields = get_field_list ( fields , schema ) gen = source [ first_row : first_row + count ] if count >= 0 else source cols = ...
Helper function for _get_data that handles lists of lists .
237,822
def _get_data_from_dataframe ( source , fields = '*' , first_row = 0 , count = - 1 , schema = None ) : if schema is None : schema = google . datalab . bigquery . Schema . from_data ( source ) fields = get_field_list ( fields , schema ) rows = [ ] if count < 0 : count = len ( source . index ) df_slice = source . reset_i...
Helper function for _get_data that handles Pandas DataFrames .
237,823
def parse_config_for_selected_keys ( content , keys ) : config_items = { key : None for key in keys } if not content : return config_items , content stripped = content . strip ( ) if len ( stripped ) == 0 : return { } , None elif stripped [ 0 ] == '{' : config = json . loads ( content ) else : config = yaml . load ( co...
Parse a config from a magic cell body for selected config keys .
237,824
def chart_html ( driver_name , chart_type , source , chart_options = None , fields = '*' , refresh_interval = 0 , refresh_data = None , control_defaults = None , control_ids = None , schema = None ) : div_id = _html . Html . next_id ( ) controls_html = '' if control_defaults is None : control_defaults = { } if control_...
Return HTML for a chart .
237,825
def default ( fields = None , count = 5 ) : projection = Sampling . _create_projection ( fields ) return lambda sql : 'SELECT %s FROM (%s) LIMIT %d' % ( projection , sql , count )
Provides a simple default sampling strategy which limits the result set by a count .
237,826
def sorted ( field_name , ascending = True , fields = None , count = 5 ) : if field_name is None : raise Exception ( 'Sort field must be specified' ) direction = '' if ascending else ' DESC' projection = Sampling . _create_projection ( fields ) return lambda sql : 'SELECT %s FROM (%s) ORDER BY %s%s LIMIT %d' % ( projec...
Provides a sampling strategy that picks from an ordered set of rows .
237,827
def hashed ( field_name , percent , fields = None , count = 0 ) : if field_name is None : raise Exception ( 'Hash field must be specified' ) def _hashed_sampling ( sql ) : projection = Sampling . _create_projection ( fields ) sql = 'SELECT %s FROM (%s) WHERE MOD(ABS(FARM_FINGERPRINT(CAST(%s AS STRING))), 100) < %d' % (...
Provides a sampling strategy based on hashing and selecting a percentage of data .
237,828
def random ( percent , fields = None , count = 0 ) : def _random_sampling ( sql ) : projection = Sampling . _create_projection ( fields ) sql = 'SELECT %s FROM (%s) WHERE rand() < %f' % ( projection , sql , ( float ( percent ) / 100.0 ) ) if count != 0 : sql = '%s LIMIT %d' % ( sql , count ) return sql return _random_s...
Provides a sampling strategy that picks a semi - random set of rows .
237,829
def _auto ( method , fields , count , percent , key_field , ascending ) : if method == 'limit' : return Sampling . default ( fields = fields , count = count ) elif method == 'random' : return Sampling . random ( fields = fields , percent = percent , count = count ) elif method == 'hashed' : return Sampling . hashed ( f...
Construct a sampling function according to the provided sampling technique provided all its needed fields are passed as arguments
237,830
def _to_query_json ( self ) : return { 'quote' : self . _quote , 'fieldDelimiter' : self . _delimiter , 'encoding' : self . _encoding . upper ( ) , 'skipLeadingRows' : self . _skip_leading_rows , 'allowQuotedNewlines' : self . _allow_quoted_newlines , 'allowJaggedRows' : self . _allow_jagged_rows }
Return the options as a dictionary to be used as JSON in a query job .
237,831
def jobs_insert_load ( self , source , table_name , append = False , overwrite = False , create = False , source_format = 'CSV' , field_delimiter = ',' , allow_jagged_rows = False , allow_quoted_newlines = False , encoding = 'UTF-8' , ignore_unknown_values = False , max_bad_records = 0 , quote = '"' , skip_leading_rows...
Issues a request to load data from GCS to a BQ table
237,832
def jobs_get ( self , job_id , project_id = None ) : if project_id is None : project_id = self . _project_id url = Api . _ENDPOINT + ( Api . _JOBS_PATH % ( project_id , job_id ) ) return datalab . utils . Http . request ( url , credentials = self . _credentials )
Issues a request to retrieve information about a job .
237,833
def datasets_insert ( self , dataset_name , friendly_name = None , description = None ) : url = Api . _ENDPOINT + ( Api . _DATASETS_PATH % ( dataset_name . project_id , '' ) ) data = { 'kind' : 'bigquery#dataset' , 'datasetReference' : { 'projectId' : dataset_name . project_id , 'datasetId' : dataset_name . dataset_id ...
Issues a request to create a dataset .
237,834
def datasets_delete ( self , dataset_name , delete_contents ) : url = Api . _ENDPOINT + ( Api . _DATASETS_PATH % dataset_name ) args = { } if delete_contents : args [ 'deleteContents' ] = True return datalab . utils . Http . request ( url , method = 'DELETE' , args = args , credentials = self . _credentials , raw_respo...
Issues a request to delete a dataset .
237,835
def datasets_update ( self , dataset_name , dataset_info ) : url = Api . _ENDPOINT + ( Api . _DATASETS_PATH % dataset_name ) return datalab . utils . Http . request ( url , method = 'PUT' , data = dataset_info , credentials = self . _credentials )
Updates the Dataset info .
237,836
def datasets_get ( self , dataset_name ) : url = Api . _ENDPOINT + ( Api . _DATASETS_PATH % dataset_name ) return datalab . utils . Http . request ( url , credentials = self . _credentials )
Issues a request to retrieve information about a dataset .
237,837
def datasets_list ( self , project_id = None , max_results = 0 , page_token = None ) : if project_id is None : project_id = self . _project_id url = Api . _ENDPOINT + ( Api . _DATASETS_PATH % ( project_id , '' ) ) args = { } if max_results != 0 : args [ 'maxResults' ] = max_results if page_token is not None : args [ 'p...
Issues a request to list the datasets in the project .
237,838
def tables_get ( self , table_name ) : url = Api . _ENDPOINT + ( Api . _TABLES_PATH % table_name ) return datalab . utils . Http . request ( url , credentials = self . _credentials )
Issues a request to retrieve information about a table .
237,839
def tables_insert ( self , table_name , schema = None , query = None , friendly_name = None , description = None ) : url = Api . _ENDPOINT + ( Api . _TABLES_PATH % ( table_name . project_id , table_name . dataset_id , '' , '' ) ) data = { 'kind' : 'bigquery#table' , 'tableReference' : { 'projectId' : table_name . proje...
Issues a request to create a table or view in the specified dataset with the specified id . A schema must be provided to create a Table or a query must be provided to create a View .
237,840
def tabledata_insert_all ( self , table_name , rows ) : url = Api . _ENDPOINT + ( Api . _TABLES_PATH % table_name ) + "/insertAll" data = { 'kind' : 'bigquery#tableDataInsertAllRequest' , 'rows' : rows } return datalab . utils . Http . request ( url , data = data , credentials = self . _credentials )
Issues a request to insert data into a table .
237,841
def tabledata_list ( self , table_name , start_index = None , max_results = None , page_token = None ) : url = Api . _ENDPOINT + ( Api . _TABLEDATA_PATH % table_name ) args = { } if start_index : args [ 'startIndex' ] = start_index if max_results : args [ 'maxResults' ] = max_results if page_token is not None : args [ ...
Retrieves the contents of a table .
237,842
def table_delete ( self , table_name ) : url = Api . _ENDPOINT + ( Api . _TABLES_PATH % table_name ) return datalab . utils . Http . request ( url , method = 'DELETE' , credentials = self . _credentials , raw_response = True )
Issues a request to delete a table .
237,843
def table_extract ( self , table_name , destination , format = 'CSV' , compress = True , field_delimiter = ',' , print_header = True ) : url = Api . _ENDPOINT + ( Api . _JOBS_PATH % ( table_name . project_id , '' ) ) if isinstance ( destination , basestring ) : destination = [ destination ] data = { 'kind' : 'bigquery#...
Exports the table to GCS .
237,844
def table_update ( self , table_name , table_info ) : url = Api . _ENDPOINT + ( Api . _TABLES_PATH % table_name ) return datalab . utils . Http . request ( url , method = 'PUT' , data = table_info , credentials = self . _credentials )
Updates the Table info .
237,845
def extract_archive ( archive_path , dest ) : if not os . path . isdir ( dest ) : os . makedirs ( dest ) try : tmpfolder = None if ( not tf . gfile . Exists ( archive_path ) ) or tf . gfile . IsDirectory ( archive_path ) : raise ValueError ( 'archive path %s is not a file' % archive_path ) if archive_path . startswith ...
Extract a local or GCS archive file to a folder .
237,846
def preprocess ( train_dataset , output_dir , eval_dataset , checkpoint , pipeline_option ) : import apache_beam as beam import google . datalab . utils from . import _preprocess if checkpoint is None : checkpoint = _util . _DEFAULT_CHECKPOINT_GSURL job_name = ( 'preprocess-image-classification-' + datetime . datetime ...
Preprocess data in Cloud with DataFlow .
237,847
def train ( input_dir , batch_size , max_steps , output_dir , checkpoint , cloud_train_config ) : import google . datalab . ml as ml if checkpoint is None : checkpoint = _util . _DEFAULT_CHECKPOINT_GSURL staging_package_url = _util . repackage_to_staging ( output_dir ) job_args = { 'input_dir' : input_dir , 'max_steps'...
Train model in the cloud with CloudML trainer service .
237,848
def from_table ( table , fields = None ) : if fields is None : fields = '*' elif isinstance ( fields , list ) : fields = ',' . join ( fields ) return Query ( 'SELECT %s FROM %s' % ( fields , table . _repr_sql_ ( ) ) )
Return a Query for the given Table object
237,849
def _expanded_sql ( self , sampling = None ) : udfs = [ ] subqueries = [ ] expanded_sql = '' def _recurse_subqueries ( query ) : if query . _subqueries : for subquery in query . _subqueries : _recurse_subqueries ( subquery [ 1 ] ) subqueries . extend ( [ s for s in query . _subqueries if s not in subqueries ] ) if quer...
Get the expanded SQL of this object including all subqueries UDFs and external datasources
237,850
def run_and_monitor ( args , pid_to_wait , std_out_filter_fn = None , cwd = None ) : monitor_process = None try : p = subprocess . Popen ( args , cwd = cwd , env = os . environ , stdout = subprocess . PIPE , stderr = subprocess . STDOUT ) pids_to_kill = [ p . pid ] script = ( 'import %s;%s._wait_and_kill(%s, %s)' % ( _...
Start a process and have it depend on another specified process .
237,851
def created_on ( self ) : timestamp = self . _info . get ( 'creationTime' ) return _parser . Parser . parse_timestamp ( timestamp )
The creation timestamp .
237,852
def expires_on ( self ) : timestamp = self . _info . get ( 'expirationTime' , None ) if timestamp is None : return None return _parser . Parser . parse_timestamp ( timestamp )
The timestamp for when the table will expire or None if unknown .
237,853
def modified_on ( self ) : timestamp = self . _info . get ( 'lastModifiedTime' ) return _parser . Parser . parse_timestamp ( timestamp )
The timestamp for when the table was last modified .
237,854
def _load_info ( self ) : if self . _info is None : try : self . _info = self . _api . tables_get ( self . _name_parts ) except Exception as e : raise e
Loads metadata about this table .
237,855
def exists ( self ) : try : info = self . _api . tables_get ( self . _name_parts ) except google . datalab . utils . RequestException as e : if e . status == 404 : return False raise e except Exception as e : raise e self . _info = info return True
Checks if the table exists .
237,856
def delete ( self ) : try : self . _api . table_delete ( self . _name_parts ) except google . datalab . utils . RequestException : pass except Exception as e : raise e return not self . exists ( )
Delete the table .
237,857
def create ( self , schema , overwrite = False ) : if overwrite and self . exists ( ) : self . delete ( ) if not isinstance ( schema , _schema . Schema ) : schema = _schema . Schema ( schema ) try : response = self . _api . tables_insert ( self . _name_parts , schema = schema . _bq_schema ) except Exception as e : rais...
Create the table with the specified schema .
237,858
def _init_job_from_response ( self , response ) : job = None if response and 'jobReference' in response : job = _job . Job ( job_id = response [ 'jobReference' ] [ 'jobId' ] , context = self . _context ) return job
Helper function to create a Job instance from a response .
237,859
def extract_async ( self , destination , format = 'csv' , csv_delimiter = None , csv_header = True , compress = False ) : format = format . upper ( ) if format == 'JSON' : format = 'NEWLINE_DELIMITED_JSON' if format == 'CSV' and csv_delimiter is None : csv_delimiter = ',' try : response = self . _api . table_extract ( ...
Starts a job to export the table to GCS .
237,860
def extract ( self , destination , format = 'csv' , csv_delimiter = None , csv_header = True , compress = False ) : job = self . extract_async ( destination , format = format , csv_delimiter = csv_delimiter , csv_header = csv_header , compress = compress ) if job is not None : job . wait ( ) return job
Exports the table to GCS ; blocks until complete .
237,861
def load_async ( self , source , mode = 'create' , source_format = 'csv' , csv_options = None , ignore_unknown_values = False , max_bad_records = 0 ) : if source_format == 'csv' : source_format = 'CSV' elif source_format == 'json' : source_format = 'NEWLINE_DELIMITED_JSON' else : raise Exception ( "Invalid source forma...
Starts importing a table from GCS and return a Future .
237,862
def load ( self , source , mode = 'create' , source_format = 'csv' , csv_options = None , ignore_unknown_values = False , max_bad_records = 0 ) : job = self . load_async ( source , mode = mode , source_format = source_format , csv_options = csv_options , ignore_unknown_values = ignore_unknown_values , max_bad_records =...
Load the table from GCS .
237,863
def _get_row_fetcher ( self , start_row = 0 , max_rows = None , page_size = _DEFAULT_PAGE_SIZE ) : if not start_row : start_row = 0 elif start_row < 0 : if self . length >= 0 : start_row += self . length else : raise Exception ( 'Cannot use negative indices for table of unknown length' ) schema = self . schema . _bq_sc...
Get a function that can retrieve a page of rows .
237,864
def schema ( self ) : if not self . _schema : try : self . _load_info ( ) self . _schema = _schema . Schema ( self . _info [ 'schema' ] [ 'fields' ] ) except KeyError : raise Exception ( 'Unexpected table response: missing schema' ) return self . _schema
Retrieves the schema of the table .
237,865
def snapshot ( self , at ) : if self . _name_parts . decorator != '' : raise Exception ( "Cannot use snapshot() on an already decorated table" ) value = Table . _convert_decorator_time ( at ) return Table ( "%s@%s" % ( self . _full_name , str ( value ) ) , context = self . _context )
Return a new Table which is a snapshot of this table at the specified time .
237,866
def window ( self , begin , end = None ) : if self . _name_parts . decorator != '' : raise Exception ( "Cannot use window() on an already decorated table" ) start = Table . _convert_decorator_time ( begin ) if end is None : if isinstance ( begin , datetime . timedelta ) : end = datetime . timedelta ( 0 ) else : end = d...
Return a new Table limited to the rows added to this Table during the specified time range .
237,867
def serialize_example ( transformed_json_data , features , feature_indices , target_name ) : import six import tensorflow as tf from trainer import feature_transforms line = str ( transformed_json_data [ target_name ] [ 0 ] ) for name , info in feature_indices : if features [ name ] [ 'transform' ] in [ feature_transfo...
Makes an instance of data in libsvm format .
237,868
def delete ( self , delete_contents = False ) : if not self . exists ( ) : raise Exception ( 'Cannot delete non-existent dataset %s' % self . _full_name ) try : self . _api . datasets_delete ( self . _name_parts , delete_contents = delete_contents ) except Exception as e : raise e self . _info = None return None
Issues a request to delete the dataset .
237,869
def create ( self , friendly_name = None , description = None ) : if not self . exists ( ) : try : response = self . _api . datasets_insert ( self . _name_parts , friendly_name = friendly_name , description = description ) except Exception as e : raise e if 'selfLink' not in response : raise Exception ( "Could not crea...
Creates the Dataset with the specified friendly name and description .
237,870
def update ( self , friendly_name = None , description = None ) : self . _get_info ( ) if self . _info : if friendly_name : self . _info [ 'friendlyName' ] = friendly_name if description : self . _info [ 'description' ] = description try : self . _api . datasets_update ( self . _name_parts , self . _info ) except Excep...
Selectively updates Dataset information .
237,871
def query ( self ) : if not self . exists ( ) : return None self . _table . _load_info ( ) if 'view' in self . _table . _info and 'query' in self . _table . _info [ 'view' ] : return _query . Query ( self . _table . _info [ 'view' ] [ 'query' ] ) return None
The Query that defines the view .
237,872
def run_numerical_categorical_analysis ( args , schema_list ) : header = [ column [ 'name' ] for column in schema_list ] input_files = file_io . get_matching_files ( args . input_file_pattern ) for col_schema in schema_list : col_type = col_schema [ 'type' ] . lower ( ) if col_type != 'string' and col_type != 'integer'...
Makes the numerical and categorical analysis files .
237,873
def run_analysis ( args ) : schema_list = json . loads ( file_io . read_file_to_string ( args . schema_file ) ) run_numerical_categorical_analysis ( args , schema_list ) file_io . copy ( args . schema_file , os . path . join ( args . output_dir , SCHEMA_FILE ) , overwrite = True )
Builds an analysis files for training .
237,874
def _repr_html_ ( self ) : parts = [ ] if self . _class : parts . append ( '<div id="hh_%s" class="%s">%s</div>' % ( self . _id , self . _class , self . _markup ) ) else : parts . append ( '<div id="hh_%s">%s</div>' % ( self . _id , self . _markup ) ) if len ( self . _script ) != 0 : parts . append ( '<script>' ) parts...
Generates the HTML representation .
237,875
def _render_objects ( self , items , attributes = None , datatype = 'object' ) : if not items : return if datatype == 'chartdata' : if not attributes : attributes = [ items [ 'cols' ] [ i ] [ 'label' ] for i in range ( 0 , len ( items [ 'cols' ] ) ) ] items = items [ 'rows' ] indices = { attributes [ i ] : i for i in r...
Renders an HTML table with the specified list of objects .
237,876
def _render_list ( self , items , empty = '<pre>&lt;empty&gt;</pre>' ) : if not items or len ( items ) == 0 : self . _segments . append ( empty ) return self . _segments . append ( '<ul>' ) for o in items : self . _segments . append ( '<li>' ) self . _segments . append ( str ( o ) ) self . _segments . append ( '</li>' ...
Renders an HTML list with the specified list of strings .
237,877
def sample ( self , fields = None , count = 5 , sampling = None , use_cache = True , dialect = None , billing_tier = None ) : from . import _query sql = self . _repr_sql_ ( ) return _query . Query . sampling_query ( sql , context = self . _context , count = count , fields = fields , sampling = sampling ) . results ( us...
Retrieves a sampling of data from the table .
237,878
def _encode_dict_as_row ( record , column_name_map ) : for k in list ( record . keys ( ) ) : v = record [ k ] if isinstance ( v , pandas . Timestamp ) or isinstance ( v , datetime . datetime ) : v = record [ k ] = record [ k ] . isoformat ( ) if k not in column_name_map : column_name_map [ k ] = '' . join ( c for c in ...
Encode a dictionary representing a table row in a form suitable for streaming to BQ .
237,879
def insert_data ( self , data , include_index = False , index_name = None ) : max_rows_per_post = 500 post_interval = 0.05 if not self . exists ( ) : raise Exception ( 'Table %s does not exist.' % self . _full_name ) data_schema = _schema . Schema . from_data ( data ) if isinstance ( data , list ) : if include_index : ...
Insert the contents of a Pandas DataFrame or a list of dictionaries into the table .
237,880
def range ( self , start_row = 0 , max_rows = None ) : fetcher = self . _get_row_fetcher ( start_row = start_row , max_rows = max_rows ) return iter ( datalab . utils . Iterator ( fetcher ) )
Get an iterator to iterate through a set of table rows .
237,881
def to_file_async ( self , destination , format = 'csv' , csv_delimiter = ',' , csv_header = True ) : self . to_file ( destination , format = format , csv_delimiter = csv_delimiter , csv_header = csv_header )
Start saving the results to a local file in CSV format and return a Job for completion .
237,882
def update ( self , friendly_name = None , description = None , expiry = None , schema = None ) : self . _load_info ( ) if friendly_name is not None : self . _info [ 'friendlyName' ] = friendly_name if description is not None : self . _info [ 'description' ] = description if expiry is not None : if isinstance ( expiry ...
Selectively updates Table information .
237,883
def to_query ( self , fields = None ) : from . import _query if fields is None : fields = '*' elif isinstance ( fields , list ) : fields = ',' . join ( fields ) return _query . Query ( 'SELECT %s FROM %s' % ( fields , self . _repr_sql_ ( ) ) , context = self . _context )
Return a Query for this Table .
237,884
def copy_to ( self , new_key , bucket = None ) : if bucket is None : bucket = self . _bucket try : new_info = self . _api . objects_copy ( self . _bucket , self . _key , bucket , new_key ) except Exception as e : raise e return Item ( bucket , new_key , new_info , context = self . _context )
Copies this item to the specified new key .
237,885
def exists ( self ) : try : return self . metadata is not None except datalab . utils . RequestException : return False except Exception as e : raise e
Checks if the item exists .
237,886
def delete ( self ) : if self . exists ( ) : try : self . _api . objects_delete ( self . _bucket , self . _key ) except Exception as e : raise e
Deletes this item from its bucket .
237,887
def write_to ( self , content , content_type ) : try : self . _api . object_upload ( self . _bucket , self . _key , content , content_type ) except Exception as e : raise e
Writes text content to this item .
237,888
def contains ( self , key ) : try : self . _api . objects_get ( self . _bucket , key ) except datalab . utils . RequestException as e : if e . status == 404 : return False raise e except Exception as e : raise e return True
Checks if the specified item exists .
237,889
def request ( url , args = None , data = None , headers = None , method = None , credentials = None , raw_response = False , stats = None ) : if headers is None : headers = { } headers [ 'user-agent' ] = 'GoogleCloudDataLab/1.0' if args is not None : qs = urllib . parse . urlencode ( args ) url = url + '?' + qs if data...
Issues HTTP requests .
237,890
def _add_command ( parser , subparser_fn , handler , cell_required = False , cell_prohibited = False ) : sub_parser = subparser_fn ( parser ) sub_parser . set_defaults ( func = lambda args , cell : _dispatch_handler ( args , cell , sub_parser , handler , cell_required = cell_required , cell_prohibited = cell_prohibited...
Create and initialize a pipeline subcommand handler .
237,891
def pipeline ( line , cell = None ) : return google . datalab . utils . commands . handle_magic_line ( line , cell , _pipeline_parser )
Implements the pipeline cell magic for ipython notebooks .
237,892
def _dispatch_handler ( args , cell , parser , handler , cell_required = False , cell_prohibited = False ) : if cell_prohibited : if cell and len ( cell . strip ( ) ) : parser . print_help ( ) raise Exception ( 'Additional data is not supported with the %s command.' % parser . prog ) return handler ( args ) if cell_req...
Makes sure cell magics include cell and line magics don t before dispatching to handler .
237,893
def expand_defaults ( schema , features ) : schema_names = [ x [ 'name' ] for x in schema ] for name , transform in six . iteritems ( features ) : if 'source_column' not in transform : transform [ 'source_column' ] = name used_schema_columns = [ ] for name , transform in six . iteritems ( features ) : if transform [ 's...
Add to features any default transformations .
237,894
def _sample_cell ( args , cell_body ) : env = datalab . utils . commands . notebook_environment ( ) query = None table = None view = None if args [ 'query' ] : query = _get_query_argument ( args , cell_body , env ) elif args [ 'table' ] : table = _get_table ( args [ 'table' ] ) elif args [ 'view' ] : view = datalab . u...
Implements the bigquery sample cell magic for ipython notebooks .
237,895
def _create_cell ( args , cell_body ) : if args [ 'command' ] == 'dataset' : try : datalab . bigquery . Dataset ( args [ 'name' ] ) . create ( friendly_name = args [ 'friendly' ] , description = cell_body ) except Exception as e : print ( 'Failed to create dataset %s: %s' % ( args [ 'name' ] , e ) ) else : if cell_body...
Implements the BigQuery cell magic used to create datasets and tables .
237,896
def _delete_cell ( args , _ ) : if args [ 'command' ] == 'dataset' : try : datalab . bigquery . Dataset ( args [ 'name' ] ) . delete ( ) except Exception as e : print ( 'Failed to delete dataset %s: %s' % ( args [ 'name' ] , e ) ) else : try : datalab . bigquery . Table ( args [ 'name' ] ) . delete ( ) except Exception...
Implements the BigQuery cell magic used to delete datasets and tables .
237,897
def _udf_cell ( args , js ) : variable_name = args [ 'module' ] if not variable_name : raise Exception ( 'Declaration must be of the form %%bigquery udf --module <variable name>' ) spec_pattern = r'\{\{([^}]+)\}\}' spec_part_pattern = r'[a-z_][a-z0-9_]*' specs = re . findall ( spec_pattern , js ) if len ( specs ) < 2 :...
Implements the bigquery_udf cell magic for ipython notebooks .
237,898
def _pipeline_cell ( args , cell_body ) : if args [ 'action' ] == 'deploy' : raise Exception ( 'Deploying a pipeline is not yet supported' ) env = { } for key , value in datalab . utils . commands . notebook_environment ( ) . items ( ) : if isinstance ( value , datalab . bigquery . _udf . UDF ) : env [ key ] = value qu...
Implements the BigQuery cell magic used to validate execute or deploy BQ pipelines .
237,899
def _table_line ( args ) : name = args [ 'table' ] table = _get_table ( name ) if table and table . exists ( ) : fields = args [ 'cols' ] . split ( ',' ) if args [ 'cols' ] else None html = _table_viewer ( table , rows_per_page = args [ 'rows' ] , fields = fields ) return IPython . core . display . HTML ( html ) else :...
Implements the BigQuery table magic used to display tables .