idx
int64
0
252k
question
stringlengths
48
5.28k
target
stringlengths
5
1.23k
237,900
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 .
237,901
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 .
237,902
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 .
237,903
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 .
237,904
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 .
237,905
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 .
237,906
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
237,907
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
237,908
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
237,909
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 .
237,910
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 .
237,911
def stop ( pid ) : if psutil . pid_exists ( pid ) : try : p = psutil . Process ( pid ) p . kill ( ) except Exception : pass
Shut down a specific process .
237,912
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 .
237,913
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 .
237,914
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 .
237,915
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 .
237,916
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 .
237,917
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 .
237,918
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 .
237,919
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 .
237,920
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 .
237,921
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 .
237,922
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 .
237,923
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 .
237,924
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 .
237,925
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 .
237,926
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 .
237,927
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 .
237,928
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 .
237,929
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 .
237,930
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 .
237,931
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 .
237,932
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 .
237,933
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 .
237,934
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 .
237,935
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 .
237,936
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 .
237,937
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 .
237,938
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 .
237,939
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 .
237,940
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 .
237,941
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 .
237,942
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 .
237,943
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 .
237,944
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 .
237,945
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 .
237,946
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 .
237,947
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 .
237,948
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 .
237,949
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 .
237,950
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 .
237,951
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 .
237,952
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 .
237,953
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 .
237,954
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
237,955
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 .
237,956
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 .
237,957
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 .
237,958
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 .
237,959
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 .
237,960
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
237,961
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
237,962
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 .
237,963
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 .
237,964
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 .
237,965
def _build_js ( inputs , outputs , name , implementation , support_code ) : input_fields = json . dumps ( [ f [ 0 ] for f in inputs ] ) output_fields = [ { 'name' : f [ 0 ] , 'type' : f [ 1 ] } for f in outputs ] output_fields = json . dumps ( output_fields , sort_keys = True ) if support_code is None : support_code = ...
Creates a BigQuery SQL UDF javascript object .
237,966
def sampling_query ( sql , fields = None , count = 5 , sampling = None ) : if sampling is None : sampling = Sampling . default ( count = count , fields = fields ) return sampling ( sql )
Returns a sampling query for the SQL object .
237,967
def _remove_nonascii ( self , df ) : df_copy = df . copy ( deep = True ) for col in df_copy . columns : if ( df_copy [ col ] . dtype == np . dtype ( 'O' ) ) : df_copy [ col ] = df [ col ] . apply ( lambda x : re . sub ( r'[^\x00-\x7f]' , r'' , x ) if isinstance ( x , six . string_types ) else x ) return df_copy
Make copy and remove non - ascii characters from it .
237,968
def plot ( self , data ) : import IPython if not isinstance ( data , dict ) or not all ( isinstance ( v , pd . DataFrame ) for v in data . values ( ) ) : raise ValueError ( 'Expect a dictionary where the values are all dataframes.' ) gfsg = GenericFeatureStatisticsGenerator ( ) data = [ { 'name' : k , 'table' : self . ...
Plots an overview in a list of dataframes
237,969
def plot ( self , data , height = 1000 , render_large_data = False ) : import IPython if not isinstance ( data , pd . DataFrame ) : raise ValueError ( 'Expect a DataFrame.' ) if ( len ( data ) > 10000 and not render_large_data ) : raise ValueError ( 'Facets dive may not work well with more than 10000 rows. ' + 'Reduce ...
Plots a detail view of data .
237,970
def DtypeToType ( self , dtype ) : if dtype . char in np . typecodes [ 'AllFloat' ] : return self . fs_proto . FLOAT elif ( dtype . char in np . typecodes [ 'AllInteger' ] or dtype == np . bool or np . issubdtype ( dtype , np . datetime64 ) or np . issubdtype ( dtype , np . timedelta64 ) ) : return self . fs_proto . IN...
Converts a Numpy dtype to the FeatureNameStatistics . Type proto enum .
237,971
def NdarrayToEntry ( self , x ) : row_counts = [ ] for row in x : try : rc = np . count_nonzero ( ~ np . isnan ( row ) ) if rc != 0 : row_counts . append ( rc ) except TypeError : try : row_counts . append ( row . size ) except AttributeError : row_counts . append ( 1 ) data_type = self . DtypeToType ( x . dtype ) conv...
Converts an ndarray to the Entry format .
237,972
def serving_from_csv_input ( train_config , args , keep_target ) : examples = tf . placeholder ( dtype = tf . string , shape = ( None , ) , name = 'csv_input_string' ) features = parse_example_tensor ( examples = examples , train_config = train_config , keep_target = keep_target ) if keep_target : target = features . p...
Read the input features from a placeholder csv string tensor .
237,973
def parse_example_tensor ( examples , train_config , keep_target ) : csv_header = [ ] if keep_target : csv_header = train_config [ 'csv_header' ] else : csv_header = [ name for name in train_config [ 'csv_header' ] if name != train_config [ 'target_column' ] ] record_defaults = [ [ train_config [ 'csv_defaults' ] [ nam...
Read the csv files .
237,974
def get_estimator ( output_dir , train_config , args ) : target_name = train_config [ 'target_column' ] if is_classification_model ( args . model_type ) and target_name not in train_config [ 'categorical_columns' ] : raise ValueError ( 'When using a classification model, the target must be a ' 'categorical variable.' )...
Returns a tf learn estimator .
237,975
def preprocess_input ( features , target , train_config , preprocess_output_dir , model_type ) : target_name = train_config [ 'target_column' ] key_name = train_config [ 'key_column' ] with tf . name_scope ( 'numerical_feature_preprocess' ) : if train_config [ 'numerical_columns' ] : numerical_analysis_file = os . path...
Perform some transformations after reading in the input tensors .
237,976
def _scale_tensor ( tensor , range_min , range_max , scale_min , scale_max ) : if range_min == range_max : return tensor float_tensor = tf . to_float ( tensor ) scaled_tensor = tf . divide ( ( tf . subtract ( float_tensor , range_min ) * tf . constant ( float ( scale_max - scale_min ) ) ) , tf . constant ( float ( rang...
Scale a tensor to scale_min to scale_max .
237,977
def _tflearn_features ( train_config , args ) : feature_columns = [ ] target_name = train_config [ 'target_column' ] key_name = train_config [ 'key_column' ] for name in train_config [ 'numerical_columns' ] : if name != target_name and name != key_name : feature_columns . append ( tf . contrib . layers . real_valued_co...
Builds the tf . learn feature list .
237,978
def get_vocabulary ( preprocess_output_dir , name ) : vocab_file = os . path . join ( preprocess_output_dir , CATEGORICAL_ANALYSIS % name ) if not file_io . file_exists ( vocab_file ) : raise ValueError ( 'File %s not found in %s' % ( CATEGORICAL_ANALYSIS % name , preprocess_output_dir ) ) labels = python_portable_stri...
Loads the vocabulary file as a list of strings .
237,979
def validate_metadata ( train_config ) : if len ( train_config [ 'csv_header' ] ) != len ( train_config [ 'csv_defaults' ] ) : raise ValueError ( 'Unequal number of columns in input features file and ' 'schema file.' ) sorted_columns = sorted ( train_config [ 'csv_header' ] + [ train_config [ 'target_column' ] ] ) sort...
Perform some checks that the trainig config is correct .
237,980
def get_default_id ( credentials = None ) : project_id = _utils . get_project_id ( ) if project_id is None : projects , _ = Projects ( credentials ) . _retrieve_projects ( None , 2 ) if len ( projects ) == 1 : project_id = projects [ 0 ] . id return project_id
Get default project id .
237,981
def init_app ( state ) : app = state . app app . config . setdefault ( 'SPLIT_ALLOW_MULTIPLE_EXPERIMENTS' , False ) app . config . setdefault ( 'SPLIT_DB_FAILOVER' , False ) app . config . setdefault ( 'SPLIT_IGNORE_IP_ADDRESSES' , [ ] ) app . config . setdefault ( 'SPLIT_ROBOT_REGEX' , r ) app . jinja_env . globals . ...
Prepare the Flask application for Flask - Split .
237,982
def finished ( experiment_name , reset = True ) : if _exclude_visitor ( ) : return redis = _get_redis_connection ( ) try : experiment = Experiment . find ( redis , experiment_name ) if not experiment : return alternative_name = _get_session ( ) . get ( experiment . key ) if alternative_name : split_finished = set ( ses...
Track a conversion .
237,983
def _is_robot ( ) : robot_regex = current_app . config [ 'SPLIT_ROBOT_REGEX' ] user_agent = request . headers . get ( 'User-Agent' , '' ) return re . search ( robot_regex , user_agent , flags = re . VERBOSE )
Return True if the current visitor is a robot or spider or False otherwise .
237,984
def start_time ( self ) : t = self . redis . hget ( 'experiment_start_times' , self . name ) if t : return datetime . strptime ( t , '%Y-%m-%dT%H:%M:%S' )
The start time of this experiment .
237,985
def reset ( self ) : for alternative in self . alternatives : alternative . reset ( ) self . reset_winner ( ) self . increment_version ( )
Delete all data for this experiment .
237,986
def delete ( self ) : for alternative in self . alternatives : alternative . delete ( ) self . reset_winner ( ) self . redis . srem ( 'experiments' , self . name ) self . redis . delete ( self . name ) self . increment_version ( )
Delete this experiment and all its data .
237,987
def _get_redis_connection ( ) : url = current_app . config . get ( 'REDIS_URL' , 'redis://localhost:6379' ) return redis . from_url ( url , decode_responses = True )
Return a Redis connection based on the Flask application s configuration .
237,988
def set_experiment_winner ( experiment ) : redis = _get_redis_connection ( ) experiment = Experiment . find ( redis , experiment ) if experiment : alternative_name = request . form . get ( 'alternative' ) alternative = Alternative ( redis , alternative_name , experiment . name ) if alternative . name in experiment . al...
Mark an alternative as the winner of the experiment .
237,989
def reset_experiment ( experiment ) : redis = _get_redis_connection ( ) experiment = Experiment . find ( redis , experiment ) if experiment : experiment . reset ( ) return redirect ( url_for ( '.index' ) )
Delete all data for an experiment .
237,990
def delete_experiment ( experiment ) : redis = _get_redis_connection ( ) experiment = Experiment . find ( redis , experiment ) if experiment : experiment . delete ( ) return redirect ( url_for ( '.index' ) )
Delete an experiment and all its data .
237,991
def _get_ipaddress ( node ) : if "ipaddress" not in node : with settings ( hide ( 'stdout' ) , warn_only = True ) : output = sudo ( 'ohai -l warn ipaddress' ) if output . succeeded : try : node [ 'ipaddress' ] = json . loads ( output ) [ 0 ] except ValueError : abort ( "Could not parse ohai's output for ipaddress" ":\n...
Adds the ipaddress attribute to the given node object if not already present and it is correctly given by ohai Returns True if ipaddress is added False otherwise
237,992
def sync_node ( node ) : if node . get ( 'dummy' ) or 'dummy' in node . get ( 'tags' , [ ] ) : lib . print_header ( "Skipping dummy: {0}" . format ( env . host ) ) return False current_node = lib . get_node ( node [ 'name' ] ) solo . configure ( current_node ) ipaddress = _get_ipaddress ( node ) filepath = save_config ...
Builds synchronizes and configures a node . It also injects the ipaddress to the node s config file if not already existent .
237,993
def build_dct ( dic , keys , value ) : key = keys . pop ( 0 ) if len ( keys ) : dic . setdefault ( key , { } ) build_dct ( dic [ key ] , keys , value ) else : if value == "false" : value = False elif value == "true" : value = True dic [ key ] = deepcopy ( value )
Builds a dictionary with arbitrary depth out of a key list
237,994
def update_dct ( dic1 , dic2 ) : for key , val in dic2 . items ( ) : if isinstance ( val , dict ) : dic1 . setdefault ( key , { } ) update_dct ( dic1 [ key ] , val ) else : dic1 [ key ] = val
Merges two dictionaries recursively dic2 will have preference over dic1
237,995
def _add_merged_attributes ( node , all_recipes , all_roles ) : attributes = { } for recipe in node [ 'recipes' ] : found = False for r in all_recipes : if recipe == r [ 'name' ] : found = True for attr in r [ 'attributes' ] : if r [ 'attributes' ] [ attr ] . get ( 'type' ) == "hash" : value = { } else : value = r [ 'a...
Merges attributes from cookbooks node and roles
237,996
def build_node_data_bag ( ) : nodes = lib . get_nodes ( ) node_data_bag_path = os . path . join ( 'data_bags' , 'node' ) remove_local_node_data_bag ( ) os . makedirs ( node_data_bag_path ) all_recipes = lib . get_recipes ( ) all_roles = lib . get_roles ( ) for node in nodes : node [ 'id' ] = node [ 'name' ] . replace (...
Builds one node data bag item per file found in the nodes directory
237,997
def remove_local_node_data_bag ( ) : node_data_bag_path = os . path . join ( 'data_bags' , 'node' ) if os . path . exists ( node_data_bag_path ) : shutil . rmtree ( node_data_bag_path )
Removes generated node data_bag locally
237,998
def ensure_berksfile_cookbooks_are_installed ( ) : msg = "Vendoring cookbooks from Berksfile {0} to directory {1}..." print ( msg . format ( env . berksfile , env . berksfile_cookbooks_directory ) ) run_vendor = True cookbooks_dir = env . berksfile_cookbooks_directory berksfile_lock_path = cookbooks_dir + '/Berksfile.l...
Run berks vendor to berksfile cookbooks directory
237,999
def _remove_remote_node_data_bag ( ) : node_data_bag_path = os . path . join ( env . node_work_path , 'data_bags' , 'node' ) if exists ( node_data_bag_path ) : sudo ( "rm -rf {0}" . format ( node_data_bag_path ) )
Removes generated node data_bag from the remote node