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
8,200
astropy/astropy-healpix
astropy_healpix/core.py
nside_to_pixel_area
def nside_to_pixel_area(nside): """ Find the area of HEALPix pixels given the pixel dimensions of one of the 12 'top-level' HEALPix tiles. Parameters ---------- nside : int The number of pixels on the side of one of the 12 'top-level' HEALPix tiles. Returns ------- pixel_area : :class:`~astropy.units.Quantity` The area of the HEALPix pixels """ nside = np.asanyarray(nside, dtype=np.int64) _validate_nside(nside) npix = 12 * nside * nside pixel_area = 4 * math.pi / npix * u.sr return pixel_area
python
def nside_to_pixel_area(nside): nside = np.asanyarray(nside, dtype=np.int64) _validate_nside(nside) npix = 12 * nside * nside pixel_area = 4 * math.pi / npix * u.sr return pixel_area
[ "def", "nside_to_pixel_area", "(", "nside", ")", ":", "nside", "=", "np", ".", "asanyarray", "(", "nside", ",", "dtype", "=", "np", ".", "int64", ")", "_validate_nside", "(", "nside", ")", "npix", "=", "12", "*", "nside", "*", "nside", "pixel_area", "=...
Find the area of HEALPix pixels given the pixel dimensions of one of the 12 'top-level' HEALPix tiles. Parameters ---------- nside : int The number of pixels on the side of one of the 12 'top-level' HEALPix tiles. Returns ------- pixel_area : :class:`~astropy.units.Quantity` The area of the HEALPix pixels
[ "Find", "the", "area", "of", "HEALPix", "pixels", "given", "the", "pixel", "dimensions", "of", "one", "of", "the", "12", "top", "-", "level", "HEALPix", "tiles", "." ]
c7fbe36305aadda9946dd37969d5dcb9ff6b1440
https://github.com/astropy/astropy-healpix/blob/c7fbe36305aadda9946dd37969d5dcb9ff6b1440/astropy_healpix/core.py#L190-L209
8,201
astropy/astropy-healpix
astropy_healpix/core.py
nside_to_pixel_resolution
def nside_to_pixel_resolution(nside): """ Find the resolution of HEALPix pixels given the pixel dimensions of one of the 12 'top-level' HEALPix tiles. Parameters ---------- nside : int The number of pixels on the side of one of the 12 'top-level' HEALPix tiles. Returns ------- resolution : :class:`~astropy.units.Quantity` The resolution of the HEALPix pixels See also -------- pixel_resolution_to_nside """ nside = np.asanyarray(nside, dtype=np.int64) _validate_nside(nside) return (nside_to_pixel_area(nside) ** 0.5).to(u.arcmin)
python
def nside_to_pixel_resolution(nside): nside = np.asanyarray(nside, dtype=np.int64) _validate_nside(nside) return (nside_to_pixel_area(nside) ** 0.5).to(u.arcmin)
[ "def", "nside_to_pixel_resolution", "(", "nside", ")", ":", "nside", "=", "np", ".", "asanyarray", "(", "nside", ",", "dtype", "=", "np", ".", "int64", ")", "_validate_nside", "(", "nside", ")", "return", "(", "nside_to_pixel_area", "(", "nside", ")", "**"...
Find the resolution of HEALPix pixels given the pixel dimensions of one of the 12 'top-level' HEALPix tiles. Parameters ---------- nside : int The number of pixels on the side of one of the 12 'top-level' HEALPix tiles. Returns ------- resolution : :class:`~astropy.units.Quantity` The resolution of the HEALPix pixels See also -------- pixel_resolution_to_nside
[ "Find", "the", "resolution", "of", "HEALPix", "pixels", "given", "the", "pixel", "dimensions", "of", "one", "of", "the", "12", "top", "-", "level", "HEALPix", "tiles", "." ]
c7fbe36305aadda9946dd37969d5dcb9ff6b1440
https://github.com/astropy/astropy-healpix/blob/c7fbe36305aadda9946dd37969d5dcb9ff6b1440/astropy_healpix/core.py#L212-L233
8,202
astropy/astropy-healpix
astropy_healpix/core.py
pixel_resolution_to_nside
def pixel_resolution_to_nside(resolution, round='nearest'): """Find closest HEALPix nside for a given angular resolution. This function is the inverse of `nside_to_pixel_resolution`, for the default rounding scheme of ``round='nearest'``. If you choose ``round='up'``, you'll get HEALPix pixels that have at least the requested resolution (usually a bit better due to rounding). Pixel resolution is defined as square root of pixel area. Parameters ---------- resolution : `~astropy.units.Quantity` Angular resolution round : {'up', 'nearest', 'down'} Which way to round Returns ------- nside : int The number of pixels on the side of one of the 12 'top-level' HEALPix tiles. Always a power of 2. Examples -------- >>> from astropy import units as u >>> from astropy_healpix import pixel_resolution_to_nside >>> pixel_resolution_to_nside(13 * u.arcmin) 256 >>> pixel_resolution_to_nside(13 * u.arcmin, round='up') 512 """ resolution = resolution.to(u.rad).value pixel_area = resolution * resolution npix = 4 * math.pi / pixel_area nside = np.sqrt(npix / 12) # Now we have to round to the closest ``nside`` # Since ``nside`` must be a power of two, # we first compute the corresponding ``level = log2(nside)` # round the level and then go back to nside level = np.log2(nside) if round == 'up': level = np.ceil(level) elif round == 'nearest': level = np.round(level) elif round == 'down': level = np.floor(level) else: raise ValueError('Invalid value for round: {!r}'.format(round)) # For very low requested resolution (i.e. large angle values), we # return ``level=0``, i.e. ``nside=1``, i.e. the lowest resolution # that exists with HEALPix level = np.clip(level.astype(int), 0, None) return level_to_nside(level)
python
def pixel_resolution_to_nside(resolution, round='nearest'): resolution = resolution.to(u.rad).value pixel_area = resolution * resolution npix = 4 * math.pi / pixel_area nside = np.sqrt(npix / 12) # Now we have to round to the closest ``nside`` # Since ``nside`` must be a power of two, # we first compute the corresponding ``level = log2(nside)` # round the level and then go back to nside level = np.log2(nside) if round == 'up': level = np.ceil(level) elif round == 'nearest': level = np.round(level) elif round == 'down': level = np.floor(level) else: raise ValueError('Invalid value for round: {!r}'.format(round)) # For very low requested resolution (i.e. large angle values), we # return ``level=0``, i.e. ``nside=1``, i.e. the lowest resolution # that exists with HEALPix level = np.clip(level.astype(int), 0, None) return level_to_nside(level)
[ "def", "pixel_resolution_to_nside", "(", "resolution", ",", "round", "=", "'nearest'", ")", ":", "resolution", "=", "resolution", ".", "to", "(", "u", ".", "rad", ")", ".", "value", "pixel_area", "=", "resolution", "*", "resolution", "npix", "=", "4", "*",...
Find closest HEALPix nside for a given angular resolution. This function is the inverse of `nside_to_pixel_resolution`, for the default rounding scheme of ``round='nearest'``. If you choose ``round='up'``, you'll get HEALPix pixels that have at least the requested resolution (usually a bit better due to rounding). Pixel resolution is defined as square root of pixel area. Parameters ---------- resolution : `~astropy.units.Quantity` Angular resolution round : {'up', 'nearest', 'down'} Which way to round Returns ------- nside : int The number of pixels on the side of one of the 12 'top-level' HEALPix tiles. Always a power of 2. Examples -------- >>> from astropy import units as u >>> from astropy_healpix import pixel_resolution_to_nside >>> pixel_resolution_to_nside(13 * u.arcmin) 256 >>> pixel_resolution_to_nside(13 * u.arcmin, round='up') 512
[ "Find", "closest", "HEALPix", "nside", "for", "a", "given", "angular", "resolution", "." ]
c7fbe36305aadda9946dd37969d5dcb9ff6b1440
https://github.com/astropy/astropy-healpix/blob/c7fbe36305aadda9946dd37969d5dcb9ff6b1440/astropy_healpix/core.py#L236-L295
8,203
astropy/astropy-healpix
astropy_healpix/core.py
nside_to_npix
def nside_to_npix(nside): """ Find the number of pixels corresponding to a HEALPix resolution. Parameters ---------- nside : int The number of pixels on the side of one of the 12 'top-level' HEALPix tiles. Returns ------- npix : int The number of pixels in the HEALPix map. """ nside = np.asanyarray(nside, dtype=np.int64) _validate_nside(nside) return 12 * nside ** 2
python
def nside_to_npix(nside): nside = np.asanyarray(nside, dtype=np.int64) _validate_nside(nside) return 12 * nside ** 2
[ "def", "nside_to_npix", "(", "nside", ")", ":", "nside", "=", "np", ".", "asanyarray", "(", "nside", ",", "dtype", "=", "np", ".", "int64", ")", "_validate_nside", "(", "nside", ")", "return", "12", "*", "nside", "**", "2" ]
Find the number of pixels corresponding to a HEALPix resolution. Parameters ---------- nside : int The number of pixels on the side of one of the 12 'top-level' HEALPix tiles. Returns ------- npix : int The number of pixels in the HEALPix map.
[ "Find", "the", "number", "of", "pixels", "corresponding", "to", "a", "HEALPix", "resolution", "." ]
c7fbe36305aadda9946dd37969d5dcb9ff6b1440
https://github.com/astropy/astropy-healpix/blob/c7fbe36305aadda9946dd37969d5dcb9ff6b1440/astropy_healpix/core.py#L298-L314
8,204
astropy/astropy-healpix
astropy_healpix/core.py
npix_to_nside
def npix_to_nside(npix): """ Find the number of pixels on the side of one of the 12 'top-level' HEALPix tiles given a total number of pixels. Parameters ---------- npix : int The number of pixels in the HEALPix map. Returns ------- nside : int The number of pixels on the side of one of the 12 'top-level' HEALPix tiles. """ npix = np.asanyarray(npix, dtype=np.int64) if not np.all(npix % 12 == 0): raise ValueError('Number of pixels must be divisible by 12') square_root = np.sqrt(npix / 12) if not np.all(square_root ** 2 == npix / 12): raise ValueError('Number of pixels is not of the form 12 * nside ** 2') return np.round(square_root).astype(int)
python
def npix_to_nside(npix): npix = np.asanyarray(npix, dtype=np.int64) if not np.all(npix % 12 == 0): raise ValueError('Number of pixels must be divisible by 12') square_root = np.sqrt(npix / 12) if not np.all(square_root ** 2 == npix / 12): raise ValueError('Number of pixels is not of the form 12 * nside ** 2') return np.round(square_root).astype(int)
[ "def", "npix_to_nside", "(", "npix", ")", ":", "npix", "=", "np", ".", "asanyarray", "(", "npix", ",", "dtype", "=", "np", ".", "int64", ")", "if", "not", "np", ".", "all", "(", "npix", "%", "12", "==", "0", ")", ":", "raise", "ValueError", "(", ...
Find the number of pixels on the side of one of the 12 'top-level' HEALPix tiles given a total number of pixels. Parameters ---------- npix : int The number of pixels in the HEALPix map. Returns ------- nside : int The number of pixels on the side of one of the 12 'top-level' HEALPix tiles.
[ "Find", "the", "number", "of", "pixels", "on", "the", "side", "of", "one", "of", "the", "12", "top", "-", "level", "HEALPix", "tiles", "given", "a", "total", "number", "of", "pixels", "." ]
c7fbe36305aadda9946dd37969d5dcb9ff6b1440
https://github.com/astropy/astropy-healpix/blob/c7fbe36305aadda9946dd37969d5dcb9ff6b1440/astropy_healpix/core.py#L317-L342
8,205
astropy/astropy-healpix
astropy_healpix/core.py
nested_to_ring
def nested_to_ring(nested_index, nside): """ Convert a HEALPix 'nested' index to a HEALPix 'ring' index Parameters ---------- nested_index : int or `~numpy.ndarray` Healpix index using the 'nested' ordering nside : int or `~numpy.ndarray` Number of pixels along the side of each of the 12 top-level HEALPix tiles Returns ------- ring_index : int or `~numpy.ndarray` Healpix index using the 'ring' ordering """ nside = np.asarray(nside, dtype=np.intc) return _core.nested_to_ring(nested_index, nside)
python
def nested_to_ring(nested_index, nside): nside = np.asarray(nside, dtype=np.intc) return _core.nested_to_ring(nested_index, nside)
[ "def", "nested_to_ring", "(", "nested_index", ",", "nside", ")", ":", "nside", "=", "np", ".", "asarray", "(", "nside", ",", "dtype", "=", "np", ".", "intc", ")", "return", "_core", ".", "nested_to_ring", "(", "nested_index", ",", "nside", ")" ]
Convert a HEALPix 'nested' index to a HEALPix 'ring' index Parameters ---------- nested_index : int or `~numpy.ndarray` Healpix index using the 'nested' ordering nside : int or `~numpy.ndarray` Number of pixels along the side of each of the 12 top-level HEALPix tiles Returns ------- ring_index : int or `~numpy.ndarray` Healpix index using the 'ring' ordering
[ "Convert", "a", "HEALPix", "nested", "index", "to", "a", "HEALPix", "ring", "index" ]
c7fbe36305aadda9946dd37969d5dcb9ff6b1440
https://github.com/astropy/astropy-healpix/blob/c7fbe36305aadda9946dd37969d5dcb9ff6b1440/astropy_healpix/core.py#L443-L462
8,206
astropy/astropy-healpix
astropy_healpix/core.py
ring_to_nested
def ring_to_nested(ring_index, nside): """ Convert a HEALPix 'ring' index to a HEALPix 'nested' index Parameters ---------- ring_index : int or `~numpy.ndarray` Healpix index using the 'ring' ordering nside : int or `~numpy.ndarray` Number of pixels along the side of each of the 12 top-level HEALPix tiles Returns ------- nested_index : int or `~numpy.ndarray` Healpix index using the 'nested' ordering """ nside = np.asarray(nside, dtype=np.intc) return _core.ring_to_nested(ring_index, nside)
python
def ring_to_nested(ring_index, nside): nside = np.asarray(nside, dtype=np.intc) return _core.ring_to_nested(ring_index, nside)
[ "def", "ring_to_nested", "(", "ring_index", ",", "nside", ")", ":", "nside", "=", "np", ".", "asarray", "(", "nside", ",", "dtype", "=", "np", ".", "intc", ")", "return", "_core", ".", "ring_to_nested", "(", "ring_index", ",", "nside", ")" ]
Convert a HEALPix 'ring' index to a HEALPix 'nested' index Parameters ---------- ring_index : int or `~numpy.ndarray` Healpix index using the 'ring' ordering nside : int or `~numpy.ndarray` Number of pixels along the side of each of the 12 top-level HEALPix tiles Returns ------- nested_index : int or `~numpy.ndarray` Healpix index using the 'nested' ordering
[ "Convert", "a", "HEALPix", "ring", "index", "to", "a", "HEALPix", "nested", "index" ]
c7fbe36305aadda9946dd37969d5dcb9ff6b1440
https://github.com/astropy/astropy-healpix/blob/c7fbe36305aadda9946dd37969d5dcb9ff6b1440/astropy_healpix/core.py#L465-L484
8,207
astropy/astropy-healpix
astropy_healpix/healpy.py
nside2resol
def nside2resol(nside, arcmin=False): """Drop-in replacement for healpy `~healpy.pixelfunc.nside2resol`.""" resolution = nside_to_pixel_resolution(nside) if arcmin: return resolution.to(u.arcmin).value else: return resolution.to(u.rad).value
python
def nside2resol(nside, arcmin=False): resolution = nside_to_pixel_resolution(nside) if arcmin: return resolution.to(u.arcmin).value else: return resolution.to(u.rad).value
[ "def", "nside2resol", "(", "nside", ",", "arcmin", "=", "False", ")", ":", "resolution", "=", "nside_to_pixel_resolution", "(", "nside", ")", "if", "arcmin", ":", "return", "resolution", ".", "to", "(", "u", ".", "arcmin", ")", ".", "value", "else", ":",...
Drop-in replacement for healpy `~healpy.pixelfunc.nside2resol`.
[ "Drop", "-", "in", "replacement", "for", "healpy", "~healpy", ".", "pixelfunc", ".", "nside2resol", "." ]
c7fbe36305aadda9946dd37969d5dcb9ff6b1440
https://github.com/astropy/astropy-healpix/blob/c7fbe36305aadda9946dd37969d5dcb9ff6b1440/astropy_healpix/healpy.py#L68-L74
8,208
astropy/astropy-healpix
astropy_healpix/healpy.py
nside2pixarea
def nside2pixarea(nside, degrees=False): """Drop-in replacement for healpy `~healpy.pixelfunc.nside2pixarea`.""" area = nside_to_pixel_area(nside) if degrees: return area.to(u.deg ** 2).value else: return area.to(u.sr).value
python
def nside2pixarea(nside, degrees=False): area = nside_to_pixel_area(nside) if degrees: return area.to(u.deg ** 2).value else: return area.to(u.sr).value
[ "def", "nside2pixarea", "(", "nside", ",", "degrees", "=", "False", ")", ":", "area", "=", "nside_to_pixel_area", "(", "nside", ")", "if", "degrees", ":", "return", "area", ".", "to", "(", "u", ".", "deg", "**", "2", ")", ".", "value", "else", ":", ...
Drop-in replacement for healpy `~healpy.pixelfunc.nside2pixarea`.
[ "Drop", "-", "in", "replacement", "for", "healpy", "~healpy", ".", "pixelfunc", ".", "nside2pixarea", "." ]
c7fbe36305aadda9946dd37969d5dcb9ff6b1440
https://github.com/astropy/astropy-healpix/blob/c7fbe36305aadda9946dd37969d5dcb9ff6b1440/astropy_healpix/healpy.py#L77-L83
8,209
astropy/astropy-healpix
astropy_healpix/healpy.py
pix2ang
def pix2ang(nside, ipix, nest=False, lonlat=False): """Drop-in replacement for healpy `~healpy.pixelfunc.pix2ang`.""" lon, lat = healpix_to_lonlat(ipix, nside, order='nested' if nest else 'ring') return _lonlat_to_healpy(lon, lat, lonlat=lonlat)
python
def pix2ang(nside, ipix, nest=False, lonlat=False): lon, lat = healpix_to_lonlat(ipix, nside, order='nested' if nest else 'ring') return _lonlat_to_healpy(lon, lat, lonlat=lonlat)
[ "def", "pix2ang", "(", "nside", ",", "ipix", ",", "nest", "=", "False", ",", "lonlat", "=", "False", ")", ":", "lon", ",", "lat", "=", "healpix_to_lonlat", "(", "ipix", ",", "nside", ",", "order", "=", "'nested'", "if", "nest", "else", "'ring'", ")",...
Drop-in replacement for healpy `~healpy.pixelfunc.pix2ang`.
[ "Drop", "-", "in", "replacement", "for", "healpy", "~healpy", ".", "pixelfunc", ".", "pix2ang", "." ]
c7fbe36305aadda9946dd37969d5dcb9ff6b1440
https://github.com/astropy/astropy-healpix/blob/c7fbe36305aadda9946dd37969d5dcb9ff6b1440/astropy_healpix/healpy.py#L101-L104
8,210
astropy/astropy-healpix
astropy_healpix/healpy.py
ang2pix
def ang2pix(nside, theta, phi, nest=False, lonlat=False): """Drop-in replacement for healpy `~healpy.pixelfunc.ang2pix`.""" lon, lat = _healpy_to_lonlat(theta, phi, lonlat=lonlat) return lonlat_to_healpix(lon, lat, nside, order='nested' if nest else 'ring')
python
def ang2pix(nside, theta, phi, nest=False, lonlat=False): lon, lat = _healpy_to_lonlat(theta, phi, lonlat=lonlat) return lonlat_to_healpix(lon, lat, nside, order='nested' if nest else 'ring')
[ "def", "ang2pix", "(", "nside", ",", "theta", ",", "phi", ",", "nest", "=", "False", ",", "lonlat", "=", "False", ")", ":", "lon", ",", "lat", "=", "_healpy_to_lonlat", "(", "theta", ",", "phi", ",", "lonlat", "=", "lonlat", ")", "return", "lonlat_to...
Drop-in replacement for healpy `~healpy.pixelfunc.ang2pix`.
[ "Drop", "-", "in", "replacement", "for", "healpy", "~healpy", ".", "pixelfunc", ".", "ang2pix", "." ]
c7fbe36305aadda9946dd37969d5dcb9ff6b1440
https://github.com/astropy/astropy-healpix/blob/c7fbe36305aadda9946dd37969d5dcb9ff6b1440/astropy_healpix/healpy.py#L107-L110
8,211
astropy/astropy-healpix
astropy_healpix/healpy.py
pix2vec
def pix2vec(nside, ipix, nest=False): """Drop-in replacement for healpy `~healpy.pixelfunc.pix2vec`.""" lon, lat = healpix_to_lonlat(ipix, nside, order='nested' if nest else 'ring') return ang2vec(*_lonlat_to_healpy(lon, lat))
python
def pix2vec(nside, ipix, nest=False): lon, lat = healpix_to_lonlat(ipix, nside, order='nested' if nest else 'ring') return ang2vec(*_lonlat_to_healpy(lon, lat))
[ "def", "pix2vec", "(", "nside", ",", "ipix", ",", "nest", "=", "False", ")", ":", "lon", ",", "lat", "=", "healpix_to_lonlat", "(", "ipix", ",", "nside", ",", "order", "=", "'nested'", "if", "nest", "else", "'ring'", ")", "return", "ang2vec", "(", "*...
Drop-in replacement for healpy `~healpy.pixelfunc.pix2vec`.
[ "Drop", "-", "in", "replacement", "for", "healpy", "~healpy", ".", "pixelfunc", ".", "pix2vec", "." ]
c7fbe36305aadda9946dd37969d5dcb9ff6b1440
https://github.com/astropy/astropy-healpix/blob/c7fbe36305aadda9946dd37969d5dcb9ff6b1440/astropy_healpix/healpy.py#L113-L116
8,212
astropy/astropy-healpix
astropy_healpix/healpy.py
vec2pix
def vec2pix(nside, x, y, z, nest=False): """Drop-in replacement for healpy `~healpy.pixelfunc.vec2pix`.""" theta, phi = vec2ang(np.transpose([x, y, z])) # hp.vec2ang() returns raveled arrays, which are 1D. if np.isscalar(x): theta = theta.item() phi = phi.item() else: shape = np.shape(x) theta = theta.reshape(shape) phi = phi.reshape(shape) lon, lat = _healpy_to_lonlat(theta, phi) return lonlat_to_healpix(lon, lat, nside, order='nested' if nest else 'ring')
python
def vec2pix(nside, x, y, z, nest=False): theta, phi = vec2ang(np.transpose([x, y, z])) # hp.vec2ang() returns raveled arrays, which are 1D. if np.isscalar(x): theta = theta.item() phi = phi.item() else: shape = np.shape(x) theta = theta.reshape(shape) phi = phi.reshape(shape) lon, lat = _healpy_to_lonlat(theta, phi) return lonlat_to_healpix(lon, lat, nside, order='nested' if nest else 'ring')
[ "def", "vec2pix", "(", "nside", ",", "x", ",", "y", ",", "z", ",", "nest", "=", "False", ")", ":", "theta", ",", "phi", "=", "vec2ang", "(", "np", ".", "transpose", "(", "[", "x", ",", "y", ",", "z", "]", ")", ")", "# hp.vec2ang() returns raveled...
Drop-in replacement for healpy `~healpy.pixelfunc.vec2pix`.
[ "Drop", "-", "in", "replacement", "for", "healpy", "~healpy", ".", "pixelfunc", ".", "vec2pix", "." ]
c7fbe36305aadda9946dd37969d5dcb9ff6b1440
https://github.com/astropy/astropy-healpix/blob/c7fbe36305aadda9946dd37969d5dcb9ff6b1440/astropy_healpix/healpy.py#L119-L131
8,213
astropy/astropy-healpix
astropy_healpix/healpy.py
nest2ring
def nest2ring(nside, ipix): """Drop-in replacement for healpy `~healpy.pixelfunc.nest2ring`.""" ipix = np.atleast_1d(ipix).astype(np.int64, copy=False) return nested_to_ring(ipix, nside)
python
def nest2ring(nside, ipix): ipix = np.atleast_1d(ipix).astype(np.int64, copy=False) return nested_to_ring(ipix, nside)
[ "def", "nest2ring", "(", "nside", ",", "ipix", ")", ":", "ipix", "=", "np", ".", "atleast_1d", "(", "ipix", ")", ".", "astype", "(", "np", ".", "int64", ",", "copy", "=", "False", ")", "return", "nested_to_ring", "(", "ipix", ",", "nside", ")" ]
Drop-in replacement for healpy `~healpy.pixelfunc.nest2ring`.
[ "Drop", "-", "in", "replacement", "for", "healpy", "~healpy", ".", "pixelfunc", ".", "nest2ring", "." ]
c7fbe36305aadda9946dd37969d5dcb9ff6b1440
https://github.com/astropy/astropy-healpix/blob/c7fbe36305aadda9946dd37969d5dcb9ff6b1440/astropy_healpix/healpy.py#L134-L137
8,214
astropy/astropy-healpix
astropy_healpix/healpy.py
ring2nest
def ring2nest(nside, ipix): """Drop-in replacement for healpy `~healpy.pixelfunc.ring2nest`.""" ipix = np.atleast_1d(ipix).astype(np.int64, copy=False) return ring_to_nested(ipix, nside)
python
def ring2nest(nside, ipix): ipix = np.atleast_1d(ipix).astype(np.int64, copy=False) return ring_to_nested(ipix, nside)
[ "def", "ring2nest", "(", "nside", ",", "ipix", ")", ":", "ipix", "=", "np", ".", "atleast_1d", "(", "ipix", ")", ".", "astype", "(", "np", ".", "int64", ",", "copy", "=", "False", ")", "return", "ring_to_nested", "(", "ipix", ",", "nside", ")" ]
Drop-in replacement for healpy `~healpy.pixelfunc.ring2nest`.
[ "Drop", "-", "in", "replacement", "for", "healpy", "~healpy", ".", "pixelfunc", ".", "ring2nest", "." ]
c7fbe36305aadda9946dd37969d5dcb9ff6b1440
https://github.com/astropy/astropy-healpix/blob/c7fbe36305aadda9946dd37969d5dcb9ff6b1440/astropy_healpix/healpy.py#L140-L143
8,215
astropy/astropy-healpix
astropy_healpix/healpy.py
boundaries
def boundaries(nside, pix, step=1, nest=False): """Drop-in replacement for healpy `~healpy.boundaries`.""" pix = np.asarray(pix) if pix.ndim > 1: # For consistency with healpy we only support scalars or 1D arrays raise ValueError("Array has to be one dimensional") lon, lat = boundaries_lonlat(pix, step, nside, order='nested' if nest else 'ring') rep_sph = UnitSphericalRepresentation(lon, lat) rep_car = rep_sph.to_cartesian().xyz.value.swapaxes(0, 1) if rep_car.shape[0] == 1: return rep_car[0] else: return rep_car
python
def boundaries(nside, pix, step=1, nest=False): pix = np.asarray(pix) if pix.ndim > 1: # For consistency with healpy we only support scalars or 1D arrays raise ValueError("Array has to be one dimensional") lon, lat = boundaries_lonlat(pix, step, nside, order='nested' if nest else 'ring') rep_sph = UnitSphericalRepresentation(lon, lat) rep_car = rep_sph.to_cartesian().xyz.value.swapaxes(0, 1) if rep_car.shape[0] == 1: return rep_car[0] else: return rep_car
[ "def", "boundaries", "(", "nside", ",", "pix", ",", "step", "=", "1", ",", "nest", "=", "False", ")", ":", "pix", "=", "np", ".", "asarray", "(", "pix", ")", "if", "pix", ".", "ndim", ">", "1", ":", "# For consistency with healpy we only support scalars ...
Drop-in replacement for healpy `~healpy.boundaries`.
[ "Drop", "-", "in", "replacement", "for", "healpy", "~healpy", ".", "boundaries", "." ]
c7fbe36305aadda9946dd37969d5dcb9ff6b1440
https://github.com/astropy/astropy-healpix/blob/c7fbe36305aadda9946dd37969d5dcb9ff6b1440/astropy_healpix/healpy.py#L146-L158
8,216
astropy/astropy-healpix
astropy_healpix/healpy.py
vec2ang
def vec2ang(vectors, lonlat=False): """Drop-in replacement for healpy `~healpy.pixelfunc.vec2ang`.""" x, y, z = vectors.transpose() rep_car = CartesianRepresentation(x, y, z) rep_sph = rep_car.represent_as(UnitSphericalRepresentation) return _lonlat_to_healpy(rep_sph.lon.ravel(), rep_sph.lat.ravel(), lonlat=lonlat)
python
def vec2ang(vectors, lonlat=False): x, y, z = vectors.transpose() rep_car = CartesianRepresentation(x, y, z) rep_sph = rep_car.represent_as(UnitSphericalRepresentation) return _lonlat_to_healpy(rep_sph.lon.ravel(), rep_sph.lat.ravel(), lonlat=lonlat)
[ "def", "vec2ang", "(", "vectors", ",", "lonlat", "=", "False", ")", ":", "x", ",", "y", ",", "z", "=", "vectors", ".", "transpose", "(", ")", "rep_car", "=", "CartesianRepresentation", "(", "x", ",", "y", ",", "z", ")", "rep_sph", "=", "rep_car", "...
Drop-in replacement for healpy `~healpy.pixelfunc.vec2ang`.
[ "Drop", "-", "in", "replacement", "for", "healpy", "~healpy", ".", "pixelfunc", ".", "vec2ang", "." ]
c7fbe36305aadda9946dd37969d5dcb9ff6b1440
https://github.com/astropy/astropy-healpix/blob/c7fbe36305aadda9946dd37969d5dcb9ff6b1440/astropy_healpix/healpy.py#L161-L166
8,217
astropy/astropy-healpix
astropy_healpix/healpy.py
ang2vec
def ang2vec(theta, phi, lonlat=False): """Drop-in replacement for healpy `~healpy.pixelfunc.ang2vec`.""" lon, lat = _healpy_to_lonlat(theta, phi, lonlat=lonlat) rep_sph = UnitSphericalRepresentation(lon, lat) rep_car = rep_sph.represent_as(CartesianRepresentation) return rep_car.xyz.value
python
def ang2vec(theta, phi, lonlat=False): lon, lat = _healpy_to_lonlat(theta, phi, lonlat=lonlat) rep_sph = UnitSphericalRepresentation(lon, lat) rep_car = rep_sph.represent_as(CartesianRepresentation) return rep_car.xyz.value
[ "def", "ang2vec", "(", "theta", ",", "phi", ",", "lonlat", "=", "False", ")", ":", "lon", ",", "lat", "=", "_healpy_to_lonlat", "(", "theta", ",", "phi", ",", "lonlat", "=", "lonlat", ")", "rep_sph", "=", "UnitSphericalRepresentation", "(", "lon", ",", ...
Drop-in replacement for healpy `~healpy.pixelfunc.ang2vec`.
[ "Drop", "-", "in", "replacement", "for", "healpy", "~healpy", ".", "pixelfunc", ".", "ang2vec", "." ]
c7fbe36305aadda9946dd37969d5dcb9ff6b1440
https://github.com/astropy/astropy-healpix/blob/c7fbe36305aadda9946dd37969d5dcb9ff6b1440/astropy_healpix/healpy.py#L169-L174
8,218
astropy/astropy-healpix
astropy_healpix/healpy.py
get_interp_weights
def get_interp_weights(nside, theta, phi=None, nest=False, lonlat=False): """ Drop-in replacement for healpy `~healpy.pixelfunc.get_interp_weights`. Although note that the order of the weights and pixels may differ. """ # if phi is not given, theta is interpreted as pixel number if phi is None: theta, phi = pix2ang(nside, ipix=theta, nest=nest) lon, lat = _healpy_to_lonlat(theta, phi, lonlat=lonlat) return bilinear_interpolation_weights(lon, lat, nside, order='nested' if nest else 'ring')
python
def get_interp_weights(nside, theta, phi=None, nest=False, lonlat=False): # if phi is not given, theta is interpreted as pixel number if phi is None: theta, phi = pix2ang(nside, ipix=theta, nest=nest) lon, lat = _healpy_to_lonlat(theta, phi, lonlat=lonlat) return bilinear_interpolation_weights(lon, lat, nside, order='nested' if nest else 'ring')
[ "def", "get_interp_weights", "(", "nside", ",", "theta", ",", "phi", "=", "None", ",", "nest", "=", "False", ",", "lonlat", "=", "False", ")", ":", "# if phi is not given, theta is interpreted as pixel number", "if", "phi", "is", "None", ":", "theta", ",", "ph...
Drop-in replacement for healpy `~healpy.pixelfunc.get_interp_weights`. Although note that the order of the weights and pixels may differ.
[ "Drop", "-", "in", "replacement", "for", "healpy", "~healpy", ".", "pixelfunc", ".", "get_interp_weights", "." ]
c7fbe36305aadda9946dd37969d5dcb9ff6b1440
https://github.com/astropy/astropy-healpix/blob/c7fbe36305aadda9946dd37969d5dcb9ff6b1440/astropy_healpix/healpy.py#L177-L188
8,219
astropy/astropy-healpix
astropy_healpix/healpy.py
get_interp_val
def get_interp_val(m, theta, phi, nest=False, lonlat=False): """ Drop-in replacement for healpy `~healpy.pixelfunc.get_interp_val`. """ lon, lat = _healpy_to_lonlat(theta, phi, lonlat=lonlat) return interpolate_bilinear_lonlat(lon, lat, m, order='nested' if nest else 'ring')
python
def get_interp_val(m, theta, phi, nest=False, lonlat=False): lon, lat = _healpy_to_lonlat(theta, phi, lonlat=lonlat) return interpolate_bilinear_lonlat(lon, lat, m, order='nested' if nest else 'ring')
[ "def", "get_interp_val", "(", "m", ",", "theta", ",", "phi", ",", "nest", "=", "False", ",", "lonlat", "=", "False", ")", ":", "lon", ",", "lat", "=", "_healpy_to_lonlat", "(", "theta", ",", "phi", ",", "lonlat", "=", "lonlat", ")", "return", "interp...
Drop-in replacement for healpy `~healpy.pixelfunc.get_interp_val`.
[ "Drop", "-", "in", "replacement", "for", "healpy", "~healpy", ".", "pixelfunc", ".", "get_interp_val", "." ]
c7fbe36305aadda9946dd37969d5dcb9ff6b1440
https://github.com/astropy/astropy-healpix/blob/c7fbe36305aadda9946dd37969d5dcb9ff6b1440/astropy_healpix/healpy.py#L191-L196
8,220
astropy/astropy-healpix
astropy_healpix/bench.py
bench_run
def bench_run(fast=False): """Run all benchmarks. Return results as a dict.""" results = [] if fast: SIZES = [10, 1e3, 1e5] else: SIZES = [10, 1e3, 1e6] for nest in [True, False]: for size in SIZES: for nside in [1, 128]: results.append(run_single('pix2ang', bench_pix2ang, fast=fast, size=int(size), nside=nside, nest=nest)) for nest in [True, False]: for size in SIZES: for nside in [1, 128]: results.append(run_single('ang2pix', bench_ang2pix, fast=fast, size=int(size), nside=nside, nest=nest)) for size in SIZES: for nside in [1, 128]: results.append(run_single('nest2ring', bench_nest2ring, fast=fast, size=int(size), nside=nside)) for size in SIZES: for nside in [1, 128]: results.append(run_single('ring2nest', bench_ring2nest, fast=fast, size=int(size), nside=nside)) for nest in [True, False]: for size in SIZES: for nside in [1, 128]: results.append(run_single('get_interp_weights', bench_get_interp_weights, fast=fast, size=int(size), nside=nside, nest=nest)) return results
python
def bench_run(fast=False): results = [] if fast: SIZES = [10, 1e3, 1e5] else: SIZES = [10, 1e3, 1e6] for nest in [True, False]: for size in SIZES: for nside in [1, 128]: results.append(run_single('pix2ang', bench_pix2ang, fast=fast, size=int(size), nside=nside, nest=nest)) for nest in [True, False]: for size in SIZES: for nside in [1, 128]: results.append(run_single('ang2pix', bench_ang2pix, fast=fast, size=int(size), nside=nside, nest=nest)) for size in SIZES: for nside in [1, 128]: results.append(run_single('nest2ring', bench_nest2ring, fast=fast, size=int(size), nside=nside)) for size in SIZES: for nside in [1, 128]: results.append(run_single('ring2nest', bench_ring2nest, fast=fast, size=int(size), nside=nside)) for nest in [True, False]: for size in SIZES: for nside in [1, 128]: results.append(run_single('get_interp_weights', bench_get_interp_weights, fast=fast, size=int(size), nside=nside, nest=nest)) return results
[ "def", "bench_run", "(", "fast", "=", "False", ")", ":", "results", "=", "[", "]", "if", "fast", ":", "SIZES", "=", "[", "10", ",", "1e3", ",", "1e5", "]", "else", ":", "SIZES", "=", "[", "10", ",", "1e3", ",", "1e6", "]", "for", "nest", "in"...
Run all benchmarks. Return results as a dict.
[ "Run", "all", "benchmarks", ".", "Return", "results", "as", "a", "dict", "." ]
c7fbe36305aadda9946dd37969d5dcb9ff6b1440
https://github.com/astropy/astropy-healpix/blob/c7fbe36305aadda9946dd37969d5dcb9ff6b1440/astropy_healpix/bench.py#L150-L188
8,221
astropy/astropy-healpix
astropy_healpix/bench.py
bench_report
def bench_report(results): """Print a report for given benchmark results to the console.""" table = Table(names=['function', 'nest', 'nside', 'size', 'time_healpy', 'time_self', 'ratio'], dtype=['S20', bool, int, int, float, float, float], masked=True) for row in results: table.add_row(row) table['time_self'].format = '10.7f' if HEALPY_INSTALLED: table['ratio'] = table['time_self'] / table['time_healpy'] table['time_healpy'].format = '10.7f' table['ratio'].format = '7.2f' table.pprint(max_lines=-1)
python
def bench_report(results): table = Table(names=['function', 'nest', 'nside', 'size', 'time_healpy', 'time_self', 'ratio'], dtype=['S20', bool, int, int, float, float, float], masked=True) for row in results: table.add_row(row) table['time_self'].format = '10.7f' if HEALPY_INSTALLED: table['ratio'] = table['time_self'] / table['time_healpy'] table['time_healpy'].format = '10.7f' table['ratio'].format = '7.2f' table.pprint(max_lines=-1)
[ "def", "bench_report", "(", "results", ")", ":", "table", "=", "Table", "(", "names", "=", "[", "'function'", ",", "'nest'", ",", "'nside'", ",", "'size'", ",", "'time_healpy'", ",", "'time_self'", ",", "'ratio'", "]", ",", "dtype", "=", "[", "'S20'", ...
Print a report for given benchmark results to the console.
[ "Print", "a", "report", "for", "given", "benchmark", "results", "to", "the", "console", "." ]
c7fbe36305aadda9946dd37969d5dcb9ff6b1440
https://github.com/astropy/astropy-healpix/blob/c7fbe36305aadda9946dd37969d5dcb9ff6b1440/astropy_healpix/bench.py#L191-L207
8,222
astropy/astropy-healpix
astropy_healpix/bench.py
main
def main(fast=False): """Run all benchmarks and print report to the console.""" print('Running benchmarks...\n') results = bench_run(fast=fast) bench_report(results)
python
def main(fast=False): print('Running benchmarks...\n') results = bench_run(fast=fast) bench_report(results)
[ "def", "main", "(", "fast", "=", "False", ")", ":", "print", "(", "'Running benchmarks...\\n'", ")", "results", "=", "bench_run", "(", "fast", "=", "fast", ")", "bench_report", "(", "results", ")" ]
Run all benchmarks and print report to the console.
[ "Run", "all", "benchmarks", "and", "print", "report", "to", "the", "console", "." ]
c7fbe36305aadda9946dd37969d5dcb9ff6b1440
https://github.com/astropy/astropy-healpix/blob/c7fbe36305aadda9946dd37969d5dcb9ff6b1440/astropy_healpix/bench.py#L210-L214
8,223
dtheodor/flask-sqlalchemy-session
flask_sqlalchemy_session/__init__.py
flask_scoped_session.init_app
def init_app(self, app): """Setup scoped sesssion creation and teardown for the passed ``app``. :param app: a :class:`~flask.Flask` application """ app.scoped_session = self @app.teardown_appcontext def remove_scoped_session(*args, **kwargs): # pylint: disable=missing-docstring,unused-argument,unused-variable app.scoped_session.remove()
python
def init_app(self, app): app.scoped_session = self @app.teardown_appcontext def remove_scoped_session(*args, **kwargs): # pylint: disable=missing-docstring,unused-argument,unused-variable app.scoped_session.remove()
[ "def", "init_app", "(", "self", ",", "app", ")", ":", "app", ".", "scoped_session", "=", "self", "@", "app", ".", "teardown_appcontext", "def", "remove_scoped_session", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "# pylint: disable=missing-docstring,u...
Setup scoped sesssion creation and teardown for the passed ``app``. :param app: a :class:`~flask.Flask` application
[ "Setup", "scoped", "sesssion", "creation", "and", "teardown", "for", "the", "passed", "app", "." ]
c7ddb03e85cdd27fcdcc809b9e1c29d7738d8ebf
https://github.com/dtheodor/flask-sqlalchemy-session/blob/c7ddb03e85cdd27fcdcc809b9e1c29d7738d8ebf/flask_sqlalchemy_session/__init__.py#L66-L76
8,224
dchaplinsky/aiohttp_validate
aiohttp_validate/__init__.py
validate
def validate(request_schema=None, response_schema=None): """ Decorate request handler to make it automagically validate it's request and response. """ def wrapper(func): # Validating the schemas itself. # Die with exception if they aren't valid if request_schema is not None: _request_schema_validator = validator_for(request_schema) _request_schema_validator.check_schema(request_schema) if response_schema is not None: _response_schema_validator = validator_for(response_schema) _response_schema_validator.check_schema(response_schema) @asyncio.coroutine @functools.wraps(func) def wrapped(*args): if asyncio.iscoroutinefunction(func): coro = func else: coro = asyncio.coroutine(func) # Supports class based views see web.View if isinstance(args[0], AbstractView): class_based = True request = args[0].request else: class_based = False request = args[-1] # Strictly expect json object here try: req_body = yield from request.json() except (json.decoder.JSONDecodeError, TypeError): _raise_exception( web.HTTPBadRequest, "Request is malformed; could not decode JSON object.") # Validate request data against request schema (if given) if request_schema is not None: _validate_data(req_body, request_schema, _request_schema_validator) coro_args = req_body, request if class_based: coro_args = (args[0], ) + coro_args context = yield from coro(*coro_args) # No validation of response for websockets stream if isinstance(context, web.StreamResponse): return context # Validate response data against response schema (if given) if response_schema is not None: _validate_data(context, response_schema, _response_schema_validator) try: return web.json_response(context) except (TypeError, ): _raise_exception( web.HTTPInternalServerError, "Response is malformed; could not encode JSON object.") # Store schemas in wrapped handlers, so it later can be reused setattr(wrapped, "_request_schema", request_schema) setattr(wrapped, "_response_schema", response_schema) return wrapped return wrapper
python
def validate(request_schema=None, response_schema=None): def wrapper(func): # Validating the schemas itself. # Die with exception if they aren't valid if request_schema is not None: _request_schema_validator = validator_for(request_schema) _request_schema_validator.check_schema(request_schema) if response_schema is not None: _response_schema_validator = validator_for(response_schema) _response_schema_validator.check_schema(response_schema) @asyncio.coroutine @functools.wraps(func) def wrapped(*args): if asyncio.iscoroutinefunction(func): coro = func else: coro = asyncio.coroutine(func) # Supports class based views see web.View if isinstance(args[0], AbstractView): class_based = True request = args[0].request else: class_based = False request = args[-1] # Strictly expect json object here try: req_body = yield from request.json() except (json.decoder.JSONDecodeError, TypeError): _raise_exception( web.HTTPBadRequest, "Request is malformed; could not decode JSON object.") # Validate request data against request schema (if given) if request_schema is not None: _validate_data(req_body, request_schema, _request_schema_validator) coro_args = req_body, request if class_based: coro_args = (args[0], ) + coro_args context = yield from coro(*coro_args) # No validation of response for websockets stream if isinstance(context, web.StreamResponse): return context # Validate response data against response schema (if given) if response_schema is not None: _validate_data(context, response_schema, _response_schema_validator) try: return web.json_response(context) except (TypeError, ): _raise_exception( web.HTTPInternalServerError, "Response is malformed; could not encode JSON object.") # Store schemas in wrapped handlers, so it later can be reused setattr(wrapped, "_request_schema", request_schema) setattr(wrapped, "_response_schema", response_schema) return wrapped return wrapper
[ "def", "validate", "(", "request_schema", "=", "None", ",", "response_schema", "=", "None", ")", ":", "def", "wrapper", "(", "func", ")", ":", "# Validating the schemas itself.", "# Die with exception if they aren't valid", "if", "request_schema", "is", "not", "None",...
Decorate request handler to make it automagically validate it's request and response.
[ "Decorate", "request", "handler", "to", "make", "it", "automagically", "validate", "it", "s", "request", "and", "response", "." ]
e581cf51df6fcc377c7704315a487b10c3dd6000
https://github.com/dchaplinsky/aiohttp_validate/blob/e581cf51df6fcc377c7704315a487b10c3dd6000/aiohttp_validate/__init__.py#L77-L148
8,225
biolink/biolink-model
metamodel/generators/jsonschemagen.py
cli
def cli(yamlfile, inline, format): """ Generate JSON Schema representation of a biolink model """ print(JsonSchemaGenerator(yamlfile, format).serialize(inline=inline))
python
def cli(yamlfile, inline, format): print(JsonSchemaGenerator(yamlfile, format).serialize(inline=inline))
[ "def", "cli", "(", "yamlfile", ",", "inline", ",", "format", ")", ":", "print", "(", "JsonSchemaGenerator", "(", "yamlfile", ",", "format", ")", ".", "serialize", "(", "inline", "=", "inline", ")", ")" ]
Generate JSON Schema representation of a biolink model
[ "Generate", "JSON", "Schema", "representation", "of", "a", "biolink", "model" ]
f379e28d5d4085e1115798c6cb28e5acc4dba8b4
https://github.com/biolink/biolink-model/blob/f379e28d5d4085e1115798c6cb28e5acc4dba8b4/metamodel/generators/jsonschemagen.py#L90-L92
8,226
biolink/biolink-model
metamodel/generators/markdowngen.py
cli
def cli(yamlfile, format, dir, classes, img, noimages): """ Generate markdown documentation of a biolink model """ MarkdownGenerator(yamlfile, format).serialize(classes=classes, directory=dir, image_dir=img, noimages=noimages)
python
def cli(yamlfile, format, dir, classes, img, noimages): MarkdownGenerator(yamlfile, format).serialize(classes=classes, directory=dir, image_dir=img, noimages=noimages)
[ "def", "cli", "(", "yamlfile", ",", "format", ",", "dir", ",", "classes", ",", "img", ",", "noimages", ")", ":", "MarkdownGenerator", "(", "yamlfile", ",", "format", ")", ".", "serialize", "(", "classes", "=", "classes", ",", "directory", "=", "dir", "...
Generate markdown documentation of a biolink model
[ "Generate", "markdown", "documentation", "of", "a", "biolink", "model" ]
f379e28d5d4085e1115798c6cb28e5acc4dba8b4
https://github.com/biolink/biolink-model/blob/f379e28d5d4085e1115798c6cb28e5acc4dba8b4/metamodel/generators/markdowngen.py#L316-L318
8,227
biolink/biolink-model
metamodel/generators/markdowngen.py
MarkdownGenerator.is_secondary_ref
def is_secondary_ref(self, en: str) -> bool: """ Determine whether 'en' is the name of something in the neighborhood of the requested classes @param en: element name @return: True if 'en' is the name of a slot, class or type in the immediate neighborhood of of what we are building """ if not self.gen_classes: return True elif en in self.schema.classes: return en in self.gen_classes_neighborhood.classrefs elif en in self.schema.slots: return en in self.gen_classes_neighborhood.slotrefs elif en in self.schema.types: return en in self.gen_classes_neighborhood.typerefs else: return True
python
def is_secondary_ref(self, en: str) -> bool: if not self.gen_classes: return True elif en in self.schema.classes: return en in self.gen_classes_neighborhood.classrefs elif en in self.schema.slots: return en in self.gen_classes_neighborhood.slotrefs elif en in self.schema.types: return en in self.gen_classes_neighborhood.typerefs else: return True
[ "def", "is_secondary_ref", "(", "self", ",", "en", ":", "str", ")", "->", "bool", ":", "if", "not", "self", ".", "gen_classes", ":", "return", "True", "elif", "en", "in", "self", ".", "schema", ".", "classes", ":", "return", "en", "in", "self", ".", ...
Determine whether 'en' is the name of something in the neighborhood of the requested classes @param en: element name @return: True if 'en' is the name of a slot, class or type in the immediate neighborhood of of what we are building
[ "Determine", "whether", "en", "is", "the", "name", "of", "something", "in", "the", "neighborhood", "of", "the", "requested", "classes" ]
f379e28d5d4085e1115798c6cb28e5acc4dba8b4
https://github.com/biolink/biolink-model/blob/f379e28d5d4085e1115798c6cb28e5acc4dba8b4/metamodel/generators/markdowngen.py#L191-L207
8,228
biolink/biolink-model
metamodel/generators/markdowngen.py
MarkdownGenerator.bbin
def bbin(obj: Union[str, Element]) -> str: """ Boldify built in types @param obj: object name or id @return: """ return obj.name if isinstance(obj, Element ) else f'**{obj}**' if obj in builtin_names else obj
python
def bbin(obj: Union[str, Element]) -> str: return obj.name if isinstance(obj, Element ) else f'**{obj}**' if obj in builtin_names else obj
[ "def", "bbin", "(", "obj", ":", "Union", "[", "str", ",", "Element", "]", ")", "->", "str", ":", "return", "obj", ".", "name", "if", "isinstance", "(", "obj", ",", "Element", ")", "else", "f'**{obj}**'", "if", "obj", "in", "builtin_names", "else", "o...
Boldify built in types @param obj: object name or id @return:
[ "Boldify", "built", "in", "types" ]
f379e28d5d4085e1115798c6cb28e5acc4dba8b4
https://github.com/biolink/biolink-model/blob/f379e28d5d4085e1115798c6cb28e5acc4dba8b4/metamodel/generators/markdowngen.py#L254-L260
8,229
biolink/biolink-model
metamodel/generators/markdowngen.py
MarkdownGenerator.link
def link(self, ref: Optional[Union[str, Element]], *, after_link: str = None, use_desc: bool=False, add_subset: bool=True) -> str: """ Create a link to ref if appropriate. @param ref: the name or value of a class, slot, type or the name of a built in type. @param after_link: Text to put between link and description @param use_desc: True means append a description after the link if available @param add_subset: True means add any subset information that is available @return: """ obj = self.obj_for(ref) if isinstance(ref, str) else ref nl = '\n' if isinstance(obj, str) or obj is None or not self.is_secondary_ref(obj.name): return self.bbin(ref) if isinstance(obj, SlotDefinition): link_name = ((be(obj.domain) + '.') if obj.alias else '') + self.aliased_slot_name(obj) link_ref = underscore(obj.name) else: link_name = self.obj_name(obj) link_ref = link_name desc = self.desc_for(obj, use_desc) return f'[{link_name}]' \ f'({link_ref}.{self.format})' + \ (f' *subsets*: ({"| ".join(obj.in_subset)})' if add_subset and obj.in_subset else '') + \ (f' {after_link} ' if after_link else '') + (f' - {desc.split(nl)[0]}' if desc else '')
python
def link(self, ref: Optional[Union[str, Element]], *, after_link: str = None, use_desc: bool=False, add_subset: bool=True) -> str: obj = self.obj_for(ref) if isinstance(ref, str) else ref nl = '\n' if isinstance(obj, str) or obj is None or not self.is_secondary_ref(obj.name): return self.bbin(ref) if isinstance(obj, SlotDefinition): link_name = ((be(obj.domain) + '.') if obj.alias else '') + self.aliased_slot_name(obj) link_ref = underscore(obj.name) else: link_name = self.obj_name(obj) link_ref = link_name desc = self.desc_for(obj, use_desc) return f'[{link_name}]' \ f'({link_ref}.{self.format})' + \ (f' *subsets*: ({"| ".join(obj.in_subset)})' if add_subset and obj.in_subset else '') + \ (f' {after_link} ' if after_link else '') + (f' - {desc.split(nl)[0]}' if desc else '')
[ "def", "link", "(", "self", ",", "ref", ":", "Optional", "[", "Union", "[", "str", ",", "Element", "]", "]", ",", "*", ",", "after_link", ":", "str", "=", "None", ",", "use_desc", ":", "bool", "=", "False", ",", "add_subset", ":", "bool", "=", "T...
Create a link to ref if appropriate. @param ref: the name or value of a class, slot, type or the name of a built in type. @param after_link: Text to put between link and description @param use_desc: True means append a description after the link if available @param add_subset: True means add any subset information that is available @return:
[ "Create", "a", "link", "to", "ref", "if", "appropriate", "." ]
f379e28d5d4085e1115798c6cb28e5acc4dba8b4
https://github.com/biolink/biolink-model/blob/f379e28d5d4085e1115798c6cb28e5acc4dba8b4/metamodel/generators/markdowngen.py#L279-L303
8,230
biolink/biolink-model
metamodel/generators/owlgen.py
cli
def cli(yamlfile, format, output): """ Generate an OWL representation of a biolink model """ print(OwlSchemaGenerator(yamlfile, format).serialize(output=output))
python
def cli(yamlfile, format, output): print(OwlSchemaGenerator(yamlfile, format).serialize(output=output))
[ "def", "cli", "(", "yamlfile", ",", "format", ",", "output", ")", ":", "print", "(", "OwlSchemaGenerator", "(", "yamlfile", ",", "format", ")", ".", "serialize", "(", "output", "=", "output", ")", ")" ]
Generate an OWL representation of a biolink model
[ "Generate", "an", "OWL", "representation", "of", "a", "biolink", "model" ]
f379e28d5d4085e1115798c6cb28e5acc4dba8b4
https://github.com/biolink/biolink-model/blob/f379e28d5d4085e1115798c6cb28e5acc4dba8b4/metamodel/generators/owlgen.py#L197-L199
8,231
biolink/biolink-model
metamodel/generators/owlgen.py
OwlSchemaGenerator.visit_slot
def visit_slot(self, slot_name: str, slot: SlotDefinition) -> None: """ Add a slot definition per slot @param slot_name: @param slot: @return: """ # Note: We use the raw name in OWL and add a subProperty arc slot_uri = self.prop_uri(slot.name) # Parent slots if slot.is_a: self.graph.add((slot_uri, RDFS.subPropertyOf, self.prop_uri(slot.is_a))) for mixin in slot.mixins: self.graph.add((slot_uri, RDFS.subPropertyOf, self.prop_uri(mixin))) # Slot range if not slot.range or slot.range in builtin_names: self.graph.add((slot_uri, RDF.type, OWL.DatatypeProperty if slot.object_property else OWL.AnnotationProperty)) self.graph.add((slot_uri, RDFS.range, URIRef(builtin_uri(slot.range, expand=True)))) elif slot.range in self.schema.types: self.graph.add((slot_uri, RDF.type, OWL.DatatypeProperty if slot.object_property else OWL.AnnotationProperty)) self.graph.add((slot_uri, RDFS.range, self.type_uri(slot.range))) else: self.graph.add((slot_uri, RDF.type, OWL.ObjectProperty if slot.object_property else OWL.AnnotationProperty)) self.graph.add((slot_uri, RDFS.range, self.class_uri(slot.range))) # Slot domain if slot.domain: self.graph.add((slot_uri, RDFS.domain, self.class_uri(slot.domain))) # Annotations self.graph.add((slot_uri, RDFS.label, Literal(slot.name))) if slot.description: self.graph.add((slot_uri, OBO.IAO_0000115, Literal(slot.description)))
python
def visit_slot(self, slot_name: str, slot: SlotDefinition) -> None: # Note: We use the raw name in OWL and add a subProperty arc slot_uri = self.prop_uri(slot.name) # Parent slots if slot.is_a: self.graph.add((slot_uri, RDFS.subPropertyOf, self.prop_uri(slot.is_a))) for mixin in slot.mixins: self.graph.add((slot_uri, RDFS.subPropertyOf, self.prop_uri(mixin))) # Slot range if not slot.range or slot.range in builtin_names: self.graph.add((slot_uri, RDF.type, OWL.DatatypeProperty if slot.object_property else OWL.AnnotationProperty)) self.graph.add((slot_uri, RDFS.range, URIRef(builtin_uri(slot.range, expand=True)))) elif slot.range in self.schema.types: self.graph.add((slot_uri, RDF.type, OWL.DatatypeProperty if slot.object_property else OWL.AnnotationProperty)) self.graph.add((slot_uri, RDFS.range, self.type_uri(slot.range))) else: self.graph.add((slot_uri, RDF.type, OWL.ObjectProperty if slot.object_property else OWL.AnnotationProperty)) self.graph.add((slot_uri, RDFS.range, self.class_uri(slot.range))) # Slot domain if slot.domain: self.graph.add((slot_uri, RDFS.domain, self.class_uri(slot.domain))) # Annotations self.graph.add((slot_uri, RDFS.label, Literal(slot.name))) if slot.description: self.graph.add((slot_uri, OBO.IAO_0000115, Literal(slot.description)))
[ "def", "visit_slot", "(", "self", ",", "slot_name", ":", "str", ",", "slot", ":", "SlotDefinition", ")", "->", "None", ":", "# Note: We use the raw name in OWL and add a subProperty arc", "slot_uri", "=", "self", ".", "prop_uri", "(", "slot", ".", "name", ")", "...
Add a slot definition per slot @param slot_name: @param slot: @return:
[ "Add", "a", "slot", "definition", "per", "slot" ]
f379e28d5d4085e1115798c6cb28e5acc4dba8b4
https://github.com/biolink/biolink-model/blob/f379e28d5d4085e1115798c6cb28e5acc4dba8b4/metamodel/generators/owlgen.py#L153-L189
8,232
biolink/biolink-model
metamodel/utils/loadschema.py
load_raw_schema
def load_raw_schema(data: Union[str, TextIO], source_file: str=None, source_file_date: str=None, source_file_size: int=None, base_dir: Optional[str]=None) -> SchemaDefinition: """ Load and flatten SchemaDefinition from a file name, a URL or a block of text @param data: URL, file name or block of text @param source_file: Source file name for the schema @param source_file_date: timestamp of source file @param source_file_size: size of source file @param base_dir: Working directory of sources @return: Map from schema name to SchemaDefinition """ if isinstance(data, str): if '\n' in data: return load_raw_schema((cast(TextIO, StringIO(data)))) # Not sure why typing doesn't see StringIO as TextIO elif '://' in data: # TODO: complete and test URL access req = Request(data) req.add_header("Accept", "application/yaml, text/yaml;q=0.9") with urlopen(req) as response: return load_raw_schema(response) else: fname = os.path.join(base_dir if base_dir else '', data) with open(fname) as f: return load_raw_schema(f, data, time.ctime(os.path.getmtime(fname)), os.path.getsize(fname)) else: schemadefs = yaml.load(data, DupCheckYamlLoader) # Some schemas don't have an outermost identifier. Construct one if necessary if 'name' in schemadefs: schemadefs = {schemadefs.pop('name'): schemadefs} elif 'id' in schemadefs: schemadefs = {schemadefs['id']: schemadefs} elif len(schemadefs) > 1 or not isinstance(list(schemadefs.values())[0], dict): schemadefs = {'Unnamed Schema': schemadefs} schema: SchemaDefinition = None for sname, sdef in {k: SchemaDefinition(name=k, **v) for k, v in schemadefs.items()}.items(): if schema is None: schema = sdef schema.source_file = os.path.basename(source_file) if source_file else None schema.source_file_date = source_file_date schema.source_file_size = source_file_size schema.generation_date = datetime.now().strftime("%Y-%m-%d %H:%M") schema.metamodel_version = metamodel_version else: merge_schemas(schema, sdef) return schema
python
def load_raw_schema(data: Union[str, TextIO], source_file: str=None, source_file_date: str=None, source_file_size: int=None, base_dir: Optional[str]=None) -> SchemaDefinition: if isinstance(data, str): if '\n' in data: return load_raw_schema((cast(TextIO, StringIO(data)))) # Not sure why typing doesn't see StringIO as TextIO elif '://' in data: # TODO: complete and test URL access req = Request(data) req.add_header("Accept", "application/yaml, text/yaml;q=0.9") with urlopen(req) as response: return load_raw_schema(response) else: fname = os.path.join(base_dir if base_dir else '', data) with open(fname) as f: return load_raw_schema(f, data, time.ctime(os.path.getmtime(fname)), os.path.getsize(fname)) else: schemadefs = yaml.load(data, DupCheckYamlLoader) # Some schemas don't have an outermost identifier. Construct one if necessary if 'name' in schemadefs: schemadefs = {schemadefs.pop('name'): schemadefs} elif 'id' in schemadefs: schemadefs = {schemadefs['id']: schemadefs} elif len(schemadefs) > 1 or not isinstance(list(schemadefs.values())[0], dict): schemadefs = {'Unnamed Schema': schemadefs} schema: SchemaDefinition = None for sname, sdef in {k: SchemaDefinition(name=k, **v) for k, v in schemadefs.items()}.items(): if schema is None: schema = sdef schema.source_file = os.path.basename(source_file) if source_file else None schema.source_file_date = source_file_date schema.source_file_size = source_file_size schema.generation_date = datetime.now().strftime("%Y-%m-%d %H:%M") schema.metamodel_version = metamodel_version else: merge_schemas(schema, sdef) return schema
[ "def", "load_raw_schema", "(", "data", ":", "Union", "[", "str", ",", "TextIO", "]", ",", "source_file", ":", "str", "=", "None", ",", "source_file_date", ":", "str", "=", "None", ",", "source_file_size", ":", "int", "=", "None", ",", "base_dir", ":", ...
Load and flatten SchemaDefinition from a file name, a URL or a block of text @param data: URL, file name or block of text @param source_file: Source file name for the schema @param source_file_date: timestamp of source file @param source_file_size: size of source file @param base_dir: Working directory of sources @return: Map from schema name to SchemaDefinition
[ "Load", "and", "flatten", "SchemaDefinition", "from", "a", "file", "name", "a", "URL", "or", "a", "block", "of", "text" ]
f379e28d5d4085e1115798c6cb28e5acc4dba8b4
https://github.com/biolink/biolink-model/blob/f379e28d5d4085e1115798c6cb28e5acc4dba8b4/metamodel/utils/loadschema.py#L14-L61
8,233
biolink/biolink-model
metamodel/utils/loadschema.py
DupCheckYamlLoader.map_constructor
def map_constructor(self, loader, node, deep=False): """ Walk the mapping, recording any duplicate keys. """ mapping = {} for key_node, value_node in node.value: key = loader.construct_object(key_node, deep=deep) value = loader.construct_object(value_node, deep=deep) if key in mapping: raise ValueError(f"Duplicate key: \"{key}\"") mapping[key] = value return mapping
python
def map_constructor(self, loader, node, deep=False): mapping = {} for key_node, value_node in node.value: key = loader.construct_object(key_node, deep=deep) value = loader.construct_object(value_node, deep=deep) if key in mapping: raise ValueError(f"Duplicate key: \"{key}\"") mapping[key] = value return mapping
[ "def", "map_constructor", "(", "self", ",", "loader", ",", "node", ",", "deep", "=", "False", ")", ":", "mapping", "=", "{", "}", "for", "key_node", ",", "value_node", "in", "node", ".", "value", ":", "key", "=", "loader", ".", "construct_object", "(",...
Walk the mapping, recording any duplicate keys.
[ "Walk", "the", "mapping", "recording", "any", "duplicate", "keys", "." ]
f379e28d5d4085e1115798c6cb28e5acc4dba8b4
https://github.com/biolink/biolink-model/blob/f379e28d5d4085e1115798c6cb28e5acc4dba8b4/metamodel/utils/loadschema.py#L69-L81
8,234
biolink/biolink-model
metamodel/utils/comparefiles.py
cli
def cli(file1, file2, comments) -> int: """ Compare file1 to file2 using a filter """ sys.exit(compare_files(file1, file2, comments))
python
def cli(file1, file2, comments) -> int: sys.exit(compare_files(file1, file2, comments))
[ "def", "cli", "(", "file1", ",", "file2", ",", "comments", ")", "->", "int", ":", "sys", ".", "exit", "(", "compare_files", "(", "file1", ",", "file2", ",", "comments", ")", ")" ]
Compare file1 to file2 using a filter
[ "Compare", "file1", "to", "file2", "using", "a", "filter" ]
f379e28d5d4085e1115798c6cb28e5acc4dba8b4
https://github.com/biolink/biolink-model/blob/f379e28d5d4085e1115798c6cb28e5acc4dba8b4/metamodel/utils/comparefiles.py#L26-L28
8,235
biolink/biolink-model
metamodel/generators/golrgen.py
cli
def cli(file, dir, format): """ Generate GOLR representation of a biolink model """ print(GolrSchemaGenerator(file, format).serialize(dirname=dir))
python
def cli(file, dir, format): print(GolrSchemaGenerator(file, format).serialize(dirname=dir))
[ "def", "cli", "(", "file", ",", "dir", ",", "format", ")", ":", "print", "(", "GolrSchemaGenerator", "(", "file", ",", "format", ")", ".", "serialize", "(", "dirname", "=", "dir", ")", ")" ]
Generate GOLR representation of a biolink model
[ "Generate", "GOLR", "representation", "of", "a", "biolink", "model" ]
f379e28d5d4085e1115798c6cb28e5acc4dba8b4
https://github.com/biolink/biolink-model/blob/f379e28d5d4085e1115798c6cb28e5acc4dba8b4/metamodel/generators/golrgen.py#L87-L89
8,236
biolink/biolink-model
metamodel/generators/dotgen.py
cli
def cli(yamlfile, directory, out, classname, format): """ Generate graphviz representations of the biolink model """ DotGenerator(yamlfile, format).serialize(classname=classname, dirname=directory, filename=out)
python
def cli(yamlfile, directory, out, classname, format): DotGenerator(yamlfile, format).serialize(classname=classname, dirname=directory, filename=out)
[ "def", "cli", "(", "yamlfile", ",", "directory", ",", "out", ",", "classname", ",", "format", ")", ":", "DotGenerator", "(", "yamlfile", ",", "format", ")", ".", "serialize", "(", "classname", "=", "classname", ",", "dirname", "=", "directory", ",", "fil...
Generate graphviz representations of the biolink model
[ "Generate", "graphviz", "representations", "of", "the", "biolink", "model" ]
f379e28d5d4085e1115798c6cb28e5acc4dba8b4
https://github.com/biolink/biolink-model/blob/f379e28d5d4085e1115798c6cb28e5acc4dba8b4/metamodel/generators/dotgen.py#L101-L103
8,237
biolink/biolink-model
metamodel/generators/jsonldgen.py
cli
def cli(yamlfile, format, context): """ Generate JSONLD file from biolink schema """ print(JSONLDGenerator(yamlfile, format).serialize(context=context))
python
def cli(yamlfile, format, context): print(JSONLDGenerator(yamlfile, format).serialize(context=context))
[ "def", "cli", "(", "yamlfile", ",", "format", ",", "context", ")", ":", "print", "(", "JSONLDGenerator", "(", "yamlfile", ",", "format", ")", ".", "serialize", "(", "context", "=", "context", ")", ")" ]
Generate JSONLD file from biolink schema
[ "Generate", "JSONLD", "file", "from", "biolink", "schema" ]
f379e28d5d4085e1115798c6cb28e5acc4dba8b4
https://github.com/biolink/biolink-model/blob/f379e28d5d4085e1115798c6cb28e5acc4dba8b4/metamodel/generators/jsonldgen.py#L102-L104
8,238
biolink/biolink-model
metamodel/generators/rdfgen.py
cli
def cli(yamlfile, format, output, context): """ Generate an RDF representation of a biolink model """ print(RDFGenerator(yamlfile, format).serialize(output=output, context=context))
python
def cli(yamlfile, format, output, context): print(RDFGenerator(yamlfile, format).serialize(output=output, context=context))
[ "def", "cli", "(", "yamlfile", ",", "format", ",", "output", ",", "context", ")", ":", "print", "(", "RDFGenerator", "(", "yamlfile", ",", "format", ")", ".", "serialize", "(", "output", "=", "output", ",", "context", "=", "context", ")", ")" ]
Generate an RDF representation of a biolink model
[ "Generate", "an", "RDF", "representation", "of", "a", "biolink", "model" ]
f379e28d5d4085e1115798c6cb28e5acc4dba8b4
https://github.com/biolink/biolink-model/blob/f379e28d5d4085e1115798c6cb28e5acc4dba8b4/metamodel/generators/rdfgen.py#L48-L50
8,239
biolink/biolink-model
metamodel/utils/generator.py
Generator.all_slots
def all_slots(self, cls: CLASS_OR_CLASSNAME, *, cls_slots_first: bool = False) \ -> List[SlotDefinition]: """ Return all slots that are part of the class definition. This includes all is_a, mixin and apply_to slots but does NOT include slot_usage targets. If class B has a slot_usage entry for slot "s", only the slot definition for the redefined slot will be included, not its base. Slots are added in the order they appear in classes, with recursive is_a's being added first followed by mixins and finally apply_tos @param cls: class definition or class definition name @param cls_slots_first: True means return class slots at the top of the list @return: ordered list of slots in the class with slot usages removed """ def merge_definitions(cls_name: Optional[ClassDefinitionName]) -> None: if cls_name: for slot in self.all_slots(cls_name): aliased_name = self.aliased_slot_name(slot) if aliased_name not in known_slots: known_slots.add(aliased_name) rval.append(slot) if not isinstance(cls, ClassDefinition): cls = self.schema.classes[cls] known_slots: Set[str] = self.aliased_slot_names(cls.slots) rval: List[SlotDefinition] = [] if cls_slots_first: rval += self.cls_slots(cls) for mixin in cls.mixins: merge_definitions(mixin) merge_definitions(cls.is_a) else: merge_definitions(cls.is_a) for mixin in cls.mixins: merge_definitions(mixin) rval += self.cls_slots(cls) return rval
python
def all_slots(self, cls: CLASS_OR_CLASSNAME, *, cls_slots_first: bool = False) \ -> List[SlotDefinition]: def merge_definitions(cls_name: Optional[ClassDefinitionName]) -> None: if cls_name: for slot in self.all_slots(cls_name): aliased_name = self.aliased_slot_name(slot) if aliased_name not in known_slots: known_slots.add(aliased_name) rval.append(slot) if not isinstance(cls, ClassDefinition): cls = self.schema.classes[cls] known_slots: Set[str] = self.aliased_slot_names(cls.slots) rval: List[SlotDefinition] = [] if cls_slots_first: rval += self.cls_slots(cls) for mixin in cls.mixins: merge_definitions(mixin) merge_definitions(cls.is_a) else: merge_definitions(cls.is_a) for mixin in cls.mixins: merge_definitions(mixin) rval += self.cls_slots(cls) return rval
[ "def", "all_slots", "(", "self", ",", "cls", ":", "CLASS_OR_CLASSNAME", ",", "*", ",", "cls_slots_first", ":", "bool", "=", "False", ")", "->", "List", "[", "SlotDefinition", "]", ":", "def", "merge_definitions", "(", "cls_name", ":", "Optional", "[", "Cla...
Return all slots that are part of the class definition. This includes all is_a, mixin and apply_to slots but does NOT include slot_usage targets. If class B has a slot_usage entry for slot "s", only the slot definition for the redefined slot will be included, not its base. Slots are added in the order they appear in classes, with recursive is_a's being added first followed by mixins and finally apply_tos @param cls: class definition or class definition name @param cls_slots_first: True means return class slots at the top of the list @return: ordered list of slots in the class with slot usages removed
[ "Return", "all", "slots", "that", "are", "part", "of", "the", "class", "definition", ".", "This", "includes", "all", "is_a", "mixin", "and", "apply_to", "slots", "but", "does", "NOT", "include", "slot_usage", "targets", ".", "If", "class", "B", "has", "a",...
f379e28d5d4085e1115798c6cb28e5acc4dba8b4
https://github.com/biolink/biolink-model/blob/f379e28d5d4085e1115798c6cb28e5acc4dba8b4/metamodel/utils/generator.py#L108-L143
8,240
biolink/biolink-model
metamodel/utils/generator.py
Generator.ancestors
def ancestors(self, definition: Union[SLOT_OR_SLOTNAME, CLASS_OR_CLASSNAME]) \ -> List[Union[SlotDefinitionName, ClassDefinitionName]]: """ Return an ordered list of ancestor names for the supplied slot or class @param definition: Slot or class name or definition @return: List of ancestor names """ definition = self.obj_for(definition) if definition is not None: return [definition.name] + self.ancestors(definition.is_a) else: return []
python
def ancestors(self, definition: Union[SLOT_OR_SLOTNAME, CLASS_OR_CLASSNAME]) \ -> List[Union[SlotDefinitionName, ClassDefinitionName]]: definition = self.obj_for(definition) if definition is not None: return [definition.name] + self.ancestors(definition.is_a) else: return []
[ "def", "ancestors", "(", "self", ",", "definition", ":", "Union", "[", "SLOT_OR_SLOTNAME", ",", "CLASS_OR_CLASSNAME", "]", ")", "->", "List", "[", "Union", "[", "SlotDefinitionName", ",", "ClassDefinitionName", "]", "]", ":", "definition", "=", "self", ".", ...
Return an ordered list of ancestor names for the supplied slot or class @param definition: Slot or class name or definition @return: List of ancestor names
[ "Return", "an", "ordered", "list", "of", "ancestor", "names", "for", "the", "supplied", "slot", "or", "class" ]
f379e28d5d4085e1115798c6cb28e5acc4dba8b4
https://github.com/biolink/biolink-model/blob/f379e28d5d4085e1115798c6cb28e5acc4dba8b4/metamodel/utils/generator.py#L145-L157
8,241
biolink/biolink-model
metamodel/utils/generator.py
Generator.neighborhood
def neighborhood(self, elements: List[ELEMENT_NAME]) \ -> References: """ Return a list of all slots, classes and types that touch any element in elements, including the element itself @param elements: Elements to do proximity with @return: All slots and classes that touch element """ touches = References() for element in elements: if element in self.schema.classes: touches.classrefs.add(element) if None in touches.classrefs: raise ValueError("1") cls = self.schema.classes[element] if cls.is_a: touches.classrefs.add(cls.is_a) if None in touches.classrefs: raise ValueError("1") # Mixins include apply_to's touches.classrefs.update(set(cls.mixins)) for slotname in cls.slots: slot = self.schema.slots[slotname] if slot.range in self.schema.classes: touches.classrefs.add(slot.range) elif slot.range in self.schema.types: touches.typerefs.add(slot.range) if None in touches.classrefs: raise ValueError("1") if element in self.synopsis.rangerefs: for slotname in self.synopsis.rangerefs[element]: touches.slotrefs.add(slotname) if self.schema.slots[slotname].domain: touches.classrefs.add(self.schema.slots[slotname].domain) elif element in self.schema.slots: touches.slotrefs.add(element) slot = self.schema.slots[element] touches.slotrefs.update(set(slot.mixins)) if slot.is_a: touches.slotrefs.add(slot.is_a) if element in self.synopsis.inverses: touches.slotrefs.update(self.synopsis.inverses[element]) if slot.domain: touches.classrefs.add(slot.domain) if slot.range in self.schema.classes: touches.classrefs.add(slot.range) elif slot.range in self.schema.types: touches.typerefs.add(slot.range) elif element in self.schema.types: if element in self.synopsis.rangerefs: touches.slotrefs.update(self.synopsis.rangerefs[element]) return touches
python
def neighborhood(self, elements: List[ELEMENT_NAME]) \ -> References: touches = References() for element in elements: if element in self.schema.classes: touches.classrefs.add(element) if None in touches.classrefs: raise ValueError("1") cls = self.schema.classes[element] if cls.is_a: touches.classrefs.add(cls.is_a) if None in touches.classrefs: raise ValueError("1") # Mixins include apply_to's touches.classrefs.update(set(cls.mixins)) for slotname in cls.slots: slot = self.schema.slots[slotname] if slot.range in self.schema.classes: touches.classrefs.add(slot.range) elif slot.range in self.schema.types: touches.typerefs.add(slot.range) if None in touches.classrefs: raise ValueError("1") if element in self.synopsis.rangerefs: for slotname in self.synopsis.rangerefs[element]: touches.slotrefs.add(slotname) if self.schema.slots[slotname].domain: touches.classrefs.add(self.schema.slots[slotname].domain) elif element in self.schema.slots: touches.slotrefs.add(element) slot = self.schema.slots[element] touches.slotrefs.update(set(slot.mixins)) if slot.is_a: touches.slotrefs.add(slot.is_a) if element in self.synopsis.inverses: touches.slotrefs.update(self.synopsis.inverses[element]) if slot.domain: touches.classrefs.add(slot.domain) if slot.range in self.schema.classes: touches.classrefs.add(slot.range) elif slot.range in self.schema.types: touches.typerefs.add(slot.range) elif element in self.schema.types: if element in self.synopsis.rangerefs: touches.slotrefs.update(self.synopsis.rangerefs[element]) return touches
[ "def", "neighborhood", "(", "self", ",", "elements", ":", "List", "[", "ELEMENT_NAME", "]", ")", "->", "References", ":", "touches", "=", "References", "(", ")", "for", "element", "in", "elements", ":", "if", "element", "in", "self", ".", "schema", ".", ...
Return a list of all slots, classes and types that touch any element in elements, including the element itself @param elements: Elements to do proximity with @return: All slots and classes that touch element
[ "Return", "a", "list", "of", "all", "slots", "classes", "and", "types", "that", "touch", "any", "element", "in", "elements", "including", "the", "element", "itself" ]
f379e28d5d4085e1115798c6cb28e5acc4dba8b4
https://github.com/biolink/biolink-model/blob/f379e28d5d4085e1115798c6cb28e5acc4dba8b4/metamodel/utils/generator.py#L159-L211
8,242
biolink/biolink-model
metamodel/utils/generator.py
Generator.grounded_slot_range
def grounded_slot_range(self, slot: Optional[Union[SlotDefinition, Optional[str]]]) -> str: """ Chase the slot range to its final form @param slot: slot to check @return: name of resolved range """ if slot is not None and not isinstance(slot, str): slot = slot.range if slot is None: return DEFAULT_BUILTIN_TYPE_NAME # Default type name elif slot in builtin_names: return slot elif slot in self.schema.types: return self.grounded_slot_range(self.schema.types[slot].typeof) else: return slot
python
def grounded_slot_range(self, slot: Optional[Union[SlotDefinition, Optional[str]]]) -> str: if slot is not None and not isinstance(slot, str): slot = slot.range if slot is None: return DEFAULT_BUILTIN_TYPE_NAME # Default type name elif slot in builtin_names: return slot elif slot in self.schema.types: return self.grounded_slot_range(self.schema.types[slot].typeof) else: return slot
[ "def", "grounded_slot_range", "(", "self", ",", "slot", ":", "Optional", "[", "Union", "[", "SlotDefinition", ",", "Optional", "[", "str", "]", "]", "]", ")", "->", "str", ":", "if", "slot", "is", "not", "None", "and", "not", "isinstance", "(", "slot",...
Chase the slot range to its final form @param slot: slot to check @return: name of resolved range
[ "Chase", "the", "slot", "range", "to", "its", "final", "form" ]
f379e28d5d4085e1115798c6cb28e5acc4dba8b4
https://github.com/biolink/biolink-model/blob/f379e28d5d4085e1115798c6cb28e5acc4dba8b4/metamodel/utils/generator.py#L213-L228
8,243
biolink/biolink-model
metamodel/utils/generator.py
Generator.aliased_slot_names
def aliased_slot_names(self, slot_names: List[SlotDefinitionName]) -> Set[str]: """ Return the aliased slot names for all members of the list @param slot_names: actual slot names @return: aliases w/ duplicates removed """ return {self.aliased_slot_name(sn) for sn in slot_names}
python
def aliased_slot_names(self, slot_names: List[SlotDefinitionName]) -> Set[str]: return {self.aliased_slot_name(sn) for sn in slot_names}
[ "def", "aliased_slot_names", "(", "self", ",", "slot_names", ":", "List", "[", "SlotDefinitionName", "]", ")", "->", "Set", "[", "str", "]", ":", "return", "{", "self", ".", "aliased_slot_name", "(", "sn", ")", "for", "sn", "in", "slot_names", "}" ]
Return the aliased slot names for all members of the list @param slot_names: actual slot names @return: aliases w/ duplicates removed
[ "Return", "the", "aliased", "slot", "names", "for", "all", "members", "of", "the", "list" ]
f379e28d5d4085e1115798c6cb28e5acc4dba8b4
https://github.com/biolink/biolink-model/blob/f379e28d5d4085e1115798c6cb28e5acc4dba8b4/metamodel/utils/generator.py#L240-L246
8,244
biolink/biolink-model
metamodel/utils/generator.py
Generator.obj_for
def obj_for(self, obj_or_name: Union[str, Element]) -> Optional[Union[str, Element]]: """ Return the class, slot or type that represents name or name itself if it is a builtin @param obj_or_name: Object or name @return: Corresponding element or None if not found (most likely cause is that it is a builtin type) """ name = obj_or_name.name if isinstance(obj_or_name, Element) else obj_or_name return self.schema.classes[name] if name in self.schema.classes \ else self.schema.slots[name] if name in self.schema.slots \ else self.schema.types[name] if name in self.schema.types else name if name in builtin_names \ else None
python
def obj_for(self, obj_or_name: Union[str, Element]) -> Optional[Union[str, Element]]: name = obj_or_name.name if isinstance(obj_or_name, Element) else obj_or_name return self.schema.classes[name] if name in self.schema.classes \ else self.schema.slots[name] if name in self.schema.slots \ else self.schema.types[name] if name in self.schema.types else name if name in builtin_names \ else None
[ "def", "obj_for", "(", "self", ",", "obj_or_name", ":", "Union", "[", "str", ",", "Element", "]", ")", "->", "Optional", "[", "Union", "[", "str", ",", "Element", "]", "]", ":", "name", "=", "obj_or_name", ".", "name", "if", "isinstance", "(", "obj_o...
Return the class, slot or type that represents name or name itself if it is a builtin @param obj_or_name: Object or name @return: Corresponding element or None if not found (most likely cause is that it is a builtin type)
[ "Return", "the", "class", "slot", "or", "type", "that", "represents", "name", "or", "name", "itself", "if", "it", "is", "a", "builtin" ]
f379e28d5d4085e1115798c6cb28e5acc4dba8b4
https://github.com/biolink/biolink-model/blob/f379e28d5d4085e1115798c6cb28e5acc4dba8b4/metamodel/utils/generator.py#L248-L258
8,245
biolink/biolink-model
metamodel/utils/generator.py
Generator.obj_name
def obj_name(self, obj: Union[str, Element]) -> str: """ Return the formatted name used for the supplied definition """ if isinstance(obj, str): obj = self.obj_for(obj) if isinstance(obj, SlotDefinition): return underscore(self.aliased_slot_name(obj)) else: return camelcase(obj if isinstance(obj, str) else obj.name)
python
def obj_name(self, obj: Union[str, Element]) -> str: if isinstance(obj, str): obj = self.obj_for(obj) if isinstance(obj, SlotDefinition): return underscore(self.aliased_slot_name(obj)) else: return camelcase(obj if isinstance(obj, str) else obj.name)
[ "def", "obj_name", "(", "self", ",", "obj", ":", "Union", "[", "str", ",", "Element", "]", ")", "->", "str", ":", "if", "isinstance", "(", "obj", ",", "str", ")", ":", "obj", "=", "self", ".", "obj_for", "(", "obj", ")", "if", "isinstance", "(", ...
Return the formatted name used for the supplied definition
[ "Return", "the", "formatted", "name", "used", "for", "the", "supplied", "definition" ]
f379e28d5d4085e1115798c6cb28e5acc4dba8b4
https://github.com/biolink/biolink-model/blob/f379e28d5d4085e1115798c6cb28e5acc4dba8b4/metamodel/utils/generator.py#L260-L267
8,246
biolink/biolink-model
metamodel/generators/pythongen.py
PythonGenerator.gen_inherited
def gen_inherited(self) -> str: """ Generate the list of slot properties that are inherited across slot_usage or is_a paths """ inherited_head = 'inherited_slots: List[str] = [' inherited_slots = ', '.join([f'"{underscore(slot.name)}"' for slot in self.schema.slots.values() if slot.inherited]) is_rows = split_line(inherited_slots, 120 - len(inherited_head)) return inherited_head + ('\n' + len(inherited_head) * ' ').join([r.strip() for r in is_rows]) + ']'
python
def gen_inherited(self) -> str: inherited_head = 'inherited_slots: List[str] = [' inherited_slots = ', '.join([f'"{underscore(slot.name)}"' for slot in self.schema.slots.values() if slot.inherited]) is_rows = split_line(inherited_slots, 120 - len(inherited_head)) return inherited_head + ('\n' + len(inherited_head) * ' ').join([r.strip() for r in is_rows]) + ']'
[ "def", "gen_inherited", "(", "self", ")", "->", "str", ":", "inherited_head", "=", "'inherited_slots: List[str] = ['", "inherited_slots", "=", "', '", ".", "join", "(", "[", "f'\"{underscore(slot.name)}\"'", "for", "slot", "in", "self", ".", "schema", ".", "slots"...
Generate the list of slot properties that are inherited across slot_usage or is_a paths
[ "Generate", "the", "list", "of", "slot", "properties", "that", "are", "inherited", "across", "slot_usage", "or", "is_a", "paths" ]
f379e28d5d4085e1115798c6cb28e5acc4dba8b4
https://github.com/biolink/biolink-model/blob/f379e28d5d4085e1115798c6cb28e5acc4dba8b4/metamodel/generators/pythongen.py#L58-L64
8,247
biolink/biolink-model
metamodel/generators/pythongen.py
PythonGenerator.gen_typedefs
def gen_typedefs(self) -> str: """ Generate python type declarations for all defined types """ rval = [] for typ in self.schema.types.values(): typname = self.python_name_for(typ.name) parent = self.python_name_for(typ.typeof) rval.append(f'class {typname}({parent}):\n\tpass') return '\n\n\n'.join(rval) + ('\n' if rval else '')
python
def gen_typedefs(self) -> str: rval = [] for typ in self.schema.types.values(): typname = self.python_name_for(typ.name) parent = self.python_name_for(typ.typeof) rval.append(f'class {typname}({parent}):\n\tpass') return '\n\n\n'.join(rval) + ('\n' if rval else '')
[ "def", "gen_typedefs", "(", "self", ")", "->", "str", ":", "rval", "=", "[", "]", "for", "typ", "in", "self", ".", "schema", ".", "types", ".", "values", "(", ")", ":", "typname", "=", "self", ".", "python_name_for", "(", "typ", ".", "name", ")", ...
Generate python type declarations for all defined types
[ "Generate", "python", "type", "declarations", "for", "all", "defined", "types" ]
f379e28d5d4085e1115798c6cb28e5acc4dba8b4
https://github.com/biolink/biolink-model/blob/f379e28d5d4085e1115798c6cb28e5acc4dba8b4/metamodel/generators/pythongen.py#L83-L90
8,248
biolink/biolink-model
metamodel/generators/pythongen.py
PythonGenerator.gen_classdefs
def gen_classdefs(self) -> str: """ Create class definitions for all non-mixin classes in the model Note that apply_to classes are transformed to mixins """ return '\n'.join([self.gen_classdef(k, v) for k, v in self.schema.classes.items() if not v.mixin])
python
def gen_classdefs(self) -> str: return '\n'.join([self.gen_classdef(k, v) for k, v in self.schema.classes.items() if not v.mixin])
[ "def", "gen_classdefs", "(", "self", ")", "->", "str", ":", "return", "'\\n'", ".", "join", "(", "[", "self", ".", "gen_classdef", "(", "k", ",", "v", ")", "for", "k", ",", "v", "in", "self", ".", "schema", ".", "classes", ".", "items", "(", ")",...
Create class definitions for all non-mixin classes in the model Note that apply_to classes are transformed to mixins
[ "Create", "class", "definitions", "for", "all", "non", "-", "mixin", "classes", "in", "the", "model", "Note", "that", "apply_to", "classes", "are", "transformed", "to", "mixins" ]
f379e28d5d4085e1115798c6cb28e5acc4dba8b4
https://github.com/biolink/biolink-model/blob/f379e28d5d4085e1115798c6cb28e5acc4dba8b4/metamodel/generators/pythongen.py#L92-L96
8,249
biolink/biolink-model
metamodel/generators/pythongen.py
PythonGenerator.gen_classdef
def gen_classdef(self, clsname: str, cls: ClassDefinition) -> str: """ Generate python definition for class clsname """ parentref = f'({self.python_name_for(cls.is_a) if cls.is_a else "YAMLRoot"})' slotdefs = self.gen_slot_variables(cls) postinits = self.gen_postinits(cls) if not slotdefs: slotdefs = 'pass' wrapped_description = f''' """ {wrapped_annotation(be(cls.description))} """''' if be(cls.description) else '' return f''' @dataclass class {camelcase(clsname)}{parentref}:{wrapped_description} {slotdefs} {postinits}'''
python
def gen_classdef(self, clsname: str, cls: ClassDefinition) -> str: parentref = f'({self.python_name_for(cls.is_a) if cls.is_a else "YAMLRoot"})' slotdefs = self.gen_slot_variables(cls) postinits = self.gen_postinits(cls) if not slotdefs: slotdefs = 'pass' wrapped_description = f''' """ {wrapped_annotation(be(cls.description))} """''' if be(cls.description) else '' return f''' @dataclass class {camelcase(clsname)}{parentref}:{wrapped_description} {slotdefs} {postinits}'''
[ "def", "gen_classdef", "(", "self", ",", "clsname", ":", "str", ",", "cls", ":", "ClassDefinition", ")", "->", "str", ":", "parentref", "=", "f'({self.python_name_for(cls.is_a) if cls.is_a else \"YAMLRoot\"})'", "slotdefs", "=", "self", ".", "gen_slot_variables", "(",...
Generate python definition for class clsname
[ "Generate", "python", "definition", "for", "class", "clsname" ]
f379e28d5d4085e1115798c6cb28e5acc4dba8b4
https://github.com/biolink/biolink-model/blob/f379e28d5d4085e1115798c6cb28e5acc4dba8b4/metamodel/generators/pythongen.py#L98-L113
8,250
biolink/biolink-model
metamodel/generators/pythongen.py
PythonGenerator.gen_slot_variables
def gen_slot_variables(self, cls: ClassDefinition) -> str: """ Generate python definition for class cls, generating primary keys first followed by the rest of the slots """ return '\n\t'.join([self.gen_slot_variable(cls, pk) for pk in self.primary_keys_for(cls)] + [self.gen_slot_variable(cls, slot) for slot in cls.slots if not self.schema.slots[slot].primary_key and not self.schema.slots[slot].identifier])
python
def gen_slot_variables(self, cls: ClassDefinition) -> str: return '\n\t'.join([self.gen_slot_variable(cls, pk) for pk in self.primary_keys_for(cls)] + [self.gen_slot_variable(cls, slot) for slot in cls.slots if not self.schema.slots[slot].primary_key and not self.schema.slots[slot].identifier])
[ "def", "gen_slot_variables", "(", "self", ",", "cls", ":", "ClassDefinition", ")", "->", "str", ":", "return", "'\\n\\t'", ".", "join", "(", "[", "self", ".", "gen_slot_variable", "(", "cls", ",", "pk", ")", "for", "pk", "in", "self", ".", "primary_keys_...
Generate python definition for class cls, generating primary keys first followed by the rest of the slots
[ "Generate", "python", "definition", "for", "class", "cls", "generating", "primary", "keys", "first", "followed", "by", "the", "rest", "of", "the", "slots" ]
f379e28d5d4085e1115798c6cb28e5acc4dba8b4
https://github.com/biolink/biolink-model/blob/f379e28d5d4085e1115798c6cb28e5acc4dba8b4/metamodel/generators/pythongen.py#L115-L121
8,251
biolink/biolink-model
metamodel/generators/pythongen.py
PythonGenerator.gen_slot_variable
def gen_slot_variable(self, cls: ClassDefinition, slotname: str) -> str: """ Generate a slot variable for slotname as defined in class """ slot = self.schema.slots[slotname] # Alias allows re-use of slot names in different contexts if slot.alias: slotname = slot.alias range_type = self.range_type_name(slot, cls.name) # Python version < 3.7 -- forward references have to be quoted if slot.inlined and slot.range in self.schema.classes and self.forward_reference(slot.range, cls.name): range_type = f'"{range_type}"' slot_range, default_val = self.range_cardinality(range_type, slot, cls) default = f'= {default_val}' if default_val else '' return f'''{underscore(slotname)}: {slot_range} {default}'''
python
def gen_slot_variable(self, cls: ClassDefinition, slotname: str) -> str: slot = self.schema.slots[slotname] # Alias allows re-use of slot names in different contexts if slot.alias: slotname = slot.alias range_type = self.range_type_name(slot, cls.name) # Python version < 3.7 -- forward references have to be quoted if slot.inlined and slot.range in self.schema.classes and self.forward_reference(slot.range, cls.name): range_type = f'"{range_type}"' slot_range, default_val = self.range_cardinality(range_type, slot, cls) default = f'= {default_val}' if default_val else '' return f'''{underscore(slotname)}: {slot_range} {default}'''
[ "def", "gen_slot_variable", "(", "self", ",", "cls", ":", "ClassDefinition", ",", "slotname", ":", "str", ")", "->", "str", ":", "slot", "=", "self", ".", "schema", ".", "slots", "[", "slotname", "]", "# Alias allows re-use of slot names in different contexts", ...
Generate a slot variable for slotname as defined in class
[ "Generate", "a", "slot", "variable", "for", "slotname", "as", "defined", "in", "class" ]
f379e28d5d4085e1115798c6cb28e5acc4dba8b4
https://github.com/biolink/biolink-model/blob/f379e28d5d4085e1115798c6cb28e5acc4dba8b4/metamodel/generators/pythongen.py#L123-L138
8,252
biolink/biolink-model
metamodel/generators/pythongen.py
PythonGenerator.gen_postinits
def gen_postinits(self, cls: ClassDefinition) -> str: """ Generate all the typing and existence checks post initialize """ post_inits = [] if not cls.abstract: pkeys = self.primary_keys_for(cls) for pkey in pkeys: post_inits.append(self.gen_postinit(cls, pkey)) for slotname in cls.slots: slot = self.schema.slots[slotname] if not (slot.primary_key or slot.identifier): post_inits.append(self.gen_postinit(cls, slotname)) post_inits_line = '\n\t\t'.join([p for p in post_inits if p]) return (f''' def _fix_elements(self): super()._fix_elements() {post_inits_line}''' + '\n') if post_inits_line else ''
python
def gen_postinits(self, cls: ClassDefinition) -> str: post_inits = [] if not cls.abstract: pkeys = self.primary_keys_for(cls) for pkey in pkeys: post_inits.append(self.gen_postinit(cls, pkey)) for slotname in cls.slots: slot = self.schema.slots[slotname] if not (slot.primary_key or slot.identifier): post_inits.append(self.gen_postinit(cls, slotname)) post_inits_line = '\n\t\t'.join([p for p in post_inits if p]) return (f''' def _fix_elements(self): super()._fix_elements() {post_inits_line}''' + '\n') if post_inits_line else ''
[ "def", "gen_postinits", "(", "self", ",", "cls", ":", "ClassDefinition", ")", "->", "str", ":", "post_inits", "=", "[", "]", "if", "not", "cls", ".", "abstract", ":", "pkeys", "=", "self", ".", "primary_keys_for", "(", "cls", ")", "for", "pkey", "in", ...
Generate all the typing and existence checks post initialize
[ "Generate", "all", "the", "typing", "and", "existence", "checks", "post", "initialize" ]
f379e28d5d4085e1115798c6cb28e5acc4dba8b4
https://github.com/biolink/biolink-model/blob/f379e28d5d4085e1115798c6cb28e5acc4dba8b4/metamodel/generators/pythongen.py#L140-L156
8,253
biolink/biolink-model
metamodel/generators/pythongen.py
PythonGenerator.gen_postinit
def gen_postinit(self, cls: ClassDefinition, slotname: str) -> Optional[str]: """ Generate python post init rules for slot in class """ rlines: List[str] = [] slot = self.schema.slots[slotname] if slot.alias: slotname = slot.alias slotname = self.python_name_for(slotname) range_type_name = self.range_type_name(slot, cls.name) # Generate existence check for required slots. Note that inherited classes have to check post-init because # named variables can't be mixed in the class signature if slot.primary_key or slot.identifier or slot.required: if cls.is_a: rlines.append(f'if self.{slotname} is None:') rlines.append(f'\traise ValueError(f"{slotname} must be supplied")') rlines.append(f'if not isinstance(self.{slotname}, {range_type_name}):') rlines.append(f'\tself.{slotname} = {range_type_name}(self.{slotname})') elif slot.range in self.schema.classes or slot.range in self.schema.types: if not slot.multivalued: rlines.append(f'if self.{slotname} and not isinstance(self.{slotname}, {range_type_name}):') # Another really wierd case -- a class that has no properties if slot.range in self.schema.classes and not self.all_slots_for(self.schema.classes[slot.range]): rlines.append(f'\tself.{slotname} = {range_type_name}()') else: rlines.append(f'\tself.{slotname} = {range_type_name}(self.{slotname})') elif slot.inlined: slot_range_cls = self.schema.classes[slot.range] pkeys = self.primary_keys_for(slot_range_cls) if pkeys: # Special situation -- if there are only two values: primary key and value, # we load it is a list, not a dictionary if len(self.all_slots_for(slot_range_cls)) - len(pkeys) == 1: class_init = '(k, v)' else: pkey_name = self.python_name_for(pkeys[0]) class_init = f'({pkey_name}=k, **({{}} if v is None else v))' rlines.append(f'for k, v in self.{slotname}.items():') rlines.append(f'\tif not isinstance(v, {range_type_name}):') rlines.append(f'\t\tself.{slotname}[k] = {range_type_name}{class_init}') else: rlines.append(f'self.{slotname} = [v if isinstance(v, {range_type_name})') indent = len(f'self.{slotname} = [') * ' ' rlines.append(f'{indent}else {range_type_name}(v) for v in self.{slotname}]') return '\n\t\t'.join(rlines)
python
def gen_postinit(self, cls: ClassDefinition, slotname: str) -> Optional[str]: rlines: List[str] = [] slot = self.schema.slots[slotname] if slot.alias: slotname = slot.alias slotname = self.python_name_for(slotname) range_type_name = self.range_type_name(slot, cls.name) # Generate existence check for required slots. Note that inherited classes have to check post-init because # named variables can't be mixed in the class signature if slot.primary_key or slot.identifier or slot.required: if cls.is_a: rlines.append(f'if self.{slotname} is None:') rlines.append(f'\traise ValueError(f"{slotname} must be supplied")') rlines.append(f'if not isinstance(self.{slotname}, {range_type_name}):') rlines.append(f'\tself.{slotname} = {range_type_name}(self.{slotname})') elif slot.range in self.schema.classes or slot.range in self.schema.types: if not slot.multivalued: rlines.append(f'if self.{slotname} and not isinstance(self.{slotname}, {range_type_name}):') # Another really wierd case -- a class that has no properties if slot.range in self.schema.classes and not self.all_slots_for(self.schema.classes[slot.range]): rlines.append(f'\tself.{slotname} = {range_type_name}()') else: rlines.append(f'\tself.{slotname} = {range_type_name}(self.{slotname})') elif slot.inlined: slot_range_cls = self.schema.classes[slot.range] pkeys = self.primary_keys_for(slot_range_cls) if pkeys: # Special situation -- if there are only two values: primary key and value, # we load it is a list, not a dictionary if len(self.all_slots_for(slot_range_cls)) - len(pkeys) == 1: class_init = '(k, v)' else: pkey_name = self.python_name_for(pkeys[0]) class_init = f'({pkey_name}=k, **({{}} if v is None else v))' rlines.append(f'for k, v in self.{slotname}.items():') rlines.append(f'\tif not isinstance(v, {range_type_name}):') rlines.append(f'\t\tself.{slotname}[k] = {range_type_name}{class_init}') else: rlines.append(f'self.{slotname} = [v if isinstance(v, {range_type_name})') indent = len(f'self.{slotname} = [') * ' ' rlines.append(f'{indent}else {range_type_name}(v) for v in self.{slotname}]') return '\n\t\t'.join(rlines)
[ "def", "gen_postinit", "(", "self", ",", "cls", ":", "ClassDefinition", ",", "slotname", ":", "str", ")", "->", "Optional", "[", "str", "]", ":", "rlines", ":", "List", "[", "str", "]", "=", "[", "]", "slot", "=", "self", ".", "schema", ".", "slots...
Generate python post init rules for slot in class
[ "Generate", "python", "post", "init", "rules", "for", "slot", "in", "class" ]
f379e28d5d4085e1115798c6cb28e5acc4dba8b4
https://github.com/biolink/biolink-model/blob/f379e28d5d4085e1115798c6cb28e5acc4dba8b4/metamodel/generators/pythongen.py#L158-L202
8,254
biolink/biolink-model
metamodel/generators/pythongen.py
PythonGenerator.all_slots_for
def all_slots_for(self, cls: ClassDefinition) -> List[SlotDefinitionName]: """ Return all slots for class cls """ if not cls.is_a: return cls.slots else: return [sn for sn in self.all_slots_for(self.schema.classes[cls.is_a]) if sn not in cls.slot_usage] \ + cls.slots
python
def all_slots_for(self, cls: ClassDefinition) -> List[SlotDefinitionName]: if not cls.is_a: return cls.slots else: return [sn for sn in self.all_slots_for(self.schema.classes[cls.is_a]) if sn not in cls.slot_usage] \ + cls.slots
[ "def", "all_slots_for", "(", "self", ",", "cls", ":", "ClassDefinition", ")", "->", "List", "[", "SlotDefinitionName", "]", ":", "if", "not", "cls", ".", "is_a", ":", "return", "cls", ".", "slots", "else", ":", "return", "[", "sn", "for", "sn", "in", ...
Return all slots for class cls
[ "Return", "all", "slots", "for", "class", "cls" ]
f379e28d5d4085e1115798c6cb28e5acc4dba8b4
https://github.com/biolink/biolink-model/blob/f379e28d5d4085e1115798c6cb28e5acc4dba8b4/metamodel/generators/pythongen.py#L242-L248
8,255
biolink/biolink-model
metamodel/generators/pythongen.py
PythonGenerator.range_type_name
def range_type_name(self, slot: SlotDefinition, containing_class_name: ClassDefinitionName) -> str: """ Generate the type name for the slot """ if slot.primary_key or slot.identifier: return self.python_name_for(containing_class_name) + camelcase(slot.name) if slot.range in self.schema.classes and not slot.inlined: class_key = self.key_name_for(cast(ClassDefinitionName, slot.range)) if class_key: return class_key return self.python_name_for(slot.range)
python
def range_type_name(self, slot: SlotDefinition, containing_class_name: ClassDefinitionName) -> str: if slot.primary_key or slot.identifier: return self.python_name_for(containing_class_name) + camelcase(slot.name) if slot.range in self.schema.classes and not slot.inlined: class_key = self.key_name_for(cast(ClassDefinitionName, slot.range)) if class_key: return class_key return self.python_name_for(slot.range)
[ "def", "range_type_name", "(", "self", ",", "slot", ":", "SlotDefinition", ",", "containing_class_name", ":", "ClassDefinitionName", ")", "->", "str", ":", "if", "slot", ".", "primary_key", "or", "slot", ".", "identifier", ":", "return", "self", ".", "python_n...
Generate the type name for the slot
[ "Generate", "the", "type", "name", "for", "the", "slot" ]
f379e28d5d4085e1115798c6cb28e5acc4dba8b4
https://github.com/biolink/biolink-model/blob/f379e28d5d4085e1115798c6cb28e5acc4dba8b4/metamodel/generators/pythongen.py#L255-L264
8,256
biolink/biolink-model
metamodel/generators/pythongen.py
PythonGenerator.forward_reference
def forward_reference(self, slot_range: str, owning_class: str) -> bool: """ Determine whether slot_range is a forward reference """ for cname in self.schema.classes: if cname == owning_class: return True # Occurs on or after elif cname == slot_range: return False # Occurs before return True
python
def forward_reference(self, slot_range: str, owning_class: str) -> bool: for cname in self.schema.classes: if cname == owning_class: return True # Occurs on or after elif cname == slot_range: return False # Occurs before return True
[ "def", "forward_reference", "(", "self", ",", "slot_range", ":", "str", ",", "owning_class", ":", "str", ")", "->", "bool", ":", "for", "cname", "in", "self", ".", "schema", ".", "classes", ":", "if", "cname", "==", "owning_class", ":", "return", "True",...
Determine whether slot_range is a forward reference
[ "Determine", "whether", "slot_range", "is", "a", "forward", "reference" ]
f379e28d5d4085e1115798c6cb28e5acc4dba8b4
https://github.com/biolink/biolink-model/blob/f379e28d5d4085e1115798c6cb28e5acc4dba8b4/metamodel/generators/pythongen.py#L266-L273
8,257
biolink/biolink-model
metamodel/utils/schemaloader.py
SchemaLoader.slot_definition_for
def slot_definition_for(self, slotname: SlotDefinitionName, cls: ClassDefinition) -> Optional[SlotDefinition]: """ Find the most proximal definition for slotname in the context of cls""" if cls.is_a: for sn in self.schema.classes[cls.is_a].slots: slot = self.schema.slots[sn] if slot.alias and slotname == slot.alias or slotname == slot.name: return slot for mixin in cls.mixins: for sn in self.schema.classes[mixin].slots: slot = self.schema.slots[sn] if slot.alias and slotname == slot.alias or slotname == slot.name: return slot if cls.is_a: defn = self.slot_definition_for(slotname, self.schema.classes[cls.is_a]) if defn: return defn for mixin in cls.mixins: defn = self.slot_definition_for(slotname, self.schema.classes[mixin]) if defn: return defn return None
python
def slot_definition_for(self, slotname: SlotDefinitionName, cls: ClassDefinition) -> Optional[SlotDefinition]: if cls.is_a: for sn in self.schema.classes[cls.is_a].slots: slot = self.schema.slots[sn] if slot.alias and slotname == slot.alias or slotname == slot.name: return slot for mixin in cls.mixins: for sn in self.schema.classes[mixin].slots: slot = self.schema.slots[sn] if slot.alias and slotname == slot.alias or slotname == slot.name: return slot if cls.is_a: defn = self.slot_definition_for(slotname, self.schema.classes[cls.is_a]) if defn: return defn for mixin in cls.mixins: defn = self.slot_definition_for(slotname, self.schema.classes[mixin]) if defn: return defn return None
[ "def", "slot_definition_for", "(", "self", ",", "slotname", ":", "SlotDefinitionName", ",", "cls", ":", "ClassDefinition", ")", "->", "Optional", "[", "SlotDefinition", "]", ":", "if", "cls", ".", "is_a", ":", "for", "sn", "in", "self", ".", "schema", ".",...
Find the most proximal definition for slotname in the context of cls
[ "Find", "the", "most", "proximal", "definition", "for", "slotname", "in", "the", "context", "of", "cls" ]
f379e28d5d4085e1115798c6cb28e5acc4dba8b4
https://github.com/biolink/biolink-model/blob/f379e28d5d4085e1115798c6cb28e5acc4dba8b4/metamodel/utils/schemaloader.py#L111-L131
8,258
biolink/biolink-model
metamodel/generators/yumlgen.py
cli
def cli(yamlfile, format, classes, directory): """ Generate a UML representation of a biolink model """ print(YumlGenerator(yamlfile, format).serialize(classes=classes, directory=directory), end="")
python
def cli(yamlfile, format, classes, directory): print(YumlGenerator(yamlfile, format).serialize(classes=classes, directory=directory), end="")
[ "def", "cli", "(", "yamlfile", ",", "format", ",", "classes", ",", "directory", ")", ":", "print", "(", "YumlGenerator", "(", "yamlfile", ",", "format", ")", ".", "serialize", "(", "classes", "=", "classes", ",", "directory", "=", "directory", ")", ",", ...
Generate a UML representation of a biolink model
[ "Generate", "a", "UML", "representation", "of", "a", "biolink", "model" ]
f379e28d5d4085e1115798c6cb28e5acc4dba8b4
https://github.com/biolink/biolink-model/blob/f379e28d5d4085e1115798c6cb28e5acc4dba8b4/metamodel/generators/yumlgen.py#L219-L221
8,259
biolink/biolink-model
metamodel/generators/yumlgen.py
YumlGenerator.class_associations
def class_associations(self, cn: ClassDefinitionName, must_render: bool=False) -> str: """ Emit all associations for a focus class. If none are specified, all classes are generated @param cn: Name of class to be emitted @param must_render: True means render even if this is a target (class is specifically requested) @return: YUML representation of the association """ # NOTE: YUML diagrams draw in the opposite order in which they are created, so we work from bottom to top and # from right to left assocs: List[str] = [] if cn not in self.associations_generated and (not self.focus_classes or cn in self.focus_classes): cls = self.schema.classes[cn] # Slots for slotname in self.filtered_cls_slots(cn, False)[::-1]: slot = self.schema.slots[slotname] if slot.range in self.schema.classes: assocs.append(self.class_box(cn) + (yuml_inline if slot.inlined else yuml_ref) + self.aliased_slot_name(slot) + self.prop_modifier(cls, slot) + self.cardinality(slot) + '>' + self.class_box(slot.range)) # Referencing slots if cn in self.synopsis.rangerefs: for slotname in sorted(self.synopsis.rangerefs[cn]): slot = self.schema.slots[slotname] if slot.domain in self.schema.classes and (slot.range != cls.name or must_render): assocs.append(self.class_box(slot.domain) + (yuml_inline if slot.inlined else yuml_ref) + self.aliased_slot_name(slot) + self.prop_modifier(cls, slot) + self.cardinality(slot) + '>' + self.class_box(cn)) # Mixins used in the class for mixin in cls.mixins: assocs.append(self.class_box(cn) + yuml_uses + self.class_box(mixin)) # Classes that use the class as a mixin if cls.name in self.synopsis.mixinrefs: for mixin in sorted(self.synopsis.mixinrefs[cls.name].classrefs, reverse=True): assocs.append(self.class_box(ClassDefinitionName(mixin)) + yuml_uses + self.class_box(cn)) # Classes that inject information if cn in self.synopsis.applytos: for injector in sorted(self.synopsis.applytos[cn].classrefs, reverse=True): assocs.append(self.class_box(cn) + yuml_injected + self.class_box(ClassDefinitionName(injector))) self.associations_generated.add(cn) # Children if cn in self.synopsis.isarefs: for is_a_cls in sorted(self.synopsis.isarefs[cn].classrefs, reverse=True): assocs.append(self.class_box(cn) + yuml_is_a + self.class_box(ClassDefinitionName(is_a_cls))) # Parent if cls.is_a: assocs.append(self.class_box(cls.is_a) + yuml_is_a + self.class_box(cn)) return ', '.join(assocs)
python
def class_associations(self, cn: ClassDefinitionName, must_render: bool=False) -> str: # NOTE: YUML diagrams draw in the opposite order in which they are created, so we work from bottom to top and # from right to left assocs: List[str] = [] if cn not in self.associations_generated and (not self.focus_classes or cn in self.focus_classes): cls = self.schema.classes[cn] # Slots for slotname in self.filtered_cls_slots(cn, False)[::-1]: slot = self.schema.slots[slotname] if slot.range in self.schema.classes: assocs.append(self.class_box(cn) + (yuml_inline if slot.inlined else yuml_ref) + self.aliased_slot_name(slot) + self.prop_modifier(cls, slot) + self.cardinality(slot) + '>' + self.class_box(slot.range)) # Referencing slots if cn in self.synopsis.rangerefs: for slotname in sorted(self.synopsis.rangerefs[cn]): slot = self.schema.slots[slotname] if slot.domain in self.schema.classes and (slot.range != cls.name or must_render): assocs.append(self.class_box(slot.domain) + (yuml_inline if slot.inlined else yuml_ref) + self.aliased_slot_name(slot) + self.prop_modifier(cls, slot) + self.cardinality(slot) + '>' + self.class_box(cn)) # Mixins used in the class for mixin in cls.mixins: assocs.append(self.class_box(cn) + yuml_uses + self.class_box(mixin)) # Classes that use the class as a mixin if cls.name in self.synopsis.mixinrefs: for mixin in sorted(self.synopsis.mixinrefs[cls.name].classrefs, reverse=True): assocs.append(self.class_box(ClassDefinitionName(mixin)) + yuml_uses + self.class_box(cn)) # Classes that inject information if cn in self.synopsis.applytos: for injector in sorted(self.synopsis.applytos[cn].classrefs, reverse=True): assocs.append(self.class_box(cn) + yuml_injected + self.class_box(ClassDefinitionName(injector))) self.associations_generated.add(cn) # Children if cn in self.synopsis.isarefs: for is_a_cls in sorted(self.synopsis.isarefs[cn].classrefs, reverse=True): assocs.append(self.class_box(cn) + yuml_is_a + self.class_box(ClassDefinitionName(is_a_cls))) # Parent if cls.is_a: assocs.append(self.class_box(cls.is_a) + yuml_is_a + self.class_box(cn)) return ', '.join(assocs)
[ "def", "class_associations", "(", "self", ",", "cn", ":", "ClassDefinitionName", ",", "must_render", ":", "bool", "=", "False", ")", "->", "str", ":", "# NOTE: YUML diagrams draw in the opposite order in which they are created, so we work from bottom to top and", "# from right ...
Emit all associations for a focus class. If none are specified, all classes are generated @param cn: Name of class to be emitted @param must_render: True means render even if this is a target (class is specifically requested) @return: YUML representation of the association
[ "Emit", "all", "associations", "for", "a", "focus", "class", ".", "If", "none", "are", "specified", "all", "classes", "are", "generated" ]
f379e28d5d4085e1115798c6cb28e5acc4dba8b4
https://github.com/biolink/biolink-model/blob/f379e28d5d4085e1115798c6cb28e5acc4dba8b4/metamodel/generators/yumlgen.py#L111-L165
8,260
biolink/biolink-model
metamodel/generators/yumlgen.py
YumlGenerator.filtered_cls_slots
def filtered_cls_slots(self, cn: ClassDefinitionName, all_slots: bool=True) \ -> List[SlotDefinitionName]: """ Return the set of slots associated with the class that meet the filter criteria. Slots will be returned in defining order, with class slots returned last @param cn: name of class to filter @param all_slots: True means include attributes @return: List of slot definitions """ rval = [] cls = self.schema.classes[cn] cls_slots = self.all_slots(cls, cls_slots_first=True) for slot in cls_slots: if all_slots or slot.range in self.schema.classes: rval.append(slot.name) return rval
python
def filtered_cls_slots(self, cn: ClassDefinitionName, all_slots: bool=True) \ -> List[SlotDefinitionName]: rval = [] cls = self.schema.classes[cn] cls_slots = self.all_slots(cls, cls_slots_first=True) for slot in cls_slots: if all_slots or slot.range in self.schema.classes: rval.append(slot.name) return rval
[ "def", "filtered_cls_slots", "(", "self", ",", "cn", ":", "ClassDefinitionName", ",", "all_slots", ":", "bool", "=", "True", ")", "->", "List", "[", "SlotDefinitionName", "]", ":", "rval", "=", "[", "]", "cls", "=", "self", ".", "schema", ".", "classes",...
Return the set of slots associated with the class that meet the filter criteria. Slots will be returned in defining order, with class slots returned last @param cn: name of class to filter @param all_slots: True means include attributes @return: List of slot definitions
[ "Return", "the", "set", "of", "slots", "associated", "with", "the", "class", "that", "meet", "the", "filter", "criteria", ".", "Slots", "will", "be", "returned", "in", "defining", "order", "with", "class", "slots", "returned", "last" ]
f379e28d5d4085e1115798c6cb28e5acc4dba8b4
https://github.com/biolink/biolink-model/blob/f379e28d5d4085e1115798c6cb28e5acc4dba8b4/metamodel/generators/yumlgen.py#L174-L190
8,261
biolink/biolink-model
metamodel/generators/shexgen.py
cli
def cli(yamlfile, format, output, collections): """ Generate a ShEx Schema for a biolink model """ print(ShExGenerator(yamlfile, format).serialize(output=output, collections=collections))
python
def cli(yamlfile, format, output, collections): print(ShExGenerator(yamlfile, format).serialize(output=output, collections=collections))
[ "def", "cli", "(", "yamlfile", ",", "format", ",", "output", ",", "collections", ")", ":", "print", "(", "ShExGenerator", "(", "yamlfile", ",", "format", ")", ".", "serialize", "(", "output", "=", "output", ",", "collections", "=", "collections", ")", ")...
Generate a ShEx Schema for a biolink model
[ "Generate", "a", "ShEx", "Schema", "for", "a", "biolink", "model" ]
f379e28d5d4085e1115798c6cb28e5acc4dba8b4
https://github.com/biolink/biolink-model/blob/f379e28d5d4085e1115798c6cb28e5acc4dba8b4/metamodel/generators/shexgen.py#L174-L176
8,262
biolink/biolink-model
metamodel/generators/shexgen.py
ShExGenerator.gen_multivalued_slot
def gen_multivalued_slot(self, target_name_base: str, target_type: IRIREF) -> IRIREF: """ Generate a shape that represents an RDF list of target_type @param target_name_base: @param target_type: @return: """ list_shape_id = IRIREF(target_name_base + "__List") if list_shape_id not in self.list_shapes: list_shape = Shape(id=list_shape_id, closed=True) list_shape.expression = EachOf() expressions = [TripleConstraint(predicate=RDF.first, valueExpr=target_type, min=0, max=1)] targets = ShapeOr() targets.shapeExprs = [(NodeConstraint(values=[RDF.nil])), list_shape_id] expressions.append(TripleConstraint(predicate=RDF.rest, valueExpr=targets)) list_shape.expression.expressions = expressions self.shapes.append(list_shape) self.list_shapes.append(list_shape_id) return list_shape_id
python
def gen_multivalued_slot(self, target_name_base: str, target_type: IRIREF) -> IRIREF: list_shape_id = IRIREF(target_name_base + "__List") if list_shape_id not in self.list_shapes: list_shape = Shape(id=list_shape_id, closed=True) list_shape.expression = EachOf() expressions = [TripleConstraint(predicate=RDF.first, valueExpr=target_type, min=0, max=1)] targets = ShapeOr() targets.shapeExprs = [(NodeConstraint(values=[RDF.nil])), list_shape_id] expressions.append(TripleConstraint(predicate=RDF.rest, valueExpr=targets)) list_shape.expression.expressions = expressions self.shapes.append(list_shape) self.list_shapes.append(list_shape_id) return list_shape_id
[ "def", "gen_multivalued_slot", "(", "self", ",", "target_name_base", ":", "str", ",", "target_type", ":", "IRIREF", ")", "->", "IRIREF", ":", "list_shape_id", "=", "IRIREF", "(", "target_name_base", "+", "\"__List\"", ")", "if", "list_shape_id", "not", "in", "...
Generate a shape that represents an RDF list of target_type @param target_name_base: @param target_type: @return:
[ "Generate", "a", "shape", "that", "represents", "an", "RDF", "list", "of", "target_type" ]
f379e28d5d4085e1115798c6cb28e5acc4dba8b4
https://github.com/biolink/biolink-model/blob/f379e28d5d4085e1115798c6cb28e5acc4dba8b4/metamodel/generators/shexgen.py#L119-L137
8,263
biolink/biolink-model
metamodel/generators/contextgen.py
ContextGenerator.add_prefix
def add_prefix(self, ncname: str) -> None: """ Look up ncname and add it to the prefix map if necessary @param ncname: name to add """ if ncname not in self.prefixmap: uri = cu.expand_uri(ncname + ':', self.curi_maps) if uri and '://' in uri: self.prefixmap[ncname] = uri else: print(f"Unrecognized prefix: {ncname}", file=sys.stderr) self.prefixmap[ncname] = f"http://example.org/unknown/{ncname}/"
python
def add_prefix(self, ncname: str) -> None: if ncname not in self.prefixmap: uri = cu.expand_uri(ncname + ':', self.curi_maps) if uri and '://' in uri: self.prefixmap[ncname] = uri else: print(f"Unrecognized prefix: {ncname}", file=sys.stderr) self.prefixmap[ncname] = f"http://example.org/unknown/{ncname}/"
[ "def", "add_prefix", "(", "self", ",", "ncname", ":", "str", ")", "->", "None", ":", "if", "ncname", "not", "in", "self", ".", "prefixmap", ":", "uri", "=", "cu", ".", "expand_uri", "(", "ncname", "+", "':'", ",", "self", ".", "curi_maps", ")", "if...
Look up ncname and add it to the prefix map if necessary @param ncname: name to add
[ "Look", "up", "ncname", "and", "add", "it", "to", "the", "prefix", "map", "if", "necessary" ]
f379e28d5d4085e1115798c6cb28e5acc4dba8b4
https://github.com/biolink/biolink-model/blob/f379e28d5d4085e1115798c6cb28e5acc4dba8b4/metamodel/generators/contextgen.py#L92-L103
8,264
biolink/biolink-model
metamodel/generators/contextgen.py
ContextGenerator.get_uri
def get_uri(self, ncname: str) -> Optional[str]: """ Get the URI associated with ncname @param ncname: """ uri = cu.expand_uri(ncname + ':', self.curi_maps) return uri if uri and uri.startswith('http') else None
python
def get_uri(self, ncname: str) -> Optional[str]: uri = cu.expand_uri(ncname + ':', self.curi_maps) return uri if uri and uri.startswith('http') else None
[ "def", "get_uri", "(", "self", ",", "ncname", ":", "str", ")", "->", "Optional", "[", "str", "]", ":", "uri", "=", "cu", ".", "expand_uri", "(", "ncname", "+", "':'", ",", "self", ".", "curi_maps", ")", "return", "uri", "if", "uri", "and", "uri", ...
Get the URI associated with ncname @param ncname:
[ "Get", "the", "URI", "associated", "with", "ncname" ]
f379e28d5d4085e1115798c6cb28e5acc4dba8b4
https://github.com/biolink/biolink-model/blob/f379e28d5d4085e1115798c6cb28e5acc4dba8b4/metamodel/generators/contextgen.py#L105-L111
8,265
biolink/biolink-model
metamodel/generators/contextgen.py
ContextGenerator.add_mappings
def add_mappings(self, defn: Definition, target: Dict) -> None: """ Process any mappings in defn, adding all of the mappings prefixes to the namespace map and add a link to the first mapping to the target @param defn: Class or Slot definition @param target: context target """ self.add_id_prefixes(defn) for mapping in defn.mappings: if '://' in mapping: target['@id'] = mapping else: if ':' not in mapping or len(mapping.split(':')) != 2: raise ValueError(f"Definition {defn.name} = unrecognized mapping: {mapping}") ns = mapping.split(':')[0] self.add_prefix(ns) target['@id'] = defn.mappings[0]
python
def add_mappings(self, defn: Definition, target: Dict) -> None: self.add_id_prefixes(defn) for mapping in defn.mappings: if '://' in mapping: target['@id'] = mapping else: if ':' not in mapping or len(mapping.split(':')) != 2: raise ValueError(f"Definition {defn.name} = unrecognized mapping: {mapping}") ns = mapping.split(':')[0] self.add_prefix(ns) target['@id'] = defn.mappings[0]
[ "def", "add_mappings", "(", "self", ",", "defn", ":", "Definition", ",", "target", ":", "Dict", ")", "->", "None", ":", "self", ".", "add_id_prefixes", "(", "defn", ")", "for", "mapping", "in", "defn", ".", "mappings", ":", "if", "'://'", "in", "mappin...
Process any mappings in defn, adding all of the mappings prefixes to the namespace map and add a link to the first mapping to the target @param defn: Class or Slot definition @param target: context target
[ "Process", "any", "mappings", "in", "defn", "adding", "all", "of", "the", "mappings", "prefixes", "to", "the", "namespace", "map", "and", "add", "a", "link", "to", "the", "first", "mapping", "to", "the", "target" ]
f379e28d5d4085e1115798c6cb28e5acc4dba8b4
https://github.com/biolink/biolink-model/blob/f379e28d5d4085e1115798c6cb28e5acc4dba8b4/metamodel/generators/contextgen.py#L117-L133
8,266
lepture/mistune-contrib
mistune_contrib/meta.py
parse
def parse(text): """Parse the given text into metadata and strip it for a Markdown parser. :param text: text to be parsed """ rv = {} m = META.match(text) while m: key = m.group(1) value = m.group(2) value = INDENTATION.sub('\n', value.strip()) rv[key] = value text = text[len(m.group(0)):] m = META.match(text) return rv, text
python
def parse(text): rv = {} m = META.match(text) while m: key = m.group(1) value = m.group(2) value = INDENTATION.sub('\n', value.strip()) rv[key] = value text = text[len(m.group(0)):] m = META.match(text) return rv, text
[ "def", "parse", "(", "text", ")", ":", "rv", "=", "{", "}", "m", "=", "META", ".", "match", "(", "text", ")", "while", "m", ":", "key", "=", "m", ".", "group", "(", "1", ")", "value", "=", "m", ".", "group", "(", "2", ")", "value", "=", "...
Parse the given text into metadata and strip it for a Markdown parser. :param text: text to be parsed
[ "Parse", "the", "given", "text", "into", "metadata", "and", "strip", "it", "for", "a", "Markdown", "parser", "." ]
3180edfc6b4477ead5ef7754a57907ae94080c24
https://github.com/lepture/mistune-contrib/blob/3180edfc6b4477ead5ef7754a57907ae94080c24/mistune_contrib/meta.py#L24-L40
8,267
gorakhargosh/pathtools
pathtools/path.py
get_dir_walker
def get_dir_walker(recursive, topdown=True, followlinks=False): """ Returns a recursive or a non-recursive directory walker. :param recursive: ``True`` produces a recursive walker; ``False`` produces a non-recursive walker. :returns: A walker function. """ if recursive: walk = partial(os.walk, topdown=topdown, followlinks=followlinks) else: def walk(path, topdown=topdown, followlinks=followlinks): try: yield next(os.walk(path, topdown=topdown, followlinks=followlinks)) except NameError: yield os.walk(path, topdown=topdown, followlinks=followlinks).next() #IGNORE:E1101 return walk
python
def get_dir_walker(recursive, topdown=True, followlinks=False): if recursive: walk = partial(os.walk, topdown=topdown, followlinks=followlinks) else: def walk(path, topdown=topdown, followlinks=followlinks): try: yield next(os.walk(path, topdown=topdown, followlinks=followlinks)) except NameError: yield os.walk(path, topdown=topdown, followlinks=followlinks).next() #IGNORE:E1101 return walk
[ "def", "get_dir_walker", "(", "recursive", ",", "topdown", "=", "True", ",", "followlinks", "=", "False", ")", ":", "if", "recursive", ":", "walk", "=", "partial", "(", "os", ".", "walk", ",", "topdown", "=", "topdown", ",", "followlinks", "=", "followli...
Returns a recursive or a non-recursive directory walker. :param recursive: ``True`` produces a recursive walker; ``False`` produces a non-recursive walker. :returns: A walker function.
[ "Returns", "a", "recursive", "or", "a", "non", "-", "recursive", "directory", "walker", "." ]
a3522fc61b00ee2d992ca375c600513bfb9020e9
https://github.com/gorakhargosh/pathtools/blob/a3522fc61b00ee2d992ca375c600513bfb9020e9/pathtools/path.py#L58-L76
8,268
gorakhargosh/pathtools
pathtools/path.py
listdir
def listdir(dir_pathname, recursive=True, topdown=True, followlinks=False): """ Enlists all items using their absolute paths in a directory, optionally recursively. :param dir_pathname: The directory to traverse. :param recursive: ``True`` for walking recursively through the directory tree; ``False`` otherwise. :param topdown: Please see the documentation for :func:`os.walk` :param followlinks: Please see the documentation for :func:`os.walk` """ for root, dirnames, filenames\ in walk(dir_pathname, recursive, topdown, followlinks): for dirname in dirnames: yield absolute_path(os.path.join(root, dirname)) for filename in filenames: yield absolute_path(os.path.join(root, filename))
python
def listdir(dir_pathname, recursive=True, topdown=True, followlinks=False): for root, dirnames, filenames\ in walk(dir_pathname, recursive, topdown, followlinks): for dirname in dirnames: yield absolute_path(os.path.join(root, dirname)) for filename in filenames: yield absolute_path(os.path.join(root, filename))
[ "def", "listdir", "(", "dir_pathname", ",", "recursive", "=", "True", ",", "topdown", "=", "True", ",", "followlinks", "=", "False", ")", ":", "for", "root", ",", "dirnames", ",", "filenames", "in", "walk", "(", "dir_pathname", ",", "recursive", ",", "to...
Enlists all items using their absolute paths in a directory, optionally recursively. :param dir_pathname: The directory to traverse. :param recursive: ``True`` for walking recursively through the directory tree; ``False`` otherwise. :param topdown: Please see the documentation for :func:`os.walk` :param followlinks: Please see the documentation for :func:`os.walk`
[ "Enlists", "all", "items", "using", "their", "absolute", "paths", "in", "a", "directory", "optionally", "recursively", "." ]
a3522fc61b00ee2d992ca375c600513bfb9020e9
https://github.com/gorakhargosh/pathtools/blob/a3522fc61b00ee2d992ca375c600513bfb9020e9/pathtools/path.py#L99-L122
8,269
gorakhargosh/pathtools
pathtools/path.py
list_directories
def list_directories(dir_pathname, recursive=True, topdown=True, followlinks=False): """ Enlists all the directories using their absolute paths within the specified directory, optionally recursively. :param dir_pathname: The directory to traverse. :param recursive: ``True`` for walking recursively through the directory tree; ``False`` otherwise. :param topdown: Please see the documentation for :func:`os.walk` :param followlinks: Please see the documentation for :func:`os.walk` """ for root, dirnames, filenames\ in walk(dir_pathname, recursive, topdown, followlinks): for dirname in dirnames: yield absolute_path(os.path.join(root, dirname))
python
def list_directories(dir_pathname, recursive=True, topdown=True, followlinks=False): for root, dirnames, filenames\ in walk(dir_pathname, recursive, topdown, followlinks): for dirname in dirnames: yield absolute_path(os.path.join(root, dirname))
[ "def", "list_directories", "(", "dir_pathname", ",", "recursive", "=", "True", ",", "topdown", "=", "True", ",", "followlinks", "=", "False", ")", ":", "for", "root", ",", "dirnames", ",", "filenames", "in", "walk", "(", "dir_pathname", ",", "recursive", "...
Enlists all the directories using their absolute paths within the specified directory, optionally recursively. :param dir_pathname: The directory to traverse. :param recursive: ``True`` for walking recursively through the directory tree; ``False`` otherwise. :param topdown: Please see the documentation for :func:`os.walk` :param followlinks: Please see the documentation for :func:`os.walk`
[ "Enlists", "all", "the", "directories", "using", "their", "absolute", "paths", "within", "the", "specified", "directory", "optionally", "recursively", "." ]
a3522fc61b00ee2d992ca375c600513bfb9020e9
https://github.com/gorakhargosh/pathtools/blob/a3522fc61b00ee2d992ca375c600513bfb9020e9/pathtools/path.py#L125-L146
8,270
gorakhargosh/pathtools
pathtools/path.py
list_files
def list_files(dir_pathname, recursive=True, topdown=True, followlinks=False): """ Enlists all the files using their absolute paths within the specified directory, optionally recursively. :param dir_pathname: The directory to traverse. :param recursive: ``True`` for walking recursively through the directory tree; ``False`` otherwise. :param topdown: Please see the documentation for :func:`os.walk` :param followlinks: Please see the documentation for :func:`os.walk` """ for root, dirnames, filenames\ in walk(dir_pathname, recursive, topdown, followlinks): for filename in filenames: yield absolute_path(os.path.join(root, filename))
python
def list_files(dir_pathname, recursive=True, topdown=True, followlinks=False): for root, dirnames, filenames\ in walk(dir_pathname, recursive, topdown, followlinks): for filename in filenames: yield absolute_path(os.path.join(root, filename))
[ "def", "list_files", "(", "dir_pathname", ",", "recursive", "=", "True", ",", "topdown", "=", "True", ",", "followlinks", "=", "False", ")", ":", "for", "root", ",", "dirnames", ",", "filenames", "in", "walk", "(", "dir_pathname", ",", "recursive", ",", ...
Enlists all the files using their absolute paths within the specified directory, optionally recursively. :param dir_pathname: The directory to traverse. :param recursive: ``True`` for walking recursively through the directory tree; ``False`` otherwise. :param topdown: Please see the documentation for :func:`os.walk` :param followlinks: Please see the documentation for :func:`os.walk`
[ "Enlists", "all", "the", "files", "using", "their", "absolute", "paths", "within", "the", "specified", "directory", "optionally", "recursively", "." ]
a3522fc61b00ee2d992ca375c600513bfb9020e9
https://github.com/gorakhargosh/pathtools/blob/a3522fc61b00ee2d992ca375c600513bfb9020e9/pathtools/path.py#L149-L170
8,271
gorakhargosh/pathtools
pathtools/patterns.py
match_path_against
def match_path_against(pathname, patterns, case_sensitive=True): """ Determines whether the pathname matches any of the given wildcard patterns, optionally ignoring the case of the pathname and patterns. :param pathname: A path name that will be matched against a wildcard pattern. :param patterns: A list of wildcard patterns to match_path the filename against. :param case_sensitive: ``True`` if the matching should be case-sensitive; ``False`` otherwise. :returns: ``True`` if the pattern matches; ``False`` otherwise. Doctests:: >>> match_path_against("/home/username/foobar/blah.py", ["*.py", "*.txt"], False) True >>> match_path_against("/home/username/foobar/blah.py", ["*.PY", "*.txt"], True) False >>> match_path_against("/home/username/foobar/blah.py", ["*.PY", "*.txt"], False) True >>> match_path_against("C:\\windows\\blah\\BLAH.PY", ["*.py", "*.txt"], True) False >>> match_path_against("C:\\windows\\blah\\BLAH.PY", ["*.py", "*.txt"], False) True """ if case_sensitive: match_func = fnmatchcase pattern_transform_func = (lambda w: w) else: match_func = fnmatch pathname = pathname.lower() pattern_transform_func = _string_lower for pattern in set(patterns): pattern = pattern_transform_func(pattern) if match_func(pathname, pattern): return True return False
python
def match_path_against(pathname, patterns, case_sensitive=True): if case_sensitive: match_func = fnmatchcase pattern_transform_func = (lambda w: w) else: match_func = fnmatch pathname = pathname.lower() pattern_transform_func = _string_lower for pattern in set(patterns): pattern = pattern_transform_func(pattern) if match_func(pathname, pattern): return True return False
[ "def", "match_path_against", "(", "pathname", ",", "patterns", ",", "case_sensitive", "=", "True", ")", ":", "if", "case_sensitive", ":", "match_func", "=", "fnmatchcase", "pattern_transform_func", "=", "(", "lambda", "w", ":", "w", ")", "else", ":", "match_fu...
Determines whether the pathname matches any of the given wildcard patterns, optionally ignoring the case of the pathname and patterns. :param pathname: A path name that will be matched against a wildcard pattern. :param patterns: A list of wildcard patterns to match_path the filename against. :param case_sensitive: ``True`` if the matching should be case-sensitive; ``False`` otherwise. :returns: ``True`` if the pattern matches; ``False`` otherwise. Doctests:: >>> match_path_against("/home/username/foobar/blah.py", ["*.py", "*.txt"], False) True >>> match_path_against("/home/username/foobar/blah.py", ["*.PY", "*.txt"], True) False >>> match_path_against("/home/username/foobar/blah.py", ["*.PY", "*.txt"], False) True >>> match_path_against("C:\\windows\\blah\\BLAH.PY", ["*.py", "*.txt"], True) False >>> match_path_against("C:\\windows\\blah\\BLAH.PY", ["*.py", "*.txt"], False) True
[ "Determines", "whether", "the", "pathname", "matches", "any", "of", "the", "given", "wildcard", "patterns", "optionally", "ignoring", "the", "case", "of", "the", "pathname", "and", "patterns", "." ]
a3522fc61b00ee2d992ca375c600513bfb9020e9
https://github.com/gorakhargosh/pathtools/blob/a3522fc61b00ee2d992ca375c600513bfb9020e9/pathtools/patterns.py#L58-L95
8,272
gorakhargosh/pathtools
pathtools/patterns.py
match_path
def match_path(pathname, included_patterns=None, excluded_patterns=None, case_sensitive=True): """ Matches a pathname against a set of acceptable and ignored patterns. :param pathname: A pathname which will be matched against a pattern. :param included_patterns: Allow filenames matching wildcard patterns specified in this list. If no pattern is specified, the function treats the pathname as a match_path. :param excluded_patterns: Ignores filenames matching wildcard patterns specified in this list. If no pattern is specified, the function treats the pathname as a match_path. :param case_sensitive: ``True`` if matching should be case-sensitive; ``False`` otherwise. :returns: ``True`` if the pathname matches; ``False`` otherwise. :raises: ValueError if included patterns and excluded patterns contain the same pattern. Doctests:: >>> match_path("/Users/gorakhargosh/foobar.py") True >>> match_path("/Users/gorakhargosh/foobar.py", case_sensitive=False) True >>> match_path("/users/gorakhargosh/foobar.py", ["*.py"], ["*.PY"], True) True >>> match_path("/users/gorakhargosh/FOOBAR.PY", ["*.py"], ["*.PY"], True) False >>> match_path("/users/gorakhargosh/foobar/", ["*.py"], ["*.txt"], False) False >>> match_path("/users/gorakhargosh/FOOBAR.PY", ["*.py"], ["*.PY"], False) Traceback (most recent call last): ... ValueError: conflicting patterns `set(['*.py'])` included and excluded """ included = ["*"] if included_patterns is None else included_patterns excluded = [] if excluded_patterns is None else excluded_patterns return _match_path(pathname, included, excluded, case_sensitive)
python
def match_path(pathname, included_patterns=None, excluded_patterns=None, case_sensitive=True): included = ["*"] if included_patterns is None else included_patterns excluded = [] if excluded_patterns is None else excluded_patterns return _match_path(pathname, included, excluded, case_sensitive)
[ "def", "match_path", "(", "pathname", ",", "included_patterns", "=", "None", ",", "excluded_patterns", "=", "None", ",", "case_sensitive", "=", "True", ")", ":", "included", "=", "[", "\"*\"", "]", "if", "included_patterns", "is", "None", "else", "included_pat...
Matches a pathname against a set of acceptable and ignored patterns. :param pathname: A pathname which will be matched against a pattern. :param included_patterns: Allow filenames matching wildcard patterns specified in this list. If no pattern is specified, the function treats the pathname as a match_path. :param excluded_patterns: Ignores filenames matching wildcard patterns specified in this list. If no pattern is specified, the function treats the pathname as a match_path. :param case_sensitive: ``True`` if matching should be case-sensitive; ``False`` otherwise. :returns: ``True`` if the pathname matches; ``False`` otherwise. :raises: ValueError if included patterns and excluded patterns contain the same pattern. Doctests:: >>> match_path("/Users/gorakhargosh/foobar.py") True >>> match_path("/Users/gorakhargosh/foobar.py", case_sensitive=False) True >>> match_path("/users/gorakhargosh/foobar.py", ["*.py"], ["*.PY"], True) True >>> match_path("/users/gorakhargosh/FOOBAR.PY", ["*.py"], ["*.PY"], True) False >>> match_path("/users/gorakhargosh/foobar/", ["*.py"], ["*.txt"], False) False >>> match_path("/users/gorakhargosh/FOOBAR.PY", ["*.py"], ["*.PY"], False) Traceback (most recent call last): ... ValueError: conflicting patterns `set(['*.py'])` included and excluded
[ "Matches", "a", "pathname", "against", "a", "set", "of", "acceptable", "and", "ignored", "patterns", "." ]
a3522fc61b00ee2d992ca375c600513bfb9020e9
https://github.com/gorakhargosh/pathtools/blob/a3522fc61b00ee2d992ca375c600513bfb9020e9/pathtools/patterns.py#L131-L174
8,273
gorakhargosh/pathtools
pathtools/patterns.py
match_any_paths
def match_any_paths(pathnames, included_patterns=None, excluded_patterns=None, case_sensitive=True): """ Matches from a set of paths based on acceptable patterns and ignorable patterns. :param pathnames: A list of path names that will be filtered based on matching and ignored patterns. :param included_patterns: Allow filenames matching wildcard patterns specified in this list. If no pattern list is specified, ["*"] is used as the default pattern, which matches all files. :param excluded_patterns: Ignores filenames matching wildcard patterns specified in this list. If no pattern list is specified, no files are ignored. :param case_sensitive: ``True`` if matching should be case-sensitive; ``False`` otherwise. :returns: ``True`` if any of the paths matches; ``False`` otherwise. Doctests:: >>> pathnames = set(["/users/gorakhargosh/foobar.py", "/var/cache/pdnsd.status", "/etc/pdnsd.conf", "/usr/local/bin/python"]) >>> match_any_paths(pathnames) True >>> match_any_paths(pathnames, case_sensitive=False) True >>> match_any_paths(pathnames, ["*.py", "*.conf"], ["*.status"], case_sensitive=True) True >>> match_any_paths(pathnames, ["*.txt"], case_sensitive=False) False >>> match_any_paths(pathnames, ["*.txt"], case_sensitive=True) False """ included = ["*"] if included_patterns is None else included_patterns excluded = [] if excluded_patterns is None else excluded_patterns for pathname in pathnames: # We don't call the public match_path because it checks arguments # and sets default values if none are found. We're already doing that # above. if _match_path(pathname, included, excluded, case_sensitive): return True return False
python
def match_any_paths(pathnames, included_patterns=None, excluded_patterns=None, case_sensitive=True): included = ["*"] if included_patterns is None else included_patterns excluded = [] if excluded_patterns is None else excluded_patterns for pathname in pathnames: # We don't call the public match_path because it checks arguments # and sets default values if none are found. We're already doing that # above. if _match_path(pathname, included, excluded, case_sensitive): return True return False
[ "def", "match_any_paths", "(", "pathnames", ",", "included_patterns", "=", "None", ",", "excluded_patterns", "=", "None", ",", "case_sensitive", "=", "True", ")", ":", "included", "=", "[", "\"*\"", "]", "if", "included_patterns", "is", "None", "else", "includ...
Matches from a set of paths based on acceptable patterns and ignorable patterns. :param pathnames: A list of path names that will be filtered based on matching and ignored patterns. :param included_patterns: Allow filenames matching wildcard patterns specified in this list. If no pattern list is specified, ["*"] is used as the default pattern, which matches all files. :param excluded_patterns: Ignores filenames matching wildcard patterns specified in this list. If no pattern list is specified, no files are ignored. :param case_sensitive: ``True`` if matching should be case-sensitive; ``False`` otherwise. :returns: ``True`` if any of the paths matches; ``False`` otherwise. Doctests:: >>> pathnames = set(["/users/gorakhargosh/foobar.py", "/var/cache/pdnsd.status", "/etc/pdnsd.conf", "/usr/local/bin/python"]) >>> match_any_paths(pathnames) True >>> match_any_paths(pathnames, case_sensitive=False) True >>> match_any_paths(pathnames, ["*.py", "*.conf"], ["*.status"], case_sensitive=True) True >>> match_any_paths(pathnames, ["*.txt"], case_sensitive=False) False >>> match_any_paths(pathnames, ["*.txt"], case_sensitive=True) False
[ "Matches", "from", "a", "set", "of", "paths", "based", "on", "acceptable", "patterns", "and", "ignorable", "patterns", "." ]
a3522fc61b00ee2d992ca375c600513bfb9020e9
https://github.com/gorakhargosh/pathtools/blob/a3522fc61b00ee2d992ca375c600513bfb9020e9/pathtools/patterns.py#L220-L265
8,274
gorakhargosh/pathtools
scripts/nosy.py
match_patterns
def match_patterns(pathname, patterns): """Returns ``True`` if the pathname matches any of the given patterns.""" for pattern in patterns: if fnmatch(pathname, pattern): return True return False
python
def match_patterns(pathname, patterns): for pattern in patterns: if fnmatch(pathname, pattern): return True return False
[ "def", "match_patterns", "(", "pathname", ",", "patterns", ")", ":", "for", "pattern", "in", "patterns", ":", "if", "fnmatch", "(", "pathname", ",", "pattern", ")", ":", "return", "True", "return", "False" ]
Returns ``True`` if the pathname matches any of the given patterns.
[ "Returns", "True", "if", "the", "pathname", "matches", "any", "of", "the", "given", "patterns", "." ]
a3522fc61b00ee2d992ca375c600513bfb9020e9
https://github.com/gorakhargosh/pathtools/blob/a3522fc61b00ee2d992ca375c600513bfb9020e9/scripts/nosy.py#L39-L44
8,275
evansloan/sports.py
sports/teams.py
_get_team_info_raw
def _get_team_info_raw(soup, base_url, team_pattern, team, sport): """ Parses through html page to gather raw data about team :param soup: BeautifulSoup object containing html to be parsed :param base_url: Pre-formatted url that is formatted depending on sport :param team_pattern: Compiled regex pattern of team name/city :param team: Name of the team that is being searched for :param sport: Sport that is being searched for :return: List containing raw data of team """ team_url = None team_name = None for link in soup.find_all('a'): if re.search(team_pattern, link.string): team_name = link.string team_url = base_url.replace('/teams/', link['href']) if team_url is not None and team_name is not None: team_soup = BeautifulSoup(requests.get(team_url).content, 'html.parser') team_info_raw = team_soup.find('div', id='meta').contents[3].get_text().split('\n') team_info_raw = [x.replace('\t', '') for x in team_info_raw] team_info_raw = [x.strip() for x in team_info_raw if x != ''] team_info_raw[0] = team_name return team_info_raw else: raise errors.TeamNotFoundError(sport, team)
python
def _get_team_info_raw(soup, base_url, team_pattern, team, sport): team_url = None team_name = None for link in soup.find_all('a'): if re.search(team_pattern, link.string): team_name = link.string team_url = base_url.replace('/teams/', link['href']) if team_url is not None and team_name is not None: team_soup = BeautifulSoup(requests.get(team_url).content, 'html.parser') team_info_raw = team_soup.find('div', id='meta').contents[3].get_text().split('\n') team_info_raw = [x.replace('\t', '') for x in team_info_raw] team_info_raw = [x.strip() for x in team_info_raw if x != ''] team_info_raw[0] = team_name return team_info_raw else: raise errors.TeamNotFoundError(sport, team)
[ "def", "_get_team_info_raw", "(", "soup", ",", "base_url", ",", "team_pattern", ",", "team", ",", "sport", ")", ":", "team_url", "=", "None", "team_name", "=", "None", "for", "link", "in", "soup", ".", "find_all", "(", "'a'", ")", ":", "if", "re", ".",...
Parses through html page to gather raw data about team :param soup: BeautifulSoup object containing html to be parsed :param base_url: Pre-formatted url that is formatted depending on sport :param team_pattern: Compiled regex pattern of team name/city :param team: Name of the team that is being searched for :param sport: Sport that is being searched for :return: List containing raw data of team
[ "Parses", "through", "html", "page", "to", "gather", "raw", "data", "about", "team" ]
852cd1e439f2de46ef68357e43f5f55b2e16d2b3
https://github.com/evansloan/sports.py/blob/852cd1e439f2de46ef68357e43f5f55b2e16d2b3/sports/teams.py#L124-L150
8,276
evansloan/sports.py
sports/scores.py
_parse_match_info
def _parse_match_info(match, soccer=False): """ Parse string containing info of a specific match :param match: Match data :type match: string :param soccer: Set to true if match contains soccer data, defaults to False :type soccer: bool, optional :return: Dictionary containing match information :rtype: dict """ match_info = {} i_open = match.index('(') i_close = match.index(')') match_info['league'] = match[i_open + 1:i_close].strip() match = match[i_close + 1:] i_vs = match.index('vs') i_colon = match.index(':') match_info['home_team'] = match[0:i_vs].replace('#', ' ').strip() match_info['away_team'] = match[i_vs + 2:i_colon].replace('#', ' ').strip() match = match[i_colon:] if soccer: i_hyph = match.index('-') match_info['match_score'] = match[1:i_hyph + 2].strip() match = match[i_hyph + 1:] i_hyph = match.index('-') match_info['match_time'] = match[i_hyph + 1:].strip() else: match_info['match_score'] = match[1:].strip() return match_info
python
def _parse_match_info(match, soccer=False): match_info = {} i_open = match.index('(') i_close = match.index(')') match_info['league'] = match[i_open + 1:i_close].strip() match = match[i_close + 1:] i_vs = match.index('vs') i_colon = match.index(':') match_info['home_team'] = match[0:i_vs].replace('#', ' ').strip() match_info['away_team'] = match[i_vs + 2:i_colon].replace('#', ' ').strip() match = match[i_colon:] if soccer: i_hyph = match.index('-') match_info['match_score'] = match[1:i_hyph + 2].strip() match = match[i_hyph + 1:] i_hyph = match.index('-') match_info['match_time'] = match[i_hyph + 1:].strip() else: match_info['match_score'] = match[1:].strip() return match_info
[ "def", "_parse_match_info", "(", "match", ",", "soccer", "=", "False", ")", ":", "match_info", "=", "{", "}", "i_open", "=", "match", ".", "index", "(", "'('", ")", "i_close", "=", "match", ".", "index", "(", "')'", ")", "match_info", "[", "'league'", ...
Parse string containing info of a specific match :param match: Match data :type match: string :param soccer: Set to true if match contains soccer data, defaults to False :type soccer: bool, optional :return: Dictionary containing match information :rtype: dict
[ "Parse", "string", "containing", "info", "of", "a", "specific", "match" ]
852cd1e439f2de46ef68357e43f5f55b2e16d2b3
https://github.com/evansloan/sports.py/blob/852cd1e439f2de46ef68357e43f5f55b2e16d2b3/sports/scores.py#L67-L100
8,277
evansloan/sports.py
sports/scores.py
get_sport
def get_sport(sport): """ Get live scores for all matches in a particular sport :param sport: the sport being played :type sport: string :return: List containing Match objects :rtype: list """ sport = sport.lower() data = _request_xml(sport) matches = [] for match in data: if sport == constants.SOCCER: desc = match.find('description').text match_info = _parse_match_info(desc, soccer=True) else: desc = match.find('title').text match_info = _parse_match_info(desc) match_info['match_time'] = match.find('description').text match_info['match_date'] = match.find('pubDate').text match_info['match_link'] = match.find('guid').text matches.append(Match(sport, match_info)) return matches
python
def get_sport(sport): sport = sport.lower() data = _request_xml(sport) matches = [] for match in data: if sport == constants.SOCCER: desc = match.find('description').text match_info = _parse_match_info(desc, soccer=True) else: desc = match.find('title').text match_info = _parse_match_info(desc) match_info['match_time'] = match.find('description').text match_info['match_date'] = match.find('pubDate').text match_info['match_link'] = match.find('guid').text matches.append(Match(sport, match_info)) return matches
[ "def", "get_sport", "(", "sport", ")", ":", "sport", "=", "sport", ".", "lower", "(", ")", "data", "=", "_request_xml", "(", "sport", ")", "matches", "=", "[", "]", "for", "match", "in", "data", ":", "if", "sport", "==", "constants", ".", "SOCCER", ...
Get live scores for all matches in a particular sport :param sport: the sport being played :type sport: string :return: List containing Match objects :rtype: list
[ "Get", "live", "scores", "for", "all", "matches", "in", "a", "particular", "sport" ]
852cd1e439f2de46ef68357e43f5f55b2e16d2b3
https://github.com/evansloan/sports.py/blob/852cd1e439f2de46ef68357e43f5f55b2e16d2b3/sports/scores.py#L103-L130
8,278
evansloan/sports.py
sports/scores.py
get_match
def get_match(sport, team1, team2): """ Get live scores for a single match :param sport: the sport being played :type sport: string :param team1: first team participating in the match :ttype team1: string :param team2: second team participating in the match :type team2: string :return: A specific match :rtype: Match """ sport = sport.lower() team1_pattern = re.compile(team1, re.I) team2_pattern = re.compile(team2, re.I) matches = get_sport(sport) for match in matches: if re.search(team1_pattern, match.home_team) or re.search(team1_pattern, match.away_team) \ and re.search(team2_pattern, match.away_team) or re.search(team2_pattern, match.home_team): return match raise errors.MatchError(sport, [team1, team2])
python
def get_match(sport, team1, team2): sport = sport.lower() team1_pattern = re.compile(team1, re.I) team2_pattern = re.compile(team2, re.I) matches = get_sport(sport) for match in matches: if re.search(team1_pattern, match.home_team) or re.search(team1_pattern, match.away_team) \ and re.search(team2_pattern, match.away_team) or re.search(team2_pattern, match.home_team): return match raise errors.MatchError(sport, [team1, team2])
[ "def", "get_match", "(", "sport", ",", "team1", ",", "team2", ")", ":", "sport", "=", "sport", ".", "lower", "(", ")", "team1_pattern", "=", "re", ".", "compile", "(", "team1", ",", "re", ".", "I", ")", "team2_pattern", "=", "re", ".", "compile", "...
Get live scores for a single match :param sport: the sport being played :type sport: string :param team1: first team participating in the match :ttype team1: string :param team2: second team participating in the match :type team2: string :return: A specific match :rtype: Match
[ "Get", "live", "scores", "for", "a", "single", "match" ]
852cd1e439f2de46ef68357e43f5f55b2e16d2b3
https://github.com/evansloan/sports.py/blob/852cd1e439f2de46ef68357e43f5f55b2e16d2b3/sports/scores.py#L133-L156
8,279
bitlabstudio/django-influxdb-metrics
influxdb_metrics/models.py
user_post_delete_handler
def user_post_delete_handler(sender, **kwargs): """Sends a metric to InfluxDB when a User object is deleted.""" total = get_user_model().objects.all().count() data = [{ 'measurement': 'django_auth_user_delete', 'tags': {'host': settings.INFLUXDB_TAGS_HOST, }, 'fields': {'value': 1, }, 'time': timezone.now().isoformat(), }] write_points(data) data = [{ 'measurement': 'django_auth_user_count', 'tags': {'host': settings.INFLUXDB_TAGS_HOST, }, 'fields': {'value': total, }, 'time': timezone.now().isoformat(), }] write_points(data)
python
def user_post_delete_handler(sender, **kwargs): total = get_user_model().objects.all().count() data = [{ 'measurement': 'django_auth_user_delete', 'tags': {'host': settings.INFLUXDB_TAGS_HOST, }, 'fields': {'value': 1, }, 'time': timezone.now().isoformat(), }] write_points(data) data = [{ 'measurement': 'django_auth_user_count', 'tags': {'host': settings.INFLUXDB_TAGS_HOST, }, 'fields': {'value': total, }, 'time': timezone.now().isoformat(), }] write_points(data)
[ "def", "user_post_delete_handler", "(", "sender", ",", "*", "*", "kwargs", ")", ":", "total", "=", "get_user_model", "(", ")", ".", "objects", ".", "all", "(", ")", ".", "count", "(", ")", "data", "=", "[", "{", "'measurement'", ":", "'django_auth_user_d...
Sends a metric to InfluxDB when a User object is deleted.
[ "Sends", "a", "metric", "to", "InfluxDB", "when", "a", "User", "object", "is", "deleted", "." ]
c9f368e28a6072813454b6b549b4afa64aad778a
https://github.com/bitlabstudio/django-influxdb-metrics/blob/c9f368e28a6072813454b6b549b4afa64aad778a/influxdb_metrics/models.py#L23-L40
8,280
bitlabstudio/django-influxdb-metrics
influxdb_metrics/models.py
user_post_save_handler
def user_post_save_handler(**kwargs): """Sends a metric to InfluxDB when a new User object is created.""" if kwargs.get('created'): total = get_user_model().objects.all().count() data = [{ 'measurement': 'django_auth_user_create', 'tags': {'host': settings.INFLUXDB_TAGS_HOST, }, 'fields': {'value': 1, }, 'time': timezone.now().isoformat(), }] write_points(data) data = [{ 'measurement': 'django_auth_user_count', 'tags': {'host': settings.INFLUXDB_TAGS_HOST, }, 'fields': {'value': total, }, 'time': timezone.now().isoformat(), }] write_points(data)
python
def user_post_save_handler(**kwargs): if kwargs.get('created'): total = get_user_model().objects.all().count() data = [{ 'measurement': 'django_auth_user_create', 'tags': {'host': settings.INFLUXDB_TAGS_HOST, }, 'fields': {'value': 1, }, 'time': timezone.now().isoformat(), }] write_points(data) data = [{ 'measurement': 'django_auth_user_count', 'tags': {'host': settings.INFLUXDB_TAGS_HOST, }, 'fields': {'value': total, }, 'time': timezone.now().isoformat(), }] write_points(data)
[ "def", "user_post_save_handler", "(", "*", "*", "kwargs", ")", ":", "if", "kwargs", ".", "get", "(", "'created'", ")", ":", "total", "=", "get_user_model", "(", ")", ".", "objects", ".", "all", "(", ")", ".", "count", "(", ")", "data", "=", "[", "{...
Sends a metric to InfluxDB when a new User object is created.
[ "Sends", "a", "metric", "to", "InfluxDB", "when", "a", "new", "User", "object", "is", "created", "." ]
c9f368e28a6072813454b6b549b4afa64aad778a
https://github.com/bitlabstudio/django-influxdb-metrics/blob/c9f368e28a6072813454b6b549b4afa64aad778a/influxdb_metrics/models.py#L46-L64
8,281
bitlabstudio/django-influxdb-metrics
influxdb_metrics/utils.py
write_points
def write_points(data, force_disable_threading=False): """ Writes a series to influxdb. :param data: Array of dicts, as required by https://github.com/influxdb/influxdb-python :param force_disable_threading: When being called from the Celery task, we set this to `True` so that the user doesn't accidentally use Celery and threading at the same time. """ if getattr(settings, 'INFLUXDB_DISABLED', False): return client = get_client() use_threading = getattr(settings, 'INFLUXDB_USE_THREADING', False) if force_disable_threading: use_threading = False if use_threading is True: thread = Thread(target=process_points, args=(client, data, )) thread.start() else: process_points(client, data)
python
def write_points(data, force_disable_threading=False): if getattr(settings, 'INFLUXDB_DISABLED', False): return client = get_client() use_threading = getattr(settings, 'INFLUXDB_USE_THREADING', False) if force_disable_threading: use_threading = False if use_threading is True: thread = Thread(target=process_points, args=(client, data, )) thread.start() else: process_points(client, data)
[ "def", "write_points", "(", "data", ",", "force_disable_threading", "=", "False", ")", ":", "if", "getattr", "(", "settings", ",", "'INFLUXDB_DISABLED'", ",", "False", ")", ":", "return", "client", "=", "get_client", "(", ")", "use_threading", "=", "getattr", ...
Writes a series to influxdb. :param data: Array of dicts, as required by https://github.com/influxdb/influxdb-python :param force_disable_threading: When being called from the Celery task, we set this to `True` so that the user doesn't accidentally use Celery and threading at the same time.
[ "Writes", "a", "series", "to", "influxdb", "." ]
c9f368e28a6072813454b6b549b4afa64aad778a
https://github.com/bitlabstudio/django-influxdb-metrics/blob/c9f368e28a6072813454b6b549b4afa64aad778a/influxdb_metrics/utils.py#L33-L55
8,282
keiichishima/pcalg
pcalg.py
_create_complete_graph
def _create_complete_graph(node_ids): """Create a complete graph from the list of node ids. Args: node_ids: a list of node ids Returns: An undirected graph (as a networkx.Graph) """ g = nx.Graph() g.add_nodes_from(node_ids) for (i, j) in combinations(node_ids, 2): g.add_edge(i, j) return g
python
def _create_complete_graph(node_ids): g = nx.Graph() g.add_nodes_from(node_ids) for (i, j) in combinations(node_ids, 2): g.add_edge(i, j) return g
[ "def", "_create_complete_graph", "(", "node_ids", ")", ":", "g", "=", "nx", ".", "Graph", "(", ")", "g", ".", "add_nodes_from", "(", "node_ids", ")", "for", "(", "i", ",", "j", ")", "in", "combinations", "(", "node_ids", ",", "2", ")", ":", "g", "....
Create a complete graph from the list of node ids. Args: node_ids: a list of node ids Returns: An undirected graph (as a networkx.Graph)
[ "Create", "a", "complete", "graph", "from", "the", "list", "of", "node", "ids", "." ]
f270e2bdb76b88c8f80a1ea07317ff4be88e2359
https://github.com/keiichishima/pcalg/blob/f270e2bdb76b88c8f80a1ea07317ff4be88e2359/pcalg.py#L22-L35
8,283
keiichishima/pcalg
pcalg.py
estimate_skeleton
def estimate_skeleton(indep_test_func, data_matrix, alpha, **kwargs): """Estimate a skeleton graph from the statistis information. Args: indep_test_func: the function name for a conditional independency test. data_matrix: data (as a numpy array). alpha: the significance level. kwargs: 'max_reach': maximum value of l (see the code). The value depends on the underlying distribution. 'method': if 'stable' given, use stable-PC algorithm (see [Colombo2014]). 'init_graph': initial structure of skeleton graph (as a networkx.Graph). If not specified, a complete graph is used. other parameters may be passed depending on the indep_test_func()s. Returns: g: a skeleton graph (as a networkx.Graph). sep_set: a separation set (as an 2D-array of set()). [Colombo2014] Diego Colombo and Marloes H Maathuis. Order-independent constraint-based causal structure learning. In The Journal of Machine Learning Research, Vol. 15, pp. 3741-3782, 2014. """ def method_stable(kwargs): return ('method' in kwargs) and kwargs['method'] == "stable" node_ids = range(data_matrix.shape[1]) node_size = data_matrix.shape[1] sep_set = [[set() for i in range(node_size)] for j in range(node_size)] if 'init_graph' in kwargs: g = kwargs['init_graph'] if not isinstance(g, nx.Graph): raise ValueError elif not g.number_of_nodes() == len(node_ids): raise ValueError('init_graph not matching data_matrix shape') for (i, j) in combinations(node_ids, 2): if not g.has_edge(i, j): sep_set[i][j] = None sep_set[j][i] = None else: g = _create_complete_graph(node_ids) l = 0 while True: cont = False remove_edges = [] for (i, j) in permutations(node_ids, 2): adj_i = list(g.neighbors(i)) if j not in adj_i: continue else: adj_i.remove(j) if len(adj_i) >= l: _logger.debug('testing %s and %s' % (i,j)) _logger.debug('neighbors of %s are %s' % (i, str(adj_i))) if len(adj_i) < l: continue for k in combinations(adj_i, l): _logger.debug('indep prob of %s and %s with subset %s' % (i, j, str(k))) p_val = indep_test_func(data_matrix, i, j, set(k), **kwargs) _logger.debug('p_val is %s' % str(p_val)) if p_val > alpha: if g.has_edge(i, j): _logger.debug('p: remove edge (%s, %s)' % (i, j)) if method_stable(kwargs): remove_edges.append((i, j)) else: g.remove_edge(i, j) sep_set[i][j] |= set(k) sep_set[j][i] |= set(k) break cont = True l += 1 if method_stable(kwargs): g.remove_edges_from(remove_edges) if cont is False: break if ('max_reach' in kwargs) and (l > kwargs['max_reach']): break return (g, sep_set)
python
def estimate_skeleton(indep_test_func, data_matrix, alpha, **kwargs): def method_stable(kwargs): return ('method' in kwargs) and kwargs['method'] == "stable" node_ids = range(data_matrix.shape[1]) node_size = data_matrix.shape[1] sep_set = [[set() for i in range(node_size)] for j in range(node_size)] if 'init_graph' in kwargs: g = kwargs['init_graph'] if not isinstance(g, nx.Graph): raise ValueError elif not g.number_of_nodes() == len(node_ids): raise ValueError('init_graph not matching data_matrix shape') for (i, j) in combinations(node_ids, 2): if not g.has_edge(i, j): sep_set[i][j] = None sep_set[j][i] = None else: g = _create_complete_graph(node_ids) l = 0 while True: cont = False remove_edges = [] for (i, j) in permutations(node_ids, 2): adj_i = list(g.neighbors(i)) if j not in adj_i: continue else: adj_i.remove(j) if len(adj_i) >= l: _logger.debug('testing %s and %s' % (i,j)) _logger.debug('neighbors of %s are %s' % (i, str(adj_i))) if len(adj_i) < l: continue for k in combinations(adj_i, l): _logger.debug('indep prob of %s and %s with subset %s' % (i, j, str(k))) p_val = indep_test_func(data_matrix, i, j, set(k), **kwargs) _logger.debug('p_val is %s' % str(p_val)) if p_val > alpha: if g.has_edge(i, j): _logger.debug('p: remove edge (%s, %s)' % (i, j)) if method_stable(kwargs): remove_edges.append((i, j)) else: g.remove_edge(i, j) sep_set[i][j] |= set(k) sep_set[j][i] |= set(k) break cont = True l += 1 if method_stable(kwargs): g.remove_edges_from(remove_edges) if cont is False: break if ('max_reach' in kwargs) and (l > kwargs['max_reach']): break return (g, sep_set)
[ "def", "estimate_skeleton", "(", "indep_test_func", ",", "data_matrix", ",", "alpha", ",", "*", "*", "kwargs", ")", ":", "def", "method_stable", "(", "kwargs", ")", ":", "return", "(", "'method'", "in", "kwargs", ")", "and", "kwargs", "[", "'method'", "]",...
Estimate a skeleton graph from the statistis information. Args: indep_test_func: the function name for a conditional independency test. data_matrix: data (as a numpy array). alpha: the significance level. kwargs: 'max_reach': maximum value of l (see the code). The value depends on the underlying distribution. 'method': if 'stable' given, use stable-PC algorithm (see [Colombo2014]). 'init_graph': initial structure of skeleton graph (as a networkx.Graph). If not specified, a complete graph is used. other parameters may be passed depending on the indep_test_func()s. Returns: g: a skeleton graph (as a networkx.Graph). sep_set: a separation set (as an 2D-array of set()). [Colombo2014] Diego Colombo and Marloes H Maathuis. Order-independent constraint-based causal structure learning. In The Journal of Machine Learning Research, Vol. 15, pp. 3741-3782, 2014.
[ "Estimate", "a", "skeleton", "graph", "from", "the", "statistis", "information", "." ]
f270e2bdb76b88c8f80a1ea07317ff4be88e2359
https://github.com/keiichishima/pcalg/blob/f270e2bdb76b88c8f80a1ea07317ff4be88e2359/pcalg.py#L37-L123
8,284
fedora-infra/fedmsg
fedmsg/utils.py
set_high_water_mark
def set_high_water_mark(socket, config): """ Set a high water mark on the zmq socket. Do so in a way that is cross-compatible with zeromq2 and zeromq3. """ if config['high_water_mark']: if hasattr(zmq, 'HWM'): # zeromq2 socket.setsockopt(zmq.HWM, config['high_water_mark']) else: # zeromq3 socket.setsockopt(zmq.SNDHWM, config['high_water_mark']) socket.setsockopt(zmq.RCVHWM, config['high_water_mark'])
python
def set_high_water_mark(socket, config): if config['high_water_mark']: if hasattr(zmq, 'HWM'): # zeromq2 socket.setsockopt(zmq.HWM, config['high_water_mark']) else: # zeromq3 socket.setsockopt(zmq.SNDHWM, config['high_water_mark']) socket.setsockopt(zmq.RCVHWM, config['high_water_mark'])
[ "def", "set_high_water_mark", "(", "socket", ",", "config", ")", ":", "if", "config", "[", "'high_water_mark'", "]", ":", "if", "hasattr", "(", "zmq", ",", "'HWM'", ")", ":", "# zeromq2", "socket", ".", "setsockopt", "(", "zmq", ".", "HWM", ",", "config"...
Set a high water mark on the zmq socket. Do so in a way that is cross-compatible with zeromq2 and zeromq3.
[ "Set", "a", "high", "water", "mark", "on", "the", "zmq", "socket", ".", "Do", "so", "in", "a", "way", "that", "is", "cross", "-", "compatible", "with", "zeromq2", "and", "zeromq3", "." ]
c21d6b3ce023fc3c0e881c704f5b55fb6e6392d7
https://github.com/fedora-infra/fedmsg/blob/c21d6b3ce023fc3c0e881c704f5b55fb6e6392d7/fedmsg/utils.py#L32-L44
8,285
fedora-infra/fedmsg
fedmsg/utils.py
set_tcp_keepalive
def set_tcp_keepalive(socket, config): """ Set a series of TCP keepalive options on the socket if and only if 1) they are specified explicitly in the config and 2) the version of pyzmq has been compiled with support We ran into a problem in FedoraInfrastructure where long-standing connections between some hosts would suddenly drop off the map silently. Because PUB/SUB sockets don't communicate regularly, nothing in the TCP stack would automatically try and fix the connection. With TCP_KEEPALIVE options (introduced in libzmq 3.2 and pyzmq 2.2.0.1) hopefully that will be fixed. See the following - http://tldp.org/HOWTO/TCP-Keepalive-HOWTO/overview.html - http://api.zeromq.org/3-2:zmq-setsockopt """ keepalive_options = { # Map fedmsg config keys to zeromq socket constants 'zmq_tcp_keepalive': 'TCP_KEEPALIVE', 'zmq_tcp_keepalive_cnt': 'TCP_KEEPALIVE_CNT', 'zmq_tcp_keepalive_idle': 'TCP_KEEPALIVE_IDLE', 'zmq_tcp_keepalive_intvl': 'TCP_KEEPALIVE_INTVL', } for key, const in keepalive_options.items(): if key in config: attr = getattr(zmq, const, None) if attr: socket.setsockopt(attr, config[key])
python
def set_tcp_keepalive(socket, config): keepalive_options = { # Map fedmsg config keys to zeromq socket constants 'zmq_tcp_keepalive': 'TCP_KEEPALIVE', 'zmq_tcp_keepalive_cnt': 'TCP_KEEPALIVE_CNT', 'zmq_tcp_keepalive_idle': 'TCP_KEEPALIVE_IDLE', 'zmq_tcp_keepalive_intvl': 'TCP_KEEPALIVE_INTVL', } for key, const in keepalive_options.items(): if key in config: attr = getattr(zmq, const, None) if attr: socket.setsockopt(attr, config[key])
[ "def", "set_tcp_keepalive", "(", "socket", ",", "config", ")", ":", "keepalive_options", "=", "{", "# Map fedmsg config keys to zeromq socket constants", "'zmq_tcp_keepalive'", ":", "'TCP_KEEPALIVE'", ",", "'zmq_tcp_keepalive_cnt'", ":", "'TCP_KEEPALIVE_CNT'", ",", "'zmq_tcp_...
Set a series of TCP keepalive options on the socket if and only if 1) they are specified explicitly in the config and 2) the version of pyzmq has been compiled with support We ran into a problem in FedoraInfrastructure where long-standing connections between some hosts would suddenly drop off the map silently. Because PUB/SUB sockets don't communicate regularly, nothing in the TCP stack would automatically try and fix the connection. With TCP_KEEPALIVE options (introduced in libzmq 3.2 and pyzmq 2.2.0.1) hopefully that will be fixed. See the following - http://tldp.org/HOWTO/TCP-Keepalive-HOWTO/overview.html - http://api.zeromq.org/3-2:zmq-setsockopt
[ "Set", "a", "series", "of", "TCP", "keepalive", "options", "on", "the", "socket", "if", "and", "only", "if", "1", ")", "they", "are", "specified", "explicitly", "in", "the", "config", "and", "2", ")", "the", "version", "of", "pyzmq", "has", "been", "co...
c21d6b3ce023fc3c0e881c704f5b55fb6e6392d7
https://github.com/fedora-infra/fedmsg/blob/c21d6b3ce023fc3c0e881c704f5b55fb6e6392d7/fedmsg/utils.py#L59-L88
8,286
fedora-infra/fedmsg
fedmsg/utils.py
set_tcp_reconnect
def set_tcp_reconnect(socket, config): """ Set a series of TCP reconnect options on the socket if and only if 1) they are specified explicitly in the config and 2) the version of pyzmq has been compiled with support Once our fedmsg bus grew to include many hundreds of endpoints, we started notices a *lot* of SYN-ACKs in the logs. By default, if an endpoint is unavailable, zeromq will attempt to reconnect every 100ms until it gets a connection. With this code, you can reconfigure that to back off exponentially to some max delay (like 1000ms) to reduce reconnect storm spam. See the following - http://api.zeromq.org/3-2:zmq-setsockopt """ reconnect_options = { # Map fedmsg config keys to zeromq socket constants 'zmq_reconnect_ivl': 'RECONNECT_IVL', 'zmq_reconnect_ivl_max': 'RECONNECT_IVL_MAX', } for key, const in reconnect_options.items(): if key in config: attr = getattr(zmq, const, None) if attr: socket.setsockopt(attr, config[key])
python
def set_tcp_reconnect(socket, config): reconnect_options = { # Map fedmsg config keys to zeromq socket constants 'zmq_reconnect_ivl': 'RECONNECT_IVL', 'zmq_reconnect_ivl_max': 'RECONNECT_IVL_MAX', } for key, const in reconnect_options.items(): if key in config: attr = getattr(zmq, const, None) if attr: socket.setsockopt(attr, config[key])
[ "def", "set_tcp_reconnect", "(", "socket", ",", "config", ")", ":", "reconnect_options", "=", "{", "# Map fedmsg config keys to zeromq socket constants", "'zmq_reconnect_ivl'", ":", "'RECONNECT_IVL'", ",", "'zmq_reconnect_ivl_max'", ":", "'RECONNECT_IVL_MAX'", ",", "}", "fo...
Set a series of TCP reconnect options on the socket if and only if 1) they are specified explicitly in the config and 2) the version of pyzmq has been compiled with support Once our fedmsg bus grew to include many hundreds of endpoints, we started notices a *lot* of SYN-ACKs in the logs. By default, if an endpoint is unavailable, zeromq will attempt to reconnect every 100ms until it gets a connection. With this code, you can reconfigure that to back off exponentially to some max delay (like 1000ms) to reduce reconnect storm spam. See the following - http://api.zeromq.org/3-2:zmq-setsockopt
[ "Set", "a", "series", "of", "TCP", "reconnect", "options", "on", "the", "socket", "if", "and", "only", "if", "1", ")", "they", "are", "specified", "explicitly", "in", "the", "config", "and", "2", ")", "the", "version", "of", "pyzmq", "has", "been", "co...
c21d6b3ce023fc3c0e881c704f5b55fb6e6392d7
https://github.com/fedora-infra/fedmsg/blob/c21d6b3ce023fc3c0e881c704f5b55fb6e6392d7/fedmsg/utils.py#L91-L117
8,287
fedora-infra/fedmsg
fedmsg/utils.py
dict_query
def dict_query(dic, query): """ Query a dict with 'dotted notation'. Returns an OrderedDict. A query of "foo.bar.baz" would retrieve 'wat' from this:: dic = { 'foo': { 'bar': { 'baz': 'wat', } } } Multiple queries can be specified if comma-separated. For instance, the query "foo.bar.baz,foo.bar.something_else" would return this:: OrderedDict({ "foo.bar.baz": "wat", "foo.bar.something_else": None, }) """ if not isinstance(query, six.string_types): raise ValueError("query must be a string, not %r" % type(query)) def _browse(tokens, d): """ Recurse through a dict to retrieve a value. """ current, rest = tokens[0], tokens[1:] if not rest: return d.get(current, None) if current in d: if isinstance(d[current], dict): return _browse(rest, d[current]) elif rest: return None else: return d[current] keys = [key.strip().split('.') for key in query.split(',')] return OrderedDict([ ('.'.join(tokens), _browse(tokens, dic)) for tokens in keys ])
python
def dict_query(dic, query): if not isinstance(query, six.string_types): raise ValueError("query must be a string, not %r" % type(query)) def _browse(tokens, d): """ Recurse through a dict to retrieve a value. """ current, rest = tokens[0], tokens[1:] if not rest: return d.get(current, None) if current in d: if isinstance(d[current], dict): return _browse(rest, d[current]) elif rest: return None else: return d[current] keys = [key.strip().split('.') for key in query.split(',')] return OrderedDict([ ('.'.join(tokens), _browse(tokens, dic)) for tokens in keys ])
[ "def", "dict_query", "(", "dic", ",", "query", ")", ":", "if", "not", "isinstance", "(", "query", ",", "six", ".", "string_types", ")", ":", "raise", "ValueError", "(", "\"query must be a string, not %r\"", "%", "type", "(", "query", ")", ")", "def", "_bro...
Query a dict with 'dotted notation'. Returns an OrderedDict. A query of "foo.bar.baz" would retrieve 'wat' from this:: dic = { 'foo': { 'bar': { 'baz': 'wat', } } } Multiple queries can be specified if comma-separated. For instance, the query "foo.bar.baz,foo.bar.something_else" would return this:: OrderedDict({ "foo.bar.baz": "wat", "foo.bar.something_else": None, })
[ "Query", "a", "dict", "with", "dotted", "notation", ".", "Returns", "an", "OrderedDict", "." ]
c21d6b3ce023fc3c0e881c704f5b55fb6e6392d7
https://github.com/fedora-infra/fedmsg/blob/c21d6b3ce023fc3c0e881c704f5b55fb6e6392d7/fedmsg/utils.py#L139-L183
8,288
fedora-infra/fedmsg
fedmsg/utils.py
cowsay_output
def cowsay_output(message): """ Invoke a shell command to print cowsay output. Primary replacement for os.system calls. """ command = 'cowsay "%s"' % message ret = subprocess.Popen( command, shell=True, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, close_fds=True) output, error = ret.communicate() return output, error
python
def cowsay_output(message): command = 'cowsay "%s"' % message ret = subprocess.Popen( command, shell=True, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, close_fds=True) output, error = ret.communicate() return output, error
[ "def", "cowsay_output", "(", "message", ")", ":", "command", "=", "'cowsay \"%s\"'", "%", "message", "ret", "=", "subprocess", ".", "Popen", "(", "command", ",", "shell", "=", "True", ",", "stdin", "=", "subprocess", ".", "PIPE", ",", "stdout", "=", "sub...
Invoke a shell command to print cowsay output. Primary replacement for os.system calls.
[ "Invoke", "a", "shell", "command", "to", "print", "cowsay", "output", ".", "Primary", "replacement", "for", "os", ".", "system", "calls", "." ]
c21d6b3ce023fc3c0e881c704f5b55fb6e6392d7
https://github.com/fedora-infra/fedmsg/blob/c21d6b3ce023fc3c0e881c704f5b55fb6e6392d7/fedmsg/utils.py#L186-L195
8,289
fedora-infra/fedmsg
fedmsg/encoding/sqla.py
expand
def expand(obj, relation, seen): """ Return the to_json or id of a sqlalchemy relationship. """ if hasattr(relation, 'all'): relation = relation.all() if hasattr(relation, '__iter__'): return [expand(obj, item, seen) for item in relation] if type(relation) not in seen: return to_json(relation, seen + [type(obj)]) else: return relation.id
python
def expand(obj, relation, seen): if hasattr(relation, 'all'): relation = relation.all() if hasattr(relation, '__iter__'): return [expand(obj, item, seen) for item in relation] if type(relation) not in seen: return to_json(relation, seen + [type(obj)]) else: return relation.id
[ "def", "expand", "(", "obj", ",", "relation", ",", "seen", ")", ":", "if", "hasattr", "(", "relation", ",", "'all'", ")", ":", "relation", "=", "relation", ".", "all", "(", ")", "if", "hasattr", "(", "relation", ",", "'__iter__'", ")", ":", "return",...
Return the to_json or id of a sqlalchemy relationship.
[ "Return", "the", "to_json", "or", "id", "of", "a", "sqlalchemy", "relationship", "." ]
c21d6b3ce023fc3c0e881c704f5b55fb6e6392d7
https://github.com/fedora-infra/fedmsg/blob/c21d6b3ce023fc3c0e881c704f5b55fb6e6392d7/fedmsg/encoding/sqla.py#L60-L72
8,290
fedora-infra/fedmsg
fedmsg/consumers/relay.py
SigningRelayConsumer.consume
def consume(self, msg): """ Sign the message prior to sending the message. Args: msg (dict): The message to sign and relay. """ msg['body'] = crypto.sign(msg['body'], **self.hub.config) super(SigningRelayConsumer, self).consume(msg)
python
def consume(self, msg): msg['body'] = crypto.sign(msg['body'], **self.hub.config) super(SigningRelayConsumer, self).consume(msg)
[ "def", "consume", "(", "self", ",", "msg", ")", ":", "msg", "[", "'body'", "]", "=", "crypto", ".", "sign", "(", "msg", "[", "'body'", "]", ",", "*", "*", "self", ".", "hub", ".", "config", ")", "super", "(", "SigningRelayConsumer", ",", "self", ...
Sign the message prior to sending the message. Args: msg (dict): The message to sign and relay.
[ "Sign", "the", "message", "prior", "to", "sending", "the", "message", "." ]
c21d6b3ce023fc3c0e881c704f5b55fb6e6392d7
https://github.com/fedora-infra/fedmsg/blob/c21d6b3ce023fc3c0e881c704f5b55fb6e6392d7/fedmsg/consumers/relay.py#L81-L89
8,291
fedora-infra/fedmsg
fedmsg/consumers/__init__.py
FedmsgConsumer._backlog
def _backlog(self, data): """Find all the datagrepper messages between 'then' and 'now'. Put those on our work queue. Should be called in a thread so as not to block the hub at startup. """ try: data = json.loads(data) except ValueError as e: self.log.info("Status contents are %r" % data) self.log.exception(e) self.log.info("Skipping backlog retrieval.") return last = data['message']['body'] if isinstance(last, str): last = json.loads(last) then = last['timestamp'] now = int(time.time()) retrieved = 0 for message in self.get_datagrepper_results(then, now): # Take the messages from datagrepper and remove any keys that were # artificially added to the message. The presence of these would # otherwise cause message crypto validation to fail. message = fedmsg.crypto.utils.fix_datagrepper_message(message) if message['msg_id'] != last['msg_id']: retrieved = retrieved + 1 self.incoming.put(dict(body=message, topic=message['topic'])) else: self.log.warning("Already seen %r; Skipping." % last['msg_id']) self.log.info("Retrieved %i messages from datagrepper." % retrieved)
python
def _backlog(self, data): try: data = json.loads(data) except ValueError as e: self.log.info("Status contents are %r" % data) self.log.exception(e) self.log.info("Skipping backlog retrieval.") return last = data['message']['body'] if isinstance(last, str): last = json.loads(last) then = last['timestamp'] now = int(time.time()) retrieved = 0 for message in self.get_datagrepper_results(then, now): # Take the messages from datagrepper and remove any keys that were # artificially added to the message. The presence of these would # otherwise cause message crypto validation to fail. message = fedmsg.crypto.utils.fix_datagrepper_message(message) if message['msg_id'] != last['msg_id']: retrieved = retrieved + 1 self.incoming.put(dict(body=message, topic=message['topic'])) else: self.log.warning("Already seen %r; Skipping." % last['msg_id']) self.log.info("Retrieved %i messages from datagrepper." % retrieved)
[ "def", "_backlog", "(", "self", ",", "data", ")", ":", "try", ":", "data", "=", "json", ".", "loads", "(", "data", ")", "except", "ValueError", "as", "e", ":", "self", ".", "log", ".", "info", "(", "\"Status contents are %r\"", "%", "data", ")", "sel...
Find all the datagrepper messages between 'then' and 'now'. Put those on our work queue. Should be called in a thread so as not to block the hub at startup.
[ "Find", "all", "the", "datagrepper", "messages", "between", "then", "and", "now", "." ]
c21d6b3ce023fc3c0e881c704f5b55fb6e6392d7
https://github.com/fedora-infra/fedmsg/blob/c21d6b3ce023fc3c0e881c704f5b55fb6e6392d7/fedmsg/consumers/__init__.py#L161-L197
8,292
fedora-infra/fedmsg
fedmsg/consumers/__init__.py
FedmsgConsumer.validate
def validate(self, message): """ Validate the message before the consumer processes it. This needs to raise an exception, caught by moksha. Args: message (dict): The message as a dictionary. This must, at a minimum, contain the 'topic' key with a unicode string value and 'body' key with a dictionary value. However, the message might also be an object with a ``__json__`` method that returns a dict with a 'body' key that can be a unicode string that is JSON-encoded. Raises: RuntimeWarning: If the message is not valid. UnicodeDecodeError: If the message body is not unicode or UTF-8 and also happens to contain invalid UTF-8 binary. """ if hasattr(message, '__json__'): message = message.__json__() if isinstance(message['body'], six.text_type): message['body'] = json.loads(message['body']) elif isinstance(message['body'], six.binary_type): # Try to decode the message body as UTF-8 since it's very likely # that that was the encoding used. This API should eventually only # accept unicode strings inside messages. If a UnicodeDecodeError # happens, let that bubble up. warnings.warn('Message body is not unicode', DeprecationWarning) message['body'] = json.loads(message['body'].decode('utf-8')) # Massage STOMP messages into a more compatible format. if 'topic' not in message['body']: message['body'] = { 'topic': message.get('topic'), 'msg': message['body'], } # If we're not validating, then everything is valid. # If this is turned on globally, our child class can override it. if not self.validate_signatures: return # We assume these match inside fedmsg.crypto, so we should enforce it. if not message['topic'] == message['body']['topic']: raise RuntimeWarning("Topic envelope mismatch.") if not fedmsg.crypto.validate(message['body'], **self.hub.config): raise RuntimeWarning("Failed to authn message.")
python
def validate(self, message): if hasattr(message, '__json__'): message = message.__json__() if isinstance(message['body'], six.text_type): message['body'] = json.loads(message['body']) elif isinstance(message['body'], six.binary_type): # Try to decode the message body as UTF-8 since it's very likely # that that was the encoding used. This API should eventually only # accept unicode strings inside messages. If a UnicodeDecodeError # happens, let that bubble up. warnings.warn('Message body is not unicode', DeprecationWarning) message['body'] = json.loads(message['body'].decode('utf-8')) # Massage STOMP messages into a more compatible format. if 'topic' not in message['body']: message['body'] = { 'topic': message.get('topic'), 'msg': message['body'], } # If we're not validating, then everything is valid. # If this is turned on globally, our child class can override it. if not self.validate_signatures: return # We assume these match inside fedmsg.crypto, so we should enforce it. if not message['topic'] == message['body']['topic']: raise RuntimeWarning("Topic envelope mismatch.") if not fedmsg.crypto.validate(message['body'], **self.hub.config): raise RuntimeWarning("Failed to authn message.")
[ "def", "validate", "(", "self", ",", "message", ")", ":", "if", "hasattr", "(", "message", ",", "'__json__'", ")", ":", "message", "=", "message", ".", "__json__", "(", ")", "if", "isinstance", "(", "message", "[", "'body'", "]", ",", "six", ".", "te...
Validate the message before the consumer processes it. This needs to raise an exception, caught by moksha. Args: message (dict): The message as a dictionary. This must, at a minimum, contain the 'topic' key with a unicode string value and 'body' key with a dictionary value. However, the message might also be an object with a ``__json__`` method that returns a dict with a 'body' key that can be a unicode string that is JSON-encoded. Raises: RuntimeWarning: If the message is not valid. UnicodeDecodeError: If the message body is not unicode or UTF-8 and also happens to contain invalid UTF-8 binary.
[ "Validate", "the", "message", "before", "the", "consumer", "processes", "it", "." ]
c21d6b3ce023fc3c0e881c704f5b55fb6e6392d7
https://github.com/fedora-infra/fedmsg/blob/c21d6b3ce023fc3c0e881c704f5b55fb6e6392d7/fedmsg/consumers/__init__.py#L224-L271
8,293
fedora-infra/fedmsg
fedmsg/consumers/__init__.py
FedmsgConsumer._consume
def _consume(self, message): """ Called when a message is consumed. This private method handles some administrative setup and teardown before calling the public interface `consume` typically implemented by a subclass. When `moksha.blocking_mode` is set to `False` in the config, this method always returns `None`. The argued message is stored in an internal queue where the consumer's worker threads should eventually pick it up. When `moksha.blocking_mode` is set to `True` in the config, this method should return True or False, indicating whether the message was handled or not. Specifically, in the event that the inner `consume` method raises an exception of any kind, this method should return `False` indicating that the message was not successfully handled. Args: message (dict): The message as a dictionary. Returns: bool: Should be interpreted as whether or not the message was handled by the consumer, or `None` if `moksha.blocking_mode` is set to False. """ try: self.validate(message) except RuntimeWarning as e: self.log.warn("Received invalid message {0}".format(e)) return # Pass along headers if present. May be useful to filters or # fedmsg.meta routines. if isinstance(message, dict) and 'headers' in message and 'body' in message: message['body']['headers'] = message['headers'] if hasattr(self, "replay_name"): for m in check_for_replay( self.replay_name, self.name_to_seq_id, message, self.hub.config): try: self.validate(m) return super(FedmsgConsumer, self)._consume(m) except RuntimeWarning as e: self.log.warn("Received invalid message {}".format(e)) else: return super(FedmsgConsumer, self)._consume(message)
python
def _consume(self, message): try: self.validate(message) except RuntimeWarning as e: self.log.warn("Received invalid message {0}".format(e)) return # Pass along headers if present. May be useful to filters or # fedmsg.meta routines. if isinstance(message, dict) and 'headers' in message and 'body' in message: message['body']['headers'] = message['headers'] if hasattr(self, "replay_name"): for m in check_for_replay( self.replay_name, self.name_to_seq_id, message, self.hub.config): try: self.validate(m) return super(FedmsgConsumer, self)._consume(m) except RuntimeWarning as e: self.log.warn("Received invalid message {}".format(e)) else: return super(FedmsgConsumer, self)._consume(message)
[ "def", "_consume", "(", "self", ",", "message", ")", ":", "try", ":", "self", ".", "validate", "(", "message", ")", "except", "RuntimeWarning", "as", "e", ":", "self", ".", "log", ".", "warn", "(", "\"Received invalid message {0}\"", ".", "format", "(", ...
Called when a message is consumed. This private method handles some administrative setup and teardown before calling the public interface `consume` typically implemented by a subclass. When `moksha.blocking_mode` is set to `False` in the config, this method always returns `None`. The argued message is stored in an internal queue where the consumer's worker threads should eventually pick it up. When `moksha.blocking_mode` is set to `True` in the config, this method should return True or False, indicating whether the message was handled or not. Specifically, in the event that the inner `consume` method raises an exception of any kind, this method should return `False` indicating that the message was not successfully handled. Args: message (dict): The message as a dictionary. Returns: bool: Should be interpreted as whether or not the message was handled by the consumer, or `None` if `moksha.blocking_mode` is set to False.
[ "Called", "when", "a", "message", "is", "consumed", "." ]
c21d6b3ce023fc3c0e881c704f5b55fb6e6392d7
https://github.com/fedora-infra/fedmsg/blob/c21d6b3ce023fc3c0e881c704f5b55fb6e6392d7/fedmsg/consumers/__init__.py#L273-L323
8,294
kenneth-reitz/args
args.py
ArgsList.files
def files(self, absolute=False): """Returns an expanded list of all valid paths that were passed in.""" _paths = [] for arg in self.all: for path in _expand_path(arg): if os.path.exists(path): if absolute: _paths.append(os.path.abspath(path)) else: _paths.append(path) return _paths
python
def files(self, absolute=False): _paths = [] for arg in self.all: for path in _expand_path(arg): if os.path.exists(path): if absolute: _paths.append(os.path.abspath(path)) else: _paths.append(path) return _paths
[ "def", "files", "(", "self", ",", "absolute", "=", "False", ")", ":", "_paths", "=", "[", "]", "for", "arg", "in", "self", ".", "all", ":", "for", "path", "in", "_expand_path", "(", "arg", ")", ":", "if", "os", ".", "path", ".", "exists", "(", ...
Returns an expanded list of all valid paths that were passed in.
[ "Returns", "an", "expanded", "list", "of", "all", "valid", "paths", "that", "were", "passed", "in", "." ]
9460f1a35eb3055e9e4de1f0a6932e0883c72d65
https://github.com/kenneth-reitz/args/blob/9460f1a35eb3055e9e4de1f0a6932e0883c72d65/args.py#L329-L342
8,295
kenneth-reitz/args
args.py
ArgsList.assignments
def assignments(self): """Extracts assignment values from assignments.""" collection = OrderedDict() for arg in self.all: if '=' in arg: collection.setdefault( arg.split('=', 1)[0], ArgsList(no_argv=True)) collection[arg.split('=', 1)[0]]._args.append( arg.split('=', 1)[1]) return collection
python
def assignments(self): collection = OrderedDict() for arg in self.all: if '=' in arg: collection.setdefault( arg.split('=', 1)[0], ArgsList(no_argv=True)) collection[arg.split('=', 1)[0]]._args.append( arg.split('=', 1)[1]) return collection
[ "def", "assignments", "(", "self", ")", ":", "collection", "=", "OrderedDict", "(", ")", "for", "arg", "in", "self", ".", "all", ":", "if", "'='", "in", "arg", ":", "collection", ".", "setdefault", "(", "arg", ".", "split", "(", "'='", ",", "1", ")...
Extracts assignment values from assignments.
[ "Extracts", "assignment", "values", "from", "assignments", "." ]
9460f1a35eb3055e9e4de1f0a6932e0883c72d65
https://github.com/kenneth-reitz/args/blob/9460f1a35eb3055e9e4de1f0a6932e0883c72d65/args.py#L364-L376
8,296
fedora-infra/fedmsg
fedmsg/crypto/gpg.py
sign
def sign(message, gpg_home=None, gpg_signing_key=None, **config): """ Insert a new field into the message dict and return it. The new field is: - 'signature' - the computed GPG message digest of the JSON repr of the `msg` field. """ if gpg_home is None or gpg_signing_key is None: raise ValueError("You must set the gpg_home \ and gpg_signing_key keyword arguments.") message['crypto'] = 'gpg' signature = _ctx.sign( fedmsg.encoding.dumps(message['msg']), gpg_signing_key, homedir=gpg_home ) return dict(list(message.items()) + [('signature', b64encode(signature))])
python
def sign(message, gpg_home=None, gpg_signing_key=None, **config): if gpg_home is None or gpg_signing_key is None: raise ValueError("You must set the gpg_home \ and gpg_signing_key keyword arguments.") message['crypto'] = 'gpg' signature = _ctx.sign( fedmsg.encoding.dumps(message['msg']), gpg_signing_key, homedir=gpg_home ) return dict(list(message.items()) + [('signature', b64encode(signature))])
[ "def", "sign", "(", "message", ",", "gpg_home", "=", "None", ",", "gpg_signing_key", "=", "None", ",", "*", "*", "config", ")", ":", "if", "gpg_home", "is", "None", "or", "gpg_signing_key", "is", "None", ":", "raise", "ValueError", "(", "\"You must set the...
Insert a new field into the message dict and return it. The new field is: - 'signature' - the computed GPG message digest of the JSON repr of the `msg` field.
[ "Insert", "a", "new", "field", "into", "the", "message", "dict", "and", "return", "it", "." ]
c21d6b3ce023fc3c0e881c704f5b55fb6e6392d7
https://github.com/fedora-infra/fedmsg/blob/c21d6b3ce023fc3c0e881c704f5b55fb6e6392d7/fedmsg/crypto/gpg.py#L157-L177
8,297
fedora-infra/fedmsg
fedmsg/core.py
FedMsgContext.destroy
def destroy(self): """ Destroy a fedmsg context """ if getattr(self, 'publisher', None): self.log.debug("closing fedmsg publisher") self.log.debug("sent %i messages" % self._i) self.publisher.close() self.publisher = None if getattr(self, 'context', None): self.context.term() self.context = None
python
def destroy(self): if getattr(self, 'publisher', None): self.log.debug("closing fedmsg publisher") self.log.debug("sent %i messages" % self._i) self.publisher.close() self.publisher = None if getattr(self, 'context', None): self.context.term() self.context = None
[ "def", "destroy", "(", "self", ")", ":", "if", "getattr", "(", "self", ",", "'publisher'", ",", "None", ")", ":", "self", ".", "log", ".", "debug", "(", "\"closing fedmsg publisher\"", ")", "self", ".", "log", ".", "debug", "(", "\"sent %i messages\"", "...
Destroy a fedmsg context
[ "Destroy", "a", "fedmsg", "context" ]
c21d6b3ce023fc3c0e881c704f5b55fb6e6392d7
https://github.com/fedora-infra/fedmsg/blob/c21d6b3ce023fc3c0e881c704f5b55fb6e6392d7/fedmsg/core.py#L173-L184
8,298
fedora-infra/fedmsg
fedmsg/core.py
FedMsgContext.publish
def publish(self, topic=None, msg=None, modname=None, pre_fire_hook=None, **kw): """ Send a message over the publishing zeromq socket. >>> import fedmsg >>> fedmsg.publish(topic='testing', modname='test', msg={ ... 'test': "Hello World", ... }) The above snippet will send the message ``'{test: "Hello World"}'`` over the ``<topic_prefix>.dev.test.testing`` topic. The fully qualified topic of a message is constructed out of the following pieces: <:ref:`conf-topic-prefix`>.<:ref:`conf-environment`>.<``modname``>.<``topic``> This function (and other API functions) do a little bit more heavy lifting than they let on. If the "zeromq context" is not yet initialized, :func:`fedmsg.init` is called to construct it and store it as :data:`fedmsg.__local.__context` before anything else is done. **An example from Fedora Tagger -- SQLAlchemy encoding** Here's an example from `fedora-tagger <https://github.com/fedora-infra/fedora-tagger>`_ that sends the information about a new tag over ``org.fedoraproject.{dev,stg,prod}.fedoratagger.tag.update``:: >>> import fedmsg >>> fedmsg.publish(topic='tag.update', msg={ ... 'user': user, ... 'tag': tag, ... }) Note that the `tag` and `user` objects are SQLAlchemy objects defined by tagger. They both have ``.__json__()`` methods which :func:`fedmsg.publish` uses to encode both objects as stringified JSON for you. Under the hood, specifically, ``.publish`` uses :mod:`fedmsg.encoding` to do this. ``fedmsg`` has also guessed the module name (``modname``) of it's caller and inserted it into the topic for you. The code from which we stole the above snippet lives in ``fedoratagger.controllers.root``. ``fedmsg`` figured that out and stripped it down to just ``fedoratagger`` for the final topic of ``org.fedoraproject.{dev,stg,prod}.fedoratagger.tag.update``. **Shell Usage** You could also use the ``fedmsg-logger`` from a shell script like so:: $ echo "Hello, world." | fedmsg-logger --topic testing $ echo '{"foo": "bar"}' | fedmsg-logger --json-input :param topic: The message topic suffix. This suffix is joined to the configured topic prefix (e.g. ``org.fedoraproject``), environment (e.g. ``prod``, ``dev``, etc.), and modname. :type topic: unicode :param msg: A message to publish. This message will be JSON-encoded prior to being sent, so the object must be composed of JSON- serializable data types. Please note that if this is already a string JSON serialization will be applied to that string. :type msg: dict :param modname: The module name that is publishing the message. If this is omitted, ``fedmsg`` will try to guess the name of the module that called it and use that to produce an intelligent topic. Specifying ``modname`` explicitly overrides this behavior. :type modname: unicode :param pre_fire_hook: A callable that will be called with a single argument -- the dict of the constructed message -- just before it is handed off to ZeroMQ for publication. :type pre_fire_hook: function """ topic = topic or 'unspecified' msg = msg or dict() # If no modname is supplied, then guess it from the call stack. modname = modname or guess_calling_module(default="fedmsg") topic = '.'.join([modname, topic]) if topic[:len(self.c['topic_prefix'])] != self.c['topic_prefix']: topic = '.'.join([ self.c['topic_prefix'], self.c['environment'], topic, ]) if isinstance(topic, six.text_type): topic = to_bytes(topic, encoding='utf8', nonstring="passthru") year = datetime.datetime.now().year self._i += 1 msg = dict( topic=topic.decode('utf-8'), msg=msg, timestamp=int(time.time()), msg_id=str(year) + '-' + str(uuid.uuid4()), i=self._i, username=getpass.getuser(), ) # Find my message-signing cert if I need one. if self.c.get('sign_messages', False): if not self.c.get("crypto_backend") == "gpg": if 'cert_prefix' in self.c: cert_index = "%s.%s" % (self.c['cert_prefix'], self.hostname) else: cert_index = self.c['name'] if cert_index == 'relay_inbound': cert_index = "shell.%s" % self.hostname self.c['certname'] = self.c['certnames'][cert_index] else: if 'gpg_signing_key' not in self.c: self.c['gpg_signing_key'] = self.c['gpg_keys'][self.hostname] if self.c.get('sign_messages', False): msg = fedmsg.crypto.sign(msg, **self.c) store = self.c.get('persistent_store', None) if store: # Add the seq_id field msg = store.add(msg) if pre_fire_hook: pre_fire_hook(msg) # We handle zeromq publishing ourselves. But, if that is disabled, # defer to the moksha' hub's twisted reactor to send messages (if # available). if self.c.get('zmq_enabled', True): self.publisher.send_multipart( [topic, fedmsg.encoding.dumps(msg).encode('utf-8')], flags=zmq.NOBLOCK, ) else: # Perhaps we're using STOMP or AMQP? Let moksha handle it. import moksha.hub # First, a quick sanity check. if not getattr(moksha.hub, '_hub', None): raise AttributeError("Unable to publish non-zeromq msg " "without moksha-hub initialization.") # Let moksha.hub do our work. moksha.hub._hub.send_message( topic=topic, message=fedmsg.encoding.dumps(msg).encode('utf-8'), jsonify=False, )
python
def publish(self, topic=None, msg=None, modname=None, pre_fire_hook=None, **kw): topic = topic or 'unspecified' msg = msg or dict() # If no modname is supplied, then guess it from the call stack. modname = modname or guess_calling_module(default="fedmsg") topic = '.'.join([modname, topic]) if topic[:len(self.c['topic_prefix'])] != self.c['topic_prefix']: topic = '.'.join([ self.c['topic_prefix'], self.c['environment'], topic, ]) if isinstance(topic, six.text_type): topic = to_bytes(topic, encoding='utf8', nonstring="passthru") year = datetime.datetime.now().year self._i += 1 msg = dict( topic=topic.decode('utf-8'), msg=msg, timestamp=int(time.time()), msg_id=str(year) + '-' + str(uuid.uuid4()), i=self._i, username=getpass.getuser(), ) # Find my message-signing cert if I need one. if self.c.get('sign_messages', False): if not self.c.get("crypto_backend") == "gpg": if 'cert_prefix' in self.c: cert_index = "%s.%s" % (self.c['cert_prefix'], self.hostname) else: cert_index = self.c['name'] if cert_index == 'relay_inbound': cert_index = "shell.%s" % self.hostname self.c['certname'] = self.c['certnames'][cert_index] else: if 'gpg_signing_key' not in self.c: self.c['gpg_signing_key'] = self.c['gpg_keys'][self.hostname] if self.c.get('sign_messages', False): msg = fedmsg.crypto.sign(msg, **self.c) store = self.c.get('persistent_store', None) if store: # Add the seq_id field msg = store.add(msg) if pre_fire_hook: pre_fire_hook(msg) # We handle zeromq publishing ourselves. But, if that is disabled, # defer to the moksha' hub's twisted reactor to send messages (if # available). if self.c.get('zmq_enabled', True): self.publisher.send_multipart( [topic, fedmsg.encoding.dumps(msg).encode('utf-8')], flags=zmq.NOBLOCK, ) else: # Perhaps we're using STOMP or AMQP? Let moksha handle it. import moksha.hub # First, a quick sanity check. if not getattr(moksha.hub, '_hub', None): raise AttributeError("Unable to publish non-zeromq msg " "without moksha-hub initialization.") # Let moksha.hub do our work. moksha.hub._hub.send_message( topic=topic, message=fedmsg.encoding.dumps(msg).encode('utf-8'), jsonify=False, )
[ "def", "publish", "(", "self", ",", "topic", "=", "None", ",", "msg", "=", "None", ",", "modname", "=", "None", ",", "pre_fire_hook", "=", "None", ",", "*", "*", "kw", ")", ":", "topic", "=", "topic", "or", "'unspecified'", "msg", "=", "msg", "or",...
Send a message over the publishing zeromq socket. >>> import fedmsg >>> fedmsg.publish(topic='testing', modname='test', msg={ ... 'test': "Hello World", ... }) The above snippet will send the message ``'{test: "Hello World"}'`` over the ``<topic_prefix>.dev.test.testing`` topic. The fully qualified topic of a message is constructed out of the following pieces: <:ref:`conf-topic-prefix`>.<:ref:`conf-environment`>.<``modname``>.<``topic``> This function (and other API functions) do a little bit more heavy lifting than they let on. If the "zeromq context" is not yet initialized, :func:`fedmsg.init` is called to construct it and store it as :data:`fedmsg.__local.__context` before anything else is done. **An example from Fedora Tagger -- SQLAlchemy encoding** Here's an example from `fedora-tagger <https://github.com/fedora-infra/fedora-tagger>`_ that sends the information about a new tag over ``org.fedoraproject.{dev,stg,prod}.fedoratagger.tag.update``:: >>> import fedmsg >>> fedmsg.publish(topic='tag.update', msg={ ... 'user': user, ... 'tag': tag, ... }) Note that the `tag` and `user` objects are SQLAlchemy objects defined by tagger. They both have ``.__json__()`` methods which :func:`fedmsg.publish` uses to encode both objects as stringified JSON for you. Under the hood, specifically, ``.publish`` uses :mod:`fedmsg.encoding` to do this. ``fedmsg`` has also guessed the module name (``modname``) of it's caller and inserted it into the topic for you. The code from which we stole the above snippet lives in ``fedoratagger.controllers.root``. ``fedmsg`` figured that out and stripped it down to just ``fedoratagger`` for the final topic of ``org.fedoraproject.{dev,stg,prod}.fedoratagger.tag.update``. **Shell Usage** You could also use the ``fedmsg-logger`` from a shell script like so:: $ echo "Hello, world." | fedmsg-logger --topic testing $ echo '{"foo": "bar"}' | fedmsg-logger --json-input :param topic: The message topic suffix. This suffix is joined to the configured topic prefix (e.g. ``org.fedoraproject``), environment (e.g. ``prod``, ``dev``, etc.), and modname. :type topic: unicode :param msg: A message to publish. This message will be JSON-encoded prior to being sent, so the object must be composed of JSON- serializable data types. Please note that if this is already a string JSON serialization will be applied to that string. :type msg: dict :param modname: The module name that is publishing the message. If this is omitted, ``fedmsg`` will try to guess the name of the module that called it and use that to produce an intelligent topic. Specifying ``modname`` explicitly overrides this behavior. :type modname: unicode :param pre_fire_hook: A callable that will be called with a single argument -- the dict of the constructed message -- just before it is handed off to ZeroMQ for publication. :type pre_fire_hook: function
[ "Send", "a", "message", "over", "the", "publishing", "zeromq", "socket", "." ]
c21d6b3ce023fc3c0e881c704f5b55fb6e6392d7
https://github.com/fedora-infra/fedmsg/blob/c21d6b3ce023fc3c0e881c704f5b55fb6e6392d7/fedmsg/core.py#L192-L343
8,299
fedora-infra/fedmsg
fedmsg/crypto/x509_ng.py
_prep_crypto_msg
def _prep_crypto_msg(message): """Split the signature and certificate in the same way M2Crypto does. M2Crypto is dropping newlines into its signature and certificate. This exists purely to maintain backwards compatibility. Args: message (dict): A message with the ``signature`` and ``certificate`` keywords. The values of these two keys must be byte strings. Returns: dict: The same message, but with the values of ``signature`` and ``certificate`` split every 76 characters with a newline and a final newline at the end. """ signature = message['signature'] certificate = message['certificate'] sliced_signature, sliced_certificate = [], [] for x in range(0, len(signature), 76): sliced_signature.append(signature[x:x+76]) for x in range(0, len(certificate), 76): sliced_certificate.append(certificate[x:x+76]) message['signature'] = u'\n'.join(sliced_signature) + u'\n' message['certificate'] = u'\n'.join(sliced_certificate) + u'\n' return message
python
def _prep_crypto_msg(message): signature = message['signature'] certificate = message['certificate'] sliced_signature, sliced_certificate = [], [] for x in range(0, len(signature), 76): sliced_signature.append(signature[x:x+76]) for x in range(0, len(certificate), 76): sliced_certificate.append(certificate[x:x+76]) message['signature'] = u'\n'.join(sliced_signature) + u'\n' message['certificate'] = u'\n'.join(sliced_certificate) + u'\n' return message
[ "def", "_prep_crypto_msg", "(", "message", ")", ":", "signature", "=", "message", "[", "'signature'", "]", "certificate", "=", "message", "[", "'certificate'", "]", "sliced_signature", ",", "sliced_certificate", "=", "[", "]", ",", "[", "]", "for", "x", "in"...
Split the signature and certificate in the same way M2Crypto does. M2Crypto is dropping newlines into its signature and certificate. This exists purely to maintain backwards compatibility. Args: message (dict): A message with the ``signature`` and ``certificate`` keywords. The values of these two keys must be byte strings. Returns: dict: The same message, but with the values of ``signature`` and ``certificate`` split every 76 characters with a newline and a final newline at the end.
[ "Split", "the", "signature", "and", "certificate", "in", "the", "same", "way", "M2Crypto", "does", "." ]
c21d6b3ce023fc3c0e881c704f5b55fb6e6392d7
https://github.com/fedora-infra/fedmsg/blob/c21d6b3ce023fc3c0e881c704f5b55fb6e6392d7/fedmsg/crypto/x509_ng.py#L100-L124