id int32 0 252k | repo stringlengths 7 55 | path stringlengths 4 127 | func_name stringlengths 1 88 | original_string stringlengths 75 19.8k | language stringclasses 1
value | code stringlengths 51 19.8k | code_tokens list | docstring stringlengths 3 17.3k | docstring_tokens list | sha stringlengths 40 40 | url stringlengths 87 242 |
|---|---|---|---|---|---|---|---|---|---|---|---|
230,000 | HazyResearch/fonduer | src/fonduer/candidates/candidates.py | CandidateExtractor.apply | def apply(self, docs, split=0, clear=True, parallelism=None, progress_bar=True):
"""Run the CandidateExtractor.
:Example: To extract candidates from a set of training documents using
4 cores::
candidate_extractor.apply(train_docs, split=0, parallelism=4)
:param docs: Set of documents to extract from.
:param split: Which split to assign the extracted Candidates to.
:type split: int
:param clear: Whether or not to clear the existing Candidates
beforehand.
:type clear: bool
:param parallelism: How many threads to use for extraction. This will
override the parallelism value used to initialize the
CandidateExtractor if it is provided.
:type parallelism: int
:param progress_bar: Whether or not to display a progress bar. The
progress bar is measured per document.
:type progress_bar: bool
"""
super(CandidateExtractor, self).apply(
docs,
split=split,
clear=clear,
parallelism=parallelism,
progress_bar=progress_bar,
) | python | def apply(self, docs, split=0, clear=True, parallelism=None, progress_bar=True):
super(CandidateExtractor, self).apply(
docs,
split=split,
clear=clear,
parallelism=parallelism,
progress_bar=progress_bar,
) | [
"def",
"apply",
"(",
"self",
",",
"docs",
",",
"split",
"=",
"0",
",",
"clear",
"=",
"True",
",",
"parallelism",
"=",
"None",
",",
"progress_bar",
"=",
"True",
")",
":",
"super",
"(",
"CandidateExtractor",
",",
"self",
")",
".",
"apply",
"(",
"docs",... | Run the CandidateExtractor.
:Example: To extract candidates from a set of training documents using
4 cores::
candidate_extractor.apply(train_docs, split=0, parallelism=4)
:param docs: Set of documents to extract from.
:param split: Which split to assign the extracted Candidates to.
:type split: int
:param clear: Whether or not to clear the existing Candidates
beforehand.
:type clear: bool
:param parallelism: How many threads to use for extraction. This will
override the parallelism value used to initialize the
CandidateExtractor if it is provided.
:type parallelism: int
:param progress_bar: Whether or not to display a progress bar. The
progress bar is measured per document.
:type progress_bar: bool | [
"Run",
"the",
"CandidateExtractor",
"."
] | 4520f86a716f03dcca458a9f4bddac75b4e7068f | https://github.com/HazyResearch/fonduer/blob/4520f86a716f03dcca458a9f4bddac75b4e7068f/src/fonduer/candidates/candidates.py#L86-L114 |
230,001 | HazyResearch/fonduer | src/fonduer/candidates/candidates.py | CandidateExtractor.clear | def clear(self, split):
"""Delete Candidates of each class initialized with the
CandidateExtractor from given split the database.
:param split: Which split to clear.
:type split: int
"""
for candidate_class in self.candidate_classes:
logger.info(
f"Clearing table {candidate_class.__tablename__} (split {split})"
)
self.session.query(Candidate).filter(
Candidate.type == candidate_class.__tablename__
).filter(Candidate.split == split).delete(synchronize_session="fetch") | python | def clear(self, split):
for candidate_class in self.candidate_classes:
logger.info(
f"Clearing table {candidate_class.__tablename__} (split {split})"
)
self.session.query(Candidate).filter(
Candidate.type == candidate_class.__tablename__
).filter(Candidate.split == split).delete(synchronize_session="fetch") | [
"def",
"clear",
"(",
"self",
",",
"split",
")",
":",
"for",
"candidate_class",
"in",
"self",
".",
"candidate_classes",
":",
"logger",
".",
"info",
"(",
"f\"Clearing table {candidate_class.__tablename__} (split {split})\"",
")",
"self",
".",
"session",
".",
"query",
... | Delete Candidates of each class initialized with the
CandidateExtractor from given split the database.
:param split: Which split to clear.
:type split: int | [
"Delete",
"Candidates",
"of",
"each",
"class",
"initialized",
"with",
"the",
"CandidateExtractor",
"from",
"given",
"split",
"the",
"database",
"."
] | 4520f86a716f03dcca458a9f4bddac75b4e7068f | https://github.com/HazyResearch/fonduer/blob/4520f86a716f03dcca458a9f4bddac75b4e7068f/src/fonduer/candidates/candidates.py#L116-L129 |
230,002 | HazyResearch/fonduer | src/fonduer/candidates/candidates.py | CandidateExtractor.clear_all | def clear_all(self, split):
"""Delete ALL Candidates from given split the database.
:param split: Which split to clear.
:type split: int
"""
logger.info("Clearing ALL Candidates.")
self.session.query(Candidate).filter(Candidate.split == split).delete(
synchronize_session="fetch"
) | python | def clear_all(self, split):
logger.info("Clearing ALL Candidates.")
self.session.query(Candidate).filter(Candidate.split == split).delete(
synchronize_session="fetch"
) | [
"def",
"clear_all",
"(",
"self",
",",
"split",
")",
":",
"logger",
".",
"info",
"(",
"\"Clearing ALL Candidates.\"",
")",
"self",
".",
"session",
".",
"query",
"(",
"Candidate",
")",
".",
"filter",
"(",
"Candidate",
".",
"split",
"==",
"split",
")",
".",... | Delete ALL Candidates from given split the database.
:param split: Which split to clear.
:type split: int | [
"Delete",
"ALL",
"Candidates",
"from",
"given",
"split",
"the",
"database",
"."
] | 4520f86a716f03dcca458a9f4bddac75b4e7068f | https://github.com/HazyResearch/fonduer/blob/4520f86a716f03dcca458a9f4bddac75b4e7068f/src/fonduer/candidates/candidates.py#L131-L140 |
230,003 | HazyResearch/fonduer | src/fonduer/candidates/candidates.py | CandidateExtractor.get_candidates | def get_candidates(self, docs=None, split=0, sort=False):
"""Return a list of lists of the candidates associated with this extractor.
Each list of the return will contain the candidates for one of the
candidate classes associated with the CandidateExtractor.
:param docs: If provided, return candidates from these documents from
all splits.
:type docs: list, tuple of ``Documents``.
:param split: If docs is None, then return all the candidates from this
split.
:type split: int
:param sort: If sort is True, then return all candidates sorted by stable_id.
:type sort: bool
:return: Candidates for each candidate_class.
:rtype: List of lists of ``Candidates``.
"""
result = []
if docs:
docs = docs if isinstance(docs, (list, tuple)) else [docs]
# Get cands from all splits
for candidate_class in self.candidate_classes:
cands = (
self.session.query(candidate_class)
.filter(candidate_class.document_id.in_([doc.id for doc in docs]))
.order_by(candidate_class.id)
.all()
)
if sort:
cands = sorted(
cands,
key=lambda x: " ".join(
[x[i][0].get_stable_id() for i in range(len(x))]
),
)
result.append(cands)
else:
for candidate_class in self.candidate_classes:
# Filter by candidate_ids in a particular split
sub_query = (
self.session.query(Candidate.id)
.filter(Candidate.split == split)
.subquery()
)
cands = (
self.session.query(candidate_class)
.filter(candidate_class.id.in_(sub_query))
.order_by(candidate_class.id)
.all()
)
if sort:
cands = sorted(
cands,
key=lambda x: " ".join(
[x[i][0].get_stable_id() for i in range(len(x))]
),
)
result.append(cands)
return result | python | def get_candidates(self, docs=None, split=0, sort=False):
result = []
if docs:
docs = docs if isinstance(docs, (list, tuple)) else [docs]
# Get cands from all splits
for candidate_class in self.candidate_classes:
cands = (
self.session.query(candidate_class)
.filter(candidate_class.document_id.in_([doc.id for doc in docs]))
.order_by(candidate_class.id)
.all()
)
if sort:
cands = sorted(
cands,
key=lambda x: " ".join(
[x[i][0].get_stable_id() for i in range(len(x))]
),
)
result.append(cands)
else:
for candidate_class in self.candidate_classes:
# Filter by candidate_ids in a particular split
sub_query = (
self.session.query(Candidate.id)
.filter(Candidate.split == split)
.subquery()
)
cands = (
self.session.query(candidate_class)
.filter(candidate_class.id.in_(sub_query))
.order_by(candidate_class.id)
.all()
)
if sort:
cands = sorted(
cands,
key=lambda x: " ".join(
[x[i][0].get_stable_id() for i in range(len(x))]
),
)
result.append(cands)
return result | [
"def",
"get_candidates",
"(",
"self",
",",
"docs",
"=",
"None",
",",
"split",
"=",
"0",
",",
"sort",
"=",
"False",
")",
":",
"result",
"=",
"[",
"]",
"if",
"docs",
":",
"docs",
"=",
"docs",
"if",
"isinstance",
"(",
"docs",
",",
"(",
"list",
",",
... | Return a list of lists of the candidates associated with this extractor.
Each list of the return will contain the candidates for one of the
candidate classes associated with the CandidateExtractor.
:param docs: If provided, return candidates from these documents from
all splits.
:type docs: list, tuple of ``Documents``.
:param split: If docs is None, then return all the candidates from this
split.
:type split: int
:param sort: If sort is True, then return all candidates sorted by stable_id.
:type sort: bool
:return: Candidates for each candidate_class.
:rtype: List of lists of ``Candidates``. | [
"Return",
"a",
"list",
"of",
"lists",
"of",
"the",
"candidates",
"associated",
"with",
"this",
"extractor",
"."
] | 4520f86a716f03dcca458a9f4bddac75b4e7068f | https://github.com/HazyResearch/fonduer/blob/4520f86a716f03dcca458a9f4bddac75b4e7068f/src/fonduer/candidates/candidates.py#L142-L200 |
230,004 | HazyResearch/fonduer | src/fonduer/learning/disc_models/modules/sparse_linear.py | SparseLinear.reset_parameters | def reset_parameters(self):
"""Reinitiate the weight parameters.
"""
stdv = 1.0 / math.sqrt(self.num_features)
self.weight.weight.data.uniform_(-stdv, stdv)
if self.bias is not None:
self.bias.data.uniform_(-stdv, stdv)
if self.padding_idx is not None:
self.weight.weight.data[self.padding_idx].fill_(0) | python | def reset_parameters(self):
stdv = 1.0 / math.sqrt(self.num_features)
self.weight.weight.data.uniform_(-stdv, stdv)
if self.bias is not None:
self.bias.data.uniform_(-stdv, stdv)
if self.padding_idx is not None:
self.weight.weight.data[self.padding_idx].fill_(0) | [
"def",
"reset_parameters",
"(",
"self",
")",
":",
"stdv",
"=",
"1.0",
"/",
"math",
".",
"sqrt",
"(",
"self",
".",
"num_features",
")",
"self",
".",
"weight",
".",
"weight",
".",
"data",
".",
"uniform_",
"(",
"-",
"stdv",
",",
"stdv",
")",
"if",
"se... | Reinitiate the weight parameters. | [
"Reinitiate",
"the",
"weight",
"parameters",
"."
] | 4520f86a716f03dcca458a9f4bddac75b4e7068f | https://github.com/HazyResearch/fonduer/blob/4520f86a716f03dcca458a9f4bddac75b4e7068f/src/fonduer/learning/disc_models/modules/sparse_linear.py#L42-L51 |
230,005 | HazyResearch/fonduer | src/fonduer/learning/utils.py | save_marginals | def save_marginals(session, X, marginals, training=True):
"""Save marginal probabilities for a set of Candidates to db.
:param X: A list of arbitrary objects with candidate ids accessible via a
.id attrib
:param marginals: A dense M x K matrix of marginal probabilities, where
K is the cardinality of the candidates, OR a M-dim list/array if K=2.
:param training: If True, these are training marginals / labels; else they
are saved as end model predictions.
Note: The marginals for k=0 are not stored, only for k = 1,...,K
"""
logger = logging.getLogger(__name__)
# Make sure that we are working with a numpy array
try:
shape = marginals.shape
except Exception:
marginals = np.array(marginals)
shape = marginals.shape
# Handle binary input as M x 1-dim array; assume elements represent
# poksitive (k=1) class values
if len(shape) == 1:
marginals = np.vstack([1 - marginals, marginals]).T
# Only add values for classes k=1,...,K
marginal_tuples = []
for i in range(shape[0]):
for k in range(1, shape[1] if len(shape) > 1 else 2):
if marginals[i, k] > 0:
marginal_tuples.append((i, k, marginals[i, k]))
# NOTE: This will delete all existing marginals of type `training`
session.query(Marginal).filter(Marginal.training == training).delete(
synchronize_session="fetch"
)
# Prepare bulk INSERT query
q = Marginal.__table__.insert()
# Prepare values
insert_vals = []
for i, k, p in marginal_tuples:
cid = X[i].id
insert_vals.append(
{
"candidate_id": cid,
"training": training,
"value": k,
# We cast p in case its a numpy type, which psycopg2 does not handle
"probability": float(p),
}
)
# Execute update
session.execute(q, insert_vals)
session.commit()
logger.info(f"Saved {len(marginals)} marginals") | python | def save_marginals(session, X, marginals, training=True):
logger = logging.getLogger(__name__)
# Make sure that we are working with a numpy array
try:
shape = marginals.shape
except Exception:
marginals = np.array(marginals)
shape = marginals.shape
# Handle binary input as M x 1-dim array; assume elements represent
# poksitive (k=1) class values
if len(shape) == 1:
marginals = np.vstack([1 - marginals, marginals]).T
# Only add values for classes k=1,...,K
marginal_tuples = []
for i in range(shape[0]):
for k in range(1, shape[1] if len(shape) > 1 else 2):
if marginals[i, k] > 0:
marginal_tuples.append((i, k, marginals[i, k]))
# NOTE: This will delete all existing marginals of type `training`
session.query(Marginal).filter(Marginal.training == training).delete(
synchronize_session="fetch"
)
# Prepare bulk INSERT query
q = Marginal.__table__.insert()
# Prepare values
insert_vals = []
for i, k, p in marginal_tuples:
cid = X[i].id
insert_vals.append(
{
"candidate_id": cid,
"training": training,
"value": k,
# We cast p in case its a numpy type, which psycopg2 does not handle
"probability": float(p),
}
)
# Execute update
session.execute(q, insert_vals)
session.commit()
logger.info(f"Saved {len(marginals)} marginals") | [
"def",
"save_marginals",
"(",
"session",
",",
"X",
",",
"marginals",
",",
"training",
"=",
"True",
")",
":",
"logger",
"=",
"logging",
".",
"getLogger",
"(",
"__name__",
")",
"# Make sure that we are working with a numpy array",
"try",
":",
"shape",
"=",
"margin... | Save marginal probabilities for a set of Candidates to db.
:param X: A list of arbitrary objects with candidate ids accessible via a
.id attrib
:param marginals: A dense M x K matrix of marginal probabilities, where
K is the cardinality of the candidates, OR a M-dim list/array if K=2.
:param training: If True, these are training marginals / labels; else they
are saved as end model predictions.
Note: The marginals for k=0 are not stored, only for k = 1,...,K | [
"Save",
"marginal",
"probabilities",
"for",
"a",
"set",
"of",
"Candidates",
"to",
"db",
"."
] | 4520f86a716f03dcca458a9f4bddac75b4e7068f | https://github.com/HazyResearch/fonduer/blob/4520f86a716f03dcca458a9f4bddac75b4e7068f/src/fonduer/learning/utils.py#L11-L69 |
230,006 | HazyResearch/fonduer | src/fonduer/features/feature_libs/content_features.py | compile_entity_feature_generator | def compile_entity_feature_generator():
"""
Given optional arguments, returns a generator function which accepts an xml
root and a list of indexes for a mention, and will generate relation
features for this entity.
"""
BASIC_ATTRIBS_REL = ["lemma", "dep_label"]
m = Mention(0)
# Basic relation feature templates
temps = [
[Indicator(m, a) for a in BASIC_ATTRIBS_REL],
Indicator(m, "dep_label,lemma"),
# The *first element on the* path to the root: ngram lemmas along it
Ngrams(Parents(m, 3), "lemma", (1, 3)),
Ngrams(Children(m), "lemma", (1, 3)),
# The siblings of the mention
[LeftNgrams(LeftSiblings(m), a) for a in BASIC_ATTRIBS_REL],
[RightNgrams(RightSiblings(m), a) for a in BASIC_ATTRIBS_REL],
]
# return generator function
return Compile(temps).apply_mention | python | def compile_entity_feature_generator():
BASIC_ATTRIBS_REL = ["lemma", "dep_label"]
m = Mention(0)
# Basic relation feature templates
temps = [
[Indicator(m, a) for a in BASIC_ATTRIBS_REL],
Indicator(m, "dep_label,lemma"),
# The *first element on the* path to the root: ngram lemmas along it
Ngrams(Parents(m, 3), "lemma", (1, 3)),
Ngrams(Children(m), "lemma", (1, 3)),
# The siblings of the mention
[LeftNgrams(LeftSiblings(m), a) for a in BASIC_ATTRIBS_REL],
[RightNgrams(RightSiblings(m), a) for a in BASIC_ATTRIBS_REL],
]
# return generator function
return Compile(temps).apply_mention | [
"def",
"compile_entity_feature_generator",
"(",
")",
":",
"BASIC_ATTRIBS_REL",
"=",
"[",
"\"lemma\"",
",",
"\"dep_label\"",
"]",
"m",
"=",
"Mention",
"(",
"0",
")",
"# Basic relation feature templates",
"temps",
"=",
"[",
"[",
"Indicator",
"(",
"m",
",",
"a",
... | Given optional arguments, returns a generator function which accepts an xml
root and a list of indexes for a mention, and will generate relation
features for this entity. | [
"Given",
"optional",
"arguments",
"returns",
"a",
"generator",
"function",
"which",
"accepts",
"an",
"xml",
"root",
"and",
"a",
"list",
"of",
"indexes",
"for",
"a",
"mention",
"and",
"will",
"generate",
"relation",
"features",
"for",
"this",
"entity",
"."
] | 4520f86a716f03dcca458a9f4bddac75b4e7068f | https://github.com/HazyResearch/fonduer/blob/4520f86a716f03dcca458a9f4bddac75b4e7068f/src/fonduer/features/feature_libs/content_features.py#L108-L132 |
230,007 | HazyResearch/fonduer | src/fonduer/features/feature_libs/content_features.py | get_ddlib_feats | def get_ddlib_feats(span, context, idxs):
"""
Minimalist port of generic mention features from ddlib
"""
if span.stable_id not in unary_ddlib_feats:
unary_ddlib_feats[span.stable_id] = set()
for seq_feat in _get_seq_features(context, idxs):
unary_ddlib_feats[span.stable_id].add(seq_feat)
for window_feat in _get_window_features(context, idxs):
unary_ddlib_feats[span.stable_id].add(window_feat)
for f in unary_ddlib_feats[span.stable_id]:
yield f | python | def get_ddlib_feats(span, context, idxs):
if span.stable_id not in unary_ddlib_feats:
unary_ddlib_feats[span.stable_id] = set()
for seq_feat in _get_seq_features(context, idxs):
unary_ddlib_feats[span.stable_id].add(seq_feat)
for window_feat in _get_window_features(context, idxs):
unary_ddlib_feats[span.stable_id].add(window_feat)
for f in unary_ddlib_feats[span.stable_id]:
yield f | [
"def",
"get_ddlib_feats",
"(",
"span",
",",
"context",
",",
"idxs",
")",
":",
"if",
"span",
".",
"stable_id",
"not",
"in",
"unary_ddlib_feats",
":",
"unary_ddlib_feats",
"[",
"span",
".",
"stable_id",
"]",
"=",
"set",
"(",
")",
"for",
"seq_feat",
"in",
"... | Minimalist port of generic mention features from ddlib | [
"Minimalist",
"port",
"of",
"generic",
"mention",
"features",
"from",
"ddlib"
] | 4520f86a716f03dcca458a9f4bddac75b4e7068f | https://github.com/HazyResearch/fonduer/blob/4520f86a716f03dcca458a9f4bddac75b4e7068f/src/fonduer/features/feature_libs/content_features.py#L135-L150 |
230,008 | HazyResearch/fonduer | src/fonduer/utils/utils_udf.py | _get_cand_values | def _get_cand_values(candidate, key_table):
"""Get the corresponding values for the key_table."""
# NOTE: Import just before checking to avoid circular imports.
from fonduer.features.models import FeatureKey
from fonduer.supervision.models import GoldLabelKey, LabelKey
if key_table == FeatureKey:
return candidate.features
elif key_table == LabelKey:
return candidate.labels
elif key_table == GoldLabelKey:
return candidate.gold_labels
else:
raise ValueError(f"{key_table} is not a valid key table.") | python | def _get_cand_values(candidate, key_table):
# NOTE: Import just before checking to avoid circular imports.
from fonduer.features.models import FeatureKey
from fonduer.supervision.models import GoldLabelKey, LabelKey
if key_table == FeatureKey:
return candidate.features
elif key_table == LabelKey:
return candidate.labels
elif key_table == GoldLabelKey:
return candidate.gold_labels
else:
raise ValueError(f"{key_table} is not a valid key table.") | [
"def",
"_get_cand_values",
"(",
"candidate",
",",
"key_table",
")",
":",
"# NOTE: Import just before checking to avoid circular imports.",
"from",
"fonduer",
".",
"features",
".",
"models",
"import",
"FeatureKey",
"from",
"fonduer",
".",
"supervision",
".",
"models",
"i... | Get the corresponding values for the key_table. | [
"Get",
"the",
"corresponding",
"values",
"for",
"the",
"key_table",
"."
] | 4520f86a716f03dcca458a9f4bddac75b4e7068f | https://github.com/HazyResearch/fonduer/blob/4520f86a716f03dcca458a9f4bddac75b4e7068f/src/fonduer/utils/utils_udf.py#L18-L31 |
230,009 | HazyResearch/fonduer | src/fonduer/utils/utils_udf.py | _batch_postgres_query | def _batch_postgres_query(table, records):
"""Break the list into chunks that can be processed as a single statement.
Postgres query cannot be too long or it will fail.
See: https://dba.stackexchange.com/questions/131399/is-there-a-maximum-
length-constraint-for-a-postgres-query
:param records: The full list of records to batch.
:type records: iterable
:param table: The sqlalchemy table.
:return: A generator of lists of records.
"""
if not records:
return
POSTGRESQL_MAX = 0x3FFFFFFF
# Create preamble and measure its length
preamble = (
"INSERT INTO "
+ table.__tablename__
+ " ("
+ ", ".join(records[0].keys())
+ ") VALUES ("
+ ", ".join(["?"] * len(records[0].keys()))
+ ")\n"
)
start = 0
end = 0
total_len = len(preamble)
while end < len(records):
record_len = sum([len(str(v)) for v in records[end].values()])
# Pre-increment to include the end element in the slice
end += 1
if total_len + record_len >= POSTGRESQL_MAX:
logger.debug(f"Splitting query due to length ({total_len} chars).")
yield records[start:end]
start = end
# Reset the total query length
total_len = len(preamble)
else:
total_len += record_len
yield records[start:end] | python | def _batch_postgres_query(table, records):
if not records:
return
POSTGRESQL_MAX = 0x3FFFFFFF
# Create preamble and measure its length
preamble = (
"INSERT INTO "
+ table.__tablename__
+ " ("
+ ", ".join(records[0].keys())
+ ") VALUES ("
+ ", ".join(["?"] * len(records[0].keys()))
+ ")\n"
)
start = 0
end = 0
total_len = len(preamble)
while end < len(records):
record_len = sum([len(str(v)) for v in records[end].values()])
# Pre-increment to include the end element in the slice
end += 1
if total_len + record_len >= POSTGRESQL_MAX:
logger.debug(f"Splitting query due to length ({total_len} chars).")
yield records[start:end]
start = end
# Reset the total query length
total_len = len(preamble)
else:
total_len += record_len
yield records[start:end] | [
"def",
"_batch_postgres_query",
"(",
"table",
",",
"records",
")",
":",
"if",
"not",
"records",
":",
"return",
"POSTGRESQL_MAX",
"=",
"0x3FFFFFFF",
"# Create preamble and measure its length",
"preamble",
"=",
"(",
"\"INSERT INTO \"",
"+",
"table",
".",
"__tablename__"... | Break the list into chunks that can be processed as a single statement.
Postgres query cannot be too long or it will fail.
See: https://dba.stackexchange.com/questions/131399/is-there-a-maximum-
length-constraint-for-a-postgres-query
:param records: The full list of records to batch.
:type records: iterable
:param table: The sqlalchemy table.
:return: A generator of lists of records. | [
"Break",
"the",
"list",
"into",
"chunks",
"that",
"can",
"be",
"processed",
"as",
"a",
"single",
"statement",
"."
] | 4520f86a716f03dcca458a9f4bddac75b4e7068f | https://github.com/HazyResearch/fonduer/blob/4520f86a716f03dcca458a9f4bddac75b4e7068f/src/fonduer/utils/utils_udf.py#L34-L79 |
230,010 | HazyResearch/fonduer | src/fonduer/utils/utils_udf.py | get_sparse_matrix_keys | def get_sparse_matrix_keys(session, key_table):
"""Return a list of keys for the sparse matrix."""
return session.query(key_table).order_by(key_table.name).all() | python | def get_sparse_matrix_keys(session, key_table):
return session.query(key_table).order_by(key_table.name).all() | [
"def",
"get_sparse_matrix_keys",
"(",
"session",
",",
"key_table",
")",
":",
"return",
"session",
".",
"query",
"(",
"key_table",
")",
".",
"order_by",
"(",
"key_table",
".",
"name",
")",
".",
"all",
"(",
")"
] | Return a list of keys for the sparse matrix. | [
"Return",
"a",
"list",
"of",
"keys",
"for",
"the",
"sparse",
"matrix",
"."
] | 4520f86a716f03dcca458a9f4bddac75b4e7068f | https://github.com/HazyResearch/fonduer/blob/4520f86a716f03dcca458a9f4bddac75b4e7068f/src/fonduer/utils/utils_udf.py#L82-L84 |
230,011 | HazyResearch/fonduer | src/fonduer/utils/utils_udf.py | batch_upsert_records | def batch_upsert_records(session, table, records):
"""Batch upsert records into postgresql database."""
if not records:
return
for record_batch in _batch_postgres_query(table, records):
stmt = insert(table.__table__)
stmt = stmt.on_conflict_do_update(
constraint=table.__table__.primary_key,
set_={
"keys": stmt.excluded.get("keys"),
"values": stmt.excluded.get("values"),
},
)
session.execute(stmt, record_batch)
session.commit() | python | def batch_upsert_records(session, table, records):
if not records:
return
for record_batch in _batch_postgres_query(table, records):
stmt = insert(table.__table__)
stmt = stmt.on_conflict_do_update(
constraint=table.__table__.primary_key,
set_={
"keys": stmt.excluded.get("keys"),
"values": stmt.excluded.get("values"),
},
)
session.execute(stmt, record_batch)
session.commit() | [
"def",
"batch_upsert_records",
"(",
"session",
",",
"table",
",",
"records",
")",
":",
"if",
"not",
"records",
":",
"return",
"for",
"record_batch",
"in",
"_batch_postgres_query",
"(",
"table",
",",
"records",
")",
":",
"stmt",
"=",
"insert",
"(",
"table",
... | Batch upsert records into postgresql database. | [
"Batch",
"upsert",
"records",
"into",
"postgresql",
"database",
"."
] | 4520f86a716f03dcca458a9f4bddac75b4e7068f | https://github.com/HazyResearch/fonduer/blob/4520f86a716f03dcca458a9f4bddac75b4e7068f/src/fonduer/utils/utils_udf.py#L87-L101 |
230,012 | HazyResearch/fonduer | src/fonduer/utils/utils_udf.py | get_docs_from_split | def get_docs_from_split(session, candidate_classes, split):
"""Return a list of documents that contain the candidates in the split."""
# Only grab the docs containing candidates from the given split.
sub_query = session.query(Candidate.id).filter(Candidate.split == split).subquery()
split_docs = set()
for candidate_class in candidate_classes:
split_docs.update(
cand.document
for cand in session.query(candidate_class)
.filter(candidate_class.id.in_(sub_query))
.all()
)
return split_docs | python | def get_docs_from_split(session, candidate_classes, split):
# Only grab the docs containing candidates from the given split.
sub_query = session.query(Candidate.id).filter(Candidate.split == split).subquery()
split_docs = set()
for candidate_class in candidate_classes:
split_docs.update(
cand.document
for cand in session.query(candidate_class)
.filter(candidate_class.id.in_(sub_query))
.all()
)
return split_docs | [
"def",
"get_docs_from_split",
"(",
"session",
",",
"candidate_classes",
",",
"split",
")",
":",
"# Only grab the docs containing candidates from the given split.",
"sub_query",
"=",
"session",
".",
"query",
"(",
"Candidate",
".",
"id",
")",
".",
"filter",
"(",
"Candid... | Return a list of documents that contain the candidates in the split. | [
"Return",
"a",
"list",
"of",
"documents",
"that",
"contain",
"the",
"candidates",
"in",
"the",
"split",
"."
] | 4520f86a716f03dcca458a9f4bddac75b4e7068f | https://github.com/HazyResearch/fonduer/blob/4520f86a716f03dcca458a9f4bddac75b4e7068f/src/fonduer/utils/utils_udf.py#L146-L158 |
230,013 | HazyResearch/fonduer | src/fonduer/utils/utils_udf.py | get_mapping | def get_mapping(session, table, candidates, generator, key_map):
"""Generate map of keys and values for the candidate from the generator.
:param session: The database session.
:param table: The table we will be inserting into (i.e. Feature or Label).
:param candidates: The candidates to get mappings for.
:param generator: A generator yielding (candidate_id, key, value) tuples.
:param key_map: A mutable dict which values will be added to as {key:
[relations]}.
:type key_map: Dict
:return: Generator of dictionaries of {"candidate_id": _, "keys": _, "values": _}
:rtype: generator of dict
"""
for cand in candidates:
# Grab the old values currently in the DB
try:
temp = session.query(table).filter(table.candidate_id == cand.id).one()
cand_map = dict(zip(temp.keys, temp.values))
except NoResultFound:
cand_map = {}
map_args = {"candidate_id": cand.id}
for cid, key, value in generator(cand):
if value == 0:
continue
cand_map[key] = value
# Assemble label arguments
map_args["keys"] = [*cand_map.keys()]
map_args["values"] = [*cand_map.values()]
# Update key_map by adding the candidate class for each key
for key in map_args["keys"]:
try:
key_map[key].add(cand.__class__.__tablename__)
except KeyError:
key_map[key] = {cand.__class__.__tablename__}
yield map_args | python | def get_mapping(session, table, candidates, generator, key_map):
for cand in candidates:
# Grab the old values currently in the DB
try:
temp = session.query(table).filter(table.candidate_id == cand.id).one()
cand_map = dict(zip(temp.keys, temp.values))
except NoResultFound:
cand_map = {}
map_args = {"candidate_id": cand.id}
for cid, key, value in generator(cand):
if value == 0:
continue
cand_map[key] = value
# Assemble label arguments
map_args["keys"] = [*cand_map.keys()]
map_args["values"] = [*cand_map.values()]
# Update key_map by adding the candidate class for each key
for key in map_args["keys"]:
try:
key_map[key].add(cand.__class__.__tablename__)
except KeyError:
key_map[key] = {cand.__class__.__tablename__}
yield map_args | [
"def",
"get_mapping",
"(",
"session",
",",
"table",
",",
"candidates",
",",
"generator",
",",
"key_map",
")",
":",
"for",
"cand",
"in",
"candidates",
":",
"# Grab the old values currently in the DB",
"try",
":",
"temp",
"=",
"session",
".",
"query",
"(",
"tabl... | Generate map of keys and values for the candidate from the generator.
:param session: The database session.
:param table: The table we will be inserting into (i.e. Feature or Label).
:param candidates: The candidates to get mappings for.
:param generator: A generator yielding (candidate_id, key, value) tuples.
:param key_map: A mutable dict which values will be added to as {key:
[relations]}.
:type key_map: Dict
:return: Generator of dictionaries of {"candidate_id": _, "keys": _, "values": _}
:rtype: generator of dict | [
"Generate",
"map",
"of",
"keys",
"and",
"values",
"for",
"the",
"candidate",
"from",
"the",
"generator",
"."
] | 4520f86a716f03dcca458a9f4bddac75b4e7068f | https://github.com/HazyResearch/fonduer/blob/4520f86a716f03dcca458a9f4bddac75b4e7068f/src/fonduer/utils/utils_udf.py#L161-L198 |
230,014 | HazyResearch/fonduer | src/fonduer/utils/utils_udf.py | get_cands_list_from_split | def get_cands_list_from_split(session, candidate_classes, doc, split):
"""Return the list of list of candidates from this document based on the split."""
cands = []
if split == ALL_SPLITS:
# Get cands from all splits
for candidate_class in candidate_classes:
cands.append(
session.query(candidate_class)
.filter(candidate_class.document_id == doc.id)
.all()
)
else:
# Get cands from the specified split
for candidate_class in candidate_classes:
cands.append(
session.query(candidate_class)
.filter(candidate_class.document_id == doc.id)
.filter(candidate_class.split == split)
.all()
)
return cands | python | def get_cands_list_from_split(session, candidate_classes, doc, split):
cands = []
if split == ALL_SPLITS:
# Get cands from all splits
for candidate_class in candidate_classes:
cands.append(
session.query(candidate_class)
.filter(candidate_class.document_id == doc.id)
.all()
)
else:
# Get cands from the specified split
for candidate_class in candidate_classes:
cands.append(
session.query(candidate_class)
.filter(candidate_class.document_id == doc.id)
.filter(candidate_class.split == split)
.all()
)
return cands | [
"def",
"get_cands_list_from_split",
"(",
"session",
",",
"candidate_classes",
",",
"doc",
",",
"split",
")",
":",
"cands",
"=",
"[",
"]",
"if",
"split",
"==",
"ALL_SPLITS",
":",
"# Get cands from all splits",
"for",
"candidate_class",
"in",
"candidate_classes",
":... | Return the list of list of candidates from this document based on the split. | [
"Return",
"the",
"list",
"of",
"list",
"of",
"candidates",
"from",
"this",
"document",
"based",
"on",
"the",
"split",
"."
] | 4520f86a716f03dcca458a9f4bddac75b4e7068f | https://github.com/HazyResearch/fonduer/blob/4520f86a716f03dcca458a9f4bddac75b4e7068f/src/fonduer/utils/utils_udf.py#L201-L221 |
230,015 | HazyResearch/fonduer | src/fonduer/utils/utils_udf.py | drop_all_keys | def drop_all_keys(session, key_table, candidate_classes):
"""Bulk drop annotation keys for all the candidate_classes in the table.
Rather than directly dropping the keys, this removes the candidate_classes
specified for the given keys only. If all candidate_classes are removed for
a key, the key is dropped.
:param key_table: The sqlalchemy class to insert into.
:param candidate_classes: A list of candidate classes to drop.
"""
if not candidate_classes:
return
candidate_classes = set([c.__tablename__ for c in candidate_classes])
# Select all rows that contain ANY of the candidate_classes
all_rows = (
session.query(key_table)
.filter(
key_table.candidate_classes.overlap(cast(candidate_classes, ARRAY(String)))
)
.all()
)
to_delete = set()
to_update = []
# All candidate classes will be the same for all keys, so just look at one
for row in all_rows:
# Remove the selected candidate_classes. If empty, mark for deletion.
row.candidate_classes = list(
set(row.candidate_classes) - set(candidate_classes)
)
if len(row.candidate_classes) == 0:
to_delete.add(row.name)
else:
to_update.append(
{"name": row.name, "candidate_classes": row.candidate_classes}
)
# Perform all deletes
if to_delete:
query = session.query(key_table).filter(key_table.name.in_(to_delete))
query.delete(synchronize_session="fetch")
# Perform all updates
if to_update:
for batch in _batch_postgres_query(key_table, to_update):
stmt = insert(key_table.__table__)
stmt = stmt.on_conflict_do_update(
constraint=key_table.__table__.primary_key,
set_={
"name": stmt.excluded.get("name"),
"candidate_classes": stmt.excluded.get("candidate_classes"),
},
)
session.execute(stmt, batch)
session.commit() | python | def drop_all_keys(session, key_table, candidate_classes):
if not candidate_classes:
return
candidate_classes = set([c.__tablename__ for c in candidate_classes])
# Select all rows that contain ANY of the candidate_classes
all_rows = (
session.query(key_table)
.filter(
key_table.candidate_classes.overlap(cast(candidate_classes, ARRAY(String)))
)
.all()
)
to_delete = set()
to_update = []
# All candidate classes will be the same for all keys, so just look at one
for row in all_rows:
# Remove the selected candidate_classes. If empty, mark for deletion.
row.candidate_classes = list(
set(row.candidate_classes) - set(candidate_classes)
)
if len(row.candidate_classes) == 0:
to_delete.add(row.name)
else:
to_update.append(
{"name": row.name, "candidate_classes": row.candidate_classes}
)
# Perform all deletes
if to_delete:
query = session.query(key_table).filter(key_table.name.in_(to_delete))
query.delete(synchronize_session="fetch")
# Perform all updates
if to_update:
for batch in _batch_postgres_query(key_table, to_update):
stmt = insert(key_table.__table__)
stmt = stmt.on_conflict_do_update(
constraint=key_table.__table__.primary_key,
set_={
"name": stmt.excluded.get("name"),
"candidate_classes": stmt.excluded.get("candidate_classes"),
},
)
session.execute(stmt, batch)
session.commit() | [
"def",
"drop_all_keys",
"(",
"session",
",",
"key_table",
",",
"candidate_classes",
")",
":",
"if",
"not",
"candidate_classes",
":",
"return",
"candidate_classes",
"=",
"set",
"(",
"[",
"c",
".",
"__tablename__",
"for",
"c",
"in",
"candidate_classes",
"]",
")"... | Bulk drop annotation keys for all the candidate_classes in the table.
Rather than directly dropping the keys, this removes the candidate_classes
specified for the given keys only. If all candidate_classes are removed for
a key, the key is dropped.
:param key_table: The sqlalchemy class to insert into.
:param candidate_classes: A list of candidate classes to drop. | [
"Bulk",
"drop",
"annotation",
"keys",
"for",
"all",
"the",
"candidate_classes",
"in",
"the",
"table",
"."
] | 4520f86a716f03dcca458a9f4bddac75b4e7068f | https://github.com/HazyResearch/fonduer/blob/4520f86a716f03dcca458a9f4bddac75b4e7068f/src/fonduer/utils/utils_udf.py#L224-L280 |
230,016 | HazyResearch/fonduer | src/fonduer/utils/utils_udf.py | drop_keys | def drop_keys(session, key_table, keys):
"""Bulk drop annotation keys to the specified table.
Rather than directly dropping the keys, this removes the candidate_classes
specified for the given keys only. If all candidate_classes are removed for
a key, the key is dropped.
:param key_table: The sqlalchemy class to insert into.
:param keys: A map of {name: [candidate_classes]}.
"""
# Do nothing if empty
if not keys:
return
for key_batch in _batch_postgres_query(
key_table, [{"name": k[0], "candidate_classes": k[1]} for k in keys.items()]
):
all_rows = (
session.query(key_table)
.filter(key_table.name.in_([key["name"] for key in key_batch]))
.all()
)
to_delete = set()
to_update = []
# All candidate classes will be the same for all keys, so just look at one
candidate_classes = key_batch[0]["candidate_classes"]
for row in all_rows:
# Remove the selected candidate_classes. If empty, mark for deletion.
row.candidate_classes = list(
set(row.candidate_classes) - set(candidate_classes)
)
if len(row.candidate_classes) == 0:
to_delete.add(row.name)
else:
to_update.append(
{"name": row.name, "candidate_classes": row.candidate_classes}
)
# Perform all deletes
if to_delete:
query = session.query(key_table).filter(key_table.name.in_(to_delete))
query.delete(synchronize_session="fetch")
# Perform all updates
if to_update:
stmt = insert(key_table.__table__)
stmt = stmt.on_conflict_do_update(
constraint=key_table.__table__.primary_key,
set_={
"name": stmt.excluded.get("name"),
"candidate_classes": stmt.excluded.get("candidate_classes"),
},
)
session.execute(stmt, to_update)
session.commit() | python | def drop_keys(session, key_table, keys):
# Do nothing if empty
if not keys:
return
for key_batch in _batch_postgres_query(
key_table, [{"name": k[0], "candidate_classes": k[1]} for k in keys.items()]
):
all_rows = (
session.query(key_table)
.filter(key_table.name.in_([key["name"] for key in key_batch]))
.all()
)
to_delete = set()
to_update = []
# All candidate classes will be the same for all keys, so just look at one
candidate_classes = key_batch[0]["candidate_classes"]
for row in all_rows:
# Remove the selected candidate_classes. If empty, mark for deletion.
row.candidate_classes = list(
set(row.candidate_classes) - set(candidate_classes)
)
if len(row.candidate_classes) == 0:
to_delete.add(row.name)
else:
to_update.append(
{"name": row.name, "candidate_classes": row.candidate_classes}
)
# Perform all deletes
if to_delete:
query = session.query(key_table).filter(key_table.name.in_(to_delete))
query.delete(synchronize_session="fetch")
# Perform all updates
if to_update:
stmt = insert(key_table.__table__)
stmt = stmt.on_conflict_do_update(
constraint=key_table.__table__.primary_key,
set_={
"name": stmt.excluded.get("name"),
"candidate_classes": stmt.excluded.get("candidate_classes"),
},
)
session.execute(stmt, to_update)
session.commit() | [
"def",
"drop_keys",
"(",
"session",
",",
"key_table",
",",
"keys",
")",
":",
"# Do nothing if empty",
"if",
"not",
"keys",
":",
"return",
"for",
"key_batch",
"in",
"_batch_postgres_query",
"(",
"key_table",
",",
"[",
"{",
"\"name\"",
":",
"k",
"[",
"0",
"]... | Bulk drop annotation keys to the specified table.
Rather than directly dropping the keys, this removes the candidate_classes
specified for the given keys only. If all candidate_classes are removed for
a key, the key is dropped.
:param key_table: The sqlalchemy class to insert into.
:param keys: A map of {name: [candidate_classes]}. | [
"Bulk",
"drop",
"annotation",
"keys",
"to",
"the",
"specified",
"table",
"."
] | 4520f86a716f03dcca458a9f4bddac75b4e7068f | https://github.com/HazyResearch/fonduer/blob/4520f86a716f03dcca458a9f4bddac75b4e7068f/src/fonduer/utils/utils_udf.py#L283-L339 |
230,017 | HazyResearch/fonduer | src/fonduer/utils/utils_udf.py | upsert_keys | def upsert_keys(session, key_table, keys):
"""Bulk add annotation keys to the specified table.
:param key_table: The sqlalchemy class to insert into.
:param keys: A map of {name: [candidate_classes]}.
"""
# Do nothing if empty
if not keys:
return
for key_batch in _batch_postgres_query(
key_table, [{"name": k[0], "candidate_classes": k[1]} for k in keys.items()]
):
stmt = insert(key_table.__table__)
stmt = stmt.on_conflict_do_update(
constraint=key_table.__table__.primary_key,
set_={
"name": stmt.excluded.get("name"),
"candidate_classes": stmt.excluded.get("candidate_classes"),
},
)
while True:
try:
session.execute(stmt, key_batch)
session.commit()
break
except Exception as e:
logger.debug(e) | python | def upsert_keys(session, key_table, keys):
# Do nothing if empty
if not keys:
return
for key_batch in _batch_postgres_query(
key_table, [{"name": k[0], "candidate_classes": k[1]} for k in keys.items()]
):
stmt = insert(key_table.__table__)
stmt = stmt.on_conflict_do_update(
constraint=key_table.__table__.primary_key,
set_={
"name": stmt.excluded.get("name"),
"candidate_classes": stmt.excluded.get("candidate_classes"),
},
)
while True:
try:
session.execute(stmt, key_batch)
session.commit()
break
except Exception as e:
logger.debug(e) | [
"def",
"upsert_keys",
"(",
"session",
",",
"key_table",
",",
"keys",
")",
":",
"# Do nothing if empty",
"if",
"not",
"keys",
":",
"return",
"for",
"key_batch",
"in",
"_batch_postgres_query",
"(",
"key_table",
",",
"[",
"{",
"\"name\"",
":",
"k",
"[",
"0",
... | Bulk add annotation keys to the specified table.
:param key_table: The sqlalchemy class to insert into.
:param keys: A map of {name: [candidate_classes]}. | [
"Bulk",
"add",
"annotation",
"keys",
"to",
"the",
"specified",
"table",
"."
] | 4520f86a716f03dcca458a9f4bddac75b4e7068f | https://github.com/HazyResearch/fonduer/blob/4520f86a716f03dcca458a9f4bddac75b4e7068f/src/fonduer/utils/utils_udf.py#L342-L369 |
230,018 | HazyResearch/fonduer | src/fonduer/supervision/labeler.py | Labeler.update | def update(self, docs=None, split=0, lfs=None, parallelism=None, progress_bar=True):
"""Update the labels of the specified candidates based on the provided LFs.
:param docs: If provided, apply the updated LFs to all the candidates
in these documents.
:param split: If docs is None, apply the updated LFs to the candidates
in this particular split.
:param lfs: A list of lists of labeling functions to update. Each list
should correspond with the candidate_classes used to initialize the
Labeler.
:param parallelism: How many threads to use for extraction. This will
override the parallelism value used to initialize the Labeler if
it is provided.
:type parallelism: int
:param progress_bar: Whether or not to display a progress bar. The
progress bar is measured per document.
:type progress_bar: bool
"""
if lfs is None:
raise ValueError("Please provide a list of lists of labeling functions.")
if len(lfs) != len(self.candidate_classes):
raise ValueError("Please provide LFs for each candidate class.")
self.apply(
docs=docs,
split=split,
lfs=lfs,
train=True,
clear=False,
parallelism=parallelism,
progress_bar=progress_bar,
) | python | def update(self, docs=None, split=0, lfs=None, parallelism=None, progress_bar=True):
if lfs is None:
raise ValueError("Please provide a list of lists of labeling functions.")
if len(lfs) != len(self.candidate_classes):
raise ValueError("Please provide LFs for each candidate class.")
self.apply(
docs=docs,
split=split,
lfs=lfs,
train=True,
clear=False,
parallelism=parallelism,
progress_bar=progress_bar,
) | [
"def",
"update",
"(",
"self",
",",
"docs",
"=",
"None",
",",
"split",
"=",
"0",
",",
"lfs",
"=",
"None",
",",
"parallelism",
"=",
"None",
",",
"progress_bar",
"=",
"True",
")",
":",
"if",
"lfs",
"is",
"None",
":",
"raise",
"ValueError",
"(",
"\"Ple... | Update the labels of the specified candidates based on the provided LFs.
:param docs: If provided, apply the updated LFs to all the candidates
in these documents.
:param split: If docs is None, apply the updated LFs to the candidates
in this particular split.
:param lfs: A list of lists of labeling functions to update. Each list
should correspond with the candidate_classes used to initialize the
Labeler.
:param parallelism: How many threads to use for extraction. This will
override the parallelism value used to initialize the Labeler if
it is provided.
:type parallelism: int
:param progress_bar: Whether or not to display a progress bar. The
progress bar is measured per document.
:type progress_bar: bool | [
"Update",
"the",
"labels",
"of",
"the",
"specified",
"candidates",
"based",
"on",
"the",
"provided",
"LFs",
"."
] | 4520f86a716f03dcca458a9f4bddac75b4e7068f | https://github.com/HazyResearch/fonduer/blob/4520f86a716f03dcca458a9f4bddac75b4e7068f/src/fonduer/supervision/labeler.py#L43-L75 |
230,019 | HazyResearch/fonduer | src/fonduer/supervision/labeler.py | Labeler.apply | def apply(
self,
docs=None,
split=0,
train=False,
lfs=None,
clear=True,
parallelism=None,
progress_bar=True,
):
"""Apply the labels of the specified candidates based on the provided LFs.
:param docs: If provided, apply the LFs to all the candidates in these
documents.
:param split: If docs is None, apply the LFs to the candidates in this
particular split.
:type split: int
:param train: Whether or not to update the global key set of labels and
the labels of candidates.
:type train: bool
:param lfs: A list of lists of labeling functions to apply. Each list
should correspond with the candidate_classes used to initialize the
Labeler.
:type lfs: list of lists
:param clear: Whether or not to clear the labels table before applying
these LFs.
:type clear: bool
:param parallelism: How many threads to use for extraction. This will
override the parallelism value used to initialize the Labeler if
it is provided.
:type parallelism: int
:param progress_bar: Whether or not to display a progress bar. The
progress bar is measured per document.
:type progress_bar: bool
:raises ValueError: If labeling functions are not provided for each
candidate class.
"""
if lfs is None:
raise ValueError("Please provide a list of labeling functions.")
if len(lfs) != len(self.candidate_classes):
raise ValueError("Please provide LFs for each candidate class.")
self.lfs = lfs
if docs:
# Call apply on the specified docs for all splits
split = ALL_SPLITS
super(Labeler, self).apply(
docs,
split=split,
train=train,
lfs=self.lfs,
clear=clear,
parallelism=parallelism,
progress_bar=progress_bar,
)
# Needed to sync the bulk operations
self.session.commit()
else:
# Only grab the docs containing candidates from the given split.
split_docs = get_docs_from_split(
self.session, self.candidate_classes, split
)
super(Labeler, self).apply(
split_docs,
split=split,
train=train,
lfs=self.lfs,
clear=clear,
parallelism=parallelism,
progress_bar=progress_bar,
)
# Needed to sync the bulk operations
self.session.commit() | python | def apply(
self,
docs=None,
split=0,
train=False,
lfs=None,
clear=True,
parallelism=None,
progress_bar=True,
):
if lfs is None:
raise ValueError("Please provide a list of labeling functions.")
if len(lfs) != len(self.candidate_classes):
raise ValueError("Please provide LFs for each candidate class.")
self.lfs = lfs
if docs:
# Call apply on the specified docs for all splits
split = ALL_SPLITS
super(Labeler, self).apply(
docs,
split=split,
train=train,
lfs=self.lfs,
clear=clear,
parallelism=parallelism,
progress_bar=progress_bar,
)
# Needed to sync the bulk operations
self.session.commit()
else:
# Only grab the docs containing candidates from the given split.
split_docs = get_docs_from_split(
self.session, self.candidate_classes, split
)
super(Labeler, self).apply(
split_docs,
split=split,
train=train,
lfs=self.lfs,
clear=clear,
parallelism=parallelism,
progress_bar=progress_bar,
)
# Needed to sync the bulk operations
self.session.commit() | [
"def",
"apply",
"(",
"self",
",",
"docs",
"=",
"None",
",",
"split",
"=",
"0",
",",
"train",
"=",
"False",
",",
"lfs",
"=",
"None",
",",
"clear",
"=",
"True",
",",
"parallelism",
"=",
"None",
",",
"progress_bar",
"=",
"True",
",",
")",
":",
"if",... | Apply the labels of the specified candidates based on the provided LFs.
:param docs: If provided, apply the LFs to all the candidates in these
documents.
:param split: If docs is None, apply the LFs to the candidates in this
particular split.
:type split: int
:param train: Whether or not to update the global key set of labels and
the labels of candidates.
:type train: bool
:param lfs: A list of lists of labeling functions to apply. Each list
should correspond with the candidate_classes used to initialize the
Labeler.
:type lfs: list of lists
:param clear: Whether or not to clear the labels table before applying
these LFs.
:type clear: bool
:param parallelism: How many threads to use for extraction. This will
override the parallelism value used to initialize the Labeler if
it is provided.
:type parallelism: int
:param progress_bar: Whether or not to display a progress bar. The
progress bar is measured per document.
:type progress_bar: bool
:raises ValueError: If labeling functions are not provided for each
candidate class. | [
"Apply",
"the",
"labels",
"of",
"the",
"specified",
"candidates",
"based",
"on",
"the",
"provided",
"LFs",
"."
] | 4520f86a716f03dcca458a9f4bddac75b4e7068f | https://github.com/HazyResearch/fonduer/blob/4520f86a716f03dcca458a9f4bddac75b4e7068f/src/fonduer/supervision/labeler.py#L77-L151 |
230,020 | HazyResearch/fonduer | src/fonduer/supervision/labeler.py | Labeler.clear | def clear(self, train, split, lfs=None):
"""Delete Labels of each class from the database.
:param train: Whether or not to clear the LabelKeys.
:type train: bool
:param split: Which split of candidates to clear labels from.
:type split: int
:param lfs: This parameter is ignored.
"""
# Clear Labels for the candidates in the split passed in.
logger.info(f"Clearing Labels (split {split})")
sub_query = (
self.session.query(Candidate.id).filter(Candidate.split == split).subquery()
)
query = self.session.query(Label).filter(Label.candidate_id.in_(sub_query))
query.delete(synchronize_session="fetch")
# Delete all old annotation keys
if train:
logger.debug(f"Clearing all LabelKeys from {self.candidate_classes}...")
drop_all_keys(self.session, LabelKey, self.candidate_classes) | python | def clear(self, train, split, lfs=None):
# Clear Labels for the candidates in the split passed in.
logger.info(f"Clearing Labels (split {split})")
sub_query = (
self.session.query(Candidate.id).filter(Candidate.split == split).subquery()
)
query = self.session.query(Label).filter(Label.candidate_id.in_(sub_query))
query.delete(synchronize_session="fetch")
# Delete all old annotation keys
if train:
logger.debug(f"Clearing all LabelKeys from {self.candidate_classes}...")
drop_all_keys(self.session, LabelKey, self.candidate_classes) | [
"def",
"clear",
"(",
"self",
",",
"train",
",",
"split",
",",
"lfs",
"=",
"None",
")",
":",
"# Clear Labels for the candidates in the split passed in.",
"logger",
".",
"info",
"(",
"f\"Clearing Labels (split {split})\"",
")",
"sub_query",
"=",
"(",
"self",
".",
"s... | Delete Labels of each class from the database.
:param train: Whether or not to clear the LabelKeys.
:type train: bool
:param split: Which split of candidates to clear labels from.
:type split: int
:param lfs: This parameter is ignored. | [
"Delete",
"Labels",
"of",
"each",
"class",
"from",
"the",
"database",
"."
] | 4520f86a716f03dcca458a9f4bddac75b4e7068f | https://github.com/HazyResearch/fonduer/blob/4520f86a716f03dcca458a9f4bddac75b4e7068f/src/fonduer/supervision/labeler.py#L209-L230 |
230,021 | HazyResearch/fonduer | src/fonduer/supervision/labeler.py | Labeler.clear_all | def clear_all(self):
"""Delete all Labels."""
logger.info("Clearing ALL Labels and LabelKeys.")
self.session.query(Label).delete(synchronize_session="fetch")
self.session.query(LabelKey).delete(synchronize_session="fetch") | python | def clear_all(self):
logger.info("Clearing ALL Labels and LabelKeys.")
self.session.query(Label).delete(synchronize_session="fetch")
self.session.query(LabelKey).delete(synchronize_session="fetch") | [
"def",
"clear_all",
"(",
"self",
")",
":",
"logger",
".",
"info",
"(",
"\"Clearing ALL Labels and LabelKeys.\"",
")",
"self",
".",
"session",
".",
"query",
"(",
"Label",
")",
".",
"delete",
"(",
"synchronize_session",
"=",
"\"fetch\"",
")",
"self",
".",
"ses... | Delete all Labels. | [
"Delete",
"all",
"Labels",
"."
] | 4520f86a716f03dcca458a9f4bddac75b4e7068f | https://github.com/HazyResearch/fonduer/blob/4520f86a716f03dcca458a9f4bddac75b4e7068f/src/fonduer/supervision/labeler.py#L232-L236 |
230,022 | HazyResearch/fonduer | src/fonduer/supervision/labeler.py | LabelerUDF._f_gen | def _f_gen(self, c):
"""Convert lfs into a generator of id, name, and labels.
In particular, catch verbose values and convert to integer ones.
"""
lf_idx = self.candidate_classes.index(c.__class__)
labels = lambda c: [(c.id, lf.__name__, lf(c)) for lf in self.lfs[lf_idx]]
for cid, lf_key, label in labels(c):
# Note: We assume if the LF output is an int, it is already
# mapped correctly
if isinstance(label, int):
yield cid, lf_key, label
# None is a protected LF output value corresponding to 0,
# representing LF abstaining
elif label is None:
yield cid, lf_key, 0
elif label in c.values:
if c.cardinality > 2:
yield cid, lf_key, c.values.index(label) + 1
# Note: Would be nice to not special-case here, but for
# consistency we leave binary LF range as {-1,0,1}
else:
val = 1 if c.values.index(label) == 0 else -1
yield cid, lf_key, val
else:
raise ValueError(
f"Can't parse label value {label} for candidate values {c.values}"
) | python | def _f_gen(self, c):
lf_idx = self.candidate_classes.index(c.__class__)
labels = lambda c: [(c.id, lf.__name__, lf(c)) for lf in self.lfs[lf_idx]]
for cid, lf_key, label in labels(c):
# Note: We assume if the LF output is an int, it is already
# mapped correctly
if isinstance(label, int):
yield cid, lf_key, label
# None is a protected LF output value corresponding to 0,
# representing LF abstaining
elif label is None:
yield cid, lf_key, 0
elif label in c.values:
if c.cardinality > 2:
yield cid, lf_key, c.values.index(label) + 1
# Note: Would be nice to not special-case here, but for
# consistency we leave binary LF range as {-1,0,1}
else:
val = 1 if c.values.index(label) == 0 else -1
yield cid, lf_key, val
else:
raise ValueError(
f"Can't parse label value {label} for candidate values {c.values}"
) | [
"def",
"_f_gen",
"(",
"self",
",",
"c",
")",
":",
"lf_idx",
"=",
"self",
".",
"candidate_classes",
".",
"index",
"(",
"c",
".",
"__class__",
")",
"labels",
"=",
"lambda",
"c",
":",
"[",
"(",
"c",
".",
"id",
",",
"lf",
".",
"__name__",
",",
"lf",
... | Convert lfs into a generator of id, name, and labels.
In particular, catch verbose values and convert to integer ones. | [
"Convert",
"lfs",
"into",
"a",
"generator",
"of",
"id",
"name",
"and",
"labels",
"."
] | 4520f86a716f03dcca458a9f4bddac75b4e7068f | https://github.com/HazyResearch/fonduer/blob/4520f86a716f03dcca458a9f4bddac75b4e7068f/src/fonduer/supervision/labeler.py#L276-L303 |
230,023 | C4ptainCrunch/ics.py | ics/utils.py | arrow_get | def arrow_get(string):
'''this function exists because ICS uses ISO 8601 without dashes or
colons, i.e. not ISO 8601 at all.'''
# replace slashes with dashes
if '/' in string:
string = string.replace('/', '-')
# if string contains dashes, assume it to be proper ISO 8601
if '-' in string:
return arrow.get(string)
string = string.rstrip('Z')
return arrow.get(string, DATE_FORMATS[len(string)]) | python | def arrow_get(string):
'''this function exists because ICS uses ISO 8601 without dashes or
colons, i.e. not ISO 8601 at all.'''
# replace slashes with dashes
if '/' in string:
string = string.replace('/', '-')
# if string contains dashes, assume it to be proper ISO 8601
if '-' in string:
return arrow.get(string)
string = string.rstrip('Z')
return arrow.get(string, DATE_FORMATS[len(string)]) | [
"def",
"arrow_get",
"(",
"string",
")",
":",
"# replace slashes with dashes",
"if",
"'/'",
"in",
"string",
":",
"string",
"=",
"string",
".",
"replace",
"(",
"'/'",
",",
"'-'",
")",
"# if string contains dashes, assume it to be proper ISO 8601",
"if",
"'-'",
"in",
... | this function exists because ICS uses ISO 8601 without dashes or
colons, i.e. not ISO 8601 at all. | [
"this",
"function",
"exists",
"because",
"ICS",
"uses",
"ISO",
"8601",
"without",
"dashes",
"or",
"colons",
"i",
".",
"e",
".",
"not",
"ISO",
"8601",
"at",
"all",
"."
] | bd918ec7453a7cf73a906cdcc78bd88eb4bab71b | https://github.com/C4ptainCrunch/ics.py/blob/bd918ec7453a7cf73a906cdcc78bd88eb4bab71b/ics/utils.py#L35-L48 |
230,024 | C4ptainCrunch/ics.py | ics/utils.py | parse_duration | def parse_duration(line):
"""
Return a timedelta object from a string in the DURATION property format
"""
DAYS, SECS = {'D': 1, 'W': 7}, {'S': 1, 'M': 60, 'H': 3600}
sign, i = 1, 0
if line[i] in '-+':
if line[i] == '-':
sign = -1
i += 1
if line[i] != 'P':
raise parse.ParseError()
i += 1
days, secs = 0, 0
while i < len(line):
if line[i] == 'T':
i += 1
if i == len(line):
break
j = i
while line[j].isdigit():
j += 1
if i == j:
raise parse.ParseError()
val = int(line[i:j])
if line[j] in DAYS:
days += val * DAYS[line[j]]
DAYS.pop(line[j])
elif line[j] in SECS:
secs += val * SECS[line[j]]
SECS.pop(line[j])
else:
raise parse.ParseError()
i = j + 1
return timedelta(sign * days, sign * secs) | python | def parse_duration(line):
DAYS, SECS = {'D': 1, 'W': 7}, {'S': 1, 'M': 60, 'H': 3600}
sign, i = 1, 0
if line[i] in '-+':
if line[i] == '-':
sign = -1
i += 1
if line[i] != 'P':
raise parse.ParseError()
i += 1
days, secs = 0, 0
while i < len(line):
if line[i] == 'T':
i += 1
if i == len(line):
break
j = i
while line[j].isdigit():
j += 1
if i == j:
raise parse.ParseError()
val = int(line[i:j])
if line[j] in DAYS:
days += val * DAYS[line[j]]
DAYS.pop(line[j])
elif line[j] in SECS:
secs += val * SECS[line[j]]
SECS.pop(line[j])
else:
raise parse.ParseError()
i = j + 1
return timedelta(sign * days, sign * secs) | [
"def",
"parse_duration",
"(",
"line",
")",
":",
"DAYS",
",",
"SECS",
"=",
"{",
"'D'",
":",
"1",
",",
"'W'",
":",
"7",
"}",
",",
"{",
"'S'",
":",
"1",
",",
"'M'",
":",
"60",
",",
"'H'",
":",
"3600",
"}",
"sign",
",",
"i",
"=",
"1",
",",
"0... | Return a timedelta object from a string in the DURATION property format | [
"Return",
"a",
"timedelta",
"object",
"from",
"a",
"string",
"in",
"the",
"DURATION",
"property",
"format"
] | bd918ec7453a7cf73a906cdcc78bd88eb4bab71b | https://github.com/C4ptainCrunch/ics.py/blob/bd918ec7453a7cf73a906cdcc78bd88eb4bab71b/ics/utils.py#L109-L143 |
230,025 | C4ptainCrunch/ics.py | ics/utils.py | timedelta_to_duration | def timedelta_to_duration(dt):
"""
Return a string according to the DURATION property format
from a timedelta object
"""
days, secs = dt.days, dt.seconds
res = 'P'
if days // 7:
res += str(days // 7) + 'W'
days %= 7
if days:
res += str(days) + 'D'
if secs:
res += 'T'
if secs // 3600:
res += str(secs // 3600) + 'H'
secs %= 3600
if secs // 60:
res += str(secs // 60) + 'M'
secs %= 60
if secs:
res += str(secs) + 'S'
return res | python | def timedelta_to_duration(dt):
days, secs = dt.days, dt.seconds
res = 'P'
if days // 7:
res += str(days // 7) + 'W'
days %= 7
if days:
res += str(days) + 'D'
if secs:
res += 'T'
if secs // 3600:
res += str(secs // 3600) + 'H'
secs %= 3600
if secs // 60:
res += str(secs // 60) + 'M'
secs %= 60
if secs:
res += str(secs) + 'S'
return res | [
"def",
"timedelta_to_duration",
"(",
"dt",
")",
":",
"days",
",",
"secs",
"=",
"dt",
".",
"days",
",",
"dt",
".",
"seconds",
"res",
"=",
"'P'",
"if",
"days",
"//",
"7",
":",
"res",
"+=",
"str",
"(",
"days",
"//",
"7",
")",
"+",
"'W'",
"days",
"... | Return a string according to the DURATION property format
from a timedelta object | [
"Return",
"a",
"string",
"according",
"to",
"the",
"DURATION",
"property",
"format",
"from",
"a",
"timedelta",
"object"
] | bd918ec7453a7cf73a906cdcc78bd88eb4bab71b | https://github.com/C4ptainCrunch/ics.py/blob/bd918ec7453a7cf73a906cdcc78bd88eb4bab71b/ics/utils.py#L146-L168 |
230,026 | C4ptainCrunch/ics.py | ics/event.py | Event.end | def end(self):
"""Get or set the end of the event.
| Will return an :class:`Arrow` object.
| May be set to anything that :func:`Arrow.get` understands.
| If set to a non null value, removes any already
existing duration.
| Setting to None will have unexpected behavior if
begin is not None.
| Must not be set to an inferior value than self.begin.
"""
if self._duration: # if end is duration defined
# return the beginning + duration
return self.begin + self._duration
elif self._end_time: # if end is time defined
if self.all_day:
return self._end_time
else:
return self._end_time
elif self._begin: # if end is not defined
if self.all_day:
return self._begin + timedelta(days=1)
else:
# instant event
return self._begin
else:
return None | python | def end(self):
if self._duration: # if end is duration defined
# return the beginning + duration
return self.begin + self._duration
elif self._end_time: # if end is time defined
if self.all_day:
return self._end_time
else:
return self._end_time
elif self._begin: # if end is not defined
if self.all_day:
return self._begin + timedelta(days=1)
else:
# instant event
return self._begin
else:
return None | [
"def",
"end",
"(",
"self",
")",
":",
"if",
"self",
".",
"_duration",
":",
"# if end is duration defined",
"# return the beginning + duration",
"return",
"self",
".",
"begin",
"+",
"self",
".",
"_duration",
"elif",
"self",
".",
"_end_time",
":",
"# if end is time d... | Get or set the end of the event.
| Will return an :class:`Arrow` object.
| May be set to anything that :func:`Arrow.get` understands.
| If set to a non null value, removes any already
existing duration.
| Setting to None will have unexpected behavior if
begin is not None.
| Must not be set to an inferior value than self.begin. | [
"Get",
"or",
"set",
"the",
"end",
"of",
"the",
"event",
"."
] | bd918ec7453a7cf73a906cdcc78bd88eb4bab71b | https://github.com/C4ptainCrunch/ics.py/blob/bd918ec7453a7cf73a906cdcc78bd88eb4bab71b/ics/event.py#L139-L166 |
230,027 | C4ptainCrunch/ics.py | ics/event.py | Event.duration | def duration(self):
"""Get or set the duration of the event.
| Will return a timedelta object.
| May be set to anything that timedelta() understands.
| May be set with a dict ({"days":2, "hours":6}).
| If set to a non null value, removes any already
existing end time.
"""
if self._duration:
return self._duration
elif self.end:
# because of the clever getter for end, this also takes care of all_day events
return self.end - self.begin
else:
# event has neither start, nor end, nor duration
return None | python | def duration(self):
if self._duration:
return self._duration
elif self.end:
# because of the clever getter for end, this also takes care of all_day events
return self.end - self.begin
else:
# event has neither start, nor end, nor duration
return None | [
"def",
"duration",
"(",
"self",
")",
":",
"if",
"self",
".",
"_duration",
":",
"return",
"self",
".",
"_duration",
"elif",
"self",
".",
"end",
":",
"# because of the clever getter for end, this also takes care of all_day events",
"return",
"self",
".",
"end",
"-",
... | Get or set the duration of the event.
| Will return a timedelta object.
| May be set to anything that timedelta() understands.
| May be set with a dict ({"days":2, "hours":6}).
| If set to a non null value, removes any already
existing end time. | [
"Get",
"or",
"set",
"the",
"duration",
"of",
"the",
"event",
"."
] | bd918ec7453a7cf73a906cdcc78bd88eb4bab71b | https://github.com/C4ptainCrunch/ics.py/blob/bd918ec7453a7cf73a906cdcc78bd88eb4bab71b/ics/event.py#L179-L195 |
230,028 | C4ptainCrunch/ics.py | ics/event.py | Event.make_all_day | def make_all_day(self):
"""Transforms self to an all-day event.
The event will span all the days from the begin to the end day.
"""
if self.all_day:
# Do nothing if we already are a all day event
return
begin_day = self.begin.floor('day')
end_day = self.end.floor('day')
self._begin = begin_day
# for a one day event, we don't need a _end_time
if begin_day == end_day:
self._end_time = None
else:
self._end_time = end_day + timedelta(days=1)
self._duration = None
self._begin_precision = 'day' | python | def make_all_day(self):
if self.all_day:
# Do nothing if we already are a all day event
return
begin_day = self.begin.floor('day')
end_day = self.end.floor('day')
self._begin = begin_day
# for a one day event, we don't need a _end_time
if begin_day == end_day:
self._end_time = None
else:
self._end_time = end_day + timedelta(days=1)
self._duration = None
self._begin_precision = 'day' | [
"def",
"make_all_day",
"(",
"self",
")",
":",
"if",
"self",
".",
"all_day",
":",
"# Do nothing if we already are a all day event",
"return",
"begin_day",
"=",
"self",
".",
"begin",
".",
"floor",
"(",
"'day'",
")",
"end_day",
"=",
"self",
".",
"end",
".",
"fl... | Transforms self to an all-day event.
The event will span all the days from the begin to the end day. | [
"Transforms",
"self",
"to",
"an",
"all",
"-",
"day",
"event",
"."
] | bd918ec7453a7cf73a906cdcc78bd88eb4bab71b | https://github.com/C4ptainCrunch/ics.py/blob/bd918ec7453a7cf73a906cdcc78bd88eb4bab71b/ics/event.py#L220-L241 |
230,029 | C4ptainCrunch/ics.py | ics/event.py | Event.join | def join(self, other, *args, **kwarg):
"""Create a new event which covers the time range of two intersecting events
All extra parameters are passed to the Event constructor.
Args:
other: the other event
Returns:
a new Event instance
"""
event = Event(*args, **kwarg)
if self.intersects(other):
if self.starts_within(other):
event.begin = other.begin
else:
event.begin = self.begin
if self.ends_within(other):
event.end = other.end
else:
event.end = self.end
return event
raise ValueError('Cannot join {} with {}: they don\'t intersect.'.format(self, other)) | python | def join(self, other, *args, **kwarg):
event = Event(*args, **kwarg)
if self.intersects(other):
if self.starts_within(other):
event.begin = other.begin
else:
event.begin = self.begin
if self.ends_within(other):
event.end = other.end
else:
event.end = self.end
return event
raise ValueError('Cannot join {} with {}: they don\'t intersect.'.format(self, other)) | [
"def",
"join",
"(",
"self",
",",
"other",
",",
"*",
"args",
",",
"*",
"*",
"kwarg",
")",
":",
"event",
"=",
"Event",
"(",
"*",
"args",
",",
"*",
"*",
"kwarg",
")",
"if",
"self",
".",
"intersects",
"(",
"other",
")",
":",
"if",
"self",
".",
"s... | Create a new event which covers the time range of two intersecting events
All extra parameters are passed to the Event constructor.
Args:
other: the other event
Returns:
a new Event instance | [
"Create",
"a",
"new",
"event",
"which",
"covers",
"the",
"time",
"range",
"of",
"two",
"intersecting",
"events"
] | bd918ec7453a7cf73a906cdcc78bd88eb4bab71b | https://github.com/C4ptainCrunch/ics.py/blob/bd918ec7453a7cf73a906cdcc78bd88eb4bab71b/ics/event.py#L387-L411 |
230,030 | C4ptainCrunch/ics.py | ics/icalendar.py | timezone | def timezone(calendar, vtimezones):
"""Receives a list of VTIMEZONE blocks.
Parses them and adds them to calendar._timezones.
"""
for vtimezone in vtimezones:
remove_x(vtimezone) # Remove non standard lines from the block
fake_file = StringIO()
fake_file.write(str(vtimezone)) # Represent the block as a string
fake_file.seek(0)
timezones = tzical(fake_file) # tzical does not like strings
# timezones is a tzical object and could contain multiple timezones
for key in timezones.keys():
calendar._timezones[key] = timezones.get(key) | python | def timezone(calendar, vtimezones):
for vtimezone in vtimezones:
remove_x(vtimezone) # Remove non standard lines from the block
fake_file = StringIO()
fake_file.write(str(vtimezone)) # Represent the block as a string
fake_file.seek(0)
timezones = tzical(fake_file) # tzical does not like strings
# timezones is a tzical object and could contain multiple timezones
for key in timezones.keys():
calendar._timezones[key] = timezones.get(key) | [
"def",
"timezone",
"(",
"calendar",
",",
"vtimezones",
")",
":",
"for",
"vtimezone",
"in",
"vtimezones",
":",
"remove_x",
"(",
"vtimezone",
")",
"# Remove non standard lines from the block",
"fake_file",
"=",
"StringIO",
"(",
")",
"fake_file",
".",
"write",
"(",
... | Receives a list of VTIMEZONE blocks.
Parses them and adds them to calendar._timezones. | [
"Receives",
"a",
"list",
"of",
"VTIMEZONE",
"blocks",
"."
] | bd918ec7453a7cf73a906cdcc78bd88eb4bab71b | https://github.com/C4ptainCrunch/ics.py/blob/bd918ec7453a7cf73a906cdcc78bd88eb4bab71b/ics/icalendar.py#L184-L197 |
230,031 | C4ptainCrunch/ics.py | ics/todo.py | Todo.due | def due(self):
"""Get or set the end of the todo.
| Will return an :class:`Arrow` object.
| May be set to anything that :func:`Arrow.get` understands.
| If set to a non null value, removes any already
existing duration.
| Setting to None will have unexpected behavior if
begin is not None.
| Must not be set to an inferior value than self.begin.
"""
if self._duration:
# if due is duration defined return the beginning + duration
return self.begin + self._duration
elif self._due_time:
# if due is time defined
return self._due_time
else:
return None | python | def due(self):
if self._duration:
# if due is duration defined return the beginning + duration
return self.begin + self._duration
elif self._due_time:
# if due is time defined
return self._due_time
else:
return None | [
"def",
"due",
"(",
"self",
")",
":",
"if",
"self",
".",
"_duration",
":",
"# if due is duration defined return the beginning + duration",
"return",
"self",
".",
"begin",
"+",
"self",
".",
"_duration",
"elif",
"self",
".",
"_due_time",
":",
"# if due is time defined"... | Get or set the end of the todo.
| Will return an :class:`Arrow` object.
| May be set to anything that :func:`Arrow.get` understands.
| If set to a non null value, removes any already
existing duration.
| Setting to None will have unexpected behavior if
begin is not None.
| Must not be set to an inferior value than self.begin. | [
"Get",
"or",
"set",
"the",
"end",
"of",
"the",
"todo",
"."
] | bd918ec7453a7cf73a906cdcc78bd88eb4bab71b | https://github.com/C4ptainCrunch/ics.py/blob/bd918ec7453a7cf73a906cdcc78bd88eb4bab71b/ics/todo.py#L158-L177 |
230,032 | C4ptainCrunch/ics.py | ics/todo.py | Todo.duration | def duration(self):
"""Get or set the duration of the todo.
| Will return a timedelta object.
| May be set to anything that timedelta() understands.
| May be set with a dict ({"days":2, "hours":6}).
| If set to a non null value, removes any already
existing end time.
"""
if self._duration:
return self._duration
elif self.due:
return self.due - self.begin
else:
# todo has neither due, nor start and duration
return None | python | def duration(self):
if self._duration:
return self._duration
elif self.due:
return self.due - self.begin
else:
# todo has neither due, nor start and duration
return None | [
"def",
"duration",
"(",
"self",
")",
":",
"if",
"self",
".",
"_duration",
":",
"return",
"self",
".",
"_duration",
"elif",
"self",
".",
"due",
":",
"return",
"self",
".",
"due",
"-",
"self",
".",
"begin",
"else",
":",
"# todo has neither due, nor start and... | Get or set the duration of the todo.
| Will return a timedelta object.
| May be set to anything that timedelta() understands.
| May be set with a dict ({"days":2, "hours":6}).
| If set to a non null value, removes any already
existing end time. | [
"Get",
"or",
"set",
"the",
"duration",
"of",
"the",
"todo",
"."
] | bd918ec7453a7cf73a906cdcc78bd88eb4bab71b | https://github.com/C4ptainCrunch/ics.py/blob/bd918ec7453a7cf73a906cdcc78bd88eb4bab71b/ics/todo.py#L191-L206 |
230,033 | kiwiz/gkeepapi | gkeepapi/__init__.py | APIAuth.login | def login(self, email, password, android_id):
"""Authenticate to Google with the provided credentials.
Args:
email (str): The account to use.
password (str): The account password.
android_id (str): An identifier for this client.
Raises:
LoginException: If there was a problem logging in.
"""
self._email = email
self._android_id = android_id
res = gpsoauth.perform_master_login(self._email, password, self._android_id)
if 'Token' not in res:
raise exception.LoginException(res.get('Error'), res.get('ErrorDetail'))
self._master_token = res['Token']
self.refresh()
return True | python | def login(self, email, password, android_id):
self._email = email
self._android_id = android_id
res = gpsoauth.perform_master_login(self._email, password, self._android_id)
if 'Token' not in res:
raise exception.LoginException(res.get('Error'), res.get('ErrorDetail'))
self._master_token = res['Token']
self.refresh()
return True | [
"def",
"login",
"(",
"self",
",",
"email",
",",
"password",
",",
"android_id",
")",
":",
"self",
".",
"_email",
"=",
"email",
"self",
".",
"_android_id",
"=",
"android_id",
"res",
"=",
"gpsoauth",
".",
"perform_master_login",
"(",
"self",
".",
"_email",
... | Authenticate to Google with the provided credentials.
Args:
email (str): The account to use.
password (str): The account password.
android_id (str): An identifier for this client.
Raises:
LoginException: If there was a problem logging in. | [
"Authenticate",
"to",
"Google",
"with",
"the",
"provided",
"credentials",
"."
] | 78aaae8b988b1cf616e3973f7f15d4c6d5e996cc | https://github.com/kiwiz/gkeepapi/blob/78aaae8b988b1cf616e3973f7f15d4c6d5e996cc/gkeepapi/__init__.py#L38-L57 |
230,034 | kiwiz/gkeepapi | gkeepapi/__init__.py | APIAuth.load | def load(self, email, master_token, android_id):
"""Authenticate to Google with the provided master token.
Args:
email (str): The account to use.
master_token (str): The master token.
android_id (str): An identifier for this client.
Raises:
LoginException: If there was a problem logging in.
"""
self._email = email
self._android_id = android_id
self._master_token = master_token
self.refresh()
return True | python | def load(self, email, master_token, android_id):
self._email = email
self._android_id = android_id
self._master_token = master_token
self.refresh()
return True | [
"def",
"load",
"(",
"self",
",",
"email",
",",
"master_token",
",",
"android_id",
")",
":",
"self",
".",
"_email",
"=",
"email",
"self",
".",
"_android_id",
"=",
"android_id",
"self",
".",
"_master_token",
"=",
"master_token",
"self",
".",
"refresh",
"(",
... | Authenticate to Google with the provided master token.
Args:
email (str): The account to use.
master_token (str): The master token.
android_id (str): An identifier for this client.
Raises:
LoginException: If there was a problem logging in. | [
"Authenticate",
"to",
"Google",
"with",
"the",
"provided",
"master",
"token",
"."
] | 78aaae8b988b1cf616e3973f7f15d4c6d5e996cc | https://github.com/kiwiz/gkeepapi/blob/78aaae8b988b1cf616e3973f7f15d4c6d5e996cc/gkeepapi/__init__.py#L59-L75 |
230,035 | kiwiz/gkeepapi | gkeepapi/__init__.py | APIAuth.refresh | def refresh(self):
"""Refresh the OAuth token.
Returns:
string: The auth token.
Raises:
LoginException: If there was a problem refreshing the OAuth token.
"""
res = gpsoauth.perform_oauth(
self._email, self._master_token, self._android_id,
service=self._scopes,
app='com.google.android.keep',
client_sig='38918a453d07199354f8b19af05ec6562ced5788'
)
if 'Auth' not in res:
if 'Token' not in res:
raise exception.LoginException(res.get('Error'))
self._auth_token = res['Auth']
return self._auth_token | python | def refresh(self):
res = gpsoauth.perform_oauth(
self._email, self._master_token, self._android_id,
service=self._scopes,
app='com.google.android.keep',
client_sig='38918a453d07199354f8b19af05ec6562ced5788'
)
if 'Auth' not in res:
if 'Token' not in res:
raise exception.LoginException(res.get('Error'))
self._auth_token = res['Auth']
return self._auth_token | [
"def",
"refresh",
"(",
"self",
")",
":",
"res",
"=",
"gpsoauth",
".",
"perform_oauth",
"(",
"self",
".",
"_email",
",",
"self",
".",
"_master_token",
",",
"self",
".",
"_android_id",
",",
"service",
"=",
"self",
".",
"_scopes",
",",
"app",
"=",
"'com.g... | Refresh the OAuth token.
Returns:
string: The auth token.
Raises:
LoginException: If there was a problem refreshing the OAuth token. | [
"Refresh",
"the",
"OAuth",
"token",
"."
] | 78aaae8b988b1cf616e3973f7f15d4c6d5e996cc | https://github.com/kiwiz/gkeepapi/blob/78aaae8b988b1cf616e3973f7f15d4c6d5e996cc/gkeepapi/__init__.py#L135-L155 |
230,036 | kiwiz/gkeepapi | gkeepapi/__init__.py | APIAuth.logout | def logout(self):
"""Log out of the account."""
self._master_token = None
self._auth_token = None
self._email = None
self._android_id = None | python | def logout(self):
self._master_token = None
self._auth_token = None
self._email = None
self._android_id = None | [
"def",
"logout",
"(",
"self",
")",
":",
"self",
".",
"_master_token",
"=",
"None",
"self",
".",
"_auth_token",
"=",
"None",
"self",
".",
"_email",
"=",
"None",
"self",
".",
"_android_id",
"=",
"None"
] | Log out of the account. | [
"Log",
"out",
"of",
"the",
"account",
"."
] | 78aaae8b988b1cf616e3973f7f15d4c6d5e996cc | https://github.com/kiwiz/gkeepapi/blob/78aaae8b988b1cf616e3973f7f15d4c6d5e996cc/gkeepapi/__init__.py#L157-L162 |
230,037 | kiwiz/gkeepapi | gkeepapi/__init__.py | API.send | def send(self, **req_kwargs):
"""Send an authenticated request to a Google API.
Automatically retries if the access token has expired.
Args:
**req_kwargs: Arbitrary keyword arguments to pass to Requests.
Return:
dict: The parsed JSON response.
Raises:
APIException: If the server returns an error.
LoginException: If :py:meth:`login` has not been called.
"""
i = 0
while True:
response = self._send(**req_kwargs).json()
if 'error' not in response:
break
error = response['error']
if error['code'] != 401:
raise exception.APIException(error['code'], error)
if i >= self.RETRY_CNT:
raise exception.APIException(error['code'], error)
logger.info('Refreshing access token')
self._auth.refresh()
i += 1
return response | python | def send(self, **req_kwargs):
i = 0
while True:
response = self._send(**req_kwargs).json()
if 'error' not in response:
break
error = response['error']
if error['code'] != 401:
raise exception.APIException(error['code'], error)
if i >= self.RETRY_CNT:
raise exception.APIException(error['code'], error)
logger.info('Refreshing access token')
self._auth.refresh()
i += 1
return response | [
"def",
"send",
"(",
"self",
",",
"*",
"*",
"req_kwargs",
")",
":",
"i",
"=",
"0",
"while",
"True",
":",
"response",
"=",
"self",
".",
"_send",
"(",
"*",
"*",
"req_kwargs",
")",
".",
"json",
"(",
")",
"if",
"'error'",
"not",
"in",
"response",
":",... | Send an authenticated request to a Google API.
Automatically retries if the access token has expired.
Args:
**req_kwargs: Arbitrary keyword arguments to pass to Requests.
Return:
dict: The parsed JSON response.
Raises:
APIException: If the server returns an error.
LoginException: If :py:meth:`login` has not been called. | [
"Send",
"an",
"authenticated",
"request",
"to",
"a",
"Google",
"API",
".",
"Automatically",
"retries",
"if",
"the",
"access",
"token",
"has",
"expired",
"."
] | 78aaae8b988b1cf616e3973f7f15d4c6d5e996cc | https://github.com/kiwiz/gkeepapi/blob/78aaae8b988b1cf616e3973f7f15d4c6d5e996cc/gkeepapi/__init__.py#L189-L220 |
230,038 | kiwiz/gkeepapi | gkeepapi/__init__.py | API._send | def _send(self, **req_kwargs):
"""Send an authenticated request to a Google API.
Args:
**req_kwargs: Arbitrary keyword arguments to pass to Requests.
Return:
requests.Response: The raw response.
Raises:
LoginException: If :py:meth:`login` has not been called.
"""
auth_token = self._auth.getAuthToken()
if auth_token is None:
raise exception.LoginException('Not logged in')
req_kwargs.setdefault('headers', {
'Authorization': 'OAuth ' + auth_token
})
return self._session.request(**req_kwargs) | python | def _send(self, **req_kwargs):
auth_token = self._auth.getAuthToken()
if auth_token is None:
raise exception.LoginException('Not logged in')
req_kwargs.setdefault('headers', {
'Authorization': 'OAuth ' + auth_token
})
return self._session.request(**req_kwargs) | [
"def",
"_send",
"(",
"self",
",",
"*",
"*",
"req_kwargs",
")",
":",
"auth_token",
"=",
"self",
".",
"_auth",
".",
"getAuthToken",
"(",
")",
"if",
"auth_token",
"is",
"None",
":",
"raise",
"exception",
".",
"LoginException",
"(",
"'Not logged in'",
")",
"... | Send an authenticated request to a Google API.
Args:
**req_kwargs: Arbitrary keyword arguments to pass to Requests.
Return:
requests.Response: The raw response.
Raises:
LoginException: If :py:meth:`login` has not been called. | [
"Send",
"an",
"authenticated",
"request",
"to",
"a",
"Google",
"API",
"."
] | 78aaae8b988b1cf616e3973f7f15d4c6d5e996cc | https://github.com/kiwiz/gkeepapi/blob/78aaae8b988b1cf616e3973f7f15d4c6d5e996cc/gkeepapi/__init__.py#L222-L242 |
230,039 | kiwiz/gkeepapi | gkeepapi/__init__.py | MediaAPI.get | def get(self, blob):
"""Get the canonical link to a media blob.
Args:
blob (gkeepapi.node.Blob): The blob.
Returns:
str: A link to the media.
"""
return self._send(
url=self._base_url + blob.parent.server_id + '/' + blob.server_id + '?s=0',
method='GET',
allow_redirects=False
).headers.get('Location') | python | def get(self, blob):
return self._send(
url=self._base_url + blob.parent.server_id + '/' + blob.server_id + '?s=0',
method='GET',
allow_redirects=False
).headers.get('Location') | [
"def",
"get",
"(",
"self",
",",
"blob",
")",
":",
"return",
"self",
".",
"_send",
"(",
"url",
"=",
"self",
".",
"_base_url",
"+",
"blob",
".",
"parent",
".",
"server_id",
"+",
"'/'",
"+",
"blob",
".",
"server_id",
"+",
"'?s=0'",
",",
"method",
"=",... | Get the canonical link to a media blob.
Args:
blob (gkeepapi.node.Blob): The blob.
Returns:
str: A link to the media. | [
"Get",
"the",
"canonical",
"link",
"to",
"a",
"media",
"blob",
"."
] | 78aaae8b988b1cf616e3973f7f15d4c6d5e996cc | https://github.com/kiwiz/gkeepapi/blob/78aaae8b988b1cf616e3973f7f15d4c6d5e996cc/gkeepapi/__init__.py#L344-L357 |
230,040 | kiwiz/gkeepapi | gkeepapi/__init__.py | RemindersAPI.create | def create(self):
"""Create a new reminder.
"""
params = {}
return self.send(
url=self._base_url + 'create',
method='POST',
json=params
) | python | def create(self):
params = {}
return self.send(
url=self._base_url + 'create',
method='POST',
json=params
) | [
"def",
"create",
"(",
"self",
")",
":",
"params",
"=",
"{",
"}",
"return",
"self",
".",
"send",
"(",
"url",
"=",
"self",
".",
"_base_url",
"+",
"'create'",
",",
"method",
"=",
"'POST'",
",",
"json",
"=",
"params",
")"
] | Create a new reminder. | [
"Create",
"a",
"new",
"reminder",
"."
] | 78aaae8b988b1cf616e3973f7f15d4c6d5e996cc | https://github.com/kiwiz/gkeepapi/blob/78aaae8b988b1cf616e3973f7f15d4c6d5e996cc/gkeepapi/__init__.py#L383-L391 |
230,041 | kiwiz/gkeepapi | gkeepapi/__init__.py | RemindersAPI.list | def list(self, master=True):
"""List current reminders.
"""
params = {}
params.update(self.static_params)
if master:
params.update({
"recurrenceOptions": {
"collapseMode": "MASTER_ONLY",
},
"includeArchived": True,
"includeDeleted": False,
})
else:
current_time = time.time()
start_time = int((current_time - (365 * 24 * 60 * 60)) * 1000)
end_time = int((current_time + (24 * 60 * 60)) * 1000)
params.update({
"recurrenceOptions": {
"collapseMode":"INSTANCES_ONLY",
"recurrencesOnly": True,
},
"includeArchived": False,
"includeCompleted": False,
"includeDeleted": False,
"dueAfterMs": start_time,
"dueBeforeMs": end_time,
"recurrenceId": [],
})
return self.send(
url=self._base_url + 'list',
method='POST',
json=params
) | python | def list(self, master=True):
params = {}
params.update(self.static_params)
if master:
params.update({
"recurrenceOptions": {
"collapseMode": "MASTER_ONLY",
},
"includeArchived": True,
"includeDeleted": False,
})
else:
current_time = time.time()
start_time = int((current_time - (365 * 24 * 60 * 60)) * 1000)
end_time = int((current_time + (24 * 60 * 60)) * 1000)
params.update({
"recurrenceOptions": {
"collapseMode":"INSTANCES_ONLY",
"recurrencesOnly": True,
},
"includeArchived": False,
"includeCompleted": False,
"includeDeleted": False,
"dueAfterMs": start_time,
"dueBeforeMs": end_time,
"recurrenceId": [],
})
return self.send(
url=self._base_url + 'list',
method='POST',
json=params
) | [
"def",
"list",
"(",
"self",
",",
"master",
"=",
"True",
")",
":",
"params",
"=",
"{",
"}",
"params",
".",
"update",
"(",
"self",
".",
"static_params",
")",
"if",
"master",
":",
"params",
".",
"update",
"(",
"{",
"\"recurrenceOptions\"",
":",
"{",
"\"... | List current reminders. | [
"List",
"current",
"reminders",
"."
] | 78aaae8b988b1cf616e3973f7f15d4c6d5e996cc | https://github.com/kiwiz/gkeepapi/blob/78aaae8b988b1cf616e3973f7f15d4c6d5e996cc/gkeepapi/__init__.py#L393-L429 |
230,042 | kiwiz/gkeepapi | gkeepapi/__init__.py | RemindersAPI.history | def history(self, storage_version):
"""Get reminder changes.
"""
params = {
"storageVersion": storage_version,
"includeSnoozePresetUpdates": True,
}
params.update(self.static_params)
return self.send(
url=self._base_url + 'history',
method='POST',
json=params
) | python | def history(self, storage_version):
params = {
"storageVersion": storage_version,
"includeSnoozePresetUpdates": True,
}
params.update(self.static_params)
return self.send(
url=self._base_url + 'history',
method='POST',
json=params
) | [
"def",
"history",
"(",
"self",
",",
"storage_version",
")",
":",
"params",
"=",
"{",
"\"storageVersion\"",
":",
"storage_version",
",",
"\"includeSnoozePresetUpdates\"",
":",
"True",
",",
"}",
"params",
".",
"update",
"(",
"self",
".",
"static_params",
")",
"r... | Get reminder changes. | [
"Get",
"reminder",
"changes",
"."
] | 78aaae8b988b1cf616e3973f7f15d4c6d5e996cc | https://github.com/kiwiz/gkeepapi/blob/78aaae8b988b1cf616e3973f7f15d4c6d5e996cc/gkeepapi/__init__.py#L431-L444 |
230,043 | kiwiz/gkeepapi | gkeepapi/__init__.py | RemindersAPI.update | def update(self):
"""Sync up changes to reminders.
"""
params = {}
return self.send(
url=self._base_url + 'update',
method='POST',
json=params
) | python | def update(self):
params = {}
return self.send(
url=self._base_url + 'update',
method='POST',
json=params
) | [
"def",
"update",
"(",
"self",
")",
":",
"params",
"=",
"{",
"}",
"return",
"self",
".",
"send",
"(",
"url",
"=",
"self",
".",
"_base_url",
"+",
"'update'",
",",
"method",
"=",
"'POST'",
",",
"json",
"=",
"params",
")"
] | Sync up changes to reminders. | [
"Sync",
"up",
"changes",
"to",
"reminders",
"."
] | 78aaae8b988b1cf616e3973f7f15d4c6d5e996cc | https://github.com/kiwiz/gkeepapi/blob/78aaae8b988b1cf616e3973f7f15d4c6d5e996cc/gkeepapi/__init__.py#L446-L454 |
230,044 | kiwiz/gkeepapi | gkeepapi/__init__.py | Keep.login | def login(self, username, password, state=None, sync=True):
"""Authenticate to Google with the provided credentials & sync.
Args:
email (str): The account to use.
password (str): The account password.
state (dict): Serialized state to load.
Raises:
LoginException: If there was a problem logging in.
"""
auth = APIAuth(self.OAUTH_SCOPES)
ret = auth.login(username, password, get_mac())
if ret:
self.load(auth, state, sync)
return ret | python | def login(self, username, password, state=None, sync=True):
auth = APIAuth(self.OAUTH_SCOPES)
ret = auth.login(username, password, get_mac())
if ret:
self.load(auth, state, sync)
return ret | [
"def",
"login",
"(",
"self",
",",
"username",
",",
"password",
",",
"state",
"=",
"None",
",",
"sync",
"=",
"True",
")",
":",
"auth",
"=",
"APIAuth",
"(",
"self",
".",
"OAUTH_SCOPES",
")",
"ret",
"=",
"auth",
".",
"login",
"(",
"username",
",",
"pa... | Authenticate to Google with the provided credentials & sync.
Args:
email (str): The account to use.
password (str): The account password.
state (dict): Serialized state to load.
Raises:
LoginException: If there was a problem logging in. | [
"Authenticate",
"to",
"Google",
"with",
"the",
"provided",
"credentials",
"&",
"sync",
"."
] | 78aaae8b988b1cf616e3973f7f15d4c6d5e996cc | https://github.com/kiwiz/gkeepapi/blob/78aaae8b988b1cf616e3973f7f15d4c6d5e996cc/gkeepapi/__init__.py#L504-L521 |
230,045 | kiwiz/gkeepapi | gkeepapi/__init__.py | Keep.resume | def resume(self, email, master_token, state=None, sync=True):
"""Authenticate to Google with the provided master token & sync.
Args:
email (str): The account to use.
master_token (str): The master token.
state (dict): Serialized state to load.
Raises:
LoginException: If there was a problem logging in.
"""
auth = APIAuth(self.OAUTH_SCOPES)
ret = auth.load(email, master_token, android_id=get_mac())
if ret:
self.load(auth, state, sync)
return ret | python | def resume(self, email, master_token, state=None, sync=True):
auth = APIAuth(self.OAUTH_SCOPES)
ret = auth.load(email, master_token, android_id=get_mac())
if ret:
self.load(auth, state, sync)
return ret | [
"def",
"resume",
"(",
"self",
",",
"email",
",",
"master_token",
",",
"state",
"=",
"None",
",",
"sync",
"=",
"True",
")",
":",
"auth",
"=",
"APIAuth",
"(",
"self",
".",
"OAUTH_SCOPES",
")",
"ret",
"=",
"auth",
".",
"load",
"(",
"email",
",",
"mast... | Authenticate to Google with the provided master token & sync.
Args:
email (str): The account to use.
master_token (str): The master token.
state (dict): Serialized state to load.
Raises:
LoginException: If there was a problem logging in. | [
"Authenticate",
"to",
"Google",
"with",
"the",
"provided",
"master",
"token",
"&",
"sync",
"."
] | 78aaae8b988b1cf616e3973f7f15d4c6d5e996cc | https://github.com/kiwiz/gkeepapi/blob/78aaae8b988b1cf616e3973f7f15d4c6d5e996cc/gkeepapi/__init__.py#L523-L540 |
230,046 | kiwiz/gkeepapi | gkeepapi/__init__.py | Keep.dump | def dump(self):
"""Serialize note data.
Args:
state (dict): Serialized state to load.
"""
# Find all nodes manually, as the Keep object isn't aware of new ListItems
# until they've been synced to the server.
nodes = []
for node in self.all():
nodes.append(node)
for child in node.children:
nodes.append(child)
return {
'keep_version': self._keep_version,
'labels': [label.save(False) for label in self.labels()],
'nodes': [node.save(False) for node in nodes]
} | python | def dump(self):
# Find all nodes manually, as the Keep object isn't aware of new ListItems
# until they've been synced to the server.
nodes = []
for node in self.all():
nodes.append(node)
for child in node.children:
nodes.append(child)
return {
'keep_version': self._keep_version,
'labels': [label.save(False) for label in self.labels()],
'nodes': [node.save(False) for node in nodes]
} | [
"def",
"dump",
"(",
"self",
")",
":",
"# Find all nodes manually, as the Keep object isn't aware of new ListItems",
"# until they've been synced to the server.",
"nodes",
"=",
"[",
"]",
"for",
"node",
"in",
"self",
".",
"all",
"(",
")",
":",
"nodes",
".",
"append",
"(... | Serialize note data.
Args:
state (dict): Serialized state to load. | [
"Serialize",
"note",
"data",
"."
] | 78aaae8b988b1cf616e3973f7f15d4c6d5e996cc | https://github.com/kiwiz/gkeepapi/blob/78aaae8b988b1cf616e3973f7f15d4c6d5e996cc/gkeepapi/__init__.py#L567-L584 |
230,047 | kiwiz/gkeepapi | gkeepapi/__init__.py | Keep.restore | def restore(self, state):
"""Unserialize saved note data.
Args:
state (dict): Serialized state to load.
"""
self._clear()
self._parseUserInfo({'labels': state['labels']})
self._parseNodes(state['nodes'])
self._keep_version = state['keep_version'] | python | def restore(self, state):
self._clear()
self._parseUserInfo({'labels': state['labels']})
self._parseNodes(state['nodes'])
self._keep_version = state['keep_version'] | [
"def",
"restore",
"(",
"self",
",",
"state",
")",
":",
"self",
".",
"_clear",
"(",
")",
"self",
".",
"_parseUserInfo",
"(",
"{",
"'labels'",
":",
"state",
"[",
"'labels'",
"]",
"}",
")",
"self",
".",
"_parseNodes",
"(",
"state",
"[",
"'nodes'",
"]",
... | Unserialize saved note data.
Args:
state (dict): Serialized state to load. | [
"Unserialize",
"saved",
"note",
"data",
"."
] | 78aaae8b988b1cf616e3973f7f15d4c6d5e996cc | https://github.com/kiwiz/gkeepapi/blob/78aaae8b988b1cf616e3973f7f15d4c6d5e996cc/gkeepapi/__init__.py#L586-L595 |
230,048 | kiwiz/gkeepapi | gkeepapi/__init__.py | Keep.get | def get(self, node_id):
"""Get a note with the given ID.
Args:
node_id (str): The note ID.
Returns:
gkeepapi.node.TopLevelNode: The Note or None if not found.
"""
return \
self._nodes[_node.Root.ID].get(node_id) or \
self._nodes[_node.Root.ID].get(self._sid_map.get(node_id)) | python | def get(self, node_id):
return \
self._nodes[_node.Root.ID].get(node_id) or \
self._nodes[_node.Root.ID].get(self._sid_map.get(node_id)) | [
"def",
"get",
"(",
"self",
",",
"node_id",
")",
":",
"return",
"self",
".",
"_nodes",
"[",
"_node",
".",
"Root",
".",
"ID",
"]",
".",
"get",
"(",
"node_id",
")",
"or",
"self",
".",
"_nodes",
"[",
"_node",
".",
"Root",
".",
"ID",
"]",
".",
"get"... | Get a note with the given ID.
Args:
node_id (str): The note ID.
Returns:
gkeepapi.node.TopLevelNode: The Note or None if not found. | [
"Get",
"a",
"note",
"with",
"the",
"given",
"ID",
"."
] | 78aaae8b988b1cf616e3973f7f15d4c6d5e996cc | https://github.com/kiwiz/gkeepapi/blob/78aaae8b988b1cf616e3973f7f15d4c6d5e996cc/gkeepapi/__init__.py#L597-L608 |
230,049 | kiwiz/gkeepapi | gkeepapi/__init__.py | Keep.find | def find(self, query=None, func=None, labels=None, colors=None, pinned=None, archived=None, trashed=False): # pylint: disable=too-many-arguments
"""Find Notes based on the specified criteria.
Args:
query (Union[_sre.SRE_Pattern, str, None]): A str or regular expression to match against the title and text.
func (Union[callable, None]): A filter function.
labels (Union[List[str], None]): A list of label ids or objects to match. An empty list matches notes with no labels.
colors (Union[List[str], None]): A list of colors to match.
pinned (Union[bool, None]): Whether to match pinned notes.
archived (Union[bool, None]): Whether to match archived notes.
trashed (Union[bool, None]): Whether to match trashed notes.
Return:
List[gkeepapi.node.TopLevelNode]: Results.
"""
if labels is not None:
labels = [i.id if isinstance(i, _node.Label) else i for i in labels]
return (node for node in self.all() if
(query is None or (
(isinstance(query, six.string_types) and (query in node.title or query in node.text)) or
(isinstance(query, Pattern) and (
query.search(node.title) or query.search(node.text)
))
)) and
(func is None or func(node)) and \
(labels is None or \
(not labels and not node.labels.all()) or \
(any((node.labels.get(i) is not None for i in labels)))
) and \
(colors is None or node.color in colors) and \
(pinned is None or node.pinned == pinned) and \
(archived is None or node.archived == archived) and \
(trashed is None or node.trashed == trashed)
) | python | def find(self, query=None, func=None, labels=None, colors=None, pinned=None, archived=None, trashed=False): # pylint: disable=too-many-arguments
if labels is not None:
labels = [i.id if isinstance(i, _node.Label) else i for i in labels]
return (node for node in self.all() if
(query is None or (
(isinstance(query, six.string_types) and (query in node.title or query in node.text)) or
(isinstance(query, Pattern) and (
query.search(node.title) or query.search(node.text)
))
)) and
(func is None or func(node)) and \
(labels is None or \
(not labels and not node.labels.all()) or \
(any((node.labels.get(i) is not None for i in labels)))
) and \
(colors is None or node.color in colors) and \
(pinned is None or node.pinned == pinned) and \
(archived is None or node.archived == archived) and \
(trashed is None or node.trashed == trashed)
) | [
"def",
"find",
"(",
"self",
",",
"query",
"=",
"None",
",",
"func",
"=",
"None",
",",
"labels",
"=",
"None",
",",
"colors",
"=",
"None",
",",
"pinned",
"=",
"None",
",",
"archived",
"=",
"None",
",",
"trashed",
"=",
"False",
")",
":",
"# pylint: di... | Find Notes based on the specified criteria.
Args:
query (Union[_sre.SRE_Pattern, str, None]): A str or regular expression to match against the title and text.
func (Union[callable, None]): A filter function.
labels (Union[List[str], None]): A list of label ids or objects to match. An empty list matches notes with no labels.
colors (Union[List[str], None]): A list of colors to match.
pinned (Union[bool, None]): Whether to match pinned notes.
archived (Union[bool, None]): Whether to match archived notes.
trashed (Union[bool, None]): Whether to match trashed notes.
Return:
List[gkeepapi.node.TopLevelNode]: Results. | [
"Find",
"Notes",
"based",
"on",
"the",
"specified",
"criteria",
"."
] | 78aaae8b988b1cf616e3973f7f15d4c6d5e996cc | https://github.com/kiwiz/gkeepapi/blob/78aaae8b988b1cf616e3973f7f15d4c6d5e996cc/gkeepapi/__init__.py#L627-L661 |
230,050 | kiwiz/gkeepapi | gkeepapi/__init__.py | Keep.findLabel | def findLabel(self, query, create=False):
"""Find a label with the given name.
Args:
name (Union[_sre.SRE_Pattern, str]): A str or regular expression to match against the name.
create (bool): Whether to create the label if it doesn't exist (only if name is a str).
Returns:
Union[gkeepapi.node.Label, None]: The label.
"""
if isinstance(query, six.string_types):
query = query.lower()
for label in self._labels.values():
if (isinstance(query, six.string_types) and query == label.name.lower()) or \
(isinstance(query, Pattern) and query.search(label.name)):
return label
return self.createLabel(query) if create and isinstance(query, six.string_types) else None | python | def findLabel(self, query, create=False):
if isinstance(query, six.string_types):
query = query.lower()
for label in self._labels.values():
if (isinstance(query, six.string_types) and query == label.name.lower()) or \
(isinstance(query, Pattern) and query.search(label.name)):
return label
return self.createLabel(query) if create and isinstance(query, six.string_types) else None | [
"def",
"findLabel",
"(",
"self",
",",
"query",
",",
"create",
"=",
"False",
")",
":",
"if",
"isinstance",
"(",
"query",
",",
"six",
".",
"string_types",
")",
":",
"query",
"=",
"query",
".",
"lower",
"(",
")",
"for",
"label",
"in",
"self",
".",
"_l... | Find a label with the given name.
Args:
name (Union[_sre.SRE_Pattern, str]): A str or regular expression to match against the name.
create (bool): Whether to create the label if it doesn't exist (only if name is a str).
Returns:
Union[gkeepapi.node.Label, None]: The label. | [
"Find",
"a",
"label",
"with",
"the",
"given",
"name",
"."
] | 78aaae8b988b1cf616e3973f7f15d4c6d5e996cc | https://github.com/kiwiz/gkeepapi/blob/78aaae8b988b1cf616e3973f7f15d4c6d5e996cc/gkeepapi/__init__.py#L721-L739 |
230,051 | kiwiz/gkeepapi | gkeepapi/__init__.py | Keep.deleteLabel | def deleteLabel(self, label_id):
"""Deletes a label.
Args:
label_id (str): Label id.
"""
if label_id not in self._labels:
return
label = self._labels[label_id]
label.delete()
for node in self.all():
node.labels.remove(label) | python | def deleteLabel(self, label_id):
if label_id not in self._labels:
return
label = self._labels[label_id]
label.delete()
for node in self.all():
node.labels.remove(label) | [
"def",
"deleteLabel",
"(",
"self",
",",
"label_id",
")",
":",
"if",
"label_id",
"not",
"in",
"self",
".",
"_labels",
":",
"return",
"label",
"=",
"self",
".",
"_labels",
"[",
"label_id",
"]",
"label",
".",
"delete",
"(",
")",
"for",
"node",
"in",
"se... | Deletes a label.
Args:
label_id (str): Label id. | [
"Deletes",
"a",
"label",
"."
] | 78aaae8b988b1cf616e3973f7f15d4c6d5e996cc | https://github.com/kiwiz/gkeepapi/blob/78aaae8b988b1cf616e3973f7f15d4c6d5e996cc/gkeepapi/__init__.py#L752-L764 |
230,052 | kiwiz/gkeepapi | gkeepapi/__init__.py | Keep.sync | def sync(self, resync=False):
"""Sync the local Keep tree with the server. If resyncing, local changes will be detroyed. Otherwise, local changes to notes, labels and reminders will be detected and synced up.
Args:
resync (bool): Whether to resync data.
Raises:
SyncException: If there is a consistency issue.
"""
if resync:
self._clear()
while True:
logger.debug('Starting reminder sync: %s', self._reminder_version)
changes = self._reminders_api.list()
if 'task' in changes:
self._parseTasks(changes['task'])
self._reminder_version = changes['storageVersion']
logger.debug('Finishing sync: %s', self._reminder_version)
history = self._reminders_api.history(self._reminder_version)
if self._reminder_version == history['highestStorageVersion']:
break
while True:
logger.debug('Starting keep sync: %s', self._keep_version)
labels_updated = any((i.dirty for i in self._labels.values()))
changes = self._keep_api.changes(
target_version=self._keep_version,
nodes=[i.save() for i in self._findDirtyNodes()],
labels=[i.save() for i in self._labels.values()] if labels_updated else None,
)
if changes.get('forceFullResync'):
raise exception.ResyncRequiredException('Full resync required')
if changes.get('upgradeRecommended'):
raise exception.UpgradeRecommendedException('Upgrade recommended')
if 'userInfo' in changes:
self._parseUserInfo(changes['userInfo'])
if 'nodes' in changes:
self._parseNodes(changes['nodes'])
self._keep_version = changes['toVersion']
logger.debug('Finishing sync: %s', self._keep_version)
if not changes['truncated']:
break
if _node.DEBUG:
self._clean() | python | def sync(self, resync=False):
if resync:
self._clear()
while True:
logger.debug('Starting reminder sync: %s', self._reminder_version)
changes = self._reminders_api.list()
if 'task' in changes:
self._parseTasks(changes['task'])
self._reminder_version = changes['storageVersion']
logger.debug('Finishing sync: %s', self._reminder_version)
history = self._reminders_api.history(self._reminder_version)
if self._reminder_version == history['highestStorageVersion']:
break
while True:
logger.debug('Starting keep sync: %s', self._keep_version)
labels_updated = any((i.dirty for i in self._labels.values()))
changes = self._keep_api.changes(
target_version=self._keep_version,
nodes=[i.save() for i in self._findDirtyNodes()],
labels=[i.save() for i in self._labels.values()] if labels_updated else None,
)
if changes.get('forceFullResync'):
raise exception.ResyncRequiredException('Full resync required')
if changes.get('upgradeRecommended'):
raise exception.UpgradeRecommendedException('Upgrade recommended')
if 'userInfo' in changes:
self._parseUserInfo(changes['userInfo'])
if 'nodes' in changes:
self._parseNodes(changes['nodes'])
self._keep_version = changes['toVersion']
logger.debug('Finishing sync: %s', self._keep_version)
if not changes['truncated']:
break
if _node.DEBUG:
self._clean() | [
"def",
"sync",
"(",
"self",
",",
"resync",
"=",
"False",
")",
":",
"if",
"resync",
":",
"self",
".",
"_clear",
"(",
")",
"while",
"True",
":",
"logger",
".",
"debug",
"(",
"'Starting reminder sync: %s'",
",",
"self",
".",
"_reminder_version",
")",
"chang... | Sync the local Keep tree with the server. If resyncing, local changes will be detroyed. Otherwise, local changes to notes, labels and reminders will be detected and synced up.
Args:
resync (bool): Whether to resync data.
Raises:
SyncException: If there is a consistency issue. | [
"Sync",
"the",
"local",
"Keep",
"tree",
"with",
"the",
"server",
".",
"If",
"resyncing",
"local",
"changes",
"will",
"be",
"detroyed",
".",
"Otherwise",
"local",
"changes",
"to",
"notes",
"labels",
"and",
"reminders",
"will",
"be",
"detected",
"and",
"synced... | 78aaae8b988b1cf616e3973f7f15d4c6d5e996cc | https://github.com/kiwiz/gkeepapi/blob/78aaae8b988b1cf616e3973f7f15d4c6d5e996cc/gkeepapi/__init__.py#L793-L846 |
230,053 | kiwiz/gkeepapi | gkeepapi/__init__.py | Keep._clean | def _clean(self):
"""Recursively check that all nodes are reachable."""
found_ids = {}
nodes = [self._nodes[_node.Root.ID]]
while nodes:
node = nodes.pop()
found_ids[node.id] = None
nodes = nodes + node.children
for node_id in self._nodes:
if node_id in found_ids:
continue
logger.error('Dangling node: %s', node_id)
for node_id in found_ids:
if node_id in self._nodes:
continue
logger.error('Unregistered node: %s', node_id) | python | def _clean(self):
found_ids = {}
nodes = [self._nodes[_node.Root.ID]]
while nodes:
node = nodes.pop()
found_ids[node.id] = None
nodes = nodes + node.children
for node_id in self._nodes:
if node_id in found_ids:
continue
logger.error('Dangling node: %s', node_id)
for node_id in found_ids:
if node_id in self._nodes:
continue
logger.error('Unregistered node: %s', node_id) | [
"def",
"_clean",
"(",
"self",
")",
":",
"found_ids",
"=",
"{",
"}",
"nodes",
"=",
"[",
"self",
".",
"_nodes",
"[",
"_node",
".",
"Root",
".",
"ID",
"]",
"]",
"while",
"nodes",
":",
"node",
"=",
"nodes",
".",
"pop",
"(",
")",
"found_ids",
"[",
"... | Recursively check that all nodes are reachable. | [
"Recursively",
"check",
"that",
"all",
"nodes",
"are",
"reachable",
"."
] | 78aaae8b988b1cf616e3973f7f15d4c6d5e996cc | https://github.com/kiwiz/gkeepapi/blob/78aaae8b988b1cf616e3973f7f15d4c6d5e996cc/gkeepapi/__init__.py#L946-L963 |
230,054 | kiwiz/gkeepapi | gkeepapi/node.py | from_json | def from_json(raw):
"""Helper to construct a node from a dict.
Args:
raw (dict): Raw node representation.
Returns:
Node: A Node object or None.
"""
ncls = None
_type = raw.get('type')
try:
ncls = _type_map[NodeType(_type)]
except (KeyError, ValueError) as e:
logger.warning('Unknown node type: %s', _type)
if DEBUG:
raise_from(exception.ParseException('Parse error for %s' % (_type), raw), e)
return None
node = ncls()
node.load(raw)
return node | python | def from_json(raw):
ncls = None
_type = raw.get('type')
try:
ncls = _type_map[NodeType(_type)]
except (KeyError, ValueError) as e:
logger.warning('Unknown node type: %s', _type)
if DEBUG:
raise_from(exception.ParseException('Parse error for %s' % (_type), raw), e)
return None
node = ncls()
node.load(raw)
return node | [
"def",
"from_json",
"(",
"raw",
")",
":",
"ncls",
"=",
"None",
"_type",
"=",
"raw",
".",
"get",
"(",
"'type'",
")",
"try",
":",
"ncls",
"=",
"_type_map",
"[",
"NodeType",
"(",
"_type",
")",
"]",
"except",
"(",
"KeyError",
",",
"ValueError",
")",
"a... | Helper to construct a node from a dict.
Args:
raw (dict): Raw node representation.
Returns:
Node: A Node object or None. | [
"Helper",
"to",
"construct",
"a",
"node",
"from",
"a",
"dict",
"."
] | 78aaae8b988b1cf616e3973f7f15d4c6d5e996cc | https://github.com/kiwiz/gkeepapi/blob/78aaae8b988b1cf616e3973f7f15d4c6d5e996cc/gkeepapi/node.py#L1817-L1838 |
230,055 | kiwiz/gkeepapi | gkeepapi/node.py | Element.save | def save(self, clean=True):
"""Serialize into raw representation. Clears the dirty bit by default.
Args:
clean (bool): Whether to clear the dirty bit.
Returns:
dict: Raw.
"""
ret = {}
if clean:
self._dirty = False
else:
ret['_dirty'] = self._dirty
return ret | python | def save(self, clean=True):
ret = {}
if clean:
self._dirty = False
else:
ret['_dirty'] = self._dirty
return ret | [
"def",
"save",
"(",
"self",
",",
"clean",
"=",
"True",
")",
":",
"ret",
"=",
"{",
"}",
"if",
"clean",
":",
"self",
".",
"_dirty",
"=",
"False",
"else",
":",
"ret",
"[",
"'_dirty'",
"]",
"=",
"self",
".",
"_dirty",
"return",
"ret"
] | Serialize into raw representation. Clears the dirty bit by default.
Args:
clean (bool): Whether to clear the dirty bit.
Returns:
dict: Raw. | [
"Serialize",
"into",
"raw",
"representation",
".",
"Clears",
"the",
"dirty",
"bit",
"by",
"default",
"."
] | 78aaae8b988b1cf616e3973f7f15d4c6d5e996cc | https://github.com/kiwiz/gkeepapi/blob/78aaae8b988b1cf616e3973f7f15d4c6d5e996cc/gkeepapi/node.py#L225-L239 |
230,056 | kiwiz/gkeepapi | gkeepapi/node.py | NodeAnnotations.from_json | def from_json(cls, raw):
"""Helper to construct an annotation from a dict.
Args:
raw (dict): Raw annotation representation.
Returns:
Node: An Annotation object or None.
"""
bcls = None
if 'webLink' in raw:
bcls = WebLink
elif 'topicCategory' in raw:
bcls = Category
elif 'taskAssist' in raw:
bcls = TaskAssist
elif 'context' in raw:
bcls = Context
if bcls is None:
logger.warning('Unknown annotation type: %s', raw.keys())
return None
annotation = bcls()
annotation.load(raw)
return annotation | python | def from_json(cls, raw):
bcls = None
if 'webLink' in raw:
bcls = WebLink
elif 'topicCategory' in raw:
bcls = Category
elif 'taskAssist' in raw:
bcls = TaskAssist
elif 'context' in raw:
bcls = Context
if bcls is None:
logger.warning('Unknown annotation type: %s', raw.keys())
return None
annotation = bcls()
annotation.load(raw)
return annotation | [
"def",
"from_json",
"(",
"cls",
",",
"raw",
")",
":",
"bcls",
"=",
"None",
"if",
"'webLink'",
"in",
"raw",
":",
"bcls",
"=",
"WebLink",
"elif",
"'topicCategory'",
"in",
"raw",
":",
"bcls",
"=",
"Category",
"elif",
"'taskAssist'",
"in",
"raw",
":",
"bcl... | Helper to construct an annotation from a dict.
Args:
raw (dict): Raw annotation representation.
Returns:
Node: An Annotation object or None. | [
"Helper",
"to",
"construct",
"an",
"annotation",
"from",
"a",
"dict",
"."
] | 78aaae8b988b1cf616e3973f7f15d4c6d5e996cc | https://github.com/kiwiz/gkeepapi/blob/78aaae8b988b1cf616e3973f7f15d4c6d5e996cc/gkeepapi/node.py#L481-L506 |
230,057 | kiwiz/gkeepapi | gkeepapi/node.py | NodeAnnotations.links | def links(self):
"""Get all links.
Returns:
list[gkeepapi.node.WebLink]: A list of links.
"""
return [annotation for annotation in self._annotations.values()
if isinstance(annotation, WebLink)
] | python | def links(self):
return [annotation for annotation in self._annotations.values()
if isinstance(annotation, WebLink)
] | [
"def",
"links",
"(",
"self",
")",
":",
"return",
"[",
"annotation",
"for",
"annotation",
"in",
"self",
".",
"_annotations",
".",
"values",
"(",
")",
"if",
"isinstance",
"(",
"annotation",
",",
"WebLink",
")",
"]"
] | Get all links.
Returns:
list[gkeepapi.node.WebLink]: A list of links. | [
"Get",
"all",
"links",
"."
] | 78aaae8b988b1cf616e3973f7f15d4c6d5e996cc | https://github.com/kiwiz/gkeepapi/blob/78aaae8b988b1cf616e3973f7f15d4c6d5e996cc/gkeepapi/node.py#L565-L573 |
230,058 | kiwiz/gkeepapi | gkeepapi/node.py | NodeAnnotations.append | def append(self, annotation):
"""Add an annotation.
Args:
annotation (gkeepapi.node.Annotation): An Annotation object.
Returns:
gkeepapi.node.Annotation: The Annotation.
"""
self._annotations[annotation.id] = annotation
self._dirty = True
return annotation | python | def append(self, annotation):
self._annotations[annotation.id] = annotation
self._dirty = True
return annotation | [
"def",
"append",
"(",
"self",
",",
"annotation",
")",
":",
"self",
".",
"_annotations",
"[",
"annotation",
".",
"id",
"]",
"=",
"annotation",
"self",
".",
"_dirty",
"=",
"True",
"return",
"annotation"
] | Add an annotation.
Args:
annotation (gkeepapi.node.Annotation): An Annotation object.
Returns:
gkeepapi.node.Annotation: The Annotation. | [
"Add",
"an",
"annotation",
"."
] | 78aaae8b988b1cf616e3973f7f15d4c6d5e996cc | https://github.com/kiwiz/gkeepapi/blob/78aaae8b988b1cf616e3973f7f15d4c6d5e996cc/gkeepapi/node.py#L575-L586 |
230,059 | kiwiz/gkeepapi | gkeepapi/node.py | NodeAnnotations.remove | def remove(self, annotation):
"""Removes an annotation.
Args:
annotation (gkeepapi.node.Annotation): An Annotation object.
Returns:
gkeepapi.node.Annotation: The Annotation.
"""
if annotation.id in self._annotations:
del self._annotations[annotation.id]
self._dirty = True | python | def remove(self, annotation):
if annotation.id in self._annotations:
del self._annotations[annotation.id]
self._dirty = True | [
"def",
"remove",
"(",
"self",
",",
"annotation",
")",
":",
"if",
"annotation",
".",
"id",
"in",
"self",
".",
"_annotations",
":",
"del",
"self",
".",
"_annotations",
"[",
"annotation",
".",
"id",
"]",
"self",
".",
"_dirty",
"=",
"True"
] | Removes an annotation.
Args:
annotation (gkeepapi.node.Annotation): An Annotation object.
Returns:
gkeepapi.node.Annotation: The Annotation. | [
"Removes",
"an",
"annotation",
"."
] | 78aaae8b988b1cf616e3973f7f15d4c6d5e996cc | https://github.com/kiwiz/gkeepapi/blob/78aaae8b988b1cf616e3973f7f15d4c6d5e996cc/gkeepapi/node.py#L588-L599 |
230,060 | kiwiz/gkeepapi | gkeepapi/node.py | NodeCollaborators.add | def add(self, email):
"""Add a collaborator.
Args:
str : Collaborator email address.
"""
if email not in self._collaborators:
self._collaborators[email] = ShareRequestValue.Add
self._dirty = True | python | def add(self, email):
if email not in self._collaborators:
self._collaborators[email] = ShareRequestValue.Add
self._dirty = True | [
"def",
"add",
"(",
"self",
",",
"email",
")",
":",
"if",
"email",
"not",
"in",
"self",
".",
"_collaborators",
":",
"self",
".",
"_collaborators",
"[",
"email",
"]",
"=",
"ShareRequestValue",
".",
"Add",
"self",
".",
"_dirty",
"=",
"True"
] | Add a collaborator.
Args:
str : Collaborator email address. | [
"Add",
"a",
"collaborator",
"."
] | 78aaae8b988b1cf616e3973f7f15d4c6d5e996cc | https://github.com/kiwiz/gkeepapi/blob/78aaae8b988b1cf616e3973f7f15d4c6d5e996cc/gkeepapi/node.py#L855-L863 |
230,061 | kiwiz/gkeepapi | gkeepapi/node.py | NodeCollaborators.remove | def remove(self, email):
"""Remove a Collaborator.
Args:
str : Collaborator email address.
"""
if email in self._collaborators:
if self._collaborators[email] == ShareRequestValue.Add:
del self._collaborators[email]
else:
self._collaborators[email] = ShareRequestValue.Remove
self._dirty = True | python | def remove(self, email):
if email in self._collaborators:
if self._collaborators[email] == ShareRequestValue.Add:
del self._collaborators[email]
else:
self._collaborators[email] = ShareRequestValue.Remove
self._dirty = True | [
"def",
"remove",
"(",
"self",
",",
"email",
")",
":",
"if",
"email",
"in",
"self",
".",
"_collaborators",
":",
"if",
"self",
".",
"_collaborators",
"[",
"email",
"]",
"==",
"ShareRequestValue",
".",
"Add",
":",
"del",
"self",
".",
"_collaborators",
"[",
... | Remove a Collaborator.
Args:
str : Collaborator email address. | [
"Remove",
"a",
"Collaborator",
"."
] | 78aaae8b988b1cf616e3973f7f15d4c6d5e996cc | https://github.com/kiwiz/gkeepapi/blob/78aaae8b988b1cf616e3973f7f15d4c6d5e996cc/gkeepapi/node.py#L865-L876 |
230,062 | kiwiz/gkeepapi | gkeepapi/node.py | NodeCollaborators.all | def all(self):
"""Get all collaborators.
Returns:
List[str]: Collaborators.
"""
return [email for email, action in self._collaborators.items() if action in [RoleValue.Owner, RoleValue.User, ShareRequestValue.Add]] | python | def all(self):
return [email for email, action in self._collaborators.items() if action in [RoleValue.Owner, RoleValue.User, ShareRequestValue.Add]] | [
"def",
"all",
"(",
"self",
")",
":",
"return",
"[",
"email",
"for",
"email",
",",
"action",
"in",
"self",
".",
"_collaborators",
".",
"items",
"(",
")",
"if",
"action",
"in",
"[",
"RoleValue",
".",
"Owner",
",",
"RoleValue",
".",
"User",
",",
"ShareR... | Get all collaborators.
Returns:
List[str]: Collaborators. | [
"Get",
"all",
"collaborators",
"."
] | 78aaae8b988b1cf616e3973f7f15d4c6d5e996cc | https://github.com/kiwiz/gkeepapi/blob/78aaae8b988b1cf616e3973f7f15d4c6d5e996cc/gkeepapi/node.py#L878-L884 |
230,063 | kiwiz/gkeepapi | gkeepapi/node.py | NodeLabels.add | def add(self, label):
"""Add a label.
Args:
label (gkeepapi.node.Label): The Label object.
"""
self._labels[label.id] = label
self._dirty = True | python | def add(self, label):
self._labels[label.id] = label
self._dirty = True | [
"def",
"add",
"(",
"self",
",",
"label",
")",
":",
"self",
".",
"_labels",
"[",
"label",
".",
"id",
"]",
"=",
"label",
"self",
".",
"_dirty",
"=",
"True"
] | Add a label.
Args:
label (gkeepapi.node.Label): The Label object. | [
"Add",
"a",
"label",
"."
] | 78aaae8b988b1cf616e3973f7f15d4c6d5e996cc | https://github.com/kiwiz/gkeepapi/blob/78aaae8b988b1cf616e3973f7f15d4c6d5e996cc/gkeepapi/node.py#L916-L923 |
230,064 | kiwiz/gkeepapi | gkeepapi/node.py | NodeLabels.remove | def remove(self, label):
"""Remove a label.
Args:
label (gkeepapi.node.Label): The Label object.
"""
if label.id in self._labels:
self._labels[label.id] = None
self._dirty = True | python | def remove(self, label):
if label.id in self._labels:
self._labels[label.id] = None
self._dirty = True | [
"def",
"remove",
"(",
"self",
",",
"label",
")",
":",
"if",
"label",
".",
"id",
"in",
"self",
".",
"_labels",
":",
"self",
".",
"_labels",
"[",
"label",
".",
"id",
"]",
"=",
"None",
"self",
".",
"_dirty",
"=",
"True"
] | Remove a label.
Args:
label (gkeepapi.node.Label): The Label object. | [
"Remove",
"a",
"label",
"."
] | 78aaae8b988b1cf616e3973f7f15d4c6d5e996cc | https://github.com/kiwiz/gkeepapi/blob/78aaae8b988b1cf616e3973f7f15d4c6d5e996cc/gkeepapi/node.py#L925-L933 |
230,065 | kiwiz/gkeepapi | gkeepapi/node.py | TimestampsMixin.touch | def touch(self, edited=False):
"""Mark the node as dirty.
Args:
edited (bool): Whether to set the edited time.
"""
self._dirty = True
dt = datetime.datetime.utcnow()
self.timestamps.updated = dt
if edited:
self.timestamps.edited = dt | python | def touch(self, edited=False):
self._dirty = True
dt = datetime.datetime.utcnow()
self.timestamps.updated = dt
if edited:
self.timestamps.edited = dt | [
"def",
"touch",
"(",
"self",
",",
"edited",
"=",
"False",
")",
":",
"self",
".",
"_dirty",
"=",
"True",
"dt",
"=",
"datetime",
".",
"datetime",
".",
"utcnow",
"(",
")",
"self",
".",
"timestamps",
".",
"updated",
"=",
"dt",
"if",
"edited",
":",
"sel... | Mark the node as dirty.
Args:
edited (bool): Whether to set the edited time. | [
"Mark",
"the",
"node",
"as",
"dirty",
"."
] | 78aaae8b988b1cf616e3973f7f15d4c6d5e996cc | https://github.com/kiwiz/gkeepapi/blob/78aaae8b988b1cf616e3973f7f15d4c6d5e996cc/gkeepapi/node.py#L953-L963 |
230,066 | kiwiz/gkeepapi | gkeepapi/node.py | TimestampsMixin.trashed | def trashed(self):
"""Get the trashed state.
Returns:
bool: Whether this item is trashed.
"""
return self.timestamps.trashed is not None and self.timestamps.trashed > NodeTimestamps.int_to_dt(0) | python | def trashed(self):
return self.timestamps.trashed is not None and self.timestamps.trashed > NodeTimestamps.int_to_dt(0) | [
"def",
"trashed",
"(",
"self",
")",
":",
"return",
"self",
".",
"timestamps",
".",
"trashed",
"is",
"not",
"None",
"and",
"self",
".",
"timestamps",
".",
"trashed",
">",
"NodeTimestamps",
".",
"int_to_dt",
"(",
"0",
")"
] | Get the trashed state.
Returns:
bool: Whether this item is trashed. | [
"Get",
"the",
"trashed",
"state",
"."
] | 78aaae8b988b1cf616e3973f7f15d4c6d5e996cc | https://github.com/kiwiz/gkeepapi/blob/78aaae8b988b1cf616e3973f7f15d4c6d5e996cc/gkeepapi/node.py#L966-L972 |
230,067 | kiwiz/gkeepapi | gkeepapi/node.py | TimestampsMixin.deleted | def deleted(self):
"""Get the deleted state.
Returns:
bool: Whether this item is deleted.
"""
return self.timestamps.deleted is not None and self.timestamps.deleted > NodeTimestamps.int_to_dt(0) | python | def deleted(self):
return self.timestamps.deleted is not None and self.timestamps.deleted > NodeTimestamps.int_to_dt(0) | [
"def",
"deleted",
"(",
"self",
")",
":",
"return",
"self",
".",
"timestamps",
".",
"deleted",
"is",
"not",
"None",
"and",
"self",
".",
"timestamps",
".",
"deleted",
">",
"NodeTimestamps",
".",
"int_to_dt",
"(",
"0",
")"
] | Get the deleted state.
Returns:
bool: Whether this item is deleted. | [
"Get",
"the",
"deleted",
"state",
"."
] | 78aaae8b988b1cf616e3973f7f15d4c6d5e996cc | https://github.com/kiwiz/gkeepapi/blob/78aaae8b988b1cf616e3973f7f15d4c6d5e996cc/gkeepapi/node.py#L975-L981 |
230,068 | kiwiz/gkeepapi | gkeepapi/node.py | Node.text | def text(self, value):
"""Set the text value.
Args:
value (str): Text value.
"""
self._text = value
self.timestamps.edited = datetime.datetime.utcnow()
self.touch(True) | python | def text(self, value):
self._text = value
self.timestamps.edited = datetime.datetime.utcnow()
self.touch(True) | [
"def",
"text",
"(",
"self",
",",
"value",
")",
":",
"self",
".",
"_text",
"=",
"value",
"self",
".",
"timestamps",
".",
"edited",
"=",
"datetime",
".",
"datetime",
".",
"utcnow",
"(",
")",
"self",
".",
"touch",
"(",
"True",
")"
] | Set the text value.
Args:
value (str): Text value. | [
"Set",
"the",
"text",
"value",
"."
] | 78aaae8b988b1cf616e3973f7f15d4c6d5e996cc | https://github.com/kiwiz/gkeepapi/blob/78aaae8b988b1cf616e3973f7f15d4c6d5e996cc/gkeepapi/node.py#L1087-L1095 |
230,069 | kiwiz/gkeepapi | gkeepapi/node.py | Node.append | def append(self, node, dirty=True):
"""Add a new child node.
Args:
node (gkeepapi.Node): Node to add.
dirty (bool): Whether this node should be marked dirty.
"""
self._children[node.id] = node
node.parent = self
if dirty:
self.touch()
return node | python | def append(self, node, dirty=True):
self._children[node.id] = node
node.parent = self
if dirty:
self.touch()
return node | [
"def",
"append",
"(",
"self",
",",
"node",
",",
"dirty",
"=",
"True",
")",
":",
"self",
".",
"_children",
"[",
"node",
".",
"id",
"]",
"=",
"node",
"node",
".",
"parent",
"=",
"self",
"if",
"dirty",
":",
"self",
".",
"touch",
"(",
")",
"return",
... | Add a new child node.
Args:
node (gkeepapi.Node): Node to add.
dirty (bool): Whether this node should be marked dirty. | [
"Add",
"a",
"new",
"child",
"node",
"."
] | 78aaae8b988b1cf616e3973f7f15d4c6d5e996cc | https://github.com/kiwiz/gkeepapi/blob/78aaae8b988b1cf616e3973f7f15d4c6d5e996cc/gkeepapi/node.py#L1126-L1138 |
230,070 | kiwiz/gkeepapi | gkeepapi/node.py | Node.remove | def remove(self, node, dirty=True):
"""Remove the given child node.
Args:
node (gkeepapi.Node): Node to remove.
dirty (bool): Whether this node should be marked dirty.
"""
if node.id in self._children:
self._children[node.id].parent = None
del self._children[node.id]
if dirty:
self.touch() | python | def remove(self, node, dirty=True):
if node.id in self._children:
self._children[node.id].parent = None
del self._children[node.id]
if dirty:
self.touch() | [
"def",
"remove",
"(",
"self",
",",
"node",
",",
"dirty",
"=",
"True",
")",
":",
"if",
"node",
".",
"id",
"in",
"self",
".",
"_children",
":",
"self",
".",
"_children",
"[",
"node",
".",
"id",
"]",
".",
"parent",
"=",
"None",
"del",
"self",
".",
... | Remove the given child node.
Args:
node (gkeepapi.Node): Node to remove.
dirty (bool): Whether this node should be marked dirty. | [
"Remove",
"the",
"given",
"child",
"node",
"."
] | 78aaae8b988b1cf616e3973f7f15d4c6d5e996cc | https://github.com/kiwiz/gkeepapi/blob/78aaae8b988b1cf616e3973f7f15d4c6d5e996cc/gkeepapi/node.py#L1140-L1151 |
230,071 | kiwiz/gkeepapi | gkeepapi/node.py | List.add | def add(self, text, checked=False, sort=None):
"""Add a new item to the list.
Args:
text (str): The text.
checked (bool): Whether this item is checked.
sort (int): Item id for sorting.
"""
node = ListItem(parent_id=self.id, parent_server_id=self.server_id)
node.checked = checked
node.text = text
if sort is not None:
node.sort = sort
self.append(node, True)
self.touch(True)
return node | python | def add(self, text, checked=False, sort=None):
node = ListItem(parent_id=self.id, parent_server_id=self.server_id)
node.checked = checked
node.text = text
if sort is not None:
node.sort = sort
self.append(node, True)
self.touch(True)
return node | [
"def",
"add",
"(",
"self",
",",
"text",
",",
"checked",
"=",
"False",
",",
"sort",
"=",
"None",
")",
":",
"node",
"=",
"ListItem",
"(",
"parent_id",
"=",
"self",
".",
"id",
",",
"parent_server_id",
"=",
"self",
".",
"server_id",
")",
"node",
".",
"... | Add a new item to the list.
Args:
text (str): The text.
checked (bool): Whether this item is checked.
sort (int): Item id for sorting. | [
"Add",
"a",
"new",
"item",
"to",
"the",
"list",
"."
] | 78aaae8b988b1cf616e3973f7f15d4c6d5e996cc | https://github.com/kiwiz/gkeepapi/blob/78aaae8b988b1cf616e3973f7f15d4c6d5e996cc/gkeepapi/node.py#L1337-L1352 |
230,072 | kiwiz/gkeepapi | gkeepapi/node.py | List.items_sort | def items_sort(cls, items):
"""Sort list items, taking into account parent items.
Args:
items (list[gkeepapi.node.ListItem]): Items to sort.
Returns:
list[gkeepapi.node.ListItem]: Sorted items.
"""
class t(tuple):
"""Tuple with element-based sorting"""
def __cmp__(self, other):
for a, b in six.moves.zip_longest(self, other):
if a != b:
if a is None:
return 1
if b is None:
return -1
return a - b
return 0
def __lt__(self, other):
return self.__cmp__(other) < 0
def __gt_(self, other):
return self.__cmp__(other) > 0
def __le__(self, other):
return self.__cmp__(other) <= 0
def __ge_(self, other):
return self.__cmp__(other) >= 0
def __eq__(self, other):
return self.__cmp__(other) == 0
def __ne__(self, other):
return self.__cmp__(other) != 0
def key_func(x):
if x.indented:
return t((int(x.parent_item.sort), int(x.sort)))
return t((int(x.sort), ))
return sorted(items, key=key_func, reverse=True) | python | def items_sort(cls, items):
class t(tuple):
"""Tuple with element-based sorting"""
def __cmp__(self, other):
for a, b in six.moves.zip_longest(self, other):
if a != b:
if a is None:
return 1
if b is None:
return -1
return a - b
return 0
def __lt__(self, other):
return self.__cmp__(other) < 0
def __gt_(self, other):
return self.__cmp__(other) > 0
def __le__(self, other):
return self.__cmp__(other) <= 0
def __ge_(self, other):
return self.__cmp__(other) >= 0
def __eq__(self, other):
return self.__cmp__(other) == 0
def __ne__(self, other):
return self.__cmp__(other) != 0
def key_func(x):
if x.indented:
return t((int(x.parent_item.sort), int(x.sort)))
return t((int(x.sort), ))
return sorted(items, key=key_func, reverse=True) | [
"def",
"items_sort",
"(",
"cls",
",",
"items",
")",
":",
"class",
"t",
"(",
"tuple",
")",
":",
"\"\"\"Tuple with element-based sorting\"\"\"",
"def",
"__cmp__",
"(",
"self",
",",
"other",
")",
":",
"for",
"a",
",",
"b",
"in",
"six",
".",
"moves",
".",
... | Sort list items, taking into account parent items.
Args:
items (list[gkeepapi.node.ListItem]): Items to sort.
Returns:
list[gkeepapi.node.ListItem]: Sorted items. | [
"Sort",
"list",
"items",
"taking",
"into",
"account",
"parent",
"items",
"."
] | 78aaae8b988b1cf616e3973f7f15d4c6d5e996cc | https://github.com/kiwiz/gkeepapi/blob/78aaae8b988b1cf616e3973f7f15d4c6d5e996cc/gkeepapi/node.py#L1359-L1397 |
230,073 | kiwiz/gkeepapi | gkeepapi/node.py | ListItem.add | def add(self, text, checked=False, sort=None):
"""Add a new sub item to the list. This item must already be attached to a list.
Args:
text (str): The text.
checked (bool): Whether this item is checked.
sort (int): Item id for sorting.
"""
if self.parent is None:
raise exception.InvalidException('Item has no parent')
node = self.parent.add(text, checked, sort)
self.indent(node)
return node | python | def add(self, text, checked=False, sort=None):
if self.parent is None:
raise exception.InvalidException('Item has no parent')
node = self.parent.add(text, checked, sort)
self.indent(node)
return node | [
"def",
"add",
"(",
"self",
",",
"text",
",",
"checked",
"=",
"False",
",",
"sort",
"=",
"None",
")",
":",
"if",
"self",
".",
"parent",
"is",
"None",
":",
"raise",
"exception",
".",
"InvalidException",
"(",
"'Item has no parent'",
")",
"node",
"=",
"sel... | Add a new sub item to the list. This item must already be attached to a list.
Args:
text (str): The text.
checked (bool): Whether this item is checked.
sort (int): Item id for sorting. | [
"Add",
"a",
"new",
"sub",
"item",
"to",
"the",
"list",
".",
"This",
"item",
"must",
"already",
"be",
"attached",
"to",
"a",
"list",
"."
] | 78aaae8b988b1cf616e3973f7f15d4c6d5e996cc | https://github.com/kiwiz/gkeepapi/blob/78aaae8b988b1cf616e3973f7f15d4c6d5e996cc/gkeepapi/node.py#L1464-L1476 |
230,074 | kiwiz/gkeepapi | gkeepapi/node.py | ListItem.indent | def indent(self, node, dirty=True):
"""Indent an item. Does nothing if the target has subitems.
Args:
node (gkeepapi.node.ListItem): Item to indent.
dirty (bool): Whether this node should be marked dirty.
"""
if node.subitems:
return
self._subitems[node.id] = node
node.super_list_item_id = self.id
node.parent_item = self
if dirty:
node.touch(True) | python | def indent(self, node, dirty=True):
if node.subitems:
return
self._subitems[node.id] = node
node.super_list_item_id = self.id
node.parent_item = self
if dirty:
node.touch(True) | [
"def",
"indent",
"(",
"self",
",",
"node",
",",
"dirty",
"=",
"True",
")",
":",
"if",
"node",
".",
"subitems",
":",
"return",
"self",
".",
"_subitems",
"[",
"node",
".",
"id",
"]",
"=",
"node",
"node",
".",
"super_list_item_id",
"=",
"self",
".",
"... | Indent an item. Does nothing if the target has subitems.
Args:
node (gkeepapi.node.ListItem): Item to indent.
dirty (bool): Whether this node should be marked dirty. | [
"Indent",
"an",
"item",
".",
"Does",
"nothing",
"if",
"the",
"target",
"has",
"subitems",
"."
] | 78aaae8b988b1cf616e3973f7f15d4c6d5e996cc | https://github.com/kiwiz/gkeepapi/blob/78aaae8b988b1cf616e3973f7f15d4c6d5e996cc/gkeepapi/node.py#L1478-L1492 |
230,075 | kiwiz/gkeepapi | gkeepapi/node.py | ListItem.dedent | def dedent(self, node, dirty=True):
"""Dedent an item. Does nothing if the target is not indented under this item.
Args:
node (gkeepapi.node.ListItem): Item to dedent.
dirty (bool): Whether this node should be marked dirty.
"""
if node.id not in self._subitems:
return
del self._subitems[node.id]
node.super_list_item_id = None
node.parent_item = None
if dirty:
node.touch(True) | python | def dedent(self, node, dirty=True):
if node.id not in self._subitems:
return
del self._subitems[node.id]
node.super_list_item_id = None
node.parent_item = None
if dirty:
node.touch(True) | [
"def",
"dedent",
"(",
"self",
",",
"node",
",",
"dirty",
"=",
"True",
")",
":",
"if",
"node",
".",
"id",
"not",
"in",
"self",
".",
"_subitems",
":",
"return",
"del",
"self",
".",
"_subitems",
"[",
"node",
".",
"id",
"]",
"node",
".",
"super_list_it... | Dedent an item. Does nothing if the target is not indented under this item.
Args:
node (gkeepapi.node.ListItem): Item to dedent.
dirty (bool): Whether this node should be marked dirty. | [
"Dedent",
"an",
"item",
".",
"Does",
"nothing",
"if",
"the",
"target",
"is",
"not",
"indented",
"under",
"this",
"item",
"."
] | 78aaae8b988b1cf616e3973f7f15d4c6d5e996cc | https://github.com/kiwiz/gkeepapi/blob/78aaae8b988b1cf616e3973f7f15d4c6d5e996cc/gkeepapi/node.py#L1494-L1508 |
230,076 | kiwiz/gkeepapi | gkeepapi/node.py | Blob.from_json | def from_json(cls, raw):
"""Helper to construct a blob from a dict.
Args:
raw (dict): Raw blob representation.
Returns:
NodeBlob: A NodeBlob object or None.
"""
if raw is None:
return None
bcls = None
_type = raw.get('type')
try:
bcls = cls._blob_type_map[BlobType(_type)]
except (KeyError, ValueError) as e:
logger.warning('Unknown blob type: %s', _type)
if DEBUG:
raise_from(exception.ParseException('Parse error for %s' % (_type), raw), e)
return None
blob = bcls()
blob.load(raw)
return blob | python | def from_json(cls, raw):
if raw is None:
return None
bcls = None
_type = raw.get('type')
try:
bcls = cls._blob_type_map[BlobType(_type)]
except (KeyError, ValueError) as e:
logger.warning('Unknown blob type: %s', _type)
if DEBUG:
raise_from(exception.ParseException('Parse error for %s' % (_type), raw), e)
return None
blob = bcls()
blob.load(raw)
return blob | [
"def",
"from_json",
"(",
"cls",
",",
"raw",
")",
":",
"if",
"raw",
"is",
"None",
":",
"return",
"None",
"bcls",
"=",
"None",
"_type",
"=",
"raw",
".",
"get",
"(",
"'type'",
")",
"try",
":",
"bcls",
"=",
"cls",
".",
"_blob_type_map",
"[",
"BlobType"... | Helper to construct a blob from a dict.
Args:
raw (dict): Raw blob representation.
Returns:
NodeBlob: A NodeBlob object or None. | [
"Helper",
"to",
"construct",
"a",
"blob",
"from",
"a",
"dict",
"."
] | 78aaae8b988b1cf616e3973f7f15d4c6d5e996cc | https://github.com/kiwiz/gkeepapi/blob/78aaae8b988b1cf616e3973f7f15d4c6d5e996cc/gkeepapi/node.py#L1706-L1730 |
230,077 | cevoaustralia/aws-google-auth | aws_google_auth/google.py | Google.check_prompt_code | def check_prompt_code(response):
"""
Sometimes there is an additional numerical code on the response page that needs to be selected
on the prompt from a list of multiple choice. Print it if it's there.
"""
num_code = response.find("div", {"jsname": "EKvSSd"})
if num_code:
print("numerical code for prompt: {}".format(num_code.string)) | python | def check_prompt_code(response):
num_code = response.find("div", {"jsname": "EKvSSd"})
if num_code:
print("numerical code for prompt: {}".format(num_code.string)) | [
"def",
"check_prompt_code",
"(",
"response",
")",
":",
"num_code",
"=",
"response",
".",
"find",
"(",
"\"div\"",
",",
"{",
"\"jsname\"",
":",
"\"EKvSSd\"",
"}",
")",
"if",
"num_code",
":",
"print",
"(",
"\"numerical code for prompt: {}\"",
".",
"format",
"(",
... | Sometimes there is an additional numerical code on the response page that needs to be selected
on the prompt from a list of multiple choice. Print it if it's there. | [
"Sometimes",
"there",
"is",
"an",
"additional",
"numerical",
"code",
"on",
"the",
"response",
"page",
"that",
"needs",
"to",
"be",
"selected",
"on",
"the",
"prompt",
"from",
"a",
"list",
"of",
"multiple",
"choice",
".",
"Print",
"it",
"if",
"it",
"s",
"t... | 6f5919d0408f117a6fa0ebc61ee23e5559ad39d5 | https://github.com/cevoaustralia/aws-google-auth/blob/6f5919d0408f117a6fa0ebc61ee23e5559ad39d5/aws_google_auth/google.py#L582-L589 |
230,078 | sphinx-gallery/sphinx-gallery | sphinx_gallery/backreferences.py | get_short_module_name | def get_short_module_name(module_name, obj_name):
""" Get the shortest possible module name """
scope = {}
try:
# Find out what the real object is supposed to be.
exec('from %s import %s' % (module_name, obj_name), scope, scope)
real_obj = scope[obj_name]
except Exception:
return module_name
parts = module_name.split('.')
short_name = module_name
for i in range(len(parts) - 1, 0, -1):
short_name = '.'.join(parts[:i])
scope = {}
try:
exec('from %s import %s' % (short_name, obj_name), scope, scope)
# Ensure shortened object is the same as what we expect.
assert real_obj is scope[obj_name]
except Exception: # libraries can throw all sorts of exceptions...
# get the last working module name
short_name = '.'.join(parts[:(i + 1)])
break
return short_name | python | def get_short_module_name(module_name, obj_name):
scope = {}
try:
# Find out what the real object is supposed to be.
exec('from %s import %s' % (module_name, obj_name), scope, scope)
real_obj = scope[obj_name]
except Exception:
return module_name
parts = module_name.split('.')
short_name = module_name
for i in range(len(parts) - 1, 0, -1):
short_name = '.'.join(parts[:i])
scope = {}
try:
exec('from %s import %s' % (short_name, obj_name), scope, scope)
# Ensure shortened object is the same as what we expect.
assert real_obj is scope[obj_name]
except Exception: # libraries can throw all sorts of exceptions...
# get the last working module name
short_name = '.'.join(parts[:(i + 1)])
break
return short_name | [
"def",
"get_short_module_name",
"(",
"module_name",
",",
"obj_name",
")",
":",
"scope",
"=",
"{",
"}",
"try",
":",
"# Find out what the real object is supposed to be.",
"exec",
"(",
"'from %s import %s'",
"%",
"(",
"module_name",
",",
"obj_name",
")",
",",
"scope",
... | Get the shortest possible module name | [
"Get",
"the",
"shortest",
"possible",
"module",
"name"
] | b0c1f6701bf3f4cef238757e1105cf3686b5e674 | https://github.com/sphinx-gallery/sphinx-gallery/blob/b0c1f6701bf3f4cef238757e1105cf3686b5e674/sphinx_gallery/backreferences.py#L85-L108 |
230,079 | sphinx-gallery/sphinx-gallery | sphinx_gallery/backreferences.py | identify_names | def identify_names(filename):
"""Builds a codeobj summary by identifying and resolving used names."""
node, _ = parse_source_file(filename)
if node is None:
return {}
# Get matches from the code (AST)
finder = NameFinder()
finder.visit(node)
names = list(finder.get_mapping())
names += extract_object_names_from_docs(filename)
example_code_obj = collections.OrderedDict()
for name, full_name in names:
if name in example_code_obj:
continue # if someone puts it in the docstring and code
# name is as written in file (e.g. np.asarray)
# full_name includes resolved import path (e.g. numpy.asarray)
splitted = full_name.rsplit('.', 1)
if len(splitted) == 1:
# module without attribute. This is not useful for
# backreferences
continue
module, attribute = splitted
# get shortened module name
module_short = get_short_module_name(module, attribute)
cobj = {'name': attribute, 'module': module,
'module_short': module_short}
example_code_obj[name] = cobj
return example_code_obj | python | def identify_names(filename):
node, _ = parse_source_file(filename)
if node is None:
return {}
# Get matches from the code (AST)
finder = NameFinder()
finder.visit(node)
names = list(finder.get_mapping())
names += extract_object_names_from_docs(filename)
example_code_obj = collections.OrderedDict()
for name, full_name in names:
if name in example_code_obj:
continue # if someone puts it in the docstring and code
# name is as written in file (e.g. np.asarray)
# full_name includes resolved import path (e.g. numpy.asarray)
splitted = full_name.rsplit('.', 1)
if len(splitted) == 1:
# module without attribute. This is not useful for
# backreferences
continue
module, attribute = splitted
# get shortened module name
module_short = get_short_module_name(module, attribute)
cobj = {'name': attribute, 'module': module,
'module_short': module_short}
example_code_obj[name] = cobj
return example_code_obj | [
"def",
"identify_names",
"(",
"filename",
")",
":",
"node",
",",
"_",
"=",
"parse_source_file",
"(",
"filename",
")",
"if",
"node",
"is",
"None",
":",
"return",
"{",
"}",
"# Get matches from the code (AST)",
"finder",
"=",
"NameFinder",
"(",
")",
"finder",
"... | Builds a codeobj summary by identifying and resolving used names. | [
"Builds",
"a",
"codeobj",
"summary",
"by",
"identifying",
"and",
"resolving",
"used",
"names",
"."
] | b0c1f6701bf3f4cef238757e1105cf3686b5e674 | https://github.com/sphinx-gallery/sphinx-gallery/blob/b0c1f6701bf3f4cef238757e1105cf3686b5e674/sphinx_gallery/backreferences.py#L125-L155 |
230,080 | sphinx-gallery/sphinx-gallery | sphinx_gallery/backreferences.py | scan_used_functions | def scan_used_functions(example_file, gallery_conf):
"""save variables so we can later add links to the documentation"""
example_code_obj = identify_names(example_file)
if example_code_obj:
codeobj_fname = example_file[:-3] + '_codeobj.pickle.new'
with open(codeobj_fname, 'wb') as fid:
pickle.dump(example_code_obj, fid, pickle.HIGHEST_PROTOCOL)
_replace_md5(codeobj_fname)
backrefs = set('{module_short}.{name}'.format(**entry)
for entry in example_code_obj.values()
if entry['module'].startswith(gallery_conf['doc_module']))
return backrefs | python | def scan_used_functions(example_file, gallery_conf):
example_code_obj = identify_names(example_file)
if example_code_obj:
codeobj_fname = example_file[:-3] + '_codeobj.pickle.new'
with open(codeobj_fname, 'wb') as fid:
pickle.dump(example_code_obj, fid, pickle.HIGHEST_PROTOCOL)
_replace_md5(codeobj_fname)
backrefs = set('{module_short}.{name}'.format(**entry)
for entry in example_code_obj.values()
if entry['module'].startswith(gallery_conf['doc_module']))
return backrefs | [
"def",
"scan_used_functions",
"(",
"example_file",
",",
"gallery_conf",
")",
":",
"example_code_obj",
"=",
"identify_names",
"(",
"example_file",
")",
"if",
"example_code_obj",
":",
"codeobj_fname",
"=",
"example_file",
"[",
":",
"-",
"3",
"]",
"+",
"'_codeobj.pic... | save variables so we can later add links to the documentation | [
"save",
"variables",
"so",
"we",
"can",
"later",
"add",
"links",
"to",
"the",
"documentation"
] | b0c1f6701bf3f4cef238757e1105cf3686b5e674 | https://github.com/sphinx-gallery/sphinx-gallery/blob/b0c1f6701bf3f4cef238757e1105cf3686b5e674/sphinx_gallery/backreferences.py#L158-L171 |
230,081 | sphinx-gallery/sphinx-gallery | sphinx_gallery/backreferences.py | _thumbnail_div | def _thumbnail_div(target_dir, src_dir, fname, snippet, is_backref=False,
check=True):
"""Generates RST to place a thumbnail in a gallery"""
thumb, _ = _find_image_ext(
os.path.join(target_dir, 'images', 'thumb',
'sphx_glr_%s_thumb.png' % fname[:-3]))
if check and not os.path.isfile(thumb):
# This means we have done something wrong in creating our thumbnail!
raise RuntimeError('Could not find internal sphinx-gallery thumbnail '
'file:\n%s' % (thumb,))
thumb = os.path.relpath(thumb, src_dir)
full_dir = os.path.relpath(target_dir, src_dir)
# Inside rst files forward slash defines paths
thumb = thumb.replace(os.sep, "/")
ref_name = os.path.join(full_dir, fname).replace(os.path.sep, '_')
template = BACKREF_THUMBNAIL_TEMPLATE if is_backref else THUMBNAIL_TEMPLATE
return template.format(snippet=escape(snippet),
thumbnail=thumb, ref_name=ref_name) | python | def _thumbnail_div(target_dir, src_dir, fname, snippet, is_backref=False,
check=True):
thumb, _ = _find_image_ext(
os.path.join(target_dir, 'images', 'thumb',
'sphx_glr_%s_thumb.png' % fname[:-3]))
if check and not os.path.isfile(thumb):
# This means we have done something wrong in creating our thumbnail!
raise RuntimeError('Could not find internal sphinx-gallery thumbnail '
'file:\n%s' % (thumb,))
thumb = os.path.relpath(thumb, src_dir)
full_dir = os.path.relpath(target_dir, src_dir)
# Inside rst files forward slash defines paths
thumb = thumb.replace(os.sep, "/")
ref_name = os.path.join(full_dir, fname).replace(os.path.sep, '_')
template = BACKREF_THUMBNAIL_TEMPLATE if is_backref else THUMBNAIL_TEMPLATE
return template.format(snippet=escape(snippet),
thumbnail=thumb, ref_name=ref_name) | [
"def",
"_thumbnail_div",
"(",
"target_dir",
",",
"src_dir",
",",
"fname",
",",
"snippet",
",",
"is_backref",
"=",
"False",
",",
"check",
"=",
"True",
")",
":",
"thumb",
",",
"_",
"=",
"_find_image_ext",
"(",
"os",
".",
"path",
".",
"join",
"(",
"target... | Generates RST to place a thumbnail in a gallery | [
"Generates",
"RST",
"to",
"place",
"a",
"thumbnail",
"in",
"a",
"gallery"
] | b0c1f6701bf3f4cef238757e1105cf3686b5e674 | https://github.com/sphinx-gallery/sphinx-gallery/blob/b0c1f6701bf3f4cef238757e1105cf3686b5e674/sphinx_gallery/backreferences.py#L197-L217 |
230,082 | sphinx-gallery/sphinx-gallery | sphinx_gallery/backreferences.py | write_backreferences | def write_backreferences(seen_backrefs, gallery_conf,
target_dir, fname, snippet):
"""Writes down back reference files, which include a thumbnail list
of examples using a certain module"""
if gallery_conf['backreferences_dir'] is None:
return
example_file = os.path.join(target_dir, fname)
backrefs = scan_used_functions(example_file, gallery_conf)
for backref in backrefs:
include_path = os.path.join(gallery_conf['src_dir'],
gallery_conf['backreferences_dir'],
'%s.examples.new' % backref)
seen = backref in seen_backrefs
with codecs.open(include_path, 'a' if seen else 'w',
encoding='utf-8') as ex_file:
if not seen:
heading = '\n\nExamples using ``%s``' % backref
ex_file.write(heading + '\n')
ex_file.write('^' * len(heading) + '\n')
ex_file.write(_thumbnail_div(target_dir, gallery_conf['src_dir'],
fname, snippet, is_backref=True))
seen_backrefs.add(backref) | python | def write_backreferences(seen_backrefs, gallery_conf,
target_dir, fname, snippet):
if gallery_conf['backreferences_dir'] is None:
return
example_file = os.path.join(target_dir, fname)
backrefs = scan_used_functions(example_file, gallery_conf)
for backref in backrefs:
include_path = os.path.join(gallery_conf['src_dir'],
gallery_conf['backreferences_dir'],
'%s.examples.new' % backref)
seen = backref in seen_backrefs
with codecs.open(include_path, 'a' if seen else 'w',
encoding='utf-8') as ex_file:
if not seen:
heading = '\n\nExamples using ``%s``' % backref
ex_file.write(heading + '\n')
ex_file.write('^' * len(heading) + '\n')
ex_file.write(_thumbnail_div(target_dir, gallery_conf['src_dir'],
fname, snippet, is_backref=True))
seen_backrefs.add(backref) | [
"def",
"write_backreferences",
"(",
"seen_backrefs",
",",
"gallery_conf",
",",
"target_dir",
",",
"fname",
",",
"snippet",
")",
":",
"if",
"gallery_conf",
"[",
"'backreferences_dir'",
"]",
"is",
"None",
":",
"return",
"example_file",
"=",
"os",
".",
"path",
".... | Writes down back reference files, which include a thumbnail list
of examples using a certain module | [
"Writes",
"down",
"back",
"reference",
"files",
"which",
"include",
"a",
"thumbnail",
"list",
"of",
"examples",
"using",
"a",
"certain",
"module"
] | b0c1f6701bf3f4cef238757e1105cf3686b5e674 | https://github.com/sphinx-gallery/sphinx-gallery/blob/b0c1f6701bf3f4cef238757e1105cf3686b5e674/sphinx_gallery/backreferences.py#L220-L242 |
230,083 | sphinx-gallery/sphinx-gallery | sphinx_gallery/backreferences.py | finalize_backreferences | def finalize_backreferences(seen_backrefs, gallery_conf):
"""Replace backref files only if necessary."""
logger = sphinx_compatibility.getLogger('sphinx-gallery')
if gallery_conf['backreferences_dir'] is None:
return
for backref in seen_backrefs:
path = os.path.join(gallery_conf['src_dir'],
gallery_conf['backreferences_dir'],
'%s.examples.new' % backref)
if os.path.isfile(path):
_replace_md5(path)
else:
level = gallery_conf['log_level'].get('backreference_missing',
'warning')
func = getattr(logger, level)
func('Could not find backreferences file: %s' % (path,))
func('The backreferences are likely to be erroneous '
'due to file system case insensitivity.') | python | def finalize_backreferences(seen_backrefs, gallery_conf):
logger = sphinx_compatibility.getLogger('sphinx-gallery')
if gallery_conf['backreferences_dir'] is None:
return
for backref in seen_backrefs:
path = os.path.join(gallery_conf['src_dir'],
gallery_conf['backreferences_dir'],
'%s.examples.new' % backref)
if os.path.isfile(path):
_replace_md5(path)
else:
level = gallery_conf['log_level'].get('backreference_missing',
'warning')
func = getattr(logger, level)
func('Could not find backreferences file: %s' % (path,))
func('The backreferences are likely to be erroneous '
'due to file system case insensitivity.') | [
"def",
"finalize_backreferences",
"(",
"seen_backrefs",
",",
"gallery_conf",
")",
":",
"logger",
"=",
"sphinx_compatibility",
".",
"getLogger",
"(",
"'sphinx-gallery'",
")",
"if",
"gallery_conf",
"[",
"'backreferences_dir'",
"]",
"is",
"None",
":",
"return",
"for",
... | Replace backref files only if necessary. | [
"Replace",
"backref",
"files",
"only",
"if",
"necessary",
"."
] | b0c1f6701bf3f4cef238757e1105cf3686b5e674 | https://github.com/sphinx-gallery/sphinx-gallery/blob/b0c1f6701bf3f4cef238757e1105cf3686b5e674/sphinx_gallery/backreferences.py#L245-L263 |
230,084 | sphinx-gallery/sphinx-gallery | sphinx_gallery/notebook.py | jupyter_notebook_skeleton | def jupyter_notebook_skeleton():
"""Returns a dictionary with the elements of a Jupyter notebook"""
py_version = sys.version_info
notebook_skeleton = {
"cells": [],
"metadata": {
"kernelspec": {
"display_name": "Python " + str(py_version[0]),
"language": "python",
"name": "python" + str(py_version[0])
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": py_version[0]
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython" + str(py_version[0]),
"version": '{0}.{1}.{2}'.format(*sys.version_info[:3])
}
},
"nbformat": 4,
"nbformat_minor": 0
}
return notebook_skeleton | python | def jupyter_notebook_skeleton():
py_version = sys.version_info
notebook_skeleton = {
"cells": [],
"metadata": {
"kernelspec": {
"display_name": "Python " + str(py_version[0]),
"language": "python",
"name": "python" + str(py_version[0])
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": py_version[0]
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython" + str(py_version[0]),
"version": '{0}.{1}.{2}'.format(*sys.version_info[:3])
}
},
"nbformat": 4,
"nbformat_minor": 0
}
return notebook_skeleton | [
"def",
"jupyter_notebook_skeleton",
"(",
")",
":",
"py_version",
"=",
"sys",
".",
"version_info",
"notebook_skeleton",
"=",
"{",
"\"cells\"",
":",
"[",
"]",
",",
"\"metadata\"",
":",
"{",
"\"kernelspec\"",
":",
"{",
"\"display_name\"",
":",
"\"Python \"",
"+",
... | Returns a dictionary with the elements of a Jupyter notebook | [
"Returns",
"a",
"dictionary",
"with",
"the",
"elements",
"of",
"a",
"Jupyter",
"notebook"
] | b0c1f6701bf3f4cef238757e1105cf3686b5e674 | https://github.com/sphinx-gallery/sphinx-gallery/blob/b0c1f6701bf3f4cef238757e1105cf3686b5e674/sphinx_gallery/notebook.py#L24-L51 |
230,085 | sphinx-gallery/sphinx-gallery | sphinx_gallery/notebook.py | directive_fun | def directive_fun(match, directive):
"""Helper to fill in directives"""
directive_to_alert = dict(note="info", warning="danger")
return ('<div class="alert alert-{0}"><h4>{1}</h4><p>{2}</p></div>'
.format(directive_to_alert[directive], directive.capitalize(),
match.group(1).strip())) | python | def directive_fun(match, directive):
directive_to_alert = dict(note="info", warning="danger")
return ('<div class="alert alert-{0}"><h4>{1}</h4><p>{2}</p></div>'
.format(directive_to_alert[directive], directive.capitalize(),
match.group(1).strip())) | [
"def",
"directive_fun",
"(",
"match",
",",
"directive",
")",
":",
"directive_to_alert",
"=",
"dict",
"(",
"note",
"=",
"\"info\"",
",",
"warning",
"=",
"\"danger\"",
")",
"return",
"(",
"'<div class=\"alert alert-{0}\"><h4>{1}</h4><p>{2}</p></div>'",
".",
"format",
... | Helper to fill in directives | [
"Helper",
"to",
"fill",
"in",
"directives"
] | b0c1f6701bf3f4cef238757e1105cf3686b5e674 | https://github.com/sphinx-gallery/sphinx-gallery/blob/b0c1f6701bf3f4cef238757e1105cf3686b5e674/sphinx_gallery/notebook.py#L54-L59 |
230,086 | sphinx-gallery/sphinx-gallery | sphinx_gallery/notebook.py | rst2md | def rst2md(text):
"""Converts the RST text from the examples docstrigs and comments
into markdown text for the Jupyter notebooks"""
top_heading = re.compile(r'^=+$\s^([\w\s-]+)^=+$', flags=re.M)
text = re.sub(top_heading, r'# \1', text)
math_eq = re.compile(r'^\.\. math::((?:.+)?(?:\n+^ .+)*)', flags=re.M)
text = re.sub(math_eq,
lambda match: r'\begin{{align}}{0}\end{{align}}'.format(
match.group(1).strip()),
text)
inline_math = re.compile(r':math:`(.+?)`', re.DOTALL)
text = re.sub(inline_math, r'$\1$', text)
directives = ('warning', 'note')
for directive in directives:
directive_re = re.compile(r'^\.\. %s::((?:.+)?(?:\n+^ .+)*)'
% directive, flags=re.M)
text = re.sub(directive_re,
partial(directive_fun, directive=directive), text)
links = re.compile(r'^ *\.\. _.*:.*$\n', flags=re.M)
text = re.sub(links, '', text)
refs = re.compile(r':ref:`')
text = re.sub(refs, '`', text)
contents = re.compile(r'^\s*\.\. contents::.*$(\n +:\S+: *$)*\n',
flags=re.M)
text = re.sub(contents, '', text)
images = re.compile(
r'^\.\. image::(.*$)(?:\n *:alt:(.*$)\n)?(?: +:\S+:.*$\n)*',
flags=re.M)
text = re.sub(
images, lambda match: '\n'.format(
match.group(1).strip(), (match.group(2) or '').strip()), text)
return text | python | def rst2md(text):
top_heading = re.compile(r'^=+$\s^([\w\s-]+)^=+$', flags=re.M)
text = re.sub(top_heading, r'# \1', text)
math_eq = re.compile(r'^\.\. math::((?:.+)?(?:\n+^ .+)*)', flags=re.M)
text = re.sub(math_eq,
lambda match: r'\begin{{align}}{0}\end{{align}}'.format(
match.group(1).strip()),
text)
inline_math = re.compile(r':math:`(.+?)`', re.DOTALL)
text = re.sub(inline_math, r'$\1$', text)
directives = ('warning', 'note')
for directive in directives:
directive_re = re.compile(r'^\.\. %s::((?:.+)?(?:\n+^ .+)*)'
% directive, flags=re.M)
text = re.sub(directive_re,
partial(directive_fun, directive=directive), text)
links = re.compile(r'^ *\.\. _.*:.*$\n', flags=re.M)
text = re.sub(links, '', text)
refs = re.compile(r':ref:`')
text = re.sub(refs, '`', text)
contents = re.compile(r'^\s*\.\. contents::.*$(\n +:\S+: *$)*\n',
flags=re.M)
text = re.sub(contents, '', text)
images = re.compile(
r'^\.\. image::(.*$)(?:\n *:alt:(.*$)\n)?(?: +:\S+:.*$\n)*',
flags=re.M)
text = re.sub(
images, lambda match: '\n'.format(
match.group(1).strip(), (match.group(2) or '').strip()), text)
return text | [
"def",
"rst2md",
"(",
"text",
")",
":",
"top_heading",
"=",
"re",
".",
"compile",
"(",
"r'^=+$\\s^([\\w\\s-]+)^=+$'",
",",
"flags",
"=",
"re",
".",
"M",
")",
"text",
"=",
"re",
".",
"sub",
"(",
"top_heading",
",",
"r'# \\1'",
",",
"text",
")",
"math_eq... | Converts the RST text from the examples docstrigs and comments
into markdown text for the Jupyter notebooks | [
"Converts",
"the",
"RST",
"text",
"from",
"the",
"examples",
"docstrigs",
"and",
"comments",
"into",
"markdown",
"text",
"for",
"the",
"Jupyter",
"notebooks"
] | b0c1f6701bf3f4cef238757e1105cf3686b5e674 | https://github.com/sphinx-gallery/sphinx-gallery/blob/b0c1f6701bf3f4cef238757e1105cf3686b5e674/sphinx_gallery/notebook.py#L62-L101 |
230,087 | sphinx-gallery/sphinx-gallery | sphinx_gallery/notebook.py | jupyter_notebook | def jupyter_notebook(script_blocks, gallery_conf):
"""Generate a Jupyter notebook file cell-by-cell
Parameters
----------
script_blocks : list
Script execution cells.
gallery_conf : dict
The sphinx-gallery configuration dictionary.
"""
first_cell = gallery_conf.get("first_notebook_cell", "%matplotlib inline")
work_notebook = jupyter_notebook_skeleton()
if first_cell is not None:
add_code_cell(work_notebook, first_cell)
fill_notebook(work_notebook, script_blocks)
return work_notebook | python | def jupyter_notebook(script_blocks, gallery_conf):
first_cell = gallery_conf.get("first_notebook_cell", "%matplotlib inline")
work_notebook = jupyter_notebook_skeleton()
if first_cell is not None:
add_code_cell(work_notebook, first_cell)
fill_notebook(work_notebook, script_blocks)
return work_notebook | [
"def",
"jupyter_notebook",
"(",
"script_blocks",
",",
"gallery_conf",
")",
":",
"first_cell",
"=",
"gallery_conf",
".",
"get",
"(",
"\"first_notebook_cell\"",
",",
"\"%matplotlib inline\"",
")",
"work_notebook",
"=",
"jupyter_notebook_skeleton",
"(",
")",
"if",
"first... | Generate a Jupyter notebook file cell-by-cell
Parameters
----------
script_blocks : list
Script execution cells.
gallery_conf : dict
The sphinx-gallery configuration dictionary. | [
"Generate",
"a",
"Jupyter",
"notebook",
"file",
"cell",
"-",
"by",
"-",
"cell"
] | b0c1f6701bf3f4cef238757e1105cf3686b5e674 | https://github.com/sphinx-gallery/sphinx-gallery/blob/b0c1f6701bf3f4cef238757e1105cf3686b5e674/sphinx_gallery/notebook.py#L104-L120 |
230,088 | sphinx-gallery/sphinx-gallery | sphinx_gallery/notebook.py | add_code_cell | def add_code_cell(work_notebook, code):
"""Add a code cell to the notebook
Parameters
----------
code : str
Cell content
"""
code_cell = {
"cell_type": "code",
"execution_count": None,
"metadata": {"collapsed": False},
"outputs": [],
"source": [code.strip()]
}
work_notebook["cells"].append(code_cell) | python | def add_code_cell(work_notebook, code):
code_cell = {
"cell_type": "code",
"execution_count": None,
"metadata": {"collapsed": False},
"outputs": [],
"source": [code.strip()]
}
work_notebook["cells"].append(code_cell) | [
"def",
"add_code_cell",
"(",
"work_notebook",
",",
"code",
")",
":",
"code_cell",
"=",
"{",
"\"cell_type\"",
":",
"\"code\"",
",",
"\"execution_count\"",
":",
"None",
",",
"\"metadata\"",
":",
"{",
"\"collapsed\"",
":",
"False",
"}",
",",
"\"outputs\"",
":",
... | Add a code cell to the notebook
Parameters
----------
code : str
Cell content | [
"Add",
"a",
"code",
"cell",
"to",
"the",
"notebook"
] | b0c1f6701bf3f4cef238757e1105cf3686b5e674 | https://github.com/sphinx-gallery/sphinx-gallery/blob/b0c1f6701bf3f4cef238757e1105cf3686b5e674/sphinx_gallery/notebook.py#L123-L139 |
230,089 | sphinx-gallery/sphinx-gallery | sphinx_gallery/notebook.py | fill_notebook | def fill_notebook(work_notebook, script_blocks):
"""Writes the Jupyter notebook cells
Parameters
----------
script_blocks : list
Each list element should be a tuple of (label, content, lineno).
"""
for blabel, bcontent, lineno in script_blocks:
if blabel == 'code':
add_code_cell(work_notebook, bcontent)
else:
add_markdown_cell(work_notebook, bcontent + '\n') | python | def fill_notebook(work_notebook, script_blocks):
for blabel, bcontent, lineno in script_blocks:
if blabel == 'code':
add_code_cell(work_notebook, bcontent)
else:
add_markdown_cell(work_notebook, bcontent + '\n') | [
"def",
"fill_notebook",
"(",
"work_notebook",
",",
"script_blocks",
")",
":",
"for",
"blabel",
",",
"bcontent",
",",
"lineno",
"in",
"script_blocks",
":",
"if",
"blabel",
"==",
"'code'",
":",
"add_code_cell",
"(",
"work_notebook",
",",
"bcontent",
")",
"else",... | Writes the Jupyter notebook cells
Parameters
----------
script_blocks : list
Each list element should be a tuple of (label, content, lineno). | [
"Writes",
"the",
"Jupyter",
"notebook",
"cells"
] | b0c1f6701bf3f4cef238757e1105cf3686b5e674 | https://github.com/sphinx-gallery/sphinx-gallery/blob/b0c1f6701bf3f4cef238757e1105cf3686b5e674/sphinx_gallery/notebook.py#L158-L171 |
230,090 | sphinx-gallery/sphinx-gallery | sphinx_gallery/notebook.py | save_notebook | def save_notebook(work_notebook, write_file):
"""Saves the Jupyter work_notebook to write_file"""
with open(write_file, 'w') as out_nb:
json.dump(work_notebook, out_nb, indent=2) | python | def save_notebook(work_notebook, write_file):
with open(write_file, 'w') as out_nb:
json.dump(work_notebook, out_nb, indent=2) | [
"def",
"save_notebook",
"(",
"work_notebook",
",",
"write_file",
")",
":",
"with",
"open",
"(",
"write_file",
",",
"'w'",
")",
"as",
"out_nb",
":",
"json",
".",
"dump",
"(",
"work_notebook",
",",
"out_nb",
",",
"indent",
"=",
"2",
")"
] | Saves the Jupyter work_notebook to write_file | [
"Saves",
"the",
"Jupyter",
"work_notebook",
"to",
"write_file"
] | b0c1f6701bf3f4cef238757e1105cf3686b5e674 | https://github.com/sphinx-gallery/sphinx-gallery/blob/b0c1f6701bf3f4cef238757e1105cf3686b5e674/sphinx_gallery/notebook.py#L174-L177 |
230,091 | sphinx-gallery/sphinx-gallery | sphinx_gallery/notebook.py | python_to_jupyter_cli | def python_to_jupyter_cli(args=None, namespace=None):
"""Exposes the jupyter notebook renderer to the command line
Takes the same arguments as ArgumentParser.parse_args
"""
from . import gen_gallery # To avoid circular import
parser = argparse.ArgumentParser(
description='Sphinx-Gallery Notebook converter')
parser.add_argument('python_src_file', nargs='+',
help='Input Python file script to convert. '
'Supports multiple files and shell wildcards'
' (e.g. *.py)')
args = parser.parse_args(args, namespace)
for src_file in args.python_src_file:
file_conf, blocks = split_code_and_text_blocks(src_file)
print('Converting {0}'.format(src_file))
gallery_conf = copy.deepcopy(gen_gallery.DEFAULT_GALLERY_CONF)
example_nb = jupyter_notebook(blocks, gallery_conf)
save_notebook(example_nb, replace_py_ipynb(src_file)) | python | def python_to_jupyter_cli(args=None, namespace=None):
from . import gen_gallery # To avoid circular import
parser = argparse.ArgumentParser(
description='Sphinx-Gallery Notebook converter')
parser.add_argument('python_src_file', nargs='+',
help='Input Python file script to convert. '
'Supports multiple files and shell wildcards'
' (e.g. *.py)')
args = parser.parse_args(args, namespace)
for src_file in args.python_src_file:
file_conf, blocks = split_code_and_text_blocks(src_file)
print('Converting {0}'.format(src_file))
gallery_conf = copy.deepcopy(gen_gallery.DEFAULT_GALLERY_CONF)
example_nb = jupyter_notebook(blocks, gallery_conf)
save_notebook(example_nb, replace_py_ipynb(src_file)) | [
"def",
"python_to_jupyter_cli",
"(",
"args",
"=",
"None",
",",
"namespace",
"=",
"None",
")",
":",
"from",
".",
"import",
"gen_gallery",
"# To avoid circular import",
"parser",
"=",
"argparse",
".",
"ArgumentParser",
"(",
"description",
"=",
"'Sphinx-Gallery Noteboo... | Exposes the jupyter notebook renderer to the command line
Takes the same arguments as ArgumentParser.parse_args | [
"Exposes",
"the",
"jupyter",
"notebook",
"renderer",
"to",
"the",
"command",
"line"
] | b0c1f6701bf3f4cef238757e1105cf3686b5e674 | https://github.com/sphinx-gallery/sphinx-gallery/blob/b0c1f6701bf3f4cef238757e1105cf3686b5e674/sphinx_gallery/notebook.py#L183-L202 |
230,092 | sphinx-gallery/sphinx-gallery | sphinx_gallery/scrapers.py | _import_matplotlib | def _import_matplotlib():
"""Import matplotlib safely."""
# make sure that the Agg backend is set before importing any
# matplotlib
import matplotlib
matplotlib.use('agg')
matplotlib_backend = matplotlib.get_backend().lower()
if matplotlib_backend != 'agg':
raise ValueError(
"Sphinx-Gallery relies on the matplotlib 'agg' backend to "
"render figures and write them to files. You are "
"currently using the {} backend. Sphinx-Gallery will "
"terminate the build now, because changing backends is "
"not well supported by matplotlib. We advise you to move "
"sphinx_gallery imports before any matplotlib-dependent "
"import. Moving sphinx_gallery imports at the top of "
"your conf.py file should fix this issue"
.format(matplotlib_backend))
import matplotlib.pyplot as plt
return matplotlib, plt | python | def _import_matplotlib():
# make sure that the Agg backend is set before importing any
# matplotlib
import matplotlib
matplotlib.use('agg')
matplotlib_backend = matplotlib.get_backend().lower()
if matplotlib_backend != 'agg':
raise ValueError(
"Sphinx-Gallery relies on the matplotlib 'agg' backend to "
"render figures and write them to files. You are "
"currently using the {} backend. Sphinx-Gallery will "
"terminate the build now, because changing backends is "
"not well supported by matplotlib. We advise you to move "
"sphinx_gallery imports before any matplotlib-dependent "
"import. Moving sphinx_gallery imports at the top of "
"your conf.py file should fix this issue"
.format(matplotlib_backend))
import matplotlib.pyplot as plt
return matplotlib, plt | [
"def",
"_import_matplotlib",
"(",
")",
":",
"# make sure that the Agg backend is set before importing any",
"# matplotlib",
"import",
"matplotlib",
"matplotlib",
".",
"use",
"(",
"'agg'",
")",
"matplotlib_backend",
"=",
"matplotlib",
".",
"get_backend",
"(",
")",
".",
"... | Import matplotlib safely. | [
"Import",
"matplotlib",
"safely",
"."
] | b0c1f6701bf3f4cef238757e1105cf3686b5e674 | https://github.com/sphinx-gallery/sphinx-gallery/blob/b0c1f6701bf3f4cef238757e1105cf3686b5e674/sphinx_gallery/scrapers.py#L29-L50 |
230,093 | sphinx-gallery/sphinx-gallery | sphinx_gallery/scrapers.py | matplotlib_scraper | def matplotlib_scraper(block, block_vars, gallery_conf, **kwargs):
"""Scrape Matplotlib images.
Parameters
----------
block : tuple
A tuple containing the (label, content, line_number) of the block.
block_vars : dict
Dict of block variables.
gallery_conf : dict
Contains the configuration of Sphinx-Gallery
**kwargs : dict
Additional keyword arguments to pass to
:meth:`~matplotlib.figure.Figure.savefig`, e.g. ``format='svg'``.
The ``format`` kwarg in particular is used to set the file extension
of the output file (currently only 'png' and 'svg' are supported).
Returns
-------
rst : str
The ReSTructuredText that will be rendered to HTML containing
the images. This is often produced by :func:`figure_rst`.
"""
matplotlib, plt = _import_matplotlib()
image_path_iterator = block_vars['image_path_iterator']
image_paths = list()
for fig_num, image_path in zip(plt.get_fignums(), image_path_iterator):
if 'format' in kwargs:
image_path = '%s.%s' % (os.path.splitext(image_path)[0],
kwargs['format'])
# Set the fig_num figure as the current figure as we can't
# save a figure that's not the current figure.
fig = plt.figure(fig_num)
to_rgba = matplotlib.colors.colorConverter.to_rgba
for attr in ['facecolor', 'edgecolor']:
fig_attr = getattr(fig, 'get_' + attr)()
default_attr = matplotlib.rcParams['figure.' + attr]
if to_rgba(fig_attr) != to_rgba(default_attr) and \
attr not in kwargs:
kwargs[attr] = fig_attr
fig.savefig(image_path, **kwargs)
image_paths.append(image_path)
plt.close('all')
return figure_rst(image_paths, gallery_conf['src_dir']) | python | def matplotlib_scraper(block, block_vars, gallery_conf, **kwargs):
matplotlib, plt = _import_matplotlib()
image_path_iterator = block_vars['image_path_iterator']
image_paths = list()
for fig_num, image_path in zip(plt.get_fignums(), image_path_iterator):
if 'format' in kwargs:
image_path = '%s.%s' % (os.path.splitext(image_path)[0],
kwargs['format'])
# Set the fig_num figure as the current figure as we can't
# save a figure that's not the current figure.
fig = plt.figure(fig_num)
to_rgba = matplotlib.colors.colorConverter.to_rgba
for attr in ['facecolor', 'edgecolor']:
fig_attr = getattr(fig, 'get_' + attr)()
default_attr = matplotlib.rcParams['figure.' + attr]
if to_rgba(fig_attr) != to_rgba(default_attr) and \
attr not in kwargs:
kwargs[attr] = fig_attr
fig.savefig(image_path, **kwargs)
image_paths.append(image_path)
plt.close('all')
return figure_rst(image_paths, gallery_conf['src_dir']) | [
"def",
"matplotlib_scraper",
"(",
"block",
",",
"block_vars",
",",
"gallery_conf",
",",
"*",
"*",
"kwargs",
")",
":",
"matplotlib",
",",
"plt",
"=",
"_import_matplotlib",
"(",
")",
"image_path_iterator",
"=",
"block_vars",
"[",
"'image_path_iterator'",
"]",
"ima... | Scrape Matplotlib images.
Parameters
----------
block : tuple
A tuple containing the (label, content, line_number) of the block.
block_vars : dict
Dict of block variables.
gallery_conf : dict
Contains the configuration of Sphinx-Gallery
**kwargs : dict
Additional keyword arguments to pass to
:meth:`~matplotlib.figure.Figure.savefig`, e.g. ``format='svg'``.
The ``format`` kwarg in particular is used to set the file extension
of the output file (currently only 'png' and 'svg' are supported).
Returns
-------
rst : str
The ReSTructuredText that will be rendered to HTML containing
the images. This is often produced by :func:`figure_rst`. | [
"Scrape",
"Matplotlib",
"images",
"."
] | b0c1f6701bf3f4cef238757e1105cf3686b5e674 | https://github.com/sphinx-gallery/sphinx-gallery/blob/b0c1f6701bf3f4cef238757e1105cf3686b5e674/sphinx_gallery/scrapers.py#L58-L101 |
230,094 | sphinx-gallery/sphinx-gallery | sphinx_gallery/scrapers.py | mayavi_scraper | def mayavi_scraper(block, block_vars, gallery_conf):
"""Scrape Mayavi images.
Parameters
----------
block : tuple
A tuple containing the (label, content, line_number) of the block.
block_vars : dict
Dict of block variables.
gallery_conf : dict
Contains the configuration of Sphinx-Gallery
Returns
-------
rst : str
The ReSTructuredText that will be rendered to HTML containing
the images. This is often produced by :func:`figure_rst`.
"""
from mayavi import mlab
image_path_iterator = block_vars['image_path_iterator']
image_paths = list()
e = mlab.get_engine()
for scene, image_path in zip(e.scenes, image_path_iterator):
mlab.savefig(image_path, figure=scene)
# make sure the image is not too large
scale_image(image_path, image_path, 850, 999)
image_paths.append(image_path)
mlab.close(all=True)
return figure_rst(image_paths, gallery_conf['src_dir']) | python | def mayavi_scraper(block, block_vars, gallery_conf):
from mayavi import mlab
image_path_iterator = block_vars['image_path_iterator']
image_paths = list()
e = mlab.get_engine()
for scene, image_path in zip(e.scenes, image_path_iterator):
mlab.savefig(image_path, figure=scene)
# make sure the image is not too large
scale_image(image_path, image_path, 850, 999)
image_paths.append(image_path)
mlab.close(all=True)
return figure_rst(image_paths, gallery_conf['src_dir']) | [
"def",
"mayavi_scraper",
"(",
"block",
",",
"block_vars",
",",
"gallery_conf",
")",
":",
"from",
"mayavi",
"import",
"mlab",
"image_path_iterator",
"=",
"block_vars",
"[",
"'image_path_iterator'",
"]",
"image_paths",
"=",
"list",
"(",
")",
"e",
"=",
"mlab",
".... | Scrape Mayavi images.
Parameters
----------
block : tuple
A tuple containing the (label, content, line_number) of the block.
block_vars : dict
Dict of block variables.
gallery_conf : dict
Contains the configuration of Sphinx-Gallery
Returns
-------
rst : str
The ReSTructuredText that will be rendered to HTML containing
the images. This is often produced by :func:`figure_rst`. | [
"Scrape",
"Mayavi",
"images",
"."
] | b0c1f6701bf3f4cef238757e1105cf3686b5e674 | https://github.com/sphinx-gallery/sphinx-gallery/blob/b0c1f6701bf3f4cef238757e1105cf3686b5e674/sphinx_gallery/scrapers.py#L104-L132 |
230,095 | sphinx-gallery/sphinx-gallery | sphinx_gallery/scrapers.py | _find_image_ext | def _find_image_ext(path, number=None):
"""Find an image, tolerant of different file extensions."""
if number is not None:
path = path.format(number)
path = os.path.splitext(path)[0]
for ext in _KNOWN_IMG_EXTS:
this_path = '%s.%s' % (path, ext)
if os.path.isfile(this_path):
break
else:
ext = 'png'
return ('%s.%s' % (path, ext), ext) | python | def _find_image_ext(path, number=None):
if number is not None:
path = path.format(number)
path = os.path.splitext(path)[0]
for ext in _KNOWN_IMG_EXTS:
this_path = '%s.%s' % (path, ext)
if os.path.isfile(this_path):
break
else:
ext = 'png'
return ('%s.%s' % (path, ext), ext) | [
"def",
"_find_image_ext",
"(",
"path",
",",
"number",
"=",
"None",
")",
":",
"if",
"number",
"is",
"not",
"None",
":",
"path",
"=",
"path",
".",
"format",
"(",
"number",
")",
"path",
"=",
"os",
".",
"path",
".",
"splitext",
"(",
"path",
")",
"[",
... | Find an image, tolerant of different file extensions. | [
"Find",
"an",
"image",
"tolerant",
"of",
"different",
"file",
"extensions",
"."
] | b0c1f6701bf3f4cef238757e1105cf3686b5e674 | https://github.com/sphinx-gallery/sphinx-gallery/blob/b0c1f6701bf3f4cef238757e1105cf3686b5e674/sphinx_gallery/scrapers.py#L200-L211 |
230,096 | sphinx-gallery/sphinx-gallery | sphinx_gallery/scrapers.py | save_figures | def save_figures(block, block_vars, gallery_conf):
"""Save all open figures of the example code-block.
Parameters
----------
block : tuple
A tuple containing the (label, content, line_number) of the block.
block_vars : dict
Dict of block variables.
gallery_conf : dict
Contains the configuration of Sphinx-Gallery
Returns
-------
images_rst : str
rst code to embed the images in the document.
"""
image_path_iterator = block_vars['image_path_iterator']
all_rst = u''
prev_count = len(image_path_iterator)
for scraper in gallery_conf['image_scrapers']:
rst = scraper(block, block_vars, gallery_conf)
if not isinstance(rst, basestring):
raise TypeError('rst from scraper %r was not a string, '
'got type %s:\n%r'
% (scraper, type(rst), rst))
n_new = len(image_path_iterator) - prev_count
for ii in range(n_new):
current_path, _ = _find_image_ext(
image_path_iterator.paths[prev_count + ii])
if not os.path.isfile(current_path):
raise RuntimeError('Scraper %s did not produce expected image:'
'\n%s' % (scraper, current_path))
all_rst += rst
return all_rst | python | def save_figures(block, block_vars, gallery_conf):
image_path_iterator = block_vars['image_path_iterator']
all_rst = u''
prev_count = len(image_path_iterator)
for scraper in gallery_conf['image_scrapers']:
rst = scraper(block, block_vars, gallery_conf)
if not isinstance(rst, basestring):
raise TypeError('rst from scraper %r was not a string, '
'got type %s:\n%r'
% (scraper, type(rst), rst))
n_new = len(image_path_iterator) - prev_count
for ii in range(n_new):
current_path, _ = _find_image_ext(
image_path_iterator.paths[prev_count + ii])
if not os.path.isfile(current_path):
raise RuntimeError('Scraper %s did not produce expected image:'
'\n%s' % (scraper, current_path))
all_rst += rst
return all_rst | [
"def",
"save_figures",
"(",
"block",
",",
"block_vars",
",",
"gallery_conf",
")",
":",
"image_path_iterator",
"=",
"block_vars",
"[",
"'image_path_iterator'",
"]",
"all_rst",
"=",
"u''",
"prev_count",
"=",
"len",
"(",
"image_path_iterator",
")",
"for",
"scraper",
... | Save all open figures of the example code-block.
Parameters
----------
block : tuple
A tuple containing the (label, content, line_number) of the block.
block_vars : dict
Dict of block variables.
gallery_conf : dict
Contains the configuration of Sphinx-Gallery
Returns
-------
images_rst : str
rst code to embed the images in the document. | [
"Save",
"all",
"open",
"figures",
"of",
"the",
"example",
"code",
"-",
"block",
"."
] | b0c1f6701bf3f4cef238757e1105cf3686b5e674 | https://github.com/sphinx-gallery/sphinx-gallery/blob/b0c1f6701bf3f4cef238757e1105cf3686b5e674/sphinx_gallery/scrapers.py#L214-L248 |
230,097 | sphinx-gallery/sphinx-gallery | sphinx_gallery/scrapers.py | figure_rst | def figure_rst(figure_list, sources_dir):
"""Generate RST for a list of PNG filenames.
Depending on whether we have one or more figures, we use a
single rst call to 'image' or a horizontal list.
Parameters
----------
figure_list : list
List of strings of the figures' absolute paths.
sources_dir : str
absolute path of Sphinx documentation sources
Returns
-------
images_rst : str
rst code to embed the images in the document
"""
figure_paths = [os.path.relpath(figure_path, sources_dir)
.replace(os.sep, '/').lstrip('/')
for figure_path in figure_list]
images_rst = ""
if len(figure_paths) == 1:
figure_name = figure_paths[0]
images_rst = SINGLE_IMAGE % figure_name
elif len(figure_paths) > 1:
images_rst = HLIST_HEADER
for figure_name in figure_paths:
images_rst += HLIST_IMAGE_TEMPLATE % figure_name
return images_rst | python | def figure_rst(figure_list, sources_dir):
figure_paths = [os.path.relpath(figure_path, sources_dir)
.replace(os.sep, '/').lstrip('/')
for figure_path in figure_list]
images_rst = ""
if len(figure_paths) == 1:
figure_name = figure_paths[0]
images_rst = SINGLE_IMAGE % figure_name
elif len(figure_paths) > 1:
images_rst = HLIST_HEADER
for figure_name in figure_paths:
images_rst += HLIST_IMAGE_TEMPLATE % figure_name
return images_rst | [
"def",
"figure_rst",
"(",
"figure_list",
",",
"sources_dir",
")",
":",
"figure_paths",
"=",
"[",
"os",
".",
"path",
".",
"relpath",
"(",
"figure_path",
",",
"sources_dir",
")",
".",
"replace",
"(",
"os",
".",
"sep",
",",
"'/'",
")",
".",
"lstrip",
"(",... | Generate RST for a list of PNG filenames.
Depending on whether we have one or more figures, we use a
single rst call to 'image' or a horizontal list.
Parameters
----------
figure_list : list
List of strings of the figures' absolute paths.
sources_dir : str
absolute path of Sphinx documentation sources
Returns
-------
images_rst : str
rst code to embed the images in the document | [
"Generate",
"RST",
"for",
"a",
"list",
"of",
"PNG",
"filenames",
"."
] | b0c1f6701bf3f4cef238757e1105cf3686b5e674 | https://github.com/sphinx-gallery/sphinx-gallery/blob/b0c1f6701bf3f4cef238757e1105cf3686b5e674/sphinx_gallery/scrapers.py#L251-L282 |
230,098 | sphinx-gallery/sphinx-gallery | sphinx_gallery/scrapers.py | _reset_seaborn | def _reset_seaborn(gallery_conf, fname):
"""Reset seaborn."""
# Horrible code to 'unload' seaborn, so that it resets
# its default when is load
# Python does not support unloading of modules
# https://bugs.python.org/issue9072
for module in list(sys.modules.keys()):
if 'seaborn' in module:
del sys.modules[module] | python | def _reset_seaborn(gallery_conf, fname):
# Horrible code to 'unload' seaborn, so that it resets
# its default when is load
# Python does not support unloading of modules
# https://bugs.python.org/issue9072
for module in list(sys.modules.keys()):
if 'seaborn' in module:
del sys.modules[module] | [
"def",
"_reset_seaborn",
"(",
"gallery_conf",
",",
"fname",
")",
":",
"# Horrible code to 'unload' seaborn, so that it resets",
"# its default when is load",
"# Python does not support unloading of modules",
"# https://bugs.python.org/issue9072",
"for",
"module",
"in",
"list",
"(",
... | Reset seaborn. | [
"Reset",
"seaborn",
"."
] | b0c1f6701bf3f4cef238757e1105cf3686b5e674 | https://github.com/sphinx-gallery/sphinx-gallery/blob/b0c1f6701bf3f4cef238757e1105cf3686b5e674/sphinx_gallery/scrapers.py#L315-L323 |
230,099 | sphinx-gallery/sphinx-gallery | sphinx_gallery/downloads.py | python_zip | def python_zip(file_list, gallery_path, extension='.py'):
"""Stores all files in file_list into an zip file
Parameters
----------
file_list : list
Holds all the file names to be included in zip file
gallery_path : str
path to where the zipfile is stored
extension : str
'.py' or '.ipynb' In order to deal with downloads of python
sources and jupyter notebooks the file extension from files in
file_list will be removed and replace with the value of this
variable while generating the zip file
Returns
-------
zipname : str
zip file name, written as `target_dir_{python,jupyter}.zip`
depending on the extension
"""
zipname = os.path.basename(os.path.normpath(gallery_path))
zipname += '_python' if extension == '.py' else '_jupyter'
zipname = os.path.join(gallery_path, zipname + '.zip')
zipname_new = zipname + '.new'
with zipfile.ZipFile(zipname_new, mode='w') as zipf:
for fname in file_list:
file_src = os.path.splitext(fname)[0] + extension
zipf.write(file_src, os.path.relpath(file_src, gallery_path))
_replace_md5(zipname_new)
return zipname | python | def python_zip(file_list, gallery_path, extension='.py'):
zipname = os.path.basename(os.path.normpath(gallery_path))
zipname += '_python' if extension == '.py' else '_jupyter'
zipname = os.path.join(gallery_path, zipname + '.zip')
zipname_new = zipname + '.new'
with zipfile.ZipFile(zipname_new, mode='w') as zipf:
for fname in file_list:
file_src = os.path.splitext(fname)[0] + extension
zipf.write(file_src, os.path.relpath(file_src, gallery_path))
_replace_md5(zipname_new)
return zipname | [
"def",
"python_zip",
"(",
"file_list",
",",
"gallery_path",
",",
"extension",
"=",
"'.py'",
")",
":",
"zipname",
"=",
"os",
".",
"path",
".",
"basename",
"(",
"os",
".",
"path",
".",
"normpath",
"(",
"gallery_path",
")",
")",
"zipname",
"+=",
"'_python'"... | Stores all files in file_list into an zip file
Parameters
----------
file_list : list
Holds all the file names to be included in zip file
gallery_path : str
path to where the zipfile is stored
extension : str
'.py' or '.ipynb' In order to deal with downloads of python
sources and jupyter notebooks the file extension from files in
file_list will be removed and replace with the value of this
variable while generating the zip file
Returns
-------
zipname : str
zip file name, written as `target_dir_{python,jupyter}.zip`
depending on the extension | [
"Stores",
"all",
"files",
"in",
"file_list",
"into",
"an",
"zip",
"file"
] | b0c1f6701bf3f4cef238757e1105cf3686b5e674 | https://github.com/sphinx-gallery/sphinx-gallery/blob/b0c1f6701bf3f4cef238757e1105cf3686b5e674/sphinx_gallery/downloads.py#L49-L78 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.