text stringlengths 81 112k |
|---|
Returns
-------
PriorFactory
def use_general_term_frequencies(self):
'''
Returns
-------
PriorFactory
'''
tdf = self._get_relevant_term_freq()
bg_df = self.term_doc_mat.get_term_and_background_counts()[['background']]
bg_df = pd.merge(tdf,
bg_df,
left_index=Tru... |
Parameters
----------
pd.Series
term -> frequency
Returns
-------
PriorFactory
def use_custom_term_frequencies(self, custom_term_frequencies):
'''
Parameters
----------
pd.Series
term -> frequency
Returns
-------
PriorFactory
'''
self.priors += custom_term_frequencies.reindex(self.prior... |
Returns
-------
PriorFactory
def use_all_categories(self):
'''
Returns
-------
PriorFactory
'''
term_df = self.term_ranker.get_ranks()
self.priors += term_df.sum(axis=1).fillna(0.)
return self |
Returns
-------
PriorFactory
def use_neutral_categories(self):
'''
Returns
-------
PriorFactory
'''
term_df = self.term_ranker.get_ranks()
self.priors += term_df[[c + ' freq' for c in self._get_neutral_categories()]].sum(axis=1)
return self |
Returns
-------
PriorFactory
def drop_neutral_categories_from_corpus(self):
'''
Returns
-------
PriorFactory
'''
neutral_categories = self._get_neutral_categories()
self.term_doc_mat = self.term_doc_mat.remove_categories(neutral_categories)
self._reindex_priors()
return self |
Returns
-------
PriorFactory
def drop_unused_terms(self):
'''
Returns
-------
PriorFactory
'''
self.term_doc_mat = self.term_doc_mat.remove_terms(
set(self.term_doc_mat.get_terms()) - set(self.priors.index)
)
self._reindex_priors()
return self |
Returns
-------
PriorFactory
def drop_zero_priors(self):
'''
Returns
-------
PriorFactory
'''
self.term_doc_mat = self.term_doc_mat.remove_terms(
self.priors[self.priors == 0].index
)
self._reindex_priors()
return self |
Parameters
----------
target_term_doc_mat : TermDocMatrix
Returns
-------
PriorFactory
def align_to_target(self, target_term_doc_mat):
'''
Parameters
----------
target_term_doc_mat : TermDocMatrix
Returns
-------
PriorFactory
'''
self.priors = self.priors[target_term_doc_mat.get_terms()].... |
Returns
-------
pd.Series
def get_priors(self):
'''
Returns
-------
pd.Series
'''
priors = self.priors
priors[~np.isfinite(priors)] = 0
priors += self.starting_count
return priors |
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
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 occu... |
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. None by default
Returns
-------
np.array of z-scores
def get_zeta_i_j(self, X):
'''
Parameters
----------
X : np.array
Array of... |
Same function as 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
def get_scores(self, y_i, y_j):
'''
Same function as get_zeta_i_j_given_separate_counts
... |
Parameters
-------
term_doc_matrix : TermDocMatrix
Returns
-------
New term doc matrix
def compact(self, term_doc_matrix):
'''
Parameters
-------
term_doc_matrix : TermDocMatrix
Returns
-------
New term doc matrix
'''
count_df = self._get_statistics_dataframe(term_doc_matrix)
return ... |
Parameters
----------
term_dict: dict {metadataname: [term1, term2, ....], ...}
Returns
-------
None
def check_topic_model_string_format(term_dict):
'''
Parameters
----------
term_dict: dict {metadataname: [term1, term2, ....], ...}
Returns
-------
None
'''
if ... |
Inserts dictionary of meta data terms into object.
Parameters
----------
term_dict: dict {metadataname: [term1, term2, ....], ...}
Returns
-------
self: ScatterChart
def inject_metadata_term_lists(self, term_dict):
'''
Inserts dictionary of meta data te... |
Inserts a set of descriptions of meta data terms. These will be displayed
below the scatter plot when a meta data term is clicked. All keys in the term dict
must occur as meta data.
Parameters
----------
term_dict: dict {metadataname: str: 'explanation to insert', ...}
... |
Inject custom x and y coordinates for each term into chart.
Parameters
----------
x_coords: array-like
positions on x-axis \in [0,1]
y_coords: array-like
positions on y-axis \in [0,1]
rescale_x: lambda list[0,1]: list[0,1], default identity
Re... |
:param vec: array to jitter
:return: array, jittered version of arrays
def _add_jitter(self, vec):
"""
:param vec: array to jitter
:return: array, jittered version of arrays
"""
if self.scatterchartdata.jitter == 0 or self.scatterchartdata.jitter is None:
ret... |
Outdated. MPLD3 drawing.
Parameters
----------
category
num_top_words_to_annotate
words_to_annotate
scores
transform
Returns
-------
pd.DataFrame, html of fgure
def draw(self,
category,
num_top_words_to_annotat... |
Parameters
----------
y_i, np.array(int)
Arrays of word counts of words occurring in positi ve class
y_j, np.array(int)
Returns
-------
np.array of z-scores
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 occ... |
Parameters
----------
tdm: TermDocMatrix
category: str, category name
Returns
-------
pd.DataFrame(['coef', 'p-val'])
def get_scores_and_p_values(self, tdm, category):
'''
Parameters
----------
tdm: TermDocMatrix
category: str, category name
Returns
-------
pd.DataFrame(['coef', 'p-val'])... |
>>> a = csr_matrix(np.array([[0, 1, 3, 0, 1, 0],
[0, 0, 1, 0, 1, 1]])
>>> delete_columns(a, [1,2]).todense()
matrix([[0, 0, 1, 0],
[0, 0, 1, 1]])
Parameters
----------
mat : csr_matrix
columns_to_delete : list[int]
Returns
-------
csr_matrix that is stripped of columns ... |
Parameters
----------
param last_col_idx : int
number of columns
def set_last_col_idx(self, last_col_idx):
'''
Parameters
----------
param last_col_idx : int
number of columns
'''
assert last_col_idx >= self._max_col
self._max_col = last_col_idx
return self |
Parameters
----------
param last_row_idx : int
number of rows
def set_last_row_idx(self, last_row_idx):
'''
Parameters
----------
param last_row_idx : int
number of rows
'''
assert last_row_idx >= self._max_row
self._max_row = last_row_idx
return self |
Parameters
----------
doc, Spacy Docs
Returns
-------
Counter noun chunk -> count
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
----------
nltk_tokenizer : nltk.tokenize.* instance (e.g., nltk.TreebankWordTokenizer())
Returns
-------
Doc of tweets
Notes
-------
Requires NLTK to be installed
def nltk_tokenzier_factory(nltk_tokenizer):
'''
Parameters
----------
nltk_tokenizer : nltk.tokenize.* instance (e.g., nltk.Treeba... |
Specifies fixed set of embeddings
:param embeddings: array-like, sparse or dense, shape should be (embedding size, # terms)
:return: EmbeddingsResolver
def set_embeddings(self, embeddings):
'''
Specifies fixed set of embeddings
:param embeddings: array-like, sparse or dense, sha... |
: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)
def project(self, projection_model=None):
'''
:param projection_model: sklearn unsuper... |
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... |
Returns
-------
pd.DataFrame
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() |
Generate a TermDocMatrix from data in parameters.
Returns
----------
term_doc_matrix : TermDocMatrix
The object that this factory class builds.
def build(self):
"""Generate a TermDocMatrix from data in parameters.
Returns
----------
term_doc_m... |
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
'... |
Parameters
----------
category_doc_iter : iterator of (string category name, spacy.tokens.doc.Doc) pairs
Returns
----------
t : TermDocMatrix
def _build_from_category_spacy_doc_iter(self, category_doc_iter):
'''
Parameters
----------
category_doc... |
Parameters
----------
raw_text, uncleaned text for parsing out features
Returns
-------
csr_matrix, feature matrix
def feats_from_doc(self, raw_text):
'''
Parameters
----------
raw_text, uncleaned text for parsing out features
Returns
... |
Parameters
----------
num_terms, int
Returns
-------
dict
def get_lexicons(self, num_terms=10):
'''
Parameters
----------
num_terms, int
Returns
-------
dict
'''
return {k: v.index[:num_terms]
... |
Parameters
----------
term_doc_matrix : TermDocMatrix
Term document matrix object to compact
Returns
-------
New term doc matrix
def compact(self, term_doc_matrix):
'''
Parameters
----------
term_doc_matrix : TermDocMatrix
... |
Parameters
----------
term_doc_matrix : TermDocMatrix
Term document matrix object to compact
Returns
-------
TermDocMatrix
def compact(self, term_doc_matrix):
'''
Parameters
----------
term_doc_matrix : TermDocMatrix
Term d... |
Parameters
----------
doc, Spacy Docs
Returns
-------
Counter (unigram, bigram) -> count
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[s... |
Parameters
----------
corpus: Corpus for phrase augmentation
Returns
-------
New ParsedCorpus containing unigrams in corpus and new phrases
def add_phrases(self, corpus):
'''
Parameters
----------
corpus: Corpus for phrase augmentation
Returns
-------
New ParsedCorpus containing unigrams in c... |
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.
def train(self, epochs=2000, training_iterations=5):
'''
Parameters... |
Trains passive aggressive classifier
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(sel... |
Builds Depoyed Classifier
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_m... |
Parameters
----------
term_to_index_dict: term -> idx dictionary
Returns
-------
IndexStore
def build(term_to_index_dict):
'''
Parameters
----------
term_to_index_dict: term -> idx dictionary
Returns
-------
IndexStore
'''
idxstore = IndexStore()
idxstore._val2i = term_to_index_dict
i... |
Returns
-------
Corpus
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... |
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
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 occu... |
Parameters
----------
term_doc_matrix : TermDocMatrix
Term document matrix object to compact
Returns
-------
New term doc matrix
def compact(self, term_doc_matrix):
'''
Parameters
----------
term_doc_matrix : TermDocMatrix
Term document matrix object to compact
Returns
-------
New term ... |
Returns
-------
pd.Series, all raw documents
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 a dataframe indexed on the number of groups a term occured in.
Parameters
----------
group_col
Returns
-------
pd.DataFrame
def term_group_freq_df(self, group_col):
# type: (str) -> pd.DataFrame
'''
Returns a dataframe indexed on the num... |
Compute variance from
:param X:
:return:
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] |
Specify the category to score. Optionally, score against a specific set of categories.
def set_categories(self,
category_name,
not_category_names=[],
neutral_category_names=[]):
'''
Specify the category to score. Optionally, score aga... |
In this case, parameters a and b aren't used, since this information is taken
directly from the corpus categories.
Returns
-------
def get_t_statistics(self):
'''
In this case, parameters a and b aren't used, since this information is taken
directly from the corpus cate... |
Parameters
----------
X_factory
mX_factory
category_idx_store
df
parse_pipeline
term_idx_store
metadata_idx_store
y
Returns
-------
CorpusDF
def _apply_pipeline_and_get_build_instance(self,
X_factory,
mX_fa... |
Parameters
----------
background
def set_background_corpus(self, background):
'''
Parameters
----------
background
'''
if issubclass(type(background), TermDocMatrixWithoutCategories):
self._background_corpus = pd.DataFrame(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 two columns, corpus and background.
>>> corpus.get_unigram_corpus().get_term_and_background_counts... |
Returns
-------
List of dicts. One dict for each document, keys are metadata, values are counts
def list_extra_features(self):
'''
Returns
-------
List of dicts. One dict for each document, keys are metadata, values are counts
'''
return FeatureLister(s... |
Returns
-------
A new TermDocumentMatrix consisting of only terms which occur at least minimum_term_count.
def remove_infrequent_words(self, minimum_term_count, term_ranker=AbsoluteFrequencyRanker):
'''
Returns
-------
A new TermDocumentMatrix consisting of only terms wh... |
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
... |
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 ... |
Parameters
----------
threshold: int
Minimum number of documents term should appear in to be kept
Returns
-------
TermDocMatrix, new object with terms removed.
def remove_terms_used_in_less_than_num_docs(self, threshold):
'''
Parameters
-----... |
Parameters
-------
stoplist : list, optional
Returns
-------
A new TermDocumentMatrix consisting of only unigrams in the current TermDocumentMatrix.
def get_stoplisted_unigram_corpus(self, stoplist=None):
'''
Parameters
-------
stoplist : list, o... |
Parameters
-------
stoplist : list of lower-cased words, optional
Returns
-------
A new TermDocumentMatrix consisting of only unigrams in the current TermDocumentMatrix.
def get_stoplisted_unigram_corpus_and_custom(self,
custom_s... |
Returns a list of document lengths in words
Returns
-------
np.array
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... |
Parameters
----------
idx_to_delete_list, list
Returns
-------
TermDocMatrix
def remove_terms_by_indices(self, idx_to_delete_list):
'''
Parameters
----------
idx_to_delete_list, list
Returns
-------
TermDocMatrix
... |
Returns
-------
dict
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)) |
Parameters
----------
term_ranker : TermRanker
Returns
-------
pd.Dataframe
def apply_ranker(self, term_ranker, use_non_text_features):
'''
Parameters
----------
term_ranker : TermRanker
Returns
-------
pd.Dataframe
... |
: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.
def add_doc_names_as_metadata(self, doc_names):
'''
:param doc_names: array-like... |
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
def add_metadata(self, metadata_matrix, meta_index_store):... |
Parameters
----------
doc, Spacy Docs
Returns
-------
Counter (unigram, bigram) -> count
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_un... |
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
def get_score_df(self, cor... |
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... |
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 ... |
In this case, args aren't used, since this information is taken
directly from the corpus categories.
Returns
-------
np.array, scores
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, sco... |
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... |
Returns a projection of the categories
:param term_doc_mat: a TermDocMatrix
:return: CategoryProjection
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
... |
Returns a projection of the
:param term_doc_mat: a TermDocMatrix
:return: CategoryProjection
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
'''
... |
In this case, parameters a and b aren't used, since this information is taken
directly from the corpus categories.
Returns
-------
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
-------
'''... |
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.
def comparable(klass):
"""
Class decorator that ensures support for th... |
Decorator to validate all the arguments to function
are of the type of calling class for passed operator
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):
d... |
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):
"""
Deco... |
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.
def utc_offset(time_struct=None)... |
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... |
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... |
Returns `datetime.timedelta` object for the passed duration.
Keyword Arguments:
duration -- `datetime.timedelta` object or seconds in `int` format.
def _seconds_or_timedelta(duration):
"""Returns `datetime.timedelta` object for the passed duration.
Keyword Arguments:
duration -- `datetime... |
Yields MayaDT objects between the start and end MayaDTs given,
at a given interval (seconds or timedelta).
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(int... |
Returns a new MayaDT object with the given offsets.
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.
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 modified by the given instruction.
Powered by snaptime. See https://github.com/zartstrom/snaptime
for a complete documentation about the snaptime instructions.
def snap(self, instruction):
"""
Returns a new MayaDT object modified by the given instruction.
... |
Returns the name of the local 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 |
Converts a datetime into an epoch.
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'))
... |
Returns MayaDT instance from a 9-tuple struct
It's assumed to be from gmtime().
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)
... |
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)
def datetime(self, to_tim... |
Returns an ISO 8601 representation of the MayaDT.
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 human slang representation of date.
Keyword Arguments:
locale -- locale to translate to, e.g. 'fr' for french.
(default: 'en' - English)
def slang_date(self, locale="en"):
""""Returns human slang representation of date.
Keyword Arguments:
... |
Returns human slang representation of time.
Keyword Arguments:
locale -- locale to translate to, e.g. 'fr' for french.
(default: 'en' - English)
def slang_time(self, locale="en"):
""""Returns human slang representation of time.
Keyword Arguments:
... |
Use sigmoid function to choose a delta that will help smoothly steer from current angle to target angle.
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:
de... |
Steer towards the target pitch/yaw, return True when within the given tolerance threshold.
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)
... |
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.
def download(branch=None, buildMod=False)... |
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... |
Set the MAMLMO_XSD_PATH environment variable in current process.
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"]) |
Return the index in arr of the closest float value to val.
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
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.