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 75
19.8k
| code_tokens
list | docstring
stringlengths 3
17.3k
| docstring_tokens
list | sha
stringlengths 40
40
| url
stringlengths 87
242
| partition
stringclasses 1
value |
|---|---|---|---|---|---|---|---|---|---|---|---|
mcs07/ChemDataExtractor
|
chemdataextractor/nlp/tag.py
|
ApTagger.save
|
def save(self, f):
"""Save pickled model to file."""
return pickle.dump((self.perceptron.weights, self.tagdict, self.classes, self.clusters), f, protocol=pickle.HIGHEST_PROTOCOL)
|
python
|
def save(self, f):
"""Save pickled model to file."""
return pickle.dump((self.perceptron.weights, self.tagdict, self.classes, self.clusters), f, protocol=pickle.HIGHEST_PROTOCOL)
|
[
"def",
"save",
"(",
"self",
",",
"f",
")",
":",
"return",
"pickle",
".",
"dump",
"(",
"(",
"self",
".",
"perceptron",
".",
"weights",
",",
"self",
".",
"tagdict",
",",
"self",
".",
"classes",
",",
"self",
".",
"clusters",
")",
",",
"f",
",",
"protocol",
"=",
"pickle",
".",
"HIGHEST_PROTOCOL",
")"
] |
Save pickled model to file.
|
[
"Save",
"pickled",
"model",
"to",
"file",
"."
] |
349a3bea965f2073141d62043b89319222e46af1
|
https://github.com/mcs07/ChemDataExtractor/blob/349a3bea965f2073141d62043b89319222e46af1/chemdataextractor/nlp/tag.py#L263-L265
|
train
|
mcs07/ChemDataExtractor
|
chemdataextractor/nlp/tag.py
|
ApTagger.load
|
def load(self, model):
"""Load pickled model."""
self.perceptron.weights, self.tagdict, self.classes, self.clusters = load_model(model)
self.perceptron.classes = self.classes
|
python
|
def load(self, model):
"""Load pickled model."""
self.perceptron.weights, self.tagdict, self.classes, self.clusters = load_model(model)
self.perceptron.classes = self.classes
|
[
"def",
"load",
"(",
"self",
",",
"model",
")",
":",
"self",
".",
"perceptron",
".",
"weights",
",",
"self",
".",
"tagdict",
",",
"self",
".",
"classes",
",",
"self",
".",
"clusters",
"=",
"load_model",
"(",
"model",
")",
"self",
".",
"perceptron",
".",
"classes",
"=",
"self",
".",
"classes"
] |
Load pickled model.
|
[
"Load",
"pickled",
"model",
"."
] |
349a3bea965f2073141d62043b89319222e46af1
|
https://github.com/mcs07/ChemDataExtractor/blob/349a3bea965f2073141d62043b89319222e46af1/chemdataextractor/nlp/tag.py#L267-L270
|
train
|
mcs07/ChemDataExtractor
|
chemdataextractor/nlp/tag.py
|
CrfTagger.train
|
def train(self, sentences, model):
"""Train the CRF tagger using CRFSuite.
:params sentences: Annotated sentences.
:params model: Path to save pickled model.
"""
trainer = pycrfsuite.Trainer(verbose=True)
trainer.set_params(self.params)
for sentence in sentences:
tokens, labels = zip(*sentence)
features = [self._get_features(tokens, i) for i in range(len(tokens))]
trainer.append(features, labels)
trainer.train(model)
self.load(model)
|
python
|
def train(self, sentences, model):
"""Train the CRF tagger using CRFSuite.
:params sentences: Annotated sentences.
:params model: Path to save pickled model.
"""
trainer = pycrfsuite.Trainer(verbose=True)
trainer.set_params(self.params)
for sentence in sentences:
tokens, labels = zip(*sentence)
features = [self._get_features(tokens, i) for i in range(len(tokens))]
trainer.append(features, labels)
trainer.train(model)
self.load(model)
|
[
"def",
"train",
"(",
"self",
",",
"sentences",
",",
"model",
")",
":",
"trainer",
"=",
"pycrfsuite",
".",
"Trainer",
"(",
"verbose",
"=",
"True",
")",
"trainer",
".",
"set_params",
"(",
"self",
".",
"params",
")",
"for",
"sentence",
"in",
"sentences",
":",
"tokens",
",",
"labels",
"=",
"zip",
"(",
"*",
"sentence",
")",
"features",
"=",
"[",
"self",
".",
"_get_features",
"(",
"tokens",
",",
"i",
")",
"for",
"i",
"in",
"range",
"(",
"len",
"(",
"tokens",
")",
")",
"]",
"trainer",
".",
"append",
"(",
"features",
",",
"labels",
")",
"trainer",
".",
"train",
"(",
"model",
")",
"self",
".",
"load",
"(",
"model",
")"
] |
Train the CRF tagger using CRFSuite.
:params sentences: Annotated sentences.
:params model: Path to save pickled model.
|
[
"Train",
"the",
"CRF",
"tagger",
"using",
"CRFSuite",
"."
] |
349a3bea965f2073141d62043b89319222e46af1
|
https://github.com/mcs07/ChemDataExtractor/blob/349a3bea965f2073141d62043b89319222e46af1/chemdataextractor/nlp/tag.py#L335-L348
|
train
|
mcs07/ChemDataExtractor
|
chemdataextractor/nlp/tag.py
|
DictionaryTagger.load
|
def load(self, model):
"""Load pickled DAWG from disk."""
self._dawg.load(find_data(model))
self._loaded_model = True
|
python
|
def load(self, model):
"""Load pickled DAWG from disk."""
self._dawg.load(find_data(model))
self._loaded_model = True
|
[
"def",
"load",
"(",
"self",
",",
"model",
")",
":",
"self",
".",
"_dawg",
".",
"load",
"(",
"find_data",
"(",
"model",
")",
")",
"self",
".",
"_loaded_model",
"=",
"True"
] |
Load pickled DAWG from disk.
|
[
"Load",
"pickled",
"DAWG",
"from",
"disk",
"."
] |
349a3bea965f2073141d62043b89319222e46af1
|
https://github.com/mcs07/ChemDataExtractor/blob/349a3bea965f2073141d62043b89319222e46af1/chemdataextractor/nlp/tag.py#L379-L382
|
train
|
mcs07/ChemDataExtractor
|
chemdataextractor/nlp/tag.py
|
DictionaryTagger.build
|
def build(self, words):
"""Construct dictionary DAWG from tokenized words."""
words = [self._normalize(tokens) for tokens in words]
self._dawg = dawg.CompletionDAWG(words)
self._loaded_model = True
|
python
|
def build(self, words):
"""Construct dictionary DAWG from tokenized words."""
words = [self._normalize(tokens) for tokens in words]
self._dawg = dawg.CompletionDAWG(words)
self._loaded_model = True
|
[
"def",
"build",
"(",
"self",
",",
"words",
")",
":",
"words",
"=",
"[",
"self",
".",
"_normalize",
"(",
"tokens",
")",
"for",
"tokens",
"in",
"words",
"]",
"self",
".",
"_dawg",
"=",
"dawg",
".",
"CompletionDAWG",
"(",
"words",
")",
"self",
".",
"_loaded_model",
"=",
"True"
] |
Construct dictionary DAWG from tokenized words.
|
[
"Construct",
"dictionary",
"DAWG",
"from",
"tokenized",
"words",
"."
] |
349a3bea965f2073141d62043b89319222e46af1
|
https://github.com/mcs07/ChemDataExtractor/blob/349a3bea965f2073141d62043b89319222e46af1/chemdataextractor/nlp/tag.py#L388-L392
|
train
|
mcs07/ChemDataExtractor
|
chemdataextractor/nlp/tag.py
|
DictionaryTagger._normalize
|
def _normalize(self, tokens):
"""Normalization transform to apply to both dictionary words and input tokens."""
if self.case_sensitive:
return ' '.join(self.lexicon[t].normalized for t in tokens)
else:
return ' '.join(self.lexicon[t].lower for t in tokens)
|
python
|
def _normalize(self, tokens):
"""Normalization transform to apply to both dictionary words and input tokens."""
if self.case_sensitive:
return ' '.join(self.lexicon[t].normalized for t in tokens)
else:
return ' '.join(self.lexicon[t].lower for t in tokens)
|
[
"def",
"_normalize",
"(",
"self",
",",
"tokens",
")",
":",
"if",
"self",
".",
"case_sensitive",
":",
"return",
"' '",
".",
"join",
"(",
"self",
".",
"lexicon",
"[",
"t",
"]",
".",
"normalized",
"for",
"t",
"in",
"tokens",
")",
"else",
":",
"return",
"' '",
".",
"join",
"(",
"self",
".",
"lexicon",
"[",
"t",
"]",
".",
"lower",
"for",
"t",
"in",
"tokens",
")"
] |
Normalization transform to apply to both dictionary words and input tokens.
|
[
"Normalization",
"transform",
"to",
"apply",
"to",
"both",
"dictionary",
"words",
"and",
"input",
"tokens",
"."
] |
349a3bea965f2073141d62043b89319222e46af1
|
https://github.com/mcs07/ChemDataExtractor/blob/349a3bea965f2073141d62043b89319222e46af1/chemdataextractor/nlp/tag.py#L394-L399
|
train
|
mcs07/ChemDataExtractor
|
chemdataextractor/parse/cem.py
|
standardize_role
|
def standardize_role(role):
"""Convert role text into standardized form."""
role = role.lower()
if any(c in role for c in {'synthesis', 'give', 'yield', 'afford', 'product', 'preparation of'}):
return 'product'
return role
|
python
|
def standardize_role(role):
"""Convert role text into standardized form."""
role = role.lower()
if any(c in role for c in {'synthesis', 'give', 'yield', 'afford', 'product', 'preparation of'}):
return 'product'
return role
|
[
"def",
"standardize_role",
"(",
"role",
")",
":",
"role",
"=",
"role",
".",
"lower",
"(",
")",
"if",
"any",
"(",
"c",
"in",
"role",
"for",
"c",
"in",
"{",
"'synthesis'",
",",
"'give'",
",",
"'yield'",
",",
"'afford'",
",",
"'product'",
",",
"'preparation of'",
"}",
")",
":",
"return",
"'product'",
"return",
"role"
] |
Convert role text into standardized form.
|
[
"Convert",
"role",
"text",
"into",
"standardized",
"form",
"."
] |
349a3bea965f2073141d62043b89319222e46af1
|
https://github.com/mcs07/ChemDataExtractor/blob/349a3bea965f2073141d62043b89319222e46af1/chemdataextractor/parse/cem.py#L279-L284
|
train
|
mcs07/ChemDataExtractor
|
chemdataextractor/cli/data.py
|
list
|
def list(ctx):
"""List active data packages."""
log.debug('chemdataextractor.data.list')
click.echo('Downloaded\tPackage')
for package in PACKAGES:
click.echo('%s\t%s' % (package.local_exists(), package.path))
|
python
|
def list(ctx):
"""List active data packages."""
log.debug('chemdataextractor.data.list')
click.echo('Downloaded\tPackage')
for package in PACKAGES:
click.echo('%s\t%s' % (package.local_exists(), package.path))
|
[
"def",
"list",
"(",
"ctx",
")",
":",
"log",
".",
"debug",
"(",
"'chemdataextractor.data.list'",
")",
"click",
".",
"echo",
"(",
"'Downloaded\\tPackage'",
")",
"for",
"package",
"in",
"PACKAGES",
":",
"click",
".",
"echo",
"(",
"'%s\\t%s'",
"%",
"(",
"package",
".",
"local_exists",
"(",
")",
",",
"package",
".",
"path",
")",
")"
] |
List active data packages.
|
[
"List",
"active",
"data",
"packages",
"."
] |
349a3bea965f2073141d62043b89319222e46af1
|
https://github.com/mcs07/ChemDataExtractor/blob/349a3bea965f2073141d62043b89319222e46af1/chemdataextractor/cli/data.py#L40-L45
|
train
|
mcs07/ChemDataExtractor
|
chemdataextractor/cli/data.py
|
download
|
def download(ctx):
"""Download data."""
log.debug('chemdataextractor.data.download')
count = 0
for package in PACKAGES:
success = package.download()
if success:
count += 1
click.echo('Successfully downloaded %s new data packages (%s existing)' % (count, len(PACKAGES) - count))
|
python
|
def download(ctx):
"""Download data."""
log.debug('chemdataextractor.data.download')
count = 0
for package in PACKAGES:
success = package.download()
if success:
count += 1
click.echo('Successfully downloaded %s new data packages (%s existing)' % (count, len(PACKAGES) - count))
|
[
"def",
"download",
"(",
"ctx",
")",
":",
"log",
".",
"debug",
"(",
"'chemdataextractor.data.download'",
")",
"count",
"=",
"0",
"for",
"package",
"in",
"PACKAGES",
":",
"success",
"=",
"package",
".",
"download",
"(",
")",
"if",
"success",
":",
"count",
"+=",
"1",
"click",
".",
"echo",
"(",
"'Successfully downloaded %s new data packages (%s existing)'",
"%",
"(",
"count",
",",
"len",
"(",
"PACKAGES",
")",
"-",
"count",
")",
")"
] |
Download data.
|
[
"Download",
"data",
"."
] |
349a3bea965f2073141d62043b89319222e46af1
|
https://github.com/mcs07/ChemDataExtractor/blob/349a3bea965f2073141d62043b89319222e46af1/chemdataextractor/cli/data.py#L50-L58
|
train
|
mcs07/ChemDataExtractor
|
chemdataextractor/data.py
|
find_data
|
def find_data(path, warn=True):
"""Return the absolute path to a data file within the data directory."""
full_path = os.path.join(get_data_dir(), path)
if warn and not os.path.isfile(full_path):
for package in PACKAGES:
if path == package.path:
log.warn('%s doesn\'t exist. Run `cde data download` to get it.' % path)
break
return full_path
|
python
|
def find_data(path, warn=True):
"""Return the absolute path to a data file within the data directory."""
full_path = os.path.join(get_data_dir(), path)
if warn and not os.path.isfile(full_path):
for package in PACKAGES:
if path == package.path:
log.warn('%s doesn\'t exist. Run `cde data download` to get it.' % path)
break
return full_path
|
[
"def",
"find_data",
"(",
"path",
",",
"warn",
"=",
"True",
")",
":",
"full_path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"get_data_dir",
"(",
")",
",",
"path",
")",
"if",
"warn",
"and",
"not",
"os",
".",
"path",
".",
"isfile",
"(",
"full_path",
")",
":",
"for",
"package",
"in",
"PACKAGES",
":",
"if",
"path",
"==",
"package",
".",
"path",
":",
"log",
".",
"warn",
"(",
"'%s doesn\\'t exist. Run `cde data download` to get it.'",
"%",
"path",
")",
"break",
"return",
"full_path"
] |
Return the absolute path to a data file within the data directory.
|
[
"Return",
"the",
"absolute",
"path",
"to",
"a",
"data",
"file",
"within",
"the",
"data",
"directory",
"."
] |
349a3bea965f2073141d62043b89319222e46af1
|
https://github.com/mcs07/ChemDataExtractor/blob/349a3bea965f2073141d62043b89319222e46af1/chemdataextractor/data.py#L119-L127
|
train
|
mcs07/ChemDataExtractor
|
chemdataextractor/data.py
|
load_model
|
def load_model(path):
"""Load a model from a pickle file in the data directory. Cached so model is only loaded once."""
abspath = find_data(path)
cached = _model_cache.get(abspath)
if cached is not None:
log.debug('Using cached copy of %s' % path)
return cached
log.debug('Loading model %s' % path)
try:
with io.open(abspath, 'rb') as f:
model = six.moves.cPickle.load(f)
except IOError:
raise ModelNotFoundError('Could not load %s. Have you run `cde data download`?' % path)
_model_cache[abspath] = model
return model
|
python
|
def load_model(path):
"""Load a model from a pickle file in the data directory. Cached so model is only loaded once."""
abspath = find_data(path)
cached = _model_cache.get(abspath)
if cached is not None:
log.debug('Using cached copy of %s' % path)
return cached
log.debug('Loading model %s' % path)
try:
with io.open(abspath, 'rb') as f:
model = six.moves.cPickle.load(f)
except IOError:
raise ModelNotFoundError('Could not load %s. Have you run `cde data download`?' % path)
_model_cache[abspath] = model
return model
|
[
"def",
"load_model",
"(",
"path",
")",
":",
"abspath",
"=",
"find_data",
"(",
"path",
")",
"cached",
"=",
"_model_cache",
".",
"get",
"(",
"abspath",
")",
"if",
"cached",
"is",
"not",
"None",
":",
"log",
".",
"debug",
"(",
"'Using cached copy of %s'",
"%",
"path",
")",
"return",
"cached",
"log",
".",
"debug",
"(",
"'Loading model %s'",
"%",
"path",
")",
"try",
":",
"with",
"io",
".",
"open",
"(",
"abspath",
",",
"'rb'",
")",
"as",
"f",
":",
"model",
"=",
"six",
".",
"moves",
".",
"cPickle",
".",
"load",
"(",
"f",
")",
"except",
"IOError",
":",
"raise",
"ModelNotFoundError",
"(",
"'Could not load %s. Have you run `cde data download`?'",
"%",
"path",
")",
"_model_cache",
"[",
"abspath",
"]",
"=",
"model",
"return",
"model"
] |
Load a model from a pickle file in the data directory. Cached so model is only loaded once.
|
[
"Load",
"a",
"model",
"from",
"a",
"pickle",
"file",
"in",
"the",
"data",
"directory",
".",
"Cached",
"so",
"model",
"is",
"only",
"loaded",
"once",
"."
] |
349a3bea965f2073141d62043b89319222e46af1
|
https://github.com/mcs07/ChemDataExtractor/blob/349a3bea965f2073141d62043b89319222e46af1/chemdataextractor/data.py#L134-L148
|
train
|
mcs07/ChemDataExtractor
|
chemdataextractor/text/normalize.py
|
ChemNormalizer.normalize
|
def normalize(self, text):
"""Normalize unicode, hyphens, whitespace, and some chemistry terms and formatting."""
text = super(ChemNormalizer, self).normalize(text)
# Normalize element spelling
if self.chem_spell:
text = re.sub(r'sulph', r'sulf', text, flags=re.I)
text = re.sub(r'aluminum', r'aluminium', text, flags=re.I)
text = re.sub(r'cesium', r'caesium', text, flags=re.I)
return text
|
python
|
def normalize(self, text):
"""Normalize unicode, hyphens, whitespace, and some chemistry terms and formatting."""
text = super(ChemNormalizer, self).normalize(text)
# Normalize element spelling
if self.chem_spell:
text = re.sub(r'sulph', r'sulf', text, flags=re.I)
text = re.sub(r'aluminum', r'aluminium', text, flags=re.I)
text = re.sub(r'cesium', r'caesium', text, flags=re.I)
return text
|
[
"def",
"normalize",
"(",
"self",
",",
"text",
")",
":",
"text",
"=",
"super",
"(",
"ChemNormalizer",
",",
"self",
")",
".",
"normalize",
"(",
"text",
")",
"# Normalize element spelling",
"if",
"self",
".",
"chem_spell",
":",
"text",
"=",
"re",
".",
"sub",
"(",
"r'sulph'",
",",
"r'sulf'",
",",
"text",
",",
"flags",
"=",
"re",
".",
"I",
")",
"text",
"=",
"re",
".",
"sub",
"(",
"r'aluminum'",
",",
"r'aluminium'",
",",
"text",
",",
"flags",
"=",
"re",
".",
"I",
")",
"text",
"=",
"re",
".",
"sub",
"(",
"r'cesium'",
",",
"r'caesium'",
",",
"text",
",",
"flags",
"=",
"re",
".",
"I",
")",
"return",
"text"
] |
Normalize unicode, hyphens, whitespace, and some chemistry terms and formatting.
|
[
"Normalize",
"unicode",
"hyphens",
"whitespace",
"and",
"some",
"chemistry",
"terms",
"and",
"formatting",
"."
] |
349a3bea965f2073141d62043b89319222e46af1
|
https://github.com/mcs07/ChemDataExtractor/blob/349a3bea965f2073141d62043b89319222e46af1/chemdataextractor/text/normalize.py#L181-L189
|
train
|
mcs07/ChemDataExtractor
|
chemdataextractor/nlp/lexicon.py
|
Lexicon.add
|
def add(self, text):
"""Add text to the lexicon.
:param string text: The text to add.
"""
# logging.debug('Adding to lexicon: %s' % text)
if text not in self.lexemes:
normalized = self.normalized(text)
self.lexemes[text] = Lexeme(
text=text,
normalized=normalized,
lower=self.lower(normalized),
first=self.first(normalized),
suffix=self.suffix(normalized),
shape=self.shape(normalized),
length=self.length(normalized),
upper_count=self.upper_count(normalized),
lower_count=self.lower_count(normalized),
digit_count=self.digit_count(normalized),
is_alpha=self.is_alpha(normalized),
is_ascii=self.is_ascii(normalized),
is_digit=self.is_digit(normalized),
is_lower=self.is_lower(normalized),
is_upper=self.is_upper(normalized),
is_title=self.is_title(normalized),
is_punct=self.is_punct(normalized),
is_hyphenated=self.is_hyphenated(normalized),
like_url=self.like_url(normalized),
like_number=self.like_number(normalized),
cluster=self.cluster(normalized)
)
|
python
|
def add(self, text):
"""Add text to the lexicon.
:param string text: The text to add.
"""
# logging.debug('Adding to lexicon: %s' % text)
if text not in self.lexemes:
normalized = self.normalized(text)
self.lexemes[text] = Lexeme(
text=text,
normalized=normalized,
lower=self.lower(normalized),
first=self.first(normalized),
suffix=self.suffix(normalized),
shape=self.shape(normalized),
length=self.length(normalized),
upper_count=self.upper_count(normalized),
lower_count=self.lower_count(normalized),
digit_count=self.digit_count(normalized),
is_alpha=self.is_alpha(normalized),
is_ascii=self.is_ascii(normalized),
is_digit=self.is_digit(normalized),
is_lower=self.is_lower(normalized),
is_upper=self.is_upper(normalized),
is_title=self.is_title(normalized),
is_punct=self.is_punct(normalized),
is_hyphenated=self.is_hyphenated(normalized),
like_url=self.like_url(normalized),
like_number=self.like_number(normalized),
cluster=self.cluster(normalized)
)
|
[
"def",
"add",
"(",
"self",
",",
"text",
")",
":",
"# logging.debug('Adding to lexicon: %s' % text)",
"if",
"text",
"not",
"in",
"self",
".",
"lexemes",
":",
"normalized",
"=",
"self",
".",
"normalized",
"(",
"text",
")",
"self",
".",
"lexemes",
"[",
"text",
"]",
"=",
"Lexeme",
"(",
"text",
"=",
"text",
",",
"normalized",
"=",
"normalized",
",",
"lower",
"=",
"self",
".",
"lower",
"(",
"normalized",
")",
",",
"first",
"=",
"self",
".",
"first",
"(",
"normalized",
")",
",",
"suffix",
"=",
"self",
".",
"suffix",
"(",
"normalized",
")",
",",
"shape",
"=",
"self",
".",
"shape",
"(",
"normalized",
")",
",",
"length",
"=",
"self",
".",
"length",
"(",
"normalized",
")",
",",
"upper_count",
"=",
"self",
".",
"upper_count",
"(",
"normalized",
")",
",",
"lower_count",
"=",
"self",
".",
"lower_count",
"(",
"normalized",
")",
",",
"digit_count",
"=",
"self",
".",
"digit_count",
"(",
"normalized",
")",
",",
"is_alpha",
"=",
"self",
".",
"is_alpha",
"(",
"normalized",
")",
",",
"is_ascii",
"=",
"self",
".",
"is_ascii",
"(",
"normalized",
")",
",",
"is_digit",
"=",
"self",
".",
"is_digit",
"(",
"normalized",
")",
",",
"is_lower",
"=",
"self",
".",
"is_lower",
"(",
"normalized",
")",
",",
"is_upper",
"=",
"self",
".",
"is_upper",
"(",
"normalized",
")",
",",
"is_title",
"=",
"self",
".",
"is_title",
"(",
"normalized",
")",
",",
"is_punct",
"=",
"self",
".",
"is_punct",
"(",
"normalized",
")",
",",
"is_hyphenated",
"=",
"self",
".",
"is_hyphenated",
"(",
"normalized",
")",
",",
"like_url",
"=",
"self",
".",
"like_url",
"(",
"normalized",
")",
",",
"like_number",
"=",
"self",
".",
"like_number",
"(",
"normalized",
")",
",",
"cluster",
"=",
"self",
".",
"cluster",
"(",
"normalized",
")",
")"
] |
Add text to the lexicon.
:param string text: The text to add.
|
[
"Add",
"text",
"to",
"the",
"lexicon",
"."
] |
349a3bea965f2073141d62043b89319222e46af1
|
https://github.com/mcs07/ChemDataExtractor/blob/349a3bea965f2073141d62043b89319222e46af1/chemdataextractor/nlp/lexicon.py#L99-L129
|
train
|
mcs07/ChemDataExtractor
|
chemdataextractor/doc/table.py
|
Table.serialize
|
def serialize(self):
"""Convert Table element to python dictionary."""
data = {
'type': self.__class__.__name__,
'caption': self.caption.serialize(),
'headings': [[cell.serialize() for cell in hrow] for hrow in self.headings],
'rows': [[cell.serialize() for cell in row] for row in self.rows],
}
return data
|
python
|
def serialize(self):
"""Convert Table element to python dictionary."""
data = {
'type': self.__class__.__name__,
'caption': self.caption.serialize(),
'headings': [[cell.serialize() for cell in hrow] for hrow in self.headings],
'rows': [[cell.serialize() for cell in row] for row in self.rows],
}
return data
|
[
"def",
"serialize",
"(",
"self",
")",
":",
"data",
"=",
"{",
"'type'",
":",
"self",
".",
"__class__",
".",
"__name__",
",",
"'caption'",
":",
"self",
".",
"caption",
".",
"serialize",
"(",
")",
",",
"'headings'",
":",
"[",
"[",
"cell",
".",
"serialize",
"(",
")",
"for",
"cell",
"in",
"hrow",
"]",
"for",
"hrow",
"in",
"self",
".",
"headings",
"]",
",",
"'rows'",
":",
"[",
"[",
"cell",
".",
"serialize",
"(",
")",
"for",
"cell",
"in",
"row",
"]",
"for",
"row",
"in",
"self",
".",
"rows",
"]",
",",
"}",
"return",
"data"
] |
Convert Table element to python dictionary.
|
[
"Convert",
"Table",
"element",
"to",
"python",
"dictionary",
"."
] |
349a3bea965f2073141d62043b89319222e46af1
|
https://github.com/mcs07/ChemDataExtractor/blob/349a3bea965f2073141d62043b89319222e46af1/chemdataextractor/doc/table.py#L78-L86
|
train
|
mcs07/ChemDataExtractor
|
chemdataextractor/model.py
|
Compound.merge
|
def merge(self, other):
"""Merge data from another Compound into this Compound."""
log.debug('Merging: %s and %s' % (self.serialize(), other.serialize()))
for k in self.keys():
for new_item in other[k]:
if new_item not in self[k]:
self[k].append(new_item)
log.debug('Result: %s' % self.serialize())
return self
|
python
|
def merge(self, other):
"""Merge data from another Compound into this Compound."""
log.debug('Merging: %s and %s' % (self.serialize(), other.serialize()))
for k in self.keys():
for new_item in other[k]:
if new_item not in self[k]:
self[k].append(new_item)
log.debug('Result: %s' % self.serialize())
return self
|
[
"def",
"merge",
"(",
"self",
",",
"other",
")",
":",
"log",
".",
"debug",
"(",
"'Merging: %s and %s'",
"%",
"(",
"self",
".",
"serialize",
"(",
")",
",",
"other",
".",
"serialize",
"(",
")",
")",
")",
"for",
"k",
"in",
"self",
".",
"keys",
"(",
")",
":",
"for",
"new_item",
"in",
"other",
"[",
"k",
"]",
":",
"if",
"new_item",
"not",
"in",
"self",
"[",
"k",
"]",
":",
"self",
"[",
"k",
"]",
".",
"append",
"(",
"new_item",
")",
"log",
".",
"debug",
"(",
"'Result: %s'",
"%",
"self",
".",
"serialize",
"(",
")",
")",
"return",
"self"
] |
Merge data from another Compound into this Compound.
|
[
"Merge",
"data",
"from",
"another",
"Compound",
"into",
"this",
"Compound",
"."
] |
349a3bea965f2073141d62043b89319222e46af1
|
https://github.com/mcs07/ChemDataExtractor/blob/349a3bea965f2073141d62043b89319222e46af1/chemdataextractor/model.py#L451-L459
|
train
|
mcs07/ChemDataExtractor
|
chemdataextractor/model.py
|
Compound.merge_contextual
|
def merge_contextual(self, other):
"""Merge in contextual info from a template Compound."""
# TODO: This is currently dependent on our data model? Make more robust to schema changes
# Currently we assume all lists at Compound level, with 1 further potential nested level of lists
for k in self.keys():
# print('key: %s' % k)
for item in self[k]:
# print('item: %s' % item)
for other_item in other.get(k, []):
# Skip text properties (don't merge names, labels, roles)
if isinstance(other_item, six.text_type):
continue
for otherk in other_item.keys():
if isinstance(other_item[otherk], list):
if len(other_item[otherk]) > 0 and len(item[otherk]) > 0:
other_nested_item = other_item[otherk][0]
for othernestedk in other_nested_item.keys():
for nested_item in item[otherk]:
if not nested_item[othernestedk]:
nested_item[othernestedk] = other_nested_item[othernestedk]
elif not item[otherk]:
item[otherk] = other_item[otherk]
log.debug('Result: %s' % self.serialize())
return self
|
python
|
def merge_contextual(self, other):
"""Merge in contextual info from a template Compound."""
# TODO: This is currently dependent on our data model? Make more robust to schema changes
# Currently we assume all lists at Compound level, with 1 further potential nested level of lists
for k in self.keys():
# print('key: %s' % k)
for item in self[k]:
# print('item: %s' % item)
for other_item in other.get(k, []):
# Skip text properties (don't merge names, labels, roles)
if isinstance(other_item, six.text_type):
continue
for otherk in other_item.keys():
if isinstance(other_item[otherk], list):
if len(other_item[otherk]) > 0 and len(item[otherk]) > 0:
other_nested_item = other_item[otherk][0]
for othernestedk in other_nested_item.keys():
for nested_item in item[otherk]:
if not nested_item[othernestedk]:
nested_item[othernestedk] = other_nested_item[othernestedk]
elif not item[otherk]:
item[otherk] = other_item[otherk]
log.debug('Result: %s' % self.serialize())
return self
|
[
"def",
"merge_contextual",
"(",
"self",
",",
"other",
")",
":",
"# TODO: This is currently dependent on our data model? Make more robust to schema changes",
"# Currently we assume all lists at Compound level, with 1 further potential nested level of lists",
"for",
"k",
"in",
"self",
".",
"keys",
"(",
")",
":",
"# print('key: %s' % k)",
"for",
"item",
"in",
"self",
"[",
"k",
"]",
":",
"# print('item: %s' % item)",
"for",
"other_item",
"in",
"other",
".",
"get",
"(",
"k",
",",
"[",
"]",
")",
":",
"# Skip text properties (don't merge names, labels, roles)",
"if",
"isinstance",
"(",
"other_item",
",",
"six",
".",
"text_type",
")",
":",
"continue",
"for",
"otherk",
"in",
"other_item",
".",
"keys",
"(",
")",
":",
"if",
"isinstance",
"(",
"other_item",
"[",
"otherk",
"]",
",",
"list",
")",
":",
"if",
"len",
"(",
"other_item",
"[",
"otherk",
"]",
")",
">",
"0",
"and",
"len",
"(",
"item",
"[",
"otherk",
"]",
")",
">",
"0",
":",
"other_nested_item",
"=",
"other_item",
"[",
"otherk",
"]",
"[",
"0",
"]",
"for",
"othernestedk",
"in",
"other_nested_item",
".",
"keys",
"(",
")",
":",
"for",
"nested_item",
"in",
"item",
"[",
"otherk",
"]",
":",
"if",
"not",
"nested_item",
"[",
"othernestedk",
"]",
":",
"nested_item",
"[",
"othernestedk",
"]",
"=",
"other_nested_item",
"[",
"othernestedk",
"]",
"elif",
"not",
"item",
"[",
"otherk",
"]",
":",
"item",
"[",
"otherk",
"]",
"=",
"other_item",
"[",
"otherk",
"]",
"log",
".",
"debug",
"(",
"'Result: %s'",
"%",
"self",
".",
"serialize",
"(",
")",
")",
"return",
"self"
] |
Merge in contextual info from a template Compound.
|
[
"Merge",
"in",
"contextual",
"info",
"from",
"a",
"template",
"Compound",
"."
] |
349a3bea965f2073141d62043b89319222e46af1
|
https://github.com/mcs07/ChemDataExtractor/blob/349a3bea965f2073141d62043b89319222e46af1/chemdataextractor/model.py#L461-L484
|
train
|
mcs07/ChemDataExtractor
|
chemdataextractor/model.py
|
Compound.is_id_only
|
def is_id_only(self):
"""Return True if identifier information only."""
for key, value in self.items():
if key not in {'names', 'labels', 'roles'} and value:
return False
if self.names or self.labels:
return True
return False
|
python
|
def is_id_only(self):
"""Return True if identifier information only."""
for key, value in self.items():
if key not in {'names', 'labels', 'roles'} and value:
return False
if self.names or self.labels:
return True
return False
|
[
"def",
"is_id_only",
"(",
"self",
")",
":",
"for",
"key",
",",
"value",
"in",
"self",
".",
"items",
"(",
")",
":",
"if",
"key",
"not",
"in",
"{",
"'names'",
",",
"'labels'",
",",
"'roles'",
"}",
"and",
"value",
":",
"return",
"False",
"if",
"self",
".",
"names",
"or",
"self",
".",
"labels",
":",
"return",
"True",
"return",
"False"
] |
Return True if identifier information only.
|
[
"Return",
"True",
"if",
"identifier",
"information",
"only",
"."
] |
349a3bea965f2073141d62043b89319222e46af1
|
https://github.com/mcs07/ChemDataExtractor/blob/349a3bea965f2073141d62043b89319222e46af1/chemdataextractor/model.py#L502-L509
|
train
|
mcs07/ChemDataExtractor
|
chemdataextractor/parse/actions.py
|
join
|
def join(tokens, start, result):
"""Join tokens into a single string with spaces between."""
texts = []
if len(result) > 0:
for e in result:
for child in e.iter():
if child.text is not None:
texts.append(child.text)
return [E(result[0].tag, ' '.join(texts))]
|
python
|
def join(tokens, start, result):
"""Join tokens into a single string with spaces between."""
texts = []
if len(result) > 0:
for e in result:
for child in e.iter():
if child.text is not None:
texts.append(child.text)
return [E(result[0].tag, ' '.join(texts))]
|
[
"def",
"join",
"(",
"tokens",
",",
"start",
",",
"result",
")",
":",
"texts",
"=",
"[",
"]",
"if",
"len",
"(",
"result",
")",
">",
"0",
":",
"for",
"e",
"in",
"result",
":",
"for",
"child",
"in",
"e",
".",
"iter",
"(",
")",
":",
"if",
"child",
".",
"text",
"is",
"not",
"None",
":",
"texts",
".",
"append",
"(",
"child",
".",
"text",
")",
"return",
"[",
"E",
"(",
"result",
"[",
"0",
"]",
".",
"tag",
",",
"' '",
".",
"join",
"(",
"texts",
")",
")",
"]"
] |
Join tokens into a single string with spaces between.
|
[
"Join",
"tokens",
"into",
"a",
"single",
"string",
"with",
"spaces",
"between",
"."
] |
349a3bea965f2073141d62043b89319222e46af1
|
https://github.com/mcs07/ChemDataExtractor/blob/349a3bea965f2073141d62043b89319222e46af1/chemdataextractor/parse/actions.py#L33-L41
|
train
|
mcs07/ChemDataExtractor
|
chemdataextractor/parse/actions.py
|
strip_stop
|
def strip_stop(tokens, start, result):
"""Remove trailing full stop from tokens."""
for e in result:
for child in e.iter():
if child.text.endswith('.'):
child.text = child.text[:-1]
return result
|
python
|
def strip_stop(tokens, start, result):
"""Remove trailing full stop from tokens."""
for e in result:
for child in e.iter():
if child.text.endswith('.'):
child.text = child.text[:-1]
return result
|
[
"def",
"strip_stop",
"(",
"tokens",
",",
"start",
",",
"result",
")",
":",
"for",
"e",
"in",
"result",
":",
"for",
"child",
"in",
"e",
".",
"iter",
"(",
")",
":",
"if",
"child",
".",
"text",
".",
"endswith",
"(",
"'.'",
")",
":",
"child",
".",
"text",
"=",
"child",
".",
"text",
"[",
":",
"-",
"1",
"]",
"return",
"result"
] |
Remove trailing full stop from tokens.
|
[
"Remove",
"trailing",
"full",
"stop",
"from",
"tokens",
"."
] |
349a3bea965f2073141d62043b89319222e46af1
|
https://github.com/mcs07/ChemDataExtractor/blob/349a3bea965f2073141d62043b89319222e46af1/chemdataextractor/parse/actions.py#L55-L61
|
train
|
mcs07/ChemDataExtractor
|
chemdataextractor/parse/actions.py
|
fix_whitespace
|
def fix_whitespace(tokens, start, result):
"""Fix whitespace around hyphens and commas. Can be used to remove whitespace tokenization artefacts."""
for e in result:
for child in e.iter():
child.text = child.text.replace(' , ', ', ')
for hyphen in HYPHENS:
child.text = child.text.replace(' %s ' % hyphen, '%s' % hyphen)
child.text = re.sub(r'- (.) -', r'-\1-', child.text)
return result
|
python
|
def fix_whitespace(tokens, start, result):
"""Fix whitespace around hyphens and commas. Can be used to remove whitespace tokenization artefacts."""
for e in result:
for child in e.iter():
child.text = child.text.replace(' , ', ', ')
for hyphen in HYPHENS:
child.text = child.text.replace(' %s ' % hyphen, '%s' % hyphen)
child.text = re.sub(r'- (.) -', r'-\1-', child.text)
return result
|
[
"def",
"fix_whitespace",
"(",
"tokens",
",",
"start",
",",
"result",
")",
":",
"for",
"e",
"in",
"result",
":",
"for",
"child",
"in",
"e",
".",
"iter",
"(",
")",
":",
"child",
".",
"text",
"=",
"child",
".",
"text",
".",
"replace",
"(",
"' , '",
",",
"', '",
")",
"for",
"hyphen",
"in",
"HYPHENS",
":",
"child",
".",
"text",
"=",
"child",
".",
"text",
".",
"replace",
"(",
"' %s '",
"%",
"hyphen",
",",
"'%s'",
"%",
"hyphen",
")",
"child",
".",
"text",
"=",
"re",
".",
"sub",
"(",
"r'- (.) -'",
",",
"r'-\\1-'",
",",
"child",
".",
"text",
")",
"return",
"result"
] |
Fix whitespace around hyphens and commas. Can be used to remove whitespace tokenization artefacts.
|
[
"Fix",
"whitespace",
"around",
"hyphens",
"and",
"commas",
".",
"Can",
"be",
"used",
"to",
"remove",
"whitespace",
"tokenization",
"artefacts",
"."
] |
349a3bea965f2073141d62043b89319222e46af1
|
https://github.com/mcs07/ChemDataExtractor/blob/349a3bea965f2073141d62043b89319222e46af1/chemdataextractor/parse/actions.py#L64-L72
|
train
|
mcs07/ChemDataExtractor
|
chemdataextractor/reader/plaintext.py
|
PlainTextReader.detect
|
def detect(self, fstring, fname=None):
"""Have a stab at most files."""
if fname is not None and '.' in fname:
extension = fname.rsplit('.', 1)[1]
if extension in {'pdf', 'html', 'xml'}:
return False
return True
|
python
|
def detect(self, fstring, fname=None):
"""Have a stab at most files."""
if fname is not None and '.' in fname:
extension = fname.rsplit('.', 1)[1]
if extension in {'pdf', 'html', 'xml'}:
return False
return True
|
[
"def",
"detect",
"(",
"self",
",",
"fstring",
",",
"fname",
"=",
"None",
")",
":",
"if",
"fname",
"is",
"not",
"None",
"and",
"'.'",
"in",
"fname",
":",
"extension",
"=",
"fname",
".",
"rsplit",
"(",
"'.'",
",",
"1",
")",
"[",
"1",
"]",
"if",
"extension",
"in",
"{",
"'pdf'",
",",
"'html'",
",",
"'xml'",
"}",
":",
"return",
"False",
"return",
"True"
] |
Have a stab at most files.
|
[
"Have",
"a",
"stab",
"at",
"most",
"files",
"."
] |
349a3bea965f2073141d62043b89319222e46af1
|
https://github.com/mcs07/ChemDataExtractor/blob/349a3bea965f2073141d62043b89319222e46af1/chemdataextractor/reader/plaintext.py#L26-L32
|
train
|
mcs07/ChemDataExtractor
|
chemdataextractor/reader/pdf.py
|
PdfReader._process_layout
|
def _process_layout(self, layout):
"""Process an LTPage layout and return a list of elements."""
# Here we just group text into paragraphs
elements = []
for lt_obj in layout:
if isinstance(lt_obj, LTTextBox) or isinstance(lt_obj, LTTextLine):
elements.append(Paragraph(lt_obj.get_text().strip()))
elif isinstance(lt_obj, LTFigure):
# Recursive...
elements.extend(self._process_layout(lt_obj))
return elements
|
python
|
def _process_layout(self, layout):
"""Process an LTPage layout and return a list of elements."""
# Here we just group text into paragraphs
elements = []
for lt_obj in layout:
if isinstance(lt_obj, LTTextBox) or isinstance(lt_obj, LTTextLine):
elements.append(Paragraph(lt_obj.get_text().strip()))
elif isinstance(lt_obj, LTFigure):
# Recursive...
elements.extend(self._process_layout(lt_obj))
return elements
|
[
"def",
"_process_layout",
"(",
"self",
",",
"layout",
")",
":",
"# Here we just group text into paragraphs",
"elements",
"=",
"[",
"]",
"for",
"lt_obj",
"in",
"layout",
":",
"if",
"isinstance",
"(",
"lt_obj",
",",
"LTTextBox",
")",
"or",
"isinstance",
"(",
"lt_obj",
",",
"LTTextLine",
")",
":",
"elements",
".",
"append",
"(",
"Paragraph",
"(",
"lt_obj",
".",
"get_text",
"(",
")",
".",
"strip",
"(",
")",
")",
")",
"elif",
"isinstance",
"(",
"lt_obj",
",",
"LTFigure",
")",
":",
"# Recursive...",
"elements",
".",
"extend",
"(",
"self",
".",
"_process_layout",
"(",
"lt_obj",
")",
")",
"return",
"elements"
] |
Process an LTPage layout and return a list of elements.
|
[
"Process",
"an",
"LTPage",
"layout",
"and",
"return",
"a",
"list",
"of",
"elements",
"."
] |
349a3bea965f2073141d62043b89319222e46af1
|
https://github.com/mcs07/ChemDataExtractor/blob/349a3bea965f2073141d62043b89319222e46af1/chemdataextractor/reader/pdf.py#L38-L48
|
train
|
mcs07/ChemDataExtractor
|
chemdataextractor/text/__init__.py
|
get_encoding
|
def get_encoding(input_string, guesses=None, is_html=False):
"""Return the encoding of a byte string. Uses bs4 UnicodeDammit.
:param string input_string: Encoded byte string.
:param list[string] guesses: (Optional) List of encoding guesses to prioritize.
:param bool is_html: Whether the input is HTML.
"""
converted = UnicodeDammit(input_string, override_encodings=[guesses] if guesses else [], is_html=is_html)
return converted.original_encoding
|
python
|
def get_encoding(input_string, guesses=None, is_html=False):
"""Return the encoding of a byte string. Uses bs4 UnicodeDammit.
:param string input_string: Encoded byte string.
:param list[string] guesses: (Optional) List of encoding guesses to prioritize.
:param bool is_html: Whether the input is HTML.
"""
converted = UnicodeDammit(input_string, override_encodings=[guesses] if guesses else [], is_html=is_html)
return converted.original_encoding
|
[
"def",
"get_encoding",
"(",
"input_string",
",",
"guesses",
"=",
"None",
",",
"is_html",
"=",
"False",
")",
":",
"converted",
"=",
"UnicodeDammit",
"(",
"input_string",
",",
"override_encodings",
"=",
"[",
"guesses",
"]",
"if",
"guesses",
"else",
"[",
"]",
",",
"is_html",
"=",
"is_html",
")",
"return",
"converted",
".",
"original_encoding"
] |
Return the encoding of a byte string. Uses bs4 UnicodeDammit.
:param string input_string: Encoded byte string.
:param list[string] guesses: (Optional) List of encoding guesses to prioritize.
:param bool is_html: Whether the input is HTML.
|
[
"Return",
"the",
"encoding",
"of",
"a",
"byte",
"string",
".",
"Uses",
"bs4",
"UnicodeDammit",
"."
] |
349a3bea965f2073141d62043b89319222e46af1
|
https://github.com/mcs07/ChemDataExtractor/blob/349a3bea965f2073141d62043b89319222e46af1/chemdataextractor/text/__init__.py#L221-L229
|
train
|
mcs07/ChemDataExtractor
|
chemdataextractor/text/__init__.py
|
levenshtein
|
def levenshtein(s1, s2, allow_substring=False):
"""Return the Levenshtein distance between two strings.
The Levenshtein distance (a.k.a "edit difference") is the number of characters that need to be substituted,
inserted or deleted to transform s1 into s2.
Setting the `allow_substring` parameter to True allows s1 to be a
substring of s2, so that, for example, "hello" and "hello there" would have a distance of zero.
:param string s1: The first string
:param string s2: The second string
:param bool allow_substring: Whether to allow s1 to be a substring of s2
:returns: Levenshtein distance.
:rtype int
"""
len1, len2 = len(s1), len(s2)
lev = []
for i in range(len1 + 1):
lev.append([0] * (len2 + 1))
for i in range(len1 + 1):
lev[i][0] = i
for j in range(len2 + 1):
lev[0][j] = 0 if allow_substring else j
for i in range(len1):
for j in range(len2):
lev[i + 1][j + 1] = min(lev[i][j + 1] + 1, lev[i + 1][j] + 1, lev[i][j] + (s1[i] != s2[j]))
return min(lev[len1]) if allow_substring else lev[len1][len2]
|
python
|
def levenshtein(s1, s2, allow_substring=False):
"""Return the Levenshtein distance between two strings.
The Levenshtein distance (a.k.a "edit difference") is the number of characters that need to be substituted,
inserted or deleted to transform s1 into s2.
Setting the `allow_substring` parameter to True allows s1 to be a
substring of s2, so that, for example, "hello" and "hello there" would have a distance of zero.
:param string s1: The first string
:param string s2: The second string
:param bool allow_substring: Whether to allow s1 to be a substring of s2
:returns: Levenshtein distance.
:rtype int
"""
len1, len2 = len(s1), len(s2)
lev = []
for i in range(len1 + 1):
lev.append([0] * (len2 + 1))
for i in range(len1 + 1):
lev[i][0] = i
for j in range(len2 + 1):
lev[0][j] = 0 if allow_substring else j
for i in range(len1):
for j in range(len2):
lev[i + 1][j + 1] = min(lev[i][j + 1] + 1, lev[i + 1][j] + 1, lev[i][j] + (s1[i] != s2[j]))
return min(lev[len1]) if allow_substring else lev[len1][len2]
|
[
"def",
"levenshtein",
"(",
"s1",
",",
"s2",
",",
"allow_substring",
"=",
"False",
")",
":",
"len1",
",",
"len2",
"=",
"len",
"(",
"s1",
")",
",",
"len",
"(",
"s2",
")",
"lev",
"=",
"[",
"]",
"for",
"i",
"in",
"range",
"(",
"len1",
"+",
"1",
")",
":",
"lev",
".",
"append",
"(",
"[",
"0",
"]",
"*",
"(",
"len2",
"+",
"1",
")",
")",
"for",
"i",
"in",
"range",
"(",
"len1",
"+",
"1",
")",
":",
"lev",
"[",
"i",
"]",
"[",
"0",
"]",
"=",
"i",
"for",
"j",
"in",
"range",
"(",
"len2",
"+",
"1",
")",
":",
"lev",
"[",
"0",
"]",
"[",
"j",
"]",
"=",
"0",
"if",
"allow_substring",
"else",
"j",
"for",
"i",
"in",
"range",
"(",
"len1",
")",
":",
"for",
"j",
"in",
"range",
"(",
"len2",
")",
":",
"lev",
"[",
"i",
"+",
"1",
"]",
"[",
"j",
"+",
"1",
"]",
"=",
"min",
"(",
"lev",
"[",
"i",
"]",
"[",
"j",
"+",
"1",
"]",
"+",
"1",
",",
"lev",
"[",
"i",
"+",
"1",
"]",
"[",
"j",
"]",
"+",
"1",
",",
"lev",
"[",
"i",
"]",
"[",
"j",
"]",
"+",
"(",
"s1",
"[",
"i",
"]",
"!=",
"s2",
"[",
"j",
"]",
")",
")",
"return",
"min",
"(",
"lev",
"[",
"len1",
"]",
")",
"if",
"allow_substring",
"else",
"lev",
"[",
"len1",
"]",
"[",
"len2",
"]"
] |
Return the Levenshtein distance between two strings.
The Levenshtein distance (a.k.a "edit difference") is the number of characters that need to be substituted,
inserted or deleted to transform s1 into s2.
Setting the `allow_substring` parameter to True allows s1 to be a
substring of s2, so that, for example, "hello" and "hello there" would have a distance of zero.
:param string s1: The first string
:param string s2: The second string
:param bool allow_substring: Whether to allow s1 to be a substring of s2
:returns: Levenshtein distance.
:rtype int
|
[
"Return",
"the",
"Levenshtein",
"distance",
"between",
"two",
"strings",
"."
] |
349a3bea965f2073141d62043b89319222e46af1
|
https://github.com/mcs07/ChemDataExtractor/blob/349a3bea965f2073141d62043b89319222e46af1/chemdataextractor/text/__init__.py#L232-L258
|
train
|
mcs07/ChemDataExtractor
|
chemdataextractor/text/__init__.py
|
bracket_level
|
def bracket_level(text, open={'(', '[', '{'}, close={')', ']', '}'}):
"""Return 0 if string contains balanced brackets or no brackets."""
level = 0
for c in text:
if c in open:
level += 1
elif c in close:
level -= 1
return level
|
python
|
def bracket_level(text, open={'(', '[', '{'}, close={')', ']', '}'}):
"""Return 0 if string contains balanced brackets or no brackets."""
level = 0
for c in text:
if c in open:
level += 1
elif c in close:
level -= 1
return level
|
[
"def",
"bracket_level",
"(",
"text",
",",
"open",
"=",
"{",
"'('",
",",
"'['",
",",
"'{'",
"}",
",",
"close",
"=",
"{",
"')'",
",",
"']'",
",",
"'}'",
"}",
")",
":",
"level",
"=",
"0",
"for",
"c",
"in",
"text",
":",
"if",
"c",
"in",
"open",
":",
"level",
"+=",
"1",
"elif",
"c",
"in",
"close",
":",
"level",
"-=",
"1",
"return",
"level"
] |
Return 0 if string contains balanced brackets or no brackets.
|
[
"Return",
"0",
"if",
"string",
"contains",
"balanced",
"brackets",
"or",
"no",
"brackets",
"."
] |
349a3bea965f2073141d62043b89319222e46af1
|
https://github.com/mcs07/ChemDataExtractor/blob/349a3bea965f2073141d62043b89319222e46af1/chemdataextractor/text/__init__.py#L261-L269
|
train
|
mcs07/ChemDataExtractor
|
chemdataextractor/cli/config.py
|
list
|
def list(ctx):
"""List all config values."""
log.debug('chemdataextractor.config.list')
for k in config:
click.echo('%s : %s' % (k, config[k]))
|
python
|
def list(ctx):
"""List all config values."""
log.debug('chemdataextractor.config.list')
for k in config:
click.echo('%s : %s' % (k, config[k]))
|
[
"def",
"list",
"(",
"ctx",
")",
":",
"log",
".",
"debug",
"(",
"'chemdataextractor.config.list'",
")",
"for",
"k",
"in",
"config",
":",
"click",
".",
"echo",
"(",
"'%s : %s'",
"%",
"(",
"k",
",",
"config",
"[",
"k",
"]",
")",
")"
] |
List all config values.
|
[
"List",
"all",
"config",
"values",
"."
] |
349a3bea965f2073141d62043b89319222e46af1
|
https://github.com/mcs07/ChemDataExtractor/blob/349a3bea965f2073141d62043b89319222e46af1/chemdataextractor/cli/config.py#L33-L37
|
train
|
mcs07/ChemDataExtractor
|
chemdataextractor/cli/cem.py
|
train_crf
|
def train_crf(ctx, input, output, clusters):
"""Train CRF CEM recognizer."""
click.echo('chemdataextractor.crf.train')
sentences = []
for line in input:
sentence = []
for t in line.split():
token, tag, iob = t.rsplit('/', 2)
sentence.append(((token, tag), iob))
if sentence:
sentences.append(sentence)
tagger = CrfCemTagger(clusters=clusters)
tagger.train(sentences, output)
|
python
|
def train_crf(ctx, input, output, clusters):
"""Train CRF CEM recognizer."""
click.echo('chemdataextractor.crf.train')
sentences = []
for line in input:
sentence = []
for t in line.split():
token, tag, iob = t.rsplit('/', 2)
sentence.append(((token, tag), iob))
if sentence:
sentences.append(sentence)
tagger = CrfCemTagger(clusters=clusters)
tagger.train(sentences, output)
|
[
"def",
"train_crf",
"(",
"ctx",
",",
"input",
",",
"output",
",",
"clusters",
")",
":",
"click",
".",
"echo",
"(",
"'chemdataextractor.crf.train'",
")",
"sentences",
"=",
"[",
"]",
"for",
"line",
"in",
"input",
":",
"sentence",
"=",
"[",
"]",
"for",
"t",
"in",
"line",
".",
"split",
"(",
")",
":",
"token",
",",
"tag",
",",
"iob",
"=",
"t",
".",
"rsplit",
"(",
"'/'",
",",
"2",
")",
"sentence",
".",
"append",
"(",
"(",
"(",
"token",
",",
"tag",
")",
",",
"iob",
")",
")",
"if",
"sentence",
":",
"sentences",
".",
"append",
"(",
"sentence",
")",
"tagger",
"=",
"CrfCemTagger",
"(",
"clusters",
"=",
"clusters",
")",
"tagger",
".",
"train",
"(",
"sentences",
",",
"output",
")"
] |
Train CRF CEM recognizer.
|
[
"Train",
"CRF",
"CEM",
"recognizer",
"."
] |
349a3bea965f2073141d62043b89319222e46af1
|
https://github.com/mcs07/ChemDataExtractor/blob/349a3bea965f2073141d62043b89319222e46af1/chemdataextractor/cli/cem.py#L31-L44
|
train
|
mcs07/ChemDataExtractor
|
chemdataextractor/doc/text.py
|
Text.sentences
|
def sentences(self):
"""Return a list of Sentences that make up this text passage."""
sents = []
spans = self.sentence_tokenizer.span_tokenize(self.text)
for span in spans:
sent = Sentence(
text=self.text[span[0]:span[1]],
start=span[0],
end=span[1],
word_tokenizer=self.word_tokenizer,
lexicon=self.lexicon,
abbreviation_detector=self.abbreviation_detector,
pos_tagger=self.pos_tagger,
ner_tagger=self.ner_tagger,
parsers=self.parsers,
document=self.document
)
sents.append(sent)
return sents
|
python
|
def sentences(self):
"""Return a list of Sentences that make up this text passage."""
sents = []
spans = self.sentence_tokenizer.span_tokenize(self.text)
for span in spans:
sent = Sentence(
text=self.text[span[0]:span[1]],
start=span[0],
end=span[1],
word_tokenizer=self.word_tokenizer,
lexicon=self.lexicon,
abbreviation_detector=self.abbreviation_detector,
pos_tagger=self.pos_tagger,
ner_tagger=self.ner_tagger,
parsers=self.parsers,
document=self.document
)
sents.append(sent)
return sents
|
[
"def",
"sentences",
"(",
"self",
")",
":",
"sents",
"=",
"[",
"]",
"spans",
"=",
"self",
".",
"sentence_tokenizer",
".",
"span_tokenize",
"(",
"self",
".",
"text",
")",
"for",
"span",
"in",
"spans",
":",
"sent",
"=",
"Sentence",
"(",
"text",
"=",
"self",
".",
"text",
"[",
"span",
"[",
"0",
"]",
":",
"span",
"[",
"1",
"]",
"]",
",",
"start",
"=",
"span",
"[",
"0",
"]",
",",
"end",
"=",
"span",
"[",
"1",
"]",
",",
"word_tokenizer",
"=",
"self",
".",
"word_tokenizer",
",",
"lexicon",
"=",
"self",
".",
"lexicon",
",",
"abbreviation_detector",
"=",
"self",
".",
"abbreviation_detector",
",",
"pos_tagger",
"=",
"self",
".",
"pos_tagger",
",",
"ner_tagger",
"=",
"self",
".",
"ner_tagger",
",",
"parsers",
"=",
"self",
".",
"parsers",
",",
"document",
"=",
"self",
".",
"document",
")",
"sents",
".",
"append",
"(",
"sent",
")",
"return",
"sents"
] |
Return a list of Sentences that make up this text passage.
|
[
"Return",
"a",
"list",
"of",
"Sentences",
"that",
"make",
"up",
"this",
"text",
"passage",
"."
] |
349a3bea965f2073141d62043b89319222e46af1
|
https://github.com/mcs07/ChemDataExtractor/blob/349a3bea965f2073141d62043b89319222e46af1/chemdataextractor/doc/text.py#L139-L157
|
train
|
mcs07/ChemDataExtractor
|
chemdataextractor/doc/text.py
|
Text.records
|
def records(self):
"""Return a list of records for this text passage."""
return ModelList(*[r for sent in self.sentences for r in sent.records])
|
python
|
def records(self):
"""Return a list of records for this text passage."""
return ModelList(*[r for sent in self.sentences for r in sent.records])
|
[
"def",
"records",
"(",
"self",
")",
":",
"return",
"ModelList",
"(",
"*",
"[",
"r",
"for",
"sent",
"in",
"self",
".",
"sentences",
"for",
"r",
"in",
"sent",
".",
"records",
"]",
")"
] |
Return a list of records for this text passage.
|
[
"Return",
"a",
"list",
"of",
"records",
"for",
"this",
"text",
"passage",
"."
] |
349a3bea965f2073141d62043b89319222e46af1
|
https://github.com/mcs07/ChemDataExtractor/blob/349a3bea965f2073141d62043b89319222e46af1/chemdataextractor/doc/text.py#L231-L233
|
train
|
mcs07/ChemDataExtractor
|
chemdataextractor/doc/text.py
|
Sentence.tokens
|
def tokens(self):
"""Return a list of token Spans for this sentence."""
spans = self.word_tokenizer.span_tokenize(self.text)
toks = [Token(
text=self.text[span[0]:span[1]],
start=span[0] + self.start,
end=span[1] + self.start,
lexicon=self.lexicon
) for span in spans]
return toks
|
python
|
def tokens(self):
"""Return a list of token Spans for this sentence."""
spans = self.word_tokenizer.span_tokenize(self.text)
toks = [Token(
text=self.text[span[0]:span[1]],
start=span[0] + self.start,
end=span[1] + self.start,
lexicon=self.lexicon
) for span in spans]
return toks
|
[
"def",
"tokens",
"(",
"self",
")",
":",
"spans",
"=",
"self",
".",
"word_tokenizer",
".",
"span_tokenize",
"(",
"self",
".",
"text",
")",
"toks",
"=",
"[",
"Token",
"(",
"text",
"=",
"self",
".",
"text",
"[",
"span",
"[",
"0",
"]",
":",
"span",
"[",
"1",
"]",
"]",
",",
"start",
"=",
"span",
"[",
"0",
"]",
"+",
"self",
".",
"start",
",",
"end",
"=",
"span",
"[",
"1",
"]",
"+",
"self",
".",
"start",
",",
"lexicon",
"=",
"self",
".",
"lexicon",
")",
"for",
"span",
"in",
"spans",
"]",
"return",
"toks"
] |
Return a list of token Spans for this sentence.
|
[
"Return",
"a",
"list",
"of",
"token",
"Spans",
"for",
"this",
"sentence",
"."
] |
349a3bea965f2073141d62043b89319222e46af1
|
https://github.com/mcs07/ChemDataExtractor/blob/349a3bea965f2073141d62043b89319222e46af1/chemdataextractor/doc/text.py#L322-L331
|
train
|
mcs07/ChemDataExtractor
|
chemdataextractor/doc/text.py
|
Sentence.tags
|
def tags(self):
"""Return combined POS and NER tags."""
tags = self.pos_tags
for i, tag in enumerate(self.ner_tags):
if tag is not None:
tags[i] = tag
return tags
|
python
|
def tags(self):
"""Return combined POS and NER tags."""
tags = self.pos_tags
for i, tag in enumerate(self.ner_tags):
if tag is not None:
tags[i] = tag
return tags
|
[
"def",
"tags",
"(",
"self",
")",
":",
"tags",
"=",
"self",
".",
"pos_tags",
"for",
"i",
",",
"tag",
"in",
"enumerate",
"(",
"self",
".",
"ner_tags",
")",
":",
"if",
"tag",
"is",
"not",
"None",
":",
"tags",
"[",
"i",
"]",
"=",
"tag",
"return",
"tags"
] |
Return combined POS and NER tags.
|
[
"Return",
"combined",
"POS",
"and",
"NER",
"tags",
"."
] |
349a3bea965f2073141d62043b89319222e46af1
|
https://github.com/mcs07/ChemDataExtractor/blob/349a3bea965f2073141d62043b89319222e46af1/chemdataextractor/doc/text.py#L492-L498
|
train
|
mcs07/ChemDataExtractor
|
chemdataextractor/doc/text.py
|
Sentence.records
|
def records(self):
"""Return a list of records for this sentence."""
compounds = ModelList()
seen_labels = set()
# Ensure no control characters are sent to a parser (need to be XML compatible)
tagged_tokens = [(CONTROL_RE.sub('', token), tag) for token, tag in self.tagged_tokens]
for parser in self.parsers:
for record in parser.parse(tagged_tokens):
p = record.serialize()
if not p: # TODO: Potential performance issues?
continue
# Skip duplicate records
if record in compounds:
continue
# Skip just labels that have already been seen (bit of a hack)
if all(k in {'labels', 'roles'} for k in p.keys()) and set(record.labels).issubset(seen_labels):
continue
seen_labels.update(record.labels)
compounds.append(record)
return compounds
|
python
|
def records(self):
"""Return a list of records for this sentence."""
compounds = ModelList()
seen_labels = set()
# Ensure no control characters are sent to a parser (need to be XML compatible)
tagged_tokens = [(CONTROL_RE.sub('', token), tag) for token, tag in self.tagged_tokens]
for parser in self.parsers:
for record in parser.parse(tagged_tokens):
p = record.serialize()
if not p: # TODO: Potential performance issues?
continue
# Skip duplicate records
if record in compounds:
continue
# Skip just labels that have already been seen (bit of a hack)
if all(k in {'labels', 'roles'} for k in p.keys()) and set(record.labels).issubset(seen_labels):
continue
seen_labels.update(record.labels)
compounds.append(record)
return compounds
|
[
"def",
"records",
"(",
"self",
")",
":",
"compounds",
"=",
"ModelList",
"(",
")",
"seen_labels",
"=",
"set",
"(",
")",
"# Ensure no control characters are sent to a parser (need to be XML compatible)",
"tagged_tokens",
"=",
"[",
"(",
"CONTROL_RE",
".",
"sub",
"(",
"''",
",",
"token",
")",
",",
"tag",
")",
"for",
"token",
",",
"tag",
"in",
"self",
".",
"tagged_tokens",
"]",
"for",
"parser",
"in",
"self",
".",
"parsers",
":",
"for",
"record",
"in",
"parser",
".",
"parse",
"(",
"tagged_tokens",
")",
":",
"p",
"=",
"record",
".",
"serialize",
"(",
")",
"if",
"not",
"p",
":",
"# TODO: Potential performance issues?",
"continue",
"# Skip duplicate records",
"if",
"record",
"in",
"compounds",
":",
"continue",
"# Skip just labels that have already been seen (bit of a hack)",
"if",
"all",
"(",
"k",
"in",
"{",
"'labels'",
",",
"'roles'",
"}",
"for",
"k",
"in",
"p",
".",
"keys",
"(",
")",
")",
"and",
"set",
"(",
"record",
".",
"labels",
")",
".",
"issubset",
"(",
"seen_labels",
")",
":",
"continue",
"seen_labels",
".",
"update",
"(",
"record",
".",
"labels",
")",
"compounds",
".",
"append",
"(",
"record",
")",
"return",
"compounds"
] |
Return a list of records for this sentence.
|
[
"Return",
"a",
"list",
"of",
"records",
"for",
"this",
"sentence",
"."
] |
349a3bea965f2073141d62043b89319222e46af1
|
https://github.com/mcs07/ChemDataExtractor/blob/349a3bea965f2073141d62043b89319222e46af1/chemdataextractor/doc/text.py#L505-L524
|
train
|
mcs07/ChemDataExtractor
|
chemdataextractor/cli/chemdner.py
|
prepare_gold
|
def prepare_gold(ctx, annotations, gout):
"""Prepare bc-evaluate gold file from annotations supplied by CHEMDNER."""
click.echo('chemdataextractor.chemdner.prepare_gold')
for line in annotations:
pmid, ta, start, end, text, category = line.strip().split('\t')
gout.write('%s\t%s:%s:%s\n' % (pmid, ta, start, end))
|
python
|
def prepare_gold(ctx, annotations, gout):
"""Prepare bc-evaluate gold file from annotations supplied by CHEMDNER."""
click.echo('chemdataextractor.chemdner.prepare_gold')
for line in annotations:
pmid, ta, start, end, text, category = line.strip().split('\t')
gout.write('%s\t%s:%s:%s\n' % (pmid, ta, start, end))
|
[
"def",
"prepare_gold",
"(",
"ctx",
",",
"annotations",
",",
"gout",
")",
":",
"click",
".",
"echo",
"(",
"'chemdataextractor.chemdner.prepare_gold'",
")",
"for",
"line",
"in",
"annotations",
":",
"pmid",
",",
"ta",
",",
"start",
",",
"end",
",",
"text",
",",
"category",
"=",
"line",
".",
"strip",
"(",
")",
".",
"split",
"(",
"'\\t'",
")",
"gout",
".",
"write",
"(",
"'%s\\t%s:%s:%s\\n'",
"%",
"(",
"pmid",
",",
"ta",
",",
"start",
",",
"end",
")",
")"
] |
Prepare bc-evaluate gold file from annotations supplied by CHEMDNER.
|
[
"Prepare",
"bc",
"-",
"evaluate",
"gold",
"file",
"from",
"annotations",
"supplied",
"by",
"CHEMDNER",
"."
] |
349a3bea965f2073141d62043b89319222e46af1
|
https://github.com/mcs07/ChemDataExtractor/blob/349a3bea965f2073141d62043b89319222e46af1/chemdataextractor/cli/chemdner.py#L33-L38
|
train
|
mcs07/ChemDataExtractor
|
chemdataextractor/cli/chemdner.py
|
prepare_tokens
|
def prepare_tokens(ctx, input, annotations, tout, lout):
"""Prepare tokenized and tagged corpus file from those supplied by CHEMDNER."""
click.echo('chemdataextractor.chemdner.prepare_tokens')
# Collect the annotations into a dict
anndict = defaultdict(list)
for line in annotations:
pmid, ta, start, end, text, category = line.strip().split('\t')
anndict[(pmid, ta)].append((int(start), int(end), text))
# Process the corpus
for line in input:
pmid, title, abstract = line.strip().split(u'\t')
for t, section, anns in [(Title(title), 'T', anndict.get((pmid, u'T'), [])), (Paragraph(abstract), u'A', anndict.get((pmid, u'A'), []))]:
# Write our tokens with POS and IOB tags
tagged = _prep_tags(t, anns)
for i, sentence in enumerate(tagged):
tout.write(u' '.join([u'/'.join([token, tag, label]) for token, tag, label in sentence]))
lout.write(u' '.join([u'/'.join([token, label]) for token, tag, label in sentence]))
tout.write(u'\n')
lout.write(u'\n')
tout.write(u'\n')
lout.write(u'\n')
|
python
|
def prepare_tokens(ctx, input, annotations, tout, lout):
"""Prepare tokenized and tagged corpus file from those supplied by CHEMDNER."""
click.echo('chemdataextractor.chemdner.prepare_tokens')
# Collect the annotations into a dict
anndict = defaultdict(list)
for line in annotations:
pmid, ta, start, end, text, category = line.strip().split('\t')
anndict[(pmid, ta)].append((int(start), int(end), text))
# Process the corpus
for line in input:
pmid, title, abstract = line.strip().split(u'\t')
for t, section, anns in [(Title(title), 'T', anndict.get((pmid, u'T'), [])), (Paragraph(abstract), u'A', anndict.get((pmid, u'A'), []))]:
# Write our tokens with POS and IOB tags
tagged = _prep_tags(t, anns)
for i, sentence in enumerate(tagged):
tout.write(u' '.join([u'/'.join([token, tag, label]) for token, tag, label in sentence]))
lout.write(u' '.join([u'/'.join([token, label]) for token, tag, label in sentence]))
tout.write(u'\n')
lout.write(u'\n')
tout.write(u'\n')
lout.write(u'\n')
|
[
"def",
"prepare_tokens",
"(",
"ctx",
",",
"input",
",",
"annotations",
",",
"tout",
",",
"lout",
")",
":",
"click",
".",
"echo",
"(",
"'chemdataextractor.chemdner.prepare_tokens'",
")",
"# Collect the annotations into a dict",
"anndict",
"=",
"defaultdict",
"(",
"list",
")",
"for",
"line",
"in",
"annotations",
":",
"pmid",
",",
"ta",
",",
"start",
",",
"end",
",",
"text",
",",
"category",
"=",
"line",
".",
"strip",
"(",
")",
".",
"split",
"(",
"'\\t'",
")",
"anndict",
"[",
"(",
"pmid",
",",
"ta",
")",
"]",
".",
"append",
"(",
"(",
"int",
"(",
"start",
")",
",",
"int",
"(",
"end",
")",
",",
"text",
")",
")",
"# Process the corpus",
"for",
"line",
"in",
"input",
":",
"pmid",
",",
"title",
",",
"abstract",
"=",
"line",
".",
"strip",
"(",
")",
".",
"split",
"(",
"u'\\t'",
")",
"for",
"t",
",",
"section",
",",
"anns",
"in",
"[",
"(",
"Title",
"(",
"title",
")",
",",
"'T'",
",",
"anndict",
".",
"get",
"(",
"(",
"pmid",
",",
"u'T'",
")",
",",
"[",
"]",
")",
")",
",",
"(",
"Paragraph",
"(",
"abstract",
")",
",",
"u'A'",
",",
"anndict",
".",
"get",
"(",
"(",
"pmid",
",",
"u'A'",
")",
",",
"[",
"]",
")",
")",
"]",
":",
"# Write our tokens with POS and IOB tags",
"tagged",
"=",
"_prep_tags",
"(",
"t",
",",
"anns",
")",
"for",
"i",
",",
"sentence",
"in",
"enumerate",
"(",
"tagged",
")",
":",
"tout",
".",
"write",
"(",
"u' '",
".",
"join",
"(",
"[",
"u'/'",
".",
"join",
"(",
"[",
"token",
",",
"tag",
",",
"label",
"]",
")",
"for",
"token",
",",
"tag",
",",
"label",
"in",
"sentence",
"]",
")",
")",
"lout",
".",
"write",
"(",
"u' '",
".",
"join",
"(",
"[",
"u'/'",
".",
"join",
"(",
"[",
"token",
",",
"label",
"]",
")",
"for",
"token",
",",
"tag",
",",
"label",
"in",
"sentence",
"]",
")",
")",
"tout",
".",
"write",
"(",
"u'\\n'",
")",
"lout",
".",
"write",
"(",
"u'\\n'",
")",
"tout",
".",
"write",
"(",
"u'\\n'",
")",
"lout",
".",
"write",
"(",
"u'\\n'",
")"
] |
Prepare tokenized and tagged corpus file from those supplied by CHEMDNER.
|
[
"Prepare",
"tokenized",
"and",
"tagged",
"corpus",
"file",
"from",
"those",
"supplied",
"by",
"CHEMDNER",
"."
] |
349a3bea965f2073141d62043b89319222e46af1
|
https://github.com/mcs07/ChemDataExtractor/blob/349a3bea965f2073141d62043b89319222e46af1/chemdataextractor/cli/chemdner.py#L47-L67
|
train
|
mcs07/ChemDataExtractor
|
chemdataextractor/cli/chemdner.py
|
_prep_tags
|
def _prep_tags(t, annotations):
"""Apply IOB chemical entity tags and POS tags to text."""
tags = [['O' for _ in sent.tokens] for sent in t.sentences]
for start, end, text in annotations:
done_first = False
for i, sent in enumerate(t.sentences):
for j, token in enumerate(sent.tokens):
if start <= token.start < end or start < token.end <= end:
# Token start or end occurs within the annotation
tags[i][j] = 'I-CM' if done_first else 'B-CM'
done_first = True
tagged = [[(token[0], token[1], tags[i][j]) for j, token in enumerate(sentence.pos_tagged_tokens)] for i, sentence in enumerate(t.sentences)]
return tagged
|
python
|
def _prep_tags(t, annotations):
"""Apply IOB chemical entity tags and POS tags to text."""
tags = [['O' for _ in sent.tokens] for sent in t.sentences]
for start, end, text in annotations:
done_first = False
for i, sent in enumerate(t.sentences):
for j, token in enumerate(sent.tokens):
if start <= token.start < end or start < token.end <= end:
# Token start or end occurs within the annotation
tags[i][j] = 'I-CM' if done_first else 'B-CM'
done_first = True
tagged = [[(token[0], token[1], tags[i][j]) for j, token in enumerate(sentence.pos_tagged_tokens)] for i, sentence in enumerate(t.sentences)]
return tagged
|
[
"def",
"_prep_tags",
"(",
"t",
",",
"annotations",
")",
":",
"tags",
"=",
"[",
"[",
"'O'",
"for",
"_",
"in",
"sent",
".",
"tokens",
"]",
"for",
"sent",
"in",
"t",
".",
"sentences",
"]",
"for",
"start",
",",
"end",
",",
"text",
"in",
"annotations",
":",
"done_first",
"=",
"False",
"for",
"i",
",",
"sent",
"in",
"enumerate",
"(",
"t",
".",
"sentences",
")",
":",
"for",
"j",
",",
"token",
"in",
"enumerate",
"(",
"sent",
".",
"tokens",
")",
":",
"if",
"start",
"<=",
"token",
".",
"start",
"<",
"end",
"or",
"start",
"<",
"token",
".",
"end",
"<=",
"end",
":",
"# Token start or end occurs within the annotation",
"tags",
"[",
"i",
"]",
"[",
"j",
"]",
"=",
"'I-CM'",
"if",
"done_first",
"else",
"'B-CM'",
"done_first",
"=",
"True",
"tagged",
"=",
"[",
"[",
"(",
"token",
"[",
"0",
"]",
",",
"token",
"[",
"1",
"]",
",",
"tags",
"[",
"i",
"]",
"[",
"j",
"]",
")",
"for",
"j",
",",
"token",
"in",
"enumerate",
"(",
"sentence",
".",
"pos_tagged_tokens",
")",
"]",
"for",
"i",
",",
"sentence",
"in",
"enumerate",
"(",
"t",
".",
"sentences",
")",
"]",
"return",
"tagged"
] |
Apply IOB chemical entity tags and POS tags to text.
|
[
"Apply",
"IOB",
"chemical",
"entity",
"tags",
"and",
"POS",
"tags",
"to",
"text",
"."
] |
349a3bea965f2073141d62043b89319222e46af1
|
https://github.com/mcs07/ChemDataExtractor/blob/349a3bea965f2073141d62043b89319222e46af1/chemdataextractor/cli/chemdner.py#L70-L82
|
train
|
mcs07/ChemDataExtractor
|
chemdataextractor/cli/pos.py
|
train_all
|
def train_all(ctx, output):
"""Train POS tagger on WSJ, GENIA, and both. With and without cluster features."""
click.echo('chemdataextractor.pos.train_all')
click.echo('Output: %s' % output)
ctx.invoke(train, output='%s_wsj_nocluster.pickle' % output, corpus='wsj', clusters=False)
ctx.invoke(train, output='%s_wsj.pickle' % output, corpus='wsj', clusters=True)
ctx.invoke(train, output='%s_genia_nocluster.pickle' % output, corpus='genia', clusters=False)
ctx.invoke(train, output='%s_genia.pickle' % output, corpus='genia', clusters=True)
ctx.invoke(train, output='%s_wsj_genia_nocluster.pickle' % output, corpus='wsj+genia', clusters=False)
ctx.invoke(train, output='%s_wsj_genia.pickle' % output, corpus='wsj+genia', clusters=True)
|
python
|
def train_all(ctx, output):
"""Train POS tagger on WSJ, GENIA, and both. With and without cluster features."""
click.echo('chemdataextractor.pos.train_all')
click.echo('Output: %s' % output)
ctx.invoke(train, output='%s_wsj_nocluster.pickle' % output, corpus='wsj', clusters=False)
ctx.invoke(train, output='%s_wsj.pickle' % output, corpus='wsj', clusters=True)
ctx.invoke(train, output='%s_genia_nocluster.pickle' % output, corpus='genia', clusters=False)
ctx.invoke(train, output='%s_genia.pickle' % output, corpus='genia', clusters=True)
ctx.invoke(train, output='%s_wsj_genia_nocluster.pickle' % output, corpus='wsj+genia', clusters=False)
ctx.invoke(train, output='%s_wsj_genia.pickle' % output, corpus='wsj+genia', clusters=True)
|
[
"def",
"train_all",
"(",
"ctx",
",",
"output",
")",
":",
"click",
".",
"echo",
"(",
"'chemdataextractor.pos.train_all'",
")",
"click",
".",
"echo",
"(",
"'Output: %s'",
"%",
"output",
")",
"ctx",
".",
"invoke",
"(",
"train",
",",
"output",
"=",
"'%s_wsj_nocluster.pickle'",
"%",
"output",
",",
"corpus",
"=",
"'wsj'",
",",
"clusters",
"=",
"False",
")",
"ctx",
".",
"invoke",
"(",
"train",
",",
"output",
"=",
"'%s_wsj.pickle'",
"%",
"output",
",",
"corpus",
"=",
"'wsj'",
",",
"clusters",
"=",
"True",
")",
"ctx",
".",
"invoke",
"(",
"train",
",",
"output",
"=",
"'%s_genia_nocluster.pickle'",
"%",
"output",
",",
"corpus",
"=",
"'genia'",
",",
"clusters",
"=",
"False",
")",
"ctx",
".",
"invoke",
"(",
"train",
",",
"output",
"=",
"'%s_genia.pickle'",
"%",
"output",
",",
"corpus",
"=",
"'genia'",
",",
"clusters",
"=",
"True",
")",
"ctx",
".",
"invoke",
"(",
"train",
",",
"output",
"=",
"'%s_wsj_genia_nocluster.pickle'",
"%",
"output",
",",
"corpus",
"=",
"'wsj+genia'",
",",
"clusters",
"=",
"False",
")",
"ctx",
".",
"invoke",
"(",
"train",
",",
"output",
"=",
"'%s_wsj_genia.pickle'",
"%",
"output",
",",
"corpus",
"=",
"'wsj+genia'",
",",
"clusters",
"=",
"True",
")"
] |
Train POS tagger on WSJ, GENIA, and both. With and without cluster features.
|
[
"Train",
"POS",
"tagger",
"on",
"WSJ",
"GENIA",
"and",
"both",
".",
"With",
"and",
"without",
"cluster",
"features",
"."
] |
349a3bea965f2073141d62043b89319222e46af1
|
https://github.com/mcs07/ChemDataExtractor/blob/349a3bea965f2073141d62043b89319222e46af1/chemdataextractor/cli/pos.py#L35-L44
|
train
|
mcs07/ChemDataExtractor
|
chemdataextractor/cli/pos.py
|
evaluate_all
|
def evaluate_all(ctx, model):
"""Evaluate POS taggers on WSJ and GENIA."""
click.echo('chemdataextractor.pos.evaluate_all')
click.echo('Model: %s' % model)
ctx.invoke(evaluate, model='%s_wsj_nocluster.pickle' % model, corpus='wsj', clusters=False)
ctx.invoke(evaluate, model='%s_wsj_nocluster.pickle' % model, corpus='genia', clusters=False)
ctx.invoke(evaluate, model='%s_wsj.pickle' % model, corpus='wsj', clusters=True)
ctx.invoke(evaluate, model='%s_wsj.pickle' % model, corpus='genia', clusters=True)
ctx.invoke(evaluate, model='%s_genia_nocluster.pickle' % model, corpus='wsj', clusters=False)
ctx.invoke(evaluate, model='%s_genia_nocluster.pickle' % model, corpus='genia', clusters=False)
ctx.invoke(evaluate, model='%s_genia.pickle' % model, corpus='wsj', clusters=True)
ctx.invoke(evaluate, model='%s_genia.pickle' % model, corpus='genia', clusters=True)
ctx.invoke(evaluate, model='%s_wsj_genia_nocluster.pickle' % model, corpus='wsj', clusters=False)
ctx.invoke(evaluate, model='%s_wsj_genia_nocluster.pickle' % model, corpus='genia', clusters=False)
ctx.invoke(evaluate, model='%s_wsj_genia.pickle' % model, corpus='wsj', clusters=True)
ctx.invoke(evaluate, model='%s_wsj_genia.pickle' % model, corpus='genia', clusters=True)
|
python
|
def evaluate_all(ctx, model):
"""Evaluate POS taggers on WSJ and GENIA."""
click.echo('chemdataextractor.pos.evaluate_all')
click.echo('Model: %s' % model)
ctx.invoke(evaluate, model='%s_wsj_nocluster.pickle' % model, corpus='wsj', clusters=False)
ctx.invoke(evaluate, model='%s_wsj_nocluster.pickle' % model, corpus='genia', clusters=False)
ctx.invoke(evaluate, model='%s_wsj.pickle' % model, corpus='wsj', clusters=True)
ctx.invoke(evaluate, model='%s_wsj.pickle' % model, corpus='genia', clusters=True)
ctx.invoke(evaluate, model='%s_genia_nocluster.pickle' % model, corpus='wsj', clusters=False)
ctx.invoke(evaluate, model='%s_genia_nocluster.pickle' % model, corpus='genia', clusters=False)
ctx.invoke(evaluate, model='%s_genia.pickle' % model, corpus='wsj', clusters=True)
ctx.invoke(evaluate, model='%s_genia.pickle' % model, corpus='genia', clusters=True)
ctx.invoke(evaluate, model='%s_wsj_genia_nocluster.pickle' % model, corpus='wsj', clusters=False)
ctx.invoke(evaluate, model='%s_wsj_genia_nocluster.pickle' % model, corpus='genia', clusters=False)
ctx.invoke(evaluate, model='%s_wsj_genia.pickle' % model, corpus='wsj', clusters=True)
ctx.invoke(evaluate, model='%s_wsj_genia.pickle' % model, corpus='genia', clusters=True)
|
[
"def",
"evaluate_all",
"(",
"ctx",
",",
"model",
")",
":",
"click",
".",
"echo",
"(",
"'chemdataextractor.pos.evaluate_all'",
")",
"click",
".",
"echo",
"(",
"'Model: %s'",
"%",
"model",
")",
"ctx",
".",
"invoke",
"(",
"evaluate",
",",
"model",
"=",
"'%s_wsj_nocluster.pickle'",
"%",
"model",
",",
"corpus",
"=",
"'wsj'",
",",
"clusters",
"=",
"False",
")",
"ctx",
".",
"invoke",
"(",
"evaluate",
",",
"model",
"=",
"'%s_wsj_nocluster.pickle'",
"%",
"model",
",",
"corpus",
"=",
"'genia'",
",",
"clusters",
"=",
"False",
")",
"ctx",
".",
"invoke",
"(",
"evaluate",
",",
"model",
"=",
"'%s_wsj.pickle'",
"%",
"model",
",",
"corpus",
"=",
"'wsj'",
",",
"clusters",
"=",
"True",
")",
"ctx",
".",
"invoke",
"(",
"evaluate",
",",
"model",
"=",
"'%s_wsj.pickle'",
"%",
"model",
",",
"corpus",
"=",
"'genia'",
",",
"clusters",
"=",
"True",
")",
"ctx",
".",
"invoke",
"(",
"evaluate",
",",
"model",
"=",
"'%s_genia_nocluster.pickle'",
"%",
"model",
",",
"corpus",
"=",
"'wsj'",
",",
"clusters",
"=",
"False",
")",
"ctx",
".",
"invoke",
"(",
"evaluate",
",",
"model",
"=",
"'%s_genia_nocluster.pickle'",
"%",
"model",
",",
"corpus",
"=",
"'genia'",
",",
"clusters",
"=",
"False",
")",
"ctx",
".",
"invoke",
"(",
"evaluate",
",",
"model",
"=",
"'%s_genia.pickle'",
"%",
"model",
",",
"corpus",
"=",
"'wsj'",
",",
"clusters",
"=",
"True",
")",
"ctx",
".",
"invoke",
"(",
"evaluate",
",",
"model",
"=",
"'%s_genia.pickle'",
"%",
"model",
",",
"corpus",
"=",
"'genia'",
",",
"clusters",
"=",
"True",
")",
"ctx",
".",
"invoke",
"(",
"evaluate",
",",
"model",
"=",
"'%s_wsj_genia_nocluster.pickle'",
"%",
"model",
",",
"corpus",
"=",
"'wsj'",
",",
"clusters",
"=",
"False",
")",
"ctx",
".",
"invoke",
"(",
"evaluate",
",",
"model",
"=",
"'%s_wsj_genia_nocluster.pickle'",
"%",
"model",
",",
"corpus",
"=",
"'genia'",
",",
"clusters",
"=",
"False",
")",
"ctx",
".",
"invoke",
"(",
"evaluate",
",",
"model",
"=",
"'%s_wsj_genia.pickle'",
"%",
"model",
",",
"corpus",
"=",
"'wsj'",
",",
"clusters",
"=",
"True",
")",
"ctx",
".",
"invoke",
"(",
"evaluate",
",",
"model",
"=",
"'%s_wsj_genia.pickle'",
"%",
"model",
",",
"corpus",
"=",
"'genia'",
",",
"clusters",
"=",
"True",
")"
] |
Evaluate POS taggers on WSJ and GENIA.
|
[
"Evaluate",
"POS",
"taggers",
"on",
"WSJ",
"and",
"GENIA",
"."
] |
349a3bea965f2073141d62043b89319222e46af1
|
https://github.com/mcs07/ChemDataExtractor/blob/349a3bea965f2073141d62043b89319222e46af1/chemdataextractor/cli/pos.py#L50-L65
|
train
|
mcs07/ChemDataExtractor
|
chemdataextractor/cli/pos.py
|
train
|
def train(ctx, output, corpus, clusters):
"""Train POS Tagger."""
click.echo('chemdataextractor.pos.train')
click.echo('Output: %s' % output)
click.echo('Corpus: %s' % corpus)
click.echo('Clusters: %s' % clusters)
wsj_sents = []
genia_sents = []
if corpus == 'wsj' or corpus == 'wsj+genia':
wsj_sents = list(wsj_training.tagged_sents())
# For WSJ, remove all tokens with -NONE- tag
for i, wsj_sent in enumerate(wsj_sents):
wsj_sents[i] = [t for t in wsj_sent if not t[1] == '-NONE-']
if corpus == 'genia' or corpus == 'wsj+genia':
genia_sents = list(genia_training.tagged_sents())
# Translate GENIA
for i, genia_sent in enumerate(genia_sents):
for j, (token, tag) in enumerate(genia_sent):
if tag == '(':
genia_sents[i][j] = (token, '-LRB-') # ( to -RLB- (also do for evaluation)
elif tag == ')':
genia_sents[i][j] = (token, '-RRB-') # ) to -RRB- (also do for evaluation)
elif tag == 'CT':
genia_sents[i][j] = (token, 'DT') # Typo?
elif tag == 'XT':
genia_sents[i][j] = (token, 'DT') # Typo?
elif tag == '-':
genia_sents[i][j] = (token, ':') # Single hyphen character for dash
elif tag == 'N':
genia_sents[i][j] = (token, 'NN') # Typo?
elif tag == 'PP':
genia_sents[i][j] = (token, 'PRP') # Typo?
elif tag == '' and token == ')':
genia_sents[i][j] = (token, '-RRB-') # Typo?
elif tag == '' and token == 'IFN-gamma':
genia_sents[i][j] = (token, 'NN') # Typo?
elif '|' in tag:
genia_sents[i][j] = (token, tag.split('|')[0]) # If contains |, choose first part
# Filter any tags not in the allowed tagset (Shouldn't be any left anyway)
genia_sents[i] = [t for t in genia_sent if t[1] in TAGS]
if corpus == 'wsj':
training_corpus = wsj_sents
elif corpus == 'genia':
training_corpus = genia_sents
elif corpus == 'wsj+genia':
training_corpus = wsj_sents + genia_sents
else:
raise click.ClickException('Invalid corpus')
tagger = ChemCrfPosTagger(clusters=clusters)
tagger.train(training_corpus, output)
|
python
|
def train(ctx, output, corpus, clusters):
"""Train POS Tagger."""
click.echo('chemdataextractor.pos.train')
click.echo('Output: %s' % output)
click.echo('Corpus: %s' % corpus)
click.echo('Clusters: %s' % clusters)
wsj_sents = []
genia_sents = []
if corpus == 'wsj' or corpus == 'wsj+genia':
wsj_sents = list(wsj_training.tagged_sents())
# For WSJ, remove all tokens with -NONE- tag
for i, wsj_sent in enumerate(wsj_sents):
wsj_sents[i] = [t for t in wsj_sent if not t[1] == '-NONE-']
if corpus == 'genia' or corpus == 'wsj+genia':
genia_sents = list(genia_training.tagged_sents())
# Translate GENIA
for i, genia_sent in enumerate(genia_sents):
for j, (token, tag) in enumerate(genia_sent):
if tag == '(':
genia_sents[i][j] = (token, '-LRB-') # ( to -RLB- (also do for evaluation)
elif tag == ')':
genia_sents[i][j] = (token, '-RRB-') # ) to -RRB- (also do for evaluation)
elif tag == 'CT':
genia_sents[i][j] = (token, 'DT') # Typo?
elif tag == 'XT':
genia_sents[i][j] = (token, 'DT') # Typo?
elif tag == '-':
genia_sents[i][j] = (token, ':') # Single hyphen character for dash
elif tag == 'N':
genia_sents[i][j] = (token, 'NN') # Typo?
elif tag == 'PP':
genia_sents[i][j] = (token, 'PRP') # Typo?
elif tag == '' and token == ')':
genia_sents[i][j] = (token, '-RRB-') # Typo?
elif tag == '' and token == 'IFN-gamma':
genia_sents[i][j] = (token, 'NN') # Typo?
elif '|' in tag:
genia_sents[i][j] = (token, tag.split('|')[0]) # If contains |, choose first part
# Filter any tags not in the allowed tagset (Shouldn't be any left anyway)
genia_sents[i] = [t for t in genia_sent if t[1] in TAGS]
if corpus == 'wsj':
training_corpus = wsj_sents
elif corpus == 'genia':
training_corpus = genia_sents
elif corpus == 'wsj+genia':
training_corpus = wsj_sents + genia_sents
else:
raise click.ClickException('Invalid corpus')
tagger = ChemCrfPosTagger(clusters=clusters)
tagger.train(training_corpus, output)
|
[
"def",
"train",
"(",
"ctx",
",",
"output",
",",
"corpus",
",",
"clusters",
")",
":",
"click",
".",
"echo",
"(",
"'chemdataextractor.pos.train'",
")",
"click",
".",
"echo",
"(",
"'Output: %s'",
"%",
"output",
")",
"click",
".",
"echo",
"(",
"'Corpus: %s'",
"%",
"corpus",
")",
"click",
".",
"echo",
"(",
"'Clusters: %s'",
"%",
"clusters",
")",
"wsj_sents",
"=",
"[",
"]",
"genia_sents",
"=",
"[",
"]",
"if",
"corpus",
"==",
"'wsj'",
"or",
"corpus",
"==",
"'wsj+genia'",
":",
"wsj_sents",
"=",
"list",
"(",
"wsj_training",
".",
"tagged_sents",
"(",
")",
")",
"# For WSJ, remove all tokens with -NONE- tag",
"for",
"i",
",",
"wsj_sent",
"in",
"enumerate",
"(",
"wsj_sents",
")",
":",
"wsj_sents",
"[",
"i",
"]",
"=",
"[",
"t",
"for",
"t",
"in",
"wsj_sent",
"if",
"not",
"t",
"[",
"1",
"]",
"==",
"'-NONE-'",
"]",
"if",
"corpus",
"==",
"'genia'",
"or",
"corpus",
"==",
"'wsj+genia'",
":",
"genia_sents",
"=",
"list",
"(",
"genia_training",
".",
"tagged_sents",
"(",
")",
")",
"# Translate GENIA",
"for",
"i",
",",
"genia_sent",
"in",
"enumerate",
"(",
"genia_sents",
")",
":",
"for",
"j",
",",
"(",
"token",
",",
"tag",
")",
"in",
"enumerate",
"(",
"genia_sent",
")",
":",
"if",
"tag",
"==",
"'('",
":",
"genia_sents",
"[",
"i",
"]",
"[",
"j",
"]",
"=",
"(",
"token",
",",
"'-LRB-'",
")",
"# ( to -RLB- (also do for evaluation)",
"elif",
"tag",
"==",
"')'",
":",
"genia_sents",
"[",
"i",
"]",
"[",
"j",
"]",
"=",
"(",
"token",
",",
"'-RRB-'",
")",
"# ) to -RRB- (also do for evaluation)",
"elif",
"tag",
"==",
"'CT'",
":",
"genia_sents",
"[",
"i",
"]",
"[",
"j",
"]",
"=",
"(",
"token",
",",
"'DT'",
")",
"# Typo?",
"elif",
"tag",
"==",
"'XT'",
":",
"genia_sents",
"[",
"i",
"]",
"[",
"j",
"]",
"=",
"(",
"token",
",",
"'DT'",
")",
"# Typo?",
"elif",
"tag",
"==",
"'-'",
":",
"genia_sents",
"[",
"i",
"]",
"[",
"j",
"]",
"=",
"(",
"token",
",",
"':'",
")",
"# Single hyphen character for dash",
"elif",
"tag",
"==",
"'N'",
":",
"genia_sents",
"[",
"i",
"]",
"[",
"j",
"]",
"=",
"(",
"token",
",",
"'NN'",
")",
"# Typo?",
"elif",
"tag",
"==",
"'PP'",
":",
"genia_sents",
"[",
"i",
"]",
"[",
"j",
"]",
"=",
"(",
"token",
",",
"'PRP'",
")",
"# Typo?",
"elif",
"tag",
"==",
"''",
"and",
"token",
"==",
"')'",
":",
"genia_sents",
"[",
"i",
"]",
"[",
"j",
"]",
"=",
"(",
"token",
",",
"'-RRB-'",
")",
"# Typo?",
"elif",
"tag",
"==",
"''",
"and",
"token",
"==",
"'IFN-gamma'",
":",
"genia_sents",
"[",
"i",
"]",
"[",
"j",
"]",
"=",
"(",
"token",
",",
"'NN'",
")",
"# Typo?",
"elif",
"'|'",
"in",
"tag",
":",
"genia_sents",
"[",
"i",
"]",
"[",
"j",
"]",
"=",
"(",
"token",
",",
"tag",
".",
"split",
"(",
"'|'",
")",
"[",
"0",
"]",
")",
"# If contains |, choose first part",
"# Filter any tags not in the allowed tagset (Shouldn't be any left anyway)",
"genia_sents",
"[",
"i",
"]",
"=",
"[",
"t",
"for",
"t",
"in",
"genia_sent",
"if",
"t",
"[",
"1",
"]",
"in",
"TAGS",
"]",
"if",
"corpus",
"==",
"'wsj'",
":",
"training_corpus",
"=",
"wsj_sents",
"elif",
"corpus",
"==",
"'genia'",
":",
"training_corpus",
"=",
"genia_sents",
"elif",
"corpus",
"==",
"'wsj+genia'",
":",
"training_corpus",
"=",
"wsj_sents",
"+",
"genia_sents",
"else",
":",
"raise",
"click",
".",
"ClickException",
"(",
"'Invalid corpus'",
")",
"tagger",
"=",
"ChemCrfPosTagger",
"(",
"clusters",
"=",
"clusters",
")",
"tagger",
".",
"train",
"(",
"training_corpus",
",",
"output",
")"
] |
Train POS Tagger.
|
[
"Train",
"POS",
"Tagger",
"."
] |
349a3bea965f2073141d62043b89319222e46af1
|
https://github.com/mcs07/ChemDataExtractor/blob/349a3bea965f2073141d62043b89319222e46af1/chemdataextractor/cli/pos.py#L73-L127
|
train
|
mcs07/ChemDataExtractor
|
chemdataextractor/cli/pos.py
|
evaluate
|
def evaluate(ctx, model, corpus, clusters):
"""Evaluate performance of POS Tagger."""
click.echo('chemdataextractor.pos.evaluate')
if corpus == 'wsj':
evaluation = wsj_evaluation
sents = list(evaluation.tagged_sents())
for i, wsj_sent in enumerate(sents):
sents[i] = [t for t in wsj_sent if not t[1] == '-NONE-']
elif corpus == 'genia':
evaluation = genia_evaluation
sents = list(evaluation.tagged_sents())
# Translate GENIA bracket tags
for i, genia_sent in enumerate(sents):
for j, (token, tag) in enumerate(genia_sent):
if tag == '(':
sents[i][j] = (token, '-LRB-')
elif tag == ')':
sents[i][j] = (token, '-RRB-')
else:
raise click.ClickException('Invalid corpus')
tagger = ChemCrfPosTagger(model=model, clusters=clusters)
accuracy = tagger.evaluate(sents)
click.echo('%s on %s: %s' % (model, evaluation, accuracy))
|
python
|
def evaluate(ctx, model, corpus, clusters):
"""Evaluate performance of POS Tagger."""
click.echo('chemdataextractor.pos.evaluate')
if corpus == 'wsj':
evaluation = wsj_evaluation
sents = list(evaluation.tagged_sents())
for i, wsj_sent in enumerate(sents):
sents[i] = [t for t in wsj_sent if not t[1] == '-NONE-']
elif corpus == 'genia':
evaluation = genia_evaluation
sents = list(evaluation.tagged_sents())
# Translate GENIA bracket tags
for i, genia_sent in enumerate(sents):
for j, (token, tag) in enumerate(genia_sent):
if tag == '(':
sents[i][j] = (token, '-LRB-')
elif tag == ')':
sents[i][j] = (token, '-RRB-')
else:
raise click.ClickException('Invalid corpus')
tagger = ChemCrfPosTagger(model=model, clusters=clusters)
accuracy = tagger.evaluate(sents)
click.echo('%s on %s: %s' % (model, evaluation, accuracy))
|
[
"def",
"evaluate",
"(",
"ctx",
",",
"model",
",",
"corpus",
",",
"clusters",
")",
":",
"click",
".",
"echo",
"(",
"'chemdataextractor.pos.evaluate'",
")",
"if",
"corpus",
"==",
"'wsj'",
":",
"evaluation",
"=",
"wsj_evaluation",
"sents",
"=",
"list",
"(",
"evaluation",
".",
"tagged_sents",
"(",
")",
")",
"for",
"i",
",",
"wsj_sent",
"in",
"enumerate",
"(",
"sents",
")",
":",
"sents",
"[",
"i",
"]",
"=",
"[",
"t",
"for",
"t",
"in",
"wsj_sent",
"if",
"not",
"t",
"[",
"1",
"]",
"==",
"'-NONE-'",
"]",
"elif",
"corpus",
"==",
"'genia'",
":",
"evaluation",
"=",
"genia_evaluation",
"sents",
"=",
"list",
"(",
"evaluation",
".",
"tagged_sents",
"(",
")",
")",
"# Translate GENIA bracket tags",
"for",
"i",
",",
"genia_sent",
"in",
"enumerate",
"(",
"sents",
")",
":",
"for",
"j",
",",
"(",
"token",
",",
"tag",
")",
"in",
"enumerate",
"(",
"genia_sent",
")",
":",
"if",
"tag",
"==",
"'('",
":",
"sents",
"[",
"i",
"]",
"[",
"j",
"]",
"=",
"(",
"token",
",",
"'-LRB-'",
")",
"elif",
"tag",
"==",
"')'",
":",
"sents",
"[",
"i",
"]",
"[",
"j",
"]",
"=",
"(",
"token",
",",
"'-RRB-'",
")",
"else",
":",
"raise",
"click",
".",
"ClickException",
"(",
"'Invalid corpus'",
")",
"tagger",
"=",
"ChemCrfPosTagger",
"(",
"model",
"=",
"model",
",",
"clusters",
"=",
"clusters",
")",
"accuracy",
"=",
"tagger",
".",
"evaluate",
"(",
"sents",
")",
"click",
".",
"echo",
"(",
"'%s on %s: %s'",
"%",
"(",
"model",
",",
"evaluation",
",",
"accuracy",
")",
")"
] |
Evaluate performance of POS Tagger.
|
[
"Evaluate",
"performance",
"of",
"POS",
"Tagger",
"."
] |
349a3bea965f2073141d62043b89319222e46af1
|
https://github.com/mcs07/ChemDataExtractor/blob/349a3bea965f2073141d62043b89319222e46af1/chemdataextractor/cli/pos.py#L135-L157
|
train
|
mcs07/ChemDataExtractor
|
chemdataextractor/cli/pos.py
|
evaluate_perceptron
|
def evaluate_perceptron(ctx, model, corpus):
"""Evaluate performance of Averaged Perceptron POS Tagger."""
click.echo('chemdataextractor.pos.evaluate')
if corpus == 'wsj':
evaluation = wsj_evaluation
sents = list(evaluation.tagged_sents())
for i, wsj_sent in enumerate(sents):
sents[i] = [t for t in wsj_sent if not t[1] == u'-NONE-']
elif corpus == 'genia':
evaluation = genia_evaluation
sents = list(evaluation.tagged_sents())
# Translate GENIA bracket tags
for i, genia_sent in enumerate(sents):
for j, (token, tag) in enumerate(genia_sent):
if tag == u'(':
sents[i][j] = (token, u'-LRB-')
elif tag == u')':
sents[i][j] = (token, u'-RRB-')
else:
raise click.ClickException('Invalid corpus')
tagger = ChemApPosTagger(model=model)
accuracy = tagger.evaluate(sents)
click.echo('%s on %s: %s' % (model, evaluation, accuracy))
|
python
|
def evaluate_perceptron(ctx, model, corpus):
"""Evaluate performance of Averaged Perceptron POS Tagger."""
click.echo('chemdataextractor.pos.evaluate')
if corpus == 'wsj':
evaluation = wsj_evaluation
sents = list(evaluation.tagged_sents())
for i, wsj_sent in enumerate(sents):
sents[i] = [t for t in wsj_sent if not t[1] == u'-NONE-']
elif corpus == 'genia':
evaluation = genia_evaluation
sents = list(evaluation.tagged_sents())
# Translate GENIA bracket tags
for i, genia_sent in enumerate(sents):
for j, (token, tag) in enumerate(genia_sent):
if tag == u'(':
sents[i][j] = (token, u'-LRB-')
elif tag == u')':
sents[i][j] = (token, u'-RRB-')
else:
raise click.ClickException('Invalid corpus')
tagger = ChemApPosTagger(model=model)
accuracy = tagger.evaluate(sents)
click.echo('%s on %s: %s' % (model, evaluation, accuracy))
|
[
"def",
"evaluate_perceptron",
"(",
"ctx",
",",
"model",
",",
"corpus",
")",
":",
"click",
".",
"echo",
"(",
"'chemdataextractor.pos.evaluate'",
")",
"if",
"corpus",
"==",
"'wsj'",
":",
"evaluation",
"=",
"wsj_evaluation",
"sents",
"=",
"list",
"(",
"evaluation",
".",
"tagged_sents",
"(",
")",
")",
"for",
"i",
",",
"wsj_sent",
"in",
"enumerate",
"(",
"sents",
")",
":",
"sents",
"[",
"i",
"]",
"=",
"[",
"t",
"for",
"t",
"in",
"wsj_sent",
"if",
"not",
"t",
"[",
"1",
"]",
"==",
"u'-NONE-'",
"]",
"elif",
"corpus",
"==",
"'genia'",
":",
"evaluation",
"=",
"genia_evaluation",
"sents",
"=",
"list",
"(",
"evaluation",
".",
"tagged_sents",
"(",
")",
")",
"# Translate GENIA bracket tags",
"for",
"i",
",",
"genia_sent",
"in",
"enumerate",
"(",
"sents",
")",
":",
"for",
"j",
",",
"(",
"token",
",",
"tag",
")",
"in",
"enumerate",
"(",
"genia_sent",
")",
":",
"if",
"tag",
"==",
"u'('",
":",
"sents",
"[",
"i",
"]",
"[",
"j",
"]",
"=",
"(",
"token",
",",
"u'-LRB-'",
")",
"elif",
"tag",
"==",
"u')'",
":",
"sents",
"[",
"i",
"]",
"[",
"j",
"]",
"=",
"(",
"token",
",",
"u'-RRB-'",
")",
"else",
":",
"raise",
"click",
".",
"ClickException",
"(",
"'Invalid corpus'",
")",
"tagger",
"=",
"ChemApPosTagger",
"(",
"model",
"=",
"model",
")",
"accuracy",
"=",
"tagger",
".",
"evaluate",
"(",
"sents",
")",
"click",
".",
"echo",
"(",
"'%s on %s: %s'",
"%",
"(",
"model",
",",
"evaluation",
",",
"accuracy",
")",
")"
] |
Evaluate performance of Averaged Perceptron POS Tagger.
|
[
"Evaluate",
"performance",
"of",
"Averaged",
"Perceptron",
"POS",
"Tagger",
"."
] |
349a3bea965f2073141d62043b89319222e46af1
|
https://github.com/mcs07/ChemDataExtractor/blob/349a3bea965f2073141d62043b89319222e46af1/chemdataextractor/cli/pos.py#L227-L249
|
train
|
mcs07/ChemDataExtractor
|
chemdataextractor/cli/pos.py
|
tag
|
def tag(ctx, input, output):
"""Output POS-tagged tokens."""
log.info('chemdataextractor.pos.tag')
log.info('Reading %s' % input.name)
doc = Document.from_file(input)
for element in doc.elements:
if isinstance(element, Text):
for sentence in element.sentences:
output.write(u' '.join(u'/'.join([token, tag]) for token, tag in sentence.pos_tagged_tokens))
output.write(u'\n')
|
python
|
def tag(ctx, input, output):
"""Output POS-tagged tokens."""
log.info('chemdataextractor.pos.tag')
log.info('Reading %s' % input.name)
doc = Document.from_file(input)
for element in doc.elements:
if isinstance(element, Text):
for sentence in element.sentences:
output.write(u' '.join(u'/'.join([token, tag]) for token, tag in sentence.pos_tagged_tokens))
output.write(u'\n')
|
[
"def",
"tag",
"(",
"ctx",
",",
"input",
",",
"output",
")",
":",
"log",
".",
"info",
"(",
"'chemdataextractor.pos.tag'",
")",
"log",
".",
"info",
"(",
"'Reading %s'",
"%",
"input",
".",
"name",
")",
"doc",
"=",
"Document",
".",
"from_file",
"(",
"input",
")",
"for",
"element",
"in",
"doc",
".",
"elements",
":",
"if",
"isinstance",
"(",
"element",
",",
"Text",
")",
":",
"for",
"sentence",
"in",
"element",
".",
"sentences",
":",
"output",
".",
"write",
"(",
"u' '",
".",
"join",
"(",
"u'/'",
".",
"join",
"(",
"[",
"token",
",",
"tag",
"]",
")",
"for",
"token",
",",
"tag",
"in",
"sentence",
".",
"pos_tagged_tokens",
")",
")",
"output",
".",
"write",
"(",
"u'\\n'",
")"
] |
Output POS-tagged tokens.
|
[
"Output",
"POS",
"-",
"tagged",
"tokens",
"."
] |
349a3bea965f2073141d62043b89319222e46af1
|
https://github.com/mcs07/ChemDataExtractor/blob/349a3bea965f2073141d62043b89319222e46af1/chemdataextractor/cli/pos.py#L256-L265
|
train
|
mcs07/ChemDataExtractor
|
chemdataextractor/scrape/scraper.py
|
GetRequester.make_request
|
def make_request(self, session, url, **kwargs):
"""Make a HTTP GET request.
:param url: The URL to get.
:returns: The response to the request.
:rtype: requests.Response
"""
log.debug('Making request: GET %s %s' % (url, kwargs))
return session.get(url, **kwargs)
|
python
|
def make_request(self, session, url, **kwargs):
"""Make a HTTP GET request.
:param url: The URL to get.
:returns: The response to the request.
:rtype: requests.Response
"""
log.debug('Making request: GET %s %s' % (url, kwargs))
return session.get(url, **kwargs)
|
[
"def",
"make_request",
"(",
"self",
",",
"session",
",",
"url",
",",
"*",
"*",
"kwargs",
")",
":",
"log",
".",
"debug",
"(",
"'Making request: GET %s %s'",
"%",
"(",
"url",
",",
"kwargs",
")",
")",
"return",
"session",
".",
"get",
"(",
"url",
",",
"*",
"*",
"kwargs",
")"
] |
Make a HTTP GET request.
:param url: The URL to get.
:returns: The response to the request.
:rtype: requests.Response
|
[
"Make",
"a",
"HTTP",
"GET",
"request",
"."
] |
349a3bea965f2073141d62043b89319222e46af1
|
https://github.com/mcs07/ChemDataExtractor/blob/349a3bea965f2073141d62043b89319222e46af1/chemdataextractor/scrape/scraper.py#L45-L53
|
train
|
mcs07/ChemDataExtractor
|
chemdataextractor/scrape/scraper.py
|
PostRequester.make_request
|
def make_request(self, session, url, **kwargs):
"""Make a HTTP POST request.
:param url: The URL to post to.
:param data: The data to post.
:returns: The response to the request.
:rtype: requests.Response
"""
log.debug('Making request: POST %s %s' % (url, kwargs))
return session.post(url, **kwargs)
|
python
|
def make_request(self, session, url, **kwargs):
"""Make a HTTP POST request.
:param url: The URL to post to.
:param data: The data to post.
:returns: The response to the request.
:rtype: requests.Response
"""
log.debug('Making request: POST %s %s' % (url, kwargs))
return session.post(url, **kwargs)
|
[
"def",
"make_request",
"(",
"self",
",",
"session",
",",
"url",
",",
"*",
"*",
"kwargs",
")",
":",
"log",
".",
"debug",
"(",
"'Making request: POST %s %s'",
"%",
"(",
"url",
",",
"kwargs",
")",
")",
"return",
"session",
".",
"post",
"(",
"url",
",",
"*",
"*",
"kwargs",
")"
] |
Make a HTTP POST request.
:param url: The URL to post to.
:param data: The data to post.
:returns: The response to the request.
:rtype: requests.Response
|
[
"Make",
"a",
"HTTP",
"POST",
"request",
"."
] |
349a3bea965f2073141d62043b89319222e46af1
|
https://github.com/mcs07/ChemDataExtractor/blob/349a3bea965f2073141d62043b89319222e46af1/chemdataextractor/scrape/scraper.py#L58-L67
|
train
|
mcs07/ChemDataExtractor
|
chemdataextractor/scrape/scraper.py
|
UrlScraper.run
|
def run(self, url):
"""Request URL, scrape response and return an EntityList."""
url = self.process_url(url)
if not url:
return
response = self.make_request(self.http, url)
selector = self.process_response(response)
entities = []
for root in self.get_roots(selector):
entity = self.entity(root)
entity = self.process_entity(entity)
if entity:
entities.append(entity)
return EntityList(*entities)
|
python
|
def run(self, url):
"""Request URL, scrape response and return an EntityList."""
url = self.process_url(url)
if not url:
return
response = self.make_request(self.http, url)
selector = self.process_response(response)
entities = []
for root in self.get_roots(selector):
entity = self.entity(root)
entity = self.process_entity(entity)
if entity:
entities.append(entity)
return EntityList(*entities)
|
[
"def",
"run",
"(",
"self",
",",
"url",
")",
":",
"url",
"=",
"self",
".",
"process_url",
"(",
"url",
")",
"if",
"not",
"url",
":",
"return",
"response",
"=",
"self",
".",
"make_request",
"(",
"self",
".",
"http",
",",
"url",
")",
"selector",
"=",
"self",
".",
"process_response",
"(",
"response",
")",
"entities",
"=",
"[",
"]",
"for",
"root",
"in",
"self",
".",
"get_roots",
"(",
"selector",
")",
":",
"entity",
"=",
"self",
".",
"entity",
"(",
"root",
")",
"entity",
"=",
"self",
".",
"process_entity",
"(",
"entity",
")",
"if",
"entity",
":",
"entities",
".",
"append",
"(",
"entity",
")",
"return",
"EntityList",
"(",
"*",
"entities",
")"
] |
Request URL, scrape response and return an EntityList.
|
[
"Request",
"URL",
"scrape",
"response",
"and",
"return",
"an",
"EntityList",
"."
] |
349a3bea965f2073141d62043b89319222e46af1
|
https://github.com/mcs07/ChemDataExtractor/blob/349a3bea965f2073141d62043b89319222e46af1/chemdataextractor/scrape/scraper.py#L77-L90
|
train
|
mcs07/ChemDataExtractor
|
chemdataextractor/scrape/clean.py
|
Cleaner.clean_html
|
def clean_html(self, html):
"""Apply ``Cleaner`` to HTML string or document and return a cleaned string or document."""
result_type = type(html)
if isinstance(html, six.string_types):
doc = html_fromstring(html)
else:
doc = copy.deepcopy(html)
self(doc)
if issubclass(result_type, six.binary_type):
return tostring(doc, encoding='utf-8')
elif issubclass(result_type, six.text_type):
return tostring(doc, encoding='unicode')
else:
return doc
|
python
|
def clean_html(self, html):
"""Apply ``Cleaner`` to HTML string or document and return a cleaned string or document."""
result_type = type(html)
if isinstance(html, six.string_types):
doc = html_fromstring(html)
else:
doc = copy.deepcopy(html)
self(doc)
if issubclass(result_type, six.binary_type):
return tostring(doc, encoding='utf-8')
elif issubclass(result_type, six.text_type):
return tostring(doc, encoding='unicode')
else:
return doc
|
[
"def",
"clean_html",
"(",
"self",
",",
"html",
")",
":",
"result_type",
"=",
"type",
"(",
"html",
")",
"if",
"isinstance",
"(",
"html",
",",
"six",
".",
"string_types",
")",
":",
"doc",
"=",
"html_fromstring",
"(",
"html",
")",
"else",
":",
"doc",
"=",
"copy",
".",
"deepcopy",
"(",
"html",
")",
"self",
"(",
"doc",
")",
"if",
"issubclass",
"(",
"result_type",
",",
"six",
".",
"binary_type",
")",
":",
"return",
"tostring",
"(",
"doc",
",",
"encoding",
"=",
"'utf-8'",
")",
"elif",
"issubclass",
"(",
"result_type",
",",
"six",
".",
"text_type",
")",
":",
"return",
"tostring",
"(",
"doc",
",",
"encoding",
"=",
"'unicode'",
")",
"else",
":",
"return",
"doc"
] |
Apply ``Cleaner`` to HTML string or document and return a cleaned string or document.
|
[
"Apply",
"Cleaner",
"to",
"HTML",
"string",
"or",
"document",
"and",
"return",
"a",
"cleaned",
"string",
"or",
"document",
"."
] |
349a3bea965f2073141d62043b89319222e46af1
|
https://github.com/mcs07/ChemDataExtractor/blob/349a3bea965f2073141d62043b89319222e46af1/chemdataextractor/scrape/clean.py#L159-L172
|
train
|
mcs07/ChemDataExtractor
|
chemdataextractor/scrape/clean.py
|
Cleaner.clean_markup
|
def clean_markup(self, markup, parser=None):
"""Apply ``Cleaner`` to markup string or document and return a cleaned string or document."""
result_type = type(markup)
if isinstance(markup, six.string_types):
doc = fromstring(markup, parser=parser)
else:
doc = copy.deepcopy(markup)
self(doc)
if issubclass(result_type, six.binary_type):
return tostring(doc, encoding='utf-8')
elif issubclass(result_type, six.text_type):
return tostring(doc, encoding='unicode')
else:
return doc
|
python
|
def clean_markup(self, markup, parser=None):
"""Apply ``Cleaner`` to markup string or document and return a cleaned string or document."""
result_type = type(markup)
if isinstance(markup, six.string_types):
doc = fromstring(markup, parser=parser)
else:
doc = copy.deepcopy(markup)
self(doc)
if issubclass(result_type, six.binary_type):
return tostring(doc, encoding='utf-8')
elif issubclass(result_type, six.text_type):
return tostring(doc, encoding='unicode')
else:
return doc
|
[
"def",
"clean_markup",
"(",
"self",
",",
"markup",
",",
"parser",
"=",
"None",
")",
":",
"result_type",
"=",
"type",
"(",
"markup",
")",
"if",
"isinstance",
"(",
"markup",
",",
"six",
".",
"string_types",
")",
":",
"doc",
"=",
"fromstring",
"(",
"markup",
",",
"parser",
"=",
"parser",
")",
"else",
":",
"doc",
"=",
"copy",
".",
"deepcopy",
"(",
"markup",
")",
"self",
"(",
"doc",
")",
"if",
"issubclass",
"(",
"result_type",
",",
"six",
".",
"binary_type",
")",
":",
"return",
"tostring",
"(",
"doc",
",",
"encoding",
"=",
"'utf-8'",
")",
"elif",
"issubclass",
"(",
"result_type",
",",
"six",
".",
"text_type",
")",
":",
"return",
"tostring",
"(",
"doc",
",",
"encoding",
"=",
"'unicode'",
")",
"else",
":",
"return",
"doc"
] |
Apply ``Cleaner`` to markup string or document and return a cleaned string or document.
|
[
"Apply",
"Cleaner",
"to",
"markup",
"string",
"or",
"document",
"and",
"return",
"a",
"cleaned",
"string",
"or",
"document",
"."
] |
349a3bea965f2073141d62043b89319222e46af1
|
https://github.com/mcs07/ChemDataExtractor/blob/349a3bea965f2073141d62043b89319222e46af1/chemdataextractor/scrape/clean.py#L174-L187
|
train
|
mcs07/ChemDataExtractor
|
chemdataextractor/text/processors.py
|
floats
|
def floats(s):
"""Convert string to float. Handles more string formats that the standard python conversion."""
try:
return float(s)
except ValueError:
s = re.sub(r'(\d)\s*\(\d+(\.\d+)?\)', r'\1', s) # Remove bracketed numbers from end
s = re.sub(r'(\d)\s*±\s*\d+(\.\d+)?', r'\1', s) # Remove uncertainties from end
s = s.rstrip('\'"+-=<>/,.:;!?)]}…∼~≈×*_≥≤') # Remove trailing punctuation
s = s.lstrip('\'"+=<>/([{∼~≈×*_≥≤£$€#§') # Remove leading punctuation
s = s.replace(',', '') # Remove commas
s = ''.join(s.split()) # Strip whitespace
s = re.sub(r'(\d)\s*[×x]\s*10\^?(-?\d)', r'\1e\2', s) # Convert scientific notation
return float(s)
|
python
|
def floats(s):
"""Convert string to float. Handles more string formats that the standard python conversion."""
try:
return float(s)
except ValueError:
s = re.sub(r'(\d)\s*\(\d+(\.\d+)?\)', r'\1', s) # Remove bracketed numbers from end
s = re.sub(r'(\d)\s*±\s*\d+(\.\d+)?', r'\1', s) # Remove uncertainties from end
s = s.rstrip('\'"+-=<>/,.:;!?)]}…∼~≈×*_≥≤') # Remove trailing punctuation
s = s.lstrip('\'"+=<>/([{∼~≈×*_≥≤£$€#§') # Remove leading punctuation
s = s.replace(',', '') # Remove commas
s = ''.join(s.split()) # Strip whitespace
s = re.sub(r'(\d)\s*[×x]\s*10\^?(-?\d)', r'\1e\2', s) # Convert scientific notation
return float(s)
|
[
"def",
"floats",
"(",
"s",
")",
":",
"try",
":",
"return",
"float",
"(",
"s",
")",
"except",
"ValueError",
":",
"s",
"=",
"re",
".",
"sub",
"(",
"r'(\\d)\\s*\\(\\d+(\\.\\d+)?\\)'",
",",
"r'\\1'",
",",
"s",
")",
"# Remove bracketed numbers from end",
"s",
"=",
"re",
".",
"sub",
"(",
"r'(\\d)\\s*±\\s*\\d+(\\.\\d+)?',",
" ",
"'\\1',",
" ",
")",
" ",
" Remove uncertainties from end",
"s",
"=",
"s",
".",
"rstrip",
"(",
"'\\'\"+-=<>/,.:;!?)]}…∼~≈×*_≥≤') ",
" ",
"ailing punctuation",
"s",
"=",
"s",
".",
"lstrip",
"(",
"'\\'\"+=<>/([{∼~≈×*_≥≤£$€#§') ",
" ",
"ing punctuation",
"s",
"=",
"s",
".",
"replace",
"(",
"','",
",",
"''",
")",
"# Remove commas",
"s",
"=",
"''",
".",
"join",
"(",
"s",
".",
"split",
"(",
")",
")",
"# Strip whitespace",
"s",
"=",
"re",
".",
"sub",
"(",
"r'(\\d)\\s*[×x]\\s*10\\^?(-?\\d)',",
" ",
"'\\1e\\2',",
" ",
")",
" ",
" Convert scientific notation",
"return",
"float",
"(",
"s",
")"
] |
Convert string to float. Handles more string formats that the standard python conversion.
|
[
"Convert",
"string",
"to",
"float",
".",
"Handles",
"more",
"string",
"formats",
"that",
"the",
"standard",
"python",
"conversion",
"."
] |
349a3bea965f2073141d62043b89319222e46af1
|
https://github.com/mcs07/ChemDataExtractor/blob/349a3bea965f2073141d62043b89319222e46af1/chemdataextractor/text/processors.py#L111-L123
|
train
|
mcs07/ChemDataExtractor
|
chemdataextractor/text/processors.py
|
strip_querystring
|
def strip_querystring(url):
"""Remove the querystring from the end of a URL."""
p = six.moves.urllib.parse.urlparse(url)
return p.scheme + "://" + p.netloc + p.path
|
python
|
def strip_querystring(url):
"""Remove the querystring from the end of a URL."""
p = six.moves.urllib.parse.urlparse(url)
return p.scheme + "://" + p.netloc + p.path
|
[
"def",
"strip_querystring",
"(",
"url",
")",
":",
"p",
"=",
"six",
".",
"moves",
".",
"urllib",
".",
"parse",
".",
"urlparse",
"(",
"url",
")",
"return",
"p",
".",
"scheme",
"+",
"\"://\"",
"+",
"p",
".",
"netloc",
"+",
"p",
".",
"path"
] |
Remove the querystring from the end of a URL.
|
[
"Remove",
"the",
"querystring",
"from",
"the",
"end",
"of",
"a",
"URL",
"."
] |
349a3bea965f2073141d62043b89319222e46af1
|
https://github.com/mcs07/ChemDataExtractor/blob/349a3bea965f2073141d62043b89319222e46af1/chemdataextractor/text/processors.py#L126-L129
|
train
|
mcs07/ChemDataExtractor
|
chemdataextractor/text/processors.py
|
extract_emails
|
def extract_emails(text):
"""Return a list of email addresses extracted from the string."""
text = text.replace(u'\u2024', '.')
emails = []
for m in EMAIL_RE.findall(text):
emails.append(m[0])
return emails
|
python
|
def extract_emails(text):
"""Return a list of email addresses extracted from the string."""
text = text.replace(u'\u2024', '.')
emails = []
for m in EMAIL_RE.findall(text):
emails.append(m[0])
return emails
|
[
"def",
"extract_emails",
"(",
"text",
")",
":",
"text",
"=",
"text",
".",
"replace",
"(",
"u'\\u2024'",
",",
"'.'",
")",
"emails",
"=",
"[",
"]",
"for",
"m",
"in",
"EMAIL_RE",
".",
"findall",
"(",
"text",
")",
":",
"emails",
".",
"append",
"(",
"m",
"[",
"0",
"]",
")",
"return",
"emails"
] |
Return a list of email addresses extracted from the string.
|
[
"Return",
"a",
"list",
"of",
"email",
"addresses",
"extracted",
"from",
"the",
"string",
"."
] |
349a3bea965f2073141d62043b89319222e46af1
|
https://github.com/mcs07/ChemDataExtractor/blob/349a3bea965f2073141d62043b89319222e46af1/chemdataextractor/text/processors.py#L159-L165
|
train
|
mcs07/ChemDataExtractor
|
chemdataextractor/text/processors.py
|
unapostrophe
|
def unapostrophe(text):
"""Strip apostrophe and 's' from the end of a string."""
text = re.sub(r'[%s]s?$' % ''.join(APOSTROPHES), '', text)
return text
|
python
|
def unapostrophe(text):
"""Strip apostrophe and 's' from the end of a string."""
text = re.sub(r'[%s]s?$' % ''.join(APOSTROPHES), '', text)
return text
|
[
"def",
"unapostrophe",
"(",
"text",
")",
":",
"text",
"=",
"re",
".",
"sub",
"(",
"r'[%s]s?$'",
"%",
"''",
".",
"join",
"(",
"APOSTROPHES",
")",
",",
"''",
",",
"text",
")",
"return",
"text"
] |
Strip apostrophe and 's' from the end of a string.
|
[
"Strip",
"apostrophe",
"and",
"s",
"from",
"the",
"end",
"of",
"a",
"string",
"."
] |
349a3bea965f2073141d62043b89319222e46af1
|
https://github.com/mcs07/ChemDataExtractor/blob/349a3bea965f2073141d62043b89319222e46af1/chemdataextractor/text/processors.py#L168-L171
|
train
|
linuxsoftware/ls.joyous
|
ls/joyous/utils/telltime.py
|
getLocalTime
|
def getLocalTime(date, time, *args, **kwargs):
"""
Get the time in the local timezone from date and time
"""
if time is not None:
return getLocalDateAndTime(date, time, *args, **kwargs)[1]
|
python
|
def getLocalTime(date, time, *args, **kwargs):
"""
Get the time in the local timezone from date and time
"""
if time is not None:
return getLocalDateAndTime(date, time, *args, **kwargs)[1]
|
[
"def",
"getLocalTime",
"(",
"date",
",",
"time",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"time",
"is",
"not",
"None",
":",
"return",
"getLocalDateAndTime",
"(",
"date",
",",
"time",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"[",
"1",
"]"
] |
Get the time in the local timezone from date and time
|
[
"Get",
"the",
"time",
"in",
"the",
"local",
"timezone",
"from",
"date",
"and",
"time"
] |
316283140ca5171a68ad3170a5964fdc89be0b56
|
https://github.com/linuxsoftware/ls.joyous/blob/316283140ca5171a68ad3170a5964fdc89be0b56/ls/joyous/utils/telltime.py#L19-L24
|
train
|
linuxsoftware/ls.joyous
|
ls/joyous/utils/telltime.py
|
getLocalDateAndTime
|
def getLocalDateAndTime(date, time, *args, **kwargs):
"""
Get the date and time in the local timezone from date and optionally time
"""
localDt = getLocalDatetime(date, time, *args, **kwargs)
if time is not None:
return (localDt.date(), localDt.timetz())
else:
return (localDt.date(), None)
|
python
|
def getLocalDateAndTime(date, time, *args, **kwargs):
"""
Get the date and time in the local timezone from date and optionally time
"""
localDt = getLocalDatetime(date, time, *args, **kwargs)
if time is not None:
return (localDt.date(), localDt.timetz())
else:
return (localDt.date(), None)
|
[
"def",
"getLocalDateAndTime",
"(",
"date",
",",
"time",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"localDt",
"=",
"getLocalDatetime",
"(",
"date",
",",
"time",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"if",
"time",
"is",
"not",
"None",
":",
"return",
"(",
"localDt",
".",
"date",
"(",
")",
",",
"localDt",
".",
"timetz",
"(",
")",
")",
"else",
":",
"return",
"(",
"localDt",
".",
"date",
"(",
")",
",",
"None",
")"
] |
Get the date and time in the local timezone from date and optionally time
|
[
"Get",
"the",
"date",
"and",
"time",
"in",
"the",
"local",
"timezone",
"from",
"date",
"and",
"optionally",
"time"
] |
316283140ca5171a68ad3170a5964fdc89be0b56
|
https://github.com/linuxsoftware/ls.joyous/blob/316283140ca5171a68ad3170a5964fdc89be0b56/ls/joyous/utils/telltime.py#L26-L34
|
train
|
linuxsoftware/ls.joyous
|
ls/joyous/utils/telltime.py
|
getLocalDatetime
|
def getLocalDatetime(date, time, tz=None, timeDefault=dt.time.max):
"""
Get a datetime in the local timezone from date and optionally time
"""
localTZ = timezone.get_current_timezone()
if tz is None or tz == localTZ:
localDt = getAwareDatetime(date, time, tz, timeDefault)
else:
# create in event's time zone
eventDt = getAwareDatetime(date, time, tz, timeDefault)
# convert to local time zone
localDt = eventDt.astimezone(localTZ)
if time is None:
localDt = getAwareDatetime(localDt.date(), None, localTZ, timeDefault)
return localDt
|
python
|
def getLocalDatetime(date, time, tz=None, timeDefault=dt.time.max):
"""
Get a datetime in the local timezone from date and optionally time
"""
localTZ = timezone.get_current_timezone()
if tz is None or tz == localTZ:
localDt = getAwareDatetime(date, time, tz, timeDefault)
else:
# create in event's time zone
eventDt = getAwareDatetime(date, time, tz, timeDefault)
# convert to local time zone
localDt = eventDt.astimezone(localTZ)
if time is None:
localDt = getAwareDatetime(localDt.date(), None, localTZ, timeDefault)
return localDt
|
[
"def",
"getLocalDatetime",
"(",
"date",
",",
"time",
",",
"tz",
"=",
"None",
",",
"timeDefault",
"=",
"dt",
".",
"time",
".",
"max",
")",
":",
"localTZ",
"=",
"timezone",
".",
"get_current_timezone",
"(",
")",
"if",
"tz",
"is",
"None",
"or",
"tz",
"==",
"localTZ",
":",
"localDt",
"=",
"getAwareDatetime",
"(",
"date",
",",
"time",
",",
"tz",
",",
"timeDefault",
")",
"else",
":",
"# create in event's time zone",
"eventDt",
"=",
"getAwareDatetime",
"(",
"date",
",",
"time",
",",
"tz",
",",
"timeDefault",
")",
"# convert to local time zone",
"localDt",
"=",
"eventDt",
".",
"astimezone",
"(",
"localTZ",
")",
"if",
"time",
"is",
"None",
":",
"localDt",
"=",
"getAwareDatetime",
"(",
"localDt",
".",
"date",
"(",
")",
",",
"None",
",",
"localTZ",
",",
"timeDefault",
")",
"return",
"localDt"
] |
Get a datetime in the local timezone from date and optionally time
|
[
"Get",
"a",
"datetime",
"in",
"the",
"local",
"timezone",
"from",
"date",
"and",
"optionally",
"time"
] |
316283140ca5171a68ad3170a5964fdc89be0b56
|
https://github.com/linuxsoftware/ls.joyous/blob/316283140ca5171a68ad3170a5964fdc89be0b56/ls/joyous/utils/telltime.py#L36-L50
|
train
|
linuxsoftware/ls.joyous
|
ls/joyous/utils/telltime.py
|
getAwareDatetime
|
def getAwareDatetime(date, time, tz, timeDefault=dt.time.max):
"""
Get a datetime in the given timezone from date and optionally time.
If time is not given it will default to timeDefault if that is given
or if not then to the end of the day.
"""
if time is None:
time = timeDefault
datetime = dt.datetime.combine(date, time)
# arbitary rule to handle DST transitions:
# if daylight savings causes an error then use standard time
datetime = timezone.make_aware(datetime, tz, is_dst=False)
return datetime
|
python
|
def getAwareDatetime(date, time, tz, timeDefault=dt.time.max):
"""
Get a datetime in the given timezone from date and optionally time.
If time is not given it will default to timeDefault if that is given
or if not then to the end of the day.
"""
if time is None:
time = timeDefault
datetime = dt.datetime.combine(date, time)
# arbitary rule to handle DST transitions:
# if daylight savings causes an error then use standard time
datetime = timezone.make_aware(datetime, tz, is_dst=False)
return datetime
|
[
"def",
"getAwareDatetime",
"(",
"date",
",",
"time",
",",
"tz",
",",
"timeDefault",
"=",
"dt",
".",
"time",
".",
"max",
")",
":",
"if",
"time",
"is",
"None",
":",
"time",
"=",
"timeDefault",
"datetime",
"=",
"dt",
".",
"datetime",
".",
"combine",
"(",
"date",
",",
"time",
")",
"# arbitary rule to handle DST transitions:",
"# if daylight savings causes an error then use standard time",
"datetime",
"=",
"timezone",
".",
"make_aware",
"(",
"datetime",
",",
"tz",
",",
"is_dst",
"=",
"False",
")",
"return",
"datetime"
] |
Get a datetime in the given timezone from date and optionally time.
If time is not given it will default to timeDefault if that is given
or if not then to the end of the day.
|
[
"Get",
"a",
"datetime",
"in",
"the",
"given",
"timezone",
"from",
"date",
"and",
"optionally",
"time",
".",
"If",
"time",
"is",
"not",
"given",
"it",
"will",
"default",
"to",
"timeDefault",
"if",
"that",
"is",
"given",
"or",
"if",
"not",
"then",
"to",
"the",
"end",
"of",
"the",
"day",
"."
] |
316283140ca5171a68ad3170a5964fdc89be0b56
|
https://github.com/linuxsoftware/ls.joyous/blob/316283140ca5171a68ad3170a5964fdc89be0b56/ls/joyous/utils/telltime.py#L52-L64
|
train
|
linuxsoftware/ls.joyous
|
ls/joyous/utils/weeks.py
|
_iso_num_weeks
|
def _iso_num_weeks(iso_year):
"Get the number of ISO-weeks in this year"
year_start = _iso_year_start(iso_year)
next_year_start = _iso_year_start(iso_year+1)
year_num_weeks = ((next_year_start - year_start).days) // 7
return year_num_weeks
|
python
|
def _iso_num_weeks(iso_year):
"Get the number of ISO-weeks in this year"
year_start = _iso_year_start(iso_year)
next_year_start = _iso_year_start(iso_year+1)
year_num_weeks = ((next_year_start - year_start).days) // 7
return year_num_weeks
|
[
"def",
"_iso_num_weeks",
"(",
"iso_year",
")",
":",
"year_start",
"=",
"_iso_year_start",
"(",
"iso_year",
")",
"next_year_start",
"=",
"_iso_year_start",
"(",
"iso_year",
"+",
"1",
")",
"year_num_weeks",
"=",
"(",
"(",
"next_year_start",
"-",
"year_start",
")",
".",
"days",
")",
"//",
"7",
"return",
"year_num_weeks"
] |
Get the number of ISO-weeks in this year
|
[
"Get",
"the",
"number",
"of",
"ISO",
"-",
"weeks",
"in",
"this",
"year"
] |
316283140ca5171a68ad3170a5964fdc89be0b56
|
https://github.com/linuxsoftware/ls.joyous/blob/316283140ca5171a68ad3170a5964fdc89be0b56/ls/joyous/utils/weeks.py#L31-L36
|
train
|
linuxsoftware/ls.joyous
|
ls/joyous/utils/weeks.py
|
_iso_info
|
def _iso_info(iso_year, iso_week):
"Give all the iso info we need from one calculation"
prev_year_start = _iso_year_start(iso_year-1)
year_start = _iso_year_start(iso_year)
next_year_start = _iso_year_start(iso_year+1)
first_day = year_start + dt.timedelta(weeks=iso_week-1)
last_day = first_day + dt.timedelta(days=6)
prev_year_num_weeks = ((year_start - prev_year_start).days) // 7
year_num_weeks = ((next_year_start - year_start).days) // 7
return (first_day, last_day, prev_year_num_weeks, year_num_weeks)
|
python
|
def _iso_info(iso_year, iso_week):
"Give all the iso info we need from one calculation"
prev_year_start = _iso_year_start(iso_year-1)
year_start = _iso_year_start(iso_year)
next_year_start = _iso_year_start(iso_year+1)
first_day = year_start + dt.timedelta(weeks=iso_week-1)
last_day = first_day + dt.timedelta(days=6)
prev_year_num_weeks = ((year_start - prev_year_start).days) // 7
year_num_weeks = ((next_year_start - year_start).days) // 7
return (first_day, last_day, prev_year_num_weeks, year_num_weeks)
|
[
"def",
"_iso_info",
"(",
"iso_year",
",",
"iso_week",
")",
":",
"prev_year_start",
"=",
"_iso_year_start",
"(",
"iso_year",
"-",
"1",
")",
"year_start",
"=",
"_iso_year_start",
"(",
"iso_year",
")",
"next_year_start",
"=",
"_iso_year_start",
"(",
"iso_year",
"+",
"1",
")",
"first_day",
"=",
"year_start",
"+",
"dt",
".",
"timedelta",
"(",
"weeks",
"=",
"iso_week",
"-",
"1",
")",
"last_day",
"=",
"first_day",
"+",
"dt",
".",
"timedelta",
"(",
"days",
"=",
"6",
")",
"prev_year_num_weeks",
"=",
"(",
"(",
"year_start",
"-",
"prev_year_start",
")",
".",
"days",
")",
"//",
"7",
"year_num_weeks",
"=",
"(",
"(",
"next_year_start",
"-",
"year_start",
")",
".",
"days",
")",
"//",
"7",
"return",
"(",
"first_day",
",",
"last_day",
",",
"prev_year_num_weeks",
",",
"year_num_weeks",
")"
] |
Give all the iso info we need from one calculation
|
[
"Give",
"all",
"the",
"iso",
"info",
"we",
"need",
"from",
"one",
"calculation"
] |
316283140ca5171a68ad3170a5964fdc89be0b56
|
https://github.com/linuxsoftware/ls.joyous/blob/316283140ca5171a68ad3170a5964fdc89be0b56/ls/joyous/utils/weeks.py#L38-L47
|
train
|
linuxsoftware/ls.joyous
|
ls/joyous/utils/weeks.py
|
_iso_week_of_month
|
def _iso_week_of_month(date_value):
"0-starting index which ISO-week in the month this date is"
weekday_of_first = date_value.replace(day=1).weekday()
return (date_value.day + weekday_of_first - 1) // 7
|
python
|
def _iso_week_of_month(date_value):
"0-starting index which ISO-week in the month this date is"
weekday_of_first = date_value.replace(day=1).weekday()
return (date_value.day + weekday_of_first - 1) // 7
|
[
"def",
"_iso_week_of_month",
"(",
"date_value",
")",
":",
"weekday_of_first",
"=",
"date_value",
".",
"replace",
"(",
"day",
"=",
"1",
")",
".",
"weekday",
"(",
")",
"return",
"(",
"date_value",
".",
"day",
"+",
"weekday_of_first",
"-",
"1",
")",
"//",
"7"
] |
0-starting index which ISO-week in the month this date is
|
[
"0",
"-",
"starting",
"index",
"which",
"ISO",
"-",
"week",
"in",
"the",
"month",
"this",
"date",
"is"
] |
316283140ca5171a68ad3170a5964fdc89be0b56
|
https://github.com/linuxsoftware/ls.joyous/blob/316283140ca5171a68ad3170a5964fdc89be0b56/ls/joyous/utils/weeks.py#L53-L56
|
train
|
linuxsoftware/ls.joyous
|
ls/joyous/utils/weeks.py
|
_ssweek_year_start
|
def _ssweek_year_start(ssweek_year):
"The gregorian calendar date of the first day of the given Sundaystarting-week year"
fifth_jan = dt.date(ssweek_year, 1, 5)
delta = dt.timedelta(fifth_jan.weekday()+1)
return fifth_jan - delta
|
python
|
def _ssweek_year_start(ssweek_year):
"The gregorian calendar date of the first day of the given Sundaystarting-week year"
fifth_jan = dt.date(ssweek_year, 1, 5)
delta = dt.timedelta(fifth_jan.weekday()+1)
return fifth_jan - delta
|
[
"def",
"_ssweek_year_start",
"(",
"ssweek_year",
")",
":",
"fifth_jan",
"=",
"dt",
".",
"date",
"(",
"ssweek_year",
",",
"1",
",",
"5",
")",
"delta",
"=",
"dt",
".",
"timedelta",
"(",
"fifth_jan",
".",
"weekday",
"(",
")",
"+",
"1",
")",
"return",
"fifth_jan",
"-",
"delta"
] |
The gregorian calendar date of the first day of the given Sundaystarting-week year
|
[
"The",
"gregorian",
"calendar",
"date",
"of",
"the",
"first",
"day",
"of",
"the",
"given",
"Sundaystarting",
"-",
"week",
"year"
] |
316283140ca5171a68ad3170a5964fdc89be0b56
|
https://github.com/linuxsoftware/ls.joyous/blob/316283140ca5171a68ad3170a5964fdc89be0b56/ls/joyous/utils/weeks.py#L60-L64
|
train
|
linuxsoftware/ls.joyous
|
ls/joyous/utils/weeks.py
|
_ssweek_to_gregorian
|
def _ssweek_to_gregorian(ssweek_year, ssweek_week, ssweek_day):
"Gregorian calendar date for the given Sundaystarting-week year, week and day"
year_start = _ssweek_year_start(ssweek_year)
return year_start + dt.timedelta(days=ssweek_day-1, weeks=ssweek_week-1)
|
python
|
def _ssweek_to_gregorian(ssweek_year, ssweek_week, ssweek_day):
"Gregorian calendar date for the given Sundaystarting-week year, week and day"
year_start = _ssweek_year_start(ssweek_year)
return year_start + dt.timedelta(days=ssweek_day-1, weeks=ssweek_week-1)
|
[
"def",
"_ssweek_to_gregorian",
"(",
"ssweek_year",
",",
"ssweek_week",
",",
"ssweek_day",
")",
":",
"year_start",
"=",
"_ssweek_year_start",
"(",
"ssweek_year",
")",
"return",
"year_start",
"+",
"dt",
".",
"timedelta",
"(",
"days",
"=",
"ssweek_day",
"-",
"1",
",",
"weeks",
"=",
"ssweek_week",
"-",
"1",
")"
] |
Gregorian calendar date for the given Sundaystarting-week year, week and day
|
[
"Gregorian",
"calendar",
"date",
"for",
"the",
"given",
"Sundaystarting",
"-",
"week",
"year",
"week",
"and",
"day"
] |
316283140ca5171a68ad3170a5964fdc89be0b56
|
https://github.com/linuxsoftware/ls.joyous/blob/316283140ca5171a68ad3170a5964fdc89be0b56/ls/joyous/utils/weeks.py#L66-L69
|
train
|
linuxsoftware/ls.joyous
|
ls/joyous/utils/weeks.py
|
_ssweek_num_weeks
|
def _ssweek_num_weeks(ssweek_year):
"Get the number of Sundaystarting-weeks in this year"
year_start = _ssweek_year_start(ssweek_year)
next_year_start = _ssweek_year_start(ssweek_year+1)
year_num_weeks = ((next_year_start - year_start).days) // 7
return year_num_weeks
|
python
|
def _ssweek_num_weeks(ssweek_year):
"Get the number of Sundaystarting-weeks in this year"
year_start = _ssweek_year_start(ssweek_year)
next_year_start = _ssweek_year_start(ssweek_year+1)
year_num_weeks = ((next_year_start - year_start).days) // 7
return year_num_weeks
|
[
"def",
"_ssweek_num_weeks",
"(",
"ssweek_year",
")",
":",
"year_start",
"=",
"_ssweek_year_start",
"(",
"ssweek_year",
")",
"next_year_start",
"=",
"_ssweek_year_start",
"(",
"ssweek_year",
"+",
"1",
")",
"year_num_weeks",
"=",
"(",
"(",
"next_year_start",
"-",
"year_start",
")",
".",
"days",
")",
"//",
"7",
"return",
"year_num_weeks"
] |
Get the number of Sundaystarting-weeks in this year
|
[
"Get",
"the",
"number",
"of",
"Sundaystarting",
"-",
"weeks",
"in",
"this",
"year"
] |
316283140ca5171a68ad3170a5964fdc89be0b56
|
https://github.com/linuxsoftware/ls.joyous/blob/316283140ca5171a68ad3170a5964fdc89be0b56/ls/joyous/utils/weeks.py#L71-L76
|
train
|
linuxsoftware/ls.joyous
|
ls/joyous/utils/weeks.py
|
_ssweek_info
|
def _ssweek_info(ssweek_year, ssweek_week):
"Give all the ssweek info we need from one calculation"
prev_year_start = _ssweek_year_start(ssweek_year-1)
year_start = _ssweek_year_start(ssweek_year)
next_year_start = _ssweek_year_start(ssweek_year+1)
first_day = year_start + dt.timedelta(weeks=ssweek_week-1)
last_day = first_day + dt.timedelta(days=6)
prev_year_num_weeks = ((year_start - prev_year_start).days) // 7
year_num_weeks = ((next_year_start - year_start).days) // 7
return (first_day, last_day, prev_year_num_weeks, year_num_weeks)
|
python
|
def _ssweek_info(ssweek_year, ssweek_week):
"Give all the ssweek info we need from one calculation"
prev_year_start = _ssweek_year_start(ssweek_year-1)
year_start = _ssweek_year_start(ssweek_year)
next_year_start = _ssweek_year_start(ssweek_year+1)
first_day = year_start + dt.timedelta(weeks=ssweek_week-1)
last_day = first_day + dt.timedelta(days=6)
prev_year_num_weeks = ((year_start - prev_year_start).days) // 7
year_num_weeks = ((next_year_start - year_start).days) // 7
return (first_day, last_day, prev_year_num_weeks, year_num_weeks)
|
[
"def",
"_ssweek_info",
"(",
"ssweek_year",
",",
"ssweek_week",
")",
":",
"prev_year_start",
"=",
"_ssweek_year_start",
"(",
"ssweek_year",
"-",
"1",
")",
"year_start",
"=",
"_ssweek_year_start",
"(",
"ssweek_year",
")",
"next_year_start",
"=",
"_ssweek_year_start",
"(",
"ssweek_year",
"+",
"1",
")",
"first_day",
"=",
"year_start",
"+",
"dt",
".",
"timedelta",
"(",
"weeks",
"=",
"ssweek_week",
"-",
"1",
")",
"last_day",
"=",
"first_day",
"+",
"dt",
".",
"timedelta",
"(",
"days",
"=",
"6",
")",
"prev_year_num_weeks",
"=",
"(",
"(",
"year_start",
"-",
"prev_year_start",
")",
".",
"days",
")",
"//",
"7",
"year_num_weeks",
"=",
"(",
"(",
"next_year_start",
"-",
"year_start",
")",
".",
"days",
")",
"//",
"7",
"return",
"(",
"first_day",
",",
"last_day",
",",
"prev_year_num_weeks",
",",
"year_num_weeks",
")"
] |
Give all the ssweek info we need from one calculation
|
[
"Give",
"all",
"the",
"ssweek",
"info",
"we",
"need",
"from",
"one",
"calculation"
] |
316283140ca5171a68ad3170a5964fdc89be0b56
|
https://github.com/linuxsoftware/ls.joyous/blob/316283140ca5171a68ad3170a5964fdc89be0b56/ls/joyous/utils/weeks.py#L78-L87
|
train
|
linuxsoftware/ls.joyous
|
ls/joyous/utils/weeks.py
|
_gregorian_to_ssweek
|
def _gregorian_to_ssweek(date_value):
"Sundaystarting-week year, week and day for the given Gregorian calendar date"
yearStart = _ssweek_year_start(date_value.year)
weekNum = ((date_value - yearStart).days) // 7 + 1
dayOfWeek = date_value.weekday()+1
return (date_value.year, weekNum, dayOfWeek)
|
python
|
def _gregorian_to_ssweek(date_value):
"Sundaystarting-week year, week and day for the given Gregorian calendar date"
yearStart = _ssweek_year_start(date_value.year)
weekNum = ((date_value - yearStart).days) // 7 + 1
dayOfWeek = date_value.weekday()+1
return (date_value.year, weekNum, dayOfWeek)
|
[
"def",
"_gregorian_to_ssweek",
"(",
"date_value",
")",
":",
"yearStart",
"=",
"_ssweek_year_start",
"(",
"date_value",
".",
"year",
")",
"weekNum",
"=",
"(",
"(",
"date_value",
"-",
"yearStart",
")",
".",
"days",
")",
"//",
"7",
"+",
"1",
"dayOfWeek",
"=",
"date_value",
".",
"weekday",
"(",
")",
"+",
"1",
"return",
"(",
"date_value",
".",
"year",
",",
"weekNum",
",",
"dayOfWeek",
")"
] |
Sundaystarting-week year, week and day for the given Gregorian calendar date
|
[
"Sundaystarting",
"-",
"week",
"year",
"week",
"and",
"day",
"for",
"the",
"given",
"Gregorian",
"calendar",
"date"
] |
316283140ca5171a68ad3170a5964fdc89be0b56
|
https://github.com/linuxsoftware/ls.joyous/blob/316283140ca5171a68ad3170a5964fdc89be0b56/ls/joyous/utils/weeks.py#L89-L94
|
train
|
linuxsoftware/ls.joyous
|
ls/joyous/utils/weeks.py
|
_ssweek_of_month
|
def _ssweek_of_month(date_value):
"0-starting index which Sundaystarting-week in the month this date is"
weekday_of_first = (date_value.replace(day=1).weekday() + 1) % 7
return (date_value.day + weekday_of_first - 1) // 7
|
python
|
def _ssweek_of_month(date_value):
"0-starting index which Sundaystarting-week in the month this date is"
weekday_of_first = (date_value.replace(day=1).weekday() + 1) % 7
return (date_value.day + weekday_of_first - 1) // 7
|
[
"def",
"_ssweek_of_month",
"(",
"date_value",
")",
":",
"weekday_of_first",
"=",
"(",
"date_value",
".",
"replace",
"(",
"day",
"=",
"1",
")",
".",
"weekday",
"(",
")",
"+",
"1",
")",
"%",
"7",
"return",
"(",
"date_value",
".",
"day",
"+",
"weekday_of_first",
"-",
"1",
")",
"//",
"7"
] |
0-starting index which Sundaystarting-week in the month this date is
|
[
"0",
"-",
"starting",
"index",
"which",
"Sundaystarting",
"-",
"week",
"in",
"the",
"month",
"this",
"date",
"is"
] |
316283140ca5171a68ad3170a5964fdc89be0b56
|
https://github.com/linuxsoftware/ls.joyous/blob/316283140ca5171a68ad3170a5964fdc89be0b56/ls/joyous/utils/weeks.py#L96-L99
|
train
|
linuxsoftware/ls.joyous
|
ls/joyous/utils/recurrence.py
|
Recurrence.byweekday
|
def byweekday(self):
"""
The weekdays where the recurrence will be applied. In RFC5545 this is
called BYDAY, but is renamed by dateutil to avoid ambiguity.
"""
retval = []
if self.rule._byweekday:
retval += [Weekday(day) for day in self.rule._byweekday]
if self.rule._bynweekday:
retval += [Weekday(day, n) for day, n in self.rule._bynweekday]
return retval
|
python
|
def byweekday(self):
"""
The weekdays where the recurrence will be applied. In RFC5545 this is
called BYDAY, but is renamed by dateutil to avoid ambiguity.
"""
retval = []
if self.rule._byweekday:
retval += [Weekday(day) for day in self.rule._byweekday]
if self.rule._bynweekday:
retval += [Weekday(day, n) for day, n in self.rule._bynweekday]
return retval
|
[
"def",
"byweekday",
"(",
"self",
")",
":",
"retval",
"=",
"[",
"]",
"if",
"self",
".",
"rule",
".",
"_byweekday",
":",
"retval",
"+=",
"[",
"Weekday",
"(",
"day",
")",
"for",
"day",
"in",
"self",
".",
"rule",
".",
"_byweekday",
"]",
"if",
"self",
".",
"rule",
".",
"_bynweekday",
":",
"retval",
"+=",
"[",
"Weekday",
"(",
"day",
",",
"n",
")",
"for",
"day",
",",
"n",
"in",
"self",
".",
"rule",
".",
"_bynweekday",
"]",
"return",
"retval"
] |
The weekdays where the recurrence will be applied. In RFC5545 this is
called BYDAY, but is renamed by dateutil to avoid ambiguity.
|
[
"The",
"weekdays",
"where",
"the",
"recurrence",
"will",
"be",
"applied",
".",
"In",
"RFC5545",
"this",
"is",
"called",
"BYDAY",
"but",
"is",
"renamed",
"by",
"dateutil",
"to",
"avoid",
"ambiguity",
"."
] |
316283140ca5171a68ad3170a5964fdc89be0b56
|
https://github.com/linuxsoftware/ls.joyous/blob/316283140ca5171a68ad3170a5964fdc89be0b56/ls/joyous/utils/recurrence.py#L151-L161
|
train
|
linuxsoftware/ls.joyous
|
ls/joyous/utils/recurrence.py
|
Recurrence.bymonthday
|
def bymonthday(self):
"""
The month days where the recurrence will be applied.
"""
retval = []
if self.rule._bymonthday:
retval += self.rule._bymonthday
if self.rule._bynmonthday:
retval += self.rule._bynmonthday
return retval
|
python
|
def bymonthday(self):
"""
The month days where the recurrence will be applied.
"""
retval = []
if self.rule._bymonthday:
retval += self.rule._bymonthday
if self.rule._bynmonthday:
retval += self.rule._bynmonthday
return retval
|
[
"def",
"bymonthday",
"(",
"self",
")",
":",
"retval",
"=",
"[",
"]",
"if",
"self",
".",
"rule",
".",
"_bymonthday",
":",
"retval",
"+=",
"self",
".",
"rule",
".",
"_bymonthday",
"if",
"self",
".",
"rule",
".",
"_bynmonthday",
":",
"retval",
"+=",
"self",
".",
"rule",
".",
"_bynmonthday",
"return",
"retval"
] |
The month days where the recurrence will be applied.
|
[
"The",
"month",
"days",
"where",
"the",
"recurrence",
"will",
"be",
"applied",
"."
] |
316283140ca5171a68ad3170a5964fdc89be0b56
|
https://github.com/linuxsoftware/ls.joyous/blob/316283140ca5171a68ad3170a5964fdc89be0b56/ls/joyous/utils/recurrence.py#L164-L173
|
train
|
linuxsoftware/ls.joyous
|
ls/joyous/models/calendar.py
|
CalendarPage.routeDefault
|
def routeDefault(self, request, year=None):
"""Route a request to the default calendar view."""
eventsView = request.GET.get('view', self.default_view)
if eventsView in ("L", "list"):
return self.serveUpcoming(request)
elif eventsView in ("W", "weekly"):
return self.serveWeek(request, year)
else:
return self.serveMonth(request, year)
|
python
|
def routeDefault(self, request, year=None):
"""Route a request to the default calendar view."""
eventsView = request.GET.get('view', self.default_view)
if eventsView in ("L", "list"):
return self.serveUpcoming(request)
elif eventsView in ("W", "weekly"):
return self.serveWeek(request, year)
else:
return self.serveMonth(request, year)
|
[
"def",
"routeDefault",
"(",
"self",
",",
"request",
",",
"year",
"=",
"None",
")",
":",
"eventsView",
"=",
"request",
".",
"GET",
".",
"get",
"(",
"'view'",
",",
"self",
".",
"default_view",
")",
"if",
"eventsView",
"in",
"(",
"\"L\"",
",",
"\"list\"",
")",
":",
"return",
"self",
".",
"serveUpcoming",
"(",
"request",
")",
"elif",
"eventsView",
"in",
"(",
"\"W\"",
",",
"\"weekly\"",
")",
":",
"return",
"self",
".",
"serveWeek",
"(",
"request",
",",
"year",
")",
"else",
":",
"return",
"self",
".",
"serveMonth",
"(",
"request",
",",
"year",
")"
] |
Route a request to the default calendar view.
|
[
"Route",
"a",
"request",
"to",
"the",
"default",
"calendar",
"view",
"."
] |
316283140ca5171a68ad3170a5964fdc89be0b56
|
https://github.com/linuxsoftware/ls.joyous/blob/316283140ca5171a68ad3170a5964fdc89be0b56/ls/joyous/models/calendar.py#L148-L156
|
train
|
linuxsoftware/ls.joyous
|
ls/joyous/models/calendar.py
|
CalendarPage.routeByMonthAbbr
|
def routeByMonthAbbr(self, request, year, monthAbbr):
"""Route a request with a month abbreviation to the monthly view."""
month = (DatePictures['Mon'].index(monthAbbr.lower()) // 4) + 1
return self.serveMonth(request, year, month)
|
python
|
def routeByMonthAbbr(self, request, year, monthAbbr):
"""Route a request with a month abbreviation to the monthly view."""
month = (DatePictures['Mon'].index(monthAbbr.lower()) // 4) + 1
return self.serveMonth(request, year, month)
|
[
"def",
"routeByMonthAbbr",
"(",
"self",
",",
"request",
",",
"year",
",",
"monthAbbr",
")",
":",
"month",
"=",
"(",
"DatePictures",
"[",
"'Mon'",
"]",
".",
"index",
"(",
"monthAbbr",
".",
"lower",
"(",
")",
")",
"//",
"4",
")",
"+",
"1",
"return",
"self",
".",
"serveMonth",
"(",
"request",
",",
"year",
",",
"month",
")"
] |
Route a request with a month abbreviation to the monthly view.
|
[
"Route",
"a",
"request",
"with",
"a",
"month",
"abbreviation",
"to",
"the",
"monthly",
"view",
"."
] |
316283140ca5171a68ad3170a5964fdc89be0b56
|
https://github.com/linuxsoftware/ls.joyous/blob/316283140ca5171a68ad3170a5964fdc89be0b56/ls/joyous/models/calendar.py#L159-L162
|
train
|
linuxsoftware/ls.joyous
|
ls/joyous/models/calendar.py
|
CalendarPage.serveMonth
|
def serveMonth(self, request, year=None, month=None):
"""Monthly calendar view."""
myurl = self.get_url(request)
def myUrl(urlYear, urlMonth):
if 1900 <= urlYear <= 2099:
return myurl + self.reverse_subpage('serveMonth',
args=[urlYear, urlMonth])
today = timezone.localdate()
if year is None: year = today.year
if month is None: month = today.month
year = int(year)
month = int(month)
if year == today.year and month == today.month:
weekNum = gregorian_to_week_date(today)[1]
else:
weekNum = gregorian_to_week_date(dt.date(year, month, 7))[1]
weeklyUrl = myurl + self.reverse_subpage('serveWeek',
args=[year, weekNum])
listUrl = myurl + self.reverse_subpage('serveUpcoming')
prevMonth = month - 1
prevMonthYear = year
if prevMonth == 0:
prevMonth = 12
prevMonthYear -= 1
nextMonth = month + 1
nextMonthYear = year
if nextMonth == 13:
nextMonth = 1
nextMonthYear += 1
# TODO Consider changing to a TemplateResponse
# https://stackoverflow.com/questions/38838601
return render(request, "joyous/calendar_month.html",
{'self': self,
'page': self,
'version': __version__,
'year': year,
'month': month,
'today': today,
'yesterday': today - dt.timedelta(1),
'lastweek': today - dt.timedelta(7),
'prevMonthUrl': myUrl(prevMonthYear, prevMonth),
'nextMonthUrl': myUrl(nextMonthYear, nextMonth),
'prevYearUrl': myUrl(year - 1, month),
'nextYearUrl': myUrl(year + 1, month),
'weeklyUrl': weeklyUrl,
'listUrl': listUrl,
'thisMonthUrl': myUrl(today.year, today.month),
'monthName': MONTH_NAMES[month],
'weekdayAbbr': weekday_abbr,
'events': self._getEventsByWeek(request, year, month)})
|
python
|
def serveMonth(self, request, year=None, month=None):
"""Monthly calendar view."""
myurl = self.get_url(request)
def myUrl(urlYear, urlMonth):
if 1900 <= urlYear <= 2099:
return myurl + self.reverse_subpage('serveMonth',
args=[urlYear, urlMonth])
today = timezone.localdate()
if year is None: year = today.year
if month is None: month = today.month
year = int(year)
month = int(month)
if year == today.year and month == today.month:
weekNum = gregorian_to_week_date(today)[1]
else:
weekNum = gregorian_to_week_date(dt.date(year, month, 7))[1]
weeklyUrl = myurl + self.reverse_subpage('serveWeek',
args=[year, weekNum])
listUrl = myurl + self.reverse_subpage('serveUpcoming')
prevMonth = month - 1
prevMonthYear = year
if prevMonth == 0:
prevMonth = 12
prevMonthYear -= 1
nextMonth = month + 1
nextMonthYear = year
if nextMonth == 13:
nextMonth = 1
nextMonthYear += 1
# TODO Consider changing to a TemplateResponse
# https://stackoverflow.com/questions/38838601
return render(request, "joyous/calendar_month.html",
{'self': self,
'page': self,
'version': __version__,
'year': year,
'month': month,
'today': today,
'yesterday': today - dt.timedelta(1),
'lastweek': today - dt.timedelta(7),
'prevMonthUrl': myUrl(prevMonthYear, prevMonth),
'nextMonthUrl': myUrl(nextMonthYear, nextMonth),
'prevYearUrl': myUrl(year - 1, month),
'nextYearUrl': myUrl(year + 1, month),
'weeklyUrl': weeklyUrl,
'listUrl': listUrl,
'thisMonthUrl': myUrl(today.year, today.month),
'monthName': MONTH_NAMES[month],
'weekdayAbbr': weekday_abbr,
'events': self._getEventsByWeek(request, year, month)})
|
[
"def",
"serveMonth",
"(",
"self",
",",
"request",
",",
"year",
"=",
"None",
",",
"month",
"=",
"None",
")",
":",
"myurl",
"=",
"self",
".",
"get_url",
"(",
"request",
")",
"def",
"myUrl",
"(",
"urlYear",
",",
"urlMonth",
")",
":",
"if",
"1900",
"<=",
"urlYear",
"<=",
"2099",
":",
"return",
"myurl",
"+",
"self",
".",
"reverse_subpage",
"(",
"'serveMonth'",
",",
"args",
"=",
"[",
"urlYear",
",",
"urlMonth",
"]",
")",
"today",
"=",
"timezone",
".",
"localdate",
"(",
")",
"if",
"year",
"is",
"None",
":",
"year",
"=",
"today",
".",
"year",
"if",
"month",
"is",
"None",
":",
"month",
"=",
"today",
".",
"month",
"year",
"=",
"int",
"(",
"year",
")",
"month",
"=",
"int",
"(",
"month",
")",
"if",
"year",
"==",
"today",
".",
"year",
"and",
"month",
"==",
"today",
".",
"month",
":",
"weekNum",
"=",
"gregorian_to_week_date",
"(",
"today",
")",
"[",
"1",
"]",
"else",
":",
"weekNum",
"=",
"gregorian_to_week_date",
"(",
"dt",
".",
"date",
"(",
"year",
",",
"month",
",",
"7",
")",
")",
"[",
"1",
"]",
"weeklyUrl",
"=",
"myurl",
"+",
"self",
".",
"reverse_subpage",
"(",
"'serveWeek'",
",",
"args",
"=",
"[",
"year",
",",
"weekNum",
"]",
")",
"listUrl",
"=",
"myurl",
"+",
"self",
".",
"reverse_subpage",
"(",
"'serveUpcoming'",
")",
"prevMonth",
"=",
"month",
"-",
"1",
"prevMonthYear",
"=",
"year",
"if",
"prevMonth",
"==",
"0",
":",
"prevMonth",
"=",
"12",
"prevMonthYear",
"-=",
"1",
"nextMonth",
"=",
"month",
"+",
"1",
"nextMonthYear",
"=",
"year",
"if",
"nextMonth",
"==",
"13",
":",
"nextMonth",
"=",
"1",
"nextMonthYear",
"+=",
"1",
"# TODO Consider changing to a TemplateResponse",
"# https://stackoverflow.com/questions/38838601",
"return",
"render",
"(",
"request",
",",
"\"joyous/calendar_month.html\"",
",",
"{",
"'self'",
":",
"self",
",",
"'page'",
":",
"self",
",",
"'version'",
":",
"__version__",
",",
"'year'",
":",
"year",
",",
"'month'",
":",
"month",
",",
"'today'",
":",
"today",
",",
"'yesterday'",
":",
"today",
"-",
"dt",
".",
"timedelta",
"(",
"1",
")",
",",
"'lastweek'",
":",
"today",
"-",
"dt",
".",
"timedelta",
"(",
"7",
")",
",",
"'prevMonthUrl'",
":",
"myUrl",
"(",
"prevMonthYear",
",",
"prevMonth",
")",
",",
"'nextMonthUrl'",
":",
"myUrl",
"(",
"nextMonthYear",
",",
"nextMonth",
")",
",",
"'prevYearUrl'",
":",
"myUrl",
"(",
"year",
"-",
"1",
",",
"month",
")",
",",
"'nextYearUrl'",
":",
"myUrl",
"(",
"year",
"+",
"1",
",",
"month",
")",
",",
"'weeklyUrl'",
":",
"weeklyUrl",
",",
"'listUrl'",
":",
"listUrl",
",",
"'thisMonthUrl'",
":",
"myUrl",
"(",
"today",
".",
"year",
",",
"today",
".",
"month",
")",
",",
"'monthName'",
":",
"MONTH_NAMES",
"[",
"month",
"]",
",",
"'weekdayAbbr'",
":",
"weekday_abbr",
",",
"'events'",
":",
"self",
".",
"_getEventsByWeek",
"(",
"request",
",",
"year",
",",
"month",
")",
"}",
")"
] |
Monthly calendar view.
|
[
"Monthly",
"calendar",
"view",
"."
] |
316283140ca5171a68ad3170a5964fdc89be0b56
|
https://github.com/linuxsoftware/ls.joyous/blob/316283140ca5171a68ad3170a5964fdc89be0b56/ls/joyous/models/calendar.py#L166-L219
|
train
|
linuxsoftware/ls.joyous
|
ls/joyous/models/calendar.py
|
CalendarPage.serveWeek
|
def serveWeek(self, request, year=None, week=None):
"""Weekly calendar view."""
myurl = self.get_url(request)
def myUrl(urlYear, urlWeek):
if (urlYear < 1900 or
urlYear > 2099 or
urlYear == 2099 and urlWeek == 53):
return None
if urlWeek == 53 and num_weeks_in_year(urlYear) == 52:
urlWeek = 52
return myurl + self.reverse_subpage('serveWeek',
args=[urlYear, urlWeek])
today = timezone.localdate()
thisYear, thisWeekNum, dow = gregorian_to_week_date(today)
if year is None: year = thisYear
if week is None: week = thisWeekNum
year = int(year)
week = int(week)
firstDay, lastDay, prevYearNumWeeks, yearNumWeeks = week_info(year, week)
if week == 53 and yearNumWeeks == 52:
raise Http404("Only 52 weeks in {}".format(year))
eventsInWeek = self._getEventsByDay(request, firstDay, lastDay)
if firstDay.year >= 1900:
monthlyUrl = myurl + self.reverse_subpage('serveMonth',
args=[firstDay.year, firstDay.month])
else:
monthlyUrl = myurl + self.reverse_subpage('serveMonth', args=[1900, 1])
listUrl = myurl + self.reverse_subpage('serveUpcoming')
prevWeek = week - 1
prevWeekYear = year
if prevWeek == 0:
prevWeek = prevYearNumWeeks
prevWeekYear -= 1
nextWeek = week + 1
nextWeekYear = year
if nextWeek > yearNumWeeks:
nextWeek = 1
nextWeekYear += 1
# TODO Consider changing to a TemplateResponse
# https://stackoverflow.com/questions/38838601
return render(request, "joyous/calendar_week.html",
{'self': self,
'page': self,
'version': __version__,
'year': year,
'week': week,
'today': today,
'yesterday': today - dt.timedelta(1),
'prevWeekUrl': myUrl(prevWeekYear, prevWeek),
'nextWeekUrl': myUrl(nextWeekYear, nextWeek),
'prevYearUrl': myUrl(year - 1, week),
'nextYearUrl': myUrl(year + 1, week),
'thisWeekUrl': myUrl(thisYear, thisWeekNum),
'monthlyUrl': monthlyUrl,
'listUrl': listUrl,
'weekName': _("Week {weekNum}").format(weekNum=week),
'weekdayAbbr': weekday_abbr,
'events': [eventsInWeek]})
|
python
|
def serveWeek(self, request, year=None, week=None):
"""Weekly calendar view."""
myurl = self.get_url(request)
def myUrl(urlYear, urlWeek):
if (urlYear < 1900 or
urlYear > 2099 or
urlYear == 2099 and urlWeek == 53):
return None
if urlWeek == 53 and num_weeks_in_year(urlYear) == 52:
urlWeek = 52
return myurl + self.reverse_subpage('serveWeek',
args=[urlYear, urlWeek])
today = timezone.localdate()
thisYear, thisWeekNum, dow = gregorian_to_week_date(today)
if year is None: year = thisYear
if week is None: week = thisWeekNum
year = int(year)
week = int(week)
firstDay, lastDay, prevYearNumWeeks, yearNumWeeks = week_info(year, week)
if week == 53 and yearNumWeeks == 52:
raise Http404("Only 52 weeks in {}".format(year))
eventsInWeek = self._getEventsByDay(request, firstDay, lastDay)
if firstDay.year >= 1900:
monthlyUrl = myurl + self.reverse_subpage('serveMonth',
args=[firstDay.year, firstDay.month])
else:
monthlyUrl = myurl + self.reverse_subpage('serveMonth', args=[1900, 1])
listUrl = myurl + self.reverse_subpage('serveUpcoming')
prevWeek = week - 1
prevWeekYear = year
if prevWeek == 0:
prevWeek = prevYearNumWeeks
prevWeekYear -= 1
nextWeek = week + 1
nextWeekYear = year
if nextWeek > yearNumWeeks:
nextWeek = 1
nextWeekYear += 1
# TODO Consider changing to a TemplateResponse
# https://stackoverflow.com/questions/38838601
return render(request, "joyous/calendar_week.html",
{'self': self,
'page': self,
'version': __version__,
'year': year,
'week': week,
'today': today,
'yesterday': today - dt.timedelta(1),
'prevWeekUrl': myUrl(prevWeekYear, prevWeek),
'nextWeekUrl': myUrl(nextWeekYear, nextWeek),
'prevYearUrl': myUrl(year - 1, week),
'nextYearUrl': myUrl(year + 1, week),
'thisWeekUrl': myUrl(thisYear, thisWeekNum),
'monthlyUrl': monthlyUrl,
'listUrl': listUrl,
'weekName': _("Week {weekNum}").format(weekNum=week),
'weekdayAbbr': weekday_abbr,
'events': [eventsInWeek]})
|
[
"def",
"serveWeek",
"(",
"self",
",",
"request",
",",
"year",
"=",
"None",
",",
"week",
"=",
"None",
")",
":",
"myurl",
"=",
"self",
".",
"get_url",
"(",
"request",
")",
"def",
"myUrl",
"(",
"urlYear",
",",
"urlWeek",
")",
":",
"if",
"(",
"urlYear",
"<",
"1900",
"or",
"urlYear",
">",
"2099",
"or",
"urlYear",
"==",
"2099",
"and",
"urlWeek",
"==",
"53",
")",
":",
"return",
"None",
"if",
"urlWeek",
"==",
"53",
"and",
"num_weeks_in_year",
"(",
"urlYear",
")",
"==",
"52",
":",
"urlWeek",
"=",
"52",
"return",
"myurl",
"+",
"self",
".",
"reverse_subpage",
"(",
"'serveWeek'",
",",
"args",
"=",
"[",
"urlYear",
",",
"urlWeek",
"]",
")",
"today",
"=",
"timezone",
".",
"localdate",
"(",
")",
"thisYear",
",",
"thisWeekNum",
",",
"dow",
"=",
"gregorian_to_week_date",
"(",
"today",
")",
"if",
"year",
"is",
"None",
":",
"year",
"=",
"thisYear",
"if",
"week",
"is",
"None",
":",
"week",
"=",
"thisWeekNum",
"year",
"=",
"int",
"(",
"year",
")",
"week",
"=",
"int",
"(",
"week",
")",
"firstDay",
",",
"lastDay",
",",
"prevYearNumWeeks",
",",
"yearNumWeeks",
"=",
"week_info",
"(",
"year",
",",
"week",
")",
"if",
"week",
"==",
"53",
"and",
"yearNumWeeks",
"==",
"52",
":",
"raise",
"Http404",
"(",
"\"Only 52 weeks in {}\"",
".",
"format",
"(",
"year",
")",
")",
"eventsInWeek",
"=",
"self",
".",
"_getEventsByDay",
"(",
"request",
",",
"firstDay",
",",
"lastDay",
")",
"if",
"firstDay",
".",
"year",
">=",
"1900",
":",
"monthlyUrl",
"=",
"myurl",
"+",
"self",
".",
"reverse_subpage",
"(",
"'serveMonth'",
",",
"args",
"=",
"[",
"firstDay",
".",
"year",
",",
"firstDay",
".",
"month",
"]",
")",
"else",
":",
"monthlyUrl",
"=",
"myurl",
"+",
"self",
".",
"reverse_subpage",
"(",
"'serveMonth'",
",",
"args",
"=",
"[",
"1900",
",",
"1",
"]",
")",
"listUrl",
"=",
"myurl",
"+",
"self",
".",
"reverse_subpage",
"(",
"'serveUpcoming'",
")",
"prevWeek",
"=",
"week",
"-",
"1",
"prevWeekYear",
"=",
"year",
"if",
"prevWeek",
"==",
"0",
":",
"prevWeek",
"=",
"prevYearNumWeeks",
"prevWeekYear",
"-=",
"1",
"nextWeek",
"=",
"week",
"+",
"1",
"nextWeekYear",
"=",
"year",
"if",
"nextWeek",
">",
"yearNumWeeks",
":",
"nextWeek",
"=",
"1",
"nextWeekYear",
"+=",
"1",
"# TODO Consider changing to a TemplateResponse",
"# https://stackoverflow.com/questions/38838601",
"return",
"render",
"(",
"request",
",",
"\"joyous/calendar_week.html\"",
",",
"{",
"'self'",
":",
"self",
",",
"'page'",
":",
"self",
",",
"'version'",
":",
"__version__",
",",
"'year'",
":",
"year",
",",
"'week'",
":",
"week",
",",
"'today'",
":",
"today",
",",
"'yesterday'",
":",
"today",
"-",
"dt",
".",
"timedelta",
"(",
"1",
")",
",",
"'prevWeekUrl'",
":",
"myUrl",
"(",
"prevWeekYear",
",",
"prevWeek",
")",
",",
"'nextWeekUrl'",
":",
"myUrl",
"(",
"nextWeekYear",
",",
"nextWeek",
")",
",",
"'prevYearUrl'",
":",
"myUrl",
"(",
"year",
"-",
"1",
",",
"week",
")",
",",
"'nextYearUrl'",
":",
"myUrl",
"(",
"year",
"+",
"1",
",",
"week",
")",
",",
"'thisWeekUrl'",
":",
"myUrl",
"(",
"thisYear",
",",
"thisWeekNum",
")",
",",
"'monthlyUrl'",
":",
"monthlyUrl",
",",
"'listUrl'",
":",
"listUrl",
",",
"'weekName'",
":",
"_",
"(",
"\"Week {weekNum}\"",
")",
".",
"format",
"(",
"weekNum",
"=",
"week",
")",
",",
"'weekdayAbbr'",
":",
"weekday_abbr",
",",
"'events'",
":",
"[",
"eventsInWeek",
"]",
"}",
")"
] |
Weekly calendar view.
|
[
"Weekly",
"calendar",
"view",
"."
] |
316283140ca5171a68ad3170a5964fdc89be0b56
|
https://github.com/linuxsoftware/ls.joyous/blob/316283140ca5171a68ad3170a5964fdc89be0b56/ls/joyous/models/calendar.py#L223-L285
|
train
|
linuxsoftware/ls.joyous
|
ls/joyous/models/calendar.py
|
CalendarPage.serveDay
|
def serveDay(self, request, year=None, month=None, dom=None):
"""The events of the day list view."""
myurl = self.get_url(request)
today = timezone.localdate()
if year is None: year = today.year
if month is None: month = today.month
if dom is None: dom = today.day
year = int(year)
month = int(month)
dom = int(dom)
day = dt.date(year, month, dom)
eventsOnDay = self._getEventsOnDay(request, day)
if len(eventsOnDay.all_events) == 1:
event = eventsOnDay.all_events[0].page
return redirect(event.get_url(request))
monthlyUrl = myurl + self.reverse_subpage('serveMonth',
args=[year, month])
weekNum = gregorian_to_week_date(today)[1]
weeklyUrl = myurl + self.reverse_subpage('serveWeek',
args=[year, weekNum])
listUrl = myurl + self.reverse_subpage('serveUpcoming')
# TODO Consider changing to a TemplateResponse
# https://stackoverflow.com/questions/38838601
return render(request, "joyous/calendar_list_day.html",
{'self': self,
'page': self,
'version': __version__,
'year': year,
'month': month,
'dom': dom,
'day': day,
'monthlyUrl': monthlyUrl,
'weeklyUrl': weeklyUrl,
'listUrl': listUrl,
'monthName': MONTH_NAMES[month],
'weekdayName': WEEKDAY_NAMES[day.weekday()],
'events': eventsOnDay})
|
python
|
def serveDay(self, request, year=None, month=None, dom=None):
"""The events of the day list view."""
myurl = self.get_url(request)
today = timezone.localdate()
if year is None: year = today.year
if month is None: month = today.month
if dom is None: dom = today.day
year = int(year)
month = int(month)
dom = int(dom)
day = dt.date(year, month, dom)
eventsOnDay = self._getEventsOnDay(request, day)
if len(eventsOnDay.all_events) == 1:
event = eventsOnDay.all_events[0].page
return redirect(event.get_url(request))
monthlyUrl = myurl + self.reverse_subpage('serveMonth',
args=[year, month])
weekNum = gregorian_to_week_date(today)[1]
weeklyUrl = myurl + self.reverse_subpage('serveWeek',
args=[year, weekNum])
listUrl = myurl + self.reverse_subpage('serveUpcoming')
# TODO Consider changing to a TemplateResponse
# https://stackoverflow.com/questions/38838601
return render(request, "joyous/calendar_list_day.html",
{'self': self,
'page': self,
'version': __version__,
'year': year,
'month': month,
'dom': dom,
'day': day,
'monthlyUrl': monthlyUrl,
'weeklyUrl': weeklyUrl,
'listUrl': listUrl,
'monthName': MONTH_NAMES[month],
'weekdayName': WEEKDAY_NAMES[day.weekday()],
'events': eventsOnDay})
|
[
"def",
"serveDay",
"(",
"self",
",",
"request",
",",
"year",
"=",
"None",
",",
"month",
"=",
"None",
",",
"dom",
"=",
"None",
")",
":",
"myurl",
"=",
"self",
".",
"get_url",
"(",
"request",
")",
"today",
"=",
"timezone",
".",
"localdate",
"(",
")",
"if",
"year",
"is",
"None",
":",
"year",
"=",
"today",
".",
"year",
"if",
"month",
"is",
"None",
":",
"month",
"=",
"today",
".",
"month",
"if",
"dom",
"is",
"None",
":",
"dom",
"=",
"today",
".",
"day",
"year",
"=",
"int",
"(",
"year",
")",
"month",
"=",
"int",
"(",
"month",
")",
"dom",
"=",
"int",
"(",
"dom",
")",
"day",
"=",
"dt",
".",
"date",
"(",
"year",
",",
"month",
",",
"dom",
")",
"eventsOnDay",
"=",
"self",
".",
"_getEventsOnDay",
"(",
"request",
",",
"day",
")",
"if",
"len",
"(",
"eventsOnDay",
".",
"all_events",
")",
"==",
"1",
":",
"event",
"=",
"eventsOnDay",
".",
"all_events",
"[",
"0",
"]",
".",
"page",
"return",
"redirect",
"(",
"event",
".",
"get_url",
"(",
"request",
")",
")",
"monthlyUrl",
"=",
"myurl",
"+",
"self",
".",
"reverse_subpage",
"(",
"'serveMonth'",
",",
"args",
"=",
"[",
"year",
",",
"month",
"]",
")",
"weekNum",
"=",
"gregorian_to_week_date",
"(",
"today",
")",
"[",
"1",
"]",
"weeklyUrl",
"=",
"myurl",
"+",
"self",
".",
"reverse_subpage",
"(",
"'serveWeek'",
",",
"args",
"=",
"[",
"year",
",",
"weekNum",
"]",
")",
"listUrl",
"=",
"myurl",
"+",
"self",
".",
"reverse_subpage",
"(",
"'serveUpcoming'",
")",
"# TODO Consider changing to a TemplateResponse",
"# https://stackoverflow.com/questions/38838601",
"return",
"render",
"(",
"request",
",",
"\"joyous/calendar_list_day.html\"",
",",
"{",
"'self'",
":",
"self",
",",
"'page'",
":",
"self",
",",
"'version'",
":",
"__version__",
",",
"'year'",
":",
"year",
",",
"'month'",
":",
"month",
",",
"'dom'",
":",
"dom",
",",
"'day'",
":",
"day",
",",
"'monthlyUrl'",
":",
"monthlyUrl",
",",
"'weeklyUrl'",
":",
"weeklyUrl",
",",
"'listUrl'",
":",
"listUrl",
",",
"'monthName'",
":",
"MONTH_NAMES",
"[",
"month",
"]",
",",
"'weekdayName'",
":",
"WEEKDAY_NAMES",
"[",
"day",
".",
"weekday",
"(",
")",
"]",
",",
"'events'",
":",
"eventsOnDay",
"}",
")"
] |
The events of the day list view.
|
[
"The",
"events",
"of",
"the",
"day",
"list",
"view",
"."
] |
316283140ca5171a68ad3170a5964fdc89be0b56
|
https://github.com/linuxsoftware/ls.joyous/blob/316283140ca5171a68ad3170a5964fdc89be0b56/ls/joyous/models/calendar.py#L289-L328
|
train
|
linuxsoftware/ls.joyous
|
ls/joyous/models/calendar.py
|
CalendarPage.serveUpcoming
|
def serveUpcoming(self, request):
"""Upcoming events list view."""
myurl = self.get_url(request)
today = timezone.localdate()
monthlyUrl = myurl + self.reverse_subpage('serveMonth',
args=[today.year, today.month])
weekNum = gregorian_to_week_date(today)[1]
weeklyUrl = myurl + self.reverse_subpage('serveWeek',
args=[today.year, weekNum])
listUrl = myurl + self.reverse_subpage('servePast')
upcomingEvents = self._getUpcomingEvents(request)
paginator = Paginator(upcomingEvents, self.EventsPerPage)
try:
eventsPage = paginator.page(request.GET.get('page'))
except PageNotAnInteger:
eventsPage = paginator.page(1)
except EmptyPage:
eventsPage = paginator.page(paginator.num_pages)
# TODO Consider changing to a TemplateResponse
# https://stackoverflow.com/questions/38838601
return render(request, "joyous/calendar_list_upcoming.html",
{'self': self,
'page': self,
'version': __version__,
'today': today,
'weeklyUrl': weeklyUrl,
'monthlyUrl': monthlyUrl,
'listUrl': listUrl,
'events': eventsPage})
|
python
|
def serveUpcoming(self, request):
"""Upcoming events list view."""
myurl = self.get_url(request)
today = timezone.localdate()
monthlyUrl = myurl + self.reverse_subpage('serveMonth',
args=[today.year, today.month])
weekNum = gregorian_to_week_date(today)[1]
weeklyUrl = myurl + self.reverse_subpage('serveWeek',
args=[today.year, weekNum])
listUrl = myurl + self.reverse_subpage('servePast')
upcomingEvents = self._getUpcomingEvents(request)
paginator = Paginator(upcomingEvents, self.EventsPerPage)
try:
eventsPage = paginator.page(request.GET.get('page'))
except PageNotAnInteger:
eventsPage = paginator.page(1)
except EmptyPage:
eventsPage = paginator.page(paginator.num_pages)
# TODO Consider changing to a TemplateResponse
# https://stackoverflow.com/questions/38838601
return render(request, "joyous/calendar_list_upcoming.html",
{'self': self,
'page': self,
'version': __version__,
'today': today,
'weeklyUrl': weeklyUrl,
'monthlyUrl': monthlyUrl,
'listUrl': listUrl,
'events': eventsPage})
|
[
"def",
"serveUpcoming",
"(",
"self",
",",
"request",
")",
":",
"myurl",
"=",
"self",
".",
"get_url",
"(",
"request",
")",
"today",
"=",
"timezone",
".",
"localdate",
"(",
")",
"monthlyUrl",
"=",
"myurl",
"+",
"self",
".",
"reverse_subpage",
"(",
"'serveMonth'",
",",
"args",
"=",
"[",
"today",
".",
"year",
",",
"today",
".",
"month",
"]",
")",
"weekNum",
"=",
"gregorian_to_week_date",
"(",
"today",
")",
"[",
"1",
"]",
"weeklyUrl",
"=",
"myurl",
"+",
"self",
".",
"reverse_subpage",
"(",
"'serveWeek'",
",",
"args",
"=",
"[",
"today",
".",
"year",
",",
"weekNum",
"]",
")",
"listUrl",
"=",
"myurl",
"+",
"self",
".",
"reverse_subpage",
"(",
"'servePast'",
")",
"upcomingEvents",
"=",
"self",
".",
"_getUpcomingEvents",
"(",
"request",
")",
"paginator",
"=",
"Paginator",
"(",
"upcomingEvents",
",",
"self",
".",
"EventsPerPage",
")",
"try",
":",
"eventsPage",
"=",
"paginator",
".",
"page",
"(",
"request",
".",
"GET",
".",
"get",
"(",
"'page'",
")",
")",
"except",
"PageNotAnInteger",
":",
"eventsPage",
"=",
"paginator",
".",
"page",
"(",
"1",
")",
"except",
"EmptyPage",
":",
"eventsPage",
"=",
"paginator",
".",
"page",
"(",
"paginator",
".",
"num_pages",
")",
"# TODO Consider changing to a TemplateResponse",
"# https://stackoverflow.com/questions/38838601",
"return",
"render",
"(",
"request",
",",
"\"joyous/calendar_list_upcoming.html\"",
",",
"{",
"'self'",
":",
"self",
",",
"'page'",
":",
"self",
",",
"'version'",
":",
"__version__",
",",
"'today'",
":",
"today",
",",
"'weeklyUrl'",
":",
"weeklyUrl",
",",
"'monthlyUrl'",
":",
"monthlyUrl",
",",
"'listUrl'",
":",
"listUrl",
",",
"'events'",
":",
"eventsPage",
"}",
")"
] |
Upcoming events list view.
|
[
"Upcoming",
"events",
"list",
"view",
"."
] |
316283140ca5171a68ad3170a5964fdc89be0b56
|
https://github.com/linuxsoftware/ls.joyous/blob/316283140ca5171a68ad3170a5964fdc89be0b56/ls/joyous/models/calendar.py#L331-L360
|
train
|
linuxsoftware/ls.joyous
|
ls/joyous/models/calendar.py
|
CalendarPage.serveMiniMonth
|
def serveMiniMonth(self, request, year=None, month=None):
"""Serve data for the MiniMonth template tag."""
if not request.is_ajax():
raise Http404("/mini/ is for ajax requests only")
today = timezone.localdate()
if year is None: year = today.year
if month is None: month = today.month
year = int(year)
month = int(month)
# TODO Consider changing to a TemplateResponse
# https://stackoverflow.com/questions/38838601
return render(request, "joyous/includes/minicalendar.html",
{'self': self,
'page': self,
'version': __version__,
'today': today,
'year': year,
'month': month,
'calendarUrl': self.get_url(request),
'monthName': MONTH_NAMES[month],
'weekdayInfo': zip(weekday_abbr, weekday_name),
'events': self._getEventsByWeek(request, year, month)})
|
python
|
def serveMiniMonth(self, request, year=None, month=None):
"""Serve data for the MiniMonth template tag."""
if not request.is_ajax():
raise Http404("/mini/ is for ajax requests only")
today = timezone.localdate()
if year is None: year = today.year
if month is None: month = today.month
year = int(year)
month = int(month)
# TODO Consider changing to a TemplateResponse
# https://stackoverflow.com/questions/38838601
return render(request, "joyous/includes/minicalendar.html",
{'self': self,
'page': self,
'version': __version__,
'today': today,
'year': year,
'month': month,
'calendarUrl': self.get_url(request),
'monthName': MONTH_NAMES[month],
'weekdayInfo': zip(weekday_abbr, weekday_name),
'events': self._getEventsByWeek(request, year, month)})
|
[
"def",
"serveMiniMonth",
"(",
"self",
",",
"request",
",",
"year",
"=",
"None",
",",
"month",
"=",
"None",
")",
":",
"if",
"not",
"request",
".",
"is_ajax",
"(",
")",
":",
"raise",
"Http404",
"(",
"\"/mini/ is for ajax requests only\"",
")",
"today",
"=",
"timezone",
".",
"localdate",
"(",
")",
"if",
"year",
"is",
"None",
":",
"year",
"=",
"today",
".",
"year",
"if",
"month",
"is",
"None",
":",
"month",
"=",
"today",
".",
"month",
"year",
"=",
"int",
"(",
"year",
")",
"month",
"=",
"int",
"(",
"month",
")",
"# TODO Consider changing to a TemplateResponse",
"# https://stackoverflow.com/questions/38838601",
"return",
"render",
"(",
"request",
",",
"\"joyous/includes/minicalendar.html\"",
",",
"{",
"'self'",
":",
"self",
",",
"'page'",
":",
"self",
",",
"'version'",
":",
"__version__",
",",
"'today'",
":",
"today",
",",
"'year'",
":",
"year",
",",
"'month'",
":",
"month",
",",
"'calendarUrl'",
":",
"self",
".",
"get_url",
"(",
"request",
")",
",",
"'monthName'",
":",
"MONTH_NAMES",
"[",
"month",
"]",
",",
"'weekdayInfo'",
":",
"zip",
"(",
"weekday_abbr",
",",
"weekday_name",
")",
",",
"'events'",
":",
"self",
".",
"_getEventsByWeek",
"(",
"request",
",",
"year",
",",
"month",
")",
"}",
")"
] |
Serve data for the MiniMonth template tag.
|
[
"Serve",
"data",
"for",
"the",
"MiniMonth",
"template",
"tag",
"."
] |
316283140ca5171a68ad3170a5964fdc89be0b56
|
https://github.com/linuxsoftware/ls.joyous/blob/316283140ca5171a68ad3170a5964fdc89be0b56/ls/joyous/models/calendar.py#L395-L418
|
train
|
linuxsoftware/ls.joyous
|
ls/joyous/models/calendar.py
|
CalendarPage._allowAnotherAt
|
def _allowAnotherAt(cls, parent):
"""You can only create one of these pages per site."""
site = parent.get_site()
if site is None:
return False
return not cls.peers().descendant_of(site.root_page).exists()
|
python
|
def _allowAnotherAt(cls, parent):
"""You can only create one of these pages per site."""
site = parent.get_site()
if site is None:
return False
return not cls.peers().descendant_of(site.root_page).exists()
|
[
"def",
"_allowAnotherAt",
"(",
"cls",
",",
"parent",
")",
":",
"site",
"=",
"parent",
".",
"get_site",
"(",
")",
"if",
"site",
"is",
"None",
":",
"return",
"False",
"return",
"not",
"cls",
".",
"peers",
"(",
")",
".",
"descendant_of",
"(",
"site",
".",
"root_page",
")",
".",
"exists",
"(",
")"
] |
You can only create one of these pages per site.
|
[
"You",
"can",
"only",
"create",
"one",
"of",
"these",
"pages",
"per",
"site",
"."
] |
316283140ca5171a68ad3170a5964fdc89be0b56
|
https://github.com/linuxsoftware/ls.joyous/blob/316283140ca5171a68ad3170a5964fdc89be0b56/ls/joyous/models/calendar.py#L425-L430
|
train
|
linuxsoftware/ls.joyous
|
ls/joyous/models/calendar.py
|
CalendarPage.peers
|
def peers(cls):
"""Return others of the same concrete type."""
contentType = ContentType.objects.get_for_model(cls)
return cls.objects.filter(content_type=contentType)
|
python
|
def peers(cls):
"""Return others of the same concrete type."""
contentType = ContentType.objects.get_for_model(cls)
return cls.objects.filter(content_type=contentType)
|
[
"def",
"peers",
"(",
"cls",
")",
":",
"contentType",
"=",
"ContentType",
".",
"objects",
".",
"get_for_model",
"(",
"cls",
")",
"return",
"cls",
".",
"objects",
".",
"filter",
"(",
"content_type",
"=",
"contentType",
")"
] |
Return others of the same concrete type.
|
[
"Return",
"others",
"of",
"the",
"same",
"concrete",
"type",
"."
] |
316283140ca5171a68ad3170a5964fdc89be0b56
|
https://github.com/linuxsoftware/ls.joyous/blob/316283140ca5171a68ad3170a5964fdc89be0b56/ls/joyous/models/calendar.py#L433-L436
|
train
|
linuxsoftware/ls.joyous
|
ls/joyous/models/calendar.py
|
CalendarPage._getEventsOnDay
|
def _getEventsOnDay(self, request, day):
"""Return all the events in this site for a given day."""
home = request.site.root_page
return getAllEventsByDay(request, day, day, home=home)[0]
|
python
|
def _getEventsOnDay(self, request, day):
"""Return all the events in this site for a given day."""
home = request.site.root_page
return getAllEventsByDay(request, day, day, home=home)[0]
|
[
"def",
"_getEventsOnDay",
"(",
"self",
",",
"request",
",",
"day",
")",
":",
"home",
"=",
"request",
".",
"site",
".",
"root_page",
"return",
"getAllEventsByDay",
"(",
"request",
",",
"day",
",",
"day",
",",
"home",
"=",
"home",
")",
"[",
"0",
"]"
] |
Return all the events in this site for a given day.
|
[
"Return",
"all",
"the",
"events",
"in",
"this",
"site",
"for",
"a",
"given",
"day",
"."
] |
316283140ca5171a68ad3170a5964fdc89be0b56
|
https://github.com/linuxsoftware/ls.joyous/blob/316283140ca5171a68ad3170a5964fdc89be0b56/ls/joyous/models/calendar.py#L438-L441
|
train
|
linuxsoftware/ls.joyous
|
ls/joyous/models/calendar.py
|
CalendarPage._getEventsByDay
|
def _getEventsByDay(self, request, firstDay, lastDay):
"""
Return the events in this site for the dates given, grouped by day.
"""
home = request.site.root_page
return getAllEventsByDay(request, firstDay, lastDay, home=home)
|
python
|
def _getEventsByDay(self, request, firstDay, lastDay):
"""
Return the events in this site for the dates given, grouped by day.
"""
home = request.site.root_page
return getAllEventsByDay(request, firstDay, lastDay, home=home)
|
[
"def",
"_getEventsByDay",
"(",
"self",
",",
"request",
",",
"firstDay",
",",
"lastDay",
")",
":",
"home",
"=",
"request",
".",
"site",
".",
"root_page",
"return",
"getAllEventsByDay",
"(",
"request",
",",
"firstDay",
",",
"lastDay",
",",
"home",
"=",
"home",
")"
] |
Return the events in this site for the dates given, grouped by day.
|
[
"Return",
"the",
"events",
"in",
"this",
"site",
"for",
"the",
"dates",
"given",
"grouped",
"by",
"day",
"."
] |
316283140ca5171a68ad3170a5964fdc89be0b56
|
https://github.com/linuxsoftware/ls.joyous/blob/316283140ca5171a68ad3170a5964fdc89be0b56/ls/joyous/models/calendar.py#L443-L448
|
train
|
linuxsoftware/ls.joyous
|
ls/joyous/models/calendar.py
|
CalendarPage._getEventsByWeek
|
def _getEventsByWeek(self, request, year, month):
"""
Return the events in this site for the given month grouped by week.
"""
home = request.site.root_page
return getAllEventsByWeek(request, year, month, home=home)
|
python
|
def _getEventsByWeek(self, request, year, month):
"""
Return the events in this site for the given month grouped by week.
"""
home = request.site.root_page
return getAllEventsByWeek(request, year, month, home=home)
|
[
"def",
"_getEventsByWeek",
"(",
"self",
",",
"request",
",",
"year",
",",
"month",
")",
":",
"home",
"=",
"request",
".",
"site",
".",
"root_page",
"return",
"getAllEventsByWeek",
"(",
"request",
",",
"year",
",",
"month",
",",
"home",
"=",
"home",
")"
] |
Return the events in this site for the given month grouped by week.
|
[
"Return",
"the",
"events",
"in",
"this",
"site",
"for",
"the",
"given",
"month",
"grouped",
"by",
"week",
"."
] |
316283140ca5171a68ad3170a5964fdc89be0b56
|
https://github.com/linuxsoftware/ls.joyous/blob/316283140ca5171a68ad3170a5964fdc89be0b56/ls/joyous/models/calendar.py#L450-L455
|
train
|
linuxsoftware/ls.joyous
|
ls/joyous/models/calendar.py
|
CalendarPage._getUpcomingEvents
|
def _getUpcomingEvents(self, request):
"""Return the upcoming events in this site."""
home = request.site.root_page
return getAllUpcomingEvents(request, home=home)
|
python
|
def _getUpcomingEvents(self, request):
"""Return the upcoming events in this site."""
home = request.site.root_page
return getAllUpcomingEvents(request, home=home)
|
[
"def",
"_getUpcomingEvents",
"(",
"self",
",",
"request",
")",
":",
"home",
"=",
"request",
".",
"site",
".",
"root_page",
"return",
"getAllUpcomingEvents",
"(",
"request",
",",
"home",
"=",
"home",
")"
] |
Return the upcoming events in this site.
|
[
"Return",
"the",
"upcoming",
"events",
"in",
"this",
"site",
"."
] |
316283140ca5171a68ad3170a5964fdc89be0b56
|
https://github.com/linuxsoftware/ls.joyous/blob/316283140ca5171a68ad3170a5964fdc89be0b56/ls/joyous/models/calendar.py#L457-L460
|
train
|
linuxsoftware/ls.joyous
|
ls/joyous/models/calendar.py
|
CalendarPage._getPastEvents
|
def _getPastEvents(self, request):
"""Return the past events in this site."""
home = request.site.root_page
return getAllPastEvents(request, home=home)
|
python
|
def _getPastEvents(self, request):
"""Return the past events in this site."""
home = request.site.root_page
return getAllPastEvents(request, home=home)
|
[
"def",
"_getPastEvents",
"(",
"self",
",",
"request",
")",
":",
"home",
"=",
"request",
".",
"site",
".",
"root_page",
"return",
"getAllPastEvents",
"(",
"request",
",",
"home",
"=",
"home",
")"
] |
Return the past events in this site.
|
[
"Return",
"the",
"past",
"events",
"in",
"this",
"site",
"."
] |
316283140ca5171a68ad3170a5964fdc89be0b56
|
https://github.com/linuxsoftware/ls.joyous/blob/316283140ca5171a68ad3170a5964fdc89be0b56/ls/joyous/models/calendar.py#L462-L465
|
train
|
linuxsoftware/ls.joyous
|
ls/joyous/models/calendar.py
|
CalendarPage._getEventFromUid
|
def _getEventFromUid(self, request, uid):
"""Try and find an event with the given UID in this site."""
event = getEventFromUid(request, uid) # might raise ObjectDoesNotExist
home = request.site.root_page
if event.get_ancestors().filter(id=home.id).exists():
# only return event if it is in the same site
return event
|
python
|
def _getEventFromUid(self, request, uid):
"""Try and find an event with the given UID in this site."""
event = getEventFromUid(request, uid) # might raise ObjectDoesNotExist
home = request.site.root_page
if event.get_ancestors().filter(id=home.id).exists():
# only return event if it is in the same site
return event
|
[
"def",
"_getEventFromUid",
"(",
"self",
",",
"request",
",",
"uid",
")",
":",
"event",
"=",
"getEventFromUid",
"(",
"request",
",",
"uid",
")",
"# might raise ObjectDoesNotExist",
"home",
"=",
"request",
".",
"site",
".",
"root_page",
"if",
"event",
".",
"get_ancestors",
"(",
")",
".",
"filter",
"(",
"id",
"=",
"home",
".",
"id",
")",
".",
"exists",
"(",
")",
":",
"# only return event if it is in the same site",
"return",
"event"
] |
Try and find an event with the given UID in this site.
|
[
"Try",
"and",
"find",
"an",
"event",
"with",
"the",
"given",
"UID",
"in",
"this",
"site",
"."
] |
316283140ca5171a68ad3170a5964fdc89be0b56
|
https://github.com/linuxsoftware/ls.joyous/blob/316283140ca5171a68ad3170a5964fdc89be0b56/ls/joyous/models/calendar.py#L467-L473
|
train
|
linuxsoftware/ls.joyous
|
ls/joyous/models/calendar.py
|
CalendarPage._getAllEvents
|
def _getAllEvents(self, request):
"""Return all the events in this site."""
home = request.site.root_page
return getAllEvents(request, home=home)
|
python
|
def _getAllEvents(self, request):
"""Return all the events in this site."""
home = request.site.root_page
return getAllEvents(request, home=home)
|
[
"def",
"_getAllEvents",
"(",
"self",
",",
"request",
")",
":",
"home",
"=",
"request",
".",
"site",
".",
"root_page",
"return",
"getAllEvents",
"(",
"request",
",",
"home",
"=",
"home",
")"
] |
Return all the events in this site.
|
[
"Return",
"all",
"the",
"events",
"in",
"this",
"site",
"."
] |
316283140ca5171a68ad3170a5964fdc89be0b56
|
https://github.com/linuxsoftware/ls.joyous/blob/316283140ca5171a68ad3170a5964fdc89be0b56/ls/joyous/models/calendar.py#L475-L478
|
train
|
linuxsoftware/ls.joyous
|
ls/joyous/models/calendar.py
|
SpecificCalendarPage._getEventsOnDay
|
def _getEventsOnDay(self, request, day):
"""Return my child events for a given day."""
return getAllEventsByDay(request, day, day, home=self)[0]
|
python
|
def _getEventsOnDay(self, request, day):
"""Return my child events for a given day."""
return getAllEventsByDay(request, day, day, home=self)[0]
|
[
"def",
"_getEventsOnDay",
"(",
"self",
",",
"request",
",",
"day",
")",
":",
"return",
"getAllEventsByDay",
"(",
"request",
",",
"day",
",",
"day",
",",
"home",
"=",
"self",
")",
"[",
"0",
"]"
] |
Return my child events for a given day.
|
[
"Return",
"my",
"child",
"events",
"for",
"a",
"given",
"day",
"."
] |
316283140ca5171a68ad3170a5964fdc89be0b56
|
https://github.com/linuxsoftware/ls.joyous/blob/316283140ca5171a68ad3170a5964fdc89be0b56/ls/joyous/models/calendar.py#L496-L498
|
train
|
linuxsoftware/ls.joyous
|
ls/joyous/models/calendar.py
|
SpecificCalendarPage._getEventsByDay
|
def _getEventsByDay(self, request, firstDay, lastDay):
"""
Return my child events for the dates given, grouped by day.
"""
return getAllEventsByDay(request, firstDay, lastDay, home=self)
|
python
|
def _getEventsByDay(self, request, firstDay, lastDay):
"""
Return my child events for the dates given, grouped by day.
"""
return getAllEventsByDay(request, firstDay, lastDay, home=self)
|
[
"def",
"_getEventsByDay",
"(",
"self",
",",
"request",
",",
"firstDay",
",",
"lastDay",
")",
":",
"return",
"getAllEventsByDay",
"(",
"request",
",",
"firstDay",
",",
"lastDay",
",",
"home",
"=",
"self",
")"
] |
Return my child events for the dates given, grouped by day.
|
[
"Return",
"my",
"child",
"events",
"for",
"the",
"dates",
"given",
"grouped",
"by",
"day",
"."
] |
316283140ca5171a68ad3170a5964fdc89be0b56
|
https://github.com/linuxsoftware/ls.joyous/blob/316283140ca5171a68ad3170a5964fdc89be0b56/ls/joyous/models/calendar.py#L500-L504
|
train
|
linuxsoftware/ls.joyous
|
ls/joyous/models/calendar.py
|
SpecificCalendarPage._getEventsByWeek
|
def _getEventsByWeek(self, request, year, month):
"""Return my child events for the given month grouped by week."""
return getAllEventsByWeek(request, year, month, home=self)
|
python
|
def _getEventsByWeek(self, request, year, month):
"""Return my child events for the given month grouped by week."""
return getAllEventsByWeek(request, year, month, home=self)
|
[
"def",
"_getEventsByWeek",
"(",
"self",
",",
"request",
",",
"year",
",",
"month",
")",
":",
"return",
"getAllEventsByWeek",
"(",
"request",
",",
"year",
",",
"month",
",",
"home",
"=",
"self",
")"
] |
Return my child events for the given month grouped by week.
|
[
"Return",
"my",
"child",
"events",
"for",
"the",
"given",
"month",
"grouped",
"by",
"week",
"."
] |
316283140ca5171a68ad3170a5964fdc89be0b56
|
https://github.com/linuxsoftware/ls.joyous/blob/316283140ca5171a68ad3170a5964fdc89be0b56/ls/joyous/models/calendar.py#L506-L508
|
train
|
linuxsoftware/ls.joyous
|
ls/joyous/models/calendar.py
|
SpecificCalendarPage._getEventFromUid
|
def _getEventFromUid(self, request, uid):
"""Try and find a child event with the given UID."""
event = getEventFromUid(request, uid)
if event.get_ancestors().filter(id=self.id).exists():
# only return event if it is a descendant
return event
|
python
|
def _getEventFromUid(self, request, uid):
"""Try and find a child event with the given UID."""
event = getEventFromUid(request, uid)
if event.get_ancestors().filter(id=self.id).exists():
# only return event if it is a descendant
return event
|
[
"def",
"_getEventFromUid",
"(",
"self",
",",
"request",
",",
"uid",
")",
":",
"event",
"=",
"getEventFromUid",
"(",
"request",
",",
"uid",
")",
"if",
"event",
".",
"get_ancestors",
"(",
")",
".",
"filter",
"(",
"id",
"=",
"self",
".",
"id",
")",
".",
"exists",
"(",
")",
":",
"# only return event if it is a descendant",
"return",
"event"
] |
Try and find a child event with the given UID.
|
[
"Try",
"and",
"find",
"a",
"child",
"event",
"with",
"the",
"given",
"UID",
"."
] |
316283140ca5171a68ad3170a5964fdc89be0b56
|
https://github.com/linuxsoftware/ls.joyous/blob/316283140ca5171a68ad3170a5964fdc89be0b56/ls/joyous/models/calendar.py#L518-L523
|
train
|
linuxsoftware/ls.joyous
|
ls/joyous/templatetags/joyous_tags.py
|
events_this_week
|
def events_this_week(context):
"""
Displays a week's worth of events. Starts week with Monday, unless today is Sunday.
"""
request = context['request']
home = request.site.root_page
cal = CalendarPage.objects.live().descendant_of(home).first()
calUrl = cal.get_url(request) if cal else None
calName = cal.title if cal else None
today = dt.date.today()
beginOrd = today.toordinal()
if today.weekday() != 6:
# Start week with Monday, unless today is Sunday
beginOrd -= today.weekday()
endOrd = beginOrd + 6
dateFrom = dt.date.fromordinal(beginOrd)
dateTo = dt.date.fromordinal(endOrd)
if cal:
events = cal._getEventsByDay(request, dateFrom, dateTo)
else:
events = getAllEventsByDay(request, dateFrom, dateTo)
return {'request': request,
'today': today,
'calendarUrl': calUrl,
'calendarName': calName,
'events': events }
|
python
|
def events_this_week(context):
"""
Displays a week's worth of events. Starts week with Monday, unless today is Sunday.
"""
request = context['request']
home = request.site.root_page
cal = CalendarPage.objects.live().descendant_of(home).first()
calUrl = cal.get_url(request) if cal else None
calName = cal.title if cal else None
today = dt.date.today()
beginOrd = today.toordinal()
if today.weekday() != 6:
# Start week with Monday, unless today is Sunday
beginOrd -= today.weekday()
endOrd = beginOrd + 6
dateFrom = dt.date.fromordinal(beginOrd)
dateTo = dt.date.fromordinal(endOrd)
if cal:
events = cal._getEventsByDay(request, dateFrom, dateTo)
else:
events = getAllEventsByDay(request, dateFrom, dateTo)
return {'request': request,
'today': today,
'calendarUrl': calUrl,
'calendarName': calName,
'events': events }
|
[
"def",
"events_this_week",
"(",
"context",
")",
":",
"request",
"=",
"context",
"[",
"'request'",
"]",
"home",
"=",
"request",
".",
"site",
".",
"root_page",
"cal",
"=",
"CalendarPage",
".",
"objects",
".",
"live",
"(",
")",
".",
"descendant_of",
"(",
"home",
")",
".",
"first",
"(",
")",
"calUrl",
"=",
"cal",
".",
"get_url",
"(",
"request",
")",
"if",
"cal",
"else",
"None",
"calName",
"=",
"cal",
".",
"title",
"if",
"cal",
"else",
"None",
"today",
"=",
"dt",
".",
"date",
".",
"today",
"(",
")",
"beginOrd",
"=",
"today",
".",
"toordinal",
"(",
")",
"if",
"today",
".",
"weekday",
"(",
")",
"!=",
"6",
":",
"# Start week with Monday, unless today is Sunday",
"beginOrd",
"-=",
"today",
".",
"weekday",
"(",
")",
"endOrd",
"=",
"beginOrd",
"+",
"6",
"dateFrom",
"=",
"dt",
".",
"date",
".",
"fromordinal",
"(",
"beginOrd",
")",
"dateTo",
"=",
"dt",
".",
"date",
".",
"fromordinal",
"(",
"endOrd",
")",
"if",
"cal",
":",
"events",
"=",
"cal",
".",
"_getEventsByDay",
"(",
"request",
",",
"dateFrom",
",",
"dateTo",
")",
"else",
":",
"events",
"=",
"getAllEventsByDay",
"(",
"request",
",",
"dateFrom",
",",
"dateTo",
")",
"return",
"{",
"'request'",
":",
"request",
",",
"'today'",
":",
"today",
",",
"'calendarUrl'",
":",
"calUrl",
",",
"'calendarName'",
":",
"calName",
",",
"'events'",
":",
"events",
"}"
] |
Displays a week's worth of events. Starts week with Monday, unless today is Sunday.
|
[
"Displays",
"a",
"week",
"s",
"worth",
"of",
"events",
".",
"Starts",
"week",
"with",
"Monday",
"unless",
"today",
"is",
"Sunday",
"."
] |
316283140ca5171a68ad3170a5964fdc89be0b56
|
https://github.com/linuxsoftware/ls.joyous/blob/316283140ca5171a68ad3170a5964fdc89be0b56/ls/joyous/templatetags/joyous_tags.py#L20-L45
|
train
|
linuxsoftware/ls.joyous
|
ls/joyous/templatetags/joyous_tags.py
|
minicalendar
|
def minicalendar(context):
"""
Displays a little ajax version of the calendar.
"""
today = dt.date.today()
request = context['request']
home = request.site.root_page
cal = CalendarPage.objects.live().descendant_of(home).first()
calUrl = cal.get_url(request) if cal else None
if cal:
events = cal._getEventsByWeek(request, today.year, today.month)
else:
events = getAllEventsByWeek(request, today.year, today.month)
return {'request': request,
'today': today,
'year': today.year,
'month': today.month,
'calendarUrl': calUrl,
'monthName': calendar.month_name[today.month],
'weekdayInfo': zip(weekday_abbr, weekday_name),
'events': events}
|
python
|
def minicalendar(context):
"""
Displays a little ajax version of the calendar.
"""
today = dt.date.today()
request = context['request']
home = request.site.root_page
cal = CalendarPage.objects.live().descendant_of(home).first()
calUrl = cal.get_url(request) if cal else None
if cal:
events = cal._getEventsByWeek(request, today.year, today.month)
else:
events = getAllEventsByWeek(request, today.year, today.month)
return {'request': request,
'today': today,
'year': today.year,
'month': today.month,
'calendarUrl': calUrl,
'monthName': calendar.month_name[today.month],
'weekdayInfo': zip(weekday_abbr, weekday_name),
'events': events}
|
[
"def",
"minicalendar",
"(",
"context",
")",
":",
"today",
"=",
"dt",
".",
"date",
".",
"today",
"(",
")",
"request",
"=",
"context",
"[",
"'request'",
"]",
"home",
"=",
"request",
".",
"site",
".",
"root_page",
"cal",
"=",
"CalendarPage",
".",
"objects",
".",
"live",
"(",
")",
".",
"descendant_of",
"(",
"home",
")",
".",
"first",
"(",
")",
"calUrl",
"=",
"cal",
".",
"get_url",
"(",
"request",
")",
"if",
"cal",
"else",
"None",
"if",
"cal",
":",
"events",
"=",
"cal",
".",
"_getEventsByWeek",
"(",
"request",
",",
"today",
".",
"year",
",",
"today",
".",
"month",
")",
"else",
":",
"events",
"=",
"getAllEventsByWeek",
"(",
"request",
",",
"today",
".",
"year",
",",
"today",
".",
"month",
")",
"return",
"{",
"'request'",
":",
"request",
",",
"'today'",
":",
"today",
",",
"'year'",
":",
"today",
".",
"year",
",",
"'month'",
":",
"today",
".",
"month",
",",
"'calendarUrl'",
":",
"calUrl",
",",
"'monthName'",
":",
"calendar",
".",
"month_name",
"[",
"today",
".",
"month",
"]",
",",
"'weekdayInfo'",
":",
"zip",
"(",
"weekday_abbr",
",",
"weekday_name",
")",
",",
"'events'",
":",
"events",
"}"
] |
Displays a little ajax version of the calendar.
|
[
"Displays",
"a",
"little",
"ajax",
"version",
"of",
"the",
"calendar",
"."
] |
316283140ca5171a68ad3170a5964fdc89be0b56
|
https://github.com/linuxsoftware/ls.joyous/blob/316283140ca5171a68ad3170a5964fdc89be0b56/ls/joyous/templatetags/joyous_tags.py#L49-L69
|
train
|
linuxsoftware/ls.joyous
|
ls/joyous/templatetags/joyous_tags.py
|
subsite_upcoming_events
|
def subsite_upcoming_events(context):
"""
Displays a list of all upcoming events in this site.
"""
request = context['request']
home = request.site.root_page
return {'request': request,
'events': getAllUpcomingEvents(request, home=home)}
|
python
|
def subsite_upcoming_events(context):
"""
Displays a list of all upcoming events in this site.
"""
request = context['request']
home = request.site.root_page
return {'request': request,
'events': getAllUpcomingEvents(request, home=home)}
|
[
"def",
"subsite_upcoming_events",
"(",
"context",
")",
":",
"request",
"=",
"context",
"[",
"'request'",
"]",
"home",
"=",
"request",
".",
"site",
".",
"root_page",
"return",
"{",
"'request'",
":",
"request",
",",
"'events'",
":",
"getAllUpcomingEvents",
"(",
"request",
",",
"home",
"=",
"home",
")",
"}"
] |
Displays a list of all upcoming events in this site.
|
[
"Displays",
"a",
"list",
"of",
"all",
"upcoming",
"events",
"in",
"this",
"site",
"."
] |
316283140ca5171a68ad3170a5964fdc89be0b56
|
https://github.com/linuxsoftware/ls.joyous/blob/316283140ca5171a68ad3170a5964fdc89be0b56/ls/joyous/templatetags/joyous_tags.py#L83-L90
|
train
|
linuxsoftware/ls.joyous
|
ls/joyous/templatetags/joyous_tags.py
|
group_upcoming_events
|
def group_upcoming_events(context, group=None):
"""
Displays a list of all upcoming events that are assigned to a specific
group. If the group is not specified it is assumed to be the current page.
"""
request = context.get('request')
if group is None:
group = context.get('page')
if group:
events = getGroupUpcomingEvents(request, group)
else:
events = []
return {'request': request,
'events': events}
|
python
|
def group_upcoming_events(context, group=None):
"""
Displays a list of all upcoming events that are assigned to a specific
group. If the group is not specified it is assumed to be the current page.
"""
request = context.get('request')
if group is None:
group = context.get('page')
if group:
events = getGroupUpcomingEvents(request, group)
else:
events = []
return {'request': request,
'events': events}
|
[
"def",
"group_upcoming_events",
"(",
"context",
",",
"group",
"=",
"None",
")",
":",
"request",
"=",
"context",
".",
"get",
"(",
"'request'",
")",
"if",
"group",
"is",
"None",
":",
"group",
"=",
"context",
".",
"get",
"(",
"'page'",
")",
"if",
"group",
":",
"events",
"=",
"getGroupUpcomingEvents",
"(",
"request",
",",
"group",
")",
"else",
":",
"events",
"=",
"[",
"]",
"return",
"{",
"'request'",
":",
"request",
",",
"'events'",
":",
"events",
"}"
] |
Displays a list of all upcoming events that are assigned to a specific
group. If the group is not specified it is assumed to be the current page.
|
[
"Displays",
"a",
"list",
"of",
"all",
"upcoming",
"events",
"that",
"are",
"assigned",
"to",
"a",
"specific",
"group",
".",
"If",
"the",
"group",
"is",
"not",
"specified",
"it",
"is",
"assumed",
"to",
"be",
"the",
"current",
"page",
"."
] |
316283140ca5171a68ad3170a5964fdc89be0b56
|
https://github.com/linuxsoftware/ls.joyous/blob/316283140ca5171a68ad3170a5964fdc89be0b56/ls/joyous/templatetags/joyous_tags.py#L94-L107
|
train
|
linuxsoftware/ls.joyous
|
ls/joyous/templatetags/joyous_tags.py
|
next_on
|
def next_on(context, rrevent=None):
"""
Displays when the next occurence of a recurring event will be. If the
recurring event is not specified it is assumed to be the current page.
"""
request = context['request']
if rrevent is None:
rrevent = context.get('page')
eventNextOn = getattr(rrevent, '_nextOn', lambda _:None)
return eventNextOn(request)
|
python
|
def next_on(context, rrevent=None):
"""
Displays when the next occurence of a recurring event will be. If the
recurring event is not specified it is assumed to be the current page.
"""
request = context['request']
if rrevent is None:
rrevent = context.get('page')
eventNextOn = getattr(rrevent, '_nextOn', lambda _:None)
return eventNextOn(request)
|
[
"def",
"next_on",
"(",
"context",
",",
"rrevent",
"=",
"None",
")",
":",
"request",
"=",
"context",
"[",
"'request'",
"]",
"if",
"rrevent",
"is",
"None",
":",
"rrevent",
"=",
"context",
".",
"get",
"(",
"'page'",
")",
"eventNextOn",
"=",
"getattr",
"(",
"rrevent",
",",
"'_nextOn'",
",",
"lambda",
"_",
":",
"None",
")",
"return",
"eventNextOn",
"(",
"request",
")"
] |
Displays when the next occurence of a recurring event will be. If the
recurring event is not specified it is assumed to be the current page.
|
[
"Displays",
"when",
"the",
"next",
"occurence",
"of",
"a",
"recurring",
"event",
"will",
"be",
".",
"If",
"the",
"recurring",
"event",
"is",
"not",
"specified",
"it",
"is",
"assumed",
"to",
"be",
"the",
"current",
"page",
"."
] |
316283140ca5171a68ad3170a5964fdc89be0b56
|
https://github.com/linuxsoftware/ls.joyous/blob/316283140ca5171a68ad3170a5964fdc89be0b56/ls/joyous/templatetags/joyous_tags.py#L128-L137
|
train
|
linuxsoftware/ls.joyous
|
ls/joyous/templatetags/joyous_tags.py
|
location_gmap
|
def location_gmap(context, location):
"""Display a link to Google maps iff we are using WagtailGMaps"""
gmapq = None
if getattr(MapFieldPanel, "UsingWagtailGMaps", False):
gmapq = location
return {'gmapq': gmapq}
|
python
|
def location_gmap(context, location):
"""Display a link to Google maps iff we are using WagtailGMaps"""
gmapq = None
if getattr(MapFieldPanel, "UsingWagtailGMaps", False):
gmapq = location
return {'gmapq': gmapq}
|
[
"def",
"location_gmap",
"(",
"context",
",",
"location",
")",
":",
"gmapq",
"=",
"None",
"if",
"getattr",
"(",
"MapFieldPanel",
",",
"\"UsingWagtailGMaps\"",
",",
"False",
")",
":",
"gmapq",
"=",
"location",
"return",
"{",
"'gmapq'",
":",
"gmapq",
"}"
] |
Display a link to Google maps iff we are using WagtailGMaps
|
[
"Display",
"a",
"link",
"to",
"Google",
"maps",
"iff",
"we",
"are",
"using",
"WagtailGMaps"
] |
316283140ca5171a68ad3170a5964fdc89be0b56
|
https://github.com/linuxsoftware/ls.joyous/blob/316283140ca5171a68ad3170a5964fdc89be0b56/ls/joyous/templatetags/joyous_tags.py#L143-L148
|
train
|
linuxsoftware/ls.joyous
|
ls/joyous/models/events.py
|
getGroupUpcomingEvents
|
def getGroupUpcomingEvents(request, group):
"""
Return all the upcoming events that are assigned to the specified group.
:param request: Django request object
:param group: for this group page
:rtype: list of the namedtuple ThisEvent (title, page, url)
"""
# Get events that are a child of a group page, or a postponement or extra
# info a child of the recurring event child of the group
rrEvents = RecurringEventPage.events(request).exclude(group_page=group) \
.upcoming().child_of(group).this()
qrys = [SimpleEventPage.events(request).exclude(group_page=group)
.upcoming().child_of(group).this(),
MultidayEventPage.events(request).exclude(group_page=group)
.upcoming().child_of(group).this(),
rrEvents]
for rrEvent in rrEvents:
qrys += [PostponementPage.events(request).child_of(rrEvent.page)
.upcoming().this(),
ExtraInfoPage.events(request).exclude(extra_title="")
.child_of(rrEvent.page).upcoming().this()]
# Get events that are linked to a group page, or a postponement or extra
# info a child of the recurring event linked to a group
rrEvents = group.recurringeventpage_set(manager='events').auth(request) \
.upcoming().this()
qrys += [group.simpleeventpage_set(manager='events').auth(request)
.upcoming().this(),
group.multidayeventpage_set(manager='events').auth(request)
.upcoming().this(),
rrEvents]
for rrEvent in rrEvents:
qrys += [PostponementPage.events(request).child_of(rrEvent.page)
.upcoming().this(),
ExtraInfoPage.events(request).exclude(extra_title="")
.child_of(rrEvent.page).upcoming().this()]
events = sorted(chain.from_iterable(qrys),
key=attrgetter('page._upcoming_datetime_from'))
return events
|
python
|
def getGroupUpcomingEvents(request, group):
"""
Return all the upcoming events that are assigned to the specified group.
:param request: Django request object
:param group: for this group page
:rtype: list of the namedtuple ThisEvent (title, page, url)
"""
# Get events that are a child of a group page, or a postponement or extra
# info a child of the recurring event child of the group
rrEvents = RecurringEventPage.events(request).exclude(group_page=group) \
.upcoming().child_of(group).this()
qrys = [SimpleEventPage.events(request).exclude(group_page=group)
.upcoming().child_of(group).this(),
MultidayEventPage.events(request).exclude(group_page=group)
.upcoming().child_of(group).this(),
rrEvents]
for rrEvent in rrEvents:
qrys += [PostponementPage.events(request).child_of(rrEvent.page)
.upcoming().this(),
ExtraInfoPage.events(request).exclude(extra_title="")
.child_of(rrEvent.page).upcoming().this()]
# Get events that are linked to a group page, or a postponement or extra
# info a child of the recurring event linked to a group
rrEvents = group.recurringeventpage_set(manager='events').auth(request) \
.upcoming().this()
qrys += [group.simpleeventpage_set(manager='events').auth(request)
.upcoming().this(),
group.multidayeventpage_set(manager='events').auth(request)
.upcoming().this(),
rrEvents]
for rrEvent in rrEvents:
qrys += [PostponementPage.events(request).child_of(rrEvent.page)
.upcoming().this(),
ExtraInfoPage.events(request).exclude(extra_title="")
.child_of(rrEvent.page).upcoming().this()]
events = sorted(chain.from_iterable(qrys),
key=attrgetter('page._upcoming_datetime_from'))
return events
|
[
"def",
"getGroupUpcomingEvents",
"(",
"request",
",",
"group",
")",
":",
"# Get events that are a child of a group page, or a postponement or extra",
"# info a child of the recurring event child of the group",
"rrEvents",
"=",
"RecurringEventPage",
".",
"events",
"(",
"request",
")",
".",
"exclude",
"(",
"group_page",
"=",
"group",
")",
".",
"upcoming",
"(",
")",
".",
"child_of",
"(",
"group",
")",
".",
"this",
"(",
")",
"qrys",
"=",
"[",
"SimpleEventPage",
".",
"events",
"(",
"request",
")",
".",
"exclude",
"(",
"group_page",
"=",
"group",
")",
".",
"upcoming",
"(",
")",
".",
"child_of",
"(",
"group",
")",
".",
"this",
"(",
")",
",",
"MultidayEventPage",
".",
"events",
"(",
"request",
")",
".",
"exclude",
"(",
"group_page",
"=",
"group",
")",
".",
"upcoming",
"(",
")",
".",
"child_of",
"(",
"group",
")",
".",
"this",
"(",
")",
",",
"rrEvents",
"]",
"for",
"rrEvent",
"in",
"rrEvents",
":",
"qrys",
"+=",
"[",
"PostponementPage",
".",
"events",
"(",
"request",
")",
".",
"child_of",
"(",
"rrEvent",
".",
"page",
")",
".",
"upcoming",
"(",
")",
".",
"this",
"(",
")",
",",
"ExtraInfoPage",
".",
"events",
"(",
"request",
")",
".",
"exclude",
"(",
"extra_title",
"=",
"\"\"",
")",
".",
"child_of",
"(",
"rrEvent",
".",
"page",
")",
".",
"upcoming",
"(",
")",
".",
"this",
"(",
")",
"]",
"# Get events that are linked to a group page, or a postponement or extra",
"# info a child of the recurring event linked to a group",
"rrEvents",
"=",
"group",
".",
"recurringeventpage_set",
"(",
"manager",
"=",
"'events'",
")",
".",
"auth",
"(",
"request",
")",
".",
"upcoming",
"(",
")",
".",
"this",
"(",
")",
"qrys",
"+=",
"[",
"group",
".",
"simpleeventpage_set",
"(",
"manager",
"=",
"'events'",
")",
".",
"auth",
"(",
"request",
")",
".",
"upcoming",
"(",
")",
".",
"this",
"(",
")",
",",
"group",
".",
"multidayeventpage_set",
"(",
"manager",
"=",
"'events'",
")",
".",
"auth",
"(",
"request",
")",
".",
"upcoming",
"(",
")",
".",
"this",
"(",
")",
",",
"rrEvents",
"]",
"for",
"rrEvent",
"in",
"rrEvents",
":",
"qrys",
"+=",
"[",
"PostponementPage",
".",
"events",
"(",
"request",
")",
".",
"child_of",
"(",
"rrEvent",
".",
"page",
")",
".",
"upcoming",
"(",
")",
".",
"this",
"(",
")",
",",
"ExtraInfoPage",
".",
"events",
"(",
"request",
")",
".",
"exclude",
"(",
"extra_title",
"=",
"\"\"",
")",
".",
"child_of",
"(",
"rrEvent",
".",
"page",
")",
".",
"upcoming",
"(",
")",
".",
"this",
"(",
")",
"]",
"events",
"=",
"sorted",
"(",
"chain",
".",
"from_iterable",
"(",
"qrys",
")",
",",
"key",
"=",
"attrgetter",
"(",
"'page._upcoming_datetime_from'",
")",
")",
"return",
"events"
] |
Return all the upcoming events that are assigned to the specified group.
:param request: Django request object
:param group: for this group page
:rtype: list of the namedtuple ThisEvent (title, page, url)
|
[
"Return",
"all",
"the",
"upcoming",
"events",
"that",
"are",
"assigned",
"to",
"the",
"specified",
"group",
"."
] |
316283140ca5171a68ad3170a5964fdc89be0b56
|
https://github.com/linuxsoftware/ls.joyous/blob/316283140ca5171a68ad3170a5964fdc89be0b56/ls/joyous/models/events.py#L109-L148
|
train
|
linuxsoftware/ls.joyous
|
ls/joyous/models/events.py
|
EventBase.group
|
def group(self):
"""
The group this event belongs to. Adding the event as a child of a
group automatically assigns the event to that group.
"""
retval = None
parent = self.get_parent()
Group = get_group_model()
if issubclass(parent.specific_class, Group):
retval = parent.specific
if retval is None:
retval = self.group_page
return retval
|
python
|
def group(self):
"""
The group this event belongs to. Adding the event as a child of a
group automatically assigns the event to that group.
"""
retval = None
parent = self.get_parent()
Group = get_group_model()
if issubclass(parent.specific_class, Group):
retval = parent.specific
if retval is None:
retval = self.group_page
return retval
|
[
"def",
"group",
"(",
"self",
")",
":",
"retval",
"=",
"None",
"parent",
"=",
"self",
".",
"get_parent",
"(",
")",
"Group",
"=",
"get_group_model",
"(",
")",
"if",
"issubclass",
"(",
"parent",
".",
"specific_class",
",",
"Group",
")",
":",
"retval",
"=",
"parent",
".",
"specific",
"if",
"retval",
"is",
"None",
":",
"retval",
"=",
"self",
".",
"group_page",
"return",
"retval"
] |
The group this event belongs to. Adding the event as a child of a
group automatically assigns the event to that group.
|
[
"The",
"group",
"this",
"event",
"belongs",
"to",
".",
"Adding",
"the",
"event",
"as",
"a",
"child",
"of",
"a",
"group",
"automatically",
"assigns",
"the",
"event",
"to",
"that",
"group",
"."
] |
316283140ca5171a68ad3170a5964fdc89be0b56
|
https://github.com/linuxsoftware/ls.joyous/blob/316283140ca5171a68ad3170a5964fdc89be0b56/ls/joyous/models/events.py#L492-L504
|
train
|
linuxsoftware/ls.joyous
|
ls/joyous/models/events.py
|
EventBase.isAuthorized
|
def isAuthorized(self, request):
"""
Is the user authorized for the requested action with this event?
"""
restrictions = self.get_view_restrictions()
if restrictions and request is None:
return False
else:
return all(restriction.accept_request(request)
for restriction in restrictions)
|
python
|
def isAuthorized(self, request):
"""
Is the user authorized for the requested action with this event?
"""
restrictions = self.get_view_restrictions()
if restrictions and request is None:
return False
else:
return all(restriction.accept_request(request)
for restriction in restrictions)
|
[
"def",
"isAuthorized",
"(",
"self",
",",
"request",
")",
":",
"restrictions",
"=",
"self",
".",
"get_view_restrictions",
"(",
")",
"if",
"restrictions",
"and",
"request",
"is",
"None",
":",
"return",
"False",
"else",
":",
"return",
"all",
"(",
"restriction",
".",
"accept_request",
"(",
"request",
")",
"for",
"restriction",
"in",
"restrictions",
")"
] |
Is the user authorized for the requested action with this event?
|
[
"Is",
"the",
"user",
"authorized",
"for",
"the",
"requested",
"action",
"with",
"this",
"event?"
] |
316283140ca5171a68ad3170a5964fdc89be0b56
|
https://github.com/linuxsoftware/ls.joyous/blob/316283140ca5171a68ad3170a5964fdc89be0b56/ls/joyous/models/events.py#L562-L571
|
train
|
linuxsoftware/ls.joyous
|
ls/joyous/models/events.py
|
RecurringEventPage._upcoming_datetime_from
|
def _upcoming_datetime_from(self):
"""
The datetime this event next starts in the local time zone, or None if
it is finished.
"""
nextDt = self.__localAfter(timezone.localtime(), dt.time.max,
excludeCancellations=True,
excludeExtraInfo=True)
return nextDt
|
python
|
def _upcoming_datetime_from(self):
"""
The datetime this event next starts in the local time zone, or None if
it is finished.
"""
nextDt = self.__localAfter(timezone.localtime(), dt.time.max,
excludeCancellations=True,
excludeExtraInfo=True)
return nextDt
|
[
"def",
"_upcoming_datetime_from",
"(",
"self",
")",
":",
"nextDt",
"=",
"self",
".",
"__localAfter",
"(",
"timezone",
".",
"localtime",
"(",
")",
",",
"dt",
".",
"time",
".",
"max",
",",
"excludeCancellations",
"=",
"True",
",",
"excludeExtraInfo",
"=",
"True",
")",
"return",
"nextDt"
] |
The datetime this event next starts in the local time zone, or None if
it is finished.
|
[
"The",
"datetime",
"this",
"event",
"next",
"starts",
"in",
"the",
"local",
"time",
"zone",
"or",
"None",
"if",
"it",
"is",
"finished",
"."
] |
316283140ca5171a68ad3170a5964fdc89be0b56
|
https://github.com/linuxsoftware/ls.joyous/blob/316283140ca5171a68ad3170a5964fdc89be0b56/ls/joyous/models/events.py#L961-L969
|
train
|
linuxsoftware/ls.joyous
|
ls/joyous/models/events.py
|
RecurringEventPage._past_datetime_from
|
def _past_datetime_from(self):
"""
The datetime this event previously started in the local time zone, or
None if it never did.
"""
prevDt = self.__localBefore(timezone.localtime(), dt.time.max,
excludeCancellations=True,
excludeExtraInfo=True)
return prevDt
|
python
|
def _past_datetime_from(self):
"""
The datetime this event previously started in the local time zone, or
None if it never did.
"""
prevDt = self.__localBefore(timezone.localtime(), dt.time.max,
excludeCancellations=True,
excludeExtraInfo=True)
return prevDt
|
[
"def",
"_past_datetime_from",
"(",
"self",
")",
":",
"prevDt",
"=",
"self",
".",
"__localBefore",
"(",
"timezone",
".",
"localtime",
"(",
")",
",",
"dt",
".",
"time",
".",
"max",
",",
"excludeCancellations",
"=",
"True",
",",
"excludeExtraInfo",
"=",
"True",
")",
"return",
"prevDt"
] |
The datetime this event previously started in the local time zone, or
None if it never did.
|
[
"The",
"datetime",
"this",
"event",
"previously",
"started",
"in",
"the",
"local",
"time",
"zone",
"or",
"None",
"if",
"it",
"never",
"did",
"."
] |
316283140ca5171a68ad3170a5964fdc89be0b56
|
https://github.com/linuxsoftware/ls.joyous/blob/316283140ca5171a68ad3170a5964fdc89be0b56/ls/joyous/models/events.py#L982-L990
|
train
|
linuxsoftware/ls.joyous
|
ls/joyous/models/events.py
|
RecurringEventPage._first_datetime_from
|
def _first_datetime_from(self):
"""
The datetime this event first started in the local time zone, or None if
it never did.
"""
myFromDt = self._getMyFirstDatetimeFrom()
localTZ = timezone.get_current_timezone()
return myFromDt.astimezone(localTZ)
|
python
|
def _first_datetime_from(self):
"""
The datetime this event first started in the local time zone, or None if
it never did.
"""
myFromDt = self._getMyFirstDatetimeFrom()
localTZ = timezone.get_current_timezone()
return myFromDt.astimezone(localTZ)
|
[
"def",
"_first_datetime_from",
"(",
"self",
")",
":",
"myFromDt",
"=",
"self",
".",
"_getMyFirstDatetimeFrom",
"(",
")",
"localTZ",
"=",
"timezone",
".",
"get_current_timezone",
"(",
")",
"return",
"myFromDt",
".",
"astimezone",
"(",
"localTZ",
")"
] |
The datetime this event first started in the local time zone, or None if
it never did.
|
[
"The",
"datetime",
"this",
"event",
"first",
"started",
"in",
"the",
"local",
"time",
"zone",
"or",
"None",
"if",
"it",
"never",
"did",
"."
] |
316283140ca5171a68ad3170a5964fdc89be0b56
|
https://github.com/linuxsoftware/ls.joyous/blob/316283140ca5171a68ad3170a5964fdc89be0b56/ls/joyous/models/events.py#L993-L1000
|
train
|
linuxsoftware/ls.joyous
|
ls/joyous/models/events.py
|
RecurringEventPage._getFromTime
|
def _getFromTime(self, atDate=None):
"""
What was the time of this event? Due to time zones that depends what
day we are talking about. If no day is given, assume today.
"""
if atDate is None:
atDate = timezone.localdate(timezone=self.tz)
return getLocalTime(atDate, self.time_from, self.tz)
|
python
|
def _getFromTime(self, atDate=None):
"""
What was the time of this event? Due to time zones that depends what
day we are talking about. If no day is given, assume today.
"""
if atDate is None:
atDate = timezone.localdate(timezone=self.tz)
return getLocalTime(atDate, self.time_from, self.tz)
|
[
"def",
"_getFromTime",
"(",
"self",
",",
"atDate",
"=",
"None",
")",
":",
"if",
"atDate",
"is",
"None",
":",
"atDate",
"=",
"timezone",
".",
"localdate",
"(",
"timezone",
"=",
"self",
".",
"tz",
")",
"return",
"getLocalTime",
"(",
"atDate",
",",
"self",
".",
"time_from",
",",
"self",
".",
"tz",
")"
] |
What was the time of this event? Due to time zones that depends what
day we are talking about. If no day is given, assume today.
|
[
"What",
"was",
"the",
"time",
"of",
"this",
"event?",
"Due",
"to",
"time",
"zones",
"that",
"depends",
"what",
"day",
"we",
"are",
"talking",
"about",
".",
"If",
"no",
"day",
"is",
"given",
"assume",
"today",
"."
] |
316283140ca5171a68ad3170a5964fdc89be0b56
|
https://github.com/linuxsoftware/ls.joyous/blob/316283140ca5171a68ad3170a5964fdc89be0b56/ls/joyous/models/events.py#L1074-L1081
|
train
|
linuxsoftware/ls.joyous
|
ls/joyous/models/events.py
|
RecurringEventPage._getFromDt
|
def _getFromDt(self):
"""
Get the datetime of the next event after or before now.
"""
myNow = timezone.localtime(timezone=self.tz)
return self.__after(myNow) or self.__before(myNow)
|
python
|
def _getFromDt(self):
"""
Get the datetime of the next event after or before now.
"""
myNow = timezone.localtime(timezone=self.tz)
return self.__after(myNow) or self.__before(myNow)
|
[
"def",
"_getFromDt",
"(",
"self",
")",
":",
"myNow",
"=",
"timezone",
".",
"localtime",
"(",
"timezone",
"=",
"self",
".",
"tz",
")",
"return",
"self",
".",
"__after",
"(",
"myNow",
")",
"or",
"self",
".",
"__before",
"(",
"myNow",
")"
] |
Get the datetime of the next event after or before now.
|
[
"Get",
"the",
"datetime",
"of",
"the",
"next",
"event",
"after",
"or",
"before",
"now",
"."
] |
316283140ca5171a68ad3170a5964fdc89be0b56
|
https://github.com/linuxsoftware/ls.joyous/blob/316283140ca5171a68ad3170a5964fdc89be0b56/ls/joyous/models/events.py#L1083-L1088
|
train
|
linuxsoftware/ls.joyous
|
ls/joyous/models/events.py
|
RecurringEventPage._futureExceptions
|
def _futureExceptions(self, request):
"""
Returns all future extra info, cancellations and postponements created
for this recurring event
"""
retval = []
# We know all future exception dates are in the parent time zone
myToday = timezone.localdate(timezone=self.tz)
for extraInfo in ExtraInfoPage.events(request).child_of(self) \
.filter(except_date__gte=myToday):
retval.append(extraInfo)
for cancellation in CancellationPage.events(request).child_of(self) \
.filter(except_date__gte=myToday):
postponement = getattr(cancellation, "postponementpage", None)
if postponement:
retval.append(postponement)
else:
retval.append(cancellation)
retval.sort(key=attrgetter('except_date'))
# notice these are events not ThisEvents
return retval
|
python
|
def _futureExceptions(self, request):
"""
Returns all future extra info, cancellations and postponements created
for this recurring event
"""
retval = []
# We know all future exception dates are in the parent time zone
myToday = timezone.localdate(timezone=self.tz)
for extraInfo in ExtraInfoPage.events(request).child_of(self) \
.filter(except_date__gte=myToday):
retval.append(extraInfo)
for cancellation in CancellationPage.events(request).child_of(self) \
.filter(except_date__gte=myToday):
postponement = getattr(cancellation, "postponementpage", None)
if postponement:
retval.append(postponement)
else:
retval.append(cancellation)
retval.sort(key=attrgetter('except_date'))
# notice these are events not ThisEvents
return retval
|
[
"def",
"_futureExceptions",
"(",
"self",
",",
"request",
")",
":",
"retval",
"=",
"[",
"]",
"# We know all future exception dates are in the parent time zone",
"myToday",
"=",
"timezone",
".",
"localdate",
"(",
"timezone",
"=",
"self",
".",
"tz",
")",
"for",
"extraInfo",
"in",
"ExtraInfoPage",
".",
"events",
"(",
"request",
")",
".",
"child_of",
"(",
"self",
")",
".",
"filter",
"(",
"except_date__gte",
"=",
"myToday",
")",
":",
"retval",
".",
"append",
"(",
"extraInfo",
")",
"for",
"cancellation",
"in",
"CancellationPage",
".",
"events",
"(",
"request",
")",
".",
"child_of",
"(",
"self",
")",
".",
"filter",
"(",
"except_date__gte",
"=",
"myToday",
")",
":",
"postponement",
"=",
"getattr",
"(",
"cancellation",
",",
"\"postponementpage\"",
",",
"None",
")",
"if",
"postponement",
":",
"retval",
".",
"append",
"(",
"postponement",
")",
"else",
":",
"retval",
".",
"append",
"(",
"cancellation",
")",
"retval",
".",
"sort",
"(",
"key",
"=",
"attrgetter",
"(",
"'except_date'",
")",
")",
"# notice these are events not ThisEvents",
"return",
"retval"
] |
Returns all future extra info, cancellations and postponements created
for this recurring event
|
[
"Returns",
"all",
"future",
"extra",
"info",
"cancellations",
"and",
"postponements",
"created",
"for",
"this",
"recurring",
"event"
] |
316283140ca5171a68ad3170a5964fdc89be0b56
|
https://github.com/linuxsoftware/ls.joyous/blob/316283140ca5171a68ad3170a5964fdc89be0b56/ls/joyous/models/events.py#L1090-L1111
|
train
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.