partition stringclasses 3
values | func_name stringlengths 1 134 | docstring stringlengths 1 46.9k | path stringlengths 4 223 | original_string stringlengths 75 104k | code stringlengths 75 104k | docstring_tokens listlengths 1 1.97k | repo stringlengths 7 55 | language stringclasses 1
value | url stringlengths 87 315 | code_tokens listlengths 19 28.4k | sha stringlengths 40 40 |
|---|---|---|---|---|---|---|---|---|---|---|---|
train | FeatsFromSpacyDocOnlyNounChunks.get_feats | Parameters
----------
doc, Spacy Docs
Returns
-------
Counter noun chunk -> count | scattertext/features/FeatsFromSpacyDocOnlyNounChunks.py | def get_feats(self, doc):
'''
Parameters
----------
doc, Spacy Docs
Returns
-------
Counter noun chunk -> count
'''
return Counter([str(c).lower() for c in doc.noun_chunks]) | def get_feats(self, doc):
'''
Parameters
----------
doc, Spacy Docs
Returns
-------
Counter noun chunk -> count
'''
return Counter([str(c).lower() for c in doc.noun_chunks]) | [
"Parameters",
"----------",
"doc",
"Spacy",
"Docs"
] | JasonKessler/scattertext | python | https://github.com/JasonKessler/scattertext/blob/cacf1f687d218ee8cae3fc05cc901db824bb1b81/scattertext/features/FeatsFromSpacyDocOnlyNounChunks.py#L11-L21 | [
"def",
"get_feats",
"(",
"self",
",",
"doc",
")",
":",
"return",
"Counter",
"(",
"[",
"str",
"(",
"c",
")",
".",
"lower",
"(",
")",
"for",
"c",
"in",
"doc",
".",
"noun_chunks",
"]",
")"
] | cacf1f687d218ee8cae3fc05cc901db824bb1b81 |
train | nltk_tokenzier_factory | Parameters
----------
nltk_tokenizer : nltk.tokenize.* instance (e.g., nltk.TreebankWordTokenizer())
Returns
-------
Doc of tweets
Notes
-------
Requires NLTK to be installed | scattertext/WhitespaceNLP.py | def nltk_tokenzier_factory(nltk_tokenizer):
'''
Parameters
----------
nltk_tokenizer : nltk.tokenize.* instance (e.g., nltk.TreebankWordTokenizer())
Returns
-------
Doc of tweets
Notes
-------
Requires NLTK to be installed
'''
def tokenize(text):
toks = []
for tok in nltk_tokenizer.tokenize(text):
... | def nltk_tokenzier_factory(nltk_tokenizer):
'''
Parameters
----------
nltk_tokenizer : nltk.tokenize.* instance (e.g., nltk.TreebankWordTokenizer())
Returns
-------
Doc of tweets
Notes
-------
Requires NLTK to be installed
'''
def tokenize(text):
toks = []
for tok in nltk_tokenizer.tokenize(text):
... | [
"Parameters",
"----------",
"nltk_tokenizer",
":",
"nltk",
".",
"tokenize",
".",
"*",
"instance",
"(",
"e",
".",
"g",
".",
"nltk",
".",
"TreebankWordTokenizer",
"()",
")"
] | JasonKessler/scattertext | python | https://github.com/JasonKessler/scattertext/blob/cacf1f687d218ee8cae3fc05cc901db824bb1b81/scattertext/WhitespaceNLP.py#L75-L101 | [
"def",
"nltk_tokenzier_factory",
"(",
"nltk_tokenizer",
")",
":",
"def",
"tokenize",
"(",
"text",
")",
":",
"toks",
"=",
"[",
"]",
"for",
"tok",
"in",
"nltk_tokenizer",
".",
"tokenize",
"(",
"text",
")",
":",
"if",
"len",
"(",
"tok",
")",
">",
"0",
"... | cacf1f687d218ee8cae3fc05cc901db824bb1b81 |
train | EmbeddingsResolver.set_embeddings | Specifies fixed set of embeddings
:param embeddings: array-like, sparse or dense, shape should be (embedding size, # terms)
:return: EmbeddingsResolver | scattertext/representations/EmbeddingsResolver.py | def set_embeddings(self, embeddings):
'''
Specifies fixed set of embeddings
:param embeddings: array-like, sparse or dense, shape should be (embedding size, # terms)
:return: EmbeddingsResolver
'''
if self.embeddings_ is not None:
raise Exception("You have alr... | def set_embeddings(self, embeddings):
'''
Specifies fixed set of embeddings
:param embeddings: array-like, sparse or dense, shape should be (embedding size, # terms)
:return: EmbeddingsResolver
'''
if self.embeddings_ is not None:
raise Exception("You have alr... | [
"Specifies",
"fixed",
"set",
"of",
"embeddings",
":",
"param",
"embeddings",
":",
"array",
"-",
"like",
"sparse",
"or",
"dense",
"shape",
"should",
"be",
"(",
"embedding",
"size",
"#",
"terms",
")",
":",
"return",
":",
"EmbeddingsResolver"
] | JasonKessler/scattertext | python | https://github.com/JasonKessler/scattertext/blob/cacf1f687d218ee8cae3fc05cc901db824bb1b81/scattertext/representations/EmbeddingsResolver.py#L17-L28 | [
"def",
"set_embeddings",
"(",
"self",
",",
"embeddings",
")",
":",
"if",
"self",
".",
"embeddings_",
"is",
"not",
"None",
":",
"raise",
"Exception",
"(",
"\"You have already set embeddings by running set_embeddings or set_embeddings_model.\"",
")",
"assert",
"embeddings",... | cacf1f687d218ee8cae3fc05cc901db824bb1b81 |
train | EmbeddingsResolver.project | :param projection_model: sklearn unsupervised model (e.g., PCA) by default the recommended model is umap.UMAP,
which requires UMAP in to be installed
:return: array, shape (num dimension, vocab size) | scattertext/representations/EmbeddingsResolver.py | def project(self, projection_model=None):
'''
:param projection_model: sklearn unsupervised model (e.g., PCA) by default the recommended model is umap.UMAP,
which requires UMAP in to be installed
:return: array, shape (num dimension, vocab size)
'''
if self.embeddings_ i... | def project(self, projection_model=None):
'''
:param projection_model: sklearn unsupervised model (e.g., PCA) by default the recommended model is umap.UMAP,
which requires UMAP in to be installed
:return: array, shape (num dimension, vocab size)
'''
if self.embeddings_ i... | [
":",
"param",
"projection_model",
":",
"sklearn",
"unsupervised",
"model",
"(",
"e",
".",
"g",
".",
"PCA",
")",
"by",
"default",
"the",
"recommended",
"model",
"is",
"umap",
".",
"UMAP",
"which",
"requires",
"UMAP",
"in",
"to",
"be",
"installed"
] | JasonKessler/scattertext | python | https://github.com/JasonKessler/scattertext/blob/cacf1f687d218ee8cae3fc05cc901db824bb1b81/scattertext/representations/EmbeddingsResolver.py#L81-L97 | [
"def",
"project",
"(",
"self",
",",
"projection_model",
"=",
"None",
")",
":",
"if",
"self",
".",
"embeddings_",
"is",
"None",
":",
"raise",
"Exception",
"(",
"\"Run set_embeddings_model or set_embeddings to get embeddings\"",
")",
"if",
"projection_model",
"is",
"N... | cacf1f687d218ee8cae3fc05cc901db824bb1b81 |
train | SentencesForTopicModeling.get_topics_from_terms | Parameters
----------
terms : list or None
If terms is list, make these the seed terms for the topoics
If none, use the first 30 terms in get_scaled_f_scores_vs_background
num_terms_per_topic : int, default 10
Use this many terms per topic
scorer : TermScorer
Implements get_scores, default is RankDi... | scattertext/topicmodel/SentencesForTopicModeling.py | def get_topics_from_terms(self,
terms=None,
num_terms_per_topic=10,
scorer=RankDifference()):
'''
Parameters
----------
terms : list or None
If terms is list, make these the seed terms for the topoics
If none, use the first 3... | def get_topics_from_terms(self,
terms=None,
num_terms_per_topic=10,
scorer=RankDifference()):
'''
Parameters
----------
terms : list or None
If terms is list, make these the seed terms for the topoics
If none, use the first 3... | [
"Parameters",
"----------",
"terms",
":",
"list",
"or",
"None",
"If",
"terms",
"is",
"list",
"make",
"these",
"the",
"seed",
"terms",
"for",
"the",
"topoics",
"If",
"none",
"use",
"the",
"first",
"30",
"terms",
"in",
"get_scaled_f_scores_vs_background",
"num_t... | JasonKessler/scattertext | python | https://github.com/JasonKessler/scattertext/blob/cacf1f687d218ee8cae3fc05cc901db824bb1b81/scattertext/topicmodel/SentencesForTopicModeling.py#L82-L114 | [
"def",
"get_topics_from_terms",
"(",
"self",
",",
"terms",
"=",
"None",
",",
"num_terms_per_topic",
"=",
"10",
",",
"scorer",
"=",
"RankDifference",
"(",
")",
")",
":",
"topic_model",
"=",
"{",
"}",
"if",
"terms",
"is",
"None",
":",
"terms",
"=",
"self",... | cacf1f687d218ee8cae3fc05cc901db824bb1b81 |
train | AbsoluteFrequencyRanker.get_ranks | Returns
-------
pd.DataFrame | scattertext/termranking/AbsoluteFrequencyRanker.py | def get_ranks(self):
'''
Returns
-------
pd.DataFrame
'''
if self._use_non_text_features:
return self._term_doc_matrix.get_metadata_freq_df()
else:
return self._term_doc_matrix.get_term_freq_df() | def get_ranks(self):
'''
Returns
-------
pd.DataFrame
'''
if self._use_non_text_features:
return self._term_doc_matrix.get_metadata_freq_df()
else:
return self._term_doc_matrix.get_term_freq_df() | [
"Returns",
"-------",
"pd",
".",
"DataFrame"
] | JasonKessler/scattertext | python | https://github.com/JasonKessler/scattertext/blob/cacf1f687d218ee8cae3fc05cc901db824bb1b81/scattertext/termranking/AbsoluteFrequencyRanker.py#L8-L18 | [
"def",
"get_ranks",
"(",
"self",
")",
":",
"if",
"self",
".",
"_use_non_text_features",
":",
"return",
"self",
".",
"_term_doc_matrix",
".",
"get_metadata_freq_df",
"(",
")",
"else",
":",
"return",
"self",
".",
"_term_doc_matrix",
".",
"get_term_freq_df",
"(",
... | cacf1f687d218ee8cae3fc05cc901db824bb1b81 |
train | TermDocMatrixFactory.build | Generate a TermDocMatrix from data in parameters.
Returns
----------
term_doc_matrix : TermDocMatrix
The object that this factory class builds. | scattertext/TermDocMatrixFactory.py | def build(self):
"""Generate a TermDocMatrix from data in parameters.
Returns
----------
term_doc_matrix : TermDocMatrix
The object that this factory class builds.
"""
if self._category_text_iter is None:
raise CategoryTextIterNotSetError()
... | def build(self):
"""Generate a TermDocMatrix from data in parameters.
Returns
----------
term_doc_matrix : TermDocMatrix
The object that this factory class builds.
"""
if self._category_text_iter is None:
raise CategoryTextIterNotSetError()
... | [
"Generate",
"a",
"TermDocMatrix",
"from",
"data",
"in",
"parameters",
"."
] | JasonKessler/scattertext | python | https://github.com/JasonKessler/scattertext/blob/cacf1f687d218ee8cae3fc05cc901db824bb1b81/scattertext/TermDocMatrixFactory.py#L115-L140 | [
"def",
"build",
"(",
"self",
")",
":",
"if",
"self",
".",
"_category_text_iter",
"is",
"None",
":",
"raise",
"CategoryTextIterNotSetError",
"(",
")",
"nlp",
"=",
"self",
".",
"get_nlp",
"(",
")",
"category_document_iter",
"=",
"(",
"(",
"category",
",",
"s... | cacf1f687d218ee8cae3fc05cc901db824bb1b81 |
train | TermDocMatrixFactory.censor_entity_types | Entity types to exclude from feature construction. Terms matching
specificed entities, instead of labeled by their lower case orthographic
form or lemma, will be labeled by their entity type.
Parameters
----------
entity_types : set of entity types outputted by spaCy
'... | scattertext/TermDocMatrixFactory.py | def censor_entity_types(self, entity_types):
# type: (set) -> TermDocMatrixFactory
'''
Entity types to exclude from feature construction. Terms matching
specificed entities, instead of labeled by their lower case orthographic
form or lemma, will be labeled by their entity type.
... | def censor_entity_types(self, entity_types):
# type: (set) -> TermDocMatrixFactory
'''
Entity types to exclude from feature construction. Terms matching
specificed entities, instead of labeled by their lower case orthographic
form or lemma, will be labeled by their entity type.
... | [
"Entity",
"types",
"to",
"exclude",
"from",
"feature",
"construction",
".",
"Terms",
"matching",
"specificed",
"entities",
"instead",
"of",
"labeled",
"by",
"their",
"lower",
"case",
"orthographic",
"form",
"or",
"lemma",
"will",
"be",
"labeled",
"by",
"their",
... | JasonKessler/scattertext | python | https://github.com/JasonKessler/scattertext/blob/cacf1f687d218ee8cae3fc05cc901db824bb1b81/scattertext/TermDocMatrixFactory.py#L149-L172 | [
"def",
"censor_entity_types",
"(",
"self",
",",
"entity_types",
")",
":",
"# type: (set) -> TermDocMatrixFactory",
"assert",
"type",
"(",
"entity_types",
")",
"==",
"set",
"self",
".",
"_entity_types_to_censor",
"=",
"entity_types",
"self",
".",
"_feats_from_spacy_doc",... | cacf1f687d218ee8cae3fc05cc901db824bb1b81 |
train | TermDocMatrixFactory._build_from_category_spacy_doc_iter | Parameters
----------
category_doc_iter : iterator of (string category name, spacy.tokens.doc.Doc) pairs
Returns
----------
t : TermDocMatrix | scattertext/TermDocMatrixFactory.py | def _build_from_category_spacy_doc_iter(self, category_doc_iter):
'''
Parameters
----------
category_doc_iter : iterator of (string category name, spacy.tokens.doc.Doc) pairs
Returns
----------
t : TermDocMatrix
'''
term_idx_store = IndexStore()
... | def _build_from_category_spacy_doc_iter(self, category_doc_iter):
'''
Parameters
----------
category_doc_iter : iterator of (string category name, spacy.tokens.doc.Doc) pairs
Returns
----------
t : TermDocMatrix
'''
term_idx_store = IndexStore()
... | [
"Parameters",
"----------",
"category_doc_iter",
":",
"iterator",
"of",
"(",
"string",
"category",
"name",
"spacy",
".",
"tokens",
".",
"doc",
".",
"Doc",
")",
"pairs"
] | JasonKessler/scattertext | python | https://github.com/JasonKessler/scattertext/blob/cacf1f687d218ee8cae3fc05cc901db824bb1b81/scattertext/TermDocMatrixFactory.py#L174-L197 | [
"def",
"_build_from_category_spacy_doc_iter",
"(",
"self",
",",
"category_doc_iter",
")",
":",
"term_idx_store",
"=",
"IndexStore",
"(",
")",
"category_idx_store",
"=",
"IndexStore",
"(",
")",
"metadata_idx_store",
"=",
"IndexStore",
"(",
")",
"X",
",",
"mX",
",",... | cacf1f687d218ee8cae3fc05cc901db824bb1b81 |
train | FeatsFromDoc.feats_from_doc | Parameters
----------
raw_text, uncleaned text for parsing out features
Returns
-------
csr_matrix, feature matrix | scattertext/TermDocMatrixFactory.py | def feats_from_doc(self, raw_text):
'''
Parameters
----------
raw_text, uncleaned text for parsing out features
Returns
-------
csr_matrix, feature matrix
'''
parsed_text = self._nlp(self._clean_function(raw_text))
X_factory = CSRMatrixFac... | def feats_from_doc(self, raw_text):
'''
Parameters
----------
raw_text, uncleaned text for parsing out features
Returns
-------
csr_matrix, feature matrix
'''
parsed_text = self._nlp(self._clean_function(raw_text))
X_factory = CSRMatrixFac... | [
"Parameters",
"----------",
"raw_text",
"uncleaned",
"text",
"for",
"parsing",
"out",
"features"
] | JasonKessler/scattertext | python | https://github.com/JasonKessler/scattertext/blob/cacf1f687d218ee8cae3fc05cc901db824bb1b81/scattertext/TermDocMatrixFactory.py#L299-L314 | [
"def",
"feats_from_doc",
"(",
"self",
",",
"raw_text",
")",
":",
"parsed_text",
"=",
"self",
".",
"_nlp",
"(",
"self",
".",
"_clean_function",
"(",
"raw_text",
")",
")",
"X_factory",
"=",
"CSRMatrixFactory",
"(",
")",
"X_factory",
".",
"set_last_col_idx",
"(... | cacf1f687d218ee8cae3fc05cc901db824bb1b81 |
train | SemioticSquare.get_lexicons | Parameters
----------
num_terms, int
Returns
-------
dict | scattertext/semioticsquare/SemioticSquare.py | def get_lexicons(self, num_terms=10):
'''
Parameters
----------
num_terms, int
Returns
-------
dict
'''
return {k: v.index[:num_terms]
for k, v in self.lexicons.items()} | def get_lexicons(self, num_terms=10):
'''
Parameters
----------
num_terms, int
Returns
-------
dict
'''
return {k: v.index[:num_terms]
for k, v in self.lexicons.items()} | [
"Parameters",
"----------",
"num_terms",
"int"
] | JasonKessler/scattertext | python | https://github.com/JasonKessler/scattertext/blob/cacf1f687d218ee8cae3fc05cc901db824bb1b81/scattertext/semioticsquare/SemioticSquare.py#L112-L123 | [
"def",
"get_lexicons",
"(",
"self",
",",
"num_terms",
"=",
"10",
")",
":",
"return",
"{",
"k",
":",
"v",
".",
"index",
"[",
":",
"num_terms",
"]",
"for",
"k",
",",
"v",
"in",
"self",
".",
"lexicons",
".",
"items",
"(",
")",
"}"
] | cacf1f687d218ee8cae3fc05cc901db824bb1b81 |
train | AssociationCompactor.compact | Parameters
----------
term_doc_matrix : TermDocMatrix
Term document matrix object to compact
Returns
-------
New term doc matrix | scattertext/termcompaction/AssociationCompactor.py | def compact(self, term_doc_matrix):
'''
Parameters
----------
term_doc_matrix : TermDocMatrix
Term document matrix object to compact
Returns
-------
New term doc matrix
'''
rank_df = self.scorer.get_rank_df(term_doc_matrix)
opti... | def compact(self, term_doc_matrix):
'''
Parameters
----------
term_doc_matrix : TermDocMatrix
Term document matrix object to compact
Returns
-------
New term doc matrix
'''
rank_df = self.scorer.get_rank_df(term_doc_matrix)
opti... | [
"Parameters",
"----------",
"term_doc_matrix",
":",
"TermDocMatrix",
"Term",
"document",
"matrix",
"object",
"to",
"compact",
"Returns",
"-------",
"New",
"term",
"doc",
"matrix"
] | JasonKessler/scattertext | python | https://github.com/JasonKessler/scattertext/blob/cacf1f687d218ee8cae3fc05cc901db824bb1b81/scattertext/termcompaction/AssociationCompactor.py#L44-L59 | [
"def",
"compact",
"(",
"self",
",",
"term_doc_matrix",
")",
":",
"rank_df",
"=",
"self",
".",
"scorer",
".",
"get_rank_df",
"(",
"term_doc_matrix",
")",
"optimal_rank",
"=",
"self",
".",
"_find_optimal_rank",
"(",
"rank_df",
")",
"compacted_term_doc_matrix",
"="... | cacf1f687d218ee8cae3fc05cc901db824bb1b81 |
train | AssociationCompactorByRank.compact | Parameters
----------
term_doc_matrix : TermDocMatrix
Term document matrix object to compact
Returns
-------
TermDocMatrix | scattertext/termcompaction/AssociationCompactor.py | def compact(self, term_doc_matrix):
'''
Parameters
----------
term_doc_matrix : TermDocMatrix
Term document matrix object to compact
Returns
-------
TermDocMatrix
'''
rank_df = self.scorer.get_rank_df(term_doc_matrix)
return s... | def compact(self, term_doc_matrix):
'''
Parameters
----------
term_doc_matrix : TermDocMatrix
Term document matrix object to compact
Returns
-------
TermDocMatrix
'''
rank_df = self.scorer.get_rank_df(term_doc_matrix)
return s... | [
"Parameters",
"----------",
"term_doc_matrix",
":",
"TermDocMatrix",
"Term",
"document",
"matrix",
"object",
"to",
"compact",
"Returns",
"-------",
"TermDocMatrix"
] | JasonKessler/scattertext | python | https://github.com/JasonKessler/scattertext/blob/cacf1f687d218ee8cae3fc05cc901db824bb1b81/scattertext/termcompaction/AssociationCompactor.py#L85-L98 | [
"def",
"compact",
"(",
"self",
",",
"term_doc_matrix",
")",
":",
"rank_df",
"=",
"self",
".",
"scorer",
".",
"get_rank_df",
"(",
"term_doc_matrix",
")",
"return",
"self",
".",
"_prune_higher_ranked_terms",
"(",
"term_doc_matrix",
",",
"rank_df",
",",
"self",
"... | cacf1f687d218ee8cae3fc05cc901db824bb1b81 |
train | FeatsFromGensim.get_feats | Parameters
----------
doc, Spacy Docs
Returns
-------
Counter (unigram, bigram) -> count | scattertext/representations/Word2VecFromParsedCorpus.py | def get_feats(self, doc):
'''
Parameters
----------
doc, Spacy Docs
Returns
-------
Counter (unigram, bigram) -> count
'''
ngram_counter = Counter()
for sent in doc.sents:
ngrams = self.phrases[str(sent)]
for subphrases in self.phrases[1:]:
ngrams = subphrases[str(sent)]
for ngram in n... | def get_feats(self, doc):
'''
Parameters
----------
doc, Spacy Docs
Returns
-------
Counter (unigram, bigram) -> count
'''
ngram_counter = Counter()
for sent in doc.sents:
ngrams = self.phrases[str(sent)]
for subphrases in self.phrases[1:]:
ngrams = subphrases[str(sent)]
for ngram in n... | [
"Parameters",
"----------",
"doc",
"Spacy",
"Docs"
] | JasonKessler/scattertext | python | https://github.com/JasonKessler/scattertext/blob/cacf1f687d218ee8cae3fc05cc901db824bb1b81/scattertext/representations/Word2VecFromParsedCorpus.py#L28-L45 | [
"def",
"get_feats",
"(",
"self",
",",
"doc",
")",
":",
"ngram_counter",
"=",
"Counter",
"(",
")",
"for",
"sent",
"in",
"doc",
".",
"sents",
":",
"ngrams",
"=",
"self",
".",
"phrases",
"[",
"str",
"(",
"sent",
")",
"]",
"for",
"subphrases",
"in",
"s... | cacf1f687d218ee8cae3fc05cc901db824bb1b81 |
train | GensimPhraseAdder.add_phrases | Parameters
----------
corpus: Corpus for phrase augmentation
Returns
-------
New ParsedCorpus containing unigrams in corpus and new phrases | scattertext/representations/Word2VecFromParsedCorpus.py | def add_phrases(self, corpus):
'''
Parameters
----------
corpus: Corpus for phrase augmentation
Returns
-------
New ParsedCorpus containing unigrams in corpus and new phrases
'''
from gensim.models import Phrases
assert isinstance(corpus, ParsedCorpus)
self.phrases = [Phrases(CorpusAdapterForGen... | def add_phrases(self, corpus):
'''
Parameters
----------
corpus: Corpus for phrase augmentation
Returns
-------
New ParsedCorpus containing unigrams in corpus and new phrases
'''
from gensim.models import Phrases
assert isinstance(corpus, ParsedCorpus)
self.phrases = [Phrases(CorpusAdapterForGen... | [
"Parameters",
"----------",
"corpus",
":",
"Corpus",
"for",
"phrase",
"augmentation"
] | JasonKessler/scattertext | python | https://github.com/JasonKessler/scattertext/blob/cacf1f687d218ee8cae3fc05cc901db824bb1b81/scattertext/representations/Word2VecFromParsedCorpus.py#L59-L77 | [
"def",
"add_phrases",
"(",
"self",
",",
"corpus",
")",
":",
"from",
"gensim",
".",
"models",
"import",
"Phrases",
"assert",
"isinstance",
"(",
"corpus",
",",
"ParsedCorpus",
")",
"self",
".",
"phrases",
"=",
"[",
"Phrases",
"(",
"CorpusAdapterForGensim",
"."... | cacf1f687d218ee8cae3fc05cc901db824bb1b81 |
train | Word2VecFromParsedCorpus.train | Parameters
----------
epochs : int
Number of epochs to train for. Default is 2000.
training_iterations : int
Number of times to repeat training process. Default is training_iterations.
Returns
-------
A trained word2vec model. | scattertext/representations/Word2VecFromParsedCorpus.py | def train(self, epochs=2000, training_iterations=5):
'''
Parameters
----------
epochs : int
Number of epochs to train for. Default is 2000.
training_iterations : int
Number of times to repeat training process. Default is training_iterations.
Returns
-------
A trained word2vec model.
'''
se... | def train(self, epochs=2000, training_iterations=5):
'''
Parameters
----------
epochs : int
Number of epochs to train for. Default is 2000.
training_iterations : int
Number of times to repeat training process. Default is training_iterations.
Returns
-------
A trained word2vec model.
'''
se... | [
"Parameters",
"----------",
"epochs",
":",
"int",
"Number",
"of",
"epochs",
"to",
"train",
"for",
".",
"Default",
"is",
"2000",
".",
"training_iterations",
":",
"int",
"Number",
"of",
"times",
"to",
"repeat",
"training",
"process",
".",
"Default",
"is",
"tra... | JasonKessler/scattertext | python | https://github.com/JasonKessler/scattertext/blob/cacf1f687d218ee8cae3fc05cc901db824bb1b81/scattertext/representations/Word2VecFromParsedCorpus.py#L117-L136 | [
"def",
"train",
"(",
"self",
",",
"epochs",
"=",
"2000",
",",
"training_iterations",
"=",
"5",
")",
":",
"self",
".",
"_scan_and_build_vocab",
"(",
")",
"for",
"_",
"in",
"range",
"(",
"training_iterations",
")",
":",
"self",
".",
"model",
".",
"train",
... | cacf1f687d218ee8cae3fc05cc901db824bb1b81 |
train | DeployedClassifierFactory.passive_aggressive_train | Trains passive aggressive classifier | scattertext/DeployedClassifier.py | def passive_aggressive_train(self):
'''Trains passive aggressive classifier
'''
self._clf = PassiveAggressiveClassifier(n_iter=50, C=0.2, n_jobs=-1, random_state=0)
self._clf.fit(self._term_doc_matrix._X, self._term_doc_matrix._y)
y_dist = self._clf.decision_function(self._term_doc_matrix._X)
pos_ecdf = EC... | def passive_aggressive_train(self):
'''Trains passive aggressive classifier
'''
self._clf = PassiveAggressiveClassifier(n_iter=50, C=0.2, n_jobs=-1, random_state=0)
self._clf.fit(self._term_doc_matrix._X, self._term_doc_matrix._y)
y_dist = self._clf.decision_function(self._term_doc_matrix._X)
pos_ecdf = EC... | [
"Trains",
"passive",
"aggressive",
"classifier"
] | JasonKessler/scattertext | python | https://github.com/JasonKessler/scattertext/blob/cacf1f687d218ee8cae3fc05cc901db824bb1b81/scattertext/DeployedClassifier.py#L60-L78 | [
"def",
"passive_aggressive_train",
"(",
"self",
")",
":",
"self",
".",
"_clf",
"=",
"PassiveAggressiveClassifier",
"(",
"n_iter",
"=",
"50",
",",
"C",
"=",
"0.2",
",",
"n_jobs",
"=",
"-",
"1",
",",
"random_state",
"=",
"0",
")",
"self",
".",
"_clf",
".... | cacf1f687d218ee8cae3fc05cc901db824bb1b81 |
train | DeployedClassifierFactory.build | Builds Depoyed Classifier | scattertext/DeployedClassifier.py | def build(self):
'''Builds Depoyed Classifier
'''
if self._clf is None:
raise NeedToTrainExceptionBeforeDeployingException()
return DeployedClassifier(self._category,
self._term_doc_matrix._category_idx_store,
self._term_doc_matrix._term_idx_store,
... | def build(self):
'''Builds Depoyed Classifier
'''
if self._clf is None:
raise NeedToTrainExceptionBeforeDeployingException()
return DeployedClassifier(self._category,
self._term_doc_matrix._category_idx_store,
self._term_doc_matrix._term_idx_store,
... | [
"Builds",
"Depoyed",
"Classifier"
] | JasonKessler/scattertext | python | https://github.com/JasonKessler/scattertext/blob/cacf1f687d218ee8cae3fc05cc901db824bb1b81/scattertext/DeployedClassifier.py#L80-L88 | [
"def",
"build",
"(",
"self",
")",
":",
"if",
"self",
".",
"_clf",
"is",
"None",
":",
"raise",
"NeedToTrainExceptionBeforeDeployingException",
"(",
")",
"return",
"DeployedClassifier",
"(",
"self",
".",
"_category",
",",
"self",
".",
"_term_doc_matrix",
".",
"_... | cacf1f687d218ee8cae3fc05cc901db824bb1b81 |
train | IndexStoreFromDict.build | Parameters
----------
term_to_index_dict: term -> idx dictionary
Returns
-------
IndexStore | scattertext/indexstore/IndexStoreFromDict.py | def build(term_to_index_dict):
'''
Parameters
----------
term_to_index_dict: term -> idx dictionary
Returns
-------
IndexStore
'''
idxstore = IndexStore()
idxstore._val2i = term_to_index_dict
idxstore._next_i = len(term_to_index_dict)
idxstore._i2val = [None for _ in range(idxstore._next_i)]
... | def build(term_to_index_dict):
'''
Parameters
----------
term_to_index_dict: term -> idx dictionary
Returns
-------
IndexStore
'''
idxstore = IndexStore()
idxstore._val2i = term_to_index_dict
idxstore._next_i = len(term_to_index_dict)
idxstore._i2val = [None for _ in range(idxstore._next_i)]
... | [
"Parameters",
"----------",
"term_to_index_dict",
":",
"term",
"-",
">",
"idx",
"dictionary"
] | JasonKessler/scattertext | python | https://github.com/JasonKessler/scattertext/blob/cacf1f687d218ee8cae3fc05cc901db824bb1b81/scattertext/indexstore/IndexStoreFromDict.py#L6-L22 | [
"def",
"build",
"(",
"term_to_index_dict",
")",
":",
"idxstore",
"=",
"IndexStore",
"(",
")",
"idxstore",
".",
"_val2i",
"=",
"term_to_index_dict",
"idxstore",
".",
"_next_i",
"=",
"len",
"(",
"term_to_index_dict",
")",
"idxstore",
".",
"_i2val",
"=",
"[",
"... | cacf1f687d218ee8cae3fc05cc901db824bb1b81 |
train | CorpusFromScikit.build | Returns
-------
Corpus | scattertext/CorpusFromScikit.py | def build(self):
'''
Returns
-------
Corpus
'''
constructor_kwargs = self._get_build_kwargs()
if type(self.raw_texts) == list:
constructor_kwargs['raw_texts'] = np.array(self.raw_texts)
else:
constructor_kwargs['raw_texts'] = self.raw_texts
return Corpus(**constructor_kwargs) | def build(self):
'''
Returns
-------
Corpus
'''
constructor_kwargs = self._get_build_kwargs()
if type(self.raw_texts) == list:
constructor_kwargs['raw_texts'] = np.array(self.raw_texts)
else:
constructor_kwargs['raw_texts'] = self.raw_texts
return Corpus(**constructor_kwargs) | [
"Returns",
"-------",
"Corpus"
] | JasonKessler/scattertext | python | https://github.com/JasonKessler/scattertext/blob/cacf1f687d218ee8cae3fc05cc901db824bb1b81/scattertext/CorpusFromScikit.py#L46-L57 | [
"def",
"build",
"(",
"self",
")",
":",
"constructor_kwargs",
"=",
"self",
".",
"_get_build_kwargs",
"(",
")",
"if",
"type",
"(",
"self",
".",
"raw_texts",
")",
"==",
"list",
":",
"constructor_kwargs",
"[",
"'raw_texts'",
"]",
"=",
"np",
".",
"array",
"("... | cacf1f687d218ee8cae3fc05cc901db824bb1b81 |
train | LogOddsRatioInformativeDirichletPrior.get_zeta_i_j_given_separate_counts | Parameters
----------
y_i, np.array(int)
Arrays of word counts of words occurring in positive class
y_j, np.array(int)
Returns
-------
np.array of z-scores | scattertext/termsignificance/LogOddsRatioInformativeDirichletPiror.py | def get_zeta_i_j_given_separate_counts(self, y_i, y_j):
'''
Parameters
----------
y_i, np.array(int)
Arrays of word counts of words occurring in positive class
y_j, np.array(int)
Returns
-------
np.array of z-scores
'''
n_i, n_j = y_i.sum(), y_j.sum()
prior_scale_j = prior_scale_i = 1
if sel... | def get_zeta_i_j_given_separate_counts(self, y_i, y_j):
'''
Parameters
----------
y_i, np.array(int)
Arrays of word counts of words occurring in positive class
y_j, np.array(int)
Returns
-------
np.array of z-scores
'''
n_i, n_j = y_i.sum(), y_j.sum()
prior_scale_j = prior_scale_i = 1
if sel... | [
"Parameters",
"----------",
"y_i",
"np",
".",
"array",
"(",
"int",
")",
"Arrays",
"of",
"word",
"counts",
"of",
"words",
"occurring",
"in",
"positive",
"class",
"y_j",
"np",
".",
"array",
"(",
"int",
")"
] | JasonKessler/scattertext | python | https://github.com/JasonKessler/scattertext/blob/cacf1f687d218ee8cae3fc05cc901db824bb1b81/scattertext/termsignificance/LogOddsRatioInformativeDirichletPiror.py#L60-L95 | [
"def",
"get_zeta_i_j_given_separate_counts",
"(",
"self",
",",
"y_i",
",",
"y_j",
")",
":",
"n_i",
",",
"n_j",
"=",
"y_i",
".",
"sum",
"(",
")",
",",
"y_j",
".",
"sum",
"(",
")",
"prior_scale_j",
"=",
"prior_scale_i",
"=",
"1",
"if",
"self",
".",
"_s... | cacf1f687d218ee8cae3fc05cc901db824bb1b81 |
train | DomainCompactor.compact | Parameters
----------
term_doc_matrix : TermDocMatrix
Term document matrix object to compact
Returns
-------
New term doc matrix | scattertext/termcompaction/DomainCompactor.py | def compact(self, term_doc_matrix):
'''
Parameters
----------
term_doc_matrix : TermDocMatrix
Term document matrix object to compact
Returns
-------
New term doc matrix
'''
domain_mat = CombineDocsIntoDomains(term_doc_matrix).get_new_term_doc_mat(self.doc_domains)
domain_count = (domain_mat > 0)... | def compact(self, term_doc_matrix):
'''
Parameters
----------
term_doc_matrix : TermDocMatrix
Term document matrix object to compact
Returns
-------
New term doc matrix
'''
domain_mat = CombineDocsIntoDomains(term_doc_matrix).get_new_term_doc_mat(self.doc_domains)
domain_count = (domain_mat > 0)... | [
"Parameters",
"----------",
"term_doc_matrix",
":",
"TermDocMatrix",
"Term",
"document",
"matrix",
"object",
"to",
"compact"
] | JasonKessler/scattertext | python | https://github.com/JasonKessler/scattertext/blob/cacf1f687d218ee8cae3fc05cc901db824bb1b81/scattertext/termcompaction/DomainCompactor.py#L35-L51 | [
"def",
"compact",
"(",
"self",
",",
"term_doc_matrix",
")",
":",
"domain_mat",
"=",
"CombineDocsIntoDomains",
"(",
"term_doc_matrix",
")",
".",
"get_new_term_doc_mat",
"(",
"self",
".",
"doc_domains",
")",
"domain_count",
"=",
"(",
"domain_mat",
">",
"0",
")",
... | cacf1f687d218ee8cae3fc05cc901db824bb1b81 |
train | ParsedCorpus.get_texts | Returns
-------
pd.Series, all raw documents | scattertext/ParsedCorpus.py | def get_texts(self):
'''
Returns
-------
pd.Series, all raw documents
'''
if sys.version_info[0] == 2:
return self._df[self._parsed_col]
return self._df[self._parsed_col].apply(str) | def get_texts(self):
'''
Returns
-------
pd.Series, all raw documents
'''
if sys.version_info[0] == 2:
return self._df[self._parsed_col]
return self._df[self._parsed_col].apply(str) | [
"Returns",
"-------",
"pd",
".",
"Series",
"all",
"raw",
"documents"
] | JasonKessler/scattertext | python | https://github.com/JasonKessler/scattertext/blob/cacf1f687d218ee8cae3fc05cc901db824bb1b81/scattertext/ParsedCorpus.py#L43-L51 | [
"def",
"get_texts",
"(",
"self",
")",
":",
"if",
"sys",
".",
"version_info",
"[",
"0",
"]",
"==",
"2",
":",
"return",
"self",
".",
"_df",
"[",
"self",
".",
"_parsed_col",
"]",
"return",
"self",
".",
"_df",
"[",
"self",
".",
"_parsed_col",
"]",
".",... | cacf1f687d218ee8cae3fc05cc901db824bb1b81 |
train | ParsedCorpus.term_group_freq_df | Returns a dataframe indexed on the number of groups a term occured in.
Parameters
----------
group_col
Returns
-------
pd.DataFrame | scattertext/ParsedCorpus.py | def term_group_freq_df(self, group_col):
# type: (str) -> pd.DataFrame
'''
Returns a dataframe indexed on the number of groups a term occured in.
Parameters
----------
group_col
Returns
-------
pd.DataFrame
'''
group_idx_store = I... | def term_group_freq_df(self, group_col):
# type: (str) -> pd.DataFrame
'''
Returns a dataframe indexed on the number of groups a term occured in.
Parameters
----------
group_col
Returns
-------
pd.DataFrame
'''
group_idx_store = I... | [
"Returns",
"a",
"dataframe",
"indexed",
"on",
"the",
"number",
"of",
"groups",
"a",
"term",
"occured",
"in",
"."
] | JasonKessler/scattertext | python | https://github.com/JasonKessler/scattertext/blob/cacf1f687d218ee8cae3fc05cc901db824bb1b81/scattertext/ParsedCorpus.py#L100-L123 | [
"def",
"term_group_freq_df",
"(",
"self",
",",
"group_col",
")",
":",
"# type: (str) -> pd.DataFrame",
"group_idx_store",
"=",
"IndexStore",
"(",
")",
"X",
"=",
"self",
".",
"_X",
"group_idx_to_cat_idx",
",",
"row_group_cat",
"=",
"self",
".",
"_get_group_docids_and... | cacf1f687d218ee8cae3fc05cc901db824bb1b81 |
train | sparse_var | Compute variance from
:param X:
:return: | scattertext/termscoring/CorpusBasedTermScorer.py | def sparse_var(X):
'''
Compute variance from
:param X:
:return:
'''
Xc = X.copy()
Xc.data **= 2
return np.array(Xc.mean(axis=0) - np.power(X.mean(axis=0), 2))[0] | def sparse_var(X):
'''
Compute variance from
:param X:
:return:
'''
Xc = X.copy()
Xc.data **= 2
return np.array(Xc.mean(axis=0) - np.power(X.mean(axis=0), 2))[0] | [
"Compute",
"variance",
"from",
":",
"param",
"X",
":",
":",
"return",
":"
] | JasonKessler/scattertext | python | https://github.com/JasonKessler/scattertext/blob/cacf1f687d218ee8cae3fc05cc901db824bb1b81/scattertext/termscoring/CorpusBasedTermScorer.py#L17-L25 | [
"def",
"sparse_var",
"(",
"X",
")",
":",
"Xc",
"=",
"X",
".",
"copy",
"(",
")",
"Xc",
".",
"data",
"**=",
"2",
"return",
"np",
".",
"array",
"(",
"Xc",
".",
"mean",
"(",
"axis",
"=",
"0",
")",
"-",
"np",
".",
"power",
"(",
"X",
".",
"mean",... | cacf1f687d218ee8cae3fc05cc901db824bb1b81 |
train | CorpusBasedTermScorer.set_categories | Specify the category to score. Optionally, score against a specific set of categories. | scattertext/termscoring/CorpusBasedTermScorer.py | def set_categories(self,
category_name,
not_category_names=[],
neutral_category_names=[]):
'''
Specify the category to score. Optionally, score against a specific set of categories.
'''
tdf = self.term_ranker_.get_ranks... | def set_categories(self,
category_name,
not_category_names=[],
neutral_category_names=[]):
'''
Specify the category to score. Optionally, score against a specific set of categories.
'''
tdf = self.term_ranker_.get_ranks... | [
"Specify",
"the",
"category",
"to",
"score",
".",
"Optionally",
"score",
"against",
"a",
"specific",
"set",
"of",
"categories",
"."
] | JasonKessler/scattertext | python | https://github.com/JasonKessler/scattertext/blob/cacf1f687d218ee8cae3fc05cc901db824bb1b81/scattertext/termscoring/CorpusBasedTermScorer.py#L61-L89 | [
"def",
"set_categories",
"(",
"self",
",",
"category_name",
",",
"not_category_names",
"=",
"[",
"]",
",",
"neutral_category_names",
"=",
"[",
"]",
")",
":",
"tdf",
"=",
"self",
".",
"term_ranker_",
".",
"get_ranks",
"(",
")",
"d",
"=",
"{",
"'cat'",
":"... | cacf1f687d218ee8cae3fc05cc901db824bb1b81 |
train | CorpusBasedTermScorer.get_t_statistics | In this case, parameters a and b aren't used, since this information is taken
directly from the corpus categories.
Returns
------- | scattertext/termscoring/CorpusBasedTermScorer.py | def get_t_statistics(self):
'''
In this case, parameters a and b aren't used, since this information is taken
directly from the corpus categories.
Returns
-------
'''
X = self._get_X()
cat_X, ncat_X = self._get_cat_and_ncat(X)
mean_delta = self... | def get_t_statistics(self):
'''
In this case, parameters a and b aren't used, since this information is taken
directly from the corpus categories.
Returns
-------
'''
X = self._get_X()
cat_X, ncat_X = self._get_cat_and_ncat(X)
mean_delta = self... | [
"In",
"this",
"case",
"parameters",
"a",
"and",
"b",
"aren",
"t",
"used",
"since",
"this",
"information",
"is",
"taken",
"directly",
"from",
"the",
"corpus",
"categories",
"."
] | JasonKessler/scattertext | python | https://github.com/JasonKessler/scattertext/blob/cacf1f687d218ee8cae3fc05cc901db824bb1b81/scattertext/termscoring/CorpusBasedTermScorer.py#L94-L127 | [
"def",
"get_t_statistics",
"(",
"self",
")",
":",
"X",
"=",
"self",
".",
"_get_X",
"(",
")",
"cat_X",
",",
"ncat_X",
"=",
"self",
".",
"_get_cat_and_ncat",
"(",
"X",
")",
"mean_delta",
"=",
"self",
".",
"_get_mean_delta",
"(",
"cat_X",
",",
"ncat_X",
"... | cacf1f687d218ee8cae3fc05cc901db824bb1b81 |
train | CorpusFromPandas._apply_pipeline_and_get_build_instance | Parameters
----------
X_factory
mX_factory
category_idx_store
df
parse_pipeline
term_idx_store
metadata_idx_store
y
Returns
-------
CorpusDF | scattertext/CorpusFromPandas.py | def _apply_pipeline_and_get_build_instance(self,
X_factory,
mX_factory,
category_idx_store,
df,
pars... | def _apply_pipeline_and_get_build_instance(self,
X_factory,
mX_factory,
category_idx_store,
df,
pars... | [
"Parameters",
"----------",
"X_factory",
"mX_factory",
"category_idx_store",
"df",
"parse_pipeline",
"term_idx_store",
"metadata_idx_store",
"y"
] | JasonKessler/scattertext | python | https://github.com/JasonKessler/scattertext/blob/cacf1f687d218ee8cae3fc05cc901db824bb1b81/scattertext/CorpusFromPandas.py#L32-L67 | [
"def",
"_apply_pipeline_and_get_build_instance",
"(",
"self",
",",
"X_factory",
",",
"mX_factory",
",",
"category_idx_store",
",",
"df",
",",
"parse_pipeline",
",",
"term_idx_store",
",",
"metadata_idx_store",
",",
"y",
")",
":",
"df",
".",
"apply",
"(",
"parse_pi... | cacf1f687d218ee8cae3fc05cc901db824bb1b81 |
train | TermDocMatrixWithoutCategories.set_background_corpus | Parameters
----------
background | scattertext/TermDocMatrixWithoutCategories.py | def set_background_corpus(self, background):
'''
Parameters
----------
background
'''
if issubclass(type(background), TermDocMatrixWithoutCategories):
self._background_corpus = pd.DataFrame(background
.get_te... | def set_background_corpus(self, background):
'''
Parameters
----------
background
'''
if issubclass(type(background), TermDocMatrixWithoutCategories):
self._background_corpus = pd.DataFrame(background
.get_te... | [
"Parameters",
"----------",
"background"
] | JasonKessler/scattertext | python | https://github.com/JasonKessler/scattertext/blob/cacf1f687d218ee8cae3fc05cc901db824bb1b81/scattertext/TermDocMatrixWithoutCategories.py#L101-L120 | [
"def",
"set_background_corpus",
"(",
"self",
",",
"background",
")",
":",
"if",
"issubclass",
"(",
"type",
"(",
"background",
")",
",",
"TermDocMatrixWithoutCategories",
")",
":",
"self",
".",
"_background_corpus",
"=",
"pd",
".",
"DataFrame",
"(",
"background",... | cacf1f687d218ee8cae3fc05cc901db824bb1b81 |
train | TermDocMatrixWithoutCategories.get_term_and_background_counts | Returns
-------
A pd.DataFrame consisting of unigram term counts of words occurring
in the TermDocumentMatrix and their corresponding background corpus
counts. The dataframe has two columns, corpus and background.
>>> corpus.get_unigram_corpus().get_term_and_background_counts... | scattertext/TermDocMatrixWithoutCategories.py | def get_term_and_background_counts(self):
'''
Returns
-------
A pd.DataFrame consisting of unigram term counts of words occurring
in the TermDocumentMatrix and their corresponding background corpus
counts. The dataframe has two columns, corpus and background.
... | def get_term_and_background_counts(self):
'''
Returns
-------
A pd.DataFrame consisting of unigram term counts of words occurring
in the TermDocumentMatrix and their corresponding background corpus
counts. The dataframe has two columns, corpus and background.
... | [
"Returns",
"-------",
"A",
"pd",
".",
"DataFrame",
"consisting",
"of",
"unigram",
"term",
"counts",
"of",
"words",
"occurring",
"in",
"the",
"TermDocumentMatrix",
"and",
"their",
"corresponding",
"background",
"corpus",
"counts",
".",
"The",
"dataframe",
"has",
... | JasonKessler/scattertext | python | https://github.com/JasonKessler/scattertext/blob/cacf1f687d218ee8cae3fc05cc901db824bb1b81/scattertext/TermDocMatrixWithoutCategories.py#L127-L147 | [
"def",
"get_term_and_background_counts",
"(",
"self",
")",
":",
"background_df",
"=",
"self",
".",
"_get_background_unigram_frequencies",
"(",
")",
"corpus_freq_df",
"=",
"self",
".",
"get_term_count_df",
"(",
")",
"corpus_unigram_freq",
"=",
"self",
".",
"_get_corpus... | cacf1f687d218ee8cae3fc05cc901db824bb1b81 |
train | TermDocMatrixWithoutCategories.list_extra_features | Returns
-------
List of dicts. One dict for each document, keys are metadata, values are counts | scattertext/TermDocMatrixWithoutCategories.py | def list_extra_features(self):
'''
Returns
-------
List of dicts. One dict for each document, keys are metadata, values are counts
'''
return FeatureLister(self._mX,
self._metadata_idx_store,
self.get_num_docs()).... | def list_extra_features(self):
'''
Returns
-------
List of dicts. One dict for each document, keys are metadata, values are counts
'''
return FeatureLister(self._mX,
self._metadata_idx_store,
self.get_num_docs()).... | [
"Returns",
"-------",
"List",
"of",
"dicts",
".",
"One",
"dict",
"for",
"each",
"document",
"keys",
"are",
"metadata",
"values",
"are",
"counts"
] | JasonKessler/scattertext | python | https://github.com/JasonKessler/scattertext/blob/cacf1f687d218ee8cae3fc05cc901db824bb1b81/scattertext/TermDocMatrixWithoutCategories.py#L164-L172 | [
"def",
"list_extra_features",
"(",
"self",
")",
":",
"return",
"FeatureLister",
"(",
"self",
".",
"_mX",
",",
"self",
".",
"_metadata_idx_store",
",",
"self",
".",
"get_num_docs",
"(",
")",
")",
".",
"output",
"(",
")"
] | cacf1f687d218ee8cae3fc05cc901db824bb1b81 |
train | TermDocMatrixWithoutCategories.remove_infrequent_words | Returns
-------
A new TermDocumentMatrix consisting of only terms which occur at least minimum_term_count. | scattertext/TermDocMatrixWithoutCategories.py | def remove_infrequent_words(self, minimum_term_count, term_ranker=AbsoluteFrequencyRanker):
'''
Returns
-------
A new TermDocumentMatrix consisting of only terms which occur at least minimum_term_count.
'''
tdf = term_ranker(self).get_ranks().sum(axis=1)
return se... | def remove_infrequent_words(self, minimum_term_count, term_ranker=AbsoluteFrequencyRanker):
'''
Returns
-------
A new TermDocumentMatrix consisting of only terms which occur at least minimum_term_count.
'''
tdf = term_ranker(self).get_ranks().sum(axis=1)
return se... | [
"Returns",
"-------",
"A",
"new",
"TermDocumentMatrix",
"consisting",
"of",
"only",
"terms",
"which",
"occur",
"at",
"least",
"minimum_term_count",
"."
] | JasonKessler/scattertext | python | https://github.com/JasonKessler/scattertext/blob/cacf1f687d218ee8cae3fc05cc901db824bb1b81/scattertext/TermDocMatrixWithoutCategories.py#L204-L211 | [
"def",
"remove_infrequent_words",
"(",
"self",
",",
"minimum_term_count",
",",
"term_ranker",
"=",
"AbsoluteFrequencyRanker",
")",
":",
"tdf",
"=",
"term_ranker",
"(",
"self",
")",
".",
"get_ranks",
"(",
")",
".",
"sum",
"(",
"axis",
"=",
"1",
")",
"return",... | cacf1f687d218ee8cae3fc05cc901db824bb1b81 |
train | TermDocMatrixWithoutCategories.remove_entity_tags | Returns
-------
A new TermDocumentMatrix consisting of only terms in the current TermDocumentMatrix
that aren't spaCy entity tags.
Note: Used if entity types are censored using FeatsFromSpacyDoc(tag_types_to_censor=...). | scattertext/TermDocMatrixWithoutCategories.py | def remove_entity_tags(self):
'''
Returns
-------
A new TermDocumentMatrix consisting of only terms in the current TermDocumentMatrix
that aren't spaCy entity tags.
Note: Used if entity types are censored using FeatsFromSpacyDoc(tag_types_to_censor=...).
'''
... | def remove_entity_tags(self):
'''
Returns
-------
A new TermDocumentMatrix consisting of only terms in the current TermDocumentMatrix
that aren't spaCy entity tags.
Note: Used if entity types are censored using FeatsFromSpacyDoc(tag_types_to_censor=...).
'''
... | [
"Returns",
"-------",
"A",
"new",
"TermDocumentMatrix",
"consisting",
"of",
"only",
"terms",
"in",
"the",
"current",
"TermDocumentMatrix",
"that",
"aren",
"t",
"spaCy",
"entity",
"tags",
"."
] | JasonKessler/scattertext | python | https://github.com/JasonKessler/scattertext/blob/cacf1f687d218ee8cae3fc05cc901db824bb1b81/scattertext/TermDocMatrixWithoutCategories.py#L213-L224 | [
"def",
"remove_entity_tags",
"(",
"self",
")",
":",
"terms_to_remove",
"=",
"[",
"term",
"for",
"term",
"in",
"self",
".",
"_term_idx_store",
".",
"_i2val",
"if",
"any",
"(",
"[",
"word",
"in",
"SPACY_ENTITY_TAGS",
"for",
"word",
"in",
"term",
".",
"split"... | cacf1f687d218ee8cae3fc05cc901db824bb1b81 |
train | TermDocMatrixWithoutCategories.remove_terms | Non destructive term removal.
Parameters
----------
terms : list
list of terms to remove
ignore_absences : bool, False by default
if term does not appear, don't raise an error, just move on.
Returns
-------
TermDocMatrix, new object with ... | scattertext/TermDocMatrixWithoutCategories.py | def remove_terms(self, terms, ignore_absences=False):
'''Non destructive term removal.
Parameters
----------
terms : list
list of terms to remove
ignore_absences : bool, False by default
if term does not appear, don't raise an error, just move on.
... | def remove_terms(self, terms, ignore_absences=False):
'''Non destructive term removal.
Parameters
----------
terms : list
list of terms to remove
ignore_absences : bool, False by default
if term does not appear, don't raise an error, just move on.
... | [
"Non",
"destructive",
"term",
"removal",
"."
] | JasonKessler/scattertext | python | https://github.com/JasonKessler/scattertext/blob/cacf1f687d218ee8cae3fc05cc901db824bb1b81/scattertext/TermDocMatrixWithoutCategories.py#L226-L241 | [
"def",
"remove_terms",
"(",
"self",
",",
"terms",
",",
"ignore_absences",
"=",
"False",
")",
":",
"idx_to_delete_list",
"=",
"self",
".",
"_build_term_index_list",
"(",
"ignore_absences",
",",
"terms",
")",
"return",
"self",
".",
"remove_terms_by_indices",
"(",
... | cacf1f687d218ee8cae3fc05cc901db824bb1b81 |
train | TermDocMatrixWithoutCategories.remove_terms_used_in_less_than_num_docs | Parameters
----------
threshold: int
Minimum number of documents term should appear in to be kept
Returns
-------
TermDocMatrix, new object with terms removed. | scattertext/TermDocMatrixWithoutCategories.py | def remove_terms_used_in_less_than_num_docs(self, threshold):
'''
Parameters
----------
threshold: int
Minimum number of documents term should appear in to be kept
Returns
-------
TermDocMatrix, new object with terms removed.
'''
term_... | def remove_terms_used_in_less_than_num_docs(self, threshold):
'''
Parameters
----------
threshold: int
Minimum number of documents term should appear in to be kept
Returns
-------
TermDocMatrix, new object with terms removed.
'''
term_... | [
"Parameters",
"----------",
"threshold",
":",
"int",
"Minimum",
"number",
"of",
"documents",
"term",
"should",
"appear",
"in",
"to",
"be",
"kept"
] | JasonKessler/scattertext | python | https://github.com/JasonKessler/scattertext/blob/cacf1f687d218ee8cae3fc05cc901db824bb1b81/scattertext/TermDocMatrixWithoutCategories.py#L268-L281 | [
"def",
"remove_terms_used_in_less_than_num_docs",
"(",
"self",
",",
"threshold",
")",
":",
"term_counts",
"=",
"self",
".",
"_X",
".",
"astype",
"(",
"bool",
")",
".",
"astype",
"(",
"int",
")",
".",
"sum",
"(",
"axis",
"=",
"0",
")",
".",
"A",
"[",
... | cacf1f687d218ee8cae3fc05cc901db824bb1b81 |
train | TermDocMatrixWithoutCategories.get_stoplisted_unigram_corpus | Parameters
-------
stoplist : list, optional
Returns
-------
A new TermDocumentMatrix consisting of only unigrams in the current TermDocumentMatrix. | scattertext/TermDocMatrixWithoutCategories.py | def get_stoplisted_unigram_corpus(self, stoplist=None):
'''
Parameters
-------
stoplist : list, optional
Returns
-------
A new TermDocumentMatrix consisting of only unigrams in the current TermDocumentMatrix.
'''
if stoplist is None:
s... | def get_stoplisted_unigram_corpus(self, stoplist=None):
'''
Parameters
-------
stoplist : list, optional
Returns
-------
A new TermDocumentMatrix consisting of only unigrams in the current TermDocumentMatrix.
'''
if stoplist is None:
s... | [
"Parameters",
"-------",
"stoplist",
":",
"list",
"optional"
] | JasonKessler/scattertext | python | https://github.com/JasonKessler/scattertext/blob/cacf1f687d218ee8cae3fc05cc901db824bb1b81/scattertext/TermDocMatrixWithoutCategories.py#L298-L312 | [
"def",
"get_stoplisted_unigram_corpus",
"(",
"self",
",",
"stoplist",
"=",
"None",
")",
":",
"if",
"stoplist",
"is",
"None",
":",
"stoplist",
"=",
"self",
".",
"get_default_stoplist",
"(",
")",
"else",
":",
"stoplist",
"=",
"[",
"w",
".",
"lower",
"(",
"... | cacf1f687d218ee8cae3fc05cc901db824bb1b81 |
train | TermDocMatrixWithoutCategories.get_stoplisted_unigram_corpus_and_custom | Parameters
-------
stoplist : list of lower-cased words, optional
Returns
-------
A new TermDocumentMatrix consisting of only unigrams in the current TermDocumentMatrix. | scattertext/TermDocMatrixWithoutCategories.py | def get_stoplisted_unigram_corpus_and_custom(self,
custom_stoplist):
'''
Parameters
-------
stoplist : list of lower-cased words, optional
Returns
-------
A new TermDocumentMatrix consisting of only unigrams in the... | def get_stoplisted_unigram_corpus_and_custom(self,
custom_stoplist):
'''
Parameters
-------
stoplist : list of lower-cased words, optional
Returns
-------
A new TermDocumentMatrix consisting of only unigrams in the... | [
"Parameters",
"-------",
"stoplist",
":",
"list",
"of",
"lower",
"-",
"cased",
"words",
"optional"
] | JasonKessler/scattertext | python | https://github.com/JasonKessler/scattertext/blob/cacf1f687d218ee8cae3fc05cc901db824bb1b81/scattertext/TermDocMatrixWithoutCategories.py#L314-L328 | [
"def",
"get_stoplisted_unigram_corpus_and_custom",
"(",
"self",
",",
"custom_stoplist",
")",
":",
"if",
"type",
"(",
"custom_stoplist",
")",
"==",
"str",
":",
"custom_stoplist",
"=",
"[",
"custom_stoplist",
"]",
"return",
"self",
".",
"_remove_terms_from_list",
"(",... | cacf1f687d218ee8cae3fc05cc901db824bb1b81 |
train | TermDocMatrixWithoutCategories.get_doc_lengths | Returns a list of document lengths in words
Returns
-------
np.array | scattertext/TermDocMatrixWithoutCategories.py | def get_doc_lengths(self):
'''
Returns a list of document lengths in words
Returns
-------
np.array
'''
idx_to_delete_list = self._build_term_index_list(True, self._get_non_unigrams())
unigram_X, _ = self._get_X_after_delete_terms(idx_to_delete_list)
... | def get_doc_lengths(self):
'''
Returns a list of document lengths in words
Returns
-------
np.array
'''
idx_to_delete_list = self._build_term_index_list(True, self._get_non_unigrams())
unigram_X, _ = self._get_X_after_delete_terms(idx_to_delete_list)
... | [
"Returns",
"a",
"list",
"of",
"document",
"lengths",
"in",
"words"
] | JasonKessler/scattertext | python | https://github.com/JasonKessler/scattertext/blob/cacf1f687d218ee8cae3fc05cc901db824bb1b81/scattertext/TermDocMatrixWithoutCategories.py#L351-L361 | [
"def",
"get_doc_lengths",
"(",
"self",
")",
":",
"idx_to_delete_list",
"=",
"self",
".",
"_build_term_index_list",
"(",
"True",
",",
"self",
".",
"_get_non_unigrams",
"(",
")",
")",
"unigram_X",
",",
"_",
"=",
"self",
".",
"_get_X_after_delete_terms",
"(",
"id... | cacf1f687d218ee8cae3fc05cc901db824bb1b81 |
train | TermDocMatrixWithoutCategories.remove_terms_by_indices | Parameters
----------
idx_to_delete_list, list
Returns
-------
TermDocMatrix | scattertext/TermDocMatrixWithoutCategories.py | def remove_terms_by_indices(self, idx_to_delete_list):
'''
Parameters
----------
idx_to_delete_list, list
Returns
-------
TermDocMatrix
'''
new_X, new_term_idx_store = self._get_X_after_delete_terms(idx_to_delete_list)
return self._make_n... | def remove_terms_by_indices(self, idx_to_delete_list):
'''
Parameters
----------
idx_to_delete_list, list
Returns
-------
TermDocMatrix
'''
new_X, new_term_idx_store = self._get_X_after_delete_terms(idx_to_delete_list)
return self._make_n... | [
"Parameters",
"----------",
"idx_to_delete_list",
"list"
] | JasonKessler/scattertext | python | https://github.com/JasonKessler/scattertext/blob/cacf1f687d218ee8cae3fc05cc901db824bb1b81/scattertext/TermDocMatrixWithoutCategories.py#L363-L381 | [
"def",
"remove_terms_by_indices",
"(",
"self",
",",
"idx_to_delete_list",
")",
":",
"new_X",
",",
"new_term_idx_store",
"=",
"self",
".",
"_get_X_after_delete_terms",
"(",
"idx_to_delete_list",
")",
"return",
"self",
".",
"_make_new_term_doc_matrix",
"(",
"new_X",
"="... | cacf1f687d218ee8cae3fc05cc901db824bb1b81 |
train | TermDocMatrixWithoutCategories.term_doc_lists | Returns
-------
dict | scattertext/TermDocMatrixWithoutCategories.py | def term_doc_lists(self):
'''
Returns
-------
dict
'''
doc_ids = self._X.transpose().tolil().rows
terms = self._term_idx_store.values()
return dict(zip(terms, doc_ids)) | def term_doc_lists(self):
'''
Returns
-------
dict
'''
doc_ids = self._X.transpose().tolil().rows
terms = self._term_idx_store.values()
return dict(zip(terms, doc_ids)) | [
"Returns",
"-------",
"dict"
] | JasonKessler/scattertext | python | https://github.com/JasonKessler/scattertext/blob/cacf1f687d218ee8cae3fc05cc901db824bb1b81/scattertext/TermDocMatrixWithoutCategories.py#L423-L431 | [
"def",
"term_doc_lists",
"(",
"self",
")",
":",
"doc_ids",
"=",
"self",
".",
"_X",
".",
"transpose",
"(",
")",
".",
"tolil",
"(",
")",
".",
"rows",
"terms",
"=",
"self",
".",
"_term_idx_store",
".",
"values",
"(",
")",
"return",
"dict",
"(",
"zip",
... | cacf1f687d218ee8cae3fc05cc901db824bb1b81 |
train | TermDocMatrixWithoutCategories.apply_ranker | Parameters
----------
term_ranker : TermRanker
Returns
-------
pd.Dataframe | scattertext/TermDocMatrixWithoutCategories.py | def apply_ranker(self, term_ranker, use_non_text_features):
'''
Parameters
----------
term_ranker : TermRanker
Returns
-------
pd.Dataframe
'''
if use_non_text_features:
return term_ranker(self).use_non_text_features().get_ranks()
... | def apply_ranker(self, term_ranker, use_non_text_features):
'''
Parameters
----------
term_ranker : TermRanker
Returns
-------
pd.Dataframe
'''
if use_non_text_features:
return term_ranker(self).use_non_text_features().get_ranks()
... | [
"Parameters",
"----------",
"term_ranker",
":",
"TermRanker"
] | JasonKessler/scattertext | python | https://github.com/JasonKessler/scattertext/blob/cacf1f687d218ee8cae3fc05cc901db824bb1b81/scattertext/TermDocMatrixWithoutCategories.py#L433-L445 | [
"def",
"apply_ranker",
"(",
"self",
",",
"term_ranker",
",",
"use_non_text_features",
")",
":",
"if",
"use_non_text_features",
":",
"return",
"term_ranker",
"(",
"self",
")",
".",
"use_non_text_features",
"(",
")",
".",
"get_ranks",
"(",
")",
"return",
"term_ran... | cacf1f687d218ee8cae3fc05cc901db824bb1b81 |
train | TermDocMatrixWithoutCategories.add_doc_names_as_metadata | :param doc_names: array-like[str], document names of reach document
:return: Corpus-like object with doc names as metadata. If two documents share the same name
(doc number) will be appended to their names. | scattertext/TermDocMatrixWithoutCategories.py | def add_doc_names_as_metadata(self, doc_names):
'''
:param doc_names: array-like[str], document names of reach document
:return: Corpus-like object with doc names as metadata. If two documents share the same name
(doc number) will be appended to their names.
'''
if len(do... | def add_doc_names_as_metadata(self, doc_names):
'''
:param doc_names: array-like[str], document names of reach document
:return: Corpus-like object with doc names as metadata. If two documents share the same name
(doc number) will be appended to their names.
'''
if len(do... | [
":",
"param",
"doc_names",
":",
"array",
"-",
"like",
"[",
"str",
"]",
"document",
"names",
"of",
"reach",
"document",
":",
"return",
":",
"Corpus",
"-",
"like",
"object",
"with",
"doc",
"names",
"as",
"metadata",
".",
"If",
"two",
"documents",
"share",
... | JasonKessler/scattertext | python | https://github.com/JasonKessler/scattertext/blob/cacf1f687d218ee8cae3fc05cc901db824bb1b81/scattertext/TermDocMatrixWithoutCategories.py#L447-L469 | [
"def",
"add_doc_names_as_metadata",
"(",
"self",
",",
"doc_names",
")",
":",
"if",
"len",
"(",
"doc_names",
")",
"!=",
"self",
".",
"get_num_docs",
"(",
")",
":",
"raise",
"Exception",
"(",
"\"The parameter doc_names contains %s elements. \"",
"\"It should have %s ele... | cacf1f687d218ee8cae3fc05cc901db824bb1b81 |
train | TermDocMatrixWithoutCategories.add_metadata | Returns a new corpus with a the metadata matrix and index store integrated.
:param metadata_matrix: scipy.sparse matrix (# docs, # metadata)
:param meta_index_store: IndexStore of metadata values
:return: TermDocMatrixWithoutCategories | scattertext/TermDocMatrixWithoutCategories.py | def add_metadata(self, metadata_matrix, meta_index_store):
'''
Returns a new corpus with a the metadata matrix and index store integrated.
:param metadata_matrix: scipy.sparse matrix (# docs, # metadata)
:param meta_index_store: IndexStore of metadata values
:return: TermDocMatr... | def add_metadata(self, metadata_matrix, meta_index_store):
'''
Returns a new corpus with a the metadata matrix and index store integrated.
:param metadata_matrix: scipy.sparse matrix (# docs, # metadata)
:param meta_index_store: IndexStore of metadata values
:return: TermDocMatr... | [
"Returns",
"a",
"new",
"corpus",
"with",
"a",
"the",
"metadata",
"matrix",
"and",
"index",
"store",
"integrated",
"."
] | JasonKessler/scattertext | python | https://github.com/JasonKessler/scattertext/blob/cacf1f687d218ee8cae3fc05cc901db824bb1b81/scattertext/TermDocMatrixWithoutCategories.py#L471-L488 | [
"def",
"add_metadata",
"(",
"self",
",",
"metadata_matrix",
",",
"meta_index_store",
")",
":",
"assert",
"isinstance",
"(",
"meta_index_store",
",",
"IndexStore",
")",
"assert",
"len",
"(",
"metadata_matrix",
".",
"shape",
")",
"==",
"2",
"assert",
"metadata_mat... | cacf1f687d218ee8cae3fc05cc901db824bb1b81 |
train | FeatsFromSpacyDoc.get_feats | Parameters
----------
doc, Spacy Docs
Returns
-------
Counter (unigram, bigram) -> count | scattertext/features/FeatsFromSpacyDoc.py | def get_feats(self, doc):
'''
Parameters
----------
doc, Spacy Docs
Returns
-------
Counter (unigram, bigram) -> count
'''
ngram_counter = Counter()
for sent in doc.sents:
unigrams = self._get_unigram_feats(sent)
bigrams = self._get_bigram_feats(unigrams)
ngram_counter += Counter(chain(uni... | def get_feats(self, doc):
'''
Parameters
----------
doc, Spacy Docs
Returns
-------
Counter (unigram, bigram) -> count
'''
ngram_counter = Counter()
for sent in doc.sents:
unigrams = self._get_unigram_feats(sent)
bigrams = self._get_bigram_feats(unigrams)
ngram_counter += Counter(chain(uni... | [
"Parameters",
"----------",
"doc",
"Spacy",
"Docs"
] | JasonKessler/scattertext | python | https://github.com/JasonKessler/scattertext/blob/cacf1f687d218ee8cae3fc05cc901db824bb1b81/scattertext/features/FeatsFromSpacyDoc.py#L38-L53 | [
"def",
"get_feats",
"(",
"self",
",",
"doc",
")",
":",
"ngram_counter",
"=",
"Counter",
"(",
")",
"for",
"sent",
"in",
"doc",
".",
"sents",
":",
"unigrams",
"=",
"self",
".",
"_get_unigram_feats",
"(",
"sent",
")",
"bigrams",
"=",
"self",
".",
"_get_bi... | cacf1f687d218ee8cae3fc05cc901db824bb1b81 |
train | MannWhitneyU.get_score_df | Computes Mann Whitney corrected p, z-values. Falls back to normal approximation when numerical limits are reached.
:param correction_method: str or None, correction method from statsmodels.stats.multitest.multipletests
'fdr_bh' is recommended.
:return: pd.DataFrame | scattertext/termscoring/MannWhitneyU.py | def get_score_df(self, correction_method=None):
'''
Computes Mann Whitney corrected p, z-values. Falls back to normal approximation when numerical limits are reached.
:param correction_method: str or None, correction method from statsmodels.stats.multitest.multipletests
'fdr_bh' is re... | def get_score_df(self, correction_method=None):
'''
Computes Mann Whitney corrected p, z-values. Falls back to normal approximation when numerical limits are reached.
:param correction_method: str or None, correction method from statsmodels.stats.multitest.multipletests
'fdr_bh' is re... | [
"Computes",
"Mann",
"Whitney",
"corrected",
"p",
"z",
"-",
"values",
".",
"Falls",
"back",
"to",
"normal",
"approximation",
"when",
"numerical",
"limits",
"are",
"reached",
"."
] | JasonKessler/scattertext | python | https://github.com/JasonKessler/scattertext/blob/cacf1f687d218ee8cae3fc05cc901db824bb1b81/scattertext/termscoring/MannWhitneyU.py#L35-L87 | [
"def",
"get_score_df",
"(",
"self",
",",
"correction_method",
"=",
"None",
")",
":",
"X",
"=",
"self",
".",
"_get_X",
"(",
")",
".",
"astype",
"(",
"np",
".",
"float64",
")",
"X",
"=",
"X",
"/",
"X",
".",
"sum",
"(",
"axis",
"=",
"1",
")",
"cat... | cacf1f687d218ee8cae3fc05cc901db824bb1b81 |
train | AutoTermSelector.reduce_terms | Parameters
----------
term_doc_matrix: TermDocMatrix or descendant
scores: array-like
Same length as number of terms in TermDocMatrix.
num_term_to_keep: int, default=4000.
Should be> 0. Number of terms to keep. Will keep between num_terms_to_keep/2 and num_terms_to_keep.
Returns
-------
TermDocMatr... | scattertext/AutoTermSelector.py | def reduce_terms(term_doc_matrix, scores, num_term_to_keep=None):
'''
Parameters
----------
term_doc_matrix: TermDocMatrix or descendant
scores: array-like
Same length as number of terms in TermDocMatrix.
num_term_to_keep: int, default=4000.
Should be> 0. Number of terms to keep. Will keep between num... | def reduce_terms(term_doc_matrix, scores, num_term_to_keep=None):
'''
Parameters
----------
term_doc_matrix: TermDocMatrix or descendant
scores: array-like
Same length as number of terms in TermDocMatrix.
num_term_to_keep: int, default=4000.
Should be> 0. Number of terms to keep. Will keep between num... | [
"Parameters",
"----------",
"term_doc_matrix",
":",
"TermDocMatrix",
"or",
"descendant",
"scores",
":",
"array",
"-",
"like",
"Same",
"length",
"as",
"number",
"of",
"terms",
"in",
"TermDocMatrix",
".",
"num_term_to_keep",
":",
"int",
"default",
"=",
"4000",
"."... | JasonKessler/scattertext | python | https://github.com/JasonKessler/scattertext/blob/cacf1f687d218ee8cae3fc05cc901db824bb1b81/scattertext/AutoTermSelector.py#L11-L28 | [
"def",
"reduce_terms",
"(",
"term_doc_matrix",
",",
"scores",
",",
"num_term_to_keep",
"=",
"None",
")",
":",
"terms_to_show",
"=",
"AutoTermSelector",
".",
"get_selected_terms",
"(",
"term_doc_matrix",
",",
"scores",
",",
"num_term_to_keep",
")",
"return",
"term_do... | cacf1f687d218ee8cae3fc05cc901db824bb1b81 |
train | AutoTermSelector.get_selected_terms | Parameters
----------
term_doc_matrix: TermDocMatrix or descendant
scores: array-like
Same length as number of terms in TermDocMatrix.
num_term_to_keep: int, default=4000.
Should be> 0. Number of terms to keep. Will keep between num_terms_to_keep/2 and num_terms_to_keep.
Returns
-------
set, terms ... | scattertext/AutoTermSelector.py | def get_selected_terms(term_doc_matrix, scores, num_term_to_keep=None):
'''
Parameters
----------
term_doc_matrix: TermDocMatrix or descendant
scores: array-like
Same length as number of terms in TermDocMatrix.
num_term_to_keep: int, default=4000.
Should be> 0. Number of terms to keep. Will keep betwe... | def get_selected_terms(term_doc_matrix, scores, num_term_to_keep=None):
'''
Parameters
----------
term_doc_matrix: TermDocMatrix or descendant
scores: array-like
Same length as number of terms in TermDocMatrix.
num_term_to_keep: int, default=4000.
Should be> 0. Number of terms to keep. Will keep betwe... | [
"Parameters",
"----------",
"term_doc_matrix",
":",
"TermDocMatrix",
"or",
"descendant",
"scores",
":",
"array",
"-",
"like",
"Same",
"length",
"as",
"number",
"of",
"terms",
"in",
"TermDocMatrix",
".",
"num_term_to_keep",
":",
"int",
"default",
"=",
"4000",
"."... | JasonKessler/scattertext | python | https://github.com/JasonKessler/scattertext/blob/cacf1f687d218ee8cae3fc05cc901db824bb1b81/scattertext/AutoTermSelector.py#L31-L53 | [
"def",
"get_selected_terms",
"(",
"term_doc_matrix",
",",
"scores",
",",
"num_term_to_keep",
"=",
"None",
")",
":",
"num_term_to_keep",
"=",
"AutoTermSelector",
".",
"_add_default_num_terms_to_keep",
"(",
"num_term_to_keep",
")",
"term_doc_freq",
"=",
"term_doc_matrix",
... | cacf1f687d218ee8cae3fc05cc901db824bb1b81 |
train | BM25Difference.get_scores | In this case, args aren't used, since this information is taken
directly from the corpus categories.
Returns
-------
np.array, scores | scattertext/termscoring/BM25Difference.py | def get_scores(self, *args):
'''
In this case, args aren't used, since this information is taken
directly from the corpus categories.
Returns
-------
np.array, scores
'''
if self.tdf_ is None:
raise Exception("Use set_category_name('category name', ['not category name', ...]) " +
... | def get_scores(self, *args):
'''
In this case, args aren't used, since this information is taken
directly from the corpus categories.
Returns
-------
np.array, scores
'''
if self.tdf_ is None:
raise Exception("Use set_category_name('category name', ['not category name', ...]) " +
... | [
"In",
"this",
"case",
"args",
"aren",
"t",
"used",
"since",
"this",
"information",
"is",
"taken",
"directly",
"from",
"the",
"corpus",
"categories",
"."
] | JasonKessler/scattertext | python | https://github.com/JasonKessler/scattertext/blob/cacf1f687d218ee8cae3fc05cc901db824bb1b81/scattertext/termscoring/BM25Difference.py#L34-L65 | [
"def",
"get_scores",
"(",
"self",
",",
"*",
"args",
")",
":",
"if",
"self",
".",
"tdf_",
"is",
"None",
":",
"raise",
"Exception",
"(",
"\"Use set_category_name('category name', ['not category name', ...]) \"",
"+",
"\"to set the category of interest\"",
")",
"avgdl",
... | cacf1f687d218ee8cae3fc05cc901db824bb1b81 |
train | ScaledFScoreSignificance.get_p_vals | Imputes p-values from the Z-scores of `ScaledFScore` scores. Assuming incorrectly
that the scaled f-scores are normally distributed.
Parameters
----------
X : np.array
Array of word counts, shape (N, 2) where N is the vocab size. X[:,0] is the
positive class, while X[:,1] is the negative class.
Retu... | scattertext/termsignificance/ScaledFScoreSignificance.py | def get_p_vals(self, X):
'''
Imputes p-values from the Z-scores of `ScaledFScore` scores. Assuming incorrectly
that the scaled f-scores are normally distributed.
Parameters
----------
X : np.array
Array of word counts, shape (N, 2) where N is the vocab size. X[:,0] is the
positive class, while X[:,... | def get_p_vals(self, X):
'''
Imputes p-values from the Z-scores of `ScaledFScore` scores. Assuming incorrectly
that the scaled f-scores are normally distributed.
Parameters
----------
X : np.array
Array of word counts, shape (N, 2) where N is the vocab size. X[:,0] is the
positive class, while X[:,... | [
"Imputes",
"p",
"-",
"values",
"from",
"the",
"Z",
"-",
"scores",
"of",
"ScaledFScore",
"scores",
".",
"Assuming",
"incorrectly",
"that",
"the",
"scaled",
"f",
"-",
"scores",
"are",
"normally",
"distributed",
"."
] | JasonKessler/scattertext | python | https://github.com/JasonKessler/scattertext/blob/cacf1f687d218ee8cae3fc05cc901db824bb1b81/scattertext/termsignificance/ScaledFScoreSignificance.py#L28-L45 | [
"def",
"get_p_vals",
"(",
"self",
",",
"X",
")",
":",
"z_scores",
"=",
"ScaledFZScore",
"(",
"self",
".",
"scaler_algo",
",",
"self",
".",
"beta",
")",
".",
"get_scores",
"(",
"X",
"[",
":",
",",
"0",
"]",
",",
"X",
"[",
":",
",",
"1",
"]",
")"... | cacf1f687d218ee8cae3fc05cc901db824bb1b81 |
train | CategoryProjectorBase.project | Returns a projection of the categories
:param term_doc_mat: a TermDocMatrix
:return: CategoryProjection | scattertext/categoryprojector/CategoryProjector.py | def project(self, term_doc_mat, x_dim=0, y_dim=1):
'''
Returns a projection of the categories
:param term_doc_mat: a TermDocMatrix
:return: CategoryProjection
'''
return self._project_category_corpus(self._get_category_metadata_corpus(term_doc_mat),
... | def project(self, term_doc_mat, x_dim=0, y_dim=1):
'''
Returns a projection of the categories
:param term_doc_mat: a TermDocMatrix
:return: CategoryProjection
'''
return self._project_category_corpus(self._get_category_metadata_corpus(term_doc_mat),
... | [
"Returns",
"a",
"projection",
"of",
"the",
"categories"
] | JasonKessler/scattertext | python | https://github.com/JasonKessler/scattertext/blob/cacf1f687d218ee8cae3fc05cc901db824bb1b81/scattertext/categoryprojector/CategoryProjector.py#L31-L39 | [
"def",
"project",
"(",
"self",
",",
"term_doc_mat",
",",
"x_dim",
"=",
"0",
",",
"y_dim",
"=",
"1",
")",
":",
"return",
"self",
".",
"_project_category_corpus",
"(",
"self",
".",
"_get_category_metadata_corpus",
"(",
"term_doc_mat",
")",
",",
"x_dim",
",",
... | cacf1f687d218ee8cae3fc05cc901db824bb1b81 |
train | CategoryProjectorBase.project_with_metadata | Returns a projection of the
:param term_doc_mat: a TermDocMatrix
:return: CategoryProjection | scattertext/categoryprojector/CategoryProjector.py | def project_with_metadata(self, term_doc_mat, x_dim=0, y_dim=1):
'''
Returns a projection of the
:param term_doc_mat: a TermDocMatrix
:return: CategoryProjection
'''
return self._project_category_corpus(self._get_category_metadata_corpus_and_replace_terms(term_doc_mat),
... | def project_with_metadata(self, term_doc_mat, x_dim=0, y_dim=1):
'''
Returns a projection of the
:param term_doc_mat: a TermDocMatrix
:return: CategoryProjection
'''
return self._project_category_corpus(self._get_category_metadata_corpus_and_replace_terms(term_doc_mat),
... | [
"Returns",
"a",
"projection",
"of",
"the"
] | JasonKessler/scattertext | python | https://github.com/JasonKessler/scattertext/blob/cacf1f687d218ee8cae3fc05cc901db824bb1b81/scattertext/categoryprojector/CategoryProjector.py#L41-L49 | [
"def",
"project_with_metadata",
"(",
"self",
",",
"term_doc_mat",
",",
"x_dim",
"=",
"0",
",",
"y_dim",
"=",
"1",
")",
":",
"return",
"self",
".",
"_project_category_corpus",
"(",
"self",
".",
"_get_category_metadata_corpus_and_replace_terms",
"(",
"term_doc_mat",
... | cacf1f687d218ee8cae3fc05cc901db824bb1b81 |
train | RelativeEntropy.get_scores | In this case, parameters a and b aren't used, since this information is taken
directly from the corpus categories.
Returns
------- | scattertext/termscoring/RelativeEntropy.py | def get_scores(self, *args):
'''
In this case, parameters a and b aren't used, since this information is taken
directly from the corpus categories.
Returns
-------
'''
def jelinek_mercer_smoothing(cat):
p_hat_w = self.tdf_[cat] * 1. / self.tdf_[cat].sum()
c_hat_w = (self.smoothing_lambda_) * self... | def get_scores(self, *args):
'''
In this case, parameters a and b aren't used, since this information is taken
directly from the corpus categories.
Returns
-------
'''
def jelinek_mercer_smoothing(cat):
p_hat_w = self.tdf_[cat] * 1. / self.tdf_[cat].sum()
c_hat_w = (self.smoothing_lambda_) * self... | [
"In",
"this",
"case",
"parameters",
"a",
"and",
"b",
"aren",
"t",
"used",
"since",
"this",
"information",
"is",
"taken",
"directly",
"from",
"the",
"corpus",
"categories",
"."
] | JasonKessler/scattertext | python | https://github.com/JasonKessler/scattertext/blob/cacf1f687d218ee8cae3fc05cc901db824bb1b81/scattertext/termscoring/RelativeEntropy.py#L36-L58 | [
"def",
"get_scores",
"(",
"self",
",",
"*",
"args",
")",
":",
"def",
"jelinek_mercer_smoothing",
"(",
"cat",
")",
":",
"p_hat_w",
"=",
"self",
".",
"tdf_",
"[",
"cat",
"]",
"*",
"1.",
"/",
"self",
".",
"tdf_",
"[",
"cat",
"]",
".",
"sum",
"(",
")... | cacf1f687d218ee8cae3fc05cc901db824bb1b81 |
train | comparable | Class decorator that ensures support for the special C{__cmp__} method.
On Python 2 this does nothing.
On Python 3, C{__eq__}, C{__lt__}, etc. methods are added to the class,
relying on C{__cmp__} to implement their comparisons. | maya/compat.py | def comparable(klass):
"""
Class decorator that ensures support for the special C{__cmp__} method.
On Python 2 this does nothing.
On Python 3, C{__eq__}, C{__lt__}, etc. methods are added to the class,
relying on C{__cmp__} to implement their comparisons.
"""
# On Python 2, __cmp__ will just... | def comparable(klass):
"""
Class decorator that ensures support for the special C{__cmp__} method.
On Python 2 this does nothing.
On Python 3, C{__eq__}, C{__lt__}, etc. methods are added to the class,
relying on C{__cmp__} to implement their comparisons.
"""
# On Python 2, __cmp__ will just... | [
"Class",
"decorator",
"that",
"ensures",
"support",
"for",
"the",
"special",
"C",
"{",
"__cmp__",
"}",
"method",
".",
"On",
"Python",
"2",
"this",
"does",
"nothing",
".",
"On",
"Python",
"3",
"C",
"{",
"__eq__",
"}",
"C",
"{",
"__lt__",
"}",
"etc",
"... | kennethreitz/maya | python | https://github.com/kennethreitz/maya/blob/774b141d91a83a5d77cb5351db3d02bf50564b21/maya/compat.py#L43-L102 | [
"def",
"comparable",
"(",
"klass",
")",
":",
"# On Python 2, __cmp__ will just work, so no need to add extra methods:",
"if",
"not",
"is_py3",
":",
"return",
"klass",
"def",
"__eq__",
"(",
"self",
",",
"other",
")",
":",
"c",
"=",
"self",
".",
"__cmp__",
"(",
"o... | 774b141d91a83a5d77cb5351db3d02bf50564b21 |
train | validate_class_type_arguments | Decorator to validate all the arguments to function
are of the type of calling class for passed operator | maya/core.py | def validate_class_type_arguments(operator):
"""
Decorator to validate all the arguments to function
are of the type of calling class for passed operator
"""
def inner(function):
def wrapper(self, *args, **kwargs):
for arg in args + tuple(kwargs.values()):
if no... | def validate_class_type_arguments(operator):
"""
Decorator to validate all the arguments to function
are of the type of calling class for passed operator
"""
def inner(function):
def wrapper(self, *args, **kwargs):
for arg in args + tuple(kwargs.values()):
if no... | [
"Decorator",
"to",
"validate",
"all",
"the",
"arguments",
"to",
"function",
"are",
"of",
"the",
"type",
"of",
"calling",
"class",
"for",
"passed",
"operator"
] | kennethreitz/maya | python | https://github.com/kennethreitz/maya/blob/774b141d91a83a5d77cb5351db3d02bf50564b21/maya/core.py#L22-L43 | [
"def",
"validate_class_type_arguments",
"(",
"operator",
")",
":",
"def",
"inner",
"(",
"function",
")",
":",
"def",
"wrapper",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"for",
"arg",
"in",
"args",
"+",
"tuple",
"(",
"kwargs",
... | 774b141d91a83a5d77cb5351db3d02bf50564b21 |
train | validate_arguments_type_of_function | Decorator to validate the <type> of arguments in
the calling function are of the `param_type` class.
if `param_type` is None, uses `param_type` as the class where it is used.
Note: Use this decorator on the functions of the class. | maya/core.py | def validate_arguments_type_of_function(param_type=None):
"""
Decorator to validate the <type> of arguments in
the calling function are of the `param_type` class.
if `param_type` is None, uses `param_type` as the class where it is used.
Note: Use this decorator on the functions of the class.
"... | def validate_arguments_type_of_function(param_type=None):
"""
Decorator to validate the <type> of arguments in
the calling function are of the `param_type` class.
if `param_type` is None, uses `param_type` as the class where it is used.
Note: Use this decorator on the functions of the class.
"... | [
"Decorator",
"to",
"validate",
"the",
"<type",
">",
"of",
"arguments",
"in",
"the",
"calling",
"function",
"are",
"of",
"the",
"param_type",
"class",
"."
] | kennethreitz/maya | python | https://github.com/kennethreitz/maya/blob/774b141d91a83a5d77cb5351db3d02bf50564b21/maya/core.py#L46-L77 | [
"def",
"validate_arguments_type_of_function",
"(",
"param_type",
"=",
"None",
")",
":",
"def",
"inner",
"(",
"function",
")",
":",
"def",
"wrapper",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"type_",
"=",
"param_type",
"or",
"type... | 774b141d91a83a5d77cb5351db3d02bf50564b21 |
train | utc_offset | Returns the time offset from UTC accounting for DST
Keyword Arguments:
time_struct {time.struct_time} -- the struct time for which to
return the UTC offset.
If None, use current local time. | maya/core.py | def utc_offset(time_struct=None):
"""
Returns the time offset from UTC accounting for DST
Keyword Arguments:
time_struct {time.struct_time} -- the struct time for which to
return the UTC offset.
If None, use current... | def utc_offset(time_struct=None):
"""
Returns the time offset from UTC accounting for DST
Keyword Arguments:
time_struct {time.struct_time} -- the struct time for which to
return the UTC offset.
If None, use current... | [
"Returns",
"the",
"time",
"offset",
"from",
"UTC",
"accounting",
"for",
"DST"
] | kennethreitz/maya | python | https://github.com/kennethreitz/maya/blob/774b141d91a83a5d77cb5351db3d02bf50564b21/maya/core.py#L369-L387 | [
"def",
"utc_offset",
"(",
"time_struct",
"=",
"None",
")",
":",
"if",
"time_struct",
":",
"ts",
"=",
"time_struct",
"else",
":",
"ts",
"=",
"time",
".",
"localtime",
"(",
")",
"if",
"ts",
"[",
"-",
"1",
"]",
":",
"offset",
"=",
"time",
".",
"altzon... | 774b141d91a83a5d77cb5351db3d02bf50564b21 |
train | when | Returns a MayaDT instance for the human moment specified.
Powered by dateparser. Useful for scraping websites.
Examples:
'next week', 'now', 'tomorrow', '300 years ago', 'August 14, 2015'
Keyword Arguments:
string -- string to be parsed
timezone -- timezone referenced from (defaul... | maya/core.py | def when(string, timezone='UTC', prefer_dates_from='current_period'):
""""Returns a MayaDT instance for the human moment specified.
Powered by dateparser. Useful for scraping websites.
Examples:
'next week', 'now', 'tomorrow', '300 years ago', 'August 14, 2015'
Keyword Arguments:
stri... | def when(string, timezone='UTC', prefer_dates_from='current_period'):
""""Returns a MayaDT instance for the human moment specified.
Powered by dateparser. Useful for scraping websites.
Examples:
'next week', 'now', 'tomorrow', '300 years ago', 'August 14, 2015'
Keyword Arguments:
stri... | [
"Returns",
"a",
"MayaDT",
"instance",
"for",
"the",
"human",
"moment",
"specified",
"."
] | kennethreitz/maya | python | https://github.com/kennethreitz/maya/blob/774b141d91a83a5d77cb5351db3d02bf50564b21/maya/core.py#L710-L739 | [
"def",
"when",
"(",
"string",
",",
"timezone",
"=",
"'UTC'",
",",
"prefer_dates_from",
"=",
"'current_period'",
")",
":",
"settings",
"=",
"{",
"'TIMEZONE'",
":",
"timezone",
",",
"'RETURN_AS_TIMEZONE_AWARE'",
":",
"True",
",",
"'TO_TIMEZONE'",
":",
"'UTC'",
"... | 774b141d91a83a5d77cb5351db3d02bf50564b21 |
train | parse | Returns a MayaDT instance for the machine-produced moment specified.
Powered by pendulum.
Accepts most known formats. Useful for working with data.
Keyword Arguments:
string -- string to be parsed
timezone -- timezone referenced from (default: 'UTC')
day_first -- if true, the first... | maya/core.py | def parse(string, timezone='UTC', day_first=False, year_first=True, strict=False):
""""Returns a MayaDT instance for the machine-produced moment specified.
Powered by pendulum.
Accepts most known formats. Useful for working with data.
Keyword Arguments:
string -- string to be parsed
ti... | def parse(string, timezone='UTC', day_first=False, year_first=True, strict=False):
""""Returns a MayaDT instance for the machine-produced moment specified.
Powered by pendulum.
Accepts most known formats. Useful for working with data.
Keyword Arguments:
string -- string to be parsed
ti... | [
"Returns",
"a",
"MayaDT",
"instance",
"for",
"the",
"machine",
"-",
"produced",
"moment",
"specified",
"."
] | kennethreitz/maya | python | https://github.com/kennethreitz/maya/blob/774b141d91a83a5d77cb5351db3d02bf50564b21/maya/core.py#L742-L767 | [
"def",
"parse",
"(",
"string",
",",
"timezone",
"=",
"'UTC'",
",",
"day_first",
"=",
"False",
",",
"year_first",
"=",
"True",
",",
"strict",
"=",
"False",
")",
":",
"options",
"=",
"{",
"}",
"options",
"[",
"'tz'",
"]",
"=",
"timezone",
"options",
"[... | 774b141d91a83a5d77cb5351db3d02bf50564b21 |
train | _seconds_or_timedelta | Returns `datetime.timedelta` object for the passed duration.
Keyword Arguments:
duration -- `datetime.timedelta` object or seconds in `int` format. | maya/core.py | def _seconds_or_timedelta(duration):
"""Returns `datetime.timedelta` object for the passed duration.
Keyword Arguments:
duration -- `datetime.timedelta` object or seconds in `int` format.
"""
if isinstance(duration, int):
dt_timedelta = timedelta(seconds=duration)
elif isinstance(du... | def _seconds_or_timedelta(duration):
"""Returns `datetime.timedelta` object for the passed duration.
Keyword Arguments:
duration -- `datetime.timedelta` object or seconds in `int` format.
"""
if isinstance(duration, int):
dt_timedelta = timedelta(seconds=duration)
elif isinstance(du... | [
"Returns",
"datetime",
".",
"timedelta",
"object",
"for",
"the",
"passed",
"duration",
"."
] | kennethreitz/maya | python | https://github.com/kennethreitz/maya/blob/774b141d91a83a5d77cb5351db3d02bf50564b21/maya/core.py#L770-L786 | [
"def",
"_seconds_or_timedelta",
"(",
"duration",
")",
":",
"if",
"isinstance",
"(",
"duration",
",",
"int",
")",
":",
"dt_timedelta",
"=",
"timedelta",
"(",
"seconds",
"=",
"duration",
")",
"elif",
"isinstance",
"(",
"duration",
",",
"timedelta",
")",
":",
... | 774b141d91a83a5d77cb5351db3d02bf50564b21 |
train | intervals | Yields MayaDT objects between the start and end MayaDTs given,
at a given interval (seconds or timedelta). | maya/core.py | def intervals(start, end, interval):
"""
Yields MayaDT objects between the start and end MayaDTs given,
at a given interval (seconds or timedelta).
"""
interval = _seconds_or_timedelta(interval)
current_timestamp = start
while current_timestamp.epoch < end.epoch:
yield current_timest... | def intervals(start, end, interval):
"""
Yields MayaDT objects between the start and end MayaDTs given,
at a given interval (seconds or timedelta).
"""
interval = _seconds_or_timedelta(interval)
current_timestamp = start
while current_timestamp.epoch < end.epoch:
yield current_timest... | [
"Yields",
"MayaDT",
"objects",
"between",
"the",
"start",
"and",
"end",
"MayaDTs",
"given",
"at",
"a",
"given",
"interval",
"(",
"seconds",
"or",
"timedelta",
")",
"."
] | kennethreitz/maya | python | https://github.com/kennethreitz/maya/blob/774b141d91a83a5d77cb5351db3d02bf50564b21/maya/core.py#L799-L811 | [
"def",
"intervals",
"(",
"start",
",",
"end",
",",
"interval",
")",
":",
"interval",
"=",
"_seconds_or_timedelta",
"(",
"interval",
")",
"current_timestamp",
"=",
"start",
"while",
"current_timestamp",
".",
"epoch",
"<",
"end",
".",
"epoch",
":",
"yield",
"c... | 774b141d91a83a5d77cb5351db3d02bf50564b21 |
train | MayaDT.add | Returns a new MayaDT object with the given offsets. | maya/core.py | def add(self, **kwargs):
"""Returns a new MayaDT object with the given offsets."""
return self.from_datetime(
pendulum.instance(self.datetime()).add(**kwargs)
) | def add(self, **kwargs):
"""Returns a new MayaDT object with the given offsets."""
return self.from_datetime(
pendulum.instance(self.datetime()).add(**kwargs)
) | [
"Returns",
"a",
"new",
"MayaDT",
"object",
"with",
"the",
"given",
"offsets",
"."
] | kennethreitz/maya | python | https://github.com/kennethreitz/maya/blob/774b141d91a83a5d77cb5351db3d02bf50564b21/maya/core.py#L142-L146 | [
"def",
"add",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"self",
".",
"from_datetime",
"(",
"pendulum",
".",
"instance",
"(",
"self",
".",
"datetime",
"(",
")",
")",
".",
"add",
"(",
"*",
"*",
"kwargs",
")",
")"
] | 774b141d91a83a5d77cb5351db3d02bf50564b21 |
train | MayaDT.subtract | Returns a new MayaDT object with the given offsets. | maya/core.py | def subtract(self, **kwargs):
"""Returns a new MayaDT object with the given offsets."""
return self.from_datetime(
pendulum.instance(self.datetime()).subtract(**kwargs)
) | def subtract(self, **kwargs):
"""Returns a new MayaDT object with the given offsets."""
return self.from_datetime(
pendulum.instance(self.datetime()).subtract(**kwargs)
) | [
"Returns",
"a",
"new",
"MayaDT",
"object",
"with",
"the",
"given",
"offsets",
"."
] | kennethreitz/maya | python | https://github.com/kennethreitz/maya/blob/774b141d91a83a5d77cb5351db3d02bf50564b21/maya/core.py#L148-L152 | [
"def",
"subtract",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"self",
".",
"from_datetime",
"(",
"pendulum",
".",
"instance",
"(",
"self",
".",
"datetime",
"(",
")",
")",
".",
"subtract",
"(",
"*",
"*",
"kwargs",
")",
")"
] | 774b141d91a83a5d77cb5351db3d02bf50564b21 |
train | MayaDT.snap | Returns a new MayaDT object modified by the given instruction.
Powered by snaptime. See https://github.com/zartstrom/snaptime
for a complete documentation about the snaptime instructions. | maya/core.py | def snap(self, instruction):
"""
Returns a new MayaDT object modified by the given instruction.
Powered by snaptime. See https://github.com/zartstrom/snaptime
for a complete documentation about the snaptime instructions.
"""
return self.from_datetime(snaptime.snap(self.... | def snap(self, instruction):
"""
Returns a new MayaDT object modified by the given instruction.
Powered by snaptime. See https://github.com/zartstrom/snaptime
for a complete documentation about the snaptime instructions.
"""
return self.from_datetime(snaptime.snap(self.... | [
"Returns",
"a",
"new",
"MayaDT",
"object",
"modified",
"by",
"the",
"given",
"instruction",
"."
] | kennethreitz/maya | python | https://github.com/kennethreitz/maya/blob/774b141d91a83a5d77cb5351db3d02bf50564b21/maya/core.py#L158-L165 | [
"def",
"snap",
"(",
"self",
",",
"instruction",
")",
":",
"return",
"self",
".",
"from_datetime",
"(",
"snaptime",
".",
"snap",
"(",
"self",
".",
"datetime",
"(",
")",
",",
"instruction",
")",
")"
] | 774b141d91a83a5d77cb5351db3d02bf50564b21 |
train | MayaDT.local_timezone | Returns the name of the local timezone. | maya/core.py | def local_timezone(self):
"""Returns the name of the local timezone."""
if self._local_tz.zone in pytz.all_timezones:
return self._local_tz.zone
return self.timezone | def local_timezone(self):
"""Returns the name of the local timezone."""
if self._local_tz.zone in pytz.all_timezones:
return self._local_tz.zone
return self.timezone | [
"Returns",
"the",
"name",
"of",
"the",
"local",
"timezone",
"."
] | kennethreitz/maya | python | https://github.com/kennethreitz/maya/blob/774b141d91a83a5d77cb5351db3d02bf50564b21/maya/core.py#L180-L185 | [
"def",
"local_timezone",
"(",
"self",
")",
":",
"if",
"self",
".",
"_local_tz",
".",
"zone",
"in",
"pytz",
".",
"all_timezones",
":",
"return",
"self",
".",
"_local_tz",
".",
"zone",
"return",
"self",
".",
"timezone"
] | 774b141d91a83a5d77cb5351db3d02bf50564b21 |
train | MayaDT.__dt_to_epoch | Converts a datetime into an epoch. | maya/core.py | def __dt_to_epoch(dt):
"""Converts a datetime into an epoch."""
# Assume UTC if no datetime is provided.
if dt.tzinfo is None:
dt = dt.replace(tzinfo=pytz.utc)
epoch_start = Datetime(*MayaDT.__EPOCH_START, tzinfo=pytz.timezone('UTC'))
return (dt - epoch_start).total_s... | def __dt_to_epoch(dt):
"""Converts a datetime into an epoch."""
# Assume UTC if no datetime is provided.
if dt.tzinfo is None:
dt = dt.replace(tzinfo=pytz.utc)
epoch_start = Datetime(*MayaDT.__EPOCH_START, tzinfo=pytz.timezone('UTC'))
return (dt - epoch_start).total_s... | [
"Converts",
"a",
"datetime",
"into",
"an",
"epoch",
"."
] | kennethreitz/maya | python | https://github.com/kennethreitz/maya/blob/774b141d91a83a5d77cb5351db3d02bf50564b21/maya/core.py#L194-L200 | [
"def",
"__dt_to_epoch",
"(",
"dt",
")",
":",
"# Assume UTC if no datetime is provided.",
"if",
"dt",
".",
"tzinfo",
"is",
"None",
":",
"dt",
"=",
"dt",
".",
"replace",
"(",
"tzinfo",
"=",
"pytz",
".",
"utc",
")",
"epoch_start",
"=",
"Datetime",
"(",
"*",
... | 774b141d91a83a5d77cb5351db3d02bf50564b21 |
train | MayaDT.from_struct | Returns MayaDT instance from a 9-tuple struct
It's assumed to be from gmtime(). | maya/core.py | def from_struct(klass, struct, timezone=pytz.UTC):
"""Returns MayaDT instance from a 9-tuple struct
It's assumed to be from gmtime().
"""
struct_time = time.mktime(struct) - utc_offset(struct)
dt = Datetime.fromtimestamp(struct_time, timezone)
return klass(klass.__dt_to_... | def from_struct(klass, struct, timezone=pytz.UTC):
"""Returns MayaDT instance from a 9-tuple struct
It's assumed to be from gmtime().
"""
struct_time = time.mktime(struct) - utc_offset(struct)
dt = Datetime.fromtimestamp(struct_time, timezone)
return klass(klass.__dt_to_... | [
"Returns",
"MayaDT",
"instance",
"from",
"a",
"9",
"-",
"tuple",
"struct"
] | kennethreitz/maya | python | https://github.com/kennethreitz/maya/blob/774b141d91a83a5d77cb5351db3d02bf50564b21/maya/core.py#L212-L219 | [
"def",
"from_struct",
"(",
"klass",
",",
"struct",
",",
"timezone",
"=",
"pytz",
".",
"UTC",
")",
":",
"struct_time",
"=",
"time",
".",
"mktime",
"(",
"struct",
")",
"-",
"utc_offset",
"(",
"struct",
")",
"dt",
"=",
"Datetime",
".",
"fromtimestamp",
"(... | 774b141d91a83a5d77cb5351db3d02bf50564b21 |
train | MayaDT.datetime | Returns a timezone-aware datetime...
Defaulting to UTC (as it should).
Keyword Arguments:
to_timezone {str} -- timezone to convert to (default: None/UTC)
naive {bool} -- if True,
the tzinfo is simply dropped (default: False) | maya/core.py | def datetime(self, to_timezone=None, naive=False):
"""Returns a timezone-aware datetime...
Defaulting to UTC (as it should).
Keyword Arguments:
to_timezone {str} -- timezone to convert to (default: None/UTC)
naive {bool} -- if True,
the tzinfo... | def datetime(self, to_timezone=None, naive=False):
"""Returns a timezone-aware datetime...
Defaulting to UTC (as it should).
Keyword Arguments:
to_timezone {str} -- timezone to convert to (default: None/UTC)
naive {bool} -- if True,
the tzinfo... | [
"Returns",
"a",
"timezone",
"-",
"aware",
"datetime",
"...",
"Defaulting",
"to",
"UTC",
"(",
"as",
"it",
"should",
")",
"."
] | kennethreitz/maya | python | https://github.com/kennethreitz/maya/blob/774b141d91a83a5d77cb5351db3d02bf50564b21/maya/core.py#L238-L259 | [
"def",
"datetime",
"(",
"self",
",",
"to_timezone",
"=",
"None",
",",
"naive",
"=",
"False",
")",
":",
"if",
"to_timezone",
":",
"dt",
"=",
"self",
".",
"datetime",
"(",
")",
".",
"astimezone",
"(",
"pytz",
".",
"timezone",
"(",
"to_timezone",
")",
"... | 774b141d91a83a5d77cb5351db3d02bf50564b21 |
train | MayaDT.iso8601 | Returns an ISO 8601 representation of the MayaDT. | maya/core.py | def iso8601(self):
"""Returns an ISO 8601 representation of the MayaDT."""
# Get a timezone-naive datetime.
dt = self.datetime(naive=True)
return '{}Z'.format(dt.isoformat()) | def iso8601(self):
"""Returns an ISO 8601 representation of the MayaDT."""
# Get a timezone-naive datetime.
dt = self.datetime(naive=True)
return '{}Z'.format(dt.isoformat()) | [
"Returns",
"an",
"ISO",
"8601",
"representation",
"of",
"the",
"MayaDT",
"."
] | kennethreitz/maya | python | https://github.com/kennethreitz/maya/blob/774b141d91a83a5d77cb5351db3d02bf50564b21/maya/core.py#L269-L273 | [
"def",
"iso8601",
"(",
"self",
")",
":",
"# Get a timezone-naive datetime.",
"dt",
"=",
"self",
".",
"datetime",
"(",
"naive",
"=",
"True",
")",
"return",
"'{}Z'",
".",
"format",
"(",
"dt",
".",
"isoformat",
"(",
")",
")"
] | 774b141d91a83a5d77cb5351db3d02bf50564b21 |
train | MayaDT.slang_date | Returns human slang representation of date.
Keyword Arguments:
locale -- locale to translate to, e.g. 'fr' for french.
(default: 'en' - English) | maya/core.py | def slang_date(self, locale="en"):
""""Returns human slang representation of date.
Keyword Arguments:
locale -- locale to translate to, e.g. 'fr' for french.
(default: 'en' - English)
"""
dt = pendulum.instance(self.datetime())
try:
... | def slang_date(self, locale="en"):
""""Returns human slang representation of date.
Keyword Arguments:
locale -- locale to translate to, e.g. 'fr' for french.
(default: 'en' - English)
"""
dt = pendulum.instance(self.datetime())
try:
... | [
"Returns",
"human",
"slang",
"representation",
"of",
"date",
"."
] | kennethreitz/maya | python | https://github.com/kennethreitz/maya/blob/774b141d91a83a5d77cb5351db3d02bf50564b21/maya/core.py#L335-L356 | [
"def",
"slang_date",
"(",
"self",
",",
"locale",
"=",
"\"en\"",
")",
":",
"dt",
"=",
"pendulum",
".",
"instance",
"(",
"self",
".",
"datetime",
"(",
")",
")",
"try",
":",
"return",
"_translate",
"(",
"dt",
",",
"locale",
")",
"except",
"KeyError",
":... | 774b141d91a83a5d77cb5351db3d02bf50564b21 |
train | MayaDT.slang_time | Returns human slang representation of time.
Keyword Arguments:
locale -- locale to translate to, e.g. 'fr' for french.
(default: 'en' - English) | maya/core.py | def slang_time(self, locale="en"):
""""Returns human slang representation of time.
Keyword Arguments:
locale -- locale to translate to, e.g. 'fr' for french.
(default: 'en' - English)
"""
dt = self.datetime()
return pendulum.instance(dt).diff_f... | def slang_time(self, locale="en"):
""""Returns human slang representation of time.
Keyword Arguments:
locale -- locale to translate to, e.g. 'fr' for french.
(default: 'en' - English)
"""
dt = self.datetime()
return pendulum.instance(dt).diff_f... | [
"Returns",
"human",
"slang",
"representation",
"of",
"time",
"."
] | kennethreitz/maya | python | https://github.com/kennethreitz/maya/blob/774b141d91a83a5d77cb5351db3d02bf50564b21/maya/core.py#L358-L366 | [
"def",
"slang_time",
"(",
"self",
",",
"locale",
"=",
"\"en\"",
")",
":",
"dt",
"=",
"self",
".",
"datetime",
"(",
")",
"return",
"pendulum",
".",
"instance",
"(",
"dt",
")",
".",
"diff_for_humans",
"(",
"locale",
"=",
"locale",
")"
] | 774b141d91a83a5d77cb5351db3d02bf50564b21 |
train | angvel | Use sigmoid function to choose a delta that will help smoothly steer from current angle to target angle. | Malmo/samples/Python_examples/mob_zoo.py | def angvel(target, current, scale):
'''Use sigmoid function to choose a delta that will help smoothly steer from current angle to target angle.'''
delta = target - current
while delta < -180:
delta += 360;
while delta > 180:
delta -= 360;
return (old_div(2.0, (1.0 + math.exp(old_div(... | def angvel(target, current, scale):
'''Use sigmoid function to choose a delta that will help smoothly steer from current angle to target angle.'''
delta = target - current
while delta < -180:
delta += 360;
while delta > 180:
delta -= 360;
return (old_div(2.0, (1.0 + math.exp(old_div(... | [
"Use",
"sigmoid",
"function",
"to",
"choose",
"a",
"delta",
"that",
"will",
"help",
"smoothly",
"steer",
"from",
"current",
"angle",
"to",
"target",
"angle",
"."
] | Microsoft/malmo | python | https://github.com/Microsoft/malmo/blob/4139cd6f3e52f6e893a931a1d4b70d35f8e70e5a/Malmo/samples/Python_examples/mob_zoo.py#L105-L112 | [
"def",
"angvel",
"(",
"target",
",",
"current",
",",
"scale",
")",
":",
"delta",
"=",
"target",
"-",
"current",
"while",
"delta",
"<",
"-",
"180",
":",
"delta",
"+=",
"360",
"while",
"delta",
">",
"180",
":",
"delta",
"-=",
"360",
"return",
"(",
"o... | 4139cd6f3e52f6e893a931a1d4b70d35f8e70e5a |
train | pointTo | Steer towards the target pitch/yaw, return True when within the given tolerance threshold. | Malmo/samples/Python_examples/mob_zoo.py | def pointTo(agent_host, ob, target_pitch, target_yaw, threshold):
'''Steer towards the target pitch/yaw, return True when within the given tolerance threshold.'''
pitch = ob.get(u'Pitch', 0)
yaw = ob.get(u'Yaw', 0)
delta_yaw = angvel(target_yaw, yaw, 50.0)
delta_pitch = angvel(target_pitch, pitch, 5... | def pointTo(agent_host, ob, target_pitch, target_yaw, threshold):
'''Steer towards the target pitch/yaw, return True when within the given tolerance threshold.'''
pitch = ob.get(u'Pitch', 0)
yaw = ob.get(u'Yaw', 0)
delta_yaw = angvel(target_yaw, yaw, 50.0)
delta_pitch = angvel(target_pitch, pitch, 5... | [
"Steer",
"towards",
"the",
"target",
"pitch",
"/",
"yaw",
"return",
"True",
"when",
"within",
"the",
"given",
"tolerance",
"threshold",
"."
] | Microsoft/malmo | python | https://github.com/Microsoft/malmo/blob/4139cd6f3e52f6e893a931a1d4b70d35f8e70e5a/Malmo/samples/Python_examples/mob_zoo.py#L114-L126 | [
"def",
"pointTo",
"(",
"agent_host",
",",
"ob",
",",
"target_pitch",
",",
"target_yaw",
",",
"threshold",
")",
":",
"pitch",
"=",
"ob",
".",
"get",
"(",
"u'Pitch'",
",",
"0",
")",
"yaw",
"=",
"ob",
".",
"get",
"(",
"u'Yaw'",
",",
"0",
")",
"delta_y... | 4139cd6f3e52f6e893a931a1d4b70d35f8e70e5a |
train | download | Download Malmo from github and optionaly build the Minecraft Mod.
Args:
branch: optional branch to clone. Default is release version.
buildMod: don't build the Mod unless build arg is given as True.
Returns:
The path for the Malmo Minecraft mod. | scripts/python-wheel/package/malmo/minecraftbootstrap.py | def download(branch=None, buildMod=False):
"""Download Malmo from github and optionaly build the Minecraft Mod.
Args:
branch: optional branch to clone. Default is release version.
buildMod: don't build the Mod unless build arg is given as True.
Returns:
The path for the Malmo Minecra... | def download(branch=None, buildMod=False):
"""Download Malmo from github and optionaly build the Minecraft Mod.
Args:
branch: optional branch to clone. Default is release version.
buildMod: don't build the Mod unless build arg is given as True.
Returns:
The path for the Malmo Minecra... | [
"Download",
"Malmo",
"from",
"github",
"and",
"optionaly",
"build",
"the",
"Minecraft",
"Mod",
".",
"Args",
":",
"branch",
":",
"optional",
"branch",
"to",
"clone",
".",
"Default",
"is",
"release",
"version",
".",
"buildMod",
":",
"don",
"t",
"build",
"the... | Microsoft/malmo | python | https://github.com/Microsoft/malmo/blob/4139cd6f3e52f6e893a931a1d4b70d35f8e70e5a/scripts/python-wheel/package/malmo/minecraftbootstrap.py#L43-L78 | [
"def",
"download",
"(",
"branch",
"=",
"None",
",",
"buildMod",
"=",
"False",
")",
":",
"gradlew",
"=",
"\"./gradlew\"",
"if",
"os",
".",
"name",
"==",
"'nt'",
":",
"gradlew",
"=",
"\"gradlew.bat\"",
"if",
"branch",
"is",
"None",
":",
"branch",
"=",
"m... | 4139cd6f3e52f6e893a931a1d4b70d35f8e70e5a |
train | launch_minecraft | Launch Malmo Minecraft Mod in one or more clients from
the Minecraft directory on the (optionally) given ports.
Args:
ports: an optionsl list of ports to start minecraft clients on.
Defaults to a single Minecraft client on port 10000.
wait_timeout: optional time in secon... | scripts/python-wheel/package/malmo/minecraftbootstrap.py | def launch_minecraft(ports = [], wait_timeout = 360):
"""Launch Malmo Minecraft Mod in one or more clients from
the Minecraft directory on the (optionally) given ports.
Args:
ports: an optionsl list of ports to start minecraft clients on.
Defaults to a single Minecraft client o... | def launch_minecraft(ports = [], wait_timeout = 360):
"""Launch Malmo Minecraft Mod in one or more clients from
the Minecraft directory on the (optionally) given ports.
Args:
ports: an optionsl list of ports to start minecraft clients on.
Defaults to a single Minecraft client o... | [
"Launch",
"Malmo",
"Minecraft",
"Mod",
"in",
"one",
"or",
"more",
"clients",
"from",
"the",
"Minecraft",
"directory",
"on",
"the",
"(",
"optionally",
")",
"given",
"ports",
".",
"Args",
":",
"ports",
":",
"an",
"optionsl",
"list",
"of",
"ports",
"to",
"s... | Microsoft/malmo | python | https://github.com/Microsoft/malmo/blob/4139cd6f3e52f6e893a931a1d4b70d35f8e70e5a/scripts/python-wheel/package/malmo/minecraftbootstrap.py#L80-L96 | [
"def",
"launch_minecraft",
"(",
"ports",
"=",
"[",
"]",
",",
"wait_timeout",
"=",
"360",
")",
":",
"if",
"\"MALMO_XSD_PATH\"",
"not",
"in",
"os",
".",
"environ",
":",
"print",
"(",
"\"Please set the MALMO_XSD_PATH environment variable.\"",
")",
"return",
"cwd",
... | 4139cd6f3e52f6e893a931a1d4b70d35f8e70e5a |
train | set_malmo_xsd_path | Set the MAMLMO_XSD_PATH environment variable in current process. | scripts/python-wheel/package/malmo/minecraftbootstrap.py | def set_malmo_xsd_path():
"""Set the MAMLMO_XSD_PATH environment variable in current process."""
os.environ["MALMO_XSD_PATH"] = str(pathlib.Path(malmo_install_dir + "/Schemas").absolute())
print(os.environ["MALMO_XSD_PATH"]) | def set_malmo_xsd_path():
"""Set the MAMLMO_XSD_PATH environment variable in current process."""
os.environ["MALMO_XSD_PATH"] = str(pathlib.Path(malmo_install_dir + "/Schemas").absolute())
print(os.environ["MALMO_XSD_PATH"]) | [
"Set",
"the",
"MAMLMO_XSD_PATH",
"environment",
"variable",
"in",
"current",
"process",
"."
] | Microsoft/malmo | python | https://github.com/Microsoft/malmo/blob/4139cd6f3e52f6e893a931a1d4b70d35f8e70e5a/scripts/python-wheel/package/malmo/minecraftbootstrap.py#L98-L102 | [
"def",
"set_malmo_xsd_path",
"(",
")",
":",
"os",
".",
"environ",
"[",
"\"MALMO_XSD_PATH\"",
"]",
"=",
"str",
"(",
"pathlib",
".",
"Path",
"(",
"malmo_install_dir",
"+",
"\"/Schemas\"",
")",
".",
"absolute",
"(",
")",
")",
"print",
"(",
"os",
".",
"envir... | 4139cd6f3e52f6e893a931a1d4b70d35f8e70e5a |
train | indexOfClosest | Return the index in arr of the closest float value to val. | Malmo/samples/Python_examples/robust_frames.py | def indexOfClosest( arr, val ):
'''Return the index in arr of the closest float value to val.'''
i_closest = None
for i,v in enumerate(arr):
d = math.fabs( v - val )
if i_closest == None or d < d_closest:
i_closest = i
d_closest = d
return i_closest | def indexOfClosest( arr, val ):
'''Return the index in arr of the closest float value to val.'''
i_closest = None
for i,v in enumerate(arr):
d = math.fabs( v - val )
if i_closest == None or d < d_closest:
i_closest = i
d_closest = d
return i_closest | [
"Return",
"the",
"index",
"in",
"arr",
"of",
"the",
"closest",
"float",
"value",
"to",
"val",
"."
] | Microsoft/malmo | python | https://github.com/Microsoft/malmo/blob/4139cd6f3e52f6e893a931a1d4b70d35f8e70e5a/Malmo/samples/Python_examples/robust_frames.py#L264-L272 | [
"def",
"indexOfClosest",
"(",
"arr",
",",
"val",
")",
":",
"i_closest",
"=",
"None",
"for",
"i",
",",
"v",
"in",
"enumerate",
"(",
"arr",
")",
":",
"d",
"=",
"math",
".",
"fabs",
"(",
"v",
"-",
"val",
")",
"if",
"i_closest",
"==",
"None",
"or",
... | 4139cd6f3e52f6e893a931a1d4b70d35f8e70e5a |
train | RandomAgent.waitForInitialState | Before a command has been sent we wait for an observation of the world and a frame. | Malmo/samples/Python_examples/robust_frames.py | def waitForInitialState( self ):
'''Before a command has been sent we wait for an observation of the world and a frame.'''
# wait for a valid observation
world_state = self.agent_host.peekWorldState()
while world_state.is_mission_running and all(e.text=='{}' for e in world_state.observat... | def waitForInitialState( self ):
'''Before a command has been sent we wait for an observation of the world and a frame.'''
# wait for a valid observation
world_state = self.agent_host.peekWorldState()
while world_state.is_mission_running and all(e.text=='{}' for e in world_state.observat... | [
"Before",
"a",
"command",
"has",
"been",
"sent",
"we",
"wait",
"for",
"an",
"observation",
"of",
"the",
"world",
"and",
"a",
"frame",
"."
] | Microsoft/malmo | python | https://github.com/Microsoft/malmo/blob/4139cd6f3e52f6e893a931a1d4b70d35f8e70e5a/Malmo/samples/Python_examples/robust_frames.py#L65-L96 | [
"def",
"waitForInitialState",
"(",
"self",
")",
":",
"# wait for a valid observation",
"world_state",
"=",
"self",
".",
"agent_host",
".",
"peekWorldState",
"(",
")",
"while",
"world_state",
".",
"is_mission_running",
"and",
"all",
"(",
"e",
".",
"text",
"==",
"... | 4139cd6f3e52f6e893a931a1d4b70d35f8e70e5a |
train | RandomAgent.waitForNextState | After each command has been sent we wait for the observation to change as expected and a frame. | Malmo/samples/Python_examples/robust_frames.py | def waitForNextState( self ):
'''After each command has been sent we wait for the observation to change as expected and a frame.'''
# wait for the observation position to have changed
print('Waiting for observation...', end=' ')
while True:
world_state = self.agent_host.peekW... | def waitForNextState( self ):
'''After each command has been sent we wait for the observation to change as expected and a frame.'''
# wait for the observation position to have changed
print('Waiting for observation...', end=' ')
while True:
world_state = self.agent_host.peekW... | [
"After",
"each",
"command",
"has",
"been",
"sent",
"we",
"wait",
"for",
"the",
"observation",
"to",
"change",
"as",
"expected",
"and",
"a",
"frame",
"."
] | Microsoft/malmo | python | https://github.com/Microsoft/malmo/blob/4139cd6f3e52f6e893a931a1d4b70d35f8e70e5a/Malmo/samples/Python_examples/robust_frames.py#L98-L202 | [
"def",
"waitForNextState",
"(",
"self",
")",
":",
"# wait for the observation position to have changed",
"print",
"(",
"'Waiting for observation...'",
",",
"end",
"=",
"' '",
")",
"while",
"True",
":",
"world_state",
"=",
"self",
".",
"agent_host",
".",
"peekWorldStat... | 4139cd6f3e52f6e893a931a1d4b70d35f8e70e5a |
train | RandomAgent.act | Take an action from the action_set and set the expected outcome so we can wait for it. | Malmo/samples/Python_examples/robust_frames.py | def act( self ):
'''Take an action from the action_set and set the expected outcome so we can wait for it.'''
if self.action_set == 'discrete_absolute':
actions = ['movenorth 1', 'movesouth 1', 'movewest 1', 'moveeast 1']
elif self.action_set == 'discrete_relative':
actio... | def act( self ):
'''Take an action from the action_set and set the expected outcome so we can wait for it.'''
if self.action_set == 'discrete_absolute':
actions = ['movenorth 1', 'movesouth 1', 'movewest 1', 'moveeast 1']
elif self.action_set == 'discrete_relative':
actio... | [
"Take",
"an",
"action",
"from",
"the",
"action_set",
"and",
"set",
"the",
"expected",
"outcome",
"so",
"we",
"can",
"wait",
"for",
"it",
"."
] | Microsoft/malmo | python | https://github.com/Microsoft/malmo/blob/4139cd6f3e52f6e893a931a1d4b70d35f8e70e5a/Malmo/samples/Python_examples/robust_frames.py#L204-L262 | [
"def",
"act",
"(",
"self",
")",
":",
"if",
"self",
".",
"action_set",
"==",
"'discrete_absolute'",
":",
"actions",
"=",
"[",
"'movenorth 1'",
",",
"'movesouth 1'",
",",
"'movewest 1'",
",",
"'moveeast 1'",
"]",
"elif",
"self",
".",
"action_set",
"==",
"'disc... | 4139cd6f3e52f6e893a931a1d4b70d35f8e70e5a |
train | processFrame | Simulate a left and right sensor output (from 0 to 1) given the input image. | Malmo/samples/Python_examples/braitenberg_simulation.py | def processFrame(frame):
"""Simulate a left and right sensor output (from 0 to 1) given the input image."""
# The pixels are grey-scale values from 0-255 - white = 255, black = 0
# We want to turn the image into two values, one for the left "sensor" and one for the right.
# There are many possible ways ... | def processFrame(frame):
"""Simulate a left and right sensor output (from 0 to 1) given the input image."""
# The pixels are grey-scale values from 0-255 - white = 255, black = 0
# We want to turn the image into two values, one for the left "sensor" and one for the right.
# There are many possible ways ... | [
"Simulate",
"a",
"left",
"and",
"right",
"sensor",
"output",
"(",
"from",
"0",
"to",
"1",
")",
"given",
"the",
"input",
"image",
"."
] | Microsoft/malmo | python | https://github.com/Microsoft/malmo/blob/4139cd6f3e52f6e893a931a1d4b70d35f8e70e5a/Malmo/samples/Python_examples/braitenberg_simulation.py#L97-L171 | [
"def",
"processFrame",
"(",
"frame",
")",
":",
"# The pixels are grey-scale values from 0-255 - white = 255, black = 0",
"# We want to turn the image into two values, one for the left \"sensor\" and one for the right.",
"# There are many possible ways to do this. The very simplest way would be",
"... | 4139cd6f3e52f6e893a931a1d4b70d35f8e70e5a |
train | getCitiesDrawingXML | Build an XML string that contains a square for each city | Malmo/samples/Python_examples/tsp_race.py | def getCitiesDrawingXML(points):
''' Build an XML string that contains a square for each city'''
xml = ""
for p in points:
x = str(p.x)
z = str(p.y)
xml += '<DrawBlock x="' + x + '" y="7" z="' + z + '" type="beacon"/>'
xml += '<DrawItem x="' + x + '" y="10" z="' + z + '" type... | def getCitiesDrawingXML(points):
''' Build an XML string that contains a square for each city'''
xml = ""
for p in points:
x = str(p.x)
z = str(p.y)
xml += '<DrawBlock x="' + x + '" y="7" z="' + z + '" type="beacon"/>'
xml += '<DrawItem x="' + x + '" y="10" z="' + z + '" type... | [
"Build",
"an",
"XML",
"string",
"that",
"contains",
"a",
"square",
"for",
"each",
"city"
] | Microsoft/malmo | python | https://github.com/Microsoft/malmo/blob/4139cd6f3e52f6e893a931a1d4b70d35f8e70e5a/Malmo/samples/Python_examples/tsp_race.py#L630-L638 | [
"def",
"getCitiesDrawingXML",
"(",
"points",
")",
":",
"xml",
"=",
"\"\"",
"for",
"p",
"in",
"points",
":",
"x",
"=",
"str",
"(",
"p",
".",
"x",
")",
"z",
"=",
"str",
"(",
"p",
".",
"y",
")",
"xml",
"+=",
"'<DrawBlock x=\"'",
"+",
"x",
"+",
"'\... | 4139cd6f3e52f6e893a931a1d4b70d35f8e70e5a |
train | HumanAgentHost.runMission | Sets a mission running.
Parameters:
mission_spec : MissionSpec instance, specifying the mission.
mission_record_spec : MissionRecordSpec instance, specifying what should be recorded.
role : int, the index of the role this human agent is to play. Zero based. | Malmo/samples/Python_examples/human_action.py | def runMission( self, mission_spec, mission_record_spec, role = 0 ):
'''Sets a mission running.
Parameters:
mission_spec : MissionSpec instance, specifying the mission.
mission_record_spec : MissionRecordSpec instance, specifying what should be recorded.
role : int, the ... | def runMission( self, mission_spec, mission_record_spec, role = 0 ):
'''Sets a mission running.
Parameters:
mission_spec : MissionSpec instance, specifying the mission.
mission_record_spec : MissionRecordSpec instance, specifying what should be recorded.
role : int, the ... | [
"Sets",
"a",
"mission",
"running",
".",
"Parameters",
":",
"mission_spec",
":",
"MissionSpec",
"instance",
"specifying",
"the",
"mission",
".",
"mission_record_spec",
":",
"MissionRecordSpec",
"instance",
"specifying",
"what",
"should",
"be",
"recorded",
".",
"role"... | Microsoft/malmo | python | https://github.com/Microsoft/malmo/blob/4139cd6f3e52f6e893a931a1d4b70d35f8e70e5a/Malmo/samples/Python_examples/human_action.py#L79-L162 | [
"def",
"runMission",
"(",
"self",
",",
"mission_spec",
",",
"mission_record_spec",
",",
"role",
"=",
"0",
")",
":",
"self",
".",
"world_state",
"=",
"None",
"total_reward",
"=",
"0",
"# decide on the action space",
"command_handlers",
"=",
"mission_spec",
".",
"... | 4139cd6f3e52f6e893a931a1d4b70d35f8e70e5a |
train | HumanAgentHost.createGUI | Create the graphical user interface. | Malmo/samples/Python_examples/human_action.py | def createGUI( self ):
'''Create the graphical user interface.'''
our_font = "Helvetica 16 bold"
small_font = "Helvetica 9 bold"
self.root_frame = Frame(self.root)
if self.action_space == 'continuous':
desc = "Running continuous-action mission.\nUse the mouse to turn,... | def createGUI( self ):
'''Create the graphical user interface.'''
our_font = "Helvetica 16 bold"
small_font = "Helvetica 9 bold"
self.root_frame = Frame(self.root)
if self.action_space == 'continuous':
desc = "Running continuous-action mission.\nUse the mouse to turn,... | [
"Create",
"the",
"graphical",
"user",
"interface",
"."
] | Microsoft/malmo | python | https://github.com/Microsoft/malmo/blob/4139cd6f3e52f6e893a931a1d4b70d35f8e70e5a/Malmo/samples/Python_examples/human_action.py#L164-L197 | [
"def",
"createGUI",
"(",
"self",
")",
":",
"our_font",
"=",
"\"Helvetica 16 bold\"",
"small_font",
"=",
"\"Helvetica 9 bold\"",
"self",
".",
"root_frame",
"=",
"Frame",
"(",
"self",
".",
"root",
")",
"if",
"self",
".",
"action_space",
"==",
"'continuous'",
":"... | 4139cd6f3e52f6e893a931a1d4b70d35f8e70e5a |
train | HumanAgentHost.onSendCommand | Called when user presses the 'send' button or presses 'Enter' while the command entry box has focus. | Malmo/samples/Python_examples/human_action.py | def onSendCommand(self):
'''Called when user presses the 'send' button or presses 'Enter' while the command entry box has focus.'''
self.agent_host.sendCommand(self.command_entry.get())
self.command_entry.delete(0,END)
self.canvas.focus_set() | def onSendCommand(self):
'''Called when user presses the 'send' button or presses 'Enter' while the command entry box has focus.'''
self.agent_host.sendCommand(self.command_entry.get())
self.command_entry.delete(0,END)
self.canvas.focus_set() | [
"Called",
"when",
"user",
"presses",
"the",
"send",
"button",
"or",
"presses",
"Enter",
"while",
"the",
"command",
"entry",
"box",
"has",
"focus",
"."
] | Microsoft/malmo | python | https://github.com/Microsoft/malmo/blob/4139cd6f3e52f6e893a931a1d4b70d35f8e70e5a/Malmo/samples/Python_examples/human_action.py#L199-L203 | [
"def",
"onSendCommand",
"(",
"self",
")",
":",
"self",
".",
"agent_host",
".",
"sendCommand",
"(",
"self",
".",
"command_entry",
".",
"get",
"(",
")",
")",
"self",
".",
"command_entry",
".",
"delete",
"(",
"0",
",",
"END",
")",
"self",
".",
"canvas",
... | 4139cd6f3e52f6e893a931a1d4b70d35f8e70e5a |
train | HumanAgentHost.update | Called at regular intervals to poll the mouse position to send continuous commands. | Malmo/samples/Python_examples/human_action.py | def update(self):
'''Called at regular intervals to poll the mouse position to send continuous commands.'''
if self.action_space == 'continuous': # mouse movement only used for continuous action space
if self.world_state and self.world_state.is_mission_running:
if self.mouse_... | def update(self):
'''Called at regular intervals to poll the mouse position to send continuous commands.'''
if self.action_space == 'continuous': # mouse movement only used for continuous action space
if self.world_state and self.world_state.is_mission_running:
if self.mouse_... | [
"Called",
"at",
"regular",
"intervals",
"to",
"poll",
"the",
"mouse",
"position",
"to",
"send",
"continuous",
"commands",
"."
] | Microsoft/malmo | python | https://github.com/Microsoft/malmo/blob/4139cd6f3e52f6e893a931a1d4b70d35f8e70e5a/Malmo/samples/Python_examples/human_action.py#L205-L222 | [
"def",
"update",
"(",
"self",
")",
":",
"if",
"self",
".",
"action_space",
"==",
"'continuous'",
":",
"# mouse movement only used for continuous action space",
"if",
"self",
".",
"world_state",
"and",
"self",
".",
"world_state",
".",
"is_mission_running",
":",
"if",... | 4139cd6f3e52f6e893a931a1d4b70d35f8e70e5a |
train | HumanAgentHost.onKeyInCommandEntry | Called when a key is pressed when the command entry box has focus. | Malmo/samples/Python_examples/human_action.py | def onKeyInCommandEntry(self, event):
'''Called when a key is pressed when the command entry box has focus.'''
if event.char == '\r':
self.onSendCommand()
self.canvas.focus_set() | def onKeyInCommandEntry(self, event):
'''Called when a key is pressed when the command entry box has focus.'''
if event.char == '\r':
self.onSendCommand()
self.canvas.focus_set() | [
"Called",
"when",
"a",
"key",
"is",
"pressed",
"when",
"the",
"command",
"entry",
"box",
"has",
"focus",
"."
] | Microsoft/malmo | python | https://github.com/Microsoft/malmo/blob/4139cd6f3e52f6e893a931a1d4b70d35f8e70e5a/Malmo/samples/Python_examples/human_action.py#L248-L252 | [
"def",
"onKeyInCommandEntry",
"(",
"self",
",",
"event",
")",
":",
"if",
"event",
".",
"char",
"==",
"'\\r'",
":",
"self",
".",
"onSendCommand",
"(",
")",
"self",
".",
"canvas",
".",
"focus_set",
"(",
")"
] | 4139cd6f3e52f6e893a931a1d4b70d35f8e70e5a |
train | HumanAgentHost.onKeyPressInCanvas | Called when a key is pressed when the canvas has focus. | Malmo/samples/Python_examples/human_action.py | def onKeyPressInCanvas(self, event):
'''Called when a key is pressed when the canvas has focus.'''
char_map = { 'w':'move 1', 'a':'strafe -1', 's':'move -1', 'd':'strafe 1', ' ':'jump 1' }
keysym_map = { 'continuous': { 'Left':'turn -1', 'Right':'turn 1', 'Up':'pitch -1', 'Down':'pitch 1', 'Shif... | def onKeyPressInCanvas(self, event):
'''Called when a key is pressed when the canvas has focus.'''
char_map = { 'w':'move 1', 'a':'strafe -1', 's':'move -1', 'd':'strafe 1', ' ':'jump 1' }
keysym_map = { 'continuous': { 'Left':'turn -1', 'Right':'turn 1', 'Up':'pitch -1', 'Down':'pitch 1', 'Shif... | [
"Called",
"when",
"a",
"key",
"is",
"pressed",
"when",
"the",
"canvas",
"has",
"focus",
"."
] | Microsoft/malmo | python | https://github.com/Microsoft/malmo/blob/4139cd6f3e52f6e893a931a1d4b70d35f8e70e5a/Malmo/samples/Python_examples/human_action.py#L254-L269 | [
"def",
"onKeyPressInCanvas",
"(",
"self",
",",
"event",
")",
":",
"char_map",
"=",
"{",
"'w'",
":",
"'move 1'",
",",
"'a'",
":",
"'strafe -1'",
",",
"'s'",
":",
"'move -1'",
",",
"'d'",
":",
"'strafe 1'",
",",
"' '",
":",
"'jump 1'",
"}",
"keysym_map",
... | 4139cd6f3e52f6e893a931a1d4b70d35f8e70e5a |
train | HumanAgentHost.onKeyReleaseInCanvas | Called when a key is released when the command entry box has focus. | Malmo/samples/Python_examples/human_action.py | def onKeyReleaseInCanvas(self, event):
'''Called when a key is released when the command entry box has focus.'''
char_map = { 'w':'move 0', 'a':'strafe 0', 's':'move 0', 'd':'strafe 0', ' ':'jump 0' }
keysym_map = { 'Left':'turn 0', 'Right':'turn 0', 'Up':'pitch 0', 'Down':'pitch 0', 'Shift_L':'... | def onKeyReleaseInCanvas(self, event):
'''Called when a key is released when the command entry box has focus.'''
char_map = { 'w':'move 0', 'a':'strafe 0', 's':'move 0', 'd':'strafe 0', ' ':'jump 0' }
keysym_map = { 'Left':'turn 0', 'Right':'turn 0', 'Up':'pitch 0', 'Down':'pitch 0', 'Shift_L':'... | [
"Called",
"when",
"a",
"key",
"is",
"released",
"when",
"the",
"command",
"entry",
"box",
"has",
"focus",
"."
] | Microsoft/malmo | python | https://github.com/Microsoft/malmo/blob/4139cd6f3e52f6e893a931a1d4b70d35f8e70e5a/Malmo/samples/Python_examples/human_action.py#L271-L280 | [
"def",
"onKeyReleaseInCanvas",
"(",
"self",
",",
"event",
")",
":",
"char_map",
"=",
"{",
"'w'",
":",
"'move 0'",
",",
"'a'",
":",
"'strafe 0'",
",",
"'s'",
":",
"'move 0'",
",",
"'d'",
":",
"'strafe 0'",
",",
"' '",
":",
"'jump 0'",
"}",
"keysym_map",
... | 4139cd6f3e52f6e893a931a1d4b70d35f8e70e5a |
train | getItemXML | Build an XML string that contains some randomly positioned goal items | Malmo/samples/Python_examples/mob_fun.py | def getItemXML():
''' Build an XML string that contains some randomly positioned goal items'''
xml=""
for item in range(NUM_GOALS):
x = str(random.randint(old_div(-ARENA_WIDTH,2),old_div(ARENA_WIDTH,2)))
z = str(random.randint(old_div(-ARENA_BREADTH,2),old_div(ARENA_BREADTH,2)))
xml ... | def getItemXML():
''' Build an XML string that contains some randomly positioned goal items'''
xml=""
for item in range(NUM_GOALS):
x = str(random.randint(old_div(-ARENA_WIDTH,2),old_div(ARENA_WIDTH,2)))
z = str(random.randint(old_div(-ARENA_BREADTH,2),old_div(ARENA_BREADTH,2)))
xml ... | [
"Build",
"an",
"XML",
"string",
"that",
"contains",
"some",
"randomly",
"positioned",
"goal",
"items"
] | Microsoft/malmo | python | https://github.com/Microsoft/malmo/blob/4139cd6f3e52f6e893a931a1d4b70d35f8e70e5a/Malmo/samples/Python_examples/mob_fun.py#L76-L83 | [
"def",
"getItemXML",
"(",
")",
":",
"xml",
"=",
"\"\"",
"for",
"item",
"in",
"range",
"(",
"NUM_GOALS",
")",
":",
"x",
"=",
"str",
"(",
"random",
".",
"randint",
"(",
"old_div",
"(",
"-",
"ARENA_WIDTH",
",",
"2",
")",
",",
"old_div",
"(",
"ARENA_WI... | 4139cd6f3e52f6e893a931a1d4b70d35f8e70e5a |
train | getCorner | Return part of the XML string that defines the requested corner | Malmo/samples/Python_examples/mob_fun.py | def getCorner(index,top,left,expand=0,y=206):
''' Return part of the XML string that defines the requested corner'''
x = str(-(expand+old_div(ARENA_WIDTH,2))) if left else str(expand+old_div(ARENA_WIDTH,2))
z = str(-(expand+old_div(ARENA_BREADTH,2))) if top else str(expand+old_div(ARENA_BREADTH,2))
retu... | def getCorner(index,top,left,expand=0,y=206):
''' Return part of the XML string that defines the requested corner'''
x = str(-(expand+old_div(ARENA_WIDTH,2))) if left else str(expand+old_div(ARENA_WIDTH,2))
z = str(-(expand+old_div(ARENA_BREADTH,2))) if top else str(expand+old_div(ARENA_BREADTH,2))
retu... | [
"Return",
"part",
"of",
"the",
"XML",
"string",
"that",
"defines",
"the",
"requested",
"corner"
] | Microsoft/malmo | python | https://github.com/Microsoft/malmo/blob/4139cd6f3e52f6e893a931a1d4b70d35f8e70e5a/Malmo/samples/Python_examples/mob_fun.py#L85-L89 | [
"def",
"getCorner",
"(",
"index",
",",
"top",
",",
"left",
",",
"expand",
"=",
"0",
",",
"y",
"=",
"206",
")",
":",
"x",
"=",
"str",
"(",
"-",
"(",
"expand",
"+",
"old_div",
"(",
"ARENA_WIDTH",
",",
"2",
")",
")",
")",
"if",
"left",
"else",
"... | 4139cd6f3e52f6e893a931a1d4b70d35f8e70e5a |
train | getMissionXML | Build an XML mission string. | Malmo/samples/Python_examples/mob_fun.py | def getMissionXML(summary):
''' Build an XML mission string.'''
spawn_end_tag = ' type="mob_spawner" variant="' + MOB_TYPE + '"/>'
return '''<?xml version="1.0" encoding="UTF-8" ?>
<Mission xmlns="http://ProjectMalmo.microsoft.com" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<About>
... | def getMissionXML(summary):
''' Build an XML mission string.'''
spawn_end_tag = ' type="mob_spawner" variant="' + MOB_TYPE + '"/>'
return '''<?xml version="1.0" encoding="UTF-8" ?>
<Mission xmlns="http://ProjectMalmo.microsoft.com" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<About>
... | [
"Build",
"an",
"XML",
"mission",
"string",
"."
] | Microsoft/malmo | python | https://github.com/Microsoft/malmo/blob/4139cd6f3e52f6e893a931a1d4b70d35f8e70e5a/Malmo/samples/Python_examples/mob_fun.py#L91-L150 | [
"def",
"getMissionXML",
"(",
"summary",
")",
":",
"spawn_end_tag",
"=",
"' type=\"mob_spawner\" variant=\"'",
"+",
"MOB_TYPE",
"+",
"'\"/>'",
"return",
"'''<?xml version=\"1.0\" encoding=\"UTF-8\" ?>\n <Mission xmlns=\"http://ProjectMalmo.microsoft.com\" xmlns:xsi=\"http://www.w3.org/... | 4139cd6f3e52f6e893a931a1d4b70d35f8e70e5a |
train | getBestAngle | Scan through 360 degrees, looking for the best direction in which to take the next step. | Malmo/samples/Python_examples/mob_fun.py | def getBestAngle(entities, current_yaw, current_health):
'''Scan through 360 degrees, looking for the best direction in which to take the next step.'''
us = findUs(entities)
scores=[]
# Normalise current yaw:
while current_yaw < 0:
current_yaw += 360
while current_yaw > 360:
curr... | def getBestAngle(entities, current_yaw, current_health):
'''Scan through 360 degrees, looking for the best direction in which to take the next step.'''
us = findUs(entities)
scores=[]
# Normalise current yaw:
while current_yaw < 0:
current_yaw += 360
while current_yaw > 360:
curr... | [
"Scan",
"through",
"360",
"degrees",
"looking",
"for",
"the",
"best",
"direction",
"in",
"which",
"to",
"take",
"the",
"next",
"step",
"."
] | Microsoft/malmo | python | https://github.com/Microsoft/malmo/blob/4139cd6f3e52f6e893a931a1d4b70d35f8e70e5a/Malmo/samples/Python_examples/mob_fun.py#L181-L231 | [
"def",
"getBestAngle",
"(",
"entities",
",",
"current_yaw",
",",
"current_health",
")",
":",
"us",
"=",
"findUs",
"(",
"entities",
")",
"scores",
"=",
"[",
"]",
"# Normalise current yaw:",
"while",
"current_yaw",
"<",
"0",
":",
"current_yaw",
"+=",
"360",
"w... | 4139cd6f3e52f6e893a931a1d4b70d35f8e70e5a |
train | restart_minecraft | Attempt to quit mission if running and kill the client | Malmo/samples/Python_examples/run_mission.py | def restart_minecraft(world_state, agent_host, client_info, message):
""""Attempt to quit mission if running and kill the client"""
if world_state.is_mission_running:
agent_host.sendCommand("quit")
time.sleep(10)
agent_host.killClient(client_info)
raise MissionTimeoutException(message) | def restart_minecraft(world_state, agent_host, client_info, message):
""""Attempt to quit mission if running and kill the client"""
if world_state.is_mission_running:
agent_host.sendCommand("quit")
time.sleep(10)
agent_host.killClient(client_info)
raise MissionTimeoutException(message) | [
"Attempt",
"to",
"quit",
"mission",
"if",
"running",
"and",
"kill",
"the",
"client"
] | Microsoft/malmo | python | https://github.com/Microsoft/malmo/blob/4139cd6f3e52f6e893a931a1d4b70d35f8e70e5a/Malmo/samples/Python_examples/run_mission.py#L43-L49 | [
"def",
"restart_minecraft",
"(",
"world_state",
",",
"agent_host",
",",
"client_info",
",",
"message",
")",
":",
"if",
"world_state",
".",
"is_mission_running",
":",
"agent_host",
".",
"sendCommand",
"(",
"\"quit\"",
")",
"time",
".",
"sleep",
"(",
"10",
")",
... | 4139cd6f3e52f6e893a931a1d4b70d35f8e70e5a |
train | Env.init | Initialize a Malmo environment.
xml - the mission xml.
port - the MalmoEnv service's port.
server - the MalmoEnv service address. Default is localhost.
server2 - the MalmoEnv service address for given role if not 0.
port2 - the MalmoEnv service port for given ... | MalmoEnv/malmoenv/core.py | def init(self, xml, port, server=None,
server2=None, port2=None,
role=0, exp_uid=None, episode=0,
action_filter=None, resync=0, step_options=0, action_space=None):
""""Initialize a Malmo environment.
xml - the mission xml.
port - the MalmoEnv servic... | def init(self, xml, port, server=None,
server2=None, port2=None,
role=0, exp_uid=None, episode=0,
action_filter=None, resync=0, step_options=0, action_space=None):
""""Initialize a Malmo environment.
xml - the mission xml.
port - the MalmoEnv servic... | [
"Initialize",
"a",
"Malmo",
"environment",
".",
"xml",
"-",
"the",
"mission",
"xml",
".",
"port",
"-",
"the",
"MalmoEnv",
"service",
"s",
"port",
".",
"server",
"-",
"the",
"MalmoEnv",
"service",
"address",
".",
"Default",
"is",
"localhost",
".",
"server2"... | Microsoft/malmo | python | https://github.com/Microsoft/malmo/blob/4139cd6f3e52f6e893a931a1d4b70d35f8e70e5a/MalmoEnv/malmoenv/core.py#L107-L216 | [
"def",
"init",
"(",
"self",
",",
"xml",
",",
"port",
",",
"server",
"=",
"None",
",",
"server2",
"=",
"None",
",",
"port2",
"=",
"None",
",",
"role",
"=",
"0",
",",
"exp_uid",
"=",
"None",
",",
"episode",
"=",
"0",
",",
"action_filter",
"=",
"Non... | 4139cd6f3e52f6e893a931a1d4b70d35f8e70e5a |
train | Env.reset | gym api reset | MalmoEnv/malmoenv/core.py | def reset(self):
"""gym api reset"""
if self.resync_period > 0 and (self.resets + 1) % self.resync_period == 0:
self._exit_resync()
while not self.done:
self.done = self._quit_episode()
if not self.done:
time.sleep(0.1)
return self._... | def reset(self):
"""gym api reset"""
if self.resync_period > 0 and (self.resets + 1) % self.resync_period == 0:
self._exit_resync()
while not self.done:
self.done = self._quit_episode()
if not self.done:
time.sleep(0.1)
return self._... | [
"gym",
"api",
"reset"
] | Microsoft/malmo | python | https://github.com/Microsoft/malmo/blob/4139cd6f3e52f6e893a931a1d4b70d35f8e70e5a/MalmoEnv/malmoenv/core.py#L223-L234 | [
"def",
"reset",
"(",
"self",
")",
":",
"if",
"self",
".",
"resync_period",
">",
"0",
"and",
"(",
"self",
".",
"resets",
"+",
"1",
")",
"%",
"self",
".",
"resync_period",
"==",
"0",
":",
"self",
".",
"_exit_resync",
"(",
")",
"while",
"not",
"self",... | 4139cd6f3e52f6e893a931a1d4b70d35f8e70e5a |
train | Env.step | gym api step | MalmoEnv/malmoenv/core.py | def step(self, action):
"""gym api step"""
obs = None
reward = None
info = None
turn = True
withturnkey = self.step_options < 2
withinfo = self.step_options == 0 or self.step_options == 2
while not self.done and \
((obs is None or len(obs)... | def step(self, action):
"""gym api step"""
obs = None
reward = None
info = None
turn = True
withturnkey = self.step_options < 2
withinfo = self.step_options == 0 or self.step_options == 2
while not self.done and \
((obs is None or len(obs)... | [
"gym",
"api",
"step"
] | Microsoft/malmo | python | https://github.com/Microsoft/malmo/blob/4139cd6f3e52f6e893a931a1d4b70d35f8e70e5a/MalmoEnv/malmoenv/core.py#L287-L327 | [
"def",
"step",
"(",
"self",
",",
"action",
")",
":",
"obs",
"=",
"None",
"reward",
"=",
"None",
"info",
"=",
"None",
"turn",
"=",
"True",
"withturnkey",
"=",
"self",
".",
"step_options",
"<",
"2",
"withinfo",
"=",
"self",
".",
"step_options",
"==",
"... | 4139cd6f3e52f6e893a931a1d4b70d35f8e70e5a |
train | Env.close | gym api close | MalmoEnv/malmoenv/core.py | def close(self):
"""gym api close"""
try:
# Purge last token from head node with <Close> message.
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.connect((self.server, self.port))
self._hello(sock)
comms.send_message(sock, ("<Clo... | def close(self):
"""gym api close"""
try:
# Purge last token from head node with <Close> message.
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.connect((self.server, self.port))
self._hello(sock)
comms.send_message(sock, ("<Clo... | [
"gym",
"api",
"close"
] | Microsoft/malmo | python | https://github.com/Microsoft/malmo/blob/4139cd6f3e52f6e893a931a1d4b70d35f8e70e5a/MalmoEnv/malmoenv/core.py#L329-L346 | [
"def",
"close",
"(",
"self",
")",
":",
"try",
":",
"# Purge last token from head node with <Close> message.",
"sock",
"=",
"socket",
".",
"socket",
"(",
"socket",
".",
"AF_INET",
",",
"socket",
".",
"SOCK_STREAM",
")",
"sock",
".",
"connect",
"(",
"(",
"self",... | 4139cd6f3e52f6e893a931a1d4b70d35f8e70e5a |
train | Env.reinit | Use carefully to reset the episode count to 0. | MalmoEnv/malmoenv/core.py | def reinit(self):
"""Use carefully to reset the episode count to 0."""
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.connect((self.server, self.port))
self._hello(sock)
comms.send_message(sock, ("<Init>" + self._get_token() + "</Init>").encode())
reply = ... | def reinit(self):
"""Use carefully to reset the episode count to 0."""
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.connect((self.server, self.port))
self._hello(sock)
comms.send_message(sock, ("<Init>" + self._get_token() + "</Init>").encode())
reply = ... | [
"Use",
"carefully",
"to",
"reset",
"the",
"episode",
"count",
"to",
"0",
"."
] | Microsoft/malmo | python | https://github.com/Microsoft/malmo/blob/4139cd6f3e52f6e893a931a1d4b70d35f8e70e5a/MalmoEnv/malmoenv/core.py#L348-L358 | [
"def",
"reinit",
"(",
"self",
")",
":",
"sock",
"=",
"socket",
".",
"socket",
"(",
"socket",
".",
"AF_INET",
",",
"socket",
".",
"SOCK_STREAM",
")",
"sock",
".",
"connect",
"(",
"(",
"self",
".",
"server",
",",
"self",
".",
"port",
")",
")",
"self"... | 4139cd6f3e52f6e893a931a1d4b70d35f8e70e5a |
train | Env.status | Get status from server.
head - Ping the the head node if True. | MalmoEnv/malmoenv/core.py | def status(self, head):
"""Get status from server.
head - Ping the the head node if True.
"""
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
if head:
sock.connect((self.server, self.port))
else:
sock.connect((self.server2, self.port2))
... | def status(self, head):
"""Get status from server.
head - Ping the the head node if True.
"""
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
if head:
sock.connect((self.server, self.port))
else:
sock.connect((self.server2, self.port2))
... | [
"Get",
"status",
"from",
"server",
".",
"head",
"-",
"Ping",
"the",
"the",
"head",
"node",
"if",
"True",
"."
] | Microsoft/malmo | python | https://github.com/Microsoft/malmo/blob/4139cd6f3e52f6e893a931a1d4b70d35f8e70e5a/MalmoEnv/malmoenv/core.py#L360-L374 | [
"def",
"status",
"(",
"self",
",",
"head",
")",
":",
"sock",
"=",
"socket",
".",
"socket",
"(",
"socket",
".",
"AF_INET",
",",
"socket",
".",
"SOCK_STREAM",
")",
"if",
"head",
":",
"sock",
".",
"connect",
"(",
"(",
"self",
".",
"server",
",",
"self... | 4139cd6f3e52f6e893a931a1d4b70d35f8e70e5a |
train | Env.exit | Use carefully to cause the Minecraft service to exit (and hopefully restart).
Likely to throw communication errors so wrap in exception handler. | MalmoEnv/malmoenv/core.py | def exit(self):
"""Use carefully to cause the Minecraft service to exit (and hopefully restart).
Likely to throw communication errors so wrap in exception handler.
"""
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.connect((self.server2, self.port2))
self._... | def exit(self):
"""Use carefully to cause the Minecraft service to exit (and hopefully restart).
Likely to throw communication errors so wrap in exception handler.
"""
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.connect((self.server2, self.port2))
self._... | [
"Use",
"carefully",
"to",
"cause",
"the",
"Minecraft",
"service",
"to",
"exit",
"(",
"and",
"hopefully",
"restart",
")",
".",
"Likely",
"to",
"throw",
"communication",
"errors",
"so",
"wrap",
"in",
"exception",
"handler",
"."
] | Microsoft/malmo | python | https://github.com/Microsoft/malmo/blob/4139cd6f3e52f6e893a931a1d4b70d35f8e70e5a/MalmoEnv/malmoenv/core.py#L376-L388 | [
"def",
"exit",
"(",
"self",
")",
":",
"sock",
"=",
"socket",
".",
"socket",
"(",
"socket",
".",
"AF_INET",
",",
"socket",
".",
"SOCK_STREAM",
")",
"sock",
".",
"connect",
"(",
"(",
"self",
".",
"server2",
",",
"self",
".",
"port2",
")",
")",
"self"... | 4139cd6f3e52f6e893a931a1d4b70d35f8e70e5a |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.