id int32 0 252k | repo stringlengths 7 55 | path stringlengths 4 127 | func_name stringlengths 1 88 | original_string stringlengths 75 19.8k | language stringclasses 1
value | code stringlengths 51 19.8k | code_tokens list | docstring stringlengths 3 17.3k | docstring_tokens list | sha stringlengths 40 40 | url stringlengths 87 242 |
|---|---|---|---|---|---|---|---|---|---|---|---|
243,800 | skyfielders/python-skyfield | skyfield/units.py | _hstr | def _hstr(hours, places=2):
"""Convert floating point `hours` into a sexagesimal string.
>>> _hstr(12.125)
'12h 07m 30.00s'
>>> _hstr(12.125, places=4)
'12h 07m 30.0000s'
>>> _hstr(float('nan'))
'nan'
"""
if isnan(hours):
return 'nan'
sgn, h, m, s, etc = _sexagesimalize... | python | def _hstr(hours, places=2):
if isnan(hours):
return 'nan'
sgn, h, m, s, etc = _sexagesimalize_to_int(hours, places)
sign = '-' if sgn < 0.0 else ''
return '%s%02dh %02dm %02d.%0*ds' % (sign, h, m, s, places, etc) | [
"def",
"_hstr",
"(",
"hours",
",",
"places",
"=",
"2",
")",
":",
"if",
"isnan",
"(",
"hours",
")",
":",
"return",
"'nan'",
"sgn",
",",
"h",
",",
"m",
",",
"s",
",",
"etc",
"=",
"_sexagesimalize_to_int",
"(",
"hours",
",",
"places",
")",
"sign",
"... | Convert floating point `hours` into a sexagesimal string.
>>> _hstr(12.125)
'12h 07m 30.00s'
>>> _hstr(12.125, places=4)
'12h 07m 30.0000s'
>>> _hstr(float('nan'))
'nan' | [
"Convert",
"floating",
"point",
"hours",
"into",
"a",
"sexagesimal",
"string",
"."
] | 51d9e042e06457f6b1f2415296d50a38cb3a300f | https://github.com/skyfielders/python-skyfield/blob/51d9e042e06457f6b1f2415296d50a38cb3a300f/skyfield/units.py#L358-L373 |
243,801 | skyfielders/python-skyfield | skyfield/units.py | _dstr | def _dstr(degrees, places=1, signed=False):
r"""Convert floating point `degrees` into a sexagesimal string.
>>> _dstr(181.875)
'181deg 52\' 30.0"'
>>> _dstr(181.875, places=3)
'181deg 52\' 30.000"'
>>> _dstr(181.875, signed=True)
'+181deg 52\' 30.0"'
>>> _dstr(float('nan'))
'nan'
... | python | def _dstr(degrees, places=1, signed=False):
r"""Convert floating point `degrees` into a sexagesimal string.
>>> _dstr(181.875)
'181deg 52\' 30.0"'
>>> _dstr(181.875, places=3)
'181deg 52\' 30.000"'
>>> _dstr(181.875, signed=True)
'+181deg 52\' 30.0"'
>>> _dstr(float('nan'))
'nan'
... | [
"def",
"_dstr",
"(",
"degrees",
",",
"places",
"=",
"1",
",",
"signed",
"=",
"False",
")",
":",
"if",
"isnan",
"(",
"degrees",
")",
":",
"return",
"'nan'",
"sgn",
",",
"d",
",",
"m",
",",
"s",
",",
"etc",
"=",
"_sexagesimalize_to_int",
"(",
"degree... | r"""Convert floating point `degrees` into a sexagesimal string.
>>> _dstr(181.875)
'181deg 52\' 30.0"'
>>> _dstr(181.875, places=3)
'181deg 52\' 30.000"'
>>> _dstr(181.875, signed=True)
'+181deg 52\' 30.0"'
>>> _dstr(float('nan'))
'nan' | [
"r",
"Convert",
"floating",
"point",
"degrees",
"into",
"a",
"sexagesimal",
"string",
"."
] | 51d9e042e06457f6b1f2415296d50a38cb3a300f | https://github.com/skyfielders/python-skyfield/blob/51d9e042e06457f6b1f2415296d50a38cb3a300f/skyfield/units.py#L375-L392 |
243,802 | skyfielders/python-skyfield | skyfield/units.py | _interpret_angle | def _interpret_angle(name, angle_object, angle_float, unit='degrees'):
"""Return an angle in radians from one of two arguments.
It is common for Skyfield routines to accept both an argument like
`alt` that takes an Angle object as well as an `alt_degrees` that
can be given a bare float or a sexagesimal... | python | def _interpret_angle(name, angle_object, angle_float, unit='degrees'):
if angle_object is not None:
if isinstance(angle_object, Angle):
return angle_object.radians
elif angle_float is not None:
return _unsexagesimalize(angle_float) * _from_degrees
raise ValueError('you must eithe... | [
"def",
"_interpret_angle",
"(",
"name",
",",
"angle_object",
",",
"angle_float",
",",
"unit",
"=",
"'degrees'",
")",
":",
"if",
"angle_object",
"is",
"not",
"None",
":",
"if",
"isinstance",
"(",
"angle_object",
",",
"Angle",
")",
":",
"return",
"angle_object... | Return an angle in radians from one of two arguments.
It is common for Skyfield routines to accept both an argument like
`alt` that takes an Angle object as well as an `alt_degrees` that
can be given a bare float or a sexagesimal tuple. A pair of such
arguments can be passed to this routine for interp... | [
"Return",
"an",
"angle",
"in",
"radians",
"from",
"one",
"of",
"two",
"arguments",
"."
] | 51d9e042e06457f6b1f2415296d50a38cb3a300f | https://github.com/skyfielders/python-skyfield/blob/51d9e042e06457f6b1f2415296d50a38cb3a300f/skyfield/units.py#L423-L439 |
243,803 | skyfielders/python-skyfield | skyfield/units.py | _interpret_ltude | def _interpret_ltude(value, name, psuffix, nsuffix):
"""Interpret a string, float, or tuple as a latitude or longitude angle.
`value` - The string to interpret.
`name` - 'latitude' or 'longitude', for use in exception messages.
`positive` - The string that indicates a positive angle ('N' or 'E').
`... | python | def _interpret_ltude(value, name, psuffix, nsuffix):
if not isinstance(value, str):
return Angle(degrees=_unsexagesimalize(value))
value = value.strip().upper()
if value.endswith(psuffix):
sign = +1.0
elif value.endswith(nsuffix):
sign = -1.0
else:
raise ValueError(... | [
"def",
"_interpret_ltude",
"(",
"value",
",",
"name",
",",
"psuffix",
",",
"nsuffix",
")",
":",
"if",
"not",
"isinstance",
"(",
"value",
",",
"str",
")",
":",
"return",
"Angle",
"(",
"degrees",
"=",
"_unsexagesimalize",
"(",
"value",
")",
")",
"value",
... | Interpret a string, float, or tuple as a latitude or longitude angle.
`value` - The string to interpret.
`name` - 'latitude' or 'longitude', for use in exception messages.
`positive` - The string that indicates a positive angle ('N' or 'E').
`negative` - The string that indicates a negative angle ('S' ... | [
"Interpret",
"a",
"string",
"float",
"or",
"tuple",
"as",
"a",
"latitude",
"or",
"longitude",
"angle",
"."
] | 51d9e042e06457f6b1f2415296d50a38cb3a300f | https://github.com/skyfielders/python-skyfield/blob/51d9e042e06457f6b1f2415296d50a38cb3a300f/skyfield/units.py#L441-L469 |
243,804 | skyfielders/python-skyfield | skyfield/units.py | Distance.to | def to(self, unit):
"""Convert this distance to the given AstroPy unit."""
from astropy.units import au
return (self.au * au).to(unit) | python | def to(self, unit):
from astropy.units import au
return (self.au * au).to(unit) | [
"def",
"to",
"(",
"self",
",",
"unit",
")",
":",
"from",
"astropy",
".",
"units",
"import",
"au",
"return",
"(",
"self",
".",
"au",
"*",
"au",
")",
".",
"to",
"(",
"unit",
")"
] | Convert this distance to the given AstroPy unit. | [
"Convert",
"this",
"distance",
"to",
"the",
"given",
"AstroPy",
"unit",
"."
] | 51d9e042e06457f6b1f2415296d50a38cb3a300f | https://github.com/skyfielders/python-skyfield/blob/51d9e042e06457f6b1f2415296d50a38cb3a300f/skyfield/units.py#L76-L79 |
243,805 | skyfielders/python-skyfield | skyfield/units.py | Velocity.to | def to(self, unit):
"""Convert this velocity to the given AstroPy unit."""
from astropy.units import au, d
return (self.au_per_d * au / d).to(unit) | python | def to(self, unit):
from astropy.units import au, d
return (self.au_per_d * au / d).to(unit) | [
"def",
"to",
"(",
"self",
",",
"unit",
")",
":",
"from",
"astropy",
".",
"units",
"import",
"au",
",",
"d",
"return",
"(",
"self",
".",
"au_per_d",
"*",
"au",
"/",
"d",
")",
".",
"to",
"(",
"unit",
")"
] | Convert this velocity to the given AstroPy unit. | [
"Convert",
"this",
"velocity",
"to",
"the",
"given",
"AstroPy",
"unit",
"."
] | 51d9e042e06457f6b1f2415296d50a38cb3a300f | https://github.com/skyfielders/python-skyfield/blob/51d9e042e06457f6b1f2415296d50a38cb3a300f/skyfield/units.py#L123-L126 |
243,806 | skyfielders/python-skyfield | skyfield/units.py | Angle.hstr | def hstr(self, places=2, warn=True):
"""Convert to a string like ``12h 07m 30.00s``."""
if warn and self.preference != 'hours':
raise WrongUnitError('hstr')
if self.radians.size == 0:
return '<Angle []>'
hours = self._hours
shape = getattr(hours, 'shape', ... | python | def hstr(self, places=2, warn=True):
if warn and self.preference != 'hours':
raise WrongUnitError('hstr')
if self.radians.size == 0:
return '<Angle []>'
hours = self._hours
shape = getattr(hours, 'shape', ())
if shape and shape != (1,):
return ... | [
"def",
"hstr",
"(",
"self",
",",
"places",
"=",
"2",
",",
"warn",
"=",
"True",
")",
":",
"if",
"warn",
"and",
"self",
".",
"preference",
"!=",
"'hours'",
":",
"raise",
"WrongUnitError",
"(",
"'hstr'",
")",
"if",
"self",
".",
"radians",
".",
"size",
... | Convert to a string like ``12h 07m 30.00s``. | [
"Convert",
"to",
"a",
"string",
"like",
"12h",
"07m",
"30",
".",
"00s",
"."
] | 51d9e042e06457f6b1f2415296d50a38cb3a300f | https://github.com/skyfielders/python-skyfield/blob/51d9e042e06457f6b1f2415296d50a38cb3a300f/skyfield/units.py#L232-L246 |
243,807 | skyfielders/python-skyfield | skyfield/units.py | Angle.dstr | def dstr(self, places=1, warn=True):
"""Convert to a string like ``181deg 52\' 30.0"``."""
if warn and self.preference != 'degrees':
raise WrongUnitError('dstr')
if self.radians.size == 0:
return '<Angle []>'
degrees = self._degrees
signed = self.signed
... | python | def dstr(self, places=1, warn=True):
if warn and self.preference != 'degrees':
raise WrongUnitError('dstr')
if self.radians.size == 0:
return '<Angle []>'
degrees = self._degrees
signed = self.signed
shape = getattr(degrees, 'shape', ())
if shape a... | [
"def",
"dstr",
"(",
"self",
",",
"places",
"=",
"1",
",",
"warn",
"=",
"True",
")",
":",
"if",
"warn",
"and",
"self",
".",
"preference",
"!=",
"'degrees'",
":",
"raise",
"WrongUnitError",
"(",
"'dstr'",
")",
"if",
"self",
".",
"radians",
".",
"size",... | Convert to a string like ``181deg 52\' 30.0"``. | [
"Convert",
"to",
"a",
"string",
"like",
"181deg",
"52",
"\\",
"30",
".",
"0",
"."
] | 51d9e042e06457f6b1f2415296d50a38cb3a300f | https://github.com/skyfielders/python-skyfield/blob/51d9e042e06457f6b1f2415296d50a38cb3a300f/skyfield/units.py#L270-L285 |
243,808 | skyfielders/python-skyfield | skyfield/units.py | Angle.to | def to(self, unit):
"""Convert this angle to the given AstroPy unit."""
from astropy.units import rad
return (self.radians * rad).to(unit)
# Or should this do:
from astropy.coordinates import Angle
from astropy.units import rad
return Angle(self.radians, rad).to(... | python | def to(self, unit):
from astropy.units import rad
return (self.radians * rad).to(unit)
# Or should this do:
from astropy.coordinates import Angle
from astropy.units import rad
return Angle(self.radians, rad).to(unit) | [
"def",
"to",
"(",
"self",
",",
"unit",
")",
":",
"from",
"astropy",
".",
"units",
"import",
"rad",
"return",
"(",
"self",
".",
"radians",
"*",
"rad",
")",
".",
"to",
"(",
"unit",
")",
"# Or should this do:",
"from",
"astropy",
".",
"coordinates",
"impo... | Convert this angle to the given AstroPy unit. | [
"Convert",
"this",
"angle",
"to",
"the",
"given",
"AstroPy",
"unit",
"."
] | 51d9e042e06457f6b1f2415296d50a38cb3a300f | https://github.com/skyfielders/python-skyfield/blob/51d9e042e06457f6b1f2415296d50a38cb3a300f/skyfield/units.py#L287-L295 |
243,809 | skyfielders/python-skyfield | skyfield/positionlib.py | ICRF.separation_from | def separation_from(self, another_icrf):
"""Return the angle between this position and another.
>>> print(ICRF([1,0,0]).separation_from(ICRF([1,1,0])))
45deg 00' 00.0"
You can also compute separations across an array of positions.
>>> directions = ICRF([[1,0,-1,0], [0,1,0,-1],... | python | def separation_from(self, another_icrf):
p1 = self.position.au
p2 = another_icrf.position.au
u1 = p1 / length_of(p1)
u2 = p2 / length_of(p2)
if u2.ndim > 1:
if u1.ndim == 1:
u1 = u1[:,None]
elif u1.ndim > 1:
u2 = u2[:,None]
... | [
"def",
"separation_from",
"(",
"self",
",",
"another_icrf",
")",
":",
"p1",
"=",
"self",
".",
"position",
".",
"au",
"p2",
"=",
"another_icrf",
".",
"position",
".",
"au",
"u1",
"=",
"p1",
"/",
"length_of",
"(",
"p1",
")",
"u2",
"=",
"p2",
"/",
"le... | Return the angle between this position and another.
>>> print(ICRF([1,0,0]).separation_from(ICRF([1,1,0])))
45deg 00' 00.0"
You can also compute separations across an array of positions.
>>> directions = ICRF([[1,0,-1,0], [0,1,0,-1], [0,0,0,0]])
>>> directions.separation_from(... | [
"Return",
"the",
"angle",
"between",
"this",
"position",
"and",
"another",
"."
] | 51d9e042e06457f6b1f2415296d50a38cb3a300f | https://github.com/skyfielders/python-skyfield/blob/51d9e042e06457f6b1f2415296d50a38cb3a300f/skyfield/positionlib.py#L134-L157 |
243,810 | skyfielders/python-skyfield | skyfield/positionlib.py | ICRF.to_skycoord | def to_skycoord(self, unit=None):
"""Convert this distance to an AstroPy ``SkyCoord`` object."""
from astropy.coordinates import SkyCoord
from astropy.units import au
x, y, z = self.position.au
return SkyCoord(representation='cartesian', x=x, y=y, z=z, unit=au) | python | def to_skycoord(self, unit=None):
from astropy.coordinates import SkyCoord
from astropy.units import au
x, y, z = self.position.au
return SkyCoord(representation='cartesian', x=x, y=y, z=z, unit=au) | [
"def",
"to_skycoord",
"(",
"self",
",",
"unit",
"=",
"None",
")",
":",
"from",
"astropy",
".",
"coordinates",
"import",
"SkyCoord",
"from",
"astropy",
".",
"units",
"import",
"au",
"x",
",",
"y",
",",
"z",
"=",
"self",
".",
"position",
".",
"au",
"re... | Convert this distance to an AstroPy ``SkyCoord`` object. | [
"Convert",
"this",
"distance",
"to",
"an",
"AstroPy",
"SkyCoord",
"object",
"."
] | 51d9e042e06457f6b1f2415296d50a38cb3a300f | https://github.com/skyfielders/python-skyfield/blob/51d9e042e06457f6b1f2415296d50a38cb3a300f/skyfield/positionlib.py#L262-L267 |
243,811 | skyfielders/python-skyfield | skyfield/positionlib.py | ICRF.from_altaz | def from_altaz(self, alt=None, az=None, alt_degrees=None, az_degrees=None,
distance=Distance(au=0.1)):
"""Generate an Apparent position from an altitude and azimuth.
The altitude and azimuth can each be provided as an `Angle`
object, or else as a number of degrees provided as... | python | def from_altaz(self, alt=None, az=None, alt_degrees=None, az_degrees=None,
distance=Distance(au=0.1)):
# TODO: should this method live on another class?
R = self.observer_data.altaz_rotation if self.observer_data else None
if R is None:
raise ValueError('only a pos... | [
"def",
"from_altaz",
"(",
"self",
",",
"alt",
"=",
"None",
",",
"az",
"=",
"None",
",",
"alt_degrees",
"=",
"None",
",",
"az_degrees",
"=",
"None",
",",
"distance",
"=",
"Distance",
"(",
"au",
"=",
"0.1",
")",
")",
":",
"# TODO: should this method live o... | Generate an Apparent position from an altitude and azimuth.
The altitude and azimuth can each be provided as an `Angle`
object, or else as a number of degrees provided as either a
float or a tuple of degrees, arcminutes, and arcseconds::
alt=Angle(...), az=Angle(...)
al... | [
"Generate",
"an",
"Apparent",
"position",
"from",
"an",
"altitude",
"and",
"azimuth",
"."
] | 51d9e042e06457f6b1f2415296d50a38cb3a300f | https://github.com/skyfielders/python-skyfield/blob/51d9e042e06457f6b1f2415296d50a38cb3a300f/skyfield/positionlib.py#L277-L304 |
243,812 | skyfielders/python-skyfield | skyfield/positionlib.py | Barycentric.observe | def observe(self, body):
"""Compute the `Astrometric` position of a body from this location.
To compute the body's astrometric position, it is first asked
for its position at the time `t` of this position itself. The
distance to the body is then divided by the speed of light to
... | python | def observe(self, body):
p, v, t, light_time = body._observe_from_bcrs(self)
astrometric = Astrometric(p, v, t, observer_data=self.observer_data)
astrometric.light_time = light_time
return astrometric | [
"def",
"observe",
"(",
"self",
",",
"body",
")",
":",
"p",
",",
"v",
",",
"t",
",",
"light_time",
"=",
"body",
".",
"_observe_from_bcrs",
"(",
"self",
")",
"astrometric",
"=",
"Astrometric",
"(",
"p",
",",
"v",
",",
"t",
",",
"observer_data",
"=",
... | Compute the `Astrometric` position of a body from this location.
To compute the body's astrometric position, it is first asked
for its position at the time `t` of this position itself. The
distance to the body is then divided by the speed of light to
find how long it takes its light to... | [
"Compute",
"the",
"Astrometric",
"position",
"of",
"a",
"body",
"from",
"this",
"location",
"."
] | 51d9e042e06457f6b1f2415296d50a38cb3a300f | https://github.com/skyfielders/python-skyfield/blob/51d9e042e06457f6b1f2415296d50a38cb3a300f/skyfield/positionlib.py#L349-L367 |
243,813 | skyfielders/python-skyfield | skyfield/positionlib.py | Geocentric.subpoint | def subpoint(self):
"""Return the latitude and longitude directly beneath this position.
Returns a :class:`~skyfield.toposlib.Topos` whose ``longitude``
and ``latitude`` are those of the point on the Earth's surface
directly beneath this position, and whose ``elevation`` is the
... | python | def subpoint(self):
if self.center != 399: # TODO: should an __init__() check this?
raise ValueError("you can only ask for the geographic subpoint"
" of a position measured from Earth's center")
t = self.t
xyz_au = einsum('ij...,j...->i...', t.M, self.po... | [
"def",
"subpoint",
"(",
"self",
")",
":",
"if",
"self",
".",
"center",
"!=",
"399",
":",
"# TODO: should an __init__() check this?",
"raise",
"ValueError",
"(",
"\"you can only ask for the geographic subpoint\"",
"\" of a position measured from Earth's center\"",
")",
"t",
... | Return the latitude and longitude directly beneath this position.
Returns a :class:`~skyfield.toposlib.Topos` whose ``longitude``
and ``latitude`` are those of the point on the Earth's surface
directly beneath this position, and whose ``elevation`` is the
height of this position above t... | [
"Return",
"the",
"latitude",
"and",
"longitude",
"directly",
"beneath",
"this",
"position",
"."
] | 51d9e042e06457f6b1f2415296d50a38cb3a300f | https://github.com/skyfielders/python-skyfield/blob/51d9e042e06457f6b1f2415296d50a38cb3a300f/skyfield/positionlib.py#L454-L478 |
243,814 | skyfielders/python-skyfield | skyfield/charting.py | _plot_stars | def _plot_stars(catalog, observer, project, ax, mag1, mag2, margin=1.25):
"""Experiment in progress, hence the underscore; expect changes."""
art = []
# from astropy import wcs
# w = wcs.WCS(naxis=2)
# w.wcs.crpix = [-234.75, 8.3393]
# w.wcs.cdelt = np.array([-0.066667, 0.066667])
# w.wcs.... | python | def _plot_stars(catalog, observer, project, ax, mag1, mag2, margin=1.25):
art = []
# from astropy import wcs
# w = wcs.WCS(naxis=2)
# w.wcs.crpix = [-234.75, 8.3393]
# w.wcs.cdelt = np.array([-0.066667, 0.066667])
# w.wcs.crval = [0, -90]
# w.wcs.ctype = ["RA---AIR", "DEC--AIR"]
# w.wcs... | [
"def",
"_plot_stars",
"(",
"catalog",
",",
"observer",
",",
"project",
",",
"ax",
",",
"mag1",
",",
"mag2",
",",
"margin",
"=",
"1.25",
")",
":",
"art",
"=",
"[",
"]",
"# from astropy import wcs",
"# w = wcs.WCS(naxis=2)",
"# w.wcs.crpix = [-234.75, 8.3393]",
"#... | Experiment in progress, hence the underscore; expect changes. | [
"Experiment",
"in",
"progress",
"hence",
"the",
"underscore",
";",
"expect",
"changes",
"."
] | 51d9e042e06457f6b1f2415296d50a38cb3a300f | https://github.com/skyfielders/python-skyfield/blob/51d9e042e06457f6b1f2415296d50a38cb3a300f/skyfield/charting.py#L9-L82 |
243,815 | skyfielders/python-skyfield | skyfield/almanac.py | phase_angle | def phase_angle(ephemeris, body, t):
"""Compute the phase angle of a body viewed from Earth.
The ``body`` should be an integer or string that can be looked up in
the given ``ephemeris``, which will also be asked to provide
positions for the Earth and Sun. The return value will be an
:class:`~skyfi... | python | def phase_angle(ephemeris, body, t):
earth = ephemeris['earth']
sun = ephemeris['sun']
body = ephemeris[body]
pe = earth.at(t).observe(body)
pe.position.au *= -1 # rotate 180 degrees to point back at Earth
t2 = t.ts.tt_jd(t.tt - pe.light_time)
ps = body.at(t2).observe(sun)
return pe.... | [
"def",
"phase_angle",
"(",
"ephemeris",
",",
"body",
",",
"t",
")",
":",
"earth",
"=",
"ephemeris",
"[",
"'earth'",
"]",
"sun",
"=",
"ephemeris",
"[",
"'sun'",
"]",
"body",
"=",
"ephemeris",
"[",
"body",
"]",
"pe",
"=",
"earth",
".",
"at",
"(",
"t"... | Compute the phase angle of a body viewed from Earth.
The ``body`` should be an integer or string that can be looked up in
the given ``ephemeris``, which will also be asked to provide
positions for the Earth and Sun. The return value will be an
:class:`~skyfield.units.Angle` object. | [
"Compute",
"the",
"phase",
"angle",
"of",
"a",
"body",
"viewed",
"from",
"Earth",
"."
] | 51d9e042e06457f6b1f2415296d50a38cb3a300f | https://github.com/skyfielders/python-skyfield/blob/51d9e042e06457f6b1f2415296d50a38cb3a300f/skyfield/almanac.py#L11-L27 |
243,816 | skyfielders/python-skyfield | skyfield/almanac.py | fraction_illuminated | def fraction_illuminated(ephemeris, body, t):
"""Compute the illuminated fraction of a body viewed from Earth.
The ``body`` should be an integer or string that can be looked up in
the given ``ephemeris``, which will also be asked to provide
positions for the Earth and Sun. The return value will be a
... | python | def fraction_illuminated(ephemeris, body, t):
a = phase_angle(ephemeris, body, t).radians
return 0.5 * (1.0 + cos(a)) | [
"def",
"fraction_illuminated",
"(",
"ephemeris",
",",
"body",
",",
"t",
")",
":",
"a",
"=",
"phase_angle",
"(",
"ephemeris",
",",
"body",
",",
"t",
")",
".",
"radians",
"return",
"0.5",
"*",
"(",
"1.0",
"+",
"cos",
"(",
"a",
")",
")"
] | Compute the illuminated fraction of a body viewed from Earth.
The ``body`` should be an integer or string that can be looked up in
the given ``ephemeris``, which will also be asked to provide
positions for the Earth and Sun. The return value will be a
floating point number between zero and one. This ... | [
"Compute",
"the",
"illuminated",
"fraction",
"of",
"a",
"body",
"viewed",
"from",
"Earth",
"."
] | 51d9e042e06457f6b1f2415296d50a38cb3a300f | https://github.com/skyfielders/python-skyfield/blob/51d9e042e06457f6b1f2415296d50a38cb3a300f/skyfield/almanac.py#L29-L40 |
243,817 | skyfielders/python-skyfield | skyfield/almanac.py | find_discrete | def find_discrete(start_time, end_time, f, epsilon=EPSILON, num=12):
"""Find the times when a function changes value.
Searches between ``start_time`` and ``end_time``, which should both
be :class:`~skyfield.timelib.Time` objects, for the occasions where
the function ``f`` changes from one value to anot... | python | def find_discrete(start_time, end_time, f, epsilon=EPSILON, num=12):
ts = start_time.ts
jd0 = start_time.tt
jd1 = end_time.tt
if jd0 >= jd1:
raise ValueError('your start_time {0} is later than your end_time {1}'
.format(start_time, end_time))
periods = (jd1 - jd0) /... | [
"def",
"find_discrete",
"(",
"start_time",
",",
"end_time",
",",
"f",
",",
"epsilon",
"=",
"EPSILON",
",",
"num",
"=",
"12",
")",
":",
"ts",
"=",
"start_time",
".",
"ts",
"jd0",
"=",
"start_time",
".",
"tt",
"jd1",
"=",
"end_time",
".",
"tt",
"if",
... | Find the times when a function changes value.
Searches between ``start_time`` and ``end_time``, which should both
be :class:`~skyfield.timelib.Time` objects, for the occasions where
the function ``f`` changes from one value to another. Use this to
search for events like sunrise or moon phases.
A ... | [
"Find",
"the",
"times",
"when",
"a",
"function",
"changes",
"value",
"."
] | 51d9e042e06457f6b1f2415296d50a38cb3a300f | https://github.com/skyfielders/python-skyfield/blob/51d9e042e06457f6b1f2415296d50a38cb3a300f/skyfield/almanac.py#L44-L101 |
243,818 | skyfielders/python-skyfield | skyfield/almanac.py | seasons | def seasons(ephemeris):
"""Build a function of time that returns the quarter of the year.
The function that this returns will expect a single argument that is
a :class:`~skyfield.timelib.Time` and will return 0 through 3 for
the seasons Spring, Summer, Autumn, and Winter.
"""
earth = ephemeris... | python | def seasons(ephemeris):
earth = ephemeris['earth']
sun = ephemeris['sun']
def season_at(t):
"""Return season 0 (Spring) through 3 (Winter) at time `t`."""
t._nutation_angles = iau2000b(t.tt)
e = earth.at(t)
_, slon, _ = e.observe(sun).apparent().ecliptic_latlon('date')
... | [
"def",
"seasons",
"(",
"ephemeris",
")",
":",
"earth",
"=",
"ephemeris",
"[",
"'earth'",
"]",
"sun",
"=",
"ephemeris",
"[",
"'sun'",
"]",
"def",
"season_at",
"(",
"t",
")",
":",
"\"\"\"Return season 0 (Spring) through 3 (Winter) at time `t`.\"\"\"",
"t",
".",
"_... | Build a function of time that returns the quarter of the year.
The function that this returns will expect a single argument that is
a :class:`~skyfield.timelib.Time` and will return 0 through 3 for
the seasons Spring, Summer, Autumn, and Winter. | [
"Build",
"a",
"function",
"of",
"time",
"that",
"returns",
"the",
"quarter",
"of",
"the",
"year",
"."
] | 51d9e042e06457f6b1f2415296d50a38cb3a300f | https://github.com/skyfielders/python-skyfield/blob/51d9e042e06457f6b1f2415296d50a38cb3a300f/skyfield/almanac.py#L161-L180 |
243,819 | skyfielders/python-skyfield | skyfield/almanac.py | sunrise_sunset | def sunrise_sunset(ephemeris, topos):
"""Build a function of time that returns whether the sun is up.
The function that this returns will expect a single argument that is
a :class:`~skyfield.timelib.Time` and will return ``True`` if the
sun is up, else ``False``.
"""
sun = ephemeris['sun']
... | python | def sunrise_sunset(ephemeris, topos):
sun = ephemeris['sun']
topos_at = (ephemeris['earth'] + topos).at
def is_sun_up_at(t):
"""Return `True` if the sun has risen by time `t`."""
t._nutation_angles = iau2000b(t.tt)
return topos_at(t).observe(sun).apparent().altaz()[0].degrees > -0.... | [
"def",
"sunrise_sunset",
"(",
"ephemeris",
",",
"topos",
")",
":",
"sun",
"=",
"ephemeris",
"[",
"'sun'",
"]",
"topos_at",
"=",
"(",
"ephemeris",
"[",
"'earth'",
"]",
"+",
"topos",
")",
".",
"at",
"def",
"is_sun_up_at",
"(",
"t",
")",
":",
"\"\"\"Retur... | Build a function of time that returns whether the sun is up.
The function that this returns will expect a single argument that is
a :class:`~skyfield.timelib.Time` and will return ``True`` if the
sun is up, else ``False``. | [
"Build",
"a",
"function",
"of",
"time",
"that",
"returns",
"whether",
"the",
"sun",
"is",
"up",
"."
] | 51d9e042e06457f6b1f2415296d50a38cb3a300f | https://github.com/skyfielders/python-skyfield/blob/51d9e042e06457f6b1f2415296d50a38cb3a300f/skyfield/almanac.py#L182-L200 |
243,820 | skyfielders/python-skyfield | skyfield/almanac.py | moon_phases | def moon_phases(ephemeris):
"""Build a function of time that returns the moon phase 0 through 3.
The function that this returns will expect a single argument that is
a :class:`~skyfield.timelib.Time` and will return the phase of the
moon as an integer. See the accompanying array ``MOON_PHASES`` if
... | python | def moon_phases(ephemeris):
earth = ephemeris['earth']
moon = ephemeris['moon']
sun = ephemeris['sun']
def moon_phase_at(t):
"""Return the phase of the moon 0 through 3 at time `t`."""
t._nutation_angles = iau2000b(t.tt)
e = earth.at(t)
_, mlon, _ = e.observe(moon).appar... | [
"def",
"moon_phases",
"(",
"ephemeris",
")",
":",
"earth",
"=",
"ephemeris",
"[",
"'earth'",
"]",
"moon",
"=",
"ephemeris",
"[",
"'moon'",
"]",
"sun",
"=",
"ephemeris",
"[",
"'sun'",
"]",
"def",
"moon_phase_at",
"(",
"t",
")",
":",
"\"\"\"Return the phase ... | Build a function of time that returns the moon phase 0 through 3.
The function that this returns will expect a single argument that is
a :class:`~skyfield.timelib.Time` and will return the phase of the
moon as an integer. See the accompanying array ``MOON_PHASES`` if
you want to give string names to e... | [
"Build",
"a",
"function",
"of",
"time",
"that",
"returns",
"the",
"moon",
"phase",
"0",
"through",
"3",
"."
] | 51d9e042e06457f6b1f2415296d50a38cb3a300f | https://github.com/skyfielders/python-skyfield/blob/51d9e042e06457f6b1f2415296d50a38cb3a300f/skyfield/almanac.py#L209-L231 |
243,821 | skyfielders/python-skyfield | skyfield/projections.py | _derive_stereographic | def _derive_stereographic():
"""Compute the formulae to cut-and-paste into the routine below."""
from sympy import symbols, atan2, acos, rot_axis1, rot_axis3, Matrix
x_c, y_c, z_c, x, y, z = symbols('x_c y_c z_c x y z')
# The angles we'll need to rotate through.
around_z = atan2(x_c, y_c)
aroun... | python | def _derive_stereographic():
from sympy import symbols, atan2, acos, rot_axis1, rot_axis3, Matrix
x_c, y_c, z_c, x, y, z = symbols('x_c y_c z_c x y z')
# The angles we'll need to rotate through.
around_z = atan2(x_c, y_c)
around_x = acos(-z_c)
# Apply rotations to produce an "o" = output vecto... | [
"def",
"_derive_stereographic",
"(",
")",
":",
"from",
"sympy",
"import",
"symbols",
",",
"atan2",
",",
"acos",
",",
"rot_axis1",
",",
"rot_axis3",
",",
"Matrix",
"x_c",
",",
"y_c",
",",
"z_c",
",",
"x",
",",
"y",
",",
"z",
"=",
"symbols",
"(",
"'x_c... | Compute the formulae to cut-and-paste into the routine below. | [
"Compute",
"the",
"formulae",
"to",
"cut",
"-",
"and",
"-",
"paste",
"into",
"the",
"routine",
"below",
"."
] | 51d9e042e06457f6b1f2415296d50a38cb3a300f | https://github.com/skyfielders/python-skyfield/blob/51d9e042e06457f6b1f2415296d50a38cb3a300f/skyfield/projections.py#L5-L23 |
243,822 | reiinakano/scikit-plot | scikitplot/classifiers.py | classifier_factory | def classifier_factory(clf):
"""Embeds scikit-plot instance methods in an sklearn classifier.
Args:
clf: Scikit-learn classifier instance
Returns:
The same scikit-learn classifier instance passed in **clf**
with embedded scikit-plot instance methods.
Raises:
ValueError... | python | def classifier_factory(clf):
required_methods = ['fit', 'score', 'predict']
for method in required_methods:
if not hasattr(clf, method):
raise TypeError('"{}" is not in clf. Did you pass a '
'classifier instance?'.format(method))
optional_methods = ['predict... | [
"def",
"classifier_factory",
"(",
"clf",
")",
":",
"required_methods",
"=",
"[",
"'fit'",
",",
"'score'",
",",
"'predict'",
"]",
"for",
"method",
"in",
"required_methods",
":",
"if",
"not",
"hasattr",
"(",
"clf",
",",
"method",
")",
":",
"raise",
"TypeErro... | Embeds scikit-plot instance methods in an sklearn classifier.
Args:
clf: Scikit-learn classifier instance
Returns:
The same scikit-learn classifier instance passed in **clf**
with embedded scikit-plot instance methods.
Raises:
ValueError: If **clf** does not contain the in... | [
"Embeds",
"scikit",
"-",
"plot",
"instance",
"methods",
"in",
"an",
"sklearn",
"classifier",
"."
] | 2dd3e6a76df77edcbd724c4db25575f70abb57cb | https://github.com/reiinakano/scikit-plot/blob/2dd3e6a76df77edcbd724c4db25575f70abb57cb/scikitplot/classifiers.py#L24-L67 |
243,823 | reiinakano/scikit-plot | scikitplot/classifiers.py | plot_confusion_matrix_with_cv | def plot_confusion_matrix_with_cv(clf, X, y, labels=None, true_labels=None,
pred_labels=None, title=None,
normalize=False, hide_zeros=False,
x_tick_rotation=0, do_cv=True, cv=None,
shu... | python | def plot_confusion_matrix_with_cv(clf, X, y, labels=None, true_labels=None,
pred_labels=None, title=None,
normalize=False, hide_zeros=False,
x_tick_rotation=0, do_cv=True, cv=None,
shu... | [
"def",
"plot_confusion_matrix_with_cv",
"(",
"clf",
",",
"X",
",",
"y",
",",
"labels",
"=",
"None",
",",
"true_labels",
"=",
"None",
",",
"pred_labels",
"=",
"None",
",",
"title",
"=",
"None",
",",
"normalize",
"=",
"False",
",",
"hide_zeros",
"=",
"Fals... | Generates the confusion matrix for a given classifier and dataset.
Args:
clf: Classifier instance that implements ``fit`` and ``predict``
methods.
X (array-like, shape (n_samples, n_features)):
Training vector, where n_samples is the number of samples and
n_feat... | [
"Generates",
"the",
"confusion",
"matrix",
"for",
"a",
"given",
"classifier",
"and",
"dataset",
"."
] | 2dd3e6a76df77edcbd724c4db25575f70abb57cb | https://github.com/reiinakano/scikit-plot/blob/2dd3e6a76df77edcbd724c4db25575f70abb57cb/scikitplot/classifiers.py#L70-L219 |
243,824 | reiinakano/scikit-plot | scikitplot/classifiers.py | plot_ks_statistic_with_cv | def plot_ks_statistic_with_cv(clf, X, y, title='KS Statistic Plot',
do_cv=True, cv=None, shuffle=True,
random_state=None, ax=None, figsize=None,
title_fontsize="large", text_fontsize="medium"):
"""Generates the KS Statistic pl... | python | def plot_ks_statistic_with_cv(clf, X, y, title='KS Statistic Plot',
do_cv=True, cv=None, shuffle=True,
random_state=None, ax=None, figsize=None,
title_fontsize="large", text_fontsize="medium"):
y = np.array(y)
if not hasa... | [
"def",
"plot_ks_statistic_with_cv",
"(",
"clf",
",",
"X",
",",
"y",
",",
"title",
"=",
"'KS Statistic Plot'",
",",
"do_cv",
"=",
"True",
",",
"cv",
"=",
"None",
",",
"shuffle",
"=",
"True",
",",
"random_state",
"=",
"None",
",",
"ax",
"=",
"None",
",",... | Generates the KS Statistic plot for a given classifier and dataset.
Args:
clf: Classifier instance that implements "fit" and "predict_proba"
methods.
X (array-like, shape (n_samples, n_features)):
Training vector, where n_samples is the number of samples and
n_f... | [
"Generates",
"the",
"KS",
"Statistic",
"plot",
"for",
"a",
"given",
"classifier",
"and",
"dataset",
"."
] | 2dd3e6a76df77edcbd724c4db25575f70abb57cb | https://github.com/reiinakano/scikit-plot/blob/2dd3e6a76df77edcbd724c4db25575f70abb57cb/scikitplot/classifiers.py#L352-L467 |
243,825 | reiinakano/scikit-plot | scikitplot/plotters.py | plot_confusion_matrix | def plot_confusion_matrix(y_true, y_pred, labels=None, true_labels=None,
pred_labels=None, title=None, normalize=False,
hide_zeros=False, x_tick_rotation=0, ax=None,
figsize=None, cmap='Blues', title_fontsize="large",
... | python | def plot_confusion_matrix(y_true, y_pred, labels=None, true_labels=None,
pred_labels=None, title=None, normalize=False,
hide_zeros=False, x_tick_rotation=0, ax=None,
figsize=None, cmap='Blues', title_fontsize="large",
... | [
"def",
"plot_confusion_matrix",
"(",
"y_true",
",",
"y_pred",
",",
"labels",
"=",
"None",
",",
"true_labels",
"=",
"None",
",",
"pred_labels",
"=",
"None",
",",
"title",
"=",
"None",
",",
"normalize",
"=",
"False",
",",
"hide_zeros",
"=",
"False",
",",
"... | Generates confusion matrix plot from predictions and true labels
Args:
y_true (array-like, shape (n_samples)):
Ground truth (correct) target values.
y_pred (array-like, shape (n_samples)):
Estimated targets as returned by a classifier.
labels (array-like, shape (n_... | [
"Generates",
"confusion",
"matrix",
"plot",
"from",
"predictions",
"and",
"true",
"labels"
] | 2dd3e6a76df77edcbd724c4db25575f70abb57cb | https://github.com/reiinakano/scikit-plot/blob/2dd3e6a76df77edcbd724c4db25575f70abb57cb/scikitplot/plotters.py#L42-L181 |
243,826 | reiinakano/scikit-plot | scikitplot/plotters.py | plot_feature_importances | def plot_feature_importances(clf, title='Feature Importance',
feature_names=None, max_num_features=20,
order='descending', x_tick_rotation=0, ax=None,
figsize=None, title_fontsize="large",
text_fontsize="... | python | def plot_feature_importances(clf, title='Feature Importance',
feature_names=None, max_num_features=20,
order='descending', x_tick_rotation=0, ax=None,
figsize=None, title_fontsize="large",
text_fontsize="... | [
"def",
"plot_feature_importances",
"(",
"clf",
",",
"title",
"=",
"'Feature Importance'",
",",
"feature_names",
"=",
"None",
",",
"max_num_features",
"=",
"20",
",",
"order",
"=",
"'descending'",
",",
"x_tick_rotation",
"=",
"0",
",",
"ax",
"=",
"None",
",",
... | Generates a plot of a classifier's feature importances.
Args:
clf: Classifier instance that implements ``fit`` and ``predict_proba``
methods. The classifier must also have a ``feature_importances_``
attribute.
title (string, optional): Title of the generated plot. Defaults ... | [
"Generates",
"a",
"plot",
"of",
"a",
"classifier",
"s",
"feature",
"importances",
"."
] | 2dd3e6a76df77edcbd724c4db25575f70abb57cb | https://github.com/reiinakano/scikit-plot/blob/2dd3e6a76df77edcbd724c4db25575f70abb57cb/scikitplot/plotters.py#L546-L661 |
243,827 | reiinakano/scikit-plot | scikitplot/plotters.py | plot_silhouette | def plot_silhouette(clf, X, title='Silhouette Analysis', metric='euclidean',
copy=True, ax=None, figsize=None, cmap='nipy_spectral',
title_fontsize="large", text_fontsize="medium"):
"""Plots silhouette analysis of clusters using fit_predict.
Args:
clf: Clusterer ... | python | def plot_silhouette(clf, X, title='Silhouette Analysis', metric='euclidean',
copy=True, ax=None, figsize=None, cmap='nipy_spectral',
title_fontsize="large", text_fontsize="medium"):
if copy:
clf = clone(clf)
cluster_labels = clf.fit_predict(X)
n_clusters = l... | [
"def",
"plot_silhouette",
"(",
"clf",
",",
"X",
",",
"title",
"=",
"'Silhouette Analysis'",
",",
"metric",
"=",
"'euclidean'",
",",
"copy",
"=",
"True",
",",
"ax",
"=",
"None",
",",
"figsize",
"=",
"None",
",",
"cmap",
"=",
"'nipy_spectral'",
",",
"title... | Plots silhouette analysis of clusters using fit_predict.
Args:
clf: Clusterer instance that implements ``fit`` and ``fit_predict``
methods.
X (array-like, shape (n_samples, n_features)):
Data to cluster, where n_samples is the number of samples and
n_features is... | [
"Plots",
"silhouette",
"analysis",
"of",
"clusters",
"using",
"fit_predict",
"."
] | 2dd3e6a76df77edcbd724c4db25575f70abb57cb | https://github.com/reiinakano/scikit-plot/blob/2dd3e6a76df77edcbd724c4db25575f70abb57cb/scikitplot/plotters.py#L775-L888 |
243,828 | reiinakano/scikit-plot | scikitplot/cluster.py | _clone_and_score_clusterer | def _clone_and_score_clusterer(clf, X, n_clusters):
"""Clones and scores clusterer instance.
Args:
clf: Clusterer instance that implements ``fit``,``fit_predict``, and
``score`` methods, and an ``n_clusters`` hyperparameter.
e.g. :class:`sklearn.cluster.KMeans` instance
... | python | def _clone_and_score_clusterer(clf, X, n_clusters):
start = time.time()
clf = clone(clf)
setattr(clf, 'n_clusters', n_clusters)
return clf.fit(X).score(X), time.time() - start | [
"def",
"_clone_and_score_clusterer",
"(",
"clf",
",",
"X",
",",
"n_clusters",
")",
":",
"start",
"=",
"time",
".",
"time",
"(",
")",
"clf",
"=",
"clone",
"(",
"clf",
")",
"setattr",
"(",
"clf",
",",
"'n_clusters'",
",",
"n_clusters",
")",
"return",
"cl... | Clones and scores clusterer instance.
Args:
clf: Clusterer instance that implements ``fit``,``fit_predict``, and
``score`` methods, and an ``n_clusters`` hyperparameter.
e.g. :class:`sklearn.cluster.KMeans` instance
X (array-like, shape (n_samples, n_features)):
... | [
"Clones",
"and",
"scores",
"clusterer",
"instance",
"."
] | 2dd3e6a76df77edcbd724c4db25575f70abb57cb | https://github.com/reiinakano/scikit-plot/blob/2dd3e6a76df77edcbd724c4db25575f70abb57cb/scikitplot/cluster.py#L110-L132 |
243,829 | reiinakano/scikit-plot | scikitplot/estimators.py | plot_learning_curve | def plot_learning_curve(clf, X, y, title='Learning Curve', cv=None,
shuffle=False, random_state=None,
train_sizes=None, n_jobs=1, scoring=None,
ax=None, figsize=None, title_fontsize="large",
text_fontsize="medium"):
"""G... | python | def plot_learning_curve(clf, X, y, title='Learning Curve', cv=None,
shuffle=False, random_state=None,
train_sizes=None, n_jobs=1, scoring=None,
ax=None, figsize=None, title_fontsize="large",
text_fontsize="medium"):
if a... | [
"def",
"plot_learning_curve",
"(",
"clf",
",",
"X",
",",
"y",
",",
"title",
"=",
"'Learning Curve'",
",",
"cv",
"=",
"None",
",",
"shuffle",
"=",
"False",
",",
"random_state",
"=",
"None",
",",
"train_sizes",
"=",
"None",
",",
"n_jobs",
"=",
"1",
",",
... | Generates a plot of the train and test learning curves for a classifier.
Args:
clf: Classifier instance that implements ``fit`` and ``predict``
methods.
X (array-like, shape (n_samples, n_features)):
Training vector, where n_samples is the number of samples and
... | [
"Generates",
"a",
"plot",
"of",
"the",
"train",
"and",
"test",
"learning",
"curves",
"for",
"a",
"classifier",
"."
] | 2dd3e6a76df77edcbd724c4db25575f70abb57cb | https://github.com/reiinakano/scikit-plot/blob/2dd3e6a76df77edcbd724c4db25575f70abb57cb/scikitplot/estimators.py#L135-L247 |
243,830 | reiinakano/scikit-plot | scikitplot/metrics.py | plot_calibration_curve | def plot_calibration_curve(y_true, probas_list, clf_names=None, n_bins=10,
title='Calibration plots (Reliability Curves)',
ax=None, figsize=None, cmap='nipy_spectral',
title_fontsize="large", text_fontsize="medium"):
"""Plots calibrati... | python | def plot_calibration_curve(y_true, probas_list, clf_names=None, n_bins=10,
title='Calibration plots (Reliability Curves)',
ax=None, figsize=None, cmap='nipy_spectral',
title_fontsize="large", text_fontsize="medium"):
y_true = np.asarra... | [
"def",
"plot_calibration_curve",
"(",
"y_true",
",",
"probas_list",
",",
"clf_names",
"=",
"None",
",",
"n_bins",
"=",
"10",
",",
"title",
"=",
"'Calibration plots (Reliability Curves)'",
",",
"ax",
"=",
"None",
",",
"figsize",
"=",
"None",
",",
"cmap",
"=",
... | Plots calibration curves for a set of classifier probability estimates.
Plotting the calibration curves of a classifier is useful for determining
whether or not you can interpret their predicted probabilities directly as
as confidence level. For instance, a well-calibrated binary classifier
should clas... | [
"Plots",
"calibration",
"curves",
"for",
"a",
"set",
"of",
"classifier",
"probability",
"estimates",
"."
] | 2dd3e6a76df77edcbd724c4db25575f70abb57cb | https://github.com/reiinakano/scikit-plot/blob/2dd3e6a76df77edcbd724c4db25575f70abb57cb/scikitplot/metrics.py#L911-L1042 |
243,831 | reiinakano/scikit-plot | scikitplot/clustering.py | clustering_factory | def clustering_factory(clf):
"""Embeds scikit-plot plotting methods in an sklearn clusterer instance.
Args:
clf: Scikit-learn clusterer instance
Returns:
The same scikit-learn clusterer instance passed in **clf** with
embedded scikit-plot instance methods.
Raises:
Valu... | python | def clustering_factory(clf):
required_methods = ['fit', 'fit_predict']
for method in required_methods:
if not hasattr(clf, method):
raise TypeError('"{}" is not in clf. Did you '
'pass a clusterer instance?'.format(method))
additional_methods = {
'pl... | [
"def",
"clustering_factory",
"(",
"clf",
")",
":",
"required_methods",
"=",
"[",
"'fit'",
",",
"'fit_predict'",
"]",
"for",
"method",
"in",
"required_methods",
":",
"if",
"not",
"hasattr",
"(",
"clf",
",",
"method",
")",
":",
"raise",
"TypeError",
"(",
"'\... | Embeds scikit-plot plotting methods in an sklearn clusterer instance.
Args:
clf: Scikit-learn clusterer instance
Returns:
The same scikit-learn clusterer instance passed in **clf** with
embedded scikit-plot instance methods.
Raises:
ValueError: If **clf** does not contain ... | [
"Embeds",
"scikit",
"-",
"plot",
"plotting",
"methods",
"in",
"an",
"sklearn",
"clusterer",
"instance",
"."
] | 2dd3e6a76df77edcbd724c4db25575f70abb57cb | https://github.com/reiinakano/scikit-plot/blob/2dd3e6a76df77edcbd724c4db25575f70abb57cb/scikitplot/clustering.py#L18-L50 |
243,832 | reiinakano/scikit-plot | scikitplot/helpers.py | validate_labels | def validate_labels(known_classes, passed_labels, argument_name):
"""Validates the labels passed into the true_labels or pred_labels
arguments in the plot_confusion_matrix function.
Raises a ValueError exception if any of the passed labels are not in the
set of known classes or if there are duplicate l... | python | def validate_labels(known_classes, passed_labels, argument_name):
known_classes = np.array(known_classes)
passed_labels = np.array(passed_labels)
unique_labels, unique_indexes = np.unique(passed_labels, return_index=True)
if len(passed_labels) != len(unique_labels):
indexes = np.arange(0, len(... | [
"def",
"validate_labels",
"(",
"known_classes",
",",
"passed_labels",
",",
"argument_name",
")",
":",
"known_classes",
"=",
"np",
".",
"array",
"(",
"known_classes",
")",
"passed_labels",
"=",
"np",
".",
"array",
"(",
"passed_labels",
")",
"unique_labels",
",",
... | Validates the labels passed into the true_labels or pred_labels
arguments in the plot_confusion_matrix function.
Raises a ValueError exception if any of the passed labels are not in the
set of known classes or if there are duplicate labels. Otherwise returns
None.
Args:
known_classes (arra... | [
"Validates",
"the",
"labels",
"passed",
"into",
"the",
"true_labels",
"or",
"pred_labels",
"arguments",
"in",
"the",
"plot_confusion_matrix",
"function",
"."
] | 2dd3e6a76df77edcbd724c4db25575f70abb57cb | https://github.com/reiinakano/scikit-plot/blob/2dd3e6a76df77edcbd724c4db25575f70abb57cb/scikitplot/helpers.py#L108-L154 |
243,833 | reiinakano/scikit-plot | scikitplot/helpers.py | cumulative_gain_curve | def cumulative_gain_curve(y_true, y_score, pos_label=None):
"""This function generates the points necessary to plot the Cumulative Gain
Note: This implementation is restricted to the binary classification task.
Args:
y_true (array-like, shape (n_samples)): True labels of the data.
y_score... | python | def cumulative_gain_curve(y_true, y_score, pos_label=None):
y_true, y_score = np.asarray(y_true), np.asarray(y_score)
# ensure binary classification if pos_label is not specified
classes = np.unique(y_true)
if (pos_label is None and
not (np.array_equal(classes, [0, 1]) or
np.array_... | [
"def",
"cumulative_gain_curve",
"(",
"y_true",
",",
"y_score",
",",
"pos_label",
"=",
"None",
")",
":",
"y_true",
",",
"y_score",
"=",
"np",
".",
"asarray",
"(",
"y_true",
")",
",",
"np",
".",
"asarray",
"(",
"y_score",
")",
"# ensure binary classification i... | This function generates the points necessary to plot the Cumulative Gain
Note: This implementation is restricted to the binary classification task.
Args:
y_true (array-like, shape (n_samples)): True labels of the data.
y_score (array-like, shape (n_samples)): Target scores, can either be
... | [
"This",
"function",
"generates",
"the",
"points",
"necessary",
"to",
"plot",
"the",
"Cumulative",
"Gain"
] | 2dd3e6a76df77edcbd724c4db25575f70abb57cb | https://github.com/reiinakano/scikit-plot/blob/2dd3e6a76df77edcbd724c4db25575f70abb57cb/scikitplot/helpers.py#L157-L213 |
243,834 | allure-framework/allure-python | allure-python-commons/src/utils.py | getargspec | def getargspec(func):
"""
Used because getargspec for python 2.7 does not accept functools.partial
which is the type for pytest fixtures.
getargspec excerpted from:
sphinx.util.inspect
~~~~~~~~~~~~~~~~~~~
Helpers for inspecting Python modules.
:copyright: Copyright 2007-2018 by the Sph... | python | def getargspec(func):
# noqa: E731 type: (Any) -> Any
if inspect.ismethod(func):
func = func.__func__
parts = 0, () # noqa: E731 type: Tuple[int, Tuple[unicode, ...]]
if type(func) is partial:
keywords = func.keywords
if keywords is None:
keywords = {}
parts ... | [
"def",
"getargspec",
"(",
"func",
")",
":",
"# noqa: E731 type: (Any) -> Any",
"if",
"inspect",
".",
"ismethod",
"(",
"func",
")",
":",
"func",
"=",
"func",
".",
"__func__",
"parts",
"=",
"0",
",",
"(",
")",
"# noqa: E731 type: Tuple[int, Tuple[unicode, ...]]",
... | Used because getargspec for python 2.7 does not accept functools.partial
which is the type for pytest fixtures.
getargspec excerpted from:
sphinx.util.inspect
~~~~~~~~~~~~~~~~~~~
Helpers for inspecting Python modules.
:copyright: Copyright 2007-2018 by the Sphinx team, see AUTHORS.
:licens... | [
"Used",
"because",
"getargspec",
"for",
"python",
"2",
".",
"7",
"does",
"not",
"accept",
"functools",
".",
"partial",
"which",
"is",
"the",
"type",
"for",
"pytest",
"fixtures",
"."
] | 070fdcc093e8743cc5e58f5f108b21f12ec8ddaf | https://github.com/allure-framework/allure-python/blob/070fdcc093e8743cc5e58f5f108b21f12ec8ddaf/allure-python-commons/src/utils.py#L18-L61 |
243,835 | miLibris/flask-rest-jsonapi | flask_rest_jsonapi/querystring.py | QueryStringManager.querystring | def querystring(self):
"""Return original querystring but containing only managed keys
:return dict: dict of managed querystring parameter
"""
return {key: value for (key, value) in self.qs.items()
if key.startswith(self.MANAGED_KEYS) or self._get_key_values('filter[')} | python | def querystring(self):
return {key: value for (key, value) in self.qs.items()
if key.startswith(self.MANAGED_KEYS) or self._get_key_values('filter[')} | [
"def",
"querystring",
"(",
"self",
")",
":",
"return",
"{",
"key",
":",
"value",
"for",
"(",
"key",
",",
"value",
")",
"in",
"self",
".",
"qs",
".",
"items",
"(",
")",
"if",
"key",
".",
"startswith",
"(",
"self",
".",
"MANAGED_KEYS",
")",
"or",
"... | Return original querystring but containing only managed keys
:return dict: dict of managed querystring parameter | [
"Return",
"original",
"querystring",
"but",
"containing",
"only",
"managed",
"keys"
] | ecc8f2cd2b54cc0bfae7acd6cffcda0ba1140c43 | https://github.com/miLibris/flask-rest-jsonapi/blob/ecc8f2cd2b54cc0bfae7acd6cffcda0ba1140c43/flask_rest_jsonapi/querystring.py#L68-L74 |
243,836 | miLibris/flask-rest-jsonapi | flask_rest_jsonapi/querystring.py | QueryStringManager.filters | def filters(self):
"""Return filters from query string.
:return list: filter information
"""
results = []
filters = self.qs.get('filter')
if filters is not None:
try:
results.extend(json.loads(filters))
except (ValueError, TypeErro... | python | def filters(self):
results = []
filters = self.qs.get('filter')
if filters is not None:
try:
results.extend(json.loads(filters))
except (ValueError, TypeError):
raise InvalidFilters("Parse error")
if self._get_key_values('filter['):... | [
"def",
"filters",
"(",
"self",
")",
":",
"results",
"=",
"[",
"]",
"filters",
"=",
"self",
".",
"qs",
".",
"get",
"(",
"'filter'",
")",
"if",
"filters",
"is",
"not",
"None",
":",
"try",
":",
"results",
".",
"extend",
"(",
"json",
".",
"loads",
"(... | Return filters from query string.
:return list: filter information | [
"Return",
"filters",
"from",
"query",
"string",
"."
] | ecc8f2cd2b54cc0bfae7acd6cffcda0ba1140c43 | https://github.com/miLibris/flask-rest-jsonapi/blob/ecc8f2cd2b54cc0bfae7acd6cffcda0ba1140c43/flask_rest_jsonapi/querystring.py#L77-L91 |
243,837 | miLibris/flask-rest-jsonapi | flask_rest_jsonapi/querystring.py | QueryStringManager.pagination | def pagination(self):
"""Return all page parameters as a dict.
:return dict: a dict of pagination information
To allow multiples strategies, all parameters starting with `page` will be included. e.g::
{
"number": '25',
"size": '150',
}
... | python | def pagination(self):
# check values type
result = self._get_key_values('page')
for key, value in result.items():
if key not in ('number', 'size'):
raise BadRequest("{} is not a valid parameter of pagination".format(key), source={'parameter': 'page'})
try:... | [
"def",
"pagination",
"(",
"self",
")",
":",
"# check values type",
"result",
"=",
"self",
".",
"_get_key_values",
"(",
"'page'",
")",
"for",
"key",
",",
"value",
"in",
"result",
".",
"items",
"(",
")",
":",
"if",
"key",
"not",
"in",
"(",
"'number'",
",... | Return all page parameters as a dict.
:return dict: a dict of pagination information
To allow multiples strategies, all parameters starting with `page` will be included. e.g::
{
"number": '25',
"size": '150',
}
Example with number strat... | [
"Return",
"all",
"page",
"parameters",
"as",
"a",
"dict",
"."
] | ecc8f2cd2b54cc0bfae7acd6cffcda0ba1140c43 | https://github.com/miLibris/flask-rest-jsonapi/blob/ecc8f2cd2b54cc0bfae7acd6cffcda0ba1140c43/flask_rest_jsonapi/querystring.py#L94-L130 |
243,838 | miLibris/flask-rest-jsonapi | flask_rest_jsonapi/querystring.py | QueryStringManager.fields | def fields(self):
"""Return fields wanted by client.
:return dict: a dict of sparse fieldsets information
Return value will be a dict containing all fields by resource, for example::
{
"user": ['name', 'email'],
}
"""
result = self._get... | python | def fields(self):
result = self._get_key_values('fields')
for key, value in result.items():
if not isinstance(value, list):
result[key] = [value]
for key, value in result.items():
schema = get_schema_from_type(key)
for obj in value:
... | [
"def",
"fields",
"(",
"self",
")",
":",
"result",
"=",
"self",
".",
"_get_key_values",
"(",
"'fields'",
")",
"for",
"key",
",",
"value",
"in",
"result",
".",
"items",
"(",
")",
":",
"if",
"not",
"isinstance",
"(",
"value",
",",
"list",
")",
":",
"r... | Return fields wanted by client.
:return dict: a dict of sparse fieldsets information
Return value will be a dict containing all fields by resource, for example::
{
"user": ['name', 'email'],
} | [
"Return",
"fields",
"wanted",
"by",
"client",
"."
] | ecc8f2cd2b54cc0bfae7acd6cffcda0ba1140c43 | https://github.com/miLibris/flask-rest-jsonapi/blob/ecc8f2cd2b54cc0bfae7acd6cffcda0ba1140c43/flask_rest_jsonapi/querystring.py#L133-L156 |
243,839 | miLibris/flask-rest-jsonapi | flask_rest_jsonapi/querystring.py | QueryStringManager.sorting | def sorting(self):
"""Return fields to sort by including sort name for SQLAlchemy and row
sort parameter for other ORMs
:return list: a list of sorting information
Example of return value::
[
{'field': 'created_at', 'order': 'desc'},
]
... | python | def sorting(self):
if self.qs.get('sort'):
sorting_results = []
for sort_field in self.qs['sort'].split(','):
field = sort_field.replace('-', '')
if field not in self.schema._declared_fields:
raise InvalidSort("{} has no attribute {}".f... | [
"def",
"sorting",
"(",
"self",
")",
":",
"if",
"self",
".",
"qs",
".",
"get",
"(",
"'sort'",
")",
":",
"sorting_results",
"=",
"[",
"]",
"for",
"sort_field",
"in",
"self",
".",
"qs",
"[",
"'sort'",
"]",
".",
"split",
"(",
"','",
")",
":",
"field"... | Return fields to sort by including sort name for SQLAlchemy and row
sort parameter for other ORMs
:return list: a list of sorting information
Example of return value::
[
{'field': 'created_at', 'order': 'desc'},
] | [
"Return",
"fields",
"to",
"sort",
"by",
"including",
"sort",
"name",
"for",
"SQLAlchemy",
"and",
"row",
"sort",
"parameter",
"for",
"other",
"ORMs"
] | ecc8f2cd2b54cc0bfae7acd6cffcda0ba1140c43 | https://github.com/miLibris/flask-rest-jsonapi/blob/ecc8f2cd2b54cc0bfae7acd6cffcda0ba1140c43/flask_rest_jsonapi/querystring.py#L159-L185 |
243,840 | miLibris/flask-rest-jsonapi | flask_rest_jsonapi/querystring.py | QueryStringManager.include | def include(self):
"""Return fields to include
:return list: a list of include information
"""
include_param = self.qs.get('include', [])
if current_app.config.get('MAX_INCLUDE_DEPTH') is not None:
for include_path in include_param:
if len(include_pa... | python | def include(self):
include_param = self.qs.get('include', [])
if current_app.config.get('MAX_INCLUDE_DEPTH') is not None:
for include_path in include_param:
if len(include_path.split('.')) > current_app.config['MAX_INCLUDE_DEPTH']:
raise InvalidInclude("Y... | [
"def",
"include",
"(",
"self",
")",
":",
"include_param",
"=",
"self",
".",
"qs",
".",
"get",
"(",
"'include'",
",",
"[",
"]",
")",
"if",
"current_app",
".",
"config",
".",
"get",
"(",
"'MAX_INCLUDE_DEPTH'",
")",
"is",
"not",
"None",
":",
"for",
"inc... | Return fields to include
:return list: a list of include information | [
"Return",
"fields",
"to",
"include"
] | ecc8f2cd2b54cc0bfae7acd6cffcda0ba1140c43 | https://github.com/miLibris/flask-rest-jsonapi/blob/ecc8f2cd2b54cc0bfae7acd6cffcda0ba1140c43/flask_rest_jsonapi/querystring.py#L188-L201 |
243,841 | miLibris/flask-rest-jsonapi | flask_rest_jsonapi/exceptions.py | JsonApiException.to_dict | def to_dict(self):
"""Return values of each fields of an jsonapi error"""
error_dict = {}
for field in ('status', 'source', 'title', 'detail', 'id', 'code', 'links', 'meta'):
if getattr(self, field, None):
error_dict.update({field: getattr(self, field)})
retu... | python | def to_dict(self):
error_dict = {}
for field in ('status', 'source', 'title', 'detail', 'id', 'code', 'links', 'meta'):
if getattr(self, field, None):
error_dict.update({field: getattr(self, field)})
return error_dict | [
"def",
"to_dict",
"(",
"self",
")",
":",
"error_dict",
"=",
"{",
"}",
"for",
"field",
"in",
"(",
"'status'",
",",
"'source'",
",",
"'title'",
",",
"'detail'",
",",
"'id'",
",",
"'code'",
",",
"'links'",
",",
"'meta'",
")",
":",
"if",
"getattr",
"(",
... | Return values of each fields of an jsonapi error | [
"Return",
"values",
"of",
"each",
"fields",
"of",
"an",
"jsonapi",
"error"
] | ecc8f2cd2b54cc0bfae7acd6cffcda0ba1140c43 | https://github.com/miLibris/flask-rest-jsonapi/blob/ecc8f2cd2b54cc0bfae7acd6cffcda0ba1140c43/flask_rest_jsonapi/exceptions.py#L30-L37 |
243,842 | miLibris/flask-rest-jsonapi | flask_rest_jsonapi/resource.py | Resource.dispatch_request | def dispatch_request(self, *args, **kwargs):
"""Logic of how to handle a request"""
method = getattr(self, request.method.lower(), None)
if method is None and request.method == 'HEAD':
method = getattr(self, 'get', None)
assert method is not None, 'Unimplemented method {}'.fo... | python | def dispatch_request(self, *args, **kwargs):
method = getattr(self, request.method.lower(), None)
if method is None and request.method == 'HEAD':
method = getattr(self, 'get', None)
assert method is not None, 'Unimplemented method {}'.format(request.method)
headers = {'Conte... | [
"def",
"dispatch_request",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"method",
"=",
"getattr",
"(",
"self",
",",
"request",
".",
"method",
".",
"lower",
"(",
")",
",",
"None",
")",
"if",
"method",
"is",
"None",
"and",
"reque... | Logic of how to handle a request | [
"Logic",
"of",
"how",
"to",
"handle",
"a",
"request"
] | ecc8f2cd2b54cc0bfae7acd6cffcda0ba1140c43 | https://github.com/miLibris/flask-rest-jsonapi/blob/ecc8f2cd2b54cc0bfae7acd6cffcda0ba1140c43/flask_rest_jsonapi/resource.py#L62-L96 |
243,843 | miLibris/flask-rest-jsonapi | flask_rest_jsonapi/resource.py | ResourceList.get | def get(self, *args, **kwargs):
"""Retrieve a collection of objects"""
self.before_get(args, kwargs)
qs = QSManager(request.args, self.schema)
objects_count, objects = self.get_collection(qs, kwargs)
schema_kwargs = getattr(self, 'get_schema_kwargs', dict())
schema_kwa... | python | def get(self, *args, **kwargs):
self.before_get(args, kwargs)
qs = QSManager(request.args, self.schema)
objects_count, objects = self.get_collection(qs, kwargs)
schema_kwargs = getattr(self, 'get_schema_kwargs', dict())
schema_kwargs.update({'many': True})
self.before... | [
"def",
"get",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"self",
".",
"before_get",
"(",
"args",
",",
"kwargs",
")",
"qs",
"=",
"QSManager",
"(",
"request",
".",
"args",
",",
"self",
".",
"schema",
")",
"objects_count",
",",
... | Retrieve a collection of objects | [
"Retrieve",
"a",
"collection",
"of",
"objects"
] | ecc8f2cd2b54cc0bfae7acd6cffcda0ba1140c43 | https://github.com/miLibris/flask-rest-jsonapi/blob/ecc8f2cd2b54cc0bfae7acd6cffcda0ba1140c43/flask_rest_jsonapi/resource.py#L103-L133 |
243,844 | miLibris/flask-rest-jsonapi | flask_rest_jsonapi/resource.py | ResourceList.post | def post(self, *args, **kwargs):
"""Create an object"""
json_data = request.get_json() or {}
qs = QSManager(request.args, self.schema)
schema = compute_schema(self.schema,
getattr(self, 'post_schema_kwargs', dict()),
qs,
... | python | def post(self, *args, **kwargs):
json_data = request.get_json() or {}
qs = QSManager(request.args, self.schema)
schema = compute_schema(self.schema,
getattr(self, 'post_schema_kwargs', dict()),
qs,
... | [
"def",
"post",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"json_data",
"=",
"request",
".",
"get_json",
"(",
")",
"or",
"{",
"}",
"qs",
"=",
"QSManager",
"(",
"request",
".",
"args",
",",
"self",
".",
"schema",
")",
"schema... | Create an object | [
"Create",
"an",
"object"
] | ecc8f2cd2b54cc0bfae7acd6cffcda0ba1140c43 | https://github.com/miLibris/flask-rest-jsonapi/blob/ecc8f2cd2b54cc0bfae7acd6cffcda0ba1140c43/flask_rest_jsonapi/resource.py#L136-L181 |
243,845 | miLibris/flask-rest-jsonapi | flask_rest_jsonapi/resource.py | ResourceDetail.get | def get(self, *args, **kwargs):
"""Get object details"""
self.before_get(args, kwargs)
qs = QSManager(request.args, self.schema)
obj = self.get_object(kwargs, qs)
self.before_marshmallow(args, kwargs)
schema = compute_schema(self.schema,
... | python | def get(self, *args, **kwargs):
self.before_get(args, kwargs)
qs = QSManager(request.args, self.schema)
obj = self.get_object(kwargs, qs)
self.before_marshmallow(args, kwargs)
schema = compute_schema(self.schema,
getattr(self, 'get_schema_kwarg... | [
"def",
"get",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"self",
".",
"before_get",
"(",
"args",
",",
"kwargs",
")",
"qs",
"=",
"QSManager",
"(",
"request",
".",
"args",
",",
"self",
".",
"schema",
")",
"obj",
"=",
"self",
... | Get object details | [
"Get",
"object",
"details"
] | ecc8f2cd2b54cc0bfae7acd6cffcda0ba1140c43 | https://github.com/miLibris/flask-rest-jsonapi/blob/ecc8f2cd2b54cc0bfae7acd6cffcda0ba1140c43/flask_rest_jsonapi/resource.py#L213-L232 |
243,846 | miLibris/flask-rest-jsonapi | flask_rest_jsonapi/resource.py | ResourceDetail.patch | def patch(self, *args, **kwargs):
"""Update an object"""
json_data = request.get_json() or {}
qs = QSManager(request.args, self.schema)
schema_kwargs = getattr(self, 'patch_schema_kwargs', dict())
schema_kwargs.update({'partial': True})
self.before_marshmallow(args, kwa... | python | def patch(self, *args, **kwargs):
json_data = request.get_json() or {}
qs = QSManager(request.args, self.schema)
schema_kwargs = getattr(self, 'patch_schema_kwargs', dict())
schema_kwargs.update({'partial': True})
self.before_marshmallow(args, kwargs)
schema = compute_... | [
"def",
"patch",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"json_data",
"=",
"request",
".",
"get_json",
"(",
")",
"or",
"{",
"}",
"qs",
"=",
"QSManager",
"(",
"request",
".",
"args",
",",
"self",
".",
"schema",
")",
"schem... | Update an object | [
"Update",
"an",
"object"
] | ecc8f2cd2b54cc0bfae7acd6cffcda0ba1140c43 | https://github.com/miLibris/flask-rest-jsonapi/blob/ecc8f2cd2b54cc0bfae7acd6cffcda0ba1140c43/flask_rest_jsonapi/resource.py#L235-L286 |
243,847 | miLibris/flask-rest-jsonapi | flask_rest_jsonapi/resource.py | ResourceDetail.delete | def delete(self, *args, **kwargs):
"""Delete an object"""
self.before_delete(args, kwargs)
self.delete_object(kwargs)
result = {'meta': {'message': 'Object successfully deleted'}}
final_result = self.after_delete(result)
return final_result | python | def delete(self, *args, **kwargs):
self.before_delete(args, kwargs)
self.delete_object(kwargs)
result = {'meta': {'message': 'Object successfully deleted'}}
final_result = self.after_delete(result)
return final_result | [
"def",
"delete",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"self",
".",
"before_delete",
"(",
"args",
",",
"kwargs",
")",
"self",
".",
"delete_object",
"(",
"kwargs",
")",
"result",
"=",
"{",
"'meta'",
":",
"{",
"'message'",
... | Delete an object | [
"Delete",
"an",
"object"
] | ecc8f2cd2b54cc0bfae7acd6cffcda0ba1140c43 | https://github.com/miLibris/flask-rest-jsonapi/blob/ecc8f2cd2b54cc0bfae7acd6cffcda0ba1140c43/flask_rest_jsonapi/resource.py#L289-L299 |
243,848 | miLibris/flask-rest-jsonapi | flask_rest_jsonapi/resource.py | ResourceRelationship.get | def get(self, *args, **kwargs):
"""Get a relationship details"""
self.before_get(args, kwargs)
relationship_field, model_relationship_field, related_type_, related_id_field = self._get_relationship_data()
obj, data = self._data_layer.get_relationship(model_relationship_field,
... | python | def get(self, *args, **kwargs):
self.before_get(args, kwargs)
relationship_field, model_relationship_field, related_type_, related_id_field = self._get_relationship_data()
obj, data = self._data_layer.get_relationship(model_relationship_field,
... | [
"def",
"get",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"self",
".",
"before_get",
"(",
"args",
",",
"kwargs",
")",
"relationship_field",
",",
"model_relationship_field",
",",
"related_type_",
",",
"related_id_field",
"=",
"self",
"... | Get a relationship details | [
"Get",
"a",
"relationship",
"details"
] | ecc8f2cd2b54cc0bfae7acd6cffcda0ba1140c43 | https://github.com/miLibris/flask-rest-jsonapi/blob/ecc8f2cd2b54cc0bfae7acd6cffcda0ba1140c43/flask_rest_jsonapi/resource.py#L346-L370 |
243,849 | miLibris/flask-rest-jsonapi | flask_rest_jsonapi/resource.py | ResourceRelationship.patch | def patch(self, *args, **kwargs):
"""Update a relationship"""
json_data = request.get_json() or {}
relationship_field, model_relationship_field, related_type_, related_id_field = self._get_relationship_data()
if 'data' not in json_data:
raise BadRequest('You must provide da... | python | def patch(self, *args, **kwargs):
json_data = request.get_json() or {}
relationship_field, model_relationship_field, related_type_, related_id_field = self._get_relationship_data()
if 'data' not in json_data:
raise BadRequest('You must provide data with a "data" route node', source... | [
"def",
"patch",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"json_data",
"=",
"request",
".",
"get_json",
"(",
")",
"or",
"{",
"}",
"relationship_field",
",",
"model_relationship_field",
",",
"related_type_",
",",
"related_id_field",
... | Update a relationship | [
"Update",
"a",
"relationship"
] | ecc8f2cd2b54cc0bfae7acd6cffcda0ba1140c43 | https://github.com/miLibris/flask-rest-jsonapi/blob/ecc8f2cd2b54cc0bfae7acd6cffcda0ba1140c43/flask_rest_jsonapi/resource.py#L417-L458 |
243,850 | miLibris/flask-rest-jsonapi | flask_rest_jsonapi/resource.py | ResourceRelationship._get_relationship_data | def _get_relationship_data(self):
"""Get useful data for relationship management"""
relationship_field = request.path.split('/')[-1].replace('-', '_')
if relationship_field not in get_relationships(self.schema):
raise RelationNotFound("{} has no attribute {}".format(self.schema.__na... | python | def _get_relationship_data(self):
relationship_field = request.path.split('/')[-1].replace('-', '_')
if relationship_field not in get_relationships(self.schema):
raise RelationNotFound("{} has no attribute {}".format(self.schema.__name__, relationship_field))
related_type_ = self.s... | [
"def",
"_get_relationship_data",
"(",
"self",
")",
":",
"relationship_field",
"=",
"request",
".",
"path",
".",
"split",
"(",
"'/'",
")",
"[",
"-",
"1",
"]",
".",
"replace",
"(",
"'-'",
",",
"'_'",
")",
"if",
"relationship_field",
"not",
"in",
"get_relat... | Get useful data for relationship management | [
"Get",
"useful",
"data",
"for",
"relationship",
"management"
] | ecc8f2cd2b54cc0bfae7acd6cffcda0ba1140c43 | https://github.com/miLibris/flask-rest-jsonapi/blob/ecc8f2cd2b54cc0bfae7acd6cffcda0ba1140c43/flask_rest_jsonapi/resource.py#L504-L515 |
243,851 | miLibris/flask-rest-jsonapi | flask_rest_jsonapi/schema.py | compute_schema | def compute_schema(schema_cls, default_kwargs, qs, include):
"""Compute a schema around compound documents and sparse fieldsets
:param Schema schema_cls: the schema class
:param dict default_kwargs: the schema default kwargs
:param QueryStringManager qs: qs
:param list include: the relation field t... | python | def compute_schema(schema_cls, default_kwargs, qs, include):
# manage include_data parameter of the schema
schema_kwargs = default_kwargs
schema_kwargs['include_data'] = tuple()
# collect sub-related_includes
related_includes = {}
if include:
for include_path in include:
fi... | [
"def",
"compute_schema",
"(",
"schema_cls",
",",
"default_kwargs",
",",
"qs",
",",
"include",
")",
":",
"# manage include_data parameter of the schema",
"schema_kwargs",
"=",
"default_kwargs",
"schema_kwargs",
"[",
"'include_data'",
"]",
"=",
"tuple",
"(",
")",
"# col... | Compute a schema around compound documents and sparse fieldsets
:param Schema schema_cls: the schema class
:param dict default_kwargs: the schema default kwargs
:param QueryStringManager qs: qs
:param list include: the relation field to include data from
:return Schema schema: the schema computed | [
"Compute",
"a",
"schema",
"around",
"compound",
"documents",
"and",
"sparse",
"fieldsets"
] | ecc8f2cd2b54cc0bfae7acd6cffcda0ba1140c43 | https://github.com/miLibris/flask-rest-jsonapi/blob/ecc8f2cd2b54cc0bfae7acd6cffcda0ba1140c43/flask_rest_jsonapi/schema.py#L12-L82 |
243,852 | miLibris/flask-rest-jsonapi | flask_rest_jsonapi/schema.py | get_model_field | def get_model_field(schema, field):
"""Get the model field of a schema field
:param Schema schema: a marshmallow schema
:param str field: the name of the schema field
:return str: the name of the field in the model
"""
if schema._declared_fields.get(field) is None:
raise Exception("{} h... | python | def get_model_field(schema, field):
if schema._declared_fields.get(field) is None:
raise Exception("{} has no attribute {}".format(schema.__name__, field))
if schema._declared_fields[field].attribute is not None:
return schema._declared_fields[field].attribute
return field | [
"def",
"get_model_field",
"(",
"schema",
",",
"field",
")",
":",
"if",
"schema",
".",
"_declared_fields",
".",
"get",
"(",
"field",
")",
"is",
"None",
":",
"raise",
"Exception",
"(",
"\"{} has no attribute {}\"",
".",
"format",
"(",
"schema",
".",
"__name__"... | Get the model field of a schema field
:param Schema schema: a marshmallow schema
:param str field: the name of the schema field
:return str: the name of the field in the model | [
"Get",
"the",
"model",
"field",
"of",
"a",
"schema",
"field"
] | ecc8f2cd2b54cc0bfae7acd6cffcda0ba1140c43 | https://github.com/miLibris/flask-rest-jsonapi/blob/ecc8f2cd2b54cc0bfae7acd6cffcda0ba1140c43/flask_rest_jsonapi/schema.py#L85-L97 |
243,853 | miLibris/flask-rest-jsonapi | flask_rest_jsonapi/schema.py | get_nested_fields | def get_nested_fields(schema, model_field=False):
"""Return nested fields of a schema to support a join
:param Schema schema: a marshmallow schema
:param boolean model_field: whether to extract the model field for the nested fields
:return list: list of nested fields of the schema
"""
nested_f... | python | def get_nested_fields(schema, model_field=False):
nested_fields = []
for (key, value) in schema._declared_fields.items():
if isinstance(value, List) and isinstance(value.container, Nested):
nested_fields.append(key)
elif isinstance(value, Nested):
nested_fields.append(key... | [
"def",
"get_nested_fields",
"(",
"schema",
",",
"model_field",
"=",
"False",
")",
":",
"nested_fields",
"=",
"[",
"]",
"for",
"(",
"key",
",",
"value",
")",
"in",
"schema",
".",
"_declared_fields",
".",
"items",
"(",
")",
":",
"if",
"isinstance",
"(",
... | Return nested fields of a schema to support a join
:param Schema schema: a marshmallow schema
:param boolean model_field: whether to extract the model field for the nested fields
:return list: list of nested fields of the schema | [
"Return",
"nested",
"fields",
"of",
"a",
"schema",
"to",
"support",
"a",
"join"
] | ecc8f2cd2b54cc0bfae7acd6cffcda0ba1140c43 | https://github.com/miLibris/flask-rest-jsonapi/blob/ecc8f2cd2b54cc0bfae7acd6cffcda0ba1140c43/flask_rest_jsonapi/schema.py#L99-L117 |
243,854 | miLibris/flask-rest-jsonapi | flask_rest_jsonapi/schema.py | get_relationships | def get_relationships(schema, model_field=False):
"""Return relationship fields of a schema
:param Schema schema: a marshmallow schema
:param list: list of relationship fields of a schema
"""
relationships = [key for (key, value) in schema._declared_fields.items() if isinstance(value, Relationship)... | python | def get_relationships(schema, model_field=False):
relationships = [key for (key, value) in schema._declared_fields.items() if isinstance(value, Relationship)]
if model_field is True:
relationships = [get_model_field(schema, key) for key in relationships]
return relationships | [
"def",
"get_relationships",
"(",
"schema",
",",
"model_field",
"=",
"False",
")",
":",
"relationships",
"=",
"[",
"key",
"for",
"(",
"key",
",",
"value",
")",
"in",
"schema",
".",
"_declared_fields",
".",
"items",
"(",
")",
"if",
"isinstance",
"(",
"valu... | Return relationship fields of a schema
:param Schema schema: a marshmallow schema
:param list: list of relationship fields of a schema | [
"Return",
"relationship",
"fields",
"of",
"a",
"schema"
] | ecc8f2cd2b54cc0bfae7acd6cffcda0ba1140c43 | https://github.com/miLibris/flask-rest-jsonapi/blob/ecc8f2cd2b54cc0bfae7acd6cffcda0ba1140c43/flask_rest_jsonapi/schema.py#L119-L130 |
243,855 | miLibris/flask-rest-jsonapi | flask_rest_jsonapi/schema.py | get_schema_from_type | def get_schema_from_type(resource_type):
"""Retrieve a schema from the registry by his type
:param str type_: the type of the resource
:return Schema: the schema class
"""
for cls_name, cls in class_registry._registry.items():
try:
if cls[0].opts.type_ == resource_type:
... | python | def get_schema_from_type(resource_type):
for cls_name, cls in class_registry._registry.items():
try:
if cls[0].opts.type_ == resource_type:
return cls[0]
except Exception:
pass
raise Exception("Couldn't find schema for type: {}".format(resource_type)) | [
"def",
"get_schema_from_type",
"(",
"resource_type",
")",
":",
"for",
"cls_name",
",",
"cls",
"in",
"class_registry",
".",
"_registry",
".",
"items",
"(",
")",
":",
"try",
":",
"if",
"cls",
"[",
"0",
"]",
".",
"opts",
".",
"type_",
"==",
"resource_type",... | Retrieve a schema from the registry by his type
:param str type_: the type of the resource
:return Schema: the schema class | [
"Retrieve",
"a",
"schema",
"from",
"the",
"registry",
"by",
"his",
"type"
] | ecc8f2cd2b54cc0bfae7acd6cffcda0ba1140c43 | https://github.com/miLibris/flask-rest-jsonapi/blob/ecc8f2cd2b54cc0bfae7acd6cffcda0ba1140c43/flask_rest_jsonapi/schema.py#L143-L156 |
243,856 | miLibris/flask-rest-jsonapi | flask_rest_jsonapi/schema.py | get_schema_field | def get_schema_field(schema, field):
"""Get the schema field of a model field
:param Schema schema: a marshmallow schema
:param str field: the name of the model field
:return str: the name of the field in the schema
"""
schema_fields_to_model = {key: get_model_field(schema, key) for (key, value... | python | def get_schema_field(schema, field):
schema_fields_to_model = {key: get_model_field(schema, key) for (key, value) in schema._declared_fields.items()}
for key, value in schema_fields_to_model.items():
if value == field:
return key
raise Exception("Couldn't find schema field from {}".form... | [
"def",
"get_schema_field",
"(",
"schema",
",",
"field",
")",
":",
"schema_fields_to_model",
"=",
"{",
"key",
":",
"get_model_field",
"(",
"schema",
",",
"key",
")",
"for",
"(",
"key",
",",
"value",
")",
"in",
"schema",
".",
"_declared_fields",
".",
"items"... | Get the schema field of a model field
:param Schema schema: a marshmallow schema
:param str field: the name of the model field
:return str: the name of the field in the schema | [
"Get",
"the",
"schema",
"field",
"of",
"a",
"model",
"field"
] | ecc8f2cd2b54cc0bfae7acd6cffcda0ba1140c43 | https://github.com/miLibris/flask-rest-jsonapi/blob/ecc8f2cd2b54cc0bfae7acd6cffcda0ba1140c43/flask_rest_jsonapi/schema.py#L159-L171 |
243,857 | miLibris/flask-rest-jsonapi | flask_rest_jsonapi/data_layers/base.py | BaseDataLayer.bound_rewritable_methods | def bound_rewritable_methods(self, methods):
"""Bound additional methods to current instance
:param class meta: information from Meta class used to configure the data layer instance
"""
for key, value in methods.items():
if key in self.REWRITABLE_METHODS:
set... | python | def bound_rewritable_methods(self, methods):
for key, value in methods.items():
if key in self.REWRITABLE_METHODS:
setattr(self, key, types.MethodType(value, self)) | [
"def",
"bound_rewritable_methods",
"(",
"self",
",",
"methods",
")",
":",
"for",
"key",
",",
"value",
"in",
"methods",
".",
"items",
"(",
")",
":",
"if",
"key",
"in",
"self",
".",
"REWRITABLE_METHODS",
":",
"setattr",
"(",
"self",
",",
"key",
",",
"typ... | Bound additional methods to current instance
:param class meta: information from Meta class used to configure the data layer instance | [
"Bound",
"additional",
"methods",
"to",
"current",
"instance"
] | ecc8f2cd2b54cc0bfae7acd6cffcda0ba1140c43 | https://github.com/miLibris/flask-rest-jsonapi/blob/ecc8f2cd2b54cc0bfae7acd6cffcda0ba1140c43/flask_rest_jsonapi/data_layers/base.py#L318-L325 |
243,858 | miLibris/flask-rest-jsonapi | flask_rest_jsonapi/data_layers/filtering/alchemy.py | create_filters | def create_filters(model, filter_info, resource):
"""Apply filters from filters information to base query
:param DeclarativeMeta model: the model of the node
:param dict filter_info: current node filter information
:param Resource resource: the resource
"""
filters = []
for filter_ in filte... | python | def create_filters(model, filter_info, resource):
filters = []
for filter_ in filter_info:
filters.append(Node(model, filter_, resource, resource.schema).resolve())
return filters | [
"def",
"create_filters",
"(",
"model",
",",
"filter_info",
",",
"resource",
")",
":",
"filters",
"=",
"[",
"]",
"for",
"filter_",
"in",
"filter_info",
":",
"filters",
".",
"append",
"(",
"Node",
"(",
"model",
",",
"filter_",
",",
"resource",
",",
"resour... | Apply filters from filters information to base query
:param DeclarativeMeta model: the model of the node
:param dict filter_info: current node filter information
:param Resource resource: the resource | [
"Apply",
"filters",
"from",
"filters",
"information",
"to",
"base",
"query"
] | ecc8f2cd2b54cc0bfae7acd6cffcda0ba1140c43 | https://github.com/miLibris/flask-rest-jsonapi/blob/ecc8f2cd2b54cc0bfae7acd6cffcda0ba1140c43/flask_rest_jsonapi/data_layers/filtering/alchemy.py#L11-L22 |
243,859 | miLibris/flask-rest-jsonapi | flask_rest_jsonapi/data_layers/filtering/alchemy.py | Node.resolve | def resolve(self):
"""Create filter for a particular node of the filter tree"""
if 'or' not in self.filter_ and 'and' not in self.filter_ and 'not' not in self.filter_:
value = self.value
if isinstance(value, dict):
value = Node(self.related_model, value, self.re... | python | def resolve(self):
if 'or' not in self.filter_ and 'and' not in self.filter_ and 'not' not in self.filter_:
value = self.value
if isinstance(value, dict):
value = Node(self.related_model, value, self.resource, self.related_schema).resolve()
if '__' in self.f... | [
"def",
"resolve",
"(",
"self",
")",
":",
"if",
"'or'",
"not",
"in",
"self",
".",
"filter_",
"and",
"'and'",
"not",
"in",
"self",
".",
"filter_",
"and",
"'not'",
"not",
"in",
"self",
".",
"filter_",
":",
"value",
"=",
"self",
".",
"value",
"if",
"is... | Create filter for a particular node of the filter tree | [
"Create",
"filter",
"for",
"a",
"particular",
"node",
"of",
"the",
"filter",
"tree"
] | ecc8f2cd2b54cc0bfae7acd6cffcda0ba1140c43 | https://github.com/miLibris/flask-rest-jsonapi/blob/ecc8f2cd2b54cc0bfae7acd6cffcda0ba1140c43/flask_rest_jsonapi/data_layers/filtering/alchemy.py#L41-L62 |
243,860 | miLibris/flask-rest-jsonapi | flask_rest_jsonapi/data_layers/filtering/alchemy.py | Node.name | def name(self):
"""Return the name of the node or raise a BadRequest exception
:return str: the name of the field to filter on
"""
name = self.filter_.get('name')
if name is None:
raise InvalidFilters("Can't find name of a filter")
if '__' in name:
... | python | def name(self):
name = self.filter_.get('name')
if name is None:
raise InvalidFilters("Can't find name of a filter")
if '__' in name:
name = name.split('__')[0]
if name not in self.schema._declared_fields:
raise InvalidFilters("{} has no attribute {... | [
"def",
"name",
"(",
"self",
")",
":",
"name",
"=",
"self",
".",
"filter_",
".",
"get",
"(",
"'name'",
")",
"if",
"name",
"is",
"None",
":",
"raise",
"InvalidFilters",
"(",
"\"Can't find name of a filter\"",
")",
"if",
"'__'",
"in",
"name",
":",
"name",
... | Return the name of the node or raise a BadRequest exception
:return str: the name of the field to filter on | [
"Return",
"the",
"name",
"of",
"the",
"node",
"or",
"raise",
"a",
"BadRequest",
"exception"
] | ecc8f2cd2b54cc0bfae7acd6cffcda0ba1140c43 | https://github.com/miLibris/flask-rest-jsonapi/blob/ecc8f2cd2b54cc0bfae7acd6cffcda0ba1140c43/flask_rest_jsonapi/data_layers/filtering/alchemy.py#L65-L81 |
243,861 | miLibris/flask-rest-jsonapi | flask_rest_jsonapi/data_layers/filtering/alchemy.py | Node.column | def column(self):
"""Get the column object
:param DeclarativeMeta model: the model
:param str field: the field
:return InstrumentedAttribute: the column to filter on
"""
field = self.name
model_field = get_model_field(self.schema, field)
try:
... | python | def column(self):
field = self.name
model_field = get_model_field(self.schema, field)
try:
return getattr(self.model, model_field)
except AttributeError:
raise InvalidFilters("{} has no attribute {}".format(self.model.__name__, model_field)) | [
"def",
"column",
"(",
"self",
")",
":",
"field",
"=",
"self",
".",
"name",
"model_field",
"=",
"get_model_field",
"(",
"self",
".",
"schema",
",",
"field",
")",
"try",
":",
"return",
"getattr",
"(",
"self",
".",
"model",
",",
"model_field",
")",
"excep... | Get the column object
:param DeclarativeMeta model: the model
:param str field: the field
:return InstrumentedAttribute: the column to filter on | [
"Get",
"the",
"column",
"object"
] | ecc8f2cd2b54cc0bfae7acd6cffcda0ba1140c43 | https://github.com/miLibris/flask-rest-jsonapi/blob/ecc8f2cd2b54cc0bfae7acd6cffcda0ba1140c43/flask_rest_jsonapi/data_layers/filtering/alchemy.py#L95-L109 |
243,862 | miLibris/flask-rest-jsonapi | flask_rest_jsonapi/data_layers/filtering/alchemy.py | Node.operator | def operator(self):
"""Get the function operator from his name
:return callable: a callable to make operation on a column
"""
operators = (self.op, self.op + '_', '__' + self.op + '__')
for op in operators:
if hasattr(self.column, op):
return op
... | python | def operator(self):
operators = (self.op, self.op + '_', '__' + self.op + '__')
for op in operators:
if hasattr(self.column, op):
return op
raise InvalidFilters("{} has no operator {}".format(self.column.key, self.op)) | [
"def",
"operator",
"(",
"self",
")",
":",
"operators",
"=",
"(",
"self",
".",
"op",
",",
"self",
".",
"op",
"+",
"'_'",
",",
"'__'",
"+",
"self",
".",
"op",
"+",
"'__'",
")",
"for",
"op",
"in",
"operators",
":",
"if",
"hasattr",
"(",
"self",
".... | Get the function operator from his name
:return callable: a callable to make operation on a column | [
"Get",
"the",
"function",
"operator",
"from",
"his",
"name"
] | ecc8f2cd2b54cc0bfae7acd6cffcda0ba1140c43 | https://github.com/miLibris/flask-rest-jsonapi/blob/ecc8f2cd2b54cc0bfae7acd6cffcda0ba1140c43/flask_rest_jsonapi/data_layers/filtering/alchemy.py#L112-L123 |
243,863 | miLibris/flask-rest-jsonapi | flask_rest_jsonapi/data_layers/filtering/alchemy.py | Node.value | def value(self):
"""Get the value to filter on
:return: the value to filter on
"""
if self.filter_.get('field') is not None:
try:
result = getattr(self.model, self.filter_['field'])
except AttributeError:
raise InvalidFilters("{} h... | python | def value(self):
if self.filter_.get('field') is not None:
try:
result = getattr(self.model, self.filter_['field'])
except AttributeError:
raise InvalidFilters("{} has no attribute {}".format(self.model.__name__, self.filter_['field']))
else:
... | [
"def",
"value",
"(",
"self",
")",
":",
"if",
"self",
".",
"filter_",
".",
"get",
"(",
"'field'",
")",
"is",
"not",
"None",
":",
"try",
":",
"result",
"=",
"getattr",
"(",
"self",
".",
"model",
",",
"self",
".",
"filter_",
"[",
"'field'",
"]",
")"... | Get the value to filter on
:return: the value to filter on | [
"Get",
"the",
"value",
"to",
"filter",
"on"
] | ecc8f2cd2b54cc0bfae7acd6cffcda0ba1140c43 | https://github.com/miLibris/flask-rest-jsonapi/blob/ecc8f2cd2b54cc0bfae7acd6cffcda0ba1140c43/flask_rest_jsonapi/data_layers/filtering/alchemy.py#L126-L142 |
243,864 | miLibris/flask-rest-jsonapi | flask_rest_jsonapi/data_layers/filtering/alchemy.py | Node.related_model | def related_model(self):
"""Get the related model of a relationship field
:return DeclarativeMeta: the related model
"""
relationship_field = self.name
if relationship_field not in get_relationships(self.schema):
raise InvalidFilters("{} has no relationship attribut... | python | def related_model(self):
relationship_field = self.name
if relationship_field not in get_relationships(self.schema):
raise InvalidFilters("{} has no relationship attribute {}".format(self.schema.__name__, relationship_field))
return getattr(self.model, get_model_field(self.schema, ... | [
"def",
"related_model",
"(",
"self",
")",
":",
"relationship_field",
"=",
"self",
".",
"name",
"if",
"relationship_field",
"not",
"in",
"get_relationships",
"(",
"self",
".",
"schema",
")",
":",
"raise",
"InvalidFilters",
"(",
"\"{} has no relationship attribute {}\... | Get the related model of a relationship field
:return DeclarativeMeta: the related model | [
"Get",
"the",
"related",
"model",
"of",
"a",
"relationship",
"field"
] | ecc8f2cd2b54cc0bfae7acd6cffcda0ba1140c43 | https://github.com/miLibris/flask-rest-jsonapi/blob/ecc8f2cd2b54cc0bfae7acd6cffcda0ba1140c43/flask_rest_jsonapi/data_layers/filtering/alchemy.py#L145-L155 |
243,865 | miLibris/flask-rest-jsonapi | flask_rest_jsonapi/data_layers/filtering/alchemy.py | Node.related_schema | def related_schema(self):
"""Get the related schema of a relationship field
:return Schema: the related schema
"""
relationship_field = self.name
if relationship_field not in get_relationships(self.schema):
raise InvalidFilters("{} has no relationship attribute {}".... | python | def related_schema(self):
relationship_field = self.name
if relationship_field not in get_relationships(self.schema):
raise InvalidFilters("{} has no relationship attribute {}".format(self.schema.__name__, relationship_field))
return self.schema._declared_fields[relationship_field]... | [
"def",
"related_schema",
"(",
"self",
")",
":",
"relationship_field",
"=",
"self",
".",
"name",
"if",
"relationship_field",
"not",
"in",
"get_relationships",
"(",
"self",
".",
"schema",
")",
":",
"raise",
"InvalidFilters",
"(",
"\"{} has no relationship attribute {}... | Get the related schema of a relationship field
:return Schema: the related schema | [
"Get",
"the",
"related",
"schema",
"of",
"a",
"relationship",
"field"
] | ecc8f2cd2b54cc0bfae7acd6cffcda0ba1140c43 | https://github.com/miLibris/flask-rest-jsonapi/blob/ecc8f2cd2b54cc0bfae7acd6cffcda0ba1140c43/flask_rest_jsonapi/data_layers/filtering/alchemy.py#L158-L168 |
243,866 | miLibris/flask-rest-jsonapi | flask_rest_jsonapi/api.py | Api.init_app | def init_app(self, app=None, blueprint=None, additional_blueprints=None):
"""Update flask application with our api
:param Application app: a flask application
"""
if app is not None:
self.app = app
if blueprint is not None:
self.blueprint = blueprint
... | python | def init_app(self, app=None, blueprint=None, additional_blueprints=None):
if app is not None:
self.app = app
if blueprint is not None:
self.blueprint = blueprint
for resource in self.resources:
self.route(resource['resource'],
resource... | [
"def",
"init_app",
"(",
"self",
",",
"app",
"=",
"None",
",",
"blueprint",
"=",
"None",
",",
"additional_blueprints",
"=",
"None",
")",
":",
"if",
"app",
"is",
"not",
"None",
":",
"self",
".",
"app",
"=",
"app",
"if",
"blueprint",
"is",
"not",
"None"... | Update flask application with our api
:param Application app: a flask application | [
"Update",
"flask",
"application",
"with",
"our",
"api"
] | ecc8f2cd2b54cc0bfae7acd6cffcda0ba1140c43 | https://github.com/miLibris/flask-rest-jsonapi/blob/ecc8f2cd2b54cc0bfae7acd6cffcda0ba1140c43/flask_rest_jsonapi/api.py#L35-L59 |
243,867 | miLibris/flask-rest-jsonapi | flask_rest_jsonapi/api.py | Api.route | def route(self, resource, view, *urls, **kwargs):
"""Create an api view.
:param Resource resource: a resource class inherited from flask_rest_jsonapi.resource.Resource
:param str view: the view name
:param list urls: the urls of the view
:param dict kwargs: additional options of... | python | def route(self, resource, view, *urls, **kwargs):
resource.view = view
url_rule_options = kwargs.get('url_rule_options') or dict()
view_func = resource.as_view(view)
if 'blueprint' in kwargs:
resource.view = '.'.join([kwargs['blueprint'].name, resource.view])
fo... | [
"def",
"route",
"(",
"self",
",",
"resource",
",",
"view",
",",
"*",
"urls",
",",
"*",
"*",
"kwargs",
")",
":",
"resource",
".",
"view",
"=",
"view",
"url_rule_options",
"=",
"kwargs",
".",
"get",
"(",
"'url_rule_options'",
")",
"or",
"dict",
"(",
")... | Create an api view.
:param Resource resource: a resource class inherited from flask_rest_jsonapi.resource.Resource
:param str view: the view name
:param list urls: the urls of the view
:param dict kwargs: additional options of the route | [
"Create",
"an",
"api",
"view",
"."
] | ecc8f2cd2b54cc0bfae7acd6cffcda0ba1140c43 | https://github.com/miLibris/flask-rest-jsonapi/blob/ecc8f2cd2b54cc0bfae7acd6cffcda0ba1140c43/flask_rest_jsonapi/api.py#L61-L91 |
243,868 | miLibris/flask-rest-jsonapi | flask_rest_jsonapi/api.py | Api.oauth_manager | def oauth_manager(self, oauth_manager):
"""Use the oauth manager to enable oauth for API
:param oauth_manager: the oauth manager
"""
@self.app.before_request
def before_request():
endpoint = request.endpoint
resource = self.app.view_functions[endpoint].vi... | python | def oauth_manager(self, oauth_manager):
@self.app.before_request
def before_request():
endpoint = request.endpoint
resource = self.app.view_functions[endpoint].view_class
if not getattr(resource, 'disable_oauth'):
scopes = request.args.get('scopes')
... | [
"def",
"oauth_manager",
"(",
"self",
",",
"oauth_manager",
")",
":",
"@",
"self",
".",
"app",
".",
"before_request",
"def",
"before_request",
"(",
")",
":",
"endpoint",
"=",
"request",
".",
"endpoint",
"resource",
"=",
"self",
".",
"app",
".",
"view_functi... | Use the oauth manager to enable oauth for API
:param oauth_manager: the oauth manager | [
"Use",
"the",
"oauth",
"manager",
"to",
"enable",
"oauth",
"for",
"API"
] | ecc8f2cd2b54cc0bfae7acd6cffcda0ba1140c43 | https://github.com/miLibris/flask-rest-jsonapi/blob/ecc8f2cd2b54cc0bfae7acd6cffcda0ba1140c43/flask_rest_jsonapi/api.py#L93-L124 |
243,869 | miLibris/flask-rest-jsonapi | flask_rest_jsonapi/api.py | Api.build_scope | def build_scope(resource, method):
"""Compute the name of the scope for oauth
:param Resource resource: the resource manager
:param str method: an http method
:return str: the name of the scope
"""
if ResourceList in inspect.getmro(resource) and method == 'GET':
... | python | def build_scope(resource, method):
if ResourceList in inspect.getmro(resource) and method == 'GET':
prefix = 'list'
else:
method_to_prefix = {'GET': 'get',
'POST': 'create',
'PATCH': 'update',
... | [
"def",
"build_scope",
"(",
"resource",
",",
"method",
")",
":",
"if",
"ResourceList",
"in",
"inspect",
".",
"getmro",
"(",
"resource",
")",
"and",
"method",
"==",
"'GET'",
":",
"prefix",
"=",
"'list'",
"else",
":",
"method_to_prefix",
"=",
"{",
"'GET'",
... | Compute the name of the scope for oauth
:param Resource resource: the resource manager
:param str method: an http method
:return str: the name of the scope | [
"Compute",
"the",
"name",
"of",
"the",
"scope",
"for",
"oauth"
] | ecc8f2cd2b54cc0bfae7acd6cffcda0ba1140c43 | https://github.com/miLibris/flask-rest-jsonapi/blob/ecc8f2cd2b54cc0bfae7acd6cffcda0ba1140c43/flask_rest_jsonapi/api.py#L127-L146 |
243,870 | miLibris/flask-rest-jsonapi | flask_rest_jsonapi/api.py | Api.permission_manager | def permission_manager(self, permission_manager):
"""Use permission manager to enable permission for API
:param callable permission_manager: the permission manager
"""
self.check_permissions = permission_manager
for resource in self.resource_registry:
if getattr(res... | python | def permission_manager(self, permission_manager):
self.check_permissions = permission_manager
for resource in self.resource_registry:
if getattr(resource, 'disable_permission', None) is not True:
for method in getattr(resource, 'methods', ('GET', 'POST', 'PATCH', 'DELETE')):... | [
"def",
"permission_manager",
"(",
"self",
",",
"permission_manager",
")",
":",
"self",
".",
"check_permissions",
"=",
"permission_manager",
"for",
"resource",
"in",
"self",
".",
"resource_registry",
":",
"if",
"getattr",
"(",
"resource",
",",
"'disable_permission'",... | Use permission manager to enable permission for API
:param callable permission_manager: the permission manager | [
"Use",
"permission",
"manager",
"to",
"enable",
"permission",
"for",
"API"
] | ecc8f2cd2b54cc0bfae7acd6cffcda0ba1140c43 | https://github.com/miLibris/flask-rest-jsonapi/blob/ecc8f2cd2b54cc0bfae7acd6cffcda0ba1140c43/flask_rest_jsonapi/api.py#L148-L160 |
243,871 | miLibris/flask-rest-jsonapi | flask_rest_jsonapi/api.py | Api.has_permission | def has_permission(self, *args, **kwargs):
"""Decorator used to check permissions before to call resource manager method"""
def wrapper(view):
if getattr(view, '_has_permissions_decorator', False) is True:
return view
@wraps(view)
@jsonapi_exception_f... | python | def has_permission(self, *args, **kwargs):
def wrapper(view):
if getattr(view, '_has_permissions_decorator', False) is True:
return view
@wraps(view)
@jsonapi_exception_formatter
def decorated(*view_args, **view_kwargs):
self.check... | [
"def",
"has_permission",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"def",
"wrapper",
"(",
"view",
")",
":",
"if",
"getattr",
"(",
"view",
",",
"'_has_permissions_decorator'",
",",
"False",
")",
"is",
"True",
":",
"return",
"view... | Decorator used to check permissions before to call resource manager method | [
"Decorator",
"used",
"to",
"check",
"permissions",
"before",
"to",
"call",
"resource",
"manager",
"method"
] | ecc8f2cd2b54cc0bfae7acd6cffcda0ba1140c43 | https://github.com/miLibris/flask-rest-jsonapi/blob/ecc8f2cd2b54cc0bfae7acd6cffcda0ba1140c43/flask_rest_jsonapi/api.py#L162-L175 |
243,872 | miLibris/flask-rest-jsonapi | flask_rest_jsonapi/decorators.py | check_headers | def check_headers(func):
"""Check headers according to jsonapi reference
:param callable func: the function to decorate
:return callable: the wrapped function
"""
@wraps(func)
def wrapper(*args, **kwargs):
if request.method in ('POST', 'PATCH'):
if 'Content-Type' in request.... | python | def check_headers(func):
@wraps(func)
def wrapper(*args, **kwargs):
if request.method in ('POST', 'PATCH'):
if 'Content-Type' in request.headers and\
'application/vnd.api+json' in request.headers['Content-Type'] and\
request.headers['Content-Type'] != ... | [
"def",
"check_headers",
"(",
"func",
")",
":",
"@",
"wraps",
"(",
"func",
")",
"def",
"wrapper",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"request",
".",
"method",
"in",
"(",
"'POST'",
",",
"'PATCH'",
")",
":",
"if",
"'Content-Typ... | Check headers according to jsonapi reference
:param callable func: the function to decorate
:return callable: the wrapped function | [
"Check",
"headers",
"according",
"to",
"jsonapi",
"reference"
] | ecc8f2cd2b54cc0bfae7acd6cffcda0ba1140c43 | https://github.com/miLibris/flask-rest-jsonapi/blob/ecc8f2cd2b54cc0bfae7acd6cffcda0ba1140c43/flask_rest_jsonapi/decorators.py#L15-L48 |
243,873 | miLibris/flask-rest-jsonapi | flask_rest_jsonapi/decorators.py | check_method_requirements | def check_method_requirements(func):
"""Check methods requirements
:param callable func: the function to decorate
:return callable: the wrapped function
"""
@wraps(func)
def wrapper(*args, **kwargs):
error_message = "You must provide {error_field} in {cls} to get access to the default {... | python | def check_method_requirements(func):
@wraps(func)
def wrapper(*args, **kwargs):
error_message = "You must provide {error_field} in {cls} to get access to the default {method} method"
error_data = {'cls': args[0].__class__.__name__, 'method': request.method.lower()}
if request.method != ... | [
"def",
"check_method_requirements",
"(",
"func",
")",
":",
"@",
"wraps",
"(",
"func",
")",
"def",
"wrapper",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"error_message",
"=",
"\"You must provide {error_field} in {cls} to get access to the default {method} met... | Check methods requirements
:param callable func: the function to decorate
:return callable: the wrapped function | [
"Check",
"methods",
"requirements"
] | ecc8f2cd2b54cc0bfae7acd6cffcda0ba1140c43 | https://github.com/miLibris/flask-rest-jsonapi/blob/ecc8f2cd2b54cc0bfae7acd6cffcda0ba1140c43/flask_rest_jsonapi/decorators.py#L51-L68 |
243,874 | miLibris/flask-rest-jsonapi | flask_rest_jsonapi/data_layers/alchemy.py | SqlalchemyDataLayer.create_object | def create_object(self, data, view_kwargs):
"""Create an object through sqlalchemy
:param dict data: the data validated by marshmallow
:param dict view_kwargs: kwargs from the resource view
:return DeclarativeMeta: an object from sqlalchemy
"""
self.before_create_object(... | python | def create_object(self, data, view_kwargs):
self.before_create_object(data, view_kwargs)
relationship_fields = get_relationships(self.resource.schema, model_field=True)
nested_fields = get_nested_fields(self.resource.schema, model_field=True)
join_fields = relationship_fields + nested_... | [
"def",
"create_object",
"(",
"self",
",",
"data",
",",
"view_kwargs",
")",
":",
"self",
".",
"before_create_object",
"(",
"data",
",",
"view_kwargs",
")",
"relationship_fields",
"=",
"get_relationships",
"(",
"self",
".",
"resource",
".",
"schema",
",",
"model... | Create an object through sqlalchemy
:param dict data: the data validated by marshmallow
:param dict view_kwargs: kwargs from the resource view
:return DeclarativeMeta: an object from sqlalchemy | [
"Create",
"an",
"object",
"through",
"sqlalchemy"
] | ecc8f2cd2b54cc0bfae7acd6cffcda0ba1140c43 | https://github.com/miLibris/flask-rest-jsonapi/blob/ecc8f2cd2b54cc0bfae7acd6cffcda0ba1140c43/flask_rest_jsonapi/data_layers/alchemy.py#L38-L69 |
243,875 | miLibris/flask-rest-jsonapi | flask_rest_jsonapi/data_layers/alchemy.py | SqlalchemyDataLayer.get_object | def get_object(self, view_kwargs, qs=None):
"""Retrieve an object through sqlalchemy
:params dict view_kwargs: kwargs from the resource view
:return DeclarativeMeta: an object from sqlalchemy
"""
self.before_get_object(view_kwargs)
id_field = getattr(self, 'id_field', i... | python | def get_object(self, view_kwargs, qs=None):
self.before_get_object(view_kwargs)
id_field = getattr(self, 'id_field', inspect(self.model).primary_key[0].key)
try:
filter_field = getattr(self.model, id_field)
except Exception:
raise Exception("{} has no attribute {... | [
"def",
"get_object",
"(",
"self",
",",
"view_kwargs",
",",
"qs",
"=",
"None",
")",
":",
"self",
".",
"before_get_object",
"(",
"view_kwargs",
")",
"id_field",
"=",
"getattr",
"(",
"self",
",",
"'id_field'",
",",
"inspect",
"(",
"self",
".",
"model",
")",... | Retrieve an object through sqlalchemy
:params dict view_kwargs: kwargs from the resource view
:return DeclarativeMeta: an object from sqlalchemy | [
"Retrieve",
"an",
"object",
"through",
"sqlalchemy"
] | ecc8f2cd2b54cc0bfae7acd6cffcda0ba1140c43 | https://github.com/miLibris/flask-rest-jsonapi/blob/ecc8f2cd2b54cc0bfae7acd6cffcda0ba1140c43/flask_rest_jsonapi/data_layers/alchemy.py#L71-L100 |
243,876 | miLibris/flask-rest-jsonapi | flask_rest_jsonapi/data_layers/alchemy.py | SqlalchemyDataLayer.get_collection | def get_collection(self, qs, view_kwargs):
"""Retrieve a collection of objects through sqlalchemy
:param QueryStringManager qs: a querystring manager to retrieve information from url
:param dict view_kwargs: kwargs from the resource view
:return tuple: the number of object and the list ... | python | def get_collection(self, qs, view_kwargs):
self.before_get_collection(qs, view_kwargs)
query = self.query(view_kwargs)
if qs.filters:
query = self.filter_query(query, qs.filters, self.model)
if qs.sorting:
query = self.sort_query(query, qs.sorting)
obj... | [
"def",
"get_collection",
"(",
"self",
",",
"qs",
",",
"view_kwargs",
")",
":",
"self",
".",
"before_get_collection",
"(",
"qs",
",",
"view_kwargs",
")",
"query",
"=",
"self",
".",
"query",
"(",
"view_kwargs",
")",
"if",
"qs",
".",
"filters",
":",
"query"... | Retrieve a collection of objects through sqlalchemy
:param QueryStringManager qs: a querystring manager to retrieve information from url
:param dict view_kwargs: kwargs from the resource view
:return tuple: the number of object and the list of objects | [
"Retrieve",
"a",
"collection",
"of",
"objects",
"through",
"sqlalchemy"
] | ecc8f2cd2b54cc0bfae7acd6cffcda0ba1140c43 | https://github.com/miLibris/flask-rest-jsonapi/blob/ecc8f2cd2b54cc0bfae7acd6cffcda0ba1140c43/flask_rest_jsonapi/data_layers/alchemy.py#L102-L130 |
243,877 | miLibris/flask-rest-jsonapi | flask_rest_jsonapi/data_layers/alchemy.py | SqlalchemyDataLayer.update_object | def update_object(self, obj, data, view_kwargs):
"""Update an object through sqlalchemy
:param DeclarativeMeta obj: an object from sqlalchemy
:param dict data: the data validated by marshmallow
:param dict view_kwargs: kwargs from the resource view
:return boolean: True if objec... | python | def update_object(self, obj, data, view_kwargs):
if obj is None:
url_field = getattr(self, 'url_field', 'id')
filter_value = view_kwargs[url_field]
raise ObjectNotFound('{}: {} not found'.format(self.model.__name__, filter_value),
source={'par... | [
"def",
"update_object",
"(",
"self",
",",
"obj",
",",
"data",
",",
"view_kwargs",
")",
":",
"if",
"obj",
"is",
"None",
":",
"url_field",
"=",
"getattr",
"(",
"self",
",",
"'url_field'",
",",
"'id'",
")",
"filter_value",
"=",
"view_kwargs",
"[",
"url_fiel... | Update an object through sqlalchemy
:param DeclarativeMeta obj: an object from sqlalchemy
:param dict data: the data validated by marshmallow
:param dict view_kwargs: kwargs from the resource view
:return boolean: True if object have changed else False | [
"Update",
"an",
"object",
"through",
"sqlalchemy"
] | ecc8f2cd2b54cc0bfae7acd6cffcda0ba1140c43 | https://github.com/miLibris/flask-rest-jsonapi/blob/ecc8f2cd2b54cc0bfae7acd6cffcda0ba1140c43/flask_rest_jsonapi/data_layers/alchemy.py#L132-L169 |
243,878 | miLibris/flask-rest-jsonapi | flask_rest_jsonapi/data_layers/alchemy.py | SqlalchemyDataLayer.delete_object | def delete_object(self, obj, view_kwargs):
"""Delete an object through sqlalchemy
:param DeclarativeMeta item: an item from sqlalchemy
:param dict view_kwargs: kwargs from the resource view
"""
if obj is None:
url_field = getattr(self, 'url_field', 'id')
... | python | def delete_object(self, obj, view_kwargs):
if obj is None:
url_field = getattr(self, 'url_field', 'id')
filter_value = view_kwargs[url_field]
raise ObjectNotFound('{}: {} not found'.format(self.model.__name__, filter_value),
source={'parameter... | [
"def",
"delete_object",
"(",
"self",
",",
"obj",
",",
"view_kwargs",
")",
":",
"if",
"obj",
"is",
"None",
":",
"url_field",
"=",
"getattr",
"(",
"self",
",",
"'url_field'",
",",
"'id'",
")",
"filter_value",
"=",
"view_kwargs",
"[",
"url_field",
"]",
"rai... | Delete an object through sqlalchemy
:param DeclarativeMeta item: an item from sqlalchemy
:param dict view_kwargs: kwargs from the resource view | [
"Delete",
"an",
"object",
"through",
"sqlalchemy"
] | ecc8f2cd2b54cc0bfae7acd6cffcda0ba1140c43 | https://github.com/miLibris/flask-rest-jsonapi/blob/ecc8f2cd2b54cc0bfae7acd6cffcda0ba1140c43/flask_rest_jsonapi/data_layers/alchemy.py#L171-L195 |
243,879 | miLibris/flask-rest-jsonapi | flask_rest_jsonapi/data_layers/alchemy.py | SqlalchemyDataLayer.create_relationship | def create_relationship(self, json_data, relationship_field, related_id_field, view_kwargs):
"""Create a relationship
:param dict json_data: the request params
:param str relationship_field: the model attribute used for relationship
:param str related_id_field: the identifier field of t... | python | def create_relationship(self, json_data, relationship_field, related_id_field, view_kwargs):
self.before_create_relationship(json_data, relationship_field, related_id_field, view_kwargs)
obj = self.get_object(view_kwargs)
if obj is None:
url_field = getattr(self, 'url_field', 'id')... | [
"def",
"create_relationship",
"(",
"self",
",",
"json_data",
",",
"relationship_field",
",",
"related_id_field",
",",
"view_kwargs",
")",
":",
"self",
".",
"before_create_relationship",
"(",
"json_data",
",",
"relationship_field",
",",
"related_id_field",
",",
"view_k... | Create a relationship
:param dict json_data: the request params
:param str relationship_field: the model attribute used for relationship
:param str related_id_field: the identifier field of the related model
:param dict view_kwargs: kwargs from the resource view
:return boolean:... | [
"Create",
"a",
"relationship"
] | ecc8f2cd2b54cc0bfae7acd6cffcda0ba1140c43 | https://github.com/miLibris/flask-rest-jsonapi/blob/ecc8f2cd2b54cc0bfae7acd6cffcda0ba1140c43/flask_rest_jsonapi/data_layers/alchemy.py#L197-L254 |
243,880 | miLibris/flask-rest-jsonapi | flask_rest_jsonapi/data_layers/alchemy.py | SqlalchemyDataLayer.get_relationship | def get_relationship(self, relationship_field, related_type_, related_id_field, view_kwargs):
"""Get a relationship
:param str relationship_field: the model attribute used for relationship
:param str related_type_: the related resource type
:param str related_id_field: the identifier fi... | python | def get_relationship(self, relationship_field, related_type_, related_id_field, view_kwargs):
self.before_get_relationship(relationship_field, related_type_, related_id_field, view_kwargs)
obj = self.get_object(view_kwargs)
if obj is None:
url_field = getattr(self, 'url_field', 'id... | [
"def",
"get_relationship",
"(",
"self",
",",
"relationship_field",
",",
"related_type_",
",",
"related_id_field",
",",
"view_kwargs",
")",
":",
"self",
".",
"before_get_relationship",
"(",
"relationship_field",
",",
"related_type_",
",",
"related_id_field",
",",
"view... | Get a relationship
:param str relationship_field: the model attribute used for relationship
:param str related_type_: the related resource type
:param str related_id_field: the identifier field of the related model
:param dict view_kwargs: kwargs from the resource view
:return t... | [
"Get",
"a",
"relationship"
] | ecc8f2cd2b54cc0bfae7acd6cffcda0ba1140c43 | https://github.com/miLibris/flask-rest-jsonapi/blob/ecc8f2cd2b54cc0bfae7acd6cffcda0ba1140c43/flask_rest_jsonapi/data_layers/alchemy.py#L256-L290 |
243,881 | miLibris/flask-rest-jsonapi | flask_rest_jsonapi/data_layers/alchemy.py | SqlalchemyDataLayer.delete_relationship | def delete_relationship(self, json_data, relationship_field, related_id_field, view_kwargs):
"""Delete a relationship
:param dict json_data: the request params
:param str relationship_field: the model attribute used for relationship
:param str related_id_field: the identifier field of t... | python | def delete_relationship(self, json_data, relationship_field, related_id_field, view_kwargs):
self.before_delete_relationship(json_data, relationship_field, related_id_field, view_kwargs)
obj = self.get_object(view_kwargs)
if obj is None:
url_field = getattr(self, 'url_field', 'id')... | [
"def",
"delete_relationship",
"(",
"self",
",",
"json_data",
",",
"relationship_field",
",",
"related_id_field",
",",
"view_kwargs",
")",
":",
"self",
".",
"before_delete_relationship",
"(",
"json_data",
",",
"relationship_field",
",",
"related_id_field",
",",
"view_k... | Delete a relationship
:param dict json_data: the request params
:param str relationship_field: the model attribute used for relationship
:param str related_id_field: the identifier field of the related model
:param dict view_kwargs: kwargs from the resource view | [
"Delete",
"a",
"relationship"
] | ecc8f2cd2b54cc0bfae7acd6cffcda0ba1140c43 | https://github.com/miLibris/flask-rest-jsonapi/blob/ecc8f2cd2b54cc0bfae7acd6cffcda0ba1140c43/flask_rest_jsonapi/data_layers/alchemy.py#L355-L403 |
243,882 | miLibris/flask-rest-jsonapi | flask_rest_jsonapi/data_layers/alchemy.py | SqlalchemyDataLayer.get_related_object | def get_related_object(self, related_model, related_id_field, obj):
"""Get a related object
:param Model related_model: an sqlalchemy model
:param str related_id_field: the identifier field of the related model
:param DeclarativeMeta obj: the sqlalchemy object to retrieve related object... | python | def get_related_object(self, related_model, related_id_field, obj):
try:
related_object = self.session.query(related_model)\
.filter(getattr(related_model, related_id_field) == obj['id'])\
.one()
except NoResul... | [
"def",
"get_related_object",
"(",
"self",
",",
"related_model",
",",
"related_id_field",
",",
"obj",
")",
":",
"try",
":",
"related_object",
"=",
"self",
".",
"session",
".",
"query",
"(",
"related_model",
")",
".",
"filter",
"(",
"getattr",
"(",
"related_mo... | Get a related object
:param Model related_model: an sqlalchemy model
:param str related_id_field: the identifier field of the related model
:param DeclarativeMeta obj: the sqlalchemy object to retrieve related objects from
:return DeclarativeMeta: a related object | [
"Get",
"a",
"related",
"object"
] | ecc8f2cd2b54cc0bfae7acd6cffcda0ba1140c43 | https://github.com/miLibris/flask-rest-jsonapi/blob/ecc8f2cd2b54cc0bfae7acd6cffcda0ba1140c43/flask_rest_jsonapi/data_layers/alchemy.py#L405-L422 |
243,883 | miLibris/flask-rest-jsonapi | flask_rest_jsonapi/data_layers/alchemy.py | SqlalchemyDataLayer.apply_relationships | def apply_relationships(self, data, obj):
"""Apply relationship provided by data to obj
:param dict data: data provided by the client
:param DeclarativeMeta obj: the sqlalchemy object to plug relationships to
:return boolean: True if relationship have changed else False
"""
... | python | def apply_relationships(self, data, obj):
relationships_to_apply = []
relationship_fields = get_relationships(self.resource.schema, model_field=True)
for key, value in data.items():
if key in relationship_fields:
related_model = getattr(obj.__class__, key).property.ma... | [
"def",
"apply_relationships",
"(",
"self",
",",
"data",
",",
"obj",
")",
":",
"relationships_to_apply",
"=",
"[",
"]",
"relationship_fields",
"=",
"get_relationships",
"(",
"self",
".",
"resource",
".",
"schema",
",",
"model_field",
"=",
"True",
")",
"for",
... | Apply relationship provided by data to obj
:param dict data: data provided by the client
:param DeclarativeMeta obj: the sqlalchemy object to plug relationships to
:return boolean: True if relationship have changed else False | [
"Apply",
"relationship",
"provided",
"by",
"data",
"to",
"obj"
] | ecc8f2cd2b54cc0bfae7acd6cffcda0ba1140c43 | https://github.com/miLibris/flask-rest-jsonapi/blob/ecc8f2cd2b54cc0bfae7acd6cffcda0ba1140c43/flask_rest_jsonapi/data_layers/alchemy.py#L425-L457 |
243,884 | miLibris/flask-rest-jsonapi | flask_rest_jsonapi/data_layers/alchemy.py | SqlalchemyDataLayer.filter_query | def filter_query(self, query, filter_info, model):
"""Filter query according to jsonapi 1.0
:param Query query: sqlalchemy query to sort
:param filter_info: filter information
:type filter_info: dict or None
:param DeclarativeMeta model: an sqlalchemy model
:return Query... | python | def filter_query(self, query, filter_info, model):
if filter_info:
filters = create_filters(model, filter_info, self.resource)
query = query.filter(*filters)
return query | [
"def",
"filter_query",
"(",
"self",
",",
"query",
",",
"filter_info",
",",
"model",
")",
":",
"if",
"filter_info",
":",
"filters",
"=",
"create_filters",
"(",
"model",
",",
"filter_info",
",",
"self",
".",
"resource",
")",
"query",
"=",
"query",
".",
"fi... | Filter query according to jsonapi 1.0
:param Query query: sqlalchemy query to sort
:param filter_info: filter information
:type filter_info: dict or None
:param DeclarativeMeta model: an sqlalchemy model
:return Query: the sorted query | [
"Filter",
"query",
"according",
"to",
"jsonapi",
"1",
".",
"0"
] | ecc8f2cd2b54cc0bfae7acd6cffcda0ba1140c43 | https://github.com/miLibris/flask-rest-jsonapi/blob/ecc8f2cd2b54cc0bfae7acd6cffcda0ba1140c43/flask_rest_jsonapi/data_layers/alchemy.py#L490-L503 |
243,885 | miLibris/flask-rest-jsonapi | flask_rest_jsonapi/data_layers/alchemy.py | SqlalchemyDataLayer.sort_query | def sort_query(self, query, sort_info):
"""Sort query according to jsonapi 1.0
:param Query query: sqlalchemy query to sort
:param list sort_info: sort information
:return Query: the sorted query
"""
for sort_opt in sort_info:
field = sort_opt['field']
... | python | def sort_query(self, query, sort_info):
for sort_opt in sort_info:
field = sort_opt['field']
if not hasattr(self.model, field):
raise InvalidSort("{} has no attribute {}".format(self.model.__name__, field))
query = query.order_by(getattr(getattr(self.model, fi... | [
"def",
"sort_query",
"(",
"self",
",",
"query",
",",
"sort_info",
")",
":",
"for",
"sort_opt",
"in",
"sort_info",
":",
"field",
"=",
"sort_opt",
"[",
"'field'",
"]",
"if",
"not",
"hasattr",
"(",
"self",
".",
"model",
",",
"field",
")",
":",
"raise",
... | Sort query according to jsonapi 1.0
:param Query query: sqlalchemy query to sort
:param list sort_info: sort information
:return Query: the sorted query | [
"Sort",
"query",
"according",
"to",
"jsonapi",
"1",
".",
"0"
] | ecc8f2cd2b54cc0bfae7acd6cffcda0ba1140c43 | https://github.com/miLibris/flask-rest-jsonapi/blob/ecc8f2cd2b54cc0bfae7acd6cffcda0ba1140c43/flask_rest_jsonapi/data_layers/alchemy.py#L505-L517 |
243,886 | miLibris/flask-rest-jsonapi | flask_rest_jsonapi/data_layers/alchemy.py | SqlalchemyDataLayer.paginate_query | def paginate_query(self, query, paginate_info):
"""Paginate query according to jsonapi 1.0
:param Query query: sqlalchemy queryset
:param dict paginate_info: pagination information
:return Query: the paginated query
"""
if int(paginate_info.get('size', 1)) == 0:
... | python | def paginate_query(self, query, paginate_info):
if int(paginate_info.get('size', 1)) == 0:
return query
page_size = int(paginate_info.get('size', 0)) or current_app.config['PAGE_SIZE']
query = query.limit(page_size)
if paginate_info.get('number'):
query = query.o... | [
"def",
"paginate_query",
"(",
"self",
",",
"query",
",",
"paginate_info",
")",
":",
"if",
"int",
"(",
"paginate_info",
".",
"get",
"(",
"'size'",
",",
"1",
")",
")",
"==",
"0",
":",
"return",
"query",
"page_size",
"=",
"int",
"(",
"paginate_info",
".",... | Paginate query according to jsonapi 1.0
:param Query query: sqlalchemy queryset
:param dict paginate_info: pagination information
:return Query: the paginated query | [
"Paginate",
"query",
"according",
"to",
"jsonapi",
"1",
".",
"0"
] | ecc8f2cd2b54cc0bfae7acd6cffcda0ba1140c43 | https://github.com/miLibris/flask-rest-jsonapi/blob/ecc8f2cd2b54cc0bfae7acd6cffcda0ba1140c43/flask_rest_jsonapi/data_layers/alchemy.py#L519-L534 |
243,887 | miLibris/flask-rest-jsonapi | flask_rest_jsonapi/data_layers/alchemy.py | SqlalchemyDataLayer.eagerload_includes | def eagerload_includes(self, query, qs):
"""Use eagerload feature of sqlalchemy to optimize data retrieval for include querystring parameter
:param Query query: sqlalchemy queryset
:param QueryStringManager qs: a querystring manager to retrieve information from url
:return Query: the qu... | python | def eagerload_includes(self, query, qs):
for include in qs.include:
joinload_object = None
if '.' in include:
current_schema = self.resource.schema
for obj in include.split('.'):
try:
field = get_model_field(cur... | [
"def",
"eagerload_includes",
"(",
"self",
",",
"query",
",",
"qs",
")",
":",
"for",
"include",
"in",
"qs",
".",
"include",
":",
"joinload_object",
"=",
"None",
"if",
"'.'",
"in",
"include",
":",
"current_schema",
"=",
"self",
".",
"resource",
".",
"schem... | Use eagerload feature of sqlalchemy to optimize data retrieval for include querystring parameter
:param Query query: sqlalchemy queryset
:param QueryStringManager qs: a querystring manager to retrieve information from url
:return Query: the query with includes eagerloaded | [
"Use",
"eagerload",
"feature",
"of",
"sqlalchemy",
"to",
"optimize",
"data",
"retrieval",
"for",
"include",
"querystring",
"parameter"
] | ecc8f2cd2b54cc0bfae7acd6cffcda0ba1140c43 | https://github.com/miLibris/flask-rest-jsonapi/blob/ecc8f2cd2b54cc0bfae7acd6cffcda0ba1140c43/flask_rest_jsonapi/data_layers/alchemy.py#L536-L577 |
243,888 | miLibris/flask-rest-jsonapi | flask_rest_jsonapi/data_layers/alchemy.py | SqlalchemyDataLayer.retrieve_object_query | def retrieve_object_query(self, view_kwargs, filter_field, filter_value):
"""Build query to retrieve object
:param dict view_kwargs: kwargs from the resource view
:params sqlalchemy_field filter_field: the field to filter on
:params filter_value: the value to filter with
:return... | python | def retrieve_object_query(self, view_kwargs, filter_field, filter_value):
return self.session.query(self.model).filter(filter_field == filter_value) | [
"def",
"retrieve_object_query",
"(",
"self",
",",
"view_kwargs",
",",
"filter_field",
",",
"filter_value",
")",
":",
"return",
"self",
".",
"session",
".",
"query",
"(",
"self",
".",
"model",
")",
".",
"filter",
"(",
"filter_field",
"==",
"filter_value",
")"... | Build query to retrieve object
:param dict view_kwargs: kwargs from the resource view
:params sqlalchemy_field filter_field: the field to filter on
:params filter_value: the value to filter with
:return sqlalchemy query: a query from sqlalchemy | [
"Build",
"query",
"to",
"retrieve",
"object"
] | ecc8f2cd2b54cc0bfae7acd6cffcda0ba1140c43 | https://github.com/miLibris/flask-rest-jsonapi/blob/ecc8f2cd2b54cc0bfae7acd6cffcda0ba1140c43/flask_rest_jsonapi/data_layers/alchemy.py#L579-L587 |
243,889 | miLibris/flask-rest-jsonapi | flask_rest_jsonapi/pagination.py | add_pagination_links | def add_pagination_links(data, object_count, querystring, base_url):
"""Add pagination links to result
:param dict data: the result of the view
:param int object_count: number of objects in result
:param QueryStringManager querystring: the managed querystring fields and values
:param str base_url: ... | python | def add_pagination_links(data, object_count, querystring, base_url):
links = {}
all_qs_args = copy(querystring.querystring)
links['self'] = base_url
# compute self link
if all_qs_args:
links['self'] += '?' + urlencode(all_qs_args)
if querystring.pagination.get('size') != '0' and objec... | [
"def",
"add_pagination_links",
"(",
"data",
",",
"object_count",
",",
"querystring",
",",
"base_url",
")",
":",
"links",
"=",
"{",
"}",
"all_qs_args",
"=",
"copy",
"(",
"querystring",
".",
"querystring",
")",
"links",
"[",
"'self'",
"]",
"=",
"base_url",
"... | Add pagination links to result
:param dict data: the result of the view
:param int object_count: number of objects in result
:param QueryStringManager querystring: the managed querystring fields and values
:param str base_url: the base url for pagination | [
"Add",
"pagination",
"links",
"to",
"result"
] | ecc8f2cd2b54cc0bfae7acd6cffcda0ba1140c43 | https://github.com/miLibris/flask-rest-jsonapi/blob/ecc8f2cd2b54cc0bfae7acd6cffcda0ba1140c43/flask_rest_jsonapi/pagination.py#L13-L56 |
243,890 | ethereum/py-evm | eth/tools/fixtures/generation.py | idfn | def idfn(fixture_params: Iterable[Any]) -> str:
"""
Function for pytest to produce uniform names for fixtures.
"""
return ":".join((str(item) for item in fixture_params)) | python | def idfn(fixture_params: Iterable[Any]) -> str:
return ":".join((str(item) for item in fixture_params)) | [
"def",
"idfn",
"(",
"fixture_params",
":",
"Iterable",
"[",
"Any",
"]",
")",
"->",
"str",
":",
"return",
"\":\"",
".",
"join",
"(",
"(",
"str",
"(",
"item",
")",
"for",
"item",
"in",
"fixture_params",
")",
")"
] | Function for pytest to produce uniform names for fixtures. | [
"Function",
"for",
"pytest",
"to",
"produce",
"uniform",
"names",
"for",
"fixtures",
"."
] | 58346848f076116381d3274bbcea96b9e2cfcbdf | https://github.com/ethereum/py-evm/blob/58346848f076116381d3274bbcea96b9e2cfcbdf/eth/tools/fixtures/generation.py#L24-L28 |
243,891 | ethereum/py-evm | eth/tools/fixtures/generation.py | get_fixtures_file_hash | def get_fixtures_file_hash(all_fixture_paths: Iterable[str]) -> str:
"""
Returns the MD5 hash of the fixture files. Used for cache busting.
"""
hasher = hashlib.md5()
for fixture_path in sorted(all_fixture_paths):
with open(fixture_path, 'rb') as fixture_file:
hasher.update(fixt... | python | def get_fixtures_file_hash(all_fixture_paths: Iterable[str]) -> str:
hasher = hashlib.md5()
for fixture_path in sorted(all_fixture_paths):
with open(fixture_path, 'rb') as fixture_file:
hasher.update(fixture_file.read())
return hasher.hexdigest() | [
"def",
"get_fixtures_file_hash",
"(",
"all_fixture_paths",
":",
"Iterable",
"[",
"str",
"]",
")",
"->",
"str",
":",
"hasher",
"=",
"hashlib",
".",
"md5",
"(",
")",
"for",
"fixture_path",
"in",
"sorted",
"(",
"all_fixture_paths",
")",
":",
"with",
"open",
"... | Returns the MD5 hash of the fixture files. Used for cache busting. | [
"Returns",
"the",
"MD5",
"hash",
"of",
"the",
"fixture",
"files",
".",
"Used",
"for",
"cache",
"busting",
"."
] | 58346848f076116381d3274bbcea96b9e2cfcbdf | https://github.com/ethereum/py-evm/blob/58346848f076116381d3274bbcea96b9e2cfcbdf/eth/tools/fixtures/generation.py#L31-L39 |
243,892 | ethereum/py-evm | eth/rlp/transactions.py | BaseTransaction.create_unsigned_transaction | def create_unsigned_transaction(cls,
*,
nonce: int,
gas_price: int,
gas: int,
to: Address,
value: int,
... | python | def create_unsigned_transaction(cls,
*,
nonce: int,
gas_price: int,
gas: int,
to: Address,
value: int,
... | [
"def",
"create_unsigned_transaction",
"(",
"cls",
",",
"*",
",",
"nonce",
":",
"int",
",",
"gas_price",
":",
"int",
",",
"gas",
":",
"int",
",",
"to",
":",
"Address",
",",
"value",
":",
"int",
",",
"data",
":",
"bytes",
")",
"->",
"'BaseUnsignedTransac... | Create an unsigned transaction. | [
"Create",
"an",
"unsigned",
"transaction",
"."
] | 58346848f076116381d3274bbcea96b9e2cfcbdf | https://github.com/ethereum/py-evm/blob/58346848f076116381d3274bbcea96b9e2cfcbdf/eth/rlp/transactions.py#L155-L166 |
243,893 | ethereum/py-evm | eth/chains/header.py | HeaderChain.import_header | def import_header(self,
header: BlockHeader
) -> Tuple[Tuple[BlockHeader, ...], Tuple[BlockHeader, ...]]:
"""
Direct passthrough to `headerdb`
Also updates the local `header` property to be the latest canonical head.
Returns an iterable of he... | python | def import_header(self,
header: BlockHeader
) -> Tuple[Tuple[BlockHeader, ...], Tuple[BlockHeader, ...]]:
new_canonical_headers = self.headerdb.persist_header(header)
self.header = self.get_canonical_head()
return new_canonical_headers | [
"def",
"import_header",
"(",
"self",
",",
"header",
":",
"BlockHeader",
")",
"->",
"Tuple",
"[",
"Tuple",
"[",
"BlockHeader",
",",
"...",
"]",
",",
"Tuple",
"[",
"BlockHeader",
",",
"...",
"]",
"]",
":",
"new_canonical_headers",
"=",
"self",
".",
"header... | Direct passthrough to `headerdb`
Also updates the local `header` property to be the latest canonical head.
Returns an iterable of headers representing the headers that are newly
part of the canonical chain.
- If the imported header is not part of the canonical chain then an
... | [
"Direct",
"passthrough",
"to",
"headerdb"
] | 58346848f076116381d3274bbcea96b9e2cfcbdf | https://github.com/ethereum/py-evm/blob/58346848f076116381d3274bbcea96b9e2cfcbdf/eth/chains/header.py#L165-L186 |
243,894 | ethereum/py-evm | eth/rlp/headers.py | BlockHeader.from_parent | def from_parent(cls,
parent: 'BlockHeader',
gas_limit: int,
difficulty: int,
timestamp: int,
coinbase: Address=ZERO_ADDRESS,
nonce: bytes=None,
extra_data: bytes=None,
... | python | def from_parent(cls,
parent: 'BlockHeader',
gas_limit: int,
difficulty: int,
timestamp: int,
coinbase: Address=ZERO_ADDRESS,
nonce: bytes=None,
extra_data: bytes=None,
... | [
"def",
"from_parent",
"(",
"cls",
",",
"parent",
":",
"'BlockHeader'",
",",
"gas_limit",
":",
"int",
",",
"difficulty",
":",
"int",
",",
"timestamp",
":",
"int",
",",
"coinbase",
":",
"Address",
"=",
"ZERO_ADDRESS",
",",
"nonce",
":",
"bytes",
"=",
"None... | Initialize a new block header with the `parent` header as the block's
parent hash. | [
"Initialize",
"a",
"new",
"block",
"header",
"with",
"the",
"parent",
"header",
"as",
"the",
"block",
"s",
"parent",
"hash",
"."
] | 58346848f076116381d3274bbcea96b9e2cfcbdf | https://github.com/ethereum/py-evm/blob/58346848f076116381d3274bbcea96b9e2cfcbdf/eth/rlp/headers.py#L170-L203 |
243,895 | ethereum/py-evm | eth/db/chain.py | ChainDB.get_block_uncles | def get_block_uncles(self, uncles_hash: Hash32) -> List[BlockHeader]:
"""
Returns an iterable of uncle headers specified by the given uncles_hash
"""
validate_word(uncles_hash, title="Uncles Hash")
if uncles_hash == EMPTY_UNCLE_HASH:
return []
try:
... | python | def get_block_uncles(self, uncles_hash: Hash32) -> List[BlockHeader]:
validate_word(uncles_hash, title="Uncles Hash")
if uncles_hash == EMPTY_UNCLE_HASH:
return []
try:
encoded_uncles = self.db[uncles_hash]
except KeyError:
raise HeaderNotFound(
... | [
"def",
"get_block_uncles",
"(",
"self",
",",
"uncles_hash",
":",
"Hash32",
")",
"->",
"List",
"[",
"BlockHeader",
"]",
":",
"validate_word",
"(",
"uncles_hash",
",",
"title",
"=",
"\"Uncles Hash\"",
")",
"if",
"uncles_hash",
"==",
"EMPTY_UNCLE_HASH",
":",
"ret... | Returns an iterable of uncle headers specified by the given uncles_hash | [
"Returns",
"an",
"iterable",
"of",
"uncle",
"headers",
"specified",
"by",
"the",
"given",
"uncles_hash"
] | 58346848f076116381d3274bbcea96b9e2cfcbdf | https://github.com/ethereum/py-evm/blob/58346848f076116381d3274bbcea96b9e2cfcbdf/eth/db/chain.py#L175-L189 |
243,896 | ethereum/py-evm | eth/db/chain.py | ChainDB.persist_block | def persist_block(self,
block: 'BaseBlock'
) -> Tuple[Tuple[Hash32, ...], Tuple[Hash32, ...]]:
"""
Persist the given block's header and uncles.
Assumes all block transactions have been persisted already.
"""
with self.db.atomic_batch()... | python | def persist_block(self,
block: 'BaseBlock'
) -> Tuple[Tuple[Hash32, ...], Tuple[Hash32, ...]]:
with self.db.atomic_batch() as db:
return self._persist_block(db, block) | [
"def",
"persist_block",
"(",
"self",
",",
"block",
":",
"'BaseBlock'",
")",
"->",
"Tuple",
"[",
"Tuple",
"[",
"Hash32",
",",
"...",
"]",
",",
"Tuple",
"[",
"Hash32",
",",
"...",
"]",
"]",
":",
"with",
"self",
".",
"db",
".",
"atomic_batch",
"(",
")... | Persist the given block's header and uncles.
Assumes all block transactions have been persisted already. | [
"Persist",
"the",
"given",
"block",
"s",
"header",
"and",
"uncles",
"."
] | 58346848f076116381d3274bbcea96b9e2cfcbdf | https://github.com/ethereum/py-evm/blob/58346848f076116381d3274bbcea96b9e2cfcbdf/eth/db/chain.py#L228-L237 |
243,897 | ethereum/py-evm | eth/db/chain.py | ChainDB.persist_uncles | def persist_uncles(self, uncles: Tuple[BlockHeader]) -> Hash32:
"""
Persists the list of uncles to the database.
Returns the uncles hash.
"""
return self._persist_uncles(self.db, uncles) | python | def persist_uncles(self, uncles: Tuple[BlockHeader]) -> Hash32:
return self._persist_uncles(self.db, uncles) | [
"def",
"persist_uncles",
"(",
"self",
",",
"uncles",
":",
"Tuple",
"[",
"BlockHeader",
"]",
")",
"->",
"Hash32",
":",
"return",
"self",
".",
"_persist_uncles",
"(",
"self",
".",
"db",
",",
"uncles",
")"
] | Persists the list of uncles to the database.
Returns the uncles hash. | [
"Persists",
"the",
"list",
"of",
"uncles",
"to",
"the",
"database",
"."
] | 58346848f076116381d3274bbcea96b9e2cfcbdf | https://github.com/ethereum/py-evm/blob/58346848f076116381d3274bbcea96b9e2cfcbdf/eth/db/chain.py#L273-L279 |
243,898 | ethereum/py-evm | eth/db/chain.py | ChainDB.add_receipt | def add_receipt(self, block_header: BlockHeader, index_key: int, receipt: Receipt) -> Hash32:
"""
Adds the given receipt to the provided block header.
Returns the updated `receipts_root` for updated block header.
"""
receipt_db = HexaryTrie(db=self.db, root_hash=block_header.rec... | python | def add_receipt(self, block_header: BlockHeader, index_key: int, receipt: Receipt) -> Hash32:
receipt_db = HexaryTrie(db=self.db, root_hash=block_header.receipt_root)
receipt_db[index_key] = rlp.encode(receipt)
return receipt_db.root_hash | [
"def",
"add_receipt",
"(",
"self",
",",
"block_header",
":",
"BlockHeader",
",",
"index_key",
":",
"int",
",",
"receipt",
":",
"Receipt",
")",
"->",
"Hash32",
":",
"receipt_db",
"=",
"HexaryTrie",
"(",
"db",
"=",
"self",
".",
"db",
",",
"root_hash",
"=",... | Adds the given receipt to the provided block header.
Returns the updated `receipts_root` for updated block header. | [
"Adds",
"the",
"given",
"receipt",
"to",
"the",
"provided",
"block",
"header",
"."
] | 58346848f076116381d3274bbcea96b9e2cfcbdf | https://github.com/ethereum/py-evm/blob/58346848f076116381d3274bbcea96b9e2cfcbdf/eth/db/chain.py#L292-L300 |
243,899 | ethereum/py-evm | eth/db/chain.py | ChainDB.add_transaction | def add_transaction(self,
block_header: BlockHeader,
index_key: int,
transaction: 'BaseTransaction') -> Hash32:
"""
Adds the given transaction to the provided block header.
Returns the updated `transactions_root` for update... | python | def add_transaction(self,
block_header: BlockHeader,
index_key: int,
transaction: 'BaseTransaction') -> Hash32:
transaction_db = HexaryTrie(self.db, root_hash=block_header.transaction_root)
transaction_db[index_key] = rlp.encode(tra... | [
"def",
"add_transaction",
"(",
"self",
",",
"block_header",
":",
"BlockHeader",
",",
"index_key",
":",
"int",
",",
"transaction",
":",
"'BaseTransaction'",
")",
"->",
"Hash32",
":",
"transaction_db",
"=",
"HexaryTrie",
"(",
"self",
".",
"db",
",",
"root_hash",... | Adds the given transaction to the provided block header.
Returns the updated `transactions_root` for updated block header. | [
"Adds",
"the",
"given",
"transaction",
"to",
"the",
"provided",
"block",
"header",
"."
] | 58346848f076116381d3274bbcea96b9e2cfcbdf | https://github.com/ethereum/py-evm/blob/58346848f076116381d3274bbcea96b9e2cfcbdf/eth/db/chain.py#L302-L313 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.