Search is not available for this dataset
identifier
stringlengths
1
155
parameters
stringlengths
2
6.09k
docstring
stringlengths
11
63.4k
docstring_summary
stringlengths
0
63.4k
function
stringlengths
29
99.8k
function_tokens
list
start_point
list
end_point
list
language
stringclasses
1 value
docstring_language
stringlengths
2
7
docstring_language_predictions
stringlengths
18
23
is_langid_reliable
stringclasses
2 values
ElasticsearchDocumentStore.get_documents_by_id
(self, ids: List[str], index: Optional[str] = None)
Fetch documents by specifying a list of text id strings
Fetch documents by specifying a list of text id strings
def get_documents_by_id(self, ids: List[str], index: Optional[str] = None) -> List[Document]: """Fetch documents by specifying a list of text id strings""" index = index or self.index query = {"query": {"ids": {"values": ids}}} result = self.client.search(index=index, body=query)["hits"]...
[ "def", "get_documents_by_id", "(", "self", ",", "ids", ":", "List", "[", "str", "]", ",", "index", ":", "Optional", "[", "str", "]", "=", "None", ")", "->", "List", "[", "Document", "]", ":", "index", "=", "index", "or", "self", ".", "index", "quer...
[ 280, 4 ]
[ 286, 24 ]
python
en
['en', 'en', 'en']
True
ElasticsearchDocumentStore.get_metadata_values_by_key
( self, key: str, query: Optional[str] = None, filters: Optional[Dict[str, List[str]]] = None, index: Optional[str] = None, )
Get values associated with a metadata key. The output is in the format: [{"value": "my-value-1", "count": 23}, {"value": "my-value-2", "count": 12}, ... ] :param key: the meta key name to get the values for. :param query: narrow down the scope to documents matching the query string...
Get values associated with a metadata key. The output is in the format: [{"value": "my-value-1", "count": 23}, {"value": "my-value-2", "count": 12}, ... ]
def get_metadata_values_by_key( self, key: str, query: Optional[str] = None, filters: Optional[Dict[str, List[str]]] = None, index: Optional[str] = None, ) -> List[dict]: """ Get values associated with a metadata key. The output is in the format: [...
[ "def", "get_metadata_values_by_key", "(", "self", ",", "key", ":", "str", ",", "query", ":", "Optional", "[", "str", "]", "=", "None", ",", "filters", ":", "Optional", "[", "Dict", "[", "str", ",", "List", "[", "str", "]", "]", "]", "=", "None", ",...
[ 288, 4 ]
[ 324, 22 ]
python
en
['en', 'error', 'th']
False
ElasticsearchDocumentStore.write_documents
( self, documents: Union[List[dict], List[Document]], index: Optional[str] = None, batch_size: int = 10_000 )
Indexes documents for later queries in Elasticsearch. Behaviour if a document with the same ID already exists in ElasticSearch: a) (Default) Throw Elastic's standard error message for duplicate IDs. b) If `self.update_existing_documents=True` for DocumentStore: Overwrite existing docum...
Indexes documents for later queries in Elasticsearch.
def write_documents( self, documents: Union[List[dict], List[Document]], index: Optional[str] = None, batch_size: int = 10_000 ): """ Indexes documents for later queries in Elasticsearch. Behaviour if a document with the same ID already exists in ElasticSearch: a) (Default)...
[ "def", "write_documents", "(", "self", ",", "documents", ":", "Union", "[", "List", "[", "dict", "]", ",", "List", "[", "Document", "]", "]", ",", "index", ":", "Optional", "[", "str", "]", "=", "None", ",", "batch_size", ":", "int", "=", "10_000", ...
[ 326, 4 ]
[ 398, 97 ]
python
en
['en', 'error', 'th']
False
ElasticsearchDocumentStore.write_labels
( self, labels: Union[List[Label], List[dict]], index: Optional[str] = None, batch_size: int = 10_000 )
Write annotation labels into document store. :param labels: A list of Python dictionaries or a list of Haystack Label objects. :param batch_size: Number of labels that are passed to Elasticsearch's bulk function at a time.
Write annotation labels into document store.
def write_labels( self, labels: Union[List[Label], List[dict]], index: Optional[str] = None, batch_size: int = 10_000 ): """Write annotation labels into document store. :param labels: A list of Python dictionaries or a list of Haystack Label objects. :param batch_size: Number of lab...
[ "def", "write_labels", "(", "self", ",", "labels", ":", "Union", "[", "List", "[", "Label", "]", ",", "List", "[", "dict", "]", "]", ",", "index", ":", "Optional", "[", "str", "]", "=", "None", ",", "batch_size", ":", "int", "=", "10_000", ")", "...
[ 400, 4 ]
[ 444, 94 ]
python
en
['en', 'en', 'en']
True
ElasticsearchDocumentStore.update_document_meta
(self, id: str, meta: Dict[str, str])
Update the metadata dictionary of a document by specifying its string id
Update the metadata dictionary of a document by specifying its string id
def update_document_meta(self, id: str, meta: Dict[str, str]): """ Update the metadata dictionary of a document by specifying its string id """ body = {"doc": meta} self.client.update(index=self.index, id=id, body=body, refresh=self.refresh_type)
[ "def", "update_document_meta", "(", "self", ",", "id", ":", "str", ",", "meta", ":", "Dict", "[", "str", ",", "str", "]", ")", ":", "body", "=", "{", "\"doc\"", ":", "meta", "}", "self", ".", "client", ".", "update", "(", "index", "=", "self", "....
[ 446, 4 ]
[ 451, 89 ]
python
en
['en', 'error', 'th']
False
ElasticsearchDocumentStore.get_document_count
(self, filters: Optional[Dict[str, List[str]]] = None, index: Optional[str] = None)
Return the number of documents in the document store.
Return the number of documents in the document store.
def get_document_count(self, filters: Optional[Dict[str, List[str]]] = None, index: Optional[str] = None) -> int: """ Return the number of documents in the document store. """ index = index or self.index body: dict = {"query": {"bool": {}}} if filters: filter...
[ "def", "get_document_count", "(", "self", ",", "filters", ":", "Optional", "[", "Dict", "[", "str", ",", "List", "[", "str", "]", "]", "]", "=", "None", ",", "index", ":", "Optional", "[", "str", "]", "=", "None", ")", "->", "int", ":", "index", ...
[ 453, 4 ]
[ 476, 20 ]
python
en
['en', 'error', 'th']
False
ElasticsearchDocumentStore.get_label_count
(self, index: Optional[str] = None)
Return the number of labels in the document store
Return the number of labels in the document store
def get_label_count(self, index: Optional[str] = None) -> int: """ Return the number of labels in the document store """ return self.get_document_count(index=index)
[ "def", "get_label_count", "(", "self", ",", "index", ":", "Optional", "[", "str", "]", "=", "None", ")", "->", "int", ":", "return", "self", ".", "get_document_count", "(", "index", "=", "index", ")" ]
[ 478, 4 ]
[ 482, 51 ]
python
en
['en', 'error', 'th']
False
ElasticsearchDocumentStore.get_all_documents
( self, index: Optional[str] = None, filters: Optional[Dict[str, List[str]]] = None, return_embedding: Optional[bool] = None, batch_size: int = 10_000, )
Get documents from the document store. :param index: Name of the index to get the documents from. If None, the DocumentStore's default index (self.index) will be used. :param filters: Optional filters to narrow down the documents to return. Example...
Get documents from the document store.
def get_all_documents( self, index: Optional[str] = None, filters: Optional[Dict[str, List[str]]] = None, return_embedding: Optional[bool] = None, batch_size: int = 10_000, ) -> List[Document]: """ Get documents from the document store. :param index: ...
[ "def", "get_all_documents", "(", "self", ",", "index", ":", "Optional", "[", "str", "]", "=", "None", ",", "filters", ":", "Optional", "[", "Dict", "[", "str", ",", "List", "[", "str", "]", "]", "]", "=", "None", ",", "return_embedding", ":", "Option...
[ 484, 4 ]
[ 505, 24 ]
python
en
['en', 'error', 'th']
False
ElasticsearchDocumentStore.get_all_documents_generator
( self, index: Optional[str] = None, filters: Optional[Dict[str, List[str]]] = None, return_embedding: Optional[bool] = None, batch_size: int = 10_000, )
Get documents from the document store. Under-the-hood, documents are fetched in batches from the document store and yielded as individual documents. This method can be used to iteratively process a large number of documents without having to load all documents in memory. :param index: ...
Get documents from the document store. Under-the-hood, documents are fetched in batches from the document store and yielded as individual documents. This method can be used to iteratively process a large number of documents without having to load all documents in memory.
def get_all_documents_generator( self, index: Optional[str] = None, filters: Optional[Dict[str, List[str]]] = None, return_embedding: Optional[bool] = None, batch_size: int = 10_000, ) -> Generator[Document, None, None]: """ Get documents from the document sto...
[ "def", "get_all_documents_generator", "(", "self", ",", "index", ":", "Optional", "[", "str", "]", "=", "None", ",", "filters", ":", "Optional", "[", "Dict", "[", "str", ",", "List", "[", "str", "]", "]", "]", "=", "None", ",", "return_embedding", ":",...
[ 507, 4 ]
[ 536, 26 ]
python
en
['en', 'error', 'th']
False
ElasticsearchDocumentStore.get_all_labels
( self, index: Optional[str] = None, filters: Optional[Dict[str, List[str]]] = None, batch_size: int = 10_000 )
Return all labels in the document store
Return all labels in the document store
def get_all_labels( self, index: Optional[str] = None, filters: Optional[Dict[str, List[str]]] = None, batch_size: int = 10_000 ) -> List[Label]: """ Return all labels in the document store """ index = index or self.label_index result = list(self._get_all_documents_in...
[ "def", "get_all_labels", "(", "self", ",", "index", ":", "Optional", "[", "str", "]", "=", "None", ",", "filters", ":", "Optional", "[", "Dict", "[", "str", ",", "List", "[", "str", "]", "]", "]", "=", "None", ",", "batch_size", ":", "int", "=", ...
[ 538, 4 ]
[ 547, 21 ]
python
en
['en', 'error', 'th']
False
ElasticsearchDocumentStore._get_all_documents_in_index
( self, index: str, filters: Optional[Dict[str, List[str]]] = None, batch_size: int = 10_000, only_documents_without_embedding: bool = False, )
Return all documents in a specific index in the document store
Return all documents in a specific index in the document store
def _get_all_documents_in_index( self, index: str, filters: Optional[Dict[str, List[str]]] = None, batch_size: int = 10_000, only_documents_without_embedding: bool = False, ) -> Generator[dict, None, None]: """ Return all documents in a specific index in the d...
[ "def", "_get_all_documents_in_index", "(", "self", ",", "index", ":", "str", ",", "filters", ":", "Optional", "[", "Dict", "[", "str", ",", "List", "[", "str", "]", "]", "]", "=", "None", ",", "batch_size", ":", "int", "=", "10_000", ",", "only_documen...
[ 549, 4 ]
[ 575, 25 ]
python
en
['en', 'error', 'th']
False
ElasticsearchDocumentStore.query
( self, query: Optional[str], filters: Optional[Dict[str, List[str]]] = None, top_k: int = 10, custom_query: Optional[str] = None, index: Optional[str] = None, )
Scan through documents in DocumentStore and return a small number documents that are most relevant to the query as defined by the BM25 algorithm. :param query: The query :param filters: A dictionary where the keys specify a metadata field and the value is a list of accepted values for ...
Scan through documents in DocumentStore and return a small number documents that are most relevant to the query as defined by the BM25 algorithm.
def query( self, query: Optional[str], filters: Optional[Dict[str, List[str]]] = None, top_k: int = 10, custom_query: Optional[str] = None, index: Optional[str] = None, ) -> List[Document]: """ Scan through documents in DocumentStore and return a small...
[ "def", "query", "(", "self", ",", "query", ":", "Optional", "[", "str", "]", ",", "filters", ":", "Optional", "[", "Dict", "[", "str", ",", "List", "[", "str", "]", "]", "]", "=", "None", ",", "top_k", ":", "int", "=", "10", ",", "custom_query", ...
[ 577, 4 ]
[ 660, 24 ]
python
en
['en', 'error', 'th']
False
ElasticsearchDocumentStore.query_by_embedding
(self, query_emb: np.ndarray, filters: Optional[Dict[str, List[str]]] = None, top_k: int = 10, index: Optional[str] = None, return_embedding: Optional[bool] = None)
Find the document that is most similar to the provided `query_emb` by using a vector similarity metric. :param query_emb: Embedding of the query (e.g. gathered from DPR) :param filters: Optional filters to narrow down the search space. Example: {"name": ["some", "more"]...
Find the document that is most similar to the provided `query_emb` by using a vector similarity metric.
def query_by_embedding(self, query_emb: np.ndarray, filters: Optional[Dict[str, List[str]]] = None, top_k: int = 10, index: Optional[str] = None, return_embedding: Optional[bool] = None...
[ "def", "query_by_embedding", "(", "self", ",", "query_emb", ":", "np", ".", "ndarray", ",", "filters", ":", "Optional", "[", "Dict", "[", "str", ",", "List", "[", "str", "]", "]", "]", "=", "None", ",", "top_k", ":", "int", "=", "10", ",", "index",...
[ 662, 4 ]
[ 728, 28 ]
python
en
['en', 'error', 'th']
False
ElasticsearchDocumentStore._get_vector_similarity_query
(self, query_emb: np.ndarray, top_k: int)
Generate Elasticsearch query for vector similarity.
Generate Elasticsearch query for vector similarity.
def _get_vector_similarity_query(self, query_emb: np.ndarray, top_k: int): """ Generate Elasticsearch query for vector similarity. """ if self.similarity == "cosine": similarity_fn_name = "cosineSimilarity" elif self.similarity == "dot_product": similarity...
[ "def", "_get_vector_similarity_query", "(", "self", ",", "query_emb", ":", "np", ".", "ndarray", ",", "top_k", ":", "int", ")", ":", "if", "self", ".", "similarity", "==", "\"cosine\"", ":", "similarity_fn_name", "=", "\"cosineSimilarity\"", "elif", "self", "....
[ 730, 4 ]
[ 751, 20 ]
python
en
['en', 'error', 'th']
False
ElasticsearchDocumentStore.describe_documents
(self, index=None)
Return a summary of the documents in the document store
Return a summary of the documents in the document store
def describe_documents(self, index=None): """ Return a summary of the documents in the document store """ if index is None: index = self.index docs = self.get_all_documents(index) l = [len(d.text) for d in docs] stats = {"count": len(docs), ...
[ "def", "describe_documents", "(", "self", ",", "index", "=", "None", ")", ":", "if", "index", "is", "None", ":", "index", "=", "self", ".", "index", "docs", "=", "self", ".", "get_all_documents", "(", "index", ")", "l", "=", "[", "len", "(", "d", "...
[ 799, 4 ]
[ 814, 20 ]
python
en
['en', 'error', 'th']
False
ElasticsearchDocumentStore.update_embeddings
( self, retriever, index: Optional[str] = None, filters: Optional[Dict[str, List[str]]] = None, update_existing_embeddings: bool = True, batch_size: int = 10_000 )
Updates the embeddings in the the document store using the encoding model specified in the retriever. This can be useful if want to add or change the embeddings for your documents (e.g. after changing the retriever config). :param retriever: Retriever to use to update the embeddings. :...
Updates the embeddings in the the document store using the encoding model specified in the retriever. This can be useful if want to add or change the embeddings for your documents (e.g. after changing the retriever config).
def update_embeddings( self, retriever, index: Optional[str] = None, filters: Optional[Dict[str, List[str]]] = None, update_existing_embeddings: bool = True, batch_size: int = 10_000 ): """ Updates the embeddings in the the document store using the enc...
[ "def", "update_embeddings", "(", "self", ",", "retriever", ",", "index", ":", "Optional", "[", "str", "]", "=", "None", ",", "filters", ":", "Optional", "[", "Dict", "[", "str", ",", "List", "[", "str", "]", "]", "]", "=", "None", ",", "update_existi...
[ 816, 4 ]
[ 875, 90 ]
python
en
['en', 'error', 'th']
False
ElasticsearchDocumentStore.delete_all_documents
(self, index: Optional[str] = None, filters: Optional[Dict[str, List[str]]] = None)
Delete documents in an index. All documents are deleted if no filters are passed. :param index: Index name to delete the document from. :param filters: Optional filters to narrow down the documents to be deleted. :return: None
Delete documents in an index. All documents are deleted if no filters are passed.
def delete_all_documents(self, index: Optional[str] = None, filters: Optional[Dict[str, List[str]]] = None): """ Delete documents in an index. All documents are deleted if no filters are passed. :param index: Index name to delete the document from. :param filters: Optional filters to na...
[ "def", "delete_all_documents", "(", "self", ",", "index", ":", "Optional", "[", "str", "]", "=", "None", ",", "filters", ":", "Optional", "[", "Dict", "[", "str", ",", "List", "[", "str", "]", "]", "]", "=", "None", ")", ":", "index", "=", "index",...
[ 877, 4 ]
[ 901, 25 ]
python
en
['en', 'error', 'th']
False
OpenDistroElasticsearchDocumentStore._create_document_index
(self, index_name: str)
Create a new index for storing documents.
Create a new index for storing documents.
def _create_document_index(self, index_name: str): """ Create a new index for storing documents. """ if self.custom_mapping: mapping = self.custom_mapping else: mapping = { "mappings": { "properties": { ...
[ "def", "_create_document_index", "(", "self", ",", "index_name", ":", "str", ")", ":", "if", "self", ".", "custom_mapping", ":", "mapping", "=", "self", ".", "custom_mapping", "else", ":", "mapping", "=", "{", "\"mappings\"", ":", "{", "\"properties\"", ":",...
[ 912, 4 ]
[ 968, 23 ]
python
en
['en', 'error', 'th']
False
OpenDistroElasticsearchDocumentStore._get_vector_similarity_query
(self, query_emb: np.ndarray, top_k: int)
Generate Elasticsearch query for vector similarity.
Generate Elasticsearch query for vector similarity.
def _get_vector_similarity_query(self, query_emb: np.ndarray, top_k: int): """ Generate Elasticsearch query for vector similarity. """ query = {"knn": {self.embedding_field: {"vector": query_emb.tolist(), "k": top_k}}} return query
[ "def", "_get_vector_similarity_query", "(", "self", ",", "query_emb", ":", "np", ".", "ndarray", ",", "top_k", ":", "int", ")", ":", "query", "=", "{", "\"knn\"", ":", "{", "self", ".", "embedding_field", ":", "{", "\"vector\"", ":", "query_emb", ".", "t...
[ 970, 4 ]
[ 975, 20 ]
python
en
['en', 'error', 'th']
False
WindowGenerator.example
(self)
Get and cache an example batch of `inputs, labels` for plotting.
Get and cache an example batch of `inputs, labels` for plotting.
def example(self): """Get and cache an example batch of `inputs, labels` for plotting.""" result = getattr(self, '_example', None) if result is None: # No example batch was found, so get one from the `.train` dataset result = next(iter(self.train)) # And cache...
[ "def", "example", "(", "self", ")", ":", "result", "=", "getattr", "(", "self", ",", "'_example'", ",", "None", ")", "if", "result", "is", "None", ":", "# No example batch was found, so get one from the `.train` dataset", "result", "=", "next", "(", "iter", "(",...
[ 162, 4 ]
[ 170, 21 ]
python
en
['en', 'en', 'en']
True
BaseXLearner.__init__
(self, learner=None, control_outcome_learner=None, treatment_outcome_learner=None, control_effect_learner=None, treatment_effect_learner=None, ate_alpha=.05, control_name=0)
Initialize a X-learner. Args: learner (optional): a model to estimate outcomes and treatment effects in both the control and treatment groups control_outcome_learner (optional): a model to estimate outcomes in the control group treatment_outcome_learner (opti...
Initialize a X-learner.
def __init__(self, learner=None, control_outcome_learner=None, treatment_outcome_learner=None, control_effect_learner=None, treatment_effect_learner=None, ate_alpha=.05, control_name=0): """Ini...
[ "def", "__init__", "(", "self", ",", "learner", "=", "None", ",", "control_outcome_learner", "=", "None", ",", "treatment_outcome_learner", "=", "None", ",", "control_effect_learner", "=", "None", ",", "treatment_effect_learner", "=", "None", ",", "ate_alpha", "="...
[ 24, 4 ]
[ 73, 36 ]
python
en
['en', 'en', 'it']
True
BaseXLearner.fit
(self, X, treatment, y, p=None)
Fit the inference model. Args: X (np.matrix or np.array or pd.Dataframe): a feature matrix treatment (np.array or pd.Series): a treatment vector y (np.array or pd.Series): an outcome vector p (np.ndarray or pd.Series or dict, optional): an array of propensity sco...
Fit the inference model.
def fit(self, X, treatment, y, p=None): """Fit the inference model. Args: X (np.matrix or np.array or pd.Dataframe): a feature matrix treatment (np.array or pd.Series): a treatment vector y (np.array or pd.Series): an outcome vector p (np.ndarray or pd.Se...
[ "def", "fit", "(", "self", ",", "X", ",", "treatment", ",", "y", ",", "p", "=", "None", ")", ":", "X", ",", "treatment", ",", "y", "=", "convert_pd_to_np", "(", "X", ",", "treatment", ",", "y", ")", "check_treatment_vector", "(", "treatment", ",", ...
[ 85, 4 ]
[ 136, 61 ]
python
en
['en', 'en', 'en']
True
BaseXLearner.predict
(self, X, treatment=None, y=None, p=None, return_components=False, verbose=True)
Predict treatment effects. Args: X (np.matrix or np.array or pd.Dataframe): a feature matrix treatment (np.array or pd.Series, optional): a treatment vector y (np.array or pd.Series, optional): an outcome vector p (np.ndarray or pd.Series or dict, optional): an a...
Predict treatment effects.
def predict(self, X, treatment=None, y=None, p=None, return_components=False, verbose=True): """Predict treatment effects. Args: X (np.matrix or np.array or pd.Dataframe): a feature matrix treatment (np.array or pd.Series, optional): a treatment vector ...
[ "def", "predict", "(", "self", ",", "X", ",", "treatment", "=", "None", ",", "y", "=", "None", ",", "p", "=", "None", ",", "return_components", "=", "False", ",", "verbose", "=", "True", ")", ":", "X", ",", "treatment", ",", "y", "=", "convert_pd_t...
[ 138, 4 ]
[ 195, 39 ]
python
en
['fr', 'en', 'en']
True
BaseXLearner.fit_predict
(self, X, treatment, y, p=None, return_ci=False, n_bootstraps=1000, bootstrap_size=10000, return_components=False, verbose=True)
Fit the treatment effect and outcome models of the R learner and predict treatment effects. Args: X (np.matrix or np.array or pd.Dataframe): a feature matrix treatment (np.array or pd.Series): a treatment vector y (np.array or pd.Series): an outcome vector p (np....
Fit the treatment effect and outcome models of the R learner and predict treatment effects.
def fit_predict(self, X, treatment, y, p=None, return_ci=False, n_bootstraps=1000, bootstrap_size=10000, return_components=False, verbose=True): """Fit the treatment effect and outcome models of the R learner and predict treatment effects. Args: X (np.matrix or np.array ...
[ "def", "fit_predict", "(", "self", ",", "X", ",", "treatment", ",", "y", ",", "p", "=", "None", ",", "return_ci", "=", "False", ",", "n_bootstraps", "=", "1000", ",", "bootstrap_size", "=", "10000", ",", "return_components", "=", "False", ",", "verbose",...
[ 197, 4 ]
[ 255, 43 ]
python
en
['en', 'en', 'en']
True
BaseXLearner.estimate_ate
(self, X, treatment, y, p=None, bootstrap_ci=False, n_bootstraps=1000, bootstrap_size=10000)
Estimate the Average Treatment Effect (ATE). Args: X (np.matrix or np.array or pd.Dataframe): a feature matrix treatment (np.array or pd.Series): a treatment vector y (np.array or pd.Series): an outcome vector p (np.ndarray or pd.Series or dict, optional): an arr...
Estimate the Average Treatment Effect (ATE).
def estimate_ate(self, X, treatment, y, p=None, bootstrap_ci=False, n_bootstraps=1000, bootstrap_size=10000): """Estimate the Average Treatment Effect (ATE). Args: X (np.matrix or np.array or pd.Dataframe): a feature matrix treatment (np.array or pd.Series): a treatment vector ...
[ "def", "estimate_ate", "(", "self", ",", "X", ",", "treatment", ",", "y", ",", "p", "=", "None", ",", "bootstrap_ci", "=", "False", ",", "n_bootstraps", "=", "1000", ",", "bootstrap_size", "=", "10000", ")", ":", "te", ",", "dhat_cs", ",", "dhat_ts", ...
[ 257, 4 ]
[ 338, 44 ]
python
en
['en', 'it', 'en']
True
BaseXRegressor.__init__
(self, learner=None, control_outcome_learner=None, treatment_outcome_learner=None, control_effect_learner=None, treatment_effect_learner=None, ate_alpha=.05, control_name=0)
Initialize an X-learner regressor. Args: learner (optional): a model to estimate outcomes and treatment effects in both the control and treatment groups control_outcome_learner (optional): a model to estimate outcomes in the control group treatment_outcome_le...
Initialize an X-learner regressor.
def __init__(self, learner=None, control_outcome_learner=None, treatment_outcome_learner=None, control_effect_learner=None, treatment_effect_learner=None, ate_alpha=.05, control_name=0): """Ini...
[ "def", "__init__", "(", "self", ",", "learner", "=", "None", ",", "control_outcome_learner", "=", "None", ",", "treatment_outcome_learner", "=", "None", ",", "control_effect_learner", "=", "None", ",", "treatment_effect_learner", "=", "None", ",", "ate_alpha", "="...
[ 346, 4 ]
[ 373, 38 ]
python
en
['en', 'fy', 'nl']
False
BaseXClassifier.__init__
(self, outcome_learner=None, effect_learner=None, control_outcome_learner=None, treatment_outcome_learner=None, control_effect_learner=None, treatment_effect_learner=None, ate_alpha=.05, ...
Initialize an X-learner classifier. Args: outcome_learner (optional): a model to estimate outcomes in both the control and treatment groups. Should be a classifier. effect_learner (optional): a model to estimate treatment effects in both the control and treatment groups....
Initialize an X-learner classifier.
def __init__(self, outcome_learner=None, effect_learner=None, control_outcome_learner=None, treatment_outcome_learner=None, control_effect_learner=None, treatment_effect_learner=None, ate_alpha=.05, ...
[ "def", "__init__", "(", "self", ",", "outcome_learner", "=", "None", ",", "effect_learner", "=", "None", ",", "control_outcome_learner", "=", "None", ",", "treatment_outcome_learner", "=", "None", ",", "control_effect_learner", "=", "None", ",", "treatment_effect_le...
[ 381, 4 ]
[ 426, 104 ]
python
en
['en', 'fy', 'nl']
False
BaseXClassifier.fit
(self, X, treatment, y, p=None)
Fit the inference model. Args: X (np.matrix or np.array or pd.Dataframe): a feature matrix treatment (np.array or pd.Series): a treatment vector y (np.array or pd.Series): an outcome vector p (np.ndarray or pd.Series or dict, optional): an array of propensity sco...
Fit the inference model.
def fit(self, X, treatment, y, p=None): """Fit the inference model. Args: X (np.matrix or np.array or pd.Dataframe): a feature matrix treatment (np.array or pd.Series): a treatment vector y (np.array or pd.Series): an outcome vector p (np.ndarray or pd.Se...
[ "def", "fit", "(", "self", ",", "X", ",", "treatment", ",", "y", ",", "p", "=", "None", ")", ":", "X", ",", "treatment", ",", "y", "=", "convert_pd_to_np", "(", "X", ",", "treatment", ",", "y", ")", "check_treatment_vector", "(", "treatment", ",", ...
[ 428, 4 ]
[ 479, 61 ]
python
en
['en', 'en', 'en']
True
BaseXClassifier.predict
(self, X, treatment=None, y=None, p=None, return_components=False, verbose=True)
Predict treatment effects. Args: X (np.matrix or np.array or pd.Dataframe): a feature matrix treatment (np.array or pd.Series, optional): a treatment vector y (np.array or pd.Series, optional): an outcome vector p (np.ndarray or pd.Series or dict, optional): an a...
Predict treatment effects.
def predict(self, X, treatment=None, y=None, p=None, return_components=False, verbose=True): """Predict treatment effects. Args: X (np.matrix or np.array or pd.Dataframe): a feature matrix treatment (np.array or pd.Series, optional): a treatment vector ...
[ "def", "predict", "(", "self", ",", "X", ",", "treatment", "=", "None", ",", "y", "=", "None", ",", "p", "=", "None", ",", "return_components", "=", "False", ",", "verbose", "=", "True", ")", ":", "X", ",", "treatment", ",", "y", "=", "convert_pd_t...
[ 481, 4 ]
[ 539, 39 ]
python
en
['fr', 'en', 'en']
True
test_ValidationsStore_with_TupleS3StoreBackend
()
What does this test and why? A Store should be able to report it's store_backend_id which is set when the StoreBackend is instantiated.
What does this test and why? A Store should be able to report it's store_backend_id which is set when the StoreBackend is instantiated.
def test_ValidationsStore_with_TupleS3StoreBackend(): bucket = "test_validation_store_bucket" prefix = "test/prefix" # create a bucket in Moto's mock AWS environment conn = boto3.resource("s3", region_name="us-east-1") conn.create_bucket(Bucket=bucket) # First, demonstrate that we pick up defa...
[ "def", "test_ValidationsStore_with_TupleS3StoreBackend", "(", ")", ":", "bucket", "=", "\"test_validation_store_bucket\"", "prefix", "=", "\"test/prefix\"", "# create a bucket in Moto's mock AWS environment", "conn", "=", "boto3", ".", "resource", "(", "\"s3\"", ",", "region_...
[ 22, 0 ]
[ 93, 63 ]
python
en
['en', 'error', 'th']
False
test_ValidationsStore_with_InMemoryStoreBackend
()
What does this test and why? A Store should be able to report it's store_backend_id which is set when the StoreBackend is instantiated.
What does this test and why? A Store should be able to report it's store_backend_id which is set when the StoreBackend is instantiated.
def test_ValidationsStore_with_InMemoryStoreBackend(): my_store = ValidationsStore( store_backend={ "module_name": "great_expectations.data_context.store", "class_name": "InMemoryStoreBackend", } ) with pytest.raises(TypeError): my_store.get("not_a_Validation...
[ "def", "test_ValidationsStore_with_InMemoryStoreBackend", "(", ")", ":", "my_store", "=", "ValidationsStore", "(", "store_backend", "=", "{", "\"module_name\"", ":", "\"great_expectations.data_context.store\"", ",", "\"class_name\"", ":", "\"InMemoryStoreBackend\"", ",", "}",...
[ 97, 0 ]
[ 149, 63 ]
python
en
['en', 'error', 'th']
False
test_ValidationsStore_with_TupleFileSystemStoreBackend
(tmp_path_factory)
What does this test and why? A Store should be able to report it's store_backend_id which is set when the StoreBackend is instantiated.
What does this test and why? A Store should be able to report it's store_backend_id which is set when the StoreBackend is instantiated.
def test_ValidationsStore_with_TupleFileSystemStoreBackend(tmp_path_factory): path = str( tmp_path_factory.mktemp( "test_ValidationResultStore_with_TupleFileSystemStoreBackend__dir" ) ) project_path = str(tmp_path_factory.mktemp("my_dir")) my_store = ValidationsStore( ...
[ "def", "test_ValidationsStore_with_TupleFileSystemStoreBackend", "(", "tmp_path_factory", ")", ":", "path", "=", "str", "(", "tmp_path_factory", ".", "mktemp", "(", "\"test_ValidationResultStore_with_TupleFileSystemStoreBackend__dir\"", ")", ")", "project_path", "=", "str", "...
[ 153, 0 ]
[ 240, 75 ]
python
en
['en', 'error', 'th']
False
test_ValidationsStore_with_DatabaseStoreBackend
(sa)
What does this test and why? A Store should be able to report it's store_backend_id which is set when the StoreBackend is instantiated.
What does this test and why? A Store should be able to report it's store_backend_id which is set when the StoreBackend is instantiated.
def test_ValidationsStore_with_DatabaseStoreBackend(sa): # Use sqlite so we don't require postgres for this test. connection_kwargs = {"drivername": "sqlite"} # First, demonstrate that we pick up default configuration my_store = ValidationsStore( store_backend={ "class_name": "Datab...
[ "def", "test_ValidationsStore_with_DatabaseStoreBackend", "(", "sa", ")", ":", "# Use sqlite so we don't require postgres for this test.", "connection_kwargs", "=", "{", "\"drivername\"", ":", "\"sqlite\"", "}", "# First, demonstrate that we pick up default configuration", "my_store", ...
[ 243, 0 ]
[ 296, 63 ]
python
en
['en', 'error', 'th']
False
test_existing_local_data_docs_urls_returns_url_on_project_with_no_datasources_and_a_site_configured
( tmp_path_factory, )
This test ensures that a url will be returned for a default site even if a datasource is not configured, and docs are not built.
This test ensures that a url will be returned for a default site even if a datasource is not configured, and docs are not built.
def test_existing_local_data_docs_urls_returns_url_on_project_with_no_datasources_and_a_site_configured( tmp_path_factory, ): """ This test ensures that a url will be returned for a default site even if a datasource is not configured, and docs are not built. """ empty_directory = str(tmp_path_fa...
[ "def", "test_existing_local_data_docs_urls_returns_url_on_project_with_no_datasources_and_a_site_configured", "(", "tmp_path_factory", ",", ")", ":", "empty_directory", "=", "str", "(", "tmp_path_factory", ".", "mktemp", "(", "\"another_empty_project\"", ")", ")", "DataContext", ...
[ 265, 0 ]
[ 280, 5 ]
python
en
['en', 'error', 'th']
False
LoadEdges
(filename, targets)
Load the edges map from the dump file, and filter it to only show targets in |targets| and their depedendents.
Load the edges map from the dump file, and filter it to only show targets in |targets| and their depedendents.
def LoadEdges(filename, targets): """Load the edges map from the dump file, and filter it to only show targets in |targets| and their depedendents.""" file = open('dump.json') edges = json.load(file) file.close() # Copy out only the edges we're interested in from the full edge list. target_edges = {} ...
[ "def", "LoadEdges", "(", "filename", ",", "targets", ")", ":", "file", "=", "open", "(", "'dump.json'", ")", "edges", "=", "json", ".", "load", "(", "file", ")", "file", ".", "close", "(", ")", "# Copy out only the edges we're interested in from the full edge li...
[ 21, 0 ]
[ 39, 21 ]
python
en
['en', 'en', 'en']
True
WriteGraph
(edges)
Print a graphviz graph to stdout. |edges| is a map of target to a list of other targets it depends on.
Print a graphviz graph to stdout. |edges| is a map of target to a list of other targets it depends on.
def WriteGraph(edges): """Print a graphviz graph to stdout. |edges| is a map of target to a list of other targets it depends on.""" # Bucket targets by file. files = collections.defaultdict(list) for src, dst in edges.items(): build_file, target_name, toolset = ParseTarget(src) files[build_file].appe...
[ "def", "WriteGraph", "(", "edges", ")", ":", "# Bucket targets by file.", "files", "=", "collections", ".", "defaultdict", "(", "list", ")", "for", "src", ",", "dst", "in", "edges", ".", "items", "(", ")", ":", "build_file", ",", "target_name", ",", "tools...
[ 42, 0 ]
[ 82, 11 ]
python
en
['en', 'ht', 'it']
False
execute_shell_command
(command: str)
Execute a shell (bash in the present case) command from inside Python program. While developed independently, this function is very similar to the one, offered in this StackOverflow article: https://stackoverflow.com/questions/30993411/environment-variables-using-subprocess-check-output-python :param...
Execute a shell (bash in the present case) command from inside Python program.
def execute_shell_command(command: str) -> int: """ Execute a shell (bash in the present case) command from inside Python program. While developed independently, this function is very similar to the one, offered in this StackOverflow article: https://stackoverflow.com/questions/30993411/environment-var...
[ "def", "execute_shell_command", "(", "command", ":", "str", ")", "->", "int", ":", "cwd", ":", "str", "=", "os", ".", "getcwd", "(", ")", "path_env_var", ":", "str", "=", "os", ".", "pathsep", ".", "join", "(", "[", "os", ".", "environ", ".", "get"...
[ 12, 0 ]
[ 59, 22 ]
python
en
['en', 'error', 'th']
False
execute_shell_command_with_progress_polling
(command: str)
Execute a shell (bash in the present case) command from inside Python program with polling (to enable progress bar). :param command: bash command -- as if typed in a shell/Terminal window :return: status code -- 0 if successful; all other values (1 is the most common) indicate an error
Execute a shell (bash in the present case) command from inside Python program with polling (to enable progress bar).
def execute_shell_command_with_progress_polling(command: str) -> int: """ Execute a shell (bash in the present case) command from inside Python program with polling (to enable progress bar). :param command: bash command -- as if typed in a shell/Terminal window :return: status code -- 0 if successful; ...
[ "def", "execute_shell_command_with_progress_polling", "(", "command", ":", "str", ")", "->", "int", ":", "cwd", ":", "str", "=", "os", ".", "getcwd", "(", ")", "path_env_var", ":", "str", "=", "os", ".", "pathsep", ".", "join", "(", "[", "os", ".", "en...
[ 62, 0 ]
[ 143, 22 ]
python
en
['en', 'error', 'th']
False
DependencyGraph.traverse
(self)
Returns the items in this graph in topological order.
Returns the items in this graph in topological order.
def traverse(self) -> Iterator[Any]: """ Returns the items in this graph in topological order. """ if len(self.vertices) == 0: return # This method implements Kahn's algorithm. See # https://en.wikipedia.org/wiki/Topological_sorting#Kahn's_algorithm for ...
[ "def", "traverse", "(", "self", ")", "->", "Iterator", "[", "Any", "]", ":", "if", "len", "(", "self", ".", "vertices", ")", "==", "0", ":", "return", "# This method implements Kahn's algorithm. See", "# https://en.wikipedia.org/wiki/Topological_sorting#Kahn's_algorithm...
[ 121, 4 ]
[ 153, 96 ]
python
en
['en', 'error', 'th']
False
get_synthetic_preds
(synthetic_data_func, n=1000, estimators={})
Generate predictions for synthetic data using specified function (single simulation) Args: synthetic_data_func (function): synthetic data generation function n (int, optional): number of samples estimators (dict of object): dict of names and objects of treatment effect estimators Retur...
Generate predictions for synthetic data using specified function (single simulation)
def get_synthetic_preds(synthetic_data_func, n=1000, estimators={}): """Generate predictions for synthetic data using specified function (single simulation) Args: synthetic_data_func (function): synthetic data generation function n (int, optional): number of samples estimators (dict of ...
[ "def", "get_synthetic_preds", "(", "synthetic_data_func", ",", "n", "=", "1000", ",", "estimators", "=", "{", "}", ")", ":", "y", ",", "X", ",", "w", ",", "tau", ",", "b", ",", "e", "=", "synthetic_data_func", "(", "n", "=", "n", ")", "preds_dict", ...
[ 29, 0 ]
[ 70, 21 ]
python
en
['en', 'en', 'en']
True
get_synthetic_summary
(synthetic_data_func, n=1000, k=1, estimators={})
Generate a summary for predictions on synthetic data using specified function Args: synthetic_data_func (function): synthetic data generation function n (int, optional): number of samples per simulation k (int, optional): number of simulations
Generate a summary for predictions on synthetic data using specified function
def get_synthetic_summary(synthetic_data_func, n=1000, k=1, estimators={}): """Generate a summary for predictions on synthetic data using specified function Args: synthetic_data_func (function): synthetic data generation function n (int, optional): number of samples per simulation k (in...
[ "def", "get_synthetic_summary", "(", "synthetic_data_func", ",", "n", "=", "1000", ",", "k", "=", "1", ",", "estimators", "=", "{", "}", ")", ":", "summaries", "=", "[", "]", "for", "i", "in", "range", "(", "k", ")", ":", "synthetic_preds", "=", "get...
[ 73, 0 ]
[ 110, 66 ]
python
en
['en', 'en', 'en']
True
scatter_plot_summary
(synthetic_summary, k, drop_learners=[], drop_cols=[])
Generates a scatter plot comparing learner performance. Each learner's performance is plotted as a point in the (Abs % Error of ATE, MSE) space. Args: synthetic_summary (pd.DataFrame): summary generated by get_synthetic_summary() k (int): number of simulations (used only for plot title text) ...
Generates a scatter plot comparing learner performance. Each learner's performance is plotted as a point in the (Abs % Error of ATE, MSE) space.
def scatter_plot_summary(synthetic_summary, k, drop_learners=[], drop_cols=[]): """Generates a scatter plot comparing learner performance. Each learner's performance is plotted as a point in the (Abs % Error of ATE, MSE) space. Args: synthetic_summary (pd.DataFrame): summary generated by get_synthe...
[ "def", "scatter_plot_summary", "(", "synthetic_summary", ",", "k", ",", "drop_learners", "=", "[", "]", ",", "drop_cols", "=", "[", "]", ")", ":", "plot_data", "=", "synthetic_summary", ".", "drop", "(", "drop_learners", ")", ".", "drop", "(", "drop_cols", ...
[ 113, 0 ]
[ 140, 82 ]
python
en
['en', 'en', 'en']
True
bar_plot_summary
(synthetic_summary, k, drop_learners=[], drop_cols=[], sort_cols=['MSE', 'Abs % Error of ATE'])
Generates a bar plot comparing learner performance. Args: synthetic_summary (pd.DataFrame): summary generated by get_synthetic_summary() k (int): number of simulations (used only for plot title text) drop_learners (list, optional): list of learners (str) to omit when plotting drop_c...
Generates a bar plot comparing learner performance.
def bar_plot_summary(synthetic_summary, k, drop_learners=[], drop_cols=[], sort_cols=['MSE', 'Abs % Error of ATE']): """Generates a bar plot comparing learner performance. Args: synthetic_summary (pd.DataFrame): summary generated by get_synthetic_summary() k (int): number of simulations (used o...
[ "def", "bar_plot_summary", "(", "synthetic_summary", ",", "k", ",", "drop_learners", "=", "[", "]", ",", "drop_cols", "=", "[", "]", ",", "sort_cols", "=", "[", "'MSE'", ",", "'Abs % Error of ATE'", "]", ")", ":", "plot_data", "=", "synthetic_summary", ".", ...
[ 143, 0 ]
[ 158, 79 ]
python
en
['en', 'en', 'en']
True
distr_plot_single_sim
(synthetic_preds, kind='kde', drop_learners=[], bins=50, histtype='step', alpha=1, linewidth=1, bw_method=1)
Plots the distribution of each learner's predictions (for a single simulation). Kernel Density Estimation (kde) and actual histogram plots supported. Args: synthetic_preds (dict): dictionary of predictions generated by get_synthetic_preds() kind (str, optional): 'kde' or 'hist' drop_lea...
Plots the distribution of each learner's predictions (for a single simulation). Kernel Density Estimation (kde) and actual histogram plots supported.
def distr_plot_single_sim(synthetic_preds, kind='kde', drop_learners=[], bins=50, histtype='step', alpha=1, linewidth=1, bw_method=1): """Plots the distribution of each learner's predictions (for a single simulation). Kernel Density Estimation (kde) and actual histogram plots supported. Args...
[ "def", "distr_plot_single_sim", "(", "synthetic_preds", ",", "kind", "=", "'kde'", ",", "drop_learners", "=", "[", "]", ",", "bins", "=", "50", ",", "histtype", "=", "'step'", ",", "alpha", "=", "1", ",", "linewidth", "=", "1", ",", "bw_method", "=", "...
[ 161, 0 ]
[ 202, 54 ]
python
en
['en', 'en', 'en']
True
scatter_plot_single_sim
(synthetic_preds)
Creates a grid of scatter plots comparing each learner's predictions with the truth (for a single simulation). Args: synthetic_preds (dict): dictionary of predictions generated by get_synthetic_preds() or get_synthetic_preds_holdout()
Creates a grid of scatter plots comparing each learner's predictions with the truth (for a single simulation).
def scatter_plot_single_sim(synthetic_preds): """Creates a grid of scatter plots comparing each learner's predictions with the truth (for a single simulation). Args: synthetic_preds (dict): dictionary of predictions generated by get_synthetic_preds() or get_synthetic_preds_holdout() """...
[ "def", "scatter_plot_single_sim", "(", "synthetic_preds", ")", ":", "preds_for_plot", "=", "synthetic_preds", ".", "copy", "(", ")", "# deleted generated data and get actual column name", "del", "preds_for_plot", "[", "KEY_GENERATED_DATA", "]", "n_row", "=", "int", "(", ...
[ 205, 0 ]
[ 229, 48 ]
python
en
['en', 'en', 'en']
True
get_synthetic_preds_holdout
(synthetic_data_func, n=1000, valid_size=0.2, estimators={})
Generate predictions for synthetic data using specified function (single simulation) for train and holdout Args: synthetic_data_func (function): synthetic data generation function n (int, optional): number of samples valid_size(float,optional): validaiton/hold out data size estimato...
Generate predictions for synthetic data using specified function (single simulation) for train and holdout
def get_synthetic_preds_holdout(synthetic_data_func, n=1000, valid_size=0.2, estimators={}): """Generate predictions for synthetic data using specified function (single simulation) for train and holdout Args: synthetic_data_func (function): synthetic data generation func...
[ "def", "get_synthetic_preds_holdout", "(", "synthetic_data_func", ",", "n", "=", "1000", ",", "valid_size", "=", "0.2", ",", "estimators", "=", "{", "}", ")", ":", "y", ",", "X", ",", "w", ",", "tau", ",", "b", ",", "e", "=", "synthetic_data_func", "("...
[ 232, 0 ]
[ 305, 45 ]
python
en
['en', 'en', 'en']
True
get_synthetic_summary_holdout
(synthetic_data_func, n=1000, valid_size=0.2, k=1)
Generate a summary for predictions on synthetic data for train and holdout using specified function Args: synthetic_data_func (function): synthetic data generation function n (int, optional): number of samples per simulation valid_size(float,optional): validation/hold out data size ...
Generate a summary for predictions on synthetic data for train and holdout using specified function
def get_synthetic_summary_holdout(synthetic_data_func, n=1000, valid_size=0.2, k=1): """Generate a summary for predictions on synthetic data for train and holdout using specified function Args: synthetic_data_func (function): synthetic data generation function n (int, optional): number of sampl...
[ "def", "get_synthetic_summary_holdout", "(", "synthetic_data_func", ",", "n", "=", "1000", ",", "valid_size", "=", "0.2", ",", "k", "=", "1", ")", ":", "summaries_train", "=", "[", "]", "summaries_validation", "=", "[", "]", "for", "i", "in", "range", "(",...
[ 308, 0 ]
[ 383, 79 ]
python
en
['en', 'en', 'en']
True
scatter_plot_summary_holdout
(train_summary, validation_summary, k, label=['Train', 'Validation'], drop_learners=[], drop_cols=[])
Generates a scatter plot comparing learner performance by training and validation. Args: train_summary (pd.DataFrame): summary for training synthetic data generated by get_synthetic_summary_holdout() validation_summary (pd.DataFrame): summary for validation synthetic data generated by g...
Generates a scatter plot comparing learner performance by training and validation.
def scatter_plot_summary_holdout(train_summary, validation_summary, k, label=['Train', 'Validation'], drop_learners=[], drop_cols=[]): """Generates a scatter plot comparing learner performance by training and validation. Args: train_summary (pd.DataFrame): summary for t...
[ "def", "scatter_plot_summary_holdout", "(", "train_summary", ",", "validation_summary", ",", "k", ",", "label", "=", "[", "'Train'", ",", "'Validation'", "]", ",", "drop_learners", "=", "[", "]", ",", "drop_cols", "=", "[", "]", ")", ":", "train_summary", "=...
[ 386, 0 ]
[ 424, 14 ]
python
en
['en', 'en', 'en']
True
bar_plot_summary_holdout
(train_summary, validation_summary, k, drop_learners=[], drop_cols=[])
Generates a bar plot comparing learner performance by training and validation Args: train_summary (pd.DataFrame): summary for training synthetic data generated by get_synthetic_summary_holdout() validation_summary (pd.DataFrame): summary for validation synthetic data generated by get_sy...
Generates a bar plot comparing learner performance by training and validation
def bar_plot_summary_holdout(train_summary, validation_summary, k, drop_learners=[], drop_cols=[]): """Generates a bar plot comparing learner performance by training and validation Args: train_summary (pd.DataFrame): summary for training synthetic data generated by get_synthetic_summary_holdout() ...
[ "def", "bar_plot_summary_holdout", "(", "train_summary", ",", "validation_summary", ",", "k", ",", "drop_learners", "=", "[", "]", ",", "drop_cols", "=", "[", "]", ")", ":", "train_summary", "=", "train_summary", ".", "drop", "(", "[", "KEY_ACTUAL", "]", ")"...
[ 427, 0 ]
[ 454, 97 ]
python
en
['en', 'en', 'en']
True
get_synthetic_auuc
(synthetic_preds, drop_learners=[], outcome_col='y', treatment_col='w', treatment_effect_col='tau', plot=True)
Get auuc values for cumulative gains of model estimates in quantiles. For details, reference get_cumgain() and plot_gain() Args: synthetic_preds (dict): dictionary of predictions generated by get_synthetic_preds() or get_synthetic_preds_holdout() outcome_col (str, optional): the column ...
Get auuc values for cumulative gains of model estimates in quantiles.
def get_synthetic_auuc(synthetic_preds, drop_learners=[], outcome_col='y', treatment_col='w', treatment_effect_col='tau', plot=True): """Get auuc values for cumulative gains of model estimates in quantiles. For details, reference get_cumgain() and plot_gain() Args: synthetic_...
[ "def", "get_synthetic_auuc", "(", "synthetic_preds", ",", "drop_learners", "=", "[", "]", ",", "outcome_col", "=", "'y'", ",", "treatment_col", "=", "'w'", ",", "treatment_effect_col", "=", "'tau'", ",", "plot", "=", "True", ")", ":", "synthetic_preds_df", "="...
[ 457, 0 ]
[ 498, 18 ]
python
en
['en', 'la', 'en']
True
generate_key
(dict_data, daily=True)
generate key from a dictionary
generate key from a dictionary
def generate_key(dict_data, daily=True): """generate key from a dictionary""" cache_dict = copy.copy(dict_data) json_data = json.dumps(cache_dict) return hashlib.md5(json_data.encode('utf-8')).hexdigest()
[ "def", "generate_key", "(", "dict_data", ",", "daily", "=", "True", ")", ":", "cache_dict", "=", "copy", ".", "copy", "(", "dict_data", ")", "json_data", "=", "json", ".", "dumps", "(", "cache_dict", ")", "return", "hashlib", ".", "md5", "(", "json_data"...
[ 48, 0 ]
[ 52, 61 ]
python
en
['en', 'en', 'en']
True
parse_location
(ip)
country_code = Column(String(10)) country_name = Column(String(10)) city = Column(String(10)) latitude = Column(Float) longitude = Column(Float)
country_code = Column(String(10)) country_name = Column(String(10)) city = Column(String(10)) latitude = Column(Float) longitude = Column(Float)
def parse_location(ip): data = {} """ country_code = Column(String(10)) country_name = Column(String(10)) city = Column(String(10)) latitude = Column(Float) longitude = Column(Float)""" keys = ["country_code", "country_name", "city", "latitude", "longitude"] try: url = f"...
[ "def", "parse_location", "(", "ip", ")", ":", "data", "=", "{", "}", "keys", "=", "[", "\"country_code\"", ",", "\"country_name\"", ",", "\"city\"", ",", "\"latitude\"", ",", "\"longitude\"", "]", "try", ":", "url", "=", "f\"https://geolocation-db.com/json/{ip}&...
[ 109, 0 ]
[ 127, 19 ]
python
en
['en', 'error', 'th']
False
isprime
(n)
check if integer n is a prime
check if integer n is a prime
def isprime(n): # https://stackoverflow.com/questions/18833759/python-prime-number-checker """check if integer n is a prime""" # make sure n is a positive integer n = abs(int(n)) # 0 and 1 are not primes if n < 2: return False # 2 is the only even prime number if n == 2: ...
[ "def", "isprime", "(", "n", ")", ":", "# https://stackoverflow.com/questions/18833759/python-prime-number-checker", "# make sure n is a positive integer", "n", "=", "abs", "(", "int", "(", "n", ")", ")", "# 0 and 1 are not primes", "if", "n", "<", "2", ":", "return", ...
[ 35, 0 ]
[ 60, 15 ]
python
en
['en', 'en', 'en']
True
TestIO.test_read_parquet
(self)
This test is unusual, because on travis (but only on travis), we have observed problems importing pyarrow, which breaks this test (since it requires pyarrow available). The issue seems to be related to a binary compatibility issue with the installed/available version of numpy: pyarrow ...
This test is unusual, because on travis (but only on travis), we have observed problems importing pyarrow, which breaks this test (since it requires pyarrow available).
def test_read_parquet(self): """ This test is unusual, because on travis (but only on travis), we have observed problems importing pyarrow, which breaks this test (since it requires pyarrow available). The issue seems to be related to a binary compatibility issue with the installed/avai...
[ "def", "test_read_parquet", "(", "self", ")", ":", "# Pass this test if the available version of pandas is less than 0.21.0, because prior", "# versions of pandas did not include the read_parquet function.", "pandas_version", "=", "re", ".", "match", "(", "r\"(\\d+)\\.(\\d+)\\..+\"", "...
[ 1067, 4 ]
[ 1092, 44 ]
python
en
['en', 'error', 'th']
False
PerfCost._run_configuration
( self, run_type: "PerfCost.RunType", settings: dict, invocations: int, repetitions: int, suffix: str = "", )
Cold experiment: schedule all invocations in parallel.
Cold experiment: schedule all invocations in parallel.
def _run_configuration( self, run_type: "PerfCost.RunType", settings: dict, invocations: int, repetitions: int, suffix: str = "", ): # Randomize starting value to ensure that it's not the same # as in the previous run. # Otherwise we could not...
[ "def", "_run_configuration", "(", "self", ",", "run_type", ":", "\"PerfCost.RunType\"", ",", "settings", ":", "dict", ",", "invocations", ":", "int", ",", "repetitions", ":", "int", ",", "suffix", ":", "str", "=", "\"\"", ",", ")", ":", "# Randomize starting...
[ 111, 4 ]
[ 229, 17 ]
python
en
['en', 'error', 'th']
False
UserSerializer.create
(self, validted_data)
Create a new user with encrypted password and return it
Create a new user with encrypted password and return it
def create(self, validted_data): """Create a new user with encrypted password and return it""" return get_user_model().objects.create_user(**validted_data)
[ "def", "create", "(", "self", ",", "validted_data", ")", ":", "return", "get_user_model", "(", ")", ".", "objects", ".", "create_user", "(", "*", "*", "validted_data", ")" ]
[ 13, 4 ]
[ 15, 68 ]
python
en
['en', 'en', 'en']
True
UserSerializer.update
(self, instance, validated_data)
Update a user, setting the password correctly and return it
Update a user, setting the password correctly and return it
def update(self, instance, validated_data): """Update a user, setting the password correctly and return it""" password = validated_data.pop('password', None) user = super().update(instance, validated_data) if password: user.set_password(password) user.save() ...
[ "def", "update", "(", "self", ",", "instance", ",", "validated_data", ")", ":", "password", "=", "validated_data", ".", "pop", "(", "'password'", ",", "None", ")", "user", "=", "super", "(", ")", ".", "update", "(", "instance", ",", "validated_data", ")"...
[ 17, 4 ]
[ 26, 19 ]
python
en
['en', 'en', 'en']
True
AuthTokenSerializer.validate
(self, attrs)
Validate and authenticate the user
Validate and authenticate the user
def validate(self, attrs): """Validate and authenticate the user""" email = attrs.get('email') password = attrs.get('password') user = authenticate( request=self.context.get('request'), username=email, password=password ) if not user: ...
[ "def", "validate", "(", "self", ",", "attrs", ")", ":", "email", "=", "attrs", ".", "get", "(", "'email'", ")", "password", "=", "attrs", ".", "get", "(", "'password'", ")", "user", "=", "authenticate", "(", "request", "=", "self", ".", "context", "....
[ 37, 4 ]
[ 52, 20 ]
python
en
['en', 'en', 'en']
True
CalculateGeneratorInputInfo
(params)
Calculate the generator specific info that gets fed to input (called by gyp).
Calculate the generator specific info that gets fed to input (called by gyp).
def CalculateGeneratorInputInfo(params): """Calculate the generator specific info that gets fed to input (called by gyp).""" generator_flags = params.get('generator_flags', {}) if generator_flags.get('adjust_static_libraries', False): global generator_wants_static_library_dependencies_adjusted generator...
[ "def", "CalculateGeneratorInputInfo", "(", "params", ")", ":", "generator_flags", "=", "params", ".", "get", "(", "'generator_flags'", ",", "{", "}", ")", "if", "generator_flags", ".", "get", "(", "'adjust_static_libraries'", ",", "False", ")", ":", "global", ...
[ 70, 0 ]
[ 76, 63 ]
python
en
['en', 'en', 'en']
True
GetAllIncludeDirectories
(target_list, target_dicts, shared_intermediate_dirs, config_name, params, compiler_path)
Calculate the set of include directories to be used. Returns: A list including all the include_dir's specified for every target followed by any include directories that were added as cflag compiler options.
Calculate the set of include directories to be used.
def GetAllIncludeDirectories(target_list, target_dicts, shared_intermediate_dirs, config_name, params, compiler_path): """Calculate the set of include directories to be used. Returns: A list including all the include_dir's specified for every target fol...
[ "def", "GetAllIncludeDirectories", "(", "target_list", ",", "target_dicts", ",", "shared_intermediate_dirs", ",", "config_name", ",", "params", ",", "compiler_path", ")", ":", "gyp_includes_set", "=", "set", "(", ")", "compiler_includes_list", "=", "[", "]", "# Find...
[ 79, 0 ]
[ 165, 26 ]
python
en
['en', 'en', 'en']
True
GetCompilerPath
(target_list, data, options)
Determine a command that can be used to invoke the compiler. Returns: If this is a gyp project that has explicit make settings, try to determine the compiler from that. Otherwise, see if a compiler was specified via the CC_target environment variable.
Determine a command that can be used to invoke the compiler.
def GetCompilerPath(target_list, data, options): """Determine a command that can be used to invoke the compiler. Returns: If this is a gyp project that has explicit make settings, try to determine the compiler from that. Otherwise, see if a compiler was specified via the CC_target environment variable...
[ "def", "GetCompilerPath", "(", "target_list", ",", "data", ",", "options", ")", ":", "# First, see if the compiler is configured in make's settings.", "build_file", ",", "_", ",", "_", "=", "gyp", ".", "common", ".", "ParseQualifiedTarget", "(", "target_list", "[", ...
[ 168, 0 ]
[ 189, 14 ]
python
en
['en', 'en', 'en']
True
GetAllDefines
(target_list, target_dicts, data, config_name, params, compiler_path)
Calculate the defines for a project. Returns: A dict that includes explict defines declared in gyp files along with all of the default defines that the compiler uses.
Calculate the defines for a project.
def GetAllDefines(target_list, target_dicts, data, config_name, params, compiler_path): """Calculate the defines for a project. Returns: A dict that includes explict defines declared in gyp files along with all of the default defines that the compiler uses. """ # Get defines declared...
[ "def", "GetAllDefines", "(", "target_list", ",", "target_dicts", ",", "data", ",", "config_name", ",", "params", ",", "compiler_path", ")", ":", "# Get defines declared in the gyp files.", "all_defines", "=", "{", "}", "flavor", "=", "gyp", ".", "common", ".", "...
[ 192, 0 ]
[ 248, 20 ]
python
en
['en', 'en', 'en']
True
WriteIncludePaths
(out, eclipse_langs, include_dirs)
Write the includes section of a CDT settings export file.
Write the includes section of a CDT settings export file.
def WriteIncludePaths(out, eclipse_langs, include_dirs): """Write the includes section of a CDT settings export file.""" out.write(' <section name="org.eclipse.cdt.internal.ui.wizards.' \ 'settingswizards.IncludePaths">\n') out.write(' <language name="holder for library settings"></language>\n') ...
[ "def", "WriteIncludePaths", "(", "out", ",", "eclipse_langs", ",", "include_dirs", ")", ":", "out", ".", "write", "(", "' <section name=\"org.eclipse.cdt.internal.ui.wizards.'", "'settingswizards.IncludePaths\">\\n'", ")", "out", ".", "write", "(", "' <language name=\"h...
[ 251, 0 ]
[ 263, 29 ]
python
en
['en', 'en', 'en']
True
WriteMacros
(out, eclipse_langs, defines)
Write the macros section of a CDT settings export file.
Write the macros section of a CDT settings export file.
def WriteMacros(out, eclipse_langs, defines): """Write the macros section of a CDT settings export file.""" out.write(' <section name="org.eclipse.cdt.internal.ui.wizards.' \ 'settingswizards.Macros">\n') out.write(' <language name="holder for library settings"></language>\n') for lang in eclip...
[ "def", "WriteMacros", "(", "out", ",", "eclipse_langs", ",", "defines", ")", ":", "out", ".", "write", "(", "' <section name=\"org.eclipse.cdt.internal.ui.wizards.'", "'settingswizards.Macros\">\\n'", ")", "out", ".", "write", "(", "' <language name=\"holder for library...
[ 266, 0 ]
[ 278, 29 ]
python
en
['en', 'en', 'en']
True
GenerateClasspathFile
(target_list, target_dicts, toplevel_dir, toplevel_build, out_name)
Generates a classpath file suitable for symbol navigation and code completion of Java code (such as in Android projects) by finding all .java and .jar files used as action inputs.
Generates a classpath file suitable for symbol navigation and code completion of Java code (such as in Android projects) by finding all .java and .jar files used as action inputs.
def GenerateClasspathFile(target_list, target_dicts, toplevel_dir, toplevel_build, out_name): '''Generates a classpath file suitable for symbol navigation and code completion of Java code (such as in Android projects) by finding all .java and .jar files used as action inputs.''' gyp.co...
[ "def", "GenerateClasspathFile", "(", "target_list", ",", "target_dicts", ",", "toplevel_dir", ",", "toplevel_build", ",", "out_name", ")", ":", "gyp", ".", "common", ".", "EnsureDirExists", "(", "out_name", ")", "result", "=", "ET", ".", "Element", "(", "'clas...
[ 336, 0 ]
[ 367, 40 ]
python
en
['en', 'en', 'en']
True
GetJavaJars
(target_list, target_dicts, toplevel_dir)
Generates a sequence of all .jars used as inputs.
Generates a sequence of all .jars used as inputs.
def GetJavaJars(target_list, target_dicts, toplevel_dir): '''Generates a sequence of all .jars used as inputs.''' for target_name in target_list: target = target_dicts[target_name] for action in target.get('actions', []): for input_ in action['inputs']: if os.path.splitext(input_)[1] == '.jar'...
[ "def", "GetJavaJars", "(", "target_list", ",", "target_dicts", ",", "toplevel_dir", ")", ":", "for", "target_name", "in", "target_list", ":", "target", "=", "target_dicts", "[", "target_name", "]", "for", "action", "in", "target", ".", "get", "(", "'actions'",...
[ 370, 0 ]
[ 380, 68 ]
python
en
['en', 'en', 'en']
True
GetJavaSourceDirs
(target_list, target_dicts, toplevel_dir)
Generates a sequence of all likely java package root directories.
Generates a sequence of all likely java package root directories.
def GetJavaSourceDirs(target_list, target_dicts, toplevel_dir): '''Generates a sequence of all likely java package root directories.''' for target_name in target_list: target = target_dicts[target_name] for action in target.get('actions', []): for input_ in action['inputs']: if (os.path.splite...
[ "def", "GetJavaSourceDirs", "(", "target_list", ",", "target_dicts", ",", "toplevel_dir", ")", ":", "for", "target_name", "in", "target_list", ":", "target", "=", "target_dicts", "[", "target_name", "]", "for", "action", "in", "target", ".", "get", "(", "'acti...
[ 383, 0 ]
[ 406, 31 ]
python
en
['en', 'en', 'en']
True
GenerateOutput
(target_list, target_dicts, data, params)
Generate an XML settings file that can be imported into a CDT project.
Generate an XML settings file that can be imported into a CDT project.
def GenerateOutput(target_list, target_dicts, data, params): """Generate an XML settings file that can be imported into a CDT project.""" if params['options'].generator_output: raise NotImplementedError("--generator_output not implemented for eclipse") user_config = params.get('generator_flags', {}).get('co...
[ "def", "GenerateOutput", "(", "target_list", ",", "target_dicts", ",", "data", ",", "params", ")", ":", "if", "params", "[", "'options'", "]", ".", "generator_output", ":", "raise", "NotImplementedError", "(", "\"--generator_output not implemented for eclipse\"", ")",...
[ 409, 0 ]
[ 423, 42 ]
python
en
['en', 'en', 'en']
True
Scanner.__init__
(self, text, flags=0)
:param text: The text which should be scanned :param flags: default regular expression flags
:param text: The text which should be scanned :param flags: default regular expression flags
def __init__(self, text, flags=0): """ :param text: The text which should be scanned :param flags: default regular expression flags """ self.data = text self.data_length = len(text) self.start_pos = 0 self.pos = 0 self.flags = flags se...
[ "def", "__init__", "(", "self", ",", "text", ",", "flags", "=", "0", ")", ":", "self", ".", "data", "=", "text", "self", ".", "data_length", "=", "len", "(", "text", ")", "self", ".", "start_pos", "=", "0", "self", ".", "pos", "=", "0", "self", ...
[ 35, 4 ]
[ 47, 27 ]
python
en
['en', 'error', 'th']
False
Scanner.eos
(self)
`True` if the scanner reached the end of text.
`True` if the scanner reached the end of text.
def eos(self): """`True` if the scanner reached the end of text.""" return self.pos >= self.data_length
[ "def", "eos", "(", "self", ")", ":", "return", "self", ".", "pos", ">=", "self", ".", "data_length" ]
[ 49, 4 ]
[ 51, 43 ]
python
en
['en', 'en', 'en']
True
Scanner.check
(self, pattern)
Apply `pattern` on the current position and return the match object. (Doesn't touch pos). Use this for lookahead.
Apply `pattern` on the current position and return the match object. (Doesn't touch pos). Use this for lookahead.
def check(self, pattern): """ Apply `pattern` on the current position and return the match object. (Doesn't touch pos). Use this for lookahead. """ if self.eos: raise EndOfText() if pattern not in self._re_cache: self._re_cache[pattern] = r...
[ "def", "check", "(", "self", ",", "pattern", ")", ":", "if", "self", ".", "eos", ":", "raise", "EndOfText", "(", ")", "if", "pattern", "not", "in", "self", ".", "_re_cache", ":", "self", ".", "_re_cache", "[", "pattern", "]", "=", "re", ".", "compi...
[ 54, 4 ]
[ 64, 65 ]
python
en
['en', 'error', 'th']
False
Scanner.test
(self, pattern)
Apply a pattern on the current position and check if it patches. Doesn't touch pos.
Apply a pattern on the current position and check if it patches. Doesn't touch pos.
def test(self, pattern): """Apply a pattern on the current position and check if it patches. Doesn't touch pos.""" return self.check(pattern) is not None
[ "def", "test", "(", "self", ",", "pattern", ")", ":", "return", "self", ".", "check", "(", "pattern", ")", "is", "not", "None" ]
[ 66, 4 ]
[ 69, 46 ]
python
en
['en', 'en', 'en']
True
Scanner.scan
(self, pattern)
Scan the text for the given pattern and update pos/match and related fields. The return value is a boolen that indicates if the pattern matched. The matched value is stored on the instance as ``match``, the last value is stored as ``last``. ``start_pos`` is the position of the ...
Scan the text for the given pattern and update pos/match and related fields. The return value is a boolen that indicates if the pattern matched. The matched value is stored on the instance as ``match``, the last value is stored as ``last``. ``start_pos`` is the position of the ...
def scan(self, pattern): """ Scan the text for the given pattern and update pos/match and related fields. The return value is a boolen that indicates if the pattern matched. The matched value is stored on the instance as ``match``, the last value is stored as ``last``. ``...
[ "def", "scan", "(", "self", ",", "pattern", ")", ":", "if", "self", ".", "eos", ":", "raise", "EndOfText", "(", ")", "if", "pattern", "not", "in", "self", ".", "_re_cache", ":", "self", ".", "_re_cache", "[", "pattern", "]", "=", "re", ".", "compil...
[ 71, 4 ]
[ 92, 19 ]
python
en
['en', 'error', 'th']
False
Scanner.get_char
(self)
Scan exactly one char.
Scan exactly one char.
def get_char(self): """Scan exactly one char.""" self.scan('.')
[ "def", "get_char", "(", "self", ")", ":", "self", ".", "scan", "(", "'.'", ")" ]
[ 94, 4 ]
[ 96, 22 ]
python
en
['en', 'en', 'en']
True
make_pipe
()
Makes a new pair of pipes.
Makes a new pair of pipes.
async def make_pipe() -> "Tuple[PipeSendStream, PipeReceiveStream]": """Makes a new pair of pipes.""" (r, w) = pipe() return PipeSendStream(w), PipeReceiveStream(r)
[ "async", "def", "make_pipe", "(", ")", "->", "\"Tuple[PipeSendStream, PipeReceiveStream]\"", ":", "(", "r", ",", "w", ")", "=", "pipe", "(", ")", "return", "PipeSendStream", "(", "w", ")", ",", "PipeReceiveStream", "(", "r", ")" ]
[ 22, 0 ]
[ 25, 50 ]
python
en
['en', 'en', 'en']
True
run
(args: List[str])
run is like "subprocess.run(args)", but with helpful settings and obeys "with capture_output(out)".
run is like "subprocess.run(args)", but with helpful settings and obeys "with capture_output(out)".
def run(args: List[str]) -> None: """run is like "subprocess.run(args)", but with helpful settings and obeys "with capture_output(out)". """ if _capturing: try: subprocess.run(args, check=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True) except subprocess.Cal...
[ "def", "run", "(", "args", ":", "List", "[", "str", "]", ")", "->", "None", ":", "if", "_capturing", ":", "try", ":", "subprocess", ".", "run", "(", "args", ",", "check", "=", "True", ",", "stdout", "=", "subprocess", ".", "PIPE", ",", "stderr", ...
[ 43, 0 ]
[ 53, 40 ]
python
en
['en', 'en', 'en']
True
run_bincapture
(args: List[str])
run is like "subprocess.run(args, capture_out=True, text=False)", but with helpful settings and obeys "with capture_output(out)".
run is like "subprocess.run(args, capture_out=True, text=False)", but with helpful settings and obeys "with capture_output(out)".
def run_bincapture(args: List[str]) -> bytes: """run is like "subprocess.run(args, capture_out=True, text=False)", but with helpful settings and obeys "with capture_output(out)". """ if _capturing: try: return subprocess.run(args, check=True, capture_output=True).stdout excep...
[ "def", "run_bincapture", "(", "args", ":", "List", "[", "str", "]", ")", "->", "bytes", ":", "if", "_capturing", ":", "try", ":", "return", "subprocess", ".", "run", "(", "args", ",", "check", "=", "True", ",", "capture_output", "=", "True", ")", "."...
[ 56, 0 ]
[ 66, 78 ]
python
en
['en', 'en', 'en']
True
run_txtcapture
(args: List[str])
run is like "subprocess.run(args, capture_out=True, text=true)", but with helpful settings and obeys "with capture_output(out)".
run is like "subprocess.run(args, capture_out=True, text=true)", but with helpful settings and obeys "with capture_output(out)".
def run_txtcapture(args: List[str]) -> str: """run is like "subprocess.run(args, capture_out=True, text=true)", but with helpful settings and obeys "with capture_output(out)". """ if _capturing: try: out = subprocess.run(args, check=True, capture_output=True, text=True).stdout ...
[ "def", "run_txtcapture", "(", "args", ":", "List", "[", "str", "]", ")", "->", "str", ":", "if", "_capturing", ":", "try", ":", "out", "=", "subprocess", ".", "run", "(", "args", ",", "check", "=", "True", ",", "capture_output", "=", "True", ",", "...
[ 69, 0 ]
[ 82, 14 ]
python
en
['en', 'en', 'en']
True
capture_output
(log: io.StringIO)
capture_output is like contextlib.redirect_stdout but also redirects stderr, and also does some extra stuff so that we can have run/run_bincapture/run_txtcapture functions that obey it.
capture_output is like contextlib.redirect_stdout but also redirects stderr, and also does some extra stuff so that we can have run/run_bincapture/run_txtcapture functions that obey it.
def capture_output(log: io.StringIO) -> Generator[None, None, None]: """capture_output is like contextlib.redirect_stdout but also redirects stderr, and also does some extra stuff so that we can have run/run_bincapture/run_txtcapture functions that obey it. """ global _capturing saved_capturing...
[ "def", "capture_output", "(", "log", ":", "io", ".", "StringIO", ")", "->", "Generator", "[", "None", ",", "None", ",", "None", "]", ":", "global", "_capturing", "saved_capturing", "=", "_capturing", "saved_stdout", "=", "sys", ".", "stdout", "saved_stderr",...
[ 86, 0 ]
[ 104, 33 ]
python
en
['en', 'en', 'en']
True
_lex_char_or_cs
(text: str)
Look atthe beginning of the given text and trim either a byte, or an ANSI control sequence from the beginning, returning a tuple ("char-or-cs", "remaining-text"). If it looks like the text is a truncated control seqence, then it doesn't trim anything, and returns ("", "original"); signaling that it nee...
Look atthe beginning of the given text and trim either a byte, or an ANSI control sequence from the beginning, returning a tuple ("char-or-cs", "remaining-text"). If it looks like the text is a truncated control seqence, then it doesn't trim anything, and returns ("", "original"); signaling that it nee...
def _lex_char_or_cs(text: str) -> Tuple[str, str]: """Look atthe beginning of the given text and trim either a byte, or an ANSI control sequence from the beginning, returning a tuple ("char-or-cs", "remaining-text"). If it looks like the text is a truncated control seqence, then it doesn't trim anythin...
[ "def", "_lex_char_or_cs", "(", "text", ":", "str", ")", "->", "Tuple", "[", "str", ",", "str", "]", ":", "if", "text", "==", "'\\033'", ":", "# wait to see if this is a control sequence", "return", "''", ",", "text", "i", "=", "1", "if", "text", ".", "st...
[ 107, 0 ]
[ 128, 29 ]
python
en
['en', 'en', 'en']
True
Indent.__init__
(self, indent: str = "", output: Optional[TextIO] = None, columns: Optional[int] = None)
Arguments: indent: str: The string to indent with. output: Optional[TextIO]: A TextIO to write to, instead of building an in-memory buffer. columns: Optional[int]: How wide the terminal is; this is imporant because a line wrap needs to trigger an ...
Arguments: indent: str: The string to indent with. output: Optional[TextIO]: A TextIO to write to, instead of building an in-memory buffer. columns: Optional[int]: How wide the terminal is; this is imporant because a line wrap needs to trigger an ...
def __init__(self, indent: str = "", output: Optional[TextIO] = None, columns: Optional[int] = None) -> None: """Arguments: indent: str: The string to indent with. output: Optional[TextIO]: A TextIO to write to, instead of building an in-memory buffer. columns: Op...
[ "def", "__init__", "(", "self", ",", "indent", ":", "str", "=", "\"\"", ",", "output", ":", "Optional", "[", "TextIO", "]", "=", "None", ",", "columns", ":", "Optional", "[", "int", "]", "=", "None", ")", "->", "None", ":", "super", "(", ")", "."...
[ 135, 4 ]
[ 163, 50 ]
python
en
['en', 'fr', 'en']
False
Indent.input
(self)
Use "myindent.input()" instead of "input()" in order to nest well with LineTrackers.
Use "myindent.input()" instead of "input()" in order to nest well with LineTrackers.
def input(self) -> str: """Use "myindent.input()" instead of "input()" in order to nest well with LineTrackers. """ if hasattr(self._output, 'input'): text: str = self._output.input() # type: ignore else: text = input() return text
[ "def", "input", "(", "self", ")", "->", "str", ":", "if", "hasattr", "(", "self", ".", "_output", ",", "'input'", ")", ":", "text", ":", "str", "=", "self", ".", "_output", ".", "input", "(", ")", "# type: ignore", "else", ":", "text", "=", "input"...
[ 219, 4 ]
[ 227, 19 ]
python
en
['en', 'en', 'en']
True
LineTracker.input
(self)
Use "mylinetracker.input()" instead of "input()" to avoid the LineTracker not seeing any newlines input by the user.
Use "mylinetracker.input()" instead of "input()" to avoid the LineTracker not seeing any newlines input by the user.
def input(self) -> str: """Use "mylinetracker.input()" instead of "input()" to avoid the LineTracker not seeing any newlines input by the user. """ if hasattr(self._output, 'input'): text: str = self._output.input() # type: ignore else: text = input() ...
[ "def", "input", "(", "self", ")", "->", "str", ":", "if", "hasattr", "(", "self", ".", "_output", ",", "'input'", ")", ":", "text", ":", "str", "=", "self", ".", "_output", ".", "input", "(", ")", "# type: ignore", "else", ":", "text", "=", "input"...
[ 259, 4 ]
[ 268, 19 ]
python
en
['en', 'fi', 'en']
True
LineTracker.goto_line
(self, line: int)
goto_line moves the cursor to the beginning of the given line; where line 1 is the line that the LineTracker started on, line 0 is the line above that, and line 1 is the line below that.
goto_line moves the cursor to the beginning of the given line; where line 1 is the line that the LineTracker started on, line 0 is the line above that, and line 1 is the line below that.
def goto_line(self, line: int) -> None: """goto_line moves the cursor to the beginning of the given line; where line 1 is the line that the LineTracker started on, line 0 is the line above that, and line 1 is the line below that. """ self.write("\r") if line < sel...
[ "def", "goto_line", "(", "self", ",", "line", ":", "int", ")", "->", "None", ":", "self", ".", "write", "(", "\"\\r\"", ")", "if", "line", "<", "self", ".", "cur_line", ":", "total_lines", "=", "shutil", ".", "get_terminal_size", "(", ")", ".", "line...
[ 270, 4 ]
[ 283, 53 ]
python
en
['en', 'en', 'en']
True
Checker.check
(self, name: str, clear_on_success: bool = True)
check returns a context manager that handles printing a '[....]' / '[ OK ]' / '[FAIL]' check. While the check is running, it will stream whatever you write to stdout/stderr. If clear_on_success is True, then once the check finishes, if the check passed then it will erase that stdout/s...
check returns a context manager that handles printing a '[....]' / '[ OK ]' / '[FAIL]' check. While the check is running, it will stream whatever you write to stdout/stderr. If clear_on_success is True, then once the check finishes, if the check passed then it will erase that stdout/s...
def check(self, name: str, clear_on_success: bool = True) -> Generator['CheckResult', None, None]: """check returns a context manager that handles printing a '[....]' / '[ OK ]' / '[FAIL]' check. While the check is running, it will stream whatever you write to stdout/stderr. If clear_...
[ "def", "check", "(", "self", ",", "name", ":", "str", ",", "clear_on_success", ":", "bool", "=", "True", ")", "->", "Generator", "[", "'CheckResult'", ",", "None", ",", "None", "]", ":", "def", "line", "(", "status", ":", "str", ",", "rest", ":", "...
[ 309, 4 ]
[ 356, 27 ]
python
en
['en', 'en', 'en']
True
currently_ki_protected
()
r"""Check whether the calling code has :exc:`KeyboardInterrupt` protection enabled. It's surprisingly easy to think that one's :exc:`KeyboardInterrupt` protection is enabled when it isn't, or vice-versa. This function tells you what Trio thinks of the matter, which makes it useful for ``assert``\s ...
r"""Check whether the calling code has :exc:`KeyboardInterrupt` protection enabled.
def currently_ki_protected(): r"""Check whether the calling code has :exc:`KeyboardInterrupt` protection enabled. It's surprisingly easy to think that one's :exc:`KeyboardInterrupt` protection is enabled when it isn't, or vice-versa. This function tells you what Trio thinks of the matter, which mak...
[ "def", "currently_ki_protected", "(", ")", ":", "return", "ki_protection_enabled", "(", "sys", ".", "_getframe", "(", ")", ")" ]
[ 95, 0 ]
[ 108, 49 ]
python
en
['en', 'en', 'en']
True
IRTCPMappingGroup.finalize
(self, ir: 'IR', aconf: Config)
Finalize a MappingGroup based on the attributes of its Mappings. Core elements get lifted into the Group so we can more easily build Envoy routes; host-redirect and shadow get handled, etc. :param ir: the IR we're working from :param aconf: the Config we're working from :return...
Finalize a MappingGroup based on the attributes of its Mappings. Core elements get lifted into the Group so we can more easily build Envoy routes; host-redirect and shadow get handled, etc.
def finalize(self, ir: 'IR', aconf: Config) -> List[IRCluster]: """ Finalize a MappingGroup based on the attributes of its Mappings. Core elements get lifted into the Group so we can more easily build Envoy routes; host-redirect and shadow get handled, etc. :param ir: the IR we're worki...
[ "def", "finalize", "(", "self", ",", "ir", ":", "'IR'", ",", "aconf", ":", "Config", ")", "->", "List", "[", "IRCluster", "]", ":", "metadata_labels", ":", "Dict", "[", "str", ",", "str", "]", "=", "{", "}", "for", "mapping", "in", "sorted", "(", ...
[ 168, 4 ]
[ 257, 69 ]
python
en
['en', 'error', 'th']
False
wait_child_exiting
(process: "_subprocess.Process")
Block until the child process managed by ``process`` is exiting. It is invalid to call this function if the process has already been waited on; that is, ``process.returncode`` must be None. When this function returns, it indicates that a call to :meth:`subprocess.Popen.wait` will immediately be able t...
Block until the child process managed by ``process`` is exiting.
async def wait_child_exiting(process: "_subprocess.Process") -> None: """Block until the child process managed by ``process`` is exiting. It is invalid to call this function if the process has already been waited on; that is, ``process.returncode`` must be None. When this function returns, it indicate...
[ "async", "def", "wait_child_exiting", "(", "process", ":", "\"_subprocess.Process\"", ")", "->", "None", ":", "raise", "NotImplementedError", "from", "_wait_child_exiting_error" ]
[ 16, 0 ]
[ 28, 60 ]
python
en
['en', 'en', 'en']
True
create_pipe_to_child_stdin
()
Create a new pipe suitable for sending data from this process to the standard input of a child we're about to spawn. Returns: A pair ``(trio_end, subprocess_end)`` where ``trio_end`` is a :class:`~trio.abc.SendStream` and ``subprocess_end`` is something suitable for passing as the ``stdin`` a...
Create a new pipe suitable for sending data from this process to the standard input of a child we're about to spawn.
def create_pipe_to_child_stdin() -> Tuple[SendStream, int]: """Create a new pipe suitable for sending data from this process to the standard input of a child we're about to spawn. Returns: A pair ``(trio_end, subprocess_end)`` where ``trio_end`` is a :class:`~trio.abc.SendStream` and ``subproce...
[ "def", "create_pipe_to_child_stdin", "(", ")", "->", "Tuple", "[", "SendStream", ",", "int", "]", ":", "raise", "NotImplementedError", "from", "_create_child_pipe_error" ]
[ 31, 0 ]
[ 41, 59 ]
python
en
['en', 'en', 'en']
True
create_pipe_from_child_output
()
Create a new pipe suitable for receiving data into this process from the standard output or error stream of a child we're about to spawn. Returns: A pair ``(trio_end, subprocess_end)`` where ``trio_end`` is a :class:`~trio.abc.ReceiveStream` and ``subprocess_end`` is something suitable fo...
Create a new pipe suitable for receiving data into this process from the standard output or error stream of a child we're about to spawn.
def create_pipe_from_child_output() -> Tuple[ReceiveStream, int]: """Create a new pipe suitable for receiving data into this process from the standard output or error stream of a child we're about to spawn. Returns: A pair ``(trio_end, subprocess_end)`` where ``trio_end`` is a :class:`~trio...
[ "def", "create_pipe_from_child_output", "(", ")", "->", "Tuple", "[", "ReceiveStream", ",", "int", "]", ":", "raise", "NotImplementedError", "from", "_create_child_pipe_error" ]
[ 44, 0 ]
[ 55, 59 ]
python
en
['en', 'en', 'en']
True
sample_user
(email='test@testmail.com', password='testpass')
Create a sample user
Create a sample user
def sample_user(email='test@testmail.com', password='testpass'): """Create a sample user""" return get_user_model().objects.create_user(email, password)
[ "def", "sample_user", "(", "email", "=", "'test@testmail.com'", ",", "password", "=", "'testpass'", ")", ":", "return", "get_user_model", "(", ")", ".", "objects", ".", "create_user", "(", "email", ",", "password", ")" ]
[ 8, 0 ]
[ 10, 64 ]
python
en
['en', 'co', 'en']
True
ModelTests.test_create_user_with_email_successful
(self)
Test creating a new user with an email is successful
Test creating a new user with an email is successful
def test_create_user_with_email_successful(self): """Test creating a new user with an email is successful""" email = 'test@testmail.com' password = 'testpass123' user = get_user_model().objects.create_user( email=email, password=password ) self.as...
[ "def", "test_create_user_with_email_successful", "(", "self", ")", ":", "email", "=", "'test@testmail.com'", "password", "=", "'testpass123'", "user", "=", "get_user_model", "(", ")", ".", "objects", ".", "create_user", "(", "email", "=", "email", ",", "password",...
[ 15, 4 ]
[ 25, 54 ]
python
en
['en', 'en', 'en']
True
ModelTests.test_new_user_email_normalize
(self)
Test the email for a new user normalized
Test the email for a new user normalized
def test_new_user_email_normalize(self): """Test the email for a new user normalized""" email = 'test@TESTMAIL.com' user = get_user_model().objects.create_user(email, 'testpass123') self.assertEqual(user.email, email.lower())
[ "def", "test_new_user_email_normalize", "(", "self", ")", ":", "email", "=", "'test@TESTMAIL.com'", "user", "=", "get_user_model", "(", ")", ".", "objects", ".", "create_user", "(", "email", ",", "'testpass123'", ")", "self", ".", "assertEqual", "(", "user", "...
[ 27, 4 ]
[ 32, 51 ]
python
en
['en', 'en', 'en']
True
ModelTests.test_new_user_invalid_email
(self)
Test creating user with no email raises error
Test creating user with no email raises error
def test_new_user_invalid_email(self): """Test creating user with no email raises error""" with self.assertRaises(ValueError): get_user_model().objects.create_user(None, 'testpass123')
[ "def", "test_new_user_invalid_email", "(", "self", ")", ":", "with", "self", ".", "assertRaises", "(", "ValueError", ")", ":", "get_user_model", "(", ")", ".", "objects", ".", "create_user", "(", "None", ",", "'testpass123'", ")" ]
[ 34, 4 ]
[ 37, 69 ]
python
en
['en', 'en', 'en']
True
ModelTests.test_create_new_superuser
(self)
Test creating a new superuser
Test creating a new superuser
def test_create_new_superuser(self): """Test creating a new superuser""" user = get_user_model().objects.create_superuser( 'test@testmail.com', 'testpass123' ) self.assertTrue(user.is_superuser) self.assertTrue(user.is_staff)
[ "def", "test_create_new_superuser", "(", "self", ")", ":", "user", "=", "get_user_model", "(", ")", ".", "objects", ".", "create_superuser", "(", "'test@testmail.com'", ",", "'testpass123'", ")", "self", ".", "assertTrue", "(", "user", ".", "is_superuser", ")", ...
[ 39, 4 ]
[ 47, 38 ]
python
en
['en', 'en', 'en']
True
ModelTests.test_tag_str
(self)
Test the tag string representation
Test the tag string representation
def test_tag_str(self): """Test the tag string representation""" tag = models.Tag.objects.create( user=sample_user(), name='Vegan' ) self.assertEqual(str(tag), tag.name)
[ "def", "test_tag_str", "(", "self", ")", ":", "tag", "=", "models", ".", "Tag", ".", "objects", ".", "create", "(", "user", "=", "sample_user", "(", ")", ",", "name", "=", "'Vegan'", ")", "self", ".", "assertEqual", "(", "str", "(", "tag", ")", ","...
[ 49, 4 ]
[ 56, 44 ]
python
en
['en', 'en', 'en']
True
ModelTests.test_ingredient_str
(self)
Test the ingredient string representation
Test the ingredient string representation
def test_ingredient_str(self): """Test the ingredient string representation""" ingredient = models.Ingredient.objects.create( user=sample_user(), name='Cucumber' ) self.assertEqual(str(ingredient), ingredient.name)
[ "def", "test_ingredient_str", "(", "self", ")", ":", "ingredient", "=", "models", ".", "Ingredient", ".", "objects", ".", "create", "(", "user", "=", "sample_user", "(", ")", ",", "name", "=", "'Cucumber'", ")", "self", ".", "assertEqual", "(", "str", "(...
[ 58, 4 ]
[ 65, 58 ]
python
en
['en', 'en', 'en']
True
ModelTests.test_recipe_str
(self)
Test the recipe string representation
Test the recipe string representation
def test_recipe_str(self): """Test the recipe string representation""" recipe = models.Recipe.objects.create( user=sample_user(), title='Steak and mashroom sauce', time_minutes=5, price=5.00 ) self.assertEqual(str(recipe), recipe.title)
[ "def", "test_recipe_str", "(", "self", ")", ":", "recipe", "=", "models", ".", "Recipe", ".", "objects", ".", "create", "(", "user", "=", "sample_user", "(", ")", ",", "title", "=", "'Steak and mashroom sauce'", ",", "time_minutes", "=", "5", ",", "price",...
[ 67, 4 ]
[ 76, 51 ]
python
en
['en', 'en', 'en']
True
ModelTests.test_recipe_file_name_uuid
(self, mock_uuid)
Test that image is saved in the correct location
Test that image is saved in the correct location
def test_recipe_file_name_uuid(self, mock_uuid): """Test that image is saved in the correct location""" uuid = 'test-uuid' mock_uuid.return_value = uuid file_path = models.recipe_image_file_path(None, 'myimage.jpg') exp_path = f'upload/recipe/{uuid}.jpg' self.assertEqual...
[ "def", "test_recipe_file_name_uuid", "(", "self", ",", "mock_uuid", ")", ":", "uuid", "=", "'test-uuid'", "mock_uuid", ".", "return_value", "=", "uuid", "file_path", "=", "models", ".", "recipe_image_file_path", "(", "None", ",", "'myimage.jpg'", ")", "exp_path", ...
[ 79, 4 ]
[ 86, 45 ]
python
en
['en', 'en', 'en']
True
_WriteWorkspace
(main_gyp, sources_gyp, params)
Create a workspace to wrap main and sources gyp paths.
Create a workspace to wrap main and sources gyp paths.
def _WriteWorkspace(main_gyp, sources_gyp, params): """ Create a workspace to wrap main and sources gyp paths. """ (build_file_root, build_file_ext) = os.path.splitext(main_gyp) workspace_path = build_file_root + '.xcworkspace' options = params['options'] if options.generator_output: workspace_path = os.p...
[ "def", "_WriteWorkspace", "(", "main_gyp", ",", "sources_gyp", ",", "params", ")", ":", "(", "build_file_root", ",", "build_file_ext", ")", "=", "os", ".", "path", ".", "splitext", "(", "main_gyp", ")", "workspace_path", "=", "build_file_root", "+", "'.xcworks...
[ 21, 0 ]
[ 53, 36 ]
python
en
['en', 'en', 'en']
True