idx
int64
0
63k
question
stringlengths
61
4.03k
target
stringlengths
6
1.23k
49,000
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 .
49,001
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 .
49,002
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 .
49,003
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 .
49,004
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 .
49,005
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 .
49,006
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 .
49,007
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 .
49,008
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 .
49,009
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 .
49,010
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 .
49,011
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 .
49,012
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 .
49,013
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 .
49,014
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 .
49,015
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 .
49,016
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 .
49,017
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 .
49,018
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 .
49,019
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 .
49,020
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 .
49,021
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 .
49,022
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 .
49,023
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 .
49,024
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 .
49,025
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 .
49,026
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 .
49,027
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 .
49,028
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 .
49,029
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 .
49,030
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 .
49,031
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 .
49,032
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 .
49,033
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 .
49,034
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 .
49,035
def _get_schema ( name ) : item = datalab . utils . commands . get_notebook_item ( name ) if not item : item = _get_table ( name ) if isinstance ( item , datalab . bigquery . Schema ) : return item if hasattr ( item , 'schema' ) and isinstance ( item . schema , datalab . bigquery . _schema . Schema ) : return item . sc...
Given a variable or table name get the Schema if it exists .
49,036
def _render_table ( data , fields = None ) : return IPython . core . display . HTML ( datalab . utils . commands . HtmlBuilder . render_table ( data , fields ) )
Helper to render a list of dictionaries as an HTML display object .
49,037
def _datasets_line ( args ) : filter_ = args [ 'filter' ] if args [ 'filter' ] else '*' return _render_list ( [ str ( dataset ) for dataset in datalab . bigquery . Datasets ( args [ 'project' ] ) if fnmatch . fnmatch ( str ( dataset ) , filter_ ) ] )
Implements the BigQuery datasets magic used to display datasets in a project .
49,038
def _tables_line ( args ) : filter_ = args [ 'filter' ] if args [ 'filter' ] else '*' if args [ 'dataset' ] : if args [ 'project' ] is None : datasets = [ datalab . bigquery . Dataset ( args [ 'dataset' ] ) ] else : datasets = [ datalab . bigquery . Dataset ( ( args [ 'project' ] , args [ 'dataset' ] ) ) ] else : datas...
Implements the BigQuery tables magic used to display tables in a dataset .
49,039
def _extract_line ( args ) : name = args [ 'source' ] source = datalab . utils . commands . get_notebook_item ( name ) if not source : source = _get_table ( name ) if not source : raise Exception ( 'No source named %s found' % name ) elif isinstance ( source , datalab . bigquery . Table ) and not source . exists ( ) : ...
Implements the BigQuery extract magic used to extract table data to GCS .
49,040
def bigquery ( line , cell = None ) : namespace = { } if line . find ( '$' ) >= 0 : namespace = datalab . utils . commands . notebook_environment ( ) return datalab . utils . commands . handle_magic_line ( line , cell , _bigquery_parser , namespace = namespace )
Implements the bigquery cell magic for ipython notebooks .
49,041
def table ( name = None , mode = 'create' , use_cache = True , priority = 'interactive' , allow_large_results = False ) : output = QueryOutput ( ) output . _output_type = 'table' output . _table_name = name output . _table_mode = mode output . _use_cache = use_cache output . _priority = priority output . _allow_large_r...
Construct a query output object where the result is a table
49,042
def file ( path , format = 'csv' , csv_delimiter = ',' , csv_header = True , compress = False , use_cache = True ) : output = QueryOutput ( ) output . _output_type = 'file' output . _file_path = path output . _file_format = format output . _csv_delimiter = csv_delimiter output . _csv_header = csv_header output . _compr...
Construct a query output object where the result is either a local file or a GCS path
49,043
def dataframe ( start_row = 0 , max_rows = None , use_cache = True ) : output = QueryOutput ( ) output . _output_type = 'dataframe' output . _dataframe_start_row = start_row output . _dataframe_max_rows = max_rows output . _use_cache = use_cache return output
Construct a query output object where the result is a dataframe
49,044
def list ( ) : running_list = [ ] parser = argparse . ArgumentParser ( ) parser . add_argument ( '--logdir' ) parser . add_argument ( '--port' ) for p in psutil . process_iter ( ) : if p . name ( ) != 'tensorboard' or p . status ( ) == psutil . STATUS_ZOMBIE : continue cmd_args = p . cmdline ( ) del cmd_args [ 0 : 2 ] ...
List running TensorBoard instances .
49,045
def start ( logdir ) : if logdir . startswith ( 'gs://' ) : datalab . storage . _api . Api . verify_permitted_to_read ( logdir ) port = datalab . utils . pick_unused_port ( ) args = [ 'tensorboard' , '--logdir=' + logdir , '--port=' + str ( port ) ] p = subprocess . Popen ( args ) retry = 10 while ( retry > 0 ) : if da...
Start a TensorBoard instance .
49,046
def stop ( pid ) : if psutil . pid_exists ( pid ) : try : p = psutil . Process ( pid ) p . kill ( ) except Exception : pass
Shut down a specific process .
49,047
def build_graph ( self ) : import tensorflow as tf input_jpeg = tf . placeholder ( tf . string , shape = None ) image = tf . image . decode_jpeg ( input_jpeg , channels = self . CHANNELS ) image = tf . expand_dims ( image , 0 ) image = tf . image . convert_image_dtype ( image , dtype = tf . float32 ) image = tf . image...
Forms the core by building a wrapper around the inception graph .
49,048
def restore_from_checkpoint ( self , checkpoint_path ) : import tensorflow as tf all_vars = tf . contrib . slim . get_variables_to_restore ( exclude = [ 'InceptionV3/AuxLogits' , 'InceptionV3/Logits' , 'global_step' ] ) saver = tf . train . Saver ( all_vars ) saver . restore ( self . tf_session , checkpoint_path )
To restore inception model variables from the checkpoint file .
49,049
def calculate_embedding ( self , batch_image_bytes ) : return self . tf_session . run ( self . embedding , feed_dict = { self . input_jpeg : batch_image_bytes } )
Get the embeddings for a given JPEG image .
49,050
def add_final_training_ops ( self , embeddings , all_labels_count , bottleneck_tensor_size , hidden_layer_size = BOTTLENECK_TENSOR_SIZE / 4 , dropout_keep_prob = None ) : with tf . name_scope ( 'input' ) : bottleneck_input = tf . placeholder_with_default ( embeddings , shape = [ None , bottleneck_tensor_size ] , name =...
Adds a new softmax and fully - connected layer for training .
49,051
def build_inception_graph ( self ) : image_str_tensor = tf . placeholder ( tf . string , shape = [ None ] ) image = tf . map_fn ( _util . decode_and_resize , image_str_tensor , back_prop = False , dtype = tf . uint8 ) image = tf . image . convert_image_dtype ( image , dtype = tf . float32 ) image = tf . subtract ( imag...
Builds an inception graph and add the necessary input & output tensors .
49,052
def build_graph ( self , data_paths , batch_size , graph_mod ) : tensors = GraphReferences ( ) is_training = graph_mod == GraphMod . TRAIN if data_paths : _ , tensors . examples = _util . read_examples ( data_paths , batch_size , shuffle = is_training , num_epochs = None if is_training else 2 ) else : tensors . example...
Builds generic graph for training or eval .
49,053
def restore_from_checkpoint ( self , session , inception_checkpoint_file , trained_checkpoint_file ) : inception_exclude_scopes = [ 'InceptionV3/AuxLogits' , 'InceptionV3/Logits' , 'global_step' , 'final_ops' ] reader = tf . train . NewCheckpointReader ( inception_checkpoint_file ) var_to_shape_map = reader . get_varia...
To restore model variables from the checkpoint file .
49,054
def build_prediction_graph ( self ) : tensors = self . build_graph ( None , 1 , GraphMod . PREDICT ) keys_placeholder = tf . placeholder ( tf . string , shape = [ None ] ) inputs = { 'key' : keys_placeholder , 'image_bytes' : tensors . input_jpeg } keys = tf . identity ( keys_placeholder ) labels = self . labels + [ 'U...
Builds prediction graph and registers appropriate endpoints .
49,055
def export ( self , last_checkpoint , output_dir ) : logging . info ( 'Exporting prediction graph to %s' , output_dir ) with tf . Session ( graph = tf . Graph ( ) ) as sess : inputs , outputs = self . build_prediction_graph ( ) signature_def_map = { 'serving_default' : signature_def_utils . predict_signature_def ( inpu...
Builds a prediction graph and xports the model .
49,056
def format_metric_values ( self , metric_values ) : loss_str = 'N/A' accuracy_str = 'N/A' try : loss_str = 'loss: %.3f' % metric_values [ 0 ] accuracy_str = 'accuracy: %.3f' % metric_values [ 1 ] except ( TypeError , IndexError ) : pass return '%s, %s' % ( loss_str , accuracy_str )
Formats metric values - used for logging purpose .
49,057
def package_and_copy ( package_root_dir , setup_py , output_tar_path ) : if not output_tar_path . startswith ( 'gs://' ) : raise ValueError ( 'output_tar_path needs to be a GCS path.' ) if not os . path . isfile ( setup_py ) : raise ValueError ( 'Supplied file "%s" does not exist.' % setup_py ) dest_setup_py = os . pat...
Repackage an CloudML package and copy it to a staging dir .
49,058
def read_file_to_string ( path ) : bytes_string = tf . gfile . Open ( path , 'r' ) . read ( ) return dlutils . python_portable_string ( bytes_string )
Read a file into a string .
49,059
def _date ( val , offset = None ) : if val is None : return val if val == '' or val == 'now' : when = datetime . datetime . utcnow ( ) elif val == 'today' : dt = datetime . datetime . utcnow ( ) when = datetime . datetime ( dt . year , dt . month , dt . day ) elif val == 'yesterday' : dt = datetime . datetime . utcnow ...
A special pseudo - type for pipeline arguments .
49,060
def _make_string_formatter ( f , offset = None ) : format = f delta = offset return lambda v : time . strftime ( format , ( _date ( v , delta ) ) . timetuple ( ) )
A closure - izer for string arguments that include a format and possibly an offset .
49,061
def _make_table_formatter ( f , offset = None ) : format = f delta = offset return lambda v : _resolve_table ( v , format , delta )
A closure - izer for table arguments that include a format and possibly an offset .
49,062
def _arguments ( code , module ) : arg_parser = CommandParser . create ( '' ) try : builtins = { 'source' : _table , 'datestring' : _datestring } env = { } env . update ( builtins ) exec ( code , env ) for key in env : if key in builtins or key [ 0 ] == '_' : continue val = env [ key ] key = '--%s' % key if isinstance ...
Define pipeline arguments .
49,063
def _split_cell ( cell , module ) : lines = cell . split ( '\n' ) code = None last_def = - 1 name = None define_wild_re = re . compile ( '^DEFINE\s+.*$' , re . IGNORECASE ) define_re = re . compile ( '^DEFINE\s+QUERY\s+([A-Z]\w*)\s*?(.*)$' , re . IGNORECASE ) select_re = re . compile ( '^SELECT\s*.*$' , re . IGNORECASE...
Split a hybrid %%sql cell into the Python code and the queries .
49,064
def sql_cell ( args , cell ) : name = args [ 'module' ] if args [ 'module' ] else '_sql_cell' module = imp . new_module ( name ) query = _split_cell ( cell , module ) ipy = IPython . get_ipython ( ) if not args [ 'module' ] : if query : return datalab . bigquery . Query ( query , values = ipy . user_ns ) . execute ( di...
Implements the SQL cell magic for ipython notebooks .
49,065
def get_reader_input_fn ( train_config , preprocess_output_dir , model_type , data_paths , batch_size , shuffle , num_epochs = None ) : def get_input_features ( ) : _ , examples = util . read_examples ( input_files = data_paths , batch_size = batch_size , shuffle = shuffle , num_epochs = num_epochs ) features = util . ...
Builds input layer for training .
49,066
def main ( argv = None ) : args = parse_arguments ( sys . argv if argv is None else argv ) tf . logging . set_verbosity ( tf . logging . INFO ) learn_runner . run ( experiment_fn = get_experiment_fn ( args ) , output_dir = args . job_dir )
Run a Tensorflow model on the Iris dataset .
49,067
def sd ( line , cell = None ) : parser = google . datalab . utils . commands . CommandParser ( prog = '%sd' , description = ( 'Execute various Stackdriver related operations. Use "%sd ' '<stackdriver_product> -h" for help on a specific Stackdriver product.' ) ) _create_monitoring_subparser ( parser ) return google . da...
Implements the stackdriver cell magic for ipython notebooks .
49,068
def make_prediction_output_tensors ( args , features , input_ops , model_fn_ops , keep_target ) : target_name = feature_transforms . get_target_name ( features ) key_names = get_key_names ( features ) outputs = { } outputs . update ( { key_name : tf . squeeze ( input_ops . features [ key_name ] ) for key_name in key_na...
Makes the final prediction output layer .
49,069
def read_vocab ( args , column_name ) : vocab_path = os . path . join ( args . analysis , feature_transforms . VOCAB_ANALYSIS_FILE % column_name ) if not file_io . file_exists ( vocab_path ) : return [ ] vocab , _ = feature_transforms . read_vocab_file ( vocab_path ) return vocab
Reads a vocab file if it exists .
49,070
def get_item ( env , name , default = None ) : for key in name . split ( '.' ) : if isinstance ( env , dict ) and key in env : env = env [ key ] elif isinstance ( env , types . ModuleType ) and key in env . __dict__ : env = env . __dict__ [ key ] else : return default return env
Get an item from a dictionary handling nested lookups with dotted notation .
49,071
def predict ( model_dir , images ) : results = _tf_predict ( model_dir , images ) predicted_and_scores = [ ( predicted , label_scores [ list ( labels ) . index ( predicted ) ] ) for predicted , labels , label_scores in results ] return predicted_and_scores
Local instant prediction .
49,072
def configure_pipeline ( p , dataset , model_dir , output_csv , output_bq_table ) : data = _util . get_sources_from_dataset ( p , dataset , 'predict' ) if len ( dataset . schema ) == 2 : output_schema = [ { 'name' : 'image_url' , 'type' : 'STRING' } , { 'name' : 'target' , 'type' : 'STRING' } , { 'name' : 'predicted' ,...
Configures a dataflow pipeline for batch prediction .
49,073
def sampling_query ( sql , context , fields = None , count = 5 , sampling = None , udfs = None , data_sources = None ) : return Query ( _sampling . Sampling . sampling_query ( sql , fields , count , sampling ) , context = context , udfs = udfs , data_sources = data_sources )
Returns a sampling Query for the SQL object .
49,074
def results ( self , use_cache = True , dialect = None , billing_tier = None ) : if not use_cache or ( self . _results is None ) : self . execute ( use_cache = use_cache , dialect = dialect , billing_tier = billing_tier ) return self . _results . results
Retrieves table of results for the query . May block if the query must be executed first .
49,075
def extract ( self , storage_uris , format = 'csv' , csv_delimiter = ',' , csv_header = True , compress = False , use_cache = True , dialect = None , billing_tier = None ) : return self . results ( use_cache = use_cache , dialect = dialect , billing_tier = billing_tier ) . extract ( storage_uris , format = format , csv...
Exports the query results to GCS .
49,076
def to_dataframe ( self , start_row = 0 , max_rows = None , use_cache = True , dialect = None , billing_tier = None ) : return self . results ( use_cache = use_cache , dialect = dialect , billing_tier = billing_tier ) . to_dataframe ( start_row = start_row , max_rows = max_rows )
Exports the query results to a Pandas dataframe .
49,077
def sample ( self , count = 5 , fields = None , sampling = None , use_cache = True , dialect = None , billing_tier = None ) : return Query . sampling_query ( self . _sql , self . _context , count = count , fields = fields , sampling = sampling , udfs = self . _udfs , data_sources = self . _data_sources ) . results ( us...
Retrieves a sampling of rows for the query .
49,078
def execute ( self , table_name = None , table_mode = 'create' , use_cache = True , priority = 'interactive' , allow_large_results = False , dialect = None , billing_tier = None ) : job = self . execute_async ( table_name = table_name , table_mode = table_mode , use_cache = use_cache , priority = priority , allow_large...
Initiate the query blocking until complete and then return the results .
49,079
def to_view ( self , view_name ) : from . import _view return _view . View ( view_name , self . _context ) . create ( self . _sql )
Create a View from this Query .
49,080
def format_help ( self ) : if not self . _cell_args : return super ( CommandParser , self ) . format_help ( ) else : epilog = self . epilog self . epilog = None orig_help = super ( CommandParser , self ) . format_help ( ) cell_args_help = '\nCell args:\n\n' for cell_arg , v in six . iteritems ( self . _cell_args ) : re...
Override help doc to add cell args .
49,081
def _get_subparsers ( self ) : subparsers = [ ] for action in self . _actions : if isinstance ( action , argparse . _SubParsersAction ) : for _ , subparser in action . choices . items ( ) : subparsers . append ( subparser ) ret = subparsers for sp in subparsers : ret += sp . _get_subparsers ( ) return ret
Recursively get subparsers .
49,082
def _get_subparser_line_args ( self , subparser_prog ) : subparsers = self . _get_subparsers ( ) for subparser in subparsers : if subparser_prog == subparser . prog : args_to_parse = [ ] for action in subparser . _actions : if action . option_strings : for argname in action . option_strings : if argname . startswith ( ...
Get line args of a specified subparser by its prog .
49,083
def _get_subparser_cell_args ( self , subparser_prog ) : subparsers = self . _get_subparsers ( ) for subparser in subparsers : if subparser_prog == subparser . prog : return subparser . _cell_args return None
Get cell args of a specified subparser by its prog .
49,084
def add_cell_argument ( self , name , help , required = False ) : for action in self . _actions : if action . dest == name : raise ValueError ( 'Arg "%s" was added by add_argument already.' % name ) self . _cell_args [ name ] = { 'required' : required , 'help' : help }
Add a cell only argument .
49,085
def parse ( self , line , cell , namespace = None ) : if namespace is None : ipy = IPython . get_ipython ( ) namespace = ipy . user_ns args = CommandParser . create_args ( line , namespace ) sub_parsers_progs = [ x . prog for x in self . _get_subparsers ( ) ] matched_progs = [ ] for prog in sub_parsers_progs : match = ...
Parses a line and cell into a dictionary of arguments expanding variables from a namespace .
49,086
def _glob_events_files ( self , paths , recursive ) : event_files = [ ] for path in paths : dirs = tf . gfile . Glob ( path ) dirs = filter ( lambda x : tf . gfile . IsDirectory ( x ) , dirs ) for dir in dirs : if recursive : dir_files_pair = [ ( root , filenames ) for root , _ , filenames in tf . gfile . Walk ( dir ) ...
Find all tf events files under a list of paths recursively .
49,087
def list_events ( self ) : event_dir_dict = collections . defaultdict ( set ) for event_file in self . _glob_events_files ( self . _paths , recursive = True ) : dir = os . path . dirname ( event_file ) try : for record in tf_record . tf_record_iterator ( event_file ) : event = event_pb2 . Event . FromString ( record ) ...
List all scalar events in the directory .
49,088
def from_storage ( source , source_format = 'csv' , csv_options = None , ignore_unknown_values = False , max_bad_records = 0 , compressed = False , schema = None ) : result = FederatedTable ( ) if source_format == 'csv' : result . _bq_source_format = 'CSV' if csv_options is None : csv_options = _csv_options . CSVOption...
Create an external table for a GCS object .
49,089
def get_query_parameters ( args , cell_body , date_time = datetime . datetime . now ( ) ) : env = google . datalab . utils . commands . notebook_environment ( ) config = google . datalab . utils . commands . parse_config ( cell_body , env = env , as_dict = False ) sql = args [ 'query' ] if sql is None : raise Exception...
Extract query parameters from cell body if provided Also validates the cell body schema using jsonschema to catch errors before sending the http request . This validation isn t complete however ; it does not validate recursive schemas but it acts as a good filter against most simple schemas
49,090
def _udf_cell ( args , cell_body ) : udf_name = args [ 'name' ] if not udf_name : raise Exception ( 'Declaration must be of the form %%bq udf --name <variable name>' ) param_pattern = r'^\s*\/\/\s*@param\s+([<>\w]+)\s+([<>\w,\s]+)\s*$' returns_pattern = r'^\s*\/\/\s*@returns\s+([<>\w,\s]+)\s*$' import_pattern = r'^\s*\...
Implements the Bigquery udf cell magic for ipython notebooks .
49,091
def _datasource_cell ( args , cell_body ) : name = args [ 'name' ] paths = args [ 'paths' ] data_format = ( args [ 'format' ] or 'CSV' ) . lower ( ) compressed = args [ 'compressed' ] or False record = google . datalab . utils . commands . parse_config ( cell_body , google . datalab . utils . commands . notebook_enviro...
Implements the BigQuery datasource cell magic for ipython notebooks .
49,092
def _query_cell ( args , cell_body ) : name = args [ 'name' ] udfs = args [ 'udfs' ] datasources = args [ 'datasources' ] subqueries = args [ 'subqueries' ] query = bigquery . Query ( cell_body , env = IPython . get_ipython ( ) . user_ns , udfs = udfs , data_sources = datasources , subqueries = subqueries ) if name is ...
Implements the BigQuery cell magic for used to build SQL objects .
49,093
def _get_table ( name ) : item = google . datalab . utils . commands . get_notebook_item ( name ) if isinstance ( item , bigquery . Table ) : return item try : return _existing_table_cache [ name ] except KeyError : table = bigquery . Table ( name ) if table . exists ( ) : _existing_table_cache [ name ] = table return ...
Given a variable or table name get a Table if it exists .
49,094
def _render_list ( data ) : return IPython . core . display . HTML ( google . datalab . utils . commands . HtmlBuilder . render_list ( data ) )
Helper to render a list of objects as an HTML list object .
49,095
def _dataset_line ( args ) : if args [ 'command' ] == 'list' : filter_ = args [ 'filter' ] if args [ 'filter' ] else '*' context = google . datalab . Context . default ( ) if args [ 'project' ] : context = google . datalab . Context ( args [ 'project' ] , context . credentials ) return _render_list ( [ str ( dataset ) ...
Implements the BigQuery dataset magic subcommand used to operate on datasets
49,096
def _table_cell ( args , cell_body ) : if args [ 'command' ] == 'list' : filter_ = args [ 'filter' ] if args [ 'filter' ] else '*' if args [ 'dataset' ] : if args [ 'project' ] is None : datasets = [ bigquery . Dataset ( args [ 'dataset' ] ) ] else : context = google . datalab . Context ( args [ 'project' ] , google . ...
Implements the BigQuery table magic subcommand used to operate on tables
49,097
def _extract_cell ( args , cell_body ) : env = google . datalab . utils . commands . notebook_environment ( ) config = google . datalab . utils . commands . parse_config ( cell_body , env , False ) or { } parameters = config . get ( 'parameters' ) if args [ 'table' ] : table = google . datalab . bigquery . Query . reso...
Implements the BigQuery extract magic used to extract query or table data to GCS .
49,098
def bq ( line , cell = None ) : return google . datalab . utils . commands . handle_magic_line ( line , cell , _bigquery_parser )
Implements the bq cell magic for ipython notebooks .
49,099
def _table_viewer ( table , rows_per_page = 25 , fields = None ) : if not table . exists ( ) : raise Exception ( 'Table %s does not exist' % table . full_name ) if not table . is_listable ( ) : return "Done" _HTML_TEMPLATE = u if fields is None : fields = google . datalab . utils . commands . get_field_list ( fields , ...
Return a table viewer .