repo stringlengths 7 55 | path stringlengths 4 127 | func_name stringlengths 1 88 | original_string stringlengths 75 19.8k | language stringclasses 1
value | code stringlengths 75 19.8k | code_tokens listlengths 20 707 | docstring stringlengths 3 17.3k | docstring_tokens listlengths 3 222 | sha stringlengths 40 40 | url stringlengths 87 242 | partition stringclasses 1
value | idx int64 0 252k |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
dougthor42/PyErf | pyerf/pyerf.py | _erf | def _erf(x):
"""
Port of cephes ``ndtr.c`` ``erf`` function.
See https://github.com/jeremybarnes/cephes/blob/master/cprob/ndtr.c
"""
T = [
9.60497373987051638749E0,
9.00260197203842689217E1,
2.23200534594684319226E3,
7.00332514112805075473E3,
5.55923013010394962768E4,
]
U = [
3.35617141647503099647E1,
5.21357949780152679795E2,
4.59432382970980127987E3,
2.26290000613890934246E4,
4.92673942608635921086E4,
]
# Shorcut special cases
if x == 0:
return 0
if x >= MAXVAL:
return 1
if x <= -MAXVAL:
return -1
if abs(x) > 1:
return 1 - erfc(x)
z = x * x
return x * _polevl(z, T, 4) / _p1evl(z, U, 5) | python | def _erf(x):
"""
Port of cephes ``ndtr.c`` ``erf`` function.
See https://github.com/jeremybarnes/cephes/blob/master/cprob/ndtr.c
"""
T = [
9.60497373987051638749E0,
9.00260197203842689217E1,
2.23200534594684319226E3,
7.00332514112805075473E3,
5.55923013010394962768E4,
]
U = [
3.35617141647503099647E1,
5.21357949780152679795E2,
4.59432382970980127987E3,
2.26290000613890934246E4,
4.92673942608635921086E4,
]
# Shorcut special cases
if x == 0:
return 0
if x >= MAXVAL:
return 1
if x <= -MAXVAL:
return -1
if abs(x) > 1:
return 1 - erfc(x)
z = x * x
return x * _polevl(z, T, 4) / _p1evl(z, U, 5) | [
"def",
"_erf",
"(",
"x",
")",
":",
"T",
"=",
"[",
"9.60497373987051638749E0",
",",
"9.00260197203842689217E1",
",",
"2.23200534594684319226E3",
",",
"7.00332514112805075473E3",
",",
"5.55923013010394962768E4",
",",
"]",
"U",
"=",
"[",
"3.35617141647503099647E1",
",",
... | Port of cephes ``ndtr.c`` ``erf`` function.
See https://github.com/jeremybarnes/cephes/blob/master/cprob/ndtr.c | [
"Port",
"of",
"cephes",
"ndtr",
".",
"c",
"erf",
"function",
"."
] | cf38a2c62556cbd4927c9b3f5523f39b6a492472 | https://github.com/dougthor42/PyErf/blob/cf38a2c62556cbd4927c9b3f5523f39b6a492472/pyerf/pyerf.py#L36-L70 | train | 54,900 |
dougthor42/PyErf | pyerf/pyerf.py | _erfc | def _erfc(a):
"""
Port of cephes ``ndtr.c`` ``erfc`` function.
See https://github.com/jeremybarnes/cephes/blob/master/cprob/ndtr.c
"""
# approximation for abs(a) < 8 and abs(a) >= 1
P = [
2.46196981473530512524E-10,
5.64189564831068821977E-1,
7.46321056442269912687E0,
4.86371970985681366614E1,
1.96520832956077098242E2,
5.26445194995477358631E2,
9.34528527171957607540E2,
1.02755188689515710272E3,
5.57535335369399327526E2,
]
Q = [
1.32281951154744992508E1,
8.67072140885989742329E1,
3.54937778887819891062E2,
9.75708501743205489753E2,
1.82390916687909736289E3,
2.24633760818710981792E3,
1.65666309194161350182E3,
5.57535340817727675546E2,
]
# approximation for abs(a) >= 8
R = [
5.64189583547755073984E-1,
1.27536670759978104416E0,
5.01905042251180477414E0,
6.16021097993053585195E0,
7.40974269950448939160E0,
2.97886665372100240670E0,
]
S = [
2.26052863220117276590E0,
9.39603524938001434673E0,
1.20489539808096656605E1,
1.70814450747565897222E1,
9.60896809063285878198E0,
3.36907645100081516050E0,
]
# Shortcut special cases
if a == 0:
return 1
if a >= MAXVAL:
return 0
if a <= -MAXVAL:
return 2
x = a
if a < 0:
x = -a
# computationally cheaper to calculate erf for small values, I guess.
if x < 1:
return 1 - erf(a)
z = -a * a
z = math.exp(z)
if x < 8:
p = _polevl(x, P, 8)
q = _p1evl(x, Q, 8)
else:
p = _polevl(x, R, 5)
q = _p1evl(x, S, 6)
y = (z * p) / q
if a < 0:
y = 2 - y
return y | python | def _erfc(a):
"""
Port of cephes ``ndtr.c`` ``erfc`` function.
See https://github.com/jeremybarnes/cephes/blob/master/cprob/ndtr.c
"""
# approximation for abs(a) < 8 and abs(a) >= 1
P = [
2.46196981473530512524E-10,
5.64189564831068821977E-1,
7.46321056442269912687E0,
4.86371970985681366614E1,
1.96520832956077098242E2,
5.26445194995477358631E2,
9.34528527171957607540E2,
1.02755188689515710272E3,
5.57535335369399327526E2,
]
Q = [
1.32281951154744992508E1,
8.67072140885989742329E1,
3.54937778887819891062E2,
9.75708501743205489753E2,
1.82390916687909736289E3,
2.24633760818710981792E3,
1.65666309194161350182E3,
5.57535340817727675546E2,
]
# approximation for abs(a) >= 8
R = [
5.64189583547755073984E-1,
1.27536670759978104416E0,
5.01905042251180477414E0,
6.16021097993053585195E0,
7.40974269950448939160E0,
2.97886665372100240670E0,
]
S = [
2.26052863220117276590E0,
9.39603524938001434673E0,
1.20489539808096656605E1,
1.70814450747565897222E1,
9.60896809063285878198E0,
3.36907645100081516050E0,
]
# Shortcut special cases
if a == 0:
return 1
if a >= MAXVAL:
return 0
if a <= -MAXVAL:
return 2
x = a
if a < 0:
x = -a
# computationally cheaper to calculate erf for small values, I guess.
if x < 1:
return 1 - erf(a)
z = -a * a
z = math.exp(z)
if x < 8:
p = _polevl(x, P, 8)
q = _p1evl(x, Q, 8)
else:
p = _polevl(x, R, 5)
q = _p1evl(x, S, 6)
y = (z * p) / q
if a < 0:
y = 2 - y
return y | [
"def",
"_erfc",
"(",
"a",
")",
":",
"# approximation for abs(a) < 8 and abs(a) >= 1",
"P",
"=",
"[",
"2.46196981473530512524E-10",
",",
"5.64189564831068821977E-1",
",",
"7.46321056442269912687E0",
",",
"4.86371970985681366614E1",
",",
"1.96520832956077098242E2",
",",
"5.2644... | Port of cephes ``ndtr.c`` ``erfc`` function.
See https://github.com/jeremybarnes/cephes/blob/master/cprob/ndtr.c | [
"Port",
"of",
"cephes",
"ndtr",
".",
"c",
"erfc",
"function",
"."
] | cf38a2c62556cbd4927c9b3f5523f39b6a492472 | https://github.com/dougthor42/PyErf/blob/cf38a2c62556cbd4927c9b3f5523f39b6a492472/pyerf/pyerf.py#L73-L154 | train | 54,901 |
dougthor42/PyErf | pyerf/pyerf.py | erfinv | def erfinv(z):
"""
Calculate the inverse error function at point ``z``.
This is a direct port of the SciPy ``erfinv`` function, originally
written in C.
Parameters
----------
z : numeric
Returns
-------
float
References
----------
+ https://en.wikipedia.org/wiki/Error_function#Inverse_functions
+ http://functions.wolfram.com/GammaBetaErf/InverseErf/
Examples
--------
>>> round(erfinv(0.1), 12)
0.088855990494
>>> round(erfinv(0.5), 12)
0.476936276204
>>> round(erfinv(-0.5), 12)
-0.476936276204
>>> round(erfinv(0.95), 12)
1.38590382435
>>> round(erf(erfinv(0.3)), 3)
0.3
>>> round(erfinv(erf(0.5)), 3)
0.5
>>> erfinv(0)
0
>>> erfinv(1)
inf
>>> erfinv(-1)
-inf
"""
if abs(z) > 1:
raise ValueError("`z` must be between -1 and 1 inclusive")
# Shortcut special cases
if z == 0:
return 0
if z == 1:
return inf
if z == -1:
return -inf
# otherwise calculate things.
return _ndtri((z + 1) / 2.0) / math.sqrt(2) | python | def erfinv(z):
"""
Calculate the inverse error function at point ``z``.
This is a direct port of the SciPy ``erfinv`` function, originally
written in C.
Parameters
----------
z : numeric
Returns
-------
float
References
----------
+ https://en.wikipedia.org/wiki/Error_function#Inverse_functions
+ http://functions.wolfram.com/GammaBetaErf/InverseErf/
Examples
--------
>>> round(erfinv(0.1), 12)
0.088855990494
>>> round(erfinv(0.5), 12)
0.476936276204
>>> round(erfinv(-0.5), 12)
-0.476936276204
>>> round(erfinv(0.95), 12)
1.38590382435
>>> round(erf(erfinv(0.3)), 3)
0.3
>>> round(erfinv(erf(0.5)), 3)
0.5
>>> erfinv(0)
0
>>> erfinv(1)
inf
>>> erfinv(-1)
-inf
"""
if abs(z) > 1:
raise ValueError("`z` must be between -1 and 1 inclusive")
# Shortcut special cases
if z == 0:
return 0
if z == 1:
return inf
if z == -1:
return -inf
# otherwise calculate things.
return _ndtri((z + 1) / 2.0) / math.sqrt(2) | [
"def",
"erfinv",
"(",
"z",
")",
":",
"if",
"abs",
"(",
"z",
")",
">",
"1",
":",
"raise",
"ValueError",
"(",
"\"`z` must be between -1 and 1 inclusive\"",
")",
"# Shortcut special cases",
"if",
"z",
"==",
"0",
":",
"return",
"0",
"if",
"z",
"==",
"1",
":"... | Calculate the inverse error function at point ``z``.
This is a direct port of the SciPy ``erfinv`` function, originally
written in C.
Parameters
----------
z : numeric
Returns
-------
float
References
----------
+ https://en.wikipedia.org/wiki/Error_function#Inverse_functions
+ http://functions.wolfram.com/GammaBetaErf/InverseErf/
Examples
--------
>>> round(erfinv(0.1), 12)
0.088855990494
>>> round(erfinv(0.5), 12)
0.476936276204
>>> round(erfinv(-0.5), 12)
-0.476936276204
>>> round(erfinv(0.95), 12)
1.38590382435
>>> round(erf(erfinv(0.3)), 3)
0.3
>>> round(erfinv(erf(0.5)), 3)
0.5
>>> erfinv(0)
0
>>> erfinv(1)
inf
>>> erfinv(-1)
-inf | [
"Calculate",
"the",
"inverse",
"error",
"function",
"at",
"point",
"z",
"."
] | cf38a2c62556cbd4927c9b3f5523f39b6a492472 | https://github.com/dougthor42/PyErf/blob/cf38a2c62556cbd4927c9b3f5523f39b6a492472/pyerf/pyerf.py#L290-L343 | train | 54,902 |
Chilipp/psy-simple | psy_simple/colors.py | get_cmap | def get_cmap(name, lut=None):
"""
Returns the specified colormap.
Parameters
----------
name: str or :class:`matplotlib.colors.Colormap`
If a colormap, it returned unchanged.
%(cmap_note)s
lut: int
An integer giving the number of entries desired in the lookup table
Returns
-------
matplotlib.colors.Colormap
The colormap specified by `name`
See Also
--------
show_colormaps: A function to display all available colormaps
Notes
-----
Different from the :func::`matpltolib.pyplot.get_cmap` function, this
function changes the number of colors if `name` is a
:class:`matplotlib.colors.Colormap` instance to match the given `lut`."""
if name in rcParams['colors.cmaps']:
colors = rcParams['colors.cmaps'][name]
lut = lut or len(colors)
return FixedColorMap.from_list(name=name, colors=colors, N=lut)
elif name in _cmapnames:
colors = _cmapnames[name]
lut = lut or len(colors)
return FixedColorMap.from_list(name=name, colors=colors, N=lut)
else:
cmap = mpl_get_cmap(name)
# Note: we could include the `lut` in the call of mpl_get_cmap, but
# this raises a ValueError for colormaps like 'viridis' in mpl version
# 1.5. Besides the mpl_get_cmap function does not modify the lut if
# it does not match
if lut is not None and cmap.N != lut:
cmap = FixedColorMap.from_list(
name=cmap.name, colors=cmap(np.linspace(0, 1, lut)), N=lut)
return cmap | python | def get_cmap(name, lut=None):
"""
Returns the specified colormap.
Parameters
----------
name: str or :class:`matplotlib.colors.Colormap`
If a colormap, it returned unchanged.
%(cmap_note)s
lut: int
An integer giving the number of entries desired in the lookup table
Returns
-------
matplotlib.colors.Colormap
The colormap specified by `name`
See Also
--------
show_colormaps: A function to display all available colormaps
Notes
-----
Different from the :func::`matpltolib.pyplot.get_cmap` function, this
function changes the number of colors if `name` is a
:class:`matplotlib.colors.Colormap` instance to match the given `lut`."""
if name in rcParams['colors.cmaps']:
colors = rcParams['colors.cmaps'][name]
lut = lut or len(colors)
return FixedColorMap.from_list(name=name, colors=colors, N=lut)
elif name in _cmapnames:
colors = _cmapnames[name]
lut = lut or len(colors)
return FixedColorMap.from_list(name=name, colors=colors, N=lut)
else:
cmap = mpl_get_cmap(name)
# Note: we could include the `lut` in the call of mpl_get_cmap, but
# this raises a ValueError for colormaps like 'viridis' in mpl version
# 1.5. Besides the mpl_get_cmap function does not modify the lut if
# it does not match
if lut is not None and cmap.N != lut:
cmap = FixedColorMap.from_list(
name=cmap.name, colors=cmap(np.linspace(0, 1, lut)), N=lut)
return cmap | [
"def",
"get_cmap",
"(",
"name",
",",
"lut",
"=",
"None",
")",
":",
"if",
"name",
"in",
"rcParams",
"[",
"'colors.cmaps'",
"]",
":",
"colors",
"=",
"rcParams",
"[",
"'colors.cmaps'",
"]",
"[",
"name",
"]",
"lut",
"=",
"lut",
"or",
"len",
"(",
"colors"... | Returns the specified colormap.
Parameters
----------
name: str or :class:`matplotlib.colors.Colormap`
If a colormap, it returned unchanged.
%(cmap_note)s
lut: int
An integer giving the number of entries desired in the lookup table
Returns
-------
matplotlib.colors.Colormap
The colormap specified by `name`
See Also
--------
show_colormaps: A function to display all available colormaps
Notes
-----
Different from the :func::`matpltolib.pyplot.get_cmap` function, this
function changes the number of colors if `name` is a
:class:`matplotlib.colors.Colormap` instance to match the given `lut`. | [
"Returns",
"the",
"specified",
"colormap",
"."
] | 7d916406a6d3c3c27c0b7102f98fef07a4da0a61 | https://github.com/Chilipp/psy-simple/blob/7d916406a6d3c3c27c0b7102f98fef07a4da0a61/psy_simple/colors.py#L155-L198 | train | 54,903 |
Chilipp/psy-simple | psy_simple/colors.py | _get_cmaps | def _get_cmaps(names):
"""Filter the given `names` for colormaps"""
import matplotlib.pyplot as plt
available_cmaps = list(
chain(plt.cm.cmap_d, _cmapnames, rcParams['colors.cmaps']))
names = list(names)
wrongs = []
for arg in (arg for arg in names if (not isinstance(arg, Colormap) and
arg not in available_cmaps)):
if isinstance(arg, str):
similarkeys = get_close_matches(arg, available_cmaps)
if similarkeys != []:
warn("Colormap %s not found in standard colormaps.\n"
"Similar colormaps are %s." % (arg, ', '.join(similarkeys)))
else:
warn("Colormap %s not found in standard colormaps.\n"
"Run function without arguments to see all colormaps" % arg)
names.remove(arg)
wrongs.append(arg)
if not names and not wrongs:
names = sorted(m for m in available_cmaps if not m.endswith("_r"))
return names | python | def _get_cmaps(names):
"""Filter the given `names` for colormaps"""
import matplotlib.pyplot as plt
available_cmaps = list(
chain(plt.cm.cmap_d, _cmapnames, rcParams['colors.cmaps']))
names = list(names)
wrongs = []
for arg in (arg for arg in names if (not isinstance(arg, Colormap) and
arg not in available_cmaps)):
if isinstance(arg, str):
similarkeys = get_close_matches(arg, available_cmaps)
if similarkeys != []:
warn("Colormap %s not found in standard colormaps.\n"
"Similar colormaps are %s." % (arg, ', '.join(similarkeys)))
else:
warn("Colormap %s not found in standard colormaps.\n"
"Run function without arguments to see all colormaps" % arg)
names.remove(arg)
wrongs.append(arg)
if not names and not wrongs:
names = sorted(m for m in available_cmaps if not m.endswith("_r"))
return names | [
"def",
"_get_cmaps",
"(",
"names",
")",
":",
"import",
"matplotlib",
".",
"pyplot",
"as",
"plt",
"available_cmaps",
"=",
"list",
"(",
"chain",
"(",
"plt",
".",
"cm",
".",
"cmap_d",
",",
"_cmapnames",
",",
"rcParams",
"[",
"'colors.cmaps'",
"]",
")",
")",... | Filter the given `names` for colormaps | [
"Filter",
"the",
"given",
"names",
"for",
"colormaps"
] | 7d916406a6d3c3c27c0b7102f98fef07a4da0a61 | https://github.com/Chilipp/psy-simple/blob/7d916406a6d3c3c27c0b7102f98fef07a4da0a61/psy_simple/colors.py#L201-L222 | train | 54,904 |
Chilipp/psy-simple | psy_simple/colors.py | show_colormaps | def show_colormaps(names=[], N=10, show=True, use_qt=None):
"""Function to show standard colormaps from pyplot
Parameters
----------
``*args``: str or :class:`matplotlib.colors.Colormap`
If a colormap, it returned unchanged.
%(cmap_note)s
N: int, optional
Default: 11. The number of increments in the colormap.
show: bool, optional
Default: True. If True, show the created figure at the end with
pyplot.show(block=False)
use_qt: bool
If True, use the
:class:`psy_simple.widgets.color.ColormapDialog.show_colormaps`, if
False use a matplotlib implementation based on [1]_. If None, use
the Qt implementation if it is running in the psyplot GUI.
Returns
-------
psy_simple.widgets.color.ColormapDialog or matplitlib.figure.Figure
Depending on `use_qt`, either an instance of the
:class:`psy_simple.widgets.color.ColormapDialog` or the
:class:`matplotlib.figure.Figure`
References
----------
.. [1] http://matplotlib.org/1.2.1/examples/pylab_examples/show_colormaps.html
"""
names = safe_list(names)
if use_qt or (use_qt is None and psyplot.with_gui):
from psy_simple.widgets.colors import ColormapDialog
from psyplot_gui.main import mainwindow
return ColormapDialog.show_colormap(names, N, show, parent=mainwindow)
import matplotlib.pyplot as plt
# This example comes from the Cookbook on www.scipy.org. According to the
# history, Andrew Straw did the conversion from an old page, but it is
# unclear who the original author is.
a = np.vstack((np.linspace(0, 1, 256).reshape(1, -1)))
# Get a list of the colormaps in matplotlib. Ignore the ones that end with
# '_r' because these are simply reversed versions of ones that don't end
# with '_r'
cmaps = _get_cmaps(names)
nargs = len(cmaps) + 1
fig = plt.figure(figsize=(5, 10))
fig.subplots_adjust(top=0.99, bottom=0.01, left=0.2, right=0.99)
for i, m in enumerate(cmaps):
ax = plt.subplot(nargs, 1, i+1)
plt.axis("off")
plt.pcolormesh(a, cmap=get_cmap(m, N + 1))
pos = list(ax.get_position().bounds)
fig.text(pos[0] - 0.01, pos[1], m, fontsize=10,
horizontalalignment='right')
fig.canvas.set_window_title("Figure %i: Predefined colormaps" % fig.number)
if show:
plt.show(block=False)
return fig | python | def show_colormaps(names=[], N=10, show=True, use_qt=None):
"""Function to show standard colormaps from pyplot
Parameters
----------
``*args``: str or :class:`matplotlib.colors.Colormap`
If a colormap, it returned unchanged.
%(cmap_note)s
N: int, optional
Default: 11. The number of increments in the colormap.
show: bool, optional
Default: True. If True, show the created figure at the end with
pyplot.show(block=False)
use_qt: bool
If True, use the
:class:`psy_simple.widgets.color.ColormapDialog.show_colormaps`, if
False use a matplotlib implementation based on [1]_. If None, use
the Qt implementation if it is running in the psyplot GUI.
Returns
-------
psy_simple.widgets.color.ColormapDialog or matplitlib.figure.Figure
Depending on `use_qt`, either an instance of the
:class:`psy_simple.widgets.color.ColormapDialog` or the
:class:`matplotlib.figure.Figure`
References
----------
.. [1] http://matplotlib.org/1.2.1/examples/pylab_examples/show_colormaps.html
"""
names = safe_list(names)
if use_qt or (use_qt is None and psyplot.with_gui):
from psy_simple.widgets.colors import ColormapDialog
from psyplot_gui.main import mainwindow
return ColormapDialog.show_colormap(names, N, show, parent=mainwindow)
import matplotlib.pyplot as plt
# This example comes from the Cookbook on www.scipy.org. According to the
# history, Andrew Straw did the conversion from an old page, but it is
# unclear who the original author is.
a = np.vstack((np.linspace(0, 1, 256).reshape(1, -1)))
# Get a list of the colormaps in matplotlib. Ignore the ones that end with
# '_r' because these are simply reversed versions of ones that don't end
# with '_r'
cmaps = _get_cmaps(names)
nargs = len(cmaps) + 1
fig = plt.figure(figsize=(5, 10))
fig.subplots_adjust(top=0.99, bottom=0.01, left=0.2, right=0.99)
for i, m in enumerate(cmaps):
ax = plt.subplot(nargs, 1, i+1)
plt.axis("off")
plt.pcolormesh(a, cmap=get_cmap(m, N + 1))
pos = list(ax.get_position().bounds)
fig.text(pos[0] - 0.01, pos[1], m, fontsize=10,
horizontalalignment='right')
fig.canvas.set_window_title("Figure %i: Predefined colormaps" % fig.number)
if show:
plt.show(block=False)
return fig | [
"def",
"show_colormaps",
"(",
"names",
"=",
"[",
"]",
",",
"N",
"=",
"10",
",",
"show",
"=",
"True",
",",
"use_qt",
"=",
"None",
")",
":",
"names",
"=",
"safe_list",
"(",
"names",
")",
"if",
"use_qt",
"or",
"(",
"use_qt",
"is",
"None",
"and",
"ps... | Function to show standard colormaps from pyplot
Parameters
----------
``*args``: str or :class:`matplotlib.colors.Colormap`
If a colormap, it returned unchanged.
%(cmap_note)s
N: int, optional
Default: 11. The number of increments in the colormap.
show: bool, optional
Default: True. If True, show the created figure at the end with
pyplot.show(block=False)
use_qt: bool
If True, use the
:class:`psy_simple.widgets.color.ColormapDialog.show_colormaps`, if
False use a matplotlib implementation based on [1]_. If None, use
the Qt implementation if it is running in the psyplot GUI.
Returns
-------
psy_simple.widgets.color.ColormapDialog or matplitlib.figure.Figure
Depending on `use_qt`, either an instance of the
:class:`psy_simple.widgets.color.ColormapDialog` or the
:class:`matplotlib.figure.Figure`
References
----------
.. [1] http://matplotlib.org/1.2.1/examples/pylab_examples/show_colormaps.html | [
"Function",
"to",
"show",
"standard",
"colormaps",
"from",
"pyplot"
] | 7d916406a6d3c3c27c0b7102f98fef07a4da0a61 | https://github.com/Chilipp/psy-simple/blob/7d916406a6d3c3c27c0b7102f98fef07a4da0a61/psy_simple/colors.py#L227-L284 | train | 54,905 |
toumorokoshi/sprinter | sprinter/next/script.py | _create_stdout_logger | def _create_stdout_logger(logging_level):
"""
create a logger to stdout. This creates logger for a series
of module we would like to log information on.
"""
out_hdlr = logging.StreamHandler(sys.stdout)
out_hdlr.setFormatter(logging.Formatter(
'[%(asctime)s] %(message)s', "%H:%M:%S"
))
out_hdlr.setLevel(logging_level)
for name in LOGGING_NAMES:
log = logging.getLogger(name)
log.addHandler(out_hdlr)
log.setLevel(logging_level) | python | def _create_stdout_logger(logging_level):
"""
create a logger to stdout. This creates logger for a series
of module we would like to log information on.
"""
out_hdlr = logging.StreamHandler(sys.stdout)
out_hdlr.setFormatter(logging.Formatter(
'[%(asctime)s] %(message)s', "%H:%M:%S"
))
out_hdlr.setLevel(logging_level)
for name in LOGGING_NAMES:
log = logging.getLogger(name)
log.addHandler(out_hdlr)
log.setLevel(logging_level) | [
"def",
"_create_stdout_logger",
"(",
"logging_level",
")",
":",
"out_hdlr",
"=",
"logging",
".",
"StreamHandler",
"(",
"sys",
".",
"stdout",
")",
"out_hdlr",
".",
"setFormatter",
"(",
"logging",
".",
"Formatter",
"(",
"'[%(asctime)s] %(message)s'",
",",
"\"%H:%M:%... | create a logger to stdout. This creates logger for a series
of module we would like to log information on. | [
"create",
"a",
"logger",
"to",
"stdout",
".",
"This",
"creates",
"logger",
"for",
"a",
"series",
"of",
"module",
"we",
"would",
"like",
"to",
"log",
"information",
"on",
"."
] | 846697a7a087e69c61d075232e754d6975a64152 | https://github.com/toumorokoshi/sprinter/blob/846697a7a087e69c61d075232e754d6975a64152/sprinter/next/script.py#L62-L75 | train | 54,906 |
jkeyes/python-docraptor | example/async.py | main | def main():
"""Generate a PDF using the async method."""
docraptor = DocRaptor()
print("Create PDF")
resp = docraptor.create(
{
"document_content": "<h1>python-docraptor</h1><p>Async Test</p>",
"test": True,
"async": True,
}
)
print("Status ID: {status_id}".format(status_id=resp["status_id"]))
status_id = resp["status_id"]
resp = docraptor.status(status_id)
print(" {status}".format(status=resp["status"]))
while resp["status"] != "completed":
time.sleep(3)
resp = docraptor.status(status_id)
print(" {status}".format(status=resp["status"]))
print("Download to test_async.pdf")
with open("test_async.pdf", "wb") as pdf_file:
pdf_file.write(docraptor.download(resp["download_key"]).content)
print("[DONE]") | python | def main():
"""Generate a PDF using the async method."""
docraptor = DocRaptor()
print("Create PDF")
resp = docraptor.create(
{
"document_content": "<h1>python-docraptor</h1><p>Async Test</p>",
"test": True,
"async": True,
}
)
print("Status ID: {status_id}".format(status_id=resp["status_id"]))
status_id = resp["status_id"]
resp = docraptor.status(status_id)
print(" {status}".format(status=resp["status"]))
while resp["status"] != "completed":
time.sleep(3)
resp = docraptor.status(status_id)
print(" {status}".format(status=resp["status"]))
print("Download to test_async.pdf")
with open("test_async.pdf", "wb") as pdf_file:
pdf_file.write(docraptor.download(resp["download_key"]).content)
print("[DONE]") | [
"def",
"main",
"(",
")",
":",
"docraptor",
"=",
"DocRaptor",
"(",
")",
"print",
"(",
"\"Create PDF\"",
")",
"resp",
"=",
"docraptor",
".",
"create",
"(",
"{",
"\"document_content\"",
":",
"\"<h1>python-docraptor</h1><p>Async Test</p>\"",
",",
"\"test\"",
":",
"T... | Generate a PDF using the async method. | [
"Generate",
"a",
"PDF",
"using",
"the",
"async",
"method",
"."
] | 4be5b641f92820539b2c42165fec9251a6603dea | https://github.com/jkeyes/python-docraptor/blob/4be5b641f92820539b2c42165fec9251a6603dea/example/async.py#L6-L32 | train | 54,907 |
smarie/python-parsyfiles | parsyfiles/type_inspection_tools.py | get_alternate_types_resolving_forwardref_union_and_typevar | def get_alternate_types_resolving_forwardref_union_and_typevar(typ, _memo: List[Any] = None) \
-> Tuple[Any, ...]:
"""
Returns a tuple of all alternate types allowed by the `typ` type annotation.
If typ is a TypeVar,
* if the typevar is bound, return get_alternate_types_resolving_forwardref_union_and_typevar(bound)
* if the typevar has constraints, return a tuple containing all the types listed in the constraints (with
appropriate recursive call to get_alternate_types_resolving_forwardref_union_and_typevar for each of them)
* otherwise return (object, )
If typ is a Union, return a tuple containing all the types listed in the union (with
appropriate recursive call to get_alternate_types_resolving_forwardref_union_and_typevar for each of them)
If typ is a forward reference, it is evaluated and this method is applied to the results.
Otherwise (typ, ) is returned
Note that this function automatically prevent infinite recursion through forward references such as in
`A = Union[str, 'A']`, by keeping a _memo of already met symbols.
:param typ:
:return:
"""
# avoid infinite recursion by using a _memo
_memo = _memo or []
if typ in _memo:
return tuple()
# remember that this was already explored
_memo.append(typ)
if is_typevar(typ):
if hasattr(typ, '__bound__') and typ.__bound__ is not None:
# TypeVar is 'bound' to a class
if hasattr(typ, '__contravariant__') and typ.__contravariant__:
# Contravariant means that only super classes of this type are supported!
raise Exception('Contravariant TypeVars are not supported')
else:
# only subclasses of this are allowed (even if not covariant, because as of today we cant do otherwise)
return get_alternate_types_resolving_forwardref_union_and_typevar(typ.__bound__, _memo=_memo)
elif hasattr(typ, '__constraints__') and typ.__constraints__ is not None:
if hasattr(typ, '__contravariant__') and typ.__contravariant__:
# Contravariant means that only super classes of this type are supported!
raise Exception('Contravariant TypeVars are not supported')
else:
# TypeVar is 'constrained' to several alternate classes, meaning that subclasses of any of them are
# allowed (even if not covariant, because as of today we cant do otherwise)
return tuple(typpp for c in typ.__constraints__
for typpp in get_alternate_types_resolving_forwardref_union_and_typevar(c, _memo=_memo))
else:
# A non-parametrized TypeVar means 'any'
return object,
elif is_union_type(typ):
# do not use typ.__args__, it may be wrong
# the solution below works even in typevar+config cases such as u = Union[T, str][Optional[int]]
return tuple(t for typpp in get_args(typ, evaluate=True)
for t in get_alternate_types_resolving_forwardref_union_and_typevar(typpp, _memo=_memo))
elif is_forward_ref(typ):
return get_alternate_types_resolving_forwardref_union_and_typevar(resolve_forward_ref(typ), _memo=_memo)
else:
return typ, | python | def get_alternate_types_resolving_forwardref_union_and_typevar(typ, _memo: List[Any] = None) \
-> Tuple[Any, ...]:
"""
Returns a tuple of all alternate types allowed by the `typ` type annotation.
If typ is a TypeVar,
* if the typevar is bound, return get_alternate_types_resolving_forwardref_union_and_typevar(bound)
* if the typevar has constraints, return a tuple containing all the types listed in the constraints (with
appropriate recursive call to get_alternate_types_resolving_forwardref_union_and_typevar for each of them)
* otherwise return (object, )
If typ is a Union, return a tuple containing all the types listed in the union (with
appropriate recursive call to get_alternate_types_resolving_forwardref_union_and_typevar for each of them)
If typ is a forward reference, it is evaluated and this method is applied to the results.
Otherwise (typ, ) is returned
Note that this function automatically prevent infinite recursion through forward references such as in
`A = Union[str, 'A']`, by keeping a _memo of already met symbols.
:param typ:
:return:
"""
# avoid infinite recursion by using a _memo
_memo = _memo or []
if typ in _memo:
return tuple()
# remember that this was already explored
_memo.append(typ)
if is_typevar(typ):
if hasattr(typ, '__bound__') and typ.__bound__ is not None:
# TypeVar is 'bound' to a class
if hasattr(typ, '__contravariant__') and typ.__contravariant__:
# Contravariant means that only super classes of this type are supported!
raise Exception('Contravariant TypeVars are not supported')
else:
# only subclasses of this are allowed (even if not covariant, because as of today we cant do otherwise)
return get_alternate_types_resolving_forwardref_union_and_typevar(typ.__bound__, _memo=_memo)
elif hasattr(typ, '__constraints__') and typ.__constraints__ is not None:
if hasattr(typ, '__contravariant__') and typ.__contravariant__:
# Contravariant means that only super classes of this type are supported!
raise Exception('Contravariant TypeVars are not supported')
else:
# TypeVar is 'constrained' to several alternate classes, meaning that subclasses of any of them are
# allowed (even if not covariant, because as of today we cant do otherwise)
return tuple(typpp for c in typ.__constraints__
for typpp in get_alternate_types_resolving_forwardref_union_and_typevar(c, _memo=_memo))
else:
# A non-parametrized TypeVar means 'any'
return object,
elif is_union_type(typ):
# do not use typ.__args__, it may be wrong
# the solution below works even in typevar+config cases such as u = Union[T, str][Optional[int]]
return tuple(t for typpp in get_args(typ, evaluate=True)
for t in get_alternate_types_resolving_forwardref_union_and_typevar(typpp, _memo=_memo))
elif is_forward_ref(typ):
return get_alternate_types_resolving_forwardref_union_and_typevar(resolve_forward_ref(typ), _memo=_memo)
else:
return typ, | [
"def",
"get_alternate_types_resolving_forwardref_union_and_typevar",
"(",
"typ",
",",
"_memo",
":",
"List",
"[",
"Any",
"]",
"=",
"None",
")",
"->",
"Tuple",
"[",
"Any",
",",
"...",
"]",
":",
"# avoid infinite recursion by using a _memo",
"_memo",
"=",
"_memo",
"o... | Returns a tuple of all alternate types allowed by the `typ` type annotation.
If typ is a TypeVar,
* if the typevar is bound, return get_alternate_types_resolving_forwardref_union_and_typevar(bound)
* if the typevar has constraints, return a tuple containing all the types listed in the constraints (with
appropriate recursive call to get_alternate_types_resolving_forwardref_union_and_typevar for each of them)
* otherwise return (object, )
If typ is a Union, return a tuple containing all the types listed in the union (with
appropriate recursive call to get_alternate_types_resolving_forwardref_union_and_typevar for each of them)
If typ is a forward reference, it is evaluated and this method is applied to the results.
Otherwise (typ, ) is returned
Note that this function automatically prevent infinite recursion through forward references such as in
`A = Union[str, 'A']`, by keeping a _memo of already met symbols.
:param typ:
:return: | [
"Returns",
"a",
"tuple",
"of",
"all",
"alternate",
"types",
"allowed",
"by",
"the",
"typ",
"type",
"annotation",
"."
] | 344b37e1151e8d4e7c2ee49ae09d6568715ae64e | https://github.com/smarie/python-parsyfiles/blob/344b37e1151e8d4e7c2ee49ae09d6568715ae64e/parsyfiles/type_inspection_tools.py#L22-L87 | train | 54,908 |
smarie/python-parsyfiles | parsyfiles/type_inspection_tools.py | robust_isinstance | def robust_isinstance(inst, typ) -> bool:
"""
Similar to isinstance, but if 'typ' is a parametrized generic Type, it is first transformed into its base generic
class so that the instance check works. It is also robust to Union and Any.
:param inst:
:param typ:
:return:
"""
if typ is Any:
return True
if is_typevar(typ):
if hasattr(typ, '__constraints__') and typ.__constraints__ is not None:
typs = get_args(typ, evaluate=True)
return any(robust_isinstance(inst, t) for t in typs)
elif hasattr(typ, '__bound__') and typ.__bound__ is not None:
return robust_isinstance(inst, typ.__bound__)
else:
# a raw TypeVar means 'anything'
return True
else:
if is_union_type(typ):
typs = get_args(typ, evaluate=True)
return any(robust_isinstance(inst, t) for t in typs)
else:
return isinstance(inst, get_base_generic_type(typ)) | python | def robust_isinstance(inst, typ) -> bool:
"""
Similar to isinstance, but if 'typ' is a parametrized generic Type, it is first transformed into its base generic
class so that the instance check works. It is also robust to Union and Any.
:param inst:
:param typ:
:return:
"""
if typ is Any:
return True
if is_typevar(typ):
if hasattr(typ, '__constraints__') and typ.__constraints__ is not None:
typs = get_args(typ, evaluate=True)
return any(robust_isinstance(inst, t) for t in typs)
elif hasattr(typ, '__bound__') and typ.__bound__ is not None:
return robust_isinstance(inst, typ.__bound__)
else:
# a raw TypeVar means 'anything'
return True
else:
if is_union_type(typ):
typs = get_args(typ, evaluate=True)
return any(robust_isinstance(inst, t) for t in typs)
else:
return isinstance(inst, get_base_generic_type(typ)) | [
"def",
"robust_isinstance",
"(",
"inst",
",",
"typ",
")",
"->",
"bool",
":",
"if",
"typ",
"is",
"Any",
":",
"return",
"True",
"if",
"is_typevar",
"(",
"typ",
")",
":",
"if",
"hasattr",
"(",
"typ",
",",
"'__constraints__'",
")",
"and",
"typ",
".",
"__... | Similar to isinstance, but if 'typ' is a parametrized generic Type, it is first transformed into its base generic
class so that the instance check works. It is also robust to Union and Any.
:param inst:
:param typ:
:return: | [
"Similar",
"to",
"isinstance",
"but",
"if",
"typ",
"is",
"a",
"parametrized",
"generic",
"Type",
"it",
"is",
"first",
"transformed",
"into",
"its",
"base",
"generic",
"class",
"so",
"that",
"the",
"instance",
"check",
"works",
".",
"It",
"is",
"also",
"rob... | 344b37e1151e8d4e7c2ee49ae09d6568715ae64e | https://github.com/smarie/python-parsyfiles/blob/344b37e1151e8d4e7c2ee49ae09d6568715ae64e/parsyfiles/type_inspection_tools.py#L90-L115 | train | 54,909 |
smarie/python-parsyfiles | parsyfiles/type_inspection_tools.py | eval_forward_ref | def eval_forward_ref(typ: _ForwardRef):
"""
Climbs the current stack until the given Forward reference has been resolved, or raises an InvalidForwardRefError
:param typ: the forward reference to resolve
:return:
"""
for frame in stack():
m = getmodule(frame[0])
m_name = m.__name__ if m is not None else '<unknown>'
if m_name.startswith('parsyfiles.tests') or not m_name.startswith('parsyfiles'):
try:
# print("File {}:{}".format(frame.filename, frame.lineno))
return typ._eval_type(frame[0].f_globals, frame[0].f_locals)
except NameError:
pass
raise InvalidForwardRefError(typ) | python | def eval_forward_ref(typ: _ForwardRef):
"""
Climbs the current stack until the given Forward reference has been resolved, or raises an InvalidForwardRefError
:param typ: the forward reference to resolve
:return:
"""
for frame in stack():
m = getmodule(frame[0])
m_name = m.__name__ if m is not None else '<unknown>'
if m_name.startswith('parsyfiles.tests') or not m_name.startswith('parsyfiles'):
try:
# print("File {}:{}".format(frame.filename, frame.lineno))
return typ._eval_type(frame[0].f_globals, frame[0].f_locals)
except NameError:
pass
raise InvalidForwardRefError(typ) | [
"def",
"eval_forward_ref",
"(",
"typ",
":",
"_ForwardRef",
")",
":",
"for",
"frame",
"in",
"stack",
"(",
")",
":",
"m",
"=",
"getmodule",
"(",
"frame",
"[",
"0",
"]",
")",
"m_name",
"=",
"m",
".",
"__name__",
"if",
"m",
"is",
"not",
"None",
"else",... | Climbs the current stack until the given Forward reference has been resolved, or raises an InvalidForwardRefError
:param typ: the forward reference to resolve
:return: | [
"Climbs",
"the",
"current",
"stack",
"until",
"the",
"given",
"Forward",
"reference",
"has",
"been",
"resolved",
"or",
"raises",
"an",
"InvalidForwardRefError"
] | 344b37e1151e8d4e7c2ee49ae09d6568715ae64e | https://github.com/smarie/python-parsyfiles/blob/344b37e1151e8d4e7c2ee49ae09d6568715ae64e/parsyfiles/type_inspection_tools.py#L330-L347 | train | 54,910 |
smarie/python-parsyfiles | parsyfiles/type_inspection_tools.py | is_valid_pep484_type_hint | def is_valid_pep484_type_hint(typ_hint, allow_forward_refs: bool = False):
"""
Returns True if the provided type is a valid PEP484 type hint, False otherwise.
Note: string type hints (forward references) are not supported by default, since callers of this function in
parsyfiles lib actually require them to be resolved already.
:param typ_hint:
:param allow_forward_refs:
:return:
"""
# most common case first, to be faster
try:
if isinstance(typ_hint, type):
return True
except:
pass
# optionally, check forward reference
try:
if allow_forward_refs and is_forward_ref(typ_hint):
return True
except:
pass
# finally check unions and typevars
try:
return is_union_type(typ_hint) or is_typevar(typ_hint)
except:
return False | python | def is_valid_pep484_type_hint(typ_hint, allow_forward_refs: bool = False):
"""
Returns True if the provided type is a valid PEP484 type hint, False otherwise.
Note: string type hints (forward references) are not supported by default, since callers of this function in
parsyfiles lib actually require them to be resolved already.
:param typ_hint:
:param allow_forward_refs:
:return:
"""
# most common case first, to be faster
try:
if isinstance(typ_hint, type):
return True
except:
pass
# optionally, check forward reference
try:
if allow_forward_refs and is_forward_ref(typ_hint):
return True
except:
pass
# finally check unions and typevars
try:
return is_union_type(typ_hint) or is_typevar(typ_hint)
except:
return False | [
"def",
"is_valid_pep484_type_hint",
"(",
"typ_hint",
",",
"allow_forward_refs",
":",
"bool",
"=",
"False",
")",
":",
"# most common case first, to be faster",
"try",
":",
"if",
"isinstance",
"(",
"typ_hint",
",",
"type",
")",
":",
"return",
"True",
"except",
":",
... | Returns True if the provided type is a valid PEP484 type hint, False otherwise.
Note: string type hints (forward references) are not supported by default, since callers of this function in
parsyfiles lib actually require them to be resolved already.
:param typ_hint:
:param allow_forward_refs:
:return: | [
"Returns",
"True",
"if",
"the",
"provided",
"type",
"is",
"a",
"valid",
"PEP484",
"type",
"hint",
"False",
"otherwise",
"."
] | 344b37e1151e8d4e7c2ee49ae09d6568715ae64e | https://github.com/smarie/python-parsyfiles/blob/344b37e1151e8d4e7c2ee49ae09d6568715ae64e/parsyfiles/type_inspection_tools.py#L363-L392 | train | 54,911 |
smarie/python-parsyfiles | parsyfiles/type_inspection_tools.py | is_pep484_nonable | def is_pep484_nonable(typ):
"""
Checks if a given type is nonable, meaning that it explicitly or implicitly declares a Union with NoneType.
Nested TypeVars and Unions are supported.
:param typ:
:return:
"""
# TODO rely on typing_inspect if there is an answer to https://github.com/ilevkivskyi/typing_inspect/issues/14
if typ is type(None):
return True
elif is_typevar(typ) or is_union_type(typ):
return any(is_pep484_nonable(tt) for tt in get_alternate_types_resolving_forwardref_union_and_typevar(typ))
else:
return False | python | def is_pep484_nonable(typ):
"""
Checks if a given type is nonable, meaning that it explicitly or implicitly declares a Union with NoneType.
Nested TypeVars and Unions are supported.
:param typ:
:return:
"""
# TODO rely on typing_inspect if there is an answer to https://github.com/ilevkivskyi/typing_inspect/issues/14
if typ is type(None):
return True
elif is_typevar(typ) or is_union_type(typ):
return any(is_pep484_nonable(tt) for tt in get_alternate_types_resolving_forwardref_union_and_typevar(typ))
else:
return False | [
"def",
"is_pep484_nonable",
"(",
"typ",
")",
":",
"# TODO rely on typing_inspect if there is an answer to https://github.com/ilevkivskyi/typing_inspect/issues/14",
"if",
"typ",
"is",
"type",
"(",
"None",
")",
":",
"return",
"True",
"elif",
"is_typevar",
"(",
"typ",
")",
"... | Checks if a given type is nonable, meaning that it explicitly or implicitly declares a Union with NoneType.
Nested TypeVars and Unions are supported.
:param typ:
:return: | [
"Checks",
"if",
"a",
"given",
"type",
"is",
"nonable",
"meaning",
"that",
"it",
"explicitly",
"or",
"implicitly",
"declares",
"a",
"Union",
"with",
"NoneType",
".",
"Nested",
"TypeVars",
"and",
"Unions",
"are",
"supported",
"."
] | 344b37e1151e8d4e7c2ee49ae09d6568715ae64e | https://github.com/smarie/python-parsyfiles/blob/344b37e1151e8d4e7c2ee49ae09d6568715ae64e/parsyfiles/type_inspection_tools.py#L395-L409 | train | 54,912 |
smarie/python-parsyfiles | parsyfiles/type_inspection_tools.py | InvalidPEP484TypeHint.create_for_collection_items | def create_for_collection_items(item_type, hint):
"""
Helper method for collection items
:param item_type:
:return:
"""
# this leads to infinite loops
# try:
# prt_type = get_pretty_type_str(item_type)
# except:
# prt_type = str(item_type)
return TypeInformationRequiredError("Cannot parse object of type {t} as a collection: this type has no valid "
"PEP484 type hint about its contents: found {h}. Please use a standard "
"PEP484 declaration such as Dict[str, Foo] or List[Foo]"
"".format(t=str(item_type), h=hint)) | python | def create_for_collection_items(item_type, hint):
"""
Helper method for collection items
:param item_type:
:return:
"""
# this leads to infinite loops
# try:
# prt_type = get_pretty_type_str(item_type)
# except:
# prt_type = str(item_type)
return TypeInformationRequiredError("Cannot parse object of type {t} as a collection: this type has no valid "
"PEP484 type hint about its contents: found {h}. Please use a standard "
"PEP484 declaration such as Dict[str, Foo] or List[Foo]"
"".format(t=str(item_type), h=hint)) | [
"def",
"create_for_collection_items",
"(",
"item_type",
",",
"hint",
")",
":",
"# this leads to infinite loops",
"# try:",
"# prt_type = get_pretty_type_str(item_type)",
"# except:",
"# prt_type = str(item_type)",
"return",
"TypeInformationRequiredError",
"(",
"\"Cannot parse... | Helper method for collection items
:param item_type:
:return: | [
"Helper",
"method",
"for",
"collection",
"items"
] | 344b37e1151e8d4e7c2ee49ae09d6568715ae64e | https://github.com/smarie/python-parsyfiles/blob/344b37e1151e8d4e7c2ee49ae09d6568715ae64e/parsyfiles/type_inspection_tools.py#L691-L706 | train | 54,913 |
smarie/python-parsyfiles | parsyfiles/type_inspection_tools.py | InvalidPEP484TypeHint.create_for_object_attributes | def create_for_object_attributes(item_type, faulty_attribute_name: str, hint):
"""
Helper method for constructor attributes
:param item_type:
:return:
"""
# this leads to infinite loops
# try:
# prt_type = get_pretty_type_str(item_type)
# except:
# prt_type = str(item_type)
return TypeInformationRequiredError("Cannot create instances of type {t}: constructor attribute '{a}' has an"
" invalid PEP484 type hint: {h}.".format(t=str(item_type),
a=faulty_attribute_name, h=hint)) | python | def create_for_object_attributes(item_type, faulty_attribute_name: str, hint):
"""
Helper method for constructor attributes
:param item_type:
:return:
"""
# this leads to infinite loops
# try:
# prt_type = get_pretty_type_str(item_type)
# except:
# prt_type = str(item_type)
return TypeInformationRequiredError("Cannot create instances of type {t}: constructor attribute '{a}' has an"
" invalid PEP484 type hint: {h}.".format(t=str(item_type),
a=faulty_attribute_name, h=hint)) | [
"def",
"create_for_object_attributes",
"(",
"item_type",
",",
"faulty_attribute_name",
":",
"str",
",",
"hint",
")",
":",
"# this leads to infinite loops",
"# try:",
"# prt_type = get_pretty_type_str(item_type)",
"# except:",
"# prt_type = str(item_type)",
"return",
"Type... | Helper method for constructor attributes
:param item_type:
:return: | [
"Helper",
"method",
"for",
"constructor",
"attributes"
] | 344b37e1151e8d4e7c2ee49ae09d6568715ae64e | https://github.com/smarie/python-parsyfiles/blob/344b37e1151e8d4e7c2ee49ae09d6568715ae64e/parsyfiles/type_inspection_tools.py#L709-L723 | train | 54,914 |
martinrusev/solid-python | solidpy/handlers/django.py | SolidDjangoMiddleware.exception_class | def exception_class(self, exception):
"""Return a name representing the class of an exception."""
cls = type(exception)
if cls.__module__ == 'exceptions': # Built-in exception.
return cls.__name__
return "%s.%s" % (cls.__module__, cls.__name__) | python | def exception_class(self, exception):
"""Return a name representing the class of an exception."""
cls = type(exception)
if cls.__module__ == 'exceptions': # Built-in exception.
return cls.__name__
return "%s.%s" % (cls.__module__, cls.__name__) | [
"def",
"exception_class",
"(",
"self",
",",
"exception",
")",
":",
"cls",
"=",
"type",
"(",
"exception",
")",
"if",
"cls",
".",
"__module__",
"==",
"'exceptions'",
":",
"# Built-in exception.",
"return",
"cls",
".",
"__name__",
"return",
"\"%s.%s\"",
"%",
"(... | Return a name representing the class of an exception. | [
"Return",
"a",
"name",
"representing",
"the",
"class",
"of",
"an",
"exception",
"."
] | c5c39ad43c19e6746ea0297e0d440a2fccfb25ed | https://github.com/martinrusev/solid-python/blob/c5c39ad43c19e6746ea0297e0d440a2fccfb25ed/solidpy/handlers/django.py#L27-L33 | train | 54,915 |
martinrusev/solid-python | solidpy/handlers/django.py | SolidDjangoMiddleware.request_info | def request_info(self, request):
"""
Return a dictionary of information for a given request.
This will be run once for every request.
"""
# We have to re-resolve the request path here, because the information
# is not stored on the request.
view, args, kwargs = resolve(request.path)
for i, arg in enumerate(args):
kwargs[i] = arg
parameters = {}
parameters.update(kwargs)
parameters.update(request.POST.items())
environ = request.META
return {
"session": dict(request.session),
'cookies': dict(request.COOKIES),
'headers': dict(get_headers(environ)),
'env': dict(get_environ(environ)),
"remote_ip": request.META["REMOTE_ADDR"],
"parameters": parameters,
"action": view.__name__,
"application": view.__module__,
"method": request.method,
"url": request.build_absolute_uri()
} | python | def request_info(self, request):
"""
Return a dictionary of information for a given request.
This will be run once for every request.
"""
# We have to re-resolve the request path here, because the information
# is not stored on the request.
view, args, kwargs = resolve(request.path)
for i, arg in enumerate(args):
kwargs[i] = arg
parameters = {}
parameters.update(kwargs)
parameters.update(request.POST.items())
environ = request.META
return {
"session": dict(request.session),
'cookies': dict(request.COOKIES),
'headers': dict(get_headers(environ)),
'env': dict(get_environ(environ)),
"remote_ip": request.META["REMOTE_ADDR"],
"parameters": parameters,
"action": view.__name__,
"application": view.__module__,
"method": request.method,
"url": request.build_absolute_uri()
} | [
"def",
"request_info",
"(",
"self",
",",
"request",
")",
":",
"# We have to re-resolve the request path here, because the information",
"# is not stored on the request.",
"view",
",",
"args",
",",
"kwargs",
"=",
"resolve",
"(",
"request",
".",
"path",
")",
"for",
"i",
... | Return a dictionary of information for a given request.
This will be run once for every request. | [
"Return",
"a",
"dictionary",
"of",
"information",
"for",
"a",
"given",
"request",
"."
] | c5c39ad43c19e6746ea0297e0d440a2fccfb25ed | https://github.com/martinrusev/solid-python/blob/c5c39ad43c19e6746ea0297e0d440a2fccfb25ed/solidpy/handlers/django.py#L35-L66 | train | 54,916 |
bioidiap/bob.ip.facedetect | bob/ip/facedetect/train/Bootstrap.py | Bootstrap._save | def _save(self, hdf5, model, positives, negatives):
"""Saves the given intermediate state of the bootstrapping to file."""
# write the model and the training set indices to the given HDF5 file
hdf5.set("PositiveIndices", sorted(list(positives)))
hdf5.set("NegativeIndices", sorted(list(negatives)))
hdf5.create_group("Model")
hdf5.cd("Model")
model.save(hdf5)
del hdf5 | python | def _save(self, hdf5, model, positives, negatives):
"""Saves the given intermediate state of the bootstrapping to file."""
# write the model and the training set indices to the given HDF5 file
hdf5.set("PositiveIndices", sorted(list(positives)))
hdf5.set("NegativeIndices", sorted(list(negatives)))
hdf5.create_group("Model")
hdf5.cd("Model")
model.save(hdf5)
del hdf5 | [
"def",
"_save",
"(",
"self",
",",
"hdf5",
",",
"model",
",",
"positives",
",",
"negatives",
")",
":",
"# write the model and the training set indices to the given HDF5 file",
"hdf5",
".",
"set",
"(",
"\"PositiveIndices\"",
",",
"sorted",
"(",
"list",
"(",
"positives... | Saves the given intermediate state of the bootstrapping to file. | [
"Saves",
"the",
"given",
"intermediate",
"state",
"of",
"the",
"bootstrapping",
"to",
"file",
"."
] | 601da5141ca7302ad36424d1421b33190ba46779 | https://github.com/bioidiap/bob.ip.facedetect/blob/601da5141ca7302ad36424d1421b33190ba46779/bob/ip/facedetect/train/Bootstrap.py#L121-L129 | train | 54,917 |
bioidiap/bob.ip.facedetect | bob/ip/facedetect/train/Bootstrap.py | Bootstrap._load | def _load(self, hdf5):
"""Loads the intermediate state of the bootstrapping from file."""
positives = set(hdf5.get("PositiveIndices"))
negatives = set(hdf5.get("NegativeIndices"))
hdf5.cd("Model")
model = bob.learn.boosting.BoostedMachine(hdf5)
return model, positives, negatives | python | def _load(self, hdf5):
"""Loads the intermediate state of the bootstrapping from file."""
positives = set(hdf5.get("PositiveIndices"))
negatives = set(hdf5.get("NegativeIndices"))
hdf5.cd("Model")
model = bob.learn.boosting.BoostedMachine(hdf5)
return model, positives, negatives | [
"def",
"_load",
"(",
"self",
",",
"hdf5",
")",
":",
"positives",
"=",
"set",
"(",
"hdf5",
".",
"get",
"(",
"\"PositiveIndices\"",
")",
")",
"negatives",
"=",
"set",
"(",
"hdf5",
".",
"get",
"(",
"\"NegativeIndices\"",
")",
")",
"hdf5",
".",
"cd",
"("... | Loads the intermediate state of the bootstrapping from file. | [
"Loads",
"the",
"intermediate",
"state",
"of",
"the",
"bootstrapping",
"from",
"file",
"."
] | 601da5141ca7302ad36424d1421b33190ba46779 | https://github.com/bioidiap/bob.ip.facedetect/blob/601da5141ca7302ad36424d1421b33190ba46779/bob/ip/facedetect/train/Bootstrap.py#L132-L138 | train | 54,918 |
bniemczyk/automata | automata/VM.py | CodeBlock.undelay | def undelay(self):
'''resolves all delayed arguments'''
i = 0
while i < len(self):
op = self[i]
i += 1
if hasattr(op, 'arg1'):
if isinstance(op.arg1,DelayedArg):
op.arg1 = op.arg1.resolve()
if isinstance(op.arg1,CodeBlock):
op.arg1.undelay() | python | def undelay(self):
'''resolves all delayed arguments'''
i = 0
while i < len(self):
op = self[i]
i += 1
if hasattr(op, 'arg1'):
if isinstance(op.arg1,DelayedArg):
op.arg1 = op.arg1.resolve()
if isinstance(op.arg1,CodeBlock):
op.arg1.undelay() | [
"def",
"undelay",
"(",
"self",
")",
":",
"i",
"=",
"0",
"while",
"i",
"<",
"len",
"(",
"self",
")",
":",
"op",
"=",
"self",
"[",
"i",
"]",
"i",
"+=",
"1",
"if",
"hasattr",
"(",
"op",
",",
"'arg1'",
")",
":",
"if",
"isinstance",
"(",
"op",
"... | resolves all delayed arguments | [
"resolves",
"all",
"delayed",
"arguments"
] | b4e21ba8b881f2cb1a07a813a4011209a3f1e017 | https://github.com/bniemczyk/automata/blob/b4e21ba8b881f2cb1a07a813a4011209a3f1e017/automata/VM.py#L126-L136 | train | 54,919 |
liam-middlebrook/csh_ldap | csh_ldap/__init__.py | CSHLDAP.get_directorship_heads | def get_directorship_heads(self, val):
"""Get the head of a directorship
Arguments:
val -- the cn of the directorship
"""
__ldap_group_ou__ = "cn=groups,cn=accounts,dc=csh,dc=rit,dc=edu"
res = self.__con__.search_s(
__ldap_group_ou__,
ldap.SCOPE_SUBTREE,
"(cn=eboard-%s)" % val,
['member'])
ret = []
for member in res[0][1]['member']:
try:
ret.append(member.decode('utf-8'))
except UnicodeDecodeError:
ret.append(member)
except KeyError:
continue
return [CSHMember(self,
dn.split('=')[1].split(',')[0],
True)
for dn in ret] | python | def get_directorship_heads(self, val):
"""Get the head of a directorship
Arguments:
val -- the cn of the directorship
"""
__ldap_group_ou__ = "cn=groups,cn=accounts,dc=csh,dc=rit,dc=edu"
res = self.__con__.search_s(
__ldap_group_ou__,
ldap.SCOPE_SUBTREE,
"(cn=eboard-%s)" % val,
['member'])
ret = []
for member in res[0][1]['member']:
try:
ret.append(member.decode('utf-8'))
except UnicodeDecodeError:
ret.append(member)
except KeyError:
continue
return [CSHMember(self,
dn.split('=')[1].split(',')[0],
True)
for dn in ret] | [
"def",
"get_directorship_heads",
"(",
"self",
",",
"val",
")",
":",
"__ldap_group_ou__",
"=",
"\"cn=groups,cn=accounts,dc=csh,dc=rit,dc=edu\"",
"res",
"=",
"self",
".",
"__con__",
".",
"search_s",
"(",
"__ldap_group_ou__",
",",
"ldap",
".",
"SCOPE_SUBTREE",
",",
"\"... | Get the head of a directorship
Arguments:
val -- the cn of the directorship | [
"Get",
"the",
"head",
"of",
"a",
"directorship"
] | 90bd334a20e13c03af07bce4f104ad96baf620e4 | https://github.com/liam-middlebrook/csh_ldap/blob/90bd334a20e13c03af07bce4f104ad96baf620e4/csh_ldap/__init__.py#L108-L135 | train | 54,920 |
liam-middlebrook/csh_ldap | csh_ldap/__init__.py | CSHLDAP.enqueue_mod | def enqueue_mod(self, dn, mod):
"""Enqueue a LDAP modification.
Arguments:
dn -- the distinguished name of the object to modify
mod -- an ldap modfication entry to enqueue
"""
# mark for update
if dn not in self.__pending_mod_dn__:
self.__pending_mod_dn__.append(dn)
self.__mod_queue__[dn] = []
self.__mod_queue__[dn].append(mod) | python | def enqueue_mod(self, dn, mod):
"""Enqueue a LDAP modification.
Arguments:
dn -- the distinguished name of the object to modify
mod -- an ldap modfication entry to enqueue
"""
# mark for update
if dn not in self.__pending_mod_dn__:
self.__pending_mod_dn__.append(dn)
self.__mod_queue__[dn] = []
self.__mod_queue__[dn].append(mod) | [
"def",
"enqueue_mod",
"(",
"self",
",",
"dn",
",",
"mod",
")",
":",
"# mark for update",
"if",
"dn",
"not",
"in",
"self",
".",
"__pending_mod_dn__",
":",
"self",
".",
"__pending_mod_dn__",
".",
"append",
"(",
"dn",
")",
"self",
".",
"__mod_queue__",
"[",
... | Enqueue a LDAP modification.
Arguments:
dn -- the distinguished name of the object to modify
mod -- an ldap modfication entry to enqueue | [
"Enqueue",
"a",
"LDAP",
"modification",
"."
] | 90bd334a20e13c03af07bce4f104ad96baf620e4 | https://github.com/liam-middlebrook/csh_ldap/blob/90bd334a20e13c03af07bce4f104ad96baf620e4/csh_ldap/__init__.py#L137-L149 | train | 54,921 |
liam-middlebrook/csh_ldap | csh_ldap/__init__.py | CSHLDAP.flush_mod | def flush_mod(self):
"""Flush all pending LDAP modifications."""
for dn in self.__pending_mod_dn__:
try:
if self.__ro__:
for mod in self.__mod_queue__[dn]:
if mod[0] == ldap.MOD_DELETE:
mod_str = "DELETE"
elif mod[0] == ldap.MOD_ADD:
mod_str = "ADD"
else:
mod_str = "REPLACE"
print("{} VALUE {} = {} FOR {}".format(mod_str,
mod[1],
mod[2],
dn))
else:
self.__con__.modify_s(dn, self.__mod_queue__[dn])
except ldap.TYPE_OR_VALUE_EXISTS:
print("Error! Conflicting Batch Modification: %s"
% str(self.__mod_queue__[dn]))
continue
except ldap.NO_SUCH_ATTRIBUTE:
print("Error! Conflicting Batch Modification: %s"
% str(self.__mod_queue__[dn]))
continue
self.__mod_queue__[dn] = None
self.__pending_mod_dn__ = [] | python | def flush_mod(self):
"""Flush all pending LDAP modifications."""
for dn in self.__pending_mod_dn__:
try:
if self.__ro__:
for mod in self.__mod_queue__[dn]:
if mod[0] == ldap.MOD_DELETE:
mod_str = "DELETE"
elif mod[0] == ldap.MOD_ADD:
mod_str = "ADD"
else:
mod_str = "REPLACE"
print("{} VALUE {} = {} FOR {}".format(mod_str,
mod[1],
mod[2],
dn))
else:
self.__con__.modify_s(dn, self.__mod_queue__[dn])
except ldap.TYPE_OR_VALUE_EXISTS:
print("Error! Conflicting Batch Modification: %s"
% str(self.__mod_queue__[dn]))
continue
except ldap.NO_SUCH_ATTRIBUTE:
print("Error! Conflicting Batch Modification: %s"
% str(self.__mod_queue__[dn]))
continue
self.__mod_queue__[dn] = None
self.__pending_mod_dn__ = [] | [
"def",
"flush_mod",
"(",
"self",
")",
":",
"for",
"dn",
"in",
"self",
".",
"__pending_mod_dn__",
":",
"try",
":",
"if",
"self",
".",
"__ro__",
":",
"for",
"mod",
"in",
"self",
".",
"__mod_queue__",
"[",
"dn",
"]",
":",
"if",
"mod",
"[",
"0",
"]",
... | Flush all pending LDAP modifications. | [
"Flush",
"all",
"pending",
"LDAP",
"modifications",
"."
] | 90bd334a20e13c03af07bce4f104ad96baf620e4 | https://github.com/liam-middlebrook/csh_ldap/blob/90bd334a20e13c03af07bce4f104ad96baf620e4/csh_ldap/__init__.py#L151-L178 | train | 54,922 |
davidwtbuxton/notrequests | notrequests.py | detect_encoding | def detect_encoding(value):
"""Returns the character encoding for a JSON string."""
# https://tools.ietf.org/html/rfc4627#section-3
if six.PY2:
null_pattern = tuple(bool(ord(char)) for char in value[:4])
else:
null_pattern = tuple(bool(char) for char in value[:4])
encodings = {
# Zero is a null-byte, 1 is anything else.
(0, 0, 0, 1): 'utf-32-be',
(0, 1, 0, 1): 'utf-16-be',
(1, 0, 0, 0): 'utf-32-le',
(1, 0, 1, 0): 'utf-16-le',
}
return encodings.get(null_pattern, 'utf-8') | python | def detect_encoding(value):
"""Returns the character encoding for a JSON string."""
# https://tools.ietf.org/html/rfc4627#section-3
if six.PY2:
null_pattern = tuple(bool(ord(char)) for char in value[:4])
else:
null_pattern = tuple(bool(char) for char in value[:4])
encodings = {
# Zero is a null-byte, 1 is anything else.
(0, 0, 0, 1): 'utf-32-be',
(0, 1, 0, 1): 'utf-16-be',
(1, 0, 0, 0): 'utf-32-le',
(1, 0, 1, 0): 'utf-16-le',
}
return encodings.get(null_pattern, 'utf-8') | [
"def",
"detect_encoding",
"(",
"value",
")",
":",
"# https://tools.ietf.org/html/rfc4627#section-3",
"if",
"six",
".",
"PY2",
":",
"null_pattern",
"=",
"tuple",
"(",
"bool",
"(",
"ord",
"(",
"char",
")",
")",
"for",
"char",
"in",
"value",
"[",
":",
"4",
"]... | Returns the character encoding for a JSON string. | [
"Returns",
"the",
"character",
"encoding",
"for",
"a",
"JSON",
"string",
"."
] | e48ee6107a58c2f373c33f78e3302608edeba7f3 | https://github.com/davidwtbuxton/notrequests/blob/e48ee6107a58c2f373c33f78e3302608edeba7f3/notrequests.py#L193-L209 | train | 54,923 |
davidwtbuxton/notrequests | notrequests.py | _merge_params | def _merge_params(url, params):
"""Merge and encode query parameters with an URL."""
if isinstance(params, dict):
params = list(params.items())
scheme, netloc, path, query, fragment = urllib.parse.urlsplit(url)
url_params = urllib.parse.parse_qsl(query, keep_blank_values=True)
url_params.extend(params)
query = _encode_data(url_params)
return urllib.parse.urlunsplit((scheme, netloc, path, query, fragment)) | python | def _merge_params(url, params):
"""Merge and encode query parameters with an URL."""
if isinstance(params, dict):
params = list(params.items())
scheme, netloc, path, query, fragment = urllib.parse.urlsplit(url)
url_params = urllib.parse.parse_qsl(query, keep_blank_values=True)
url_params.extend(params)
query = _encode_data(url_params)
return urllib.parse.urlunsplit((scheme, netloc, path, query, fragment)) | [
"def",
"_merge_params",
"(",
"url",
",",
"params",
")",
":",
"if",
"isinstance",
"(",
"params",
",",
"dict",
")",
":",
"params",
"=",
"list",
"(",
"params",
".",
"items",
"(",
")",
")",
"scheme",
",",
"netloc",
",",
"path",
",",
"query",
",",
"frag... | Merge and encode query parameters with an URL. | [
"Merge",
"and",
"encode",
"query",
"parameters",
"with",
"an",
"URL",
"."
] | e48ee6107a58c2f373c33f78e3302608edeba7f3 | https://github.com/davidwtbuxton/notrequests/blob/e48ee6107a58c2f373c33f78e3302608edeba7f3/notrequests.py#L332-L343 | train | 54,924 |
davidwtbuxton/notrequests | notrequests.py | Response.json | def json(self, **kwargs):
"""Decodes response as JSON."""
encoding = detect_encoding(self.content[:4])
value = self.content.decode(encoding)
return simplejson.loads(value, **kwargs) | python | def json(self, **kwargs):
"""Decodes response as JSON."""
encoding = detect_encoding(self.content[:4])
value = self.content.decode(encoding)
return simplejson.loads(value, **kwargs) | [
"def",
"json",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"encoding",
"=",
"detect_encoding",
"(",
"self",
".",
"content",
"[",
":",
"4",
"]",
")",
"value",
"=",
"self",
".",
"content",
".",
"decode",
"(",
"encoding",
")",
"return",
"simplejson"... | Decodes response as JSON. | [
"Decodes",
"response",
"as",
"JSON",
"."
] | e48ee6107a58c2f373c33f78e3302608edeba7f3 | https://github.com/davidwtbuxton/notrequests/blob/e48ee6107a58c2f373c33f78e3302608edeba7f3/notrequests.py#L121-L126 | train | 54,925 |
davidwtbuxton/notrequests | notrequests.py | Response.raise_for_status | def raise_for_status(self):
"""Raises HTTPError if the request got an error."""
if 400 <= self.status_code < 600:
message = 'Error %s for %s' % (self.status_code, self.url)
raise HTTPError(message) | python | def raise_for_status(self):
"""Raises HTTPError if the request got an error."""
if 400 <= self.status_code < 600:
message = 'Error %s for %s' % (self.status_code, self.url)
raise HTTPError(message) | [
"def",
"raise_for_status",
"(",
"self",
")",
":",
"if",
"400",
"<=",
"self",
".",
"status_code",
"<",
"600",
":",
"message",
"=",
"'Error %s for %s'",
"%",
"(",
"self",
".",
"status_code",
",",
"self",
".",
"url",
")",
"raise",
"HTTPError",
"(",
"message... | Raises HTTPError if the request got an error. | [
"Raises",
"HTTPError",
"if",
"the",
"request",
"got",
"an",
"error",
"."
] | e48ee6107a58c2f373c33f78e3302608edeba7f3 | https://github.com/davidwtbuxton/notrequests/blob/e48ee6107a58c2f373c33f78e3302608edeba7f3/notrequests.py#L173-L177 | train | 54,926 |
wearpants/instrument | instrument/output/_numpy.py | NumpyMetric.metric | def metric(cls, name, count, elapsed):
"""A metric function that buffers through numpy
:arg str name: name of the metric
:arg int count: number of items
:arg float elapsed: time in seconds
"""
if name is None:
warnings.warn("Ignoring unnamed metric", stacklevel=3)
return
with cls.lock:
# register with atexit on first call
if cls.dump_atexit and not cls.instances:
atexit.register(cls.dump)
try:
self = cls.instances[name]
except KeyError:
self = cls.instances[name] = cls(name)
self.temp.write(self.struct.pack(count, elapsed)) | python | def metric(cls, name, count, elapsed):
"""A metric function that buffers through numpy
:arg str name: name of the metric
:arg int count: number of items
:arg float elapsed: time in seconds
"""
if name is None:
warnings.warn("Ignoring unnamed metric", stacklevel=3)
return
with cls.lock:
# register with atexit on first call
if cls.dump_atexit and not cls.instances:
atexit.register(cls.dump)
try:
self = cls.instances[name]
except KeyError:
self = cls.instances[name] = cls(name)
self.temp.write(self.struct.pack(count, elapsed)) | [
"def",
"metric",
"(",
"cls",
",",
"name",
",",
"count",
",",
"elapsed",
")",
":",
"if",
"name",
"is",
"None",
":",
"warnings",
".",
"warn",
"(",
"\"Ignoring unnamed metric\"",
",",
"stacklevel",
"=",
"3",
")",
"return",
"with",
"cls",
".",
"lock",
":",... | A metric function that buffers through numpy
:arg str name: name of the metric
:arg int count: number of items
:arg float elapsed: time in seconds | [
"A",
"metric",
"function",
"that",
"buffers",
"through",
"numpy"
] | a0f6103574ab58a82361a951e5e56b69aedfe294 | https://github.com/wearpants/instrument/blob/a0f6103574ab58a82361a951e5e56b69aedfe294/instrument/output/_numpy.py#L38-L60 | train | 54,927 |
wearpants/instrument | instrument/output/_numpy.py | NumpyMetric._dump | def _dump(self):
"""dump data for an individual metric. For internal use only."""
try:
self.temp.seek(0) # seek to beginning
arr = np.fromfile(self.temp, self.dtype)
self.count_arr = arr['count']
self.elapsed_arr = arr['elapsed']
if self.calc_stats:
# calculate mean & standard deviation
self.count_mean = np.mean(self.count_arr)
self.count_std = np.std(self.count_arr)
self.elapsed_mean = np.mean(self.elapsed_arr)
self.elapsed_std = np.std(self.elapsed_arr)
self._output()
finally:
self.temp.close()
self._cleanup() | python | def _dump(self):
"""dump data for an individual metric. For internal use only."""
try:
self.temp.seek(0) # seek to beginning
arr = np.fromfile(self.temp, self.dtype)
self.count_arr = arr['count']
self.elapsed_arr = arr['elapsed']
if self.calc_stats:
# calculate mean & standard deviation
self.count_mean = np.mean(self.count_arr)
self.count_std = np.std(self.count_arr)
self.elapsed_mean = np.mean(self.elapsed_arr)
self.elapsed_std = np.std(self.elapsed_arr)
self._output()
finally:
self.temp.close()
self._cleanup() | [
"def",
"_dump",
"(",
"self",
")",
":",
"try",
":",
"self",
".",
"temp",
".",
"seek",
"(",
"0",
")",
"# seek to beginning",
"arr",
"=",
"np",
".",
"fromfile",
"(",
"self",
".",
"temp",
",",
"self",
".",
"dtype",
")",
"self",
".",
"count_arr",
"=",
... | dump data for an individual metric. For internal use only. | [
"dump",
"data",
"for",
"an",
"individual",
"metric",
".",
"For",
"internal",
"use",
"only",
"."
] | a0f6103574ab58a82361a951e5e56b69aedfe294 | https://github.com/wearpants/instrument/blob/a0f6103574ab58a82361a951e5e56b69aedfe294/instrument/output/_numpy.py#L76-L95 | train | 54,928 |
KvasirSecurity/kvasirapi-python | KvasirAPI/jsonrpc/vulns.py | Vulns.list | def list(self, host_rec=None, service_rec=None, hostfilter=None):
"""
Returns a list of vulnerabilities based on t_hosts.id or t_services.id.
If neither are set then statistical results are added
:param host_rec: db.t_hosts.id
:param service_rec: db.t_services.id
:param hostfilter: Valid hostfilter or None
:return: [(vulndata) ...] if host_rec or service_rec set
:return: [(vulndata, vuln_cnt, [vuln_ip, ...], [services ...]) ...] if nothing sent
"""
return self.send.vuln_list(host_rec, service_rec, hostfilter) | python | def list(self, host_rec=None, service_rec=None, hostfilter=None):
"""
Returns a list of vulnerabilities based on t_hosts.id or t_services.id.
If neither are set then statistical results are added
:param host_rec: db.t_hosts.id
:param service_rec: db.t_services.id
:param hostfilter: Valid hostfilter or None
:return: [(vulndata) ...] if host_rec or service_rec set
:return: [(vulndata, vuln_cnt, [vuln_ip, ...], [services ...]) ...] if nothing sent
"""
return self.send.vuln_list(host_rec, service_rec, hostfilter) | [
"def",
"list",
"(",
"self",
",",
"host_rec",
"=",
"None",
",",
"service_rec",
"=",
"None",
",",
"hostfilter",
"=",
"None",
")",
":",
"return",
"self",
".",
"send",
".",
"vuln_list",
"(",
"host_rec",
",",
"service_rec",
",",
"hostfilter",
")"
] | Returns a list of vulnerabilities based on t_hosts.id or t_services.id.
If neither are set then statistical results are added
:param host_rec: db.t_hosts.id
:param service_rec: db.t_services.id
:param hostfilter: Valid hostfilter or None
:return: [(vulndata) ...] if host_rec or service_rec set
:return: [(vulndata, vuln_cnt, [vuln_ip, ...], [services ...]) ...] if nothing sent | [
"Returns",
"a",
"list",
"of",
"vulnerabilities",
"based",
"on",
"t_hosts",
".",
"id",
"or",
"t_services",
".",
"id",
".",
"If",
"neither",
"are",
"set",
"then",
"statistical",
"results",
"are",
"added"
] | ec8c5818bd5913f3afd150f25eaec6e7cc732f4c | https://github.com/KvasirSecurity/kvasirapi-python/blob/ec8c5818bd5913f3afd150f25eaec6e7cc732f4c/KvasirAPI/jsonrpc/vulns.py#L20-L31 | train | 54,929 |
KvasirSecurity/kvasirapi-python | KvasirAPI/jsonrpc/vulns.py | Vulns.ip_info | def ip_info(self, vuln_name=None, vuln_id=None, ip_list_only=True, hostfilter=None):
"""
List of all IP Addresses with a vulnerability
:param vuln_name: t_vulndata.f_vulnid
:param vuln_id: t_vulndata.id
:param ip_list_only: IP List only (default) or rest of t_hosts fields
:param hostfilter: Valid hostfilter or none
:return: [(ip, hostname) ...] or [(ip, hostname, t_service_vulns.f_proof, t_service_vulns.f_status), ...]
"""
return self.send.vuln_ip_info(vuln_name, vuln_id, ip_list_only, hostfilter) | python | def ip_info(self, vuln_name=None, vuln_id=None, ip_list_only=True, hostfilter=None):
"""
List of all IP Addresses with a vulnerability
:param vuln_name: t_vulndata.f_vulnid
:param vuln_id: t_vulndata.id
:param ip_list_only: IP List only (default) or rest of t_hosts fields
:param hostfilter: Valid hostfilter or none
:return: [(ip, hostname) ...] or [(ip, hostname, t_service_vulns.f_proof, t_service_vulns.f_status), ...]
"""
return self.send.vuln_ip_info(vuln_name, vuln_id, ip_list_only, hostfilter) | [
"def",
"ip_info",
"(",
"self",
",",
"vuln_name",
"=",
"None",
",",
"vuln_id",
"=",
"None",
",",
"ip_list_only",
"=",
"True",
",",
"hostfilter",
"=",
"None",
")",
":",
"return",
"self",
".",
"send",
".",
"vuln_ip_info",
"(",
"vuln_name",
",",
"vuln_id",
... | List of all IP Addresses with a vulnerability
:param vuln_name: t_vulndata.f_vulnid
:param vuln_id: t_vulndata.id
:param ip_list_only: IP List only (default) or rest of t_hosts fields
:param hostfilter: Valid hostfilter or none
:return: [(ip, hostname) ...] or [(ip, hostname, t_service_vulns.f_proof, t_service_vulns.f_status), ...] | [
"List",
"of",
"all",
"IP",
"Addresses",
"with",
"a",
"vulnerability"
] | ec8c5818bd5913f3afd150f25eaec6e7cc732f4c | https://github.com/KvasirSecurity/kvasirapi-python/blob/ec8c5818bd5913f3afd150f25eaec6e7cc732f4c/KvasirAPI/jsonrpc/vulns.py#L43-L53 | train | 54,930 |
KvasirSecurity/kvasirapi-python | KvasirAPI/jsonrpc/vulns.py | Vulns.service_list | def service_list(self, vuln_name=None, vuln_id=None, hostfilter=None):
"""
Returns a dictionary of vulns with services and IP Addresses
:param vuln_name: t_vulndata.f_vulnid
:param vuln_id: t_vulndata.id
:param hostfilter: Valid hostfilter or none
:return: {'vuln-id': {'port': [ ip, hostname ]} ...} ...
"""
return self.send.vuln_service_list(vuln_name, vuln_id, hostfilter) | python | def service_list(self, vuln_name=None, vuln_id=None, hostfilter=None):
"""
Returns a dictionary of vulns with services and IP Addresses
:param vuln_name: t_vulndata.f_vulnid
:param vuln_id: t_vulndata.id
:param hostfilter: Valid hostfilter or none
:return: {'vuln-id': {'port': [ ip, hostname ]} ...} ...
"""
return self.send.vuln_service_list(vuln_name, vuln_id, hostfilter) | [
"def",
"service_list",
"(",
"self",
",",
"vuln_name",
"=",
"None",
",",
"vuln_id",
"=",
"None",
",",
"hostfilter",
"=",
"None",
")",
":",
"return",
"self",
".",
"send",
".",
"vuln_service_list",
"(",
"vuln_name",
",",
"vuln_id",
",",
"hostfilter",
")"
] | Returns a dictionary of vulns with services and IP Addresses
:param vuln_name: t_vulndata.f_vulnid
:param vuln_id: t_vulndata.id
:param hostfilter: Valid hostfilter or none
:return: {'vuln-id': {'port': [ ip, hostname ]} ...} ... | [
"Returns",
"a",
"dictionary",
"of",
"vulns",
"with",
"services",
"and",
"IP",
"Addresses"
] | ec8c5818bd5913f3afd150f25eaec6e7cc732f4c | https://github.com/KvasirSecurity/kvasirapi-python/blob/ec8c5818bd5913f3afd150f25eaec6e7cc732f4c/KvasirAPI/jsonrpc/vulns.py#L55-L64 | train | 54,931 |
AoiKuiyuyou/AoikImportUtil-Python | src/aoikimportutil/aoikimportutil.py | import_name | def import_name(mod_name):
"""Import a module by module name.
@param mod_name: module name.
"""
try:
mod_obj_old = sys.modules[mod_name]
except KeyError:
mod_obj_old = None
if mod_obj_old is not None:
return mod_obj_old
__import__(mod_name)
mod_obj = sys.modules[mod_name]
return mod_obj | python | def import_name(mod_name):
"""Import a module by module name.
@param mod_name: module name.
"""
try:
mod_obj_old = sys.modules[mod_name]
except KeyError:
mod_obj_old = None
if mod_obj_old is not None:
return mod_obj_old
__import__(mod_name)
mod_obj = sys.modules[mod_name]
return mod_obj | [
"def",
"import_name",
"(",
"mod_name",
")",
":",
"try",
":",
"mod_obj_old",
"=",
"sys",
".",
"modules",
"[",
"mod_name",
"]",
"except",
"KeyError",
":",
"mod_obj_old",
"=",
"None",
"if",
"mod_obj_old",
"is",
"not",
"None",
":",
"return",
"mod_obj_old",
"__... | Import a module by module name.
@param mod_name: module name. | [
"Import",
"a",
"module",
"by",
"module",
"name",
"."
] | c6711719f5190cec81c8f29b989fc7609175b403 | https://github.com/AoiKuiyuyou/AoikImportUtil-Python/blob/c6711719f5190cec81c8f29b989fc7609175b403/src/aoikimportutil/aoikimportutil.py#L68-L85 | train | 54,932 |
AoiKuiyuyou/AoikImportUtil-Python | src/aoikimportutil/aoikimportutil.py | import_path | def import_path(mod_path, mod_name):
"""Import a module by module file path.
@param mod_path: module file path.
@param mod_name: module name.
"""
mod_code = open(mod_path).read()
mod_obj = import_code(
mod_code=mod_code,
mod_name=mod_name,
)
if not hasattr(mod_obj, '__file__'):
mod_obj.__file__ = mod_path
return mod_obj | python | def import_path(mod_path, mod_name):
"""Import a module by module file path.
@param mod_path: module file path.
@param mod_name: module name.
"""
mod_code = open(mod_path).read()
mod_obj = import_code(
mod_code=mod_code,
mod_name=mod_name,
)
if not hasattr(mod_obj, '__file__'):
mod_obj.__file__ = mod_path
return mod_obj | [
"def",
"import_path",
"(",
"mod_path",
",",
"mod_name",
")",
":",
"mod_code",
"=",
"open",
"(",
"mod_path",
")",
".",
"read",
"(",
")",
"mod_obj",
"=",
"import_code",
"(",
"mod_code",
"=",
"mod_code",
",",
"mod_name",
"=",
"mod_name",
",",
")",
"if",
"... | Import a module by module file path.
@param mod_path: module file path.
@param mod_name: module name. | [
"Import",
"a",
"module",
"by",
"module",
"file",
"path",
"."
] | c6711719f5190cec81c8f29b989fc7609175b403 | https://github.com/AoiKuiyuyou/AoikImportUtil-Python/blob/c6711719f5190cec81c8f29b989fc7609175b403/src/aoikimportutil/aoikimportutil.py#L88-L105 | train | 54,933 |
AoiKuiyuyou/AoikImportUtil-Python | src/aoikimportutil/aoikimportutil.py | import_obj | def import_obj(
uri,
mod_name=None,
mod_attr_sep='::',
attr_chain_sep='.',
retn_mod=False,
):
"""Load an object from a module.
@param uri: an uri specifying which object to load.
An `uri` consists of two parts: module URI and attribute chain,
e.g. `a/b/c.py::x.y.z` or `a.b.c::x.y.z`
# Module URI
E.g. `a/b/c.py` or `a.b.c`.
Can be either a module name or a file path.
Whether it is a file path is determined by whether it ends with `.py`.
# Attribute chain
E.g. `x.y.z`.
@param mod_name: module name.
Must be given when `uri` specifies a module file path, not a module name.
@param mod_attr_sep: the separator between module name and attribute name.
@param attr_chain_sep: the separator between parts of attribute name.
@retn_mod: whether return module object.
"""
if mod_attr_sep is None:
mod_attr_sep = '::'
uri_parts = split_uri(uri=uri, mod_attr_sep=mod_attr_sep)
protocol, mod_uri, attr_chain = uri_parts
if protocol == 'py':
mod_obj = import_name(mod_uri)
else:
if not mod_name:
msg = (
'Argument `mod_name` must be given when loading by file path.'
)
raise ValueError(msg)
mod_obj = import_path(mod_uri, mod_name=mod_name)
if not attr_chain:
if retn_mod:
return mod_obj, None
else:
return mod_obj
if attr_chain_sep is None:
attr_chain_sep = '.'
attr_obj = get_attr_chain(
obj=mod_obj,
attr_chain=attr_chain,
sep=attr_chain_sep,
)
if retn_mod:
return mod_obj, attr_obj
else:
return attr_obj | python | def import_obj(
uri,
mod_name=None,
mod_attr_sep='::',
attr_chain_sep='.',
retn_mod=False,
):
"""Load an object from a module.
@param uri: an uri specifying which object to load.
An `uri` consists of two parts: module URI and attribute chain,
e.g. `a/b/c.py::x.y.z` or `a.b.c::x.y.z`
# Module URI
E.g. `a/b/c.py` or `a.b.c`.
Can be either a module name or a file path.
Whether it is a file path is determined by whether it ends with `.py`.
# Attribute chain
E.g. `x.y.z`.
@param mod_name: module name.
Must be given when `uri` specifies a module file path, not a module name.
@param mod_attr_sep: the separator between module name and attribute name.
@param attr_chain_sep: the separator between parts of attribute name.
@retn_mod: whether return module object.
"""
if mod_attr_sep is None:
mod_attr_sep = '::'
uri_parts = split_uri(uri=uri, mod_attr_sep=mod_attr_sep)
protocol, mod_uri, attr_chain = uri_parts
if protocol == 'py':
mod_obj = import_name(mod_uri)
else:
if not mod_name:
msg = (
'Argument `mod_name` must be given when loading by file path.'
)
raise ValueError(msg)
mod_obj = import_path(mod_uri, mod_name=mod_name)
if not attr_chain:
if retn_mod:
return mod_obj, None
else:
return mod_obj
if attr_chain_sep is None:
attr_chain_sep = '.'
attr_obj = get_attr_chain(
obj=mod_obj,
attr_chain=attr_chain,
sep=attr_chain_sep,
)
if retn_mod:
return mod_obj, attr_obj
else:
return attr_obj | [
"def",
"import_obj",
"(",
"uri",
",",
"mod_name",
"=",
"None",
",",
"mod_attr_sep",
"=",
"'::'",
",",
"attr_chain_sep",
"=",
"'.'",
",",
"retn_mod",
"=",
"False",
",",
")",
":",
"if",
"mod_attr_sep",
"is",
"None",
":",
"mod_attr_sep",
"=",
"'::'",
"uri_p... | Load an object from a module.
@param uri: an uri specifying which object to load.
An `uri` consists of two parts: module URI and attribute chain,
e.g. `a/b/c.py::x.y.z` or `a.b.c::x.y.z`
# Module URI
E.g. `a/b/c.py` or `a.b.c`.
Can be either a module name or a file path.
Whether it is a file path is determined by whether it ends with `.py`.
# Attribute chain
E.g. `x.y.z`.
@param mod_name: module name.
Must be given when `uri` specifies a module file path, not a module name.
@param mod_attr_sep: the separator between module name and attribute name.
@param attr_chain_sep: the separator between parts of attribute name.
@retn_mod: whether return module object. | [
"Load",
"an",
"object",
"from",
"a",
"module",
"."
] | c6711719f5190cec81c8f29b989fc7609175b403 | https://github.com/AoiKuiyuyou/AoikImportUtil-Python/blob/c6711719f5190cec81c8f29b989fc7609175b403/src/aoikimportutil/aoikimportutil.py#L108-L176 | train | 54,934 |
AoiKuiyuyou/AoikImportUtil-Python | src/aoikimportutil/aoikimportutil.py | add_to_sys_modules | def add_to_sys_modules(mod_name, mod_obj=None):
"""Add a module object to `sys.modules`.
@param mod_name: module name, used as key to `sys.modules`.
If `mod_name` is `a.b.c` while modules `a` and `a.b` are not existing,
empty modules will be created for `a` and `a.b` as well.
@param mod_obj: a module object.
If None, an empty module object will be created.
"""
mod_snames = mod_name.split('.')
parent_mod_name = ''
parent_mod_obj = None
for mod_sname in mod_snames:
if parent_mod_name == '':
current_mod_name = mod_sname
else:
current_mod_name = parent_mod_name + '.' + mod_sname
if current_mod_name == mod_name:
current_mod_obj = mod_obj
else:
current_mod_obj = sys.modules.get(current_mod_name, None)
if current_mod_obj is None:
current_mod_obj = imp.new_module(current_mod_name)
sys.modules[current_mod_name] = current_mod_obj
if parent_mod_obj is not None:
setattr(parent_mod_obj, mod_sname, current_mod_obj)
parent_mod_name = current_mod_name
parent_mod_obj = current_mod_obj | python | def add_to_sys_modules(mod_name, mod_obj=None):
"""Add a module object to `sys.modules`.
@param mod_name: module name, used as key to `sys.modules`.
If `mod_name` is `a.b.c` while modules `a` and `a.b` are not existing,
empty modules will be created for `a` and `a.b` as well.
@param mod_obj: a module object.
If None, an empty module object will be created.
"""
mod_snames = mod_name.split('.')
parent_mod_name = ''
parent_mod_obj = None
for mod_sname in mod_snames:
if parent_mod_name == '':
current_mod_name = mod_sname
else:
current_mod_name = parent_mod_name + '.' + mod_sname
if current_mod_name == mod_name:
current_mod_obj = mod_obj
else:
current_mod_obj = sys.modules.get(current_mod_name, None)
if current_mod_obj is None:
current_mod_obj = imp.new_module(current_mod_name)
sys.modules[current_mod_name] = current_mod_obj
if parent_mod_obj is not None:
setattr(parent_mod_obj, mod_sname, current_mod_obj)
parent_mod_name = current_mod_name
parent_mod_obj = current_mod_obj | [
"def",
"add_to_sys_modules",
"(",
"mod_name",
",",
"mod_obj",
"=",
"None",
")",
":",
"mod_snames",
"=",
"mod_name",
".",
"split",
"(",
"'.'",
")",
"parent_mod_name",
"=",
"''",
"parent_mod_obj",
"=",
"None",
"for",
"mod_sname",
"in",
"mod_snames",
":",
"if",... | Add a module object to `sys.modules`.
@param mod_name: module name, used as key to `sys.modules`.
If `mod_name` is `a.b.c` while modules `a` and `a.b` are not existing,
empty modules will be created for `a` and `a.b` as well.
@param mod_obj: a module object.
If None, an empty module object will be created. | [
"Add",
"a",
"module",
"object",
"to",
"sys",
".",
"modules",
"."
] | c6711719f5190cec81c8f29b989fc7609175b403 | https://github.com/AoiKuiyuyou/AoikImportUtil-Python/blob/c6711719f5190cec81c8f29b989fc7609175b403/src/aoikimportutil/aoikimportutil.py#L179-L216 | train | 54,935 |
martinrusev/solid-python | solidpy/utils/wsgi.py | get_host | def get_host(environ):
"""Return the real host for the given WSGI environment. This takes care
of the `X-Forwarded-Host` header.
:param environ: the WSGI environment to get the host of.
"""
scheme = environ.get('wsgi.url_scheme')
if 'HTTP_X_FORWARDED_HOST' in environ:
result = environ['HTTP_X_FORWARDED_HOST']
elif 'HTTP_HOST' in environ:
result = environ['HTTP_HOST']
else:
result = environ['SERVER_NAME']
if (scheme, str(environ['SERVER_PORT'])) not \
in (('https', '443'), ('http', '80')):
result += ':' + environ['SERVER_PORT']
if result.endswith(':80') and scheme == 'http':
result = result[:-3]
elif result.endswith(':443') and scheme == 'https':
result = result[:-4]
return result | python | def get_host(environ):
"""Return the real host for the given WSGI environment. This takes care
of the `X-Forwarded-Host` header.
:param environ: the WSGI environment to get the host of.
"""
scheme = environ.get('wsgi.url_scheme')
if 'HTTP_X_FORWARDED_HOST' in environ:
result = environ['HTTP_X_FORWARDED_HOST']
elif 'HTTP_HOST' in environ:
result = environ['HTTP_HOST']
else:
result = environ['SERVER_NAME']
if (scheme, str(environ['SERVER_PORT'])) not \
in (('https', '443'), ('http', '80')):
result += ':' + environ['SERVER_PORT']
if result.endswith(':80') and scheme == 'http':
result = result[:-3]
elif result.endswith(':443') and scheme == 'https':
result = result[:-4]
return result | [
"def",
"get_host",
"(",
"environ",
")",
":",
"scheme",
"=",
"environ",
".",
"get",
"(",
"'wsgi.url_scheme'",
")",
"if",
"'HTTP_X_FORWARDED_HOST'",
"in",
"environ",
":",
"result",
"=",
"environ",
"[",
"'HTTP_X_FORWARDED_HOST'",
"]",
"elif",
"'HTTP_HOST'",
"in",
... | Return the real host for the given WSGI environment. This takes care
of the `X-Forwarded-Host` header.
:param environ: the WSGI environment to get the host of. | [
"Return",
"the",
"real",
"host",
"for",
"the",
"given",
"WSGI",
"environment",
".",
"This",
"takes",
"care",
"of",
"the",
"X",
"-",
"Forwarded",
"-",
"Host",
"header",
"."
] | c5c39ad43c19e6746ea0297e0d440a2fccfb25ed | https://github.com/martinrusev/solid-python/blob/c5c39ad43c19e6746ea0297e0d440a2fccfb25ed/solidpy/utils/wsgi.py#L25-L45 | train | 54,936 |
mdickinson/refcycle | refcycle/object_graph.py | ObjectGraph._raw | def _raw(cls, vertices, edges, out_edges, in_edges, head, tail):
"""
Private constructor for direct construction
of an ObjectGraph from its attributes.
vertices is the collection of vertices
out_edges and in_edges map vertices to lists of edges
head and tail map edges to objects.
"""
self = object.__new__(cls)
self._out_edges = out_edges
self._in_edges = in_edges
self._head = head
self._tail = tail
self._vertices = vertices
self._edges = edges
return self | python | def _raw(cls, vertices, edges, out_edges, in_edges, head, tail):
"""
Private constructor for direct construction
of an ObjectGraph from its attributes.
vertices is the collection of vertices
out_edges and in_edges map vertices to lists of edges
head and tail map edges to objects.
"""
self = object.__new__(cls)
self._out_edges = out_edges
self._in_edges = in_edges
self._head = head
self._tail = tail
self._vertices = vertices
self._edges = edges
return self | [
"def",
"_raw",
"(",
"cls",
",",
"vertices",
",",
"edges",
",",
"out_edges",
",",
"in_edges",
",",
"head",
",",
"tail",
")",
":",
"self",
"=",
"object",
".",
"__new__",
"(",
"cls",
")",
"self",
".",
"_out_edges",
"=",
"out_edges",
"self",
".",
"_in_ed... | Private constructor for direct construction
of an ObjectGraph from its attributes.
vertices is the collection of vertices
out_edges and in_edges map vertices to lists of edges
head and tail map edges to objects. | [
"Private",
"constructor",
"for",
"direct",
"construction",
"of",
"an",
"ObjectGraph",
"from",
"its",
"attributes",
"."
] | 627fad74c74efc601209c96405f8118cd99b2241 | https://github.com/mdickinson/refcycle/blob/627fad74c74efc601209c96405f8118cd99b2241/refcycle/object_graph.py#L182-L199 | train | 54,937 |
mdickinson/refcycle | refcycle/object_graph.py | ObjectGraph.annotated | def annotated(self):
"""
Annotate this graph, returning an AnnotatedGraph object
with the same structure.
"""
# Build up dictionary of edge annotations.
edge_annotations = {}
for edge in self.edges:
if edge not in edge_annotations:
# We annotate all edges from a given object at once.
referrer = self._tail[edge]
known_refs = annotated_references(referrer)
for out_edge in self._out_edges[referrer]:
referent = self._head[out_edge]
if known_refs[referent]:
annotation = known_refs[referent].pop()
else:
annotation = None
edge_annotations[out_edge] = annotation
annotated_vertices = [
AnnotatedVertex(
id=id(vertex),
annotation=object_annotation(vertex),
)
for vertex in self.vertices
]
annotated_edges = [
AnnotatedEdge(
id=edge,
annotation=edge_annotations[edge],
head=id(self._head[edge]),
tail=id(self._tail[edge]),
)
for edge in self.edges
]
return AnnotatedGraph(
vertices=annotated_vertices,
edges=annotated_edges,
) | python | def annotated(self):
"""
Annotate this graph, returning an AnnotatedGraph object
with the same structure.
"""
# Build up dictionary of edge annotations.
edge_annotations = {}
for edge in self.edges:
if edge not in edge_annotations:
# We annotate all edges from a given object at once.
referrer = self._tail[edge]
known_refs = annotated_references(referrer)
for out_edge in self._out_edges[referrer]:
referent = self._head[out_edge]
if known_refs[referent]:
annotation = known_refs[referent].pop()
else:
annotation = None
edge_annotations[out_edge] = annotation
annotated_vertices = [
AnnotatedVertex(
id=id(vertex),
annotation=object_annotation(vertex),
)
for vertex in self.vertices
]
annotated_edges = [
AnnotatedEdge(
id=edge,
annotation=edge_annotations[edge],
head=id(self._head[edge]),
tail=id(self._tail[edge]),
)
for edge in self.edges
]
return AnnotatedGraph(
vertices=annotated_vertices,
edges=annotated_edges,
) | [
"def",
"annotated",
"(",
"self",
")",
":",
"# Build up dictionary of edge annotations.",
"edge_annotations",
"=",
"{",
"}",
"for",
"edge",
"in",
"self",
".",
"edges",
":",
"if",
"edge",
"not",
"in",
"edge_annotations",
":",
"# We annotate all edges from a given object... | Annotate this graph, returning an AnnotatedGraph object
with the same structure. | [
"Annotate",
"this",
"graph",
"returning",
"an",
"AnnotatedGraph",
"object",
"with",
"the",
"same",
"structure",
"."
] | 627fad74c74efc601209c96405f8118cd99b2241 | https://github.com/mdickinson/refcycle/blob/627fad74c74efc601209c96405f8118cd99b2241/refcycle/object_graph.py#L253-L295 | train | 54,938 |
mdickinson/refcycle | refcycle/object_graph.py | ObjectGraph.owned_objects | def owned_objects(self):
"""
List of gc-tracked objects owned by this ObjectGraph instance.
"""
return (
[
self,
self.__dict__,
self._head,
self._tail,
self._out_edges,
self._out_edges._keys,
self._out_edges._values,
self._in_edges,
self._in_edges._keys,
self._in_edges._values,
self._vertices,
self._vertices._elements,
self._edges,
] +
list(six.itervalues(self._out_edges)) +
list(six.itervalues(self._in_edges))
) | python | def owned_objects(self):
"""
List of gc-tracked objects owned by this ObjectGraph instance.
"""
return (
[
self,
self.__dict__,
self._head,
self._tail,
self._out_edges,
self._out_edges._keys,
self._out_edges._values,
self._in_edges,
self._in_edges._keys,
self._in_edges._values,
self._vertices,
self._vertices._elements,
self._edges,
] +
list(six.itervalues(self._out_edges)) +
list(six.itervalues(self._in_edges))
) | [
"def",
"owned_objects",
"(",
"self",
")",
":",
"return",
"(",
"[",
"self",
",",
"self",
".",
"__dict__",
",",
"self",
".",
"_head",
",",
"self",
".",
"_tail",
",",
"self",
".",
"_out_edges",
",",
"self",
".",
"_out_edges",
".",
"_keys",
",",
"self",
... | List of gc-tracked objects owned by this ObjectGraph instance. | [
"List",
"of",
"gc",
"-",
"tracked",
"objects",
"owned",
"by",
"this",
"ObjectGraph",
"instance",
"."
] | 627fad74c74efc601209c96405f8118cd99b2241 | https://github.com/mdickinson/refcycle/blob/627fad74c74efc601209c96405f8118cd99b2241/refcycle/object_graph.py#L352-L375 | train | 54,939 |
mdickinson/refcycle | refcycle/object_graph.py | ObjectGraph.find_by_typename | def find_by_typename(self, typename):
"""
List of all objects whose type has the given name.
"""
return self.find_by(lambda obj: type(obj).__name__ == typename) | python | def find_by_typename(self, typename):
"""
List of all objects whose type has the given name.
"""
return self.find_by(lambda obj: type(obj).__name__ == typename) | [
"def",
"find_by_typename",
"(",
"self",
",",
"typename",
")",
":",
"return",
"self",
".",
"find_by",
"(",
"lambda",
"obj",
":",
"type",
"(",
"obj",
")",
".",
"__name__",
"==",
"typename",
")"
] | List of all objects whose type has the given name. | [
"List",
"of",
"all",
"objects",
"whose",
"type",
"has",
"the",
"given",
"name",
"."
] | 627fad74c74efc601209c96405f8118cd99b2241 | https://github.com/mdickinson/refcycle/blob/627fad74c74efc601209c96405f8118cd99b2241/refcycle/object_graph.py#L377-L381 | train | 54,940 |
toumorokoshi/sprinter | sprinter/core/inputs.py | Inputs.get_unset_inputs | def get_unset_inputs(self):
""" Return a set of unset inputs """
return set([k for k, v in self._inputs.items() if v.is_empty(False)]) | python | def get_unset_inputs(self):
""" Return a set of unset inputs """
return set([k for k, v in self._inputs.items() if v.is_empty(False)]) | [
"def",
"get_unset_inputs",
"(",
"self",
")",
":",
"return",
"set",
"(",
"[",
"k",
"for",
"k",
",",
"v",
"in",
"self",
".",
"_inputs",
".",
"items",
"(",
")",
"if",
"v",
".",
"is_empty",
"(",
"False",
")",
"]",
")"
] | Return a set of unset inputs | [
"Return",
"a",
"set",
"of",
"unset",
"inputs"
] | 846697a7a087e69c61d075232e754d6975a64152 | https://github.com/toumorokoshi/sprinter/blob/846697a7a087e69c61d075232e754d6975a64152/sprinter/core/inputs.py#L135-L137 | train | 54,941 |
toumorokoshi/sprinter | sprinter/core/inputs.py | Inputs.prompt_unset_inputs | def prompt_unset_inputs(self, force=False):
""" Prompt for unset input values """
for k, v in self._inputs.items():
if force or v.is_empty(False):
self.get_input(k, force=force) | python | def prompt_unset_inputs(self, force=False):
""" Prompt for unset input values """
for k, v in self._inputs.items():
if force or v.is_empty(False):
self.get_input(k, force=force) | [
"def",
"prompt_unset_inputs",
"(",
"self",
",",
"force",
"=",
"False",
")",
":",
"for",
"k",
",",
"v",
"in",
"self",
".",
"_inputs",
".",
"items",
"(",
")",
":",
"if",
"force",
"or",
"v",
".",
"is_empty",
"(",
"False",
")",
":",
"self",
".",
"get... | Prompt for unset input values | [
"Prompt",
"for",
"unset",
"input",
"values"
] | 846697a7a087e69c61d075232e754d6975a64152 | https://github.com/toumorokoshi/sprinter/blob/846697a7a087e69c61d075232e754d6975a64152/sprinter/core/inputs.py#L139-L143 | train | 54,942 |
toumorokoshi/sprinter | sprinter/core/inputs.py | Inputs.values | def values(self, with_defaults=True):
""" Return the values dictionary, defaulting to default values """
return dict(((k, str(v)) for k, v in self._inputs.items() if not v.is_empty(with_defaults))) | python | def values(self, with_defaults=True):
""" Return the values dictionary, defaulting to default values """
return dict(((k, str(v)) for k, v in self._inputs.items() if not v.is_empty(with_defaults))) | [
"def",
"values",
"(",
"self",
",",
"with_defaults",
"=",
"True",
")",
":",
"return",
"dict",
"(",
"(",
"(",
"k",
",",
"str",
"(",
"v",
")",
")",
"for",
"k",
",",
"v",
"in",
"self",
".",
"_inputs",
".",
"items",
"(",
")",
"if",
"not",
"v",
"."... | Return the values dictionary, defaulting to default values | [
"Return",
"the",
"values",
"dictionary",
"defaulting",
"to",
"default",
"values"
] | 846697a7a087e69c61d075232e754d6975a64152 | https://github.com/toumorokoshi/sprinter/blob/846697a7a087e69c61d075232e754d6975a64152/sprinter/core/inputs.py#L149-L151 | train | 54,943 |
toumorokoshi/sprinter | sprinter/core/inputs.py | Inputs.write_values | def write_values(self):
""" Return the dictionary with which to write values """
return dict(((k, v.value) for k, v in self._inputs.items() if not v.is_secret and not v.is_empty(False))) | python | def write_values(self):
""" Return the dictionary with which to write values """
return dict(((k, v.value) for k, v in self._inputs.items() if not v.is_secret and not v.is_empty(False))) | [
"def",
"write_values",
"(",
"self",
")",
":",
"return",
"dict",
"(",
"(",
"(",
"k",
",",
"v",
".",
"value",
")",
"for",
"k",
",",
"v",
"in",
"self",
".",
"_inputs",
".",
"items",
"(",
")",
"if",
"not",
"v",
".",
"is_secret",
"and",
"not",
"v",
... | Return the dictionary with which to write values | [
"Return",
"the",
"dictionary",
"with",
"which",
"to",
"write",
"values"
] | 846697a7a087e69c61d075232e754d6975a64152 | https://github.com/toumorokoshi/sprinter/blob/846697a7a087e69c61d075232e754d6975a64152/sprinter/core/inputs.py#L153-L155 | train | 54,944 |
toumorokoshi/sprinter | sprinter/core/inputs.py | Inputs._parse_param_line | def _parse_param_line(self, line):
""" Parse a single param line. """
value = line.strip('\n \t')
if len(value) > 0:
i = Input()
if value.find('#') != -1:
value, extra_attributes = value.split('#')
try:
extra_attributes = eval(extra_attributes)
except SyntaxError:
raise InputException("Incorrectly formatted input for {0}!".format(value))
if not isinstance(extra_attributes, dict):
raise InputException("Incorrectly formatted input for {0}!".format(value))
if 'prompt' in extra_attributes:
i.prompt = extra_attributes['prompt']
if 'help' in extra_attributes:
i.help = extra_attributes['help']
if 'type' in extra_attributes:
i.in_type = extra_attributes['type']
if i.in_type.find('/') != -1:
i.in_type, i.out_type = i.in_type.split('/')
if 'cast' in extra_attributes:
i.out_type = extra_attributes['cast']
if value.find('==') != -1:
value, default = value.split('==')
i.default = default
if value.endswith('?'):
value = value[:-1]
i.is_secret = True
return (value, i)
return None | python | def _parse_param_line(self, line):
""" Parse a single param line. """
value = line.strip('\n \t')
if len(value) > 0:
i = Input()
if value.find('#') != -1:
value, extra_attributes = value.split('#')
try:
extra_attributes = eval(extra_attributes)
except SyntaxError:
raise InputException("Incorrectly formatted input for {0}!".format(value))
if not isinstance(extra_attributes, dict):
raise InputException("Incorrectly formatted input for {0}!".format(value))
if 'prompt' in extra_attributes:
i.prompt = extra_attributes['prompt']
if 'help' in extra_attributes:
i.help = extra_attributes['help']
if 'type' in extra_attributes:
i.in_type = extra_attributes['type']
if i.in_type.find('/') != -1:
i.in_type, i.out_type = i.in_type.split('/')
if 'cast' in extra_attributes:
i.out_type = extra_attributes['cast']
if value.find('==') != -1:
value, default = value.split('==')
i.default = default
if value.endswith('?'):
value = value[:-1]
i.is_secret = True
return (value, i)
return None | [
"def",
"_parse_param_line",
"(",
"self",
",",
"line",
")",
":",
"value",
"=",
"line",
".",
"strip",
"(",
"'\\n \\t'",
")",
"if",
"len",
"(",
"value",
")",
">",
"0",
":",
"i",
"=",
"Input",
"(",
")",
"if",
"value",
".",
"find",
"(",
"'#'",
")",
... | Parse a single param line. | [
"Parse",
"a",
"single",
"param",
"line",
"."
] | 846697a7a087e69c61d075232e754d6975a64152 | https://github.com/toumorokoshi/sprinter/blob/846697a7a087e69c61d075232e754d6975a64152/sprinter/core/inputs.py#L171-L201 | train | 54,945 |
sephii/zipch | zipch/zipcodes.py | ZipcodesDatabase.download | def download(self, overwrite=True):
"""
Download the zipcodes CSV file. If ``overwrite`` is set to False, the
file won't be downloaded if it already exists.
"""
if overwrite or not os.path.exists(self.file_path):
_, f = tempfile.mkstemp()
try:
urlretrieve(self.DOWNLOAD_URL, f)
extract_csv(f, self.file_path)
finally:
os.remove(f) | python | def download(self, overwrite=True):
"""
Download the zipcodes CSV file. If ``overwrite`` is set to False, the
file won't be downloaded if it already exists.
"""
if overwrite or not os.path.exists(self.file_path):
_, f = tempfile.mkstemp()
try:
urlretrieve(self.DOWNLOAD_URL, f)
extract_csv(f, self.file_path)
finally:
os.remove(f) | [
"def",
"download",
"(",
"self",
",",
"overwrite",
"=",
"True",
")",
":",
"if",
"overwrite",
"or",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"self",
".",
"file_path",
")",
":",
"_",
",",
"f",
"=",
"tempfile",
".",
"mkstemp",
"(",
")",
"try",
"... | Download the zipcodes CSV file. If ``overwrite`` is set to False, the
file won't be downloaded if it already exists. | [
"Download",
"the",
"zipcodes",
"CSV",
"file",
".",
"If",
"overwrite",
"is",
"set",
"to",
"False",
"the",
"file",
"won",
"t",
"be",
"downloaded",
"if",
"it",
"already",
"exists",
"."
] | a64720e8cb55d00edeab30c426791cf87bcca82a | https://github.com/sephii/zipch/blob/a64720e8cb55d00edeab30c426791cf87bcca82a/zipch/zipcodes.py#L65-L76 | train | 54,946 |
sephii/zipch | zipch/zipcodes.py | ZipcodesDatabase.get_zipcodes_for_canton | def get_zipcodes_for_canton(self, canton):
"""
Return the list of zipcodes for the given canton code.
"""
zipcodes = [
zipcode for zipcode, location in self.get_locations().items()
if location.canton == canton
]
return zipcodes | python | def get_zipcodes_for_canton(self, canton):
"""
Return the list of zipcodes for the given canton code.
"""
zipcodes = [
zipcode for zipcode, location in self.get_locations().items()
if location.canton == canton
]
return zipcodes | [
"def",
"get_zipcodes_for_canton",
"(",
"self",
",",
"canton",
")",
":",
"zipcodes",
"=",
"[",
"zipcode",
"for",
"zipcode",
",",
"location",
"in",
"self",
".",
"get_locations",
"(",
")",
".",
"items",
"(",
")",
"if",
"location",
".",
"canton",
"==",
"cant... | Return the list of zipcodes for the given canton code. | [
"Return",
"the",
"list",
"of",
"zipcodes",
"for",
"the",
"given",
"canton",
"code",
"."
] | a64720e8cb55d00edeab30c426791cf87bcca82a | https://github.com/sephii/zipch/blob/a64720e8cb55d00edeab30c426791cf87bcca82a/zipch/zipcodes.py#L115-L124 | train | 54,947 |
sephii/zipch | zipch/zipcodes.py | ZipcodesDatabase.get_cantons | def get_cantons(self):
"""
Return the list of unique cantons, sorted by name.
"""
return sorted(list(set([
location.canton for location in self.get_locations().values()
]))) | python | def get_cantons(self):
"""
Return the list of unique cantons, sorted by name.
"""
return sorted(list(set([
location.canton for location in self.get_locations().values()
]))) | [
"def",
"get_cantons",
"(",
"self",
")",
":",
"return",
"sorted",
"(",
"list",
"(",
"set",
"(",
"[",
"location",
".",
"canton",
"for",
"location",
"in",
"self",
".",
"get_locations",
"(",
")",
".",
"values",
"(",
")",
"]",
")",
")",
")"
] | Return the list of unique cantons, sorted by name. | [
"Return",
"the",
"list",
"of",
"unique",
"cantons",
"sorted",
"by",
"name",
"."
] | a64720e8cb55d00edeab30c426791cf87bcca82a | https://github.com/sephii/zipch/blob/a64720e8cb55d00edeab30c426791cf87bcca82a/zipch/zipcodes.py#L126-L132 | train | 54,948 |
sephii/zipch | zipch/zipcodes.py | ZipcodesDatabase.get_municipalities | def get_municipalities(self):
"""
Return the list of unique municipalities, sorted by name.
"""
return sorted(list(set([
location.municipality for location in self.get_locations().values()
]))) | python | def get_municipalities(self):
"""
Return the list of unique municipalities, sorted by name.
"""
return sorted(list(set([
location.municipality for location in self.get_locations().values()
]))) | [
"def",
"get_municipalities",
"(",
"self",
")",
":",
"return",
"sorted",
"(",
"list",
"(",
"set",
"(",
"[",
"location",
".",
"municipality",
"for",
"location",
"in",
"self",
".",
"get_locations",
"(",
")",
".",
"values",
"(",
")",
"]",
")",
")",
")"
] | Return the list of unique municipalities, sorted by name. | [
"Return",
"the",
"list",
"of",
"unique",
"municipalities",
"sorted",
"by",
"name",
"."
] | a64720e8cb55d00edeab30c426791cf87bcca82a | https://github.com/sephii/zipch/blob/a64720e8cb55d00edeab30c426791cf87bcca82a/zipch/zipcodes.py#L134-L140 | train | 54,949 |
toumorokoshi/sprinter | sprinter/core/featuredict.py | FeatureDict._get_formula_class | def _get_formula_class(self, formula):
"""
get a formula class object if it exists, else
create one, add it to the dict, and pass return it.
"""
# recursive import otherwise
from sprinter.formula.base import FormulaBase
if formula in LEGACY_MAPPINGS:
formula = LEGACY_MAPPINGS[formula]
formula_class, formula_url = formula, None
if ':' in formula:
formula_class, formula_url = formula.split(":", 1)
if formula_class not in self._formula_dict:
try:
self._formula_dict[formula_class] = lib.get_subclass_from_module(formula_class, FormulaBase)
except (SprinterException, ImportError):
logger.info("Downloading %s..." % formula_class)
try:
self._pip.install_egg(formula_url or formula_class)
try:
self._formula_dict[formula_class] = lib.get_subclass_from_module(formula_class, FormulaBase)
except ImportError:
logger.debug("FeatureDict import Error", exc_info=sys.exc_info())
raise SprinterException("Error: Unable to retrieve formula %s!" % formula_class)
except PipException:
logger.error("ERROR: Unable to download %s!" % formula_class)
return self._formula_dict[formula_class] | python | def _get_formula_class(self, formula):
"""
get a formula class object if it exists, else
create one, add it to the dict, and pass return it.
"""
# recursive import otherwise
from sprinter.formula.base import FormulaBase
if formula in LEGACY_MAPPINGS:
formula = LEGACY_MAPPINGS[formula]
formula_class, formula_url = formula, None
if ':' in formula:
formula_class, formula_url = formula.split(":", 1)
if formula_class not in self._formula_dict:
try:
self._formula_dict[formula_class] = lib.get_subclass_from_module(formula_class, FormulaBase)
except (SprinterException, ImportError):
logger.info("Downloading %s..." % formula_class)
try:
self._pip.install_egg(formula_url or formula_class)
try:
self._formula_dict[formula_class] = lib.get_subclass_from_module(formula_class, FormulaBase)
except ImportError:
logger.debug("FeatureDict import Error", exc_info=sys.exc_info())
raise SprinterException("Error: Unable to retrieve formula %s!" % formula_class)
except PipException:
logger.error("ERROR: Unable to download %s!" % formula_class)
return self._formula_dict[formula_class] | [
"def",
"_get_formula_class",
"(",
"self",
",",
"formula",
")",
":",
"# recursive import otherwise",
"from",
"sprinter",
".",
"formula",
".",
"base",
"import",
"FormulaBase",
"if",
"formula",
"in",
"LEGACY_MAPPINGS",
":",
"formula",
"=",
"LEGACY_MAPPINGS",
"[",
"fo... | get a formula class object if it exists, else
create one, add it to the dict, and pass return it. | [
"get",
"a",
"formula",
"class",
"object",
"if",
"it",
"exists",
"else",
"create",
"one",
"add",
"it",
"to",
"the",
"dict",
"and",
"pass",
"return",
"it",
"."
] | 846697a7a087e69c61d075232e754d6975a64152 | https://github.com/toumorokoshi/sprinter/blob/846697a7a087e69c61d075232e754d6975a64152/sprinter/core/featuredict.py#L82-L108 | train | 54,950 |
memphis-iis/GLUDB | gludb/backup.py | is_backup_class | def is_backup_class(cls):
"""Return true if given class supports back up. Currently this means a
gludb.data.Storable-derived class that has a mapping as defined in
gludb.config"""
return True if (
isclass(cls) and
issubclass(cls, Storable) and
get_mapping(cls, no_mapping_ok=True)
) else False | python | def is_backup_class(cls):
"""Return true if given class supports back up. Currently this means a
gludb.data.Storable-derived class that has a mapping as defined in
gludb.config"""
return True if (
isclass(cls) and
issubclass(cls, Storable) and
get_mapping(cls, no_mapping_ok=True)
) else False | [
"def",
"is_backup_class",
"(",
"cls",
")",
":",
"return",
"True",
"if",
"(",
"isclass",
"(",
"cls",
")",
"and",
"issubclass",
"(",
"cls",
",",
"Storable",
")",
"and",
"get_mapping",
"(",
"cls",
",",
"no_mapping_ok",
"=",
"True",
")",
")",
"else",
"Fals... | Return true if given class supports back up. Currently this means a
gludb.data.Storable-derived class that has a mapping as defined in
gludb.config | [
"Return",
"true",
"if",
"given",
"class",
"supports",
"back",
"up",
".",
"Currently",
"this",
"means",
"a",
"gludb",
".",
"data",
".",
"Storable",
"-",
"derived",
"class",
"that",
"has",
"a",
"mapping",
"as",
"defined",
"in",
"gludb",
".",
"config"
] | 25692528ff6fe8184a3570f61f31f1a90088a388 | https://github.com/memphis-iis/GLUDB/blob/25692528ff6fe8184a3570f61f31f1a90088a388/gludb/backup.py#L29-L37 | train | 54,951 |
bryanwweber/thermohw | thermohw/convert_thermo_hw.py | process | def process(
hw_num: int,
problems_to_do: Optional[Iterable[int]] = None,
prefix: Optional[Path] = None,
by_hand: Optional[Iterable[int]] = None,
) -> None:
"""Process the homework problems in ``prefix`` folder.
Arguments
---------
hw_num
The number of this homework
problems_to_do, optional
A list of the problems to be processed
prefix, optional
A `~pathlib.Path` to this homework assignment folder
by_hand, optional
A list of the problems that should be labeled to be completed
by hand and have an image with the solution included.
"""
if prefix is None:
prefix = Path(".")
problems: Iterable[Path]
if problems_to_do is None:
# The glob syntax here means a the filename must start with
# homework-, be followed the homework number, followed by a
# dash, then a digit representing the problem number for this
# homework number, then any number of characters (in practice
# either nothing or, rarely, another digit), then the ipynb
# extension. Examples:
# homework-1-1.ipynb, homework-10-1.ipynb, homework-3-10.ipynb
problems = list(prefix.glob(f"homework-{hw_num}-[0-9]*.ipynb"))
else:
problems = [prefix / f"homework-{hw_num}-{i}.ipynb" for i in problems_to_do]
problems = sorted(problems, key=lambda k: k.stem[-1])
output_directory: Path = (prefix / "output").resolve()
fw = FilesWriter(build_directory=str(output_directory))
assignment_zip_name = output_directory / f"homework-{hw_num}.zip"
solution_zip_name = output_directory / f"homework-{hw_num}-soln.zip"
assignment_pdfs: List[BytesIO] = []
solution_pdfs: List[BytesIO] = []
assignment_pdf: bytes
solution_pdf: bytes
assignment_nb: str
solution_nb: str
res: Dict[str, Union[str, bool]] = {
"delete_pymarkdown": True,
"global_content_filter": {"include_raw": False},
}
for problem in problems:
print("Working on:", problem)
res["unique_key"] = problem.stem
problem_number = int(problem.stem.split("-")[-1])
if by_hand is not None and problem_number in by_hand:
res["by_hand"] = True
else:
res["by_hand"] = False
problem_fname = str(problem.resolve())
# Process assignments
res["remove_solution"] = True
assignment_pdf, _ = pdf_exp.from_filename(problem_fname, resources=res)
assignment_pdfs.append(BytesIO(assignment_pdf))
assignment_nb, _ = nb_exp.from_filename(problem_fname, resources=res)
with ZipFile(assignment_zip_name, mode="a") as zip_file:
zip_file.writestr(problem.name, assignment_nb)
# Process solutions
res["remove_solution"] = False
solution_pdf, _ = pdf_exp.from_filename(problem_fname, resources=res)
solution_pdfs.append(BytesIO(solution_pdf))
solution_nb, _ = nb_exp.from_filename(problem_fname, resources=res)
with ZipFile(solution_zip_name, mode="a") as zip_file:
zip_file.writestr(problem.stem + "-soln" + problem.suffix, solution_nb)
resources: Dict[str, Any] = {
"metadata": {
"name": f"homework-{hw_num}",
"path": str(prefix),
"modified_date": date.today().strftime("%B %d, %Y"),
},
"output_extension": ".pdf",
}
fw.write(combine_pdf_as_bytes(assignment_pdfs), resources, f"homework-{hw_num}")
resources["metadata"]["name"] = f"homework-{hw_num}-soln"
fw.write(combine_pdf_as_bytes(solution_pdfs), resources, f"homework-{hw_num}-soln") | python | def process(
hw_num: int,
problems_to_do: Optional[Iterable[int]] = None,
prefix: Optional[Path] = None,
by_hand: Optional[Iterable[int]] = None,
) -> None:
"""Process the homework problems in ``prefix`` folder.
Arguments
---------
hw_num
The number of this homework
problems_to_do, optional
A list of the problems to be processed
prefix, optional
A `~pathlib.Path` to this homework assignment folder
by_hand, optional
A list of the problems that should be labeled to be completed
by hand and have an image with the solution included.
"""
if prefix is None:
prefix = Path(".")
problems: Iterable[Path]
if problems_to_do is None:
# The glob syntax here means a the filename must start with
# homework-, be followed the homework number, followed by a
# dash, then a digit representing the problem number for this
# homework number, then any number of characters (in practice
# either nothing or, rarely, another digit), then the ipynb
# extension. Examples:
# homework-1-1.ipynb, homework-10-1.ipynb, homework-3-10.ipynb
problems = list(prefix.glob(f"homework-{hw_num}-[0-9]*.ipynb"))
else:
problems = [prefix / f"homework-{hw_num}-{i}.ipynb" for i in problems_to_do]
problems = sorted(problems, key=lambda k: k.stem[-1])
output_directory: Path = (prefix / "output").resolve()
fw = FilesWriter(build_directory=str(output_directory))
assignment_zip_name = output_directory / f"homework-{hw_num}.zip"
solution_zip_name = output_directory / f"homework-{hw_num}-soln.zip"
assignment_pdfs: List[BytesIO] = []
solution_pdfs: List[BytesIO] = []
assignment_pdf: bytes
solution_pdf: bytes
assignment_nb: str
solution_nb: str
res: Dict[str, Union[str, bool]] = {
"delete_pymarkdown": True,
"global_content_filter": {"include_raw": False},
}
for problem in problems:
print("Working on:", problem)
res["unique_key"] = problem.stem
problem_number = int(problem.stem.split("-")[-1])
if by_hand is not None and problem_number in by_hand:
res["by_hand"] = True
else:
res["by_hand"] = False
problem_fname = str(problem.resolve())
# Process assignments
res["remove_solution"] = True
assignment_pdf, _ = pdf_exp.from_filename(problem_fname, resources=res)
assignment_pdfs.append(BytesIO(assignment_pdf))
assignment_nb, _ = nb_exp.from_filename(problem_fname, resources=res)
with ZipFile(assignment_zip_name, mode="a") as zip_file:
zip_file.writestr(problem.name, assignment_nb)
# Process solutions
res["remove_solution"] = False
solution_pdf, _ = pdf_exp.from_filename(problem_fname, resources=res)
solution_pdfs.append(BytesIO(solution_pdf))
solution_nb, _ = nb_exp.from_filename(problem_fname, resources=res)
with ZipFile(solution_zip_name, mode="a") as zip_file:
zip_file.writestr(problem.stem + "-soln" + problem.suffix, solution_nb)
resources: Dict[str, Any] = {
"metadata": {
"name": f"homework-{hw_num}",
"path": str(prefix),
"modified_date": date.today().strftime("%B %d, %Y"),
},
"output_extension": ".pdf",
}
fw.write(combine_pdf_as_bytes(assignment_pdfs), resources, f"homework-{hw_num}")
resources["metadata"]["name"] = f"homework-{hw_num}-soln"
fw.write(combine_pdf_as_bytes(solution_pdfs), resources, f"homework-{hw_num}-soln") | [
"def",
"process",
"(",
"hw_num",
":",
"int",
",",
"problems_to_do",
":",
"Optional",
"[",
"Iterable",
"[",
"int",
"]",
"]",
"=",
"None",
",",
"prefix",
":",
"Optional",
"[",
"Path",
"]",
"=",
"None",
",",
"by_hand",
":",
"Optional",
"[",
"Iterable",
... | Process the homework problems in ``prefix`` folder.
Arguments
---------
hw_num
The number of this homework
problems_to_do, optional
A list of the problems to be processed
prefix, optional
A `~pathlib.Path` to this homework assignment folder
by_hand, optional
A list of the problems that should be labeled to be completed
by hand and have an image with the solution included. | [
"Process",
"the",
"homework",
"problems",
"in",
"prefix",
"folder",
"."
] | b6be276c14f8adf6ae23f5498065de74f868ccaa | https://github.com/bryanwweber/thermohw/blob/b6be276c14f8adf6ae23f5498065de74f868ccaa/thermohw/convert_thermo_hw.py#L80-L178 | train | 54,952 |
bryanwweber/thermohw | thermohw/convert_thermo_hw.py | main | def main(argv: Optional[Sequence[str]] = None) -> None:
"""Parse arguments and process the homework assignment."""
parser = ArgumentParser(description="Convert Jupyter Notebook assignments to PDFs")
parser.add_argument(
"--hw",
type=int,
required=True,
help="Homework number to convert",
dest="hw_num",
)
parser.add_argument(
"-p",
"--problems",
type=int,
help="Problem numbers to convert",
dest="problems",
nargs="*",
)
parser.add_argument(
"--by-hand",
type=int,
help="Problem numbers to be completed by hand",
dest="by_hand",
nargs="*",
)
args = parser.parse_args(argv)
prefix = Path(f"homework/homework-{args.hw_num}")
process(args.hw_num, args.problems, prefix=prefix, by_hand=args.by_hand) | python | def main(argv: Optional[Sequence[str]] = None) -> None:
"""Parse arguments and process the homework assignment."""
parser = ArgumentParser(description="Convert Jupyter Notebook assignments to PDFs")
parser.add_argument(
"--hw",
type=int,
required=True,
help="Homework number to convert",
dest="hw_num",
)
parser.add_argument(
"-p",
"--problems",
type=int,
help="Problem numbers to convert",
dest="problems",
nargs="*",
)
parser.add_argument(
"--by-hand",
type=int,
help="Problem numbers to be completed by hand",
dest="by_hand",
nargs="*",
)
args = parser.parse_args(argv)
prefix = Path(f"homework/homework-{args.hw_num}")
process(args.hw_num, args.problems, prefix=prefix, by_hand=args.by_hand) | [
"def",
"main",
"(",
"argv",
":",
"Optional",
"[",
"Sequence",
"[",
"str",
"]",
"]",
"=",
"None",
")",
"->",
"None",
":",
"parser",
"=",
"ArgumentParser",
"(",
"description",
"=",
"\"Convert Jupyter Notebook assignments to PDFs\"",
")",
"parser",
".",
"add_argu... | Parse arguments and process the homework assignment. | [
"Parse",
"arguments",
"and",
"process",
"the",
"homework",
"assignment",
"."
] | b6be276c14f8adf6ae23f5498065de74f868ccaa | https://github.com/bryanwweber/thermohw/blob/b6be276c14f8adf6ae23f5498065de74f868ccaa/thermohw/convert_thermo_hw.py#L181-L208 | train | 54,953 |
pschmitt/shortmomi | shortmomi/views.py | get_vm_by_name | def get_vm_by_name(content, name, regex=False):
'''
Get a VM by its name
'''
return get_object_by_name(content, vim.VirtualMachine, name, regex) | python | def get_vm_by_name(content, name, regex=False):
'''
Get a VM by its name
'''
return get_object_by_name(content, vim.VirtualMachine, name, regex) | [
"def",
"get_vm_by_name",
"(",
"content",
",",
"name",
",",
"regex",
"=",
"False",
")",
":",
"return",
"get_object_by_name",
"(",
"content",
",",
"vim",
".",
"VirtualMachine",
",",
"name",
",",
"regex",
")"
] | Get a VM by its name | [
"Get",
"a",
"VM",
"by",
"its",
"name"
] | 81ad5a874e454ef0da93b7fd95474e7b9b9918d8 | https://github.com/pschmitt/shortmomi/blob/81ad5a874e454ef0da93b7fd95474e7b9b9918d8/shortmomi/views.py#L29-L33 | train | 54,954 |
pschmitt/shortmomi | shortmomi/views.py | get_datacenter | def get_datacenter(content, obj):
'''
Get the datacenter to whom an object belongs
'''
datacenters = content.rootFolder.childEntity
for d in datacenters:
dch = get_all(content, d, type(obj))
if dch is not None and obj in dch:
return d | python | def get_datacenter(content, obj):
'''
Get the datacenter to whom an object belongs
'''
datacenters = content.rootFolder.childEntity
for d in datacenters:
dch = get_all(content, d, type(obj))
if dch is not None and obj in dch:
return d | [
"def",
"get_datacenter",
"(",
"content",
",",
"obj",
")",
":",
"datacenters",
"=",
"content",
".",
"rootFolder",
".",
"childEntity",
"for",
"d",
"in",
"datacenters",
":",
"dch",
"=",
"get_all",
"(",
"content",
",",
"d",
",",
"type",
"(",
"obj",
")",
")... | Get the datacenter to whom an object belongs | [
"Get",
"the",
"datacenter",
"to",
"whom",
"an",
"object",
"belongs"
] | 81ad5a874e454ef0da93b7fd95474e7b9b9918d8 | https://github.com/pschmitt/shortmomi/blob/81ad5a874e454ef0da93b7fd95474e7b9b9918d8/shortmomi/views.py#L95-L103 | train | 54,955 |
pschmitt/shortmomi | shortmomi/views.py | get_all_vswitches | def get_all_vswitches(content):
'''
Get all the virtual switches
'''
vswitches = []
hosts = get_all_hosts(content)
for h in hosts:
for s in h.config.network.vswitch:
vswitches.append(s)
return vswitches | python | def get_all_vswitches(content):
'''
Get all the virtual switches
'''
vswitches = []
hosts = get_all_hosts(content)
for h in hosts:
for s in h.config.network.vswitch:
vswitches.append(s)
return vswitches | [
"def",
"get_all_vswitches",
"(",
"content",
")",
":",
"vswitches",
"=",
"[",
"]",
"hosts",
"=",
"get_all_hosts",
"(",
"content",
")",
"for",
"h",
"in",
"hosts",
":",
"for",
"s",
"in",
"h",
".",
"config",
".",
"network",
".",
"vswitch",
":",
"vswitches"... | Get all the virtual switches | [
"Get",
"all",
"the",
"virtual",
"switches"
] | 81ad5a874e454ef0da93b7fd95474e7b9b9918d8 | https://github.com/pschmitt/shortmomi/blob/81ad5a874e454ef0da93b7fd95474e7b9b9918d8/shortmomi/views.py#L122-L131 | train | 54,956 |
pschmitt/shortmomi | shortmomi/views.py | print_vm_info | def print_vm_info(vm):
'''
Print information for a particular virtual machine
'''
summary = vm.summary
print('Name : ', summary.config.name)
print('Path : ', summary.config.vmPathName)
print('Guest : ', summary.config.guestFullName)
annotation = summary.config.annotation
if annotation is not None and annotation != '':
print('Annotation : ', annotation)
print('State : ', summary.runtime.powerState)
if summary.guest is not None:
ip = summary.guest.ipAddress
if ip is not None and ip != '':
print('IP : ', ip)
if summary.runtime.question is not None:
print('Question : ', summary.runtime.question.text)
print('') | python | def print_vm_info(vm):
'''
Print information for a particular virtual machine
'''
summary = vm.summary
print('Name : ', summary.config.name)
print('Path : ', summary.config.vmPathName)
print('Guest : ', summary.config.guestFullName)
annotation = summary.config.annotation
if annotation is not None and annotation != '':
print('Annotation : ', annotation)
print('State : ', summary.runtime.powerState)
if summary.guest is not None:
ip = summary.guest.ipAddress
if ip is not None and ip != '':
print('IP : ', ip)
if summary.runtime.question is not None:
print('Question : ', summary.runtime.question.text)
print('') | [
"def",
"print_vm_info",
"(",
"vm",
")",
":",
"summary",
"=",
"vm",
".",
"summary",
"print",
"(",
"'Name : '",
",",
"summary",
".",
"config",
".",
"name",
")",
"print",
"(",
"'Path : '",
",",
"summary",
".",
"config",
".",
"vmPathName",
")",
"print",
... | Print information for a particular virtual machine | [
"Print",
"information",
"for",
"a",
"particular",
"virtual",
"machine"
] | 81ad5a874e454ef0da93b7fd95474e7b9b9918d8 | https://github.com/pschmitt/shortmomi/blob/81ad5a874e454ef0da93b7fd95474e7b9b9918d8/shortmomi/views.py#L134-L152 | train | 54,957 |
Workiva/contour | contour/contour.py | module_import | def module_import(module_path):
"""Imports the module indicated in name
Args:
module_path: string representing a module path such as
'app.config' or 'app.extras.my_module'
Returns:
the module matching name of the last component, ie: for
'app.extras.my_module' it returns a
reference to my_module
Raises:
BadModulePathError if the module is not found
"""
try:
# Import whole module path.
module = __import__(module_path)
# Split into components: ['contour',
# 'extras','appengine','ndb_persistence'].
components = module_path.split('.')
# Starting at the second component, set module to a
# a reference to that component. at the end
# module with be the last component. In this case:
# ndb_persistence
for component in components[1:]:
module = getattr(module, component)
return module
except ImportError:
raise BadModulePathError(
'Unable to find module "%s".' % (module_path,)) | python | def module_import(module_path):
"""Imports the module indicated in name
Args:
module_path: string representing a module path such as
'app.config' or 'app.extras.my_module'
Returns:
the module matching name of the last component, ie: for
'app.extras.my_module' it returns a
reference to my_module
Raises:
BadModulePathError if the module is not found
"""
try:
# Import whole module path.
module = __import__(module_path)
# Split into components: ['contour',
# 'extras','appengine','ndb_persistence'].
components = module_path.split('.')
# Starting at the second component, set module to a
# a reference to that component. at the end
# module with be the last component. In this case:
# ndb_persistence
for component in components[1:]:
module = getattr(module, component)
return module
except ImportError:
raise BadModulePathError(
'Unable to find module "%s".' % (module_path,)) | [
"def",
"module_import",
"(",
"module_path",
")",
":",
"try",
":",
"# Import whole module path.",
"module",
"=",
"__import__",
"(",
"module_path",
")",
"# Split into components: ['contour',",
"# 'extras','appengine','ndb_persistence'].",
"components",
"=",
"module_path",
".",
... | Imports the module indicated in name
Args:
module_path: string representing a module path such as
'app.config' or 'app.extras.my_module'
Returns:
the module matching name of the last component, ie: for
'app.extras.my_module' it returns a
reference to my_module
Raises:
BadModulePathError if the module is not found | [
"Imports",
"the",
"module",
"indicated",
"in",
"name"
] | 599e05c7ab6020b1ccc27e3f64f625abaec33ff2 | https://github.com/Workiva/contour/blob/599e05c7ab6020b1ccc27e3f64f625abaec33ff2/contour/contour.py#L93-L125 | train | 54,958 |
Workiva/contour | contour/contour.py | find_contour_yaml | def find_contour_yaml(config_file=__file__, names=None):
"""
Traverse directory trees to find a contour.yaml file
Begins with the location of this file then checks the
working directory if not found
Args:
config_file: location of this file, override for
testing
Returns:
the path of contour.yaml or None if not found
"""
checked = set()
contour_yaml = _find_countour_yaml(os.path.dirname(config_file), checked,
names=names)
if not contour_yaml:
contour_yaml = _find_countour_yaml(os.getcwd(), checked, names=names)
return contour_yaml | python | def find_contour_yaml(config_file=__file__, names=None):
"""
Traverse directory trees to find a contour.yaml file
Begins with the location of this file then checks the
working directory if not found
Args:
config_file: location of this file, override for
testing
Returns:
the path of contour.yaml or None if not found
"""
checked = set()
contour_yaml = _find_countour_yaml(os.path.dirname(config_file), checked,
names=names)
if not contour_yaml:
contour_yaml = _find_countour_yaml(os.getcwd(), checked, names=names)
return contour_yaml | [
"def",
"find_contour_yaml",
"(",
"config_file",
"=",
"__file__",
",",
"names",
"=",
"None",
")",
":",
"checked",
"=",
"set",
"(",
")",
"contour_yaml",
"=",
"_find_countour_yaml",
"(",
"os",
".",
"path",
".",
"dirname",
"(",
"config_file",
")",
",",
"checke... | Traverse directory trees to find a contour.yaml file
Begins with the location of this file then checks the
working directory if not found
Args:
config_file: location of this file, override for
testing
Returns:
the path of contour.yaml or None if not found | [
"Traverse",
"directory",
"trees",
"to",
"find",
"a",
"contour",
".",
"yaml",
"file"
] | 599e05c7ab6020b1ccc27e3f64f625abaec33ff2 | https://github.com/Workiva/contour/blob/599e05c7ab6020b1ccc27e3f64f625abaec33ff2/contour/contour.py#L128-L148 | train | 54,959 |
Workiva/contour | contour/contour.py | _find_countour_yaml | def _find_countour_yaml(start, checked, names=None):
"""Traverse the directory tree identified by start
until a directory already in checked is encountered or the path
of countour.yaml is found.
Checked is present both to make the loop termination easy
to reason about and so the same directories do not get
rechecked
Args:
start: the path to start looking in and work upward from
checked: the set of already checked directories
Returns:
the path of the countour.yaml file or None if it is not found
"""
extensions = []
if names:
for name in names:
if not os.path.splitext(name)[1]:
extensions.append(name + ".yaml")
extensions.append(name + ".yml")
yaml_names = (names or []) + CONTOUR_YAML_NAMES + extensions
directory = start
while directory not in checked:
checked.add(directory)
for fs_yaml_name in yaml_names:
yaml_path = os.path.join(directory, fs_yaml_name)
if os.path.exists(yaml_path):
return yaml_path
directory = os.path.dirname(directory)
return | python | def _find_countour_yaml(start, checked, names=None):
"""Traverse the directory tree identified by start
until a directory already in checked is encountered or the path
of countour.yaml is found.
Checked is present both to make the loop termination easy
to reason about and so the same directories do not get
rechecked
Args:
start: the path to start looking in and work upward from
checked: the set of already checked directories
Returns:
the path of the countour.yaml file or None if it is not found
"""
extensions = []
if names:
for name in names:
if not os.path.splitext(name)[1]:
extensions.append(name + ".yaml")
extensions.append(name + ".yml")
yaml_names = (names or []) + CONTOUR_YAML_NAMES + extensions
directory = start
while directory not in checked:
checked.add(directory)
for fs_yaml_name in yaml_names:
yaml_path = os.path.join(directory, fs_yaml_name)
if os.path.exists(yaml_path):
return yaml_path
directory = os.path.dirname(directory)
return | [
"def",
"_find_countour_yaml",
"(",
"start",
",",
"checked",
",",
"names",
"=",
"None",
")",
":",
"extensions",
"=",
"[",
"]",
"if",
"names",
":",
"for",
"name",
"in",
"names",
":",
"if",
"not",
"os",
".",
"path",
".",
"splitext",
"(",
"name",
")",
... | Traverse the directory tree identified by start
until a directory already in checked is encountered or the path
of countour.yaml is found.
Checked is present both to make the loop termination easy
to reason about and so the same directories do not get
rechecked
Args:
start: the path to start looking in and work upward from
checked: the set of already checked directories
Returns:
the path of the countour.yaml file or None if it is not found | [
"Traverse",
"the",
"directory",
"tree",
"identified",
"by",
"start",
"until",
"a",
"directory",
"already",
"in",
"checked",
"is",
"encountered",
"or",
"the",
"path",
"of",
"countour",
".",
"yaml",
"is",
"found",
"."
] | 599e05c7ab6020b1ccc27e3f64f625abaec33ff2 | https://github.com/Workiva/contour/blob/599e05c7ab6020b1ccc27e3f64f625abaec33ff2/contour/contour.py#L151-L189 | train | 54,960 |
smarie/python-parsyfiles | parsyfiles/plugins_optional/support_for_attrs.py | _guess_type_from_validator | def _guess_type_from_validator(validator):
"""
Utility method to return the declared type of an attribute or None. It handles _OptionalValidator and _AndValidator
in order to unpack the validators.
:param validator:
:return: the type of attribute declared in an inner 'instance_of' validator (if any is found, the first one is used)
or None if no inner 'instance_of' validator is found
"""
if isinstance(validator, _OptionalValidator):
# Optional : look inside
return _guess_type_from_validator(validator.validator)
elif isinstance(validator, _AndValidator):
# Sequence : try each of them
for v in validator.validators:
typ = _guess_type_from_validator(v)
if typ is not None:
return typ
return None
elif isinstance(validator, _InstanceOfValidator):
# InstanceOf validator : found it !
return validator.type
else:
# we could not find the type
return None | python | def _guess_type_from_validator(validator):
"""
Utility method to return the declared type of an attribute or None. It handles _OptionalValidator and _AndValidator
in order to unpack the validators.
:param validator:
:return: the type of attribute declared in an inner 'instance_of' validator (if any is found, the first one is used)
or None if no inner 'instance_of' validator is found
"""
if isinstance(validator, _OptionalValidator):
# Optional : look inside
return _guess_type_from_validator(validator.validator)
elif isinstance(validator, _AndValidator):
# Sequence : try each of them
for v in validator.validators:
typ = _guess_type_from_validator(v)
if typ is not None:
return typ
return None
elif isinstance(validator, _InstanceOfValidator):
# InstanceOf validator : found it !
return validator.type
else:
# we could not find the type
return None | [
"def",
"_guess_type_from_validator",
"(",
"validator",
")",
":",
"if",
"isinstance",
"(",
"validator",
",",
"_OptionalValidator",
")",
":",
"# Optional : look inside",
"return",
"_guess_type_from_validator",
"(",
"validator",
".",
"validator",
")",
"elif",
"isinstance",... | Utility method to return the declared type of an attribute or None. It handles _OptionalValidator and _AndValidator
in order to unpack the validators.
:param validator:
:return: the type of attribute declared in an inner 'instance_of' validator (if any is found, the first one is used)
or None if no inner 'instance_of' validator is found | [
"Utility",
"method",
"to",
"return",
"the",
"declared",
"type",
"of",
"an",
"attribute",
"or",
"None",
".",
"It",
"handles",
"_OptionalValidator",
"and",
"_AndValidator",
"in",
"order",
"to",
"unpack",
"the",
"validators",
"."
] | 344b37e1151e8d4e7c2ee49ae09d6568715ae64e | https://github.com/smarie/python-parsyfiles/blob/344b37e1151e8d4e7c2ee49ae09d6568715ae64e/parsyfiles/plugins_optional/support_for_attrs.py#L6-L33 | train | 54,961 |
smarie/python-parsyfiles | parsyfiles/plugins_optional/support_for_attrs.py | is_optional | def is_optional(attr):
"""
Helper method to find if an attribute is mandatory
:param attr:
:return:
"""
return isinstance(attr.validator, _OptionalValidator) or (attr.default is not None and attr.default is not NOTHING) | python | def is_optional(attr):
"""
Helper method to find if an attribute is mandatory
:param attr:
:return:
"""
return isinstance(attr.validator, _OptionalValidator) or (attr.default is not None and attr.default is not NOTHING) | [
"def",
"is_optional",
"(",
"attr",
")",
":",
"return",
"isinstance",
"(",
"attr",
".",
"validator",
",",
"_OptionalValidator",
")",
"or",
"(",
"attr",
".",
"default",
"is",
"not",
"None",
"and",
"attr",
".",
"default",
"is",
"not",
"NOTHING",
")"
] | Helper method to find if an attribute is mandatory
:param attr:
:return: | [
"Helper",
"method",
"to",
"find",
"if",
"an",
"attribute",
"is",
"mandatory"
] | 344b37e1151e8d4e7c2ee49ae09d6568715ae64e | https://github.com/smarie/python-parsyfiles/blob/344b37e1151e8d4e7c2ee49ae09d6568715ae64e/parsyfiles/plugins_optional/support_for_attrs.py#L48-L55 | train | 54,962 |
bryanwweber/thermohw | thermohw/preprocessors.py | RawRemover.preprocess | def preprocess(
self, nb: "NotebookNode", resources: dict
) -> Tuple["NotebookNode", dict]:
"""Remove any raw cells from the Notebook.
By default, exclude raw cells from the output. Change this by including
global_content_filter->include_raw = True in the resources dictionary.
This preprocessor is necessary because the NotebookExporter doesn't
include the exclude_raw config."""
if not resources.get("global_content_filter", {}).get("include_raw", False):
keep_cells = []
for cell in nb.cells:
if cell.cell_type != "raw":
keep_cells.append(cell)
nb.cells = keep_cells
return nb, resources | python | def preprocess(
self, nb: "NotebookNode", resources: dict
) -> Tuple["NotebookNode", dict]:
"""Remove any raw cells from the Notebook.
By default, exclude raw cells from the output. Change this by including
global_content_filter->include_raw = True in the resources dictionary.
This preprocessor is necessary because the NotebookExporter doesn't
include the exclude_raw config."""
if not resources.get("global_content_filter", {}).get("include_raw", False):
keep_cells = []
for cell in nb.cells:
if cell.cell_type != "raw":
keep_cells.append(cell)
nb.cells = keep_cells
return nb, resources | [
"def",
"preprocess",
"(",
"self",
",",
"nb",
":",
"\"NotebookNode\"",
",",
"resources",
":",
"dict",
")",
"->",
"Tuple",
"[",
"\"NotebookNode\"",
",",
"dict",
"]",
":",
"if",
"not",
"resources",
".",
"get",
"(",
"\"global_content_filter\"",
",",
"{",
"}",
... | Remove any raw cells from the Notebook.
By default, exclude raw cells from the output. Change this by including
global_content_filter->include_raw = True in the resources dictionary.
This preprocessor is necessary because the NotebookExporter doesn't
include the exclude_raw config. | [
"Remove",
"any",
"raw",
"cells",
"from",
"the",
"Notebook",
"."
] | b6be276c14f8adf6ae23f5498065de74f868ccaa | https://github.com/bryanwweber/thermohw/blob/b6be276c14f8adf6ae23f5498065de74f868ccaa/thermohw/preprocessors.py#L109-L126 | train | 54,963 |
bryanwweber/thermohw | thermohw/preprocessors.py | SolutionRemover.preprocess | def preprocess(
self, nb: "NotebookNode", resources: dict
) -> Tuple["NotebookNode", dict]:
"""Preprocess the entire notebook."""
if "remove_solution" not in resources:
raise KeyError("The resources dictionary must have a remove_solution key.")
if resources["remove_solution"]:
keep_cells_idx = []
for index, cell in enumerate(nb.cells):
if "## solution" in cell.source.lower():
keep_cells_idx.append(index)
# The space at the end of the test string here is important
elif len(keep_cells_idx) > 0 and cell.source.startswith("### "):
keep_cells_idx.append(index)
keep_cells = nb.cells[: keep_cells_idx[0] + 1]
for i in keep_cells_idx[1:]:
keep_cells.append(nb.cells[i])
if resources["by_hand"]:
keep_cells.append(by_hand_cell)
else:
if "sketch" in nb.cells[i].source.lower():
keep_cells.append(sketch_cell)
else:
keep_cells.append(md_expl_cell)
keep_cells.append(code_ans_cell)
keep_cells.append(md_ans_cell)
nb.cells = keep_cells
return nb, resources | python | def preprocess(
self, nb: "NotebookNode", resources: dict
) -> Tuple["NotebookNode", dict]:
"""Preprocess the entire notebook."""
if "remove_solution" not in resources:
raise KeyError("The resources dictionary must have a remove_solution key.")
if resources["remove_solution"]:
keep_cells_idx = []
for index, cell in enumerate(nb.cells):
if "## solution" in cell.source.lower():
keep_cells_idx.append(index)
# The space at the end of the test string here is important
elif len(keep_cells_idx) > 0 and cell.source.startswith("### "):
keep_cells_idx.append(index)
keep_cells = nb.cells[: keep_cells_idx[0] + 1]
for i in keep_cells_idx[1:]:
keep_cells.append(nb.cells[i])
if resources["by_hand"]:
keep_cells.append(by_hand_cell)
else:
if "sketch" in nb.cells[i].source.lower():
keep_cells.append(sketch_cell)
else:
keep_cells.append(md_expl_cell)
keep_cells.append(code_ans_cell)
keep_cells.append(md_ans_cell)
nb.cells = keep_cells
return nb, resources | [
"def",
"preprocess",
"(",
"self",
",",
"nb",
":",
"\"NotebookNode\"",
",",
"resources",
":",
"dict",
")",
"->",
"Tuple",
"[",
"\"NotebookNode\"",
",",
"dict",
"]",
":",
"if",
"\"remove_solution\"",
"not",
"in",
"resources",
":",
"raise",
"KeyError",
"(",
"... | Preprocess the entire notebook. | [
"Preprocess",
"the",
"entire",
"notebook",
"."
] | b6be276c14f8adf6ae23f5498065de74f868ccaa | https://github.com/bryanwweber/thermohw/blob/b6be276c14f8adf6ae23f5498065de74f868ccaa/thermohw/preprocessors.py#L143-L172 | train | 54,964 |
gtaylor/EVE-Market-Data-Structures | emds/formats/unified/orders.py | parse_from_dict | def parse_from_dict(json_dict):
"""
Given a Unified Uploader message, parse the contents and return a
MarketOrderList.
:param dict json_dict: A Unified Uploader message as a JSON dict.
:rtype: MarketOrderList
:returns: An instance of MarketOrderList, containing the orders
within.
"""
order_columns = json_dict['columns']
order_list = MarketOrderList(
upload_keys=json_dict['uploadKeys'],
order_generator=json_dict['generator'],
)
for rowset in json_dict['rowsets']:
generated_at = parse_datetime(rowset['generatedAt'])
region_id = rowset['regionID']
type_id = rowset['typeID']
order_list.set_empty_region(region_id, type_id, generated_at)
for row in rowset['rows']:
order_kwargs = _columns_to_kwargs(
SPEC_TO_KWARG_CONVERSION, order_columns, row)
order_kwargs.update({
'region_id': region_id,
'type_id': type_id,
'generated_at': generated_at,
})
order_kwargs['order_issue_date'] = parse_datetime(order_kwargs['order_issue_date'])
order_list.add_order(MarketOrder(**order_kwargs))
return order_list | python | def parse_from_dict(json_dict):
"""
Given a Unified Uploader message, parse the contents and return a
MarketOrderList.
:param dict json_dict: A Unified Uploader message as a JSON dict.
:rtype: MarketOrderList
:returns: An instance of MarketOrderList, containing the orders
within.
"""
order_columns = json_dict['columns']
order_list = MarketOrderList(
upload_keys=json_dict['uploadKeys'],
order_generator=json_dict['generator'],
)
for rowset in json_dict['rowsets']:
generated_at = parse_datetime(rowset['generatedAt'])
region_id = rowset['regionID']
type_id = rowset['typeID']
order_list.set_empty_region(region_id, type_id, generated_at)
for row in rowset['rows']:
order_kwargs = _columns_to_kwargs(
SPEC_TO_KWARG_CONVERSION, order_columns, row)
order_kwargs.update({
'region_id': region_id,
'type_id': type_id,
'generated_at': generated_at,
})
order_kwargs['order_issue_date'] = parse_datetime(order_kwargs['order_issue_date'])
order_list.add_order(MarketOrder(**order_kwargs))
return order_list | [
"def",
"parse_from_dict",
"(",
"json_dict",
")",
":",
"order_columns",
"=",
"json_dict",
"[",
"'columns'",
"]",
"order_list",
"=",
"MarketOrderList",
"(",
"upload_keys",
"=",
"json_dict",
"[",
"'uploadKeys'",
"]",
",",
"order_generator",
"=",
"json_dict",
"[",
"... | Given a Unified Uploader message, parse the contents and return a
MarketOrderList.
:param dict json_dict: A Unified Uploader message as a JSON dict.
:rtype: MarketOrderList
:returns: An instance of MarketOrderList, containing the orders
within. | [
"Given",
"a",
"Unified",
"Uploader",
"message",
"parse",
"the",
"contents",
"and",
"return",
"a",
"MarketOrderList",
"."
] | 77d69b24f2aada3aeff8fba3d75891bfba8fdcf3 | https://github.com/gtaylor/EVE-Market-Data-Structures/blob/77d69b24f2aada3aeff8fba3d75891bfba8fdcf3/emds/formats/unified/orders.py#L37-L73 | train | 54,965 |
gtaylor/EVE-Market-Data-Structures | emds/formats/unified/orders.py | encode_to_json | def encode_to_json(order_list):
"""
Encodes this list of MarketOrder instances to a JSON string.
:param MarketOrderList order_list: The order list to serialize.
:rtype: str
"""
rowsets = []
for items_in_region_list in order_list._orders.values():
region_id = items_in_region_list.region_id
type_id = items_in_region_list.type_id
generated_at = gen_iso_datetime_str(items_in_region_list.generated_at)
rows = []
for order in items_in_region_list.orders:
issue_date = gen_iso_datetime_str(order.order_issue_date)
# The order in which these values are added is crucial. It must
# match STANDARD_ENCODED_COLUMNS.
rows.append([
order.price,
order.volume_remaining,
order.order_range,
order.order_id,
order.volume_entered,
order.minimum_volume,
order.is_bid,
issue_date,
order.order_duration,
order.station_id,
order.solar_system_id,
])
rowsets.append(dict(
generatedAt = generated_at,
regionID = region_id,
typeID = type_id,
rows = rows,
))
json_dict = {
'resultType': 'orders',
'version': '0.1',
'uploadKeys': order_list.upload_keys,
'generator': order_list.order_generator,
'currentTime': gen_iso_datetime_str(now_dtime_in_utc()),
# This must match the order of the values in the row assembling portion
# above this.
'columns': STANDARD_ENCODED_COLUMNS,
'rowsets': rowsets,
}
return json.dumps(json_dict) | python | def encode_to_json(order_list):
"""
Encodes this list of MarketOrder instances to a JSON string.
:param MarketOrderList order_list: The order list to serialize.
:rtype: str
"""
rowsets = []
for items_in_region_list in order_list._orders.values():
region_id = items_in_region_list.region_id
type_id = items_in_region_list.type_id
generated_at = gen_iso_datetime_str(items_in_region_list.generated_at)
rows = []
for order in items_in_region_list.orders:
issue_date = gen_iso_datetime_str(order.order_issue_date)
# The order in which these values are added is crucial. It must
# match STANDARD_ENCODED_COLUMNS.
rows.append([
order.price,
order.volume_remaining,
order.order_range,
order.order_id,
order.volume_entered,
order.minimum_volume,
order.is_bid,
issue_date,
order.order_duration,
order.station_id,
order.solar_system_id,
])
rowsets.append(dict(
generatedAt = generated_at,
regionID = region_id,
typeID = type_id,
rows = rows,
))
json_dict = {
'resultType': 'orders',
'version': '0.1',
'uploadKeys': order_list.upload_keys,
'generator': order_list.order_generator,
'currentTime': gen_iso_datetime_str(now_dtime_in_utc()),
# This must match the order of the values in the row assembling portion
# above this.
'columns': STANDARD_ENCODED_COLUMNS,
'rowsets': rowsets,
}
return json.dumps(json_dict) | [
"def",
"encode_to_json",
"(",
"order_list",
")",
":",
"rowsets",
"=",
"[",
"]",
"for",
"items_in_region_list",
"in",
"order_list",
".",
"_orders",
".",
"values",
"(",
")",
":",
"region_id",
"=",
"items_in_region_list",
".",
"region_id",
"type_id",
"=",
"items_... | Encodes this list of MarketOrder instances to a JSON string.
:param MarketOrderList order_list: The order list to serialize.
:rtype: str | [
"Encodes",
"this",
"list",
"of",
"MarketOrder",
"instances",
"to",
"a",
"JSON",
"string",
"."
] | 77d69b24f2aada3aeff8fba3d75891bfba8fdcf3 | https://github.com/gtaylor/EVE-Market-Data-Structures/blob/77d69b24f2aada3aeff8fba3d75891bfba8fdcf3/emds/formats/unified/orders.py#L75-L127 | train | 54,966 |
kcallin/mqtt-codec | mqtt_codec/packet.py | MqttFixedHeader.decode | def decode(f):
"""Extract a `MqttFixedHeader` from ``f``.
Parameters
----------
f: file
Object with read method.
Raises
-------
DecodeError
When bytes decoded have values incompatible with a
`MqttFixedHeader` object.
UnderflowDecodeError
When end-of-stream is encountered before the end of the
fixed header.
Returns
-------
int
Number of bytes consumed from ``f``.
MqttFixedHeader
Header object extracted from ``f``.
"""
decoder = mqtt_io.FileDecoder(f)
(byte_0,) = decoder.unpack(mqtt_io.FIELD_U8)
packet_type_u4 = (byte_0 >> 4)
flags = byte_0 & 0x0f
try:
packet_type = MqttControlPacketType(packet_type_u4)
except ValueError:
raise DecodeError('Unknown packet type 0x{:02x}.'.format(packet_type_u4))
if not are_flags_valid(packet_type, flags):
raise DecodeError('Invalid flags for packet type.')
num_bytes, num_remaining_bytes = decoder.unpack_varint(4)
return decoder.num_bytes_consumed, MqttFixedHeader(packet_type, flags, num_remaining_bytes) | python | def decode(f):
"""Extract a `MqttFixedHeader` from ``f``.
Parameters
----------
f: file
Object with read method.
Raises
-------
DecodeError
When bytes decoded have values incompatible with a
`MqttFixedHeader` object.
UnderflowDecodeError
When end-of-stream is encountered before the end of the
fixed header.
Returns
-------
int
Number of bytes consumed from ``f``.
MqttFixedHeader
Header object extracted from ``f``.
"""
decoder = mqtt_io.FileDecoder(f)
(byte_0,) = decoder.unpack(mqtt_io.FIELD_U8)
packet_type_u4 = (byte_0 >> 4)
flags = byte_0 & 0x0f
try:
packet_type = MqttControlPacketType(packet_type_u4)
except ValueError:
raise DecodeError('Unknown packet type 0x{:02x}.'.format(packet_type_u4))
if not are_flags_valid(packet_type, flags):
raise DecodeError('Invalid flags for packet type.')
num_bytes, num_remaining_bytes = decoder.unpack_varint(4)
return decoder.num_bytes_consumed, MqttFixedHeader(packet_type, flags, num_remaining_bytes) | [
"def",
"decode",
"(",
"f",
")",
":",
"decoder",
"=",
"mqtt_io",
".",
"FileDecoder",
"(",
"f",
")",
"(",
"byte_0",
",",
")",
"=",
"decoder",
".",
"unpack",
"(",
"mqtt_io",
".",
"FIELD_U8",
")",
"packet_type_u4",
"=",
"(",
"byte_0",
">>",
"4",
")",
"... | Extract a `MqttFixedHeader` from ``f``.
Parameters
----------
f: file
Object with read method.
Raises
-------
DecodeError
When bytes decoded have values incompatible with a
`MqttFixedHeader` object.
UnderflowDecodeError
When end-of-stream is encountered before the end of the
fixed header.
Returns
-------
int
Number of bytes consumed from ``f``.
MqttFixedHeader
Header object extracted from ``f``. | [
"Extract",
"a",
"MqttFixedHeader",
"from",
"f",
"."
] | 0f754250cc3f44f4376777e7e8b3676c5a4d413a | https://github.com/kcallin/mqtt-codec/blob/0f754250cc3f44f4376777e7e8b3676c5a4d413a/mqtt_codec/packet.py#L197-L237 | train | 54,967 |
kcallin/mqtt-codec | mqtt_codec/packet.py | MqttSubscribe.decode_body | def decode_body(cls, header, f):
"""Generates a `MqttSubscribe` packet given a
`MqttFixedHeader`. This method asserts that header.packet_type
is `subscribe`.
Parameters
----------
header: MqttFixedHeader
f: file
Object with a read method.
Raises
------
DecodeError
When there are extra bytes at the end of the packet.
Returns
-------
int
Number of bytes consumed from ``f``.
MqttSubscribe
Object extracted from ``f``.
"""
assert header.packet_type == MqttControlPacketType.subscribe
decoder = mqtt_io.FileDecoder(mqtt_io.LimitReader(f, header.remaining_len))
packet_id, = decoder.unpack(mqtt_io.FIELD_PACKET_ID)
topics = []
while header.remaining_len > decoder.num_bytes_consumed:
num_str_bytes, name = decoder.unpack_utf8()
max_qos, = decoder.unpack(mqtt_io.FIELD_U8)
try:
sub_topic = MqttTopic(name, max_qos)
except ValueError:
raise DecodeError('Invalid QOS {}'.format(max_qos))
topics.append(sub_topic)
assert header.remaining_len == decoder.num_bytes_consumed
return decoder.num_bytes_consumed, MqttSubscribe(packet_id, topics) | python | def decode_body(cls, header, f):
"""Generates a `MqttSubscribe` packet given a
`MqttFixedHeader`. This method asserts that header.packet_type
is `subscribe`.
Parameters
----------
header: MqttFixedHeader
f: file
Object with a read method.
Raises
------
DecodeError
When there are extra bytes at the end of the packet.
Returns
-------
int
Number of bytes consumed from ``f``.
MqttSubscribe
Object extracted from ``f``.
"""
assert header.packet_type == MqttControlPacketType.subscribe
decoder = mqtt_io.FileDecoder(mqtt_io.LimitReader(f, header.remaining_len))
packet_id, = decoder.unpack(mqtt_io.FIELD_PACKET_ID)
topics = []
while header.remaining_len > decoder.num_bytes_consumed:
num_str_bytes, name = decoder.unpack_utf8()
max_qos, = decoder.unpack(mqtt_io.FIELD_U8)
try:
sub_topic = MqttTopic(name, max_qos)
except ValueError:
raise DecodeError('Invalid QOS {}'.format(max_qos))
topics.append(sub_topic)
assert header.remaining_len == decoder.num_bytes_consumed
return decoder.num_bytes_consumed, MqttSubscribe(packet_id, topics) | [
"def",
"decode_body",
"(",
"cls",
",",
"header",
",",
"f",
")",
":",
"assert",
"header",
".",
"packet_type",
"==",
"MqttControlPacketType",
".",
"subscribe",
"decoder",
"=",
"mqtt_io",
".",
"FileDecoder",
"(",
"mqtt_io",
".",
"LimitReader",
"(",
"f",
",",
... | Generates a `MqttSubscribe` packet given a
`MqttFixedHeader`. This method asserts that header.packet_type
is `subscribe`.
Parameters
----------
header: MqttFixedHeader
f: file
Object with a read method.
Raises
------
DecodeError
When there are extra bytes at the end of the packet.
Returns
-------
int
Number of bytes consumed from ``f``.
MqttSubscribe
Object extracted from ``f``. | [
"Generates",
"a",
"MqttSubscribe",
"packet",
"given",
"a",
"MqttFixedHeader",
".",
"This",
"method",
"asserts",
"that",
"header",
".",
"packet_type",
"is",
"subscribe",
"."
] | 0f754250cc3f44f4376777e7e8b3676c5a4d413a | https://github.com/kcallin/mqtt-codec/blob/0f754250cc3f44f4376777e7e8b3676c5a4d413a/mqtt_codec/packet.py#L892-L932 | train | 54,968 |
kcallin/mqtt-codec | mqtt_codec/packet.py | MqttSuback.decode_body | def decode_body(cls, header, f):
"""Generates a `MqttSuback` packet given a
`MqttFixedHeader`. This method asserts that header.packet_type
is `suback`.
Parameters
----------
header: MqttFixedHeader
f: file
Object with a read method.
Raises
------
DecodeError
When there are extra bytes at the end of the packet.
Returns
-------
int
Number of bytes consumed from ``f``.
MqttSuback
Object extracted from ``f``.
"""
assert header.packet_type == MqttControlPacketType.suback
decoder = mqtt_io.FileDecoder(mqtt_io.LimitReader(f, header.remaining_len))
packet_id, = decoder.unpack(mqtt_io.FIELD_PACKET_ID)
results = []
while header.remaining_len > decoder.num_bytes_consumed:
result, = decoder.unpack(mqtt_io.FIELD_U8)
try:
results.append(SubscribeResult(result))
except ValueError:
raise DecodeError('Unsupported result {:02x}.'.format(result))
assert header.remaining_len == decoder.num_bytes_consumed
return decoder.num_bytes_consumed, MqttSuback(packet_id, results) | python | def decode_body(cls, header, f):
"""Generates a `MqttSuback` packet given a
`MqttFixedHeader`. This method asserts that header.packet_type
is `suback`.
Parameters
----------
header: MqttFixedHeader
f: file
Object with a read method.
Raises
------
DecodeError
When there are extra bytes at the end of the packet.
Returns
-------
int
Number of bytes consumed from ``f``.
MqttSuback
Object extracted from ``f``.
"""
assert header.packet_type == MqttControlPacketType.suback
decoder = mqtt_io.FileDecoder(mqtt_io.LimitReader(f, header.remaining_len))
packet_id, = decoder.unpack(mqtt_io.FIELD_PACKET_ID)
results = []
while header.remaining_len > decoder.num_bytes_consumed:
result, = decoder.unpack(mqtt_io.FIELD_U8)
try:
results.append(SubscribeResult(result))
except ValueError:
raise DecodeError('Unsupported result {:02x}.'.format(result))
assert header.remaining_len == decoder.num_bytes_consumed
return decoder.num_bytes_consumed, MqttSuback(packet_id, results) | [
"def",
"decode_body",
"(",
"cls",
",",
"header",
",",
"f",
")",
":",
"assert",
"header",
".",
"packet_type",
"==",
"MqttControlPacketType",
".",
"suback",
"decoder",
"=",
"mqtt_io",
".",
"FileDecoder",
"(",
"mqtt_io",
".",
"LimitReader",
"(",
"f",
",",
"he... | Generates a `MqttSuback` packet given a
`MqttFixedHeader`. This method asserts that header.packet_type
is `suback`.
Parameters
----------
header: MqttFixedHeader
f: file
Object with a read method.
Raises
------
DecodeError
When there are extra bytes at the end of the packet.
Returns
-------
int
Number of bytes consumed from ``f``.
MqttSuback
Object extracted from ``f``. | [
"Generates",
"a",
"MqttSuback",
"packet",
"given",
"a",
"MqttFixedHeader",
".",
"This",
"method",
"asserts",
"that",
"header",
".",
"packet_type",
"is",
"suback",
"."
] | 0f754250cc3f44f4376777e7e8b3676c5a4d413a | https://github.com/kcallin/mqtt-codec/blob/0f754250cc3f44f4376777e7e8b3676c5a4d413a/mqtt_codec/packet.py#L1044-L1082 | train | 54,969 |
kcallin/mqtt-codec | mqtt_codec/packet.py | MqttPublish.decode_body | def decode_body(cls, header, f):
"""Generates a `MqttPublish` packet given a
`MqttFixedHeader`. This method asserts that header.packet_type
is `publish`.
Parameters
----------
header: MqttFixedHeader
f: file
Object with a read method.
Raises
------
DecodeError
When there are extra bytes at the end of the packet.
Returns
-------
int
Number of bytes consumed from ``f``.
MqttPublish
Object extracted from ``f``.
"""
assert header.packet_type == MqttControlPacketType.publish
dupe = bool(header.flags & 0x08)
retain = bool(header.flags & 0x01)
qos = ((header.flags & 0x06) >> 1)
if qos == 0 and dupe:
# The DUP flag MUST be set to 0 for all QoS 0 messages
# [MQTT-3.3.1-2]
raise DecodeError("Unexpected dupe=True for qos==0 message [MQTT-3.3.1-2].")
decoder = mqtt_io.FileDecoder(mqtt_io.LimitReader(f, header.remaining_len))
num_bytes_consumed, topic_name = decoder.unpack_utf8()
if qos != 0:
# See MQTT 3.1.1 section 3.3.2.2
# See https://github.com/kcallin/mqtt-codec/issues/5
packet_id, = decoder.unpack(mqtt_io.FIELD_PACKET_ID)
else:
packet_id = 0
payload_len = header.remaining_len - decoder.num_bytes_consumed
payload = decoder.read(payload_len)
return decoder.num_bytes_consumed, MqttPublish(packet_id, topic_name, payload, dupe, qos, retain) | python | def decode_body(cls, header, f):
"""Generates a `MqttPublish` packet given a
`MqttFixedHeader`. This method asserts that header.packet_type
is `publish`.
Parameters
----------
header: MqttFixedHeader
f: file
Object with a read method.
Raises
------
DecodeError
When there are extra bytes at the end of the packet.
Returns
-------
int
Number of bytes consumed from ``f``.
MqttPublish
Object extracted from ``f``.
"""
assert header.packet_type == MqttControlPacketType.publish
dupe = bool(header.flags & 0x08)
retain = bool(header.flags & 0x01)
qos = ((header.flags & 0x06) >> 1)
if qos == 0 and dupe:
# The DUP flag MUST be set to 0 for all QoS 0 messages
# [MQTT-3.3.1-2]
raise DecodeError("Unexpected dupe=True for qos==0 message [MQTT-3.3.1-2].")
decoder = mqtt_io.FileDecoder(mqtt_io.LimitReader(f, header.remaining_len))
num_bytes_consumed, topic_name = decoder.unpack_utf8()
if qos != 0:
# See MQTT 3.1.1 section 3.3.2.2
# See https://github.com/kcallin/mqtt-codec/issues/5
packet_id, = decoder.unpack(mqtt_io.FIELD_PACKET_ID)
else:
packet_id = 0
payload_len = header.remaining_len - decoder.num_bytes_consumed
payload = decoder.read(payload_len)
return decoder.num_bytes_consumed, MqttPublish(packet_id, topic_name, payload, dupe, qos, retain) | [
"def",
"decode_body",
"(",
"cls",
",",
"header",
",",
"f",
")",
":",
"assert",
"header",
".",
"packet_type",
"==",
"MqttControlPacketType",
".",
"publish",
"dupe",
"=",
"bool",
"(",
"header",
".",
"flags",
"&",
"0x08",
")",
"retain",
"=",
"bool",
"(",
... | Generates a `MqttPublish` packet given a
`MqttFixedHeader`. This method asserts that header.packet_type
is `publish`.
Parameters
----------
header: MqttFixedHeader
f: file
Object with a read method.
Raises
------
DecodeError
When there are extra bytes at the end of the packet.
Returns
-------
int
Number of bytes consumed from ``f``.
MqttPublish
Object extracted from ``f``. | [
"Generates",
"a",
"MqttPublish",
"packet",
"given",
"a",
"MqttFixedHeader",
".",
"This",
"method",
"asserts",
"that",
"header",
".",
"packet_type",
"is",
"publish",
"."
] | 0f754250cc3f44f4376777e7e8b3676c5a4d413a | https://github.com/kcallin/mqtt-codec/blob/0f754250cc3f44f4376777e7e8b3676c5a4d413a/mqtt_codec/packet.py#L1269-L1316 | train | 54,970 |
kcallin/mqtt-codec | mqtt_codec/packet.py | MqttPubrel.decode_body | def decode_body(cls, header, f):
"""Generates a `MqttPubrel` packet given a
`MqttFixedHeader`. This method asserts that header.packet_type
is `pubrel`.
Parameters
----------
header: MqttFixedHeader
f: file
Object with a read method.
Raises
------
DecodeError
When there are extra bytes at the end of the packet.
Returns
-------
int
Number of bytes consumed from ``f``.
MqttPubrel
Object extracted from ``f``.
"""
assert header.packet_type == MqttControlPacketType.pubrel
decoder = mqtt_io.FileDecoder(mqtt_io.LimitReader(f, header.remaining_len))
packet_id, = decoder.unpack(mqtt_io.FIELD_U16)
if header.remaining_len != decoder.num_bytes_consumed:
raise DecodeError('Extra bytes at end of packet.')
return decoder.num_bytes_consumed, MqttPubrel(packet_id) | python | def decode_body(cls, header, f):
"""Generates a `MqttPubrel` packet given a
`MqttFixedHeader`. This method asserts that header.packet_type
is `pubrel`.
Parameters
----------
header: MqttFixedHeader
f: file
Object with a read method.
Raises
------
DecodeError
When there are extra bytes at the end of the packet.
Returns
-------
int
Number of bytes consumed from ``f``.
MqttPubrel
Object extracted from ``f``.
"""
assert header.packet_type == MqttControlPacketType.pubrel
decoder = mqtt_io.FileDecoder(mqtt_io.LimitReader(f, header.remaining_len))
packet_id, = decoder.unpack(mqtt_io.FIELD_U16)
if header.remaining_len != decoder.num_bytes_consumed:
raise DecodeError('Extra bytes at end of packet.')
return decoder.num_bytes_consumed, MqttPubrel(packet_id) | [
"def",
"decode_body",
"(",
"cls",
",",
"header",
",",
"f",
")",
":",
"assert",
"header",
".",
"packet_type",
"==",
"MqttControlPacketType",
".",
"pubrel",
"decoder",
"=",
"mqtt_io",
".",
"FileDecoder",
"(",
"mqtt_io",
".",
"LimitReader",
"(",
"f",
",",
"he... | Generates a `MqttPubrel` packet given a
`MqttFixedHeader`. This method asserts that header.packet_type
is `pubrel`.
Parameters
----------
header: MqttFixedHeader
f: file
Object with a read method.
Raises
------
DecodeError
When there are extra bytes at the end of the packet.
Returns
-------
int
Number of bytes consumed from ``f``.
MqttPubrel
Object extracted from ``f``. | [
"Generates",
"a",
"MqttPubrel",
"packet",
"given",
"a",
"MqttFixedHeader",
".",
"This",
"method",
"asserts",
"that",
"header",
".",
"packet_type",
"is",
"pubrel",
"."
] | 0f754250cc3f44f4376777e7e8b3676c5a4d413a | https://github.com/kcallin/mqtt-codec/blob/0f754250cc3f44f4376777e7e8b3676c5a4d413a/mqtt_codec/packet.py#L1513-L1544 | train | 54,971 |
kcallin/mqtt-codec | mqtt_codec/packet.py | MqttUnsubscribe.decode_body | def decode_body(cls, header, f):
"""Generates a `MqttUnsubscribe` packet given a
`MqttFixedHeader`. This method asserts that header.packet_type
is `unsubscribe`.
Parameters
----------
header: MqttFixedHeader
f: file
Object with a read method.
Raises
------
DecodeError
When there are extra bytes at the end of the packet.
Returns
-------
int
Number of bytes consumed from ``f``.
MqttUnsubscribe
Object extracted from ``f``.
"""
assert header.packet_type == MqttControlPacketType.unsubscribe
decoder = mqtt_io.FileDecoder(mqtt_io.LimitReader(f, header.remaining_len))
packet_id, = decoder.unpack(mqtt_io.FIELD_PACKET_ID)
topics = []
while header.remaining_len > decoder.num_bytes_consumed:
num_str_bytes, topic = decoder.unpack_utf8()
topics.append(topic)
assert header.remaining_len - decoder.num_bytes_consumed == 0
return decoder.num_bytes_consumed, MqttUnsubscribe(packet_id, topics) | python | def decode_body(cls, header, f):
"""Generates a `MqttUnsubscribe` packet given a
`MqttFixedHeader`. This method asserts that header.packet_type
is `unsubscribe`.
Parameters
----------
header: MqttFixedHeader
f: file
Object with a read method.
Raises
------
DecodeError
When there are extra bytes at the end of the packet.
Returns
-------
int
Number of bytes consumed from ``f``.
MqttUnsubscribe
Object extracted from ``f``.
"""
assert header.packet_type == MqttControlPacketType.unsubscribe
decoder = mqtt_io.FileDecoder(mqtt_io.LimitReader(f, header.remaining_len))
packet_id, = decoder.unpack(mqtt_io.FIELD_PACKET_ID)
topics = []
while header.remaining_len > decoder.num_bytes_consumed:
num_str_bytes, topic = decoder.unpack_utf8()
topics.append(topic)
assert header.remaining_len - decoder.num_bytes_consumed == 0
return decoder.num_bytes_consumed, MqttUnsubscribe(packet_id, topics) | [
"def",
"decode_body",
"(",
"cls",
",",
"header",
",",
"f",
")",
":",
"assert",
"header",
".",
"packet_type",
"==",
"MqttControlPacketType",
".",
"unsubscribe",
"decoder",
"=",
"mqtt_io",
".",
"FileDecoder",
"(",
"mqtt_io",
".",
"LimitReader",
"(",
"f",
",",
... | Generates a `MqttUnsubscribe` packet given a
`MqttFixedHeader`. This method asserts that header.packet_type
is `unsubscribe`.
Parameters
----------
header: MqttFixedHeader
f: file
Object with a read method.
Raises
------
DecodeError
When there are extra bytes at the end of the packet.
Returns
-------
int
Number of bytes consumed from ``f``.
MqttUnsubscribe
Object extracted from ``f``. | [
"Generates",
"a",
"MqttUnsubscribe",
"packet",
"given",
"a",
"MqttFixedHeader",
".",
"This",
"method",
"asserts",
"that",
"header",
".",
"packet_type",
"is",
"unsubscribe",
"."
] | 0f754250cc3f44f4376777e7e8b3676c5a4d413a | https://github.com/kcallin/mqtt-codec/blob/0f754250cc3f44f4376777e7e8b3676c5a4d413a/mqtt_codec/packet.py#L1690-L1725 | train | 54,972 |
kcallin/mqtt-codec | mqtt_codec/packet.py | MqttUnsuback.decode_body | def decode_body(cls, header, f):
"""Generates a `MqttUnsuback` packet given a
`MqttFixedHeader`. This method asserts that header.packet_type
is `unsuback`.
Parameters
----------
header: MqttFixedHeader
f: file
Object with a read method.
Raises
------
DecodeError
When there are extra bytes at the end of the packet.
Returns
-------
int
Number of bytes consumed from ``f``.
MqttUnsuback
Object extracted from ``f``.
"""
assert header.packet_type == MqttControlPacketType.unsuback
decoder = mqtt_io.FileDecoder(mqtt_io.LimitReader(f, header.remaining_len))
packet_id, = decoder.unpack(mqtt_io.FIELD_PACKET_ID)
if header.remaining_len != decoder.num_bytes_consumed:
raise DecodeError('Extra bytes at end of packet.')
return decoder.num_bytes_consumed, MqttUnsuback(packet_id) | python | def decode_body(cls, header, f):
"""Generates a `MqttUnsuback` packet given a
`MqttFixedHeader`. This method asserts that header.packet_type
is `unsuback`.
Parameters
----------
header: MqttFixedHeader
f: file
Object with a read method.
Raises
------
DecodeError
When there are extra bytes at the end of the packet.
Returns
-------
int
Number of bytes consumed from ``f``.
MqttUnsuback
Object extracted from ``f``.
"""
assert header.packet_type == MqttControlPacketType.unsuback
decoder = mqtt_io.FileDecoder(mqtt_io.LimitReader(f, header.remaining_len))
packet_id, = decoder.unpack(mqtt_io.FIELD_PACKET_ID)
if header.remaining_len != decoder.num_bytes_consumed:
raise DecodeError('Extra bytes at end of packet.')
return decoder.num_bytes_consumed, MqttUnsuback(packet_id) | [
"def",
"decode_body",
"(",
"cls",
",",
"header",
",",
"f",
")",
":",
"assert",
"header",
".",
"packet_type",
"==",
"MqttControlPacketType",
".",
"unsuback",
"decoder",
"=",
"mqtt_io",
".",
"FileDecoder",
"(",
"mqtt_io",
".",
"LimitReader",
"(",
"f",
",",
"... | Generates a `MqttUnsuback` packet given a
`MqttFixedHeader`. This method asserts that header.packet_type
is `unsuback`.
Parameters
----------
header: MqttFixedHeader
f: file
Object with a read method.
Raises
------
DecodeError
When there are extra bytes at the end of the packet.
Returns
-------
int
Number of bytes consumed from ``f``.
MqttUnsuback
Object extracted from ``f``. | [
"Generates",
"a",
"MqttUnsuback",
"packet",
"given",
"a",
"MqttFixedHeader",
".",
"This",
"method",
"asserts",
"that",
"header",
".",
"packet_type",
"is",
"unsuback",
"."
] | 0f754250cc3f44f4376777e7e8b3676c5a4d413a | https://github.com/kcallin/mqtt-codec/blob/0f754250cc3f44f4376777e7e8b3676c5a4d413a/mqtt_codec/packet.py#L1767-L1798 | train | 54,973 |
kcallin/mqtt-codec | mqtt_codec/packet.py | MqttPingreq.decode_body | def decode_body(cls, header, f):
"""Generates a `MqttPingreq` packet given a
`MqttFixedHeader`. This method asserts that header.packet_type
is `pingreq`.
Parameters
----------
header: MqttFixedHeader
f: file
Object with a read method.
Raises
------
DecodeError
When there are extra bytes at the end of the packet.
Returns
-------
int
Number of bytes consumed from ``f``.
MqttPingreq
Object extracted from ``f``.
"""
assert header.packet_type == MqttControlPacketType.pingreq
if header.remaining_len != 0:
raise DecodeError('Extra bytes at end of packet.')
return 0, MqttPingreq() | python | def decode_body(cls, header, f):
"""Generates a `MqttPingreq` packet given a
`MqttFixedHeader`. This method asserts that header.packet_type
is `pingreq`.
Parameters
----------
header: MqttFixedHeader
f: file
Object with a read method.
Raises
------
DecodeError
When there are extra bytes at the end of the packet.
Returns
-------
int
Number of bytes consumed from ``f``.
MqttPingreq
Object extracted from ``f``.
"""
assert header.packet_type == MqttControlPacketType.pingreq
if header.remaining_len != 0:
raise DecodeError('Extra bytes at end of packet.')
return 0, MqttPingreq() | [
"def",
"decode_body",
"(",
"cls",
",",
"header",
",",
"f",
")",
":",
"assert",
"header",
".",
"packet_type",
"==",
"MqttControlPacketType",
".",
"pingreq",
"if",
"header",
".",
"remaining_len",
"!=",
"0",
":",
"raise",
"DecodeError",
"(",
"'Extra bytes at end ... | Generates a `MqttPingreq` packet given a
`MqttFixedHeader`. This method asserts that header.packet_type
is `pingreq`.
Parameters
----------
header: MqttFixedHeader
f: file
Object with a read method.
Raises
------
DecodeError
When there are extra bytes at the end of the packet.
Returns
-------
int
Number of bytes consumed from ``f``.
MqttPingreq
Object extracted from ``f``. | [
"Generates",
"a",
"MqttPingreq",
"packet",
"given",
"a",
"MqttFixedHeader",
".",
"This",
"method",
"asserts",
"that",
"header",
".",
"packet_type",
"is",
"pingreq",
"."
] | 0f754250cc3f44f4376777e7e8b3676c5a4d413a | https://github.com/kcallin/mqtt-codec/blob/0f754250cc3f44f4376777e7e8b3676c5a4d413a/mqtt_codec/packet.py#L1828-L1856 | train | 54,974 |
kcallin/mqtt-codec | mqtt_codec/packet.py | MqttPingresp.decode_body | def decode_body(cls, header, f):
"""Generates a `MqttPingresp` packet given a
`MqttFixedHeader`. This method asserts that header.packet_type
is `pingresp`.
Parameters
----------
header: MqttFixedHeader
f: file
Object with a read method.
Raises
------
DecodeError
When there are extra bytes at the end of the packet.
Returns
-------
int
Number of bytes consumed from ``f``.
MqttPingresp
Object extracted from ``f``.
"""
assert header.packet_type == MqttControlPacketType.pingresp
if header.remaining_len != 0:
raise DecodeError('Extra bytes at end of packet.')
return 0, MqttPingresp() | python | def decode_body(cls, header, f):
"""Generates a `MqttPingresp` packet given a
`MqttFixedHeader`. This method asserts that header.packet_type
is `pingresp`.
Parameters
----------
header: MqttFixedHeader
f: file
Object with a read method.
Raises
------
DecodeError
When there are extra bytes at the end of the packet.
Returns
-------
int
Number of bytes consumed from ``f``.
MqttPingresp
Object extracted from ``f``.
"""
assert header.packet_type == MqttControlPacketType.pingresp
if header.remaining_len != 0:
raise DecodeError('Extra bytes at end of packet.')
return 0, MqttPingresp() | [
"def",
"decode_body",
"(",
"cls",
",",
"header",
",",
"f",
")",
":",
"assert",
"header",
".",
"packet_type",
"==",
"MqttControlPacketType",
".",
"pingresp",
"if",
"header",
".",
"remaining_len",
"!=",
"0",
":",
"raise",
"DecodeError",
"(",
"'Extra bytes at end... | Generates a `MqttPingresp` packet given a
`MqttFixedHeader`. This method asserts that header.packet_type
is `pingresp`.
Parameters
----------
header: MqttFixedHeader
f: file
Object with a read method.
Raises
------
DecodeError
When there are extra bytes at the end of the packet.
Returns
-------
int
Number of bytes consumed from ``f``.
MqttPingresp
Object extracted from ``f``. | [
"Generates",
"a",
"MqttPingresp",
"packet",
"given",
"a",
"MqttFixedHeader",
".",
"This",
"method",
"asserts",
"that",
"header",
".",
"packet_type",
"is",
"pingresp",
"."
] | 0f754250cc3f44f4376777e7e8b3676c5a4d413a | https://github.com/kcallin/mqtt-codec/blob/0f754250cc3f44f4376777e7e8b3676c5a4d413a/mqtt_codec/packet.py#L1884-L1912 | train | 54,975 |
legoktm/fab | phabricator/__init__.py | Phabricator.connect | def connect(self):
"""
Sets up your Phabricator session, it's not necessary to call
this directly
"""
if self.token:
self.phab_session = {'token': self.token}
return
req = self.req_session.post('%s/api/conduit.connect' % self.host, data={
'params': json.dumps(self.connect_params),
'output': 'json',
'__conduit__': True,
})
# Parse out the response (error handling ommitted)
result = req.json()['result']
self.phab_session = {
'sessionKey': result['sessionKey'],
'connectionID': result['connectionID'],
} | python | def connect(self):
"""
Sets up your Phabricator session, it's not necessary to call
this directly
"""
if self.token:
self.phab_session = {'token': self.token}
return
req = self.req_session.post('%s/api/conduit.connect' % self.host, data={
'params': json.dumps(self.connect_params),
'output': 'json',
'__conduit__': True,
})
# Parse out the response (error handling ommitted)
result = req.json()['result']
self.phab_session = {
'sessionKey': result['sessionKey'],
'connectionID': result['connectionID'],
} | [
"def",
"connect",
"(",
"self",
")",
":",
"if",
"self",
".",
"token",
":",
"self",
".",
"phab_session",
"=",
"{",
"'token'",
":",
"self",
".",
"token",
"}",
"return",
"req",
"=",
"self",
".",
"req_session",
".",
"post",
"(",
"'%s/api/conduit.connect'",
... | Sets up your Phabricator session, it's not necessary to call
this directly | [
"Sets",
"up",
"your",
"Phabricator",
"session",
"it",
"s",
"not",
"necessary",
"to",
"call",
"this",
"directly"
] | 29a8aba9671ae661864cbdb24e2ac9b842f41633 | https://github.com/legoktm/fab/blob/29a8aba9671ae661864cbdb24e2ac9b842f41633/phabricator/__init__.py#L56-L76 | train | 54,976 |
inveniosoftware/kwalitee | kwalitee/cli/githooks.py | install | def install(force=False):
"""Install git hooks."""
ret, git_dir, _ = run("git rev-parse --show-toplevel")
if ret != 0:
click.echo(
"ERROR: Please run from within a GIT repository.",
file=sys.stderr)
raise click.Abort
git_dir = git_dir[0]
hooks_dir = os.path.join(git_dir, HOOK_PATH)
for hook in HOOKS:
hook_path = os.path.join(hooks_dir, hook)
if os.path.exists(hook_path):
if not force:
click.echo(
"Hook already exists. Skipping {0}".format(hook_path),
file=sys.stderr)
continue
else:
os.unlink(hook_path)
source = os.path.join(sys.prefix, "bin", "kwalitee-" + hook)
os.symlink(os.path.normpath(source), hook_path)
return True | python | def install(force=False):
"""Install git hooks."""
ret, git_dir, _ = run("git rev-parse --show-toplevel")
if ret != 0:
click.echo(
"ERROR: Please run from within a GIT repository.",
file=sys.stderr)
raise click.Abort
git_dir = git_dir[0]
hooks_dir = os.path.join(git_dir, HOOK_PATH)
for hook in HOOKS:
hook_path = os.path.join(hooks_dir, hook)
if os.path.exists(hook_path):
if not force:
click.echo(
"Hook already exists. Skipping {0}".format(hook_path),
file=sys.stderr)
continue
else:
os.unlink(hook_path)
source = os.path.join(sys.prefix, "bin", "kwalitee-" + hook)
os.symlink(os.path.normpath(source), hook_path)
return True | [
"def",
"install",
"(",
"force",
"=",
"False",
")",
":",
"ret",
",",
"git_dir",
",",
"_",
"=",
"run",
"(",
"\"git rev-parse --show-toplevel\"",
")",
"if",
"ret",
"!=",
"0",
":",
"click",
".",
"echo",
"(",
"\"ERROR: Please run from within a GIT repository.\"",
"... | Install git hooks. | [
"Install",
"git",
"hooks",
"."
] | 9124f8f55b15547fef08c6c43cabced314e70674 | https://github.com/inveniosoftware/kwalitee/blob/9124f8f55b15547fef08c6c43cabced314e70674/kwalitee/cli/githooks.py#L51-L76 | train | 54,977 |
inveniosoftware/kwalitee | kwalitee/cli/githooks.py | uninstall | def uninstall():
"""Uninstall git hooks."""
ret, git_dir, _ = run("git rev-parse --show-toplevel")
if ret != 0:
click.echo(
"ERROR: Please run from within a GIT repository.",
file=sys.stderr)
raise click.Abort
git_dir = git_dir[0]
hooks_dir = os.path.join(git_dir, HOOK_PATH)
for hook in HOOKS:
hook_path = os.path.join(hooks_dir, hook)
if os.path.exists(hook_path):
os.remove(hook_path)
return True | python | def uninstall():
"""Uninstall git hooks."""
ret, git_dir, _ = run("git rev-parse --show-toplevel")
if ret != 0:
click.echo(
"ERROR: Please run from within a GIT repository.",
file=sys.stderr)
raise click.Abort
git_dir = git_dir[0]
hooks_dir = os.path.join(git_dir, HOOK_PATH)
for hook in HOOKS:
hook_path = os.path.join(hooks_dir, hook)
if os.path.exists(hook_path):
os.remove(hook_path)
return True | [
"def",
"uninstall",
"(",
")",
":",
"ret",
",",
"git_dir",
",",
"_",
"=",
"run",
"(",
"\"git rev-parse --show-toplevel\"",
")",
"if",
"ret",
"!=",
"0",
":",
"click",
".",
"echo",
"(",
"\"ERROR: Please run from within a GIT repository.\"",
",",
"file",
"=",
"sys... | Uninstall git hooks. | [
"Uninstall",
"git",
"hooks",
"."
] | 9124f8f55b15547fef08c6c43cabced314e70674 | https://github.com/inveniosoftware/kwalitee/blob/9124f8f55b15547fef08c6c43cabced314e70674/kwalitee/cli/githooks.py#L80-L96 | train | 54,978 |
evansde77/dockerstache | src/dockerstache/__init__.py | setup_logger | def setup_logger():
"""
setup basic logger
"""
logger = logging.getLogger('dockerstache')
logger.setLevel(logging.INFO)
handler = logging.StreamHandler(stream=sys.stdout)
handler.setLevel(logging.INFO)
logger.addHandler(handler)
return logger | python | def setup_logger():
"""
setup basic logger
"""
logger = logging.getLogger('dockerstache')
logger.setLevel(logging.INFO)
handler = logging.StreamHandler(stream=sys.stdout)
handler.setLevel(logging.INFO)
logger.addHandler(handler)
return logger | [
"def",
"setup_logger",
"(",
")",
":",
"logger",
"=",
"logging",
".",
"getLogger",
"(",
"'dockerstache'",
")",
"logger",
".",
"setLevel",
"(",
"logging",
".",
"INFO",
")",
"handler",
"=",
"logging",
".",
"StreamHandler",
"(",
"stream",
"=",
"sys",
".",
"s... | setup basic logger | [
"setup",
"basic",
"logger"
] | 929c102e9fffde322dbf17f8e69533a00976aacb | https://github.com/evansde77/dockerstache/blob/929c102e9fffde322dbf17f8e69533a00976aacb/src/dockerstache/__init__.py#L31-L40 | train | 54,979 |
nimbusproject/dashi | dashi/bootstrap/containers.py | named_any | def named_any(name):
"""
Retrieve a Python object by its fully qualified name from the global Python
module namespace. The first part of the name, that describes a module,
will be discovered and imported. Each subsequent part of the name is
treated as the name of an attribute of the object specified by all of the
name which came before it.
@param name: The name of the object to return.
@return: the Python object identified by 'name'.
"""
assert name, 'Empty module name'
names = name.split('.')
topLevelPackage = None
moduleNames = names[:]
while not topLevelPackage:
if moduleNames:
trialname = '.'.join(moduleNames)
try:
topLevelPackage = __import__(trialname)
except Exception, ex:
moduleNames.pop()
else:
if len(names) == 1:
raise Exception("No module named %r" % (name,))
else:
raise Exception('%r does not name an object' % (name,))
obj = topLevelPackage
for n in names[1:]:
obj = getattr(obj, n)
return obj | python | def named_any(name):
"""
Retrieve a Python object by its fully qualified name from the global Python
module namespace. The first part of the name, that describes a module,
will be discovered and imported. Each subsequent part of the name is
treated as the name of an attribute of the object specified by all of the
name which came before it.
@param name: The name of the object to return.
@return: the Python object identified by 'name'.
"""
assert name, 'Empty module name'
names = name.split('.')
topLevelPackage = None
moduleNames = names[:]
while not topLevelPackage:
if moduleNames:
trialname = '.'.join(moduleNames)
try:
topLevelPackage = __import__(trialname)
except Exception, ex:
moduleNames.pop()
else:
if len(names) == 1:
raise Exception("No module named %r" % (name,))
else:
raise Exception('%r does not name an object' % (name,))
obj = topLevelPackage
for n in names[1:]:
obj = getattr(obj, n)
return obj | [
"def",
"named_any",
"(",
"name",
")",
":",
"assert",
"name",
",",
"'Empty module name'",
"names",
"=",
"name",
".",
"split",
"(",
"'.'",
")",
"topLevelPackage",
"=",
"None",
"moduleNames",
"=",
"names",
"[",
":",
"]",
"while",
"not",
"topLevelPackage",
":"... | Retrieve a Python object by its fully qualified name from the global Python
module namespace. The first part of the name, that describes a module,
will be discovered and imported. Each subsequent part of the name is
treated as the name of an attribute of the object specified by all of the
name which came before it.
@param name: The name of the object to return.
@return: the Python object identified by 'name'. | [
"Retrieve",
"a",
"Python",
"object",
"by",
"its",
"fully",
"qualified",
"name",
"from",
"the",
"global",
"Python",
"module",
"namespace",
".",
"The",
"first",
"part",
"of",
"the",
"name",
"that",
"describes",
"a",
"module",
"will",
"be",
"discovered",
"and",... | 368b3963ec8abd60aebe0f81915429b45cbf4b5a | https://github.com/nimbusproject/dashi/blob/368b3963ec8abd60aebe0f81915429b45cbf4b5a/dashi/bootstrap/containers.py#L126-L158 | train | 54,980 |
nimbusproject/dashi | dashi/bootstrap/containers.py | for_name | def for_name(modpath, classname):
'''
Returns a class of "classname" from module "modname".
'''
module = __import__(modpath, fromlist=[classname])
classobj = getattr(module, classname)
return classobj() | python | def for_name(modpath, classname):
'''
Returns a class of "classname" from module "modname".
'''
module = __import__(modpath, fromlist=[classname])
classobj = getattr(module, classname)
return classobj() | [
"def",
"for_name",
"(",
"modpath",
",",
"classname",
")",
":",
"module",
"=",
"__import__",
"(",
"modpath",
",",
"fromlist",
"=",
"[",
"classname",
"]",
")",
"classobj",
"=",
"getattr",
"(",
"module",
",",
"classname",
")",
"return",
"classobj",
"(",
")"... | Returns a class of "classname" from module "modname". | [
"Returns",
"a",
"class",
"of",
"classname",
"from",
"module",
"modname",
"."
] | 368b3963ec8abd60aebe0f81915429b45cbf4b5a | https://github.com/nimbusproject/dashi/blob/368b3963ec8abd60aebe0f81915429b45cbf4b5a/dashi/bootstrap/containers.py#L160-L166 | train | 54,981 |
nimbusproject/dashi | dashi/bootstrap/containers.py | DotNotationGetItem._convert | def _convert(self, val):
""" Convert the type if necessary and return if a conversion happened. """
if isinstance(val, dict) and not isinstance(val, DotDict):
return DotDict(val), True
elif isinstance(val, list) and not isinstance(val, DotList):
return DotList(val), True
return val, False | python | def _convert(self, val):
""" Convert the type if necessary and return if a conversion happened. """
if isinstance(val, dict) and not isinstance(val, DotDict):
return DotDict(val), True
elif isinstance(val, list) and not isinstance(val, DotList):
return DotList(val), True
return val, False | [
"def",
"_convert",
"(",
"self",
",",
"val",
")",
":",
"if",
"isinstance",
"(",
"val",
",",
"dict",
")",
"and",
"not",
"isinstance",
"(",
"val",
",",
"DotDict",
")",
":",
"return",
"DotDict",
"(",
"val",
")",
",",
"True",
"elif",
"isinstance",
"(",
... | Convert the type if necessary and return if a conversion happened. | [
"Convert",
"the",
"type",
"if",
"necessary",
"and",
"return",
"if",
"a",
"conversion",
"happened",
"."
] | 368b3963ec8abd60aebe0f81915429b45cbf4b5a | https://github.com/nimbusproject/dashi/blob/368b3963ec8abd60aebe0f81915429b45cbf4b5a/dashi/bootstrap/containers.py#L11-L18 | train | 54,982 |
mdickinson/refcycle | refcycle/annotated_graph.py | AnnotatedGraph.to_json | def to_json(self):
"""
Convert to a JSON string.
"""
obj = {
"vertices": [
{
"id": vertex.id,
"annotation": vertex.annotation,
}
for vertex in self.vertices
],
"edges": [
{
"id": edge.id,
"annotation": edge.annotation,
"head": edge.head,
"tail": edge.tail,
}
for edge in self._edges
],
}
# Ensure that we always return unicode output on Python 2.
return six.text_type(json.dumps(obj, ensure_ascii=False)) | python | def to_json(self):
"""
Convert to a JSON string.
"""
obj = {
"vertices": [
{
"id": vertex.id,
"annotation": vertex.annotation,
}
for vertex in self.vertices
],
"edges": [
{
"id": edge.id,
"annotation": edge.annotation,
"head": edge.head,
"tail": edge.tail,
}
for edge in self._edges
],
}
# Ensure that we always return unicode output on Python 2.
return six.text_type(json.dumps(obj, ensure_ascii=False)) | [
"def",
"to_json",
"(",
"self",
")",
":",
"obj",
"=",
"{",
"\"vertices\"",
":",
"[",
"{",
"\"id\"",
":",
"vertex",
".",
"id",
",",
"\"annotation\"",
":",
"vertex",
".",
"annotation",
",",
"}",
"for",
"vertex",
"in",
"self",
".",
"vertices",
"]",
",",
... | Convert to a JSON string. | [
"Convert",
"to",
"a",
"JSON",
"string",
"."
] | 627fad74c74efc601209c96405f8118cd99b2241 | https://github.com/mdickinson/refcycle/blob/627fad74c74efc601209c96405f8118cd99b2241/refcycle/annotated_graph.py#L199-L223 | train | 54,983 |
mdickinson/refcycle | refcycle/annotated_graph.py | AnnotatedGraph.from_json | def from_json(cls, json_graph):
"""
Reconstruct the graph from a graph exported to JSON.
"""
obj = json.loads(json_graph)
vertices = [
AnnotatedVertex(
id=vertex["id"],
annotation=vertex["annotation"],
)
for vertex in obj["vertices"]
]
edges = [
AnnotatedEdge(
id=edge["id"],
annotation=edge["annotation"],
head=edge["head"],
tail=edge["tail"],
)
for edge in obj["edges"]
]
return cls(vertices=vertices, edges=edges) | python | def from_json(cls, json_graph):
"""
Reconstruct the graph from a graph exported to JSON.
"""
obj = json.loads(json_graph)
vertices = [
AnnotatedVertex(
id=vertex["id"],
annotation=vertex["annotation"],
)
for vertex in obj["vertices"]
]
edges = [
AnnotatedEdge(
id=edge["id"],
annotation=edge["annotation"],
head=edge["head"],
tail=edge["tail"],
)
for edge in obj["edges"]
]
return cls(vertices=vertices, edges=edges) | [
"def",
"from_json",
"(",
"cls",
",",
"json_graph",
")",
":",
"obj",
"=",
"json",
".",
"loads",
"(",
"json_graph",
")",
"vertices",
"=",
"[",
"AnnotatedVertex",
"(",
"id",
"=",
"vertex",
"[",
"\"id\"",
"]",
",",
"annotation",
"=",
"vertex",
"[",
"\"anno... | Reconstruct the graph from a graph exported to JSON. | [
"Reconstruct",
"the",
"graph",
"from",
"a",
"graph",
"exported",
"to",
"JSON",
"."
] | 627fad74c74efc601209c96405f8118cd99b2241 | https://github.com/mdickinson/refcycle/blob/627fad74c74efc601209c96405f8118cd99b2241/refcycle/annotated_graph.py#L226-L251 | train | 54,984 |
mdickinson/refcycle | refcycle/annotated_graph.py | AnnotatedGraph.export_json | def export_json(self, filename):
"""
Export graph in JSON form to the given file.
"""
json_graph = self.to_json()
with open(filename, 'wb') as f:
f.write(json_graph.encode('utf-8')) | python | def export_json(self, filename):
"""
Export graph in JSON form to the given file.
"""
json_graph = self.to_json()
with open(filename, 'wb') as f:
f.write(json_graph.encode('utf-8')) | [
"def",
"export_json",
"(",
"self",
",",
"filename",
")",
":",
"json_graph",
"=",
"self",
".",
"to_json",
"(",
")",
"with",
"open",
"(",
"filename",
",",
"'wb'",
")",
"as",
"f",
":",
"f",
".",
"write",
"(",
"json_graph",
".",
"encode",
"(",
"'utf-8'",... | Export graph in JSON form to the given file. | [
"Export",
"graph",
"in",
"JSON",
"form",
"to",
"the",
"given",
"file",
"."
] | 627fad74c74efc601209c96405f8118cd99b2241 | https://github.com/mdickinson/refcycle/blob/627fad74c74efc601209c96405f8118cd99b2241/refcycle/annotated_graph.py#L253-L260 | train | 54,985 |
mdickinson/refcycle | refcycle/annotated_graph.py | AnnotatedGraph.import_json | def import_json(cls, filename):
"""
Import graph from the given file. The file is expected
to contain UTF-8 encoded JSON data.
"""
with open(filename, 'rb') as f:
json_graph = f.read().decode('utf-8')
return cls.from_json(json_graph) | python | def import_json(cls, filename):
"""
Import graph from the given file. The file is expected
to contain UTF-8 encoded JSON data.
"""
with open(filename, 'rb') as f:
json_graph = f.read().decode('utf-8')
return cls.from_json(json_graph) | [
"def",
"import_json",
"(",
"cls",
",",
"filename",
")",
":",
"with",
"open",
"(",
"filename",
",",
"'rb'",
")",
"as",
"f",
":",
"json_graph",
"=",
"f",
".",
"read",
"(",
")",
".",
"decode",
"(",
"'utf-8'",
")",
"return",
"cls",
".",
"from_json",
"(... | Import graph from the given file. The file is expected
to contain UTF-8 encoded JSON data. | [
"Import",
"graph",
"from",
"the",
"given",
"file",
".",
"The",
"file",
"is",
"expected",
"to",
"contain",
"UTF",
"-",
"8",
"encoded",
"JSON",
"data",
"."
] | 627fad74c74efc601209c96405f8118cd99b2241 | https://github.com/mdickinson/refcycle/blob/627fad74c74efc601209c96405f8118cd99b2241/refcycle/annotated_graph.py#L263-L271 | train | 54,986 |
mdickinson/refcycle | refcycle/annotated_graph.py | AnnotatedGraph.to_dot | def to_dot(self):
"""
Produce a graph in DOT format.
"""
edge_labels = {
edge.id: edge.annotation
for edge in self._edges
}
edges = [self._format_edge(edge_labels, edge) for edge in self._edges]
vertices = [
DOT_VERTEX_TEMPLATE.format(
vertex=vertex.id,
label=dot_quote(vertex.annotation),
)
for vertex in self.vertices
]
return DOT_DIGRAPH_TEMPLATE.format(
edges="".join(edges),
vertices="".join(vertices),
) | python | def to_dot(self):
"""
Produce a graph in DOT format.
"""
edge_labels = {
edge.id: edge.annotation
for edge in self._edges
}
edges = [self._format_edge(edge_labels, edge) for edge in self._edges]
vertices = [
DOT_VERTEX_TEMPLATE.format(
vertex=vertex.id,
label=dot_quote(vertex.annotation),
)
for vertex in self.vertices
]
return DOT_DIGRAPH_TEMPLATE.format(
edges="".join(edges),
vertices="".join(vertices),
) | [
"def",
"to_dot",
"(",
"self",
")",
":",
"edge_labels",
"=",
"{",
"edge",
".",
"id",
":",
"edge",
".",
"annotation",
"for",
"edge",
"in",
"self",
".",
"_edges",
"}",
"edges",
"=",
"[",
"self",
".",
"_format_edge",
"(",
"edge_labels",
",",
"edge",
")",... | Produce a graph in DOT format. | [
"Produce",
"a",
"graph",
"in",
"DOT",
"format",
"."
] | 627fad74c74efc601209c96405f8118cd99b2241 | https://github.com/mdickinson/refcycle/blob/627fad74c74efc601209c96405f8118cd99b2241/refcycle/annotated_graph.py#L293-L316 | train | 54,987 |
toumorokoshi/sprinter | sprinter/external/brew.py | install_brew | def install_brew(target_path):
""" Install brew to the target path """
if not os.path.exists(target_path):
try:
os.makedirs(target_path)
except OSError:
logger.warn("Unable to create directory %s for brew." % target_path)
logger.warn("Skipping...")
return
extract_targz(HOMEBREW_URL, target_path, remove_common_prefix=True) | python | def install_brew(target_path):
""" Install brew to the target path """
if not os.path.exists(target_path):
try:
os.makedirs(target_path)
except OSError:
logger.warn("Unable to create directory %s for brew." % target_path)
logger.warn("Skipping...")
return
extract_targz(HOMEBREW_URL, target_path, remove_common_prefix=True) | [
"def",
"install_brew",
"(",
"target_path",
")",
":",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"target_path",
")",
":",
"try",
":",
"os",
".",
"makedirs",
"(",
"target_path",
")",
"except",
"OSError",
":",
"logger",
".",
"warn",
"(",
"\"Unabl... | Install brew to the target path | [
"Install",
"brew",
"to",
"the",
"target",
"path"
] | 846697a7a087e69c61d075232e754d6975a64152 | https://github.com/toumorokoshi/sprinter/blob/846697a7a087e69c61d075232e754d6975a64152/sprinter/external/brew.py#L14-L23 | train | 54,988 |
frascoweb/frasco | frasco/services.py | pass_service | def pass_service(*names):
"""Injects a service instance into the kwargs
"""
def decorator(f):
@functools.wraps(f)
def wrapper(*args, **kwargs):
for name in names:
kwargs[name] = service_proxy(name)
return f(*args, **kwargs)
return wrapper
return decorator | python | def pass_service(*names):
"""Injects a service instance into the kwargs
"""
def decorator(f):
@functools.wraps(f)
def wrapper(*args, **kwargs):
for name in names:
kwargs[name] = service_proxy(name)
return f(*args, **kwargs)
return wrapper
return decorator | [
"def",
"pass_service",
"(",
"*",
"names",
")",
":",
"def",
"decorator",
"(",
"f",
")",
":",
"@",
"functools",
".",
"wraps",
"(",
"f",
")",
"def",
"wrapper",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"for",
"name",
"in",
"names",
":",
... | Injects a service instance into the kwargs | [
"Injects",
"a",
"service",
"instance",
"into",
"the",
"kwargs"
] | ea519d69dd5ca6deaf3650175692ee4a1a02518f | https://github.com/frascoweb/frasco/blob/ea519d69dd5ca6deaf3650175692ee4a1a02518f/frasco/services.py#L54-L64 | train | 54,989 |
memphis-iis/GLUDB | gludb/backends/dynamodb.py | get_conn | def get_conn():
"""Return a connection to DynamoDB."""
if os.environ.get('DEBUG', False) or os.environ.get('travis', False):
# In DEBUG mode - use the local DynamoDB
# This also works for travis since we'll be running dynalite
conn = DynamoDBConnection(
host='localhost',
port=8000,
aws_access_key_id='TEST',
aws_secret_access_key='TEST',
is_secure=False
)
else:
# Regular old production
conn = DynamoDBConnection()
return conn | python | def get_conn():
"""Return a connection to DynamoDB."""
if os.environ.get('DEBUG', False) or os.environ.get('travis', False):
# In DEBUG mode - use the local DynamoDB
# This also works for travis since we'll be running dynalite
conn = DynamoDBConnection(
host='localhost',
port=8000,
aws_access_key_id='TEST',
aws_secret_access_key='TEST',
is_secure=False
)
else:
# Regular old production
conn = DynamoDBConnection()
return conn | [
"def",
"get_conn",
"(",
")",
":",
"if",
"os",
".",
"environ",
".",
"get",
"(",
"'DEBUG'",
",",
"False",
")",
"or",
"os",
".",
"environ",
".",
"get",
"(",
"'travis'",
",",
"False",
")",
":",
"# In DEBUG mode - use the local DynamoDB",
"# This also works for t... | Return a connection to DynamoDB. | [
"Return",
"a",
"connection",
"to",
"DynamoDB",
"."
] | 25692528ff6fe8184a3570f61f31f1a90088a388 | https://github.com/memphis-iis/GLUDB/blob/25692528ff6fe8184a3570f61f31f1a90088a388/gludb/backends/dynamodb.py#L19-L35 | train | 54,990 |
memphis-iis/GLUDB | gludb/backends/dynamodb.py | Backend.table_schema_call | def table_schema_call(self, target, cls):
"""Perform a table schema call.
We call the callable target with the args and keywords needed for the
table defined by cls. This is how we centralize the Table.create and
Table ctor calls.
"""
index_defs = []
for name in cls.index_names() or []:
index_defs.append(GlobalIncludeIndex(
gsi_name(name),
parts=[HashKey(name)],
includes=['value']
))
return target(
cls.get_table_name(),
connection=get_conn(),
schema=[HashKey('id')],
global_indexes=index_defs or None
) | python | def table_schema_call(self, target, cls):
"""Perform a table schema call.
We call the callable target with the args and keywords needed for the
table defined by cls. This is how we centralize the Table.create and
Table ctor calls.
"""
index_defs = []
for name in cls.index_names() or []:
index_defs.append(GlobalIncludeIndex(
gsi_name(name),
parts=[HashKey(name)],
includes=['value']
))
return target(
cls.get_table_name(),
connection=get_conn(),
schema=[HashKey('id')],
global_indexes=index_defs or None
) | [
"def",
"table_schema_call",
"(",
"self",
",",
"target",
",",
"cls",
")",
":",
"index_defs",
"=",
"[",
"]",
"for",
"name",
"in",
"cls",
".",
"index_names",
"(",
")",
"or",
"[",
"]",
":",
"index_defs",
".",
"append",
"(",
"GlobalIncludeIndex",
"(",
"gsi_... | Perform a table schema call.
We call the callable target with the args and keywords needed for the
table defined by cls. This is how we centralize the Table.create and
Table ctor calls. | [
"Perform",
"a",
"table",
"schema",
"call",
"."
] | 25692528ff6fe8184a3570f61f31f1a90088a388 | https://github.com/memphis-iis/GLUDB/blob/25692528ff6fe8184a3570f61f31f1a90088a388/gludb/backends/dynamodb.py#L94-L114 | train | 54,991 |
maikelboogerd/eventcore | eventcore/consumer.py | Consumer.thread | def thread(self):
"""
Start a thread for this consumer.
"""
log.info('@{}.thread starting'.format(self.__class__.__name__))
thread = threading.Thread(target=thread_wrapper(self.consume), args=())
thread.daemon = True
thread.start() | python | def thread(self):
"""
Start a thread for this consumer.
"""
log.info('@{}.thread starting'.format(self.__class__.__name__))
thread = threading.Thread(target=thread_wrapper(self.consume), args=())
thread.daemon = True
thread.start() | [
"def",
"thread",
"(",
"self",
")",
":",
"log",
".",
"info",
"(",
"'@{}.thread starting'",
".",
"format",
"(",
"self",
".",
"__class__",
".",
"__name__",
")",
")",
"thread",
"=",
"threading",
".",
"Thread",
"(",
"target",
"=",
"thread_wrapper",
"(",
"self... | Start a thread for this consumer. | [
"Start",
"a",
"thread",
"for",
"this",
"consumer",
"."
] | 3675f15344d70111874e0f5e5d3305c925dd38d4 | https://github.com/maikelboogerd/eventcore/blob/3675f15344d70111874e0f5e5d3305c925dd38d4/eventcore/consumer.py#L58-L65 | train | 54,992 |
smarie/python-parsyfiles | parsyfiles/parsing_core.py | _BaseParser._parse_multifile | def _parse_multifile(self, desired_type: Type[T], obj: PersistedObject,
parsing_plan_for_children: Dict[str, ParsingPlan], logger: Logger,
options: Dict[str, Dict[str, Any]]) -> T:
"""
First parse all children from the parsing plan, then calls _build_object_from_parsed_children
:param desired_type:
:param obj:
:param parsing_plan_for_children:
:param logger:
:param options:
:return:
"""
pass | python | def _parse_multifile(self, desired_type: Type[T], obj: PersistedObject,
parsing_plan_for_children: Dict[str, ParsingPlan], logger: Logger,
options: Dict[str, Dict[str, Any]]) -> T:
"""
First parse all children from the parsing plan, then calls _build_object_from_parsed_children
:param desired_type:
:param obj:
:param parsing_plan_for_children:
:param logger:
:param options:
:return:
"""
pass | [
"def",
"_parse_multifile",
"(",
"self",
",",
"desired_type",
":",
"Type",
"[",
"T",
"]",
",",
"obj",
":",
"PersistedObject",
",",
"parsing_plan_for_children",
":",
"Dict",
"[",
"str",
",",
"ParsingPlan",
"]",
",",
"logger",
":",
"Logger",
",",
"options",
"... | First parse all children from the parsing plan, then calls _build_object_from_parsed_children
:param desired_type:
:param obj:
:param parsing_plan_for_children:
:param logger:
:param options:
:return: | [
"First",
"parse",
"all",
"children",
"from",
"the",
"parsing",
"plan",
"then",
"calls",
"_build_object_from_parsed_children"
] | 344b37e1151e8d4e7c2ee49ae09d6568715ae64e | https://github.com/smarie/python-parsyfiles/blob/344b37e1151e8d4e7c2ee49ae09d6568715ae64e/parsyfiles/parsing_core.py#L71-L84 | train | 54,993 |
smarie/python-parsyfiles | parsyfiles/parsing_core.py | _BaseParsingPlan.execute | def execute(self, logger: Logger, options: Dict[str, Dict[str, Any]]) -> T:
"""
Overrides the parent method to add log messages.
:param logger: the logger to use during parsing (optional: None is supported)
:param options:
:return:
"""
in_root_call = False
if logger is not None:
# log only for the root object, not for the children that will be created by the code below
if not hasattr(_BaseParsingPlan.thrd_locals, 'flag_exec') \
or _BaseParsingPlan.thrd_locals.flag_exec == 0:
# print('Executing Parsing Plan for ' + str(self))
logger.debug('Executing Parsing Plan for [{location}]'
''.format(location=self.obj_on_fs_to_parse.get_pretty_location(append_file_ext=False)))
_BaseParsingPlan.thrd_locals.flag_exec = 1
in_root_call = True
# Common log message
logger.debug('(P) ' + get_parsing_plan_log_str(self.obj_on_fs_to_parse, self.obj_type,
log_only_last=not in_root_call, parser=self.parser))
try:
res = super(_BaseParsingPlan, self).execute(logger, options)
if logger.isEnabledFor(DEBUG):
logger.info('(P) {loc} -> {type} SUCCESS !'
''.format(loc=self.obj_on_fs_to_parse.get_pretty_location(
blank_parent_part=not GLOBAL_CONFIG.full_paths_in_logs,
compact_file_ext=True),
type=get_pretty_type_str(self.obj_type)))
else:
logger.info('SUCCESS parsed [{loc}] as a [{type}] successfully. Parser used was [{parser}]'
''.format(loc=self.obj_on_fs_to_parse.get_pretty_location(compact_file_ext=True),
type=get_pretty_type_str(self.obj_type),
parser=str(self.parser)))
if in_root_call:
# print('Completed parsing successfully')
logger.debug('Completed parsing successfully')
return res
finally:
# remove threadlocal flag if needed
if in_root_call:
_BaseParsingPlan.thrd_locals.flag_exec = 0 | python | def execute(self, logger: Logger, options: Dict[str, Dict[str, Any]]) -> T:
"""
Overrides the parent method to add log messages.
:param logger: the logger to use during parsing (optional: None is supported)
:param options:
:return:
"""
in_root_call = False
if logger is not None:
# log only for the root object, not for the children that will be created by the code below
if not hasattr(_BaseParsingPlan.thrd_locals, 'flag_exec') \
or _BaseParsingPlan.thrd_locals.flag_exec == 0:
# print('Executing Parsing Plan for ' + str(self))
logger.debug('Executing Parsing Plan for [{location}]'
''.format(location=self.obj_on_fs_to_parse.get_pretty_location(append_file_ext=False)))
_BaseParsingPlan.thrd_locals.flag_exec = 1
in_root_call = True
# Common log message
logger.debug('(P) ' + get_parsing_plan_log_str(self.obj_on_fs_to_parse, self.obj_type,
log_only_last=not in_root_call, parser=self.parser))
try:
res = super(_BaseParsingPlan, self).execute(logger, options)
if logger.isEnabledFor(DEBUG):
logger.info('(P) {loc} -> {type} SUCCESS !'
''.format(loc=self.obj_on_fs_to_parse.get_pretty_location(
blank_parent_part=not GLOBAL_CONFIG.full_paths_in_logs,
compact_file_ext=True),
type=get_pretty_type_str(self.obj_type)))
else:
logger.info('SUCCESS parsed [{loc}] as a [{type}] successfully. Parser used was [{parser}]'
''.format(loc=self.obj_on_fs_to_parse.get_pretty_location(compact_file_ext=True),
type=get_pretty_type_str(self.obj_type),
parser=str(self.parser)))
if in_root_call:
# print('Completed parsing successfully')
logger.debug('Completed parsing successfully')
return res
finally:
# remove threadlocal flag if needed
if in_root_call:
_BaseParsingPlan.thrd_locals.flag_exec = 0 | [
"def",
"execute",
"(",
"self",
",",
"logger",
":",
"Logger",
",",
"options",
":",
"Dict",
"[",
"str",
",",
"Dict",
"[",
"str",
",",
"Any",
"]",
"]",
")",
"->",
"T",
":",
"in_root_call",
"=",
"False",
"if",
"logger",
"is",
"not",
"None",
":",
"# l... | Overrides the parent method to add log messages.
:param logger: the logger to use during parsing (optional: None is supported)
:param options:
:return: | [
"Overrides",
"the",
"parent",
"method",
"to",
"add",
"log",
"messages",
"."
] | 344b37e1151e8d4e7c2ee49ae09d6568715ae64e | https://github.com/smarie/python-parsyfiles/blob/344b37e1151e8d4e7c2ee49ae09d6568715ae64e/parsyfiles/parsing_core.py#L115-L159 | train | 54,994 |
smarie/python-parsyfiles | parsyfiles/parsing_core.py | _BaseParsingPlan._execute | def _execute(self, logger: Logger, options: Dict[str, Dict[str, Any]]) -> T:
"""
Implementation of the parent class method.
Checks that self.parser is a _BaseParser, and calls the appropriate parsing method.
:param logger:
:param options:
:return:
"""
if isinstance(self.parser, _BaseParser):
if (not self.is_singlefile) and self.parser.supports_multifile():
return self.parser._parse_multifile(self.obj_type, self.obj_on_fs_to_parse,
self._get_children_parsing_plan(), logger, options)
elif self.is_singlefile and self.parser.supports_singlefile():
return self.parser._parse_singlefile(self.obj_type, self.get_singlefile_path(),
self.get_singlefile_encoding(), logger, options)
else:
raise _InvalidParserException.create(self.parser, self.obj_on_fs_to_parse)
else:
raise TypeError('Parser attached to this _BaseParsingPlan is not a ' + str(_BaseParser)) | python | def _execute(self, logger: Logger, options: Dict[str, Dict[str, Any]]) -> T:
"""
Implementation of the parent class method.
Checks that self.parser is a _BaseParser, and calls the appropriate parsing method.
:param logger:
:param options:
:return:
"""
if isinstance(self.parser, _BaseParser):
if (not self.is_singlefile) and self.parser.supports_multifile():
return self.parser._parse_multifile(self.obj_type, self.obj_on_fs_to_parse,
self._get_children_parsing_plan(), logger, options)
elif self.is_singlefile and self.parser.supports_singlefile():
return self.parser._parse_singlefile(self.obj_type, self.get_singlefile_path(),
self.get_singlefile_encoding(), logger, options)
else:
raise _InvalidParserException.create(self.parser, self.obj_on_fs_to_parse)
else:
raise TypeError('Parser attached to this _BaseParsingPlan is not a ' + str(_BaseParser)) | [
"def",
"_execute",
"(",
"self",
",",
"logger",
":",
"Logger",
",",
"options",
":",
"Dict",
"[",
"str",
",",
"Dict",
"[",
"str",
",",
"Any",
"]",
"]",
")",
"->",
"T",
":",
"if",
"isinstance",
"(",
"self",
".",
"parser",
",",
"_BaseParser",
")",
":... | Implementation of the parent class method.
Checks that self.parser is a _BaseParser, and calls the appropriate parsing method.
:param logger:
:param options:
:return: | [
"Implementation",
"of",
"the",
"parent",
"class",
"method",
".",
"Checks",
"that",
"self",
".",
"parser",
"is",
"a",
"_BaseParser",
"and",
"calls",
"the",
"appropriate",
"parsing",
"method",
"."
] | 344b37e1151e8d4e7c2ee49ae09d6568715ae64e | https://github.com/smarie/python-parsyfiles/blob/344b37e1151e8d4e7c2ee49ae09d6568715ae64e/parsyfiles/parsing_core.py#L161-L181 | train | 54,995 |
smarie/python-parsyfiles | parsyfiles/parsing_core.py | AnyParser.create_parsing_plan | def create_parsing_plan(self, desired_type: Type[T], filesystem_object: PersistedObject, logger: Logger,
_main_call: bool = True):
"""
Implements the abstract parent method by using the recursive parsing plan impl. Subclasses wishing to produce
their own parsing plans should rather override _create_parsing_plan in order to benefit from this same log msg.
:param desired_type:
:param filesystem_object:
:param logger:
:param _main_call: internal parameter for recursive calls. Should not be changed by the user.
:return:
"""
in_root_call = False
# -- log msg only for the root call, not for the children that will be created by the code below
if _main_call and (not hasattr(AnyParser.thrd_locals, 'flag_init') or AnyParser.thrd_locals.flag_init == 0):
# print('Building a parsing plan to parse ' + str(filesystem_object) + ' into a ' +
# get_pretty_type_str(desired_type))
logger.debug('Building a parsing plan to parse [{location}] into a {type}'
''.format(location=filesystem_object.get_pretty_location(append_file_ext=False),
type=get_pretty_type_str(desired_type)))
AnyParser.thrd_locals.flag_init = 1
in_root_call = True
# -- create the parsing plan
try:
pp = self._create_parsing_plan(desired_type, filesystem_object, logger, log_only_last=(not _main_call))
finally:
# remove threadlocal flag if needed
if in_root_call:
AnyParser.thrd_locals.flag_init = 0
# -- log success only if in root call
if in_root_call:
# print('Parsing Plan created successfully')
logger.debug('Parsing Plan created successfully')
# -- finally return
return pp | python | def create_parsing_plan(self, desired_type: Type[T], filesystem_object: PersistedObject, logger: Logger,
_main_call: bool = True):
"""
Implements the abstract parent method by using the recursive parsing plan impl. Subclasses wishing to produce
their own parsing plans should rather override _create_parsing_plan in order to benefit from this same log msg.
:param desired_type:
:param filesystem_object:
:param logger:
:param _main_call: internal parameter for recursive calls. Should not be changed by the user.
:return:
"""
in_root_call = False
# -- log msg only for the root call, not for the children that will be created by the code below
if _main_call and (not hasattr(AnyParser.thrd_locals, 'flag_init') or AnyParser.thrd_locals.flag_init == 0):
# print('Building a parsing plan to parse ' + str(filesystem_object) + ' into a ' +
# get_pretty_type_str(desired_type))
logger.debug('Building a parsing plan to parse [{location}] into a {type}'
''.format(location=filesystem_object.get_pretty_location(append_file_ext=False),
type=get_pretty_type_str(desired_type)))
AnyParser.thrd_locals.flag_init = 1
in_root_call = True
# -- create the parsing plan
try:
pp = self._create_parsing_plan(desired_type, filesystem_object, logger, log_only_last=(not _main_call))
finally:
# remove threadlocal flag if needed
if in_root_call:
AnyParser.thrd_locals.flag_init = 0
# -- log success only if in root call
if in_root_call:
# print('Parsing Plan created successfully')
logger.debug('Parsing Plan created successfully')
# -- finally return
return pp | [
"def",
"create_parsing_plan",
"(",
"self",
",",
"desired_type",
":",
"Type",
"[",
"T",
"]",
",",
"filesystem_object",
":",
"PersistedObject",
",",
"logger",
":",
"Logger",
",",
"_main_call",
":",
"bool",
"=",
"True",
")",
":",
"in_root_call",
"=",
"False",
... | Implements the abstract parent method by using the recursive parsing plan impl. Subclasses wishing to produce
their own parsing plans should rather override _create_parsing_plan in order to benefit from this same log msg.
:param desired_type:
:param filesystem_object:
:param logger:
:param _main_call: internal parameter for recursive calls. Should not be changed by the user.
:return: | [
"Implements",
"the",
"abstract",
"parent",
"method",
"by",
"using",
"the",
"recursive",
"parsing",
"plan",
"impl",
".",
"Subclasses",
"wishing",
"to",
"produce",
"their",
"own",
"parsing",
"plans",
"should",
"rather",
"override",
"_create_parsing_plan",
"in",
"ord... | 344b37e1151e8d4e7c2ee49ae09d6568715ae64e | https://github.com/smarie/python-parsyfiles/blob/344b37e1151e8d4e7c2ee49ae09d6568715ae64e/parsyfiles/parsing_core.py#L266-L304 | train | 54,996 |
smarie/python-parsyfiles | parsyfiles/parsing_core.py | AnyParser._create_parsing_plan | def _create_parsing_plan(self, desired_type: Type[T], filesystem_object: PersistedObject, logger: Logger,
log_only_last: bool = False):
"""
Adds a log message and creates a recursive parsing plan.
:param desired_type:
:param filesystem_object:
:param logger:
:param log_only_last: a flag to only log the last part of the file path (default False)
:return:
"""
logger.debug('(B) ' + get_parsing_plan_log_str(filesystem_object, desired_type,
log_only_last=log_only_last, parser=self))
return AnyParser._RecursiveParsingPlan(desired_type, filesystem_object, self, logger) | python | def _create_parsing_plan(self, desired_type: Type[T], filesystem_object: PersistedObject, logger: Logger,
log_only_last: bool = False):
"""
Adds a log message and creates a recursive parsing plan.
:param desired_type:
:param filesystem_object:
:param logger:
:param log_only_last: a flag to only log the last part of the file path (default False)
:return:
"""
logger.debug('(B) ' + get_parsing_plan_log_str(filesystem_object, desired_type,
log_only_last=log_only_last, parser=self))
return AnyParser._RecursiveParsingPlan(desired_type, filesystem_object, self, logger) | [
"def",
"_create_parsing_plan",
"(",
"self",
",",
"desired_type",
":",
"Type",
"[",
"T",
"]",
",",
"filesystem_object",
":",
"PersistedObject",
",",
"logger",
":",
"Logger",
",",
"log_only_last",
":",
"bool",
"=",
"False",
")",
":",
"logger",
".",
"debug",
... | Adds a log message and creates a recursive parsing plan.
:param desired_type:
:param filesystem_object:
:param logger:
:param log_only_last: a flag to only log the last part of the file path (default False)
:return: | [
"Adds",
"a",
"log",
"message",
"and",
"creates",
"a",
"recursive",
"parsing",
"plan",
"."
] | 344b37e1151e8d4e7c2ee49ae09d6568715ae64e | https://github.com/smarie/python-parsyfiles/blob/344b37e1151e8d4e7c2ee49ae09d6568715ae64e/parsyfiles/parsing_core.py#L306-L319 | train | 54,997 |
smarie/python-parsyfiles | parsyfiles/parsing_core.py | AnyParser._get_parsing_plan_for_multifile_children | def _get_parsing_plan_for_multifile_children(self, obj_on_fs: PersistedObject, desired_type: Type[T],
logger: Logger) -> Dict[str, ParsingPlan[T]]:
"""
This method is called by the _RecursiveParsingPlan when created.
Implementing classes should return a dictionary containing a ParsingPlan for each child they plan to parse
using this framework. Note that for the files that will be parsed using a parsing library it is not necessary to
return a ParsingPlan.
In other words, implementing classes should return here everything they need for their implementation of
_parse_multifile to succeed. Indeed during parsing execution, the framework will call their _parse_multifile
method with that same dictionary as an argument (argument name is 'parsing_plan_for_children', see _BaseParser).
:param obj_on_fs:
:param desired_type:
:param logger:
:return:
"""
pass | python | def _get_parsing_plan_for_multifile_children(self, obj_on_fs: PersistedObject, desired_type: Type[T],
logger: Logger) -> Dict[str, ParsingPlan[T]]:
"""
This method is called by the _RecursiveParsingPlan when created.
Implementing classes should return a dictionary containing a ParsingPlan for each child they plan to parse
using this framework. Note that for the files that will be parsed using a parsing library it is not necessary to
return a ParsingPlan.
In other words, implementing classes should return here everything they need for their implementation of
_parse_multifile to succeed. Indeed during parsing execution, the framework will call their _parse_multifile
method with that same dictionary as an argument (argument name is 'parsing_plan_for_children', see _BaseParser).
:param obj_on_fs:
:param desired_type:
:param logger:
:return:
"""
pass | [
"def",
"_get_parsing_plan_for_multifile_children",
"(",
"self",
",",
"obj_on_fs",
":",
"PersistedObject",
",",
"desired_type",
":",
"Type",
"[",
"T",
"]",
",",
"logger",
":",
"Logger",
")",
"->",
"Dict",
"[",
"str",
",",
"ParsingPlan",
"[",
"T",
"]",
"]",
... | This method is called by the _RecursiveParsingPlan when created.
Implementing classes should return a dictionary containing a ParsingPlan for each child they plan to parse
using this framework. Note that for the files that will be parsed using a parsing library it is not necessary to
return a ParsingPlan.
In other words, implementing classes should return here everything they need for their implementation of
_parse_multifile to succeed. Indeed during parsing execution, the framework will call their _parse_multifile
method with that same dictionary as an argument (argument name is 'parsing_plan_for_children', see _BaseParser).
:param obj_on_fs:
:param desired_type:
:param logger:
:return: | [
"This",
"method",
"is",
"called",
"by",
"the",
"_RecursiveParsingPlan",
"when",
"created",
".",
"Implementing",
"classes",
"should",
"return",
"a",
"dictionary",
"containing",
"a",
"ParsingPlan",
"for",
"each",
"child",
"they",
"plan",
"to",
"parse",
"using",
"t... | 344b37e1151e8d4e7c2ee49ae09d6568715ae64e | https://github.com/smarie/python-parsyfiles/blob/344b37e1151e8d4e7c2ee49ae09d6568715ae64e/parsyfiles/parsing_core.py#L322-L339 | train | 54,998 |
smarie/python-parsyfiles | parsyfiles/parsing_core.py | SingleFileParserFunction._parse_singlefile | def _parse_singlefile(self, desired_type: Type[T], file_path: str, encoding: str, logger: Logger,
options: Dict[str, Dict[str, Any]]) -> T:
"""
Relies on the inner parsing function to parse the file.
If _streaming_mode is True, the file will be opened and closed by this method. Otherwise the parsing function
will be responsible to open and close.
:param desired_type:
:param file_path:
:param encoding:
:param options:
:return:
"""
opts = get_options_for_id(options, self.get_id_for_options())
if self._streaming_mode:
# We open the stream, and let the function parse from it
file_stream = None
try:
# Open the file with the appropriate encoding
file_stream = open(file_path, 'r', encoding=encoding)
# Apply the parsing function
if self.function_args is None:
return self._parser_func(desired_type, file_stream, logger, **opts)
else:
return self._parser_func(desired_type, file_stream, logger, **self.function_args, **opts)
except TypeError as e:
raise CaughtTypeError.create(self._parser_func, e)
finally:
if file_stream is not None:
# Close the File in any case
file_stream.close()
else:
# the parsing function will open the file itself
if self.function_args is None:
return self._parser_func(desired_type, file_path, encoding, logger, **opts)
else:
return self._parser_func(desired_type, file_path, encoding, logger, **self.function_args, **opts) | python | def _parse_singlefile(self, desired_type: Type[T], file_path: str, encoding: str, logger: Logger,
options: Dict[str, Dict[str, Any]]) -> T:
"""
Relies on the inner parsing function to parse the file.
If _streaming_mode is True, the file will be opened and closed by this method. Otherwise the parsing function
will be responsible to open and close.
:param desired_type:
:param file_path:
:param encoding:
:param options:
:return:
"""
opts = get_options_for_id(options, self.get_id_for_options())
if self._streaming_mode:
# We open the stream, and let the function parse from it
file_stream = None
try:
# Open the file with the appropriate encoding
file_stream = open(file_path, 'r', encoding=encoding)
# Apply the parsing function
if self.function_args is None:
return self._parser_func(desired_type, file_stream, logger, **opts)
else:
return self._parser_func(desired_type, file_stream, logger, **self.function_args, **opts)
except TypeError as e:
raise CaughtTypeError.create(self._parser_func, e)
finally:
if file_stream is not None:
# Close the File in any case
file_stream.close()
else:
# the parsing function will open the file itself
if self.function_args is None:
return self._parser_func(desired_type, file_path, encoding, logger, **opts)
else:
return self._parser_func(desired_type, file_path, encoding, logger, **self.function_args, **opts) | [
"def",
"_parse_singlefile",
"(",
"self",
",",
"desired_type",
":",
"Type",
"[",
"T",
"]",
",",
"file_path",
":",
"str",
",",
"encoding",
":",
"str",
",",
"logger",
":",
"Logger",
",",
"options",
":",
"Dict",
"[",
"str",
",",
"Dict",
"[",
"str",
",",
... | Relies on the inner parsing function to parse the file.
If _streaming_mode is True, the file will be opened and closed by this method. Otherwise the parsing function
will be responsible to open and close.
:param desired_type:
:param file_path:
:param encoding:
:param options:
:return: | [
"Relies",
"on",
"the",
"inner",
"parsing",
"function",
"to",
"parse",
"the",
"file",
".",
"If",
"_streaming_mode",
"is",
"True",
"the",
"file",
"will",
"be",
"opened",
"and",
"closed",
"by",
"this",
"method",
".",
"Otherwise",
"the",
"parsing",
"function",
... | 344b37e1151e8d4e7c2ee49ae09d6568715ae64e | https://github.com/smarie/python-parsyfiles/blob/344b37e1151e8d4e7c2ee49ae09d6568715ae64e/parsyfiles/parsing_core.py#L573-L615 | train | 54,999 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.