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 |
---|---|---|---|---|---|---|---|---|---|---|---|
kaniblu/pytorch-text-utils | torchtextutils/vocab.py | Vocabulary.remove | def remove(self, w):
"""
Removes a word from the vocab. The indices are unchanged.
"""
if w not in self.f2i:
raise ValueError("'{}' does not exist.".format(w))
if w in self.reserved:
raise ValueError("'{}' is one of the reserved words, and thus"
"cannot be removed.".format(w))
index = self.f2i[w]
del self.f2i[w]
del self.i2f[index]
self.words.remove(w) | python | def remove(self, w):
"""
Removes a word from the vocab. The indices are unchanged.
"""
if w not in self.f2i:
raise ValueError("'{}' does not exist.".format(w))
if w in self.reserved:
raise ValueError("'{}' is one of the reserved words, and thus"
"cannot be removed.".format(w))
index = self.f2i[w]
del self.f2i[w]
del self.i2f[index]
self.words.remove(w) | [
"def",
"remove",
"(",
"self",
",",
"w",
")",
":",
"if",
"w",
"not",
"in",
"self",
".",
"f2i",
":",
"raise",
"ValueError",
"(",
"\"'{}' does not exist.\"",
".",
"format",
"(",
"w",
")",
")",
"if",
"w",
"in",
"self",
".",
"reserved",
":",
"raise",
"ValueError",
"(",
"\"'{}' is one of the reserved words, and thus\"",
"\"cannot be removed.\"",
".",
"format",
"(",
"w",
")",
")",
"index",
"=",
"self",
".",
"f2i",
"[",
"w",
"]",
"del",
"self",
".",
"f2i",
"[",
"w",
"]",
"del",
"self",
".",
"i2f",
"[",
"index",
"]",
"self",
".",
"words",
".",
"remove",
"(",
"w",
")"
]
| Removes a word from the vocab. The indices are unchanged. | [
"Removes",
"a",
"word",
"from",
"the",
"vocab",
".",
"The",
"indices",
"are",
"unchanged",
"."
]
| ab26b88b3e1ed8e777abf32dbfab900399e0cf08 | https://github.com/kaniblu/pytorch-text-utils/blob/ab26b88b3e1ed8e777abf32dbfab900399e0cf08/torchtextutils/vocab.py#L37-L52 | train |
kaniblu/pytorch-text-utils | torchtextutils/vocab.py | Vocabulary.reconstruct_indices | def reconstruct_indices(self):
"""
Reconstruct word indices in case of word removals.
Vocabulary does not handle empty indices when words are removed,
hence it need to be told explicity about when to reconstruct them.
"""
del self.i2f, self.f2i
self.f2i, self.i2f = {}, {}
for i, w in enumerate(self.words):
self.f2i[w] = i
self.i2f[i] = w | python | def reconstruct_indices(self):
"""
Reconstruct word indices in case of word removals.
Vocabulary does not handle empty indices when words are removed,
hence it need to be told explicity about when to reconstruct them.
"""
del self.i2f, self.f2i
self.f2i, self.i2f = {}, {}
for i, w in enumerate(self.words):
self.f2i[w] = i
self.i2f[i] = w | [
"def",
"reconstruct_indices",
"(",
"self",
")",
":",
"del",
"self",
".",
"i2f",
",",
"self",
".",
"f2i",
"self",
".",
"f2i",
",",
"self",
".",
"i2f",
"=",
"{",
"}",
",",
"{",
"}",
"for",
"i",
",",
"w",
"in",
"enumerate",
"(",
"self",
".",
"words",
")",
":",
"self",
".",
"f2i",
"[",
"w",
"]",
"=",
"i",
"self",
".",
"i2f",
"[",
"i",
"]",
"=",
"w"
]
| Reconstruct word indices in case of word removals.
Vocabulary does not handle empty indices when words are removed,
hence it need to be told explicity about when to reconstruct them. | [
"Reconstruct",
"word",
"indices",
"in",
"case",
"of",
"word",
"removals",
".",
"Vocabulary",
"does",
"not",
"handle",
"empty",
"indices",
"when",
"words",
"are",
"removed",
"hence",
"it",
"need",
"to",
"be",
"told",
"explicity",
"about",
"when",
"to",
"reconstruct",
"them",
"."
]
| ab26b88b3e1ed8e777abf32dbfab900399e0cf08 | https://github.com/kaniblu/pytorch-text-utils/blob/ab26b88b3e1ed8e777abf32dbfab900399e0cf08/torchtextutils/vocab.py#L54-L65 | train |
Genida/archan | src/archan/plugins/__init__.py | Checker.run | def run(self, data):
"""
Run the check method and format the result for analysis.
Args:
data (DSM/DMM/MDM): DSM/DMM/MDM instance to check.
Returns:
tuple (int, str): status constant from Checker class and messages.
"""
result_type = namedtuple('Result', 'code messages')
if self.passes is True:
result = result_type(Checker.Code.PASSED, '')
elif self.passes is False:
if self.allow_failure:
result = result_type(Checker.Code.IGNORED, '')
else:
result = result_type(Checker.Code.FAILED, '')
else:
try:
result = self.check(data, **self.arguments)
messages = ''
if isinstance(result, tuple):
result, messages = result
if result not in Checker.Code:
result = Checker.Code.PASSED if bool(result) else Checker.Code.FAILED
if result == Checker.Code.FAILED and self.allow_failure:
result = Checker.Code.IGNORED
result = result_type(result, messages)
except NotImplementedError:
result = result_type(Checker.Code.NOT_IMPLEMENTED, '')
self.result = result | python | def run(self, data):
"""
Run the check method and format the result for analysis.
Args:
data (DSM/DMM/MDM): DSM/DMM/MDM instance to check.
Returns:
tuple (int, str): status constant from Checker class and messages.
"""
result_type = namedtuple('Result', 'code messages')
if self.passes is True:
result = result_type(Checker.Code.PASSED, '')
elif self.passes is False:
if self.allow_failure:
result = result_type(Checker.Code.IGNORED, '')
else:
result = result_type(Checker.Code.FAILED, '')
else:
try:
result = self.check(data, **self.arguments)
messages = ''
if isinstance(result, tuple):
result, messages = result
if result not in Checker.Code:
result = Checker.Code.PASSED if bool(result) else Checker.Code.FAILED
if result == Checker.Code.FAILED and self.allow_failure:
result = Checker.Code.IGNORED
result = result_type(result, messages)
except NotImplementedError:
result = result_type(Checker.Code.NOT_IMPLEMENTED, '')
self.result = result | [
"def",
"run",
"(",
"self",
",",
"data",
")",
":",
"result_type",
"=",
"namedtuple",
"(",
"'Result'",
",",
"'code messages'",
")",
"if",
"self",
".",
"passes",
"is",
"True",
":",
"result",
"=",
"result_type",
"(",
"Checker",
".",
"Code",
".",
"PASSED",
",",
"''",
")",
"elif",
"self",
".",
"passes",
"is",
"False",
":",
"if",
"self",
".",
"allow_failure",
":",
"result",
"=",
"result_type",
"(",
"Checker",
".",
"Code",
".",
"IGNORED",
",",
"''",
")",
"else",
":",
"result",
"=",
"result_type",
"(",
"Checker",
".",
"Code",
".",
"FAILED",
",",
"''",
")",
"else",
":",
"try",
":",
"result",
"=",
"self",
".",
"check",
"(",
"data",
",",
"*",
"*",
"self",
".",
"arguments",
")",
"messages",
"=",
"''",
"if",
"isinstance",
"(",
"result",
",",
"tuple",
")",
":",
"result",
",",
"messages",
"=",
"result",
"if",
"result",
"not",
"in",
"Checker",
".",
"Code",
":",
"result",
"=",
"Checker",
".",
"Code",
".",
"PASSED",
"if",
"bool",
"(",
"result",
")",
"else",
"Checker",
".",
"Code",
".",
"FAILED",
"if",
"result",
"==",
"Checker",
".",
"Code",
".",
"FAILED",
"and",
"self",
".",
"allow_failure",
":",
"result",
"=",
"Checker",
".",
"Code",
".",
"IGNORED",
"result",
"=",
"result_type",
"(",
"result",
",",
"messages",
")",
"except",
"NotImplementedError",
":",
"result",
"=",
"result_type",
"(",
"Checker",
".",
"Code",
".",
"NOT_IMPLEMENTED",
",",
"''",
")",
"self",
".",
"result",
"=",
"result"
]
| Run the check method and format the result for analysis.
Args:
data (DSM/DMM/MDM): DSM/DMM/MDM instance to check.
Returns:
tuple (int, str): status constant from Checker class and messages. | [
"Run",
"the",
"check",
"method",
"and",
"format",
"the",
"result",
"for",
"analysis",
"."
]
| a026d3105c7e86f30e6c9507b93ceb736684bfdc | https://github.com/Genida/archan/blob/a026d3105c7e86f30e6c9507b93ceb736684bfdc/src/archan/plugins/__init__.py#L90-L125 | train |
VIVelev/PyDojoML | dojo/tree/utils/structure.py | Question.is_numeric | def is_numeric(value):
"""Test if a value is numeric.
"""
return type(value) in [
int,
float,
np.int8,
np.int16,
np.int32,
np.int64,
np.float16,
np.float32,
np.float64,
np.float128
] | python | def is_numeric(value):
"""Test if a value is numeric.
"""
return type(value) in [
int,
float,
np.int8,
np.int16,
np.int32,
np.int64,
np.float16,
np.float32,
np.float64,
np.float128
] | [
"def",
"is_numeric",
"(",
"value",
")",
":",
"return",
"type",
"(",
"value",
")",
"in",
"[",
"int",
",",
"float",
",",
"np",
".",
"int8",
",",
"np",
".",
"int16",
",",
"np",
".",
"int32",
",",
"np",
".",
"int64",
",",
"np",
".",
"float16",
",",
"np",
".",
"float32",
",",
"np",
".",
"float64",
",",
"np",
".",
"float128",
"]"
]
| Test if a value is numeric. | [
"Test",
"if",
"a",
"value",
"is",
"numeric",
"."
]
| 773fdce6866aa6decd306a5a85f94129fed816eb | https://github.com/VIVelev/PyDojoML/blob/773fdce6866aa6decd306a5a85f94129fed816eb/dojo/tree/utils/structure.py#L20-L36 | train |
tjcsl/cslbot | cslbot/commands/fortune.py | cmd | def cmd(send, msg, args):
"""Returns a fortune.
Syntax: {command} <list|[-a|-o] [module]>
"""
if msg == 'list':
fortunes = list_fortunes() + list_fortunes(True)
send(" ".join(fortunes), ignore_length=True)
else:
output = get_fortune(msg, args['name'])
for line in output.splitlines():
send(line) | python | def cmd(send, msg, args):
"""Returns a fortune.
Syntax: {command} <list|[-a|-o] [module]>
"""
if msg == 'list':
fortunes = list_fortunes() + list_fortunes(True)
send(" ".join(fortunes), ignore_length=True)
else:
output = get_fortune(msg, args['name'])
for line in output.splitlines():
send(line) | [
"def",
"cmd",
"(",
"send",
",",
"msg",
",",
"args",
")",
":",
"if",
"msg",
"==",
"'list'",
":",
"fortunes",
"=",
"list_fortunes",
"(",
")",
"+",
"list_fortunes",
"(",
"True",
")",
"send",
"(",
"\" \"",
".",
"join",
"(",
"fortunes",
")",
",",
"ignore_length",
"=",
"True",
")",
"else",
":",
"output",
"=",
"get_fortune",
"(",
"msg",
",",
"args",
"[",
"'name'",
"]",
")",
"for",
"line",
"in",
"output",
".",
"splitlines",
"(",
")",
":",
"send",
"(",
"line",
")"
]
| Returns a fortune.
Syntax: {command} <list|[-a|-o] [module]> | [
"Returns",
"a",
"fortune",
"."
]
| aebe07be47141f61d7c180706bddfb707f19b2b5 | https://github.com/tjcsl/cslbot/blob/aebe07be47141f61d7c180706bddfb707f19b2b5/cslbot/commands/fortune.py#L23-L35 | train |
tylerbutler/engineer | engineer/devtools/theme_tools.py | compile_theme | def compile_theme(theme_id=None):
"""Compiles a theme."""
from engineer.processors import convert_less
from engineer.themes import ThemeManager
if theme_id is None:
themes = ThemeManager.themes().values()
else:
themes = [ThemeManager.theme(theme_id)]
with(indent(2)):
puts(colored.yellow("Compiling %s themes." % len(themes)))
for theme in themes:
theme_output_path = (theme.static_root / ('stylesheets/%s_precompiled.css' % theme.id)).normpath()
puts(colored.cyan("Compiling theme %s to %s" % (theme.id, theme_output_path)))
with indent(4):
puts("Compiling...")
convert_less(theme.static_root / ('stylesheets/%s.less' % theme.id),
theme_output_path,
minify=True)
puts(colored.green("Done.", bold=True)) | python | def compile_theme(theme_id=None):
"""Compiles a theme."""
from engineer.processors import convert_less
from engineer.themes import ThemeManager
if theme_id is None:
themes = ThemeManager.themes().values()
else:
themes = [ThemeManager.theme(theme_id)]
with(indent(2)):
puts(colored.yellow("Compiling %s themes." % len(themes)))
for theme in themes:
theme_output_path = (theme.static_root / ('stylesheets/%s_precompiled.css' % theme.id)).normpath()
puts(colored.cyan("Compiling theme %s to %s" % (theme.id, theme_output_path)))
with indent(4):
puts("Compiling...")
convert_less(theme.static_root / ('stylesheets/%s.less' % theme.id),
theme_output_path,
minify=True)
puts(colored.green("Done.", bold=True)) | [
"def",
"compile_theme",
"(",
"theme_id",
"=",
"None",
")",
":",
"from",
"engineer",
".",
"processors",
"import",
"convert_less",
"from",
"engineer",
".",
"themes",
"import",
"ThemeManager",
"if",
"theme_id",
"is",
"None",
":",
"themes",
"=",
"ThemeManager",
".",
"themes",
"(",
")",
".",
"values",
"(",
")",
"else",
":",
"themes",
"=",
"[",
"ThemeManager",
".",
"theme",
"(",
"theme_id",
")",
"]",
"with",
"(",
"indent",
"(",
"2",
")",
")",
":",
"puts",
"(",
"colored",
".",
"yellow",
"(",
"\"Compiling %s themes.\"",
"%",
"len",
"(",
"themes",
")",
")",
")",
"for",
"theme",
"in",
"themes",
":",
"theme_output_path",
"=",
"(",
"theme",
".",
"static_root",
"/",
"(",
"'stylesheets/%s_precompiled.css'",
"%",
"theme",
".",
"id",
")",
")",
".",
"normpath",
"(",
")",
"puts",
"(",
"colored",
".",
"cyan",
"(",
"\"Compiling theme %s to %s\"",
"%",
"(",
"theme",
".",
"id",
",",
"theme_output_path",
")",
")",
")",
"with",
"indent",
"(",
"4",
")",
":",
"puts",
"(",
"\"Compiling...\"",
")",
"convert_less",
"(",
"theme",
".",
"static_root",
"/",
"(",
"'stylesheets/%s.less'",
"%",
"theme",
".",
"id",
")",
",",
"theme_output_path",
",",
"minify",
"=",
"True",
")",
"puts",
"(",
"colored",
".",
"green",
"(",
"\"Done.\"",
",",
"bold",
"=",
"True",
")",
")"
]
| Compiles a theme. | [
"Compiles",
"a",
"theme",
"."
]
| 8884f587297f37646c40e5553174852b444a4024 | https://github.com/tylerbutler/engineer/blob/8884f587297f37646c40e5553174852b444a4024/engineer/devtools/theme_tools.py#L20-L42 | train |
tylerbutler/engineer | engineer/devtools/theme_tools.py | list_theme | def list_theme():
"""List all available Engineer themes."""
from engineer.themes import ThemeManager
themes = ThemeManager.themes()
col1, col2 = map(max, zip(*[(len(t.id) + 2, len(t.root_path) + 2) for t in themes.itervalues()]))
themes = ThemeManager.themes_by_finder()
for finder in sorted(themes.iterkeys()):
if len(themes[finder]) > 0:
puts("%s: " % finder)
for theme in sorted(themes[finder], key=lambda _: _.id):
with indent(4):
puts(
columns(
[colored.cyan("%s:" % theme.id), col1],
[colored.white(theme.root_path, bold=True), col2]
)
) | python | def list_theme():
"""List all available Engineer themes."""
from engineer.themes import ThemeManager
themes = ThemeManager.themes()
col1, col2 = map(max, zip(*[(len(t.id) + 2, len(t.root_path) + 2) for t in themes.itervalues()]))
themes = ThemeManager.themes_by_finder()
for finder in sorted(themes.iterkeys()):
if len(themes[finder]) > 0:
puts("%s: " % finder)
for theme in sorted(themes[finder], key=lambda _: _.id):
with indent(4):
puts(
columns(
[colored.cyan("%s:" % theme.id), col1],
[colored.white(theme.root_path, bold=True), col2]
)
) | [
"def",
"list_theme",
"(",
")",
":",
"from",
"engineer",
".",
"themes",
"import",
"ThemeManager",
"themes",
"=",
"ThemeManager",
".",
"themes",
"(",
")",
"col1",
",",
"col2",
"=",
"map",
"(",
"max",
",",
"zip",
"(",
"*",
"[",
"(",
"len",
"(",
"t",
".",
"id",
")",
"+",
"2",
",",
"len",
"(",
"t",
".",
"root_path",
")",
"+",
"2",
")",
"for",
"t",
"in",
"themes",
".",
"itervalues",
"(",
")",
"]",
")",
")",
"themes",
"=",
"ThemeManager",
".",
"themes_by_finder",
"(",
")",
"for",
"finder",
"in",
"sorted",
"(",
"themes",
".",
"iterkeys",
"(",
")",
")",
":",
"if",
"len",
"(",
"themes",
"[",
"finder",
"]",
")",
">",
"0",
":",
"puts",
"(",
"\"%s: \"",
"%",
"finder",
")",
"for",
"theme",
"in",
"sorted",
"(",
"themes",
"[",
"finder",
"]",
",",
"key",
"=",
"lambda",
"_",
":",
"_",
".",
"id",
")",
":",
"with",
"indent",
"(",
"4",
")",
":",
"puts",
"(",
"columns",
"(",
"[",
"colored",
".",
"cyan",
"(",
"\"%s:\"",
"%",
"theme",
".",
"id",
")",
",",
"col1",
"]",
",",
"[",
"colored",
".",
"white",
"(",
"theme",
".",
"root_path",
",",
"bold",
"=",
"True",
")",
",",
"col2",
"]",
")",
")"
]
| List all available Engineer themes. | [
"List",
"all",
"available",
"Engineer",
"themes",
"."
]
| 8884f587297f37646c40e5553174852b444a4024 | https://github.com/tylerbutler/engineer/blob/8884f587297f37646c40e5553174852b444a4024/engineer/devtools/theme_tools.py#L47-L65 | train |
rraadd88/rohan | rohan/dandage/stat/norm.py | quantile_norm | def quantile_norm(X):
"""Normalize the columns of X to each have the same distribution.
Given an expression matrix (microarray data, read counts, etc) of M genes
by N samples, quantile normalization ensures all samples have the same
spread of data (by construction).
The data across each row are averaged to obtain an average column. Each
column quantile is replaced with the corresponding quantile of the average
column.
Parameters
----------
X : 2D array of float, shape (M, N)
The input data, with M rows (genes/features) and N columns (samples).
Returns
-------
Xn : 2D array of float, shape (M, N)
The normalized data.
"""
# compute the quantiles
quantiles = np.mean(np.sort(X, axis=0), axis=1)
# compute the column-wise ranks. Each observation is replaced with its
# rank in that column: the smallest observation is replaced by 1, the
# second-smallest by 2, ..., and the largest by M, the number of rows.
ranks = np.apply_along_axis(stats.rankdata, 0, X)
# convert ranks to integer indices from 0 to M-1
rank_indices = ranks.astype(int) - 1
# index the quantiles for each rank with the ranks matrix
Xn = quantiles[rank_indices]
return(Xn) | python | def quantile_norm(X):
"""Normalize the columns of X to each have the same distribution.
Given an expression matrix (microarray data, read counts, etc) of M genes
by N samples, quantile normalization ensures all samples have the same
spread of data (by construction).
The data across each row are averaged to obtain an average column. Each
column quantile is replaced with the corresponding quantile of the average
column.
Parameters
----------
X : 2D array of float, shape (M, N)
The input data, with M rows (genes/features) and N columns (samples).
Returns
-------
Xn : 2D array of float, shape (M, N)
The normalized data.
"""
# compute the quantiles
quantiles = np.mean(np.sort(X, axis=0), axis=1)
# compute the column-wise ranks. Each observation is replaced with its
# rank in that column: the smallest observation is replaced by 1, the
# second-smallest by 2, ..., and the largest by M, the number of rows.
ranks = np.apply_along_axis(stats.rankdata, 0, X)
# convert ranks to integer indices from 0 to M-1
rank_indices = ranks.astype(int) - 1
# index the quantiles for each rank with the ranks matrix
Xn = quantiles[rank_indices]
return(Xn) | [
"def",
"quantile_norm",
"(",
"X",
")",
":",
"# compute the quantiles",
"quantiles",
"=",
"np",
".",
"mean",
"(",
"np",
".",
"sort",
"(",
"X",
",",
"axis",
"=",
"0",
")",
",",
"axis",
"=",
"1",
")",
"# compute the column-wise ranks. Each observation is replaced with its",
"# rank in that column: the smallest observation is replaced by 1, the",
"# second-smallest by 2, ..., and the largest by M, the number of rows.",
"ranks",
"=",
"np",
".",
"apply_along_axis",
"(",
"stats",
".",
"rankdata",
",",
"0",
",",
"X",
")",
"# convert ranks to integer indices from 0 to M-1",
"rank_indices",
"=",
"ranks",
".",
"astype",
"(",
"int",
")",
"-",
"1",
"# index the quantiles for each rank with the ranks matrix",
"Xn",
"=",
"quantiles",
"[",
"rank_indices",
"]",
"return",
"(",
"Xn",
")"
]
| Normalize the columns of X to each have the same distribution.
Given an expression matrix (microarray data, read counts, etc) of M genes
by N samples, quantile normalization ensures all samples have the same
spread of data (by construction).
The data across each row are averaged to obtain an average column. Each
column quantile is replaced with the corresponding quantile of the average
column.
Parameters
----------
X : 2D array of float, shape (M, N)
The input data, with M rows (genes/features) and N columns (samples).
Returns
-------
Xn : 2D array of float, shape (M, N)
The normalized data. | [
"Normalize",
"the",
"columns",
"of",
"X",
"to",
"each",
"have",
"the",
"same",
"distribution",
"."
]
| b0643a3582a2fffc0165ace69fb80880d92bfb10 | https://github.com/rraadd88/rohan/blob/b0643a3582a2fffc0165ace69fb80880d92bfb10/rohan/dandage/stat/norm.py#L4-L39 | train |
rraadd88/rohan | rohan/dandage/stat/corr.py | corrdfs | def corrdfs(df1,df2,method):
"""
df1 in columns
df2 in rows
"""
dcorr=pd.DataFrame(columns=df1.columns,index=df2.columns)
dpval=pd.DataFrame(columns=df1.columns,index=df2.columns)
for c1 in df1:
for c2 in df2:
if method=='spearman':
dcorr.loc[c2,c1],dpval.loc[c2,c1]=spearmanr(df1[c1],df2[c2],
nan_policy='omit'
)
elif method=='pearson':
dcorr.loc[c2,c1],dpval.loc[c2,c1]=pearsonr(df1[c1],df2[c2],
# nan_policy='omit'
)
if not df1.columns.name is None:
dcorr.columns.name=df1.columns.name
dpval.columns.name=df1.columns.name
if not df2.columns.name is None:
dcorr.index.name=df2.columns.name
dpval.index.name=df2.columns.name
return dcorr,dpval | python | def corrdfs(df1,df2,method):
"""
df1 in columns
df2 in rows
"""
dcorr=pd.DataFrame(columns=df1.columns,index=df2.columns)
dpval=pd.DataFrame(columns=df1.columns,index=df2.columns)
for c1 in df1:
for c2 in df2:
if method=='spearman':
dcorr.loc[c2,c1],dpval.loc[c2,c1]=spearmanr(df1[c1],df2[c2],
nan_policy='omit'
)
elif method=='pearson':
dcorr.loc[c2,c1],dpval.loc[c2,c1]=pearsonr(df1[c1],df2[c2],
# nan_policy='omit'
)
if not df1.columns.name is None:
dcorr.columns.name=df1.columns.name
dpval.columns.name=df1.columns.name
if not df2.columns.name is None:
dcorr.index.name=df2.columns.name
dpval.index.name=df2.columns.name
return dcorr,dpval | [
"def",
"corrdfs",
"(",
"df1",
",",
"df2",
",",
"method",
")",
":",
"dcorr",
"=",
"pd",
".",
"DataFrame",
"(",
"columns",
"=",
"df1",
".",
"columns",
",",
"index",
"=",
"df2",
".",
"columns",
")",
"dpval",
"=",
"pd",
".",
"DataFrame",
"(",
"columns",
"=",
"df1",
".",
"columns",
",",
"index",
"=",
"df2",
".",
"columns",
")",
"for",
"c1",
"in",
"df1",
":",
"for",
"c2",
"in",
"df2",
":",
"if",
"method",
"==",
"'spearman'",
":",
"dcorr",
".",
"loc",
"[",
"c2",
",",
"c1",
"]",
",",
"dpval",
".",
"loc",
"[",
"c2",
",",
"c1",
"]",
"=",
"spearmanr",
"(",
"df1",
"[",
"c1",
"]",
",",
"df2",
"[",
"c2",
"]",
",",
"nan_policy",
"=",
"'omit'",
")",
"elif",
"method",
"==",
"'pearson'",
":",
"dcorr",
".",
"loc",
"[",
"c2",
",",
"c1",
"]",
",",
"dpval",
".",
"loc",
"[",
"c2",
",",
"c1",
"]",
"=",
"pearsonr",
"(",
"df1",
"[",
"c1",
"]",
",",
"df2",
"[",
"c2",
"]",
",",
"# nan_policy='omit'",
")",
"if",
"not",
"df1",
".",
"columns",
".",
"name",
"is",
"None",
":",
"dcorr",
".",
"columns",
".",
"name",
"=",
"df1",
".",
"columns",
".",
"name",
"dpval",
".",
"columns",
".",
"name",
"=",
"df1",
".",
"columns",
".",
"name",
"if",
"not",
"df2",
".",
"columns",
".",
"name",
"is",
"None",
":",
"dcorr",
".",
"index",
".",
"name",
"=",
"df2",
".",
"columns",
".",
"name",
"dpval",
".",
"index",
".",
"name",
"=",
"df2",
".",
"columns",
".",
"name",
"return",
"dcorr",
",",
"dpval"
]
| df1 in columns
df2 in rows | [
"df1",
"in",
"columns",
"df2",
"in",
"rows"
]
| b0643a3582a2fffc0165ace69fb80880d92bfb10 | https://github.com/rraadd88/rohan/blob/b0643a3582a2fffc0165ace69fb80880d92bfb10/rohan/dandage/stat/corr.py#L8-L32 | train |
Genida/archan | src/archan/printing.py | pretty_description | def pretty_description(description, wrap_at=None, indent=0):
"""
Return a pretty formatted string given some text.
Args:
description (str): string to format.
wrap_at (int): maximum length of a line.
indent (int): level of indentation.
Returns:
str: pretty formatted string.
"""
if wrap_at is None or wrap_at < 0:
width = console_width(default=79)
if wrap_at is None:
wrap_at = width
else:
wrap_at += width
indent = ' ' * indent
text_wrapper = textwrap.TextWrapper(
width=wrap_at, replace_whitespace=False,
initial_indent=indent, subsequent_indent=indent)
new_desc = []
for line in description.split('\n'):
new_desc.append(line.replace('\n', '').strip())
while not new_desc[0]:
del new_desc[0]
while not new_desc[-1]:
del new_desc[-1]
separators = [i for i, l in enumerate(new_desc) if not l]
paragraphs = []
if separators:
start, end = 0, separators[0]
paragraphs.append(new_desc[start:end])
for i in range(len(separators) - 1):
start = end + 1
end = separators[i + 1]
paragraphs.append(new_desc[start:end])
paragraphs.append(new_desc[end + 1:])
return '\n\n'.join(text_wrapper.fill(' '.join(p)) for p in paragraphs)
return text_wrapper.fill(' '.join(new_desc)) | python | def pretty_description(description, wrap_at=None, indent=0):
"""
Return a pretty formatted string given some text.
Args:
description (str): string to format.
wrap_at (int): maximum length of a line.
indent (int): level of indentation.
Returns:
str: pretty formatted string.
"""
if wrap_at is None or wrap_at < 0:
width = console_width(default=79)
if wrap_at is None:
wrap_at = width
else:
wrap_at += width
indent = ' ' * indent
text_wrapper = textwrap.TextWrapper(
width=wrap_at, replace_whitespace=False,
initial_indent=indent, subsequent_indent=indent)
new_desc = []
for line in description.split('\n'):
new_desc.append(line.replace('\n', '').strip())
while not new_desc[0]:
del new_desc[0]
while not new_desc[-1]:
del new_desc[-1]
separators = [i for i, l in enumerate(new_desc) if not l]
paragraphs = []
if separators:
start, end = 0, separators[0]
paragraphs.append(new_desc[start:end])
for i in range(len(separators) - 1):
start = end + 1
end = separators[i + 1]
paragraphs.append(new_desc[start:end])
paragraphs.append(new_desc[end + 1:])
return '\n\n'.join(text_wrapper.fill(' '.join(p)) for p in paragraphs)
return text_wrapper.fill(' '.join(new_desc)) | [
"def",
"pretty_description",
"(",
"description",
",",
"wrap_at",
"=",
"None",
",",
"indent",
"=",
"0",
")",
":",
"if",
"wrap_at",
"is",
"None",
"or",
"wrap_at",
"<",
"0",
":",
"width",
"=",
"console_width",
"(",
"default",
"=",
"79",
")",
"if",
"wrap_at",
"is",
"None",
":",
"wrap_at",
"=",
"width",
"else",
":",
"wrap_at",
"+=",
"width",
"indent",
"=",
"' '",
"*",
"indent",
"text_wrapper",
"=",
"textwrap",
".",
"TextWrapper",
"(",
"width",
"=",
"wrap_at",
",",
"replace_whitespace",
"=",
"False",
",",
"initial_indent",
"=",
"indent",
",",
"subsequent_indent",
"=",
"indent",
")",
"new_desc",
"=",
"[",
"]",
"for",
"line",
"in",
"description",
".",
"split",
"(",
"'\\n'",
")",
":",
"new_desc",
".",
"append",
"(",
"line",
".",
"replace",
"(",
"'\\n'",
",",
"''",
")",
".",
"strip",
"(",
")",
")",
"while",
"not",
"new_desc",
"[",
"0",
"]",
":",
"del",
"new_desc",
"[",
"0",
"]",
"while",
"not",
"new_desc",
"[",
"-",
"1",
"]",
":",
"del",
"new_desc",
"[",
"-",
"1",
"]",
"separators",
"=",
"[",
"i",
"for",
"i",
",",
"l",
"in",
"enumerate",
"(",
"new_desc",
")",
"if",
"not",
"l",
"]",
"paragraphs",
"=",
"[",
"]",
"if",
"separators",
":",
"start",
",",
"end",
"=",
"0",
",",
"separators",
"[",
"0",
"]",
"paragraphs",
".",
"append",
"(",
"new_desc",
"[",
"start",
":",
"end",
"]",
")",
"for",
"i",
"in",
"range",
"(",
"len",
"(",
"separators",
")",
"-",
"1",
")",
":",
"start",
"=",
"end",
"+",
"1",
"end",
"=",
"separators",
"[",
"i",
"+",
"1",
"]",
"paragraphs",
".",
"append",
"(",
"new_desc",
"[",
"start",
":",
"end",
"]",
")",
"paragraphs",
".",
"append",
"(",
"new_desc",
"[",
"end",
"+",
"1",
":",
"]",
")",
"return",
"'\\n\\n'",
".",
"join",
"(",
"text_wrapper",
".",
"fill",
"(",
"' '",
".",
"join",
"(",
"p",
")",
")",
"for",
"p",
"in",
"paragraphs",
")",
"return",
"text_wrapper",
".",
"fill",
"(",
"' '",
".",
"join",
"(",
"new_desc",
")",
")"
]
| Return a pretty formatted string given some text.
Args:
description (str): string to format.
wrap_at (int): maximum length of a line.
indent (int): level of indentation.
Returns:
str: pretty formatted string. | [
"Return",
"a",
"pretty",
"formatted",
"string",
"given",
"some",
"text",
"."
]
| a026d3105c7e86f30e6c9507b93ceb736684bfdc | https://github.com/Genida/archan/blob/a026d3105c7e86f30e6c9507b93ceb736684bfdc/src/archan/printing.py#L31-L72 | train |
Genida/archan | src/archan/printing.py | PrintableNameMixin.print_name | def print_name(self, indent=0, end='\n'):
"""Print name with optional indent and end."""
print(Style.BRIGHT + ' ' * indent + self.name, end=end) | python | def print_name(self, indent=0, end='\n'):
"""Print name with optional indent and end."""
print(Style.BRIGHT + ' ' * indent + self.name, end=end) | [
"def",
"print_name",
"(",
"self",
",",
"indent",
"=",
"0",
",",
"end",
"=",
"'\\n'",
")",
":",
"print",
"(",
"Style",
".",
"BRIGHT",
"+",
"' '",
"*",
"indent",
"+",
"self",
".",
"name",
",",
"end",
"=",
"end",
")"
]
| Print name with optional indent and end. | [
"Print",
"name",
"with",
"optional",
"indent",
"and",
"end",
"."
]
| a026d3105c7e86f30e6c9507b93ceb736684bfdc | https://github.com/Genida/archan/blob/a026d3105c7e86f30e6c9507b93ceb736684bfdc/src/archan/printing.py#L78-L80 | train |
Genida/archan | src/archan/printing.py | PrintablePluginMixin.print | def print(self):
"""Print self."""
print(
'{dim}Identifier:{none} {cyan}{identifier}{none}\n'
'{dim}Name:{none} {name}\n'
'{dim}Description:{none}\n{description}'.format(
dim=Style.DIM,
cyan=Fore.CYAN,
none=Style.RESET_ALL,
identifier=self.identifier,
name=self.name,
description=pretty_description(self.description, indent=2)
)
)
if hasattr(self, 'argument_list') and self.argument_list:
print('{dim}Arguments:{none}'.format(
dim=Style.DIM, none=Style.RESET_ALL))
for argument in self.argument_list:
argument.print(indent=2) | python | def print(self):
"""Print self."""
print(
'{dim}Identifier:{none} {cyan}{identifier}{none}\n'
'{dim}Name:{none} {name}\n'
'{dim}Description:{none}\n{description}'.format(
dim=Style.DIM,
cyan=Fore.CYAN,
none=Style.RESET_ALL,
identifier=self.identifier,
name=self.name,
description=pretty_description(self.description, indent=2)
)
)
if hasattr(self, 'argument_list') and self.argument_list:
print('{dim}Arguments:{none}'.format(
dim=Style.DIM, none=Style.RESET_ALL))
for argument in self.argument_list:
argument.print(indent=2) | [
"def",
"print",
"(",
"self",
")",
":",
"print",
"(",
"'{dim}Identifier:{none} {cyan}{identifier}{none}\\n'",
"'{dim}Name:{none} {name}\\n'",
"'{dim}Description:{none}\\n{description}'",
".",
"format",
"(",
"dim",
"=",
"Style",
".",
"DIM",
",",
"cyan",
"=",
"Fore",
".",
"CYAN",
",",
"none",
"=",
"Style",
".",
"RESET_ALL",
",",
"identifier",
"=",
"self",
".",
"identifier",
",",
"name",
"=",
"self",
".",
"name",
",",
"description",
"=",
"pretty_description",
"(",
"self",
".",
"description",
",",
"indent",
"=",
"2",
")",
")",
")",
"if",
"hasattr",
"(",
"self",
",",
"'argument_list'",
")",
"and",
"self",
".",
"argument_list",
":",
"print",
"(",
"'{dim}Arguments:{none}'",
".",
"format",
"(",
"dim",
"=",
"Style",
".",
"DIM",
",",
"none",
"=",
"Style",
".",
"RESET_ALL",
")",
")",
"for",
"argument",
"in",
"self",
".",
"argument_list",
":",
"argument",
".",
"print",
"(",
"indent",
"=",
"2",
")"
]
| Print self. | [
"Print",
"self",
"."
]
| a026d3105c7e86f30e6c9507b93ceb736684bfdc | https://github.com/Genida/archan/blob/a026d3105c7e86f30e6c9507b93ceb736684bfdc/src/archan/printing.py#L111-L130 | train |
UMIACS/qav | qav/filters.py | DynamicFilter.filter | def filter(self, value, table=None):
'''
Return True if the value should be pruned; False otherwise.
If a `table` argument was provided, pass it to filterable_func.
'''
if table is not None:
filterable = self.filterable_func(value, table)
else:
filterable = self.filterable_func(value)
return filterable | python | def filter(self, value, table=None):
'''
Return True if the value should be pruned; False otherwise.
If a `table` argument was provided, pass it to filterable_func.
'''
if table is not None:
filterable = self.filterable_func(value, table)
else:
filterable = self.filterable_func(value)
return filterable | [
"def",
"filter",
"(",
"self",
",",
"value",
",",
"table",
"=",
"None",
")",
":",
"if",
"table",
"is",
"not",
"None",
":",
"filterable",
"=",
"self",
".",
"filterable_func",
"(",
"value",
",",
"table",
")",
"else",
":",
"filterable",
"=",
"self",
".",
"filterable_func",
"(",
"value",
")",
"return",
"filterable"
]
| Return True if the value should be pruned; False otherwise.
If a `table` argument was provided, pass it to filterable_func. | [
"Return",
"True",
"if",
"the",
"value",
"should",
"be",
"pruned",
";",
"False",
"otherwise",
"."
]
| f92108855f9fcbe3ccea5fc6f683bd90a6e18e1b | https://github.com/UMIACS/qav/blob/f92108855f9fcbe3ccea5fc6f683bd90a6e18e1b/qav/filters.py#L21-L31 | train |
Genida/archan | src/archan/plugins/providers.py | CSVInput.get_data | def get_data(self,
file_path=sys.stdin,
delimiter=',',
categories_delimiter=None):
"""
Implement get_dsm method from Provider class.
Parse CSV to return an instance of DSM.
Args:
file_path (str/fd): path or file descriptor.
delimiter (str): character(s) used as delimiter for columns.
categories_delimiter (str):
character(s) used as delimiter for categories and keys
(first column).
Returns:
DSM: instance of DSM.
"""
if file_path == sys.stdin:
logger.info('Read data from standard input')
lines = [line.replace('\n', '') for line in file_path]
else:
logger.info('Read data from file ' + file_path)
with open(file_path) as file:
lines = list(file)
columns = lines[0].rstrip('\n').split(delimiter)[1:]
categories = None
if categories_delimiter:
columns, categories = zip(*[c.split(categories_delimiter, 1)
for c in columns])
size = len(columns)
data = [list(map(int, l.split(delimiter)[1:]))
for l in lines[1:size + 1]]
return DesignStructureMatrix(data, columns, categories) | python | def get_data(self,
file_path=sys.stdin,
delimiter=',',
categories_delimiter=None):
"""
Implement get_dsm method from Provider class.
Parse CSV to return an instance of DSM.
Args:
file_path (str/fd): path or file descriptor.
delimiter (str): character(s) used as delimiter for columns.
categories_delimiter (str):
character(s) used as delimiter for categories and keys
(first column).
Returns:
DSM: instance of DSM.
"""
if file_path == sys.stdin:
logger.info('Read data from standard input')
lines = [line.replace('\n', '') for line in file_path]
else:
logger.info('Read data from file ' + file_path)
with open(file_path) as file:
lines = list(file)
columns = lines[0].rstrip('\n').split(delimiter)[1:]
categories = None
if categories_delimiter:
columns, categories = zip(*[c.split(categories_delimiter, 1)
for c in columns])
size = len(columns)
data = [list(map(int, l.split(delimiter)[1:]))
for l in lines[1:size + 1]]
return DesignStructureMatrix(data, columns, categories) | [
"def",
"get_data",
"(",
"self",
",",
"file_path",
"=",
"sys",
".",
"stdin",
",",
"delimiter",
"=",
"','",
",",
"categories_delimiter",
"=",
"None",
")",
":",
"if",
"file_path",
"==",
"sys",
".",
"stdin",
":",
"logger",
".",
"info",
"(",
"'Read data from standard input'",
")",
"lines",
"=",
"[",
"line",
".",
"replace",
"(",
"'\\n'",
",",
"''",
")",
"for",
"line",
"in",
"file_path",
"]",
"else",
":",
"logger",
".",
"info",
"(",
"'Read data from file '",
"+",
"file_path",
")",
"with",
"open",
"(",
"file_path",
")",
"as",
"file",
":",
"lines",
"=",
"list",
"(",
"file",
")",
"columns",
"=",
"lines",
"[",
"0",
"]",
".",
"rstrip",
"(",
"'\\n'",
")",
".",
"split",
"(",
"delimiter",
")",
"[",
"1",
":",
"]",
"categories",
"=",
"None",
"if",
"categories_delimiter",
":",
"columns",
",",
"categories",
"=",
"zip",
"(",
"*",
"[",
"c",
".",
"split",
"(",
"categories_delimiter",
",",
"1",
")",
"for",
"c",
"in",
"columns",
"]",
")",
"size",
"=",
"len",
"(",
"columns",
")",
"data",
"=",
"[",
"list",
"(",
"map",
"(",
"int",
",",
"l",
".",
"split",
"(",
"delimiter",
")",
"[",
"1",
":",
"]",
")",
")",
"for",
"l",
"in",
"lines",
"[",
"1",
":",
"size",
"+",
"1",
"]",
"]",
"return",
"DesignStructureMatrix",
"(",
"data",
",",
"columns",
",",
"categories",
")"
]
| Implement get_dsm method from Provider class.
Parse CSV to return an instance of DSM.
Args:
file_path (str/fd): path or file descriptor.
delimiter (str): character(s) used as delimiter for columns.
categories_delimiter (str):
character(s) used as delimiter for categories and keys
(first column).
Returns:
DSM: instance of DSM. | [
"Implement",
"get_dsm",
"method",
"from",
"Provider",
"class",
"."
]
| a026d3105c7e86f30e6c9507b93ceb736684bfdc | https://github.com/Genida/archan/blob/a026d3105c7e86f30e6c9507b93ceb736684bfdc/src/archan/plugins/providers.py#L28-L62 | train |
jmbeach/KEP.py | src/keppy/tag_group.py | TagGroup.parse_tags | def parse_tags(self):
"""Parses tags in tag group"""
tags = []
try:
for tag in self._tag_group_dict["tags"]:
tags.append(Tag(tag))
except:
return tags
return tags | python | def parse_tags(self):
"""Parses tags in tag group"""
tags = []
try:
for tag in self._tag_group_dict["tags"]:
tags.append(Tag(tag))
except:
return tags
return tags | [
"def",
"parse_tags",
"(",
"self",
")",
":",
"tags",
"=",
"[",
"]",
"try",
":",
"for",
"tag",
"in",
"self",
".",
"_tag_group_dict",
"[",
"\"tags\"",
"]",
":",
"tags",
".",
"append",
"(",
"Tag",
"(",
"tag",
")",
")",
"except",
":",
"return",
"tags",
"return",
"tags"
]
| Parses tags in tag group | [
"Parses",
"tags",
"in",
"tag",
"group"
]
| 68cda64ab649640a486534867c81274c41e39446 | https://github.com/jmbeach/KEP.py/blob/68cda64ab649640a486534867c81274c41e39446/src/keppy/tag_group.py#L18-L26 | train |
jmbeach/KEP.py | src/keppy/tag_group.py | TagGroup.update | def update(self):
"""Updates the dictionary of the tag group"""
if self._is_ignored or "tags" not in self._tag_group_dict:
return
for i in range(len(self._tag_group_dict["tags"])):
tag_dict = self._tag_group_dict["tags"][i]
for tag in self._tags:
if tag.name == tag_dict["common.ALLTYPES_NAME"]:
self._tag_group_dict["tags"][i] = tag.as_dict()
break
for i in range(len(self._sub_groups)):
sub_group = self._sub_groups[i]
sub_group.update()
self._tag_group_dict["tag_groups"][i] = sub_group.as_dict() | python | def update(self):
"""Updates the dictionary of the tag group"""
if self._is_ignored or "tags" not in self._tag_group_dict:
return
for i in range(len(self._tag_group_dict["tags"])):
tag_dict = self._tag_group_dict["tags"][i]
for tag in self._tags:
if tag.name == tag_dict["common.ALLTYPES_NAME"]:
self._tag_group_dict["tags"][i] = tag.as_dict()
break
for i in range(len(self._sub_groups)):
sub_group = self._sub_groups[i]
sub_group.update()
self._tag_group_dict["tag_groups"][i] = sub_group.as_dict() | [
"def",
"update",
"(",
"self",
")",
":",
"if",
"self",
".",
"_is_ignored",
"or",
"\"tags\"",
"not",
"in",
"self",
".",
"_tag_group_dict",
":",
"return",
"for",
"i",
"in",
"range",
"(",
"len",
"(",
"self",
".",
"_tag_group_dict",
"[",
"\"tags\"",
"]",
")",
")",
":",
"tag_dict",
"=",
"self",
".",
"_tag_group_dict",
"[",
"\"tags\"",
"]",
"[",
"i",
"]",
"for",
"tag",
"in",
"self",
".",
"_tags",
":",
"if",
"tag",
".",
"name",
"==",
"tag_dict",
"[",
"\"common.ALLTYPES_NAME\"",
"]",
":",
"self",
".",
"_tag_group_dict",
"[",
"\"tags\"",
"]",
"[",
"i",
"]",
"=",
"tag",
".",
"as_dict",
"(",
")",
"break",
"for",
"i",
"in",
"range",
"(",
"len",
"(",
"self",
".",
"_sub_groups",
")",
")",
":",
"sub_group",
"=",
"self",
".",
"_sub_groups",
"[",
"i",
"]",
"sub_group",
".",
"update",
"(",
")",
"self",
".",
"_tag_group_dict",
"[",
"\"tag_groups\"",
"]",
"[",
"i",
"]",
"=",
"sub_group",
".",
"as_dict",
"(",
")"
]
| Updates the dictionary of the tag group | [
"Updates",
"the",
"dictionary",
"of",
"the",
"tag",
"group"
]
| 68cda64ab649640a486534867c81274c41e39446 | https://github.com/jmbeach/KEP.py/blob/68cda64ab649640a486534867c81274c41e39446/src/keppy/tag_group.py#L56-L70 | train |
tjcsl/cslbot | cslbot/commands/wolf.py | cmd | def cmd(send, msg, args):
"""Queries WolframAlpha.
Syntax: {command} <expression>
"""
if not msg:
send("Evaluate what?")
return
params = {'format': 'plaintext', 'reinterpret': 'true', 'input': msg, 'appid': args['config']['api']['wolframapikey']}
req = get('http://api.wolframalpha.com/v2/query', params=params)
if req.status_code == 403:
send("WolframAlpha is having issues.")
return
if not req.content:
send("WolframAlpha returned an empty response.")
return
xml = fromstring(req.content)
output = xml.findall('./pod')
key = args['config']['api']['bitlykey']
url = get_short("http://www.wolframalpha.com/input/?i=%s" % quote(msg), key)
text = "No output found."
for x in output:
if 'primary' in x.keys():
text = x.find('./subpod/plaintext').text
if text is None:
send("No Output parsable")
else:
# Only send the first three lines of output
for t in text.splitlines()[:3]:
send(t)
send("See %s for more info" % url) | python | def cmd(send, msg, args):
"""Queries WolframAlpha.
Syntax: {command} <expression>
"""
if not msg:
send("Evaluate what?")
return
params = {'format': 'plaintext', 'reinterpret': 'true', 'input': msg, 'appid': args['config']['api']['wolframapikey']}
req = get('http://api.wolframalpha.com/v2/query', params=params)
if req.status_code == 403:
send("WolframAlpha is having issues.")
return
if not req.content:
send("WolframAlpha returned an empty response.")
return
xml = fromstring(req.content)
output = xml.findall('./pod')
key = args['config']['api']['bitlykey']
url = get_short("http://www.wolframalpha.com/input/?i=%s" % quote(msg), key)
text = "No output found."
for x in output:
if 'primary' in x.keys():
text = x.find('./subpod/plaintext').text
if text is None:
send("No Output parsable")
else:
# Only send the first three lines of output
for t in text.splitlines()[:3]:
send(t)
send("See %s for more info" % url) | [
"def",
"cmd",
"(",
"send",
",",
"msg",
",",
"args",
")",
":",
"if",
"not",
"msg",
":",
"send",
"(",
"\"Evaluate what?\"",
")",
"return",
"params",
"=",
"{",
"'format'",
":",
"'plaintext'",
",",
"'reinterpret'",
":",
"'true'",
",",
"'input'",
":",
"msg",
",",
"'appid'",
":",
"args",
"[",
"'config'",
"]",
"[",
"'api'",
"]",
"[",
"'wolframapikey'",
"]",
"}",
"req",
"=",
"get",
"(",
"'http://api.wolframalpha.com/v2/query'",
",",
"params",
"=",
"params",
")",
"if",
"req",
".",
"status_code",
"==",
"403",
":",
"send",
"(",
"\"WolframAlpha is having issues.\"",
")",
"return",
"if",
"not",
"req",
".",
"content",
":",
"send",
"(",
"\"WolframAlpha returned an empty response.\"",
")",
"return",
"xml",
"=",
"fromstring",
"(",
"req",
".",
"content",
")",
"output",
"=",
"xml",
".",
"findall",
"(",
"'./pod'",
")",
"key",
"=",
"args",
"[",
"'config'",
"]",
"[",
"'api'",
"]",
"[",
"'bitlykey'",
"]",
"url",
"=",
"get_short",
"(",
"\"http://www.wolframalpha.com/input/?i=%s\"",
"%",
"quote",
"(",
"msg",
")",
",",
"key",
")",
"text",
"=",
"\"No output found.\"",
"for",
"x",
"in",
"output",
":",
"if",
"'primary'",
"in",
"x",
".",
"keys",
"(",
")",
":",
"text",
"=",
"x",
".",
"find",
"(",
"'./subpod/plaintext'",
")",
".",
"text",
"if",
"text",
"is",
"None",
":",
"send",
"(",
"\"No Output parsable\"",
")",
"else",
":",
"# Only send the first three lines of output",
"for",
"t",
"in",
"text",
".",
"splitlines",
"(",
")",
"[",
":",
"3",
"]",
":",
"send",
"(",
"t",
")",
"send",
"(",
"\"See %s for more info\"",
"%",
"url",
")"
]
| Queries WolframAlpha.
Syntax: {command} <expression> | [
"Queries",
"WolframAlpha",
"."
]
| aebe07be47141f61d7c180706bddfb707f19b2b5 | https://github.com/tjcsl/cslbot/blob/aebe07be47141f61d7c180706bddfb707f19b2b5/cslbot/commands/wolf.py#L28-L59 | train |
stephan-mclean/KickassTorrentsAPI | kat.py | _get_soup | def _get_soup(page):
"""Return BeautifulSoup object for given page"""
request = requests.get(page)
data = request.text
return bs4.BeautifulSoup(data) | python | def _get_soup(page):
"""Return BeautifulSoup object for given page"""
request = requests.get(page)
data = request.text
return bs4.BeautifulSoup(data) | [
"def",
"_get_soup",
"(",
"page",
")",
":",
"request",
"=",
"requests",
".",
"get",
"(",
"page",
")",
"data",
"=",
"request",
".",
"text",
"return",
"bs4",
".",
"BeautifulSoup",
"(",
"data",
")"
]
| Return BeautifulSoup object for given page | [
"Return",
"BeautifulSoup",
"object",
"for",
"given",
"page"
]
| 4d867a090c06ce95b9ed996b48092cb5bfe28bbd | https://github.com/stephan-mclean/KickassTorrentsAPI/blob/4d867a090c06ce95b9ed996b48092cb5bfe28bbd/kat.py#L37-L41 | train |
stephan-mclean/KickassTorrentsAPI | kat.py | search | def search(term, category=Categories.ALL, pages=1, sort=None, order=None):
"""Return a search result for term in category. Can also be
sorted and span multiple pages."""
s = Search()
s.search(term=term, category=category, pages=pages, sort=sort, order=order)
return s | python | def search(term, category=Categories.ALL, pages=1, sort=None, order=None):
"""Return a search result for term in category. Can also be
sorted and span multiple pages."""
s = Search()
s.search(term=term, category=category, pages=pages, sort=sort, order=order)
return s | [
"def",
"search",
"(",
"term",
",",
"category",
"=",
"Categories",
".",
"ALL",
",",
"pages",
"=",
"1",
",",
"sort",
"=",
"None",
",",
"order",
"=",
"None",
")",
":",
"s",
"=",
"Search",
"(",
")",
"s",
".",
"search",
"(",
"term",
"=",
"term",
",",
"category",
"=",
"category",
",",
"pages",
"=",
"pages",
",",
"sort",
"=",
"sort",
",",
"order",
"=",
"order",
")",
"return",
"s"
]
| Return a search result for term in category. Can also be
sorted and span multiple pages. | [
"Return",
"a",
"search",
"result",
"for",
"term",
"in",
"category",
".",
"Can",
"also",
"be",
"sorted",
"and",
"span",
"multiple",
"pages",
"."
]
| 4d867a090c06ce95b9ed996b48092cb5bfe28bbd | https://github.com/stephan-mclean/KickassTorrentsAPI/blob/4d867a090c06ce95b9ed996b48092cb5bfe28bbd/kat.py#L334-L339 | train |
stephan-mclean/KickassTorrentsAPI | kat.py | popular | def popular(category=None, sortOption = "title"):
"""Return a search result containing torrents appearing
on the KAT home page. Can be categorized. Cannot be
sorted or contain multiple pages"""
s = Search()
s.popular(category, sortOption)
return s | python | def popular(category=None, sortOption = "title"):
"""Return a search result containing torrents appearing
on the KAT home page. Can be categorized. Cannot be
sorted or contain multiple pages"""
s = Search()
s.popular(category, sortOption)
return s | [
"def",
"popular",
"(",
"category",
"=",
"None",
",",
"sortOption",
"=",
"\"title\"",
")",
":",
"s",
"=",
"Search",
"(",
")",
"s",
".",
"popular",
"(",
"category",
",",
"sortOption",
")",
"return",
"s"
]
| Return a search result containing torrents appearing
on the KAT home page. Can be categorized. Cannot be
sorted or contain multiple pages | [
"Return",
"a",
"search",
"result",
"containing",
"torrents",
"appearing",
"on",
"the",
"KAT",
"home",
"page",
".",
"Can",
"be",
"categorized",
".",
"Cannot",
"be",
"sorted",
"or",
"contain",
"multiple",
"pages"
]
| 4d867a090c06ce95b9ed996b48092cb5bfe28bbd | https://github.com/stephan-mclean/KickassTorrentsAPI/blob/4d867a090c06ce95b9ed996b48092cb5bfe28bbd/kat.py#L341-L347 | train |
stephan-mclean/KickassTorrentsAPI | kat.py | recent | def recent(category=None, pages=1, sort=None, order=None):
"""Return most recently added torrents. Can be sorted and categorized
and contain multiple pages."""
s = Search()
s.recent(category, pages, sort, order)
return s | python | def recent(category=None, pages=1, sort=None, order=None):
"""Return most recently added torrents. Can be sorted and categorized
and contain multiple pages."""
s = Search()
s.recent(category, pages, sort, order)
return s | [
"def",
"recent",
"(",
"category",
"=",
"None",
",",
"pages",
"=",
"1",
",",
"sort",
"=",
"None",
",",
"order",
"=",
"None",
")",
":",
"s",
"=",
"Search",
"(",
")",
"s",
".",
"recent",
"(",
"category",
",",
"pages",
",",
"sort",
",",
"order",
")",
"return",
"s"
]
| Return most recently added torrents. Can be sorted and categorized
and contain multiple pages. | [
"Return",
"most",
"recently",
"added",
"torrents",
".",
"Can",
"be",
"sorted",
"and",
"categorized",
"and",
"contain",
"multiple",
"pages",
"."
]
| 4d867a090c06ce95b9ed996b48092cb5bfe28bbd | https://github.com/stephan-mclean/KickassTorrentsAPI/blob/4d867a090c06ce95b9ed996b48092cb5bfe28bbd/kat.py#L349-L354 | train |
stephan-mclean/KickassTorrentsAPI | kat.py | Torrent.print_details | def print_details(self):
"""Print torrent details"""
print("Title:", self.title)
print("Category:", self.category)
print("Page: ", self.page)
print("Size: ", self.size)
print("Files: ", self.files)
print("Age: ", self.age)
print("Seeds:", self.seeders)
print("Leechers: ", self.leechers)
print("Magnet: ", self.magnet)
print("Download: ", self.download)
print("Verified:", self.isVerified) | python | def print_details(self):
"""Print torrent details"""
print("Title:", self.title)
print("Category:", self.category)
print("Page: ", self.page)
print("Size: ", self.size)
print("Files: ", self.files)
print("Age: ", self.age)
print("Seeds:", self.seeders)
print("Leechers: ", self.leechers)
print("Magnet: ", self.magnet)
print("Download: ", self.download)
print("Verified:", self.isVerified) | [
"def",
"print_details",
"(",
"self",
")",
":",
"print",
"(",
"\"Title:\"",
",",
"self",
".",
"title",
")",
"print",
"(",
"\"Category:\"",
",",
"self",
".",
"category",
")",
"print",
"(",
"\"Page: \"",
",",
"self",
".",
"page",
")",
"print",
"(",
"\"Size: \"",
",",
"self",
".",
"size",
")",
"print",
"(",
"\"Files: \"",
",",
"self",
".",
"files",
")",
"print",
"(",
"\"Age: \"",
",",
"self",
".",
"age",
")",
"print",
"(",
"\"Seeds:\"",
",",
"self",
".",
"seeders",
")",
"print",
"(",
"\"Leechers: \"",
",",
"self",
".",
"leechers",
")",
"print",
"(",
"\"Magnet: \"",
",",
"self",
".",
"magnet",
")",
"print",
"(",
"\"Download: \"",
",",
"self",
".",
"download",
")",
"print",
"(",
"\"Verified:\"",
",",
"self",
".",
"isVerified",
")"
]
| Print torrent details | [
"Print",
"torrent",
"details"
]
| 4d867a090c06ce95b9ed996b48092cb5bfe28bbd | https://github.com/stephan-mclean/KickassTorrentsAPI/blob/4d867a090c06ce95b9ed996b48092cb5bfe28bbd/kat.py#L98-L110 | train |
stephan-mclean/KickassTorrentsAPI | kat.py | Search.search | def search(self, term=None, category=None, pages=1, url=search_url,
sort=None, order=None):
"""Search a given URL for torrent results."""
if not self.current_url:
self.current_url = url
if self.current_url == Search.base_url:
# Searching home page so no formatting
results = self._get_results(self.current_url)
self._add_results(results)
else:
search = self._format_search(term, category)
sorting = self._format_sort(sort, order)
# Now get the results.
for i in range(pages):
results = self._get_results(search + "/" + str(self._current_page) +
"/" + sorting)
self._add_results(results)
self._current_page += 1
self._current_page -= 1 | python | def search(self, term=None, category=None, pages=1, url=search_url,
sort=None, order=None):
"""Search a given URL for torrent results."""
if not self.current_url:
self.current_url = url
if self.current_url == Search.base_url:
# Searching home page so no formatting
results = self._get_results(self.current_url)
self._add_results(results)
else:
search = self._format_search(term, category)
sorting = self._format_sort(sort, order)
# Now get the results.
for i in range(pages):
results = self._get_results(search + "/" + str(self._current_page) +
"/" + sorting)
self._add_results(results)
self._current_page += 1
self._current_page -= 1 | [
"def",
"search",
"(",
"self",
",",
"term",
"=",
"None",
",",
"category",
"=",
"None",
",",
"pages",
"=",
"1",
",",
"url",
"=",
"search_url",
",",
"sort",
"=",
"None",
",",
"order",
"=",
"None",
")",
":",
"if",
"not",
"self",
".",
"current_url",
":",
"self",
".",
"current_url",
"=",
"url",
"if",
"self",
".",
"current_url",
"==",
"Search",
".",
"base_url",
":",
"# Searching home page so no formatting",
"results",
"=",
"self",
".",
"_get_results",
"(",
"self",
".",
"current_url",
")",
"self",
".",
"_add_results",
"(",
"results",
")",
"else",
":",
"search",
"=",
"self",
".",
"_format_search",
"(",
"term",
",",
"category",
")",
"sorting",
"=",
"self",
".",
"_format_sort",
"(",
"sort",
",",
"order",
")",
"# Now get the results.",
"for",
"i",
"in",
"range",
"(",
"pages",
")",
":",
"results",
"=",
"self",
".",
"_get_results",
"(",
"search",
"+",
"\"/\"",
"+",
"str",
"(",
"self",
".",
"_current_page",
")",
"+",
"\"/\"",
"+",
"sorting",
")",
"self",
".",
"_add_results",
"(",
"results",
")",
"self",
".",
"_current_page",
"+=",
"1",
"self",
".",
"_current_page",
"-=",
"1"
]
| Search a given URL for torrent results. | [
"Search",
"a",
"given",
"URL",
"for",
"torrent",
"results",
"."
]
| 4d867a090c06ce95b9ed996b48092cb5bfe28bbd | https://github.com/stephan-mclean/KickassTorrentsAPI/blob/4d867a090c06ce95b9ed996b48092cb5bfe28bbd/kat.py#L161-L183 | train |
stephan-mclean/KickassTorrentsAPI | kat.py | Search._categorize | def _categorize(self, category):
"""Remove torrents with unwanted category from self.torrents"""
self.torrents = [result for result in self.torrents
if result.category == category] | python | def _categorize(self, category):
"""Remove torrents with unwanted category from self.torrents"""
self.torrents = [result for result in self.torrents
if result.category == category] | [
"def",
"_categorize",
"(",
"self",
",",
"category",
")",
":",
"self",
".",
"torrents",
"=",
"[",
"result",
"for",
"result",
"in",
"self",
".",
"torrents",
"if",
"result",
".",
"category",
"==",
"category",
"]"
]
| Remove torrents with unwanted category from self.torrents | [
"Remove",
"torrents",
"with",
"unwanted",
"category",
"from",
"self",
".",
"torrents"
]
| 4d867a090c06ce95b9ed996b48092cb5bfe28bbd | https://github.com/stephan-mclean/KickassTorrentsAPI/blob/4d867a090c06ce95b9ed996b48092cb5bfe28bbd/kat.py#L197-L200 | train |
stephan-mclean/KickassTorrentsAPI | kat.py | Search.page | def page(self, i):
"""Get page i of search results"""
# Need to clear previous results.
self.torrents = list()
self._current_page = i
self.search(term=self.term, category=self.category,
sort=self.sort, order=self.order) | python | def page(self, i):
"""Get page i of search results"""
# Need to clear previous results.
self.torrents = list()
self._current_page = i
self.search(term=self.term, category=self.category,
sort=self.sort, order=self.order) | [
"def",
"page",
"(",
"self",
",",
"i",
")",
":",
"# Need to clear previous results.",
"self",
".",
"torrents",
"=",
"list",
"(",
")",
"self",
".",
"_current_page",
"=",
"i",
"self",
".",
"search",
"(",
"term",
"=",
"self",
".",
"term",
",",
"category",
"=",
"self",
".",
"category",
",",
"sort",
"=",
"self",
".",
"sort",
",",
"order",
"=",
"self",
".",
"order",
")"
]
| Get page i of search results | [
"Get",
"page",
"i",
"of",
"search",
"results"
]
| 4d867a090c06ce95b9ed996b48092cb5bfe28bbd | https://github.com/stephan-mclean/KickassTorrentsAPI/blob/4d867a090c06ce95b9ed996b48092cb5bfe28bbd/kat.py#L225-L231 | train |
stephan-mclean/KickassTorrentsAPI | kat.py | Search._get_results | def _get_results(self, page):
"""Find every div tag containing torrent details on given page,
then parse the results into a list of Torrents and return them"""
soup = _get_soup(page)
details = soup.find_all("tr", class_="odd")
even = soup.find_all("tr", class_="even")
# Join the results
for i in range(len(even)):
details.insert((i * 2)+1, even[i])
return self._parse_details(details) | python | def _get_results(self, page):
"""Find every div tag containing torrent details on given page,
then parse the results into a list of Torrents and return them"""
soup = _get_soup(page)
details = soup.find_all("tr", class_="odd")
even = soup.find_all("tr", class_="even")
# Join the results
for i in range(len(even)):
details.insert((i * 2)+1, even[i])
return self._parse_details(details) | [
"def",
"_get_results",
"(",
"self",
",",
"page",
")",
":",
"soup",
"=",
"_get_soup",
"(",
"page",
")",
"details",
"=",
"soup",
".",
"find_all",
"(",
"\"tr\"",
",",
"class_",
"=",
"\"odd\"",
")",
"even",
"=",
"soup",
".",
"find_all",
"(",
"\"tr\"",
",",
"class_",
"=",
"\"even\"",
")",
"# Join the results",
"for",
"i",
"in",
"range",
"(",
"len",
"(",
"even",
")",
")",
":",
"details",
".",
"insert",
"(",
"(",
"i",
"*",
"2",
")",
"+",
"1",
",",
"even",
"[",
"i",
"]",
")",
"return",
"self",
".",
"_parse_details",
"(",
"details",
")"
]
| Find every div tag containing torrent details on given page,
then parse the results into a list of Torrents and return them | [
"Find",
"every",
"div",
"tag",
"containing",
"torrent",
"details",
"on",
"given",
"page",
"then",
"parse",
"the",
"results",
"into",
"a",
"list",
"of",
"Torrents",
"and",
"return",
"them"
]
| 4d867a090c06ce95b9ed996b48092cb5bfe28bbd | https://github.com/stephan-mclean/KickassTorrentsAPI/blob/4d867a090c06ce95b9ed996b48092cb5bfe28bbd/kat.py#L237-L248 | train |
stephan-mclean/KickassTorrentsAPI | kat.py | Search._parse_details | def _parse_details(self, tag_list):
"""Given a list of tags from either a search page or the
KAT home page parse the details and return a list of
Torrents"""
result = list()
for i, item in enumerate(tag_list):
title = item.find("a", class_="cellMainLink")
title_text = title.text
link = title.get("href")
tds = item.find_all("td", class_="center") # Better name here.
size = tds[0].text
files = tds[1].text
age = tds[2].text
seed = tds[3].text
leech = tds[4].text
magnet = item.find("a", class_="imagnet icon16")
download = item.find("a", class_="idownload icon16")
isVerified = item.find("a", class_="iverify icon16") != None
# Home page doesn't have magnet or download links
if magnet:
magnet = magnet.get("href")
if download:
download = download.get("href")
# Get category changes depending on if we're parsing
# the home page or a search page.
if self.current_url == self.base_url:
category = self._get_torrent_category(item, result=i)
else:
category = self._get_torrent_category(item)
result.append(Torrent(title_text, category, link, size, seed,
leech, magnet, download,files, age, isVerified))
return result | python | def _parse_details(self, tag_list):
"""Given a list of tags from either a search page or the
KAT home page parse the details and return a list of
Torrents"""
result = list()
for i, item in enumerate(tag_list):
title = item.find("a", class_="cellMainLink")
title_text = title.text
link = title.get("href")
tds = item.find_all("td", class_="center") # Better name here.
size = tds[0].text
files = tds[1].text
age = tds[2].text
seed = tds[3].text
leech = tds[4].text
magnet = item.find("a", class_="imagnet icon16")
download = item.find("a", class_="idownload icon16")
isVerified = item.find("a", class_="iverify icon16") != None
# Home page doesn't have magnet or download links
if magnet:
magnet = magnet.get("href")
if download:
download = download.get("href")
# Get category changes depending on if we're parsing
# the home page or a search page.
if self.current_url == self.base_url:
category = self._get_torrent_category(item, result=i)
else:
category = self._get_torrent_category(item)
result.append(Torrent(title_text, category, link, size, seed,
leech, magnet, download,files, age, isVerified))
return result | [
"def",
"_parse_details",
"(",
"self",
",",
"tag_list",
")",
":",
"result",
"=",
"list",
"(",
")",
"for",
"i",
",",
"item",
"in",
"enumerate",
"(",
"tag_list",
")",
":",
"title",
"=",
"item",
".",
"find",
"(",
"\"a\"",
",",
"class_",
"=",
"\"cellMainLink\"",
")",
"title_text",
"=",
"title",
".",
"text",
"link",
"=",
"title",
".",
"get",
"(",
"\"href\"",
")",
"tds",
"=",
"item",
".",
"find_all",
"(",
"\"td\"",
",",
"class_",
"=",
"\"center\"",
")",
"# Better name here.",
"size",
"=",
"tds",
"[",
"0",
"]",
".",
"text",
"files",
"=",
"tds",
"[",
"1",
"]",
".",
"text",
"age",
"=",
"tds",
"[",
"2",
"]",
".",
"text",
"seed",
"=",
"tds",
"[",
"3",
"]",
".",
"text",
"leech",
"=",
"tds",
"[",
"4",
"]",
".",
"text",
"magnet",
"=",
"item",
".",
"find",
"(",
"\"a\"",
",",
"class_",
"=",
"\"imagnet icon16\"",
")",
"download",
"=",
"item",
".",
"find",
"(",
"\"a\"",
",",
"class_",
"=",
"\"idownload icon16\"",
")",
"isVerified",
"=",
"item",
".",
"find",
"(",
"\"a\"",
",",
"class_",
"=",
"\"iverify icon16\"",
")",
"!=",
"None",
"# Home page doesn't have magnet or download links",
"if",
"magnet",
":",
"magnet",
"=",
"magnet",
".",
"get",
"(",
"\"href\"",
")",
"if",
"download",
":",
"download",
"=",
"download",
".",
"get",
"(",
"\"href\"",
")",
"# Get category changes depending on if we're parsing",
"# the home page or a search page.",
"if",
"self",
".",
"current_url",
"==",
"self",
".",
"base_url",
":",
"category",
"=",
"self",
".",
"_get_torrent_category",
"(",
"item",
",",
"result",
"=",
"i",
")",
"else",
":",
"category",
"=",
"self",
".",
"_get_torrent_category",
"(",
"item",
")",
"result",
".",
"append",
"(",
"Torrent",
"(",
"title_text",
",",
"category",
",",
"link",
",",
"size",
",",
"seed",
",",
"leech",
",",
"magnet",
",",
"download",
",",
"files",
",",
"age",
",",
"isVerified",
")",
")",
"return",
"result"
]
| Given a list of tags from either a search page or the
KAT home page parse the details and return a list of
Torrents | [
"Given",
"a",
"list",
"of",
"tags",
"from",
"either",
"a",
"search",
"page",
"or",
"the",
"KAT",
"home",
"page",
"parse",
"the",
"details",
"and",
"return",
"a",
"list",
"of",
"Torrents"
]
| 4d867a090c06ce95b9ed996b48092cb5bfe28bbd | https://github.com/stephan-mclean/KickassTorrentsAPI/blob/4d867a090c06ce95b9ed996b48092cb5bfe28bbd/kat.py#L250-L286 | train |
VIVelev/PyDojoML | dojo/nn/layers.py | Dense.init_weights | def init_weights(self):
"""Performs He initialization"""
self.W = np.random.randn(self.n_neurons, self.n_inputs) * np.sqrt(2 / self.n_inputs)
self.b = np.zeros((self.n_neurons, 1)) | python | def init_weights(self):
"""Performs He initialization"""
self.W = np.random.randn(self.n_neurons, self.n_inputs) * np.sqrt(2 / self.n_inputs)
self.b = np.zeros((self.n_neurons, 1)) | [
"def",
"init_weights",
"(",
"self",
")",
":",
"self",
".",
"W",
"=",
"np",
".",
"random",
".",
"randn",
"(",
"self",
".",
"n_neurons",
",",
"self",
".",
"n_inputs",
")",
"*",
"np",
".",
"sqrt",
"(",
"2",
"/",
"self",
".",
"n_inputs",
")",
"self",
".",
"b",
"=",
"np",
".",
"zeros",
"(",
"(",
"self",
".",
"n_neurons",
",",
"1",
")",
")"
]
| Performs He initialization | [
"Performs",
"He",
"initialization"
]
| 773fdce6866aa6decd306a5a85f94129fed816eb | https://github.com/VIVelev/PyDojoML/blob/773fdce6866aa6decd306a5a85f94129fed816eb/dojo/nn/layers.py#L93-L97 | train |
The-Politico/politico-civic-election-night | electionnight/management/commands/methods/bootstrap/executive_office_states.py | ExecutiveOfficeStates.bootstrap_executive_office_states | def bootstrap_executive_office_states(self, election):
"""
Create state page content exclusively for the U.S. president.
"""
content_type = ContentType.objects.get_for_model(election.race.office)
for division in Division.objects.filter(level=self.STATE_LEVEL):
PageContent.objects.get_or_create(
content_type=content_type,
object_id=election.race.office.pk,
election_day=election.election_day,
division=division
)
# Create national presidential page type
page_type, created = PageType.objects.get_or_create(
model_type=ContentType.objects.get(
app_label='government',
model='office'
),
election_day=election.election_day,
division_level=self.NATIONAL_LEVEL,
jurisdiction=self.FEDERAL_JURISDICTION,
office=election.race.office,
)
PageContent.objects.get_or_create(
content_type=ContentType.objects.get_for_model(page_type),
object_id=page_type.pk,
election_day=election.election_day,
)
# Create state results for president page type
page_type, created = PageType.objects.get_or_create(
model_type=ContentType.objects.get(
app_label='government',
model='office'
),
election_day=election.election_day,
division_level=self.STATE_LEVEL,
jurisdiction=self.FEDERAL_JURISDICTION,
office=election.race.office,
)
PageContent.objects.get_or_create(
content_type=ContentType.objects.get_for_model(page_type),
object_id=page_type.pk,
election_day=election.election_day,
) | python | def bootstrap_executive_office_states(self, election):
"""
Create state page content exclusively for the U.S. president.
"""
content_type = ContentType.objects.get_for_model(election.race.office)
for division in Division.objects.filter(level=self.STATE_LEVEL):
PageContent.objects.get_or_create(
content_type=content_type,
object_id=election.race.office.pk,
election_day=election.election_day,
division=division
)
# Create national presidential page type
page_type, created = PageType.objects.get_or_create(
model_type=ContentType.objects.get(
app_label='government',
model='office'
),
election_day=election.election_day,
division_level=self.NATIONAL_LEVEL,
jurisdiction=self.FEDERAL_JURISDICTION,
office=election.race.office,
)
PageContent.objects.get_or_create(
content_type=ContentType.objects.get_for_model(page_type),
object_id=page_type.pk,
election_day=election.election_day,
)
# Create state results for president page type
page_type, created = PageType.objects.get_or_create(
model_type=ContentType.objects.get(
app_label='government',
model='office'
),
election_day=election.election_day,
division_level=self.STATE_LEVEL,
jurisdiction=self.FEDERAL_JURISDICTION,
office=election.race.office,
)
PageContent.objects.get_or_create(
content_type=ContentType.objects.get_for_model(page_type),
object_id=page_type.pk,
election_day=election.election_day,
) | [
"def",
"bootstrap_executive_office_states",
"(",
"self",
",",
"election",
")",
":",
"content_type",
"=",
"ContentType",
".",
"objects",
".",
"get_for_model",
"(",
"election",
".",
"race",
".",
"office",
")",
"for",
"division",
"in",
"Division",
".",
"objects",
".",
"filter",
"(",
"level",
"=",
"self",
".",
"STATE_LEVEL",
")",
":",
"PageContent",
".",
"objects",
".",
"get_or_create",
"(",
"content_type",
"=",
"content_type",
",",
"object_id",
"=",
"election",
".",
"race",
".",
"office",
".",
"pk",
",",
"election_day",
"=",
"election",
".",
"election_day",
",",
"division",
"=",
"division",
")",
"# Create national presidential page type",
"page_type",
",",
"created",
"=",
"PageType",
".",
"objects",
".",
"get_or_create",
"(",
"model_type",
"=",
"ContentType",
".",
"objects",
".",
"get",
"(",
"app_label",
"=",
"'government'",
",",
"model",
"=",
"'office'",
")",
",",
"election_day",
"=",
"election",
".",
"election_day",
",",
"division_level",
"=",
"self",
".",
"NATIONAL_LEVEL",
",",
"jurisdiction",
"=",
"self",
".",
"FEDERAL_JURISDICTION",
",",
"office",
"=",
"election",
".",
"race",
".",
"office",
",",
")",
"PageContent",
".",
"objects",
".",
"get_or_create",
"(",
"content_type",
"=",
"ContentType",
".",
"objects",
".",
"get_for_model",
"(",
"page_type",
")",
",",
"object_id",
"=",
"page_type",
".",
"pk",
",",
"election_day",
"=",
"election",
".",
"election_day",
",",
")",
"# Create state results for president page type",
"page_type",
",",
"created",
"=",
"PageType",
".",
"objects",
".",
"get_or_create",
"(",
"model_type",
"=",
"ContentType",
".",
"objects",
".",
"get",
"(",
"app_label",
"=",
"'government'",
",",
"model",
"=",
"'office'",
")",
",",
"election_day",
"=",
"election",
".",
"election_day",
",",
"division_level",
"=",
"self",
".",
"STATE_LEVEL",
",",
"jurisdiction",
"=",
"self",
".",
"FEDERAL_JURISDICTION",
",",
"office",
"=",
"election",
".",
"race",
".",
"office",
",",
")",
"PageContent",
".",
"objects",
".",
"get_or_create",
"(",
"content_type",
"=",
"ContentType",
".",
"objects",
".",
"get_for_model",
"(",
"page_type",
")",
",",
"object_id",
"=",
"page_type",
".",
"pk",
",",
"election_day",
"=",
"election",
".",
"election_day",
",",
")"
]
| Create state page content exclusively for the U.S. president. | [
"Create",
"state",
"page",
"content",
"exclusively",
"for",
"the",
"U",
".",
"S",
".",
"president",
"."
]
| a8aaf5be43872a7b84d2b0d7c2b6151d32d4d8b6 | https://github.com/The-Politico/politico-civic-election-night/blob/a8aaf5be43872a7b84d2b0d7c2b6151d32d4d8b6/electionnight/management/commands/methods/bootstrap/executive_office_states.py#L8-L51 | train |
ktdreyer/txkoji | txkoji/estimates.py | average_last_builds | def average_last_builds(connection, package, limit=5):
"""
Find the average duration time for the last couple of builds.
:param connection: txkoji.Connection
:param package: package name
:returns: deferred that when fired returns a datetime.timedelta object, or
None if there were no previous builds for this package.
"""
# TODO: take branches (targets, or tags, etc) into account when estimating
# a package's build time.
state = build_states.COMPLETE
opts = {'limit': limit, 'order': '-completion_time'}
builds = yield connection.listBuilds(package, state=state, queryOpts=opts)
if not builds:
defer.returnValue(None)
durations = [build.duration for build in builds]
average = sum(durations, timedelta()) / len(durations)
# print('average duration for %s is %s' % (package, average))
defer.returnValue(average) | python | def average_last_builds(connection, package, limit=5):
"""
Find the average duration time for the last couple of builds.
:param connection: txkoji.Connection
:param package: package name
:returns: deferred that when fired returns a datetime.timedelta object, or
None if there were no previous builds for this package.
"""
# TODO: take branches (targets, or tags, etc) into account when estimating
# a package's build time.
state = build_states.COMPLETE
opts = {'limit': limit, 'order': '-completion_time'}
builds = yield connection.listBuilds(package, state=state, queryOpts=opts)
if not builds:
defer.returnValue(None)
durations = [build.duration for build in builds]
average = sum(durations, timedelta()) / len(durations)
# print('average duration for %s is %s' % (package, average))
defer.returnValue(average) | [
"def",
"average_last_builds",
"(",
"connection",
",",
"package",
",",
"limit",
"=",
"5",
")",
":",
"# TODO: take branches (targets, or tags, etc) into account when estimating",
"# a package's build time.",
"state",
"=",
"build_states",
".",
"COMPLETE",
"opts",
"=",
"{",
"'limit'",
":",
"limit",
",",
"'order'",
":",
"'-completion_time'",
"}",
"builds",
"=",
"yield",
"connection",
".",
"listBuilds",
"(",
"package",
",",
"state",
"=",
"state",
",",
"queryOpts",
"=",
"opts",
")",
"if",
"not",
"builds",
":",
"defer",
".",
"returnValue",
"(",
"None",
")",
"durations",
"=",
"[",
"build",
".",
"duration",
"for",
"build",
"in",
"builds",
"]",
"average",
"=",
"sum",
"(",
"durations",
",",
"timedelta",
"(",
")",
")",
"/",
"len",
"(",
"durations",
")",
"# print('average duration for %s is %s' % (package, average))",
"defer",
".",
"returnValue",
"(",
"average",
")"
]
| Find the average duration time for the last couple of builds.
:param connection: txkoji.Connection
:param package: package name
:returns: deferred that when fired returns a datetime.timedelta object, or
None if there were no previous builds for this package. | [
"Find",
"the",
"average",
"duration",
"time",
"for",
"the",
"last",
"couple",
"of",
"builds",
"."
]
| a7de380f29f745bf11730b27217208f6d4da7733 | https://github.com/ktdreyer/txkoji/blob/a7de380f29f745bf11730b27217208f6d4da7733/txkoji/estimates.py#L84-L103 | train |
hapyak/flask-peewee-swagger | flask_peewee_swagger/swagger.py | Swagger.model_resources | def model_resources(self):
""" Listing of all supported resources. """
response = jsonify({
'apiVersion': '0.1',
'swaggerVersion': '1.1',
'basePath': '%s%s' % (self.base_uri(), self.api.url_prefix),
'apis': self.get_model_resources()
})
response.headers.add('Cache-Control', 'max-age=0')
return response | python | def model_resources(self):
""" Listing of all supported resources. """
response = jsonify({
'apiVersion': '0.1',
'swaggerVersion': '1.1',
'basePath': '%s%s' % (self.base_uri(), self.api.url_prefix),
'apis': self.get_model_resources()
})
response.headers.add('Cache-Control', 'max-age=0')
return response | [
"def",
"model_resources",
"(",
"self",
")",
":",
"response",
"=",
"jsonify",
"(",
"{",
"'apiVersion'",
":",
"'0.1'",
",",
"'swaggerVersion'",
":",
"'1.1'",
",",
"'basePath'",
":",
"'%s%s'",
"%",
"(",
"self",
".",
"base_uri",
"(",
")",
",",
"self",
".",
"api",
".",
"url_prefix",
")",
",",
"'apis'",
":",
"self",
".",
"get_model_resources",
"(",
")",
"}",
")",
"response",
".",
"headers",
".",
"add",
"(",
"'Cache-Control'",
",",
"'max-age=0'",
")",
"return",
"response"
]
| Listing of all supported resources. | [
"Listing",
"of",
"all",
"supported",
"resources",
"."
]
| 1b7dd54a5e823401b80e04ac421ee15c9fab3f06 | https://github.com/hapyak/flask-peewee-swagger/blob/1b7dd54a5e823401b80e04ac421ee15c9fab3f06/flask_peewee_swagger/swagger.py#L67-L78 | train |
hapyak/flask-peewee-swagger | flask_peewee_swagger/swagger.py | Swagger.model_resource | def model_resource(self, resource_name):
""" Details of a specific model resource. """
resource = first(
[resource for resource in self.api._registry.values()
if resource.get_api_name() == resource_name])
data = {
'apiVersion': '0.1',
'swaggerVersion': '1.1',
'basePath': '%s%s' % (self.base_uri(), self.api.url_prefix),
'resourcePath': '/meta/%s' % resource.get_api_name(),
'apis': self.get_model_apis(resource),
'models': self.get_model(resource)
}
response = jsonify(data)
response.headers.add('Cache-Control', 'max-age=0')
return response | python | def model_resource(self, resource_name):
""" Details of a specific model resource. """
resource = first(
[resource for resource in self.api._registry.values()
if resource.get_api_name() == resource_name])
data = {
'apiVersion': '0.1',
'swaggerVersion': '1.1',
'basePath': '%s%s' % (self.base_uri(), self.api.url_prefix),
'resourcePath': '/meta/%s' % resource.get_api_name(),
'apis': self.get_model_apis(resource),
'models': self.get_model(resource)
}
response = jsonify(data)
response.headers.add('Cache-Control', 'max-age=0')
return response | [
"def",
"model_resource",
"(",
"self",
",",
"resource_name",
")",
":",
"resource",
"=",
"first",
"(",
"[",
"resource",
"for",
"resource",
"in",
"self",
".",
"api",
".",
"_registry",
".",
"values",
"(",
")",
"if",
"resource",
".",
"get_api_name",
"(",
")",
"==",
"resource_name",
"]",
")",
"data",
"=",
"{",
"'apiVersion'",
":",
"'0.1'",
",",
"'swaggerVersion'",
":",
"'1.1'",
",",
"'basePath'",
":",
"'%s%s'",
"%",
"(",
"self",
".",
"base_uri",
"(",
")",
",",
"self",
".",
"api",
".",
"url_prefix",
")",
",",
"'resourcePath'",
":",
"'/meta/%s'",
"%",
"resource",
".",
"get_api_name",
"(",
")",
",",
"'apis'",
":",
"self",
".",
"get_model_apis",
"(",
"resource",
")",
",",
"'models'",
":",
"self",
".",
"get_model",
"(",
"resource",
")",
"}",
"response",
"=",
"jsonify",
"(",
"data",
")",
"response",
".",
"headers",
".",
"add",
"(",
"'Cache-Control'",
",",
"'max-age=0'",
")",
"return",
"response"
]
| Details of a specific model resource. | [
"Details",
"of",
"a",
"specific",
"model",
"resource",
"."
]
| 1b7dd54a5e823401b80e04ac421ee15c9fab3f06 | https://github.com/hapyak/flask-peewee-swagger/blob/1b7dd54a5e823401b80e04ac421ee15c9fab3f06/flask_peewee_swagger/swagger.py#L93-L110 | train |
VIVelev/PyDojoML | dojo/dimred/tsne.py | TSNE._high_dim_sim | def _high_dim_sim(self, v, w, normalize=False, X=None, idx=0):
"""Similarity measurement based on Gaussian Distribution"""
sim = np.exp((-np.linalg.norm(v - w) ** 2) / (2*self._sigma[idx] ** 2))
if normalize:
return sim / sum(map(lambda x: x[1], self._knn(idx, X, high_dim=True)))
else:
return sim | python | def _high_dim_sim(self, v, w, normalize=False, X=None, idx=0):
"""Similarity measurement based on Gaussian Distribution"""
sim = np.exp((-np.linalg.norm(v - w) ** 2) / (2*self._sigma[idx] ** 2))
if normalize:
return sim / sum(map(lambda x: x[1], self._knn(idx, X, high_dim=True)))
else:
return sim | [
"def",
"_high_dim_sim",
"(",
"self",
",",
"v",
",",
"w",
",",
"normalize",
"=",
"False",
",",
"X",
"=",
"None",
",",
"idx",
"=",
"0",
")",
":",
"sim",
"=",
"np",
".",
"exp",
"(",
"(",
"-",
"np",
".",
"linalg",
".",
"norm",
"(",
"v",
"-",
"w",
")",
"**",
"2",
")",
"/",
"(",
"2",
"*",
"self",
".",
"_sigma",
"[",
"idx",
"]",
"**",
"2",
")",
")",
"if",
"normalize",
":",
"return",
"sim",
"/",
"sum",
"(",
"map",
"(",
"lambda",
"x",
":",
"x",
"[",
"1",
"]",
",",
"self",
".",
"_knn",
"(",
"idx",
",",
"X",
",",
"high_dim",
"=",
"True",
")",
")",
")",
"else",
":",
"return",
"sim"
]
| Similarity measurement based on Gaussian Distribution | [
"Similarity",
"measurement",
"based",
"on",
"Gaussian",
"Distribution"
]
| 773fdce6866aa6decd306a5a85f94129fed816eb | https://github.com/VIVelev/PyDojoML/blob/773fdce6866aa6decd306a5a85f94129fed816eb/dojo/dimred/tsne.py#L58-L66 | train |
tjcsl/cslbot | cslbot/helpers/core.py | init | def init(confdir="/etc/cslbot"):
"""The bot's main entry point.
| Initialize the bot and start processing messages.
"""
multiprocessing.set_start_method('spawn')
parser = argparse.ArgumentParser()
parser.add_argument('-d', '--debug', help='Enable debug logging.', action='store_true')
parser.add_argument('--validate', help='Initialize the db and perform other sanity checks.', action='store_true')
args = parser.parse_args()
loglevel = logging.DEBUG if args.debug else logging.INFO
logging.basicConfig(level=loglevel, format="%(asctime)s %(levelname)s:%(module)s:%(message)s")
# We don't need a bunch of output from the requests module.
logging.getLogger("requests").setLevel(logging.WARNING)
cslbot = IrcBot(confdir)
if args.validate:
cslbot.shutdown_mp()
print("Everything is ready to go!")
return
try:
cslbot.start()
except KeyboardInterrupt:
# KeyboardInterrupt means someone tried to ^C, so shut down the bot
cslbot.disconnect('Bot received a Ctrl-C')
cslbot.shutdown_mp()
sys.exit(0)
except Exception as ex:
cslbot.shutdown_mp(False)
logging.error("The bot died! %s", ex)
output = "".join(traceback.format_exc()).strip()
for line in output.split('\n'):
logging.error(line)
sys.exit(1) | python | def init(confdir="/etc/cslbot"):
"""The bot's main entry point.
| Initialize the bot and start processing messages.
"""
multiprocessing.set_start_method('spawn')
parser = argparse.ArgumentParser()
parser.add_argument('-d', '--debug', help='Enable debug logging.', action='store_true')
parser.add_argument('--validate', help='Initialize the db and perform other sanity checks.', action='store_true')
args = parser.parse_args()
loglevel = logging.DEBUG if args.debug else logging.INFO
logging.basicConfig(level=loglevel, format="%(asctime)s %(levelname)s:%(module)s:%(message)s")
# We don't need a bunch of output from the requests module.
logging.getLogger("requests").setLevel(logging.WARNING)
cslbot = IrcBot(confdir)
if args.validate:
cslbot.shutdown_mp()
print("Everything is ready to go!")
return
try:
cslbot.start()
except KeyboardInterrupt:
# KeyboardInterrupt means someone tried to ^C, so shut down the bot
cslbot.disconnect('Bot received a Ctrl-C')
cslbot.shutdown_mp()
sys.exit(0)
except Exception as ex:
cslbot.shutdown_mp(False)
logging.error("The bot died! %s", ex)
output = "".join(traceback.format_exc()).strip()
for line in output.split('\n'):
logging.error(line)
sys.exit(1) | [
"def",
"init",
"(",
"confdir",
"=",
"\"/etc/cslbot\"",
")",
":",
"multiprocessing",
".",
"set_start_method",
"(",
"'spawn'",
")",
"parser",
"=",
"argparse",
".",
"ArgumentParser",
"(",
")",
"parser",
".",
"add_argument",
"(",
"'-d'",
",",
"'--debug'",
",",
"help",
"=",
"'Enable debug logging.'",
",",
"action",
"=",
"'store_true'",
")",
"parser",
".",
"add_argument",
"(",
"'--validate'",
",",
"help",
"=",
"'Initialize the db and perform other sanity checks.'",
",",
"action",
"=",
"'store_true'",
")",
"args",
"=",
"parser",
".",
"parse_args",
"(",
")",
"loglevel",
"=",
"logging",
".",
"DEBUG",
"if",
"args",
".",
"debug",
"else",
"logging",
".",
"INFO",
"logging",
".",
"basicConfig",
"(",
"level",
"=",
"loglevel",
",",
"format",
"=",
"\"%(asctime)s %(levelname)s:%(module)s:%(message)s\"",
")",
"# We don't need a bunch of output from the requests module.",
"logging",
".",
"getLogger",
"(",
"\"requests\"",
")",
".",
"setLevel",
"(",
"logging",
".",
"WARNING",
")",
"cslbot",
"=",
"IrcBot",
"(",
"confdir",
")",
"if",
"args",
".",
"validate",
":",
"cslbot",
".",
"shutdown_mp",
"(",
")",
"print",
"(",
"\"Everything is ready to go!\"",
")",
"return",
"try",
":",
"cslbot",
".",
"start",
"(",
")",
"except",
"KeyboardInterrupt",
":",
"# KeyboardInterrupt means someone tried to ^C, so shut down the bot",
"cslbot",
".",
"disconnect",
"(",
"'Bot received a Ctrl-C'",
")",
"cslbot",
".",
"shutdown_mp",
"(",
")",
"sys",
".",
"exit",
"(",
"0",
")",
"except",
"Exception",
"as",
"ex",
":",
"cslbot",
".",
"shutdown_mp",
"(",
"False",
")",
"logging",
".",
"error",
"(",
"\"The bot died! %s\"",
",",
"ex",
")",
"output",
"=",
"\"\"",
".",
"join",
"(",
"traceback",
".",
"format_exc",
"(",
")",
")",
".",
"strip",
"(",
")",
"for",
"line",
"in",
"output",
".",
"split",
"(",
"'\\n'",
")",
":",
"logging",
".",
"error",
"(",
"line",
")",
"sys",
".",
"exit",
"(",
"1",
")"
]
| The bot's main entry point.
| Initialize the bot and start processing messages. | [
"The",
"bot",
"s",
"main",
"entry",
"point",
"."
]
| aebe07be47141f61d7c180706bddfb707f19b2b5 | https://github.com/tjcsl/cslbot/blob/aebe07be47141f61d7c180706bddfb707f19b2b5/cslbot/helpers/core.py#L210-L247 | train |
tjcsl/cslbot | cslbot/helpers/core.py | IrcBot.get_version | def get_version(self):
"""Get the version."""
_, version = misc.get_version(self.confdir)
if version is None:
return "Can't get the version."
else:
return "cslbot - %s" % version | python | def get_version(self):
"""Get the version."""
_, version = misc.get_version(self.confdir)
if version is None:
return "Can't get the version."
else:
return "cslbot - %s" % version | [
"def",
"get_version",
"(",
"self",
")",
":",
"_",
",",
"version",
"=",
"misc",
".",
"get_version",
"(",
"self",
".",
"confdir",
")",
"if",
"version",
"is",
"None",
":",
"return",
"\"Can't get the version.\"",
"else",
":",
"return",
"\"cslbot - %s\"",
"%",
"version"
]
| Get the version. | [
"Get",
"the",
"version",
"."
]
| aebe07be47141f61d7c180706bddfb707f19b2b5 | https://github.com/tjcsl/cslbot/blob/aebe07be47141f61d7c180706bddfb707f19b2b5/cslbot/helpers/core.py#L99-L105 | train |
tjcsl/cslbot | cslbot/helpers/core.py | IrcBot.shutdown_mp | def shutdown_mp(self, clean=True):
"""Shutdown all the multiprocessing.
:param bool clean: Whether to shutdown things cleanly, or force a quick and dirty shutdown.
"""
# The server runs on a worker thread, so we need to shut it down first.
if hasattr(self, 'server'):
# Shutdown the server quickly.
try:
# For some strange reason, this throws an OSError on windows.
self.server.socket.shutdown(socket.SHUT_RDWR)
except OSError:
pass
self.server.socket.close()
self.server.shutdown()
if hasattr(self, 'handler'):
self.handler.workers.stop_workers(clean) | python | def shutdown_mp(self, clean=True):
"""Shutdown all the multiprocessing.
:param bool clean: Whether to shutdown things cleanly, or force a quick and dirty shutdown.
"""
# The server runs on a worker thread, so we need to shut it down first.
if hasattr(self, 'server'):
# Shutdown the server quickly.
try:
# For some strange reason, this throws an OSError on windows.
self.server.socket.shutdown(socket.SHUT_RDWR)
except OSError:
pass
self.server.socket.close()
self.server.shutdown()
if hasattr(self, 'handler'):
self.handler.workers.stop_workers(clean) | [
"def",
"shutdown_mp",
"(",
"self",
",",
"clean",
"=",
"True",
")",
":",
"# The server runs on a worker thread, so we need to shut it down first.",
"if",
"hasattr",
"(",
"self",
",",
"'server'",
")",
":",
"# Shutdown the server quickly.",
"try",
":",
"# For some strange reason, this throws an OSError on windows.",
"self",
".",
"server",
".",
"socket",
".",
"shutdown",
"(",
"socket",
".",
"SHUT_RDWR",
")",
"except",
"OSError",
":",
"pass",
"self",
".",
"server",
".",
"socket",
".",
"close",
"(",
")",
"self",
".",
"server",
".",
"shutdown",
"(",
")",
"if",
"hasattr",
"(",
"self",
",",
"'handler'",
")",
":",
"self",
".",
"handler",
".",
"workers",
".",
"stop_workers",
"(",
"clean",
")"
]
| Shutdown all the multiprocessing.
:param bool clean: Whether to shutdown things cleanly, or force a quick and dirty shutdown. | [
"Shutdown",
"all",
"the",
"multiprocessing",
"."
]
| aebe07be47141f61d7c180706bddfb707f19b2b5 | https://github.com/tjcsl/cslbot/blob/aebe07be47141f61d7c180706bddfb707f19b2b5/cslbot/helpers/core.py#L128-L145 | train |
tjcsl/cslbot | cslbot/helpers/core.py | IrcBot.handle_msg | def handle_msg(self, c, e):
"""Handles all messages.
- If a exception is thrown, catch it and display a nice traceback instead of crashing.
- Do the appropriate processing for each event type.
"""
try:
self.handler.handle_msg(c, e)
except Exception as ex:
backtrace.handle_traceback(ex, c, self.get_target(e), self.config) | python | def handle_msg(self, c, e):
"""Handles all messages.
- If a exception is thrown, catch it and display a nice traceback instead of crashing.
- Do the appropriate processing for each event type.
"""
try:
self.handler.handle_msg(c, e)
except Exception as ex:
backtrace.handle_traceback(ex, c, self.get_target(e), self.config) | [
"def",
"handle_msg",
"(",
"self",
",",
"c",
",",
"e",
")",
":",
"try",
":",
"self",
".",
"handler",
".",
"handle_msg",
"(",
"c",
",",
"e",
")",
"except",
"Exception",
"as",
"ex",
":",
"backtrace",
".",
"handle_traceback",
"(",
"ex",
",",
"c",
",",
"self",
".",
"get_target",
"(",
"e",
")",
",",
"self",
".",
"config",
")"
]
| Handles all messages.
- If a exception is thrown, catch it and display a nice traceback instead of crashing.
- Do the appropriate processing for each event type. | [
"Handles",
"all",
"messages",
"."
]
| aebe07be47141f61d7c180706bddfb707f19b2b5 | https://github.com/tjcsl/cslbot/blob/aebe07be47141f61d7c180706bddfb707f19b2b5/cslbot/helpers/core.py#L158-L168 | train |
tjcsl/cslbot | cslbot/helpers/core.py | IrcBot.reload_handler | def reload_handler(self, c, e):
"""This handles reloads."""
cmd = self.is_reload(e)
cmdchar = self.config['core']['cmdchar']
if cmd is not None:
# If we're in a minimal reload state, only the owner can do stuff, as we can't rely on the db working.
if self.reload_event.set():
admins = [self.config['auth']['owner']]
else:
with self.handler.db.session_scope() as session:
admins = [x.nick for x in session.query(orm.Permissions).all()]
if e.source.nick not in admins:
c.privmsg(self.get_target(e), "Nope, not gonna do it.")
return
importlib.reload(reloader)
self.reload_event.set()
cmdargs = cmd[len('%sreload' % cmdchar) + 1:]
try:
if reloader.do_reload(self, e, cmdargs):
if self.config.getboolean('feature', 'server'):
self.server = server.init_server(self)
self.reload_event.clear()
logging.info("Successfully reloaded")
except Exception as ex:
backtrace.handle_traceback(ex, c, self.get_target(e), self.config) | python | def reload_handler(self, c, e):
"""This handles reloads."""
cmd = self.is_reload(e)
cmdchar = self.config['core']['cmdchar']
if cmd is not None:
# If we're in a minimal reload state, only the owner can do stuff, as we can't rely on the db working.
if self.reload_event.set():
admins = [self.config['auth']['owner']]
else:
with self.handler.db.session_scope() as session:
admins = [x.nick for x in session.query(orm.Permissions).all()]
if e.source.nick not in admins:
c.privmsg(self.get_target(e), "Nope, not gonna do it.")
return
importlib.reload(reloader)
self.reload_event.set()
cmdargs = cmd[len('%sreload' % cmdchar) + 1:]
try:
if reloader.do_reload(self, e, cmdargs):
if self.config.getboolean('feature', 'server'):
self.server = server.init_server(self)
self.reload_event.clear()
logging.info("Successfully reloaded")
except Exception as ex:
backtrace.handle_traceback(ex, c, self.get_target(e), self.config) | [
"def",
"reload_handler",
"(",
"self",
",",
"c",
",",
"e",
")",
":",
"cmd",
"=",
"self",
".",
"is_reload",
"(",
"e",
")",
"cmdchar",
"=",
"self",
".",
"config",
"[",
"'core'",
"]",
"[",
"'cmdchar'",
"]",
"if",
"cmd",
"is",
"not",
"None",
":",
"# If we're in a minimal reload state, only the owner can do stuff, as we can't rely on the db working.",
"if",
"self",
".",
"reload_event",
".",
"set",
"(",
")",
":",
"admins",
"=",
"[",
"self",
".",
"config",
"[",
"'auth'",
"]",
"[",
"'owner'",
"]",
"]",
"else",
":",
"with",
"self",
".",
"handler",
".",
"db",
".",
"session_scope",
"(",
")",
"as",
"session",
":",
"admins",
"=",
"[",
"x",
".",
"nick",
"for",
"x",
"in",
"session",
".",
"query",
"(",
"orm",
".",
"Permissions",
")",
".",
"all",
"(",
")",
"]",
"if",
"e",
".",
"source",
".",
"nick",
"not",
"in",
"admins",
":",
"c",
".",
"privmsg",
"(",
"self",
".",
"get_target",
"(",
"e",
")",
",",
"\"Nope, not gonna do it.\"",
")",
"return",
"importlib",
".",
"reload",
"(",
"reloader",
")",
"self",
".",
"reload_event",
".",
"set",
"(",
")",
"cmdargs",
"=",
"cmd",
"[",
"len",
"(",
"'%sreload'",
"%",
"cmdchar",
")",
"+",
"1",
":",
"]",
"try",
":",
"if",
"reloader",
".",
"do_reload",
"(",
"self",
",",
"e",
",",
"cmdargs",
")",
":",
"if",
"self",
".",
"config",
".",
"getboolean",
"(",
"'feature'",
",",
"'server'",
")",
":",
"self",
".",
"server",
"=",
"server",
".",
"init_server",
"(",
"self",
")",
"self",
".",
"reload_event",
".",
"clear",
"(",
")",
"logging",
".",
"info",
"(",
"\"Successfully reloaded\"",
")",
"except",
"Exception",
"as",
"ex",
":",
"backtrace",
".",
"handle_traceback",
"(",
"ex",
",",
"c",
",",
"self",
".",
"get_target",
"(",
"e",
")",
",",
"self",
".",
"config",
")"
]
| This handles reloads. | [
"This",
"handles",
"reloads",
"."
]
| aebe07be47141f61d7c180706bddfb707f19b2b5 | https://github.com/tjcsl/cslbot/blob/aebe07be47141f61d7c180706bddfb707f19b2b5/cslbot/helpers/core.py#L183-L207 | train |
jaumebonet/libconfig | libconfig/config.py | _options_to_dict | def _options_to_dict(df):
"""Make a dictionary to print."""
kolums = ["k1", "k2", "value"]
d = df[kolums].values.tolist()
dc = {}
for x in d:
dc.setdefault(x[0], {})
dc[x[0]][x[1]] = x[2]
return dc | python | def _options_to_dict(df):
"""Make a dictionary to print."""
kolums = ["k1", "k2", "value"]
d = df[kolums].values.tolist()
dc = {}
for x in d:
dc.setdefault(x[0], {})
dc[x[0]][x[1]] = x[2]
return dc | [
"def",
"_options_to_dict",
"(",
"df",
")",
":",
"kolums",
"=",
"[",
"\"k1\"",
",",
"\"k2\"",
",",
"\"value\"",
"]",
"d",
"=",
"df",
"[",
"kolums",
"]",
".",
"values",
".",
"tolist",
"(",
")",
"dc",
"=",
"{",
"}",
"for",
"x",
"in",
"d",
":",
"dc",
".",
"setdefault",
"(",
"x",
"[",
"0",
"]",
",",
"{",
"}",
")",
"dc",
"[",
"x",
"[",
"0",
"]",
"]",
"[",
"x",
"[",
"1",
"]",
"]",
"=",
"x",
"[",
"2",
"]",
"return",
"dc"
]
| Make a dictionary to print. | [
"Make",
"a",
"dictionary",
"to",
"print",
"."
]
| 9b34cefcbaf9a326e3f3cd517896c2933cf61a3b | https://github.com/jaumebonet/libconfig/blob/9b34cefcbaf9a326e3f3cd517896c2933cf61a3b/libconfig/config.py#L611-L619 | train |
jaumebonet/libconfig | libconfig/config.py | _get_repo | def _get_repo():
"""Identify the path to the repository origin."""
command = ['git', 'rev-parse', '--show-toplevel']
if six.PY2:
try:
return check_output(command).decode('utf-8').strip() # nosec
except CalledProcessError:
return ''
else:
return (run(command, stdout=PIPE, stderr=PIPE)
.stdout.decode('utf-8').strip()) | python | def _get_repo():
"""Identify the path to the repository origin."""
command = ['git', 'rev-parse', '--show-toplevel']
if six.PY2:
try:
return check_output(command).decode('utf-8').strip() # nosec
except CalledProcessError:
return ''
else:
return (run(command, stdout=PIPE, stderr=PIPE)
.stdout.decode('utf-8').strip()) | [
"def",
"_get_repo",
"(",
")",
":",
"command",
"=",
"[",
"'git'",
",",
"'rev-parse'",
",",
"'--show-toplevel'",
"]",
"if",
"six",
".",
"PY2",
":",
"try",
":",
"return",
"check_output",
"(",
"command",
")",
".",
"decode",
"(",
"'utf-8'",
")",
".",
"strip",
"(",
")",
"# nosec",
"except",
"CalledProcessError",
":",
"return",
"''",
"else",
":",
"return",
"(",
"run",
"(",
"command",
",",
"stdout",
"=",
"PIPE",
",",
"stderr",
"=",
"PIPE",
")",
".",
"stdout",
".",
"decode",
"(",
"'utf-8'",
")",
".",
"strip",
"(",
")",
")"
]
| Identify the path to the repository origin. | [
"Identify",
"the",
"path",
"to",
"the",
"repository",
"origin",
"."
]
| 9b34cefcbaf9a326e3f3cd517896c2933cf61a3b | https://github.com/jaumebonet/libconfig/blob/9b34cefcbaf9a326e3f3cd517896c2933cf61a3b/libconfig/config.py#L622-L632 | train |
jaumebonet/libconfig | libconfig/config.py | _entry_must_exist | def _entry_must_exist(df, k1, k2):
"""Evaluate key-subkey existence.
Checks that the key-subkey combo exists in the
configuration options.
"""
count = df[(df['k1'] == k1) &
(df['k2'] == k2)].shape[0]
if count == 0:
raise NotRegisteredError(
"Option {0}.{1} not registered".format(k1, k2)) | python | def _entry_must_exist(df, k1, k2):
"""Evaluate key-subkey existence.
Checks that the key-subkey combo exists in the
configuration options.
"""
count = df[(df['k1'] == k1) &
(df['k2'] == k2)].shape[0]
if count == 0:
raise NotRegisteredError(
"Option {0}.{1} not registered".format(k1, k2)) | [
"def",
"_entry_must_exist",
"(",
"df",
",",
"k1",
",",
"k2",
")",
":",
"count",
"=",
"df",
"[",
"(",
"df",
"[",
"'k1'",
"]",
"==",
"k1",
")",
"&",
"(",
"df",
"[",
"'k2'",
"]",
"==",
"k2",
")",
"]",
".",
"shape",
"[",
"0",
"]",
"if",
"count",
"==",
"0",
":",
"raise",
"NotRegisteredError",
"(",
"\"Option {0}.{1} not registered\"",
".",
"format",
"(",
"k1",
",",
"k2",
")",
")"
]
| Evaluate key-subkey existence.
Checks that the key-subkey combo exists in the
configuration options. | [
"Evaluate",
"key",
"-",
"subkey",
"existence",
"."
]
| 9b34cefcbaf9a326e3f3cd517896c2933cf61a3b | https://github.com/jaumebonet/libconfig/blob/9b34cefcbaf9a326e3f3cd517896c2933cf61a3b/libconfig/config.py#L640-L650 | train |
jaumebonet/libconfig | libconfig/config.py | _entry_must_not_exist | def _entry_must_not_exist(df, k1, k2):
"""Evaluate key-subkey non-existence.
Checks that the key-subkey combo does not exists in the
configuration options.
"""
count = df[(df['k1'] == k1) &
(df['k2'] == k2)].shape[0]
if count > 0:
raise AlreadyRegisteredError(
"Option {0}.{1} already registered".format(k1, k2)) | python | def _entry_must_not_exist(df, k1, k2):
"""Evaluate key-subkey non-existence.
Checks that the key-subkey combo does not exists in the
configuration options.
"""
count = df[(df['k1'] == k1) &
(df['k2'] == k2)].shape[0]
if count > 0:
raise AlreadyRegisteredError(
"Option {0}.{1} already registered".format(k1, k2)) | [
"def",
"_entry_must_not_exist",
"(",
"df",
",",
"k1",
",",
"k2",
")",
":",
"count",
"=",
"df",
"[",
"(",
"df",
"[",
"'k1'",
"]",
"==",
"k1",
")",
"&",
"(",
"df",
"[",
"'k2'",
"]",
"==",
"k2",
")",
"]",
".",
"shape",
"[",
"0",
"]",
"if",
"count",
">",
"0",
":",
"raise",
"AlreadyRegisteredError",
"(",
"\"Option {0}.{1} already registered\"",
".",
"format",
"(",
"k1",
",",
"k2",
")",
")"
]
| Evaluate key-subkey non-existence.
Checks that the key-subkey combo does not exists in the
configuration options. | [
"Evaluate",
"key",
"-",
"subkey",
"non",
"-",
"existence",
"."
]
| 9b34cefcbaf9a326e3f3cd517896c2933cf61a3b | https://github.com/jaumebonet/libconfig/blob/9b34cefcbaf9a326e3f3cd517896c2933cf61a3b/libconfig/config.py#L653-L663 | train |
jaumebonet/libconfig | libconfig/config.py | Config.register_option | def register_option(self, key, subkey, default, _type, definition,
values=None, locked=False):
"""Create a new option.
:param str key: First identifier of the option.
:param str subkey: Second identifier of the option.
:param default: Default value of the option. Type varies and it is
described by ``_type``.
:param str _type: Type of the value of the option. Available
options are: [``int``, ``float``, ``bool``, ``text``,
``string``, ``path_in``, ``path_out``].
:param str definition: Brief explanation of the option.
:type definition: :class:`str`
:param values: Available values for the option.
:type values: :func:`list` of accepted ``_type``
:param bool locked: If True, option cannot be altered.
:raise:
:AlreadyRegisteredError: If ``key`` or ``subkey`` already
define an option.
"""
if not self.open:
return
key, subkey = _lower_keys(key, subkey)
_entry_must_not_exist(self.gc, key, subkey)
ev.value_eval(default, _type)
values = None if values is False else values
new_opt = pd.Series([key, subkey, default, _type, default,
locked, definition, values], index=self.clmn)
self.gc = self.gc.append(new_opt, ignore_index=True) | python | def register_option(self, key, subkey, default, _type, definition,
values=None, locked=False):
"""Create a new option.
:param str key: First identifier of the option.
:param str subkey: Second identifier of the option.
:param default: Default value of the option. Type varies and it is
described by ``_type``.
:param str _type: Type of the value of the option. Available
options are: [``int``, ``float``, ``bool``, ``text``,
``string``, ``path_in``, ``path_out``].
:param str definition: Brief explanation of the option.
:type definition: :class:`str`
:param values: Available values for the option.
:type values: :func:`list` of accepted ``_type``
:param bool locked: If True, option cannot be altered.
:raise:
:AlreadyRegisteredError: If ``key`` or ``subkey`` already
define an option.
"""
if not self.open:
return
key, subkey = _lower_keys(key, subkey)
_entry_must_not_exist(self.gc, key, subkey)
ev.value_eval(default, _type)
values = None if values is False else values
new_opt = pd.Series([key, subkey, default, _type, default,
locked, definition, values], index=self.clmn)
self.gc = self.gc.append(new_opt, ignore_index=True) | [
"def",
"register_option",
"(",
"self",
",",
"key",
",",
"subkey",
",",
"default",
",",
"_type",
",",
"definition",
",",
"values",
"=",
"None",
",",
"locked",
"=",
"False",
")",
":",
"if",
"not",
"self",
".",
"open",
":",
"return",
"key",
",",
"subkey",
"=",
"_lower_keys",
"(",
"key",
",",
"subkey",
")",
"_entry_must_not_exist",
"(",
"self",
".",
"gc",
",",
"key",
",",
"subkey",
")",
"ev",
".",
"value_eval",
"(",
"default",
",",
"_type",
")",
"values",
"=",
"None",
"if",
"values",
"is",
"False",
"else",
"values",
"new_opt",
"=",
"pd",
".",
"Series",
"(",
"[",
"key",
",",
"subkey",
",",
"default",
",",
"_type",
",",
"default",
",",
"locked",
",",
"definition",
",",
"values",
"]",
",",
"index",
"=",
"self",
".",
"clmn",
")",
"self",
".",
"gc",
"=",
"self",
".",
"gc",
".",
"append",
"(",
"new_opt",
",",
"ignore_index",
"=",
"True",
")"
]
| Create a new option.
:param str key: First identifier of the option.
:param str subkey: Second identifier of the option.
:param default: Default value of the option. Type varies and it is
described by ``_type``.
:param str _type: Type of the value of the option. Available
options are: [``int``, ``float``, ``bool``, ``text``,
``string``, ``path_in``, ``path_out``].
:param str definition: Brief explanation of the option.
:type definition: :class:`str`
:param values: Available values for the option.
:type values: :func:`list` of accepted ``_type``
:param bool locked: If True, option cannot be altered.
:raise:
:AlreadyRegisteredError: If ``key`` or ``subkey`` already
define an option. | [
"Create",
"a",
"new",
"option",
"."
]
| 9b34cefcbaf9a326e3f3cd517896c2933cf61a3b | https://github.com/jaumebonet/libconfig/blob/9b34cefcbaf9a326e3f3cd517896c2933cf61a3b/libconfig/config.py#L37-L70 | train |
jaumebonet/libconfig | libconfig/config.py | Config.unregister_option | def unregister_option(self, key, subkey):
"""Removes an option from the manager.
:param str key: First identifier of the option.
:param str subkey: Second identifier of the option.
raise:
:NotRegisteredError: If ``key`` or ``subkey`` do not define
any option.
"""
if not self.open:
return
key, subkey = _lower_keys(key, subkey)
_entry_must_exist(self.gc, key, subkey)
self.gc = self.gc[~((self.gc['k1'] == key) &
(self.gc['k2'] == subkey))] | python | def unregister_option(self, key, subkey):
"""Removes an option from the manager.
:param str key: First identifier of the option.
:param str subkey: Second identifier of the option.
raise:
:NotRegisteredError: If ``key`` or ``subkey`` do not define
any option.
"""
if not self.open:
return
key, subkey = _lower_keys(key, subkey)
_entry_must_exist(self.gc, key, subkey)
self.gc = self.gc[~((self.gc['k1'] == key) &
(self.gc['k2'] == subkey))] | [
"def",
"unregister_option",
"(",
"self",
",",
"key",
",",
"subkey",
")",
":",
"if",
"not",
"self",
".",
"open",
":",
"return",
"key",
",",
"subkey",
"=",
"_lower_keys",
"(",
"key",
",",
"subkey",
")",
"_entry_must_exist",
"(",
"self",
".",
"gc",
",",
"key",
",",
"subkey",
")",
"self",
".",
"gc",
"=",
"self",
".",
"gc",
"[",
"~",
"(",
"(",
"self",
".",
"gc",
"[",
"'k1'",
"]",
"==",
"key",
")",
"&",
"(",
"self",
".",
"gc",
"[",
"'k2'",
"]",
"==",
"subkey",
")",
")",
"]"
]
| Removes an option from the manager.
:param str key: First identifier of the option.
:param str subkey: Second identifier of the option.
raise:
:NotRegisteredError: If ``key`` or ``subkey`` do not define
any option. | [
"Removes",
"an",
"option",
"from",
"the",
"manager",
"."
]
| 9b34cefcbaf9a326e3f3cd517896c2933cf61a3b | https://github.com/jaumebonet/libconfig/blob/9b34cefcbaf9a326e3f3cd517896c2933cf61a3b/libconfig/config.py#L72-L89 | train |
jaumebonet/libconfig | libconfig/config.py | Config.get_option | def get_option(self, key, subkey, in_path_none=False):
"""Get the current value of the option.
:param str key: First identifier of the option.
:param str subkey: Second identifier of the option.
:param bool in_path_none: Allows for ``in_path`` values of
:data:`None` to be retrieved.
:return: Current value of the option (type varies).
:raise:
:NotRegisteredError: If ``key`` or ``subkey`` do not define
any option.
:ValueError: If a ``in_path`` type with :data:`None` value is
requested.
"""
key, subkey = _lower_keys(key, subkey)
_entry_must_exist(self.gc, key, subkey)
df = self.gc[(self.gc["k1"] == key) & (self.gc["k2"] == subkey)]
if df["type"].values[0] == "bool":
return bool(df["value"].values[0])
elif df["type"].values[0] == "int":
return int(df["value"].values[0])
elif df["type"].values[0] == "path_in":
if df["value"].values[0] is None and not in_path_none:
raise ValueError('Unspecified path for {0}.{1}'.format(key,
subkey))
return df["value"].values[0]
else:
return df["value"].values[0] | python | def get_option(self, key, subkey, in_path_none=False):
"""Get the current value of the option.
:param str key: First identifier of the option.
:param str subkey: Second identifier of the option.
:param bool in_path_none: Allows for ``in_path`` values of
:data:`None` to be retrieved.
:return: Current value of the option (type varies).
:raise:
:NotRegisteredError: If ``key`` or ``subkey`` do not define
any option.
:ValueError: If a ``in_path`` type with :data:`None` value is
requested.
"""
key, subkey = _lower_keys(key, subkey)
_entry_must_exist(self.gc, key, subkey)
df = self.gc[(self.gc["k1"] == key) & (self.gc["k2"] == subkey)]
if df["type"].values[0] == "bool":
return bool(df["value"].values[0])
elif df["type"].values[0] == "int":
return int(df["value"].values[0])
elif df["type"].values[0] == "path_in":
if df["value"].values[0] is None and not in_path_none:
raise ValueError('Unspecified path for {0}.{1}'.format(key,
subkey))
return df["value"].values[0]
else:
return df["value"].values[0] | [
"def",
"get_option",
"(",
"self",
",",
"key",
",",
"subkey",
",",
"in_path_none",
"=",
"False",
")",
":",
"key",
",",
"subkey",
"=",
"_lower_keys",
"(",
"key",
",",
"subkey",
")",
"_entry_must_exist",
"(",
"self",
".",
"gc",
",",
"key",
",",
"subkey",
")",
"df",
"=",
"self",
".",
"gc",
"[",
"(",
"self",
".",
"gc",
"[",
"\"k1\"",
"]",
"==",
"key",
")",
"&",
"(",
"self",
".",
"gc",
"[",
"\"k2\"",
"]",
"==",
"subkey",
")",
"]",
"if",
"df",
"[",
"\"type\"",
"]",
".",
"values",
"[",
"0",
"]",
"==",
"\"bool\"",
":",
"return",
"bool",
"(",
"df",
"[",
"\"value\"",
"]",
".",
"values",
"[",
"0",
"]",
")",
"elif",
"df",
"[",
"\"type\"",
"]",
".",
"values",
"[",
"0",
"]",
"==",
"\"int\"",
":",
"return",
"int",
"(",
"df",
"[",
"\"value\"",
"]",
".",
"values",
"[",
"0",
"]",
")",
"elif",
"df",
"[",
"\"type\"",
"]",
".",
"values",
"[",
"0",
"]",
"==",
"\"path_in\"",
":",
"if",
"df",
"[",
"\"value\"",
"]",
".",
"values",
"[",
"0",
"]",
"is",
"None",
"and",
"not",
"in_path_none",
":",
"raise",
"ValueError",
"(",
"'Unspecified path for {0}.{1}'",
".",
"format",
"(",
"key",
",",
"subkey",
")",
")",
"return",
"df",
"[",
"\"value\"",
"]",
".",
"values",
"[",
"0",
"]",
"else",
":",
"return",
"df",
"[",
"\"value\"",
"]",
".",
"values",
"[",
"0",
"]"
]
| Get the current value of the option.
:param str key: First identifier of the option.
:param str subkey: Second identifier of the option.
:param bool in_path_none: Allows for ``in_path`` values of
:data:`None` to be retrieved.
:return: Current value of the option (type varies).
:raise:
:NotRegisteredError: If ``key`` or ``subkey`` do not define
any option.
:ValueError: If a ``in_path`` type with :data:`None` value is
requested. | [
"Get",
"the",
"current",
"value",
"of",
"the",
"option",
"."
]
| 9b34cefcbaf9a326e3f3cd517896c2933cf61a3b | https://github.com/jaumebonet/libconfig/blob/9b34cefcbaf9a326e3f3cd517896c2933cf61a3b/libconfig/config.py#L91-L121 | train |
jaumebonet/libconfig | libconfig/config.py | Config.get_option_default | def get_option_default(self, key, subkey):
"""Get the default value of the option.
:param str key: First identifier of the option.
:param str subkey: Second identifier of the option.
:return: Default value of the option (type varies).
:raise:
:NotRegisteredError: If ``key`` or ``subkey`` do not define
any option.
"""
key, subkey = _lower_keys(key, subkey)
_entry_must_exist(self.gc, key, subkey)
df = self.gc[(self.gc["k1"] == key) & (self.gc["k2"] == subkey)]
if df["type"].values[0] == "bool":
return bool(df["default"].values[0])
elif df["type"].values[0] == "int":
return int(df["default"].values[0])
else:
return df["default"].values[0] | python | def get_option_default(self, key, subkey):
"""Get the default value of the option.
:param str key: First identifier of the option.
:param str subkey: Second identifier of the option.
:return: Default value of the option (type varies).
:raise:
:NotRegisteredError: If ``key`` or ``subkey`` do not define
any option.
"""
key, subkey = _lower_keys(key, subkey)
_entry_must_exist(self.gc, key, subkey)
df = self.gc[(self.gc["k1"] == key) & (self.gc["k2"] == subkey)]
if df["type"].values[0] == "bool":
return bool(df["default"].values[0])
elif df["type"].values[0] == "int":
return int(df["default"].values[0])
else:
return df["default"].values[0] | [
"def",
"get_option_default",
"(",
"self",
",",
"key",
",",
"subkey",
")",
":",
"key",
",",
"subkey",
"=",
"_lower_keys",
"(",
"key",
",",
"subkey",
")",
"_entry_must_exist",
"(",
"self",
".",
"gc",
",",
"key",
",",
"subkey",
")",
"df",
"=",
"self",
".",
"gc",
"[",
"(",
"self",
".",
"gc",
"[",
"\"k1\"",
"]",
"==",
"key",
")",
"&",
"(",
"self",
".",
"gc",
"[",
"\"k2\"",
"]",
"==",
"subkey",
")",
"]",
"if",
"df",
"[",
"\"type\"",
"]",
".",
"values",
"[",
"0",
"]",
"==",
"\"bool\"",
":",
"return",
"bool",
"(",
"df",
"[",
"\"default\"",
"]",
".",
"values",
"[",
"0",
"]",
")",
"elif",
"df",
"[",
"\"type\"",
"]",
".",
"values",
"[",
"0",
"]",
"==",
"\"int\"",
":",
"return",
"int",
"(",
"df",
"[",
"\"default\"",
"]",
".",
"values",
"[",
"0",
"]",
")",
"else",
":",
"return",
"df",
"[",
"\"default\"",
"]",
".",
"values",
"[",
"0",
"]"
]
| Get the default value of the option.
:param str key: First identifier of the option.
:param str subkey: Second identifier of the option.
:return: Default value of the option (type varies).
:raise:
:NotRegisteredError: If ``key`` or ``subkey`` do not define
any option. | [
"Get",
"the",
"default",
"value",
"of",
"the",
"option",
"."
]
| 9b34cefcbaf9a326e3f3cd517896c2933cf61a3b | https://github.com/jaumebonet/libconfig/blob/9b34cefcbaf9a326e3f3cd517896c2933cf61a3b/libconfig/config.py#L123-L144 | train |
jaumebonet/libconfig | libconfig/config.py | Config.get_option_description | def get_option_description(self, key, subkey):
"""Get the string describing a particular option.
:param str key: First identifier of the option.
:param str subkey: Second identifier of the option.
:return: :class:`str` - description of the option.
:raise:
:NotRegisteredError: If ``key`` or ``subkey`` do not define any
option.
"""
key, subkey = _lower_keys(key, subkey)
_entry_must_exist(self.gc, key, subkey)
return self.gc[(self.gc["k1"] == key) &
(self.gc["k2"] == subkey)]["description"].values[0] | python | def get_option_description(self, key, subkey):
"""Get the string describing a particular option.
:param str key: First identifier of the option.
:param str subkey: Second identifier of the option.
:return: :class:`str` - description of the option.
:raise:
:NotRegisteredError: If ``key`` or ``subkey`` do not define any
option.
"""
key, subkey = _lower_keys(key, subkey)
_entry_must_exist(self.gc, key, subkey)
return self.gc[(self.gc["k1"] == key) &
(self.gc["k2"] == subkey)]["description"].values[0] | [
"def",
"get_option_description",
"(",
"self",
",",
"key",
",",
"subkey",
")",
":",
"key",
",",
"subkey",
"=",
"_lower_keys",
"(",
"key",
",",
"subkey",
")",
"_entry_must_exist",
"(",
"self",
".",
"gc",
",",
"key",
",",
"subkey",
")",
"return",
"self",
".",
"gc",
"[",
"(",
"self",
".",
"gc",
"[",
"\"k1\"",
"]",
"==",
"key",
")",
"&",
"(",
"self",
".",
"gc",
"[",
"\"k2\"",
"]",
"==",
"subkey",
")",
"]",
"[",
"\"description\"",
"]",
".",
"values",
"[",
"0",
"]"
]
| Get the string describing a particular option.
:param str key: First identifier of the option.
:param str subkey: Second identifier of the option.
:return: :class:`str` - description of the option.
:raise:
:NotRegisteredError: If ``key`` or ``subkey`` do not define any
option. | [
"Get",
"the",
"string",
"describing",
"a",
"particular",
"option",
"."
]
| 9b34cefcbaf9a326e3f3cd517896c2933cf61a3b | https://github.com/jaumebonet/libconfig/blob/9b34cefcbaf9a326e3f3cd517896c2933cf61a3b/libconfig/config.py#L146-L162 | train |
jaumebonet/libconfig | libconfig/config.py | Config.get_option_type | def get_option_type(self, key, subkey):
"""Get the type of a particular option.
:param str key: First identifier of the option.
:param str subkey: Second identifier of the option.
:return: :class:`str` - description of the type.
:raise:
:NotRegisteredError: If ``key`` or ``subkey`` do not define any
option.
"""
key, subkey = _lower_keys(key, subkey)
_entry_must_exist(self.gc, key, subkey)
return self.gc[(self.gc["k1"] == key) &
(self.gc["k2"] == subkey)]["type"].values[0] | python | def get_option_type(self, key, subkey):
"""Get the type of a particular option.
:param str key: First identifier of the option.
:param str subkey: Second identifier of the option.
:return: :class:`str` - description of the type.
:raise:
:NotRegisteredError: If ``key`` or ``subkey`` do not define any
option.
"""
key, subkey = _lower_keys(key, subkey)
_entry_must_exist(self.gc, key, subkey)
return self.gc[(self.gc["k1"] == key) &
(self.gc["k2"] == subkey)]["type"].values[0] | [
"def",
"get_option_type",
"(",
"self",
",",
"key",
",",
"subkey",
")",
":",
"key",
",",
"subkey",
"=",
"_lower_keys",
"(",
"key",
",",
"subkey",
")",
"_entry_must_exist",
"(",
"self",
".",
"gc",
",",
"key",
",",
"subkey",
")",
"return",
"self",
".",
"gc",
"[",
"(",
"self",
".",
"gc",
"[",
"\"k1\"",
"]",
"==",
"key",
")",
"&",
"(",
"self",
".",
"gc",
"[",
"\"k2\"",
"]",
"==",
"subkey",
")",
"]",
"[",
"\"type\"",
"]",
".",
"values",
"[",
"0",
"]"
]
| Get the type of a particular option.
:param str key: First identifier of the option.
:param str subkey: Second identifier of the option.
:return: :class:`str` - description of the type.
:raise:
:NotRegisteredError: If ``key`` or ``subkey`` do not define any
option. | [
"Get",
"the",
"type",
"of",
"a",
"particular",
"option",
"."
]
| 9b34cefcbaf9a326e3f3cd517896c2933cf61a3b | https://github.com/jaumebonet/libconfig/blob/9b34cefcbaf9a326e3f3cd517896c2933cf61a3b/libconfig/config.py#L164-L180 | train |
jaumebonet/libconfig | libconfig/config.py | Config.get_option_alternatives | def get_option_alternatives(self, key, subkey):
"""Get list of available values for an option.
:param str key: First identifier of the option.
:param str subkey: Second identifier of the option.
:return: Union[:func:`list`, :data:`None`] - alternative values
for the option, if any specified (otherwise, is open).
:raise:
:NotRegisteredError: If ``key`` or ``subkey`` do not define any
option.
"""
key, subkey = _lower_keys(key, subkey)
_entry_must_exist(self.gc, key, subkey)
return self.gc[(self.gc["k1"] == key) &
(self.gc["k2"] == subkey)]["values"].values[0] | python | def get_option_alternatives(self, key, subkey):
"""Get list of available values for an option.
:param str key: First identifier of the option.
:param str subkey: Second identifier of the option.
:return: Union[:func:`list`, :data:`None`] - alternative values
for the option, if any specified (otherwise, is open).
:raise:
:NotRegisteredError: If ``key`` or ``subkey`` do not define any
option.
"""
key, subkey = _lower_keys(key, subkey)
_entry_must_exist(self.gc, key, subkey)
return self.gc[(self.gc["k1"] == key) &
(self.gc["k2"] == subkey)]["values"].values[0] | [
"def",
"get_option_alternatives",
"(",
"self",
",",
"key",
",",
"subkey",
")",
":",
"key",
",",
"subkey",
"=",
"_lower_keys",
"(",
"key",
",",
"subkey",
")",
"_entry_must_exist",
"(",
"self",
".",
"gc",
",",
"key",
",",
"subkey",
")",
"return",
"self",
".",
"gc",
"[",
"(",
"self",
".",
"gc",
"[",
"\"k1\"",
"]",
"==",
"key",
")",
"&",
"(",
"self",
".",
"gc",
"[",
"\"k2\"",
"]",
"==",
"subkey",
")",
"]",
"[",
"\"values\"",
"]",
".",
"values",
"[",
"0",
"]"
]
| Get list of available values for an option.
:param str key: First identifier of the option.
:param str subkey: Second identifier of the option.
:return: Union[:func:`list`, :data:`None`] - alternative values
for the option, if any specified (otherwise, is open).
:raise:
:NotRegisteredError: If ``key`` or ``subkey`` do not define any
option. | [
"Get",
"list",
"of",
"available",
"values",
"for",
"an",
"option",
"."
]
| 9b34cefcbaf9a326e3f3cd517896c2933cf61a3b | https://github.com/jaumebonet/libconfig/blob/9b34cefcbaf9a326e3f3cd517896c2933cf61a3b/libconfig/config.py#L182-L199 | train |
jaumebonet/libconfig | libconfig/config.py | Config.set_option | def set_option(self, key, subkey, value):
"""Sets the value of an option.
:param str key: First identifier of the option.
:param str subkey: Second identifier of the option.
:param value: New value for the option (type varies).
:raise:
:NotRegisteredError: If ``key`` or ``subkey`` do not define any
option.
:ValueError: If the targeted obtion is locked.
:ValueError: If the provided value is not the expected
type for the option.
:ValueError: If the provided value is not in the expected
available values for the option.
"""
key, subkey = _lower_keys(key, subkey)
_entry_must_exist(self.gc, key, subkey)
df = self.gc[(self.gc["k1"] == key) & (self.gc["k2"] == subkey)]
if df["locked"].values[0]:
raise ValueError("{0}.{1} option is locked".format(key, subkey))
ev.value_eval(value, df["type"].values[0])
if not self.check_option(key, subkey, value):
info = "{0}.{1} accepted options are: ".format(key, subkey)
info += "[{}]".format(", ".join(df["values"].values[0]))
raise ValueError(info)
self.gc.loc[
(self.gc["k1"] == key) &
(self.gc["k2"] == subkey), "value"] = value | python | def set_option(self, key, subkey, value):
"""Sets the value of an option.
:param str key: First identifier of the option.
:param str subkey: Second identifier of the option.
:param value: New value for the option (type varies).
:raise:
:NotRegisteredError: If ``key`` or ``subkey`` do not define any
option.
:ValueError: If the targeted obtion is locked.
:ValueError: If the provided value is not the expected
type for the option.
:ValueError: If the provided value is not in the expected
available values for the option.
"""
key, subkey = _lower_keys(key, subkey)
_entry_must_exist(self.gc, key, subkey)
df = self.gc[(self.gc["k1"] == key) & (self.gc["k2"] == subkey)]
if df["locked"].values[0]:
raise ValueError("{0}.{1} option is locked".format(key, subkey))
ev.value_eval(value, df["type"].values[0])
if not self.check_option(key, subkey, value):
info = "{0}.{1} accepted options are: ".format(key, subkey)
info += "[{}]".format(", ".join(df["values"].values[0]))
raise ValueError(info)
self.gc.loc[
(self.gc["k1"] == key) &
(self.gc["k2"] == subkey), "value"] = value | [
"def",
"set_option",
"(",
"self",
",",
"key",
",",
"subkey",
",",
"value",
")",
":",
"key",
",",
"subkey",
"=",
"_lower_keys",
"(",
"key",
",",
"subkey",
")",
"_entry_must_exist",
"(",
"self",
".",
"gc",
",",
"key",
",",
"subkey",
")",
"df",
"=",
"self",
".",
"gc",
"[",
"(",
"self",
".",
"gc",
"[",
"\"k1\"",
"]",
"==",
"key",
")",
"&",
"(",
"self",
".",
"gc",
"[",
"\"k2\"",
"]",
"==",
"subkey",
")",
"]",
"if",
"df",
"[",
"\"locked\"",
"]",
".",
"values",
"[",
"0",
"]",
":",
"raise",
"ValueError",
"(",
"\"{0}.{1} option is locked\"",
".",
"format",
"(",
"key",
",",
"subkey",
")",
")",
"ev",
".",
"value_eval",
"(",
"value",
",",
"df",
"[",
"\"type\"",
"]",
".",
"values",
"[",
"0",
"]",
")",
"if",
"not",
"self",
".",
"check_option",
"(",
"key",
",",
"subkey",
",",
"value",
")",
":",
"info",
"=",
"\"{0}.{1} accepted options are: \"",
".",
"format",
"(",
"key",
",",
"subkey",
")",
"info",
"+=",
"\"[{}]\"",
".",
"format",
"(",
"\", \"",
".",
"join",
"(",
"df",
"[",
"\"values\"",
"]",
".",
"values",
"[",
"0",
"]",
")",
")",
"raise",
"ValueError",
"(",
"info",
")",
"self",
".",
"gc",
".",
"loc",
"[",
"(",
"self",
".",
"gc",
"[",
"\"k1\"",
"]",
"==",
"key",
")",
"&",
"(",
"self",
".",
"gc",
"[",
"\"k2\"",
"]",
"==",
"subkey",
")",
",",
"\"value\"",
"]",
"=",
"value"
]
| Sets the value of an option.
:param str key: First identifier of the option.
:param str subkey: Second identifier of the option.
:param value: New value for the option (type varies).
:raise:
:NotRegisteredError: If ``key`` or ``subkey`` do not define any
option.
:ValueError: If the targeted obtion is locked.
:ValueError: If the provided value is not the expected
type for the option.
:ValueError: If the provided value is not in the expected
available values for the option. | [
"Sets",
"the",
"value",
"of",
"an",
"option",
"."
]
| 9b34cefcbaf9a326e3f3cd517896c2933cf61a3b | https://github.com/jaumebonet/libconfig/blob/9b34cefcbaf9a326e3f3cd517896c2933cf61a3b/libconfig/config.py#L201-L230 | train |
jaumebonet/libconfig | libconfig/config.py | Config.check_option | def check_option(self, key, subkey, value):
"""Evaluate if a given value fits the option.
If an option has a limited set of available values, check if the
provided value is amongst them.
:param str key: First identifier of the option.
:param str subkey: Second identifier of the option.
:param value: Value to test (type varies).
:return: :class:`bool` - does ``value`` belong to the options?
:raise:
:NotRegisteredError: If ``key`` or ``subkey`` do not define any
option.
:ValueError: If the provided value is not the expected
type for the option.
"""
key, subkey = _lower_keys(key, subkey)
_entry_must_exist(self.gc, key, subkey)
df = self.gc[(self.gc["k1"] == key) & (self.gc["k2"] == subkey)]
ev.value_eval(value, df["type"].values[0])
if df["values"].values[0] is not None:
return value in df["values"].values[0]
return True | python | def check_option(self, key, subkey, value):
"""Evaluate if a given value fits the option.
If an option has a limited set of available values, check if the
provided value is amongst them.
:param str key: First identifier of the option.
:param str subkey: Second identifier of the option.
:param value: Value to test (type varies).
:return: :class:`bool` - does ``value`` belong to the options?
:raise:
:NotRegisteredError: If ``key`` or ``subkey`` do not define any
option.
:ValueError: If the provided value is not the expected
type for the option.
"""
key, subkey = _lower_keys(key, subkey)
_entry_must_exist(self.gc, key, subkey)
df = self.gc[(self.gc["k1"] == key) & (self.gc["k2"] == subkey)]
ev.value_eval(value, df["type"].values[0])
if df["values"].values[0] is not None:
return value in df["values"].values[0]
return True | [
"def",
"check_option",
"(",
"self",
",",
"key",
",",
"subkey",
",",
"value",
")",
":",
"key",
",",
"subkey",
"=",
"_lower_keys",
"(",
"key",
",",
"subkey",
")",
"_entry_must_exist",
"(",
"self",
".",
"gc",
",",
"key",
",",
"subkey",
")",
"df",
"=",
"self",
".",
"gc",
"[",
"(",
"self",
".",
"gc",
"[",
"\"k1\"",
"]",
"==",
"key",
")",
"&",
"(",
"self",
".",
"gc",
"[",
"\"k2\"",
"]",
"==",
"subkey",
")",
"]",
"ev",
".",
"value_eval",
"(",
"value",
",",
"df",
"[",
"\"type\"",
"]",
".",
"values",
"[",
"0",
"]",
")",
"if",
"df",
"[",
"\"values\"",
"]",
".",
"values",
"[",
"0",
"]",
"is",
"not",
"None",
":",
"return",
"value",
"in",
"df",
"[",
"\"values\"",
"]",
".",
"values",
"[",
"0",
"]",
"return",
"True"
]
| Evaluate if a given value fits the option.
If an option has a limited set of available values, check if the
provided value is amongst them.
:param str key: First identifier of the option.
:param str subkey: Second identifier of the option.
:param value: Value to test (type varies).
:return: :class:`bool` - does ``value`` belong to the options?
:raise:
:NotRegisteredError: If ``key`` or ``subkey`` do not define any
option.
:ValueError: If the provided value is not the expected
type for the option. | [
"Evaluate",
"if",
"a",
"given",
"value",
"fits",
"the",
"option",
"."
]
| 9b34cefcbaf9a326e3f3cd517896c2933cf61a3b | https://github.com/jaumebonet/libconfig/blob/9b34cefcbaf9a326e3f3cd517896c2933cf61a3b/libconfig/config.py#L232-L257 | train |
jaumebonet/libconfig | libconfig/config.py | Config.reset_option | def reset_option(self, key, subkey):
"""Resets a single option to the default values.
:param str key: First identifier of the option.
:param str subkey: Second identifier of the option.
:raise:
:NotRegisteredError: If ``key`` or ``subkey`` do not define any
option.
:ValueError: If the targeted obtion is locked.
"""
if not self.open:
return
key, subkey = _lower_keys(key, subkey)
_entry_must_exist(self.gc, key, subkey)
df = self.gc[(self.gc["k1"] == key) & (self.gc["k2"] == subkey)]
if df["locked"].values[0]:
raise ValueError("{0}.{1} option is locked".format(key, subkey))
val = df["default"].values[0]
self.gc.loc[
(self.gc["k1"] == key) &
(self.gc["k2"] == subkey), "value"] = val | python | def reset_option(self, key, subkey):
"""Resets a single option to the default values.
:param str key: First identifier of the option.
:param str subkey: Second identifier of the option.
:raise:
:NotRegisteredError: If ``key`` or ``subkey`` do not define any
option.
:ValueError: If the targeted obtion is locked.
"""
if not self.open:
return
key, subkey = _lower_keys(key, subkey)
_entry_must_exist(self.gc, key, subkey)
df = self.gc[(self.gc["k1"] == key) & (self.gc["k2"] == subkey)]
if df["locked"].values[0]:
raise ValueError("{0}.{1} option is locked".format(key, subkey))
val = df["default"].values[0]
self.gc.loc[
(self.gc["k1"] == key) &
(self.gc["k2"] == subkey), "value"] = val | [
"def",
"reset_option",
"(",
"self",
",",
"key",
",",
"subkey",
")",
":",
"if",
"not",
"self",
".",
"open",
":",
"return",
"key",
",",
"subkey",
"=",
"_lower_keys",
"(",
"key",
",",
"subkey",
")",
"_entry_must_exist",
"(",
"self",
".",
"gc",
",",
"key",
",",
"subkey",
")",
"df",
"=",
"self",
".",
"gc",
"[",
"(",
"self",
".",
"gc",
"[",
"\"k1\"",
"]",
"==",
"key",
")",
"&",
"(",
"self",
".",
"gc",
"[",
"\"k2\"",
"]",
"==",
"subkey",
")",
"]",
"if",
"df",
"[",
"\"locked\"",
"]",
".",
"values",
"[",
"0",
"]",
":",
"raise",
"ValueError",
"(",
"\"{0}.{1} option is locked\"",
".",
"format",
"(",
"key",
",",
"subkey",
")",
")",
"val",
"=",
"df",
"[",
"\"default\"",
"]",
".",
"values",
"[",
"0",
"]",
"self",
".",
"gc",
".",
"loc",
"[",
"(",
"self",
".",
"gc",
"[",
"\"k1\"",
"]",
"==",
"key",
")",
"&",
"(",
"self",
".",
"gc",
"[",
"\"k2\"",
"]",
"==",
"subkey",
")",
",",
"\"value\"",
"]",
"=",
"val"
]
| Resets a single option to the default values.
:param str key: First identifier of the option.
:param str subkey: Second identifier of the option.
:raise:
:NotRegisteredError: If ``key`` or ``subkey`` do not define any
option.
:ValueError: If the targeted obtion is locked. | [
"Resets",
"a",
"single",
"option",
"to",
"the",
"default",
"values",
"."
]
| 9b34cefcbaf9a326e3f3cd517896c2933cf61a3b | https://github.com/jaumebonet/libconfig/blob/9b34cefcbaf9a326e3f3cd517896c2933cf61a3b/libconfig/config.py#L259-L282 | train |
jaumebonet/libconfig | libconfig/config.py | Config.lock_option | def lock_option(self, key, subkey):
"""Make an option unmutable.
:param str key: First identifier of the option.
:param str subkey: Second identifier of the option.
:raise:
:NotRegisteredError: If ``key`` or ``subkey`` do not define any
option.
"""
key, subkey = _lower_keys(key, subkey)
_entry_must_exist(self.gc, key, subkey)
self.gc.loc[
(self.gc["k1"] == key) &
(self.gc["k2"] == subkey), "locked"] = True | python | def lock_option(self, key, subkey):
"""Make an option unmutable.
:param str key: First identifier of the option.
:param str subkey: Second identifier of the option.
:raise:
:NotRegisteredError: If ``key`` or ``subkey`` do not define any
option.
"""
key, subkey = _lower_keys(key, subkey)
_entry_must_exist(self.gc, key, subkey)
self.gc.loc[
(self.gc["k1"] == key) &
(self.gc["k2"] == subkey), "locked"] = True | [
"def",
"lock_option",
"(",
"self",
",",
"key",
",",
"subkey",
")",
":",
"key",
",",
"subkey",
"=",
"_lower_keys",
"(",
"key",
",",
"subkey",
")",
"_entry_must_exist",
"(",
"self",
".",
"gc",
",",
"key",
",",
"subkey",
")",
"self",
".",
"gc",
".",
"loc",
"[",
"(",
"self",
".",
"gc",
"[",
"\"k1\"",
"]",
"==",
"key",
")",
"&",
"(",
"self",
".",
"gc",
"[",
"\"k2\"",
"]",
"==",
"subkey",
")",
",",
"\"locked\"",
"]",
"=",
"True"
]
| Make an option unmutable.
:param str key: First identifier of the option.
:param str subkey: Second identifier of the option.
:raise:
:NotRegisteredError: If ``key`` or ``subkey`` do not define any
option. | [
"Make",
"an",
"option",
"unmutable",
"."
]
| 9b34cefcbaf9a326e3f3cd517896c2933cf61a3b | https://github.com/jaumebonet/libconfig/blob/9b34cefcbaf9a326e3f3cd517896c2933cf61a3b/libconfig/config.py#L284-L299 | train |
jaumebonet/libconfig | libconfig/config.py | Config.reset_options | def reset_options(self, empty=True):
"""Empty ALL options.
:param bool empty: When :data:`True`, completelly removes all options;
when :data:`False`, sets them back to its original value.
This function skips ``locked`` control.
"""
if empty:
self.gc = pd.DataFrame(columns=self.clmn)
else:
self.gc["value"] = self.gc["default"] | python | def reset_options(self, empty=True):
"""Empty ALL options.
:param bool empty: When :data:`True`, completelly removes all options;
when :data:`False`, sets them back to its original value.
This function skips ``locked`` control.
"""
if empty:
self.gc = pd.DataFrame(columns=self.clmn)
else:
self.gc["value"] = self.gc["default"] | [
"def",
"reset_options",
"(",
"self",
",",
"empty",
"=",
"True",
")",
":",
"if",
"empty",
":",
"self",
".",
"gc",
"=",
"pd",
".",
"DataFrame",
"(",
"columns",
"=",
"self",
".",
"clmn",
")",
"else",
":",
"self",
".",
"gc",
"[",
"\"value\"",
"]",
"=",
"self",
".",
"gc",
"[",
"\"default\"",
"]"
]
| Empty ALL options.
:param bool empty: When :data:`True`, completelly removes all options;
when :data:`False`, sets them back to its original value.
This function skips ``locked`` control. | [
"Empty",
"ALL",
"options",
"."
]
| 9b34cefcbaf9a326e3f3cd517896c2933cf61a3b | https://github.com/jaumebonet/libconfig/blob/9b34cefcbaf9a326e3f3cd517896c2933cf61a3b/libconfig/config.py#L326-L337 | train |
jaumebonet/libconfig | libconfig/config.py | Config.set_options_from_file | def set_options_from_file(self, filename, file_format='yaml'):
"""Load options from file.
This is a wrapper over :func:`.set_options_from_JSON` and
:func:`.set_options_from_YAML`.
:param str filename: File from which to load the options.
:param str file_format: File format (``yaml`` or ``json``).
:raises:
:ValueError: If an unknown ``format`` is requested.
"""
if file_format.lower() == 'yaml':
return self.set_options_from_YAML(filename)
elif file_format.lower() == 'json':
return self.set_options_from_JSON(filename)
else:
raise ValueError('Unknown format {}'.format(file_format)) | python | def set_options_from_file(self, filename, file_format='yaml'):
"""Load options from file.
This is a wrapper over :func:`.set_options_from_JSON` and
:func:`.set_options_from_YAML`.
:param str filename: File from which to load the options.
:param str file_format: File format (``yaml`` or ``json``).
:raises:
:ValueError: If an unknown ``format`` is requested.
"""
if file_format.lower() == 'yaml':
return self.set_options_from_YAML(filename)
elif file_format.lower() == 'json':
return self.set_options_from_JSON(filename)
else:
raise ValueError('Unknown format {}'.format(file_format)) | [
"def",
"set_options_from_file",
"(",
"self",
",",
"filename",
",",
"file_format",
"=",
"'yaml'",
")",
":",
"if",
"file_format",
".",
"lower",
"(",
")",
"==",
"'yaml'",
":",
"return",
"self",
".",
"set_options_from_YAML",
"(",
"filename",
")",
"elif",
"file_format",
".",
"lower",
"(",
")",
"==",
"'json'",
":",
"return",
"self",
".",
"set_options_from_JSON",
"(",
"filename",
")",
"else",
":",
"raise",
"ValueError",
"(",
"'Unknown format {}'",
".",
"format",
"(",
"file_format",
")",
")"
]
| Load options from file.
This is a wrapper over :func:`.set_options_from_JSON` and
:func:`.set_options_from_YAML`.
:param str filename: File from which to load the options.
:param str file_format: File format (``yaml`` or ``json``).
:raises:
:ValueError: If an unknown ``format`` is requested. | [
"Load",
"options",
"from",
"file",
"."
]
| 9b34cefcbaf9a326e3f3cd517896c2933cf61a3b | https://github.com/jaumebonet/libconfig/blob/9b34cefcbaf9a326e3f3cd517896c2933cf61a3b/libconfig/config.py#L367-L384 | train |
jaumebonet/libconfig | libconfig/config.py | Config.set_options_from_dict | def set_options_from_dict(self, data_dict, filename=None):
"""Load options from a dictionary.
:param dict data_dict: Dictionary with the options to load.
:param str filename: If provided, assume that non-absolute
paths provided are in reference to the file.
"""
if filename is not None:
filename = os.path.dirname(filename)
for k in data_dict:
if not isinstance(data_dict[k], dict):
raise ValueError("The input data has to be a dict of dict")
for sk in data_dict[k]:
if self.gc[(self.gc["k1"] == k) &
(self.gc["k2"] == sk)].shape[0] == 0:
continue
if isinstance(data_dict[k][sk], six.string_types):
data_dict[k][sk] = str(data_dict[k][sk])
_type = self.gc[(self.gc["k1"] == k) &
(self.gc["k2"] == sk)][["type"]].values[0]
data_dict[k][sk] = ev.cast(data_dict[k][sk], _type)
if self.get_option(k, sk, True) != data_dict[k][sk]:
try:
self.set_option(k, sk, data_dict[k][sk])
# Provided paths do not work: try add them relative
# to the config file
except IOError:
if filename is None:
raise IOError('Error path: {0}.{1}'.format(k, sk))
npat = os.path.join(filename, data_dict[k][sk])
self.set_option(k, sk, os.path.normpath(npat))
except ValueError:
pass | python | def set_options_from_dict(self, data_dict, filename=None):
"""Load options from a dictionary.
:param dict data_dict: Dictionary with the options to load.
:param str filename: If provided, assume that non-absolute
paths provided are in reference to the file.
"""
if filename is not None:
filename = os.path.dirname(filename)
for k in data_dict:
if not isinstance(data_dict[k], dict):
raise ValueError("The input data has to be a dict of dict")
for sk in data_dict[k]:
if self.gc[(self.gc["k1"] == k) &
(self.gc["k2"] == sk)].shape[0] == 0:
continue
if isinstance(data_dict[k][sk], six.string_types):
data_dict[k][sk] = str(data_dict[k][sk])
_type = self.gc[(self.gc["k1"] == k) &
(self.gc["k2"] == sk)][["type"]].values[0]
data_dict[k][sk] = ev.cast(data_dict[k][sk], _type)
if self.get_option(k, sk, True) != data_dict[k][sk]:
try:
self.set_option(k, sk, data_dict[k][sk])
# Provided paths do not work: try add them relative
# to the config file
except IOError:
if filename is None:
raise IOError('Error path: {0}.{1}'.format(k, sk))
npat = os.path.join(filename, data_dict[k][sk])
self.set_option(k, sk, os.path.normpath(npat))
except ValueError:
pass | [
"def",
"set_options_from_dict",
"(",
"self",
",",
"data_dict",
",",
"filename",
"=",
"None",
")",
":",
"if",
"filename",
"is",
"not",
"None",
":",
"filename",
"=",
"os",
".",
"path",
".",
"dirname",
"(",
"filename",
")",
"for",
"k",
"in",
"data_dict",
":",
"if",
"not",
"isinstance",
"(",
"data_dict",
"[",
"k",
"]",
",",
"dict",
")",
":",
"raise",
"ValueError",
"(",
"\"The input data has to be a dict of dict\"",
")",
"for",
"sk",
"in",
"data_dict",
"[",
"k",
"]",
":",
"if",
"self",
".",
"gc",
"[",
"(",
"self",
".",
"gc",
"[",
"\"k1\"",
"]",
"==",
"k",
")",
"&",
"(",
"self",
".",
"gc",
"[",
"\"k2\"",
"]",
"==",
"sk",
")",
"]",
".",
"shape",
"[",
"0",
"]",
"==",
"0",
":",
"continue",
"if",
"isinstance",
"(",
"data_dict",
"[",
"k",
"]",
"[",
"sk",
"]",
",",
"six",
".",
"string_types",
")",
":",
"data_dict",
"[",
"k",
"]",
"[",
"sk",
"]",
"=",
"str",
"(",
"data_dict",
"[",
"k",
"]",
"[",
"sk",
"]",
")",
"_type",
"=",
"self",
".",
"gc",
"[",
"(",
"self",
".",
"gc",
"[",
"\"k1\"",
"]",
"==",
"k",
")",
"&",
"(",
"self",
".",
"gc",
"[",
"\"k2\"",
"]",
"==",
"sk",
")",
"]",
"[",
"[",
"\"type\"",
"]",
"]",
".",
"values",
"[",
"0",
"]",
"data_dict",
"[",
"k",
"]",
"[",
"sk",
"]",
"=",
"ev",
".",
"cast",
"(",
"data_dict",
"[",
"k",
"]",
"[",
"sk",
"]",
",",
"_type",
")",
"if",
"self",
".",
"get_option",
"(",
"k",
",",
"sk",
",",
"True",
")",
"!=",
"data_dict",
"[",
"k",
"]",
"[",
"sk",
"]",
":",
"try",
":",
"self",
".",
"set_option",
"(",
"k",
",",
"sk",
",",
"data_dict",
"[",
"k",
"]",
"[",
"sk",
"]",
")",
"# Provided paths do not work: try add them relative",
"# to the config file",
"except",
"IOError",
":",
"if",
"filename",
"is",
"None",
":",
"raise",
"IOError",
"(",
"'Error path: {0}.{1}'",
".",
"format",
"(",
"k",
",",
"sk",
")",
")",
"npat",
"=",
"os",
".",
"path",
".",
"join",
"(",
"filename",
",",
"data_dict",
"[",
"k",
"]",
"[",
"sk",
"]",
")",
"self",
".",
"set_option",
"(",
"k",
",",
"sk",
",",
"os",
".",
"path",
".",
"normpath",
"(",
"npat",
")",
")",
"except",
"ValueError",
":",
"pass"
]
| Load options from a dictionary.
:param dict data_dict: Dictionary with the options to load.
:param str filename: If provided, assume that non-absolute
paths provided are in reference to the file. | [
"Load",
"options",
"from",
"a",
"dictionary",
"."
]
| 9b34cefcbaf9a326e3f3cd517896c2933cf61a3b | https://github.com/jaumebonet/libconfig/blob/9b34cefcbaf9a326e3f3cd517896c2933cf61a3b/libconfig/config.py#L386-L418 | train |
jaumebonet/libconfig | libconfig/config.py | Config.write_options_to_file | def write_options_to_file(self, filename, file_format='yaml'):
"""Write options to file.
This is a wrapper over :func:`.write_options_to_JSON` and
:func:`.write_options_to_YAML`.
:param str filename: Target file to write the options.
:param str file_format: File format (``yaml`` or ``json``).
:raises:
:ValueError: If an unknown ``format`` is requested.
"""
if file_format.lower() == 'yaml':
self.write_options_to_YAML(filename)
elif file_format.lower() == 'json':
self.write_options_to_JSON(filename)
else:
raise ValueError('Unknown format {}'.format(file_format)) | python | def write_options_to_file(self, filename, file_format='yaml'):
"""Write options to file.
This is a wrapper over :func:`.write_options_to_JSON` and
:func:`.write_options_to_YAML`.
:param str filename: Target file to write the options.
:param str file_format: File format (``yaml`` or ``json``).
:raises:
:ValueError: If an unknown ``format`` is requested.
"""
if file_format.lower() == 'yaml':
self.write_options_to_YAML(filename)
elif file_format.lower() == 'json':
self.write_options_to_JSON(filename)
else:
raise ValueError('Unknown format {}'.format(file_format)) | [
"def",
"write_options_to_file",
"(",
"self",
",",
"filename",
",",
"file_format",
"=",
"'yaml'",
")",
":",
"if",
"file_format",
".",
"lower",
"(",
")",
"==",
"'yaml'",
":",
"self",
".",
"write_options_to_YAML",
"(",
"filename",
")",
"elif",
"file_format",
".",
"lower",
"(",
")",
"==",
"'json'",
":",
"self",
".",
"write_options_to_JSON",
"(",
"filename",
")",
"else",
":",
"raise",
"ValueError",
"(",
"'Unknown format {}'",
".",
"format",
"(",
"file_format",
")",
")"
]
| Write options to file.
This is a wrapper over :func:`.write_options_to_JSON` and
:func:`.write_options_to_YAML`.
:param str filename: Target file to write the options.
:param str file_format: File format (``yaml`` or ``json``).
:raises:
:ValueError: If an unknown ``format`` is requested. | [
"Write",
"options",
"to",
"file",
"."
]
| 9b34cefcbaf9a326e3f3cd517896c2933cf61a3b | https://github.com/jaumebonet/libconfig/blob/9b34cefcbaf9a326e3f3cd517896c2933cf61a3b/libconfig/config.py#L420-L437 | train |
jaumebonet/libconfig | libconfig/config.py | Config.write_options_to_YAML | def write_options_to_YAML(self, filename):
"""Writes the options in YAML format to a file.
:param str filename: Target file to write the options.
"""
fd = open(filename, "w")
yaml.dump(_options_to_dict(self.gc), fd, default_flow_style=False)
fd.close() | python | def write_options_to_YAML(self, filename):
"""Writes the options in YAML format to a file.
:param str filename: Target file to write the options.
"""
fd = open(filename, "w")
yaml.dump(_options_to_dict(self.gc), fd, default_flow_style=False)
fd.close() | [
"def",
"write_options_to_YAML",
"(",
"self",
",",
"filename",
")",
":",
"fd",
"=",
"open",
"(",
"filename",
",",
"\"w\"",
")",
"yaml",
".",
"dump",
"(",
"_options_to_dict",
"(",
"self",
".",
"gc",
")",
",",
"fd",
",",
"default_flow_style",
"=",
"False",
")",
"fd",
".",
"close",
"(",
")"
]
| Writes the options in YAML format to a file.
:param str filename: Target file to write the options. | [
"Writes",
"the",
"options",
"in",
"YAML",
"format",
"to",
"a",
"file",
"."
]
| 9b34cefcbaf9a326e3f3cd517896c2933cf61a3b | https://github.com/jaumebonet/libconfig/blob/9b34cefcbaf9a326e3f3cd517896c2933cf61a3b/libconfig/config.py#L439-L446 | train |
jaumebonet/libconfig | libconfig/config.py | Config.write_options_to_JSON | def write_options_to_JSON(self, filename):
"""Writes the options in JSON format to a file.
:param str filename: Target file to write the options.
"""
fd = open(filename, "w")
fd.write(json.dumps(_options_to_dict(self.gc), indent=2,
separators=(',', ': ')))
fd.close() | python | def write_options_to_JSON(self, filename):
"""Writes the options in JSON format to a file.
:param str filename: Target file to write the options.
"""
fd = open(filename, "w")
fd.write(json.dumps(_options_to_dict(self.gc), indent=2,
separators=(',', ': ')))
fd.close() | [
"def",
"write_options_to_JSON",
"(",
"self",
",",
"filename",
")",
":",
"fd",
"=",
"open",
"(",
"filename",
",",
"\"w\"",
")",
"fd",
".",
"write",
"(",
"json",
".",
"dumps",
"(",
"_options_to_dict",
"(",
"self",
".",
"gc",
")",
",",
"indent",
"=",
"2",
",",
"separators",
"=",
"(",
"','",
",",
"': '",
")",
")",
")",
"fd",
".",
"close",
"(",
")"
]
| Writes the options in JSON format to a file.
:param str filename: Target file to write the options. | [
"Writes",
"the",
"options",
"in",
"JSON",
"format",
"to",
"a",
"file",
"."
]
| 9b34cefcbaf9a326e3f3cd517896c2933cf61a3b | https://github.com/jaumebonet/libconfig/blob/9b34cefcbaf9a326e3f3cd517896c2933cf61a3b/libconfig/config.py#L448-L456 | train |
jaumebonet/libconfig | libconfig/config.py | Config.document_options | def document_options(self):
"""Generates a docstring table to add to the library documentation.
:return: :class:`str`
"""
k1 = max([len(_) for _ in self.gc['k1']]) + 4
k1 = max([k1, len('Option Class')])
k2 = max([len(_) for _ in self.gc['k2']]) + 4
k2 = max([k2, len('Option ID')])
separators = " ".join(["".join(["=", ] * k1),
"".join(["=", ] * k2),
"".join(["=", ] * 11)])
line = ("{0:>"+str(k1)+"} {1:>"+str(k2)+"} {2}")
data = []
data.append(separators)
data.append(line.format('Option Class', 'Option ID', 'Description'))
data.append(separators)
for _, row in self.gc.iterrows():
data.append(line.format("**" + row['k1'] + "**",
"**" + row['k2'] + "**",
row['description']))
data.append(separators)
return "\n".join(data) | python | def document_options(self):
"""Generates a docstring table to add to the library documentation.
:return: :class:`str`
"""
k1 = max([len(_) for _ in self.gc['k1']]) + 4
k1 = max([k1, len('Option Class')])
k2 = max([len(_) for _ in self.gc['k2']]) + 4
k2 = max([k2, len('Option ID')])
separators = " ".join(["".join(["=", ] * k1),
"".join(["=", ] * k2),
"".join(["=", ] * 11)])
line = ("{0:>"+str(k1)+"} {1:>"+str(k2)+"} {2}")
data = []
data.append(separators)
data.append(line.format('Option Class', 'Option ID', 'Description'))
data.append(separators)
for _, row in self.gc.iterrows():
data.append(line.format("**" + row['k1'] + "**",
"**" + row['k2'] + "**",
row['description']))
data.append(separators)
return "\n".join(data) | [
"def",
"document_options",
"(",
"self",
")",
":",
"k1",
"=",
"max",
"(",
"[",
"len",
"(",
"_",
")",
"for",
"_",
"in",
"self",
".",
"gc",
"[",
"'k1'",
"]",
"]",
")",
"+",
"4",
"k1",
"=",
"max",
"(",
"[",
"k1",
",",
"len",
"(",
"'Option Class'",
")",
"]",
")",
"k2",
"=",
"max",
"(",
"[",
"len",
"(",
"_",
")",
"for",
"_",
"in",
"self",
".",
"gc",
"[",
"'k2'",
"]",
"]",
")",
"+",
"4",
"k2",
"=",
"max",
"(",
"[",
"k2",
",",
"len",
"(",
"'Option ID'",
")",
"]",
")",
"separators",
"=",
"\" \"",
".",
"join",
"(",
"[",
"\"\"",
".",
"join",
"(",
"[",
"\"=\"",
",",
"]",
"*",
"k1",
")",
",",
"\"\"",
".",
"join",
"(",
"[",
"\"=\"",
",",
"]",
"*",
"k2",
")",
",",
"\"\"",
".",
"join",
"(",
"[",
"\"=\"",
",",
"]",
"*",
"11",
")",
"]",
")",
"line",
"=",
"(",
"\"{0:>\"",
"+",
"str",
"(",
"k1",
")",
"+",
"\"} {1:>\"",
"+",
"str",
"(",
"k2",
")",
"+",
"\"} {2}\"",
")",
"data",
"=",
"[",
"]",
"data",
".",
"append",
"(",
"separators",
")",
"data",
".",
"append",
"(",
"line",
".",
"format",
"(",
"'Option Class'",
",",
"'Option ID'",
",",
"'Description'",
")",
")",
"data",
".",
"append",
"(",
"separators",
")",
"for",
"_",
",",
"row",
"in",
"self",
".",
"gc",
".",
"iterrows",
"(",
")",
":",
"data",
".",
"append",
"(",
"line",
".",
"format",
"(",
"\"**\"",
"+",
"row",
"[",
"'k1'",
"]",
"+",
"\"**\"",
",",
"\"**\"",
"+",
"row",
"[",
"'k2'",
"]",
"+",
"\"**\"",
",",
"row",
"[",
"'description'",
"]",
")",
")",
"data",
".",
"append",
"(",
"separators",
")",
"return",
"\"\\n\"",
".",
"join",
"(",
"data",
")"
]
| Generates a docstring table to add to the library documentation.
:return: :class:`str` | [
"Generates",
"a",
"docstring",
"table",
"to",
"add",
"to",
"the",
"library",
"documentation",
"."
]
| 9b34cefcbaf9a326e3f3cd517896c2933cf61a3b | https://github.com/jaumebonet/libconfig/blob/9b34cefcbaf9a326e3f3cd517896c2933cf61a3b/libconfig/config.py#L458-L482 | train |
jaumebonet/libconfig | libconfig/config.py | Config.get_local_config_file | def get_local_config_file(cls, filename):
"""Find local file to setup default values.
There is a pre-fixed logic on how the search of the configuration
file is performed. If the highes priority configuration file is found,
there is no need to search for the next. From highest to lowest
priority:
1. **Local:** Configuration file found in the current working
directory.
2. **Project:** Configuration file found in the root of the current
working ``git`` repository.
3. **User:** Configuration file found in the user's ``$HOME``.
:param str filename: Raw name of the configuration file.
:return: Union[:class:`.str`, :data:`None`] - Configuration file with
the highest priority, :data:`None` if no config file is found.
"""
if os.path.isfile(filename):
# Local has priority
return filename
else:
try:
# Project. If not in a git repo, this will not exist.
config_repo = _get_repo()
if len(config_repo) == 0:
raise Exception()
config_repo = os.path.join(config_repo, filename)
if os.path.isfile(config_repo):
return config_repo
else:
raise Exception()
except Exception:
home = os.getenv("HOME", os.path.expanduser("~"))
config_home = os.path.join(home, filename)
if os.path.isfile(config_home):
return config_home
return None | python | def get_local_config_file(cls, filename):
"""Find local file to setup default values.
There is a pre-fixed logic on how the search of the configuration
file is performed. If the highes priority configuration file is found,
there is no need to search for the next. From highest to lowest
priority:
1. **Local:** Configuration file found in the current working
directory.
2. **Project:** Configuration file found in the root of the current
working ``git`` repository.
3. **User:** Configuration file found in the user's ``$HOME``.
:param str filename: Raw name of the configuration file.
:return: Union[:class:`.str`, :data:`None`] - Configuration file with
the highest priority, :data:`None` if no config file is found.
"""
if os.path.isfile(filename):
# Local has priority
return filename
else:
try:
# Project. If not in a git repo, this will not exist.
config_repo = _get_repo()
if len(config_repo) == 0:
raise Exception()
config_repo = os.path.join(config_repo, filename)
if os.path.isfile(config_repo):
return config_repo
else:
raise Exception()
except Exception:
home = os.getenv("HOME", os.path.expanduser("~"))
config_home = os.path.join(home, filename)
if os.path.isfile(config_home):
return config_home
return None | [
"def",
"get_local_config_file",
"(",
"cls",
",",
"filename",
")",
":",
"if",
"os",
".",
"path",
".",
"isfile",
"(",
"filename",
")",
":",
"# Local has priority",
"return",
"filename",
"else",
":",
"try",
":",
"# Project. If not in a git repo, this will not exist.",
"config_repo",
"=",
"_get_repo",
"(",
")",
"if",
"len",
"(",
"config_repo",
")",
"==",
"0",
":",
"raise",
"Exception",
"(",
")",
"config_repo",
"=",
"os",
".",
"path",
".",
"join",
"(",
"config_repo",
",",
"filename",
")",
"if",
"os",
".",
"path",
".",
"isfile",
"(",
"config_repo",
")",
":",
"return",
"config_repo",
"else",
":",
"raise",
"Exception",
"(",
")",
"except",
"Exception",
":",
"home",
"=",
"os",
".",
"getenv",
"(",
"\"HOME\"",
",",
"os",
".",
"path",
".",
"expanduser",
"(",
"\"~\"",
")",
")",
"config_home",
"=",
"os",
".",
"path",
".",
"join",
"(",
"home",
",",
"filename",
")",
"if",
"os",
".",
"path",
".",
"isfile",
"(",
"config_home",
")",
":",
"return",
"config_home",
"return",
"None"
]
| Find local file to setup default values.
There is a pre-fixed logic on how the search of the configuration
file is performed. If the highes priority configuration file is found,
there is no need to search for the next. From highest to lowest
priority:
1. **Local:** Configuration file found in the current working
directory.
2. **Project:** Configuration file found in the root of the current
working ``git`` repository.
3. **User:** Configuration file found in the user's ``$HOME``.
:param str filename: Raw name of the configuration file.
:return: Union[:class:`.str`, :data:`None`] - Configuration file with
the highest priority, :data:`None` if no config file is found. | [
"Find",
"local",
"file",
"to",
"setup",
"default",
"values",
"."
]
| 9b34cefcbaf9a326e3f3cd517896c2933cf61a3b | https://github.com/jaumebonet/libconfig/blob/9b34cefcbaf9a326e3f3cd517896c2933cf61a3b/libconfig/config.py#L485-L523 | train |
tjcsl/cslbot | cslbot/commands/man.py | cmd | def cmd(send, msg, args):
"""Gets a man page.
Syntax: {command} [section] <command>
"""
parser = arguments.ArgParser(args['config'])
parser.add_argument('section', nargs='?')
parser.add_argument('command')
try:
cmdargs = parser.parse_args(msg)
except arguments.ArgumentException as e:
send(str(e))
return
if cmdargs.section:
html = get('http://linux.die.net/man/%s/%s' % (cmdargs.section, cmdargs.command))
short = fromstring(html.text).find('.//meta[@name="description"]')
if short is not None:
short = short.get('content')
send("%s -- http://linux.die.net/man/%s/%s" % (short, cmdargs.section, cmdargs.command))
else:
send("No manual entry for %s in section %s" % (cmdargs.command, cmdargs.section))
else:
for section in range(0, 8):
html = get('http://linux.die.net/man/%d/%s' % (section, cmdargs.command))
if html.status_code == 200:
short = fromstring(html.text).find('.//meta[@name="description"]')
if short is not None:
short = short.get('content')
send("%s -- http://linux.die.net/man/%d/%s" % (short, section, cmdargs.command))
return
send("No manual entry for %s" % cmdargs.command) | python | def cmd(send, msg, args):
"""Gets a man page.
Syntax: {command} [section] <command>
"""
parser = arguments.ArgParser(args['config'])
parser.add_argument('section', nargs='?')
parser.add_argument('command')
try:
cmdargs = parser.parse_args(msg)
except arguments.ArgumentException as e:
send(str(e))
return
if cmdargs.section:
html = get('http://linux.die.net/man/%s/%s' % (cmdargs.section, cmdargs.command))
short = fromstring(html.text).find('.//meta[@name="description"]')
if short is not None:
short = short.get('content')
send("%s -- http://linux.die.net/man/%s/%s" % (short, cmdargs.section, cmdargs.command))
else:
send("No manual entry for %s in section %s" % (cmdargs.command, cmdargs.section))
else:
for section in range(0, 8):
html = get('http://linux.die.net/man/%d/%s' % (section, cmdargs.command))
if html.status_code == 200:
short = fromstring(html.text).find('.//meta[@name="description"]')
if short is not None:
short = short.get('content')
send("%s -- http://linux.die.net/man/%d/%s" % (short, section, cmdargs.command))
return
send("No manual entry for %s" % cmdargs.command) | [
"def",
"cmd",
"(",
"send",
",",
"msg",
",",
"args",
")",
":",
"parser",
"=",
"arguments",
".",
"ArgParser",
"(",
"args",
"[",
"'config'",
"]",
")",
"parser",
".",
"add_argument",
"(",
"'section'",
",",
"nargs",
"=",
"'?'",
")",
"parser",
".",
"add_argument",
"(",
"'command'",
")",
"try",
":",
"cmdargs",
"=",
"parser",
".",
"parse_args",
"(",
"msg",
")",
"except",
"arguments",
".",
"ArgumentException",
"as",
"e",
":",
"send",
"(",
"str",
"(",
"e",
")",
")",
"return",
"if",
"cmdargs",
".",
"section",
":",
"html",
"=",
"get",
"(",
"'http://linux.die.net/man/%s/%s'",
"%",
"(",
"cmdargs",
".",
"section",
",",
"cmdargs",
".",
"command",
")",
")",
"short",
"=",
"fromstring",
"(",
"html",
".",
"text",
")",
".",
"find",
"(",
"'.//meta[@name=\"description\"]'",
")",
"if",
"short",
"is",
"not",
"None",
":",
"short",
"=",
"short",
".",
"get",
"(",
"'content'",
")",
"send",
"(",
"\"%s -- http://linux.die.net/man/%s/%s\"",
"%",
"(",
"short",
",",
"cmdargs",
".",
"section",
",",
"cmdargs",
".",
"command",
")",
")",
"else",
":",
"send",
"(",
"\"No manual entry for %s in section %s\"",
"%",
"(",
"cmdargs",
".",
"command",
",",
"cmdargs",
".",
"section",
")",
")",
"else",
":",
"for",
"section",
"in",
"range",
"(",
"0",
",",
"8",
")",
":",
"html",
"=",
"get",
"(",
"'http://linux.die.net/man/%d/%s'",
"%",
"(",
"section",
",",
"cmdargs",
".",
"command",
")",
")",
"if",
"html",
".",
"status_code",
"==",
"200",
":",
"short",
"=",
"fromstring",
"(",
"html",
".",
"text",
")",
".",
"find",
"(",
"'.//meta[@name=\"description\"]'",
")",
"if",
"short",
"is",
"not",
"None",
":",
"short",
"=",
"short",
".",
"get",
"(",
"'content'",
")",
"send",
"(",
"\"%s -- http://linux.die.net/man/%d/%s\"",
"%",
"(",
"short",
",",
"section",
",",
"cmdargs",
".",
"command",
")",
")",
"return",
"send",
"(",
"\"No manual entry for %s\"",
"%",
"cmdargs",
".",
"command",
")"
]
| Gets a man page.
Syntax: {command} [section] <command> | [
"Gets",
"a",
"man",
"page",
"."
]
| aebe07be47141f61d7c180706bddfb707f19b2b5 | https://github.com/tjcsl/cslbot/blob/aebe07be47141f61d7c180706bddfb707f19b2b5/cslbot/commands/man.py#L27-L58 | train |
tjcsl/cslbot | cslbot/commands/urban.py | cmd | def cmd(send, msg, args):
"""Gets a definition from urban dictionary.
Syntax: {command} <[#<num>] <term>|--blacklist (word)|--unblacklist (word)>
"""
key = args['config']['api']['bitlykey']
parser = arguments.ArgParser(args['config'])
parser.add_argument('--blacklist')
parser.add_argument('--unblacklist')
try:
cmdargs, msg = parser.parse_known_args(msg)
msg = ' '.join(msg)
except arguments.ArgumentException as e:
send(str(e))
return
if cmdargs.blacklist:
if args['is_admin'](args['nick']):
send(blacklist_word(args['db'], cmdargs.blacklist))
else:
send("Blacklisting is admin-only")
elif cmdargs.unblacklist:
if args['is_admin'](args['nick']):
send(unblacklist_word(args['db'], cmdargs.unblacklist))
else:
send("Unblacklisting is admin-only")
else:
defn, url = get_urban(msg, args['db'], key)
send(defn)
if url:
send("See full definition at %s" % url) | python | def cmd(send, msg, args):
"""Gets a definition from urban dictionary.
Syntax: {command} <[#<num>] <term>|--blacklist (word)|--unblacklist (word)>
"""
key = args['config']['api']['bitlykey']
parser = arguments.ArgParser(args['config'])
parser.add_argument('--blacklist')
parser.add_argument('--unblacklist')
try:
cmdargs, msg = parser.parse_known_args(msg)
msg = ' '.join(msg)
except arguments.ArgumentException as e:
send(str(e))
return
if cmdargs.blacklist:
if args['is_admin'](args['nick']):
send(blacklist_word(args['db'], cmdargs.blacklist))
else:
send("Blacklisting is admin-only")
elif cmdargs.unblacklist:
if args['is_admin'](args['nick']):
send(unblacklist_word(args['db'], cmdargs.unblacklist))
else:
send("Unblacklisting is admin-only")
else:
defn, url = get_urban(msg, args['db'], key)
send(defn)
if url:
send("See full definition at %s" % url) | [
"def",
"cmd",
"(",
"send",
",",
"msg",
",",
"args",
")",
":",
"key",
"=",
"args",
"[",
"'config'",
"]",
"[",
"'api'",
"]",
"[",
"'bitlykey'",
"]",
"parser",
"=",
"arguments",
".",
"ArgParser",
"(",
"args",
"[",
"'config'",
"]",
")",
"parser",
".",
"add_argument",
"(",
"'--blacklist'",
")",
"parser",
".",
"add_argument",
"(",
"'--unblacklist'",
")",
"try",
":",
"cmdargs",
",",
"msg",
"=",
"parser",
".",
"parse_known_args",
"(",
"msg",
")",
"msg",
"=",
"' '",
".",
"join",
"(",
"msg",
")",
"except",
"arguments",
".",
"ArgumentException",
"as",
"e",
":",
"send",
"(",
"str",
"(",
"e",
")",
")",
"return",
"if",
"cmdargs",
".",
"blacklist",
":",
"if",
"args",
"[",
"'is_admin'",
"]",
"(",
"args",
"[",
"'nick'",
"]",
")",
":",
"send",
"(",
"blacklist_word",
"(",
"args",
"[",
"'db'",
"]",
",",
"cmdargs",
".",
"blacklist",
")",
")",
"else",
":",
"send",
"(",
"\"Blacklisting is admin-only\"",
")",
"elif",
"cmdargs",
".",
"unblacklist",
":",
"if",
"args",
"[",
"'is_admin'",
"]",
"(",
"args",
"[",
"'nick'",
"]",
")",
":",
"send",
"(",
"unblacklist_word",
"(",
"args",
"[",
"'db'",
"]",
",",
"cmdargs",
".",
"unblacklist",
")",
")",
"else",
":",
"send",
"(",
"\"Unblacklisting is admin-only\"",
")",
"else",
":",
"defn",
",",
"url",
"=",
"get_urban",
"(",
"msg",
",",
"args",
"[",
"'db'",
"]",
",",
"key",
")",
"send",
"(",
"defn",
")",
"if",
"url",
":",
"send",
"(",
"\"See full definition at %s\"",
"%",
"url",
")"
]
| Gets a definition from urban dictionary.
Syntax: {command} <[#<num>] <term>|--blacklist (word)|--unblacklist (word)> | [
"Gets",
"a",
"definition",
"from",
"urban",
"dictionary",
"."
]
| aebe07be47141f61d7c180706bddfb707f19b2b5 | https://github.com/tjcsl/cslbot/blob/aebe07be47141f61d7c180706bddfb707f19b2b5/cslbot/commands/urban.py#L40-L71 | train |
jakebasile/reap | reap/api/admin.py | Harvest.people | def people(self):
'''Generates a list of all People.'''
people_response = self.get_request('people/')
return [Person(self, pjson['user']) for pjson in people_response] | python | def people(self):
'''Generates a list of all People.'''
people_response = self.get_request('people/')
return [Person(self, pjson['user']) for pjson in people_response] | [
"def",
"people",
"(",
"self",
")",
":",
"people_response",
"=",
"self",
".",
"get_request",
"(",
"'people/'",
")",
"return",
"[",
"Person",
"(",
"self",
",",
"pjson",
"[",
"'user'",
"]",
")",
"for",
"pjson",
"in",
"people_response",
"]"
]
| Generates a list of all People. | [
"Generates",
"a",
"list",
"of",
"all",
"People",
"."
]
| c90c033c5388f5380155001957b26b1a930311f0 | https://github.com/jakebasile/reap/blob/c90c033c5388f5380155001957b26b1a930311f0/reap/api/admin.py#L38-L41 | train |
jakebasile/reap | reap/api/admin.py | Harvest.tasks | def tasks(self):
'''Generates a list of all Tasks.'''
tasks_response = self.get_request('tasks/')
return [Task(self, tjson['task']) for tjson in tasks_response] | python | def tasks(self):
'''Generates a list of all Tasks.'''
tasks_response = self.get_request('tasks/')
return [Task(self, tjson['task']) for tjson in tasks_response] | [
"def",
"tasks",
"(",
"self",
")",
":",
"tasks_response",
"=",
"self",
".",
"get_request",
"(",
"'tasks/'",
")",
"return",
"[",
"Task",
"(",
"self",
",",
"tjson",
"[",
"'task'",
"]",
")",
"for",
"tjson",
"in",
"tasks_response",
"]"
]
| Generates a list of all Tasks. | [
"Generates",
"a",
"list",
"of",
"all",
"Tasks",
"."
]
| c90c033c5388f5380155001957b26b1a930311f0 | https://github.com/jakebasile/reap/blob/c90c033c5388f5380155001957b26b1a930311f0/reap/api/admin.py#L48-L51 | train |
jakebasile/reap | reap/api/admin.py | Harvest.clients | def clients(self):
'''Generates a list of all Clients.'''
clients_response = self.get_request('clients/')
return [Client(self, cjson['client']) for cjson in clients_response] | python | def clients(self):
'''Generates a list of all Clients.'''
clients_response = self.get_request('clients/')
return [Client(self, cjson['client']) for cjson in clients_response] | [
"def",
"clients",
"(",
"self",
")",
":",
"clients_response",
"=",
"self",
".",
"get_request",
"(",
"'clients/'",
")",
"return",
"[",
"Client",
"(",
"self",
",",
"cjson",
"[",
"'client'",
"]",
")",
"for",
"cjson",
"in",
"clients_response",
"]"
]
| Generates a list of all Clients. | [
"Generates",
"a",
"list",
"of",
"all",
"Clients",
"."
]
| c90c033c5388f5380155001957b26b1a930311f0 | https://github.com/jakebasile/reap/blob/c90c033c5388f5380155001957b26b1a930311f0/reap/api/admin.py#L53-L56 | train |
jakebasile/reap | reap/api/admin.py | Harvest.get_client | def get_client(self, client_id):
'''Gets a single client by id.'''
client_response = self.get_request('clients/%s' % client_id)
return Client(self, client_response['client']) | python | def get_client(self, client_id):
'''Gets a single client by id.'''
client_response = self.get_request('clients/%s' % client_id)
return Client(self, client_response['client']) | [
"def",
"get_client",
"(",
"self",
",",
"client_id",
")",
":",
"client_response",
"=",
"self",
".",
"get_request",
"(",
"'clients/%s'",
"%",
"client_id",
")",
"return",
"Client",
"(",
"self",
",",
"client_response",
"[",
"'client'",
"]",
")"
]
| Gets a single client by id. | [
"Gets",
"a",
"single",
"client",
"by",
"id",
"."
]
| c90c033c5388f5380155001957b26b1a930311f0 | https://github.com/jakebasile/reap/blob/c90c033c5388f5380155001957b26b1a930311f0/reap/api/admin.py#L58-L61 | train |
jakebasile/reap | reap/api/admin.py | Harvest.get_project | def get_project(self, project_id):
'''Gets a single project by id.'''
project_response = self.get_request('projects/%s' % project_id)
return Project(self, project_response['project']) | python | def get_project(self, project_id):
'''Gets a single project by id.'''
project_response = self.get_request('projects/%s' % project_id)
return Project(self, project_response['project']) | [
"def",
"get_project",
"(",
"self",
",",
"project_id",
")",
":",
"project_response",
"=",
"self",
".",
"get_request",
"(",
"'projects/%s'",
"%",
"project_id",
")",
"return",
"Project",
"(",
"self",
",",
"project_response",
"[",
"'project'",
"]",
")"
]
| Gets a single project by id. | [
"Gets",
"a",
"single",
"project",
"by",
"id",
"."
]
| c90c033c5388f5380155001957b26b1a930311f0 | https://github.com/jakebasile/reap/blob/c90c033c5388f5380155001957b26b1a930311f0/reap/api/admin.py#L63-L66 | train |
jakebasile/reap | reap/api/admin.py | Harvest.create_person | def create_person(self, first_name, last_name, email, department = None,
default_rate = None, admin = False, contractor = False):
'''Creates a Person with the given information.'''
person = {'user':{
'first_name': first_name,
'last_name': last_name,
'email': email,
'department': department,
'default_hourly_rate': default_rate,
'is_admin': admin,
'is_contractor': contractor,
}}
response = self.post_request('people/', person, follow = True)
if response:
return Person(self, response['user']) | python | def create_person(self, first_name, last_name, email, department = None,
default_rate = None, admin = False, contractor = False):
'''Creates a Person with the given information.'''
person = {'user':{
'first_name': first_name,
'last_name': last_name,
'email': email,
'department': department,
'default_hourly_rate': default_rate,
'is_admin': admin,
'is_contractor': contractor,
}}
response = self.post_request('people/', person, follow = True)
if response:
return Person(self, response['user']) | [
"def",
"create_person",
"(",
"self",
",",
"first_name",
",",
"last_name",
",",
"email",
",",
"department",
"=",
"None",
",",
"default_rate",
"=",
"None",
",",
"admin",
"=",
"False",
",",
"contractor",
"=",
"False",
")",
":",
"person",
"=",
"{",
"'user'",
":",
"{",
"'first_name'",
":",
"first_name",
",",
"'last_name'",
":",
"last_name",
",",
"'email'",
":",
"email",
",",
"'department'",
":",
"department",
",",
"'default_hourly_rate'",
":",
"default_rate",
",",
"'is_admin'",
":",
"admin",
",",
"'is_contractor'",
":",
"contractor",
",",
"}",
"}",
"response",
"=",
"self",
".",
"post_request",
"(",
"'people/'",
",",
"person",
",",
"follow",
"=",
"True",
")",
"if",
"response",
":",
"return",
"Person",
"(",
"self",
",",
"response",
"[",
"'user'",
"]",
")"
]
| Creates a Person with the given information. | [
"Creates",
"a",
"Person",
"with",
"the",
"given",
"information",
"."
]
| c90c033c5388f5380155001957b26b1a930311f0 | https://github.com/jakebasile/reap/blob/c90c033c5388f5380155001957b26b1a930311f0/reap/api/admin.py#L68-L82 | train |
jakebasile/reap | reap/api/admin.py | Harvest.create_project | def create_project(self, name, client_id, budget = None, budget_by =
'none', notes = None, billable = True):
'''Creates a Project with the given information.'''
project = {'project':{
'name': name,
'client_id': client_id,
'budget_by': budget_by,
'budget': budget,
'notes': notes,
'billable': billable,
}}
response = self.post_request('projects/', project, follow = True)
if response:
return Project(self, response['project']) | python | def create_project(self, name, client_id, budget = None, budget_by =
'none', notes = None, billable = True):
'''Creates a Project with the given information.'''
project = {'project':{
'name': name,
'client_id': client_id,
'budget_by': budget_by,
'budget': budget,
'notes': notes,
'billable': billable,
}}
response = self.post_request('projects/', project, follow = True)
if response:
return Project(self, response['project']) | [
"def",
"create_project",
"(",
"self",
",",
"name",
",",
"client_id",
",",
"budget",
"=",
"None",
",",
"budget_by",
"=",
"'none'",
",",
"notes",
"=",
"None",
",",
"billable",
"=",
"True",
")",
":",
"project",
"=",
"{",
"'project'",
":",
"{",
"'name'",
":",
"name",
",",
"'client_id'",
":",
"client_id",
",",
"'budget_by'",
":",
"budget_by",
",",
"'budget'",
":",
"budget",
",",
"'notes'",
":",
"notes",
",",
"'billable'",
":",
"billable",
",",
"}",
"}",
"response",
"=",
"self",
".",
"post_request",
"(",
"'projects/'",
",",
"project",
",",
"follow",
"=",
"True",
")",
"if",
"response",
":",
"return",
"Project",
"(",
"self",
",",
"response",
"[",
"'project'",
"]",
")"
]
| Creates a Project with the given information. | [
"Creates",
"a",
"Project",
"with",
"the",
"given",
"information",
"."
]
| c90c033c5388f5380155001957b26b1a930311f0 | https://github.com/jakebasile/reap/blob/c90c033c5388f5380155001957b26b1a930311f0/reap/api/admin.py#L84-L97 | train |
jakebasile/reap | reap/api/admin.py | Harvest.create_client | def create_client(self, name):
'''Creates a Client with the given information.'''
client = {'client':{
'name': name,
}}
response = self.post_request('clients/', client, follow = True)
if response:
return Client(self, response['client']) | python | def create_client(self, name):
'''Creates a Client with the given information.'''
client = {'client':{
'name': name,
}}
response = self.post_request('clients/', client, follow = True)
if response:
return Client(self, response['client']) | [
"def",
"create_client",
"(",
"self",
",",
"name",
")",
":",
"client",
"=",
"{",
"'client'",
":",
"{",
"'name'",
":",
"name",
",",
"}",
"}",
"response",
"=",
"self",
".",
"post_request",
"(",
"'clients/'",
",",
"client",
",",
"follow",
"=",
"True",
")",
"if",
"response",
":",
"return",
"Client",
"(",
"self",
",",
"response",
"[",
"'client'",
"]",
")"
]
| Creates a Client with the given information. | [
"Creates",
"a",
"Client",
"with",
"the",
"given",
"information",
"."
]
| c90c033c5388f5380155001957b26b1a930311f0 | https://github.com/jakebasile/reap/blob/c90c033c5388f5380155001957b26b1a930311f0/reap/api/admin.py#L99-L106 | train |
jakebasile/reap | reap/api/admin.py | Person.delete | def delete(self):
'''Deletes the person immediately.'''
response = self.hv.delete_request('people/' + str(self.id))
return response | python | def delete(self):
'''Deletes the person immediately.'''
response = self.hv.delete_request('people/' + str(self.id))
return response | [
"def",
"delete",
"(",
"self",
")",
":",
"response",
"=",
"self",
".",
"hv",
".",
"delete_request",
"(",
"'people/'",
"+",
"str",
"(",
"self",
".",
"id",
")",
")",
"return",
"response"
]
| Deletes the person immediately. | [
"Deletes",
"the",
"person",
"immediately",
"."
]
| c90c033c5388f5380155001957b26b1a930311f0 | https://github.com/jakebasile/reap/blob/c90c033c5388f5380155001957b26b1a930311f0/reap/api/admin.py#L125-L128 | train |
jakebasile/reap | reap/api/admin.py | Project.task_assignments | def task_assignments(self):
'''Retrieves all tasks currently assigned to this project.'''
url = str.format(
'projects/{}/task_assignments',
self.id
)
response = self.hv.get_request(url)
return [TaskAssignment(self.hv, tj['task_assignment']) for tj in response] | python | def task_assignments(self):
'''Retrieves all tasks currently assigned to this project.'''
url = str.format(
'projects/{}/task_assignments',
self.id
)
response = self.hv.get_request(url)
return [TaskAssignment(self.hv, tj['task_assignment']) for tj in response] | [
"def",
"task_assignments",
"(",
"self",
")",
":",
"url",
"=",
"str",
".",
"format",
"(",
"'projects/{}/task_assignments'",
",",
"self",
".",
"id",
")",
"response",
"=",
"self",
".",
"hv",
".",
"get_request",
"(",
"url",
")",
"return",
"[",
"TaskAssignment",
"(",
"self",
".",
"hv",
",",
"tj",
"[",
"'task_assignment'",
"]",
")",
"for",
"tj",
"in",
"response",
"]"
]
| Retrieves all tasks currently assigned to this project. | [
"Retrieves",
"all",
"tasks",
"currently",
"assigned",
"to",
"this",
"project",
"."
]
| c90c033c5388f5380155001957b26b1a930311f0 | https://github.com/jakebasile/reap/blob/c90c033c5388f5380155001957b26b1a930311f0/reap/api/admin.py#L209-L216 | train |
marrow/util | marrow/util/bunch.py | Bunch.partial | def partial(cls, prefix, source):
"""Strip a prefix from the keys of another dictionary, returning a Bunch containing only valid key, value pairs."""
match = prefix + "."
matches = cls([(key[len(match):], source[key]) for key in source if key.startswith(match)])
if not matches:
raise ValueError()
return matches | python | def partial(cls, prefix, source):
"""Strip a prefix from the keys of another dictionary, returning a Bunch containing only valid key, value pairs."""
match = prefix + "."
matches = cls([(key[len(match):], source[key]) for key in source if key.startswith(match)])
if not matches:
raise ValueError()
return matches | [
"def",
"partial",
"(",
"cls",
",",
"prefix",
",",
"source",
")",
":",
"match",
"=",
"prefix",
"+",
"\".\"",
"matches",
"=",
"cls",
"(",
"[",
"(",
"key",
"[",
"len",
"(",
"match",
")",
":",
"]",
",",
"source",
"[",
"key",
"]",
")",
"for",
"key",
"in",
"source",
"if",
"key",
".",
"startswith",
"(",
"match",
")",
"]",
")",
"if",
"not",
"matches",
":",
"raise",
"ValueError",
"(",
")",
"return",
"matches"
]
| Strip a prefix from the keys of another dictionary, returning a Bunch containing only valid key, value pairs. | [
"Strip",
"a",
"prefix",
"from",
"the",
"keys",
"of",
"another",
"dictionary",
"returning",
"a",
"Bunch",
"containing",
"only",
"valid",
"key",
"value",
"pairs",
"."
]
| abb8163dbd1fa0692d42a44d129b12ae2b39cdf2 | https://github.com/marrow/util/blob/abb8163dbd1fa0692d42a44d129b12ae2b39cdf2/marrow/util/bunch.py#L41-L50 | train |
tjcsl/cslbot | cslbot/commands/grep.py | cmd | def cmd(send, msg, args):
"""Greps the log for a string.
Syntax: {command} [--nick <nick>] [--ignore-case/-i] <string>
"""
parser = arguments.ArgParser(args['config'])
parser.add_argument('--nick', action=arguments.NickParser)
parser.add_argument('--ignore-case', '-i', action='store_true')
parser.add_argument('string', nargs='*')
try:
cmdargs = parser.parse_args(msg)
except arguments.ArgumentException as e:
send(str(e))
return
if not cmdargs.string:
send('Please specify a search term.')
return
cmdchar = args['config']['core']['cmdchar']
term = ' '.join(cmdargs.string)
if cmdargs.nick:
query = args['db'].query(Log).filter(Log.type == 'pubmsg', Log.source == cmdargs.nick, ~Log.msg.startswith(cmdchar))
else:
query = args['db'].query(Log).filter(Log.type == 'pubmsg', ~Log.msg.startswith(cmdchar))
if cmdargs.ignore_case:
query = query.filter(Log.msg.ilike('%%%s%%' % escape(term)))
else:
query = query.filter(Log.msg.like('%%%s%%' % escape(term)))
query = query.order_by(Log.time.desc())
result = query.limit(1).first()
count = query.count()
if result is not None:
logtime = result.time.strftime('%Y-%m-%d %H:%M:%S')
send("%s was last said by %s at %s (%d occurrences)" % (result.msg, result.source, logtime, count))
elif cmdargs.nick:
send('%s has never said %s.' % (cmdargs.nick, term))
else:
send('%s has never been said.' % term) | python | def cmd(send, msg, args):
"""Greps the log for a string.
Syntax: {command} [--nick <nick>] [--ignore-case/-i] <string>
"""
parser = arguments.ArgParser(args['config'])
parser.add_argument('--nick', action=arguments.NickParser)
parser.add_argument('--ignore-case', '-i', action='store_true')
parser.add_argument('string', nargs='*')
try:
cmdargs = parser.parse_args(msg)
except arguments.ArgumentException as e:
send(str(e))
return
if not cmdargs.string:
send('Please specify a search term.')
return
cmdchar = args['config']['core']['cmdchar']
term = ' '.join(cmdargs.string)
if cmdargs.nick:
query = args['db'].query(Log).filter(Log.type == 'pubmsg', Log.source == cmdargs.nick, ~Log.msg.startswith(cmdchar))
else:
query = args['db'].query(Log).filter(Log.type == 'pubmsg', ~Log.msg.startswith(cmdchar))
if cmdargs.ignore_case:
query = query.filter(Log.msg.ilike('%%%s%%' % escape(term)))
else:
query = query.filter(Log.msg.like('%%%s%%' % escape(term)))
query = query.order_by(Log.time.desc())
result = query.limit(1).first()
count = query.count()
if result is not None:
logtime = result.time.strftime('%Y-%m-%d %H:%M:%S')
send("%s was last said by %s at %s (%d occurrences)" % (result.msg, result.source, logtime, count))
elif cmdargs.nick:
send('%s has never said %s.' % (cmdargs.nick, term))
else:
send('%s has never been said.' % term) | [
"def",
"cmd",
"(",
"send",
",",
"msg",
",",
"args",
")",
":",
"parser",
"=",
"arguments",
".",
"ArgParser",
"(",
"args",
"[",
"'config'",
"]",
")",
"parser",
".",
"add_argument",
"(",
"'--nick'",
",",
"action",
"=",
"arguments",
".",
"NickParser",
")",
"parser",
".",
"add_argument",
"(",
"'--ignore-case'",
",",
"'-i'",
",",
"action",
"=",
"'store_true'",
")",
"parser",
".",
"add_argument",
"(",
"'string'",
",",
"nargs",
"=",
"'*'",
")",
"try",
":",
"cmdargs",
"=",
"parser",
".",
"parse_args",
"(",
"msg",
")",
"except",
"arguments",
".",
"ArgumentException",
"as",
"e",
":",
"send",
"(",
"str",
"(",
"e",
")",
")",
"return",
"if",
"not",
"cmdargs",
".",
"string",
":",
"send",
"(",
"'Please specify a search term.'",
")",
"return",
"cmdchar",
"=",
"args",
"[",
"'config'",
"]",
"[",
"'core'",
"]",
"[",
"'cmdchar'",
"]",
"term",
"=",
"' '",
".",
"join",
"(",
"cmdargs",
".",
"string",
")",
"if",
"cmdargs",
".",
"nick",
":",
"query",
"=",
"args",
"[",
"'db'",
"]",
".",
"query",
"(",
"Log",
")",
".",
"filter",
"(",
"Log",
".",
"type",
"==",
"'pubmsg'",
",",
"Log",
".",
"source",
"==",
"cmdargs",
".",
"nick",
",",
"~",
"Log",
".",
"msg",
".",
"startswith",
"(",
"cmdchar",
")",
")",
"else",
":",
"query",
"=",
"args",
"[",
"'db'",
"]",
".",
"query",
"(",
"Log",
")",
".",
"filter",
"(",
"Log",
".",
"type",
"==",
"'pubmsg'",
",",
"~",
"Log",
".",
"msg",
".",
"startswith",
"(",
"cmdchar",
")",
")",
"if",
"cmdargs",
".",
"ignore_case",
":",
"query",
"=",
"query",
".",
"filter",
"(",
"Log",
".",
"msg",
".",
"ilike",
"(",
"'%%%s%%'",
"%",
"escape",
"(",
"term",
")",
")",
")",
"else",
":",
"query",
"=",
"query",
".",
"filter",
"(",
"Log",
".",
"msg",
".",
"like",
"(",
"'%%%s%%'",
"%",
"escape",
"(",
"term",
")",
")",
")",
"query",
"=",
"query",
".",
"order_by",
"(",
"Log",
".",
"time",
".",
"desc",
"(",
")",
")",
"result",
"=",
"query",
".",
"limit",
"(",
"1",
")",
".",
"first",
"(",
")",
"count",
"=",
"query",
".",
"count",
"(",
")",
"if",
"result",
"is",
"not",
"None",
":",
"logtime",
"=",
"result",
".",
"time",
".",
"strftime",
"(",
"'%Y-%m-%d %H:%M:%S'",
")",
"send",
"(",
"\"%s was last said by %s at %s (%d occurrences)\"",
"%",
"(",
"result",
".",
"msg",
",",
"result",
".",
"source",
",",
"logtime",
",",
"count",
")",
")",
"elif",
"cmdargs",
".",
"nick",
":",
"send",
"(",
"'%s has never said %s.'",
"%",
"(",
"cmdargs",
".",
"nick",
",",
"term",
")",
")",
"else",
":",
"send",
"(",
"'%s has never been said.'",
"%",
"term",
")"
]
| Greps the log for a string.
Syntax: {command} [--nick <nick>] [--ignore-case/-i] <string> | [
"Greps",
"the",
"log",
"for",
"a",
"string",
"."
]
| aebe07be47141f61d7c180706bddfb707f19b2b5 | https://github.com/tjcsl/cslbot/blob/aebe07be47141f61d7c180706bddfb707f19b2b5/cslbot/commands/grep.py#L25-L62 | train |
acutesoftware/virtual-AI-simulator | vais/examples/game_incremental.py | pick_action_todo | def pick_action_todo():
"""
only for testing and AI - user will usually choose an action
Sort of works
"""
for ndx, todo in enumerate(things_to_do):
#print('todo = ', todo)
if roll_dice(todo["chance"]):
cur_act = actions[get_action_by_name(todo["name"])]
if todo["WHERE_COL"] == "energy" and my_char["energy"] > todo["WHERE_VAL"]:
return cur_act
if todo["WHERE_COL"] == "gold" and my_char["gold"] > todo["WHERE_VAL"]:
return cur_act
return actions[3] | python | def pick_action_todo():
"""
only for testing and AI - user will usually choose an action
Sort of works
"""
for ndx, todo in enumerate(things_to_do):
#print('todo = ', todo)
if roll_dice(todo["chance"]):
cur_act = actions[get_action_by_name(todo["name"])]
if todo["WHERE_COL"] == "energy" and my_char["energy"] > todo["WHERE_VAL"]:
return cur_act
if todo["WHERE_COL"] == "gold" and my_char["gold"] > todo["WHERE_VAL"]:
return cur_act
return actions[3] | [
"def",
"pick_action_todo",
"(",
")",
":",
"for",
"ndx",
",",
"todo",
"in",
"enumerate",
"(",
"things_to_do",
")",
":",
"#print('todo = ', todo)",
"if",
"roll_dice",
"(",
"todo",
"[",
"\"chance\"",
"]",
")",
":",
"cur_act",
"=",
"actions",
"[",
"get_action_by_name",
"(",
"todo",
"[",
"\"name\"",
"]",
")",
"]",
"if",
"todo",
"[",
"\"WHERE_COL\"",
"]",
"==",
"\"energy\"",
"and",
"my_char",
"[",
"\"energy\"",
"]",
">",
"todo",
"[",
"\"WHERE_VAL\"",
"]",
":",
"return",
"cur_act",
"if",
"todo",
"[",
"\"WHERE_COL\"",
"]",
"==",
"\"gold\"",
"and",
"my_char",
"[",
"\"gold\"",
"]",
">",
"todo",
"[",
"\"WHERE_VAL\"",
"]",
":",
"return",
"cur_act",
"return",
"actions",
"[",
"3",
"]"
]
| only for testing and AI - user will usually choose an action
Sort of works | [
"only",
"for",
"testing",
"and",
"AI",
"-",
"user",
"will",
"usually",
"choose",
"an",
"action",
"Sort",
"of",
"works"
]
| 57de679a5b1a58c38fefe6aea58af1f3a7e79c58 | https://github.com/acutesoftware/virtual-AI-simulator/blob/57de679a5b1a58c38fefe6aea58af1f3a7e79c58/vais/examples/game_incremental.py#L142-L157 | train |
acutesoftware/virtual-AI-simulator | vais/examples/game_incremental.py | do_action | def do_action(character, action):
"""
called by main game loop to run an action
"""
stats = "Energy=" + str(round(character["energy"], 0)) + ", "
stats += "Gold=" + str(round(character["gold"], 0)) + ", "
ndx_action_skill = get_skill_by_name(action["name"], character)
stats += "Skill=" + str(round(character["skills"][ndx_action_skill]["level"], 1))
my_char["energy"] -= action["cost_energy"]
my_char["skills"][ndx_action_skill]["level"] += action["exp_gain"]
# NOT NEEDED act = get_action_by_name(character["skills"][ndx_action_skill]["name"])
reward_item = action["reward_item"]
#print('reward_item = ', reward_item)
#print('action = ', action)
inv = get_inventory_by_name(reward_item, my_char)
#print('inv=', inv)
if roll_dice(action["reward_chance"]) :
my_char["inventory"][inv]["val"] += 1
#my_char["inventory"][inv] += 1
#my_char["inventory"][inv][reward_item] += 1
print(character["name"] + " is " + action["name"] + ". " + stats + ' FOUND ' + reward_item)
else:
print(character["name"] + " is " + action["name"] + ". " + stats) | python | def do_action(character, action):
"""
called by main game loop to run an action
"""
stats = "Energy=" + str(round(character["energy"], 0)) + ", "
stats += "Gold=" + str(round(character["gold"], 0)) + ", "
ndx_action_skill = get_skill_by_name(action["name"], character)
stats += "Skill=" + str(round(character["skills"][ndx_action_skill]["level"], 1))
my_char["energy"] -= action["cost_energy"]
my_char["skills"][ndx_action_skill]["level"] += action["exp_gain"]
# NOT NEEDED act = get_action_by_name(character["skills"][ndx_action_skill]["name"])
reward_item = action["reward_item"]
#print('reward_item = ', reward_item)
#print('action = ', action)
inv = get_inventory_by_name(reward_item, my_char)
#print('inv=', inv)
if roll_dice(action["reward_chance"]) :
my_char["inventory"][inv]["val"] += 1
#my_char["inventory"][inv] += 1
#my_char["inventory"][inv][reward_item] += 1
print(character["name"] + " is " + action["name"] + ". " + stats + ' FOUND ' + reward_item)
else:
print(character["name"] + " is " + action["name"] + ". " + stats) | [
"def",
"do_action",
"(",
"character",
",",
"action",
")",
":",
"stats",
"=",
"\"Energy=\"",
"+",
"str",
"(",
"round",
"(",
"character",
"[",
"\"energy\"",
"]",
",",
"0",
")",
")",
"+",
"\", \"",
"stats",
"+=",
"\"Gold=\"",
"+",
"str",
"(",
"round",
"(",
"character",
"[",
"\"gold\"",
"]",
",",
"0",
")",
")",
"+",
"\", \"",
"ndx_action_skill",
"=",
"get_skill_by_name",
"(",
"action",
"[",
"\"name\"",
"]",
",",
"character",
")",
"stats",
"+=",
"\"Skill=\"",
"+",
"str",
"(",
"round",
"(",
"character",
"[",
"\"skills\"",
"]",
"[",
"ndx_action_skill",
"]",
"[",
"\"level\"",
"]",
",",
"1",
")",
")",
"my_char",
"[",
"\"energy\"",
"]",
"-=",
"action",
"[",
"\"cost_energy\"",
"]",
"my_char",
"[",
"\"skills\"",
"]",
"[",
"ndx_action_skill",
"]",
"[",
"\"level\"",
"]",
"+=",
"action",
"[",
"\"exp_gain\"",
"]",
"# NOT NEEDED act = get_action_by_name(character[\"skills\"][ndx_action_skill][\"name\"])",
"reward_item",
"=",
"action",
"[",
"\"reward_item\"",
"]",
"#print('reward_item = ', reward_item)",
"#print('action = ', action)",
"inv",
"=",
"get_inventory_by_name",
"(",
"reward_item",
",",
"my_char",
")",
"#print('inv=', inv)",
"if",
"roll_dice",
"(",
"action",
"[",
"\"reward_chance\"",
"]",
")",
":",
"my_char",
"[",
"\"inventory\"",
"]",
"[",
"inv",
"]",
"[",
"\"val\"",
"]",
"+=",
"1",
"#my_char[\"inventory\"][inv] += 1",
"#my_char[\"inventory\"][inv][reward_item] += 1",
"print",
"(",
"character",
"[",
"\"name\"",
"]",
"+",
"\" is \"",
"+",
"action",
"[",
"\"name\"",
"]",
"+",
"\". \"",
"+",
"stats",
"+",
"' FOUND '",
"+",
"reward_item",
")",
"else",
":",
"print",
"(",
"character",
"[",
"\"name\"",
"]",
"+",
"\" is \"",
"+",
"action",
"[",
"\"name\"",
"]",
"+",
"\". \"",
"+",
"stats",
")"
]
| called by main game loop to run an action | [
"called",
"by",
"main",
"game",
"loop",
"to",
"run",
"an",
"action"
]
| 57de679a5b1a58c38fefe6aea58af1f3a7e79c58 | https://github.com/acutesoftware/virtual-AI-simulator/blob/57de679a5b1a58c38fefe6aea58af1f3a7e79c58/vais/examples/game_incremental.py#L160-L188 | train |
acutesoftware/virtual-AI-simulator | vais/examples/game_incremental.py | get_inventory_by_name | def get_inventory_by_name(nme, character):
"""
returns the inventory index by name
"""
for ndx, sk in enumerate(character["inventory"]):
#print("sk = ", sk, " , nme = ", nme)
if sk["name"] == nme:
return ndx
return 0 | python | def get_inventory_by_name(nme, character):
"""
returns the inventory index by name
"""
for ndx, sk in enumerate(character["inventory"]):
#print("sk = ", sk, " , nme = ", nme)
if sk["name"] == nme:
return ndx
return 0 | [
"def",
"get_inventory_by_name",
"(",
"nme",
",",
"character",
")",
":",
"for",
"ndx",
",",
"sk",
"in",
"enumerate",
"(",
"character",
"[",
"\"inventory\"",
"]",
")",
":",
"#print(\"sk = \", sk, \" , nme = \", nme)",
"if",
"sk",
"[",
"\"name\"",
"]",
"==",
"nme",
":",
"return",
"ndx",
"return",
"0"
]
| returns the inventory index by name | [
"returns",
"the",
"inventory",
"index",
"by",
"name"
]
| 57de679a5b1a58c38fefe6aea58af1f3a7e79c58 | https://github.com/acutesoftware/virtual-AI-simulator/blob/57de679a5b1a58c38fefe6aea58af1f3a7e79c58/vais/examples/game_incremental.py#L202-L211 | train |
acutesoftware/virtual-AI-simulator | vais/examples/game_incremental.py | get_skill_by_name | def get_skill_by_name(nme, character):
"""
returns the skill by name in a character
"""
for ndx, sk in enumerate(character["skills"]):
if sk["name"] == nme:
return ndx
return 0 | python | def get_skill_by_name(nme, character):
"""
returns the skill by name in a character
"""
for ndx, sk in enumerate(character["skills"]):
if sk["name"] == nme:
return ndx
return 0 | [
"def",
"get_skill_by_name",
"(",
"nme",
",",
"character",
")",
":",
"for",
"ndx",
",",
"sk",
"in",
"enumerate",
"(",
"character",
"[",
"\"skills\"",
"]",
")",
":",
"if",
"sk",
"[",
"\"name\"",
"]",
"==",
"nme",
":",
"return",
"ndx",
"return",
"0"
]
| returns the skill by name in a character | [
"returns",
"the",
"skill",
"by",
"name",
"in",
"a",
"character"
]
| 57de679a5b1a58c38fefe6aea58af1f3a7e79c58 | https://github.com/acutesoftware/virtual-AI-simulator/blob/57de679a5b1a58c38fefe6aea58af1f3a7e79c58/vais/examples/game_incremental.py#L224-L232 | train |
sbma44/beautifulsoupselect | beautifulsoupselect/soupselect.py | attribute_checker | def attribute_checker(operator, attribute, value=''):
"""
Takes an operator, attribute and optional value; returns a function that
will return True for elements that match that combination.
"""
return {
'=': lambda el: el.get(attribute) == value,
# attribute includes value as one of a set of space separated tokens
'~': lambda el: value in el.get(attribute, '').split(),
# attribute starts with value
'^': lambda el: el.get(attribute, '').startswith(value),
# attribute ends with value
'$': lambda el: el.get(attribute, '').endswith(value),
# attribute contains value
'*': lambda el: value in el.get(attribute, ''),
# attribute is either exactly value or starts with value-
'|': lambda el: el.get(attribute, '') == value \
or el.get(attribute, '').startswith('%s-' % value),
}.get(operator, lambda el: el.has_key(attribute)) | python | def attribute_checker(operator, attribute, value=''):
"""
Takes an operator, attribute and optional value; returns a function that
will return True for elements that match that combination.
"""
return {
'=': lambda el: el.get(attribute) == value,
# attribute includes value as one of a set of space separated tokens
'~': lambda el: value in el.get(attribute, '').split(),
# attribute starts with value
'^': lambda el: el.get(attribute, '').startswith(value),
# attribute ends with value
'$': lambda el: el.get(attribute, '').endswith(value),
# attribute contains value
'*': lambda el: value in el.get(attribute, ''),
# attribute is either exactly value or starts with value-
'|': lambda el: el.get(attribute, '') == value \
or el.get(attribute, '').startswith('%s-' % value),
}.get(operator, lambda el: el.has_key(attribute)) | [
"def",
"attribute_checker",
"(",
"operator",
",",
"attribute",
",",
"value",
"=",
"''",
")",
":",
"return",
"{",
"'='",
":",
"lambda",
"el",
":",
"el",
".",
"get",
"(",
"attribute",
")",
"==",
"value",
",",
"# attribute includes value as one of a set of space separated tokens",
"'~'",
":",
"lambda",
"el",
":",
"value",
"in",
"el",
".",
"get",
"(",
"attribute",
",",
"''",
")",
".",
"split",
"(",
")",
",",
"# attribute starts with value",
"'^'",
":",
"lambda",
"el",
":",
"el",
".",
"get",
"(",
"attribute",
",",
"''",
")",
".",
"startswith",
"(",
"value",
")",
",",
"# attribute ends with value",
"'$'",
":",
"lambda",
"el",
":",
"el",
".",
"get",
"(",
"attribute",
",",
"''",
")",
".",
"endswith",
"(",
"value",
")",
",",
"# attribute contains value",
"'*'",
":",
"lambda",
"el",
":",
"value",
"in",
"el",
".",
"get",
"(",
"attribute",
",",
"''",
")",
",",
"# attribute is either exactly value or starts with value-",
"'|'",
":",
"lambda",
"el",
":",
"el",
".",
"get",
"(",
"attribute",
",",
"''",
")",
"==",
"value",
"or",
"el",
".",
"get",
"(",
"attribute",
",",
"''",
")",
".",
"startswith",
"(",
"'%s-'",
"%",
"value",
")",
",",
"}",
".",
"get",
"(",
"operator",
",",
"lambda",
"el",
":",
"el",
".",
"has_key",
"(",
"attribute",
")",
")"
]
| Takes an operator, attribute and optional value; returns a function that
will return True for elements that match that combination. | [
"Takes",
"an",
"operator",
"attribute",
"and",
"optional",
"value",
";",
"returns",
"a",
"function",
"that",
"will",
"return",
"True",
"for",
"elements",
"that",
"match",
"that",
"combination",
"."
]
| 624c152ccd91fb69f46314ef6be253e75b13ca5b | https://github.com/sbma44/beautifulsoupselect/blob/624c152ccd91fb69f46314ef6be253e75b13ca5b/beautifulsoupselect/soupselect.py#L32-L50 | train |
sbma44/beautifulsoupselect | beautifulsoupselect/soupselect.py | select | def select(soup, selector):
"""
soup should be a BeautifulSoup instance; selector is a CSS selector
specifying the elements you want to retrieve.
"""
tokens = selector.split()
current_context = [soup]
for token in tokens:
m = attribselect_re.match(token)
if m:
# Attribute selector
tag, attribute, operator, value = m.groups()
if not tag:
tag = True
checker = attribute_checker(operator, attribute, value)
found = []
for context in current_context:
found.extend([el for el in context.findAll(tag) if checker(el)])
current_context = found
continue
if '#' in token:
# ID selector
tag, id = token.split('#', 1)
if not tag:
tag = True
el = current_context[0].find(tag, {'id': id})
if not el:
return [] # No match
current_context = [el]
continue
if '.' in token:
# Class selector
tag, klass = token.split('.', 1)
if not tag:
tag = True
found = []
for context in current_context:
found.extend(
context.findAll(tag,
{'class': lambda attr: attr and klass in attr.split()}
)
)
current_context = found
continue
if token == '*':
# Star selector
found = []
for context in current_context:
found.extend(context.findAll(True))
current_context = found
continue
# Here we should just have a regular tag
if not tag_re.match(token):
return []
found = []
for context in current_context:
found.extend(context.findAll(token))
current_context = found
return current_context | python | def select(soup, selector):
"""
soup should be a BeautifulSoup instance; selector is a CSS selector
specifying the elements you want to retrieve.
"""
tokens = selector.split()
current_context = [soup]
for token in tokens:
m = attribselect_re.match(token)
if m:
# Attribute selector
tag, attribute, operator, value = m.groups()
if not tag:
tag = True
checker = attribute_checker(operator, attribute, value)
found = []
for context in current_context:
found.extend([el for el in context.findAll(tag) if checker(el)])
current_context = found
continue
if '#' in token:
# ID selector
tag, id = token.split('#', 1)
if not tag:
tag = True
el = current_context[0].find(tag, {'id': id})
if not el:
return [] # No match
current_context = [el]
continue
if '.' in token:
# Class selector
tag, klass = token.split('.', 1)
if not tag:
tag = True
found = []
for context in current_context:
found.extend(
context.findAll(tag,
{'class': lambda attr: attr and klass in attr.split()}
)
)
current_context = found
continue
if token == '*':
# Star selector
found = []
for context in current_context:
found.extend(context.findAll(True))
current_context = found
continue
# Here we should just have a regular tag
if not tag_re.match(token):
return []
found = []
for context in current_context:
found.extend(context.findAll(token))
current_context = found
return current_context | [
"def",
"select",
"(",
"soup",
",",
"selector",
")",
":",
"tokens",
"=",
"selector",
".",
"split",
"(",
")",
"current_context",
"=",
"[",
"soup",
"]",
"for",
"token",
"in",
"tokens",
":",
"m",
"=",
"attribselect_re",
".",
"match",
"(",
"token",
")",
"if",
"m",
":",
"# Attribute selector",
"tag",
",",
"attribute",
",",
"operator",
",",
"value",
"=",
"m",
".",
"groups",
"(",
")",
"if",
"not",
"tag",
":",
"tag",
"=",
"True",
"checker",
"=",
"attribute_checker",
"(",
"operator",
",",
"attribute",
",",
"value",
")",
"found",
"=",
"[",
"]",
"for",
"context",
"in",
"current_context",
":",
"found",
".",
"extend",
"(",
"[",
"el",
"for",
"el",
"in",
"context",
".",
"findAll",
"(",
"tag",
")",
"if",
"checker",
"(",
"el",
")",
"]",
")",
"current_context",
"=",
"found",
"continue",
"if",
"'#'",
"in",
"token",
":",
"# ID selector",
"tag",
",",
"id",
"=",
"token",
".",
"split",
"(",
"'#'",
",",
"1",
")",
"if",
"not",
"tag",
":",
"tag",
"=",
"True",
"el",
"=",
"current_context",
"[",
"0",
"]",
".",
"find",
"(",
"tag",
",",
"{",
"'id'",
":",
"id",
"}",
")",
"if",
"not",
"el",
":",
"return",
"[",
"]",
"# No match",
"current_context",
"=",
"[",
"el",
"]",
"continue",
"if",
"'.'",
"in",
"token",
":",
"# Class selector",
"tag",
",",
"klass",
"=",
"token",
".",
"split",
"(",
"'.'",
",",
"1",
")",
"if",
"not",
"tag",
":",
"tag",
"=",
"True",
"found",
"=",
"[",
"]",
"for",
"context",
"in",
"current_context",
":",
"found",
".",
"extend",
"(",
"context",
".",
"findAll",
"(",
"tag",
",",
"{",
"'class'",
":",
"lambda",
"attr",
":",
"attr",
"and",
"klass",
"in",
"attr",
".",
"split",
"(",
")",
"}",
")",
")",
"current_context",
"=",
"found",
"continue",
"if",
"token",
"==",
"'*'",
":",
"# Star selector",
"found",
"=",
"[",
"]",
"for",
"context",
"in",
"current_context",
":",
"found",
".",
"extend",
"(",
"context",
".",
"findAll",
"(",
"True",
")",
")",
"current_context",
"=",
"found",
"continue",
"# Here we should just have a regular tag",
"if",
"not",
"tag_re",
".",
"match",
"(",
"token",
")",
":",
"return",
"[",
"]",
"found",
"=",
"[",
"]",
"for",
"context",
"in",
"current_context",
":",
"found",
".",
"extend",
"(",
"context",
".",
"findAll",
"(",
"token",
")",
")",
"current_context",
"=",
"found",
"return",
"current_context"
]
| soup should be a BeautifulSoup instance; selector is a CSS selector
specifying the elements you want to retrieve. | [
"soup",
"should",
"be",
"a",
"BeautifulSoup",
"instance",
";",
"selector",
"is",
"a",
"CSS",
"selector",
"specifying",
"the",
"elements",
"you",
"want",
"to",
"retrieve",
"."
]
| 624c152ccd91fb69f46314ef6be253e75b13ca5b | https://github.com/sbma44/beautifulsoupselect/blob/624c152ccd91fb69f46314ef6be253e75b13ca5b/beautifulsoupselect/soupselect.py#L53-L111 | train |
VIVelev/PyDojoML | dojo/losses.py | KL_Divergence.gradient | def gradient(self, P, Q, Y, i):
"""Computes the gradient of KL divergence with respect to the i'th example of Y"""
return 4 * sum([
(P[i, j] - Q[i, j]) * (Y[i] - Y[j]) * (1 + np.linalg.norm(Y[i] - Y[j]) ** 2) ** -1 \
for j in range(Y.shape[0])
]) | python | def gradient(self, P, Q, Y, i):
"""Computes the gradient of KL divergence with respect to the i'th example of Y"""
return 4 * sum([
(P[i, j] - Q[i, j]) * (Y[i] - Y[j]) * (1 + np.linalg.norm(Y[i] - Y[j]) ** 2) ** -1 \
for j in range(Y.shape[0])
]) | [
"def",
"gradient",
"(",
"self",
",",
"P",
",",
"Q",
",",
"Y",
",",
"i",
")",
":",
"return",
"4",
"*",
"sum",
"(",
"[",
"(",
"P",
"[",
"i",
",",
"j",
"]",
"-",
"Q",
"[",
"i",
",",
"j",
"]",
")",
"*",
"(",
"Y",
"[",
"i",
"]",
"-",
"Y",
"[",
"j",
"]",
")",
"*",
"(",
"1",
"+",
"np",
".",
"linalg",
".",
"norm",
"(",
"Y",
"[",
"i",
"]",
"-",
"Y",
"[",
"j",
"]",
")",
"**",
"2",
")",
"**",
"-",
"1",
"for",
"j",
"in",
"range",
"(",
"Y",
".",
"shape",
"[",
"0",
"]",
")",
"]",
")"
]
| Computes the gradient of KL divergence with respect to the i'th example of Y | [
"Computes",
"the",
"gradient",
"of",
"KL",
"divergence",
"with",
"respect",
"to",
"the",
"i",
"th",
"example",
"of",
"Y"
]
| 773fdce6866aa6decd306a5a85f94129fed816eb | https://github.com/VIVelev/PyDojoML/blob/773fdce6866aa6decd306a5a85f94129fed816eb/dojo/losses.py#L75-L81 | train |
Xion/taipan | taipan/functional/constructs.py | try_ | def try_(block, except_=None, else_=None, finally_=None):
"""Emulate a ``try`` block.
:param block: Function to be executed within the ``try`` statement
:param except_: Function to execute when an :class:`Exception` occurs.
It receives a single argument: the exception object.
Alternatively, a list of key-value pairs can be passed,
mapping exception types to their handler functions.
:param else_: Function to execute when ``block`` completes successfully.
Note that it requires ``except_`` to be provided as well
:param finally_: Function to execute at the end,
regardless of whether an exception occurred or not
:return: If no exception was raised while executing ``block``,
the result of ``else_`` (if provided) or ``block`` is returned.
Otherwise, the result of ``except_`` is returned.
Note that :func:`try_` can _still_ raise an exception if it occurs
while evaluating ``except_``, ``else_`` or ``finally_`` functions.
"""
ensure_callable(block)
if not (except_ or else_ or finally_):
raise TypeError("at least one of `except_`, `else_` or `finally_` "
"functions must be provided")
if else_ and not except_:
raise TypeError("`else_` can only be provided along with `except_`")
if except_:
if callable(except_):
except_ = [(Exception, except_)]
else:
ensure_iterable(except_)
if is_mapping(except_):
ensure_ordered_mapping(except_)
except_ = except_.items()
def handle_exception():
"""Dispatch current exception to proper handler in ``except_``."""
exc_type, exc_object = sys.exc_info()[:2]
for t, handler in except_:
if issubclass(exc_type, t):
return handler(exc_object)
raise
if else_:
ensure_callable(else_)
if finally_:
ensure_callable(finally_)
try:
block()
except:
return handle_exception()
else:
return else_()
finally:
finally_()
else:
try:
block()
except:
return handle_exception()
else:
return else_()
else:
if finally_:
ensure_callable(finally_)
try:
return block()
except:
return handle_exception()
finally:
finally_()
else:
try:
return block()
except:
return handle_exception()
elif finally_:
ensure_callable(finally_)
try:
return block()
finally:
finally_() | python | def try_(block, except_=None, else_=None, finally_=None):
"""Emulate a ``try`` block.
:param block: Function to be executed within the ``try`` statement
:param except_: Function to execute when an :class:`Exception` occurs.
It receives a single argument: the exception object.
Alternatively, a list of key-value pairs can be passed,
mapping exception types to their handler functions.
:param else_: Function to execute when ``block`` completes successfully.
Note that it requires ``except_`` to be provided as well
:param finally_: Function to execute at the end,
regardless of whether an exception occurred or not
:return: If no exception was raised while executing ``block``,
the result of ``else_`` (if provided) or ``block`` is returned.
Otherwise, the result of ``except_`` is returned.
Note that :func:`try_` can _still_ raise an exception if it occurs
while evaluating ``except_``, ``else_`` or ``finally_`` functions.
"""
ensure_callable(block)
if not (except_ or else_ or finally_):
raise TypeError("at least one of `except_`, `else_` or `finally_` "
"functions must be provided")
if else_ and not except_:
raise TypeError("`else_` can only be provided along with `except_`")
if except_:
if callable(except_):
except_ = [(Exception, except_)]
else:
ensure_iterable(except_)
if is_mapping(except_):
ensure_ordered_mapping(except_)
except_ = except_.items()
def handle_exception():
"""Dispatch current exception to proper handler in ``except_``."""
exc_type, exc_object = sys.exc_info()[:2]
for t, handler in except_:
if issubclass(exc_type, t):
return handler(exc_object)
raise
if else_:
ensure_callable(else_)
if finally_:
ensure_callable(finally_)
try:
block()
except:
return handle_exception()
else:
return else_()
finally:
finally_()
else:
try:
block()
except:
return handle_exception()
else:
return else_()
else:
if finally_:
ensure_callable(finally_)
try:
return block()
except:
return handle_exception()
finally:
finally_()
else:
try:
return block()
except:
return handle_exception()
elif finally_:
ensure_callable(finally_)
try:
return block()
finally:
finally_() | [
"def",
"try_",
"(",
"block",
",",
"except_",
"=",
"None",
",",
"else_",
"=",
"None",
",",
"finally_",
"=",
"None",
")",
":",
"ensure_callable",
"(",
"block",
")",
"if",
"not",
"(",
"except_",
"or",
"else_",
"or",
"finally_",
")",
":",
"raise",
"TypeError",
"(",
"\"at least one of `except_`, `else_` or `finally_` \"",
"\"functions must be provided\"",
")",
"if",
"else_",
"and",
"not",
"except_",
":",
"raise",
"TypeError",
"(",
"\"`else_` can only be provided along with `except_`\"",
")",
"if",
"except_",
":",
"if",
"callable",
"(",
"except_",
")",
":",
"except_",
"=",
"[",
"(",
"Exception",
",",
"except_",
")",
"]",
"else",
":",
"ensure_iterable",
"(",
"except_",
")",
"if",
"is_mapping",
"(",
"except_",
")",
":",
"ensure_ordered_mapping",
"(",
"except_",
")",
"except_",
"=",
"except_",
".",
"items",
"(",
")",
"def",
"handle_exception",
"(",
")",
":",
"\"\"\"Dispatch current exception to proper handler in ``except_``.\"\"\"",
"exc_type",
",",
"exc_object",
"=",
"sys",
".",
"exc_info",
"(",
")",
"[",
":",
"2",
"]",
"for",
"t",
",",
"handler",
"in",
"except_",
":",
"if",
"issubclass",
"(",
"exc_type",
",",
"t",
")",
":",
"return",
"handler",
"(",
"exc_object",
")",
"raise",
"if",
"else_",
":",
"ensure_callable",
"(",
"else_",
")",
"if",
"finally_",
":",
"ensure_callable",
"(",
"finally_",
")",
"try",
":",
"block",
"(",
")",
"except",
":",
"return",
"handle_exception",
"(",
")",
"else",
":",
"return",
"else_",
"(",
")",
"finally",
":",
"finally_",
"(",
")",
"else",
":",
"try",
":",
"block",
"(",
")",
"except",
":",
"return",
"handle_exception",
"(",
")",
"else",
":",
"return",
"else_",
"(",
")",
"else",
":",
"if",
"finally_",
":",
"ensure_callable",
"(",
"finally_",
")",
"try",
":",
"return",
"block",
"(",
")",
"except",
":",
"return",
"handle_exception",
"(",
")",
"finally",
":",
"finally_",
"(",
")",
"else",
":",
"try",
":",
"return",
"block",
"(",
")",
"except",
":",
"return",
"handle_exception",
"(",
")",
"elif",
"finally_",
":",
"ensure_callable",
"(",
"finally_",
")",
"try",
":",
"return",
"block",
"(",
")",
"finally",
":",
"finally_",
"(",
")"
]
| Emulate a ``try`` block.
:param block: Function to be executed within the ``try`` statement
:param except_: Function to execute when an :class:`Exception` occurs.
It receives a single argument: the exception object.
Alternatively, a list of key-value pairs can be passed,
mapping exception types to their handler functions.
:param else_: Function to execute when ``block`` completes successfully.
Note that it requires ``except_`` to be provided as well
:param finally_: Function to execute at the end,
regardless of whether an exception occurred or not
:return: If no exception was raised while executing ``block``,
the result of ``else_`` (if provided) or ``block`` is returned.
Otherwise, the result of ``except_`` is returned.
Note that :func:`try_` can _still_ raise an exception if it occurs
while evaluating ``except_``, ``else_`` or ``finally_`` functions. | [
"Emulate",
"a",
"try",
"block",
"."
]
| f333f0287c8bd0915182c7d5308e5f05ef0cca78 | https://github.com/Xion/taipan/blob/f333f0287c8bd0915182c7d5308e5f05ef0cca78/taipan/functional/constructs.py#L57-L139 | train |
Xion/taipan | taipan/functional/constructs.py | with_ | def with_(contextmanager, do):
"""Emulate a `with`` statement, performing an operation within context.
:param contextmanager: Context manager to use for ``with`` statement
:param do: Operation to perform: callable that receives the ``as`` value
:return: Result of the operation
Example::
# read all lines from given list of ``files``
all_lines = sum((with_(open(filename), do=dotcall('readlines'))
for filename in files), [])
"""
ensure_contextmanager(contextmanager)
ensure_callable(do)
with contextmanager as value:
return do(value) | python | def with_(contextmanager, do):
"""Emulate a `with`` statement, performing an operation within context.
:param contextmanager: Context manager to use for ``with`` statement
:param do: Operation to perform: callable that receives the ``as`` value
:return: Result of the operation
Example::
# read all lines from given list of ``files``
all_lines = sum((with_(open(filename), do=dotcall('readlines'))
for filename in files), [])
"""
ensure_contextmanager(contextmanager)
ensure_callable(do)
with contextmanager as value:
return do(value) | [
"def",
"with_",
"(",
"contextmanager",
",",
"do",
")",
":",
"ensure_contextmanager",
"(",
"contextmanager",
")",
"ensure_callable",
"(",
"do",
")",
"with",
"contextmanager",
"as",
"value",
":",
"return",
"do",
"(",
"value",
")"
]
| Emulate a `with`` statement, performing an operation within context.
:param contextmanager: Context manager to use for ``with`` statement
:param do: Operation to perform: callable that receives the ``as`` value
:return: Result of the operation
Example::
# read all lines from given list of ``files``
all_lines = sum((with_(open(filename), do=dotcall('readlines'))
for filename in files), []) | [
"Emulate",
"a",
"with",
"statement",
"performing",
"an",
"operation",
"within",
"context",
"."
]
| f333f0287c8bd0915182c7d5308e5f05ef0cca78 | https://github.com/Xion/taipan/blob/f333f0287c8bd0915182c7d5308e5f05ef0cca78/taipan/functional/constructs.py#L142-L160 | train |
nucypher/constantSorrow | constant_sorrow/constants.py | _Constant._cast_repr | def _cast_repr(self, caster, *args, **kwargs):
"""
Will cast this constant with the provided caster, passing args and kwargs.
If there is no registered representation, will hash the name using sha512 and use the first 8 bytes
of the digest.
"""
if self.__repr_content is None:
self.__repr_content = hash_and_truncate(self)
assert self.__uses_default_repr # Sanity check: we are indeed using the default repr here. If this has ever changed, something went wrong.
return caster(self.__repr_content, *args, **kwargs) | python | def _cast_repr(self, caster, *args, **kwargs):
"""
Will cast this constant with the provided caster, passing args and kwargs.
If there is no registered representation, will hash the name using sha512 and use the first 8 bytes
of the digest.
"""
if self.__repr_content is None:
self.__repr_content = hash_and_truncate(self)
assert self.__uses_default_repr # Sanity check: we are indeed using the default repr here. If this has ever changed, something went wrong.
return caster(self.__repr_content, *args, **kwargs) | [
"def",
"_cast_repr",
"(",
"self",
",",
"caster",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"self",
".",
"__repr_content",
"is",
"None",
":",
"self",
".",
"__repr_content",
"=",
"hash_and_truncate",
"(",
"self",
")",
"assert",
"self",
".",
"__uses_default_repr",
"# Sanity check: we are indeed using the default repr here. If this has ever changed, something went wrong.",
"return",
"caster",
"(",
"self",
".",
"__repr_content",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
]
| Will cast this constant with the provided caster, passing args and kwargs.
If there is no registered representation, will hash the name using sha512 and use the first 8 bytes
of the digest. | [
"Will",
"cast",
"this",
"constant",
"with",
"the",
"provided",
"caster",
"passing",
"args",
"and",
"kwargs",
"."
]
| 546f83d7e8e8f551b57c16bc754a1ea33d73f92e | https://github.com/nucypher/constantSorrow/blob/546f83d7e8e8f551b57c16bc754a1ea33d73f92e/constant_sorrow/constants.py#L189-L200 | train |
tjcsl/cslbot | cslbot/commands/threads.py | cmd | def cmd(send, *_):
"""Enumerate threads.
Syntax: {command}
"""
thread_names = []
for x in sorted(threading.enumerate(), key=lambda k: k.name):
res = re.match(r'Thread-(\d+$)', x.name)
if res:
tid = int(res.group(1))
# Handle the main server thread (permanently listed as _worker)
if x._target.__name__ == '_worker':
thread_names.append((tid, "%s running server thread" % x.name))
# Handle the multiprocessing pool worker threads (they don't have names beyond Thread-x)
elif x._target.__module__ == 'multiprocessing.pool':
thread_names.append((tid, "%s running multiprocessing pool worker thread" % x.name))
# Handle everything else including MainThread and deferred threads
else:
res = re.match(r'Thread-(\d+)', x.name)
tid = 0
if res:
tid = int(res.group(1))
thread_names.append((tid, x.name))
for x in sorted(thread_names, key=lambda k: k[0]):
send(x[1]) | python | def cmd(send, *_):
"""Enumerate threads.
Syntax: {command}
"""
thread_names = []
for x in sorted(threading.enumerate(), key=lambda k: k.name):
res = re.match(r'Thread-(\d+$)', x.name)
if res:
tid = int(res.group(1))
# Handle the main server thread (permanently listed as _worker)
if x._target.__name__ == '_worker':
thread_names.append((tid, "%s running server thread" % x.name))
# Handle the multiprocessing pool worker threads (they don't have names beyond Thread-x)
elif x._target.__module__ == 'multiprocessing.pool':
thread_names.append((tid, "%s running multiprocessing pool worker thread" % x.name))
# Handle everything else including MainThread and deferred threads
else:
res = re.match(r'Thread-(\d+)', x.name)
tid = 0
if res:
tid = int(res.group(1))
thread_names.append((tid, x.name))
for x in sorted(thread_names, key=lambda k: k[0]):
send(x[1]) | [
"def",
"cmd",
"(",
"send",
",",
"*",
"_",
")",
":",
"thread_names",
"=",
"[",
"]",
"for",
"x",
"in",
"sorted",
"(",
"threading",
".",
"enumerate",
"(",
")",
",",
"key",
"=",
"lambda",
"k",
":",
"k",
".",
"name",
")",
":",
"res",
"=",
"re",
".",
"match",
"(",
"r'Thread-(\\d+$)'",
",",
"x",
".",
"name",
")",
"if",
"res",
":",
"tid",
"=",
"int",
"(",
"res",
".",
"group",
"(",
"1",
")",
")",
"# Handle the main server thread (permanently listed as _worker)",
"if",
"x",
".",
"_target",
".",
"__name__",
"==",
"'_worker'",
":",
"thread_names",
".",
"append",
"(",
"(",
"tid",
",",
"\"%s running server thread\"",
"%",
"x",
".",
"name",
")",
")",
"# Handle the multiprocessing pool worker threads (they don't have names beyond Thread-x)",
"elif",
"x",
".",
"_target",
".",
"__module__",
"==",
"'multiprocessing.pool'",
":",
"thread_names",
".",
"append",
"(",
"(",
"tid",
",",
"\"%s running multiprocessing pool worker thread\"",
"%",
"x",
".",
"name",
")",
")",
"# Handle everything else including MainThread and deferred threads",
"else",
":",
"res",
"=",
"re",
".",
"match",
"(",
"r'Thread-(\\d+)'",
",",
"x",
".",
"name",
")",
"tid",
"=",
"0",
"if",
"res",
":",
"tid",
"=",
"int",
"(",
"res",
".",
"group",
"(",
"1",
")",
")",
"thread_names",
".",
"append",
"(",
"(",
"tid",
",",
"x",
".",
"name",
")",
")",
"for",
"x",
"in",
"sorted",
"(",
"thread_names",
",",
"key",
"=",
"lambda",
"k",
":",
"k",
"[",
"0",
"]",
")",
":",
"send",
"(",
"x",
"[",
"1",
"]",
")"
]
| Enumerate threads.
Syntax: {command} | [
"Enumerate",
"threads",
"."
]
| aebe07be47141f61d7c180706bddfb707f19b2b5 | https://github.com/tjcsl/cslbot/blob/aebe07be47141f61d7c180706bddfb707f19b2b5/cslbot/commands/threads.py#L25-L50 | train |
marrow/util | marrow/util/pipe.py | pipe | def pipe():
"""Return the optimum pipe implementation for the capabilities of the active system."""
try:
from os import pipe
return pipe()
except:
pipe = Pipe()
return pipe.reader_fd, pipe.writer_fd | python | def pipe():
"""Return the optimum pipe implementation for the capabilities of the active system."""
try:
from os import pipe
return pipe()
except:
pipe = Pipe()
return pipe.reader_fd, pipe.writer_fd | [
"def",
"pipe",
"(",
")",
":",
"try",
":",
"from",
"os",
"import",
"pipe",
"return",
"pipe",
"(",
")",
"except",
":",
"pipe",
"=",
"Pipe",
"(",
")",
"return",
"pipe",
".",
"reader_fd",
",",
"pipe",
".",
"writer_fd"
]
| Return the optimum pipe implementation for the capabilities of the active system. | [
"Return",
"the",
"optimum",
"pipe",
"implementation",
"for",
"the",
"capabilities",
"of",
"the",
"active",
"system",
"."
]
| abb8163dbd1fa0692d42a44d129b12ae2b39cdf2 | https://github.com/marrow/util/blob/abb8163dbd1fa0692d42a44d129b12ae2b39cdf2/marrow/util/pipe.py#L63-L72 | train |
marrow/util | marrow/util/pipe.py | Pipe.read | def read(self):
"""Emulate a file descriptors read method"""
try:
return self.reader.recv(1)
except socket.error:
ex = exception().exception
if ex.args[0] == errno.EWOULDBLOCK:
raise IOError
raise | python | def read(self):
"""Emulate a file descriptors read method"""
try:
return self.reader.recv(1)
except socket.error:
ex = exception().exception
if ex.args[0] == errno.EWOULDBLOCK:
raise IOError
raise | [
"def",
"read",
"(",
"self",
")",
":",
"try",
":",
"return",
"self",
".",
"reader",
".",
"recv",
"(",
"1",
")",
"except",
"socket",
".",
"error",
":",
"ex",
"=",
"exception",
"(",
")",
".",
"exception",
"if",
"ex",
".",
"args",
"[",
"0",
"]",
"==",
"errno",
".",
"EWOULDBLOCK",
":",
"raise",
"IOError",
"raise"
]
| Emulate a file descriptors read method | [
"Emulate",
"a",
"file",
"descriptors",
"read",
"method"
]
| abb8163dbd1fa0692d42a44d129b12ae2b39cdf2 | https://github.com/marrow/util/blob/abb8163dbd1fa0692d42a44d129b12ae2b39cdf2/marrow/util/pipe.py#L48-L56 | train |
unt-libraries/edtf-validate | edtf_validate/valid_edtf.py | replace_all | def replace_all(text, dic):
"""Takes a string and dictionary. replaces all occurrences of i with j"""
for i, j in dic.iteritems():
text = text.replace(i, j)
return text | python | def replace_all(text, dic):
"""Takes a string and dictionary. replaces all occurrences of i with j"""
for i, j in dic.iteritems():
text = text.replace(i, j)
return text | [
"def",
"replace_all",
"(",
"text",
",",
"dic",
")",
":",
"for",
"i",
",",
"j",
"in",
"dic",
".",
"iteritems",
"(",
")",
":",
"text",
"=",
"text",
".",
"replace",
"(",
"i",
",",
"j",
")",
"return",
"text"
]
| Takes a string and dictionary. replaces all occurrences of i with j | [
"Takes",
"a",
"string",
"and",
"dictionary",
".",
"replaces",
"all",
"occurrences",
"of",
"i",
"with",
"j"
]
| d6d63141919a66aea4ff1c31fa0cb8ff744ef9d9 | https://github.com/unt-libraries/edtf-validate/blob/d6d63141919a66aea4ff1c31fa0cb8ff744ef9d9/edtf_validate/valid_edtf.py#L242-L247 | train |
unt-libraries/edtf-validate | edtf_validate/valid_edtf.py | replace_u_start_month | def replace_u_start_month(month):
"""Find the earliest legitimate month."""
month = month.lstrip('-')
if month == 'uu' or month == '0u':
return '01'
if month == 'u0':
return '10'
return month.replace('u', '0') | python | def replace_u_start_month(month):
"""Find the earliest legitimate month."""
month = month.lstrip('-')
if month == 'uu' or month == '0u':
return '01'
if month == 'u0':
return '10'
return month.replace('u', '0') | [
"def",
"replace_u_start_month",
"(",
"month",
")",
":",
"month",
"=",
"month",
".",
"lstrip",
"(",
"'-'",
")",
"if",
"month",
"==",
"'uu'",
"or",
"month",
"==",
"'0u'",
":",
"return",
"'01'",
"if",
"month",
"==",
"'u0'",
":",
"return",
"'10'",
"return",
"month",
".",
"replace",
"(",
"'u'",
",",
"'0'",
")"
]
| Find the earliest legitimate month. | [
"Find",
"the",
"earliest",
"legitimate",
"month",
"."
]
| d6d63141919a66aea4ff1c31fa0cb8ff744ef9d9 | https://github.com/unt-libraries/edtf-validate/blob/d6d63141919a66aea4ff1c31fa0cb8ff744ef9d9/edtf_validate/valid_edtf.py#L254-L261 | train |
unt-libraries/edtf-validate | edtf_validate/valid_edtf.py | replace_u_end_month | def replace_u_end_month(month):
"""Find the latest legitimate month."""
month = month.lstrip('-')
if month == 'uu' or month == '1u':
return '12'
if month == 'u0':
return '10'
if month == '0u':
return '09'
if month[1] in ['1', '2']:
# 'u1' or 'u2'
return month.replace('u', '1')
# Otherwise it should match r'u[3-9]'.
return month.replace('u', '0') | python | def replace_u_end_month(month):
"""Find the latest legitimate month."""
month = month.lstrip('-')
if month == 'uu' or month == '1u':
return '12'
if month == 'u0':
return '10'
if month == '0u':
return '09'
if month[1] in ['1', '2']:
# 'u1' or 'u2'
return month.replace('u', '1')
# Otherwise it should match r'u[3-9]'.
return month.replace('u', '0') | [
"def",
"replace_u_end_month",
"(",
"month",
")",
":",
"month",
"=",
"month",
".",
"lstrip",
"(",
"'-'",
")",
"if",
"month",
"==",
"'uu'",
"or",
"month",
"==",
"'1u'",
":",
"return",
"'12'",
"if",
"month",
"==",
"'u0'",
":",
"return",
"'10'",
"if",
"month",
"==",
"'0u'",
":",
"return",
"'09'",
"if",
"month",
"[",
"1",
"]",
"in",
"[",
"'1'",
",",
"'2'",
"]",
":",
"# 'u1' or 'u2'",
"return",
"month",
".",
"replace",
"(",
"'u'",
",",
"'1'",
")",
"# Otherwise it should match r'u[3-9]'.",
"return",
"month",
".",
"replace",
"(",
"'u'",
",",
"'0'",
")"
]
| Find the latest legitimate month. | [
"Find",
"the",
"latest",
"legitimate",
"month",
"."
]
| d6d63141919a66aea4ff1c31fa0cb8ff744ef9d9 | https://github.com/unt-libraries/edtf-validate/blob/d6d63141919a66aea4ff1c31fa0cb8ff744ef9d9/edtf_validate/valid_edtf.py#L264-L277 | train |
unt-libraries/edtf-validate | edtf_validate/valid_edtf.py | replace_u_start_day | def replace_u_start_day(day):
"""Find the earliest legitimate day."""
day = day.lstrip('-')
if day == 'uu' or day == '0u':
return '01'
if day == 'u0':
return '10'
return day.replace('u', '0') | python | def replace_u_start_day(day):
"""Find the earliest legitimate day."""
day = day.lstrip('-')
if day == 'uu' or day == '0u':
return '01'
if day == 'u0':
return '10'
return day.replace('u', '0') | [
"def",
"replace_u_start_day",
"(",
"day",
")",
":",
"day",
"=",
"day",
".",
"lstrip",
"(",
"'-'",
")",
"if",
"day",
"==",
"'uu'",
"or",
"day",
"==",
"'0u'",
":",
"return",
"'01'",
"if",
"day",
"==",
"'u0'",
":",
"return",
"'10'",
"return",
"day",
".",
"replace",
"(",
"'u'",
",",
"'0'",
")"
]
| Find the earliest legitimate day. | [
"Find",
"the",
"earliest",
"legitimate",
"day",
"."
]
| d6d63141919a66aea4ff1c31fa0cb8ff744ef9d9 | https://github.com/unt-libraries/edtf-validate/blob/d6d63141919a66aea4ff1c31fa0cb8ff744ef9d9/edtf_validate/valid_edtf.py#L280-L287 | train |
unt-libraries/edtf-validate | edtf_validate/valid_edtf.py | replace_u_end_day | def replace_u_end_day(day, year, month):
"""Find the latest legitimate day."""
day = day.lstrip('-')
year = int(year)
month = int(month.lstrip('-'))
if day == 'uu' or day == '3u':
# Use the last day of the month for a given year/month.
return str(calendar.monthrange(year, month)[1])
if day == '0u' or day == '1u':
return day.replace('u', '9')
if day == '2u' or day == 'u9':
if month != '02' or calendar.isleap(year):
return '29'
elif day == '2u':
# It is Feburary and not a leap year.
return '28'
else:
# It is February, not a leap year, day ends in 9.
return '19'
# 'u2' 'u3' 'u4' 'u5' 'u6' 'u7' 'u8'
if 1 < int(day[1]) < 9:
return day.replace('u', '2')
# 'u0' 'u1'
if day == 'u1':
if calendar.monthrange(year, month)[1] == 31:
# See if the month has a 31st.
return '31'
else:
return '21'
if day == 'u0':
if calendar.monthrange(year, month)[1] >= 30:
return '30'
else:
return '20' | python | def replace_u_end_day(day, year, month):
"""Find the latest legitimate day."""
day = day.lstrip('-')
year = int(year)
month = int(month.lstrip('-'))
if day == 'uu' or day == '3u':
# Use the last day of the month for a given year/month.
return str(calendar.monthrange(year, month)[1])
if day == '0u' or day == '1u':
return day.replace('u', '9')
if day == '2u' or day == 'u9':
if month != '02' or calendar.isleap(year):
return '29'
elif day == '2u':
# It is Feburary and not a leap year.
return '28'
else:
# It is February, not a leap year, day ends in 9.
return '19'
# 'u2' 'u3' 'u4' 'u5' 'u6' 'u7' 'u8'
if 1 < int(day[1]) < 9:
return day.replace('u', '2')
# 'u0' 'u1'
if day == 'u1':
if calendar.monthrange(year, month)[1] == 31:
# See if the month has a 31st.
return '31'
else:
return '21'
if day == 'u0':
if calendar.monthrange(year, month)[1] >= 30:
return '30'
else:
return '20' | [
"def",
"replace_u_end_day",
"(",
"day",
",",
"year",
",",
"month",
")",
":",
"day",
"=",
"day",
".",
"lstrip",
"(",
"'-'",
")",
"year",
"=",
"int",
"(",
"year",
")",
"month",
"=",
"int",
"(",
"month",
".",
"lstrip",
"(",
"'-'",
")",
")",
"if",
"day",
"==",
"'uu'",
"or",
"day",
"==",
"'3u'",
":",
"# Use the last day of the month for a given year/month.",
"return",
"str",
"(",
"calendar",
".",
"monthrange",
"(",
"year",
",",
"month",
")",
"[",
"1",
"]",
")",
"if",
"day",
"==",
"'0u'",
"or",
"day",
"==",
"'1u'",
":",
"return",
"day",
".",
"replace",
"(",
"'u'",
",",
"'9'",
")",
"if",
"day",
"==",
"'2u'",
"or",
"day",
"==",
"'u9'",
":",
"if",
"month",
"!=",
"'02'",
"or",
"calendar",
".",
"isleap",
"(",
"year",
")",
":",
"return",
"'29'",
"elif",
"day",
"==",
"'2u'",
":",
"# It is Feburary and not a leap year.",
"return",
"'28'",
"else",
":",
"# It is February, not a leap year, day ends in 9.",
"return",
"'19'",
"# 'u2' 'u3' 'u4' 'u5' 'u6' 'u7' 'u8'",
"if",
"1",
"<",
"int",
"(",
"day",
"[",
"1",
"]",
")",
"<",
"9",
":",
"return",
"day",
".",
"replace",
"(",
"'u'",
",",
"'2'",
")",
"# 'u0' 'u1'",
"if",
"day",
"==",
"'u1'",
":",
"if",
"calendar",
".",
"monthrange",
"(",
"year",
",",
"month",
")",
"[",
"1",
"]",
"==",
"31",
":",
"# See if the month has a 31st.",
"return",
"'31'",
"else",
":",
"return",
"'21'",
"if",
"day",
"==",
"'u0'",
":",
"if",
"calendar",
".",
"monthrange",
"(",
"year",
",",
"month",
")",
"[",
"1",
"]",
">=",
"30",
":",
"return",
"'30'",
"else",
":",
"return",
"'20'"
]
| Find the latest legitimate day. | [
"Find",
"the",
"latest",
"legitimate",
"day",
"."
]
| d6d63141919a66aea4ff1c31fa0cb8ff744ef9d9 | https://github.com/unt-libraries/edtf-validate/blob/d6d63141919a66aea4ff1c31fa0cb8ff744ef9d9/edtf_validate/valid_edtf.py#L290-L323 | train |
unt-libraries/edtf-validate | edtf_validate/valid_edtf.py | replace_u | def replace_u(matchobj):
"""Break the interval into parts, and replace 'u's.
pieces - [pos/neg, start_year, start_month, start_day,
pos/neg, end_year, end_month, end_day]
"""
pieces = list(matchobj.groups(''))
# Replace "u"s in start and end years.
if 'u' in pieces[1]:
pieces[1] = pieces[1].replace('u', '0')
if 'u' in pieces[5]:
pieces[5] = pieces[5].replace('u', '9')
# Replace "u"s in start month.
if 'u' in pieces[2]:
pieces[2] = '-' + replace_u_start_month(pieces[2])
# Replace "u"s in end month.
if 'u' in pieces[6]:
pieces[6] = '-' + replace_u_end_month(pieces[6])
# Replace "u"s in start day.
if 'u' in pieces[3]:
pieces[3] = '-' + replace_u_start_day(pieces[3])
# Replace "u"s in end day.
if 'u' in pieces[7]:
pieces[7] = '-' + replace_u_end_day(pieces[7], year=pieces[5],
month=pieces[6])
return ''.join((''.join(pieces[:4]), '/', ''.join(pieces[4:]))) | python | def replace_u(matchobj):
"""Break the interval into parts, and replace 'u's.
pieces - [pos/neg, start_year, start_month, start_day,
pos/neg, end_year, end_month, end_day]
"""
pieces = list(matchobj.groups(''))
# Replace "u"s in start and end years.
if 'u' in pieces[1]:
pieces[1] = pieces[1].replace('u', '0')
if 'u' in pieces[5]:
pieces[5] = pieces[5].replace('u', '9')
# Replace "u"s in start month.
if 'u' in pieces[2]:
pieces[2] = '-' + replace_u_start_month(pieces[2])
# Replace "u"s in end month.
if 'u' in pieces[6]:
pieces[6] = '-' + replace_u_end_month(pieces[6])
# Replace "u"s in start day.
if 'u' in pieces[3]:
pieces[3] = '-' + replace_u_start_day(pieces[3])
# Replace "u"s in end day.
if 'u' in pieces[7]:
pieces[7] = '-' + replace_u_end_day(pieces[7], year=pieces[5],
month=pieces[6])
return ''.join((''.join(pieces[:4]), '/', ''.join(pieces[4:]))) | [
"def",
"replace_u",
"(",
"matchobj",
")",
":",
"pieces",
"=",
"list",
"(",
"matchobj",
".",
"groups",
"(",
"''",
")",
")",
"# Replace \"u\"s in start and end years.",
"if",
"'u'",
"in",
"pieces",
"[",
"1",
"]",
":",
"pieces",
"[",
"1",
"]",
"=",
"pieces",
"[",
"1",
"]",
".",
"replace",
"(",
"'u'",
",",
"'0'",
")",
"if",
"'u'",
"in",
"pieces",
"[",
"5",
"]",
":",
"pieces",
"[",
"5",
"]",
"=",
"pieces",
"[",
"5",
"]",
".",
"replace",
"(",
"'u'",
",",
"'9'",
")",
"# Replace \"u\"s in start month.",
"if",
"'u'",
"in",
"pieces",
"[",
"2",
"]",
":",
"pieces",
"[",
"2",
"]",
"=",
"'-'",
"+",
"replace_u_start_month",
"(",
"pieces",
"[",
"2",
"]",
")",
"# Replace \"u\"s in end month.",
"if",
"'u'",
"in",
"pieces",
"[",
"6",
"]",
":",
"pieces",
"[",
"6",
"]",
"=",
"'-'",
"+",
"replace_u_end_month",
"(",
"pieces",
"[",
"6",
"]",
")",
"# Replace \"u\"s in start day.",
"if",
"'u'",
"in",
"pieces",
"[",
"3",
"]",
":",
"pieces",
"[",
"3",
"]",
"=",
"'-'",
"+",
"replace_u_start_day",
"(",
"pieces",
"[",
"3",
"]",
")",
"# Replace \"u\"s in end day.",
"if",
"'u'",
"in",
"pieces",
"[",
"7",
"]",
":",
"pieces",
"[",
"7",
"]",
"=",
"'-'",
"+",
"replace_u_end_day",
"(",
"pieces",
"[",
"7",
"]",
",",
"year",
"=",
"pieces",
"[",
"5",
"]",
",",
"month",
"=",
"pieces",
"[",
"6",
"]",
")",
"return",
"''",
".",
"join",
"(",
"(",
"''",
".",
"join",
"(",
"pieces",
"[",
":",
"4",
"]",
")",
",",
"'/'",
",",
"''",
".",
"join",
"(",
"pieces",
"[",
"4",
":",
"]",
")",
")",
")"
]
| Break the interval into parts, and replace 'u's.
pieces - [pos/neg, start_year, start_month, start_day,
pos/neg, end_year, end_month, end_day] | [
"Break",
"the",
"interval",
"into",
"parts",
"and",
"replace",
"u",
"s",
"."
]
| d6d63141919a66aea4ff1c31fa0cb8ff744ef9d9 | https://github.com/unt-libraries/edtf-validate/blob/d6d63141919a66aea4ff1c31fa0cb8ff744ef9d9/edtf_validate/valid_edtf.py#L326-L351 | train |
unt-libraries/edtf-validate | edtf_validate/valid_edtf.py | zero_year_special_case | def zero_year_special_case(from_date, to_date, start, end):
"""strptime does not resolve a 0000 year, we must handle this."""
if start == 'pos' and end == 'pos':
# always interval from earlier to later
if from_date.startswith('0000') and not to_date.startswith('0000'):
return True
# always interval from later to earlier
if not from_date.startswith('0000') and to_date.startswith('0000'):
return False
# an interval from 0000-MM-DD/0000-MM-DD ??? PARSE !!!
if from_date.startswith('0000') and to_date.startswith('0000'):
# fill from date assuming first subsequent date object if missing
# missing m+d, assume jan 1
if len(from_date) == 4:
fm, fd = 1, 1
# missing d, assume the 1st
elif len(from_date) == 7:
fm, fd = int(from_date[5:7]), 1
# not missing any date objects
elif len(from_date) == 10:
fm, fd = int(from_date[5:7]), int(from_date[8:10])
# fill to date assuming first subsequent date object if missing
# missing m+d, assume jan 1
if len(to_date) == 4:
tm, td = 1, 1
# missing d, assume the 1st
elif len(to_date) == 7:
tm, td = int(to_date[5:7]), 1
# not missing any date objects
elif len(to_date) == 10:
tm, td = int(to_date[5:7]), int(to_date[8:10])
# equality check
if from_date == to_date:
return True
# compare the dates
if fm <= tm:
if fd <= td:
return True
else:
return False
else:
return False
# these cases are always one way or the other
# "-0000" is an invalid edtf
elif start == 'neg' and end == 'neg':
return False
# False unless start is not "0000"
elif start == 'neg' and end == 'pos':
if from_date.startswith("0000"):
return False
else:
return True | python | def zero_year_special_case(from_date, to_date, start, end):
"""strptime does not resolve a 0000 year, we must handle this."""
if start == 'pos' and end == 'pos':
# always interval from earlier to later
if from_date.startswith('0000') and not to_date.startswith('0000'):
return True
# always interval from later to earlier
if not from_date.startswith('0000') and to_date.startswith('0000'):
return False
# an interval from 0000-MM-DD/0000-MM-DD ??? PARSE !!!
if from_date.startswith('0000') and to_date.startswith('0000'):
# fill from date assuming first subsequent date object if missing
# missing m+d, assume jan 1
if len(from_date) == 4:
fm, fd = 1, 1
# missing d, assume the 1st
elif len(from_date) == 7:
fm, fd = int(from_date[5:7]), 1
# not missing any date objects
elif len(from_date) == 10:
fm, fd = int(from_date[5:7]), int(from_date[8:10])
# fill to date assuming first subsequent date object if missing
# missing m+d, assume jan 1
if len(to_date) == 4:
tm, td = 1, 1
# missing d, assume the 1st
elif len(to_date) == 7:
tm, td = int(to_date[5:7]), 1
# not missing any date objects
elif len(to_date) == 10:
tm, td = int(to_date[5:7]), int(to_date[8:10])
# equality check
if from_date == to_date:
return True
# compare the dates
if fm <= tm:
if fd <= td:
return True
else:
return False
else:
return False
# these cases are always one way or the other
# "-0000" is an invalid edtf
elif start == 'neg' and end == 'neg':
return False
# False unless start is not "0000"
elif start == 'neg' and end == 'pos':
if from_date.startswith("0000"):
return False
else:
return True | [
"def",
"zero_year_special_case",
"(",
"from_date",
",",
"to_date",
",",
"start",
",",
"end",
")",
":",
"if",
"start",
"==",
"'pos'",
"and",
"end",
"==",
"'pos'",
":",
"# always interval from earlier to later",
"if",
"from_date",
".",
"startswith",
"(",
"'0000'",
")",
"and",
"not",
"to_date",
".",
"startswith",
"(",
"'0000'",
")",
":",
"return",
"True",
"# always interval from later to earlier",
"if",
"not",
"from_date",
".",
"startswith",
"(",
"'0000'",
")",
"and",
"to_date",
".",
"startswith",
"(",
"'0000'",
")",
":",
"return",
"False",
"# an interval from 0000-MM-DD/0000-MM-DD ??? PARSE !!!",
"if",
"from_date",
".",
"startswith",
"(",
"'0000'",
")",
"and",
"to_date",
".",
"startswith",
"(",
"'0000'",
")",
":",
"# fill from date assuming first subsequent date object if missing",
"# missing m+d, assume jan 1",
"if",
"len",
"(",
"from_date",
")",
"==",
"4",
":",
"fm",
",",
"fd",
"=",
"1",
",",
"1",
"# missing d, assume the 1st",
"elif",
"len",
"(",
"from_date",
")",
"==",
"7",
":",
"fm",
",",
"fd",
"=",
"int",
"(",
"from_date",
"[",
"5",
":",
"7",
"]",
")",
",",
"1",
"# not missing any date objects",
"elif",
"len",
"(",
"from_date",
")",
"==",
"10",
":",
"fm",
",",
"fd",
"=",
"int",
"(",
"from_date",
"[",
"5",
":",
"7",
"]",
")",
",",
"int",
"(",
"from_date",
"[",
"8",
":",
"10",
"]",
")",
"# fill to date assuming first subsequent date object if missing",
"# missing m+d, assume jan 1",
"if",
"len",
"(",
"to_date",
")",
"==",
"4",
":",
"tm",
",",
"td",
"=",
"1",
",",
"1",
"# missing d, assume the 1st",
"elif",
"len",
"(",
"to_date",
")",
"==",
"7",
":",
"tm",
",",
"td",
"=",
"int",
"(",
"to_date",
"[",
"5",
":",
"7",
"]",
")",
",",
"1",
"# not missing any date objects",
"elif",
"len",
"(",
"to_date",
")",
"==",
"10",
":",
"tm",
",",
"td",
"=",
"int",
"(",
"to_date",
"[",
"5",
":",
"7",
"]",
")",
",",
"int",
"(",
"to_date",
"[",
"8",
":",
"10",
"]",
")",
"# equality check",
"if",
"from_date",
"==",
"to_date",
":",
"return",
"True",
"# compare the dates",
"if",
"fm",
"<=",
"tm",
":",
"if",
"fd",
"<=",
"td",
":",
"return",
"True",
"else",
":",
"return",
"False",
"else",
":",
"return",
"False",
"# these cases are always one way or the other",
"# \"-0000\" is an invalid edtf",
"elif",
"start",
"==",
"'neg'",
"and",
"end",
"==",
"'neg'",
":",
"return",
"False",
"# False unless start is not \"0000\"",
"elif",
"start",
"==",
"'neg'",
"and",
"end",
"==",
"'pos'",
":",
"if",
"from_date",
".",
"startswith",
"(",
"\"0000\"",
")",
":",
"return",
"False",
"else",
":",
"return",
"True"
]
| strptime does not resolve a 0000 year, we must handle this. | [
"strptime",
"does",
"not",
"resolve",
"a",
"0000",
"year",
"we",
"must",
"handle",
"this",
"."
]
| d6d63141919a66aea4ff1c31fa0cb8ff744ef9d9 | https://github.com/unt-libraries/edtf-validate/blob/d6d63141919a66aea4ff1c31fa0cb8ff744ef9d9/edtf_validate/valid_edtf.py#L354-L406 | train |
unt-libraries/edtf-validate | edtf_validate/valid_edtf.py | is_valid_interval | def is_valid_interval(edtf_candidate):
"""Test to see if the edtf candidate is a valid interval"""
# resolve interval into from / to datetime objects
from_date = None
to_date = None
# initialize interval flags for special cases, assume positive
end, start = 'pos', 'pos'
if edtf_candidate.count('/') == 1:
# replace all 'problem' cases (unspecified, 0000 date, ?~, -, y)
# break the interval into two date strings
edtf_candidate = replace_all(edtf_candidate, interval_replacements)
edtf_candidate = re.sub(U_PATTERN, replace_u, edtf_candidate)
parts = edtf_candidate.split('/')
# set flag for negative start date
if parts[0].startswith("-"):
start = 'neg'
parts[0] = parts[0][1:]
# set flag for negative end date
if parts[1].startswith("-"):
end = 'neg'
parts[1] = parts[1][1:]
# if starts positive and ends negative, that's always False
if start == 'pos' and end == 'neg':
return False
# handle special case of 0000 year
if parts[0].startswith("0000") or parts[1].startswith("0000"):
return zero_year_special_case(parts[0], parts[1], start, end)
# 2 '-' characters means we are matching year-month-day
if parts[0].count("-") == 2:
from_date = datetime.datetime.strptime(parts[0], "%Y-%m-%d")
if parts[1].count("-") == 2:
to_date = datetime.datetime.strptime(parts[1], "%Y-%m-%d")
# 1 '-' character means we are match year-month
if parts[0].count("-") == 1:
from_date = datetime.datetime.strptime(parts[0], "%Y-%m")
if parts[1].count("-") == 1:
to_date = datetime.datetime.strptime(parts[1], "%Y-%m")
# zero '-' characters means we are matching a year
if parts[0].count("-") == 0:
# if from_date is unknown, we can assume the lowest possible date
if parts[0] == 'unknown':
from_date = datetime.datetime.strptime("0001", "%Y")
else:
from_date = datetime.datetime.strptime(parts[0], "%Y")
if parts[1].count("-") == 0:
# when the to_date is open and the from_date is valid, it's valid
if parts[1] == 'open' or parts[1] == 'unknown':
to_date = 'open'
else:
to_date = datetime.datetime.strptime(parts[1], "%Y")
# if it starts negative and ends positive, that's always True
if start == 'neg' and end == 'pos':
return True
# if start and end are negative, the from_date must be >= to_date
elif start == 'neg' and end == 'neg':
if from_date >= to_date and from_date and to_date:
return True
# if the to_date is unknown or open, it could be any date, therefore
elif (
parts[1] == 'unknown' or
parts[1] == 'open' or
parts[0] == 'unknown'
):
return True
# if start and end are positive, the from_date must be <= to_date
elif start == 'pos' and end == 'pos':
if from_date <= to_date and from_date and to_date:
return True
else:
return False
else:
return False | python | def is_valid_interval(edtf_candidate):
"""Test to see if the edtf candidate is a valid interval"""
# resolve interval into from / to datetime objects
from_date = None
to_date = None
# initialize interval flags for special cases, assume positive
end, start = 'pos', 'pos'
if edtf_candidate.count('/') == 1:
# replace all 'problem' cases (unspecified, 0000 date, ?~, -, y)
# break the interval into two date strings
edtf_candidate = replace_all(edtf_candidate, interval_replacements)
edtf_candidate = re.sub(U_PATTERN, replace_u, edtf_candidate)
parts = edtf_candidate.split('/')
# set flag for negative start date
if parts[0].startswith("-"):
start = 'neg'
parts[0] = parts[0][1:]
# set flag for negative end date
if parts[1].startswith("-"):
end = 'neg'
parts[1] = parts[1][1:]
# if starts positive and ends negative, that's always False
if start == 'pos' and end == 'neg':
return False
# handle special case of 0000 year
if parts[0].startswith("0000") or parts[1].startswith("0000"):
return zero_year_special_case(parts[0], parts[1], start, end)
# 2 '-' characters means we are matching year-month-day
if parts[0].count("-") == 2:
from_date = datetime.datetime.strptime(parts[0], "%Y-%m-%d")
if parts[1].count("-") == 2:
to_date = datetime.datetime.strptime(parts[1], "%Y-%m-%d")
# 1 '-' character means we are match year-month
if parts[0].count("-") == 1:
from_date = datetime.datetime.strptime(parts[0], "%Y-%m")
if parts[1].count("-") == 1:
to_date = datetime.datetime.strptime(parts[1], "%Y-%m")
# zero '-' characters means we are matching a year
if parts[0].count("-") == 0:
# if from_date is unknown, we can assume the lowest possible date
if parts[0] == 'unknown':
from_date = datetime.datetime.strptime("0001", "%Y")
else:
from_date = datetime.datetime.strptime(parts[0], "%Y")
if parts[1].count("-") == 0:
# when the to_date is open and the from_date is valid, it's valid
if parts[1] == 'open' or parts[1] == 'unknown':
to_date = 'open'
else:
to_date = datetime.datetime.strptime(parts[1], "%Y")
# if it starts negative and ends positive, that's always True
if start == 'neg' and end == 'pos':
return True
# if start and end are negative, the from_date must be >= to_date
elif start == 'neg' and end == 'neg':
if from_date >= to_date and from_date and to_date:
return True
# if the to_date is unknown or open, it could be any date, therefore
elif (
parts[1] == 'unknown' or
parts[1] == 'open' or
parts[0] == 'unknown'
):
return True
# if start and end are positive, the from_date must be <= to_date
elif start == 'pos' and end == 'pos':
if from_date <= to_date and from_date and to_date:
return True
else:
return False
else:
return False | [
"def",
"is_valid_interval",
"(",
"edtf_candidate",
")",
":",
"# resolve interval into from / to datetime objects",
"from_date",
"=",
"None",
"to_date",
"=",
"None",
"# initialize interval flags for special cases, assume positive",
"end",
",",
"start",
"=",
"'pos'",
",",
"'pos'",
"if",
"edtf_candidate",
".",
"count",
"(",
"'/'",
")",
"==",
"1",
":",
"# replace all 'problem' cases (unspecified, 0000 date, ?~, -, y)",
"# break the interval into two date strings",
"edtf_candidate",
"=",
"replace_all",
"(",
"edtf_candidate",
",",
"interval_replacements",
")",
"edtf_candidate",
"=",
"re",
".",
"sub",
"(",
"U_PATTERN",
",",
"replace_u",
",",
"edtf_candidate",
")",
"parts",
"=",
"edtf_candidate",
".",
"split",
"(",
"'/'",
")",
"# set flag for negative start date",
"if",
"parts",
"[",
"0",
"]",
".",
"startswith",
"(",
"\"-\"",
")",
":",
"start",
"=",
"'neg'",
"parts",
"[",
"0",
"]",
"=",
"parts",
"[",
"0",
"]",
"[",
"1",
":",
"]",
"# set flag for negative end date",
"if",
"parts",
"[",
"1",
"]",
".",
"startswith",
"(",
"\"-\"",
")",
":",
"end",
"=",
"'neg'",
"parts",
"[",
"1",
"]",
"=",
"parts",
"[",
"1",
"]",
"[",
"1",
":",
"]",
"# if starts positive and ends negative, that's always False",
"if",
"start",
"==",
"'pos'",
"and",
"end",
"==",
"'neg'",
":",
"return",
"False",
"# handle special case of 0000 year",
"if",
"parts",
"[",
"0",
"]",
".",
"startswith",
"(",
"\"0000\"",
")",
"or",
"parts",
"[",
"1",
"]",
".",
"startswith",
"(",
"\"0000\"",
")",
":",
"return",
"zero_year_special_case",
"(",
"parts",
"[",
"0",
"]",
",",
"parts",
"[",
"1",
"]",
",",
"start",
",",
"end",
")",
"# 2 '-' characters means we are matching year-month-day",
"if",
"parts",
"[",
"0",
"]",
".",
"count",
"(",
"\"-\"",
")",
"==",
"2",
":",
"from_date",
"=",
"datetime",
".",
"datetime",
".",
"strptime",
"(",
"parts",
"[",
"0",
"]",
",",
"\"%Y-%m-%d\"",
")",
"if",
"parts",
"[",
"1",
"]",
".",
"count",
"(",
"\"-\"",
")",
"==",
"2",
":",
"to_date",
"=",
"datetime",
".",
"datetime",
".",
"strptime",
"(",
"parts",
"[",
"1",
"]",
",",
"\"%Y-%m-%d\"",
")",
"# 1 '-' character means we are match year-month",
"if",
"parts",
"[",
"0",
"]",
".",
"count",
"(",
"\"-\"",
")",
"==",
"1",
":",
"from_date",
"=",
"datetime",
".",
"datetime",
".",
"strptime",
"(",
"parts",
"[",
"0",
"]",
",",
"\"%Y-%m\"",
")",
"if",
"parts",
"[",
"1",
"]",
".",
"count",
"(",
"\"-\"",
")",
"==",
"1",
":",
"to_date",
"=",
"datetime",
".",
"datetime",
".",
"strptime",
"(",
"parts",
"[",
"1",
"]",
",",
"\"%Y-%m\"",
")",
"# zero '-' characters means we are matching a year",
"if",
"parts",
"[",
"0",
"]",
".",
"count",
"(",
"\"-\"",
")",
"==",
"0",
":",
"# if from_date is unknown, we can assume the lowest possible date",
"if",
"parts",
"[",
"0",
"]",
"==",
"'unknown'",
":",
"from_date",
"=",
"datetime",
".",
"datetime",
".",
"strptime",
"(",
"\"0001\"",
",",
"\"%Y\"",
")",
"else",
":",
"from_date",
"=",
"datetime",
".",
"datetime",
".",
"strptime",
"(",
"parts",
"[",
"0",
"]",
",",
"\"%Y\"",
")",
"if",
"parts",
"[",
"1",
"]",
".",
"count",
"(",
"\"-\"",
")",
"==",
"0",
":",
"# when the to_date is open and the from_date is valid, it's valid",
"if",
"parts",
"[",
"1",
"]",
"==",
"'open'",
"or",
"parts",
"[",
"1",
"]",
"==",
"'unknown'",
":",
"to_date",
"=",
"'open'",
"else",
":",
"to_date",
"=",
"datetime",
".",
"datetime",
".",
"strptime",
"(",
"parts",
"[",
"1",
"]",
",",
"\"%Y\"",
")",
"# if it starts negative and ends positive, that's always True",
"if",
"start",
"==",
"'neg'",
"and",
"end",
"==",
"'pos'",
":",
"return",
"True",
"# if start and end are negative, the from_date must be >= to_date",
"elif",
"start",
"==",
"'neg'",
"and",
"end",
"==",
"'neg'",
":",
"if",
"from_date",
">=",
"to_date",
"and",
"from_date",
"and",
"to_date",
":",
"return",
"True",
"# if the to_date is unknown or open, it could be any date, therefore",
"elif",
"(",
"parts",
"[",
"1",
"]",
"==",
"'unknown'",
"or",
"parts",
"[",
"1",
"]",
"==",
"'open'",
"or",
"parts",
"[",
"0",
"]",
"==",
"'unknown'",
")",
":",
"return",
"True",
"# if start and end are positive, the from_date must be <= to_date",
"elif",
"start",
"==",
"'pos'",
"and",
"end",
"==",
"'pos'",
":",
"if",
"from_date",
"<=",
"to_date",
"and",
"from_date",
"and",
"to_date",
":",
"return",
"True",
"else",
":",
"return",
"False",
"else",
":",
"return",
"False"
]
| Test to see if the edtf candidate is a valid interval | [
"Test",
"to",
"see",
"if",
"the",
"edtf",
"candidate",
"is",
"a",
"valid",
"interval"
]
| d6d63141919a66aea4ff1c31fa0cb8ff744ef9d9 | https://github.com/unt-libraries/edtf-validate/blob/d6d63141919a66aea4ff1c31fa0cb8ff744ef9d9/edtf_validate/valid_edtf.py#L409-L481 | train |
unt-libraries/edtf-validate | edtf_validate/valid_edtf.py | isLevel2 | def isLevel2(edtf_candidate):
"""Checks to see if the date is level 2 valid"""
if "[" in edtf_candidate or "{" in edtf_candidate:
result = edtf_candidate == level2Expression
elif " " in edtf_candidate:
result = False
else:
result = edtf_candidate == level2Expression
return result | python | def isLevel2(edtf_candidate):
"""Checks to see if the date is level 2 valid"""
if "[" in edtf_candidate or "{" in edtf_candidate:
result = edtf_candidate == level2Expression
elif " " in edtf_candidate:
result = False
else:
result = edtf_candidate == level2Expression
return result | [
"def",
"isLevel2",
"(",
"edtf_candidate",
")",
":",
"if",
"\"[\"",
"in",
"edtf_candidate",
"or",
"\"{\"",
"in",
"edtf_candidate",
":",
"result",
"=",
"edtf_candidate",
"==",
"level2Expression",
"elif",
"\" \"",
"in",
"edtf_candidate",
":",
"result",
"=",
"False",
"else",
":",
"result",
"=",
"edtf_candidate",
"==",
"level2Expression",
"return",
"result"
]
| Checks to see if the date is level 2 valid | [
"Checks",
"to",
"see",
"if",
"the",
"date",
"is",
"level",
"2",
"valid"
]
| d6d63141919a66aea4ff1c31fa0cb8ff744ef9d9 | https://github.com/unt-libraries/edtf-validate/blob/d6d63141919a66aea4ff1c31fa0cb8ff744ef9d9/edtf_validate/valid_edtf.py#L504-L513 | train |
unt-libraries/edtf-validate | edtf_validate/valid_edtf.py | is_valid | def is_valid(edtf_candidate):
"""isValid takes a candidate date and returns if it is valid or not"""
if (
isLevel0(edtf_candidate) or
isLevel1(edtf_candidate) or
isLevel2(edtf_candidate)
):
if '/' in edtf_candidate:
return is_valid_interval(edtf_candidate)
else:
return True
else:
return False | python | def is_valid(edtf_candidate):
"""isValid takes a candidate date and returns if it is valid or not"""
if (
isLevel0(edtf_candidate) or
isLevel1(edtf_candidate) or
isLevel2(edtf_candidate)
):
if '/' in edtf_candidate:
return is_valid_interval(edtf_candidate)
else:
return True
else:
return False | [
"def",
"is_valid",
"(",
"edtf_candidate",
")",
":",
"if",
"(",
"isLevel0",
"(",
"edtf_candidate",
")",
"or",
"isLevel1",
"(",
"edtf_candidate",
")",
"or",
"isLevel2",
"(",
"edtf_candidate",
")",
")",
":",
"if",
"'/'",
"in",
"edtf_candidate",
":",
"return",
"is_valid_interval",
"(",
"edtf_candidate",
")",
"else",
":",
"return",
"True",
"else",
":",
"return",
"False"
]
| isValid takes a candidate date and returns if it is valid or not | [
"isValid",
"takes",
"a",
"candidate",
"date",
"and",
"returns",
"if",
"it",
"is",
"valid",
"or",
"not"
]
| d6d63141919a66aea4ff1c31fa0cb8ff744ef9d9 | https://github.com/unt-libraries/edtf-validate/blob/d6d63141919a66aea4ff1c31fa0cb8ff744ef9d9/edtf_validate/valid_edtf.py#L516-L529 | train |
Xion/taipan | taipan/objective/classes.py | is_direct_subclass | def is_direct_subclass(class_, of):
"""Check whether given class is a direct subclass of the other.
:param class_: Class to check
:param of: Superclass to check against
:return: Boolean result of the test
.. versionadded:: 0.0.4
"""
ensure_class(class_)
ensure_class(of) # TODO(xion): support predicates in addition to classes
return of in class_.__bases__ | python | def is_direct_subclass(class_, of):
"""Check whether given class is a direct subclass of the other.
:param class_: Class to check
:param of: Superclass to check against
:return: Boolean result of the test
.. versionadded:: 0.0.4
"""
ensure_class(class_)
ensure_class(of) # TODO(xion): support predicates in addition to classes
return of in class_.__bases__ | [
"def",
"is_direct_subclass",
"(",
"class_",
",",
"of",
")",
":",
"ensure_class",
"(",
"class_",
")",
"ensure_class",
"(",
"of",
")",
"# TODO(xion): support predicates in addition to classes",
"return",
"of",
"in",
"class_",
".",
"__bases__"
]
| Check whether given class is a direct subclass of the other.
:param class_: Class to check
:param of: Superclass to check against
:return: Boolean result of the test
.. versionadded:: 0.0.4 | [
"Check",
"whether",
"given",
"class",
"is",
"a",
"direct",
"subclass",
"of",
"the",
"other",
"."
]
| f333f0287c8bd0915182c7d5308e5f05ef0cca78 | https://github.com/Xion/taipan/blob/f333f0287c8bd0915182c7d5308e5f05ef0cca78/taipan/objective/classes.py#L41-L54 | train |
Xion/taipan | taipan/objective/classes.py | ensure_direct_subclass | def ensure_direct_subclass(class_, of):
"""Check whether given class is a direct subclass of another.
:param class_: Class to check
:param of: Superclass to check against
:return: ``class_``, if the check succeeds
:raise TypeError: When the check fails
.. versionadded:: 0.0.4
"""
if not is_direct_subclass(class_, of):
raise TypeError("expected a direct subclass of %r, got %s instead" % (
of, class_.__name__))
return class_ | python | def ensure_direct_subclass(class_, of):
"""Check whether given class is a direct subclass of another.
:param class_: Class to check
:param of: Superclass to check against
:return: ``class_``, if the check succeeds
:raise TypeError: When the check fails
.. versionadded:: 0.0.4
"""
if not is_direct_subclass(class_, of):
raise TypeError("expected a direct subclass of %r, got %s instead" % (
of, class_.__name__))
return class_ | [
"def",
"ensure_direct_subclass",
"(",
"class_",
",",
"of",
")",
":",
"if",
"not",
"is_direct_subclass",
"(",
"class_",
",",
"of",
")",
":",
"raise",
"TypeError",
"(",
"\"expected a direct subclass of %r, got %s instead\"",
"%",
"(",
"of",
",",
"class_",
".",
"__name__",
")",
")",
"return",
"class_"
]
| Check whether given class is a direct subclass of another.
:param class_: Class to check
:param of: Superclass to check against
:return: ``class_``, if the check succeeds
:raise TypeError: When the check fails
.. versionadded:: 0.0.4 | [
"Check",
"whether",
"given",
"class",
"is",
"a",
"direct",
"subclass",
"of",
"another",
"."
]
| f333f0287c8bd0915182c7d5308e5f05ef0cca78 | https://github.com/Xion/taipan/blob/f333f0287c8bd0915182c7d5308e5f05ef0cca78/taipan/objective/classes.py#L57-L71 | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.