Code
stringlengths
103
85.9k
Summary
listlengths
0
94
Please provide a description of the function:def transform(self, X): selected = auto_select_categorical_features(X, threshold=self.threshold) _, X_sel, n_selected, _ = _X_selected(X, selected) if n_selected == 0: # No features selected. raise ValueError('No cont...
[ "Select continuous features and transform them using PCA.\n\n Parameters\n ----------\n X: numpy ndarray, {n_samples, n_components}\n New data, where n_samples is the number of samples and n_components is the number of components.\n\n Returns\n -------\n array-li...
Please provide a description of the function:def fit(self, X, y=None, **fit_params): self.estimator.fit(X, y, **fit_params) return self
[ "Fit the StackingEstimator meta-transformer.\n\n Parameters\n ----------\n X: array-like of shape (n_samples, n_features)\n The training input samples.\n y: array-like, shape (n_samples,)\n The target values (integers that correspond to classes in classification, re...
Please provide a description of the function:def transform(self, X): X = check_array(X) X_transformed = np.copy(X) # add class probabilities as a synthetic feature if issubclass(self.estimator.__class__, ClassifierMixin) and hasattr(self.estimator, 'predict_proba'): ...
[ "Transform data by adding two synthetic feature(s).\n\n Parameters\n ----------\n X: numpy ndarray, {n_samples, n_components}\n New data, where n_samples is the number of samples and n_components is the number of components.\n\n Returns\n -------\n X_transformed:...
Please provide a description of the function:def balanced_accuracy(y_true, y_pred): all_classes = list(set(np.append(y_true, y_pred))) all_class_accuracies = [] for this_class in all_classes: this_class_sensitivity = 0. this_class_specificity = 0. if sum(y_true == this_class) !=...
[ "Default scoring function: balanced accuracy.\n\n Balanced accuracy computes each class' accuracy on a per-class basis using a\n one-vs-rest encoding, then computes an unweighted average of the class accuracies.\n\n Parameters\n ----------\n y_true: numpy.ndarray {n_samples}\n True class label...
Please provide a description of the function:def transform(self, X, y=None): X = check_array(X) n_features = X.shape[1] X_transformed = np.copy(X) non_zero_vector = np.count_nonzero(X_transformed, axis=1) non_zero = np.reshape(non_zero_vector, (-1, 1)) zero_col...
[ "Transform data by adding two virtual features.\n\n Parameters\n ----------\n X: numpy ndarray, {n_samples, n_components}\n New data, where n_samples is the number of samples and n_components\n is the number of components.\n y: None\n Unused\n\n Re...
Please provide a description of the function:def source_decode(sourcecode, verbose=0): tmp_path = sourcecode.split('.') op_str = tmp_path.pop() import_str = '.'.join(tmp_path) try: if sourcecode.startswith('tpot.'): exec('from {} import {}'.format(import_str[4:], op_str)) ...
[ "Decode operator source and import operator class.\n\n Parameters\n ----------\n sourcecode: string\n a string of operator source (e.g 'sklearn.feature_selection.RFE')\n verbose: int, optional (default: 0)\n How much information TPOT communicates while it's running.\n 0 = none, 1 = ...
Please provide a description of the function:def set_sample_weight(pipeline_steps, sample_weight=None): sample_weight_dict = {} if not isinstance(sample_weight, type(None)): for (pname, obj) in pipeline_steps: if inspect.getargspec(obj.fit).args.count('sample_weight'): s...
[ "Recursively iterates through all objects in the pipeline and sets sample weight.\n\n Parameters\n ----------\n pipeline_steps: array-like\n List of (str, obj) tuples from a scikit-learn pipeline or related object\n sample_weight: array-like\n List of sample weight\n Returns\n ------...
Please provide a description of the function:def TPOTOperatorClassFactory(opsourse, opdict, BaseClass=Operator, ArgBaseClass=ARGType, verbose=0): class_profile = {} dep_op_list = {} # list of nested estimator/callable function dep_op_type = {} # type of nested estimator/callable function import_str...
[ "Dynamically create operator class.\n\n Parameters\n ----------\n opsourse: string\n operator source in config dictionary (key)\n opdict: dictionary\n operator params in config dictionary (value)\n regression: bool\n True if it can be used in TPOTRegressor\n classification: bo...
Please provide a description of the function:def positive_integer(value): try: value = int(value) except Exception: raise argparse.ArgumentTypeError('Invalid int value: \'{}\''.format(value)) if value < 0: raise argparse.ArgumentTypeError('Invalid positive int value: \'{}\''.for...
[ "Ensure that the provided value is a positive integer.\n\n Parameters\n ----------\n value: int\n The number to evaluate\n\n Returns\n -------\n value: int\n Returns a positive integer\n " ]
Please provide a description of the function:def float_range(value): try: value = float(value) except Exception: raise argparse.ArgumentTypeError('Invalid float value: \'{}\''.format(value)) if value < 0.0 or value > 1.0: raise argparse.ArgumentTypeError('Invalid float value: \'...
[ "Ensure that the provided value is a float integer in the range [0., 1.].\n\n Parameters\n ----------\n value: float\n The number to evaluate\n\n Returns\n -------\n value: float\n Returns a float in the range (0., 1.)\n " ]
Please provide a description of the function:def _get_arg_parser(): parser = argparse.ArgumentParser( description=( 'A Python tool that automatically creates and optimizes machine ' 'learning pipelines using genetic programming.' ), add_help=False ) pars...
[ "Main function that is called when TPOT is run on the command line." ]
Please provide a description of the function:def load_scoring_function(scoring_func): if scoring_func and ("." in scoring_func): try: module_name, func_name = scoring_func.rsplit('.', 1) module_path = os.getcwd() sys.path.insert(0, module_path) scoring_f...
[ "\n converts mymodule.myfunc in the myfunc\n object itself so tpot receives a scoring function\n " ]
Please provide a description of the function:def tpot_driver(args): if args.VERBOSITY >= 2: _print_args(args) input_data = _read_data_file(args) features = input_data.drop(args.TARGET_NAME, axis=1) training_features, testing_features, training_target, testing_target = \ train_test...
[ "Perform a TPOT run." ]
Please provide a description of the function:def fit(self, X, y=None): subset_df = pd.read_csv(self.subset_list, header=0, index_col=0) if isinstance(self.sel_subset, int): self.sel_subset_name = subset_df.index[self.sel_subset] elif isinstance(self.sel_subset, str): ...
[ "Fit FeatureSetSelector for feature selection\n\n Parameters\n ----------\n X: array-like of shape (n_samples, n_features)\n The training input samples.\n y: array-like, shape (n_samples,)\n The target values (integers that correspond to classes in classification, r...
Please provide a description of the function:def transform(self, X): if isinstance(X, pd.DataFrame): X_transformed = X[self.feat_list].values elif isinstance(X, np.ndarray): X_transformed = X[:, self.feat_list_idx] return X_transformed.astype(np.float64)
[ "Make subset after fit\n\n Parameters\n ----------\n X: numpy ndarray, {n_samples, n_features}\n New data, where n_samples is the number of samples and n_features is the number of features.\n\n Returns\n -------\n X_transformed: array-like, shape (n_samples, n_fe...
Please provide a description of the function:def _get_support_mask(self): check_is_fitted(self, 'feat_list_idx') n_features = len(self.feature_names) mask = np.zeros(n_features, dtype=bool) mask[np.asarray(self.feat_list_idx)] = True return mask
[ "\n Get the boolean mask indicating which features are selected\n Returns\n -------\n support : boolean array of shape [# input features]\n An element is True iff its corresponding feature is selected for\n retention.\n " ]
Please provide a description of the function:def pick_two_individuals_eligible_for_crossover(population): primitives_by_ind = [set([node.name for node in ind if isinstance(node, gp.Primitive)]) for ind in population] pop_as_str = [str(ind) for ind in population] eligible_pairs...
[ "Pick two individuals from the population which can do crossover, that is, they share a primitive.\n\n Parameters\n ----------\n population: array of individuals\n\n Returns\n ----------\n tuple: (individual, individual)\n Two individuals which are not the same, but share at least one primi...
Please provide a description of the function:def mutate_random_individual(population, toolbox): idx = np.random.randint(0,len(population)) ind = population[idx] ind, = toolbox.mutate(ind) del ind.fitness.values return ind
[ "Picks a random individual from the population, and performs mutation on a copy of it.\n\n Parameters\n ----------\n population: array of individuals\n\n Returns\n ----------\n individual: individual\n An individual which is a mutated copy of one of the individuals in population,\n t...
Please provide a description of the function:def varOr(population, toolbox, lambda_, cxpb, mutpb): offspring = [] for _ in range(lambda_): op_choice = np.random.random() if op_choice < cxpb: # Apply crossover ind1, ind2 = pick_two_individuals_eligible_for_crossover(population)...
[ "Part of an evolutionary algorithm applying only the variation part\n (crossover, mutation **or** reproduction). The modified individuals have\n their fitness invalidated. The individuals are cloned so returned\n population is independent of the input population.\n :param population: A list of individua...
Please provide a description of the function:def initialize_stats_dict(individual): ''' Initializes the stats dict for individual The statistics initialized are: 'generation': generation in which the individual was evaluated. Initialized as: 0 'mutation_count': number of mutation operations ...
[]
Please provide a description of the function:def eaMuPlusLambda(population, toolbox, mu, lambda_, cxpb, mutpb, ngen, pbar, stats=None, halloffame=None, verbose=0, per_generation_function=None): logbook = tools.Logbook() logbook.header = ['gen', 'nevals'] + (stats.fields if stats else [])...
[ "This is the :math:`(\\mu + \\lambda)` evolutionary algorithm.\n :param population: A list of individuals.\n :param toolbox: A :class:`~deap.base.Toolbox` that contains the evolution\n operators.\n :param mu: The number of individuals to select for the next generation.\n :param lambda...
Please provide a description of the function:def cxOnePoint(ind1, ind2): # List all available primitive types in each individual types1 = defaultdict(list) types2 = defaultdict(list) for idx, node in enumerate(ind1[1:], 1): types1[node.ret].append(idx) common_types = [] for idx, no...
[ "Randomly select in each individual and exchange each subtree with the\n point as root between each individual.\n :param ind1: First tree participating in the crossover.\n :param ind2: Second tree participating in the crossover.\n :returns: A tuple of two trees.\n " ]
Please provide a description of the function:def mutNodeReplacement(individual, pset): index = np.random.randint(0, len(individual)) node = individual[index] slice_ = individual.searchSubtree(index) if node.arity == 0: # Terminal term = np.random.choice(pset.terminals[node.ret]) ...
[ "Replaces a randomly chosen primitive from *individual* by a randomly\n chosen primitive no matter if it has the same number of arguments from the :attr:`pset`\n attribute of the individual.\n Parameters\n ----------\n individual: DEAP individual\n A list of pipeline operators and model parame...
Please provide a description of the function:def _wrapped_cross_val_score(sklearn_pipeline, features, target, cv, scoring_function, sample_weight=None, groups=None, use_dask=False): sample_weight_dict = set_sample_weight(sklearn_pipeline.steps, sample_w...
[ "Fit estimator and compute scores for a given dataset split.\n\n Parameters\n ----------\n sklearn_pipeline : pipeline object implementing 'fit'\n The object to use to fit the data.\n features : array-like of shape at least 2D\n The data to fit.\n target : array-like, optional, default:...
Please provide a description of the function:def get_by_name(opname, operators): ret_op_classes = [op for op in operators if op.__name__ == opname] if len(ret_op_classes) == 0: raise TypeError('Cannot found operator {} in operator dictionary'.format(opname)) elif len(ret_op_classes) > 1: ...
[ "Return operator class instance by name.\n\n Parameters\n ----------\n opname: str\n Name of the sklearn class that belongs to a TPOT operator\n operators: list\n List of operator classes from operator library\n\n Returns\n -------\n ret_op_class: class\n An operator class\...
Please provide a description of the function:def export_pipeline(exported_pipeline, operators, pset, impute=False, pipeline_score=None, random_state=None, data_file_path=''): # Unroll the nested function calls into serial code ...
[ "Generate source code for a TPOT Pipeline.\n\n Parameters\n ----------\n exported_pipeline: deap.creator.Individual\n The pipeline that is being exported\n operators:\n List of operator classes from operator library\n pipeline_score:\n Optional pipeline score to be saved to the e...
Please provide a description of the function:def expr_to_tree(ind, pset): def prim_to_list(prim, args): if isinstance(prim, deap.gp.Terminal): if prim.name in pset.context: return pset.context[prim.name] else: return prim.value return [pr...
[ "Convert the unstructured DEAP pipeline into a tree data-structure.\n\n Parameters\n ----------\n ind: deap.creator.Individual\n The pipeline that is being exported\n\n Returns\n -------\n pipeline_tree: list\n List of operators in the current optimized pipeline\n\n EXAMPLE:\n ...
Please provide a description of the function:def generate_import_code(pipeline, operators, impute=False): def merge_imports(old_dict, new_dict): # Key is a module name for key in new_dict.keys(): if key in old_dict.keys(): # Union imports from the same module ...
[ "Generate all library import calls for use in TPOT.export().\n\n Parameters\n ----------\n pipeline: List\n List of operators in the current optimized pipeline\n operators:\n List of operator class from operator library\n impute : bool\n Whether to impute new values in the featur...
Please provide a description of the function:def generate_pipeline_code(pipeline_tree, operators): steps = _process_operator(pipeline_tree, operators) pipeline_text = "make_pipeline(\n{STEPS}\n)".format(STEPS=_indent(",\n".join(steps), 4)) return pipeline_text
[ "Generate code specific to the construction of the sklearn Pipeline.\n\n Parameters\n ----------\n pipeline_tree: list\n List of operators in the current optimized pipeline\n\n Returns\n -------\n Source code for the sklearn pipeline\n\n " ]
Please provide a description of the function:def generate_export_pipeline_code(pipeline_tree, operators): steps = _process_operator(pipeline_tree, operators) # number of steps in a pipeline num_step = len(steps) if num_step > 1: pipeline_text = "make_pipeline(\n{STEPS}\n)".format(STEPS=_ind...
[ "Generate code specific to the construction of the sklearn Pipeline for export_pipeline.\n\n Parameters\n ----------\n pipeline_tree: list\n List of operators in the current optimized pipeline\n\n Returns\n -------\n Source code for the sklearn pipeline\n\n " ]
Please provide a description of the function:def _indent(text, amount): indentation = amount * ' ' return indentation + ('\n' + indentation).join(text.split('\n'))
[ "Indent a multiline string by some number of spaces.\n\n Parameters\n ----------\n text: str\n The text to be indented\n amount: int\n The number of spaces to indent the text\n\n Returns\n -------\n indented_text\n\n " ]
Please provide a description of the function:def next(self): item = six.next(self._item_iter) result = self._item_to_value(self._parent, item) # Since we've successfully got the next value from the # iterator, we update the number of remaining. self._remaining -= 1 ...
[ "Get the next value in the page." ]
Please provide a description of the function:def _verify_params(self): reserved_in_use = self._RESERVED_PARAMS.intersection(self.extra_params) if reserved_in_use: raise ValueError("Using a reserved parameter", reserved_in_use)
[ "Verifies the parameters don't use any reserved parameter.\n\n Raises:\n ValueError: If a reserved parameter is used.\n " ]
Please provide a description of the function:def _next_page(self): if self._has_next_page(): response = self._get_next_page_response() items = response.get(self._items_key, ()) page = Page(self, items, self.item_to_value) self._page_start(self, page, resp...
[ "Get the next page in the iterator.\n\n Returns:\n Optional[Page]: The next page in the iterator or :data:`None` if\n there are no pages left.\n " ]
Please provide a description of the function:def _get_query_params(self): result = {} if self.next_page_token is not None: result[self._PAGE_TOKEN] = self.next_page_token if self.max_results is not None: result[self._MAX_RESULTS] = self.max_results - self.num_res...
[ "Getter for query parameters for the next request.\n\n Returns:\n dict: A dictionary of query parameters.\n " ]
Please provide a description of the function:def _get_next_page_response(self): params = self._get_query_params() if self._HTTP_METHOD == "GET": return self.api_request( method=self._HTTP_METHOD, path=self.path, query_params=params ) elif self._HT...
[ "Requests the next page from the path provided.\n\n Returns:\n dict: The parsed JSON response of the next page's contents.\n\n Raises:\n ValueError: If the HTTP method is not ``GET`` or ``POST``.\n " ]
Please provide a description of the function:def _next_page(self): try: items = six.next(self._gax_page_iter) page = Page(self, items, self.item_to_value) self.next_page_token = self._gax_page_iter.page_token or None return page except StopIterati...
[ "Get the next page in the iterator.\n\n Wraps the response from the :class:`~google.gax.PageIterator` in a\n :class:`Page` instance and captures some state at each page.\n\n Returns:\n Optional[Page]: The next page in the iterator or :data:`None` if\n there are no pa...
Please provide a description of the function:def _next_page(self): if not self._has_next_page(): return None if self.next_page_token is not None: setattr(self._request, self._request_token_field, self.next_page_token) response = self._method(self._request) ...
[ "Get the next page in the iterator.\n\n Returns:\n Page: The next page in the iterator or :data:`None` if\n there are no pages left.\n " ]
Please provide a description of the function:def _has_next_page(self): if self.page_number == 0: return True if self.max_results is not None: if self.num_results >= self.max_results: return False # Note: intentionally a falsy check instead of a ...
[ "Determines whether or not there are more pages with results.\n\n Returns:\n bool: Whether the iterator has more pages.\n " ]
Please provide a description of the function:def compare(cls, left, right): # First compare the types. leftType = TypeOrder.from_value(left).value rightType = TypeOrder.from_value(right).value if leftType != rightType: if leftType < rightType: return...
[ "\n Main comparison function for all Firestore types.\n @return -1 is left < right, 0 if left == right, otherwise 1\n " ]
Please provide a description of the function:def batch_annotate_files( self, requests, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None, ): # Wrap the transport method to add retry and timeout logic...
[ "\n Service that performs image detection and annotation for a batch of files.\n Now only \"application/pdf\", \"image/tiff\" and \"image/gif\" are supported.\n\n This service will extract at most the first 10 frames (gif) or pages\n (pdf or tiff) from each file provided and perform dete...
Please provide a description of the function:def async_batch_annotate_images( self, requests, output_config, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None, ): # Wrap the transport method ...
[ "\n Run asynchronous image detection and annotation for a list of images.\n\n Progress and results can be retrieved through the\n ``google.longrunning.Operations`` interface. ``Operation.metadata``\n contains ``OperationMetadata`` (metadata). ``Operation.response``\n contains ``As...
Please provide a description of the function:def async_batch_annotate_files( self, requests, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None, ): # Wrap the transport method to add retry and timeout...
[ "\n Run asynchronous image detection and annotation for a list of generic\n files, such as PDF files, which may contain multiple pages and multiple\n images per page. Progress and results can be retrieved through the\n ``google.longrunning.Operations`` interface. ``Operation.metadata``\n...
Please provide a description of the function:def load_ipython_extension(ipython): from google.cloud.bigquery.magics import _cell_magic ipython.register_magic_function( _cell_magic, magic_kind="cell", magic_name="bigquery" )
[ "Called by IPython when this module is loaded as an IPython extension." ]
Please provide a description of the function:def from_http_status(status_code, message, **kwargs): error_class = exception_class_for_http_status(status_code) error = error_class(message, **kwargs) if error.code is None: error.code = status_code return error
[ "Create a :class:`GoogleAPICallError` from an HTTP status code.\n\n Args:\n status_code (int): The HTTP status code.\n message (str): The exception message.\n kwargs: Additional arguments passed to the :class:`GoogleAPICallError`\n constructor.\n\n Returns:\n GoogleAPICa...
Please provide a description of the function:def from_http_response(response): try: payload = response.json() except ValueError: payload = {"error": {"message": response.text or "unknown error"}} error_message = payload.get("error", {}).get("message", "unknown error") errors = payl...
[ "Create a :class:`GoogleAPICallError` from a :class:`requests.Response`.\n\n Args:\n response (requests.Response): The HTTP response.\n\n Returns:\n GoogleAPICallError: An instance of the appropriate subclass of\n :class:`GoogleAPICallError`, with the message and errors populated\n ...
Please provide a description of the function:def from_grpc_status(status_code, message, **kwargs): error_class = exception_class_for_grpc_status(status_code) error = error_class(message, **kwargs) if error.grpc_status_code is None: error.grpc_status_code = status_code return error
[ "Create a :class:`GoogleAPICallError` from a :class:`grpc.StatusCode`.\n\n Args:\n status_code (grpc.StatusCode): The gRPC status code.\n message (str): The exception message.\n kwargs: Additional arguments passed to the :class:`GoogleAPICallError`\n constructor.\n\n Returns:\n...
Please provide a description of the function:def from_grpc_error(rpc_exc): if isinstance(rpc_exc, grpc.Call): return from_grpc_status( rpc_exc.code(), rpc_exc.details(), errors=(rpc_exc,), response=rpc_exc ) else: return GoogleAPICallError(str(rpc_exc), errors=(rpc_exc,)...
[ "Create a :class:`GoogleAPICallError` from a :class:`grpc.RpcError`.\n\n Args:\n rpc_exc (grpc.RpcError): The gRPC error.\n\n Returns:\n GoogleAPICallError: An instance of the appropriate subclass of\n :class:`GoogleAPICallError`.\n " ]
Please provide a description of the function:def _request(http, project, method, data, base_url): headers = { "Content-Type": "application/x-protobuf", "User-Agent": connection_module.DEFAULT_USER_AGENT, connection_module.CLIENT_INFO_HEADER: _CLIENT_INFO, } api_url = build_api_u...
[ "Make a request over the Http transport to the Cloud Datastore API.\n\n :type http: :class:`requests.Session`\n :param http: HTTP object to make requests.\n\n :type project: str\n :param project: The project to make the request for.\n\n :type method: str\n :param method: The API call method name (...
Please provide a description of the function:def _rpc(http, project, method, base_url, request_pb, response_pb_cls): req_data = request_pb.SerializeToString() response = _request(http, project, method, req_data, base_url) return response_pb_cls.FromString(response)
[ "Make a protobuf RPC request.\n\n :type http: :class:`requests.Session`\n :param http: HTTP object to make requests.\n\n :type project: str\n :param project: The project to connect to. This is\n usually your project name in the cloud console.\n\n :type method: str\n :param metho...
Please provide a description of the function:def build_api_url(project, method, base_url): return API_URL_TEMPLATE.format( api_base=base_url, api_version=API_VERSION, project=project, method=method )
[ "Construct the URL for a particular API call.\n\n This method is used internally to come up with the URL to use when\n making RPCs to the Cloud Datastore API.\n\n :type project: str\n :param project: The project to connect to. This is\n usually your project name in the cloud console.\...
Please provide a description of the function:def lookup(self, project_id, keys, read_options=None): request_pb = _datastore_pb2.LookupRequest( project_id=project_id, read_options=read_options, keys=keys ) return _rpc( self.client._http, project_id, ...
[ "Perform a ``lookup`` request.\n\n :type project_id: str\n :param project_id: The project to connect to. This is\n usually your project name in the cloud console.\n\n :type keys: List[.entity_pb2.Key]\n :param keys: The keys to retrieve from the datastore.\n\n ...
Please provide a description of the function:def run_query( self, project_id, partition_id, read_options=None, query=None, gql_query=None ): request_pb = _datastore_pb2.RunQueryRequest( project_id=project_id, partition_id=partition_id, read_options=read_o...
[ "Perform a ``runQuery`` request.\n\n :type project_id: str\n :param project_id: The project to connect to. This is\n usually your project name in the cloud console.\n\n :type partition_id: :class:`.entity_pb2.PartitionId`\n :param partition_id: Partition ID corr...
Please provide a description of the function:def begin_transaction(self, project_id, transaction_options=None): request_pb = _datastore_pb2.BeginTransactionRequest() return _rpc( self.client._http, project_id, "beginTransaction", self.client._base...
[ "Perform a ``beginTransaction`` request.\n\n :type project_id: str\n :param project_id: The project to connect to. This is\n usually your project name in the cloud console.\n\n :type transaction_options: ~.datastore_v1.types.TransactionOptions\n :param transacti...
Please provide a description of the function:def commit(self, project_id, mode, mutations, transaction=None): request_pb = _datastore_pb2.CommitRequest( project_id=project_id, mode=mode, transaction=transaction, mutations=mutations, ) retu...
[ "Perform a ``commit`` request.\n\n :type project_id: str\n :param project_id: The project to connect to. This is\n usually your project name in the cloud console.\n\n :type mode: :class:`.gapic.datastore.v1.enums.CommitRequest.Mode`\n :param mode: The type of co...
Please provide a description of the function:def rollback(self, project_id, transaction): request_pb = _datastore_pb2.RollbackRequest( project_id=project_id, transaction=transaction ) # Response is empty (i.e. no fields) but we return it anyway. return _rpc( ...
[ "Perform a ``rollback`` request.\n\n :type project_id: str\n :param project_id: The project to connect to. This is\n usually your project name in the cloud console.\n\n :type transaction: bytes\n :param transaction: The transaction ID to rollback.\n\n :rt...
Please provide a description of the function:def allocate_ids(self, project_id, keys): request_pb = _datastore_pb2.AllocateIdsRequest(keys=keys) return _rpc( self.client._http, project_id, "allocateIds", self.client._base_url, request_...
[ "Perform an ``allocateIds`` request.\n\n :type project_id: str\n :param project_id: The project to connect to. This is\n usually your project name in the cloud console.\n\n :type keys: List[.entity_pb2.Key]\n :param keys: The keys for which the backend should al...
Please provide a description of the function:def _create_row_request( table_name, start_key=None, end_key=None, filter_=None, limit=None, end_inclusive=False, app_profile_id=None, row_set=None, ): request_kwargs = {"table_name": table_name} if (start_key is not None or end_k...
[ "Creates a request to read rows in a table.\n\n :type table_name: str\n :param table_name: The name of the table to read from.\n\n :type start_key: bytes\n :param start_key: (Optional) The beginning of a range of row keys to\n read from. The range will include ``start_key``. If\n ...
Please provide a description of the function:def _mutate_rows_request(table_name, rows, app_profile_id=None): request_pb = data_messages_v2_pb2.MutateRowsRequest( table_name=table_name, app_profile_id=app_profile_id ) mutations_count = 0 for row in rows: _check_row_table_name(table_...
[ "Creates a request to mutate rows in a table.\n\n :type table_name: str\n :param table_name: The name of the table to write to.\n\n :type rows: list\n :param rows: List or other iterable of :class:`.DirectRow` instances.\n\n :type: app_profile_id: str\n :param app_profile_id: (Optional) The unique...
Please provide a description of the function:def _check_row_table_name(table_name, row): if row.table is not None and row.table.name != table_name: raise TableMismatchError( "Row %s is a part of %s table. Current table: %s" % (row.row_key, row.table.name, table_name) )
[ "Checks that a row belongs to a table.\n\n :type table_name: str\n :param table_name: The name of the table.\n\n :type row: :class:`~google.cloud.bigtable.row.Row`\n :param row: An instance of :class:`~google.cloud.bigtable.row.Row`\n subclasses.\n\n :raises: :exc:`~.table.TableMismatc...
Please provide a description of the function:def name(self): project = self._instance._client.project instance_id = self._instance.instance_id table_client = self._instance._client.table_data_client return table_client.table_path( project=project, instance=instance_i...
[ "Table name used in requests.\n\n For example:\n\n .. literalinclude:: snippets_table.py\n :start-after: [START bigtable_table_name]\n :end-before: [END bigtable_table_name]\n\n .. note::\n\n This property will not change if ``table_id`` does not, but the\n ...
Please provide a description of the function:def row(self, row_key, filter_=None, append=False): if append and filter_ is not None: raise ValueError("At most one of filter_ and append can be set") if append: return AppendRow(row_key, self) elif filter_ is not Non...
[ "Factory to create a row associated with this table.\n\n For example:\n\n .. literalinclude:: snippets_table.py\n :start-after: [START bigtable_table_row]\n :end-before: [END bigtable_table_row]\n\n .. warning::\n\n At most one of ``filter_`` and ``append`` can b...
Please provide a description of the function:def create(self, initial_split_keys=[], column_families={}): table_client = self._instance._client.table_admin_client instance_name = self._instance.name families = { id: ColumnFamily(id, self, rule).to_pb() for (id, ...
[ "Creates this table.\n\n For example:\n\n .. literalinclude:: snippets_table.py\n :start-after: [START bigtable_create_table]\n :end-before: [END bigtable_create_table]\n\n .. note::\n\n A create request returns a\n :class:`._generated.table_pb2.Table...
Please provide a description of the function:def exists(self): table_client = self._instance._client.table_admin_client try: table_client.get_table(name=self.name, view=VIEW_NAME_ONLY) return True except NotFound: return False
[ "Check whether the table exists.\n\n For example:\n\n .. literalinclude:: snippets_table.py\n :start-after: [START bigtable_check_table_exists]\n :end-before: [END bigtable_check_table_exists]\n\n :rtype: bool\n :returns: True if the table exists, else False.\n ...
Please provide a description of the function:def delete(self): table_client = self._instance._client.table_admin_client table_client.delete_table(name=self.name)
[ "Delete this table.\n\n For example:\n\n .. literalinclude:: snippets_table.py\n :start-after: [START bigtable_delete_table]\n :end-before: [END bigtable_delete_table]\n\n " ]
Please provide a description of the function:def list_column_families(self): table_client = self._instance._client.table_admin_client table_pb = table_client.get_table(self.name) result = {} for column_family_id, value_pb in table_pb.column_families.items(): gc_rule...
[ "List the column families owned by this table.\n\n For example:\n\n .. literalinclude:: snippets_table.py\n :start-after: [START bigtable_list_column_families]\n :end-before: [END bigtable_list_column_families]\n\n :rtype: dict\n :returns: Dictionary of column famil...
Please provide a description of the function:def get_cluster_states(self): REPLICATION_VIEW = enums.Table.View.REPLICATION_VIEW table_client = self._instance._client.table_admin_client table_pb = table_client.get_table(self.name, view=REPLICATION_VIEW) return { clu...
[ "List the cluster states owned by this table.\n\n For example:\n\n .. literalinclude:: snippets_table.py\n :start-after: [START bigtable_get_cluster_states]\n :end-before: [END bigtable_get_cluster_states]\n\n :rtype: dict\n :returns: Dictionary of cluster states fo...
Please provide a description of the function:def read_row(self, row_key, filter_=None): row_set = RowSet() row_set.add_row_key(row_key) result_iter = iter(self.read_rows(filter_=filter_, row_set=row_set)) row = next(result_iter, None) if next(result_iter, None) is not No...
[ "Read a single row from this table.\n\n For example:\n\n .. literalinclude:: snippets_table.py\n :start-after: [START bigtable_read_row]\n :end-before: [END bigtable_read_row]\n\n :type row_key: bytes\n :param row_key: The key of the row to read from.\n\n :ty...
Please provide a description of the function:def read_rows( self, start_key=None, end_key=None, limit=None, filter_=None, end_inclusive=False, row_set=None, retry=DEFAULT_RETRY_READ_ROWS, ): request_pb = _create_row_request( ...
[ "Read rows from this table.\n\n For example:\n\n .. literalinclude:: snippets_table.py\n :start-after: [START bigtable_read_rows]\n :end-before: [END bigtable_read_rows]\n\n :type start_key: bytes\n :param start_key: (Optional) The beginning of a range of row keys t...
Please provide a description of the function:def yield_rows(self, **kwargs): warnings.warn( "`yield_rows()` is depricated; use `red_rows()` instead", DeprecationWarning, stacklevel=2, ) return self.read_rows(**kwargs)
[ "Read rows from this table.\n\n .. warning::\n This method will be removed in future releases. Please use\n ``read_rows`` instead.\n\n :type start_key: bytes\n :param start_key: (Optional) The beginning of a range of row keys to\n read from. The ran...
Please provide a description of the function:def mutate_rows(self, rows, retry=DEFAULT_RETRY): retryable_mutate_rows = _RetryableMutateRowsWorker( self._instance._client, self.name, rows, app_profile_id=self._app_profile_id, timeout=self.mutat...
[ "Mutates multiple rows in bulk.\n\n For example:\n\n .. literalinclude:: snippets_table.py\n :start-after: [START bigtable_mutate_rows]\n :end-before: [END bigtable_mutate_rows]\n\n The method tries to update all specified rows.\n If some of the rows weren't updated...
Please provide a description of the function:def sample_row_keys(self): data_client = self._instance._client.table_data_client response_iterator = data_client.sample_row_keys( self.name, app_profile_id=self._app_profile_id ) return response_iterator
[ "Read a sample of row keys in the table.\n\n For example:\n\n .. literalinclude:: snippets_table.py\n :start-after: [START bigtable_sample_row_keys]\n :end-before: [END bigtable_sample_row_keys]\n\n The returned row keys will delimit contiguous sections of the table of\n ...
Please provide a description of the function:def truncate(self, timeout=None): client = self._instance._client table_admin_client = client.table_admin_client if timeout: table_admin_client.drop_row_range( self.name, delete_all_data_from_table=True, timeout=ti...
[ "Truncate the table\n\n For example:\n\n .. literalinclude:: snippets_table.py\n :start-after: [START bigtable_truncate_table]\n :end-before: [END bigtable_truncate_table]\n\n :type timeout: float\n :param timeout: (Optional) The amount of time, in seconds, to wait\...
Please provide a description of the function:def mutations_batcher(self, flush_count=FLUSH_COUNT, max_row_bytes=MAX_ROW_BYTES): return MutationsBatcher(self, flush_count, max_row_bytes)
[ "Factory to create a mutation batcher associated with this instance.\n\n For example:\n\n .. literalinclude:: snippets_table.py\n :start-after: [START bigtable_mutations_batcher]\n :end-before: [END bigtable_mutations_batcher]\n\n :type table: class\n :param table: ...
Please provide a description of the function:def _do_mutate_retryable_rows(self): retryable_rows = [] index_into_all_rows = [] for index, status in enumerate(self.responses_statuses): if self._is_retryable(status): retryable_rows.append(self.rows[index]) ...
[ "Mutate all the rows that are eligible for retry.\n\n A row is eligible for retry if it has not been tried or if it resulted\n in a transient error in a previous call.\n\n :rtype: list\n :return: The responses statuses, which is a list of\n :class:`~google.rpc.status_pb2....
Please provide a description of the function:def heartbeat(self): while self._manager.is_active and not self._stop_event.is_set(): self._manager.heartbeat() _LOGGER.debug("Sent heartbeat.") self._stop_event.wait(timeout=self._period) _LOGGER.info("%s exiting...
[ "Periodically send heartbeats." ]
Please provide a description of the function:def report_error_event( self, project_name, event, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None, ): # Wrap the transport method to add retry ...
[ "\n Report an individual error event.\n\n Example:\n >>> from google.cloud import errorreporting_v1beta1\n >>>\n >>> client = errorreporting_v1beta1.ReportErrorsServiceClient()\n >>>\n >>> project_name = client.project_path('[PROJECT]')\n ...
Please provide a description of the function:def scalar_to_query_parameter(value, name=None): parameter_type = None if isinstance(value, bool): parameter_type = "BOOL" elif isinstance(value, numbers.Integral): parameter_type = "INT64" elif isinstance(value, numbers.Real): p...
[ "Convert a scalar value into a query parameter.\n\n :type value: any\n :param value: A scalar value to convert into a query parameter.\n\n :type name: str\n :param name: (Optional) Name of the query parameter.\n\n :rtype: :class:`~google.cloud.bigquery.ScalarQueryParameter`\n :returns:\n A ...
Please provide a description of the function:def to_query_parameters_dict(parameters): return [ scalar_to_query_parameter(value, name=name) for name, value in six.iteritems(parameters) ]
[ "Converts a dictionary of parameter values into query parameters.\n\n :type parameters: Mapping[str, Any]\n :param parameters: Dictionary of query parameter values.\n\n :rtype: List[google.cloud.bigquery.query._AbstractQueryParameter]\n :returns: A list of named query parameters.\n " ]
Please provide a description of the function:def to_query_parameters(parameters): if parameters is None: return [] if isinstance(parameters, collections_abc.Mapping): return to_query_parameters_dict(parameters) return to_query_parameters_list(parameters)
[ "Converts DB-API parameter values into query parameters.\n\n :type parameters: Mapping[str, Any] or Sequence[Any]\n :param parameters: A dictionary or sequence of query parameter values.\n\n :rtype: List[google.cloud.bigquery.query._AbstractQueryParameter]\n :returns: A list of query parameters.\n " ...
Please provide a description of the function:def _refresh_http(api_request, operation_name): path = "operations/{}".format(operation_name) api_response = api_request(method="GET", path=path) return json_format.ParseDict(api_response, operations_pb2.Operation())
[ "Refresh an operation using a JSON/HTTP client.\n\n Args:\n api_request (Callable): A callable used to make an API request. This\n should generally be\n :meth:`google.cloud._http.Connection.api_request`.\n operation_name (str): The name of the operation.\n\n Returns:\n ...
Please provide a description of the function:def _cancel_http(api_request, operation_name): path = "operations/{}:cancel".format(operation_name) api_request(method="POST", path=path)
[ "Cancel an operation using a JSON/HTTP client.\n\n Args:\n api_request (Callable): A callable used to make an API request. This\n should generally be\n :meth:`google.cloud._http.Connection.api_request`.\n operation_name (str): The name of the operation.\n " ]
Please provide a description of the function:def from_http_json(operation, api_request, result_type, **kwargs): operation_proto = json_format.ParseDict(operation, operations_pb2.Operation()) refresh = functools.partial(_refresh_http, api_request, operation_proto.name) cancel = functools.partial(_cancel...
[ "Create an operation future using a HTTP/JSON client.\n\n This interacts with the long-running operations `service`_ (specific\n to a given API) via `HTTP/JSON`_.\n\n .. _HTTP/JSON: https://cloud.google.com/speech/reference/rest/\\\n v1beta1/operations#Operation\n\n Args:\n operation (...
Please provide a description of the function:def _refresh_grpc(operations_stub, operation_name): request_pb = operations_pb2.GetOperationRequest(name=operation_name) return operations_stub.GetOperation(request_pb)
[ "Refresh an operation using a gRPC client.\n\n Args:\n operations_stub (google.longrunning.operations_pb2.OperationsStub):\n The gRPC operations stub.\n operation_name (str): The name of the operation.\n\n Returns:\n google.longrunning.operations_pb2.Operation: The operation.\n...
Please provide a description of the function:def _cancel_grpc(operations_stub, operation_name): request_pb = operations_pb2.CancelOperationRequest(name=operation_name) operations_stub.CancelOperation(request_pb)
[ "Cancel an operation using a gRPC client.\n\n Args:\n operations_stub (google.longrunning.operations_pb2.OperationsStub):\n The gRPC operations stub.\n operation_name (str): The name of the operation.\n " ]
Please provide a description of the function:def from_grpc(operation, operations_stub, result_type, **kwargs): refresh = functools.partial(_refresh_grpc, operations_stub, operation.name) cancel = functools.partial(_cancel_grpc, operations_stub, operation.name) return Operation(operation, refresh, cance...
[ "Create an operation future using a gRPC client.\n\n This interacts with the long-running operations `service`_ (specific\n to a given API) via gRPC.\n\n .. _service: https://github.com/googleapis/googleapis/blob/\\\n 050400df0fdb16f63b63e9dee53819044bffc857/\\\n google/long...
Please provide a description of the function:def from_gapic(operation, operations_client, result_type, **kwargs): refresh = functools.partial(operations_client.get_operation, operation.name) cancel = functools.partial(operations_client.cancel_operation, operation.name) return Operation(operation, refre...
[ "Create an operation future from a gapic client.\n\n This interacts with the long-running operations `service`_ (specific\n to a given API) via a gapic client.\n\n .. _service: https://github.com/googleapis/googleapis/blob/\\\n 050400df0fdb16f63b63e9dee53819044bffc857/\\\n g...
Please provide a description of the function:def metadata(self): if not self._operation.HasField("metadata"): return None return protobuf_helpers.from_any_pb( self._metadata_type, self._operation.metadata )
[ "google.protobuf.Message: the current operation metadata." ]
Please provide a description of the function:def _set_result_from_operation(self): # This must be done in a lock to prevent the polling thread # and main thread from both executing the completion logic # at the same time. with self._completion_lock: # If the operatio...
[ "Set the result or exception from the operation if it is complete." ]
Please provide a description of the function:def _refresh_and_update(self): # If the currently cached operation is done, no need to make another # RPC as it will not change once done. if not self._operation.done: self._operation = self._refresh() self._set_result...
[ "Refresh the operation and update the result if needed." ]
Please provide a description of the function:def cancelled(self): self._refresh_and_update() return ( self._operation.HasField("error") and self._operation.error.code == code_pb2.CANCELLED )
[ "True if the operation was cancelled." ]
Please provide a description of the function:def revoke(self, role): if role in self.roles: self.roles.remove(role)
[ "Remove a role from the entity.\n\n :type role: str\n :param role: The role to remove from the entity.\n " ]
Please provide a description of the function:def validate_predefined(cls, predefined): predefined = cls.PREDEFINED_XML_ACLS.get(predefined, predefined) if predefined and predefined not in cls.PREDEFINED_JSON_ACLS: raise ValueError("Invalid predefined ACL: %s" % (predefined,)) ...
[ "Ensures predefined is in list of predefined json values\n\n :type predefined: str\n :param predefined: name of a predefined acl\n\n :type predefined: str\n :param predefined: validated JSON name of predefined acl\n\n :raises: :exc: `ValueError`: If predefined is not a valid acl\n...
Please provide a description of the function:def entity_from_dict(self, entity_dict): entity = entity_dict["entity"] role = entity_dict["role"] if entity == "allUsers": entity = self.all() elif entity == "allAuthenticatedUsers": entity = self.all_authen...
[ "Build an _ACLEntity object from a dictionary of data.\n\n An entity is a mutable object that represents a list of roles\n belonging to either a user or group or the special types for all\n users and all authenticated users.\n\n :type entity_dict: dict\n :param entity_dict: Dictio...
Please provide a description of the function:def get_entity(self, entity, default=None): self._ensure_loaded() return self.entities.get(str(entity), default)
[ "Gets an entity object from the ACL.\n\n :type entity: :class:`_ACLEntity` or string\n :param entity: The entity to get lookup in the ACL.\n\n :type default: anything\n :param default: This value will be returned if the entity\n doesn't exist.\n\n :rtype: :c...
Please provide a description of the function:def add_entity(self, entity): self._ensure_loaded() self.entities[str(entity)] = entity
[ "Add an entity to the ACL.\n\n :type entity: :class:`_ACLEntity`\n :param entity: The entity to add to this ACL.\n " ]
Please provide a description of the function:def entity(self, entity_type, identifier=None): entity = _ACLEntity(entity_type=entity_type, identifier=identifier) if self.has_entity(entity): entity = self.get_entity(entity) else: self.add_entity(entity) ret...
[ "Factory method for creating an Entity.\n\n If an entity with the same type and identifier already exists,\n this will return a reference to that entity. If not, it will\n create a new one and add it to the list of known entities for\n this ACL.\n\n :type entity_type: str\n ...
Please provide a description of the function:def reload(self, client=None): path = self.reload_path client = self._require_client(client) query_params = {} if self.user_project is not None: query_params["userProject"] = self.user_project self.entities.clear...
[ "Reload the ACL data from Cloud Storage.\n\n If :attr:`user_project` is set, bills the API request to that project.\n\n :type client: :class:`~google.cloud.storage.client.Client` or\n ``NoneType``\n :param client: Optional. The client to use. If not passed, falls back\n ...
Please provide a description of the function:def _save(self, acl, predefined, client): query_params = {"projection": "full"} if predefined is not None: acl = [] query_params[self._PREDEFINED_QUERY_PARAM] = predefined if self.user_project is not None: ...
[ "Helper for :meth:`save` and :meth:`save_predefined`.\n\n :type acl: :class:`google.cloud.storage.acl.ACL`, or a compatible list.\n :param acl: The ACL object to save. If left blank, this will save\n current entries.\n\n :type predefined: str\n :param predefined:\n ...
Please provide a description of the function:def save(self, acl=None, client=None): if acl is None: acl = self save_to_backend = acl.loaded else: save_to_backend = True if save_to_backend: self._save(acl, None, client)
[ "Save this ACL for the current bucket.\n\n If :attr:`user_project` is set, bills the API request to that project.\n\n :type acl: :class:`google.cloud.storage.acl.ACL`, or a compatible list.\n :param acl: The ACL object to save. If left blank, this will save\n current entries...