repository_name stringlengths 5 67 | func_path_in_repository stringlengths 4 234 | func_name stringlengths 0 314 | whole_func_string stringlengths 52 3.87M | language stringclasses 6
values | func_code_string stringlengths 52 3.87M | func_code_tokens listlengths 15 672k | func_documentation_string stringlengths 1 47.2k | func_documentation_tokens listlengths 1 3.92k | split_name stringclasses 1
value | func_code_url stringlengths 85 339 |
|---|---|---|---|---|---|---|---|---|---|---|
avalente/appmetrics | appmetrics/statistics.py | pstdev | def pstdev(data, mu=None):
"""Return the square root of the population variance.
See ``pvariance`` for arguments and other details.
"""
var = pvariance(data, mu)
try:
return var.sqrt()
except AttributeError:
return math.sqrt(var) | python | def pstdev(data, mu=None):
"""Return the square root of the population variance.
See ``pvariance`` for arguments and other details.
"""
var = pvariance(data, mu)
try:
return var.sqrt()
except AttributeError:
return math.sqrt(var) | [
"def",
"pstdev",
"(",
"data",
",",
"mu",
"=",
"None",
")",
":",
"var",
"=",
"pvariance",
"(",
"data",
",",
"mu",
")",
"try",
":",
"return",
"var",
".",
"sqrt",
"(",
")",
"except",
"AttributeError",
":",
"return",
"math",
".",
"sqrt",
"(",
"var",
... | Return the square root of the population variance.
See ``pvariance`` for arguments and other details. | [
"Return",
"the",
"square",
"root",
"of",
"the",
"population",
"variance",
"."
] | train | https://github.com/avalente/appmetrics/blob/366fc7e1ca897e49a2227cbfa43bfa02a47f1acc/appmetrics/statistics.py#L369-L379 |
avalente/appmetrics | appmetrics/statistics.py | geometric_mean | def geometric_mean(data):
"""Return the geometric mean of data
"""
if not data:
raise StatisticsError('geometric_mean requires at least one data point')
# in order to support negative or null values
data = [x if x > 0 else math.e if x == 0 else 1.0 for x in data]
return math.pow(math.fabs(functools.reduce(operator.mul, data)), 1.0 / len(data)) | python | def geometric_mean(data):
"""Return the geometric mean of data
"""
if not data:
raise StatisticsError('geometric_mean requires at least one data point')
# in order to support negative or null values
data = [x if x > 0 else math.e if x == 0 else 1.0 for x in data]
return math.pow(math.fabs(functools.reduce(operator.mul, data)), 1.0 / len(data)) | [
"def",
"geometric_mean",
"(",
"data",
")",
":",
"if",
"not",
"data",
":",
"raise",
"StatisticsError",
"(",
"'geometric_mean requires at least one data point'",
")",
"# in order to support negative or null values",
"data",
"=",
"[",
"x",
"if",
"x",
">",
"0",
"else",
... | Return the geometric mean of data | [
"Return",
"the",
"geometric",
"mean",
"of",
"data"
] | train | https://github.com/avalente/appmetrics/blob/366fc7e1ca897e49a2227cbfa43bfa02a47f1acc/appmetrics/statistics.py#L382-L392 |
avalente/appmetrics | appmetrics/statistics.py | harmonic_mean | def harmonic_mean(data):
"""Return the harmonic mean of data
"""
if not data:
raise StatisticsError('harmonic_mean requires at least one data point')
divisor = sum(map(lambda x: 1.0 / x if x else 0.0, data))
return len(data) / divisor if divisor else 0.0 | python | def harmonic_mean(data):
"""Return the harmonic mean of data
"""
if not data:
raise StatisticsError('harmonic_mean requires at least one data point')
divisor = sum(map(lambda x: 1.0 / x if x else 0.0, data))
return len(data) / divisor if divisor else 0.0 | [
"def",
"harmonic_mean",
"(",
"data",
")",
":",
"if",
"not",
"data",
":",
"raise",
"StatisticsError",
"(",
"'harmonic_mean requires at least one data point'",
")",
"divisor",
"=",
"sum",
"(",
"map",
"(",
"lambda",
"x",
":",
"1.0",
"/",
"x",
"if",
"x",
"else",... | Return the harmonic mean of data | [
"Return",
"the",
"harmonic",
"mean",
"of",
"data"
] | train | https://github.com/avalente/appmetrics/blob/366fc7e1ca897e49a2227cbfa43bfa02a47f1acc/appmetrics/statistics.py#L395-L403 |
avalente/appmetrics | appmetrics/statistics.py | kurtosis | def kurtosis(data):
"""Return the kurtosis of the data's distribution
"""
if not data:
raise StatisticsError('kurtosis requires at least one data point')
size = len(data)
sd = stdev(data) ** 4
if not sd:
return 0.0
mn = mean(data)
return sum(map(lambda x: ((x - mn) ** 4 / sd), data)) / size - 3 | python | def kurtosis(data):
"""Return the kurtosis of the data's distribution
"""
if not data:
raise StatisticsError('kurtosis requires at least one data point')
size = len(data)
sd = stdev(data) ** 4
if not sd:
return 0.0
mn = mean(data)
return sum(map(lambda x: ((x - mn) ** 4 / sd), data)) / size - 3 | [
"def",
"kurtosis",
"(",
"data",
")",
":",
"if",
"not",
"data",
":",
"raise",
"StatisticsError",
"(",
"'kurtosis requires at least one data point'",
")",
"size",
"=",
"len",
"(",
"data",
")",
"sd",
"=",
"stdev",
"(",
"data",
")",
"**",
"4",
"if",
"not",
"... | Return the kurtosis of the data's distribution | [
"Return",
"the",
"kurtosis",
"of",
"the",
"data",
"s",
"distribution"
] | train | https://github.com/avalente/appmetrics/blob/366fc7e1ca897e49a2227cbfa43bfa02a47f1acc/appmetrics/statistics.py#L424-L439 |
avalente/appmetrics | appmetrics/statistics.py | percentile | def percentile(data, n):
"""Return the n-th percentile of the given data
Assume that the data are already sorted
"""
size = len(data)
idx = (n / 100.0) * size - 0.5
if idx < 0 or idx > size:
raise StatisticsError("Too few data points ({}) for {}th percentile".format(size, n))
return data[int(idx)] | python | def percentile(data, n):
"""Return the n-th percentile of the given data
Assume that the data are already sorted
"""
size = len(data)
idx = (n / 100.0) * size - 0.5
if idx < 0 or idx > size:
raise StatisticsError("Too few data points ({}) for {}th percentile".format(size, n))
return data[int(idx)] | [
"def",
"percentile",
"(",
"data",
",",
"n",
")",
":",
"size",
"=",
"len",
"(",
"data",
")",
"idx",
"=",
"(",
"n",
"/",
"100.0",
")",
"*",
"size",
"-",
"0.5",
"if",
"idx",
"<",
"0",
"or",
"idx",
">",
"size",
":",
"raise",
"StatisticsError",
"(",... | Return the n-th percentile of the given data
Assume that the data are already sorted | [
"Return",
"the",
"n",
"-",
"th",
"percentile",
"of",
"the",
"given",
"data"
] | train | https://github.com/avalente/appmetrics/blob/366fc7e1ca897e49a2227cbfa43bfa02a47f1acc/appmetrics/statistics.py#L442-L455 |
avalente/appmetrics | appmetrics/statistics.py | get_histogram | def get_histogram(data):
"""Return the histogram relative to the given data
Assume that the data are already sorted
"""
count = len(data)
if count < 2:
raise StatisticsError('Too few data points ({}) for get_histogram'.format(count))
min_ = data[0]
max_ = data[-1]
std = stdev(data)
bins = get_histogram_bins(min_, max_, std, count)
res = {x: 0 for x in bins}
for value in data:
for bin_ in bins:
if value <= bin_:
res[bin_] += 1
break
return sorted(iteritems(res)) | python | def get_histogram(data):
"""Return the histogram relative to the given data
Assume that the data are already sorted
"""
count = len(data)
if count < 2:
raise StatisticsError('Too few data points ({}) for get_histogram'.format(count))
min_ = data[0]
max_ = data[-1]
std = stdev(data)
bins = get_histogram_bins(min_, max_, std, count)
res = {x: 0 for x in bins}
for value in data:
for bin_ in bins:
if value <= bin_:
res[bin_] += 1
break
return sorted(iteritems(res)) | [
"def",
"get_histogram",
"(",
"data",
")",
":",
"count",
"=",
"len",
"(",
"data",
")",
"if",
"count",
"<",
"2",
":",
"raise",
"StatisticsError",
"(",
"'Too few data points ({}) for get_histogram'",
".",
"format",
"(",
"count",
")",
")",
"min_",
"=",
"data",
... | Return the histogram relative to the given data
Assume that the data are already sorted | [
"Return",
"the",
"histogram",
"relative",
"to",
"the",
"given",
"data"
] | train | https://github.com/avalente/appmetrics/blob/366fc7e1ca897e49a2227cbfa43bfa02a47f1acc/appmetrics/statistics.py#L458-L484 |
avalente/appmetrics | appmetrics/statistics.py | get_histogram_bins | def get_histogram_bins(min_, max_, std, count):
"""
Return optimal bins given the input parameters
"""
width = _get_bin_width(std, count)
count = int(round((max_ - min_) / width) + 1)
if count:
bins = [i * width + min_ for i in xrange(1, count + 1)]
else:
bins = [min_]
return bins | python | def get_histogram_bins(min_, max_, std, count):
"""
Return optimal bins given the input parameters
"""
width = _get_bin_width(std, count)
count = int(round((max_ - min_) / width) + 1)
if count:
bins = [i * width + min_ for i in xrange(1, count + 1)]
else:
bins = [min_]
return bins | [
"def",
"get_histogram_bins",
"(",
"min_",
",",
"max_",
",",
"std",
",",
"count",
")",
":",
"width",
"=",
"_get_bin_width",
"(",
"std",
",",
"count",
")",
"count",
"=",
"int",
"(",
"round",
"(",
"(",
"max_",
"-",
"min_",
")",
"/",
"width",
")",
"+",... | Return optimal bins given the input parameters | [
"Return",
"optimal",
"bins",
"given",
"the",
"input",
"parameters"
] | train | https://github.com/avalente/appmetrics/blob/366fc7e1ca897e49a2227cbfa43bfa02a47f1acc/appmetrics/statistics.py#L487-L501 |
avalente/appmetrics | appmetrics/statistics.py | _get_bin_width | def _get_bin_width(stdev, count):
"""Return the histogram's optimal bin width based on Sturges
http://www.jstor.org/pss/2965501
"""
w = int(round((3.5 * stdev) / (count ** (1.0 / 3))))
if w:
return w
else:
return 1 | python | def _get_bin_width(stdev, count):
"""Return the histogram's optimal bin width based on Sturges
http://www.jstor.org/pss/2965501
"""
w = int(round((3.5 * stdev) / (count ** (1.0 / 3))))
if w:
return w
else:
return 1 | [
"def",
"_get_bin_width",
"(",
"stdev",
",",
"count",
")",
":",
"w",
"=",
"int",
"(",
"round",
"(",
"(",
"3.5",
"*",
"stdev",
")",
"/",
"(",
"count",
"**",
"(",
"1.0",
"/",
"3",
")",
")",
")",
")",
"if",
"w",
":",
"return",
"w",
"else",
":",
... | Return the histogram's optimal bin width based on Sturges
http://www.jstor.org/pss/2965501 | [
"Return",
"the",
"histogram",
"s",
"optimal",
"bin",
"width",
"based",
"on",
"Sturges"
] | train | https://github.com/avalente/appmetrics/blob/366fc7e1ca897e49a2227cbfa43bfa02a47f1acc/appmetrics/statistics.py#L504-L514 |
schneiderfelipe/pyrrole | pyrrole/drawing.py | _longest_common_subsequence | def _longest_common_subsequence(x, y):
"""
Return the longest common subsequence between two sequences.
Parameters
----------
x, y : sequence
Returns
-------
sequence
Longest common subsequence of x and y.
Examples
--------
>>> _longest_common_subsequence("AGGTAB", "GXTXAYB")
['G', 'T', 'A', 'B']
>>> _longest_common_subsequence(["A", "GA", "G", "T", "A", "B"],
... ["GA", "X", "T", "X", "A", "Y", "B"])
['GA', 'T', 'A', 'B']
"""
m = len(x)
n = len(y)
# L[i, j] will contain the length of the longest common subsequence of
# x[0..i - 1] and y[0..j - 1].
L = _np.zeros((m + 1, n + 1), dtype=int)
for i in range(m + 1):
for j in range(n + 1):
if i == 0 or j == 0:
continue
elif x[i - 1] == y[j - 1]:
L[i, j] = L[i - 1, j - 1] + 1
else:
L[i, j] = max(L[i - 1, j], L[i, j - 1])
ret = []
i, j = m, n
while i > 0 and j > 0:
# If current character in x and y are same, then current character is
# part of the longest common subsequence.
if x[i - 1] == y[j - 1]:
ret.append(x[i - 1])
i, j = i - 1, j - 1
# If not same, then find the larger of two and go in the direction of
# larger value.
elif L[i - 1, j] > L[i, j - 1]:
i -= 1
else:
j -= 1
return ret[::-1] | python | def _longest_common_subsequence(x, y):
"""
Return the longest common subsequence between two sequences.
Parameters
----------
x, y : sequence
Returns
-------
sequence
Longest common subsequence of x and y.
Examples
--------
>>> _longest_common_subsequence("AGGTAB", "GXTXAYB")
['G', 'T', 'A', 'B']
>>> _longest_common_subsequence(["A", "GA", "G", "T", "A", "B"],
... ["GA", "X", "T", "X", "A", "Y", "B"])
['GA', 'T', 'A', 'B']
"""
m = len(x)
n = len(y)
# L[i, j] will contain the length of the longest common subsequence of
# x[0..i - 1] and y[0..j - 1].
L = _np.zeros((m + 1, n + 1), dtype=int)
for i in range(m + 1):
for j in range(n + 1):
if i == 0 or j == 0:
continue
elif x[i - 1] == y[j - 1]:
L[i, j] = L[i - 1, j - 1] + 1
else:
L[i, j] = max(L[i - 1, j], L[i, j - 1])
ret = []
i, j = m, n
while i > 0 and j > 0:
# If current character in x and y are same, then current character is
# part of the longest common subsequence.
if x[i - 1] == y[j - 1]:
ret.append(x[i - 1])
i, j = i - 1, j - 1
# If not same, then find the larger of two and go in the direction of
# larger value.
elif L[i - 1, j] > L[i, j - 1]:
i -= 1
else:
j -= 1
return ret[::-1] | [
"def",
"_longest_common_subsequence",
"(",
"x",
",",
"y",
")",
":",
"m",
"=",
"len",
"(",
"x",
")",
"n",
"=",
"len",
"(",
"y",
")",
"# L[i, j] will contain the length of the longest common subsequence of",
"# x[0..i - 1] and y[0..j - 1].",
"L",
"=",
"_np",
".",
"z... | Return the longest common subsequence between two sequences.
Parameters
----------
x, y : sequence
Returns
-------
sequence
Longest common subsequence of x and y.
Examples
--------
>>> _longest_common_subsequence("AGGTAB", "GXTXAYB")
['G', 'T', 'A', 'B']
>>> _longest_common_subsequence(["A", "GA", "G", "T", "A", "B"],
... ["GA", "X", "T", "X", "A", "Y", "B"])
['GA', 'T', 'A', 'B'] | [
"Return",
"the",
"longest",
"common",
"subsequence",
"between",
"two",
"sequences",
"."
] | train | https://github.com/schneiderfelipe/pyrrole/blob/13e26accc9a059f0ab69773648b24292fe1fbfd6/pyrrole/drawing.py#L24-L78 |
schneiderfelipe/pyrrole | pyrrole/drawing.py | tower_layout | def tower_layout(graph, height='freeenergy', scale=None, center=None, dim=2):
"""
Position all nodes of graph stacked on top of each other.
Parameters
----------
graph : `networkx.Graph` or `list` of nodes
A position will be assigned to every node in graph.
height : `str` or `None`, optional
The node attribute that holds the numerical value used for the node
height. This defaults to ``'freeenergy'``. If `None`, all node heights
are set to zero.
scale : number, optional
Scale factor for positions.
center : array-like, optional
Coordinate pair around which to center the layout. Default is the
origin.
dim : `int`
Dimension of layout. If `dim` > 2, the remaining dimensions are set to
zero in the returned positions.
Returns
-------
pos : mapping
A mapping of positions keyed by node.
Examples
--------
>>> from pyrrole import ChemicalSystem
>>> from pyrrole.atoms import create_data, read_cclib
>>> from pyrrole.drawing import tower_layout
>>> data = create_data(
... read_cclib("data/acetate/acetic_acid.out", "AcOH(g)"),
... read_cclib("data/acetate/acetic_acid@water.out", "AcOH(aq)"))
>>> digraph = (ChemicalSystem("AcOH(g) <=> AcOH(aq)", data)
... .to_digraph())
>>> layout = tower_layout(digraph)
>>> layout['AcOH(g)']
array([ 0. , -228.56450866])
Passing ``scale=1`` means scaling positions to ``(-1, 1)`` in all axes:
>>> layout = tower_layout(digraph, scale=1)
>>> layout['AcOH(g)'][1] <= 1.
True
"""
# TODO: private function of packages should not be used.
graph, center = _nx.drawing.layout._process_params(graph, center, dim)
num_nodes = len(graph)
if num_nodes == 0:
return {}
elif num_nodes == 1:
return {_nx.utils.arbitrary_element(graph): center}
paddims = max(0, (dim - 2))
if height is None:
y = _np.zeros(len(graph))
else:
y = _np.array([data for node, data in graph.nodes(data=height)])
pos_arr = _np.column_stack([_np.zeros((num_nodes, 1)), y,
_np.zeros((num_nodes, paddims))])
if scale is not None:
pos_arr = _nx.drawing.layout.rescale_layout(pos_arr,
scale=scale) + center
pos = dict(zip(graph, pos_arr))
# TODO: make test
return pos | python | def tower_layout(graph, height='freeenergy', scale=None, center=None, dim=2):
"""
Position all nodes of graph stacked on top of each other.
Parameters
----------
graph : `networkx.Graph` or `list` of nodes
A position will be assigned to every node in graph.
height : `str` or `None`, optional
The node attribute that holds the numerical value used for the node
height. This defaults to ``'freeenergy'``. If `None`, all node heights
are set to zero.
scale : number, optional
Scale factor for positions.
center : array-like, optional
Coordinate pair around which to center the layout. Default is the
origin.
dim : `int`
Dimension of layout. If `dim` > 2, the remaining dimensions are set to
zero in the returned positions.
Returns
-------
pos : mapping
A mapping of positions keyed by node.
Examples
--------
>>> from pyrrole import ChemicalSystem
>>> from pyrrole.atoms import create_data, read_cclib
>>> from pyrrole.drawing import tower_layout
>>> data = create_data(
... read_cclib("data/acetate/acetic_acid.out", "AcOH(g)"),
... read_cclib("data/acetate/acetic_acid@water.out", "AcOH(aq)"))
>>> digraph = (ChemicalSystem("AcOH(g) <=> AcOH(aq)", data)
... .to_digraph())
>>> layout = tower_layout(digraph)
>>> layout['AcOH(g)']
array([ 0. , -228.56450866])
Passing ``scale=1`` means scaling positions to ``(-1, 1)`` in all axes:
>>> layout = tower_layout(digraph, scale=1)
>>> layout['AcOH(g)'][1] <= 1.
True
"""
# TODO: private function of packages should not be used.
graph, center = _nx.drawing.layout._process_params(graph, center, dim)
num_nodes = len(graph)
if num_nodes == 0:
return {}
elif num_nodes == 1:
return {_nx.utils.arbitrary_element(graph): center}
paddims = max(0, (dim - 2))
if height is None:
y = _np.zeros(len(graph))
else:
y = _np.array([data for node, data in graph.nodes(data=height)])
pos_arr = _np.column_stack([_np.zeros((num_nodes, 1)), y,
_np.zeros((num_nodes, paddims))])
if scale is not None:
pos_arr = _nx.drawing.layout.rescale_layout(pos_arr,
scale=scale) + center
pos = dict(zip(graph, pos_arr))
# TODO: make test
return pos | [
"def",
"tower_layout",
"(",
"graph",
",",
"height",
"=",
"'freeenergy'",
",",
"scale",
"=",
"None",
",",
"center",
"=",
"None",
",",
"dim",
"=",
"2",
")",
":",
"# TODO: private function of packages should not be used.",
"graph",
",",
"center",
"=",
"_nx",
".",... | Position all nodes of graph stacked on top of each other.
Parameters
----------
graph : `networkx.Graph` or `list` of nodes
A position will be assigned to every node in graph.
height : `str` or `None`, optional
The node attribute that holds the numerical value used for the node
height. This defaults to ``'freeenergy'``. If `None`, all node heights
are set to zero.
scale : number, optional
Scale factor for positions.
center : array-like, optional
Coordinate pair around which to center the layout. Default is the
origin.
dim : `int`
Dimension of layout. If `dim` > 2, the remaining dimensions are set to
zero in the returned positions.
Returns
-------
pos : mapping
A mapping of positions keyed by node.
Examples
--------
>>> from pyrrole import ChemicalSystem
>>> from pyrrole.atoms import create_data, read_cclib
>>> from pyrrole.drawing import tower_layout
>>> data = create_data(
... read_cclib("data/acetate/acetic_acid.out", "AcOH(g)"),
... read_cclib("data/acetate/acetic_acid@water.out", "AcOH(aq)"))
>>> digraph = (ChemicalSystem("AcOH(g) <=> AcOH(aq)", data)
... .to_digraph())
>>> layout = tower_layout(digraph)
>>> layout['AcOH(g)']
array([ 0. , -228.56450866])
Passing ``scale=1`` means scaling positions to ``(-1, 1)`` in all axes:
>>> layout = tower_layout(digraph, scale=1)
>>> layout['AcOH(g)'][1] <= 1.
True | [
"Position",
"all",
"nodes",
"of",
"graph",
"stacked",
"on",
"top",
"of",
"each",
"other",
"."
] | train | https://github.com/schneiderfelipe/pyrrole/blob/13e26accc9a059f0ab69773648b24292fe1fbfd6/pyrrole/drawing.py#L81-L152 |
schneiderfelipe/pyrrole | pyrrole/drawing.py | diagram_layout | def diagram_layout(graph, height='freeenergy', sources=None, targets=None,
pos=None, scale=None, center=None, dim=2):
"""
Position nodes such that paths are highlighted, from left to right.
Parameters
----------
graph : `networkx.Graph` or `list` of nodes
A position will be assigned to every node in graph.
height : `str` or `None`, optional
The node attribute that holds the numerical value used for the node
height. This defaults to ``'freeenergy'``. If `None`, all node heights
are set to zero.
sources : `list` of `str`
All simple paths starting at members of `sources` are considered.
Defaults to all nodes of graph.
targets : `list` of `str`
All simple paths ending at members of `targets` are considered.
Defaults to all nodes of graph.
pos : mapping, optional
Initial positions for nodes as a mapping with node as keys and
values as a coordinate `list` or `tuple`. If not specified (default),
initial positions are computed with `tower_layout`.
scale : number, optional
Scale factor for positions.
center : array-like, optional
Coordinate pair around which to center the layout. Default is the
origin.
dim : `int`
Dimension of layout. If `dim` > 2, the remaining dimensions are set to
zero in the returned positions.
Returns
-------
pos : mapping
A mapping of positions keyed by node.
Examples
--------
>>> import pandas as pd
>>> from pyrrole import ChemicalSystem
>>> from pyrrole.drawing import diagram_layout
>>> data = pd.DataFrame(
... [{"name": "Separated_Reactants", "freeenergy": 0.},
... {"name": "mlC1", "freeenergy": -5.4},
... {"name": "mlC2", "freeenergy": -15.6},
... {"name": "mTS1", "freeenergy": 28.5, "color": "g"},
... {"name": "mCARB1", "freeenergy": -9.7},
... {"name": "mCARB2", "freeenergy": -19.8},
... {"name": "mCARBX", "freeenergy": 20}]).set_index("name")
>>> system = ChemicalSystem(
... ["Separated_Reactants -> mlC1 -> mTS1",
... "Separated_Reactants -> mlC2 -> mTS1",
... "mCARB2 <- mTS1 -> mCARB1",
... "Separated_Reactants -> mCARBX"], data)
>>> digraph = system.to_digraph()
>>> layout = diagram_layout(digraph)
>>> layout['mCARB2']
array([ 3. , -19.8])
Passing ``scale=1`` means scaling positions to ``(-1, 1)`` in all axes:
>>> layout = diagram_layout(digraph, scale=1)
>>> layout['mTS1'][1] <= 1.
True
"""
# TODO: private function of packages should not be used.
graph, center = _nx.drawing.layout._process_params(graph, center, dim)
num_nodes = len(graph)
if num_nodes == 0:
return {}
elif num_nodes == 1:
return {_nx.utils.arbitrary_element(graph): center}
if sources is None:
sources = graph.nodes()
if targets is None:
targets = graph.nodes()
simple_paths = [path for source in set(sources) for target in set(targets)
for path in _nx.all_simple_paths(graph, source, target)]
if pos is None:
pos = tower_layout(graph, height=height, scale=None, center=center,
dim=dim)
for path in simple_paths:
for n, step in enumerate(path):
if pos[step][0] < n:
pos[step][0] = n
if scale is not None:
pos_arr = _np.array([pos[node] for node in graph])
pos_arr = _nx.drawing.layout.rescale_layout(pos_arr,
scale=scale) + center
pos = dict(zip(graph, pos_arr))
# TODO: make test
return pos | python | def diagram_layout(graph, height='freeenergy', sources=None, targets=None,
pos=None, scale=None, center=None, dim=2):
"""
Position nodes such that paths are highlighted, from left to right.
Parameters
----------
graph : `networkx.Graph` or `list` of nodes
A position will be assigned to every node in graph.
height : `str` or `None`, optional
The node attribute that holds the numerical value used for the node
height. This defaults to ``'freeenergy'``. If `None`, all node heights
are set to zero.
sources : `list` of `str`
All simple paths starting at members of `sources` are considered.
Defaults to all nodes of graph.
targets : `list` of `str`
All simple paths ending at members of `targets` are considered.
Defaults to all nodes of graph.
pos : mapping, optional
Initial positions for nodes as a mapping with node as keys and
values as a coordinate `list` or `tuple`. If not specified (default),
initial positions are computed with `tower_layout`.
scale : number, optional
Scale factor for positions.
center : array-like, optional
Coordinate pair around which to center the layout. Default is the
origin.
dim : `int`
Dimension of layout. If `dim` > 2, the remaining dimensions are set to
zero in the returned positions.
Returns
-------
pos : mapping
A mapping of positions keyed by node.
Examples
--------
>>> import pandas as pd
>>> from pyrrole import ChemicalSystem
>>> from pyrrole.drawing import diagram_layout
>>> data = pd.DataFrame(
... [{"name": "Separated_Reactants", "freeenergy": 0.},
... {"name": "mlC1", "freeenergy": -5.4},
... {"name": "mlC2", "freeenergy": -15.6},
... {"name": "mTS1", "freeenergy": 28.5, "color": "g"},
... {"name": "mCARB1", "freeenergy": -9.7},
... {"name": "mCARB2", "freeenergy": -19.8},
... {"name": "mCARBX", "freeenergy": 20}]).set_index("name")
>>> system = ChemicalSystem(
... ["Separated_Reactants -> mlC1 -> mTS1",
... "Separated_Reactants -> mlC2 -> mTS1",
... "mCARB2 <- mTS1 -> mCARB1",
... "Separated_Reactants -> mCARBX"], data)
>>> digraph = system.to_digraph()
>>> layout = diagram_layout(digraph)
>>> layout['mCARB2']
array([ 3. , -19.8])
Passing ``scale=1`` means scaling positions to ``(-1, 1)`` in all axes:
>>> layout = diagram_layout(digraph, scale=1)
>>> layout['mTS1'][1] <= 1.
True
"""
# TODO: private function of packages should not be used.
graph, center = _nx.drawing.layout._process_params(graph, center, dim)
num_nodes = len(graph)
if num_nodes == 0:
return {}
elif num_nodes == 1:
return {_nx.utils.arbitrary_element(graph): center}
if sources is None:
sources = graph.nodes()
if targets is None:
targets = graph.nodes()
simple_paths = [path for source in set(sources) for target in set(targets)
for path in _nx.all_simple_paths(graph, source, target)]
if pos is None:
pos = tower_layout(graph, height=height, scale=None, center=center,
dim=dim)
for path in simple_paths:
for n, step in enumerate(path):
if pos[step][0] < n:
pos[step][0] = n
if scale is not None:
pos_arr = _np.array([pos[node] for node in graph])
pos_arr = _nx.drawing.layout.rescale_layout(pos_arr,
scale=scale) + center
pos = dict(zip(graph, pos_arr))
# TODO: make test
return pos | [
"def",
"diagram_layout",
"(",
"graph",
",",
"height",
"=",
"'freeenergy'",
",",
"sources",
"=",
"None",
",",
"targets",
"=",
"None",
",",
"pos",
"=",
"None",
",",
"scale",
"=",
"None",
",",
"center",
"=",
"None",
",",
"dim",
"=",
"2",
")",
":",
"# ... | Position nodes such that paths are highlighted, from left to right.
Parameters
----------
graph : `networkx.Graph` or `list` of nodes
A position will be assigned to every node in graph.
height : `str` or `None`, optional
The node attribute that holds the numerical value used for the node
height. This defaults to ``'freeenergy'``. If `None`, all node heights
are set to zero.
sources : `list` of `str`
All simple paths starting at members of `sources` are considered.
Defaults to all nodes of graph.
targets : `list` of `str`
All simple paths ending at members of `targets` are considered.
Defaults to all nodes of graph.
pos : mapping, optional
Initial positions for nodes as a mapping with node as keys and
values as a coordinate `list` or `tuple`. If not specified (default),
initial positions are computed with `tower_layout`.
scale : number, optional
Scale factor for positions.
center : array-like, optional
Coordinate pair around which to center the layout. Default is the
origin.
dim : `int`
Dimension of layout. If `dim` > 2, the remaining dimensions are set to
zero in the returned positions.
Returns
-------
pos : mapping
A mapping of positions keyed by node.
Examples
--------
>>> import pandas as pd
>>> from pyrrole import ChemicalSystem
>>> from pyrrole.drawing import diagram_layout
>>> data = pd.DataFrame(
... [{"name": "Separated_Reactants", "freeenergy": 0.},
... {"name": "mlC1", "freeenergy": -5.4},
... {"name": "mlC2", "freeenergy": -15.6},
... {"name": "mTS1", "freeenergy": 28.5, "color": "g"},
... {"name": "mCARB1", "freeenergy": -9.7},
... {"name": "mCARB2", "freeenergy": -19.8},
... {"name": "mCARBX", "freeenergy": 20}]).set_index("name")
>>> system = ChemicalSystem(
... ["Separated_Reactants -> mlC1 -> mTS1",
... "Separated_Reactants -> mlC2 -> mTS1",
... "mCARB2 <- mTS1 -> mCARB1",
... "Separated_Reactants -> mCARBX"], data)
>>> digraph = system.to_digraph()
>>> layout = diagram_layout(digraph)
>>> layout['mCARB2']
array([ 3. , -19.8])
Passing ``scale=1`` means scaling positions to ``(-1, 1)`` in all axes:
>>> layout = diagram_layout(digraph, scale=1)
>>> layout['mTS1'][1] <= 1.
True | [
"Position",
"nodes",
"such",
"that",
"paths",
"are",
"highlighted",
"from",
"left",
"to",
"right",
"."
] | train | https://github.com/schneiderfelipe/pyrrole/blob/13e26accc9a059f0ab69773648b24292fe1fbfd6/pyrrole/drawing.py#L155-L254 |
schneiderfelipe/pyrrole | pyrrole/drawing.py | draw_diagram_nodes | def draw_diagram_nodes(graph, pos=None, nodelist=None, node_size=.7,
node_color='k', style='solid', alpha=1.0, cmap=None,
vmin=None, vmax=None, ax=None, label=None):
"""
Draw nodes of graph.
This draws only the nodes of graph as horizontal lines at each
``y = pos[1]`` from ``x - node_size/2`` to ``x + node_size/2``, where
``x = pos[0]``.
Parameters
----------
graph : `networkx.Graph`
A NetworkX graph.
pos : mapping, optional
A mapping with nodes as keys and positions as values. Positions should
be sequences of length 2. If not specified (default), a diagram layout
positioning will be computed. See `networkx.layout` and
`pyrrole.drawing` for functions that compute node positions.
nodelist : `list`, optional
Draw only specified nodes (default is ``graph.nodes()``).
node_size : scalar or array
Size of nodes (default is ``.7``). If an array is specified it must be
the same length as nodelist.
node_color : color `str`, or array of `float`
Node color. Can be a single color format `str` (default is ``'k'``), or
a sequence of colors with the same length as nodelist. If numeric
values are specified they will be mapped to colors using the `cmap` and
`vmin`, `vmax` parameters. See `matplotlib.hlines` for more details.
style : `str` (``'solid'``, ``'dashed'``, ``'dotted'``, ``'dashdot'``)
Edge line style (default is ``'solid'``). See `matplotlib.hlines` for
more details.
alpha : `float` or array of `float`, optional
The node transparency. This can be a single alpha value (default is
``'1.0'``), in which case it will be applied to all the nodes of color.
Otherwise, if it is an array, the elements of alpha will be applied to
the colors in order (cycling through alpha multiple times if
necessary).
cmap : Matplotlib colormap, optional
Colormap name or Colormap instance for mapping intensities of nodes.
vmin : `float`, optional
Minimum for node colormap scaling.
vmax : `float`, optional
Maximum for node colormap scaling.
ax : `matplotlib.axes.Axes`, optional
Draw the graph in the specified Matplotlib axes.
label : `str`, optional
Label for legend.
Returns
-------
`matplotlib.collections.LineCollection`
`LineCollection` of the nodes.
Raises
------
networkx.NetworkXError
Raised if a node has no position or one with bad value.
Examples
--------
>>> import pandas as pd
>>> from pyrrole import ChemicalSystem
>>> from pyrrole.drawing import draw_diagram_nodes
>>> data = pd.DataFrame(
... [{"name": "Separated_Reactants", "freeenergy": 0.},
... {"name": "mlC1", "freeenergy": -5.4},
... {"name": "mlC2", "freeenergy": -15.6},
... {"name": "mTS1", "freeenergy": 28.5, "color": "g"},
... {"name": "mCARB1", "freeenergy": -9.7},
... {"name": "mCARB2", "freeenergy": -19.8},
... {"name": "mCARBX", "freeenergy": 20}]).set_index("name")
>>> system = ChemicalSystem(
... ["Separated_Reactants -> mlC1 -> mTS1",
... "Separated_Reactants -> mlC2 -> mTS1",
... "mCARB2 <- mTS1 -> mCARB1",
... "Separated_Reactants -> mCARBX"], data)
>>> digraph = system.to_digraph()
>>> nodes = draw_diagram_nodes(digraph)
"""
if ax is None:
ax = _plt.gca()
if nodelist is None:
nodelist = list(graph.nodes())
if not nodelist or len(nodelist) == 0: # empty nodelist, no drawing
return None
if pos is None:
pos = diagram_layout(graph)
try:
xy = _np.asarray([pos[v] for v in nodelist])
except KeyError as e:
raise _nx.NetworkXError('Node {} has no position.'.format(e))
except ValueError:
raise _nx.NetworkXError('Bad value in node positions.')
if isinstance(alpha, _collections.Iterable):
node_color = _nx.drawing.apply_alpha(node_color, alpha, nodelist, cmap,
vmin, vmax)
alpha = None
node_collection = ax.hlines(xy[:, 1],
xy[:, 0] - node_size/2.,
xy[:, 0] + node_size/2.,
colors=node_color,
linestyles=style,
label=label,
cmap=cmap)
node_collection.set_zorder(2)
return node_collection | python | def draw_diagram_nodes(graph, pos=None, nodelist=None, node_size=.7,
node_color='k', style='solid', alpha=1.0, cmap=None,
vmin=None, vmax=None, ax=None, label=None):
"""
Draw nodes of graph.
This draws only the nodes of graph as horizontal lines at each
``y = pos[1]`` from ``x - node_size/2`` to ``x + node_size/2``, where
``x = pos[0]``.
Parameters
----------
graph : `networkx.Graph`
A NetworkX graph.
pos : mapping, optional
A mapping with nodes as keys and positions as values. Positions should
be sequences of length 2. If not specified (default), a diagram layout
positioning will be computed. See `networkx.layout` and
`pyrrole.drawing` for functions that compute node positions.
nodelist : `list`, optional
Draw only specified nodes (default is ``graph.nodes()``).
node_size : scalar or array
Size of nodes (default is ``.7``). If an array is specified it must be
the same length as nodelist.
node_color : color `str`, or array of `float`
Node color. Can be a single color format `str` (default is ``'k'``), or
a sequence of colors with the same length as nodelist. If numeric
values are specified they will be mapped to colors using the `cmap` and
`vmin`, `vmax` parameters. See `matplotlib.hlines` for more details.
style : `str` (``'solid'``, ``'dashed'``, ``'dotted'``, ``'dashdot'``)
Edge line style (default is ``'solid'``). See `matplotlib.hlines` for
more details.
alpha : `float` or array of `float`, optional
The node transparency. This can be a single alpha value (default is
``'1.0'``), in which case it will be applied to all the nodes of color.
Otherwise, if it is an array, the elements of alpha will be applied to
the colors in order (cycling through alpha multiple times if
necessary).
cmap : Matplotlib colormap, optional
Colormap name or Colormap instance for mapping intensities of nodes.
vmin : `float`, optional
Minimum for node colormap scaling.
vmax : `float`, optional
Maximum for node colormap scaling.
ax : `matplotlib.axes.Axes`, optional
Draw the graph in the specified Matplotlib axes.
label : `str`, optional
Label for legend.
Returns
-------
`matplotlib.collections.LineCollection`
`LineCollection` of the nodes.
Raises
------
networkx.NetworkXError
Raised if a node has no position or one with bad value.
Examples
--------
>>> import pandas as pd
>>> from pyrrole import ChemicalSystem
>>> from pyrrole.drawing import draw_diagram_nodes
>>> data = pd.DataFrame(
... [{"name": "Separated_Reactants", "freeenergy": 0.},
... {"name": "mlC1", "freeenergy": -5.4},
... {"name": "mlC2", "freeenergy": -15.6},
... {"name": "mTS1", "freeenergy": 28.5, "color": "g"},
... {"name": "mCARB1", "freeenergy": -9.7},
... {"name": "mCARB2", "freeenergy": -19.8},
... {"name": "mCARBX", "freeenergy": 20}]).set_index("name")
>>> system = ChemicalSystem(
... ["Separated_Reactants -> mlC1 -> mTS1",
... "Separated_Reactants -> mlC2 -> mTS1",
... "mCARB2 <- mTS1 -> mCARB1",
... "Separated_Reactants -> mCARBX"], data)
>>> digraph = system.to_digraph()
>>> nodes = draw_diagram_nodes(digraph)
"""
if ax is None:
ax = _plt.gca()
if nodelist is None:
nodelist = list(graph.nodes())
if not nodelist or len(nodelist) == 0: # empty nodelist, no drawing
return None
if pos is None:
pos = diagram_layout(graph)
try:
xy = _np.asarray([pos[v] for v in nodelist])
except KeyError as e:
raise _nx.NetworkXError('Node {} has no position.'.format(e))
except ValueError:
raise _nx.NetworkXError('Bad value in node positions.')
if isinstance(alpha, _collections.Iterable):
node_color = _nx.drawing.apply_alpha(node_color, alpha, nodelist, cmap,
vmin, vmax)
alpha = None
node_collection = ax.hlines(xy[:, 1],
xy[:, 0] - node_size/2.,
xy[:, 0] + node_size/2.,
colors=node_color,
linestyles=style,
label=label,
cmap=cmap)
node_collection.set_zorder(2)
return node_collection | [
"def",
"draw_diagram_nodes",
"(",
"graph",
",",
"pos",
"=",
"None",
",",
"nodelist",
"=",
"None",
",",
"node_size",
"=",
".7",
",",
"node_color",
"=",
"'k'",
",",
"style",
"=",
"'solid'",
",",
"alpha",
"=",
"1.0",
",",
"cmap",
"=",
"None",
",",
"vmin... | Draw nodes of graph.
This draws only the nodes of graph as horizontal lines at each
``y = pos[1]`` from ``x - node_size/2`` to ``x + node_size/2``, where
``x = pos[0]``.
Parameters
----------
graph : `networkx.Graph`
A NetworkX graph.
pos : mapping, optional
A mapping with nodes as keys and positions as values. Positions should
be sequences of length 2. If not specified (default), a diagram layout
positioning will be computed. See `networkx.layout` and
`pyrrole.drawing` for functions that compute node positions.
nodelist : `list`, optional
Draw only specified nodes (default is ``graph.nodes()``).
node_size : scalar or array
Size of nodes (default is ``.7``). If an array is specified it must be
the same length as nodelist.
node_color : color `str`, or array of `float`
Node color. Can be a single color format `str` (default is ``'k'``), or
a sequence of colors with the same length as nodelist. If numeric
values are specified they will be mapped to colors using the `cmap` and
`vmin`, `vmax` parameters. See `matplotlib.hlines` for more details.
style : `str` (``'solid'``, ``'dashed'``, ``'dotted'``, ``'dashdot'``)
Edge line style (default is ``'solid'``). See `matplotlib.hlines` for
more details.
alpha : `float` or array of `float`, optional
The node transparency. This can be a single alpha value (default is
``'1.0'``), in which case it will be applied to all the nodes of color.
Otherwise, if it is an array, the elements of alpha will be applied to
the colors in order (cycling through alpha multiple times if
necessary).
cmap : Matplotlib colormap, optional
Colormap name or Colormap instance for mapping intensities of nodes.
vmin : `float`, optional
Minimum for node colormap scaling.
vmax : `float`, optional
Maximum for node colormap scaling.
ax : `matplotlib.axes.Axes`, optional
Draw the graph in the specified Matplotlib axes.
label : `str`, optional
Label for legend.
Returns
-------
`matplotlib.collections.LineCollection`
`LineCollection` of the nodes.
Raises
------
networkx.NetworkXError
Raised if a node has no position or one with bad value.
Examples
--------
>>> import pandas as pd
>>> from pyrrole import ChemicalSystem
>>> from pyrrole.drawing import draw_diagram_nodes
>>> data = pd.DataFrame(
... [{"name": "Separated_Reactants", "freeenergy": 0.},
... {"name": "mlC1", "freeenergy": -5.4},
... {"name": "mlC2", "freeenergy": -15.6},
... {"name": "mTS1", "freeenergy": 28.5, "color": "g"},
... {"name": "mCARB1", "freeenergy": -9.7},
... {"name": "mCARB2", "freeenergy": -19.8},
... {"name": "mCARBX", "freeenergy": 20}]).set_index("name")
>>> system = ChemicalSystem(
... ["Separated_Reactants -> mlC1 -> mTS1",
... "Separated_Reactants -> mlC2 -> mTS1",
... "mCARB2 <- mTS1 -> mCARB1",
... "Separated_Reactants -> mCARBX"], data)
>>> digraph = system.to_digraph()
>>> nodes = draw_diagram_nodes(digraph) | [
"Draw",
"nodes",
"of",
"graph",
"."
] | train | https://github.com/schneiderfelipe/pyrrole/blob/13e26accc9a059f0ab69773648b24292fe1fbfd6/pyrrole/drawing.py#L257-L371 |
schneiderfelipe/pyrrole | pyrrole/drawing.py | draw_diagram_edges | def draw_diagram_edges(graph, pos=None, edgelist=None, width=1.0,
edge_color='k', style='dashed', alpha=1.0,
edge_cmap=None, edge_vmin=None, edge_vmax=None, ax=None,
label=None, nodelist=None, node_size=.7):
"""
Draw edges of graph.
This draws only the edges of a graph.
Parameters
----------
graph : `networkx.Graph`
A NetworkX graph.
pos : mapping, optional
A mapping with nodes as keys and positions as values. Positions should
be sequences of length 2. If not specified (default), a diagram layout
positioning will be computed. See `networkx.layout` and
`pyrrole.drawing` for functions that compute node positions.
edgelist : collection of edge `tuple`
Draw only specified edges (default is ``graph.edges()``).
width : `float`, or array of `float`
Line width of edges (default is ``1.0``).
edge_color : color `str`, or array of `float`
Edge color. Can be a single color format `str` (default is ``'r'``),
or a sequence of colors with the same length as edgelist. If numeric
values are specified they will be mapped to colors using the
`edge_cmap` and `edge_vmin`, `edge_vmax` parameters.
style : `str` (``'solid'``, ``'dashed'``, ``'dotted'``, ``'dashdot'``)
Edge line style (default is ``'dashed'``). See `matplotlib.hlines` for
more details.
alpha : `float`, optional
The edge transparency (default is ``1.0``).
edge_cmap : Matplotlib colormap, optional
Colormap for mapping intensities of edges.
edge_vmin : `float`, optional
Minimum for edge colormap scaling.
edge_vmax : `float`, optional
Maximum for edge colormap scaling.
ax : `matplotlib.axes.Axes`, optional
Draw the graph in the specified Matplotlib axes.
label : `str`, optional
Label for legend.
nodelist : `list`, optional
Draw only specified nodes (default is ``graph.nodes()``).
node_size : scalar or array
Size of nodes (default is ``.7``). If an array is specified it must be
the same length as nodelist.
Returns
-------
`matplotlib.collections.LineCollection`
`LineCollection` of the edges.
Raises
------
networkx.NetworkXError
Raised if a node has no position or one with bad value.
ValueError
Raised if `edge_color` contains something other than color names (one
or a list of one per edge) or numbers.
Examples
--------
>>> import pandas as pd
>>> from pyrrole import ChemicalSystem
>>> from pyrrole.drawing import draw_diagram_edges
>>> data = pd.DataFrame(
... [{"name": "Separated_Reactants", "freeenergy": 0.},
... {"name": "mlC1", "freeenergy": -5.4},
... {"name": "mlC2", "freeenergy": -15.6},
... {"name": "mTS1", "freeenergy": 28.5, "color": "g"},
... {"name": "mCARB1", "freeenergy": -9.7},
... {"name": "mCARB2", "freeenergy": -19.8},
... {"name": "mCARBX", "freeenergy": 20}]).set_index("name")
>>> system = ChemicalSystem(
... ["Separated_Reactants -> mlC1 -> mTS1",
... "Separated_Reactants -> mlC2 -> mTS1",
... "mCARB2 <- mTS1 -> mCARB1",
... "Separated_Reactants -> mCARBX"], data)
>>> digraph = system.to_digraph()
>>> edges = draw_diagram_edges(digraph)
"""
if ax is None:
ax = _plt.gca()
if edgelist is None:
edgelist = list(graph.edges())
if not edgelist or len(edgelist) == 0: # no edges!
return None
if nodelist is None:
nodelist = list(graph.nodes())
if pos is None:
pos = diagram_layout(graph)
try:
# set edge positions
edge_pos = _np.asarray([(pos[e[0]] + node_size/2.,
pos[e[1]] - node_size/2.) for e in edgelist])
except KeyError as e:
raise _nx.NetworkXError('Node {} has no position.'.format(e))
except ValueError:
raise _nx.NetworkXError('Bad value in node positions.')
if not _cb.iterable(width):
lw = (width,)
else:
lw = width
if not isinstance(edge_color, str) \
and _cb.iterable(edge_color) \
and len(edge_color) == len(edge_pos):
if _np.alltrue([isinstance(c, str) for c in edge_color]):
# (should check ALL elements)
# list of color letters such as ['k','r','k',...]
edge_colors = tuple([_colorConverter.to_rgba(c, alpha)
for c in edge_color])
elif _np.alltrue([not isinstance(c, str) for c in edge_color]):
# If color specs are given as (rgb) or (rgba) tuples, we're OK
if _np.alltrue([_cb.iterable(c) and len(c) in (3, 4)
for c in edge_color]):
edge_colors = tuple(edge_color)
else:
# numbers (which are going to be mapped with a colormap)
edge_colors = None
else:
raise ValueError('edge_color must contain color names or numbers')
else:
if isinstance(edge_color, str) or len(edge_color) == 1:
edge_colors = (_colorConverter.to_rgba(edge_color, alpha), )
else:
raise ValueError('edge_color must be a color or list of one color '
' per edge')
edge_collection = _LineCollection(edge_pos,
colors=edge_colors,
linewidths=lw,
antialiaseds=(1,),
linestyle=style,
transOffset=ax.transData)
edge_collection.set_zorder(1) # edges go behind nodes
edge_collection.set_label(label)
ax.add_collection(edge_collection)
if _cb.is_numlike(alpha):
edge_collection.set_alpha(alpha)
if edge_colors is None:
if edge_cmap is not None:
assert(isinstance(edge_cmap, _Colormap))
edge_collection.set_array(_np.asarray(edge_color))
edge_collection.set_cmap(edge_cmap)
if edge_vmin is not None or edge_vmax is not None:
edge_collection.set_clim(edge_vmin, edge_vmax)
else:
edge_collection.autoscale()
ax.autoscale_view()
return edge_collection | python | def draw_diagram_edges(graph, pos=None, edgelist=None, width=1.0,
edge_color='k', style='dashed', alpha=1.0,
edge_cmap=None, edge_vmin=None, edge_vmax=None, ax=None,
label=None, nodelist=None, node_size=.7):
"""
Draw edges of graph.
This draws only the edges of a graph.
Parameters
----------
graph : `networkx.Graph`
A NetworkX graph.
pos : mapping, optional
A mapping with nodes as keys and positions as values. Positions should
be sequences of length 2. If not specified (default), a diagram layout
positioning will be computed. See `networkx.layout` and
`pyrrole.drawing` for functions that compute node positions.
edgelist : collection of edge `tuple`
Draw only specified edges (default is ``graph.edges()``).
width : `float`, or array of `float`
Line width of edges (default is ``1.0``).
edge_color : color `str`, or array of `float`
Edge color. Can be a single color format `str` (default is ``'r'``),
or a sequence of colors with the same length as edgelist. If numeric
values are specified they will be mapped to colors using the
`edge_cmap` and `edge_vmin`, `edge_vmax` parameters.
style : `str` (``'solid'``, ``'dashed'``, ``'dotted'``, ``'dashdot'``)
Edge line style (default is ``'dashed'``). See `matplotlib.hlines` for
more details.
alpha : `float`, optional
The edge transparency (default is ``1.0``).
edge_cmap : Matplotlib colormap, optional
Colormap for mapping intensities of edges.
edge_vmin : `float`, optional
Minimum for edge colormap scaling.
edge_vmax : `float`, optional
Maximum for edge colormap scaling.
ax : `matplotlib.axes.Axes`, optional
Draw the graph in the specified Matplotlib axes.
label : `str`, optional
Label for legend.
nodelist : `list`, optional
Draw only specified nodes (default is ``graph.nodes()``).
node_size : scalar or array
Size of nodes (default is ``.7``). If an array is specified it must be
the same length as nodelist.
Returns
-------
`matplotlib.collections.LineCollection`
`LineCollection` of the edges.
Raises
------
networkx.NetworkXError
Raised if a node has no position or one with bad value.
ValueError
Raised if `edge_color` contains something other than color names (one
or a list of one per edge) or numbers.
Examples
--------
>>> import pandas as pd
>>> from pyrrole import ChemicalSystem
>>> from pyrrole.drawing import draw_diagram_edges
>>> data = pd.DataFrame(
... [{"name": "Separated_Reactants", "freeenergy": 0.},
... {"name": "mlC1", "freeenergy": -5.4},
... {"name": "mlC2", "freeenergy": -15.6},
... {"name": "mTS1", "freeenergy": 28.5, "color": "g"},
... {"name": "mCARB1", "freeenergy": -9.7},
... {"name": "mCARB2", "freeenergy": -19.8},
... {"name": "mCARBX", "freeenergy": 20}]).set_index("name")
>>> system = ChemicalSystem(
... ["Separated_Reactants -> mlC1 -> mTS1",
... "Separated_Reactants -> mlC2 -> mTS1",
... "mCARB2 <- mTS1 -> mCARB1",
... "Separated_Reactants -> mCARBX"], data)
>>> digraph = system.to_digraph()
>>> edges = draw_diagram_edges(digraph)
"""
if ax is None:
ax = _plt.gca()
if edgelist is None:
edgelist = list(graph.edges())
if not edgelist or len(edgelist) == 0: # no edges!
return None
if nodelist is None:
nodelist = list(graph.nodes())
if pos is None:
pos = diagram_layout(graph)
try:
# set edge positions
edge_pos = _np.asarray([(pos[e[0]] + node_size/2.,
pos[e[1]] - node_size/2.) for e in edgelist])
except KeyError as e:
raise _nx.NetworkXError('Node {} has no position.'.format(e))
except ValueError:
raise _nx.NetworkXError('Bad value in node positions.')
if not _cb.iterable(width):
lw = (width,)
else:
lw = width
if not isinstance(edge_color, str) \
and _cb.iterable(edge_color) \
and len(edge_color) == len(edge_pos):
if _np.alltrue([isinstance(c, str) for c in edge_color]):
# (should check ALL elements)
# list of color letters such as ['k','r','k',...]
edge_colors = tuple([_colorConverter.to_rgba(c, alpha)
for c in edge_color])
elif _np.alltrue([not isinstance(c, str) for c in edge_color]):
# If color specs are given as (rgb) or (rgba) tuples, we're OK
if _np.alltrue([_cb.iterable(c) and len(c) in (3, 4)
for c in edge_color]):
edge_colors = tuple(edge_color)
else:
# numbers (which are going to be mapped with a colormap)
edge_colors = None
else:
raise ValueError('edge_color must contain color names or numbers')
else:
if isinstance(edge_color, str) or len(edge_color) == 1:
edge_colors = (_colorConverter.to_rgba(edge_color, alpha), )
else:
raise ValueError('edge_color must be a color or list of one color '
' per edge')
edge_collection = _LineCollection(edge_pos,
colors=edge_colors,
linewidths=lw,
antialiaseds=(1,),
linestyle=style,
transOffset=ax.transData)
edge_collection.set_zorder(1) # edges go behind nodes
edge_collection.set_label(label)
ax.add_collection(edge_collection)
if _cb.is_numlike(alpha):
edge_collection.set_alpha(alpha)
if edge_colors is None:
if edge_cmap is not None:
assert(isinstance(edge_cmap, _Colormap))
edge_collection.set_array(_np.asarray(edge_color))
edge_collection.set_cmap(edge_cmap)
if edge_vmin is not None or edge_vmax is not None:
edge_collection.set_clim(edge_vmin, edge_vmax)
else:
edge_collection.autoscale()
ax.autoscale_view()
return edge_collection | [
"def",
"draw_diagram_edges",
"(",
"graph",
",",
"pos",
"=",
"None",
",",
"edgelist",
"=",
"None",
",",
"width",
"=",
"1.0",
",",
"edge_color",
"=",
"'k'",
",",
"style",
"=",
"'dashed'",
",",
"alpha",
"=",
"1.0",
",",
"edge_cmap",
"=",
"None",
",",
"e... | Draw edges of graph.
This draws only the edges of a graph.
Parameters
----------
graph : `networkx.Graph`
A NetworkX graph.
pos : mapping, optional
A mapping with nodes as keys and positions as values. Positions should
be sequences of length 2. If not specified (default), a diagram layout
positioning will be computed. See `networkx.layout` and
`pyrrole.drawing` for functions that compute node positions.
edgelist : collection of edge `tuple`
Draw only specified edges (default is ``graph.edges()``).
width : `float`, or array of `float`
Line width of edges (default is ``1.0``).
edge_color : color `str`, or array of `float`
Edge color. Can be a single color format `str` (default is ``'r'``),
or a sequence of colors with the same length as edgelist. If numeric
values are specified they will be mapped to colors using the
`edge_cmap` and `edge_vmin`, `edge_vmax` parameters.
style : `str` (``'solid'``, ``'dashed'``, ``'dotted'``, ``'dashdot'``)
Edge line style (default is ``'dashed'``). See `matplotlib.hlines` for
more details.
alpha : `float`, optional
The edge transparency (default is ``1.0``).
edge_cmap : Matplotlib colormap, optional
Colormap for mapping intensities of edges.
edge_vmin : `float`, optional
Minimum for edge colormap scaling.
edge_vmax : `float`, optional
Maximum for edge colormap scaling.
ax : `matplotlib.axes.Axes`, optional
Draw the graph in the specified Matplotlib axes.
label : `str`, optional
Label for legend.
nodelist : `list`, optional
Draw only specified nodes (default is ``graph.nodes()``).
node_size : scalar or array
Size of nodes (default is ``.7``). If an array is specified it must be
the same length as nodelist.
Returns
-------
`matplotlib.collections.LineCollection`
`LineCollection` of the edges.
Raises
------
networkx.NetworkXError
Raised if a node has no position or one with bad value.
ValueError
Raised if `edge_color` contains something other than color names (one
or a list of one per edge) or numbers.
Examples
--------
>>> import pandas as pd
>>> from pyrrole import ChemicalSystem
>>> from pyrrole.drawing import draw_diagram_edges
>>> data = pd.DataFrame(
... [{"name": "Separated_Reactants", "freeenergy": 0.},
... {"name": "mlC1", "freeenergy": -5.4},
... {"name": "mlC2", "freeenergy": -15.6},
... {"name": "mTS1", "freeenergy": 28.5, "color": "g"},
... {"name": "mCARB1", "freeenergy": -9.7},
... {"name": "mCARB2", "freeenergy": -19.8},
... {"name": "mCARBX", "freeenergy": 20}]).set_index("name")
>>> system = ChemicalSystem(
... ["Separated_Reactants -> mlC1 -> mTS1",
... "Separated_Reactants -> mlC2 -> mTS1",
... "mCARB2 <- mTS1 -> mCARB1",
... "Separated_Reactants -> mCARBX"], data)
>>> digraph = system.to_digraph()
>>> edges = draw_diagram_edges(digraph) | [
"Draw",
"edges",
"of",
"graph",
"."
] | train | https://github.com/schneiderfelipe/pyrrole/blob/13e26accc9a059f0ab69773648b24292fe1fbfd6/pyrrole/drawing.py#L374-L536 |
schneiderfelipe/pyrrole | pyrrole/drawing.py | draw_diagram_labels | def draw_diagram_labels(graph, pos=None, labels=None, font_size=12,
font_color='k', font_family='sans-serif',
font_weight='normal', alpha=1.0, bbox=None, ax=None,
offset=None, **kwds):
"""
Draw node labels of graph.
This draws only the node labels of a graph.
Parameters
----------
graph : `networkx.Graph`
A NetworkX graph.
pos : mapping, optional
A mapping with nodes as keys and positions as values. Positions should
be sequences of length 2. If not specified (default), a diagram layout
positioning will be computed. See `networkx.layout` and
`pyrrole.drawing` for functions that compute node positions.
labels : mapping, optional
Node labels in a mapping keyed by node of text labels.
font_size : `int`, optional
Font size for text labels (default is ``12``).
font_color : `str`, optional
Font color `str` (default is ``'k'``, i.e., black).
font_family : `str`, optional
Font family (default is ``'sans-serif'``).
font_weight : `str`, optional
Font weight (default is ``'normal'``).
alpha : `float`, optional
The text transparency (default is ``1.0``).
ax : `matplotlib.axes.Axes`, optional
Draw the graph in the specified Matplotlib axes.
offset : array-like or `str`, optional
Label positions are summed to this before drawing. Defaults to zero
vector. If `str`, can be either ``'above'`` (equivalent to
``(0, 1.5)``) or ``'below'`` (equivalent to ``(0, -1.5)``).
Returns
-------
mapping
Mapping of labels keyed on the nodes.
Examples
--------
>>> import pandas as pd
>>> from pyrrole import ChemicalSystem
>>> from pyrrole.drawing import draw_diagram_labels
>>> data = pd.DataFrame(
... [{"name": "Separated_Reactants", "freeenergy": 0.},
... {"name": "mlC1", "freeenergy": -5.4},
... {"name": "mlC2", "freeenergy": -15.6},
... {"name": "mTS1", "freeenergy": 28.5, "color": "g"},
... {"name": "mCARB1", "freeenergy": -9.7},
... {"name": "mCARB2", "freeenergy": -19.8},
... {"name": "mCARBX", "freeenergy": 20}]).set_index("name")
>>> system = ChemicalSystem(
... ["Separated_Reactants -> mlC1 -> mTS1",
... "Separated_Reactants -> mlC2 -> mTS1",
... "mCARB2 <- mTS1 -> mCARB1",
... "Separated_Reactants -> mCARBX"], data)
>>> digraph = system.to_digraph()
>>> edges = draw_diagram_labels(digraph, font_color='blue',
... offset="below")
>>> labels = {k: "{:g}".format(v)
... for k, v in digraph.nodes(data='freeenergy')}
>>> edges = draw_diagram_labels(digraph, labels=labels,
... offset="above")
"""
if ax is None:
ax = _plt.gca()
if labels is None:
labels = dict((n, n) for n in graph.nodes())
if pos is None:
pos = diagram_layout(graph)
if offset is None:
offset = _np.array([0., 0.])
elif offset == "above":
offset = _np.array([0., 1.5])
elif offset == "below":
offset = _np.array([0., -1.5])
# set optional alignment
horizontalalignment = kwds.get('horizontalalignment', 'center')
verticalalignment = kwds.get('verticalalignment', 'center')
text_items = {} # there is no text collection so we'll fake one
for n, label in labels.items():
(x, y) = _np.asanyarray(pos[n]) + _np.asanyarray(offset)
if not isinstance(label, str):
label = str(label) # this makes "1" and 1 labeled the same
t = ax.text(x, y, label,
size=font_size,
color=font_color,
family=font_family,
weight=font_weight,
alpha=alpha,
horizontalalignment=horizontalalignment,
verticalalignment=verticalalignment,
transform=ax.transData,
bbox=bbox,
clip_on=True)
text_items[n] = t
return text_items | python | def draw_diagram_labels(graph, pos=None, labels=None, font_size=12,
font_color='k', font_family='sans-serif',
font_weight='normal', alpha=1.0, bbox=None, ax=None,
offset=None, **kwds):
"""
Draw node labels of graph.
This draws only the node labels of a graph.
Parameters
----------
graph : `networkx.Graph`
A NetworkX graph.
pos : mapping, optional
A mapping with nodes as keys and positions as values. Positions should
be sequences of length 2. If not specified (default), a diagram layout
positioning will be computed. See `networkx.layout` and
`pyrrole.drawing` for functions that compute node positions.
labels : mapping, optional
Node labels in a mapping keyed by node of text labels.
font_size : `int`, optional
Font size for text labels (default is ``12``).
font_color : `str`, optional
Font color `str` (default is ``'k'``, i.e., black).
font_family : `str`, optional
Font family (default is ``'sans-serif'``).
font_weight : `str`, optional
Font weight (default is ``'normal'``).
alpha : `float`, optional
The text transparency (default is ``1.0``).
ax : `matplotlib.axes.Axes`, optional
Draw the graph in the specified Matplotlib axes.
offset : array-like or `str`, optional
Label positions are summed to this before drawing. Defaults to zero
vector. If `str`, can be either ``'above'`` (equivalent to
``(0, 1.5)``) or ``'below'`` (equivalent to ``(0, -1.5)``).
Returns
-------
mapping
Mapping of labels keyed on the nodes.
Examples
--------
>>> import pandas as pd
>>> from pyrrole import ChemicalSystem
>>> from pyrrole.drawing import draw_diagram_labels
>>> data = pd.DataFrame(
... [{"name": "Separated_Reactants", "freeenergy": 0.},
... {"name": "mlC1", "freeenergy": -5.4},
... {"name": "mlC2", "freeenergy": -15.6},
... {"name": "mTS1", "freeenergy": 28.5, "color": "g"},
... {"name": "mCARB1", "freeenergy": -9.7},
... {"name": "mCARB2", "freeenergy": -19.8},
... {"name": "mCARBX", "freeenergy": 20}]).set_index("name")
>>> system = ChemicalSystem(
... ["Separated_Reactants -> mlC1 -> mTS1",
... "Separated_Reactants -> mlC2 -> mTS1",
... "mCARB2 <- mTS1 -> mCARB1",
... "Separated_Reactants -> mCARBX"], data)
>>> digraph = system.to_digraph()
>>> edges = draw_diagram_labels(digraph, font_color='blue',
... offset="below")
>>> labels = {k: "{:g}".format(v)
... for k, v in digraph.nodes(data='freeenergy')}
>>> edges = draw_diagram_labels(digraph, labels=labels,
... offset="above")
"""
if ax is None:
ax = _plt.gca()
if labels is None:
labels = dict((n, n) for n in graph.nodes())
if pos is None:
pos = diagram_layout(graph)
if offset is None:
offset = _np.array([0., 0.])
elif offset == "above":
offset = _np.array([0., 1.5])
elif offset == "below":
offset = _np.array([0., -1.5])
# set optional alignment
horizontalalignment = kwds.get('horizontalalignment', 'center')
verticalalignment = kwds.get('verticalalignment', 'center')
text_items = {} # there is no text collection so we'll fake one
for n, label in labels.items():
(x, y) = _np.asanyarray(pos[n]) + _np.asanyarray(offset)
if not isinstance(label, str):
label = str(label) # this makes "1" and 1 labeled the same
t = ax.text(x, y, label,
size=font_size,
color=font_color,
family=font_family,
weight=font_weight,
alpha=alpha,
horizontalalignment=horizontalalignment,
verticalalignment=verticalalignment,
transform=ax.transData,
bbox=bbox,
clip_on=True)
text_items[n] = t
return text_items | [
"def",
"draw_diagram_labels",
"(",
"graph",
",",
"pos",
"=",
"None",
",",
"labels",
"=",
"None",
",",
"font_size",
"=",
"12",
",",
"font_color",
"=",
"'k'",
",",
"font_family",
"=",
"'sans-serif'",
",",
"font_weight",
"=",
"'normal'",
",",
"alpha",
"=",
... | Draw node labels of graph.
This draws only the node labels of a graph.
Parameters
----------
graph : `networkx.Graph`
A NetworkX graph.
pos : mapping, optional
A mapping with nodes as keys and positions as values. Positions should
be sequences of length 2. If not specified (default), a diagram layout
positioning will be computed. See `networkx.layout` and
`pyrrole.drawing` for functions that compute node positions.
labels : mapping, optional
Node labels in a mapping keyed by node of text labels.
font_size : `int`, optional
Font size for text labels (default is ``12``).
font_color : `str`, optional
Font color `str` (default is ``'k'``, i.e., black).
font_family : `str`, optional
Font family (default is ``'sans-serif'``).
font_weight : `str`, optional
Font weight (default is ``'normal'``).
alpha : `float`, optional
The text transparency (default is ``1.0``).
ax : `matplotlib.axes.Axes`, optional
Draw the graph in the specified Matplotlib axes.
offset : array-like or `str`, optional
Label positions are summed to this before drawing. Defaults to zero
vector. If `str`, can be either ``'above'`` (equivalent to
``(0, 1.5)``) or ``'below'`` (equivalent to ``(0, -1.5)``).
Returns
-------
mapping
Mapping of labels keyed on the nodes.
Examples
--------
>>> import pandas as pd
>>> from pyrrole import ChemicalSystem
>>> from pyrrole.drawing import draw_diagram_labels
>>> data = pd.DataFrame(
... [{"name": "Separated_Reactants", "freeenergy": 0.},
... {"name": "mlC1", "freeenergy": -5.4},
... {"name": "mlC2", "freeenergy": -15.6},
... {"name": "mTS1", "freeenergy": 28.5, "color": "g"},
... {"name": "mCARB1", "freeenergy": -9.7},
... {"name": "mCARB2", "freeenergy": -19.8},
... {"name": "mCARBX", "freeenergy": 20}]).set_index("name")
>>> system = ChemicalSystem(
... ["Separated_Reactants -> mlC1 -> mTS1",
... "Separated_Reactants -> mlC2 -> mTS1",
... "mCARB2 <- mTS1 -> mCARB1",
... "Separated_Reactants -> mCARBX"], data)
>>> digraph = system.to_digraph()
>>> edges = draw_diagram_labels(digraph, font_color='blue',
... offset="below")
>>> labels = {k: "{:g}".format(v)
... for k, v in digraph.nodes(data='freeenergy')}
>>> edges = draw_diagram_labels(digraph, labels=labels,
... offset="above") | [
"Draw",
"node",
"labels",
"of",
"graph",
"."
] | train | https://github.com/schneiderfelipe/pyrrole/blob/13e26accc9a059f0ab69773648b24292fe1fbfd6/pyrrole/drawing.py#L539-L646 |
schneiderfelipe/pyrrole | pyrrole/drawing.py | draw_diagram | def draw_diagram(graph, pos=None, with_labels=True, offset=None, **kwds):
"""
Draw a diagram for graph using Matplotlib.
Draw graph as a simple energy diagram with Matplotlib with options for node
positions, labeling, titles, and many other drawing features. See examples
below.
Parameters
----------
graph : `networkx.Graph`
A NetworkX graph.
pos : mapping, optional
A mapping with nodes as keys and positions as values. Positions should
be sequences of length 2. If not specified (default) a diagram layout
positioning will be computed. See `networkx.drawing.layout` and
`pyrrole.drawing` for functions that compute node positions.
with_labels : `bool`, optional
Set to `True` (default) to draw labels on the nodes.
offset : array-like or `str`, optional
Label positions are summed to this before drawing. Defaults to
``'below'``. See `draw_diagram_labels` for more.
Notes
-----
Further keywords are passed to `draw_diagram_nodes` and
`draw_diagram_edges`. If `pos` is `None`, `diagram_layout` is also called
and have keywords passed as well. The same happens with
`draw_diagram_labels` if `with_labels` is `True`.
Examples
--------
>>> import pandas as pd
>>> from pyrrole import ChemicalSystem
>>> from pyrrole.drawing import draw_diagram, draw_diagram_labels
>>> data = pd.DataFrame(
... [{"name": "Separated_Reactants", "freeenergy": 0.},
... {"name": "mlC1", "freeenergy": -5.4},
... {"name": "mlC2", "freeenergy": -15.6},
... {"name": "mTS1", "freeenergy": 28.5, "color": "g"},
... {"name": "mCARB1", "freeenergy": -9.7},
... {"name": "mCARB2", "freeenergy": -19.8},
... {"name": "mCARBX", "freeenergy": 20}]).set_index("name")
>>> system = ChemicalSystem(
... ["Separated_Reactants -> mlC1 -> mTS1",
... "Separated_Reactants -> mlC2 -> mTS1",
... "mCARB2 <- mTS1 -> mCARB1",
... "Separated_Reactants -> mCARBX"], data)
>>> digraph = system.to_digraph()
>>> draw_diagram(digraph)
>>> labels = {k: "{:g}".format(v)
... for k, v in digraph.nodes(data='freeenergy')}
>>> edges = draw_diagram_labels(digraph, labels=labels,
... offset="above")
"""
if pos is None:
pos = diagram_layout(graph, **kwds) # default to diagram layout
node_collection = draw_diagram_nodes(graph, pos, **kwds) # noqa
edge_collection = draw_diagram_edges(graph, pos, **kwds) # noqa
if with_labels:
if offset is None:
# TODO: This changes the default behaviour of draw_diagram_labels.
offset = "below"
draw_diagram_labels(graph, pos, offset=offset, **kwds)
_plt.draw_if_interactive() | python | def draw_diagram(graph, pos=None, with_labels=True, offset=None, **kwds):
"""
Draw a diagram for graph using Matplotlib.
Draw graph as a simple energy diagram with Matplotlib with options for node
positions, labeling, titles, and many other drawing features. See examples
below.
Parameters
----------
graph : `networkx.Graph`
A NetworkX graph.
pos : mapping, optional
A mapping with nodes as keys and positions as values. Positions should
be sequences of length 2. If not specified (default) a diagram layout
positioning will be computed. See `networkx.drawing.layout` and
`pyrrole.drawing` for functions that compute node positions.
with_labels : `bool`, optional
Set to `True` (default) to draw labels on the nodes.
offset : array-like or `str`, optional
Label positions are summed to this before drawing. Defaults to
``'below'``. See `draw_diagram_labels` for more.
Notes
-----
Further keywords are passed to `draw_diagram_nodes` and
`draw_diagram_edges`. If `pos` is `None`, `diagram_layout` is also called
and have keywords passed as well. The same happens with
`draw_diagram_labels` if `with_labels` is `True`.
Examples
--------
>>> import pandas as pd
>>> from pyrrole import ChemicalSystem
>>> from pyrrole.drawing import draw_diagram, draw_diagram_labels
>>> data = pd.DataFrame(
... [{"name": "Separated_Reactants", "freeenergy": 0.},
... {"name": "mlC1", "freeenergy": -5.4},
... {"name": "mlC2", "freeenergy": -15.6},
... {"name": "mTS1", "freeenergy": 28.5, "color": "g"},
... {"name": "mCARB1", "freeenergy": -9.7},
... {"name": "mCARB2", "freeenergy": -19.8},
... {"name": "mCARBX", "freeenergy": 20}]).set_index("name")
>>> system = ChemicalSystem(
... ["Separated_Reactants -> mlC1 -> mTS1",
... "Separated_Reactants -> mlC2 -> mTS1",
... "mCARB2 <- mTS1 -> mCARB1",
... "Separated_Reactants -> mCARBX"], data)
>>> digraph = system.to_digraph()
>>> draw_diagram(digraph)
>>> labels = {k: "{:g}".format(v)
... for k, v in digraph.nodes(data='freeenergy')}
>>> edges = draw_diagram_labels(digraph, labels=labels,
... offset="above")
"""
if pos is None:
pos = diagram_layout(graph, **kwds) # default to diagram layout
node_collection = draw_diagram_nodes(graph, pos, **kwds) # noqa
edge_collection = draw_diagram_edges(graph, pos, **kwds) # noqa
if with_labels:
if offset is None:
# TODO: This changes the default behaviour of draw_diagram_labels.
offset = "below"
draw_diagram_labels(graph, pos, offset=offset, **kwds)
_plt.draw_if_interactive() | [
"def",
"draw_diagram",
"(",
"graph",
",",
"pos",
"=",
"None",
",",
"with_labels",
"=",
"True",
",",
"offset",
"=",
"None",
",",
"*",
"*",
"kwds",
")",
":",
"if",
"pos",
"is",
"None",
":",
"pos",
"=",
"diagram_layout",
"(",
"graph",
",",
"*",
"*",
... | Draw a diagram for graph using Matplotlib.
Draw graph as a simple energy diagram with Matplotlib with options for node
positions, labeling, titles, and many other drawing features. See examples
below.
Parameters
----------
graph : `networkx.Graph`
A NetworkX graph.
pos : mapping, optional
A mapping with nodes as keys and positions as values. Positions should
be sequences of length 2. If not specified (default) a diagram layout
positioning will be computed. See `networkx.drawing.layout` and
`pyrrole.drawing` for functions that compute node positions.
with_labels : `bool`, optional
Set to `True` (default) to draw labels on the nodes.
offset : array-like or `str`, optional
Label positions are summed to this before drawing. Defaults to
``'below'``. See `draw_diagram_labels` for more.
Notes
-----
Further keywords are passed to `draw_diagram_nodes` and
`draw_diagram_edges`. If `pos` is `None`, `diagram_layout` is also called
and have keywords passed as well. The same happens with
`draw_diagram_labels` if `with_labels` is `True`.
Examples
--------
>>> import pandas as pd
>>> from pyrrole import ChemicalSystem
>>> from pyrrole.drawing import draw_diagram, draw_diagram_labels
>>> data = pd.DataFrame(
... [{"name": "Separated_Reactants", "freeenergy": 0.},
... {"name": "mlC1", "freeenergy": -5.4},
... {"name": "mlC2", "freeenergy": -15.6},
... {"name": "mTS1", "freeenergy": 28.5, "color": "g"},
... {"name": "mCARB1", "freeenergy": -9.7},
... {"name": "mCARB2", "freeenergy": -19.8},
... {"name": "mCARBX", "freeenergy": 20}]).set_index("name")
>>> system = ChemicalSystem(
... ["Separated_Reactants -> mlC1 -> mTS1",
... "Separated_Reactants -> mlC2 -> mTS1",
... "mCARB2 <- mTS1 -> mCARB1",
... "Separated_Reactants -> mCARBX"], data)
>>> digraph = system.to_digraph()
>>> draw_diagram(digraph)
>>> labels = {k: "{:g}".format(v)
... for k, v in digraph.nodes(data='freeenergy')}
>>> edges = draw_diagram_labels(digraph, labels=labels,
... offset="above") | [
"Draw",
"a",
"diagram",
"for",
"graph",
"using",
"Matplotlib",
"."
] | train | https://github.com/schneiderfelipe/pyrrole/blob/13e26accc9a059f0ab69773648b24292fe1fbfd6/pyrrole/drawing.py#L649-L715 |
pebble/libpebble2 | libpebble2/protocol/base/__init__.py | PebblePacket.serialise | def serialise(self, default_endianness=None):
"""
Serialise a message, without including any framing.
:param default_endianness: The default endianness, unless overridden by the fields or class metadata.
Should usually be left at ``None``. Otherwise, use ``'<'`` for little endian and
``'>'`` for big endian.
:type default_endianness: str
:return: The serialised message.
:rtype: bytes
"""
# Figure out an endianness.
endianness = (default_endianness or DEFAULT_ENDIANNESS)
if hasattr(self, '_Meta'):
endianness = self._Meta.get('endianness', endianness)
inferred_fields = set()
for k, v in iteritems(self._type_mapping):
inferred_fields |= {x._name for x in v.dependent_fields()}
for field in inferred_fields:
setattr(self, field, None)
# Some fields want to manipulate other fields that appear before them (e.g. Unions)
for k, v in iteritems(self._type_mapping):
v.prepare(self, getattr(self, k))
message = b''
for k, v in iteritems(self._type_mapping):
message += v.value_to_bytes(self, getattr(self, k), default_endianness=endianness)
return message | python | def serialise(self, default_endianness=None):
"""
Serialise a message, without including any framing.
:param default_endianness: The default endianness, unless overridden by the fields or class metadata.
Should usually be left at ``None``. Otherwise, use ``'<'`` for little endian and
``'>'`` for big endian.
:type default_endianness: str
:return: The serialised message.
:rtype: bytes
"""
# Figure out an endianness.
endianness = (default_endianness or DEFAULT_ENDIANNESS)
if hasattr(self, '_Meta'):
endianness = self._Meta.get('endianness', endianness)
inferred_fields = set()
for k, v in iteritems(self._type_mapping):
inferred_fields |= {x._name for x in v.dependent_fields()}
for field in inferred_fields:
setattr(self, field, None)
# Some fields want to manipulate other fields that appear before them (e.g. Unions)
for k, v in iteritems(self._type_mapping):
v.prepare(self, getattr(self, k))
message = b''
for k, v in iteritems(self._type_mapping):
message += v.value_to_bytes(self, getattr(self, k), default_endianness=endianness)
return message | [
"def",
"serialise",
"(",
"self",
",",
"default_endianness",
"=",
"None",
")",
":",
"# Figure out an endianness.",
"endianness",
"=",
"(",
"default_endianness",
"or",
"DEFAULT_ENDIANNESS",
")",
"if",
"hasattr",
"(",
"self",
",",
"'_Meta'",
")",
":",
"endianness",
... | Serialise a message, without including any framing.
:param default_endianness: The default endianness, unless overridden by the fields or class metadata.
Should usually be left at ``None``. Otherwise, use ``'<'`` for little endian and
``'>'`` for big endian.
:type default_endianness: str
:return: The serialised message.
:rtype: bytes | [
"Serialise",
"a",
"message",
"without",
"including",
"any",
"framing",
"."
] | train | https://github.com/pebble/libpebble2/blob/23e2eb92cfc084e6f9e8c718711ac994ef606d18/libpebble2/protocol/base/__init__.py#L112-L141 |
pebble/libpebble2 | libpebble2/protocol/base/__init__.py | PebblePacket.serialise_packet | def serialise_packet(self):
"""
Serialise a message, including framing information inferred from the ``Meta`` inner class of the packet.
``self.Meta.endpoint`` must be defined to call this method.
:return: A serialised message, ready to be sent to the Pebble.
"""
if not hasattr(self, '_Meta'):
raise ReferenceError("Can't serialise a packet that doesn't have an endpoint ID.")
serialised = self.serialise()
return struct.pack('!HH', len(serialised), self._Meta['endpoint']) + serialised | python | def serialise_packet(self):
"""
Serialise a message, including framing information inferred from the ``Meta`` inner class of the packet.
``self.Meta.endpoint`` must be defined to call this method.
:return: A serialised message, ready to be sent to the Pebble.
"""
if not hasattr(self, '_Meta'):
raise ReferenceError("Can't serialise a packet that doesn't have an endpoint ID.")
serialised = self.serialise()
return struct.pack('!HH', len(serialised), self._Meta['endpoint']) + serialised | [
"def",
"serialise_packet",
"(",
"self",
")",
":",
"if",
"not",
"hasattr",
"(",
"self",
",",
"'_Meta'",
")",
":",
"raise",
"ReferenceError",
"(",
"\"Can't serialise a packet that doesn't have an endpoint ID.\"",
")",
"serialised",
"=",
"self",
".",
"serialise",
"(",
... | Serialise a message, including framing information inferred from the ``Meta`` inner class of the packet.
``self.Meta.endpoint`` must be defined to call this method.
:return: A serialised message, ready to be sent to the Pebble. | [
"Serialise",
"a",
"message",
"including",
"framing",
"information",
"inferred",
"from",
"the",
"Meta",
"inner",
"class",
"of",
"the",
"packet",
".",
"self",
".",
"Meta",
".",
"endpoint",
"must",
"be",
"defined",
"to",
"call",
"this",
"method",
"."
] | train | https://github.com/pebble/libpebble2/blob/23e2eb92cfc084e6f9e8c718711ac994ef606d18/libpebble2/protocol/base/__init__.py#L143-L153 |
pebble/libpebble2 | libpebble2/protocol/base/__init__.py | PebblePacket.parse_message | def parse_message(cls, message):
"""
Parses a message received from the Pebble. Uses Pebble Protocol framing to figure out what sort of packet
it is. If the packet is registered (has been defined and imported), returns the deserialised packet, which will
not necessarily be the same class as this. Otherwise returns ``None``.
Also returns the length of the message consumed during deserialisation.
:param message: A serialised message received from the Pebble.
:type message: bytes
:return: ``(decoded_message, decoded length)``
:rtype: (:class:`PebblePacket`, :any:`int`)
"""
length = struct.unpack_from('!H', message, 0)[0] + 4
if len(message) < length:
raise IncompleteMessage()
command, = struct.unpack_from('!H', message, 2)
if command in _PacketRegistry:
return _PacketRegistry[command].parse(message[4:length])[0], length
else:
return None, length | python | def parse_message(cls, message):
"""
Parses a message received from the Pebble. Uses Pebble Protocol framing to figure out what sort of packet
it is. If the packet is registered (has been defined and imported), returns the deserialised packet, which will
not necessarily be the same class as this. Otherwise returns ``None``.
Also returns the length of the message consumed during deserialisation.
:param message: A serialised message received from the Pebble.
:type message: bytes
:return: ``(decoded_message, decoded length)``
:rtype: (:class:`PebblePacket`, :any:`int`)
"""
length = struct.unpack_from('!H', message, 0)[0] + 4
if len(message) < length:
raise IncompleteMessage()
command, = struct.unpack_from('!H', message, 2)
if command in _PacketRegistry:
return _PacketRegistry[command].parse(message[4:length])[0], length
else:
return None, length | [
"def",
"parse_message",
"(",
"cls",
",",
"message",
")",
":",
"length",
"=",
"struct",
".",
"unpack_from",
"(",
"'!H'",
",",
"message",
",",
"0",
")",
"[",
"0",
"]",
"+",
"4",
"if",
"len",
"(",
"message",
")",
"<",
"length",
":",
"raise",
"Incomple... | Parses a message received from the Pebble. Uses Pebble Protocol framing to figure out what sort of packet
it is. If the packet is registered (has been defined and imported), returns the deserialised packet, which will
not necessarily be the same class as this. Otherwise returns ``None``.
Also returns the length of the message consumed during deserialisation.
:param message: A serialised message received from the Pebble.
:type message: bytes
:return: ``(decoded_message, decoded length)``
:rtype: (:class:`PebblePacket`, :any:`int`) | [
"Parses",
"a",
"message",
"received",
"from",
"the",
"Pebble",
".",
"Uses",
"Pebble",
"Protocol",
"framing",
"to",
"figure",
"out",
"what",
"sort",
"of",
"packet",
"it",
"is",
".",
"If",
"the",
"packet",
"is",
"registered",
"(",
"has",
"been",
"defined",
... | train | https://github.com/pebble/libpebble2/blob/23e2eb92cfc084e6f9e8c718711ac994ef606d18/libpebble2/protocol/base/__init__.py#L156-L176 |
pebble/libpebble2 | libpebble2/protocol/base/__init__.py | PebblePacket.parse | def parse(cls, message, default_endianness=DEFAULT_ENDIANNESS):
"""
Parses a message without any framing, returning the decoded result and length of message consumed. The result
will always be of the same class as :meth:`parse` was called on. If the message is invalid,
:exc:`.PacketDecodeError` will be raised.
:param message: The message to decode.
:type message: bytes
:param default_endianness: The default endianness, unless overridden by the fields or class metadata.
Should usually be left at ``None``. Otherwise, use ``'<'`` for little endian and
``'>'`` for big endian.
:return: ``(decoded_message, decoded length)``
:rtype: (:class:`PebblePacket`, :any:`int`)
"""
obj = cls()
offset = 0
if hasattr(cls, '_Meta'):
default_endianness = cls._Meta.get('endianness', default_endianness)
for k, v in iteritems(cls._type_mapping):
try:
value, length = v.buffer_to_value(obj, message, offset, default_endianness=default_endianness)
except Exception:
logger.warning("Exception decoding {}.{}".format(cls.__name__, k))
raise
offset += length
setattr(obj, k, value)
return obj, offset | python | def parse(cls, message, default_endianness=DEFAULT_ENDIANNESS):
"""
Parses a message without any framing, returning the decoded result and length of message consumed. The result
will always be of the same class as :meth:`parse` was called on. If the message is invalid,
:exc:`.PacketDecodeError` will be raised.
:param message: The message to decode.
:type message: bytes
:param default_endianness: The default endianness, unless overridden by the fields or class metadata.
Should usually be left at ``None``. Otherwise, use ``'<'`` for little endian and
``'>'`` for big endian.
:return: ``(decoded_message, decoded length)``
:rtype: (:class:`PebblePacket`, :any:`int`)
"""
obj = cls()
offset = 0
if hasattr(cls, '_Meta'):
default_endianness = cls._Meta.get('endianness', default_endianness)
for k, v in iteritems(cls._type_mapping):
try:
value, length = v.buffer_to_value(obj, message, offset, default_endianness=default_endianness)
except Exception:
logger.warning("Exception decoding {}.{}".format(cls.__name__, k))
raise
offset += length
setattr(obj, k, value)
return obj, offset | [
"def",
"parse",
"(",
"cls",
",",
"message",
",",
"default_endianness",
"=",
"DEFAULT_ENDIANNESS",
")",
":",
"obj",
"=",
"cls",
"(",
")",
"offset",
"=",
"0",
"if",
"hasattr",
"(",
"cls",
",",
"'_Meta'",
")",
":",
"default_endianness",
"=",
"cls",
".",
"... | Parses a message without any framing, returning the decoded result and length of message consumed. The result
will always be of the same class as :meth:`parse` was called on. If the message is invalid,
:exc:`.PacketDecodeError` will be raised.
:param message: The message to decode.
:type message: bytes
:param default_endianness: The default endianness, unless overridden by the fields or class metadata.
Should usually be left at ``None``. Otherwise, use ``'<'`` for little endian and
``'>'`` for big endian.
:return: ``(decoded_message, decoded length)``
:rtype: (:class:`PebblePacket`, :any:`int`) | [
"Parses",
"a",
"message",
"without",
"any",
"framing",
"returning",
"the",
"decoded",
"result",
"and",
"length",
"of",
"message",
"consumed",
".",
"The",
"result",
"will",
"always",
"be",
"of",
"the",
"same",
"class",
"as",
":",
"meth",
":",
"parse",
"was"... | train | https://github.com/pebble/libpebble2/blob/23e2eb92cfc084e6f9e8c718711ac994ef606d18/libpebble2/protocol/base/__init__.py#L179-L205 |
tkf/rash | rash/query.py | expand_query | def expand_query(config, kwds):
"""
Expand `kwds` based on `config.search.query_expander`.
:type config: .config.Configuration
:type kwds: dict
:rtype: dict
:return: Return `kwds`, modified in place.
"""
pattern = []
for query in kwds.pop('pattern', []):
expansion = config.search.alias.get(query)
if expansion is None:
pattern.append(query)
else:
parser = SafeArgumentParser()
search_add_arguments(parser)
ns = parser.parse_args(expansion)
for (key, value) in vars(ns).items():
if isinstance(value, (list, tuple)):
if not kwds.get(key):
kwds[key] = value
else:
kwds[key].extend(value)
else:
kwds[key] = value
kwds['pattern'] = pattern
return config.search.kwds_adapter(kwds) | python | def expand_query(config, kwds):
"""
Expand `kwds` based on `config.search.query_expander`.
:type config: .config.Configuration
:type kwds: dict
:rtype: dict
:return: Return `kwds`, modified in place.
"""
pattern = []
for query in kwds.pop('pattern', []):
expansion = config.search.alias.get(query)
if expansion is None:
pattern.append(query)
else:
parser = SafeArgumentParser()
search_add_arguments(parser)
ns = parser.parse_args(expansion)
for (key, value) in vars(ns).items():
if isinstance(value, (list, tuple)):
if not kwds.get(key):
kwds[key] = value
else:
kwds[key].extend(value)
else:
kwds[key] = value
kwds['pattern'] = pattern
return config.search.kwds_adapter(kwds) | [
"def",
"expand_query",
"(",
"config",
",",
"kwds",
")",
":",
"pattern",
"=",
"[",
"]",
"for",
"query",
"in",
"kwds",
".",
"pop",
"(",
"'pattern'",
",",
"[",
"]",
")",
":",
"expansion",
"=",
"config",
".",
"search",
".",
"alias",
".",
"get",
"(",
... | Expand `kwds` based on `config.search.query_expander`.
:type config: .config.Configuration
:type kwds: dict
:rtype: dict
:return: Return `kwds`, modified in place. | [
"Expand",
"kwds",
"based",
"on",
"config",
".",
"search",
".",
"query_expander",
"."
] | train | https://github.com/tkf/rash/blob/585da418ec37dd138f1a4277718b6f507e9536a2/rash/query.py#L32-L60 |
tkf/rash | rash/query.py | preprocess_kwds | def preprocess_kwds(kwds):
"""
Preprocess keyword arguments for `DataBase.search_command_record`.
"""
from .utils.timeutils import parse_datetime, parse_duration
for key in ['output', 'format', 'format_level',
'with_command_id', 'with_session_id']:
kwds.pop(key, None)
for key in ['time_after', 'time_before']:
val = kwds[key]
if val:
dt = parse_datetime(val)
if dt:
kwds[key] = dt
for key in ['duration_longer_than', 'duration_less_than']:
val = kwds[key]
if val:
dt = parse_duration(val)
if dt:
kwds[key] = dt
# interpret "pattern" (currently just copying to --include-pattern)
less_strict_pattern = list(map("*{0}*".format, kwds.pop('pattern', [])))
kwds['match_pattern'] = kwds['match_pattern'] + less_strict_pattern
if not kwds['sort_by']:
kwds['sort_by'] = ['count']
kwds['sort_by'] = [SORT_KEY_SYNONYMS[k] for k in kwds['sort_by']]
return kwds | python | def preprocess_kwds(kwds):
"""
Preprocess keyword arguments for `DataBase.search_command_record`.
"""
from .utils.timeutils import parse_datetime, parse_duration
for key in ['output', 'format', 'format_level',
'with_command_id', 'with_session_id']:
kwds.pop(key, None)
for key in ['time_after', 'time_before']:
val = kwds[key]
if val:
dt = parse_datetime(val)
if dt:
kwds[key] = dt
for key in ['duration_longer_than', 'duration_less_than']:
val = kwds[key]
if val:
dt = parse_duration(val)
if dt:
kwds[key] = dt
# interpret "pattern" (currently just copying to --include-pattern)
less_strict_pattern = list(map("*{0}*".format, kwds.pop('pattern', [])))
kwds['match_pattern'] = kwds['match_pattern'] + less_strict_pattern
if not kwds['sort_by']:
kwds['sort_by'] = ['count']
kwds['sort_by'] = [SORT_KEY_SYNONYMS[k] for k in kwds['sort_by']]
return kwds | [
"def",
"preprocess_kwds",
"(",
"kwds",
")",
":",
"from",
".",
"utils",
".",
"timeutils",
"import",
"parse_datetime",
",",
"parse_duration",
"for",
"key",
"in",
"[",
"'output'",
",",
"'format'",
",",
"'format_level'",
",",
"'with_command_id'",
",",
"'with_session... | Preprocess keyword arguments for `DataBase.search_command_record`. | [
"Preprocess",
"keyword",
"arguments",
"for",
"DataBase",
".",
"search_command_record",
"."
] | train | https://github.com/tkf/rash/blob/585da418ec37dd138f1a4277718b6f507e9536a2/rash/query.py#L63-L94 |
RonenNess/grepfunc | grepfunc/grepfunc.py | __fix_args | def __fix_args(kwargs):
"""
Set all named arguments shortcuts and flags.
"""
kwargs.setdefault('fixed_strings', kwargs.get('F'))
kwargs.setdefault('basic_regexp', kwargs.get('G'))
kwargs.setdefault('extended_regexp', kwargs.get('E'))
kwargs.setdefault('ignore_case', kwargs.get('i'))
kwargs.setdefault('invert', kwargs.get('v'))
kwargs.setdefault('words', kwargs.get('w'))
kwargs.setdefault('line', kwargs.get('x'))
kwargs.setdefault('count', kwargs.get('c'))
kwargs.setdefault('max_count', kwargs.get('m'))
kwargs.setdefault('after_context', kwargs.get('A'))
kwargs.setdefault('before_context', kwargs.get('B'))
kwargs.setdefault('quiet', kwargs.get('q'))
kwargs.setdefault('byte_offset', kwargs.get('b'))
kwargs.setdefault('only_matching', kwargs.get('o'))
kwargs.setdefault('line_number', kwargs.get('n'))
kwargs.setdefault('regex_flags', kwargs.get('r'))
kwargs.setdefault('keep_eol', kwargs.get('k'))
kwargs.setdefault('trim', kwargs.get('t')) | python | def __fix_args(kwargs):
"""
Set all named arguments shortcuts and flags.
"""
kwargs.setdefault('fixed_strings', kwargs.get('F'))
kwargs.setdefault('basic_regexp', kwargs.get('G'))
kwargs.setdefault('extended_regexp', kwargs.get('E'))
kwargs.setdefault('ignore_case', kwargs.get('i'))
kwargs.setdefault('invert', kwargs.get('v'))
kwargs.setdefault('words', kwargs.get('w'))
kwargs.setdefault('line', kwargs.get('x'))
kwargs.setdefault('count', kwargs.get('c'))
kwargs.setdefault('max_count', kwargs.get('m'))
kwargs.setdefault('after_context', kwargs.get('A'))
kwargs.setdefault('before_context', kwargs.get('B'))
kwargs.setdefault('quiet', kwargs.get('q'))
kwargs.setdefault('byte_offset', kwargs.get('b'))
kwargs.setdefault('only_matching', kwargs.get('o'))
kwargs.setdefault('line_number', kwargs.get('n'))
kwargs.setdefault('regex_flags', kwargs.get('r'))
kwargs.setdefault('keep_eol', kwargs.get('k'))
kwargs.setdefault('trim', kwargs.get('t')) | [
"def",
"__fix_args",
"(",
"kwargs",
")",
":",
"kwargs",
".",
"setdefault",
"(",
"'fixed_strings'",
",",
"kwargs",
".",
"get",
"(",
"'F'",
")",
")",
"kwargs",
".",
"setdefault",
"(",
"'basic_regexp'",
",",
"kwargs",
".",
"get",
"(",
"'G'",
")",
")",
"kw... | Set all named arguments shortcuts and flags. | [
"Set",
"all",
"named",
"arguments",
"shortcuts",
"and",
"flags",
"."
] | train | https://github.com/RonenNess/grepfunc/blob/a5323d082c0a581e4b053ef85838c9a0101b43ff/grepfunc/grepfunc.py#L18-L39 |
RonenNess/grepfunc | grepfunc/grepfunc.py | grep | def grep(target, pattern, **kwargs):
"""
Main grep function.
:param target: Target to apply grep on. Can be a single string, an iterable, a function, or an opened file handler.
:param pattern: Grep pattern to search.
:param kwargs: Optional flags (note: the docs below talk about matching 'lines', but this function also accept lists
and other iterables - in those cases, a 'line' means a single value from the iterable).
The available flags are:
- F, fixed_strings: Interpret 'pattern' as a string or a list of strings, any of which is to be matched.
If not set, will interpret 'pattern' as a python regular expression.
- i, ignore_case: Ignore case.
- v, invert: Invert (eg return non-matching lines / values).
- w, words: Select only those lines containing matches that form whole words.
- x, line: Select only matches that exactly match the whole line.
- c, count: Instead of the normal output, print a count of matching lines.
- m NUM, max_count: Stop reading after NUM matching values.
- A NUM, after_context: Return NUM lines of trailing context after matching lines. This will replace the string
part of the reply to a list of strings. Note that in some input types this might skip
following matches. For example, if the input is a file or a custom iterator.
- B NUM, before_context: Return NUM lines of leading context before matching lines. This will replace the string
part of the reply to a list of strings.
- q, quiet: Instead of returning string / list of strings return just a single True / False if
found matches.
- b, byte_offset: Instead of a list of strings will return a list of (offset, string), where offset is
the offset of the matched 'pattern' in line.
- n, line_number: Instead of a list of strings will return a list of (index, string), where index is the
line number.
- o, only_matching: Return only the part of a matching line that matches 'pattern'.
- r, regex_flags: Any additional regex flags you want to add when using regex (see python re flags).
- k, keep_eol When iterating file, if this option is set will keep the end-of-line at the end of every
line. If not (default) will trim the end of line character.
- t, trim Trim all whitespace characters from every line processed.
:return: A list with matching lines (even if provided target is a single string), unless flags state otherwise.
"""
# unify flags (convert shortcuts to full name)
__fix_args(kwargs)
# parse the params that are relevant to this function
f_count = kwargs.get('count')
f_max_count = kwargs.get('max_count')
f_quiet = kwargs.get('quiet')
# use the grep_iter to build the return list
ret = []
for value in grep_iter(target, pattern, **kwargs):
# if quiet mode no need to continue, just return True because we got a value
if f_quiet:
return True
# add current value to return list
ret.append(value)
# if have max limit and exceeded that limit, break:
if f_max_count and len(ret) >= f_max_count:
break
# if quiet mode and got here it means we didn't find a match
if f_quiet:
return False
# if requested count return results count
if f_count:
return len(ret)
# return results list
return ret | python | def grep(target, pattern, **kwargs):
"""
Main grep function.
:param target: Target to apply grep on. Can be a single string, an iterable, a function, or an opened file handler.
:param pattern: Grep pattern to search.
:param kwargs: Optional flags (note: the docs below talk about matching 'lines', but this function also accept lists
and other iterables - in those cases, a 'line' means a single value from the iterable).
The available flags are:
- F, fixed_strings: Interpret 'pattern' as a string or a list of strings, any of which is to be matched.
If not set, will interpret 'pattern' as a python regular expression.
- i, ignore_case: Ignore case.
- v, invert: Invert (eg return non-matching lines / values).
- w, words: Select only those lines containing matches that form whole words.
- x, line: Select only matches that exactly match the whole line.
- c, count: Instead of the normal output, print a count of matching lines.
- m NUM, max_count: Stop reading after NUM matching values.
- A NUM, after_context: Return NUM lines of trailing context after matching lines. This will replace the string
part of the reply to a list of strings. Note that in some input types this might skip
following matches. For example, if the input is a file or a custom iterator.
- B NUM, before_context: Return NUM lines of leading context before matching lines. This will replace the string
part of the reply to a list of strings.
- q, quiet: Instead of returning string / list of strings return just a single True / False if
found matches.
- b, byte_offset: Instead of a list of strings will return a list of (offset, string), where offset is
the offset of the matched 'pattern' in line.
- n, line_number: Instead of a list of strings will return a list of (index, string), where index is the
line number.
- o, only_matching: Return only the part of a matching line that matches 'pattern'.
- r, regex_flags: Any additional regex flags you want to add when using regex (see python re flags).
- k, keep_eol When iterating file, if this option is set will keep the end-of-line at the end of every
line. If not (default) will trim the end of line character.
- t, trim Trim all whitespace characters from every line processed.
:return: A list with matching lines (even if provided target is a single string), unless flags state otherwise.
"""
# unify flags (convert shortcuts to full name)
__fix_args(kwargs)
# parse the params that are relevant to this function
f_count = kwargs.get('count')
f_max_count = kwargs.get('max_count')
f_quiet = kwargs.get('quiet')
# use the grep_iter to build the return list
ret = []
for value in grep_iter(target, pattern, **kwargs):
# if quiet mode no need to continue, just return True because we got a value
if f_quiet:
return True
# add current value to return list
ret.append(value)
# if have max limit and exceeded that limit, break:
if f_max_count and len(ret) >= f_max_count:
break
# if quiet mode and got here it means we didn't find a match
if f_quiet:
return False
# if requested count return results count
if f_count:
return len(ret)
# return results list
return ret | [
"def",
"grep",
"(",
"target",
",",
"pattern",
",",
"*",
"*",
"kwargs",
")",
":",
"# unify flags (convert shortcuts to full name)",
"__fix_args",
"(",
"kwargs",
")",
"# parse the params that are relevant to this function",
"f_count",
"=",
"kwargs",
".",
"get",
"(",
"'c... | Main grep function.
:param target: Target to apply grep on. Can be a single string, an iterable, a function, or an opened file handler.
:param pattern: Grep pattern to search.
:param kwargs: Optional flags (note: the docs below talk about matching 'lines', but this function also accept lists
and other iterables - in those cases, a 'line' means a single value from the iterable).
The available flags are:
- F, fixed_strings: Interpret 'pattern' as a string or a list of strings, any of which is to be matched.
If not set, will interpret 'pattern' as a python regular expression.
- i, ignore_case: Ignore case.
- v, invert: Invert (eg return non-matching lines / values).
- w, words: Select only those lines containing matches that form whole words.
- x, line: Select only matches that exactly match the whole line.
- c, count: Instead of the normal output, print a count of matching lines.
- m NUM, max_count: Stop reading after NUM matching values.
- A NUM, after_context: Return NUM lines of trailing context after matching lines. This will replace the string
part of the reply to a list of strings. Note that in some input types this might skip
following matches. For example, if the input is a file or a custom iterator.
- B NUM, before_context: Return NUM lines of leading context before matching lines. This will replace the string
part of the reply to a list of strings.
- q, quiet: Instead of returning string / list of strings return just a single True / False if
found matches.
- b, byte_offset: Instead of a list of strings will return a list of (offset, string), where offset is
the offset of the matched 'pattern' in line.
- n, line_number: Instead of a list of strings will return a list of (index, string), where index is the
line number.
- o, only_matching: Return only the part of a matching line that matches 'pattern'.
- r, regex_flags: Any additional regex flags you want to add when using regex (see python re flags).
- k, keep_eol When iterating file, if this option is set will keep the end-of-line at the end of every
line. If not (default) will trim the end of line character.
- t, trim Trim all whitespace characters from every line processed.
:return: A list with matching lines (even if provided target is a single string), unless flags state otherwise. | [
"Main",
"grep",
"function",
".",
":",
"param",
"target",
":",
"Target",
"to",
"apply",
"grep",
"on",
".",
"Can",
"be",
"a",
"single",
"string",
"an",
"iterable",
"a",
"function",
"or",
"an",
"opened",
"file",
"handler",
".",
":",
"param",
"pattern",
":... | train | https://github.com/RonenNess/grepfunc/blob/a5323d082c0a581e4b053ef85838c9a0101b43ff/grepfunc/grepfunc.py#L49-L118 |
RonenNess/grepfunc | grepfunc/grepfunc.py | grep_iter | def grep_iter(target, pattern, **kwargs):
"""
Main grep function, as a memory efficient iterator.
Note: this function does not support the 'quiet' or 'count' flags.
:param target: Target to apply grep on. Can be a single string, an iterable, a function, or an opened file handler.
:param pattern: Grep pattern to search.
:param kwargs: See grep() help for more info.
:return: Next match.
"""
# unify flags (convert shortcuts to full name)
__fix_args(kwargs)
# parse the params that are relevant to this function
f_offset = kwargs.get('byte_offset')
f_line_number = kwargs.get('line_number')
f_trim = kwargs.get('trim')
f_after_context = kwargs.get('after_context')
f_before_context = kwargs.get('before_context')
f_only_matching = kwargs.get('only_matching')
# if target is a callable function, call it first to get value
if callable(target):
target = target()
# if we got a single string convert it to a list
if isinstance(target, _basestring):
target = [target]
# calculate if need to trim end of lines
need_to_trim_eol = not kwargs.get('keep_eol') and hasattr(target, 'readline')
# list of previous lines, used only when f_before_context is set
prev_lines = []
# iterate target and grep
for line_index, line in enumerate(target):
# fix current line
line = __process_line(line, need_to_trim_eol, f_trim)
# do grap
match, offset, endpos = __do_grep(line, pattern, **kwargs)
# nullify return value
value = None
# if matched
if match:
# the textual part we return in response
ret_str = line
# if only return matching
if f_only_matching:
ret_str = ret_str[offset:endpos]
# if 'before_context' is set
if f_before_context:
# make ret_str be a list with previous lines
ret_str = prev_lines + [ret_str]
# if need to return X lines after trailing context
if f_after_context:
# convert return string to list (unless f_before_context is set, in which case its already a list)
if not f_before_context:
ret_str = [ret_str]
# iterate X lines to read after
for i in range(f_after_context):
# if target got next or readline, use next()
# note: unfortunately due to python files next() implementation we can't use tell and seek to
# restore position and not skip next matches.
if hasattr(target, '__next__') or hasattr(target, 'readline'):
try:
val = next(target)
except StopIteration:
break
# if not, try to access next item based on index (for lists)
else:
try:
val = target[line_index+i+1]
except IndexError:
break
# add value to return string
ret_str.append(__process_line(val, need_to_trim_eol, f_trim))
# if requested offset, add offset + line to return list
if f_offset:
value = (offset, ret_str)
# if requested line number, add offset + line to return list
elif f_line_number:
value = (line_index, ret_str)
# default: add line to return list
else:
value = ret_str
# maintain a list of previous lines, if the before-context option is provided
if f_before_context:
prev_lines.append(line)
if len(prev_lines) > f_before_context:
prev_lines.pop(0)
# if we had a match return current value
if value is not None:
yield value
# done iteration
raise StopIteration | python | def grep_iter(target, pattern, **kwargs):
"""
Main grep function, as a memory efficient iterator.
Note: this function does not support the 'quiet' or 'count' flags.
:param target: Target to apply grep on. Can be a single string, an iterable, a function, or an opened file handler.
:param pattern: Grep pattern to search.
:param kwargs: See grep() help for more info.
:return: Next match.
"""
# unify flags (convert shortcuts to full name)
__fix_args(kwargs)
# parse the params that are relevant to this function
f_offset = kwargs.get('byte_offset')
f_line_number = kwargs.get('line_number')
f_trim = kwargs.get('trim')
f_after_context = kwargs.get('after_context')
f_before_context = kwargs.get('before_context')
f_only_matching = kwargs.get('only_matching')
# if target is a callable function, call it first to get value
if callable(target):
target = target()
# if we got a single string convert it to a list
if isinstance(target, _basestring):
target = [target]
# calculate if need to trim end of lines
need_to_trim_eol = not kwargs.get('keep_eol') and hasattr(target, 'readline')
# list of previous lines, used only when f_before_context is set
prev_lines = []
# iterate target and grep
for line_index, line in enumerate(target):
# fix current line
line = __process_line(line, need_to_trim_eol, f_trim)
# do grap
match, offset, endpos = __do_grep(line, pattern, **kwargs)
# nullify return value
value = None
# if matched
if match:
# the textual part we return in response
ret_str = line
# if only return matching
if f_only_matching:
ret_str = ret_str[offset:endpos]
# if 'before_context' is set
if f_before_context:
# make ret_str be a list with previous lines
ret_str = prev_lines + [ret_str]
# if need to return X lines after trailing context
if f_after_context:
# convert return string to list (unless f_before_context is set, in which case its already a list)
if not f_before_context:
ret_str = [ret_str]
# iterate X lines to read after
for i in range(f_after_context):
# if target got next or readline, use next()
# note: unfortunately due to python files next() implementation we can't use tell and seek to
# restore position and not skip next matches.
if hasattr(target, '__next__') or hasattr(target, 'readline'):
try:
val = next(target)
except StopIteration:
break
# if not, try to access next item based on index (for lists)
else:
try:
val = target[line_index+i+1]
except IndexError:
break
# add value to return string
ret_str.append(__process_line(val, need_to_trim_eol, f_trim))
# if requested offset, add offset + line to return list
if f_offset:
value = (offset, ret_str)
# if requested line number, add offset + line to return list
elif f_line_number:
value = (line_index, ret_str)
# default: add line to return list
else:
value = ret_str
# maintain a list of previous lines, if the before-context option is provided
if f_before_context:
prev_lines.append(line)
if len(prev_lines) > f_before_context:
prev_lines.pop(0)
# if we had a match return current value
if value is not None:
yield value
# done iteration
raise StopIteration | [
"def",
"grep_iter",
"(",
"target",
",",
"pattern",
",",
"*",
"*",
"kwargs",
")",
":",
"# unify flags (convert shortcuts to full name)",
"__fix_args",
"(",
"kwargs",
")",
"# parse the params that are relevant to this function",
"f_offset",
"=",
"kwargs",
".",
"get",
"(",... | Main grep function, as a memory efficient iterator.
Note: this function does not support the 'quiet' or 'count' flags.
:param target: Target to apply grep on. Can be a single string, an iterable, a function, or an opened file handler.
:param pattern: Grep pattern to search.
:param kwargs: See grep() help for more info.
:return: Next match. | [
"Main",
"grep",
"function",
"as",
"a",
"memory",
"efficient",
"iterator",
".",
"Note",
":",
"this",
"function",
"does",
"not",
"support",
"the",
"quiet",
"or",
"count",
"flags",
".",
":",
"param",
"target",
":",
"Target",
"to",
"apply",
"grep",
"on",
"."... | train | https://github.com/RonenNess/grepfunc/blob/a5323d082c0a581e4b053ef85838c9a0101b43ff/grepfunc/grepfunc.py#L121-L235 |
RonenNess/grepfunc | grepfunc/grepfunc.py | __process_line | def __process_line(line, strip_eol, strip):
"""
process a single line value.
"""
if strip:
line = line.strip()
elif strip_eol and line.endswith('\n'):
line = line[:-1]
return line | python | def __process_line(line, strip_eol, strip):
"""
process a single line value.
"""
if strip:
line = line.strip()
elif strip_eol and line.endswith('\n'):
line = line[:-1]
return line | [
"def",
"__process_line",
"(",
"line",
",",
"strip_eol",
",",
"strip",
")",
":",
"if",
"strip",
":",
"line",
"=",
"line",
".",
"strip",
"(",
")",
"elif",
"strip_eol",
"and",
"line",
".",
"endswith",
"(",
"'\\n'",
")",
":",
"line",
"=",
"line",
"[",
... | process a single line value. | [
"process",
"a",
"single",
"line",
"value",
"."
] | train | https://github.com/RonenNess/grepfunc/blob/a5323d082c0a581e4b053ef85838c9a0101b43ff/grepfunc/grepfunc.py#L238-L246 |
RonenNess/grepfunc | grepfunc/grepfunc.py | __do_grep | def __do_grep(curr_line, pattern, **kwargs):
"""
Do grep on a single string.
See 'grep' docs for info about kwargs.
:param curr_line: a single line to test.
:param pattern: pattern to search.
:return: (matched, position, end_position).
"""
# currently found position
position = -1
end_pos = -1
# check if fixed strings mode
if kwargs.get('fixed_strings'):
# if case insensitive fix case
if kwargs.get('ignore_case'):
pattern = pattern.lower()
curr_line = curr_line.lower()
# if pattern is a single string, match it:
pattern_len = 0
if isinstance(pattern, _basestring):
position = curr_line.find(pattern)
pattern_len = len(pattern)
# if not, treat it as a list of strings and match any
else:
for p in pattern:
position = curr_line.find(p)
pattern_len = len(p)
if position != -1:
break
# calc end position
end_pos = position + pattern_len
# check if need to match whole words
if kwargs.get('words') and position != -1:
foundpart = (' ' + curr_line + ' ')[position:position+len(pattern)+2]
if _is_part_of_word(foundpart[0]):
position = -1
elif _is_part_of_word(foundpart[-1]):
position = -1
# if not fixed string, it means its a regex
else:
# set regex flags
flags = kwargs.get('regex_flags') or 0
flags |= re.IGNORECASE if kwargs.get('ignore_case') else 0
# add whole-words option
if kwargs.get('words'):
pattern = r'\b' + pattern + r'\b'
# do search
result = re.search(pattern, curr_line, flags)
# if found, set position
if result:
position = result.start()
end_pos = result.end()
# check if need to match whole line
if kwargs.get('line') and (position != 0 or end_pos != len(curr_line)):
position = -1
# parse return value
matched = position != -1
# if invert flag is on, invert value
if kwargs.get('invert'):
matched = not matched
# if position is -1 reset end pos as well
if not matched:
end_pos = -1
# return result
return matched, position, end_pos | python | def __do_grep(curr_line, pattern, **kwargs):
"""
Do grep on a single string.
See 'grep' docs for info about kwargs.
:param curr_line: a single line to test.
:param pattern: pattern to search.
:return: (matched, position, end_position).
"""
# currently found position
position = -1
end_pos = -1
# check if fixed strings mode
if kwargs.get('fixed_strings'):
# if case insensitive fix case
if kwargs.get('ignore_case'):
pattern = pattern.lower()
curr_line = curr_line.lower()
# if pattern is a single string, match it:
pattern_len = 0
if isinstance(pattern, _basestring):
position = curr_line.find(pattern)
pattern_len = len(pattern)
# if not, treat it as a list of strings and match any
else:
for p in pattern:
position = curr_line.find(p)
pattern_len = len(p)
if position != -1:
break
# calc end position
end_pos = position + pattern_len
# check if need to match whole words
if kwargs.get('words') and position != -1:
foundpart = (' ' + curr_line + ' ')[position:position+len(pattern)+2]
if _is_part_of_word(foundpart[0]):
position = -1
elif _is_part_of_word(foundpart[-1]):
position = -1
# if not fixed string, it means its a regex
else:
# set regex flags
flags = kwargs.get('regex_flags') or 0
flags |= re.IGNORECASE if kwargs.get('ignore_case') else 0
# add whole-words option
if kwargs.get('words'):
pattern = r'\b' + pattern + r'\b'
# do search
result = re.search(pattern, curr_line, flags)
# if found, set position
if result:
position = result.start()
end_pos = result.end()
# check if need to match whole line
if kwargs.get('line') and (position != 0 or end_pos != len(curr_line)):
position = -1
# parse return value
matched = position != -1
# if invert flag is on, invert value
if kwargs.get('invert'):
matched = not matched
# if position is -1 reset end pos as well
if not matched:
end_pos = -1
# return result
return matched, position, end_pos | [
"def",
"__do_grep",
"(",
"curr_line",
",",
"pattern",
",",
"*",
"*",
"kwargs",
")",
":",
"# currently found position",
"position",
"=",
"-",
"1",
"end_pos",
"=",
"-",
"1",
"# check if fixed strings mode",
"if",
"kwargs",
".",
"get",
"(",
"'fixed_strings'",
")"... | Do grep on a single string.
See 'grep' docs for info about kwargs.
:param curr_line: a single line to test.
:param pattern: pattern to search.
:return: (matched, position, end_position). | [
"Do",
"grep",
"on",
"a",
"single",
"string",
".",
"See",
"grep",
"docs",
"for",
"info",
"about",
"kwargs",
".",
":",
"param",
"curr_line",
":",
"a",
"single",
"line",
"to",
"test",
".",
":",
"param",
"pattern",
":",
"pattern",
"to",
"search",
".",
":... | train | https://github.com/RonenNess/grepfunc/blob/a5323d082c0a581e4b053ef85838c9a0101b43ff/grepfunc/grepfunc.py#L249-L330 |
tkf/rash | rash/cli.py | get_parser | def get_parser(commands):
"""
Generate argument parser given a list of subcommand specifications.
:type commands: list of (str, function, function)
:arg commands:
Each element must be a tuple ``(name, adder, runner)``.
:param name: subcommand
:param adder: a function takes one object which is an instance
of :class:`argparse.ArgumentParser` and add
arguments to it
:param runner: a function takes keyword arguments which must be
specified by the arguments parsed by the parser
defined by `adder`. Docstring of this function
will be the description of the subcommand.
"""
parser = argparse.ArgumentParser(
formatter_class=Formatter,
description=__doc__,
epilog=EPILOG,
)
subparsers = parser.add_subparsers()
for (name, adder, runner) in commands:
subp = subparsers.add_parser(
name,
formatter_class=Formatter,
description=runner.__doc__ and textwrap.dedent(runner.__doc__))
adder(subp)
subp.set_defaults(func=runner)
return parser | python | def get_parser(commands):
"""
Generate argument parser given a list of subcommand specifications.
:type commands: list of (str, function, function)
:arg commands:
Each element must be a tuple ``(name, adder, runner)``.
:param name: subcommand
:param adder: a function takes one object which is an instance
of :class:`argparse.ArgumentParser` and add
arguments to it
:param runner: a function takes keyword arguments which must be
specified by the arguments parsed by the parser
defined by `adder`. Docstring of this function
will be the description of the subcommand.
"""
parser = argparse.ArgumentParser(
formatter_class=Formatter,
description=__doc__,
epilog=EPILOG,
)
subparsers = parser.add_subparsers()
for (name, adder, runner) in commands:
subp = subparsers.add_parser(
name,
formatter_class=Formatter,
description=runner.__doc__ and textwrap.dedent(runner.__doc__))
adder(subp)
subp.set_defaults(func=runner)
return parser | [
"def",
"get_parser",
"(",
"commands",
")",
":",
"parser",
"=",
"argparse",
".",
"ArgumentParser",
"(",
"formatter_class",
"=",
"Formatter",
",",
"description",
"=",
"__doc__",
",",
"epilog",
"=",
"EPILOG",
",",
")",
"subparsers",
"=",
"parser",
".",
"add_sub... | Generate argument parser given a list of subcommand specifications.
:type commands: list of (str, function, function)
:arg commands:
Each element must be a tuple ``(name, adder, runner)``.
:param name: subcommand
:param adder: a function takes one object which is an instance
of :class:`argparse.ArgumentParser` and add
arguments to it
:param runner: a function takes keyword arguments which must be
specified by the arguments parsed by the parser
defined by `adder`. Docstring of this function
will be the description of the subcommand. | [
"Generate",
"argument",
"parser",
"given",
"a",
"list",
"of",
"subcommand",
"specifications",
"."
] | train | https://github.com/tkf/rash/blob/585da418ec37dd138f1a4277718b6f507e9536a2/rash/cli.py#L31-L64 |
tkf/rash | rash/cli.py | locate_run | def locate_run(output, target, no_newline):
"""
Print location of RASH related file.
"""
from .config import ConfigStore
cfstore = ConfigStore()
path = getattr(cfstore, "{0}_path".format(target))
output.write(path)
if not no_newline:
output.write("\n") | python | def locate_run(output, target, no_newline):
"""
Print location of RASH related file.
"""
from .config import ConfigStore
cfstore = ConfigStore()
path = getattr(cfstore, "{0}_path".format(target))
output.write(path)
if not no_newline:
output.write("\n") | [
"def",
"locate_run",
"(",
"output",
",",
"target",
",",
"no_newline",
")",
":",
"from",
".",
"config",
"import",
"ConfigStore",
"cfstore",
"=",
"ConfigStore",
"(",
")",
"path",
"=",
"getattr",
"(",
"cfstore",
",",
"\"{0}_path\"",
".",
"format",
"(",
"targe... | Print location of RASH related file. | [
"Print",
"location",
"of",
"RASH",
"related",
"file",
"."
] | train | https://github.com/tkf/rash/blob/585da418ec37dd138f1a4277718b6f507e9536a2/rash/cli.py#L102-L111 |
twisted/mantissa | xmantissa/webadmin.py | UserInteractionFragment.userBrowser | def userBrowser(self, request, tag):
"""
Render a TDB of local users.
"""
f = LocalUserBrowserFragment(self.browser)
f.docFactory = webtheme.getLoader(f.fragmentName)
f.setFragmentParent(self)
return f | python | def userBrowser(self, request, tag):
"""
Render a TDB of local users.
"""
f = LocalUserBrowserFragment(self.browser)
f.docFactory = webtheme.getLoader(f.fragmentName)
f.setFragmentParent(self)
return f | [
"def",
"userBrowser",
"(",
"self",
",",
"request",
",",
"tag",
")",
":",
"f",
"=",
"LocalUserBrowserFragment",
"(",
"self",
".",
"browser",
")",
"f",
".",
"docFactory",
"=",
"webtheme",
".",
"getLoader",
"(",
"f",
".",
"fragmentName",
")",
"f",
".",
"s... | Render a TDB of local users. | [
"Render",
"a",
"TDB",
"of",
"local",
"users",
"."
] | train | https://github.com/twisted/mantissa/blob/53e5502aba23ce99be78b27f923a276593033fe8/xmantissa/webadmin.py#L140-L147 |
twisted/mantissa | xmantissa/webadmin.py | UserInteractionFragment.userCreate | def userCreate(self, request, tag):
"""
Render a form for creating new users.
"""
userCreator = liveform.LiveForm(
self.createUser,
[liveform.Parameter(
"localpart",
liveform.TEXT_INPUT,
unicode,
"localpart"),
liveform.Parameter(
"domain",
liveform.TEXT_INPUT,
unicode,
"domain"),
liveform.Parameter(
"password",
liveform.PASSWORD_INPUT,
unicode,
"password")])
userCreator.setFragmentParent(self)
return userCreator | python | def userCreate(self, request, tag):
"""
Render a form for creating new users.
"""
userCreator = liveform.LiveForm(
self.createUser,
[liveform.Parameter(
"localpart",
liveform.TEXT_INPUT,
unicode,
"localpart"),
liveform.Parameter(
"domain",
liveform.TEXT_INPUT,
unicode,
"domain"),
liveform.Parameter(
"password",
liveform.PASSWORD_INPUT,
unicode,
"password")])
userCreator.setFragmentParent(self)
return userCreator | [
"def",
"userCreate",
"(",
"self",
",",
"request",
",",
"tag",
")",
":",
"userCreator",
"=",
"liveform",
".",
"LiveForm",
"(",
"self",
".",
"createUser",
",",
"[",
"liveform",
".",
"Parameter",
"(",
"\"localpart\"",
",",
"liveform",
".",
"TEXT_INPUT",
",",
... | Render a form for creating new users. | [
"Render",
"a",
"form",
"for",
"creating",
"new",
"users",
"."
] | train | https://github.com/twisted/mantissa/blob/53e5502aba23ce99be78b27f923a276593033fe8/xmantissa/webadmin.py#L151-L173 |
twisted/mantissa | xmantissa/webadmin.py | UserInteractionFragment.createUser | def createUser(self, localpart, domain, password=None):
"""
Create a new, blank user account with the given name and domain and, if
specified, with the given password.
@type localpart: C{unicode}
@param localpart: The local portion of the username. ie, the
C{'alice'} in C{'alice@example.com'}.
@type domain: C{unicode}
@param domain: The domain portion of the username. ie, the
C{'example.com'} in C{'alice@example.com'}.
@type password: C{unicode} or C{None}
@param password: The password to associate with the new account. If
C{None}, generate a new password automatically.
"""
loginSystem = self.browser.store.parent.findUnique(userbase.LoginSystem)
if password is None:
password = u''.join([random.choice(string.ascii_letters + string.digits) for i in xrange(8)])
loginSystem.addAccount(localpart, domain, password) | python | def createUser(self, localpart, domain, password=None):
"""
Create a new, blank user account with the given name and domain and, if
specified, with the given password.
@type localpart: C{unicode}
@param localpart: The local portion of the username. ie, the
C{'alice'} in C{'alice@example.com'}.
@type domain: C{unicode}
@param domain: The domain portion of the username. ie, the
C{'example.com'} in C{'alice@example.com'}.
@type password: C{unicode} or C{None}
@param password: The password to associate with the new account. If
C{None}, generate a new password automatically.
"""
loginSystem = self.browser.store.parent.findUnique(userbase.LoginSystem)
if password is None:
password = u''.join([random.choice(string.ascii_letters + string.digits) for i in xrange(8)])
loginSystem.addAccount(localpart, domain, password) | [
"def",
"createUser",
"(",
"self",
",",
"localpart",
",",
"domain",
",",
"password",
"=",
"None",
")",
":",
"loginSystem",
"=",
"self",
".",
"browser",
".",
"store",
".",
"parent",
".",
"findUnique",
"(",
"userbase",
".",
"LoginSystem",
")",
"if",
"passwo... | Create a new, blank user account with the given name and domain and, if
specified, with the given password.
@type localpart: C{unicode}
@param localpart: The local portion of the username. ie, the
C{'alice'} in C{'alice@example.com'}.
@type domain: C{unicode}
@param domain: The domain portion of the username. ie, the
C{'example.com'} in C{'alice@example.com'}.
@type password: C{unicode} or C{None}
@param password: The password to associate with the new account. If
C{None}, generate a new password automatically. | [
"Create",
"a",
"new",
"blank",
"user",
"account",
"with",
"the",
"given",
"name",
"and",
"domain",
"and",
"if",
"specified",
"with",
"the",
"given",
"password",
"."
] | train | https://github.com/twisted/mantissa/blob/53e5502aba23ce99be78b27f923a276593033fe8/xmantissa/webadmin.py#L177-L197 |
twisted/mantissa | xmantissa/webadmin.py | LocalUserBrowserFragment.doAction | def doAction(self, loginMethod, actionClass):
"""
Show the form for the requested action.
"""
loginAccount = loginMethod.account
return actionClass(
self,
loginMethod.localpart + u'@' + loginMethod.domain,
loginAccount) | python | def doAction(self, loginMethod, actionClass):
"""
Show the form for the requested action.
"""
loginAccount = loginMethod.account
return actionClass(
self,
loginMethod.localpart + u'@' + loginMethod.domain,
loginAccount) | [
"def",
"doAction",
"(",
"self",
",",
"loginMethod",
",",
"actionClass",
")",
":",
"loginAccount",
"=",
"loginMethod",
".",
"account",
"return",
"actionClass",
"(",
"self",
",",
"loginMethod",
".",
"localpart",
"+",
"u'@'",
"+",
"loginMethod",
".",
"domain",
... | Show the form for the requested action. | [
"Show",
"the",
"form",
"for",
"the",
"requested",
"action",
"."
] | train | https://github.com/twisted/mantissa/blob/53e5502aba23ce99be78b27f923a276593033fe8/xmantissa/webadmin.py#L224-L232 |
twisted/mantissa | xmantissa/webadmin.py | EndowDepriveFragment.productForm | def productForm(self, request, tag):
"""
Render a L{liveform.LiveForm} -- the main purpose of this fragment --
which will allow the administrator to endow or deprive existing users
using Products.
"""
def makeRemover(i):
def remover(s3lected):
if s3lected:
return self.products[i]
return None
return remover
f = liveform.LiveForm(
self._endow,
[liveform.Parameter(
'products' + str(i),
liveform.FORM_INPUT,
liveform.LiveForm(
makeRemover(i),
[liveform.Parameter(
's3lected',
liveform.RADIO_INPUT,
bool,
repr(p),
)],
'',
),
)
for (i, p)
in enumerate(self.products)],
self.which.capitalize() + u' ' + self.username)
f.setFragmentParent(self)
return f | python | def productForm(self, request, tag):
"""
Render a L{liveform.LiveForm} -- the main purpose of this fragment --
which will allow the administrator to endow or deprive existing users
using Products.
"""
def makeRemover(i):
def remover(s3lected):
if s3lected:
return self.products[i]
return None
return remover
f = liveform.LiveForm(
self._endow,
[liveform.Parameter(
'products' + str(i),
liveform.FORM_INPUT,
liveform.LiveForm(
makeRemover(i),
[liveform.Parameter(
's3lected',
liveform.RADIO_INPUT,
bool,
repr(p),
)],
'',
),
)
for (i, p)
in enumerate(self.products)],
self.which.capitalize() + u' ' + self.username)
f.setFragmentParent(self)
return f | [
"def",
"productForm",
"(",
"self",
",",
"request",
",",
"tag",
")",
":",
"def",
"makeRemover",
"(",
"i",
")",
":",
"def",
"remover",
"(",
"s3lected",
")",
":",
"if",
"s3lected",
":",
"return",
"self",
".",
"products",
"[",
"i",
"]",
"return",
"None",... | Render a L{liveform.LiveForm} -- the main purpose of this fragment --
which will allow the administrator to endow or deprive existing users
using Products. | [
"Render",
"a",
"L",
"{",
"liveform",
".",
"LiveForm",
"}",
"--",
"the",
"main",
"purpose",
"of",
"this",
"fragment",
"--",
"which",
"will",
"allow",
"the",
"administrator",
"to",
"endow",
"or",
"deprive",
"existing",
"users",
"using",
"Products",
"."
] | train | https://github.com/twisted/mantissa/blob/53e5502aba23ce99be78b27f923a276593033fe8/xmantissa/webadmin.py#L263-L297 |
twisted/mantissa | xmantissa/webadmin.py | REPL.getStore | def getStore(self, name, domain):
"""Convenience method for the REPL. I got tired of typing this string every time I logged in."""
return IRealm(self.original.store.parent).accountByAddress(name, domain).avatars.open() | python | def getStore(self, name, domain):
"""Convenience method for the REPL. I got tired of typing this string every time I logged in."""
return IRealm(self.original.store.parent).accountByAddress(name, domain).avatars.open() | [
"def",
"getStore",
"(",
"self",
",",
"name",
",",
"domain",
")",
":",
"return",
"IRealm",
"(",
"self",
".",
"original",
".",
"store",
".",
"parent",
")",
".",
"accountByAddress",
"(",
"name",
",",
"domain",
")",
".",
"avatars",
".",
"open",
"(",
")"
... | Convenience method for the REPL. I got tired of typing this string every time I logged in. | [
"Convenience",
"method",
"for",
"the",
"REPL",
".",
"I",
"got",
"tired",
"of",
"typing",
"this",
"string",
"every",
"time",
"I",
"logged",
"in",
"."
] | train | https://github.com/twisted/mantissa/blob/53e5502aba23ce99be78b27f923a276593033fe8/xmantissa/webadmin.py#L415-L417 |
twisted/mantissa | xmantissa/webadmin.py | PortConfiguration.createPort | def createPort(self, portNumber, ssl, certPath, factory, interface=u''):
"""
Create a new listening port.
@type portNumber: C{int}
@param portNumber: Port number on which to listen.
@type ssl: C{bool}
@param ssl: Indicates whether this should be an SSL port or not.
@type certPath: C{str}
@param ssl: If C{ssl} is true, a path to a certificate file somewhere
within the site store's files directory. Ignored otherwise.
@param factory: L{Item} which provides L{IProtocolFactoryFactory} which
will be used to get a protocol factory to associate with this port.
@return: C{None}
"""
store = self.store.parent
if ssl:
port = SSLPort(store=store, portNumber=portNumber,
certificatePath=FilePath(certPath), factory=factory,
interface=interface)
else:
port = TCPPort(store=store, portNumber=portNumber, factory=factory,
interface=interface)
installOn(port, store) | python | def createPort(self, portNumber, ssl, certPath, factory, interface=u''):
"""
Create a new listening port.
@type portNumber: C{int}
@param portNumber: Port number on which to listen.
@type ssl: C{bool}
@param ssl: Indicates whether this should be an SSL port or not.
@type certPath: C{str}
@param ssl: If C{ssl} is true, a path to a certificate file somewhere
within the site store's files directory. Ignored otherwise.
@param factory: L{Item} which provides L{IProtocolFactoryFactory} which
will be used to get a protocol factory to associate with this port.
@return: C{None}
"""
store = self.store.parent
if ssl:
port = SSLPort(store=store, portNumber=portNumber,
certificatePath=FilePath(certPath), factory=factory,
interface=interface)
else:
port = TCPPort(store=store, portNumber=portNumber, factory=factory,
interface=interface)
installOn(port, store) | [
"def",
"createPort",
"(",
"self",
",",
"portNumber",
",",
"ssl",
",",
"certPath",
",",
"factory",
",",
"interface",
"=",
"u''",
")",
":",
"store",
"=",
"self",
".",
"store",
".",
"parent",
"if",
"ssl",
":",
"port",
"=",
"SSLPort",
"(",
"store",
"=",
... | Create a new listening port.
@type portNumber: C{int}
@param portNumber: Port number on which to listen.
@type ssl: C{bool}
@param ssl: Indicates whether this should be an SSL port or not.
@type certPath: C{str}
@param ssl: If C{ssl} is true, a path to a certificate file somewhere
within the site store's files directory. Ignored otherwise.
@param factory: L{Item} which provides L{IProtocolFactoryFactory} which
will be used to get a protocol factory to associate with this port.
@return: C{None} | [
"Create",
"a",
"new",
"listening",
"port",
"."
] | train | https://github.com/twisted/mantissa/blob/53e5502aba23ce99be78b27f923a276593033fe8/xmantissa/webadmin.py#L565-L592 |
twisted/mantissa | xmantissa/webadmin.py | FactoryColumn.extractValue | def extractValue(self, model, item):
"""
Get the class name of the factory referenced by a port.
@param model: Either a TabularDataModel or a ScrollableView, depending
on what this column is part of.
@param item: A port item instance (as defined by L{xmantissa.port}).
@rtype: C{unicode}
@return: The name of the class of the item to which this column's
attribute refers.
"""
factory = super(FactoryColumn, self).extractValue(model, item)
return factory.__class__.__name__.decode('ascii') | python | def extractValue(self, model, item):
"""
Get the class name of the factory referenced by a port.
@param model: Either a TabularDataModel or a ScrollableView, depending
on what this column is part of.
@param item: A port item instance (as defined by L{xmantissa.port}).
@rtype: C{unicode}
@return: The name of the class of the item to which this column's
attribute refers.
"""
factory = super(FactoryColumn, self).extractValue(model, item)
return factory.__class__.__name__.decode('ascii') | [
"def",
"extractValue",
"(",
"self",
",",
"model",
",",
"item",
")",
":",
"factory",
"=",
"super",
"(",
"FactoryColumn",
",",
"self",
")",
".",
"extractValue",
"(",
"model",
",",
"item",
")",
"return",
"factory",
".",
"__class__",
".",
"__name__",
".",
... | Get the class name of the factory referenced by a port.
@param model: Either a TabularDataModel or a ScrollableView, depending
on what this column is part of.
@param item: A port item instance (as defined by L{xmantissa.port}).
@rtype: C{unicode}
@return: The name of the class of the item to which this column's
attribute refers. | [
"Get",
"the",
"class",
"name",
"of",
"the",
"factory",
"referenced",
"by",
"a",
"port",
"."
] | train | https://github.com/twisted/mantissa/blob/53e5502aba23ce99be78b27f923a276593033fe8/xmantissa/webadmin.py#L601-L615 |
twisted/mantissa | xmantissa/webadmin.py | CertificateColumn.extractValue | def extractValue(self, model, item):
"""
Get the path referenced by this column's attribute.
@param model: Either a TabularDataModel or a ScrollableView, depending
on what this column is part of.
@param item: A port item instance (as defined by L{xmantissa.port}).
@rtype: C{unicode}
"""
certPath = super(CertificateColumn, self).extractValue(model, item)
return certPath.path.decode('utf-8', 'replace') | python | def extractValue(self, model, item):
"""
Get the path referenced by this column's attribute.
@param model: Either a TabularDataModel or a ScrollableView, depending
on what this column is part of.
@param item: A port item instance (as defined by L{xmantissa.port}).
@rtype: C{unicode}
"""
certPath = super(CertificateColumn, self).extractValue(model, item)
return certPath.path.decode('utf-8', 'replace') | [
"def",
"extractValue",
"(",
"self",
",",
"model",
",",
"item",
")",
":",
"certPath",
"=",
"super",
"(",
"CertificateColumn",
",",
"self",
")",
".",
"extractValue",
"(",
"model",
",",
"item",
")",
"return",
"certPath",
".",
"path",
".",
"decode",
"(",
"... | Get the path referenced by this column's attribute.
@param model: Either a TabularDataModel or a ScrollableView, depending
on what this column is part of.
@param item: A port item instance (as defined by L{xmantissa.port}).
@rtype: C{unicode} | [
"Get",
"the",
"path",
"referenced",
"by",
"this",
"column",
"s",
"attribute",
"."
] | train | https://github.com/twisted/mantissa/blob/53e5502aba23ce99be78b27f923a276593033fe8/xmantissa/webadmin.py#L623-L635 |
twisted/mantissa | xmantissa/webadmin.py | PortScrollingFragment.itemFromLink | def itemFromLink(self, link):
"""
@type link: C{unicode}
@param link: A webID to translate into an item.
@rtype: L{Item}
@return: The item to which the given link referred.
"""
return self.siteStore.getItemByID(self.webTranslator.linkFrom(link)) | python | def itemFromLink(self, link):
"""
@type link: C{unicode}
@param link: A webID to translate into an item.
@rtype: L{Item}
@return: The item to which the given link referred.
"""
return self.siteStore.getItemByID(self.webTranslator.linkFrom(link)) | [
"def",
"itemFromLink",
"(",
"self",
",",
"link",
")",
":",
"return",
"self",
".",
"siteStore",
".",
"getItemByID",
"(",
"self",
".",
"webTranslator",
".",
"linkFrom",
"(",
"link",
")",
")"
] | @type link: C{unicode}
@param link: A webID to translate into an item.
@rtype: L{Item}
@return: The item to which the given link referred. | [
"@type",
"link",
":",
"C",
"{",
"unicode",
"}",
"@param",
"link",
":",
"A",
"webID",
"to",
"translate",
"into",
"an",
"item",
"."
] | train | https://github.com/twisted/mantissa/blob/53e5502aba23ce99be78b27f923a276593033fe8/xmantissa/webadmin.py#L662-L670 |
twisted/mantissa | xmantissa/webadmin.py | PortConfigurationFragment.tcpPorts | def tcpPorts(self, req, tag):
"""
Create and return a L{PortScrollingFragment} for the L{TCPPort} items
in site store.
"""
f = PortScrollingFragment(
self.store,
TCPPort,
(TCPPort.portNumber,
TCPPort.interface,
FactoryColumn(TCPPort.factory)))
f.setFragmentParent(self)
f.docFactory = webtheme.getLoader(f.fragmentName)
return tag[f] | python | def tcpPorts(self, req, tag):
"""
Create and return a L{PortScrollingFragment} for the L{TCPPort} items
in site store.
"""
f = PortScrollingFragment(
self.store,
TCPPort,
(TCPPort.portNumber,
TCPPort.interface,
FactoryColumn(TCPPort.factory)))
f.setFragmentParent(self)
f.docFactory = webtheme.getLoader(f.fragmentName)
return tag[f] | [
"def",
"tcpPorts",
"(",
"self",
",",
"req",
",",
"tag",
")",
":",
"f",
"=",
"PortScrollingFragment",
"(",
"self",
".",
"store",
",",
"TCPPort",
",",
"(",
"TCPPort",
".",
"portNumber",
",",
"TCPPort",
".",
"interface",
",",
"FactoryColumn",
"(",
"TCPPort"... | Create and return a L{PortScrollingFragment} for the L{TCPPort} items
in site store. | [
"Create",
"and",
"return",
"a",
"L",
"{",
"PortScrollingFragment",
"}",
"for",
"the",
"L",
"{",
"TCPPort",
"}",
"items",
"in",
"site",
"store",
"."
] | train | https://github.com/twisted/mantissa/blob/53e5502aba23ce99be78b27f923a276593033fe8/xmantissa/webadmin.py#L708-L721 |
twisted/mantissa | xmantissa/webadmin.py | PortConfigurationFragment.sslPorts | def sslPorts(self, req, tag):
"""
Create and return a L{PortScrollingFragment} for the L{SSLPort} items
in the site store.
"""
f = PortScrollingFragment(
self.store,
SSLPort,
(SSLPort.portNumber,
SSLPort.interface,
CertificateColumn(SSLPort.certificatePath),
FactoryColumn(SSLPort.factory)))
f.setFragmentParent(self)
f.docFactory = webtheme.getLoader(f.fragmentName)
return tag[f] | python | def sslPorts(self, req, tag):
"""
Create and return a L{PortScrollingFragment} for the L{SSLPort} items
in the site store.
"""
f = PortScrollingFragment(
self.store,
SSLPort,
(SSLPort.portNumber,
SSLPort.interface,
CertificateColumn(SSLPort.certificatePath),
FactoryColumn(SSLPort.factory)))
f.setFragmentParent(self)
f.docFactory = webtheme.getLoader(f.fragmentName)
return tag[f] | [
"def",
"sslPorts",
"(",
"self",
",",
"req",
",",
"tag",
")",
":",
"f",
"=",
"PortScrollingFragment",
"(",
"self",
".",
"store",
",",
"SSLPort",
",",
"(",
"SSLPort",
".",
"portNumber",
",",
"SSLPort",
".",
"interface",
",",
"CertificateColumn",
"(",
"SSLP... | Create and return a L{PortScrollingFragment} for the L{SSLPort} items
in the site store. | [
"Create",
"and",
"return",
"a",
"L",
"{",
"PortScrollingFragment",
"}",
"for",
"the",
"L",
"{",
"SSLPort",
"}",
"items",
"in",
"the",
"site",
"store",
"."
] | train | https://github.com/twisted/mantissa/blob/53e5502aba23ce99be78b27f923a276593033fe8/xmantissa/webadmin.py#L725-L739 |
twisted/mantissa | xmantissa/webadmin.py | PortConfigurationFragment.createPortForm | def createPortForm(self, req, tag):
"""
Create and return a L{LiveForm} for adding a new L{TCPPort} or
L{SSLPort} to the site store.
"""
def port(s):
n = int(s)
if n < 0 or n > 65535:
raise ValueError(s)
return n
factories = []
for f in self.store.parent.powerupsFor(IProtocolFactoryFactory):
factories.append((f.__class__.__name__.decode('ascii'),
f,
False))
f = LiveForm(
self.portConf.createPort,
[Parameter('portNumber', TEXT_INPUT, port, 'Port Number',
'Integer 0 <= n <= 65535 giving the TCP port to bind.'),
Parameter('interface', TEXT_INPUT, unicode, 'Interface',
'Hostname to bind to, or blank for all interfaces.'),
Parameter('ssl', CHECKBOX_INPUT, bool, 'SSL',
'Select to indicate port should use SSL.'),
# Text area? File upload? What?
Parameter('certPath', TEXT_INPUT, unicode, 'Certificate Path',
'Path to a certificate file on the server, if SSL is to be used.'),
ChoiceParameter('factory', factories, 'Protocol Factory',
'Which pre-existing protocol factory to associate with this port.')])
f.setFragmentParent(self)
# f.docFactory = webtheme.getLoader(f.fragmentName)
return tag[f] | python | def createPortForm(self, req, tag):
"""
Create and return a L{LiveForm} for adding a new L{TCPPort} or
L{SSLPort} to the site store.
"""
def port(s):
n = int(s)
if n < 0 or n > 65535:
raise ValueError(s)
return n
factories = []
for f in self.store.parent.powerupsFor(IProtocolFactoryFactory):
factories.append((f.__class__.__name__.decode('ascii'),
f,
False))
f = LiveForm(
self.portConf.createPort,
[Parameter('portNumber', TEXT_INPUT, port, 'Port Number',
'Integer 0 <= n <= 65535 giving the TCP port to bind.'),
Parameter('interface', TEXT_INPUT, unicode, 'Interface',
'Hostname to bind to, or blank for all interfaces.'),
Parameter('ssl', CHECKBOX_INPUT, bool, 'SSL',
'Select to indicate port should use SSL.'),
# Text area? File upload? What?
Parameter('certPath', TEXT_INPUT, unicode, 'Certificate Path',
'Path to a certificate file on the server, if SSL is to be used.'),
ChoiceParameter('factory', factories, 'Protocol Factory',
'Which pre-existing protocol factory to associate with this port.')])
f.setFragmentParent(self)
# f.docFactory = webtheme.getLoader(f.fragmentName)
return tag[f] | [
"def",
"createPortForm",
"(",
"self",
",",
"req",
",",
"tag",
")",
":",
"def",
"port",
"(",
"s",
")",
":",
"n",
"=",
"int",
"(",
"s",
")",
"if",
"n",
"<",
"0",
"or",
"n",
">",
"65535",
":",
"raise",
"ValueError",
"(",
"s",
")",
"return",
"n",... | Create and return a L{LiveForm} for adding a new L{TCPPort} or
L{SSLPort} to the site store. | [
"Create",
"and",
"return",
"a",
"L",
"{",
"LiveForm",
"}",
"for",
"adding",
"a",
"new",
"L",
"{",
"TCPPort",
"}",
"or",
"L",
"{",
"SSLPort",
"}",
"to",
"the",
"site",
"store",
"."
] | train | https://github.com/twisted/mantissa/blob/53e5502aba23ce99be78b27f923a276593033fe8/xmantissa/webadmin.py#L743-L779 |
twisted/mantissa | xmantissa/ampserver.py | connectRoute | def connectRoute(amp, router, receiver, protocol):
"""
Connect the given receiver to a new box receiver for the given
protocol.
After connecting this router to an AMP server, use this method
similarly to how you would use C{reactor.connectTCP} to establish a new
connection to an HTTP, SMTP, or IRC server.
@param receiver: An L{IBoxReceiver} which will be started when a route
to a receiver for the given protocol is found.
@param protocol: The name of a protocol which the AMP peer to which
this router is connected has an L{IBoxReceiverFactory}.
@return: A L{Deferred} which fires with C{receiver} when the route is
established.
"""
route = router.bindRoute(receiver)
d = amp.callRemote(
Connect,
origin=route.localRouteName,
protocol=protocol)
def cbGotRoute(result):
route.connectTo(result['route'])
return receiver
d.addCallback(cbGotRoute)
return d | python | def connectRoute(amp, router, receiver, protocol):
"""
Connect the given receiver to a new box receiver for the given
protocol.
After connecting this router to an AMP server, use this method
similarly to how you would use C{reactor.connectTCP} to establish a new
connection to an HTTP, SMTP, or IRC server.
@param receiver: An L{IBoxReceiver} which will be started when a route
to a receiver for the given protocol is found.
@param protocol: The name of a protocol which the AMP peer to which
this router is connected has an L{IBoxReceiverFactory}.
@return: A L{Deferred} which fires with C{receiver} when the route is
established.
"""
route = router.bindRoute(receiver)
d = amp.callRemote(
Connect,
origin=route.localRouteName,
protocol=protocol)
def cbGotRoute(result):
route.connectTo(result['route'])
return receiver
d.addCallback(cbGotRoute)
return d | [
"def",
"connectRoute",
"(",
"amp",
",",
"router",
",",
"receiver",
",",
"protocol",
")",
":",
"route",
"=",
"router",
".",
"bindRoute",
"(",
"receiver",
")",
"d",
"=",
"amp",
".",
"callRemote",
"(",
"Connect",
",",
"origin",
"=",
"route",
".",
"localRo... | Connect the given receiver to a new box receiver for the given
protocol.
After connecting this router to an AMP server, use this method
similarly to how you would use C{reactor.connectTCP} to establish a new
connection to an HTTP, SMTP, or IRC server.
@param receiver: An L{IBoxReceiver} which will be started when a route
to a receiver for the given protocol is found.
@param protocol: The name of a protocol which the AMP peer to which
this router is connected has an L{IBoxReceiverFactory}.
@return: A L{Deferred} which fires with C{receiver} when the route is
established. | [
"Connect",
"the",
"given",
"receiver",
"to",
"a",
"new",
"box",
"receiver",
"for",
"the",
"given",
"protocol",
"."
] | train | https://github.com/twisted/mantissa/blob/53e5502aba23ce99be78b27f923a276593033fe8/xmantissa/ampserver.py#L220-L247 |
twisted/mantissa | xmantissa/ampserver.py | AMPConfiguration.generateOneTimePad | def generateOneTimePad(self, userStore):
"""
Generate a pad which can be used to authenticate via AMP. This pad
will expire in L{ONE_TIME_PAD_DURATION} seconds.
"""
pad = secureRandom(16).encode('hex')
self._oneTimePads[pad] = userStore.idInParent
def expirePad():
self._oneTimePads.pop(pad, None)
self.callLater(self.ONE_TIME_PAD_DURATION, expirePad)
return pad | python | def generateOneTimePad(self, userStore):
"""
Generate a pad which can be used to authenticate via AMP. This pad
will expire in L{ONE_TIME_PAD_DURATION} seconds.
"""
pad = secureRandom(16).encode('hex')
self._oneTimePads[pad] = userStore.idInParent
def expirePad():
self._oneTimePads.pop(pad, None)
self.callLater(self.ONE_TIME_PAD_DURATION, expirePad)
return pad | [
"def",
"generateOneTimePad",
"(",
"self",
",",
"userStore",
")",
":",
"pad",
"=",
"secureRandom",
"(",
"16",
")",
".",
"encode",
"(",
"'hex'",
")",
"self",
".",
"_oneTimePads",
"[",
"pad",
"]",
"=",
"userStore",
".",
"idInParent",
"def",
"expirePad",
"("... | Generate a pad which can be used to authenticate via AMP. This pad
will expire in L{ONE_TIME_PAD_DURATION} seconds. | [
"Generate",
"a",
"pad",
"which",
"can",
"be",
"used",
"to",
"authenticate",
"via",
"AMP",
".",
"This",
"pad",
"will",
"expire",
"in",
"L",
"{",
"ONE_TIME_PAD_DURATION",
"}",
"seconds",
"."
] | train | https://github.com/twisted/mantissa/blob/53e5502aba23ce99be78b27f923a276593033fe8/xmantissa/ampserver.py#L64-L74 |
twisted/mantissa | xmantissa/ampserver.py | AMPConfiguration.getFactory | def getFactory(self):
"""
Return a server factory which creates AMP protocol instances.
"""
factory = ServerFactory()
def protocol():
proto = CredReceiver()
proto.portal = Portal(
self.loginSystem,
[self.loginSystem,
OneTimePadChecker(self._oneTimePads)])
return proto
factory.protocol = protocol
return factory | python | def getFactory(self):
"""
Return a server factory which creates AMP protocol instances.
"""
factory = ServerFactory()
def protocol():
proto = CredReceiver()
proto.portal = Portal(
self.loginSystem,
[self.loginSystem,
OneTimePadChecker(self._oneTimePads)])
return proto
factory.protocol = protocol
return factory | [
"def",
"getFactory",
"(",
"self",
")",
":",
"factory",
"=",
"ServerFactory",
"(",
")",
"def",
"protocol",
"(",
")",
":",
"proto",
"=",
"CredReceiver",
"(",
")",
"proto",
".",
"portal",
"=",
"Portal",
"(",
"self",
".",
"loginSystem",
",",
"[",
"self",
... | Return a server factory which creates AMP protocol instances. | [
"Return",
"a",
"server",
"factory",
"which",
"creates",
"AMP",
"protocol",
"instances",
"."
] | train | https://github.com/twisted/mantissa/blob/53e5502aba23ce99be78b27f923a276593033fe8/xmantissa/ampserver.py#L78-L91 |
twisted/mantissa | xmantissa/ampserver.py | _RouteConnector.accept | def accept(self, origin, protocol):
"""
Create a new route attached to a L{IBoxReceiver} created by the
L{IBoxReceiverFactory} with the indicated protocol.
@type origin: C{unicode}
@param origin: The identifier of a route on the peer which will be
associated with this connection. Boxes sent back by the protocol
which is created in this call will be sent back to this route.
@type protocol: C{unicode}
@param protocol: The name of the protocol to which to establish a
connection.
@raise ProtocolUnknown: If no factory can be found for the named
protocol.
@return: A newly created C{unicode} route identifier for this
connection (as the value of a C{dict} with a C{'route'} key).
"""
for factory in self.store.powerupsFor(IBoxReceiverFactory):
# XXX What if there's a duplicate somewhere?
if factory.protocol == protocol:
receiver = factory.getBoxReceiver()
route = self.router.bindRoute(receiver)
# This might be better implemented using a hook on the box.
# See Twisted ticket #3479.
self.reactor.callLater(0, route.connectTo, origin)
return {'route': route.localRouteName}
raise ProtocolUnknown() | python | def accept(self, origin, protocol):
"""
Create a new route attached to a L{IBoxReceiver} created by the
L{IBoxReceiverFactory} with the indicated protocol.
@type origin: C{unicode}
@param origin: The identifier of a route on the peer which will be
associated with this connection. Boxes sent back by the protocol
which is created in this call will be sent back to this route.
@type protocol: C{unicode}
@param protocol: The name of the protocol to which to establish a
connection.
@raise ProtocolUnknown: If no factory can be found for the named
protocol.
@return: A newly created C{unicode} route identifier for this
connection (as the value of a C{dict} with a C{'route'} key).
"""
for factory in self.store.powerupsFor(IBoxReceiverFactory):
# XXX What if there's a duplicate somewhere?
if factory.protocol == protocol:
receiver = factory.getBoxReceiver()
route = self.router.bindRoute(receiver)
# This might be better implemented using a hook on the box.
# See Twisted ticket #3479.
self.reactor.callLater(0, route.connectTo, origin)
return {'route': route.localRouteName}
raise ProtocolUnknown() | [
"def",
"accept",
"(",
"self",
",",
"origin",
",",
"protocol",
")",
":",
"for",
"factory",
"in",
"self",
".",
"store",
".",
"powerupsFor",
"(",
"IBoxReceiverFactory",
")",
":",
"# XXX What if there's a duplicate somewhere?",
"if",
"factory",
".",
"protocol",
"=="... | Create a new route attached to a L{IBoxReceiver} created by the
L{IBoxReceiverFactory} with the indicated protocol.
@type origin: C{unicode}
@param origin: The identifier of a route on the peer which will be
associated with this connection. Boxes sent back by the protocol
which is created in this call will be sent back to this route.
@type protocol: C{unicode}
@param protocol: The name of the protocol to which to establish a
connection.
@raise ProtocolUnknown: If no factory can be found for the named
protocol.
@return: A newly created C{unicode} route identifier for this
connection (as the value of a C{dict} with a C{'route'} key). | [
"Create",
"a",
"new",
"route",
"attached",
"to",
"a",
"L",
"{",
"IBoxReceiver",
"}",
"created",
"by",
"the",
"L",
"{",
"IBoxReceiverFactory",
"}",
"with",
"the",
"indicated",
"protocol",
"."
] | train | https://github.com/twisted/mantissa/blob/53e5502aba23ce99be78b27f923a276593033fe8/xmantissa/ampserver.py#L151-L180 |
twisted/mantissa | xmantissa/ampserver.py | AMPAvatar.indirect | def indirect(self, interface):
"""
Create a L{Router} to handle AMP boxes received over an AMP connection.
"""
if interface is IBoxReceiver:
router = Router()
connector = self.connectorFactory(router)
router.bindRoute(connector, None).connectTo(None)
return router
raise NotImplementedError() | python | def indirect(self, interface):
"""
Create a L{Router} to handle AMP boxes received over an AMP connection.
"""
if interface is IBoxReceiver:
router = Router()
connector = self.connectorFactory(router)
router.bindRoute(connector, None).connectTo(None)
return router
raise NotImplementedError() | [
"def",
"indirect",
"(",
"self",
",",
"interface",
")",
":",
"if",
"interface",
"is",
"IBoxReceiver",
":",
"router",
"=",
"Router",
"(",
")",
"connector",
"=",
"self",
".",
"connectorFactory",
"(",
"router",
")",
"router",
".",
"bindRoute",
"(",
"connector"... | Create a L{Router} to handle AMP boxes received over an AMP connection. | [
"Create",
"a",
"L",
"{",
"Router",
"}",
"to",
"handle",
"AMP",
"boxes",
"received",
"over",
"an",
"AMP",
"connection",
"."
] | train | https://github.com/twisted/mantissa/blob/53e5502aba23ce99be78b27f923a276593033fe8/xmantissa/ampserver.py#L207-L216 |
miku/gluish | gluish/common.py | getfirstline | def getfirstline(file, default):
"""
Returns the first line of a file.
"""
with open(file, 'rb') as fh:
content = fh.readlines()
if len(content) == 1:
return content[0].decode('utf-8').strip('\n')
return default | python | def getfirstline(file, default):
"""
Returns the first line of a file.
"""
with open(file, 'rb') as fh:
content = fh.readlines()
if len(content) == 1:
return content[0].decode('utf-8').strip('\n')
return default | [
"def",
"getfirstline",
"(",
"file",
",",
"default",
")",
":",
"with",
"open",
"(",
"file",
",",
"'rb'",
")",
"as",
"fh",
":",
"content",
"=",
"fh",
".",
"readlines",
"(",
")",
"if",
"len",
"(",
"content",
")",
"==",
"1",
":",
"return",
"content",
... | Returns the first line of a file. | [
"Returns",
"the",
"first",
"line",
"of",
"a",
"file",
"."
] | train | https://github.com/miku/gluish/blob/56d3ac4f41a944e31ecac0aa3b6d1dc2ce705e29/gluish/common.py#L51-L60 |
zenotech/MyCluster | mycluster/slurm.py | job_stats_enhanced | def job_stats_enhanced(job_id):
"""
Get full job and step stats for job_id
"""
stats_dict = {}
with os.popen('sacct --noheader --format JobId,Elapsed,TotalCPU,Partition,NTasks,AveRSS,State,ExitCode,start,end -P -j ' + str(job_id)) as f:
try:
line = f.readline()
if line in ["SLURM accounting storage is disabled",
"slurm_load_job error: Invalid job id specified"]:
raise
cols = line.split('|')
stats_dict['job_id'] = cols[0]
stats_dict['wallclock'] = get_timedelta(cols[1])
stats_dict['cpu'] = get_timedelta(cols[2])
stats_dict['queue'] = cols[3]
stats_dict['status'] = cols[6]
stats_dict['exit_code'] = cols[7].split(':')[0]
stats_dict['start'] = cols[8]
stats_dict['end'] = cols[9]
steps = []
for line in f:
step = {}
cols = line.split('|')
step_val = cols[0].split('.')[1]
step['step'] = step_val
step['wallclock'] = get_timedelta(cols[1])
step['cpu'] = get_timedelta(cols[2])
step['ntasks'] = cols[4]
step['status'] = cols[6]
step['exit_code'] = cols[7].split(':')[0]
step['start'] = cols[8]
step['end'] = cols[9]
steps.append(step)
stats_dict['steps'] = steps
except:
with os.popen('squeue -h -j %s' % str(job_id)) as f:
try:
for line in f:
new_line = re.sub(' +', ' ', line.strip())
job_id = int(new_line.split(' ')[0])
state = new_line.split(' ')[4]
stats_dict['job_id'] = str(job_id)
stats_dict['status'] = state
except:
print('SLURM: Error reading job stats')
stats_dict['status'] = 'UNKNOWN'
with os.popen('squeue --format %%S -h -j ' + str(job_id)) as f:
try:
line = f.readline()
if len(line) > 0:
stats_dict['start_time'] = line
else:
stats_dict['start_time'] = ""
except:
print('SLURM: Error getting start time')
return stats_dict | python | def job_stats_enhanced(job_id):
"""
Get full job and step stats for job_id
"""
stats_dict = {}
with os.popen('sacct --noheader --format JobId,Elapsed,TotalCPU,Partition,NTasks,AveRSS,State,ExitCode,start,end -P -j ' + str(job_id)) as f:
try:
line = f.readline()
if line in ["SLURM accounting storage is disabled",
"slurm_load_job error: Invalid job id specified"]:
raise
cols = line.split('|')
stats_dict['job_id'] = cols[0]
stats_dict['wallclock'] = get_timedelta(cols[1])
stats_dict['cpu'] = get_timedelta(cols[2])
stats_dict['queue'] = cols[3]
stats_dict['status'] = cols[6]
stats_dict['exit_code'] = cols[7].split(':')[0]
stats_dict['start'] = cols[8]
stats_dict['end'] = cols[9]
steps = []
for line in f:
step = {}
cols = line.split('|')
step_val = cols[0].split('.')[1]
step['step'] = step_val
step['wallclock'] = get_timedelta(cols[1])
step['cpu'] = get_timedelta(cols[2])
step['ntasks'] = cols[4]
step['status'] = cols[6]
step['exit_code'] = cols[7].split(':')[0]
step['start'] = cols[8]
step['end'] = cols[9]
steps.append(step)
stats_dict['steps'] = steps
except:
with os.popen('squeue -h -j %s' % str(job_id)) as f:
try:
for line in f:
new_line = re.sub(' +', ' ', line.strip())
job_id = int(new_line.split(' ')[0])
state = new_line.split(' ')[4]
stats_dict['job_id'] = str(job_id)
stats_dict['status'] = state
except:
print('SLURM: Error reading job stats')
stats_dict['status'] = 'UNKNOWN'
with os.popen('squeue --format %%S -h -j ' + str(job_id)) as f:
try:
line = f.readline()
if len(line) > 0:
stats_dict['start_time'] = line
else:
stats_dict['start_time'] = ""
except:
print('SLURM: Error getting start time')
return stats_dict | [
"def",
"job_stats_enhanced",
"(",
"job_id",
")",
":",
"stats_dict",
"=",
"{",
"}",
"with",
"os",
".",
"popen",
"(",
"'sacct --noheader --format JobId,Elapsed,TotalCPU,Partition,NTasks,AveRSS,State,ExitCode,start,end -P -j '",
"+",
"str",
"(",
"job_id",
")",
")",
"as",
"... | Get full job and step stats for job_id | [
"Get",
"full",
"job",
"and",
"step",
"stats",
"for",
"job_id"
] | train | https://github.com/zenotech/MyCluster/blob/d2b7e35c57a515926e83bbc083d26930cd67e1bd/mycluster/slurm.py#L300-L357 |
vladcalin/gemstone | gemstone/core/structs.py | parse_json_structure | def parse_json_structure(string_item):
"""
Given a raw representation of a json structure, returns the parsed corresponding data
structure (``JsonRpcRequest`` or ``JsonRpcRequestBatch``)
:param string_item:
:return:
"""
if not isinstance(string_item, str):
raise TypeError("Expected str but got {} instead".format(type(string_item).__name__))
try:
item = json.loads(string_item)
except json.JSONDecodeError:
raise JsonRpcParseError()
if isinstance(item, dict):
return JsonRpcRequest.from_dict(item)
elif isinstance(item, list):
if len(item) == 0:
raise JsonRpcInvalidRequestError()
request_batch = JsonRpcRequestBatch([])
for d in item:
try:
# handles the case of valid batch but with invalid
# requests.
if not isinstance(d, dict):
raise JsonRpcInvalidRequestError()
# is dict, all fine
parsed_entry = JsonRpcRequest.from_dict(d)
except JsonRpcInvalidRequestError:
parsed_entry = GenericResponse.INVALID_REQUEST
request_batch.add_item(parsed_entry)
return request_batch | python | def parse_json_structure(string_item):
"""
Given a raw representation of a json structure, returns the parsed corresponding data
structure (``JsonRpcRequest`` or ``JsonRpcRequestBatch``)
:param string_item:
:return:
"""
if not isinstance(string_item, str):
raise TypeError("Expected str but got {} instead".format(type(string_item).__name__))
try:
item = json.loads(string_item)
except json.JSONDecodeError:
raise JsonRpcParseError()
if isinstance(item, dict):
return JsonRpcRequest.from_dict(item)
elif isinstance(item, list):
if len(item) == 0:
raise JsonRpcInvalidRequestError()
request_batch = JsonRpcRequestBatch([])
for d in item:
try:
# handles the case of valid batch but with invalid
# requests.
if not isinstance(d, dict):
raise JsonRpcInvalidRequestError()
# is dict, all fine
parsed_entry = JsonRpcRequest.from_dict(d)
except JsonRpcInvalidRequestError:
parsed_entry = GenericResponse.INVALID_REQUEST
request_batch.add_item(parsed_entry)
return request_batch | [
"def",
"parse_json_structure",
"(",
"string_item",
")",
":",
"if",
"not",
"isinstance",
"(",
"string_item",
",",
"str",
")",
":",
"raise",
"TypeError",
"(",
"\"Expected str but got {} instead\"",
".",
"format",
"(",
"type",
"(",
"string_item",
")",
".",
"__name_... | Given a raw representation of a json structure, returns the parsed corresponding data
structure (``JsonRpcRequest`` or ``JsonRpcRequestBatch``)
:param string_item:
:return: | [
"Given",
"a",
"raw",
"representation",
"of",
"a",
"json",
"structure",
"returns",
"the",
"parsed",
"corresponding",
"data",
"structure",
"(",
"JsonRpcRequest",
"or",
"JsonRpcRequestBatch",
")"
] | train | https://github.com/vladcalin/gemstone/blob/325a49d17621b9d45ffd2b5eca6f0de284de8ba4/gemstone/core/structs.py#L195-L229 |
vladcalin/gemstone | gemstone/core/structs.py | JsonRpcRequest.from_dict | def from_dict(cls, d):
"""
Validates a dict instance and transforms it in a
:py:class:`gemstone.core.structs.JsonRpcRequest`
instance
:param d: The dict instance
:return: A :py:class:`gemstone.core.structs.JsonRpcRequest`
if everything goes well, or None if the validation fails
"""
for key in ("method", "jsonrpc"):
if key not in d:
raise JsonRpcInvalidRequestError()
# check jsonrpc version
jsonrpc = d.get("jsonrpc", None)
if jsonrpc != "2.0":
raise JsonRpcInvalidRequestError()
# check method
method = d.get("method", None)
if not method:
raise JsonRpcInvalidRequestError()
if not isinstance(method, str):
raise JsonRpcInvalidRequestError()
# params
params = d.get("params", {})
if not isinstance(params, (list, dict)):
raise JsonRpcInvalidRequestError()
req_id = d.get("id", None)
if not isinstance(req_id, (int, str)) and req_id is not None:
raise JsonRpcInvalidRequestError()
extras = {k: d[k] for k in d if k not in ("jsonrpc", "id", "method", "params")}
instance = cls(
id=req_id,
method=method,
params=params,
extra=extras
)
return instance | python | def from_dict(cls, d):
"""
Validates a dict instance and transforms it in a
:py:class:`gemstone.core.structs.JsonRpcRequest`
instance
:param d: The dict instance
:return: A :py:class:`gemstone.core.structs.JsonRpcRequest`
if everything goes well, or None if the validation fails
"""
for key in ("method", "jsonrpc"):
if key not in d:
raise JsonRpcInvalidRequestError()
# check jsonrpc version
jsonrpc = d.get("jsonrpc", None)
if jsonrpc != "2.0":
raise JsonRpcInvalidRequestError()
# check method
method = d.get("method", None)
if not method:
raise JsonRpcInvalidRequestError()
if not isinstance(method, str):
raise JsonRpcInvalidRequestError()
# params
params = d.get("params", {})
if not isinstance(params, (list, dict)):
raise JsonRpcInvalidRequestError()
req_id = d.get("id", None)
if not isinstance(req_id, (int, str)) and req_id is not None:
raise JsonRpcInvalidRequestError()
extras = {k: d[k] for k in d if k not in ("jsonrpc", "id", "method", "params")}
instance = cls(
id=req_id,
method=method,
params=params,
extra=extras
)
return instance | [
"def",
"from_dict",
"(",
"cls",
",",
"d",
")",
":",
"for",
"key",
"in",
"(",
"\"method\"",
",",
"\"jsonrpc\"",
")",
":",
"if",
"key",
"not",
"in",
"d",
":",
"raise",
"JsonRpcInvalidRequestError",
"(",
")",
"# check jsonrpc version",
"jsonrpc",
"=",
"d",
... | Validates a dict instance and transforms it in a
:py:class:`gemstone.core.structs.JsonRpcRequest`
instance
:param d: The dict instance
:return: A :py:class:`gemstone.core.structs.JsonRpcRequest`
if everything goes well, or None if the validation fails | [
"Validates",
"a",
"dict",
"instance",
"and",
"transforms",
"it",
"in",
"a",
":",
"py",
":",
"class",
":",
"gemstone",
".",
"core",
".",
"structs",
".",
"JsonRpcRequest",
"instance"
] | train | https://github.com/vladcalin/gemstone/blob/325a49d17621b9d45ffd2b5eca6f0de284de8ba4/gemstone/core/structs.py#L46-L89 |
vladcalin/gemstone | gemstone/core/structs.py | JsonRpcResponseBatch.add_item | def add_item(self, item):
"""Adds an item to the batch."""
if not isinstance(item, JsonRpcResponse):
raise TypeError(
"Expected JsonRpcResponse but got {} instead".format(type(item).__name__))
self.items.append(item) | python | def add_item(self, item):
"""Adds an item to the batch."""
if not isinstance(item, JsonRpcResponse):
raise TypeError(
"Expected JsonRpcResponse but got {} instead".format(type(item).__name__))
self.items.append(item) | [
"def",
"add_item",
"(",
"self",
",",
"item",
")",
":",
"if",
"not",
"isinstance",
"(",
"item",
",",
"JsonRpcResponse",
")",
":",
"raise",
"TypeError",
"(",
"\"Expected JsonRpcResponse but got {} instead\"",
".",
"format",
"(",
"type",
"(",
"item",
")",
".",
... | Adds an item to the batch. | [
"Adds",
"an",
"item",
"to",
"the",
"batch",
"."
] | train | https://github.com/vladcalin/gemstone/blob/325a49d17621b9d45ffd2b5eca6f0de284de8ba4/gemstone/core/structs.py#L165-L172 |
murphy214/berrl | build/lib/berrl/quickmaps.py | make_spark_lines | def make_spark_lines(table,filename,sc,**kwargs):
spark_output = True
lines_out_count = False
extrema = False
for key,value in kwargs.iteritems():
if key == 'lines_out_count':
lines_out_count = value
if key == 'extrema':
extrema = value
# removing datetime references from imported postgis database
# CURRENTLY datetime from postgis dbs throw errors
# fields containing dates removed
list = []
count = 0
for row in table.columns.values.tolist():
if 'date' in row:
list.append(count)
count += 1
table.drop(table.columns[list], axis=1, inplace=True)
# getting spark arguments
if lines_out_count == False:
args = make_spark_args(table,25,lines_out = True,extrema=extrema)
else:
args = make_spark_args(table,25,lines_out_count=lines_out_count)
# concurrent represents rdd structure that will be parrelized
concurrent = sc.parallelize(args)
# getting table that would normally be going into this function
table = concurrent.map(map_spark_lines).collect()
'''
alignment_field = False
spark_output = True
if kwargs is not None:
for key,value in kwargs.iteritems():
if key == 'alignment_field':
alignment_field = value
if key == 'spark_output':
spark_output = value
#changing dataframe to list if dataframe
if isinstance(table,pd.DataFrame):
table=df2list(table)
header=table[0]
total = []
# making table the proper iterable for each input
if spark_output == True:
#table = sum(table,[])
pass
else:
table = table[1:]
'''
'''
# making filenames list
filenames = []
count = 0
while not len(filenames) == len(table):
count += 1
filename = 'lines%s.geojson' % str(count)
filenames.append(filename)
args = []
# zipping arguments together for each value in table
for filename,row in itertools.izip(filenames,table):
args.append([filename,row])
concurrent = sc.parallelize(args)
concurrent.map(map_lines_output).collect()
'''
'''
count=0
total=0
for row in table:
count+=1
# logic to treat rows as outputs of make_line or to perform make_line operation
if spark_output == False:
value = make_line([header,row],list=True,postgis=True,alignment_field=alignment_field)
elif spark_output == True:
value = row
# logic for how to handle starting and ending geojson objects
if row==table[0]:
#value=make_line([header,row],list=True,postgis=True,alignment_field=alignment_field)
if not len(table)==2:
value=value[:-3]
totalvalue=value+['\t},']
elif row==table[-1]:
#value=make_line([header,row],list=True,postgis=True,alignment_field=alignment_field)
value=value[2:]
totalvalue=totalvalue+value
else:
#value=make_line([header,row],list=True,postgis=True,alignment_field=alignment_field)
value=value[2:-3]
value=value+['\t},']
totalvalue=totalvalue+value
if count == 1000:
total += count
count = 0
print '[%s/%s]' % (total,len(table))
bl.parselist(totalvalue,filename)
''' | python | def make_spark_lines(table,filename,sc,**kwargs):
spark_output = True
lines_out_count = False
extrema = False
for key,value in kwargs.iteritems():
if key == 'lines_out_count':
lines_out_count = value
if key == 'extrema':
extrema = value
# removing datetime references from imported postgis database
# CURRENTLY datetime from postgis dbs throw errors
# fields containing dates removed
list = []
count = 0
for row in table.columns.values.tolist():
if 'date' in row:
list.append(count)
count += 1
table.drop(table.columns[list], axis=1, inplace=True)
# getting spark arguments
if lines_out_count == False:
args = make_spark_args(table,25,lines_out = True,extrema=extrema)
else:
args = make_spark_args(table,25,lines_out_count=lines_out_count)
# concurrent represents rdd structure that will be parrelized
concurrent = sc.parallelize(args)
# getting table that would normally be going into this function
table = concurrent.map(map_spark_lines).collect()
'''
alignment_field = False
spark_output = True
if kwargs is not None:
for key,value in kwargs.iteritems():
if key == 'alignment_field':
alignment_field = value
if key == 'spark_output':
spark_output = value
#changing dataframe to list if dataframe
if isinstance(table,pd.DataFrame):
table=df2list(table)
header=table[0]
total = []
# making table the proper iterable for each input
if spark_output == True:
#table = sum(table,[])
pass
else:
table = table[1:]
'''
'''
# making filenames list
filenames = []
count = 0
while not len(filenames) == len(table):
count += 1
filename = 'lines%s.geojson' % str(count)
filenames.append(filename)
args = []
# zipping arguments together for each value in table
for filename,row in itertools.izip(filenames,table):
args.append([filename,row])
concurrent = sc.parallelize(args)
concurrent.map(map_lines_output).collect()
'''
'''
count=0
total=0
for row in table:
count+=1
# logic to treat rows as outputs of make_line or to perform make_line operation
if spark_output == False:
value = make_line([header,row],list=True,postgis=True,alignment_field=alignment_field)
elif spark_output == True:
value = row
# logic for how to handle starting and ending geojson objects
if row==table[0]:
#value=make_line([header,row],list=True,postgis=True,alignment_field=alignment_field)
if not len(table)==2:
value=value[:-3]
totalvalue=value+['\t},']
elif row==table[-1]:
#value=make_line([header,row],list=True,postgis=True,alignment_field=alignment_field)
value=value[2:]
totalvalue=totalvalue+value
else:
#value=make_line([header,row],list=True,postgis=True,alignment_field=alignment_field)
value=value[2:-3]
value=value+['\t},']
totalvalue=totalvalue+value
if count == 1000:
total += count
count = 0
print '[%s/%s]' % (total,len(table))
bl.parselist(totalvalue,filename)
''' | [
"def",
"make_spark_lines",
"(",
"table",
",",
"filename",
",",
"sc",
",",
"*",
"*",
"kwargs",
")",
":",
"spark_output",
"=",
"True",
"lines_out_count",
"=",
"False",
"extrema",
"=",
"False",
"for",
"key",
",",
"value",
"in",
"kwargs",
".",
"iteritems",
"... | alignment_field = False
spark_output = True
if kwargs is not None:
for key,value in kwargs.iteritems():
if key == 'alignment_field':
alignment_field = value
if key == 'spark_output':
spark_output = value
#changing dataframe to list if dataframe
if isinstance(table,pd.DataFrame):
table=df2list(table)
header=table[0]
total = []
# making table the proper iterable for each input
if spark_output == True:
#table = sum(table,[])
pass
else:
table = table[1:] | [
"alignment_field",
"=",
"False",
"spark_output",
"=",
"True",
"if",
"kwargs",
"is",
"not",
"None",
":",
"for",
"key",
"value",
"in",
"kwargs",
".",
"iteritems",
"()",
":",
"if",
"key",
"==",
"alignment_field",
":",
"alignment_field",
"=",
"value",
"if",
"k... | train | https://github.com/murphy214/berrl/blob/ce4d060cc7db74c32facc538fa1d7030f1a27467/build/lib/berrl/quickmaps.py#L445-L552 |
axiom-data-science/pygc | pygc/gc.py | great_circle | def great_circle(**kwargs):
"""
Named arguments:
distance = distance to travel, or numpy array of distances
azimuth = angle, in DEGREES of HEADING from NORTH, or numpy array of azimuths
latitude = latitude, in DECIMAL DEGREES, or numpy array of latitudes
longitude = longitude, in DECIMAL DEGREES, or numpy array of longitudes
rmajor = radius of earth's major axis. default=6378137.0 (WGS84)
rminor = radius of earth's minor axis. default=6356752.3142 (WGS84)
Returns a dictionary with:
'latitude' in decimal degrees
'longitude' in decimal degrees
'reverse_azimuth' in decimal degrees
"""
distance = kwargs.pop('distance')
azimuth = np.radians(kwargs.pop('azimuth'))
latitude = np.radians(kwargs.pop('latitude'))
longitude = np.radians(kwargs.pop('longitude'))
rmajor = kwargs.pop('rmajor', 6378137.0)
rminor = kwargs.pop('rminor', 6356752.3142)
f = (rmajor - rminor) / rmajor
vector_pt = np.vectorize(vinc_pt)
lat_result, lon_result, angle_result = vector_pt(f, rmajor,
latitude,
longitude,
azimuth,
distance)
return {'latitude': np.degrees(lat_result),
'longitude': np.degrees(lon_result),
'reverse_azimuth': np.degrees(angle_result)} | python | def great_circle(**kwargs):
"""
Named arguments:
distance = distance to travel, or numpy array of distances
azimuth = angle, in DEGREES of HEADING from NORTH, or numpy array of azimuths
latitude = latitude, in DECIMAL DEGREES, or numpy array of latitudes
longitude = longitude, in DECIMAL DEGREES, or numpy array of longitudes
rmajor = radius of earth's major axis. default=6378137.0 (WGS84)
rminor = radius of earth's minor axis. default=6356752.3142 (WGS84)
Returns a dictionary with:
'latitude' in decimal degrees
'longitude' in decimal degrees
'reverse_azimuth' in decimal degrees
"""
distance = kwargs.pop('distance')
azimuth = np.radians(kwargs.pop('azimuth'))
latitude = np.radians(kwargs.pop('latitude'))
longitude = np.radians(kwargs.pop('longitude'))
rmajor = kwargs.pop('rmajor', 6378137.0)
rminor = kwargs.pop('rminor', 6356752.3142)
f = (rmajor - rminor) / rmajor
vector_pt = np.vectorize(vinc_pt)
lat_result, lon_result, angle_result = vector_pt(f, rmajor,
latitude,
longitude,
azimuth,
distance)
return {'latitude': np.degrees(lat_result),
'longitude': np.degrees(lon_result),
'reverse_azimuth': np.degrees(angle_result)} | [
"def",
"great_circle",
"(",
"*",
"*",
"kwargs",
")",
":",
"distance",
"=",
"kwargs",
".",
"pop",
"(",
"'distance'",
")",
"azimuth",
"=",
"np",
".",
"radians",
"(",
"kwargs",
".",
"pop",
"(",
"'azimuth'",
")",
")",
"latitude",
"=",
"np",
".",
"radians... | Named arguments:
distance = distance to travel, or numpy array of distances
azimuth = angle, in DEGREES of HEADING from NORTH, or numpy array of azimuths
latitude = latitude, in DECIMAL DEGREES, or numpy array of latitudes
longitude = longitude, in DECIMAL DEGREES, or numpy array of longitudes
rmajor = radius of earth's major axis. default=6378137.0 (WGS84)
rminor = radius of earth's minor axis. default=6356752.3142 (WGS84)
Returns a dictionary with:
'latitude' in decimal degrees
'longitude' in decimal degrees
'reverse_azimuth' in decimal degrees | [
"Named",
"arguments",
":",
"distance",
"=",
"distance",
"to",
"travel",
"or",
"numpy",
"array",
"of",
"distances",
"azimuth",
"=",
"angle",
"in",
"DEGREES",
"of",
"HEADING",
"from",
"NORTH",
"or",
"numpy",
"array",
"of",
"azimuths",
"latitude",
"=",
"latitud... | train | https://github.com/axiom-data-science/pygc/blob/e9ea49628809ba332d1203b67ec956d4dbc4a1d0/pygc/gc.py#L4-L37 |
axiom-data-science/pygc | pygc/gc.py | great_distance | def great_distance(**kwargs):
"""
Named arguments:
start_latitude = starting latitude, in DECIMAL DEGREES
start_longitude = starting longitude, in DECIMAL DEGREES
end_latitude = ending latitude, in DECIMAL DEGREES
end_longitude = ending longitude, in DECIMAL DEGREES
rmajor = radius of earth's major axis. default=6378137.0 (WGS84)
rminor = radius of earth's minor axis. default=6356752.3142 (WGS84)
Returns a dictionaty with:
'distance' in meters
'azimuth' in decimal degrees
'reverse_azimuth' in decimal degrees
"""
sy = kwargs.pop('start_latitude')
sx = kwargs.pop('start_longitude')
ey = kwargs.pop('end_latitude')
ex = kwargs.pop('end_longitude')
rmajor = kwargs.pop('rmajor', 6378137.0)
rminor = kwargs.pop('rminor', 6356752.3142)
f = (rmajor - rminor) / rmajor
if (np.ma.isMaskedArray(sy) or
np.ma.isMaskedArray(sx) or
np.ma.isMaskedArray(ey) or
np.ma.isMaskedArray(ex)
):
try:
assert sy.size == sx.size == ey.size == ex.size
except AttributeError:
raise ValueError("All or none of the inputs should be masked")
except AssertionError:
raise ValueError("When using masked arrays all must be of equal size")
final_mask = np.logical_not((sy.mask | sx.mask | ey.mask | ex.mask))
if np.isscalar(final_mask):
final_mask = np.full(sy.size, final_mask, dtype=bool)
sy = sy[final_mask]
sx = sx[final_mask]
ey = ey[final_mask]
ex = ex[final_mask]
if (np.all(sy.mask) or np.all(sx.mask) or np.all(ey.mask) or np.all(ex.mask)) or \
(sy.size == 0 or sx.size == 0 or ey.size == 0 or ex.size == 0):
vector_dist = np.vectorize(vinc_dist, otypes=[np.float64])
else:
vector_dist = np.vectorize(vinc_dist)
results = vector_dist(f, rmajor,
np.radians(sy),
np.radians(sx),
np.radians(ey),
np.radians(ex))
d = np.ma.masked_all(final_mask.size, dtype=np.float64)
a = np.ma.masked_all(final_mask.size, dtype=np.float64)
ra = np.ma.masked_all(final_mask.size, dtype=np.float64)
if len(results) == 3:
d[final_mask] = results[0]
a[final_mask] = results[1]
ra[final_mask] = results[2]
else:
vector_dist = np.vectorize(vinc_dist)
d, a, ra = vector_dist(f, rmajor,
np.radians(sy),
np.radians(sx),
np.radians(ey),
np.radians(ex))
return {'distance': d,
'azimuth': np.degrees(a),
'reverse_azimuth': np.degrees(ra)} | python | def great_distance(**kwargs):
"""
Named arguments:
start_latitude = starting latitude, in DECIMAL DEGREES
start_longitude = starting longitude, in DECIMAL DEGREES
end_latitude = ending latitude, in DECIMAL DEGREES
end_longitude = ending longitude, in DECIMAL DEGREES
rmajor = radius of earth's major axis. default=6378137.0 (WGS84)
rminor = radius of earth's minor axis. default=6356752.3142 (WGS84)
Returns a dictionaty with:
'distance' in meters
'azimuth' in decimal degrees
'reverse_azimuth' in decimal degrees
"""
sy = kwargs.pop('start_latitude')
sx = kwargs.pop('start_longitude')
ey = kwargs.pop('end_latitude')
ex = kwargs.pop('end_longitude')
rmajor = kwargs.pop('rmajor', 6378137.0)
rminor = kwargs.pop('rminor', 6356752.3142)
f = (rmajor - rminor) / rmajor
if (np.ma.isMaskedArray(sy) or
np.ma.isMaskedArray(sx) or
np.ma.isMaskedArray(ey) or
np.ma.isMaskedArray(ex)
):
try:
assert sy.size == sx.size == ey.size == ex.size
except AttributeError:
raise ValueError("All or none of the inputs should be masked")
except AssertionError:
raise ValueError("When using masked arrays all must be of equal size")
final_mask = np.logical_not((sy.mask | sx.mask | ey.mask | ex.mask))
if np.isscalar(final_mask):
final_mask = np.full(sy.size, final_mask, dtype=bool)
sy = sy[final_mask]
sx = sx[final_mask]
ey = ey[final_mask]
ex = ex[final_mask]
if (np.all(sy.mask) or np.all(sx.mask) or np.all(ey.mask) or np.all(ex.mask)) or \
(sy.size == 0 or sx.size == 0 or ey.size == 0 or ex.size == 0):
vector_dist = np.vectorize(vinc_dist, otypes=[np.float64])
else:
vector_dist = np.vectorize(vinc_dist)
results = vector_dist(f, rmajor,
np.radians(sy),
np.radians(sx),
np.radians(ey),
np.radians(ex))
d = np.ma.masked_all(final_mask.size, dtype=np.float64)
a = np.ma.masked_all(final_mask.size, dtype=np.float64)
ra = np.ma.masked_all(final_mask.size, dtype=np.float64)
if len(results) == 3:
d[final_mask] = results[0]
a[final_mask] = results[1]
ra[final_mask] = results[2]
else:
vector_dist = np.vectorize(vinc_dist)
d, a, ra = vector_dist(f, rmajor,
np.radians(sy),
np.radians(sx),
np.radians(ey),
np.radians(ex))
return {'distance': d,
'azimuth': np.degrees(a),
'reverse_azimuth': np.degrees(ra)} | [
"def",
"great_distance",
"(",
"*",
"*",
"kwargs",
")",
":",
"sy",
"=",
"kwargs",
".",
"pop",
"(",
"'start_latitude'",
")",
"sx",
"=",
"kwargs",
".",
"pop",
"(",
"'start_longitude'",
")",
"ey",
"=",
"kwargs",
".",
"pop",
"(",
"'end_latitude'",
")",
"ex"... | Named arguments:
start_latitude = starting latitude, in DECIMAL DEGREES
start_longitude = starting longitude, in DECIMAL DEGREES
end_latitude = ending latitude, in DECIMAL DEGREES
end_longitude = ending longitude, in DECIMAL DEGREES
rmajor = radius of earth's major axis. default=6378137.0 (WGS84)
rminor = radius of earth's minor axis. default=6356752.3142 (WGS84)
Returns a dictionaty with:
'distance' in meters
'azimuth' in decimal degrees
'reverse_azimuth' in decimal degrees | [
"Named",
"arguments",
":",
"start_latitude",
"=",
"starting",
"latitude",
"in",
"DECIMAL",
"DEGREES",
"start_longitude",
"=",
"starting",
"longitude",
"in",
"DECIMAL",
"DEGREES",
"end_latitude",
"=",
"ending",
"latitude",
"in",
"DECIMAL",
"DEGREES",
"end_longitude",
... | train | https://github.com/axiom-data-science/pygc/blob/e9ea49628809ba332d1203b67ec956d4dbc4a1d0/pygc/gc.py#L40-L117 |
laurivosandi/butterknife | host/butterknife/pool.py | LocalPool.manifest | def manifest(self, subvol):
"""
Generator for manifest, yields 7-tuples
"""
subvol_path = os.path.join(self.path, str(subvol))
builtin_path = os.path.join(subvol_path, MANIFEST_DIR[1:], str(subvol))
manifest_path = os.path.join(MANIFEST_DIR, str(subvol))
if os.path.exists(builtin_path):
# Stream the manifest written into the (read-only) template,
# note that this has not been done up to now
return open(builtin_path, "rb")
elif os.path.exists(manifest_path):
# Stream the manifest written into /var/lib/butterknife/manifests
return open(manifest_path, "rb")
else:
# If we don't have any stream manifest and save it under /var/lib/butterknife/manifests
def generator():
with tempfile.NamedTemporaryFile(prefix=str(subvol), dir=MANIFEST_DIR, delete=False) as fh:
print("Temporarily writing to", fh.name)
for entry in generate_manifest(os.path.join(self.path, str(subvol))):
line = ("\t".join(["-" if j == None else str(j) for j in entry])).encode("utf-8")+b"\n"
fh.write(line)
yield line
print("Renaming to", manifest_path)
os.rename(fh.name, manifest_path)
return generator() | python | def manifest(self, subvol):
"""
Generator for manifest, yields 7-tuples
"""
subvol_path = os.path.join(self.path, str(subvol))
builtin_path = os.path.join(subvol_path, MANIFEST_DIR[1:], str(subvol))
manifest_path = os.path.join(MANIFEST_DIR, str(subvol))
if os.path.exists(builtin_path):
# Stream the manifest written into the (read-only) template,
# note that this has not been done up to now
return open(builtin_path, "rb")
elif os.path.exists(manifest_path):
# Stream the manifest written into /var/lib/butterknife/manifests
return open(manifest_path, "rb")
else:
# If we don't have any stream manifest and save it under /var/lib/butterknife/manifests
def generator():
with tempfile.NamedTemporaryFile(prefix=str(subvol), dir=MANIFEST_DIR, delete=False) as fh:
print("Temporarily writing to", fh.name)
for entry in generate_manifest(os.path.join(self.path, str(subvol))):
line = ("\t".join(["-" if j == None else str(j) for j in entry])).encode("utf-8")+b"\n"
fh.write(line)
yield line
print("Renaming to", manifest_path)
os.rename(fh.name, manifest_path)
return generator() | [
"def",
"manifest",
"(",
"self",
",",
"subvol",
")",
":",
"subvol_path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"path",
",",
"str",
"(",
"subvol",
")",
")",
"builtin_path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"subvol_path",
","... | Generator for manifest, yields 7-tuples | [
"Generator",
"for",
"manifest",
"yields",
"7",
"-",
"tuples"
] | train | https://github.com/laurivosandi/butterknife/blob/076ddabd66dcc1cedda7eba27ddca2a9ebed309e/host/butterknife/pool.py#L70-L96 |
vladcalin/gemstone | gemstone/core/decorators.py | event_handler | def event_handler(event_name):
"""
Decorator for designating a handler for an event type. ``event_name`` must be a string
representing the name of the event type.
The decorated function must accept a parameter: the body of the received event,
which will be a Python object that can be encoded as a JSON (dict, list, str, int,
bool, float or None)
:param event_name: The name of the event that will be handled. Only one handler per
event name is supported by the same microservice.
"""
def wrapper(func):
func._event_handler = True
func._handled_event = event_name
return func
return wrapper | python | def event_handler(event_name):
"""
Decorator for designating a handler for an event type. ``event_name`` must be a string
representing the name of the event type.
The decorated function must accept a parameter: the body of the received event,
which will be a Python object that can be encoded as a JSON (dict, list, str, int,
bool, float or None)
:param event_name: The name of the event that will be handled. Only one handler per
event name is supported by the same microservice.
"""
def wrapper(func):
func._event_handler = True
func._handled_event = event_name
return func
return wrapper | [
"def",
"event_handler",
"(",
"event_name",
")",
":",
"def",
"wrapper",
"(",
"func",
")",
":",
"func",
".",
"_event_handler",
"=",
"True",
"func",
".",
"_handled_event",
"=",
"event_name",
"return",
"func",
"return",
"wrapper"
] | Decorator for designating a handler for an event type. ``event_name`` must be a string
representing the name of the event type.
The decorated function must accept a parameter: the body of the received event,
which will be a Python object that can be encoded as a JSON (dict, list, str, int,
bool, float or None)
:param event_name: The name of the event that will be handled. Only one handler per
event name is supported by the same microservice. | [
"Decorator",
"for",
"designating",
"a",
"handler",
"for",
"an",
"event",
"type",
".",
"event_name",
"must",
"be",
"a",
"string",
"representing",
"the",
"name",
"of",
"the",
"event",
"type",
"."
] | train | https://github.com/vladcalin/gemstone/blob/325a49d17621b9d45ffd2b5eca6f0de284de8ba4/gemstone/core/decorators.py#L14-L32 |
vladcalin/gemstone | gemstone/core/decorators.py | exposed_method | def exposed_method(name=None, private=False, is_coroutine=True, requires_handler_reference=False):
"""
Marks a method as exposed via JSON RPC.
:param name: the name of the exposed method. Must contains only letters, digits, dots and underscores.
If not present or is set explicitly to ``None``, this parameter will default to the name
of the exposed method.
If two methods with the same name are exposed, a ``ValueError`` is raised.
:type name: str
:param private: Flag that specifies if the exposed method is private.
:type private: bool
:param is_coroutine: Flag that specifies if the method is a Tornado coroutine. If True, it will be wrapped
with the :py:func:`tornado.gen.coroutine` decorator.
:type is_coroutine: bool
:param requires_handler_reference: If ``True``, the handler method will receive as the first
parameter a ``handler`` argument with the Tornado
request handler for the current request. This request handler
can be further used to extract various information from the
request, such as headers, cookies, etc.
:type requires_handler_reference: bool
.. versionadded:: 0.9.0
"""
def wrapper(func):
# validation
if name:
method_name = name
else:
method_name = func.__name__
if not METHOD_NAME_REGEX.match(method_name):
raise ValueError("Invalid method name: '{}'".format(method_name))
@functools.wraps(func)
def real_wrapper(*args, **kwargs):
return func(*args, **kwargs)
# set appropriate flags
if private:
setattr(real_wrapper, "_exposed_private", True)
else:
setattr(real_wrapper, "_exposed_public", True)
if is_coroutine:
real_wrapper.__gemstone_is_coroutine = True
real_wrapper = tornado.gen.coroutine(real_wrapper)
setattr(real_wrapper, "_is_coroutine", True)
if requires_handler_reference:
setattr(real_wrapper, "_req_h_ref", True)
setattr(real_wrapper, "_exposed_name", method_name)
return real_wrapper
return wrapper | python | def exposed_method(name=None, private=False, is_coroutine=True, requires_handler_reference=False):
"""
Marks a method as exposed via JSON RPC.
:param name: the name of the exposed method. Must contains only letters, digits, dots and underscores.
If not present or is set explicitly to ``None``, this parameter will default to the name
of the exposed method.
If two methods with the same name are exposed, a ``ValueError`` is raised.
:type name: str
:param private: Flag that specifies if the exposed method is private.
:type private: bool
:param is_coroutine: Flag that specifies if the method is a Tornado coroutine. If True, it will be wrapped
with the :py:func:`tornado.gen.coroutine` decorator.
:type is_coroutine: bool
:param requires_handler_reference: If ``True``, the handler method will receive as the first
parameter a ``handler`` argument with the Tornado
request handler for the current request. This request handler
can be further used to extract various information from the
request, such as headers, cookies, etc.
:type requires_handler_reference: bool
.. versionadded:: 0.9.0
"""
def wrapper(func):
# validation
if name:
method_name = name
else:
method_name = func.__name__
if not METHOD_NAME_REGEX.match(method_name):
raise ValueError("Invalid method name: '{}'".format(method_name))
@functools.wraps(func)
def real_wrapper(*args, **kwargs):
return func(*args, **kwargs)
# set appropriate flags
if private:
setattr(real_wrapper, "_exposed_private", True)
else:
setattr(real_wrapper, "_exposed_public", True)
if is_coroutine:
real_wrapper.__gemstone_is_coroutine = True
real_wrapper = tornado.gen.coroutine(real_wrapper)
setattr(real_wrapper, "_is_coroutine", True)
if requires_handler_reference:
setattr(real_wrapper, "_req_h_ref", True)
setattr(real_wrapper, "_exposed_name", method_name)
return real_wrapper
return wrapper | [
"def",
"exposed_method",
"(",
"name",
"=",
"None",
",",
"private",
"=",
"False",
",",
"is_coroutine",
"=",
"True",
",",
"requires_handler_reference",
"=",
"False",
")",
":",
"def",
"wrapper",
"(",
"func",
")",
":",
"# validation",
"if",
"name",
":",
"metho... | Marks a method as exposed via JSON RPC.
:param name: the name of the exposed method. Must contains only letters, digits, dots and underscores.
If not present or is set explicitly to ``None``, this parameter will default to the name
of the exposed method.
If two methods with the same name are exposed, a ``ValueError`` is raised.
:type name: str
:param private: Flag that specifies if the exposed method is private.
:type private: bool
:param is_coroutine: Flag that specifies if the method is a Tornado coroutine. If True, it will be wrapped
with the :py:func:`tornado.gen.coroutine` decorator.
:type is_coroutine: bool
:param requires_handler_reference: If ``True``, the handler method will receive as the first
parameter a ``handler`` argument with the Tornado
request handler for the current request. This request handler
can be further used to extract various information from the
request, such as headers, cookies, etc.
:type requires_handler_reference: bool
.. versionadded:: 0.9.0 | [
"Marks",
"a",
"method",
"as",
"exposed",
"via",
"JSON",
"RPC",
"."
] | train | https://github.com/vladcalin/gemstone/blob/325a49d17621b9d45ffd2b5eca6f0de284de8ba4/gemstone/core/decorators.py#L35-L94 |
xav-b/pyconsul | pyconsul/iron.py | Metrics.available | def available(self):
''' Check if a related database exists '''
return self.db_name in map(
lambda x: x['name'], self._db.get_database_list()
) | python | def available(self):
''' Check if a related database exists '''
return self.db_name in map(
lambda x: x['name'], self._db.get_database_list()
) | [
"def",
"available",
"(",
"self",
")",
":",
"return",
"self",
".",
"db_name",
"in",
"map",
"(",
"lambda",
"x",
":",
"x",
"[",
"'name'",
"]",
",",
"self",
".",
"_db",
".",
"get_database_list",
"(",
")",
")"
] | Check if a related database exists | [
"Check",
"if",
"a",
"related",
"database",
"exists"
] | train | https://github.com/xav-b/pyconsul/blob/06ce3b921d01010c19643424486bea4b22196076/pyconsul/iron.py#L36-L40 |
murphy214/berrl | build/lib/berrl/pipegeohash.py | make_geohash_tables | def make_geohash_tables(table,listofprecisions,**kwargs):
'''
sort_by - field to sort by for each group
return_squares - boolean arg if true returns a list of squares instead of writing out to table
'''
return_squares = False
sort_by = 'COUNT'
# logic for accepting kwarg inputs
for key,value in kwargs.iteritems():
if key == 'sort_by':
sort_by = value
if key == 'return_squares':
return_squares = value
# getting header
header = df2list(table)[0]
# getting columns
columns = header[10:]
# getting original table
originaltable = table
if not sort_by == 'COUNT':
originaltable = originaltable.sort([sort_by],ascending=[0])
listofprecisions = sorted(listofprecisions,reverse=True)
# making total table to hold a list of dfs
if return_squares == True and listofprecisions[-1] == 8:
total_list = [table]
elif return_squares == True:
total_list = []
for row in listofprecisions:
precision = int(row)
table = originaltable
table['GEOHASH'] = table.GEOHASH.str[:precision]
table = table[['GEOHASH','COUNT']+columns].groupby(['GEOHASH'],sort=True).sum()
table = table.sort([sort_by],ascending=[0])
table = table.reset_index()
newsquares = [header]
# iterating through each square here
for row in df2list(table)[1:]:
# getting points
points = get_points_geohash(row[0])
# making new row
newrow = [row[0]] + points + row[1:]
# appending to newsquares
newsquares.append(newrow)
# taking newsquares to dataframe
table = list2df(newsquares)
if return_squares == True:
total_list.append(table)
else:
table.to_csv('squares' + str(precision) + '.csv',index=False)
if return_squares == True:
return total_list
else:
print 'Wrote output squares tables to csv files.' | python | def make_geohash_tables(table,listofprecisions,**kwargs):
'''
sort_by - field to sort by for each group
return_squares - boolean arg if true returns a list of squares instead of writing out to table
'''
return_squares = False
sort_by = 'COUNT'
# logic for accepting kwarg inputs
for key,value in kwargs.iteritems():
if key == 'sort_by':
sort_by = value
if key == 'return_squares':
return_squares = value
# getting header
header = df2list(table)[0]
# getting columns
columns = header[10:]
# getting original table
originaltable = table
if not sort_by == 'COUNT':
originaltable = originaltable.sort([sort_by],ascending=[0])
listofprecisions = sorted(listofprecisions,reverse=True)
# making total table to hold a list of dfs
if return_squares == True and listofprecisions[-1] == 8:
total_list = [table]
elif return_squares == True:
total_list = []
for row in listofprecisions:
precision = int(row)
table = originaltable
table['GEOHASH'] = table.GEOHASH.str[:precision]
table = table[['GEOHASH','COUNT']+columns].groupby(['GEOHASH'],sort=True).sum()
table = table.sort([sort_by],ascending=[0])
table = table.reset_index()
newsquares = [header]
# iterating through each square here
for row in df2list(table)[1:]:
# getting points
points = get_points_geohash(row[0])
# making new row
newrow = [row[0]] + points + row[1:]
# appending to newsquares
newsquares.append(newrow)
# taking newsquares to dataframe
table = list2df(newsquares)
if return_squares == True:
total_list.append(table)
else:
table.to_csv('squares' + str(precision) + '.csv',index=False)
if return_squares == True:
return total_list
else:
print 'Wrote output squares tables to csv files.' | [
"def",
"make_geohash_tables",
"(",
"table",
",",
"listofprecisions",
",",
"*",
"*",
"kwargs",
")",
":",
"return_squares",
"=",
"False",
"sort_by",
"=",
"'COUNT'",
"# logic for accepting kwarg inputs",
"for",
"key",
",",
"value",
"in",
"kwargs",
".",
"iteritems",
... | sort_by - field to sort by for each group
return_squares - boolean arg if true returns a list of squares instead of writing out to table | [
"sort_by",
"-",
"field",
"to",
"sort",
"by",
"for",
"each",
"group",
"return_squares",
"-",
"boolean",
"arg",
"if",
"true",
"returns",
"a",
"list",
"of",
"squares",
"instead",
"of",
"writing",
"out",
"to",
"table"
] | train | https://github.com/murphy214/berrl/blob/ce4d060cc7db74c32facc538fa1d7030f1a27467/build/lib/berrl/pipegeohash.py#L265-L331 |
svetlyak40wt/python-processor | setup.py | expand_includes | def expand_includes(text, path='.'):
"""Recursively expands includes in given text."""
def read_and_expand(match):
filename = match.group('filename')
filename = join(path, filename)
text = read(filename)
return expand_includes(
text, path=join(path, dirname(filename)))
return re.sub(r'^\.\. include:: (?P<filename>.*)$',
read_and_expand,
text,
flags=re.MULTILINE) | python | def expand_includes(text, path='.'):
"""Recursively expands includes in given text."""
def read_and_expand(match):
filename = match.group('filename')
filename = join(path, filename)
text = read(filename)
return expand_includes(
text, path=join(path, dirname(filename)))
return re.sub(r'^\.\. include:: (?P<filename>.*)$',
read_and_expand,
text,
flags=re.MULTILINE) | [
"def",
"expand_includes",
"(",
"text",
",",
"path",
"=",
"'.'",
")",
":",
"def",
"read_and_expand",
"(",
"match",
")",
":",
"filename",
"=",
"match",
".",
"group",
"(",
"'filename'",
")",
"filename",
"=",
"join",
"(",
"path",
",",
"filename",
")",
"tex... | Recursively expands includes in given text. | [
"Recursively",
"expands",
"includes",
"in",
"given",
"text",
"."
] | train | https://github.com/svetlyak40wt/python-processor/blob/9126a021d603030899897803ab9973250e5b16f6/setup.py#L25-L37 |
KeplerGO/K2fov | K2fov/K2onSilicon.py | angSepVincenty | def angSepVincenty(ra1, dec1, ra2, dec2):
"""
Vincenty formula for distances on a sphere
"""
ra1_rad = np.radians(ra1)
dec1_rad = np.radians(dec1)
ra2_rad = np.radians(ra2)
dec2_rad = np.radians(dec2)
sin_dec1, cos_dec1 = np.sin(dec1_rad), np.cos(dec1_rad)
sin_dec2, cos_dec2 = np.sin(dec2_rad), np.cos(dec2_rad)
delta_ra = ra2_rad - ra1_rad
cos_delta_ra, sin_delta_ra = np.cos(delta_ra), np.sin(delta_ra)
diffpos = np.arctan2(np.sqrt((cos_dec2 * sin_delta_ra) ** 2 +
(cos_dec1 * sin_dec2 -
sin_dec1 * cos_dec2 * cos_delta_ra) ** 2),
sin_dec1 * sin_dec2 + cos_dec1 * cos_dec2 * cos_delta_ra)
return np.degrees(diffpos) | python | def angSepVincenty(ra1, dec1, ra2, dec2):
"""
Vincenty formula for distances on a sphere
"""
ra1_rad = np.radians(ra1)
dec1_rad = np.radians(dec1)
ra2_rad = np.radians(ra2)
dec2_rad = np.radians(dec2)
sin_dec1, cos_dec1 = np.sin(dec1_rad), np.cos(dec1_rad)
sin_dec2, cos_dec2 = np.sin(dec2_rad), np.cos(dec2_rad)
delta_ra = ra2_rad - ra1_rad
cos_delta_ra, sin_delta_ra = np.cos(delta_ra), np.sin(delta_ra)
diffpos = np.arctan2(np.sqrt((cos_dec2 * sin_delta_ra) ** 2 +
(cos_dec1 * sin_dec2 -
sin_dec1 * cos_dec2 * cos_delta_ra) ** 2),
sin_dec1 * sin_dec2 + cos_dec1 * cos_dec2 * cos_delta_ra)
return np.degrees(diffpos) | [
"def",
"angSepVincenty",
"(",
"ra1",
",",
"dec1",
",",
"ra2",
",",
"dec2",
")",
":",
"ra1_rad",
"=",
"np",
".",
"radians",
"(",
"ra1",
")",
"dec1_rad",
"=",
"np",
".",
"radians",
"(",
"dec1",
")",
"ra2_rad",
"=",
"np",
".",
"radians",
"(",
"ra2",
... | Vincenty formula for distances on a sphere | [
"Vincenty",
"formula",
"for",
"distances",
"on",
"a",
"sphere"
] | train | https://github.com/KeplerGO/K2fov/blob/fb122b35687340e0357cba9e0dd47b3be0760693/K2fov/K2onSilicon.py#L41-L60 |
KeplerGO/K2fov | K2fov/K2onSilicon.py | parse_file | def parse_file(infile, exit_on_error=True):
"""Parse a comma-separated file with columns "ra,dec,magnitude".
"""
try:
a, b, mag = np.atleast_2d(
np.genfromtxt(
infile,
usecols=[0, 1, 2],
delimiter=','
)
).T
except IOError as e:
if exit_on_error:
logger.error("There seems to be a problem with the input file, "
"the format should be: RA_degrees (J2000), Dec_degrees (J2000), "
"Magnitude. There should be no header, columns should be "
"separated by a comma")
sys.exit(1)
else:
raise e
return a, b, mag | python | def parse_file(infile, exit_on_error=True):
"""Parse a comma-separated file with columns "ra,dec,magnitude".
"""
try:
a, b, mag = np.atleast_2d(
np.genfromtxt(
infile,
usecols=[0, 1, 2],
delimiter=','
)
).T
except IOError as e:
if exit_on_error:
logger.error("There seems to be a problem with the input file, "
"the format should be: RA_degrees (J2000), Dec_degrees (J2000), "
"Magnitude. There should be no header, columns should be "
"separated by a comma")
sys.exit(1)
else:
raise e
return a, b, mag | [
"def",
"parse_file",
"(",
"infile",
",",
"exit_on_error",
"=",
"True",
")",
":",
"try",
":",
"a",
",",
"b",
",",
"mag",
"=",
"np",
".",
"atleast_2d",
"(",
"np",
".",
"genfromtxt",
"(",
"infile",
",",
"usecols",
"=",
"[",
"0",
",",
"1",
",",
"2",
... | Parse a comma-separated file with columns "ra,dec,magnitude". | [
"Parse",
"a",
"comma",
"-",
"separated",
"file",
"with",
"columns",
"ra",
"dec",
"magnitude",
"."
] | train | https://github.com/KeplerGO/K2fov/blob/fb122b35687340e0357cba9e0dd47b3be0760693/K2fov/K2onSilicon.py#L63-L83 |
KeplerGO/K2fov | K2fov/K2onSilicon.py | onSiliconCheck | def onSiliconCheck(ra_deg, dec_deg, FovObj, padding_pix=DEFAULT_PADDING):
"""Check a single position."""
dist = angSepVincenty(FovObj.ra0_deg, FovObj.dec0_deg, ra_deg, dec_deg)
if dist >= 90.:
return False
# padding_pix=3 means that objects less than 3 pixels off the edge of
# a channel are counted inside, to account for inaccuracies in K2fov.
return FovObj.isOnSilicon(ra_deg, dec_deg, padding_pix=padding_pix) | python | def onSiliconCheck(ra_deg, dec_deg, FovObj, padding_pix=DEFAULT_PADDING):
"""Check a single position."""
dist = angSepVincenty(FovObj.ra0_deg, FovObj.dec0_deg, ra_deg, dec_deg)
if dist >= 90.:
return False
# padding_pix=3 means that objects less than 3 pixels off the edge of
# a channel are counted inside, to account for inaccuracies in K2fov.
return FovObj.isOnSilicon(ra_deg, dec_deg, padding_pix=padding_pix) | [
"def",
"onSiliconCheck",
"(",
"ra_deg",
",",
"dec_deg",
",",
"FovObj",
",",
"padding_pix",
"=",
"DEFAULT_PADDING",
")",
":",
"dist",
"=",
"angSepVincenty",
"(",
"FovObj",
".",
"ra0_deg",
",",
"FovObj",
".",
"dec0_deg",
",",
"ra_deg",
",",
"dec_deg",
")",
"... | Check a single position. | [
"Check",
"a",
"single",
"position",
"."
] | train | https://github.com/KeplerGO/K2fov/blob/fb122b35687340e0357cba9e0dd47b3be0760693/K2fov/K2onSilicon.py#L86-L93 |
KeplerGO/K2fov | K2fov/K2onSilicon.py | onSiliconCheckList | def onSiliconCheckList(ra_deg, dec_deg, FovObj, padding_pix=DEFAULT_PADDING):
"""Check a list of positions."""
dist = angSepVincenty(FovObj.ra0_deg, FovObj.dec0_deg, ra_deg, dec_deg)
mask = (dist < 90.)
out = np.zeros(len(dist), dtype=bool)
out[mask] = FovObj.isOnSiliconList(ra_deg[mask], dec_deg[mask], padding_pix=padding_pix)
return out | python | def onSiliconCheckList(ra_deg, dec_deg, FovObj, padding_pix=DEFAULT_PADDING):
"""Check a list of positions."""
dist = angSepVincenty(FovObj.ra0_deg, FovObj.dec0_deg, ra_deg, dec_deg)
mask = (dist < 90.)
out = np.zeros(len(dist), dtype=bool)
out[mask] = FovObj.isOnSiliconList(ra_deg[mask], dec_deg[mask], padding_pix=padding_pix)
return out | [
"def",
"onSiliconCheckList",
"(",
"ra_deg",
",",
"dec_deg",
",",
"FovObj",
",",
"padding_pix",
"=",
"DEFAULT_PADDING",
")",
":",
"dist",
"=",
"angSepVincenty",
"(",
"FovObj",
".",
"ra0_deg",
",",
"FovObj",
".",
"dec0_deg",
",",
"ra_deg",
",",
"dec_deg",
")",... | Check a list of positions. | [
"Check",
"a",
"list",
"of",
"positions",
"."
] | train | https://github.com/KeplerGO/K2fov/blob/fb122b35687340e0357cba9e0dd47b3be0760693/K2fov/K2onSilicon.py#L96-L102 |
KeplerGO/K2fov | K2fov/K2onSilicon.py | K2onSilicon | def K2onSilicon(infile, fieldnum, do_nearSiliconCheck=False):
"""Checks whether targets are on silicon during a given campaign.
This function will write a csv table called targets_siliconFlag.csv,
which details the silicon status for each target listed in `infile`
(0 = not on silicon, 2 = on silion).
Parameters
----------
infile : str
Path to a csv table with columns ra_deg,dec_deg,magnitude (no header).
fieldnum : int
K2 Campaign number.
do_nearSiliconCheck : bool
If `True`, targets near (but not on) silicon are flagged with a "1".
"""
ra_sources_deg, dec_sources_deg, mag = parse_file(infile)
n_sources = np.shape(ra_sources_deg)[0]
if n_sources > 500:
logger.warning("Warning: there are {0} sources in your target list, "
"this could take some time".format(n_sources))
k = fields.getKeplerFov(fieldnum)
raDec = k.getCoordsOfChannelCorners()
onSilicon = list(
map(
onSiliconCheck,
ra_sources_deg,
dec_sources_deg,
np.repeat(k, len(ra_sources_deg))
)
)
onSilicon = np.array(onSilicon, dtype=bool)
if do_nearSiliconCheck:
nearSilicon = list(
map(
nearSiliconCheck,
ra_sources_deg,
dec_sources_deg,
np.repeat(k, len(ra_sources_deg))
)
)
nearSilicon = np.array(nearSilicon, dtype=bool)
if got_mpl:
almost_black = '#262626'
light_grey = np.array([float(248)/float(255)]*3)
ph = proj.PlateCaree()
k.plotPointing(ph, showOuts=False)
targets = ph.skyToPix(ra_sources_deg, dec_sources_deg)
targets = np.array(targets)
fig = pl.gcf()
ax = fig.gca()
ax = fig.add_subplot(111)
ax.scatter(*targets, color='#fc8d62', s=7, label='not on silicon')
ax.scatter(targets[0][onSilicon], targets[1][onSilicon],
color='#66c2a5', s=8, label='on silicon')
ax.set_xlabel('R.A. [degrees]', fontsize=16)
ax.set_ylabel('Declination [degrees]', fontsize=16)
ax.invert_xaxis()
ax.minorticks_on()
legend = ax.legend(loc=0, frameon=True, scatterpoints=1)
rect = legend.get_frame()
rect.set_alpha(0.3)
rect.set_facecolor(light_grey)
rect.set_linewidth(0.0)
texts = legend.texts
for t in texts:
t.set_color(almost_black)
fig.savefig('targets_fov.png', dpi=300)
pl.close('all')
# prints zero if target is not on silicon
siliconFlag = np.zeros_like(ra_sources_deg)
# print a 1 if target is near but not on silicon
if do_nearSiliconCheck:
siliconFlag = np.where(nearSilicon, 1, siliconFlag)
# prints a 2 if target is on silicon
siliconFlag = np.where(onSilicon, 2, siliconFlag)
outarr = np.array([ra_sources_deg, dec_sources_deg, mag, siliconFlag])
np.savetxt('targets_siliconFlag.csv', outarr.T, delimiter=', ',
fmt=['%10.10f', '%10.10f', '%10.2f', '%i'])
if got_mpl:
print('I made two files: targets_siliconFlag.csv and targets_fov.png')
else:
print('I made one file: targets_siliconFlag.csv') | python | def K2onSilicon(infile, fieldnum, do_nearSiliconCheck=False):
"""Checks whether targets are on silicon during a given campaign.
This function will write a csv table called targets_siliconFlag.csv,
which details the silicon status for each target listed in `infile`
(0 = not on silicon, 2 = on silion).
Parameters
----------
infile : str
Path to a csv table with columns ra_deg,dec_deg,magnitude (no header).
fieldnum : int
K2 Campaign number.
do_nearSiliconCheck : bool
If `True`, targets near (but not on) silicon are flagged with a "1".
"""
ra_sources_deg, dec_sources_deg, mag = parse_file(infile)
n_sources = np.shape(ra_sources_deg)[0]
if n_sources > 500:
logger.warning("Warning: there are {0} sources in your target list, "
"this could take some time".format(n_sources))
k = fields.getKeplerFov(fieldnum)
raDec = k.getCoordsOfChannelCorners()
onSilicon = list(
map(
onSiliconCheck,
ra_sources_deg,
dec_sources_deg,
np.repeat(k, len(ra_sources_deg))
)
)
onSilicon = np.array(onSilicon, dtype=bool)
if do_nearSiliconCheck:
nearSilicon = list(
map(
nearSiliconCheck,
ra_sources_deg,
dec_sources_deg,
np.repeat(k, len(ra_sources_deg))
)
)
nearSilicon = np.array(nearSilicon, dtype=bool)
if got_mpl:
almost_black = '#262626'
light_grey = np.array([float(248)/float(255)]*3)
ph = proj.PlateCaree()
k.plotPointing(ph, showOuts=False)
targets = ph.skyToPix(ra_sources_deg, dec_sources_deg)
targets = np.array(targets)
fig = pl.gcf()
ax = fig.gca()
ax = fig.add_subplot(111)
ax.scatter(*targets, color='#fc8d62', s=7, label='not on silicon')
ax.scatter(targets[0][onSilicon], targets[1][onSilicon],
color='#66c2a5', s=8, label='on silicon')
ax.set_xlabel('R.A. [degrees]', fontsize=16)
ax.set_ylabel('Declination [degrees]', fontsize=16)
ax.invert_xaxis()
ax.minorticks_on()
legend = ax.legend(loc=0, frameon=True, scatterpoints=1)
rect = legend.get_frame()
rect.set_alpha(0.3)
rect.set_facecolor(light_grey)
rect.set_linewidth(0.0)
texts = legend.texts
for t in texts:
t.set_color(almost_black)
fig.savefig('targets_fov.png', dpi=300)
pl.close('all')
# prints zero if target is not on silicon
siliconFlag = np.zeros_like(ra_sources_deg)
# print a 1 if target is near but not on silicon
if do_nearSiliconCheck:
siliconFlag = np.where(nearSilicon, 1, siliconFlag)
# prints a 2 if target is on silicon
siliconFlag = np.where(onSilicon, 2, siliconFlag)
outarr = np.array([ra_sources_deg, dec_sources_deg, mag, siliconFlag])
np.savetxt('targets_siliconFlag.csv', outarr.T, delimiter=', ',
fmt=['%10.10f', '%10.10f', '%10.2f', '%i'])
if got_mpl:
print('I made two files: targets_siliconFlag.csv and targets_fov.png')
else:
print('I made one file: targets_siliconFlag.csv') | [
"def",
"K2onSilicon",
"(",
"infile",
",",
"fieldnum",
",",
"do_nearSiliconCheck",
"=",
"False",
")",
":",
"ra_sources_deg",
",",
"dec_sources_deg",
",",
"mag",
"=",
"parse_file",
"(",
"infile",
")",
"n_sources",
"=",
"np",
".",
"shape",
"(",
"ra_sources_deg",
... | Checks whether targets are on silicon during a given campaign.
This function will write a csv table called targets_siliconFlag.csv,
which details the silicon status for each target listed in `infile`
(0 = not on silicon, 2 = on silion).
Parameters
----------
infile : str
Path to a csv table with columns ra_deg,dec_deg,magnitude (no header).
fieldnum : int
K2 Campaign number.
do_nearSiliconCheck : bool
If `True`, targets near (but not on) silicon are flagged with a "1". | [
"Checks",
"whether",
"targets",
"are",
"on",
"silicon",
"during",
"a",
"given",
"campaign",
"."
] | train | https://github.com/KeplerGO/K2fov/blob/fb122b35687340e0357cba9e0dd47b3be0760693/K2fov/K2onSilicon.py#L122-L215 |
KeplerGO/K2fov | K2fov/K2onSilicon.py | K2onSilicon_main | def K2onSilicon_main(args=None):
"""Function called when `K2onSilicon` is executed on the command line."""
import argparse
parser = argparse.ArgumentParser(
description="Run K2onSilicon to find which targets in a "
"list call on active silicon for a given K2 campaign.")
parser.add_argument('csv_file', type=str,
help="Name of input csv file with targets, column are "
"Ra_degrees, Dec_degrees, Kepmag")
parser.add_argument('campaign', type=int, help='K2 Campaign number')
args = parser.parse_args(args)
K2onSilicon(args.csv_file, args.campaign) | python | def K2onSilicon_main(args=None):
"""Function called when `K2onSilicon` is executed on the command line."""
import argparse
parser = argparse.ArgumentParser(
description="Run K2onSilicon to find which targets in a "
"list call on active silicon for a given K2 campaign.")
parser.add_argument('csv_file', type=str,
help="Name of input csv file with targets, column are "
"Ra_degrees, Dec_degrees, Kepmag")
parser.add_argument('campaign', type=int, help='K2 Campaign number')
args = parser.parse_args(args)
K2onSilicon(args.csv_file, args.campaign) | [
"def",
"K2onSilicon_main",
"(",
"args",
"=",
"None",
")",
":",
"import",
"argparse",
"parser",
"=",
"argparse",
".",
"ArgumentParser",
"(",
"description",
"=",
"\"Run K2onSilicon to find which targets in a \"",
"\"list call on active silicon for a given K2 campaign.\"",
")",
... | Function called when `K2onSilicon` is executed on the command line. | [
"Function",
"called",
"when",
"K2onSilicon",
"is",
"executed",
"on",
"the",
"command",
"line",
"."
] | train | https://github.com/KeplerGO/K2fov/blob/fb122b35687340e0357cba9e0dd47b3be0760693/K2fov/K2onSilicon.py#L218-L229 |
mardix/ses-mailer | ses_mailer.py | Template._get_template | def _get_template(self, template_name):
"""
Retrieve the cached version of the template
"""
if template_name not in self.chached_templates:
self.chached_templates[template_name] = self.env.get_template(template_name)
return self.chached_templates[template_name] | python | def _get_template(self, template_name):
"""
Retrieve the cached version of the template
"""
if template_name not in self.chached_templates:
self.chached_templates[template_name] = self.env.get_template(template_name)
return self.chached_templates[template_name] | [
"def",
"_get_template",
"(",
"self",
",",
"template_name",
")",
":",
"if",
"template_name",
"not",
"in",
"self",
".",
"chached_templates",
":",
"self",
".",
"chached_templates",
"[",
"template_name",
"]",
"=",
"self",
".",
"env",
".",
"get_template",
"(",
"t... | Retrieve the cached version of the template | [
"Retrieve",
"the",
"cached",
"version",
"of",
"the",
"template"
] | train | https://github.com/mardix/ses-mailer/blob/14be4fbdf7182bce8a22235df56c524235b84c89/ses_mailer.py#L57-L63 |
mardix/ses-mailer | ses_mailer.py | Template.render_blocks | def render_blocks(self, template_name, **context):
"""
To render all the blocks
:param template_name: The template file name
:param context: **kwargs context to render
:retuns dict: of all the blocks with block_name as key
"""
blocks = {}
template = self._get_template(template_name)
for block in template.blocks:
blocks[block] = self._render_context(template,
template.blocks[block],
**context)
return blocks | python | def render_blocks(self, template_name, **context):
"""
To render all the blocks
:param template_name: The template file name
:param context: **kwargs context to render
:retuns dict: of all the blocks with block_name as key
"""
blocks = {}
template = self._get_template(template_name)
for block in template.blocks:
blocks[block] = self._render_context(template,
template.blocks[block],
**context)
return blocks | [
"def",
"render_blocks",
"(",
"self",
",",
"template_name",
",",
"*",
"*",
"context",
")",
":",
"blocks",
"=",
"{",
"}",
"template",
"=",
"self",
".",
"_get_template",
"(",
"template_name",
")",
"for",
"block",
"in",
"template",
".",
"blocks",
":",
"block... | To render all the blocks
:param template_name: The template file name
:param context: **kwargs context to render
:retuns dict: of all the blocks with block_name as key | [
"To",
"render",
"all",
"the",
"blocks",
":",
"param",
"template_name",
":",
"The",
"template",
"file",
"name",
":",
"param",
"context",
":",
"**",
"kwargs",
"context",
"to",
"render",
":",
"retuns",
"dict",
":",
"of",
"all",
"the",
"blocks",
"with",
"blo... | train | https://github.com/mardix/ses-mailer/blob/14be4fbdf7182bce8a22235df56c524235b84c89/ses_mailer.py#L66-L79 |
mardix/ses-mailer | ses_mailer.py | Template.render | def render(self, template_name, block, **context):
"""
TO render a block in the template
:param template_name: the template file name
:param block: the name of the block within {% block $block_name %}
:param context: **kwargs context to render
:returns string: of rendered content
"""
template = self._get_template(template_name)
return self._render_context(template,
template.blocks[block],
**context) | python | def render(self, template_name, block, **context):
"""
TO render a block in the template
:param template_name: the template file name
:param block: the name of the block within {% block $block_name %}
:param context: **kwargs context to render
:returns string: of rendered content
"""
template = self._get_template(template_name)
return self._render_context(template,
template.blocks[block],
**context) | [
"def",
"render",
"(",
"self",
",",
"template_name",
",",
"block",
",",
"*",
"*",
"context",
")",
":",
"template",
"=",
"self",
".",
"_get_template",
"(",
"template_name",
")",
"return",
"self",
".",
"_render_context",
"(",
"template",
",",
"template",
".",... | TO render a block in the template
:param template_name: the template file name
:param block: the name of the block within {% block $block_name %}
:param context: **kwargs context to render
:returns string: of rendered content | [
"TO",
"render",
"a",
"block",
"in",
"the",
"template",
":",
"param",
"template_name",
":",
"the",
"template",
"file",
"name",
":",
"param",
"block",
":",
"the",
"name",
"of",
"the",
"block",
"within",
"{",
"%",
"block",
"$block_name",
"%",
"}",
":",
"p... | train | https://github.com/mardix/ses-mailer/blob/14be4fbdf7182bce8a22235df56c524235b84c89/ses_mailer.py#L81-L92 |
mardix/ses-mailer | ses_mailer.py | Template._render_context | def _render_context(self, template, block, **context):
"""
Render a block to a string with its context
"""
return u''.join(block(template.new_context(context))) | python | def _render_context(self, template, block, **context):
"""
Render a block to a string with its context
"""
return u''.join(block(template.new_context(context))) | [
"def",
"_render_context",
"(",
"self",
",",
"template",
",",
"block",
",",
"*",
"*",
"context",
")",
":",
"return",
"u''",
".",
"join",
"(",
"block",
"(",
"template",
".",
"new_context",
"(",
"context",
")",
")",
")"
] | Render a block to a string with its context | [
"Render",
"a",
"block",
"to",
"a",
"string",
"with",
"its",
"context"
] | train | https://github.com/mardix/ses-mailer/blob/14be4fbdf7182bce8a22235df56c524235b84c89/ses_mailer.py#L94-L98 |
mardix/ses-mailer | ses_mailer.py | Mail.init_app | def init_app(self, app):
"""
For Flask using the app config
"""
self.__init__(aws_access_key_id=app.config.get("SES_AWS_ACCESS_KEY"),
aws_secret_access_key=app.config.get("SES_AWS_SECRET_KEY"),
region=app.config.get("SES_REGION", "us-east-1"),
sender=app.config.get("SES_SENDER", None),
reply_to=app.config.get("SES_REPLY_TO", None),
template=app.config.get("SES_TEMPLATE", None),
template_context=app.config.get("SES_TEMPLATE_CONTEXT", {})
) | python | def init_app(self, app):
"""
For Flask using the app config
"""
self.__init__(aws_access_key_id=app.config.get("SES_AWS_ACCESS_KEY"),
aws_secret_access_key=app.config.get("SES_AWS_SECRET_KEY"),
region=app.config.get("SES_REGION", "us-east-1"),
sender=app.config.get("SES_SENDER", None),
reply_to=app.config.get("SES_REPLY_TO", None),
template=app.config.get("SES_TEMPLATE", None),
template_context=app.config.get("SES_TEMPLATE_CONTEXT", {})
) | [
"def",
"init_app",
"(",
"self",
",",
"app",
")",
":",
"self",
".",
"__init__",
"(",
"aws_access_key_id",
"=",
"app",
".",
"config",
".",
"get",
"(",
"\"SES_AWS_ACCESS_KEY\"",
")",
",",
"aws_secret_access_key",
"=",
"app",
".",
"config",
".",
"get",
"(",
... | For Flask using the app config | [
"For",
"Flask",
"using",
"the",
"app",
"config"
] | train | https://github.com/mardix/ses-mailer/blob/14be4fbdf7182bce8a22235df56c524235b84c89/ses_mailer.py#L143-L154 |
mardix/ses-mailer | ses_mailer.py | Mail.send | def send(self, to, subject, body, reply_to=None, **kwargs):
"""
Send email via AWS SES.
:returns string: message id
***
Composes an email message based on input data, and then immediately
queues the message for sending.
:type to: list of strings or string
:param to: The To: field(s) of the message.
:type subject: string
:param subject: The subject of the message: A short summary of the
content, which will appear in the recipient's inbox.
:type body: string
:param body: The message body.
:sender: email address of the sender. String or typle(name, email)
:reply_to: email to reply to
**kwargs:
:type cc_addresses: list of strings or string
:param cc_addresses: The CC: field(s) of the message.
:type bcc_addresses: list of strings or string
:param bcc_addresses: The BCC: field(s) of the message.
:type format: string
:param format: The format of the message's body, must be either "text"
or "html".
:type return_path: string
:param return_path: The email address to which bounce notifications are
to be forwarded. If the message cannot be delivered
to the recipient, then an error message will be
returned from the recipient's ISP; this message
will then be forwarded to the email address
specified by the ReturnPath parameter.
:type text_body: string
:param text_body: The text body to send with this email.
:type html_body: string
:param html_body: The html body to send with this email.
"""
if not self.sender:
raise AttributeError("Sender email 'sender' or 'source' is not provided")
kwargs["to_addresses"] = to
kwargs["subject"] = subject
kwargs["body"] = body
kwargs["source"] = self._get_sender(self.sender)[0]
kwargs["reply_addresses"] = self._get_sender(reply_to or self.reply_to)[2]
response = self.ses.send_email(**kwargs)
return response["SendEmailResponse"]["SendEmailResult"]["MessageId"] | python | def send(self, to, subject, body, reply_to=None, **kwargs):
"""
Send email via AWS SES.
:returns string: message id
***
Composes an email message based on input data, and then immediately
queues the message for sending.
:type to: list of strings or string
:param to: The To: field(s) of the message.
:type subject: string
:param subject: The subject of the message: A short summary of the
content, which will appear in the recipient's inbox.
:type body: string
:param body: The message body.
:sender: email address of the sender. String or typle(name, email)
:reply_to: email to reply to
**kwargs:
:type cc_addresses: list of strings or string
:param cc_addresses: The CC: field(s) of the message.
:type bcc_addresses: list of strings or string
:param bcc_addresses: The BCC: field(s) of the message.
:type format: string
:param format: The format of the message's body, must be either "text"
or "html".
:type return_path: string
:param return_path: The email address to which bounce notifications are
to be forwarded. If the message cannot be delivered
to the recipient, then an error message will be
returned from the recipient's ISP; this message
will then be forwarded to the email address
specified by the ReturnPath parameter.
:type text_body: string
:param text_body: The text body to send with this email.
:type html_body: string
:param html_body: The html body to send with this email.
"""
if not self.sender:
raise AttributeError("Sender email 'sender' or 'source' is not provided")
kwargs["to_addresses"] = to
kwargs["subject"] = subject
kwargs["body"] = body
kwargs["source"] = self._get_sender(self.sender)[0]
kwargs["reply_addresses"] = self._get_sender(reply_to or self.reply_to)[2]
response = self.ses.send_email(**kwargs)
return response["SendEmailResponse"]["SendEmailResult"]["MessageId"] | [
"def",
"send",
"(",
"self",
",",
"to",
",",
"subject",
",",
"body",
",",
"reply_to",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"not",
"self",
".",
"sender",
":",
"raise",
"AttributeError",
"(",
"\"Sender email 'sender' or 'source' is not provided... | Send email via AWS SES.
:returns string: message id
***
Composes an email message based on input data, and then immediately
queues the message for sending.
:type to: list of strings or string
:param to: The To: field(s) of the message.
:type subject: string
:param subject: The subject of the message: A short summary of the
content, which will appear in the recipient's inbox.
:type body: string
:param body: The message body.
:sender: email address of the sender. String or typle(name, email)
:reply_to: email to reply to
**kwargs:
:type cc_addresses: list of strings or string
:param cc_addresses: The CC: field(s) of the message.
:type bcc_addresses: list of strings or string
:param bcc_addresses: The BCC: field(s) of the message.
:type format: string
:param format: The format of the message's body, must be either "text"
or "html".
:type return_path: string
:param return_path: The email address to which bounce notifications are
to be forwarded. If the message cannot be delivered
to the recipient, then an error message will be
returned from the recipient's ISP; this message
will then be forwarded to the email address
specified by the ReturnPath parameter.
:type text_body: string
:param text_body: The text body to send with this email.
:type html_body: string
:param html_body: The html body to send with this email. | [
"Send",
"email",
"via",
"AWS",
"SES",
".",
":",
"returns",
"string",
":",
"message",
"id"
] | train | https://github.com/mardix/ses-mailer/blob/14be4fbdf7182bce8a22235df56c524235b84c89/ses_mailer.py#L157-L217 |
mardix/ses-mailer | ses_mailer.py | Mail.send_template | def send_template(self, template, to, reply_to=None, **context):
"""
Send email from template
"""
mail_data = self.parse_template(template, **context)
subject = mail_data["subject"]
body = mail_data["body"]
del(mail_data["subject"])
del(mail_data["body"])
return self.send(to=to,
subject=subject,
body=body,
reply_to=reply_to,
**mail_data) | python | def send_template(self, template, to, reply_to=None, **context):
"""
Send email from template
"""
mail_data = self.parse_template(template, **context)
subject = mail_data["subject"]
body = mail_data["body"]
del(mail_data["subject"])
del(mail_data["body"])
return self.send(to=to,
subject=subject,
body=body,
reply_to=reply_to,
**mail_data) | [
"def",
"send_template",
"(",
"self",
",",
"template",
",",
"to",
",",
"reply_to",
"=",
"None",
",",
"*",
"*",
"context",
")",
":",
"mail_data",
"=",
"self",
".",
"parse_template",
"(",
"template",
",",
"*",
"*",
"context",
")",
"subject",
"=",
"mail_da... | Send email from template | [
"Send",
"email",
"from",
"template"
] | train | https://github.com/mardix/ses-mailer/blob/14be4fbdf7182bce8a22235df56c524235b84c89/ses_mailer.py#L219-L233 |
mardix/ses-mailer | ses_mailer.py | Mail.parse_template | def parse_template(self, template, **context):
"""
To parse a template and return all the blocks
"""
required_blocks = ["subject", "body"]
optional_blocks = ["text_body", "html_body", "return_path", "format"]
if self.template_context:
context = dict(self.template_context.items() + context.items())
blocks = self.template.render_blocks(template, **context)
for rb in required_blocks:
if rb not in blocks:
raise AttributeError("Template error: block '%s' is missing from '%s'" % (rb, template))
mail_params = {
"subject": blocks["subject"].strip(),
"body": blocks["body"]
}
for ob in optional_blocks:
if ob in blocks:
if ob == "format" and mail_params[ob].lower() not in ["html", "text"]:
continue
mail_params[ob] = blocks[ob]
return mail_params | python | def parse_template(self, template, **context):
"""
To parse a template and return all the blocks
"""
required_blocks = ["subject", "body"]
optional_blocks = ["text_body", "html_body", "return_path", "format"]
if self.template_context:
context = dict(self.template_context.items() + context.items())
blocks = self.template.render_blocks(template, **context)
for rb in required_blocks:
if rb not in blocks:
raise AttributeError("Template error: block '%s' is missing from '%s'" % (rb, template))
mail_params = {
"subject": blocks["subject"].strip(),
"body": blocks["body"]
}
for ob in optional_blocks:
if ob in blocks:
if ob == "format" and mail_params[ob].lower() not in ["html", "text"]:
continue
mail_params[ob] = blocks[ob]
return mail_params | [
"def",
"parse_template",
"(",
"self",
",",
"template",
",",
"*",
"*",
"context",
")",
":",
"required_blocks",
"=",
"[",
"\"subject\"",
",",
"\"body\"",
"]",
"optional_blocks",
"=",
"[",
"\"text_body\"",
",",
"\"html_body\"",
",",
"\"return_path\"",
",",
"\"for... | To parse a template and return all the blocks | [
"To",
"parse",
"a",
"template",
"and",
"return",
"all",
"the",
"blocks"
] | train | https://github.com/mardix/ses-mailer/blob/14be4fbdf7182bce8a22235df56c524235b84c89/ses_mailer.py#L235-L259 |
mardix/ses-mailer | ses_mailer.py | Mail._get_sender | def _get_sender(self, sender):
"""
Return a tuple of 3 elements
0: the email signature "Me <email@me.com>"
1: the name "Me"
2: the email address "email@me.com"
if sender is an email string, all 3 elements will be the email address
"""
if isinstance(sender, tuple):
return "%s <%s>" % sender, sender[0], sender[1]
else:
return sender, sender, sender | python | def _get_sender(self, sender):
"""
Return a tuple of 3 elements
0: the email signature "Me <email@me.com>"
1: the name "Me"
2: the email address "email@me.com"
if sender is an email string, all 3 elements will be the email address
"""
if isinstance(sender, tuple):
return "%s <%s>" % sender, sender[0], sender[1]
else:
return sender, sender, sender | [
"def",
"_get_sender",
"(",
"self",
",",
"sender",
")",
":",
"if",
"isinstance",
"(",
"sender",
",",
"tuple",
")",
":",
"return",
"\"%s <%s>\"",
"%",
"sender",
",",
"sender",
"[",
"0",
"]",
",",
"sender",
"[",
"1",
"]",
"else",
":",
"return",
"sender"... | Return a tuple of 3 elements
0: the email signature "Me <email@me.com>"
1: the name "Me"
2: the email address "email@me.com"
if sender is an email string, all 3 elements will be the email address | [
"Return",
"a",
"tuple",
"of",
"3",
"elements",
"0",
":",
"the",
"email",
"signature",
"Me",
"<email@me",
".",
"com",
">",
"1",
":",
"the",
"name",
"Me",
"2",
":",
"the",
"email",
"address",
"email@me",
".",
"com"
] | train | https://github.com/mardix/ses-mailer/blob/14be4fbdf7182bce8a22235df56c524235b84c89/ses_mailer.py#L262-L274 |
p3trus/slave | slave/driver.py | _typelist | def _typelist(x):
"""Helper function converting all items of x to instances."""
if isinstance(x, collections.Sequence):
return list(map(_to_instance, x))
elif isinstance(x, collections.Iterable):
return x
return None if x is None else [_to_instance(x)] | python | def _typelist(x):
"""Helper function converting all items of x to instances."""
if isinstance(x, collections.Sequence):
return list(map(_to_instance, x))
elif isinstance(x, collections.Iterable):
return x
return None if x is None else [_to_instance(x)] | [
"def",
"_typelist",
"(",
"x",
")",
":",
"if",
"isinstance",
"(",
"x",
",",
"collections",
".",
"Sequence",
")",
":",
"return",
"list",
"(",
"map",
"(",
"_to_instance",
",",
"x",
")",
")",
"elif",
"isinstance",
"(",
"x",
",",
"collections",
".",
"Iter... | Helper function converting all items of x to instances. | [
"Helper",
"function",
"converting",
"all",
"items",
"of",
"x",
"to",
"instances",
"."
] | train | https://github.com/p3trus/slave/blob/bdc74e73bd0f47b74a090c43aa2283c469cde3be/slave/driver.py#L48-L54 |
p3trus/slave | slave/driver.py | Command.write | def write(self, transport, protocol, *data):
"""Generates and sends a command message unit.
:param transport: An object implementing the `.Transport` interface.
It is used by the protocol to send the message.
:param protocol: An object implementing the `.Protocol` interface.
:param data: The program data.
:raises AttributeError: if the command is not writable.
"""
if not self._write:
raise AttributeError('Command is not writeable')
if self.protocol:
protocol = self.protocol
if self._write.data_type:
data = _dump(self._write.data_type, data)
else:
# TODO We silently ignore possible data
data = ()
if isinstance(transport, SimulatedTransport):
self.simulate_write(data)
else:
protocol.write(transport, self._write.header, *data) | python | def write(self, transport, protocol, *data):
"""Generates and sends a command message unit.
:param transport: An object implementing the `.Transport` interface.
It is used by the protocol to send the message.
:param protocol: An object implementing the `.Protocol` interface.
:param data: The program data.
:raises AttributeError: if the command is not writable.
"""
if not self._write:
raise AttributeError('Command is not writeable')
if self.protocol:
protocol = self.protocol
if self._write.data_type:
data = _dump(self._write.data_type, data)
else:
# TODO We silently ignore possible data
data = ()
if isinstance(transport, SimulatedTransport):
self.simulate_write(data)
else:
protocol.write(transport, self._write.header, *data) | [
"def",
"write",
"(",
"self",
",",
"transport",
",",
"protocol",
",",
"*",
"data",
")",
":",
"if",
"not",
"self",
".",
"_write",
":",
"raise",
"AttributeError",
"(",
"'Command is not writeable'",
")",
"if",
"self",
".",
"protocol",
":",
"protocol",
"=",
"... | Generates and sends a command message unit.
:param transport: An object implementing the `.Transport` interface.
It is used by the protocol to send the message.
:param protocol: An object implementing the `.Protocol` interface.
:param data: The program data.
:raises AttributeError: if the command is not writable. | [
"Generates",
"and",
"sends",
"a",
"command",
"message",
"unit",
"."
] | train | https://github.com/p3trus/slave/blob/bdc74e73bd0f47b74a090c43aa2283c469cde3be/slave/driver.py#L131-L154 |
p3trus/slave | slave/driver.py | Command.query | def query(self, transport, protocol, *data):
"""Generates and sends a query message unit.
:param transport: An object implementing the `.Transport` interface.
It is used by the protocol to send the message and receive the
response.
:param protocol: An object implementing the `.Protocol` interface.
:param data: The program data.
:raises AttributeError: if the command is not queryable.
"""
if not self._query:
raise AttributeError('Command is not queryable')
if self.protocol:
protocol = self.protocol
if self._query.data_type:
data = _dump(self._query.data_type, data)
else:
# TODO We silently ignore possible data
data = ()
if isinstance(transport, SimulatedTransport):
response = self.simulate_query(data)
else:
response = protocol.query(transport, self._query.header, *data)
response = _load(self._query.response_type, response)
# Return single value if parsed_data is 1-tuple.
return response[0] if len(response) == 1 else response | python | def query(self, transport, protocol, *data):
"""Generates and sends a query message unit.
:param transport: An object implementing the `.Transport` interface.
It is used by the protocol to send the message and receive the
response.
:param protocol: An object implementing the `.Protocol` interface.
:param data: The program data.
:raises AttributeError: if the command is not queryable.
"""
if not self._query:
raise AttributeError('Command is not queryable')
if self.protocol:
protocol = self.protocol
if self._query.data_type:
data = _dump(self._query.data_type, data)
else:
# TODO We silently ignore possible data
data = ()
if isinstance(transport, SimulatedTransport):
response = self.simulate_query(data)
else:
response = protocol.query(transport, self._query.header, *data)
response = _load(self._query.response_type, response)
# Return single value if parsed_data is 1-tuple.
return response[0] if len(response) == 1 else response | [
"def",
"query",
"(",
"self",
",",
"transport",
",",
"protocol",
",",
"*",
"data",
")",
":",
"if",
"not",
"self",
".",
"_query",
":",
"raise",
"AttributeError",
"(",
"'Command is not queryable'",
")",
"if",
"self",
".",
"protocol",
":",
"protocol",
"=",
"... | Generates and sends a query message unit.
:param transport: An object implementing the `.Transport` interface.
It is used by the protocol to send the message and receive the
response.
:param protocol: An object implementing the `.Protocol` interface.
:param data: The program data.
:raises AttributeError: if the command is not queryable. | [
"Generates",
"and",
"sends",
"a",
"query",
"message",
"unit",
"."
] | train | https://github.com/p3trus/slave/blob/bdc74e73bd0f47b74a090c43aa2283c469cde3be/slave/driver.py#L156-L184 |
p3trus/slave | slave/driver.py | Driver._write | def _write(self, cmd, *datas):
"""Helper function to simplify writing."""
cmd = Command(write=cmd)
cmd.write(self._transport, self._protocol, *datas) | python | def _write(self, cmd, *datas):
"""Helper function to simplify writing."""
cmd = Command(write=cmd)
cmd.write(self._transport, self._protocol, *datas) | [
"def",
"_write",
"(",
"self",
",",
"cmd",
",",
"*",
"datas",
")",
":",
"cmd",
"=",
"Command",
"(",
"write",
"=",
"cmd",
")",
"cmd",
".",
"write",
"(",
"self",
".",
"_transport",
",",
"self",
".",
"_protocol",
",",
"*",
"datas",
")"
] | Helper function to simplify writing. | [
"Helper",
"function",
"to",
"simplify",
"writing",
"."
] | train | https://github.com/p3trus/slave/blob/bdc74e73bd0f47b74a090c43aa2283c469cde3be/slave/driver.py#L237-L240 |
p3trus/slave | slave/driver.py | Driver._query | def _query(self, cmd, *datas):
"""Helper function to allow method queries."""
cmd = Command(query=cmd)
return cmd.query(self._transport, self._protocol, *datas) | python | def _query(self, cmd, *datas):
"""Helper function to allow method queries."""
cmd = Command(query=cmd)
return cmd.query(self._transport, self._protocol, *datas) | [
"def",
"_query",
"(",
"self",
",",
"cmd",
",",
"*",
"datas",
")",
":",
"cmd",
"=",
"Command",
"(",
"query",
"=",
"cmd",
")",
"return",
"cmd",
".",
"query",
"(",
"self",
".",
"_transport",
",",
"self",
".",
"_protocol",
",",
"*",
"datas",
")"
] | Helper function to allow method queries. | [
"Helper",
"function",
"to",
"allow",
"method",
"queries",
"."
] | train | https://github.com/p3trus/slave/blob/bdc74e73bd0f47b74a090c43aa2283c469cde3be/slave/driver.py#L242-L245 |
llazzaro/analyzerdam | analyzerdam/DAMFactory.py | DAMFactory.createDAM | def createDAM(dam_name, config):
''' create DAM '''
if 'yahoo' == dam_name:
from analyzerdam.yahooDAM import YahooDAM
dam=YahooDAM()
elif 'google' == dam_name:
from analyzerdam.google import GoogleDAM
dam=GoogleDAM()
elif 'excel' == dam_name:
from analyzerdam.excelDAM import ExcelDAM
dam=ExcelDAM()
elif 'hbase' == dam_name:
from analyzerdam.hbaseDAM import HBaseDAM
dam=HBaseDAM()
elif 'sql' == dam_name:
from analyzerdam.sqlDAM import SqlDAM
dam=SqlDAM(config)
elif 'cex' == dam_name:
from analyzerdam.cex import CexDAM
dam=CexDAM(config)
else:
raise UfException(Errors.INVALID_DAM_TYPE,
"DAM type is invalid %s" % dam_name)
return dam | python | def createDAM(dam_name, config):
''' create DAM '''
if 'yahoo' == dam_name:
from analyzerdam.yahooDAM import YahooDAM
dam=YahooDAM()
elif 'google' == dam_name:
from analyzerdam.google import GoogleDAM
dam=GoogleDAM()
elif 'excel' == dam_name:
from analyzerdam.excelDAM import ExcelDAM
dam=ExcelDAM()
elif 'hbase' == dam_name:
from analyzerdam.hbaseDAM import HBaseDAM
dam=HBaseDAM()
elif 'sql' == dam_name:
from analyzerdam.sqlDAM import SqlDAM
dam=SqlDAM(config)
elif 'cex' == dam_name:
from analyzerdam.cex import CexDAM
dam=CexDAM(config)
else:
raise UfException(Errors.INVALID_DAM_TYPE,
"DAM type is invalid %s" % dam_name)
return dam | [
"def",
"createDAM",
"(",
"dam_name",
",",
"config",
")",
":",
"if",
"'yahoo'",
"==",
"dam_name",
":",
"from",
"analyzerdam",
".",
"yahooDAM",
"import",
"YahooDAM",
"dam",
"=",
"YahooDAM",
"(",
")",
"elif",
"'google'",
"==",
"dam_name",
":",
"from",
"analyz... | create DAM | [
"create",
"DAM"
] | train | https://github.com/llazzaro/analyzerdam/blob/c5bc7483dae23bd2e14bbf36147b7a43a0067bc0/analyzerdam/DAMFactory.py#L13-L37 |
llazzaro/analyzerdam | analyzerdam/yahooFinance.py | YahooFinance.getAll | def getAll(self, symbol):
"""
Get all available quote data for the given ticker symbol.
Returns a dictionary.
"""
values = self.__request(symbol, 'l1c1va2xj1b4j4dyekjm3m4rr5p5p6s7').split(',')
data = {}
data['price'] = values[0]
data['change'] = values[1]
data['volume'] = values[2]
data['avg_daily_volume'] = values[3]
data['stock_exchange'] = values[4]
data['market_cap'] = values[5]
data['book_value'] = values[6]
data['ebitda'] = values[7]
data['dividend_per_share'] = values[8]
data['dividend_yield'] = values[9]
data['earnings_per_share'] = values[10]
data['52_week_high'] = values[11]
data['52_week_low'] = values[12]
data['50day_moving_avg'] = values[13]
data['200day_moving_avg'] = values[14]
data['price_earnings_ratio'] = values[15]
data['price_earnings_growth_ratio'] = values[16]
data['price_sales_ratio'] = values[17]
data['price_book_ratio'] = values[18]
data['short_ratio'] = values[19]
return data | python | def getAll(self, symbol):
"""
Get all available quote data for the given ticker symbol.
Returns a dictionary.
"""
values = self.__request(symbol, 'l1c1va2xj1b4j4dyekjm3m4rr5p5p6s7').split(',')
data = {}
data['price'] = values[0]
data['change'] = values[1]
data['volume'] = values[2]
data['avg_daily_volume'] = values[3]
data['stock_exchange'] = values[4]
data['market_cap'] = values[5]
data['book_value'] = values[6]
data['ebitda'] = values[7]
data['dividend_per_share'] = values[8]
data['dividend_yield'] = values[9]
data['earnings_per_share'] = values[10]
data['52_week_high'] = values[11]
data['52_week_low'] = values[12]
data['50day_moving_avg'] = values[13]
data['200day_moving_avg'] = values[14]
data['price_earnings_ratio'] = values[15]
data['price_earnings_growth_ratio'] = values[16]
data['price_sales_ratio'] = values[17]
data['price_book_ratio'] = values[18]
data['short_ratio'] = values[19]
return data | [
"def",
"getAll",
"(",
"self",
",",
"symbol",
")",
":",
"values",
"=",
"self",
".",
"__request",
"(",
"symbol",
",",
"'l1c1va2xj1b4j4dyekjm3m4rr5p5p6s7'",
")",
".",
"split",
"(",
"','",
")",
"data",
"=",
"{",
"}",
"data",
"[",
"'price'",
"]",
"=",
"valu... | Get all available quote data for the given ticker symbol.
Returns a dictionary. | [
"Get",
"all",
"available",
"quote",
"data",
"for",
"the",
"given",
"ticker",
"symbol",
".",
"Returns",
"a",
"dictionary",
"."
] | train | https://github.com/llazzaro/analyzerdam/blob/c5bc7483dae23bd2e14bbf36147b7a43a0067bc0/analyzerdam/yahooFinance.py#L30-L57 |
llazzaro/analyzerdam | analyzerdam/yahooFinance.py | YahooFinance.getQuotes | def getQuotes(self, symbol, start, end):
"""
Get historical prices for the given ticker symbol.
Date format is 'YYYY-MM-DD'
Returns a nested list.
"""
try:
start = str(start).replace('-', '')
end = str(end).replace('-', '')
url = 'http://ichart.yahoo.com/table.csv?s=%s&' % symbol + \
'd=%s&' % str(int(end[4:6]) - 1) + \
'e=%s&' % str(int(end[6:8])) + \
'f=%s&' % str(int(end[0:4])) + \
'g=d&' + \
'a=%s&' % str(int(start[4:6]) - 1) + \
'b=%s&' % str(int(start[6:8])) + \
'c=%s&' % str(int(start[0:4])) + \
'ignore=.csv'
days = urllib.urlopen(url).readlines()
values = [day[:-2].split(',') for day in days]
# sample values:[['Date', 'Open', 'High', 'Low', 'Close', 'Volume', 'Adj Clos'], \
# ['2009-12-31', '112.77', '112.80', '111.39', '111.44', '90637900', '109.7']...]
data = []
for value in values[1:]:
data.append(Quote(value[0], value[1], value[2], value[3], value[4], value[5], value[6]))
dateValues = sorted(data, key = lambda q: q.time)
return dateValues
except IOError:
raise UfException(Errors.NETWORK_ERROR, "Can't connect to Yahoo server")
except BaseException:
raise UfException(Errors.UNKNOWN_ERROR, "Unknown Error in YahooFinance.getHistoricalPrices %s" % traceback.format_exc()) | python | def getQuotes(self, symbol, start, end):
"""
Get historical prices for the given ticker symbol.
Date format is 'YYYY-MM-DD'
Returns a nested list.
"""
try:
start = str(start).replace('-', '')
end = str(end).replace('-', '')
url = 'http://ichart.yahoo.com/table.csv?s=%s&' % symbol + \
'd=%s&' % str(int(end[4:6]) - 1) + \
'e=%s&' % str(int(end[6:8])) + \
'f=%s&' % str(int(end[0:4])) + \
'g=d&' + \
'a=%s&' % str(int(start[4:6]) - 1) + \
'b=%s&' % str(int(start[6:8])) + \
'c=%s&' % str(int(start[0:4])) + \
'ignore=.csv'
days = urllib.urlopen(url).readlines()
values = [day[:-2].split(',') for day in days]
# sample values:[['Date', 'Open', 'High', 'Low', 'Close', 'Volume', 'Adj Clos'], \
# ['2009-12-31', '112.77', '112.80', '111.39', '111.44', '90637900', '109.7']...]
data = []
for value in values[1:]:
data.append(Quote(value[0], value[1], value[2], value[3], value[4], value[5], value[6]))
dateValues = sorted(data, key = lambda q: q.time)
return dateValues
except IOError:
raise UfException(Errors.NETWORK_ERROR, "Can't connect to Yahoo server")
except BaseException:
raise UfException(Errors.UNKNOWN_ERROR, "Unknown Error in YahooFinance.getHistoricalPrices %s" % traceback.format_exc()) | [
"def",
"getQuotes",
"(",
"self",
",",
"symbol",
",",
"start",
",",
"end",
")",
":",
"try",
":",
"start",
"=",
"str",
"(",
"start",
")",
".",
"replace",
"(",
"'-'",
",",
"''",
")",
"end",
"=",
"str",
"(",
"end",
")",
".",
"replace",
"(",
"'-'",
... | Get historical prices for the given ticker symbol.
Date format is 'YYYY-MM-DD'
Returns a nested list. | [
"Get",
"historical",
"prices",
"for",
"the",
"given",
"ticker",
"symbol",
".",
"Date",
"format",
"is",
"YYYY",
"-",
"MM",
"-",
"DD",
"Returns",
"a",
"nested",
"list",
"."
] | train | https://github.com/llazzaro/analyzerdam/blob/c5bc7483dae23bd2e14bbf36147b7a43a0067bc0/analyzerdam/yahooFinance.py#L59-L93 |
twisted/mantissa | xmantissa/product.py | Product.installProductOn | def installProductOn(self, userstore):
"""
Creates an Installation in this user store for our collection
of powerups, and then install those powerups on the user's
store.
"""
def install():
i = Installation(store=userstore)
i.types = self.types
i.install()
userstore.transact(install) | python | def installProductOn(self, userstore):
"""
Creates an Installation in this user store for our collection
of powerups, and then install those powerups on the user's
store.
"""
def install():
i = Installation(store=userstore)
i.types = self.types
i.install()
userstore.transact(install) | [
"def",
"installProductOn",
"(",
"self",
",",
"userstore",
")",
":",
"def",
"install",
"(",
")",
":",
"i",
"=",
"Installation",
"(",
"store",
"=",
"userstore",
")",
"i",
".",
"types",
"=",
"self",
".",
"types",
"i",
".",
"install",
"(",
")",
"userstor... | Creates an Installation in this user store for our collection
of powerups, and then install those powerups on the user's
store. | [
"Creates",
"an",
"Installation",
"in",
"this",
"user",
"store",
"for",
"our",
"collection",
"of",
"powerups",
"and",
"then",
"install",
"those",
"powerups",
"on",
"the",
"user",
"s",
"store",
"."
] | train | https://github.com/twisted/mantissa/blob/53e5502aba23ce99be78b27f923a276593033fe8/xmantissa/product.py#L29-L40 |
twisted/mantissa | xmantissa/product.py | Product.removeProductFrom | def removeProductFrom(self, userstore):
"""
Uninstall all the powerups this product references and remove
the Installation item from the user's store. Doesn't remove
the actual powerups currently, but /should/ reactivate them if
this product is reinstalled.
"""
def uninstall():
#this is probably highly insufficient, but i don't know the
#requirements
i = userstore.findFirst(Installation,
Installation.types == self.types)
i.uninstall()
i.deleteFromStore()
userstore.transact(uninstall) | python | def removeProductFrom(self, userstore):
"""
Uninstall all the powerups this product references and remove
the Installation item from the user's store. Doesn't remove
the actual powerups currently, but /should/ reactivate them if
this product is reinstalled.
"""
def uninstall():
#this is probably highly insufficient, but i don't know the
#requirements
i = userstore.findFirst(Installation,
Installation.types == self.types)
i.uninstall()
i.deleteFromStore()
userstore.transact(uninstall) | [
"def",
"removeProductFrom",
"(",
"self",
",",
"userstore",
")",
":",
"def",
"uninstall",
"(",
")",
":",
"#this is probably highly insufficient, but i don't know the",
"#requirements",
"i",
"=",
"userstore",
".",
"findFirst",
"(",
"Installation",
",",
"Installation",
"... | Uninstall all the powerups this product references and remove
the Installation item from the user's store. Doesn't remove
the actual powerups currently, but /should/ reactivate them if
this product is reinstalled. | [
"Uninstall",
"all",
"the",
"powerups",
"this",
"product",
"references",
"and",
"remove",
"the",
"Installation",
"item",
"from",
"the",
"user",
"s",
"store",
".",
"Doesn",
"t",
"remove",
"the",
"actual",
"powerups",
"currently",
"but",
"/",
"should",
"/",
"re... | train | https://github.com/twisted/mantissa/blob/53e5502aba23ce99be78b27f923a276593033fe8/xmantissa/product.py#L42-L56 |
twisted/mantissa | xmantissa/product.py | Product.installOrResume | def installOrResume(self, userstore):
"""
Install this product on a user store. If this product has been
installed on the user store already and the installation is suspended,
it will be resumed. If it exists and is not suspended, an error will be
raised.
"""
for i in userstore.query(Installation, Installation.types == self.types):
if i.suspended:
unsuspendTabProviders(i)
return
else:
raise RuntimeError("installOrResume called for an"
" installation that isn't suspended")
else:
self.installProductOn(userstore) | python | def installOrResume(self, userstore):
"""
Install this product on a user store. If this product has been
installed on the user store already and the installation is suspended,
it will be resumed. If it exists and is not suspended, an error will be
raised.
"""
for i in userstore.query(Installation, Installation.types == self.types):
if i.suspended:
unsuspendTabProviders(i)
return
else:
raise RuntimeError("installOrResume called for an"
" installation that isn't suspended")
else:
self.installProductOn(userstore) | [
"def",
"installOrResume",
"(",
"self",
",",
"userstore",
")",
":",
"for",
"i",
"in",
"userstore",
".",
"query",
"(",
"Installation",
",",
"Installation",
".",
"types",
"==",
"self",
".",
"types",
")",
":",
"if",
"i",
".",
"suspended",
":",
"unsuspendTabP... | Install this product on a user store. If this product has been
installed on the user store already and the installation is suspended,
it will be resumed. If it exists and is not suspended, an error will be
raised. | [
"Install",
"this",
"product",
"on",
"a",
"user",
"store",
".",
"If",
"this",
"product",
"has",
"been",
"installed",
"on",
"the",
"user",
"store",
"already",
"and",
"the",
"installation",
"is",
"suspended",
"it",
"will",
"be",
"resumed",
".",
"If",
"it",
... | train | https://github.com/twisted/mantissa/blob/53e5502aba23ce99be78b27f923a276593033fe8/xmantissa/product.py#L58-L73 |
twisted/mantissa | xmantissa/product.py | Installation.items | def items(self):
"""
Loads the items this Installation refers to.
"""
for id in self._items:
yield self.store.getItemByID(int(id)) | python | def items(self):
"""
Loads the items this Installation refers to.
"""
for id in self._items:
yield self.store.getItemByID(int(id)) | [
"def",
"items",
"(",
"self",
")",
":",
"for",
"id",
"in",
"self",
".",
"_items",
":",
"yield",
"self",
".",
"store",
".",
"getItemByID",
"(",
"int",
"(",
"id",
")",
")"
] | Loads the items this Installation refers to. | [
"Loads",
"the",
"items",
"this",
"Installation",
"refers",
"to",
"."
] | train | https://github.com/twisted/mantissa/blob/53e5502aba23ce99be78b27f923a276593033fe8/xmantissa/product.py#L85-L90 |
twisted/mantissa | xmantissa/product.py | Installation.install | def install(self):
"""
Called when installed on the user store. Installs my powerups.
"""
items = []
for typeName in self.types:
it = self.store.findOrCreate(namedAny(typeName))
installOn(it, self.store)
items.append(str(it.storeID).decode('ascii'))
self._items = items | python | def install(self):
"""
Called when installed on the user store. Installs my powerups.
"""
items = []
for typeName in self.types:
it = self.store.findOrCreate(namedAny(typeName))
installOn(it, self.store)
items.append(str(it.storeID).decode('ascii'))
self._items = items | [
"def",
"install",
"(",
"self",
")",
":",
"items",
"=",
"[",
"]",
"for",
"typeName",
"in",
"self",
".",
"types",
":",
"it",
"=",
"self",
".",
"store",
".",
"findOrCreate",
"(",
"namedAny",
"(",
"typeName",
")",
")",
"installOn",
"(",
"it",
",",
"sel... | Called when installed on the user store. Installs my powerups. | [
"Called",
"when",
"installed",
"on",
"the",
"user",
"store",
".",
"Installs",
"my",
"powerups",
"."
] | train | https://github.com/twisted/mantissa/blob/53e5502aba23ce99be78b27f923a276593033fe8/xmantissa/product.py#L97-L106 |
twisted/mantissa | xmantissa/product.py | Installation.uninstall | def uninstall(self):
"""
Called when uninstalled from the user store. Uninstalls all my
powerups.
"""
for item in self.items:
uninstallFrom(item, self.store)
self._items = [] | python | def uninstall(self):
"""
Called when uninstalled from the user store. Uninstalls all my
powerups.
"""
for item in self.items:
uninstallFrom(item, self.store)
self._items = [] | [
"def",
"uninstall",
"(",
"self",
")",
":",
"for",
"item",
"in",
"self",
".",
"items",
":",
"uninstallFrom",
"(",
"item",
",",
"self",
".",
"store",
")",
"self",
".",
"_items",
"=",
"[",
"]"
] | Called when uninstalled from the user store. Uninstalls all my
powerups. | [
"Called",
"when",
"uninstalled",
"from",
"the",
"user",
"store",
".",
"Uninstalls",
"all",
"my",
"powerups",
"."
] | train | https://github.com/twisted/mantissa/blob/53e5502aba23ce99be78b27f923a276593033fe8/xmantissa/product.py#L108-L115 |
twisted/mantissa | xmantissa/product.py | ProductConfiguration.createProduct | def createProduct(self, powerups):
"""
Create a new L{Product} instance which confers the given
powerups.
@type powerups: C{list} of powerup item types
@rtype: L{Product}
@return: The new product instance.
"""
types = [qual(powerup).decode('ascii')
for powerup in powerups]
for p in self.store.parent.query(Product):
for t in types:
if t in p.types:
raise ValueError("%s is already included in a Product" % (t,))
return Product(store=self.store.parent,
types=types) | python | def createProduct(self, powerups):
"""
Create a new L{Product} instance which confers the given
powerups.
@type powerups: C{list} of powerup item types
@rtype: L{Product}
@return: The new product instance.
"""
types = [qual(powerup).decode('ascii')
for powerup in powerups]
for p in self.store.parent.query(Product):
for t in types:
if t in p.types:
raise ValueError("%s is already included in a Product" % (t,))
return Product(store=self.store.parent,
types=types) | [
"def",
"createProduct",
"(",
"self",
",",
"powerups",
")",
":",
"types",
"=",
"[",
"qual",
"(",
"powerup",
")",
".",
"decode",
"(",
"'ascii'",
")",
"for",
"powerup",
"in",
"powerups",
"]",
"for",
"p",
"in",
"self",
".",
"store",
".",
"parent",
".",
... | Create a new L{Product} instance which confers the given
powerups.
@type powerups: C{list} of powerup item types
@rtype: L{Product}
@return: The new product instance. | [
"Create",
"a",
"new",
"L",
"{",
"Product",
"}",
"instance",
"which",
"confers",
"the",
"given",
"powerups",
"."
] | train | https://github.com/twisted/mantissa/blob/53e5502aba23ce99be78b27f923a276593033fe8/xmantissa/product.py#L129-L146 |
twisted/mantissa | xmantissa/product.py | ProductFragment.coerceProduct | def coerceProduct(self, **kw):
"""
Create a product and return a status string which should be part of a
template.
@param **kw: Fully qualified Python names for powerup types to
associate with the created product.
"""
self.original.createProduct(filter(None, kw.values()))
return u'Created.' | python | def coerceProduct(self, **kw):
"""
Create a product and return a status string which should be part of a
template.
@param **kw: Fully qualified Python names for powerup types to
associate with the created product.
"""
self.original.createProduct(filter(None, kw.values()))
return u'Created.' | [
"def",
"coerceProduct",
"(",
"self",
",",
"*",
"*",
"kw",
")",
":",
"self",
".",
"original",
".",
"createProduct",
"(",
"filter",
"(",
"None",
",",
"kw",
".",
"values",
"(",
")",
")",
")",
"return",
"u'Created.'"
] | Create a product and return a status string which should be part of a
template.
@param **kw: Fully qualified Python names for powerup types to
associate with the created product. | [
"Create",
"a",
"product",
"and",
"return",
"a",
"status",
"string",
"which",
"should",
"be",
"part",
"of",
"a",
"template",
"."
] | train | https://github.com/twisted/mantissa/blob/53e5502aba23ce99be78b27f923a276593033fe8/xmantissa/product.py#L168-L177 |
jwodder/doapi | doapi/action.py | Action.fetch | def fetch(self):
"""
Fetch & return a new `Action` object representing the action's current
state
:rtype: Action
:raises DOAPIError: if the API endpoint replies with an error
"""
api = self.doapi_manager
return api._action(api.request(self.url)["action"]) | python | def fetch(self):
"""
Fetch & return a new `Action` object representing the action's current
state
:rtype: Action
:raises DOAPIError: if the API endpoint replies with an error
"""
api = self.doapi_manager
return api._action(api.request(self.url)["action"]) | [
"def",
"fetch",
"(",
"self",
")",
":",
"api",
"=",
"self",
".",
"doapi_manager",
"return",
"api",
".",
"_action",
"(",
"api",
".",
"request",
"(",
"self",
".",
"url",
")",
"[",
"\"action\"",
"]",
")"
] | Fetch & return a new `Action` object representing the action's current
state
:rtype: Action
:raises DOAPIError: if the API endpoint replies with an error | [
"Fetch",
"&",
"return",
"a",
"new",
"Action",
"object",
"representing",
"the",
"action",
"s",
"current",
"state"
] | train | https://github.com/jwodder/doapi/blob/b1306de86a01d8ae7b9c1fe2699765bb82e4f310/doapi/action.py#L94-L103 |
jwodder/doapi | doapi/action.py | Action.fetch_resource | def fetch_resource(self):
"""
Fetch & return the resource that the action operated on, or `None` if
the resource no longer exists (specifically, if the API returns a 404)
:rtype: `Droplet`, `Image`, `FloatingIP`, or `None`
:raises ValueError: if the action has an unknown ``resource_type``
(This indicates a deficiency in the library; please report it!)
:raises DOAPIError: if the API endpoint replies with a non-404 error
"""
try:
if self.resource_type == "droplet":
return self.doapi_manager.fetch_droplet(self.resource_id)
elif self.resource_type == "image":
return self.doapi_manager.fetch_image(self.resource_id)
elif self.resource_type == "floating_ip":
return self.doapi_manager.fetch_floating_ip(self.resource_id)
else:
raise ValueError('{0.resource_type!r}: unknown resource_type'\
.format(self))
except DOAPIError as e:
if e.response.status_code == 404:
return None
else:
raise | python | def fetch_resource(self):
"""
Fetch & return the resource that the action operated on, or `None` if
the resource no longer exists (specifically, if the API returns a 404)
:rtype: `Droplet`, `Image`, `FloatingIP`, or `None`
:raises ValueError: if the action has an unknown ``resource_type``
(This indicates a deficiency in the library; please report it!)
:raises DOAPIError: if the API endpoint replies with a non-404 error
"""
try:
if self.resource_type == "droplet":
return self.doapi_manager.fetch_droplet(self.resource_id)
elif self.resource_type == "image":
return self.doapi_manager.fetch_image(self.resource_id)
elif self.resource_type == "floating_ip":
return self.doapi_manager.fetch_floating_ip(self.resource_id)
else:
raise ValueError('{0.resource_type!r}: unknown resource_type'\
.format(self))
except DOAPIError as e:
if e.response.status_code == 404:
return None
else:
raise | [
"def",
"fetch_resource",
"(",
"self",
")",
":",
"try",
":",
"if",
"self",
".",
"resource_type",
"==",
"\"droplet\"",
":",
"return",
"self",
".",
"doapi_manager",
".",
"fetch_droplet",
"(",
"self",
".",
"resource_id",
")",
"elif",
"self",
".",
"resource_type"... | Fetch & return the resource that the action operated on, or `None` if
the resource no longer exists (specifically, if the API returns a 404)
:rtype: `Droplet`, `Image`, `FloatingIP`, or `None`
:raises ValueError: if the action has an unknown ``resource_type``
(This indicates a deficiency in the library; please report it!)
:raises DOAPIError: if the API endpoint replies with a non-404 error | [
"Fetch",
"&",
"return",
"the",
"resource",
"that",
"the",
"action",
"operated",
"on",
"or",
"None",
"if",
"the",
"resource",
"no",
"longer",
"exists",
"(",
"specifically",
"if",
"the",
"API",
"returns",
"a",
"404",
")"
] | train | https://github.com/jwodder/doapi/blob/b1306de86a01d8ae7b9c1fe2699765bb82e4f310/doapi/action.py#L105-L129 |
jwodder/doapi | doapi/action.py | Action.wait | def wait(self, wait_interval=None, wait_time=None):
"""
Poll the server periodically until the action has either completed or
errored out and return its final state.
If ``wait_time`` is exceeded, a `WaitTimeoutError` (containing the
action's most recently fetched state) is raised.
If a `KeyboardInterrupt` is caught, the action's most recently fetched
state is returned immediately without waiting for completion.
.. versionchanged:: 0.2.0
Raises `WaitTimeoutError` on timeout
:param number wait_interval: how many seconds to sleep between
requests; defaults to the `doapi` object's
:attr:`~doapi.wait_interval` if not specified or `None`
:param number wait_time: the total number of seconds after which the
method will raise an error if the action has not yet completed, or
a negative number to wait indefinitely; defaults to the `doapi`
object's :attr:`~doapi.wait_time` if not specified or `None`
:return: the action's final state
:rtype: Action
:raises DOAPIError: if the API endpoint replies with an error
:raises WaitTimeoutError: if ``wait_time`` is exceeded
"""
return next(self.doapi_manager.wait_actions([self], wait_interval,
wait_time)) | python | def wait(self, wait_interval=None, wait_time=None):
"""
Poll the server periodically until the action has either completed or
errored out and return its final state.
If ``wait_time`` is exceeded, a `WaitTimeoutError` (containing the
action's most recently fetched state) is raised.
If a `KeyboardInterrupt` is caught, the action's most recently fetched
state is returned immediately without waiting for completion.
.. versionchanged:: 0.2.0
Raises `WaitTimeoutError` on timeout
:param number wait_interval: how many seconds to sleep between
requests; defaults to the `doapi` object's
:attr:`~doapi.wait_interval` if not specified or `None`
:param number wait_time: the total number of seconds after which the
method will raise an error if the action has not yet completed, or
a negative number to wait indefinitely; defaults to the `doapi`
object's :attr:`~doapi.wait_time` if not specified or `None`
:return: the action's final state
:rtype: Action
:raises DOAPIError: if the API endpoint replies with an error
:raises WaitTimeoutError: if ``wait_time`` is exceeded
"""
return next(self.doapi_manager.wait_actions([self], wait_interval,
wait_time)) | [
"def",
"wait",
"(",
"self",
",",
"wait_interval",
"=",
"None",
",",
"wait_time",
"=",
"None",
")",
":",
"return",
"next",
"(",
"self",
".",
"doapi_manager",
".",
"wait_actions",
"(",
"[",
"self",
"]",
",",
"wait_interval",
",",
"wait_time",
")",
")"
] | Poll the server periodically until the action has either completed or
errored out and return its final state.
If ``wait_time`` is exceeded, a `WaitTimeoutError` (containing the
action's most recently fetched state) is raised.
If a `KeyboardInterrupt` is caught, the action's most recently fetched
state is returned immediately without waiting for completion.
.. versionchanged:: 0.2.0
Raises `WaitTimeoutError` on timeout
:param number wait_interval: how many seconds to sleep between
requests; defaults to the `doapi` object's
:attr:`~doapi.wait_interval` if not specified or `None`
:param number wait_time: the total number of seconds after which the
method will raise an error if the action has not yet completed, or
a negative number to wait indefinitely; defaults to the `doapi`
object's :attr:`~doapi.wait_time` if not specified or `None`
:return: the action's final state
:rtype: Action
:raises DOAPIError: if the API endpoint replies with an error
:raises WaitTimeoutError: if ``wait_time`` is exceeded | [
"Poll",
"the",
"server",
"periodically",
"until",
"the",
"action",
"has",
"either",
"completed",
"or",
"errored",
"out",
"and",
"return",
"its",
"final",
"state",
"."
] | train | https://github.com/jwodder/doapi/blob/b1306de86a01d8ae7b9c1fe2699765bb82e4f310/doapi/action.py#L131-L158 |
twisted/mantissa | xmantissa/cachejs.py | CachedJSModule.wasModified | def wasModified(self):
"""
Check to see if this module has been modified on disk since the last
time it was cached.
@return: True if it has been modified, False if not.
"""
self.filePath.restat()
mtime = self.filePath.getmtime()
if mtime >= self.lastModified:
return True
else:
return False | python | def wasModified(self):
"""
Check to see if this module has been modified on disk since the last
time it was cached.
@return: True if it has been modified, False if not.
"""
self.filePath.restat()
mtime = self.filePath.getmtime()
if mtime >= self.lastModified:
return True
else:
return False | [
"def",
"wasModified",
"(",
"self",
")",
":",
"self",
".",
"filePath",
".",
"restat",
"(",
")",
"mtime",
"=",
"self",
".",
"filePath",
".",
"getmtime",
"(",
")",
"if",
"mtime",
">=",
"self",
".",
"lastModified",
":",
"return",
"True",
"else",
":",
"re... | Check to see if this module has been modified on disk since the last
time it was cached.
@return: True if it has been modified, False if not. | [
"Check",
"to",
"see",
"if",
"this",
"module",
"has",
"been",
"modified",
"on",
"disk",
"since",
"the",
"last",
"time",
"it",
"was",
"cached",
"."
] | train | https://github.com/twisted/mantissa/blob/53e5502aba23ce99be78b27f923a276593033fe8/xmantissa/cachejs.py#L45-L57 |
twisted/mantissa | xmantissa/cachejs.py | CachedJSModule.maybeUpdate | def maybeUpdate(self):
"""
Check this cache entry and update it if any filesystem information has
changed.
"""
if self.wasModified():
self.lastModified = self.filePath.getmtime()
self.fileContents = self.filePath.getContent()
self.hashValue = hashlib.sha1(self.fileContents).hexdigest() | python | def maybeUpdate(self):
"""
Check this cache entry and update it if any filesystem information has
changed.
"""
if self.wasModified():
self.lastModified = self.filePath.getmtime()
self.fileContents = self.filePath.getContent()
self.hashValue = hashlib.sha1(self.fileContents).hexdigest() | [
"def",
"maybeUpdate",
"(",
"self",
")",
":",
"if",
"self",
".",
"wasModified",
"(",
")",
":",
"self",
".",
"lastModified",
"=",
"self",
".",
"filePath",
".",
"getmtime",
"(",
")",
"self",
".",
"fileContents",
"=",
"self",
".",
"filePath",
".",
"getCont... | Check this cache entry and update it if any filesystem information has
changed. | [
"Check",
"this",
"cache",
"entry",
"and",
"update",
"it",
"if",
"any",
"filesystem",
"information",
"has",
"changed",
"."
] | train | https://github.com/twisted/mantissa/blob/53e5502aba23ce99be78b27f923a276593033fe8/xmantissa/cachejs.py#L60-L68 |
twisted/mantissa | xmantissa/cachejs.py | HashedJSModuleProvider.getModule | def getModule(self, moduleName):
"""
Retrieve a JavaScript module cache from the file path cache.
@returns: Module cache for the named module.
@rtype: L{CachedJSModule}
"""
if moduleName not in self.moduleCache:
modulePath = FilePath(
athena.jsDeps.getModuleForName(moduleName)._cache.path)
cachedModule = self.moduleCache[moduleName] = CachedJSModule(
moduleName, modulePath)
else:
cachedModule = self.moduleCache[moduleName]
return cachedModule | python | def getModule(self, moduleName):
"""
Retrieve a JavaScript module cache from the file path cache.
@returns: Module cache for the named module.
@rtype: L{CachedJSModule}
"""
if moduleName not in self.moduleCache:
modulePath = FilePath(
athena.jsDeps.getModuleForName(moduleName)._cache.path)
cachedModule = self.moduleCache[moduleName] = CachedJSModule(
moduleName, modulePath)
else:
cachedModule = self.moduleCache[moduleName]
return cachedModule | [
"def",
"getModule",
"(",
"self",
",",
"moduleName",
")",
":",
"if",
"moduleName",
"not",
"in",
"self",
".",
"moduleCache",
":",
"modulePath",
"=",
"FilePath",
"(",
"athena",
".",
"jsDeps",
".",
"getModuleForName",
"(",
"moduleName",
")",
".",
"_cache",
"."... | Retrieve a JavaScript module cache from the file path cache.
@returns: Module cache for the named module.
@rtype: L{CachedJSModule} | [
"Retrieve",
"a",
"JavaScript",
"module",
"cache",
"from",
"the",
"file",
"path",
"cache",
"."
] | train | https://github.com/twisted/mantissa/blob/53e5502aba23ce99be78b27f923a276593033fe8/xmantissa/cachejs.py#L93-L107 |
twisted/mantissa | xmantissa/cachejs.py | HashedJSModuleProvider.locateChild | def locateChild(self, ctx, segments):
"""
Retrieve an L{inevow.IResource} to render the contents of the given
module.
"""
if len(segments) != 2:
return NotFound
hashCode, moduleName = segments
cachedModule = self.getModule(moduleName)
return static.Data(
cachedModule.fileContents,
'text/javascript', expires=(60 * 60 * 24 * 365 * 5)), [] | python | def locateChild(self, ctx, segments):
"""
Retrieve an L{inevow.IResource} to render the contents of the given
module.
"""
if len(segments) != 2:
return NotFound
hashCode, moduleName = segments
cachedModule = self.getModule(moduleName)
return static.Data(
cachedModule.fileContents,
'text/javascript', expires=(60 * 60 * 24 * 365 * 5)), [] | [
"def",
"locateChild",
"(",
"self",
",",
"ctx",
",",
"segments",
")",
":",
"if",
"len",
"(",
"segments",
")",
"!=",
"2",
":",
"return",
"NotFound",
"hashCode",
",",
"moduleName",
"=",
"segments",
"cachedModule",
"=",
"self",
".",
"getModule",
"(",
"module... | Retrieve an L{inevow.IResource} to render the contents of the given
module. | [
"Retrieve",
"an",
"L",
"{",
"inevow",
".",
"IResource",
"}",
"to",
"render",
"the",
"contents",
"of",
"the",
"given",
"module",
"."
] | train | https://github.com/twisted/mantissa/blob/53e5502aba23ce99be78b27f923a276593033fe8/xmantissa/cachejs.py#L111-L122 |
inveniosoftware/invenio-openaire | invenio_openaire/resolvers/grants.py | resolve_grant_endpoint | def resolve_grant_endpoint(doi_grant_code):
"""Resolve the OpenAIRE grant."""
# jsonresolver will evaluate current_app on import if outside of function.
from flask import current_app
pid_value = '10.13039/{0}'.format(doi_grant_code)
try:
_, record = Resolver(pid_type='grant', object_type='rec',
getter=Record.get_record).resolve(pid_value)
return record
except Exception:
current_app.logger.error(
'Grant {0} does not exists.'.format(pid_value), exc_info=True)
raise | python | def resolve_grant_endpoint(doi_grant_code):
"""Resolve the OpenAIRE grant."""
# jsonresolver will evaluate current_app on import if outside of function.
from flask import current_app
pid_value = '10.13039/{0}'.format(doi_grant_code)
try:
_, record = Resolver(pid_type='grant', object_type='rec',
getter=Record.get_record).resolve(pid_value)
return record
except Exception:
current_app.logger.error(
'Grant {0} does not exists.'.format(pid_value), exc_info=True)
raise | [
"def",
"resolve_grant_endpoint",
"(",
"doi_grant_code",
")",
":",
"# jsonresolver will evaluate current_app on import if outside of function.",
"from",
"flask",
"import",
"current_app",
"pid_value",
"=",
"'10.13039/{0}'",
".",
"format",
"(",
"doi_grant_code",
")",
"try",
":",... | Resolve the OpenAIRE grant. | [
"Resolve",
"the",
"OpenAIRE",
"grant",
"."
] | train | https://github.com/inveniosoftware/invenio-openaire/blob/71860effff6abe7f658d3a11894e064202ef1c36/invenio_openaire/resolvers/grants.py#L35-L47 |
inveniosoftware/invenio-openaire | invenio_openaire/resolvers/grants.py | jsonresolver_loader | def jsonresolver_loader(url_map):
"""Resolve the OpenAIRE grant."""
from flask import current_app
url_map.add(Rule(
'/grants/10.13039/<path:doi_grant_code>',
endpoint=resolve_grant_endpoint,
host=current_app.config['OPENAIRE_JSONRESOLVER_GRANTS_HOST'])) | python | def jsonresolver_loader(url_map):
"""Resolve the OpenAIRE grant."""
from flask import current_app
url_map.add(Rule(
'/grants/10.13039/<path:doi_grant_code>',
endpoint=resolve_grant_endpoint,
host=current_app.config['OPENAIRE_JSONRESOLVER_GRANTS_HOST'])) | [
"def",
"jsonresolver_loader",
"(",
"url_map",
")",
":",
"from",
"flask",
"import",
"current_app",
"url_map",
".",
"add",
"(",
"Rule",
"(",
"'/grants/10.13039/<path:doi_grant_code>'",
",",
"endpoint",
"=",
"resolve_grant_endpoint",
",",
"host",
"=",
"current_app",
".... | Resolve the OpenAIRE grant. | [
"Resolve",
"the",
"OpenAIRE",
"grant",
"."
] | train | https://github.com/inveniosoftware/invenio-openaire/blob/71860effff6abe7f658d3a11894e064202ef1c36/invenio_openaire/resolvers/grants.py#L51-L57 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.