repo stringlengths 7 55 | path stringlengths 4 127 | func_name stringlengths 1 88 | original_string stringlengths 75 19.8k | language stringclasses 1
value | code stringlengths 75 19.8k | code_tokens listlengths 20 707 | docstring stringlengths 3 17.3k | docstring_tokens listlengths 3 222 | sha stringlengths 40 40 | url stringlengths 87 242 | partition stringclasses 1
value | idx int64 0 252k |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
OSSOS/MOP | src/ossos/core/ossos/downloads/cutouts/source.py | SourceCutout.reset_coord | def reset_coord(self):
"""
Reset the source location based on the init_skycoord values
@return:
"""
(x, y, idx) = self.world2pix(self.init_skycoord.ra,
self.init_skycoord.dec,
usepv=True)
self.update_pixel_location((x, y), idx) | python | def reset_coord(self):
"""
Reset the source location based on the init_skycoord values
@return:
"""
(x, y, idx) = self.world2pix(self.init_skycoord.ra,
self.init_skycoord.dec,
usepv=True)
self.update_pixel_location((x, y), idx) | [
"def",
"reset_coord",
"(",
"self",
")",
":",
"(",
"x",
",",
"y",
",",
"idx",
")",
"=",
"self",
".",
"world2pix",
"(",
"self",
".",
"init_skycoord",
".",
"ra",
",",
"self",
".",
"init_skycoord",
".",
"dec",
",",
"usepv",
"=",
"True",
")",
"self",
... | Reset the source location based on the init_skycoord values
@return: | [
"Reset",
"the",
"source",
"location",
"based",
"on",
"the",
"init_skycoord",
"values"
] | 94f91d32ad5ec081d5a1ebd67604a838003465af | https://github.com/OSSOS/MOP/blob/94f91d32ad5ec081d5a1ebd67604a838003465af/src/ossos/core/ossos/downloads/cutouts/source.py#L63-L71 | train | 47,900 |
OSSOS/MOP | src/ossos/core/ossos/downloads/cutouts/source.py | SourceCutout.pixel_coord | def pixel_coord(self):
"""
Return the coordinates of the source in the cutout reference frame.
@return:
"""
return self.get_pixel_coordinates(self.reading.pix_coord, self.reading.get_ccd_num()) | python | def pixel_coord(self):
"""
Return the coordinates of the source in the cutout reference frame.
@return:
"""
return self.get_pixel_coordinates(self.reading.pix_coord, self.reading.get_ccd_num()) | [
"def",
"pixel_coord",
"(",
"self",
")",
":",
"return",
"self",
".",
"get_pixel_coordinates",
"(",
"self",
".",
"reading",
".",
"pix_coord",
",",
"self",
".",
"reading",
".",
"get_ccd_num",
"(",
")",
")"
] | Return the coordinates of the source in the cutout reference frame.
@return: | [
"Return",
"the",
"coordinates",
"of",
"the",
"source",
"in",
"the",
"cutout",
"reference",
"frame",
"."
] | 94f91d32ad5ec081d5a1ebd67604a838003465af | https://github.com/OSSOS/MOP/blob/94f91d32ad5ec081d5a1ebd67604a838003465af/src/ossos/core/ossos/downloads/cutouts/source.py#L74-L79 | train | 47,901 |
OSSOS/MOP | src/ossos/core/ossos/downloads/cutouts/source.py | SourceCutout.get_pixel_coordinates | def get_pixel_coordinates(self, point, ccdnum):
"""
Retrieves the pixel location of a point within the current HDUList given the
location in the original FITS image. This takes into account that
the image may be a cutout of a larger original.
Args:
point: tuple(float, float)
(x, y) in original.
Returns:
(x, y) pixel in this image.
@param extno: the extno from the original Mosaic that the x/y coordinates are from.
"""
hdulist_index = self.get_hdulist_idx(ccdnum)
if isinstance(point[0], Quantity) and isinstance(point[1], Quantity):
pix_point = point[0].value, point[1].value
else:
pix_point = point
if self.reading.inverted:
pix_point = self.reading.obs.naxis1 - pix_point[0] +1 , self.reading.obs.naxis2 - pix_point[1] + 1
(x, y) = self.hdulist[hdulist_index].converter.convert(pix_point)
return x, y, hdulist_index | python | def get_pixel_coordinates(self, point, ccdnum):
"""
Retrieves the pixel location of a point within the current HDUList given the
location in the original FITS image. This takes into account that
the image may be a cutout of a larger original.
Args:
point: tuple(float, float)
(x, y) in original.
Returns:
(x, y) pixel in this image.
@param extno: the extno from the original Mosaic that the x/y coordinates are from.
"""
hdulist_index = self.get_hdulist_idx(ccdnum)
if isinstance(point[0], Quantity) and isinstance(point[1], Quantity):
pix_point = point[0].value, point[1].value
else:
pix_point = point
if self.reading.inverted:
pix_point = self.reading.obs.naxis1 - pix_point[0] +1 , self.reading.obs.naxis2 - pix_point[1] + 1
(x, y) = self.hdulist[hdulist_index].converter.convert(pix_point)
return x, y, hdulist_index | [
"def",
"get_pixel_coordinates",
"(",
"self",
",",
"point",
",",
"ccdnum",
")",
":",
"hdulist_index",
"=",
"self",
".",
"get_hdulist_idx",
"(",
"ccdnum",
")",
"if",
"isinstance",
"(",
"point",
"[",
"0",
"]",
",",
"Quantity",
")",
"and",
"isinstance",
"(",
... | Retrieves the pixel location of a point within the current HDUList given the
location in the original FITS image. This takes into account that
the image may be a cutout of a larger original.
Args:
point: tuple(float, float)
(x, y) in original.
Returns:
(x, y) pixel in this image.
@param extno: the extno from the original Mosaic that the x/y coordinates are from. | [
"Retrieves",
"the",
"pixel",
"location",
"of",
"a",
"point",
"within",
"the",
"current",
"HDUList",
"given",
"the",
"location",
"in",
"the",
"original",
"FITS",
"image",
".",
"This",
"takes",
"into",
"account",
"that",
"the",
"image",
"may",
"be",
"a",
"cu... | 94f91d32ad5ec081d5a1ebd67604a838003465af | https://github.com/OSSOS/MOP/blob/94f91d32ad5ec081d5a1ebd67604a838003465af/src/ossos/core/ossos/downloads/cutouts/source.py#L209-L232 | train | 47,902 |
OSSOS/MOP | src/ossos/core/ossos/downloads/cutouts/source.py | SourceCutout.get_observation_coordinates | def get_observation_coordinates(self, x, y, hdulist_index):
"""
Retrieves the location of a point using the coordinate system of
the original observation, i.e. the original image before any
cutouts were done.
Returns:
(x, y) in the original image coordinate system.
@param x: x-pixel location in the cutout frame of reference
@param y: y-pixel location in the cutout frame of reference
@param idx: index of hdu in hdulist that the given x/y corresponds to.
"""
return self.hdulist[hdulist_index].converter.get_inverse_converter().convert((x, y)) | python | def get_observation_coordinates(self, x, y, hdulist_index):
"""
Retrieves the location of a point using the coordinate system of
the original observation, i.e. the original image before any
cutouts were done.
Returns:
(x, y) in the original image coordinate system.
@param x: x-pixel location in the cutout frame of reference
@param y: y-pixel location in the cutout frame of reference
@param idx: index of hdu in hdulist that the given x/y corresponds to.
"""
return self.hdulist[hdulist_index].converter.get_inverse_converter().convert((x, y)) | [
"def",
"get_observation_coordinates",
"(",
"self",
",",
"x",
",",
"y",
",",
"hdulist_index",
")",
":",
"return",
"self",
".",
"hdulist",
"[",
"hdulist_index",
"]",
".",
"converter",
".",
"get_inverse_converter",
"(",
")",
".",
"convert",
"(",
"(",
"x",
","... | Retrieves the location of a point using the coordinate system of
the original observation, i.e. the original image before any
cutouts were done.
Returns:
(x, y) in the original image coordinate system.
@param x: x-pixel location in the cutout frame of reference
@param y: y-pixel location in the cutout frame of reference
@param idx: index of hdu in hdulist that the given x/y corresponds to. | [
"Retrieves",
"the",
"location",
"of",
"a",
"point",
"using",
"the",
"coordinate",
"system",
"of",
"the",
"original",
"observation",
"i",
".",
"e",
".",
"the",
"original",
"image",
"before",
"any",
"cutouts",
"were",
"done",
"."
] | 94f91d32ad5ec081d5a1ebd67604a838003465af | https://github.com/OSSOS/MOP/blob/94f91d32ad5ec081d5a1ebd67604a838003465af/src/ossos/core/ossos/downloads/cutouts/source.py#L234-L246 | train | 47,903 |
OSSOS/MOP | src/ossos/core/ossos/downloads/cutouts/source.py | SourceCutout.zmag | def zmag(self,):
"""
Return the photometric zeropoint of the CCD associated with the reading.
@return: float
"""
if self._zmag is None:
hdulist_index = self.get_hdulist_idx(self.reading.get_ccd_num())
self._zmag = self.hdulist[hdulist_index].header.get('PHOTZP', 0.0)
return self._zmag | python | def zmag(self,):
"""
Return the photometric zeropoint of the CCD associated with the reading.
@return: float
"""
if self._zmag is None:
hdulist_index = self.get_hdulist_idx(self.reading.get_ccd_num())
self._zmag = self.hdulist[hdulist_index].header.get('PHOTZP', 0.0)
return self._zmag | [
"def",
"zmag",
"(",
"self",
",",
")",
":",
"if",
"self",
".",
"_zmag",
"is",
"None",
":",
"hdulist_index",
"=",
"self",
".",
"get_hdulist_idx",
"(",
"self",
".",
"reading",
".",
"get_ccd_num",
"(",
")",
")",
"self",
".",
"_zmag",
"=",
"self",
".",
... | Return the photometric zeropoint of the CCD associated with the reading.
@return: float | [
"Return",
"the",
"photometric",
"zeropoint",
"of",
"the",
"CCD",
"associated",
"with",
"the",
"reading",
"."
] | 94f91d32ad5ec081d5a1ebd67604a838003465af | https://github.com/OSSOS/MOP/blob/94f91d32ad5ec081d5a1ebd67604a838003465af/src/ossos/core/ossos/downloads/cutouts/source.py#L275-L283 | train | 47,904 |
OSSOS/MOP | src/ossos/core/ossos/downloads/cutouts/source.py | SourceCutout.apcor | def apcor(self):
"""
return the aperture correction of for the CCD assocated with the reading.
@return: Apcor
"""
if self._apcor is None:
try:
self._apcor = Downloader().download_apcor(self.reading.get_apcor_uri())
except:
self._apcor = ApcorData.from_string("5 15 99.99 99.99")
return self._apcor | python | def apcor(self):
"""
return the aperture correction of for the CCD assocated with the reading.
@return: Apcor
"""
if self._apcor is None:
try:
self._apcor = Downloader().download_apcor(self.reading.get_apcor_uri())
except:
self._apcor = ApcorData.from_string("5 15 99.99 99.99")
return self._apcor | [
"def",
"apcor",
"(",
"self",
")",
":",
"if",
"self",
".",
"_apcor",
"is",
"None",
":",
"try",
":",
"self",
".",
"_apcor",
"=",
"Downloader",
"(",
")",
".",
"download_apcor",
"(",
"self",
".",
"reading",
".",
"get_apcor_uri",
"(",
")",
")",
"except",
... | return the aperture correction of for the CCD assocated with the reading.
@return: Apcor | [
"return",
"the",
"aperture",
"correction",
"of",
"for",
"the",
"CCD",
"assocated",
"with",
"the",
"reading",
"."
] | 94f91d32ad5ec081d5a1ebd67604a838003465af | https://github.com/OSSOS/MOP/blob/94f91d32ad5ec081d5a1ebd67604a838003465af/src/ossos/core/ossos/downloads/cutouts/source.py#L286-L296 | train | 47,905 |
OSSOS/MOP | src/ossos/core/ossos/downloads/cutouts/source.py | SourceCutout._hdu_on_disk | def _hdu_on_disk(self, hdulist_index):
"""
IRAF routines such as daophot need input on disk.
Returns:
filename: str
The name of the file containing the FITS data.
"""
if self._tempfile is None:
self._tempfile = tempfile.NamedTemporaryFile(
mode="r+b", suffix=".fits")
self.hdulist[hdulist_index].writeto(self._tempfile.name)
return self._tempfile.name | python | def _hdu_on_disk(self, hdulist_index):
"""
IRAF routines such as daophot need input on disk.
Returns:
filename: str
The name of the file containing the FITS data.
"""
if self._tempfile is None:
self._tempfile = tempfile.NamedTemporaryFile(
mode="r+b", suffix=".fits")
self.hdulist[hdulist_index].writeto(self._tempfile.name)
return self._tempfile.name | [
"def",
"_hdu_on_disk",
"(",
"self",
",",
"hdulist_index",
")",
":",
"if",
"self",
".",
"_tempfile",
"is",
"None",
":",
"self",
".",
"_tempfile",
"=",
"tempfile",
".",
"NamedTemporaryFile",
"(",
"mode",
"=",
"\"r+b\"",
",",
"suffix",
"=",
"\".fits\"",
")",
... | IRAF routines such as daophot need input on disk.
Returns:
filename: str
The name of the file containing the FITS data. | [
"IRAF",
"routines",
"such",
"as",
"daophot",
"need",
"input",
"on",
"disk",
"."
] | 94f91d32ad5ec081d5a1ebd67604a838003465af | https://github.com/OSSOS/MOP/blob/94f91d32ad5ec081d5a1ebd67604a838003465af/src/ossos/core/ossos/downloads/cutouts/source.py#L330-L342 | train | 47,906 |
OSSOS/MOP | src/ossos/core/ossos/downloads/cutouts/source.py | SourceCutout.comparison_image_list | def comparison_image_list(self):
"""
returns a list of possible comparison images for the current cutout. Will query CADC to create the list when
first called.
@rtype: Table
"""
if self._comparison_image_list is not None:
return self._comparison_image_list
ref_ra = self.reading.ra * units.degree
ref_dec = self.reading.dec * units.degree
radius = self.radius is not None and self.radius or config.read('CUTOUTS.SINGLETS.RADIUS') * units.arcminute
print("Querying CADC for list of possible comparison images at RA: {}, DEC: {}, raidus: {}".format(ref_ra,
ref_dec,
radius))
query_result = storage.cone_search(ref_ra, ref_dec, radius, radius) # returns an astropy.table.table.Table
print("Got {} possible images".format(len(query_result)))
ans = raw_input("Do you want to lookup IQ? (y/n)")
print("Building table for presentation and selection")
if ans == "y":
print("Including getting fwhm which is a bit slow.")
comparison_image_list = []
if len(query_result['collectionID']) > 0: # are there any comparison images even available on that sky?
index = -1
for row in query_result:
expnum = row['collectionID']
if expnum in self._bad_comparison_images:
continue
date = Time(row['mjdate'], format='mjd').mpc
if Time(row['mjdate'], format='mjd') < Time('2013-01-01 00:00:00', format='iso'):
continue
exptime = row['exptime']
if float(exptime) < 250:
continue
filter_name = row['filter']
if 'U' in filter_name:
continue
if filter_name.lower() in self.hdulist[-1].header['FILTER'].lower():
filter_name = "* {:8s}".format(filter_name)
fwhm = -1.0
if ans == 'y':
try:
fwhm = "{:5.2f}".format(float(storage.get_fwhm_tag(expnum, 22)))
except:
pass
index += 1
comparison_image_list.append([index, expnum, date, exptime, filter_name, fwhm, None])
self._comparison_image_list = Table(data=numpy.array(comparison_image_list),
names=["ID", "EXPNUM", "DATE-OBS", "EXPTIME", "FILTER", "FWHM", "REFERENCE"])
return self._comparison_image_list | python | def comparison_image_list(self):
"""
returns a list of possible comparison images for the current cutout. Will query CADC to create the list when
first called.
@rtype: Table
"""
if self._comparison_image_list is not None:
return self._comparison_image_list
ref_ra = self.reading.ra * units.degree
ref_dec = self.reading.dec * units.degree
radius = self.radius is not None and self.radius or config.read('CUTOUTS.SINGLETS.RADIUS') * units.arcminute
print("Querying CADC for list of possible comparison images at RA: {}, DEC: {}, raidus: {}".format(ref_ra,
ref_dec,
radius))
query_result = storage.cone_search(ref_ra, ref_dec, radius, radius) # returns an astropy.table.table.Table
print("Got {} possible images".format(len(query_result)))
ans = raw_input("Do you want to lookup IQ? (y/n)")
print("Building table for presentation and selection")
if ans == "y":
print("Including getting fwhm which is a bit slow.")
comparison_image_list = []
if len(query_result['collectionID']) > 0: # are there any comparison images even available on that sky?
index = -1
for row in query_result:
expnum = row['collectionID']
if expnum in self._bad_comparison_images:
continue
date = Time(row['mjdate'], format='mjd').mpc
if Time(row['mjdate'], format='mjd') < Time('2013-01-01 00:00:00', format='iso'):
continue
exptime = row['exptime']
if float(exptime) < 250:
continue
filter_name = row['filter']
if 'U' in filter_name:
continue
if filter_name.lower() in self.hdulist[-1].header['FILTER'].lower():
filter_name = "* {:8s}".format(filter_name)
fwhm = -1.0
if ans == 'y':
try:
fwhm = "{:5.2f}".format(float(storage.get_fwhm_tag(expnum, 22)))
except:
pass
index += 1
comparison_image_list.append([index, expnum, date, exptime, filter_name, fwhm, None])
self._comparison_image_list = Table(data=numpy.array(comparison_image_list),
names=["ID", "EXPNUM", "DATE-OBS", "EXPTIME", "FILTER", "FWHM", "REFERENCE"])
return self._comparison_image_list | [
"def",
"comparison_image_list",
"(",
"self",
")",
":",
"if",
"self",
".",
"_comparison_image_list",
"is",
"not",
"None",
":",
"return",
"self",
".",
"_comparison_image_list",
"ref_ra",
"=",
"self",
".",
"reading",
".",
"ra",
"*",
"units",
".",
"degree",
"ref... | returns a list of possible comparison images for the current cutout. Will query CADC to create the list when
first called.
@rtype: Table | [
"returns",
"a",
"list",
"of",
"possible",
"comparison",
"images",
"for",
"the",
"current",
"cutout",
".",
"Will",
"query",
"CADC",
"to",
"create",
"the",
"list",
"when",
"first",
"called",
"."
] | 94f91d32ad5ec081d5a1ebd67604a838003465af | https://github.com/OSSOS/MOP/blob/94f91d32ad5ec081d5a1ebd67604a838003465af/src/ossos/core/ossos/downloads/cutouts/source.py#L372-L422 | train | 47,907 |
OSSOS/MOP | src/ossos/core/ossos/downloads/cutouts/source.py | SourceCutout.retrieve_comparison_image | def retrieve_comparison_image(self):
"""
Search the DB for a comparison image for this cutout.
"""
# selecting comparator when on a comparator should load a new one.
collectionID = self.comparison_image_list[self.comparison_image_index]['EXPNUM']
ref_ra = self.reading.ra * units.degree
ref_dec = self.reading.dec * units.degree
radius = self.radius is not None and self.radius or config.read('CUTOUTS.SINGLETS.RADIUS') * units.arcminute
try:
comparison = collectionID
hdu_list = storage.ra_dec_cutout(storage.dbimages_uri(comparison),
SkyCoord(ref_ra, ref_dec), radius)
ccd = int(hdu_list[-1].header.get('EXTVER', 0))
obs = Observation(str(comparison), 'p',
ccdnum=ccd)
x = hdu_list[-1].header.get('NAXIS1', 0) // 2.0
y = hdu_list[-1].header.get('NAXIS2', 0) // 2.0
ref_ra = self.reading.ra * units.degree
ref_dec = self.reading.dec * units.degree
reading = SourceReading(x, y, self.reading.x, self.reading.y,
ref_ra, ref_dec, self.reading.x, self.reading.y, obs)
self.comparison_image_list[self.comparison_image_index]["REFERENCE"] = SourceCutout(reading, hdu_list)
except Exception as ex:
print traceback.format_exc()
print ex
print "Failed to load comparison image;"
self.comparison_image_index = None
logger.error("{} {}".format(type(ex), str(ex)))
logger.error(traceback.format_exc()) | python | def retrieve_comparison_image(self):
"""
Search the DB for a comparison image for this cutout.
"""
# selecting comparator when on a comparator should load a new one.
collectionID = self.comparison_image_list[self.comparison_image_index]['EXPNUM']
ref_ra = self.reading.ra * units.degree
ref_dec = self.reading.dec * units.degree
radius = self.radius is not None and self.radius or config.read('CUTOUTS.SINGLETS.RADIUS') * units.arcminute
try:
comparison = collectionID
hdu_list = storage.ra_dec_cutout(storage.dbimages_uri(comparison),
SkyCoord(ref_ra, ref_dec), radius)
ccd = int(hdu_list[-1].header.get('EXTVER', 0))
obs = Observation(str(comparison), 'p',
ccdnum=ccd)
x = hdu_list[-1].header.get('NAXIS1', 0) // 2.0
y = hdu_list[-1].header.get('NAXIS2', 0) // 2.0
ref_ra = self.reading.ra * units.degree
ref_dec = self.reading.dec * units.degree
reading = SourceReading(x, y, self.reading.x, self.reading.y,
ref_ra, ref_dec, self.reading.x, self.reading.y, obs)
self.comparison_image_list[self.comparison_image_index]["REFERENCE"] = SourceCutout(reading, hdu_list)
except Exception as ex:
print traceback.format_exc()
print ex
print "Failed to load comparison image;"
self.comparison_image_index = None
logger.error("{} {}".format(type(ex), str(ex)))
logger.error(traceback.format_exc()) | [
"def",
"retrieve_comparison_image",
"(",
"self",
")",
":",
"# selecting comparator when on a comparator should load a new one.",
"collectionID",
"=",
"self",
".",
"comparison_image_list",
"[",
"self",
".",
"comparison_image_index",
"]",
"[",
"'EXPNUM'",
"]",
"ref_ra",
"=",
... | Search the DB for a comparison image for this cutout. | [
"Search",
"the",
"DB",
"for",
"a",
"comparison",
"image",
"for",
"this",
"cutout",
"."
] | 94f91d32ad5ec081d5a1ebd67604a838003465af | https://github.com/OSSOS/MOP/blob/94f91d32ad5ec081d5a1ebd67604a838003465af/src/ossos/core/ossos/downloads/cutouts/source.py#L425-L454 | train | 47,908 |
OSSOS/MOP | src/ossos/web/web/auth/model.py | User.check_password | def check_password(self, passwd, group):
# This provides authentication via CADC.
"""check that the passwd provided matches the required password."""
return gms.isMember(self.login, passwd, group) | python | def check_password(self, passwd, group):
# This provides authentication via CADC.
"""check that the passwd provided matches the required password."""
return gms.isMember(self.login, passwd, group) | [
"def",
"check_password",
"(",
"self",
",",
"passwd",
",",
"group",
")",
":",
"# This provides authentication via CADC.",
"return",
"gms",
".",
"isMember",
"(",
"self",
".",
"login",
",",
"passwd",
",",
"group",
")"
] | check that the passwd provided matches the required password. | [
"check",
"that",
"the",
"passwd",
"provided",
"matches",
"the",
"required",
"password",
"."
] | 94f91d32ad5ec081d5a1ebd67604a838003465af | https://github.com/OSSOS/MOP/blob/94f91d32ad5ec081d5a1ebd67604a838003465af/src/ossos/web/web/auth/model.py#L22-L25 | train | 47,909 |
OSSOS/MOP | src/ossos/core/scripts/plant.py | plant | def plant(expnums, ccd, rmin, rmax, ang, width, number=10, mmin=21.0, mmax=25.5, version='s', dry_run=False):
"""Plant artificial sources into the list of images provided.
:param expnums: list of MegaPrime exposure numbers to add artificial KBOs to
:param ccd: which ccd to work on.
:param rmin: The minimum rate of motion to add sources at (''/hour)
:param rmax: The maximum rate of motion to add sources at (''/hour)
:param ang: The mean angle of motion to add sources
:param width: The +/- range of angles of motion
:param version: Add sources to the 'o', 'p' or 's' images
:param dry_run: don't push results to VOSpace.
"""
# Construct a list of artificial KBOs with positions in the image
# and rates of motion within the bounds given by the caller.
filename = storage.get_image(expnums[0],
ccd=ccd,
version=version)
header = fits.open(filename)[0].header
bounds = util.get_pixel_bounds_from_datasec_keyword(header.get('DATASEC', '[33:2080,1:4612]'))
# generate a set of artificial KBOs to add to the image.
kbos = KBOGenerator.get_kbos(n=number,
rate=(rmin, rmax),
angle=(ang - width, ang + width),
mag=(mmin, mmax),
x=(bounds[0][0], bounds[0][1]),
y=(bounds[1][0], bounds[1][1]),
filename='Object.planted')
for expnum in expnums:
filename = storage.get_image(expnum, ccd, version)
psf = storage.get_file(expnum, ccd, version, ext='psf.fits')
plant_kbos(filename, psf, kbos, get_shifts(expnum, ccd, version), "fk")
if dry_run:
return
uri = storage.get_uri('Object', ext='planted', version='',
subdir=str(
expnums[0]) + "/ccd%s" % (str(ccd).zfill(2)))
storage.copy('Object.planted', uri)
for expnum in expnums:
uri = storage.get_uri(expnum,
ccd=ccd,
version=version,
ext='fits', prefix='fk')
filename = os.path.basename(uri)
storage.copy(filename, uri)
return | python | def plant(expnums, ccd, rmin, rmax, ang, width, number=10, mmin=21.0, mmax=25.5, version='s', dry_run=False):
"""Plant artificial sources into the list of images provided.
:param expnums: list of MegaPrime exposure numbers to add artificial KBOs to
:param ccd: which ccd to work on.
:param rmin: The minimum rate of motion to add sources at (''/hour)
:param rmax: The maximum rate of motion to add sources at (''/hour)
:param ang: The mean angle of motion to add sources
:param width: The +/- range of angles of motion
:param version: Add sources to the 'o', 'p' or 's' images
:param dry_run: don't push results to VOSpace.
"""
# Construct a list of artificial KBOs with positions in the image
# and rates of motion within the bounds given by the caller.
filename = storage.get_image(expnums[0],
ccd=ccd,
version=version)
header = fits.open(filename)[0].header
bounds = util.get_pixel_bounds_from_datasec_keyword(header.get('DATASEC', '[33:2080,1:4612]'))
# generate a set of artificial KBOs to add to the image.
kbos = KBOGenerator.get_kbos(n=number,
rate=(rmin, rmax),
angle=(ang - width, ang + width),
mag=(mmin, mmax),
x=(bounds[0][0], bounds[0][1]),
y=(bounds[1][0], bounds[1][1]),
filename='Object.planted')
for expnum in expnums:
filename = storage.get_image(expnum, ccd, version)
psf = storage.get_file(expnum, ccd, version, ext='psf.fits')
plant_kbos(filename, psf, kbos, get_shifts(expnum, ccd, version), "fk")
if dry_run:
return
uri = storage.get_uri('Object', ext='planted', version='',
subdir=str(
expnums[0]) + "/ccd%s" % (str(ccd).zfill(2)))
storage.copy('Object.planted', uri)
for expnum in expnums:
uri = storage.get_uri(expnum,
ccd=ccd,
version=version,
ext='fits', prefix='fk')
filename = os.path.basename(uri)
storage.copy(filename, uri)
return | [
"def",
"plant",
"(",
"expnums",
",",
"ccd",
",",
"rmin",
",",
"rmax",
",",
"ang",
",",
"width",
",",
"number",
"=",
"10",
",",
"mmin",
"=",
"21.0",
",",
"mmax",
"=",
"25.5",
",",
"version",
"=",
"'s'",
",",
"dry_run",
"=",
"False",
")",
":",
"#... | Plant artificial sources into the list of images provided.
:param expnums: list of MegaPrime exposure numbers to add artificial KBOs to
:param ccd: which ccd to work on.
:param rmin: The minimum rate of motion to add sources at (''/hour)
:param rmax: The maximum rate of motion to add sources at (''/hour)
:param ang: The mean angle of motion to add sources
:param width: The +/- range of angles of motion
:param version: Add sources to the 'o', 'p' or 's' images
:param dry_run: don't push results to VOSpace. | [
"Plant",
"artificial",
"sources",
"into",
"the",
"list",
"of",
"images",
"provided",
"."
] | 94f91d32ad5ec081d5a1ebd67604a838003465af | https://github.com/OSSOS/MOP/blob/94f91d32ad5ec081d5a1ebd67604a838003465af/src/ossos/core/scripts/plant.py#L141-L192 | train | 47,910 |
OSSOS/MOP | src/ossos/core/ossos/kbo.py | Orbfit._fit_radec | def _fit_radec(self):
"""
call fit_radec of BK passing in the observations.
"""
# call fitradec with mpcfile, abgfile, resfile
self.orbfit.fitradec.restype = ctypes.c_int
self.orbfit.fitradec.argtypes = [ ctypes.c_char_p, ctypes.c_char_p, ctypes.c_char_p ]
mpc_file = tempfile.NamedTemporaryFile(suffix='.mpc')
for observation in self.observations:
mpc_file.write("{}\n".format(str(observation)))
mpc_file.seek(0)
abg_file = tempfile.NamedTemporaryFile()
res_file = tempfile.NamedTemporaryFile()
self.orbfit.fitradec(ctypes.c_char_p(mpc_file.name),
ctypes.c_char_p(abg_file.name),
ctypes.c_char_p(res_file.name))
self.abg = abg_file
self.abg.seek(0)
self.residuals = res_file
self.residuals.seek(0) | python | def _fit_radec(self):
"""
call fit_radec of BK passing in the observations.
"""
# call fitradec with mpcfile, abgfile, resfile
self.orbfit.fitradec.restype = ctypes.c_int
self.orbfit.fitradec.argtypes = [ ctypes.c_char_p, ctypes.c_char_p, ctypes.c_char_p ]
mpc_file = tempfile.NamedTemporaryFile(suffix='.mpc')
for observation in self.observations:
mpc_file.write("{}\n".format(str(observation)))
mpc_file.seek(0)
abg_file = tempfile.NamedTemporaryFile()
res_file = tempfile.NamedTemporaryFile()
self.orbfit.fitradec(ctypes.c_char_p(mpc_file.name),
ctypes.c_char_p(abg_file.name),
ctypes.c_char_p(res_file.name))
self.abg = abg_file
self.abg.seek(0)
self.residuals = res_file
self.residuals.seek(0) | [
"def",
"_fit_radec",
"(",
"self",
")",
":",
"# call fitradec with mpcfile, abgfile, resfile",
"self",
".",
"orbfit",
".",
"fitradec",
".",
"restype",
"=",
"ctypes",
".",
"c_int",
"self",
".",
"orbfit",
".",
"fitradec",
".",
"argtypes",
"=",
"[",
"ctypes",
".",... | call fit_radec of BK passing in the observations. | [
"call",
"fit_radec",
"of",
"BK",
"passing",
"in",
"the",
"observations",
"."
] | 94f91d32ad5ec081d5a1ebd67604a838003465af | https://github.com/OSSOS/MOP/blob/94f91d32ad5ec081d5a1ebd67604a838003465af/src/ossos/core/ossos/kbo.py#L21-L46 | train | 47,911 |
OSSOS/MOP | src/ossos/core/ossos/kbo.py | Orbfit.predict | def predict(self, date, obs_code=568):
"""
use the bk predict method to compute the location of the source on the given date.
"""
time = Time(date, scale='utc', precision=6)
jd = ctypes.c_double(time.jd)
# call predict with agbfile, jdate, obscode
self.orbfit.predict.restype = ctypes.POINTER(ctypes.c_double * 5)
self.orbfit.predict.argtypes = [ ctypes.c_char_p, ctypes.c_double, ctypes.c_int ]
predict = self.orbfit.predict(ctypes.c_char_p(self.abg.name),
jd,
ctypes.c_int(obs_code))
self.coordinate = coordinates.SkyCoord(predict.contents[0],
predict.contents[1],
unit=(units.degree, units.degree))
self.dra = predict.contents[2]
self.ddec = predict.contents[3]
self.pa = predict.contents[4]
self.date = str(time) | python | def predict(self, date, obs_code=568):
"""
use the bk predict method to compute the location of the source on the given date.
"""
time = Time(date, scale='utc', precision=6)
jd = ctypes.c_double(time.jd)
# call predict with agbfile, jdate, obscode
self.orbfit.predict.restype = ctypes.POINTER(ctypes.c_double * 5)
self.orbfit.predict.argtypes = [ ctypes.c_char_p, ctypes.c_double, ctypes.c_int ]
predict = self.orbfit.predict(ctypes.c_char_p(self.abg.name),
jd,
ctypes.c_int(obs_code))
self.coordinate = coordinates.SkyCoord(predict.contents[0],
predict.contents[1],
unit=(units.degree, units.degree))
self.dra = predict.contents[2]
self.ddec = predict.contents[3]
self.pa = predict.contents[4]
self.date = str(time) | [
"def",
"predict",
"(",
"self",
",",
"date",
",",
"obs_code",
"=",
"568",
")",
":",
"time",
"=",
"Time",
"(",
"date",
",",
"scale",
"=",
"'utc'",
",",
"precision",
"=",
"6",
")",
"jd",
"=",
"ctypes",
".",
"c_double",
"(",
"time",
".",
"jd",
")",
... | use the bk predict method to compute the location of the source on the given date. | [
"use",
"the",
"bk",
"predict",
"method",
"to",
"compute",
"the",
"location",
"of",
"the",
"source",
"on",
"the",
"given",
"date",
"."
] | 94f91d32ad5ec081d5a1ebd67604a838003465af | https://github.com/OSSOS/MOP/blob/94f91d32ad5ec081d5a1ebd67604a838003465af/src/ossos/core/ossos/kbo.py#L48-L66 | train | 47,912 |
OSSOS/MOP | src/jjk/preproc/MOPfiles.py | write | def write(file,hdu,order=None,format=None):
"""Write a file in the crazy MOP format given an mop data hdu."""
if order or format:
warnings.warn('Use of <order> and <format> depricated',DeprecationWarning)
## if the order of the columns isn't constrained just use the keys in what ever order
data='data'
if not order:
if not hdu.has_key('order'):
hdu['order']=hdu[data].keys()
else:
hdu['order']=order
if not format:
if not hdu.has_key('format'):
hdu['format']={}
for o in hdu['order']:
if not hdu['format'].has_key(o):
hdu['format'][o]='%10s'
else:
hdu['format']=format
f=open(file,'w')
kline='## '
vline='# '
header='header'
num=0
for keyword in hdu[header]:
kline+='%10s ' % (keyword, )
vline+='%10s ' % str(hdu[header][keyword])
num+=1
if not ( num % 6 ) :
num=0
f.write(kline+'\n')
f.write(vline+'\n')
kline='## '
vline='# '
if num > 0:
f.write(kline+'\n')
f.write(vline+'\n')
f.write('## ')
for column in hdu['order']:
f.write(' %10s' % (column))
f.write('\n')
dlen=len(hdu[data][hdu['order'][0]])
for i in range(dlen):
f.write(' ')
for column in hdu['order']:
f.write(hdu['format'][column] % (hdu[data][column][i]))
f.write(' ')
f.write('\n')
f.close()
return | python | def write(file,hdu,order=None,format=None):
"""Write a file in the crazy MOP format given an mop data hdu."""
if order or format:
warnings.warn('Use of <order> and <format> depricated',DeprecationWarning)
## if the order of the columns isn't constrained just use the keys in what ever order
data='data'
if not order:
if not hdu.has_key('order'):
hdu['order']=hdu[data].keys()
else:
hdu['order']=order
if not format:
if not hdu.has_key('format'):
hdu['format']={}
for o in hdu['order']:
if not hdu['format'].has_key(o):
hdu['format'][o]='%10s'
else:
hdu['format']=format
f=open(file,'w')
kline='## '
vline='# '
header='header'
num=0
for keyword in hdu[header]:
kline+='%10s ' % (keyword, )
vline+='%10s ' % str(hdu[header][keyword])
num+=1
if not ( num % 6 ) :
num=0
f.write(kline+'\n')
f.write(vline+'\n')
kline='## '
vline='# '
if num > 0:
f.write(kline+'\n')
f.write(vline+'\n')
f.write('## ')
for column in hdu['order']:
f.write(' %10s' % (column))
f.write('\n')
dlen=len(hdu[data][hdu['order'][0]])
for i in range(dlen):
f.write(' ')
for column in hdu['order']:
f.write(hdu['format'][column] % (hdu[data][column][i]))
f.write(' ')
f.write('\n')
f.close()
return | [
"def",
"write",
"(",
"file",
",",
"hdu",
",",
"order",
"=",
"None",
",",
"format",
"=",
"None",
")",
":",
"if",
"order",
"or",
"format",
":",
"warnings",
".",
"warn",
"(",
"'Use of <order> and <format> depricated'",
",",
"DeprecationWarning",
")",
"## if the... | Write a file in the crazy MOP format given an mop data hdu. | [
"Write",
"a",
"file",
"in",
"the",
"crazy",
"MOP",
"format",
"given",
"an",
"mop",
"data",
"hdu",
"."
] | 94f91d32ad5ec081d5a1ebd67604a838003465af | https://github.com/OSSOS/MOP/blob/94f91d32ad5ec081d5a1ebd67604a838003465af/src/jjk/preproc/MOPfiles.py#L57-L112 | train | 47,913 |
OSSOS/MOP | src/jjk/preproc/MOPfiles.py | read | def read(file):
"""Read in a file and create a data strucuture that is a hash with members 'header'
and 'data'. The 'header' is a hash of header keywords, the data is a hash of columns.
To get to the nth element of column NAME use hdu[data][NAME][n]. To get the header
information use hdu[header][KEYWORD]. """
f = open(file,'r')
lines=f.readlines()
f.close()
import re, string
keywords=[]
values=[]
formats={}
header={}
cdata={}
for line in lines:
if ( re.match(r'^##',line)):
## header line
m=string.split(string.lstrip(line[2:]))
if not m:
sys.stderr.write( "Ill formed header line in %s \ n " % ( file, ))
sys.stderr.write( line)
continue
keywords=m
add_id=False
continue
if ( re.match(r'^# ',line)):
## this is a keyword value line, must match the previous keyword line
m=string.split(string.lstrip(line[1:]))
values=m
if len(values)!= len(keywords):
sys.stderr.write( "Ill formed header, keyword/value missmatach\n")
for index in range(len(values)):
header[keywords[index]]=values[index]
## blank the arrays, we've already stuck this into the header
keywords=[]
values=[]
continue
if ( re.match(r'^#F',line)):
## this is a format line for the columns needs to be a keyword line first
if not keywords:
sys.stderr.write("Cann't have formats without column names...\n")
continue
f=string.split(string.lstrip(line))
if add_id:
f.append('%8d')
for col in keywords:
formats[col]=f.pop(0)
### must be the actual data
### expect a previous header line to define column headers
if not keywords:
sys.stderr.write( "No keywords for data columns, assuming x,y,mag,msky\n")
keywords=('X','Y','MAG','MSKY')
values = string.split(string.lstrip(line))
### add the id value to the values array if needed
if not 'ID' in keywords:
keywords.append('ID')
add_id=True
if not cdata:
for keyword in keywords:
cdata[keyword]=[]
if add_id:
values.append(len(cdata[keywords[0]])+1)
if len(values)!=len(keywords):
sys.stderr.write("Keyword and value index have different length?\n")
continue
for index in range(len(values)):
cdata[keywords[index]].append(values[index])
hdu={'data': cdata, 'header': header, 'format': formats, 'order': keywords}
### the hdu is a dictionary with the header and data
return hdu | python | def read(file):
"""Read in a file and create a data strucuture that is a hash with members 'header'
and 'data'. The 'header' is a hash of header keywords, the data is a hash of columns.
To get to the nth element of column NAME use hdu[data][NAME][n]. To get the header
information use hdu[header][KEYWORD]. """
f = open(file,'r')
lines=f.readlines()
f.close()
import re, string
keywords=[]
values=[]
formats={}
header={}
cdata={}
for line in lines:
if ( re.match(r'^##',line)):
## header line
m=string.split(string.lstrip(line[2:]))
if not m:
sys.stderr.write( "Ill formed header line in %s \ n " % ( file, ))
sys.stderr.write( line)
continue
keywords=m
add_id=False
continue
if ( re.match(r'^# ',line)):
## this is a keyword value line, must match the previous keyword line
m=string.split(string.lstrip(line[1:]))
values=m
if len(values)!= len(keywords):
sys.stderr.write( "Ill formed header, keyword/value missmatach\n")
for index in range(len(values)):
header[keywords[index]]=values[index]
## blank the arrays, we've already stuck this into the header
keywords=[]
values=[]
continue
if ( re.match(r'^#F',line)):
## this is a format line for the columns needs to be a keyword line first
if not keywords:
sys.stderr.write("Cann't have formats without column names...\n")
continue
f=string.split(string.lstrip(line))
if add_id:
f.append('%8d')
for col in keywords:
formats[col]=f.pop(0)
### must be the actual data
### expect a previous header line to define column headers
if not keywords:
sys.stderr.write( "No keywords for data columns, assuming x,y,mag,msky\n")
keywords=('X','Y','MAG','MSKY')
values = string.split(string.lstrip(line))
### add the id value to the values array if needed
if not 'ID' in keywords:
keywords.append('ID')
add_id=True
if not cdata:
for keyword in keywords:
cdata[keyword]=[]
if add_id:
values.append(len(cdata[keywords[0]])+1)
if len(values)!=len(keywords):
sys.stderr.write("Keyword and value index have different length?\n")
continue
for index in range(len(values)):
cdata[keywords[index]].append(values[index])
hdu={'data': cdata, 'header': header, 'format': formats, 'order': keywords}
### the hdu is a dictionary with the header and data
return hdu | [
"def",
"read",
"(",
"file",
")",
":",
"f",
"=",
"open",
"(",
"file",
",",
"'r'",
")",
"lines",
"=",
"f",
".",
"readlines",
"(",
")",
"f",
".",
"close",
"(",
")",
"import",
"re",
",",
"string",
"keywords",
"=",
"[",
"]",
"values",
"=",
"[",
"]... | Read in a file and create a data strucuture that is a hash with members 'header'
and 'data'. The 'header' is a hash of header keywords, the data is a hash of columns.
To get to the nth element of column NAME use hdu[data][NAME][n]. To get the header
information use hdu[header][KEYWORD]. | [
"Read",
"in",
"a",
"file",
"and",
"create",
"a",
"data",
"strucuture",
"that",
"is",
"a",
"hash",
"with",
"members",
"header",
"and",
"data",
".",
"The",
"header",
"is",
"a",
"hash",
"of",
"header",
"keywords",
"the",
"data",
"is",
"a",
"hash",
"of",
... | 94f91d32ad5ec081d5a1ebd67604a838003465af | https://github.com/OSSOS/MOP/blob/94f91d32ad5ec081d5a1ebd67604a838003465af/src/jjk/preproc/MOPfiles.py#L168-L242 | train | 47,914 |
playpauseandstop/rororo | rororo/logger.py | default_logging_dict | def default_logging_dict(*loggers: str, **kwargs: Any) -> DictStrAny:
r"""Prepare logging dict suitable with ``logging.config.dictConfig``.
**Usage**::
from logging.config import dictConfig
dictConfig(default_logging_dict('yourlogger'))
:param \*loggers: Enable logging for each logger in sequence.
:param \*\*kwargs: Setup additional logger params via keyword arguments.
"""
kwargs.setdefault('level', 'INFO')
return {
'version': 1,
'disable_existing_loggers': True,
'filters': {
'ignore_errors': {
'()': IgnoreErrorsFilter,
},
},
'formatters': {
'default': {
'format': '%(asctime)s [%(levelname)s:%(name)s] %(message)s',
},
'naked': {
'format': u'%(message)s',
},
},
'handlers': {
'stdout': {
'class': 'logging.StreamHandler',
'filters': ['ignore_errors'],
'formatter': 'default',
'level': 'DEBUG',
'stream': sys.stdout,
},
'stderr': {
'class': 'logging.StreamHandler',
'formatter': 'default',
'level': 'WARNING',
'stream': sys.stderr,
},
},
'loggers': {
logger: dict(handlers=['stdout', 'stderr'], **kwargs)
for logger in loggers
},
} | python | def default_logging_dict(*loggers: str, **kwargs: Any) -> DictStrAny:
r"""Prepare logging dict suitable with ``logging.config.dictConfig``.
**Usage**::
from logging.config import dictConfig
dictConfig(default_logging_dict('yourlogger'))
:param \*loggers: Enable logging for each logger in sequence.
:param \*\*kwargs: Setup additional logger params via keyword arguments.
"""
kwargs.setdefault('level', 'INFO')
return {
'version': 1,
'disable_existing_loggers': True,
'filters': {
'ignore_errors': {
'()': IgnoreErrorsFilter,
},
},
'formatters': {
'default': {
'format': '%(asctime)s [%(levelname)s:%(name)s] %(message)s',
},
'naked': {
'format': u'%(message)s',
},
},
'handlers': {
'stdout': {
'class': 'logging.StreamHandler',
'filters': ['ignore_errors'],
'formatter': 'default',
'level': 'DEBUG',
'stream': sys.stdout,
},
'stderr': {
'class': 'logging.StreamHandler',
'formatter': 'default',
'level': 'WARNING',
'stream': sys.stderr,
},
},
'loggers': {
logger: dict(handlers=['stdout', 'stderr'], **kwargs)
for logger in loggers
},
} | [
"def",
"default_logging_dict",
"(",
"*",
"loggers",
":",
"str",
",",
"*",
"*",
"kwargs",
":",
"Any",
")",
"->",
"DictStrAny",
":",
"kwargs",
".",
"setdefault",
"(",
"'level'",
",",
"'INFO'",
")",
"return",
"{",
"'version'",
":",
"1",
",",
"'disable_exist... | r"""Prepare logging dict suitable with ``logging.config.dictConfig``.
**Usage**::
from logging.config import dictConfig
dictConfig(default_logging_dict('yourlogger'))
:param \*loggers: Enable logging for each logger in sequence.
:param \*\*kwargs: Setup additional logger params via keyword arguments. | [
"r",
"Prepare",
"logging",
"dict",
"suitable",
"with",
"logging",
".",
"config",
".",
"dictConfig",
"."
] | 28a04e8028c29647941e727116335e9d6fd64c27 | https://github.com/playpauseandstop/rororo/blob/28a04e8028c29647941e727116335e9d6fd64c27/rororo/logger.py#L28-L75 | train | 47,915 |
playpauseandstop/rororo | rororo/logger.py | update_sentry_logging | def update_sentry_logging(logging_dict: DictStrAny,
sentry_dsn: Optional[str],
*loggers: str,
level: Union[str, int] = None,
**kwargs: Any) -> None:
r"""Enable Sentry logging if Sentry DSN passed.
.. note::
Sentry logging requires `raven <http://pypi.python.org/pypi/raven>`_
library to be installed.
**Usage**::
from logging.config import dictConfig
LOGGING = default_logging_dict()
SENTRY_DSN = '...'
update_sentry_logging(LOGGING, SENTRY_DSN)
dictConfig(LOGGING)
**Using AioHttpTransport for SentryHandler**
This will allow to use ``aiohttp.client`` for pushing data to Sentry in
your ``aiohttp.web`` app, which means elimination of sync calls to Sentry.
::
from raven_aiohttp import AioHttpTransport
update_sentry_logging(LOGGING, SENTRY_DSN, transport=AioHttpTransport)
:param logging_dict: Logging dict.
:param sentry_dsn:
Sentry DSN value. If ``None`` do not update logging dict at all.
:param \*loggers:
Use Sentry logging for each logger in the sequence. If the sequence is
empty use Sentry logging to each available logger.
:param \*\*kwargs: Additional kwargs to be passed to ``SentryHandler``.
"""
# No Sentry DSN, nothing to do
if not sentry_dsn:
return
# Add Sentry handler
kwargs['class'] = 'raven.handlers.logging.SentryHandler'
kwargs['dsn'] = sentry_dsn
logging_dict['handlers']['sentry'] = dict(
level=level or 'WARNING',
**kwargs)
loggers = tuple(logging_dict['loggers']) if not loggers else loggers
for logger in loggers:
# Ignore missing loggers
logger_dict = logging_dict['loggers'].get(logger)
if not logger_dict:
continue
# Ignore logger from logger config
if logger_dict.pop('ignore_sentry', False):
continue
# Handlers list should exist
handlers = list(logger_dict.setdefault('handlers', []))
handlers.append('sentry')
logger_dict['handlers'] = tuple(handlers) | python | def update_sentry_logging(logging_dict: DictStrAny,
sentry_dsn: Optional[str],
*loggers: str,
level: Union[str, int] = None,
**kwargs: Any) -> None:
r"""Enable Sentry logging if Sentry DSN passed.
.. note::
Sentry logging requires `raven <http://pypi.python.org/pypi/raven>`_
library to be installed.
**Usage**::
from logging.config import dictConfig
LOGGING = default_logging_dict()
SENTRY_DSN = '...'
update_sentry_logging(LOGGING, SENTRY_DSN)
dictConfig(LOGGING)
**Using AioHttpTransport for SentryHandler**
This will allow to use ``aiohttp.client`` for pushing data to Sentry in
your ``aiohttp.web`` app, which means elimination of sync calls to Sentry.
::
from raven_aiohttp import AioHttpTransport
update_sentry_logging(LOGGING, SENTRY_DSN, transport=AioHttpTransport)
:param logging_dict: Logging dict.
:param sentry_dsn:
Sentry DSN value. If ``None`` do not update logging dict at all.
:param \*loggers:
Use Sentry logging for each logger in the sequence. If the sequence is
empty use Sentry logging to each available logger.
:param \*\*kwargs: Additional kwargs to be passed to ``SentryHandler``.
"""
# No Sentry DSN, nothing to do
if not sentry_dsn:
return
# Add Sentry handler
kwargs['class'] = 'raven.handlers.logging.SentryHandler'
kwargs['dsn'] = sentry_dsn
logging_dict['handlers']['sentry'] = dict(
level=level or 'WARNING',
**kwargs)
loggers = tuple(logging_dict['loggers']) if not loggers else loggers
for logger in loggers:
# Ignore missing loggers
logger_dict = logging_dict['loggers'].get(logger)
if not logger_dict:
continue
# Ignore logger from logger config
if logger_dict.pop('ignore_sentry', False):
continue
# Handlers list should exist
handlers = list(logger_dict.setdefault('handlers', []))
handlers.append('sentry')
logger_dict['handlers'] = tuple(handlers) | [
"def",
"update_sentry_logging",
"(",
"logging_dict",
":",
"DictStrAny",
",",
"sentry_dsn",
":",
"Optional",
"[",
"str",
"]",
",",
"*",
"loggers",
":",
"str",
",",
"level",
":",
"Union",
"[",
"str",
",",
"int",
"]",
"=",
"None",
",",
"*",
"*",
"kwargs",... | r"""Enable Sentry logging if Sentry DSN passed.
.. note::
Sentry logging requires `raven <http://pypi.python.org/pypi/raven>`_
library to be installed.
**Usage**::
from logging.config import dictConfig
LOGGING = default_logging_dict()
SENTRY_DSN = '...'
update_sentry_logging(LOGGING, SENTRY_DSN)
dictConfig(LOGGING)
**Using AioHttpTransport for SentryHandler**
This will allow to use ``aiohttp.client`` for pushing data to Sentry in
your ``aiohttp.web`` app, which means elimination of sync calls to Sentry.
::
from raven_aiohttp import AioHttpTransport
update_sentry_logging(LOGGING, SENTRY_DSN, transport=AioHttpTransport)
:param logging_dict: Logging dict.
:param sentry_dsn:
Sentry DSN value. If ``None`` do not update logging dict at all.
:param \*loggers:
Use Sentry logging for each logger in the sequence. If the sequence is
empty use Sentry logging to each available logger.
:param \*\*kwargs: Additional kwargs to be passed to ``SentryHandler``. | [
"r",
"Enable",
"Sentry",
"logging",
"if",
"Sentry",
"DSN",
"passed",
"."
] | 28a04e8028c29647941e727116335e9d6fd64c27 | https://github.com/playpauseandstop/rororo/blob/28a04e8028c29647941e727116335e9d6fd64c27/rororo/logger.py#L78-L142 | train | 47,916 |
OSSOS/MOP | src/ossos/core/ossos/parsers.py | ossos_release_parser | def ossos_release_parser(table=False, data_release=parameters.RELEASE_VERSION):
"""
extra fun as this is space-separated so using CSV parsers is not an option
"""
names = ['cl', 'p', 'j', 'k', 'sh', 'object', 'mag', 'e_mag', 'Filt', 'Hsur', 'dist', 'e_dist', 'Nobs',
'time', 'av_xres', 'av_yres', 'max_x', 'max_y', 'a', 'e_a', 'e', 'e_e', 'i', 'e_i', 'Omega', 'e_Omega',
'omega', 'e_omega', 'tperi', 'e_tperi', 'RAdeg', 'DEdeg', 'JD', 'rate']#, 'eff', 'm_lim']
if table:
retval = Table.read(parameters.RELEASE_DETECTIONS[data_release], format='ascii', guess=False,
delimiter=' ', data_start=0, comment='#', names=names, header_start=None)
else:
retval = []
with open(data_release, 'r') as detectionsfile:
for line in detectionsfile.readlines()[1:]: # first line is column definitions
obj = TNO.from_string(line, version=parameters.RELEASE_DETECTIONS[data_release])
retval.append(obj)
return retval | python | def ossos_release_parser(table=False, data_release=parameters.RELEASE_VERSION):
"""
extra fun as this is space-separated so using CSV parsers is not an option
"""
names = ['cl', 'p', 'j', 'k', 'sh', 'object', 'mag', 'e_mag', 'Filt', 'Hsur', 'dist', 'e_dist', 'Nobs',
'time', 'av_xres', 'av_yres', 'max_x', 'max_y', 'a', 'e_a', 'e', 'e_e', 'i', 'e_i', 'Omega', 'e_Omega',
'omega', 'e_omega', 'tperi', 'e_tperi', 'RAdeg', 'DEdeg', 'JD', 'rate']#, 'eff', 'm_lim']
if table:
retval = Table.read(parameters.RELEASE_DETECTIONS[data_release], format='ascii', guess=False,
delimiter=' ', data_start=0, comment='#', names=names, header_start=None)
else:
retval = []
with open(data_release, 'r') as detectionsfile:
for line in detectionsfile.readlines()[1:]: # first line is column definitions
obj = TNO.from_string(line, version=parameters.RELEASE_DETECTIONS[data_release])
retval.append(obj)
return retval | [
"def",
"ossos_release_parser",
"(",
"table",
"=",
"False",
",",
"data_release",
"=",
"parameters",
".",
"RELEASE_VERSION",
")",
":",
"names",
"=",
"[",
"'cl'",
",",
"'p'",
",",
"'j'",
",",
"'k'",
",",
"'sh'",
",",
"'object'",
",",
"'mag'",
",",
"'e_mag'"... | extra fun as this is space-separated so using CSV parsers is not an option | [
"extra",
"fun",
"as",
"this",
"is",
"space",
"-",
"separated",
"so",
"using",
"CSV",
"parsers",
"is",
"not",
"an",
"option"
] | 94f91d32ad5ec081d5a1ebd67604a838003465af | https://github.com/OSSOS/MOP/blob/94f91d32ad5ec081d5a1ebd67604a838003465af/src/ossos/core/ossos/parsers.py#L23-L41 | train | 47,917 |
OSSOS/MOP | src/ossos/core/ossos/parsers.py | ossos_discoveries | def ossos_discoveries(directory=parameters.REAL_KBO_AST_DIR,
suffix='ast',
no_nt_and_u=False,
single_object=None,
all_objects=True,
data_release=None,
):
"""
Returns a list of objects holding orbfit.Orbfit objects with the observations in the Orbfit.observations field.
Default is to return only the objects corresponding to the current Data Release.
"""
retval = []
# working_context = context.get_context(directory)
# files = working_context.get_listing(suffix)
files = [f for f in os.listdir(directory) if (f.endswith('mpc') or f.endswith('ast') or f.endswith('DONE'))]
if single_object is not None:
files = filter(lambda name: name.startswith(single_object), files)
elif all_objects and data_release is not None:
# only return the objects corresponding to a particular Data Release
data_release = ossos_release_parser(table=True, data_release=data_release)
objects = data_release['object']
files = filter(lambda name: name.partition(suffix)[0].rstrip('.') in objects, files)
for filename in files:
# keep out the not-tracked and uncharacteried.
if no_nt_and_u and (filename.__contains__('nt') or filename.startswith('u')):
continue
# observations = mpc.MPCReader(directory + filename)
mpc_filename = directory + filename
abg_filename = os.path.abspath(directory + '/../abg/') + "/" + os.path.splitext(filename)[0] + ".abg"
obj = TNO(None, ast_filename=mpc_filename, abg_filename=abg_filename)
retval.append(obj)
return retval | python | def ossos_discoveries(directory=parameters.REAL_KBO_AST_DIR,
suffix='ast',
no_nt_and_u=False,
single_object=None,
all_objects=True,
data_release=None,
):
"""
Returns a list of objects holding orbfit.Orbfit objects with the observations in the Orbfit.observations field.
Default is to return only the objects corresponding to the current Data Release.
"""
retval = []
# working_context = context.get_context(directory)
# files = working_context.get_listing(suffix)
files = [f for f in os.listdir(directory) if (f.endswith('mpc') or f.endswith('ast') or f.endswith('DONE'))]
if single_object is not None:
files = filter(lambda name: name.startswith(single_object), files)
elif all_objects and data_release is not None:
# only return the objects corresponding to a particular Data Release
data_release = ossos_release_parser(table=True, data_release=data_release)
objects = data_release['object']
files = filter(lambda name: name.partition(suffix)[0].rstrip('.') in objects, files)
for filename in files:
# keep out the not-tracked and uncharacteried.
if no_nt_and_u and (filename.__contains__('nt') or filename.startswith('u')):
continue
# observations = mpc.MPCReader(directory + filename)
mpc_filename = directory + filename
abg_filename = os.path.abspath(directory + '/../abg/') + "/" + os.path.splitext(filename)[0] + ".abg"
obj = TNO(None, ast_filename=mpc_filename, abg_filename=abg_filename)
retval.append(obj)
return retval | [
"def",
"ossos_discoveries",
"(",
"directory",
"=",
"parameters",
".",
"REAL_KBO_AST_DIR",
",",
"suffix",
"=",
"'ast'",
",",
"no_nt_and_u",
"=",
"False",
",",
"single_object",
"=",
"None",
",",
"all_objects",
"=",
"True",
",",
"data_release",
"=",
"None",
",",
... | Returns a list of objects holding orbfit.Orbfit objects with the observations in the Orbfit.observations field.
Default is to return only the objects corresponding to the current Data Release. | [
"Returns",
"a",
"list",
"of",
"objects",
"holding",
"orbfit",
".",
"Orbfit",
"objects",
"with",
"the",
"observations",
"in",
"the",
"Orbfit",
".",
"observations",
"field",
".",
"Default",
"is",
"to",
"return",
"only",
"the",
"objects",
"corresponding",
"to",
... | 94f91d32ad5ec081d5a1ebd67604a838003465af | https://github.com/OSSOS/MOP/blob/94f91d32ad5ec081d5a1ebd67604a838003465af/src/ossos/core/ossos/parsers.py#L83-L117 | train | 47,918 |
OSSOS/MOP | src/ossos/core/ossos/parsers.py | ossos_release_with_metadata | def ossos_release_with_metadata():
"""
Wrap the objects from the Version Releases together with the objects instantiated from fitting their mpc lines
"""
# discoveries = ossos_release_parser()
discoveries = []
observations = ossos_discoveries()
for obj in observations:
discov = [n for n in obj[0].mpc_observations if n.discovery.is_discovery][0]
tno = parameters.tno()
tno.dist = obj[1].distance
tno.ra_discov = discov.coordinate.ra.degrees
tno.mag = discov.mag
tno.name = discov.provisional_name
discoveries.append(tno)
# for obj in discoveries:
# observation = [n for n in observations if n.observations[-1].provisional_name == obj.name][0]
# for obs in observation.observations:
# if obs.discovery.is_discovery:
# if obj.mag is not None:
# H = obj.mag + 2.5 * math.log10(1. / ((obj.dist ** 2) * ((obj.dist - 1.) ** 2)))
# else:
# H = None
# obj.H = H
# obj.T = observation.T
# obj.discovery_date = obs.date
# obj.observations = observation
return discoveries | python | def ossos_release_with_metadata():
"""
Wrap the objects from the Version Releases together with the objects instantiated from fitting their mpc lines
"""
# discoveries = ossos_release_parser()
discoveries = []
observations = ossos_discoveries()
for obj in observations:
discov = [n for n in obj[0].mpc_observations if n.discovery.is_discovery][0]
tno = parameters.tno()
tno.dist = obj[1].distance
tno.ra_discov = discov.coordinate.ra.degrees
tno.mag = discov.mag
tno.name = discov.provisional_name
discoveries.append(tno)
# for obj in discoveries:
# observation = [n for n in observations if n.observations[-1].provisional_name == obj.name][0]
# for obs in observation.observations:
# if obs.discovery.is_discovery:
# if obj.mag is not None:
# H = obj.mag + 2.5 * math.log10(1. / ((obj.dist ** 2) * ((obj.dist - 1.) ** 2)))
# else:
# H = None
# obj.H = H
# obj.T = observation.T
# obj.discovery_date = obs.date
# obj.observations = observation
return discoveries | [
"def",
"ossos_release_with_metadata",
"(",
")",
":",
"# discoveries = ossos_release_parser()",
"discoveries",
"=",
"[",
"]",
"observations",
"=",
"ossos_discoveries",
"(",
")",
"for",
"obj",
"in",
"observations",
":",
"discov",
"=",
"[",
"n",
"for",
"n",
"in",
"... | Wrap the objects from the Version Releases together with the objects instantiated from fitting their mpc lines | [
"Wrap",
"the",
"objects",
"from",
"the",
"Version",
"Releases",
"together",
"with",
"the",
"objects",
"instantiated",
"from",
"fitting",
"their",
"mpc",
"lines"
] | 94f91d32ad5ec081d5a1ebd67604a838003465af | https://github.com/OSSOS/MOP/blob/94f91d32ad5ec081d5a1ebd67604a838003465af/src/ossos/core/ossos/parsers.py#L120-L149 | train | 47,919 |
OSSOS/MOP | src/ossos/core/ossos/parsers.py | _kbos_from_survey_sym_model_input_file | def _kbos_from_survey_sym_model_input_file(model_file):
"""
Load a Survey Simulator model file as an array of ephem EllipticalBody objects.
@param model_file:
@return:
"""
lines = storage.open_vos_or_local(model_file).read().split('\n')
kbos = []
for line in lines:
if len(line) == 0 or line[0] == '#': # skip initial column descriptors and the final blank line
continue
kbo = ephem.EllipticalBody()
values = line.split()
kbo.name = values[8]
kbo.j = values[9]
kbo.k = values[10]
kbo._a = float(values[0])
kbo._e = float(values[1])
kbo._inc = float(values[2])
kbo._Om = float(values[3])
kbo._om = float(values[4])
kbo._M = float(values[5])
kbo._H = float(values[6])
epoch = ephem.date(2453157.50000 - ephem.julian_date(0))
kbo._epoch_M = epoch
kbo._epoch = epoch
kbos.append(kbo)
return kbos | python | def _kbos_from_survey_sym_model_input_file(model_file):
"""
Load a Survey Simulator model file as an array of ephem EllipticalBody objects.
@param model_file:
@return:
"""
lines = storage.open_vos_or_local(model_file).read().split('\n')
kbos = []
for line in lines:
if len(line) == 0 or line[0] == '#': # skip initial column descriptors and the final blank line
continue
kbo = ephem.EllipticalBody()
values = line.split()
kbo.name = values[8]
kbo.j = values[9]
kbo.k = values[10]
kbo._a = float(values[0])
kbo._e = float(values[1])
kbo._inc = float(values[2])
kbo._Om = float(values[3])
kbo._om = float(values[4])
kbo._M = float(values[5])
kbo._H = float(values[6])
epoch = ephem.date(2453157.50000 - ephem.julian_date(0))
kbo._epoch_M = epoch
kbo._epoch = epoch
kbos.append(kbo)
return kbos | [
"def",
"_kbos_from_survey_sym_model_input_file",
"(",
"model_file",
")",
":",
"lines",
"=",
"storage",
".",
"open_vos_or_local",
"(",
"model_file",
")",
".",
"read",
"(",
")",
".",
"split",
"(",
"'\\n'",
")",
"kbos",
"=",
"[",
"]",
"for",
"line",
"in",
"li... | Load a Survey Simulator model file as an array of ephem EllipticalBody objects.
@param model_file:
@return: | [
"Load",
"a",
"Survey",
"Simulator",
"model",
"file",
"as",
"an",
"array",
"of",
"ephem",
"EllipticalBody",
"objects",
"."
] | 94f91d32ad5ec081d5a1ebd67604a838003465af | https://github.com/OSSOS/MOP/blob/94f91d32ad5ec081d5a1ebd67604a838003465af/src/ossos/core/ossos/parsers.py#L152-L179 | train | 47,920 |
openstack/python-scciclient | scciclient/irmc/elcm.py | _parse_elcm_response_body_as_json | def _parse_elcm_response_body_as_json(response):
"""parse eLCM response body as json data
eLCM response should be in form of:
_
Key1: value1 <-- optional -->
Key2: value2 <-- optional -->
KeyN: valueN <-- optional -->
- CRLF -
JSON string
-
:param response: eLCM response
:return: json object if success
:raise ELCMInvalidResponse: if the response does not contain valid
json data.
"""
try:
body = response.text
body_parts = body.split('\r\n')
if len(body_parts) > 0:
return jsonutils.loads(body_parts[-1])
else:
return None
except (TypeError, ValueError):
raise ELCMInvalidResponse('eLCM response does not contain valid json '
'data. Response is "%s".' % body) | python | def _parse_elcm_response_body_as_json(response):
"""parse eLCM response body as json data
eLCM response should be in form of:
_
Key1: value1 <-- optional -->
Key2: value2 <-- optional -->
KeyN: valueN <-- optional -->
- CRLF -
JSON string
-
:param response: eLCM response
:return: json object if success
:raise ELCMInvalidResponse: if the response does not contain valid
json data.
"""
try:
body = response.text
body_parts = body.split('\r\n')
if len(body_parts) > 0:
return jsonutils.loads(body_parts[-1])
else:
return None
except (TypeError, ValueError):
raise ELCMInvalidResponse('eLCM response does not contain valid json '
'data. Response is "%s".' % body) | [
"def",
"_parse_elcm_response_body_as_json",
"(",
"response",
")",
":",
"try",
":",
"body",
"=",
"response",
".",
"text",
"body_parts",
"=",
"body",
".",
"split",
"(",
"'\\r\\n'",
")",
"if",
"len",
"(",
"body_parts",
")",
">",
"0",
":",
"return",
"jsonutils... | parse eLCM response body as json data
eLCM response should be in form of:
_
Key1: value1 <-- optional -->
Key2: value2 <-- optional -->
KeyN: valueN <-- optional -->
- CRLF -
JSON string
-
:param response: eLCM response
:return: json object if success
:raise ELCMInvalidResponse: if the response does not contain valid
json data. | [
"parse",
"eLCM",
"response",
"body",
"as",
"json",
"data"
] | 4585ce2f76853b9773fb190ca0cfff0aa04a7cf8 | https://github.com/openstack/python-scciclient/blob/4585ce2f76853b9773fb190ca0cfff0aa04a7cf8/scciclient/irmc/elcm.py#L149-L177 | train | 47,921 |
openstack/python-scciclient | scciclient/irmc/elcm.py | elcm_request | def elcm_request(irmc_info, method, path, **kwargs):
"""send an eLCM request to the server
:param irmc_info: dict of iRMC params to access the server node
{
'irmc_address': host,
'irmc_username': user_id,
'irmc_password': password,
'irmc_port': 80 or 443, default is 443,
'irmc_auth_method': 'basic' or 'digest', default is 'basic',
'irmc_client_timeout': timeout, default is 60,
...
}
:param method: request method such as 'GET', 'POST'
:param path: url path for eLCM request
:returns: requests.Response from SCCI server
:raises SCCIInvalidInputError: if port and/or auth_method params
are invalid
:raises SCCIClientError: if SCCI failed
"""
host = irmc_info['irmc_address']
port = irmc_info.get('irmc_port', 443)
auth_method = irmc_info.get('irmc_auth_method', 'basic')
userid = irmc_info['irmc_username']
password = irmc_info['irmc_password']
client_timeout = irmc_info.get('irmc_client_timeout', 60)
# Request headers, params, and data
headers = kwargs.get('headers', {'Accept': 'application/json'})
params = kwargs.get('params')
data = kwargs.get('data')
auth_obj = None
try:
protocol = {80: 'http', 443: 'https'}[port]
auth_obj = {
'basic': requests.auth.HTTPBasicAuth(userid, password),
'digest': requests.auth.HTTPDigestAuth(userid, password)
}[auth_method.lower()]
except KeyError:
raise scci.SCCIInvalidInputError(
("Invalid port %(port)d or " +
"auth_method for method %(auth_method)s") %
{'port': port, 'auth_method': auth_method})
try:
r = requests.request(method,
protocol + '://' + host + path,
headers=headers,
params=params,
data=data,
verify=False,
timeout=client_timeout,
allow_redirects=False,
auth=auth_obj)
except requests.exceptions.RequestException as requests_exception:
raise scci.SCCIClientError(requests_exception)
# Process status_code 401
if r.status_code == 401:
raise scci.SCCIClientError('UNAUTHORIZED')
return r | python | def elcm_request(irmc_info, method, path, **kwargs):
"""send an eLCM request to the server
:param irmc_info: dict of iRMC params to access the server node
{
'irmc_address': host,
'irmc_username': user_id,
'irmc_password': password,
'irmc_port': 80 or 443, default is 443,
'irmc_auth_method': 'basic' or 'digest', default is 'basic',
'irmc_client_timeout': timeout, default is 60,
...
}
:param method: request method such as 'GET', 'POST'
:param path: url path for eLCM request
:returns: requests.Response from SCCI server
:raises SCCIInvalidInputError: if port and/or auth_method params
are invalid
:raises SCCIClientError: if SCCI failed
"""
host = irmc_info['irmc_address']
port = irmc_info.get('irmc_port', 443)
auth_method = irmc_info.get('irmc_auth_method', 'basic')
userid = irmc_info['irmc_username']
password = irmc_info['irmc_password']
client_timeout = irmc_info.get('irmc_client_timeout', 60)
# Request headers, params, and data
headers = kwargs.get('headers', {'Accept': 'application/json'})
params = kwargs.get('params')
data = kwargs.get('data')
auth_obj = None
try:
protocol = {80: 'http', 443: 'https'}[port]
auth_obj = {
'basic': requests.auth.HTTPBasicAuth(userid, password),
'digest': requests.auth.HTTPDigestAuth(userid, password)
}[auth_method.lower()]
except KeyError:
raise scci.SCCIInvalidInputError(
("Invalid port %(port)d or " +
"auth_method for method %(auth_method)s") %
{'port': port, 'auth_method': auth_method})
try:
r = requests.request(method,
protocol + '://' + host + path,
headers=headers,
params=params,
data=data,
verify=False,
timeout=client_timeout,
allow_redirects=False,
auth=auth_obj)
except requests.exceptions.RequestException as requests_exception:
raise scci.SCCIClientError(requests_exception)
# Process status_code 401
if r.status_code == 401:
raise scci.SCCIClientError('UNAUTHORIZED')
return r | [
"def",
"elcm_request",
"(",
"irmc_info",
",",
"method",
",",
"path",
",",
"*",
"*",
"kwargs",
")",
":",
"host",
"=",
"irmc_info",
"[",
"'irmc_address'",
"]",
"port",
"=",
"irmc_info",
".",
"get",
"(",
"'irmc_port'",
",",
"443",
")",
"auth_method",
"=",
... | send an eLCM request to the server
:param irmc_info: dict of iRMC params to access the server node
{
'irmc_address': host,
'irmc_username': user_id,
'irmc_password': password,
'irmc_port': 80 or 443, default is 443,
'irmc_auth_method': 'basic' or 'digest', default is 'basic',
'irmc_client_timeout': timeout, default is 60,
...
}
:param method: request method such as 'GET', 'POST'
:param path: url path for eLCM request
:returns: requests.Response from SCCI server
:raises SCCIInvalidInputError: if port and/or auth_method params
are invalid
:raises SCCIClientError: if SCCI failed | [
"send",
"an",
"eLCM",
"request",
"to",
"the",
"server"
] | 4585ce2f76853b9773fb190ca0cfff0aa04a7cf8 | https://github.com/openstack/python-scciclient/blob/4585ce2f76853b9773fb190ca0cfff0aa04a7cf8/scciclient/irmc/elcm.py#L180-L243 | train | 47,922 |
openstack/python-scciclient | scciclient/irmc/elcm.py | elcm_profile_get_versions | def elcm_profile_get_versions(irmc_info):
"""send an eLCM request to get profile versions
:param irmc_info: node info
:returns: dict object of profiles if succeed
{
"Server":{
"@Version": "1.01",
"AdapterConfigIrmc":{
"@Version": "1.00"
},
"HWConfigurationIrmc":{
"@Version": "1.00"
},
"SystemConfig":{
"IrmcConfig":{
"@Version": "1.02"
},
"BiosConfig":{
"@Version": "1.02"
}
}
}
}
:raises: SCCIClientError if SCCI failed
"""
# Send GET request to the server
resp = elcm_request(irmc_info,
method='GET',
path=URL_PATH_PROFILE_MGMT + 'version')
if resp.status_code == 200:
return _parse_elcm_response_body_as_json(resp)
else:
raise scci.SCCIClientError(('Failed to get profile versions with '
'error code %s' % resp.status_code)) | python | def elcm_profile_get_versions(irmc_info):
"""send an eLCM request to get profile versions
:param irmc_info: node info
:returns: dict object of profiles if succeed
{
"Server":{
"@Version": "1.01",
"AdapterConfigIrmc":{
"@Version": "1.00"
},
"HWConfigurationIrmc":{
"@Version": "1.00"
},
"SystemConfig":{
"IrmcConfig":{
"@Version": "1.02"
},
"BiosConfig":{
"@Version": "1.02"
}
}
}
}
:raises: SCCIClientError if SCCI failed
"""
# Send GET request to the server
resp = elcm_request(irmc_info,
method='GET',
path=URL_PATH_PROFILE_MGMT + 'version')
if resp.status_code == 200:
return _parse_elcm_response_body_as_json(resp)
else:
raise scci.SCCIClientError(('Failed to get profile versions with '
'error code %s' % resp.status_code)) | [
"def",
"elcm_profile_get_versions",
"(",
"irmc_info",
")",
":",
"# Send GET request to the server",
"resp",
"=",
"elcm_request",
"(",
"irmc_info",
",",
"method",
"=",
"'GET'",
",",
"path",
"=",
"URL_PATH_PROFILE_MGMT",
"+",
"'version'",
")",
"if",
"resp",
".",
"st... | send an eLCM request to get profile versions
:param irmc_info: node info
:returns: dict object of profiles if succeed
{
"Server":{
"@Version": "1.01",
"AdapterConfigIrmc":{
"@Version": "1.00"
},
"HWConfigurationIrmc":{
"@Version": "1.00"
},
"SystemConfig":{
"IrmcConfig":{
"@Version": "1.02"
},
"BiosConfig":{
"@Version": "1.02"
}
}
}
}
:raises: SCCIClientError if SCCI failed | [
"send",
"an",
"eLCM",
"request",
"to",
"get",
"profile",
"versions"
] | 4585ce2f76853b9773fb190ca0cfff0aa04a7cf8 | https://github.com/openstack/python-scciclient/blob/4585ce2f76853b9773fb190ca0cfff0aa04a7cf8/scciclient/irmc/elcm.py#L246-L281 | train | 47,923 |
openstack/python-scciclient | scciclient/irmc/elcm.py | elcm_profile_get | def elcm_profile_get(irmc_info, profile_name):
"""send an eLCM request to get profile data
:param irmc_info: node info
:param profile_name: name of profile
:returns: dict object of profile data if succeed
:raises: ELCMProfileNotFound if profile does not exist
:raises: SCCIClientError if SCCI failed
"""
# Send GET request to the server
resp = elcm_request(irmc_info,
method='GET',
path=URL_PATH_PROFILE_MGMT + profile_name)
if resp.status_code == 200:
return _parse_elcm_response_body_as_json(resp)
elif resp.status_code == 404:
raise ELCMProfileNotFound('Profile "%s" not found '
'in the profile store.' % profile_name)
else:
raise scci.SCCIClientError(('Failed to get profile "%(profile)s" with '
'error code %(error)s' %
{'profile': profile_name,
'error': resp.status_code})) | python | def elcm_profile_get(irmc_info, profile_name):
"""send an eLCM request to get profile data
:param irmc_info: node info
:param profile_name: name of profile
:returns: dict object of profile data if succeed
:raises: ELCMProfileNotFound if profile does not exist
:raises: SCCIClientError if SCCI failed
"""
# Send GET request to the server
resp = elcm_request(irmc_info,
method='GET',
path=URL_PATH_PROFILE_MGMT + profile_name)
if resp.status_code == 200:
return _parse_elcm_response_body_as_json(resp)
elif resp.status_code == 404:
raise ELCMProfileNotFound('Profile "%s" not found '
'in the profile store.' % profile_name)
else:
raise scci.SCCIClientError(('Failed to get profile "%(profile)s" with '
'error code %(error)s' %
{'profile': profile_name,
'error': resp.status_code})) | [
"def",
"elcm_profile_get",
"(",
"irmc_info",
",",
"profile_name",
")",
":",
"# Send GET request to the server",
"resp",
"=",
"elcm_request",
"(",
"irmc_info",
",",
"method",
"=",
"'GET'",
",",
"path",
"=",
"URL_PATH_PROFILE_MGMT",
"+",
"profile_name",
")",
"if",
"... | send an eLCM request to get profile data
:param irmc_info: node info
:param profile_name: name of profile
:returns: dict object of profile data if succeed
:raises: ELCMProfileNotFound if profile does not exist
:raises: SCCIClientError if SCCI failed | [
"send",
"an",
"eLCM",
"request",
"to",
"get",
"profile",
"data"
] | 4585ce2f76853b9773fb190ca0cfff0aa04a7cf8 | https://github.com/openstack/python-scciclient/blob/4585ce2f76853b9773fb190ca0cfff0aa04a7cf8/scciclient/irmc/elcm.py#L314-L337 | train | 47,924 |
openstack/python-scciclient | scciclient/irmc/elcm.py | elcm_profile_create | def elcm_profile_create(irmc_info, param_path):
"""send an eLCM request to create profile
To create a profile, a new session is spawned with status 'running'.
When profile is created completely, the session ends.
:param irmc_info: node info
:param param_path: path of profile
:returns: dict object of session info if succeed
{
'Session':
{
'Id': id
'Status': 'activated'
...
}
}
:raises: SCCIClientError if SCCI failed
"""
# Send POST request to the server
# NOTE: This task may take time, so set a timeout
_irmc_info = dict(irmc_info)
_irmc_info['irmc_client_timeout'] = PROFILE_CREATE_TIMEOUT
resp = elcm_request(_irmc_info,
method='POST',
path=URL_PATH_PROFILE_MGMT + 'get',
params={'PARAM_PATH': param_path})
if resp.status_code == 202:
return _parse_elcm_response_body_as_json(resp)
else:
raise scci.SCCIClientError(('Failed to create profile for path '
'"%(param_path)s" with error code '
'%(error)s' %
{'param_path': param_path,
'error': resp.status_code})) | python | def elcm_profile_create(irmc_info, param_path):
"""send an eLCM request to create profile
To create a profile, a new session is spawned with status 'running'.
When profile is created completely, the session ends.
:param irmc_info: node info
:param param_path: path of profile
:returns: dict object of session info if succeed
{
'Session':
{
'Id': id
'Status': 'activated'
...
}
}
:raises: SCCIClientError if SCCI failed
"""
# Send POST request to the server
# NOTE: This task may take time, so set a timeout
_irmc_info = dict(irmc_info)
_irmc_info['irmc_client_timeout'] = PROFILE_CREATE_TIMEOUT
resp = elcm_request(_irmc_info,
method='POST',
path=URL_PATH_PROFILE_MGMT + 'get',
params={'PARAM_PATH': param_path})
if resp.status_code == 202:
return _parse_elcm_response_body_as_json(resp)
else:
raise scci.SCCIClientError(('Failed to create profile for path '
'"%(param_path)s" with error code '
'%(error)s' %
{'param_path': param_path,
'error': resp.status_code})) | [
"def",
"elcm_profile_create",
"(",
"irmc_info",
",",
"param_path",
")",
":",
"# Send POST request to the server",
"# NOTE: This task may take time, so set a timeout",
"_irmc_info",
"=",
"dict",
"(",
"irmc_info",
")",
"_irmc_info",
"[",
"'irmc_client_timeout'",
"]",
"=",
"PR... | send an eLCM request to create profile
To create a profile, a new session is spawned with status 'running'.
When profile is created completely, the session ends.
:param irmc_info: node info
:param param_path: path of profile
:returns: dict object of session info if succeed
{
'Session':
{
'Id': id
'Status': 'activated'
...
}
}
:raises: SCCIClientError if SCCI failed | [
"send",
"an",
"eLCM",
"request",
"to",
"create",
"profile"
] | 4585ce2f76853b9773fb190ca0cfff0aa04a7cf8 | https://github.com/openstack/python-scciclient/blob/4585ce2f76853b9773fb190ca0cfff0aa04a7cf8/scciclient/irmc/elcm.py#L340-L376 | train | 47,925 |
openstack/python-scciclient | scciclient/irmc/elcm.py | elcm_profile_set | def elcm_profile_set(irmc_info, input_data):
"""send an eLCM request to set param values
To apply param values, a new session is spawned with status 'running'.
When values are applied or error, the session ends.
:param irmc_info: node info
:param input_data: param values to apply, eg.
{
'Server':
{
'SystemConfig':
{
'BiosConfig':
{
'@Processing': 'execute',
-- config data --
}
}
}
}
:returns: dict object of session info if succeed
{
'Session':
{
'Id': id
'Status': 'activated'
...
}
}
:raises: SCCIClientError if SCCI failed
"""
# Prepare the data to apply
if isinstance(input_data, dict):
data = jsonutils.dumps(input_data)
else:
data = input_data
# Send POST request to the server
# NOTE: This task may take time, so set a timeout
_irmc_info = dict(irmc_info)
_irmc_info['irmc_client_timeout'] = PROFILE_SET_TIMEOUT
content_type = 'application/x-www-form-urlencoded'
if input_data['Server'].get('HWConfigurationIrmc'):
content_type = 'application/json'
resp = elcm_request(_irmc_info,
method='POST',
path=URL_PATH_PROFILE_MGMT + 'set',
headers={'Content-type': content_type},
data=data)
if resp.status_code == 202:
return _parse_elcm_response_body_as_json(resp)
else:
raise scci.SCCIClientError(('Failed to apply param values with '
'error code %(error)s' %
{'error': resp.status_code})) | python | def elcm_profile_set(irmc_info, input_data):
"""send an eLCM request to set param values
To apply param values, a new session is spawned with status 'running'.
When values are applied or error, the session ends.
:param irmc_info: node info
:param input_data: param values to apply, eg.
{
'Server':
{
'SystemConfig':
{
'BiosConfig':
{
'@Processing': 'execute',
-- config data --
}
}
}
}
:returns: dict object of session info if succeed
{
'Session':
{
'Id': id
'Status': 'activated'
...
}
}
:raises: SCCIClientError if SCCI failed
"""
# Prepare the data to apply
if isinstance(input_data, dict):
data = jsonutils.dumps(input_data)
else:
data = input_data
# Send POST request to the server
# NOTE: This task may take time, so set a timeout
_irmc_info = dict(irmc_info)
_irmc_info['irmc_client_timeout'] = PROFILE_SET_TIMEOUT
content_type = 'application/x-www-form-urlencoded'
if input_data['Server'].get('HWConfigurationIrmc'):
content_type = 'application/json'
resp = elcm_request(_irmc_info,
method='POST',
path=URL_PATH_PROFILE_MGMT + 'set',
headers={'Content-type': content_type},
data=data)
if resp.status_code == 202:
return _parse_elcm_response_body_as_json(resp)
else:
raise scci.SCCIClientError(('Failed to apply param values with '
'error code %(error)s' %
{'error': resp.status_code})) | [
"def",
"elcm_profile_set",
"(",
"irmc_info",
",",
"input_data",
")",
":",
"# Prepare the data to apply",
"if",
"isinstance",
"(",
"input_data",
",",
"dict",
")",
":",
"data",
"=",
"jsonutils",
".",
"dumps",
"(",
"input_data",
")",
"else",
":",
"data",
"=",
"... | send an eLCM request to set param values
To apply param values, a new session is spawned with status 'running'.
When values are applied or error, the session ends.
:param irmc_info: node info
:param input_data: param values to apply, eg.
{
'Server':
{
'SystemConfig':
{
'BiosConfig':
{
'@Processing': 'execute',
-- config data --
}
}
}
}
:returns: dict object of session info if succeed
{
'Session':
{
'Id': id
'Status': 'activated'
...
}
}
:raises: SCCIClientError if SCCI failed | [
"send",
"an",
"eLCM",
"request",
"to",
"set",
"param",
"values"
] | 4585ce2f76853b9773fb190ca0cfff0aa04a7cf8 | https://github.com/openstack/python-scciclient/blob/4585ce2f76853b9773fb190ca0cfff0aa04a7cf8/scciclient/irmc/elcm.py#L379-L436 | train | 47,926 |
openstack/python-scciclient | scciclient/irmc/elcm.py | elcm_profile_delete | def elcm_profile_delete(irmc_info, profile_name):
"""send an eLCM request to delete a profile
:param irmc_info: node info
:param profile_name: name of profile
:raises: ELCMProfileNotFound if the profile does not exist
:raises: SCCIClientError if SCCI failed
"""
# Send DELETE request to the server
resp = elcm_request(irmc_info,
method='DELETE',
path=URL_PATH_PROFILE_MGMT + profile_name)
if resp.status_code == 200:
# Profile deleted
return
elif resp.status_code == 404:
# Profile not found
raise ELCMProfileNotFound('Profile "%s" not found '
'in the profile store.' % profile_name)
else:
raise scci.SCCIClientError(('Failed to delete profile "%(profile)s" '
'with error code %(error)s' %
{'profile': profile_name,
'error': resp.status_code})) | python | def elcm_profile_delete(irmc_info, profile_name):
"""send an eLCM request to delete a profile
:param irmc_info: node info
:param profile_name: name of profile
:raises: ELCMProfileNotFound if the profile does not exist
:raises: SCCIClientError if SCCI failed
"""
# Send DELETE request to the server
resp = elcm_request(irmc_info,
method='DELETE',
path=URL_PATH_PROFILE_MGMT + profile_name)
if resp.status_code == 200:
# Profile deleted
return
elif resp.status_code == 404:
# Profile not found
raise ELCMProfileNotFound('Profile "%s" not found '
'in the profile store.' % profile_name)
else:
raise scci.SCCIClientError(('Failed to delete profile "%(profile)s" '
'with error code %(error)s' %
{'profile': profile_name,
'error': resp.status_code})) | [
"def",
"elcm_profile_delete",
"(",
"irmc_info",
",",
"profile_name",
")",
":",
"# Send DELETE request to the server",
"resp",
"=",
"elcm_request",
"(",
"irmc_info",
",",
"method",
"=",
"'DELETE'",
",",
"path",
"=",
"URL_PATH_PROFILE_MGMT",
"+",
"profile_name",
")",
... | send an eLCM request to delete a profile
:param irmc_info: node info
:param profile_name: name of profile
:raises: ELCMProfileNotFound if the profile does not exist
:raises: SCCIClientError if SCCI failed | [
"send",
"an",
"eLCM",
"request",
"to",
"delete",
"a",
"profile"
] | 4585ce2f76853b9773fb190ca0cfff0aa04a7cf8 | https://github.com/openstack/python-scciclient/blob/4585ce2f76853b9773fb190ca0cfff0aa04a7cf8/scciclient/irmc/elcm.py#L439-L463 | train | 47,927 |
openstack/python-scciclient | scciclient/irmc/elcm.py | elcm_session_list | def elcm_session_list(irmc_info):
"""send an eLCM request to list all sessions
:param irmc_info: node info
:returns: dict object of sessions if succeed
{
'SessionList':
{
'Contains':
[
{ 'Id': id1, 'Name': name1 },
{ 'Id': id2, 'Name': name2 },
{ 'Id': idN, 'Name': nameN },
]
}
}
:raises: SCCIClientError if SCCI failed
"""
# Send GET request to the server
resp = elcm_request(irmc_info,
method='GET',
path='/sessionInformation/')
if resp.status_code == 200:
return _parse_elcm_response_body_as_json(resp)
else:
raise scci.SCCIClientError(('Failed to list sessions with '
'error code %s' % resp.status_code)) | python | def elcm_session_list(irmc_info):
"""send an eLCM request to list all sessions
:param irmc_info: node info
:returns: dict object of sessions if succeed
{
'SessionList':
{
'Contains':
[
{ 'Id': id1, 'Name': name1 },
{ 'Id': id2, 'Name': name2 },
{ 'Id': idN, 'Name': nameN },
]
}
}
:raises: SCCIClientError if SCCI failed
"""
# Send GET request to the server
resp = elcm_request(irmc_info,
method='GET',
path='/sessionInformation/')
if resp.status_code == 200:
return _parse_elcm_response_body_as_json(resp)
else:
raise scci.SCCIClientError(('Failed to list sessions with '
'error code %s' % resp.status_code)) | [
"def",
"elcm_session_list",
"(",
"irmc_info",
")",
":",
"# Send GET request to the server",
"resp",
"=",
"elcm_request",
"(",
"irmc_info",
",",
"method",
"=",
"'GET'",
",",
"path",
"=",
"'/sessionInformation/'",
")",
"if",
"resp",
".",
"status_code",
"==",
"200",
... | send an eLCM request to list all sessions
:param irmc_info: node info
:returns: dict object of sessions if succeed
{
'SessionList':
{
'Contains':
[
{ 'Id': id1, 'Name': name1 },
{ 'Id': id2, 'Name': name2 },
{ 'Id': idN, 'Name': nameN },
]
}
}
:raises: SCCIClientError if SCCI failed | [
"send",
"an",
"eLCM",
"request",
"to",
"list",
"all",
"sessions"
] | 4585ce2f76853b9773fb190ca0cfff0aa04a7cf8 | https://github.com/openstack/python-scciclient/blob/4585ce2f76853b9773fb190ca0cfff0aa04a7cf8/scciclient/irmc/elcm.py#L466-L493 | train | 47,928 |
openstack/python-scciclient | scciclient/irmc/elcm.py | elcm_session_get_status | def elcm_session_get_status(irmc_info, session_id):
"""send an eLCM request to get session status
:param irmc_info: node info
:param session_id: session id
:returns: dict object of session info if succeed
{
'Session':
{
'Id': id
'Status': status
...
}
}
:raises: ELCMSessionNotFound if the session does not exist
:raises: SCCIClientError if SCCI failed
"""
# Send GET request to the server
resp = elcm_request(irmc_info,
method='GET',
path='/sessionInformation/%s/status' % session_id)
if resp.status_code == 200:
return _parse_elcm_response_body_as_json(resp)
elif resp.status_code == 404:
raise ELCMSessionNotFound('Session "%s" does not exist' % session_id)
else:
raise scci.SCCIClientError(('Failed to get status of session '
'"%(session)s" with error code %(error)s' %
{'session': session_id,
'error': resp.status_code})) | python | def elcm_session_get_status(irmc_info, session_id):
"""send an eLCM request to get session status
:param irmc_info: node info
:param session_id: session id
:returns: dict object of session info if succeed
{
'Session':
{
'Id': id
'Status': status
...
}
}
:raises: ELCMSessionNotFound if the session does not exist
:raises: SCCIClientError if SCCI failed
"""
# Send GET request to the server
resp = elcm_request(irmc_info,
method='GET',
path='/sessionInformation/%s/status' % session_id)
if resp.status_code == 200:
return _parse_elcm_response_body_as_json(resp)
elif resp.status_code == 404:
raise ELCMSessionNotFound('Session "%s" does not exist' % session_id)
else:
raise scci.SCCIClientError(('Failed to get status of session '
'"%(session)s" with error code %(error)s' %
{'session': session_id,
'error': resp.status_code})) | [
"def",
"elcm_session_get_status",
"(",
"irmc_info",
",",
"session_id",
")",
":",
"# Send GET request to the server",
"resp",
"=",
"elcm_request",
"(",
"irmc_info",
",",
"method",
"=",
"'GET'",
",",
"path",
"=",
"'/sessionInformation/%s/status'",
"%",
"session_id",
")"... | send an eLCM request to get session status
:param irmc_info: node info
:param session_id: session id
:returns: dict object of session info if succeed
{
'Session':
{
'Id': id
'Status': status
...
}
}
:raises: ELCMSessionNotFound if the session does not exist
:raises: SCCIClientError if SCCI failed | [
"send",
"an",
"eLCM",
"request",
"to",
"get",
"session",
"status"
] | 4585ce2f76853b9773fb190ca0cfff0aa04a7cf8 | https://github.com/openstack/python-scciclient/blob/4585ce2f76853b9773fb190ca0cfff0aa04a7cf8/scciclient/irmc/elcm.py#L496-L526 | train | 47,929 |
openstack/python-scciclient | scciclient/irmc/elcm.py | elcm_session_terminate | def elcm_session_terminate(irmc_info, session_id):
"""send an eLCM request to terminate a session
:param irmc_info: node info
:param session_id: session id
:raises: ELCMSessionNotFound if the session does not exist
:raises: SCCIClientError if SCCI failed
"""
# Send DELETE request to the server
resp = elcm_request(irmc_info,
method='DELETE',
path='/sessionInformation/%s/terminate' % session_id)
if resp.status_code == 200:
return
elif resp.status_code == 404:
raise ELCMSessionNotFound('Session "%s" does not exist' % session_id)
else:
raise scci.SCCIClientError(('Failed to terminate session '
'"%(session)s" with error code %(error)s' %
{'session': session_id,
'error': resp.status_code})) | python | def elcm_session_terminate(irmc_info, session_id):
"""send an eLCM request to terminate a session
:param irmc_info: node info
:param session_id: session id
:raises: ELCMSessionNotFound if the session does not exist
:raises: SCCIClientError if SCCI failed
"""
# Send DELETE request to the server
resp = elcm_request(irmc_info,
method='DELETE',
path='/sessionInformation/%s/terminate' % session_id)
if resp.status_code == 200:
return
elif resp.status_code == 404:
raise ELCMSessionNotFound('Session "%s" does not exist' % session_id)
else:
raise scci.SCCIClientError(('Failed to terminate session '
'"%(session)s" with error code %(error)s' %
{'session': session_id,
'error': resp.status_code})) | [
"def",
"elcm_session_terminate",
"(",
"irmc_info",
",",
"session_id",
")",
":",
"# Send DELETE request to the server",
"resp",
"=",
"elcm_request",
"(",
"irmc_info",
",",
"method",
"=",
"'DELETE'",
",",
"path",
"=",
"'/sessionInformation/%s/terminate'",
"%",
"session_id... | send an eLCM request to terminate a session
:param irmc_info: node info
:param session_id: session id
:raises: ELCMSessionNotFound if the session does not exist
:raises: SCCIClientError if SCCI failed | [
"send",
"an",
"eLCM",
"request",
"to",
"terminate",
"a",
"session"
] | 4585ce2f76853b9773fb190ca0cfff0aa04a7cf8 | https://github.com/openstack/python-scciclient/blob/4585ce2f76853b9773fb190ca0cfff0aa04a7cf8/scciclient/irmc/elcm.py#L561-L582 | train | 47,930 |
openstack/python-scciclient | scciclient/irmc/elcm.py | elcm_session_delete | def elcm_session_delete(irmc_info, session_id, terminate=False):
"""send an eLCM request to remove a session from the session list
:param irmc_info: node info
:param session_id: session id
:param terminate: a running session must be terminated before removing
:raises: ELCMSessionNotFound if the session does not exist
:raises: SCCIClientError if SCCI failed
"""
# Terminate the session first if needs to
if terminate:
# Get session status to check
session = elcm_session_get_status(irmc_info, session_id)
status = session['Session']['Status']
# Terminate session if it is activated or running
if status == 'running' or status == 'activated':
elcm_session_terminate(irmc_info, session_id)
# Send DELETE request to the server
resp = elcm_request(irmc_info,
method='DELETE',
path='/sessionInformation/%s/remove' % session_id)
if resp.status_code == 200:
return
elif resp.status_code == 404:
raise ELCMSessionNotFound('Session "%s" does not exist' % session_id)
else:
raise scci.SCCIClientError(('Failed to remove session '
'"%(session)s" with error code %(error)s' %
{'session': session_id,
'error': resp.status_code})) | python | def elcm_session_delete(irmc_info, session_id, terminate=False):
"""send an eLCM request to remove a session from the session list
:param irmc_info: node info
:param session_id: session id
:param terminate: a running session must be terminated before removing
:raises: ELCMSessionNotFound if the session does not exist
:raises: SCCIClientError if SCCI failed
"""
# Terminate the session first if needs to
if terminate:
# Get session status to check
session = elcm_session_get_status(irmc_info, session_id)
status = session['Session']['Status']
# Terminate session if it is activated or running
if status == 'running' or status == 'activated':
elcm_session_terminate(irmc_info, session_id)
# Send DELETE request to the server
resp = elcm_request(irmc_info,
method='DELETE',
path='/sessionInformation/%s/remove' % session_id)
if resp.status_code == 200:
return
elif resp.status_code == 404:
raise ELCMSessionNotFound('Session "%s" does not exist' % session_id)
else:
raise scci.SCCIClientError(('Failed to remove session '
'"%(session)s" with error code %(error)s' %
{'session': session_id,
'error': resp.status_code})) | [
"def",
"elcm_session_delete",
"(",
"irmc_info",
",",
"session_id",
",",
"terminate",
"=",
"False",
")",
":",
"# Terminate the session first if needs to",
"if",
"terminate",
":",
"# Get session status to check",
"session",
"=",
"elcm_session_get_status",
"(",
"irmc_info",
... | send an eLCM request to remove a session from the session list
:param irmc_info: node info
:param session_id: session id
:param terminate: a running session must be terminated before removing
:raises: ELCMSessionNotFound if the session does not exist
:raises: SCCIClientError if SCCI failed | [
"send",
"an",
"eLCM",
"request",
"to",
"remove",
"a",
"session",
"from",
"the",
"session",
"list"
] | 4585ce2f76853b9773fb190ca0cfff0aa04a7cf8 | https://github.com/openstack/python-scciclient/blob/4585ce2f76853b9773fb190ca0cfff0aa04a7cf8/scciclient/irmc/elcm.py#L585-L617 | train | 47,931 |
openstack/python-scciclient | scciclient/irmc/elcm.py | backup_bios_config | def backup_bios_config(irmc_info):
"""backup current bios configuration
This function sends a BACKUP BIOS request to the server. Then when the bios
config data are ready for retrieving, it will return the data to the
caller. Note that this operation may take time.
:param irmc_info: node info
:return: a dict with following values:
{
'bios_config': <bios config data>,
'warning': <warning message if there is>
}
"""
# 1. Make sure there is no BiosConfig profile in the store
try:
# Get the profile first, if not found, then an exception
# will be raised.
elcm_profile_get(irmc_info=irmc_info,
profile_name=PROFILE_BIOS_CONFIG)
# Profile found, delete it
elcm_profile_delete(irmc_info=irmc_info,
profile_name=PROFILE_BIOS_CONFIG)
except ELCMProfileNotFound:
# Ignore this error as it's not an error in this case
pass
# 2. Send request to create a new profile for BiosConfig
session = elcm_profile_create(irmc_info=irmc_info,
param_path=PARAM_PATH_BIOS_CONFIG)
# 3. Profile creation is in progress, we monitor the session
session_timeout = irmc_info.get('irmc_bios_session_timeout',
BIOS_CONFIG_SESSION_TIMEOUT)
return _process_session_data(
irmc_info=irmc_info,
operation='BACKUP_BIOS',
session_id=session['Session']['Id'],
session_timeout=session_timeout) | python | def backup_bios_config(irmc_info):
"""backup current bios configuration
This function sends a BACKUP BIOS request to the server. Then when the bios
config data are ready for retrieving, it will return the data to the
caller. Note that this operation may take time.
:param irmc_info: node info
:return: a dict with following values:
{
'bios_config': <bios config data>,
'warning': <warning message if there is>
}
"""
# 1. Make sure there is no BiosConfig profile in the store
try:
# Get the profile first, if not found, then an exception
# will be raised.
elcm_profile_get(irmc_info=irmc_info,
profile_name=PROFILE_BIOS_CONFIG)
# Profile found, delete it
elcm_profile_delete(irmc_info=irmc_info,
profile_name=PROFILE_BIOS_CONFIG)
except ELCMProfileNotFound:
# Ignore this error as it's not an error in this case
pass
# 2. Send request to create a new profile for BiosConfig
session = elcm_profile_create(irmc_info=irmc_info,
param_path=PARAM_PATH_BIOS_CONFIG)
# 3. Profile creation is in progress, we monitor the session
session_timeout = irmc_info.get('irmc_bios_session_timeout',
BIOS_CONFIG_SESSION_TIMEOUT)
return _process_session_data(
irmc_info=irmc_info,
operation='BACKUP_BIOS',
session_id=session['Session']['Id'],
session_timeout=session_timeout) | [
"def",
"backup_bios_config",
"(",
"irmc_info",
")",
":",
"# 1. Make sure there is no BiosConfig profile in the store",
"try",
":",
"# Get the profile first, if not found, then an exception",
"# will be raised.",
"elcm_profile_get",
"(",
"irmc_info",
"=",
"irmc_info",
",",
"profile_... | backup current bios configuration
This function sends a BACKUP BIOS request to the server. Then when the bios
config data are ready for retrieving, it will return the data to the
caller. Note that this operation may take time.
:param irmc_info: node info
:return: a dict with following values:
{
'bios_config': <bios config data>,
'warning': <warning message if there is>
} | [
"backup",
"current",
"bios",
"configuration"
] | 4585ce2f76853b9773fb190ca0cfff0aa04a7cf8 | https://github.com/openstack/python-scciclient/blob/4585ce2f76853b9773fb190ca0cfff0aa04a7cf8/scciclient/irmc/elcm.py#L701-L739 | train | 47,932 |
openstack/python-scciclient | scciclient/irmc/elcm.py | restore_bios_config | def restore_bios_config(irmc_info, bios_config):
"""restore bios configuration
This function sends a RESTORE BIOS request to the server. Then when the
bios
is ready for restoring, it will apply the provided settings and return.
Note that this operation may take time.
:param irmc_info: node info
:param bios_config: bios config
"""
def _process_bios_config():
try:
if isinstance(bios_config, dict):
input_data = bios_config
else:
input_data = jsonutils.loads(bios_config)
# The input data must contain flag "@Processing":"execute" in the
# equivalent section.
bios_cfg = input_data['Server']['SystemConfig']['BiosConfig']
bios_cfg['@Processing'] = 'execute'
return input_data
except (TypeError, ValueError, KeyError):
raise scci.SCCIInvalidInputError(
('Invalid input bios config "%s".' % bios_config))
# 1. Parse the bios config and create the input data
input_data = _process_bios_config()
# 2. Make sure there is no BiosConfig profile in the store
try:
# Get the profile first, if not found, then an exception
# will be raised.
elcm_profile_get(irmc_info=irmc_info,
profile_name=PROFILE_BIOS_CONFIG)
# Profile found, delete it
elcm_profile_delete(irmc_info=irmc_info,
profile_name=PROFILE_BIOS_CONFIG)
except ELCMProfileNotFound:
# Ignore this error as it's not an error in this case
pass
# 3. Send a request to apply the param values
session = elcm_profile_set(irmc_info=irmc_info,
input_data=input_data)
# 4. Param values applying is in progress, we monitor the session
session_timeout = irmc_info.get('irmc_bios_session_timeout',
BIOS_CONFIG_SESSION_TIMEOUT)
_process_session_data(irmc_info=irmc_info,
operation='RESTORE_BIOS',
session_id=session['Session']['Id'],
session_timeout=session_timeout) | python | def restore_bios_config(irmc_info, bios_config):
"""restore bios configuration
This function sends a RESTORE BIOS request to the server. Then when the
bios
is ready for restoring, it will apply the provided settings and return.
Note that this operation may take time.
:param irmc_info: node info
:param bios_config: bios config
"""
def _process_bios_config():
try:
if isinstance(bios_config, dict):
input_data = bios_config
else:
input_data = jsonutils.loads(bios_config)
# The input data must contain flag "@Processing":"execute" in the
# equivalent section.
bios_cfg = input_data['Server']['SystemConfig']['BiosConfig']
bios_cfg['@Processing'] = 'execute'
return input_data
except (TypeError, ValueError, KeyError):
raise scci.SCCIInvalidInputError(
('Invalid input bios config "%s".' % bios_config))
# 1. Parse the bios config and create the input data
input_data = _process_bios_config()
# 2. Make sure there is no BiosConfig profile in the store
try:
# Get the profile first, if not found, then an exception
# will be raised.
elcm_profile_get(irmc_info=irmc_info,
profile_name=PROFILE_BIOS_CONFIG)
# Profile found, delete it
elcm_profile_delete(irmc_info=irmc_info,
profile_name=PROFILE_BIOS_CONFIG)
except ELCMProfileNotFound:
# Ignore this error as it's not an error in this case
pass
# 3. Send a request to apply the param values
session = elcm_profile_set(irmc_info=irmc_info,
input_data=input_data)
# 4. Param values applying is in progress, we monitor the session
session_timeout = irmc_info.get('irmc_bios_session_timeout',
BIOS_CONFIG_SESSION_TIMEOUT)
_process_session_data(irmc_info=irmc_info,
operation='RESTORE_BIOS',
session_id=session['Session']['Id'],
session_timeout=session_timeout) | [
"def",
"restore_bios_config",
"(",
"irmc_info",
",",
"bios_config",
")",
":",
"def",
"_process_bios_config",
"(",
")",
":",
"try",
":",
"if",
"isinstance",
"(",
"bios_config",
",",
"dict",
")",
":",
"input_data",
"=",
"bios_config",
"else",
":",
"input_data",
... | restore bios configuration
This function sends a RESTORE BIOS request to the server. Then when the
bios
is ready for restoring, it will apply the provided settings and return.
Note that this operation may take time.
:param irmc_info: node info
:param bios_config: bios config | [
"restore",
"bios",
"configuration"
] | 4585ce2f76853b9773fb190ca0cfff0aa04a7cf8 | https://github.com/openstack/python-scciclient/blob/4585ce2f76853b9773fb190ca0cfff0aa04a7cf8/scciclient/irmc/elcm.py#L742-L797 | train | 47,933 |
openstack/python-scciclient | scciclient/irmc/elcm.py | get_secure_boot_mode | def get_secure_boot_mode(irmc_info):
"""Get the status if secure boot is enabled or not.
:param irmc_info: node info.
:raises: SecureBootConfigNotFound, if there is no configuration for secure
boot mode in the bios.
:return: True if secure boot mode is enabled on the node, False otherwise.
"""
result = backup_bios_config(irmc_info=irmc_info)
try:
bioscfg = result['bios_config']['Server']['SystemConfig']['BiosConfig']
return bioscfg['SecurityConfig']['SecureBootControlEnabled']
except KeyError:
msg = ("Failed to get secure boot mode from server %s. Upgrading iRMC "
"firmware may resolve this issue." % irmc_info['irmc_address'])
raise SecureBootConfigNotFound(msg) | python | def get_secure_boot_mode(irmc_info):
"""Get the status if secure boot is enabled or not.
:param irmc_info: node info.
:raises: SecureBootConfigNotFound, if there is no configuration for secure
boot mode in the bios.
:return: True if secure boot mode is enabled on the node, False otherwise.
"""
result = backup_bios_config(irmc_info=irmc_info)
try:
bioscfg = result['bios_config']['Server']['SystemConfig']['BiosConfig']
return bioscfg['SecurityConfig']['SecureBootControlEnabled']
except KeyError:
msg = ("Failed to get secure boot mode from server %s. Upgrading iRMC "
"firmware may resolve this issue." % irmc_info['irmc_address'])
raise SecureBootConfigNotFound(msg) | [
"def",
"get_secure_boot_mode",
"(",
"irmc_info",
")",
":",
"result",
"=",
"backup_bios_config",
"(",
"irmc_info",
"=",
"irmc_info",
")",
"try",
":",
"bioscfg",
"=",
"result",
"[",
"'bios_config'",
"]",
"[",
"'Server'",
"]",
"[",
"'SystemConfig'",
"]",
"[",
"... | Get the status if secure boot is enabled or not.
:param irmc_info: node info.
:raises: SecureBootConfigNotFound, if there is no configuration for secure
boot mode in the bios.
:return: True if secure boot mode is enabled on the node, False otherwise. | [
"Get",
"the",
"status",
"if",
"secure",
"boot",
"is",
"enabled",
"or",
"not",
"."
] | 4585ce2f76853b9773fb190ca0cfff0aa04a7cf8 | https://github.com/openstack/python-scciclient/blob/4585ce2f76853b9773fb190ca0cfff0aa04a7cf8/scciclient/irmc/elcm.py#L800-L818 | train | 47,934 |
openstack/python-scciclient | scciclient/irmc/elcm.py | _update_raid_input_data | def _update_raid_input_data(target_raid_config, raid_input):
"""Process raid input data.
:param target_raid_config: node raid info
:param raid_input: raid information for creating via eLCM
:raises ELCMValueError: raise msg if wrong input
:return: raid_input: raid input data which create raid configuration
{
"Server":{
"HWConfigurationIrmc":{
"@Processing":"execute",
"Adapters":{
"RAIDAdapter":[
{
"@AdapterId":"RAIDAdapter0",
"@ConfigurationType":"Addressing",
"LogicalDrives":{
"LogicalDrive":[
{
"@Number":0,
"@Action":"Create",
"RaidLevel":"1"
}
]
}
}
]
},
"@Version":"1.00"
},
"@Version":"1.01"
}
}
"""
logical_disk_list = target_raid_config['logical_disks']
raid_input['Server']['HWConfigurationIrmc'].update({'@Processing':
'execute'})
array_info = raid_input['Server']['HWConfigurationIrmc']['Adapters'][
'RAIDAdapter'][0]
array_info['LogicalDrives'] = {'LogicalDrive': []}
array_info['Arrays'] = {'Array': []}
for i, logical_disk in enumerate(logical_disk_list):
physical_disks = logical_disk.get('physical_disks')
# Auto create logical drive along with random physical disks.
# Allow auto create along with raid 10 and raid 50
# with specific physical drive.
if not physical_disks or logical_disk['raid_level'] \
in ('10', '50'):
array_info['LogicalDrives']['LogicalDrive'].append(
{'@Action': 'Create',
'RaidLevel': logical_disk['raid_level'],
'InitMode': 'slow'})
array_info['LogicalDrives']['LogicalDrive'][i].update({
"@Number": i})
else:
# Create array disks with specific physical servers
arrays = {
"@Number": i,
"@ConfigurationType": "Setting",
"PhysicalDiskRefs": {
"PhysicalDiskRef": []
}
}
lo_drive = {
"@Number": i,
"@Action": "Create",
"RaidLevel": "",
"ArrayRefs": {
"ArrayRef": [
]
},
"InitMode": "slow"
}
array_info['Arrays']['Array'].append(arrays)
array_info['LogicalDrives']['LogicalDrive'].append(lo_drive)
lo_drive.update({'RaidLevel': logical_disk['raid_level']})
lo_drive['ArrayRefs']['ArrayRef'].append({"@Number": i})
for element in logical_disk['physical_disks']:
arrays['PhysicalDiskRefs']['PhysicalDiskRef'].append({
'@Number': element})
if logical_disk['size_gb'] != "MAX":
# Ensure correctly order these items in dict
size = collections.OrderedDict()
size['@Unit'] = 'GB'
size['#text'] = logical_disk['size_gb']
array_info['LogicalDrives']['LogicalDrive'][i]['Size'] = size
return raid_input | python | def _update_raid_input_data(target_raid_config, raid_input):
"""Process raid input data.
:param target_raid_config: node raid info
:param raid_input: raid information for creating via eLCM
:raises ELCMValueError: raise msg if wrong input
:return: raid_input: raid input data which create raid configuration
{
"Server":{
"HWConfigurationIrmc":{
"@Processing":"execute",
"Adapters":{
"RAIDAdapter":[
{
"@AdapterId":"RAIDAdapter0",
"@ConfigurationType":"Addressing",
"LogicalDrives":{
"LogicalDrive":[
{
"@Number":0,
"@Action":"Create",
"RaidLevel":"1"
}
]
}
}
]
},
"@Version":"1.00"
},
"@Version":"1.01"
}
}
"""
logical_disk_list = target_raid_config['logical_disks']
raid_input['Server']['HWConfigurationIrmc'].update({'@Processing':
'execute'})
array_info = raid_input['Server']['HWConfigurationIrmc']['Adapters'][
'RAIDAdapter'][0]
array_info['LogicalDrives'] = {'LogicalDrive': []}
array_info['Arrays'] = {'Array': []}
for i, logical_disk in enumerate(logical_disk_list):
physical_disks = logical_disk.get('physical_disks')
# Auto create logical drive along with random physical disks.
# Allow auto create along with raid 10 and raid 50
# with specific physical drive.
if not physical_disks or logical_disk['raid_level'] \
in ('10', '50'):
array_info['LogicalDrives']['LogicalDrive'].append(
{'@Action': 'Create',
'RaidLevel': logical_disk['raid_level'],
'InitMode': 'slow'})
array_info['LogicalDrives']['LogicalDrive'][i].update({
"@Number": i})
else:
# Create array disks with specific physical servers
arrays = {
"@Number": i,
"@ConfigurationType": "Setting",
"PhysicalDiskRefs": {
"PhysicalDiskRef": []
}
}
lo_drive = {
"@Number": i,
"@Action": "Create",
"RaidLevel": "",
"ArrayRefs": {
"ArrayRef": [
]
},
"InitMode": "slow"
}
array_info['Arrays']['Array'].append(arrays)
array_info['LogicalDrives']['LogicalDrive'].append(lo_drive)
lo_drive.update({'RaidLevel': logical_disk['raid_level']})
lo_drive['ArrayRefs']['ArrayRef'].append({"@Number": i})
for element in logical_disk['physical_disks']:
arrays['PhysicalDiskRefs']['PhysicalDiskRef'].append({
'@Number': element})
if logical_disk['size_gb'] != "MAX":
# Ensure correctly order these items in dict
size = collections.OrderedDict()
size['@Unit'] = 'GB'
size['#text'] = logical_disk['size_gb']
array_info['LogicalDrives']['LogicalDrive'][i]['Size'] = size
return raid_input | [
"def",
"_update_raid_input_data",
"(",
"target_raid_config",
",",
"raid_input",
")",
":",
"logical_disk_list",
"=",
"target_raid_config",
"[",
"'logical_disks'",
"]",
"raid_input",
"[",
"'Server'",
"]",
"[",
"'HWConfigurationIrmc'",
"]",
".",
"update",
"(",
"{",
"'@... | Process raid input data.
:param target_raid_config: node raid info
:param raid_input: raid information for creating via eLCM
:raises ELCMValueError: raise msg if wrong input
:return: raid_input: raid input data which create raid configuration
{
"Server":{
"HWConfigurationIrmc":{
"@Processing":"execute",
"Adapters":{
"RAIDAdapter":[
{
"@AdapterId":"RAIDAdapter0",
"@ConfigurationType":"Addressing",
"LogicalDrives":{
"LogicalDrive":[
{
"@Number":0,
"@Action":"Create",
"RaidLevel":"1"
}
]
}
}
]
},
"@Version":"1.00"
},
"@Version":"1.01"
}
} | [
"Process",
"raid",
"input",
"data",
"."
] | 4585ce2f76853b9773fb190ca0cfff0aa04a7cf8 | https://github.com/openstack/python-scciclient/blob/4585ce2f76853b9773fb190ca0cfff0aa04a7cf8/scciclient/irmc/elcm.py#L845-L941 | train | 47,935 |
openstack/python-scciclient | scciclient/irmc/elcm.py | _get_existing_logical_drives | def _get_existing_logical_drives(raid_adapter):
"""Collect existing logical drives on the server.
:param raid_adapter: raid adapter info
:returns: existing_logical_drives: get logical drive on server
"""
existing_logical_drives = []
logical_drives = raid_adapter['Server']['HWConfigurationIrmc'][
'Adapters']['RAIDAdapter'][0].get('LogicalDrives')
if logical_drives is not None:
for drive in logical_drives['LogicalDrive']:
existing_logical_drives.append(drive['@Number'])
return existing_logical_drives | python | def _get_existing_logical_drives(raid_adapter):
"""Collect existing logical drives on the server.
:param raid_adapter: raid adapter info
:returns: existing_logical_drives: get logical drive on server
"""
existing_logical_drives = []
logical_drives = raid_adapter['Server']['HWConfigurationIrmc'][
'Adapters']['RAIDAdapter'][0].get('LogicalDrives')
if logical_drives is not None:
for drive in logical_drives['LogicalDrive']:
existing_logical_drives.append(drive['@Number'])
return existing_logical_drives | [
"def",
"_get_existing_logical_drives",
"(",
"raid_adapter",
")",
":",
"existing_logical_drives",
"=",
"[",
"]",
"logical_drives",
"=",
"raid_adapter",
"[",
"'Server'",
"]",
"[",
"'HWConfigurationIrmc'",
"]",
"[",
"'Adapters'",
"]",
"[",
"'RAIDAdapter'",
"]",
"[",
... | Collect existing logical drives on the server.
:param raid_adapter: raid adapter info
:returns: existing_logical_drives: get logical drive on server | [
"Collect",
"existing",
"logical",
"drives",
"on",
"the",
"server",
"."
] | 4585ce2f76853b9773fb190ca0cfff0aa04a7cf8 | https://github.com/openstack/python-scciclient/blob/4585ce2f76853b9773fb190ca0cfff0aa04a7cf8/scciclient/irmc/elcm.py#L958-L971 | train | 47,936 |
openstack/python-scciclient | scciclient/irmc/elcm.py | _create_raid_adapter_profile | def _create_raid_adapter_profile(irmc_info):
"""Attempt delete exist adapter then create new raid adapter on the server.
:param irmc_info: node info
:returns: result: a dict with following values:
{
'raid_config': <data of raid adapter profile>,
'warning': <warning message if there is>
}
"""
try:
# Attempt erase exist adapter on BM Server
elcm_profile_delete(irmc_info, PROFILE_RAID_CONFIG)
except ELCMProfileNotFound:
# Ignore this error as it's not an error in this case
pass
session = elcm_profile_create(irmc_info, PARAM_PATH_RAID_CONFIG)
# Monitoring currently session until done.
session_timeout = irmc_info.get('irmc_raid_session_timeout',
RAID_CONFIG_SESSION_TIMEOUT)
return _process_session_data(irmc_info, 'CONFIG_RAID',
session['Session']['Id'],
session_timeout) | python | def _create_raid_adapter_profile(irmc_info):
"""Attempt delete exist adapter then create new raid adapter on the server.
:param irmc_info: node info
:returns: result: a dict with following values:
{
'raid_config': <data of raid adapter profile>,
'warning': <warning message if there is>
}
"""
try:
# Attempt erase exist adapter on BM Server
elcm_profile_delete(irmc_info, PROFILE_RAID_CONFIG)
except ELCMProfileNotFound:
# Ignore this error as it's not an error in this case
pass
session = elcm_profile_create(irmc_info, PARAM_PATH_RAID_CONFIG)
# Monitoring currently session until done.
session_timeout = irmc_info.get('irmc_raid_session_timeout',
RAID_CONFIG_SESSION_TIMEOUT)
return _process_session_data(irmc_info, 'CONFIG_RAID',
session['Session']['Id'],
session_timeout) | [
"def",
"_create_raid_adapter_profile",
"(",
"irmc_info",
")",
":",
"try",
":",
"# Attempt erase exist adapter on BM Server",
"elcm_profile_delete",
"(",
"irmc_info",
",",
"PROFILE_RAID_CONFIG",
")",
"except",
"ELCMProfileNotFound",
":",
"# Ignore this error as it's not an error i... | Attempt delete exist adapter then create new raid adapter on the server.
:param irmc_info: node info
:returns: result: a dict with following values:
{
'raid_config': <data of raid adapter profile>,
'warning': <warning message if there is>
} | [
"Attempt",
"delete",
"exist",
"adapter",
"then",
"create",
"new",
"raid",
"adapter",
"on",
"the",
"server",
"."
] | 4585ce2f76853b9773fb190ca0cfff0aa04a7cf8 | https://github.com/openstack/python-scciclient/blob/4585ce2f76853b9773fb190ca0cfff0aa04a7cf8/scciclient/irmc/elcm.py#L974-L1000 | train | 47,937 |
openstack/python-scciclient | scciclient/irmc/elcm.py | create_raid_configuration | def create_raid_configuration(irmc_info, target_raid_config):
"""Process raid_input then perform raid configuration into server.
:param irmc_info: node info
:param target_raid_config: node raid information
"""
if len(target_raid_config['logical_disks']) < 1:
raise ELCMValueError(message="logical_disks must not be empty")
# Check RAID config in the new RAID adapter. Must be erased before
# create new RAID config.
raid_adapter = get_raid_adapter(irmc_info)
logical_drives = raid_adapter['Server']['HWConfigurationIrmc'][
'Adapters']['RAIDAdapter'][0].get('LogicalDrives')
session_timeout = irmc_info.get('irmc_raid_session_timeout',
RAID_CONFIG_SESSION_TIMEOUT)
if logical_drives is not None:
# Delete exist logical drives in server.
# NOTE(trungnv): Wait session complete and raise error if
# delete raid config during FGI(Foreground Initialization) in-progress
# in previous mechanism.
delete_raid_configuration(irmc_info)
# Updating raid adapter profile after deleted profile.
raid_adapter = get_raid_adapter(irmc_info)
# Create raid configuration based on target_raid_config of node
raid_input = _update_raid_input_data(target_raid_config, raid_adapter)
session = elcm_profile_set(irmc_info, raid_input)
# Monitoring raid creation session until done.
_process_session_data(irmc_info, 'CONFIG_RAID',
session['Session']['Id'],
session_timeout) | python | def create_raid_configuration(irmc_info, target_raid_config):
"""Process raid_input then perform raid configuration into server.
:param irmc_info: node info
:param target_raid_config: node raid information
"""
if len(target_raid_config['logical_disks']) < 1:
raise ELCMValueError(message="logical_disks must not be empty")
# Check RAID config in the new RAID adapter. Must be erased before
# create new RAID config.
raid_adapter = get_raid_adapter(irmc_info)
logical_drives = raid_adapter['Server']['HWConfigurationIrmc'][
'Adapters']['RAIDAdapter'][0].get('LogicalDrives')
session_timeout = irmc_info.get('irmc_raid_session_timeout',
RAID_CONFIG_SESSION_TIMEOUT)
if logical_drives is not None:
# Delete exist logical drives in server.
# NOTE(trungnv): Wait session complete and raise error if
# delete raid config during FGI(Foreground Initialization) in-progress
# in previous mechanism.
delete_raid_configuration(irmc_info)
# Updating raid adapter profile after deleted profile.
raid_adapter = get_raid_adapter(irmc_info)
# Create raid configuration based on target_raid_config of node
raid_input = _update_raid_input_data(target_raid_config, raid_adapter)
session = elcm_profile_set(irmc_info, raid_input)
# Monitoring raid creation session until done.
_process_session_data(irmc_info, 'CONFIG_RAID',
session['Session']['Id'],
session_timeout) | [
"def",
"create_raid_configuration",
"(",
"irmc_info",
",",
"target_raid_config",
")",
":",
"if",
"len",
"(",
"target_raid_config",
"[",
"'logical_disks'",
"]",
")",
"<",
"1",
":",
"raise",
"ELCMValueError",
"(",
"message",
"=",
"\"logical_disks must not be empty\"",
... | Process raid_input then perform raid configuration into server.
:param irmc_info: node info
:param target_raid_config: node raid information | [
"Process",
"raid_input",
"then",
"perform",
"raid",
"configuration",
"into",
"server",
"."
] | 4585ce2f76853b9773fb190ca0cfff0aa04a7cf8 | https://github.com/openstack/python-scciclient/blob/4585ce2f76853b9773fb190ca0cfff0aa04a7cf8/scciclient/irmc/elcm.py#L1003-L1035 | train | 47,938 |
openstack/python-scciclient | scciclient/irmc/elcm.py | delete_raid_configuration | def delete_raid_configuration(irmc_info):
"""Delete whole raid configuration or one of logical drive on the server.
:param irmc_info: node info
"""
# Attempt to get raid configuration on BM Server
raid_adapter = get_raid_adapter(irmc_info)
existing_logical_drives = _get_existing_logical_drives(raid_adapter)
# Ironic requires delete_configuration first. Will pass if blank raid
# configuration in server.
if not existing_logical_drives:
return
raid_adapter['Server']['HWConfigurationIrmc'].update({
'@Processing': 'execute'})
logical_drive = raid_adapter['Server']['HWConfigurationIrmc'][
'Adapters']['RAIDAdapter'][0]['LogicalDrives']['LogicalDrive']
for drive in logical_drive:
drive['@Action'] = 'Delete'
# Attempt to delete logical drive in the raid config
session = elcm_profile_set(irmc_info, raid_adapter)
# Monitoring raid config delete session until done.
session_timeout = irmc_info.get('irmc_raid_session_timeout',
RAID_CONFIG_SESSION_TIMEOUT)
_process_session_data(irmc_info, 'CONFIG_RAID', session['Session']['Id'],
session_timeout)
# Attempt to delete raid adapter
elcm_profile_delete(irmc_info, PROFILE_RAID_CONFIG) | python | def delete_raid_configuration(irmc_info):
"""Delete whole raid configuration or one of logical drive on the server.
:param irmc_info: node info
"""
# Attempt to get raid configuration on BM Server
raid_adapter = get_raid_adapter(irmc_info)
existing_logical_drives = _get_existing_logical_drives(raid_adapter)
# Ironic requires delete_configuration first. Will pass if blank raid
# configuration in server.
if not existing_logical_drives:
return
raid_adapter['Server']['HWConfigurationIrmc'].update({
'@Processing': 'execute'})
logical_drive = raid_adapter['Server']['HWConfigurationIrmc'][
'Adapters']['RAIDAdapter'][0]['LogicalDrives']['LogicalDrive']
for drive in logical_drive:
drive['@Action'] = 'Delete'
# Attempt to delete logical drive in the raid config
session = elcm_profile_set(irmc_info, raid_adapter)
# Monitoring raid config delete session until done.
session_timeout = irmc_info.get('irmc_raid_session_timeout',
RAID_CONFIG_SESSION_TIMEOUT)
_process_session_data(irmc_info, 'CONFIG_RAID', session['Session']['Id'],
session_timeout)
# Attempt to delete raid adapter
elcm_profile_delete(irmc_info, PROFILE_RAID_CONFIG) | [
"def",
"delete_raid_configuration",
"(",
"irmc_info",
")",
":",
"# Attempt to get raid configuration on BM Server",
"raid_adapter",
"=",
"get_raid_adapter",
"(",
"irmc_info",
")",
"existing_logical_drives",
"=",
"_get_existing_logical_drives",
"(",
"raid_adapter",
")",
"# Ironi... | Delete whole raid configuration or one of logical drive on the server.
:param irmc_info: node info | [
"Delete",
"whole",
"raid",
"configuration",
"or",
"one",
"of",
"logical",
"drive",
"on",
"the",
"server",
"."
] | 4585ce2f76853b9773fb190ca0cfff0aa04a7cf8 | https://github.com/openstack/python-scciclient/blob/4585ce2f76853b9773fb190ca0cfff0aa04a7cf8/scciclient/irmc/elcm.py#L1038-L1067 | train | 47,939 |
openstack/python-scciclient | scciclient/irmc/elcm.py | set_bios_configuration | def set_bios_configuration(irmc_info, settings):
"""Set BIOS configurations on the server.
:param irmc_info: node info
:param settings: Dictionary containing the BIOS configuration.
:raise: BiosConfigNotFound, if there is wrong settings for bios
configuration.
"""
bios_config_data = {
'Server': {
'SystemConfig': {
'BiosConfig': {}
}
}
}
versions = elcm_profile_get_versions(irmc_info)
server_version = versions['Server'].get('@Version')
bios_version = \
versions['Server']['SystemConfig']['BiosConfig'].get('@Version')
if server_version:
bios_config_data['Server']['@Version'] = server_version
if bios_version:
bios_config_data['Server']['SystemConfig']['BiosConfig']['@Version'] = \
bios_version
configs = {}
for setting_param in settings:
setting_name = setting_param.get("name")
setting_value = setting_param.get("value")
# Revert-conversion from a string of True/False to boolean.
# It will be raise failed if put "True" or "False" string value.
if isinstance(setting_value, six.string_types):
if setting_value.lower() == "true":
setting_value = True
elif setting_value.lower() == "false":
setting_value = False
try:
type_config, config = BIOS_CONFIGURATION_DICTIONARY[
setting_name].split("_")
if type_config in configs.keys():
configs[type_config][config] = setting_value
else:
configs.update({type_config: {config: setting_value}})
except KeyError:
raise BiosConfigNotFound("Invalid BIOS setting: %s"
% setting_param)
bios_config_data['Server']['SystemConfig']['BiosConfig'].update(configs)
restore_bios_config(irmc_info, bios_config_data) | python | def set_bios_configuration(irmc_info, settings):
"""Set BIOS configurations on the server.
:param irmc_info: node info
:param settings: Dictionary containing the BIOS configuration.
:raise: BiosConfigNotFound, if there is wrong settings for bios
configuration.
"""
bios_config_data = {
'Server': {
'SystemConfig': {
'BiosConfig': {}
}
}
}
versions = elcm_profile_get_versions(irmc_info)
server_version = versions['Server'].get('@Version')
bios_version = \
versions['Server']['SystemConfig']['BiosConfig'].get('@Version')
if server_version:
bios_config_data['Server']['@Version'] = server_version
if bios_version:
bios_config_data['Server']['SystemConfig']['BiosConfig']['@Version'] = \
bios_version
configs = {}
for setting_param in settings:
setting_name = setting_param.get("name")
setting_value = setting_param.get("value")
# Revert-conversion from a string of True/False to boolean.
# It will be raise failed if put "True" or "False" string value.
if isinstance(setting_value, six.string_types):
if setting_value.lower() == "true":
setting_value = True
elif setting_value.lower() == "false":
setting_value = False
try:
type_config, config = BIOS_CONFIGURATION_DICTIONARY[
setting_name].split("_")
if type_config in configs.keys():
configs[type_config][config] = setting_value
else:
configs.update({type_config: {config: setting_value}})
except KeyError:
raise BiosConfigNotFound("Invalid BIOS setting: %s"
% setting_param)
bios_config_data['Server']['SystemConfig']['BiosConfig'].update(configs)
restore_bios_config(irmc_info, bios_config_data) | [
"def",
"set_bios_configuration",
"(",
"irmc_info",
",",
"settings",
")",
":",
"bios_config_data",
"=",
"{",
"'Server'",
":",
"{",
"'SystemConfig'",
":",
"{",
"'BiosConfig'",
":",
"{",
"}",
"}",
"}",
"}",
"versions",
"=",
"elcm_profile_get_versions",
"(",
"irmc... | Set BIOS configurations on the server.
:param irmc_info: node info
:param settings: Dictionary containing the BIOS configuration.
:raise: BiosConfigNotFound, if there is wrong settings for bios
configuration. | [
"Set",
"BIOS",
"configurations",
"on",
"the",
"server",
"."
] | 4585ce2f76853b9773fb190ca0cfff0aa04a7cf8 | https://github.com/openstack/python-scciclient/blob/4585ce2f76853b9773fb190ca0cfff0aa04a7cf8/scciclient/irmc/elcm.py#L1070-L1120 | train | 47,940 |
openstack/python-scciclient | scciclient/irmc/elcm.py | get_bios_settings | def get_bios_settings(irmc_info):
"""Get the current BIOS settings on the server
:param irmc_info: node info.
:returns: a list of dictionary BIOS settings
"""
bios_config = backup_bios_config(irmc_info)['bios_config']
bios_config_data = bios_config['Server']['SystemConfig']['BiosConfig']
settings = []
# TODO(trungnv): Allow working with multi levels of BIOS dictionary.
for setting_param in BIOS_CONFIGURATION_DICTIONARY:
type_config, config = BIOS_CONFIGURATION_DICTIONARY[
setting_param].split("_")
if config in bios_config_data.get(type_config, {}):
value = six.text_type(bios_config_data[type_config][config])
settings.append({'name': setting_param, 'value': value})
return settings | python | def get_bios_settings(irmc_info):
"""Get the current BIOS settings on the server
:param irmc_info: node info.
:returns: a list of dictionary BIOS settings
"""
bios_config = backup_bios_config(irmc_info)['bios_config']
bios_config_data = bios_config['Server']['SystemConfig']['BiosConfig']
settings = []
# TODO(trungnv): Allow working with multi levels of BIOS dictionary.
for setting_param in BIOS_CONFIGURATION_DICTIONARY:
type_config, config = BIOS_CONFIGURATION_DICTIONARY[
setting_param].split("_")
if config in bios_config_data.get(type_config, {}):
value = six.text_type(bios_config_data[type_config][config])
settings.append({'name': setting_param, 'value': value})
return settings | [
"def",
"get_bios_settings",
"(",
"irmc_info",
")",
":",
"bios_config",
"=",
"backup_bios_config",
"(",
"irmc_info",
")",
"[",
"'bios_config'",
"]",
"bios_config_data",
"=",
"bios_config",
"[",
"'Server'",
"]",
"[",
"'SystemConfig'",
"]",
"[",
"'BiosConfig'",
"]",
... | Get the current BIOS settings on the server
:param irmc_info: node info.
:returns: a list of dictionary BIOS settings | [
"Get",
"the",
"current",
"BIOS",
"settings",
"on",
"the",
"server"
] | 4585ce2f76853b9773fb190ca0cfff0aa04a7cf8 | https://github.com/openstack/python-scciclient/blob/4585ce2f76853b9773fb190ca0cfff0aa04a7cf8/scciclient/irmc/elcm.py#L1123-L1141 | train | 47,941 |
playpauseandstop/rororo | rororo/aio.py | add_resource_context | def add_resource_context(router: web.AbstractRouter,
url_prefix: str = None,
name_prefix: str = None) -> Iterator[Any]:
"""Context manager for adding resources for given router.
Main goal of context manager to easify process of adding resources with
routes to the router. This also allow to reduce amount of repeats, when
supplying new resources by reusing URL & name prefixes for all routes
inside context manager.
Behind the scene, context manager returns a function which calls::
resource = router.add_resource(url, name)
resource.add_route(method, handler)
**Usage**::
with add_resource_context(app.router, '/api', 'api') as add_resource:
add_resource('/', get=views.index)
add_resource('/news', get=views.list_news, post=views.create_news)
:param router: Route to add resources to.
:param url_prefix: If supplied prepend this prefix to each resource URL.
:param name_prefix: If supplied prepend this prefix to each resource name.
"""
def add_resource(url: str,
get: View = None,
*,
name: str = None,
**kwargs: Any) -> web.Resource:
"""Inner function to create resource and add necessary routes to it.
Support adding routes of all methods, supported by aiohttp, as
GET/POST/PUT/PATCH/DELETE/HEAD/OPTIONS/*, e.g.,
::
with add_resource_context(app.router) as add_resource:
add_resource('/', get=views.get, post=views.post)
add_resource('/wildcard', **{'*': views.wildcard})
:param url:
Resource URL. If ``url_prefix`` setup in context it will be
prepended to URL with ``/``.
:param get:
GET handler. Only handler to be setup without explicit call.
:param name: Resource name.
:type name: str
:rtype: aiohttp.web.Resource
"""
kwargs['get'] = get
if url_prefix:
url = '/'.join((url_prefix.rstrip('/'), url.lstrip('/')))
if not name and get:
name = get.__name__
if name_prefix and name:
name = '.'.join((name_prefix.rstrip('.'), name.lstrip('.')))
resource = router.add_resource(url, name=name)
for method, handler in kwargs.items():
if handler is None:
continue
resource.add_route(method.upper(), handler)
return resource
yield add_resource | python | def add_resource_context(router: web.AbstractRouter,
url_prefix: str = None,
name_prefix: str = None) -> Iterator[Any]:
"""Context manager for adding resources for given router.
Main goal of context manager to easify process of adding resources with
routes to the router. This also allow to reduce amount of repeats, when
supplying new resources by reusing URL & name prefixes for all routes
inside context manager.
Behind the scene, context manager returns a function which calls::
resource = router.add_resource(url, name)
resource.add_route(method, handler)
**Usage**::
with add_resource_context(app.router, '/api', 'api') as add_resource:
add_resource('/', get=views.index)
add_resource('/news', get=views.list_news, post=views.create_news)
:param router: Route to add resources to.
:param url_prefix: If supplied prepend this prefix to each resource URL.
:param name_prefix: If supplied prepend this prefix to each resource name.
"""
def add_resource(url: str,
get: View = None,
*,
name: str = None,
**kwargs: Any) -> web.Resource:
"""Inner function to create resource and add necessary routes to it.
Support adding routes of all methods, supported by aiohttp, as
GET/POST/PUT/PATCH/DELETE/HEAD/OPTIONS/*, e.g.,
::
with add_resource_context(app.router) as add_resource:
add_resource('/', get=views.get, post=views.post)
add_resource('/wildcard', **{'*': views.wildcard})
:param url:
Resource URL. If ``url_prefix`` setup in context it will be
prepended to URL with ``/``.
:param get:
GET handler. Only handler to be setup without explicit call.
:param name: Resource name.
:type name: str
:rtype: aiohttp.web.Resource
"""
kwargs['get'] = get
if url_prefix:
url = '/'.join((url_prefix.rstrip('/'), url.lstrip('/')))
if not name and get:
name = get.__name__
if name_prefix and name:
name = '.'.join((name_prefix.rstrip('.'), name.lstrip('.')))
resource = router.add_resource(url, name=name)
for method, handler in kwargs.items():
if handler is None:
continue
resource.add_route(method.upper(), handler)
return resource
yield add_resource | [
"def",
"add_resource_context",
"(",
"router",
":",
"web",
".",
"AbstractRouter",
",",
"url_prefix",
":",
"str",
"=",
"None",
",",
"name_prefix",
":",
"str",
"=",
"None",
")",
"->",
"Iterator",
"[",
"Any",
"]",
":",
"def",
"add_resource",
"(",
"url",
":",... | Context manager for adding resources for given router.
Main goal of context manager to easify process of adding resources with
routes to the router. This also allow to reduce amount of repeats, when
supplying new resources by reusing URL & name prefixes for all routes
inside context manager.
Behind the scene, context manager returns a function which calls::
resource = router.add_resource(url, name)
resource.add_route(method, handler)
**Usage**::
with add_resource_context(app.router, '/api', 'api') as add_resource:
add_resource('/', get=views.index)
add_resource('/news', get=views.list_news, post=views.create_news)
:param router: Route to add resources to.
:param url_prefix: If supplied prepend this prefix to each resource URL.
:param name_prefix: If supplied prepend this prefix to each resource name. | [
"Context",
"manager",
"for",
"adding",
"resources",
"for",
"given",
"router",
"."
] | 28a04e8028c29647941e727116335e9d6fd64c27 | https://github.com/playpauseandstop/rororo/blob/28a04e8028c29647941e727116335e9d6fd64c27/rororo/aio.py#L42-L110 | train | 47,942 |
OSSOS/MOP | src/ossos/core/ossos/downloads/cutouts/focus.py | SingletFocusCalculator.calculate_focus | def calculate_focus(self, reading):
"""
Determines what the focal point of the downloaded image should be.
Returns:
focal_point: (x, y)
The location of the source in the middle observation, in the
coordinate system of the current source reading.
"""
middle_index = len(self.source.get_readings()) // 2
middle_reading = self.source.get_reading(middle_index)
return self.convert_source_location(middle_reading, reading) | python | def calculate_focus(self, reading):
"""
Determines what the focal point of the downloaded image should be.
Returns:
focal_point: (x, y)
The location of the source in the middle observation, in the
coordinate system of the current source reading.
"""
middle_index = len(self.source.get_readings()) // 2
middle_reading = self.source.get_reading(middle_index)
return self.convert_source_location(middle_reading, reading) | [
"def",
"calculate_focus",
"(",
"self",
",",
"reading",
")",
":",
"middle_index",
"=",
"len",
"(",
"self",
".",
"source",
".",
"get_readings",
"(",
")",
")",
"//",
"2",
"middle_reading",
"=",
"self",
".",
"source",
".",
"get_reading",
"(",
"middle_index",
... | Determines what the focal point of the downloaded image should be.
Returns:
focal_point: (x, y)
The location of the source in the middle observation, in the
coordinate system of the current source reading. | [
"Determines",
"what",
"the",
"focal",
"point",
"of",
"the",
"downloaded",
"image",
"should",
"be",
"."
] | 94f91d32ad5ec081d5a1ebd67604a838003465af | https://github.com/OSSOS/MOP/blob/94f91d32ad5ec081d5a1ebd67604a838003465af/src/ossos/core/ossos/downloads/cutouts/focus.py#L24-L35 | train | 47,943 |
OSSOS/MOP | src/ossos/plotting/scripts/rose_topdown.py | plot_ossos_discoveries | def plot_ossos_discoveries(ax, discoveries, plot_discoveries,
plot_colossos=False, split_plutinos=False):
"""
plotted at their discovery locations, provided by the Version Releases in decimal degrees.
"""
fc = ['b', '#E47833', 'k']
alpha = [0.85, 0.6, 1.]
marker = ['o', 'd']
size = [7, 25]
plottable = [] # Which blocks' discoveries to include?
for d in discoveries:
for n in plot_discoveries:
if d['object'].startswith(n): # can for sure be better, but this hack works. Need to get where going
plottable.append(d)
# Hack to get in the O15BD objects
# directory_name = '/Users/bannisterm/Dropbox/OSSOS/measure3/ossin/D_tmp/'
# kbos = parsers.ossos_discoveries(directory_name, all_objects=False, data_release=None)
# for kbo in kbos:
# plottable_kbo = {'RAdeg': kbo.discovery.coordinate.ra.to_string(unit=units.degree, sep=':'),
# 'dist': kbo.orbit.distance.value}
# plottable.append(plottable_kbo)
if plot_colossos:
fainter = []
colossos = []
for n in plottable:
if n['object'] in parameters.COLOSSOS:
colossos.append(n)
else:
fainter.append(n)
plot_ossos_points(fainter, ax, marker[0], size[0], fc[0], alpha[1], 1)
plot_ossos_points(colossos, ax, marker[1], size[1], fc[2], alpha[2], 2)
elif split_plutinos:
# plutino_index = np.where((plottable['cl'] == 'res') & (plottable['j'] == 3) & (plottable['k'] == 2))
raise NotImplementedError
else:
plot_ossos_points(plottable, ax, marker[0], size[0], fc[0], alpha[0], 2)
return | python | def plot_ossos_discoveries(ax, discoveries, plot_discoveries,
plot_colossos=False, split_plutinos=False):
"""
plotted at their discovery locations, provided by the Version Releases in decimal degrees.
"""
fc = ['b', '#E47833', 'k']
alpha = [0.85, 0.6, 1.]
marker = ['o', 'd']
size = [7, 25]
plottable = [] # Which blocks' discoveries to include?
for d in discoveries:
for n in plot_discoveries:
if d['object'].startswith(n): # can for sure be better, but this hack works. Need to get where going
plottable.append(d)
# Hack to get in the O15BD objects
# directory_name = '/Users/bannisterm/Dropbox/OSSOS/measure3/ossin/D_tmp/'
# kbos = parsers.ossos_discoveries(directory_name, all_objects=False, data_release=None)
# for kbo in kbos:
# plottable_kbo = {'RAdeg': kbo.discovery.coordinate.ra.to_string(unit=units.degree, sep=':'),
# 'dist': kbo.orbit.distance.value}
# plottable.append(plottable_kbo)
if plot_colossos:
fainter = []
colossos = []
for n in plottable:
if n['object'] in parameters.COLOSSOS:
colossos.append(n)
else:
fainter.append(n)
plot_ossos_points(fainter, ax, marker[0], size[0], fc[0], alpha[1], 1)
plot_ossos_points(colossos, ax, marker[1], size[1], fc[2], alpha[2], 2)
elif split_plutinos:
# plutino_index = np.where((plottable['cl'] == 'res') & (plottable['j'] == 3) & (plottable['k'] == 2))
raise NotImplementedError
else:
plot_ossos_points(plottable, ax, marker[0], size[0], fc[0], alpha[0], 2)
return | [
"def",
"plot_ossos_discoveries",
"(",
"ax",
",",
"discoveries",
",",
"plot_discoveries",
",",
"plot_colossos",
"=",
"False",
",",
"split_plutinos",
"=",
"False",
")",
":",
"fc",
"=",
"[",
"'b'",
",",
"'#E47833'",
",",
"'k'",
"]",
"alpha",
"=",
"[",
"0.85",... | plotted at their discovery locations, provided by the Version Releases in decimal degrees. | [
"plotted",
"at",
"their",
"discovery",
"locations",
"provided",
"by",
"the",
"Version",
"Releases",
"in",
"decimal",
"degrees",
"."
] | 94f91d32ad5ec081d5a1ebd67604a838003465af | https://github.com/OSSOS/MOP/blob/94f91d32ad5ec081d5a1ebd67604a838003465af/src/ossos/plotting/scripts/rose_topdown.py#L165-L205 | train | 47,944 |
openstack/python-scciclient | scciclient/irmc/snmp.py | get_irmc_firmware_version | def get_irmc_firmware_version(snmp_client):
"""Get irmc firmware version of the node.
:param snmp_client: an SNMP client object.
:raises: SNMPFailure if SNMP operation failed.
:returns: a string of bmc name and irmc firmware version.
"""
try:
bmc_name = snmp_client.get(BMC_NAME_OID)
irmc_firm_ver = snmp_client.get(IRMC_FW_VERSION_OID)
return ('%(bmc)s%(sep)s%(firm_ver)s' %
{'bmc': bmc_name if bmc_name else '',
'firm_ver': irmc_firm_ver if irmc_firm_ver else '',
'sep': '-' if bmc_name and irmc_firm_ver else ''})
except SNMPFailure as e:
raise SNMPIRMCFirmwareFailure(
SNMP_FAILURE_MSG % ("GET IRMC FIRMWARE VERSION", e)) | python | def get_irmc_firmware_version(snmp_client):
"""Get irmc firmware version of the node.
:param snmp_client: an SNMP client object.
:raises: SNMPFailure if SNMP operation failed.
:returns: a string of bmc name and irmc firmware version.
"""
try:
bmc_name = snmp_client.get(BMC_NAME_OID)
irmc_firm_ver = snmp_client.get(IRMC_FW_VERSION_OID)
return ('%(bmc)s%(sep)s%(firm_ver)s' %
{'bmc': bmc_name if bmc_name else '',
'firm_ver': irmc_firm_ver if irmc_firm_ver else '',
'sep': '-' if bmc_name and irmc_firm_ver else ''})
except SNMPFailure as e:
raise SNMPIRMCFirmwareFailure(
SNMP_FAILURE_MSG % ("GET IRMC FIRMWARE VERSION", e)) | [
"def",
"get_irmc_firmware_version",
"(",
"snmp_client",
")",
":",
"try",
":",
"bmc_name",
"=",
"snmp_client",
".",
"get",
"(",
"BMC_NAME_OID",
")",
"irmc_firm_ver",
"=",
"snmp_client",
".",
"get",
"(",
"IRMC_FW_VERSION_OID",
")",
"return",
"(",
"'%(bmc)s%(sep)s%(f... | Get irmc firmware version of the node.
:param snmp_client: an SNMP client object.
:raises: SNMPFailure if SNMP operation failed.
:returns: a string of bmc name and irmc firmware version. | [
"Get",
"irmc",
"firmware",
"version",
"of",
"the",
"node",
"."
] | 4585ce2f76853b9773fb190ca0cfff0aa04a7cf8 | https://github.com/openstack/python-scciclient/blob/4585ce2f76853b9773fb190ca0cfff0aa04a7cf8/scciclient/irmc/snmp.py#L69-L86 | train | 47,945 |
openstack/python-scciclient | scciclient/irmc/snmp.py | get_bios_firmware_version | def get_bios_firmware_version(snmp_client):
"""Get bios firmware version of the node.
:param snmp_client: an SNMP client object.
:raises: SNMPFailure if SNMP operation failed.
:returns: a string of bios firmware version.
"""
try:
bios_firmware_version = snmp_client.get(BIOS_FW_VERSION_OID)
return six.text_type(bios_firmware_version)
except SNMPFailure as e:
raise SNMPBIOSFirmwareFailure(
SNMP_FAILURE_MSG % ("GET BIOS FIRMWARE VERSION", e)) | python | def get_bios_firmware_version(snmp_client):
"""Get bios firmware version of the node.
:param snmp_client: an SNMP client object.
:raises: SNMPFailure if SNMP operation failed.
:returns: a string of bios firmware version.
"""
try:
bios_firmware_version = snmp_client.get(BIOS_FW_VERSION_OID)
return six.text_type(bios_firmware_version)
except SNMPFailure as e:
raise SNMPBIOSFirmwareFailure(
SNMP_FAILURE_MSG % ("GET BIOS FIRMWARE VERSION", e)) | [
"def",
"get_bios_firmware_version",
"(",
"snmp_client",
")",
":",
"try",
":",
"bios_firmware_version",
"=",
"snmp_client",
".",
"get",
"(",
"BIOS_FW_VERSION_OID",
")",
"return",
"six",
".",
"text_type",
"(",
"bios_firmware_version",
")",
"except",
"SNMPFailure",
"as... | Get bios firmware version of the node.
:param snmp_client: an SNMP client object.
:raises: SNMPFailure if SNMP operation failed.
:returns: a string of bios firmware version. | [
"Get",
"bios",
"firmware",
"version",
"of",
"the",
"node",
"."
] | 4585ce2f76853b9773fb190ca0cfff0aa04a7cf8 | https://github.com/openstack/python-scciclient/blob/4585ce2f76853b9773fb190ca0cfff0aa04a7cf8/scciclient/irmc/snmp.py#L89-L102 | train | 47,946 |
openstack/python-scciclient | scciclient/irmc/snmp.py | get_server_model | def get_server_model(snmp_client):
"""Get server model of the node.
:param snmp_client: an SNMP client object.
:raises: SNMPFailure if SNMP operation failed.
:returns: a string of server model.
"""
try:
server_model = snmp_client.get(SERVER_MODEL_OID)
return six.text_type(server_model)
except SNMPFailure as e:
raise SNMPServerModelFailure(
SNMP_FAILURE_MSG % ("GET SERVER MODEL", e)) | python | def get_server_model(snmp_client):
"""Get server model of the node.
:param snmp_client: an SNMP client object.
:raises: SNMPFailure if SNMP operation failed.
:returns: a string of server model.
"""
try:
server_model = snmp_client.get(SERVER_MODEL_OID)
return six.text_type(server_model)
except SNMPFailure as e:
raise SNMPServerModelFailure(
SNMP_FAILURE_MSG % ("GET SERVER MODEL", e)) | [
"def",
"get_server_model",
"(",
"snmp_client",
")",
":",
"try",
":",
"server_model",
"=",
"snmp_client",
".",
"get",
"(",
"SERVER_MODEL_OID",
")",
"return",
"six",
".",
"text_type",
"(",
"server_model",
")",
"except",
"SNMPFailure",
"as",
"e",
":",
"raise",
... | Get server model of the node.
:param snmp_client: an SNMP client object.
:raises: SNMPFailure if SNMP operation failed.
:returns: a string of server model. | [
"Get",
"server",
"model",
"of",
"the",
"node",
"."
] | 4585ce2f76853b9773fb190ca0cfff0aa04a7cf8 | https://github.com/openstack/python-scciclient/blob/4585ce2f76853b9773fb190ca0cfff0aa04a7cf8/scciclient/irmc/snmp.py#L105-L118 | train | 47,947 |
openstack/python-scciclient | scciclient/irmc/snmp.py | SNMPClient._get_auth | def _get_auth(self):
"""Return the authorization data for an SNMP request.
:returns: A
:class:`pysnmp.entity.rfc3413.oneliner.cmdgen.CommunityData`
object.
"""
if self.version == SNMP_V3:
# Handling auth/encryption credentials is not (yet) supported.
# This version supports a security name analogous to community.
return cmdgen.UsmUserData(self.security)
else:
mp_model = 1 if self.version == SNMP_V2C else 0
return cmdgen.CommunityData(self.community, mpModel=mp_model) | python | def _get_auth(self):
"""Return the authorization data for an SNMP request.
:returns: A
:class:`pysnmp.entity.rfc3413.oneliner.cmdgen.CommunityData`
object.
"""
if self.version == SNMP_V3:
# Handling auth/encryption credentials is not (yet) supported.
# This version supports a security name analogous to community.
return cmdgen.UsmUserData(self.security)
else:
mp_model = 1 if self.version == SNMP_V2C else 0
return cmdgen.CommunityData(self.community, mpModel=mp_model) | [
"def",
"_get_auth",
"(",
"self",
")",
":",
"if",
"self",
".",
"version",
"==",
"SNMP_V3",
":",
"# Handling auth/encryption credentials is not (yet) supported.",
"# This version supports a security name analogous to community.",
"return",
"cmdgen",
".",
"UsmUserData",
"(",
"se... | Return the authorization data for an SNMP request.
:returns: A
:class:`pysnmp.entity.rfc3413.oneliner.cmdgen.CommunityData`
object. | [
"Return",
"the",
"authorization",
"data",
"for",
"an",
"SNMP",
"request",
"."
] | 4585ce2f76853b9773fb190ca0cfff0aa04a7cf8 | https://github.com/openstack/python-scciclient/blob/4585ce2f76853b9773fb190ca0cfff0aa04a7cf8/scciclient/irmc/snmp.py#L138-L151 | train | 47,948 |
openstack/python-scciclient | scciclient/irmc/snmp.py | SNMPClient.get | def get(self, oid):
"""Use PySNMP to perform an SNMP GET operation on a single object.
:param oid: The OID of the object to get.
:raises: SNMPFailure if an SNMP request fails.
:returns: The value of the requested object.
"""
try:
results = self.cmd_gen.getCmd(self._get_auth(),
self._get_transport(),
oid)
except snmp_error.PySnmpError as e:
raise SNMPFailure(SNMP_FAILURE_MSG % ("GET", e))
error_indication, error_status, error_index, var_binds = results
if error_indication:
# SNMP engine-level error.
raise SNMPFailure(SNMP_FAILURE_MSG % ("GET", error_indication))
if error_status:
# SNMP PDU error.
raise SNMPFailure(
"SNMP operation '%(operation)s' failed: %(error)s at"
" %(index)s" %
{'operation': "GET", 'error': error_status.prettyPrint(),
'index':
error_index and var_binds[int(error_index) - 1]
or '?'})
# We only expect a single value back
name, val = var_binds[0]
return val | python | def get(self, oid):
"""Use PySNMP to perform an SNMP GET operation on a single object.
:param oid: The OID of the object to get.
:raises: SNMPFailure if an SNMP request fails.
:returns: The value of the requested object.
"""
try:
results = self.cmd_gen.getCmd(self._get_auth(),
self._get_transport(),
oid)
except snmp_error.PySnmpError as e:
raise SNMPFailure(SNMP_FAILURE_MSG % ("GET", e))
error_indication, error_status, error_index, var_binds = results
if error_indication:
# SNMP engine-level error.
raise SNMPFailure(SNMP_FAILURE_MSG % ("GET", error_indication))
if error_status:
# SNMP PDU error.
raise SNMPFailure(
"SNMP operation '%(operation)s' failed: %(error)s at"
" %(index)s" %
{'operation': "GET", 'error': error_status.prettyPrint(),
'index':
error_index and var_binds[int(error_index) - 1]
or '?'})
# We only expect a single value back
name, val = var_binds[0]
return val | [
"def",
"get",
"(",
"self",
",",
"oid",
")",
":",
"try",
":",
"results",
"=",
"self",
".",
"cmd_gen",
".",
"getCmd",
"(",
"self",
".",
"_get_auth",
"(",
")",
",",
"self",
".",
"_get_transport",
"(",
")",
",",
"oid",
")",
"except",
"snmp_error",
".",... | Use PySNMP to perform an SNMP GET operation on a single object.
:param oid: The OID of the object to get.
:raises: SNMPFailure if an SNMP request fails.
:returns: The value of the requested object. | [
"Use",
"PySNMP",
"to",
"perform",
"an",
"SNMP",
"GET",
"operation",
"on",
"a",
"single",
"object",
"."
] | 4585ce2f76853b9773fb190ca0cfff0aa04a7cf8 | https://github.com/openstack/python-scciclient/blob/4585ce2f76853b9773fb190ca0cfff0aa04a7cf8/scciclient/irmc/snmp.py#L165-L197 | train | 47,949 |
openstack/python-scciclient | scciclient/irmc/snmp.py | SNMPClient.get_next | def get_next(self, oid):
"""Use PySNMP to perform an SNMP GET NEXT operation on a table object.
:param oid: The OID of the object to get.
:raises: SNMPFailure if an SNMP request fails.
:returns: A list of values of the requested table object.
"""
try:
results = self.cmd_gen.nextCmd(self._get_auth(),
self._get_transport(),
oid)
except snmp_error.PySnmpError as e:
raise SNMPFailure(SNMP_FAILURE_MSG % ("GET_NEXT", e))
error_indication, error_status, error_index, var_binds = results
if error_indication:
# SNMP engine-level error.
raise SNMPFailure(
SNMP_FAILURE_MSG % ("GET_NEXT", error_indication))
if error_status:
# SNMP PDU error.
raise SNMPFailure(
"SNMP operation '%(operation)s' failed: %(error)s at"
" %(index)s" %
{'operation': "GET_NEXT", 'error': error_status.prettyPrint(),
'index':
error_index and var_binds[int(error_index) - 1]
or '?'})
return [val for row in var_binds for name, val in row] | python | def get_next(self, oid):
"""Use PySNMP to perform an SNMP GET NEXT operation on a table object.
:param oid: The OID of the object to get.
:raises: SNMPFailure if an SNMP request fails.
:returns: A list of values of the requested table object.
"""
try:
results = self.cmd_gen.nextCmd(self._get_auth(),
self._get_transport(),
oid)
except snmp_error.PySnmpError as e:
raise SNMPFailure(SNMP_FAILURE_MSG % ("GET_NEXT", e))
error_indication, error_status, error_index, var_binds = results
if error_indication:
# SNMP engine-level error.
raise SNMPFailure(
SNMP_FAILURE_MSG % ("GET_NEXT", error_indication))
if error_status:
# SNMP PDU error.
raise SNMPFailure(
"SNMP operation '%(operation)s' failed: %(error)s at"
" %(index)s" %
{'operation': "GET_NEXT", 'error': error_status.prettyPrint(),
'index':
error_index and var_binds[int(error_index) - 1]
or '?'})
return [val for row in var_binds for name, val in row] | [
"def",
"get_next",
"(",
"self",
",",
"oid",
")",
":",
"try",
":",
"results",
"=",
"self",
".",
"cmd_gen",
".",
"nextCmd",
"(",
"self",
".",
"_get_auth",
"(",
")",
",",
"self",
".",
"_get_transport",
"(",
")",
",",
"oid",
")",
"except",
"snmp_error",
... | Use PySNMP to perform an SNMP GET NEXT operation on a table object.
:param oid: The OID of the object to get.
:raises: SNMPFailure if an SNMP request fails.
:returns: A list of values of the requested table object. | [
"Use",
"PySNMP",
"to",
"perform",
"an",
"SNMP",
"GET",
"NEXT",
"operation",
"on",
"a",
"table",
"object",
"."
] | 4585ce2f76853b9773fb190ca0cfff0aa04a7cf8 | https://github.com/openstack/python-scciclient/blob/4585ce2f76853b9773fb190ca0cfff0aa04a7cf8/scciclient/irmc/snmp.py#L199-L230 | train | 47,950 |
openstack/python-scciclient | scciclient/irmc/snmp.py | SNMPClient.set | def set(self, oid, value):
"""Use PySNMP to perform an SNMP SET operation on a single object.
:param oid: The OID of the object to set.
:param value: The value of the object to set.
:raises: SNMPFailure if an SNMP request fails.
"""
try:
results = self.cmd_gen.setCmd(self._get_auth(),
self._get_transport(),
(oid, value))
except snmp_error.PySnmpError as e:
raise SNMPFailure(SNMP_FAILURE_MSG % ("SET", e))
error_indication, error_status, error_index, var_binds = results
if error_indication:
# SNMP engine-level error.
raise SNMPFailure(SNMP_FAILURE_MSG % ("SET", error_indication))
if error_status:
# SNMP PDU error.
raise SNMPFailure(
"SNMP operation '%(operation)s' failed: %(error)s at"
" %(index)s" %
{'operation': "SET", 'error': error_status.prettyPrint(),
'index':
error_index and var_binds[int(error_index) - 1]
or '?'}) | python | def set(self, oid, value):
"""Use PySNMP to perform an SNMP SET operation on a single object.
:param oid: The OID of the object to set.
:param value: The value of the object to set.
:raises: SNMPFailure if an SNMP request fails.
"""
try:
results = self.cmd_gen.setCmd(self._get_auth(),
self._get_transport(),
(oid, value))
except snmp_error.PySnmpError as e:
raise SNMPFailure(SNMP_FAILURE_MSG % ("SET", e))
error_indication, error_status, error_index, var_binds = results
if error_indication:
# SNMP engine-level error.
raise SNMPFailure(SNMP_FAILURE_MSG % ("SET", error_indication))
if error_status:
# SNMP PDU error.
raise SNMPFailure(
"SNMP operation '%(operation)s' failed: %(error)s at"
" %(index)s" %
{'operation': "SET", 'error': error_status.prettyPrint(),
'index':
error_index and var_binds[int(error_index) - 1]
or '?'}) | [
"def",
"set",
"(",
"self",
",",
"oid",
",",
"value",
")",
":",
"try",
":",
"results",
"=",
"self",
".",
"cmd_gen",
".",
"setCmd",
"(",
"self",
".",
"_get_auth",
"(",
")",
",",
"self",
".",
"_get_transport",
"(",
")",
",",
"(",
"oid",
",",
"value"... | Use PySNMP to perform an SNMP SET operation on a single object.
:param oid: The OID of the object to set.
:param value: The value of the object to set.
:raises: SNMPFailure if an SNMP request fails. | [
"Use",
"PySNMP",
"to",
"perform",
"an",
"SNMP",
"SET",
"operation",
"on",
"a",
"single",
"object",
"."
] | 4585ce2f76853b9773fb190ca0cfff0aa04a7cf8 | https://github.com/openstack/python-scciclient/blob/4585ce2f76853b9773fb190ca0cfff0aa04a7cf8/scciclient/irmc/snmp.py#L232-L260 | train | 47,951 |
OSSOS/MOP | src/ossos/core/ossos/mop_file.py | MOPFile.filename | def filename(self):
"""
Name if the MOP formatted file to parse.
@rtype: basestring
@return: filename
"""
if self._filename is None:
self._filename = storage.get_file(self.basename,
self.ccd,
ext=self.extension,
version=self.type,
prefix=self.prefix)
return self._filename | python | def filename(self):
"""
Name if the MOP formatted file to parse.
@rtype: basestring
@return: filename
"""
if self._filename is None:
self._filename = storage.get_file(self.basename,
self.ccd,
ext=self.extension,
version=self.type,
prefix=self.prefix)
return self._filename | [
"def",
"filename",
"(",
"self",
")",
":",
"if",
"self",
".",
"_filename",
"is",
"None",
":",
"self",
".",
"_filename",
"=",
"storage",
".",
"get_file",
"(",
"self",
".",
"basename",
",",
"self",
".",
"ccd",
",",
"ext",
"=",
"self",
".",
"extension",
... | Name if the MOP formatted file to parse.
@rtype: basestring
@return: filename | [
"Name",
"if",
"the",
"MOP",
"formatted",
"file",
"to",
"parse",
"."
] | 94f91d32ad5ec081d5a1ebd67604a838003465af | https://github.com/OSSOS/MOP/blob/94f91d32ad5ec081d5a1ebd67604a838003465af/src/ossos/core/ossos/mop_file.py#L28-L40 | train | 47,952 |
OSSOS/MOP | src/ossos/core/ossos/mop_file.py | MOPFile._parse | def _parse(self):
"""read in a file and return a MOPFile object."""
with open(self.filename, 'r') as fobj:
lines = fobj.read().split('\n')
# Create a header object with content at start of file
self.header = MOPHeader(self.subfmt).parser(lines)
# Create a data attribute to hold an astropy.table.Table object
self.data = MOPDataParser(self.header).parse(lines) | python | def _parse(self):
"""read in a file and return a MOPFile object."""
with open(self.filename, 'r') as fobj:
lines = fobj.read().split('\n')
# Create a header object with content at start of file
self.header = MOPHeader(self.subfmt).parser(lines)
# Create a data attribute to hold an astropy.table.Table object
self.data = MOPDataParser(self.header).parse(lines) | [
"def",
"_parse",
"(",
"self",
")",
":",
"with",
"open",
"(",
"self",
".",
"filename",
",",
"'r'",
")",
"as",
"fobj",
":",
"lines",
"=",
"fobj",
".",
"read",
"(",
")",
".",
"split",
"(",
"'\\n'",
")",
"# Create a header object with content at start of file"... | read in a file and return a MOPFile object. | [
"read",
"in",
"a",
"file",
"and",
"return",
"a",
"MOPFile",
"object",
"."
] | 94f91d32ad5ec081d5a1ebd67604a838003465af | https://github.com/OSSOS/MOP/blob/94f91d32ad5ec081d5a1ebd67604a838003465af/src/ossos/core/ossos/mop_file.py#L56-L65 | train | 47,953 |
OSSOS/MOP | src/ossos/core/ossos/mop_file.py | MOPDataParser.table | def table(self):
"""
The astropy.table.Table object that will contain the data result
@rtype: Table
@return: data table
"""
if self._table is None:
column_names = []
for fileid in self.header.file_ids:
for column_name in self.header.column_names:
column_names.append("{}_{}".format(column_name, fileid))
column_names.append("ZP_{}".format(fileid))
if len(column_names) > 0:
self._table = Table(names=column_names)
else:
self._table = Table()
return self._table | python | def table(self):
"""
The astropy.table.Table object that will contain the data result
@rtype: Table
@return: data table
"""
if self._table is None:
column_names = []
for fileid in self.header.file_ids:
for column_name in self.header.column_names:
column_names.append("{}_{}".format(column_name, fileid))
column_names.append("ZP_{}".format(fileid))
if len(column_names) > 0:
self._table = Table(names=column_names)
else:
self._table = Table()
return self._table | [
"def",
"table",
"(",
"self",
")",
":",
"if",
"self",
".",
"_table",
"is",
"None",
":",
"column_names",
"=",
"[",
"]",
"for",
"fileid",
"in",
"self",
".",
"header",
".",
"file_ids",
":",
"for",
"column_name",
"in",
"self",
".",
"header",
".",
"column_... | The astropy.table.Table object that will contain the data result
@rtype: Table
@return: data table | [
"The",
"astropy",
".",
"table",
".",
"Table",
"object",
"that",
"will",
"contain",
"the",
"data",
"result"
] | 94f91d32ad5ec081d5a1ebd67604a838003465af | https://github.com/OSSOS/MOP/blob/94f91d32ad5ec081d5a1ebd67604a838003465af/src/ossos/core/ossos/mop_file.py#L80-L96 | train | 47,954 |
OSSOS/MOP | src/ossos/core/ossos/mop_file.py | MOPHeader.parser | def parser(self, lines):
"""Given a set of lines parse the into a MOP Header"""
while len(lines) > 0:
if lines[0].startswith('##') and lines[1].startswith('# '):
# A two-line keyword/value line starts here.
self._header_append(lines.pop(0), lines.pop(0))
elif lines[0].startswith('# '):
# Lines with single comments are exposure numbers unless preceeded by double comment line
self._append_file_id(lines.pop(0))
elif lines[0].startswith('##'):
# Double comment lines without a single comment following are column headers for dataset.
self._set_column_names(lines.pop(0)[2:])
else:
# Last line of the header reached.
return self
raise IOError("Failed trying to read header") | python | def parser(self, lines):
"""Given a set of lines parse the into a MOP Header"""
while len(lines) > 0:
if lines[0].startswith('##') and lines[1].startswith('# '):
# A two-line keyword/value line starts here.
self._header_append(lines.pop(0), lines.pop(0))
elif lines[0].startswith('# '):
# Lines with single comments are exposure numbers unless preceeded by double comment line
self._append_file_id(lines.pop(0))
elif lines[0].startswith('##'):
# Double comment lines without a single comment following are column headers for dataset.
self._set_column_names(lines.pop(0)[2:])
else:
# Last line of the header reached.
return self
raise IOError("Failed trying to read header") | [
"def",
"parser",
"(",
"self",
",",
"lines",
")",
":",
"while",
"len",
"(",
"lines",
")",
">",
"0",
":",
"if",
"lines",
"[",
"0",
"]",
".",
"startswith",
"(",
"'##'",
")",
"and",
"lines",
"[",
"1",
"]",
".",
"startswith",
"(",
"'# '",
")",
":",
... | Given a set of lines parse the into a MOP Header | [
"Given",
"a",
"set",
"of",
"lines",
"parse",
"the",
"into",
"a",
"MOP",
"Header"
] | 94f91d32ad5ec081d5a1ebd67604a838003465af | https://github.com/OSSOS/MOP/blob/94f91d32ad5ec081d5a1ebd67604a838003465af/src/ossos/core/ossos/mop_file.py#L147-L162 | train | 47,955 |
OSSOS/MOP | src/ossos/core/ossos/mop_file.py | MOPHeader._compute_mjd | def _compute_mjd(self, kw, val):
"""
Sometimes that MJD-OBS-CENTER keyword maps to a three component string, instead of a single value.
@param kw: a list of keywords
@param val: a list of matching values
@return: the MJD-OBS-CENTER as a julian date.
"""
try:
idx = kw.index('MJD-OBS-CENTER')
except ValueError:
return
if len(val) == len(kw):
return
if len(val) - 2 != len(kw):
raise ValueError("convert: keyword/value lengths don't match: {}/{}".format(kw, val))
val.insert(idx, Time("{} {} {}".format(val.pop(idx), val.pop(idx), val.pop(idx)),
format='mpc',
scale='utc').mjd)
logging.debug("Computed MJD: {}".format(val[idx])) | python | def _compute_mjd(self, kw, val):
"""
Sometimes that MJD-OBS-CENTER keyword maps to a three component string, instead of a single value.
@param kw: a list of keywords
@param val: a list of matching values
@return: the MJD-OBS-CENTER as a julian date.
"""
try:
idx = kw.index('MJD-OBS-CENTER')
except ValueError:
return
if len(val) == len(kw):
return
if len(val) - 2 != len(kw):
raise ValueError("convert: keyword/value lengths don't match: {}/{}".format(kw, val))
val.insert(idx, Time("{} {} {}".format(val.pop(idx), val.pop(idx), val.pop(idx)),
format='mpc',
scale='utc').mjd)
logging.debug("Computed MJD: {}".format(val[idx])) | [
"def",
"_compute_mjd",
"(",
"self",
",",
"kw",
",",
"val",
")",
":",
"try",
":",
"idx",
"=",
"kw",
".",
"index",
"(",
"'MJD-OBS-CENTER'",
")",
"except",
"ValueError",
":",
"return",
"if",
"len",
"(",
"val",
")",
"==",
"len",
"(",
"kw",
")",
":",
... | Sometimes that MJD-OBS-CENTER keyword maps to a three component string, instead of a single value.
@param kw: a list of keywords
@param val: a list of matching values
@return: the MJD-OBS-CENTER as a julian date. | [
"Sometimes",
"that",
"MJD",
"-",
"OBS",
"-",
"CENTER",
"keyword",
"maps",
"to",
"a",
"three",
"component",
"string",
"instead",
"of",
"a",
"single",
"value",
"."
] | 94f91d32ad5ec081d5a1ebd67604a838003465af | https://github.com/OSSOS/MOP/blob/94f91d32ad5ec081d5a1ebd67604a838003465af/src/ossos/core/ossos/mop_file.py#L164-L182 | train | 47,956 |
OSSOS/MOP | src/jjk/preproc/findTriplets.py | getExpInfo | def getExpInfo(expnum):
"""Return a dictionary of information about a particular exposure"""
col_names=['object',
'e.expnum',
'mjdate',
'uttime',
'filter',
'elongation',
'obs_iq_refccd',
'triple', 'qso_status']
sql="SELECT "
sep=" "
for col_name in col_names:
sql=sql+sep+col_name
sep=","
sql=sql+" FROM bucket.exposure e "
sql=sql+" JOIN bucket.circumstance c ON e.expnum=c.expnum "
sql=sql+" LEFT JOIN triple_members t ON e.expnum=t.expnum "
sql=sql+" WHERE e.expnum=%d " % ( expnum )
#sys.stderr.write(sql);
cfeps.execute(sql)
rows=cfeps.fetchall()
#print rows
result={}
#import datetime
for idx in range(len(rows[0])):
result[col_names[idx]]=rows[0][idx]
return(result) | python | def getExpInfo(expnum):
"""Return a dictionary of information about a particular exposure"""
col_names=['object',
'e.expnum',
'mjdate',
'uttime',
'filter',
'elongation',
'obs_iq_refccd',
'triple', 'qso_status']
sql="SELECT "
sep=" "
for col_name in col_names:
sql=sql+sep+col_name
sep=","
sql=sql+" FROM bucket.exposure e "
sql=sql+" JOIN bucket.circumstance c ON e.expnum=c.expnum "
sql=sql+" LEFT JOIN triple_members t ON e.expnum=t.expnum "
sql=sql+" WHERE e.expnum=%d " % ( expnum )
#sys.stderr.write(sql);
cfeps.execute(sql)
rows=cfeps.fetchall()
#print rows
result={}
#import datetime
for idx in range(len(rows[0])):
result[col_names[idx]]=rows[0][idx]
return(result) | [
"def",
"getExpInfo",
"(",
"expnum",
")",
":",
"col_names",
"=",
"[",
"'object'",
",",
"'e.expnum'",
",",
"'mjdate'",
",",
"'uttime'",
",",
"'filter'",
",",
"'elongation'",
",",
"'obs_iq_refccd'",
",",
"'triple'",
",",
"'qso_status'",
"]",
"sql",
"=",
"\"SELE... | Return a dictionary of information about a particular exposure | [
"Return",
"a",
"dictionary",
"of",
"information",
"about",
"a",
"particular",
"exposure"
] | 94f91d32ad5ec081d5a1ebd67604a838003465af | https://github.com/OSSOS/MOP/blob/94f91d32ad5ec081d5a1ebd67604a838003465af/src/jjk/preproc/findTriplets.py#L79-L109 | train | 47,957 |
OSSOS/MOP | src/jjk/preproc/findTriplets.py | getTripInfo | def getTripInfo(triple):
"""Return a dictionary of information about a particular triple"""
col_names=['mjdate', 'filter', 'elongation', 'discovery','checkup', 'recovery', 'iq','block' ]
sql="SELECT mjdate md,"
sql=sql+" filter, avg(elongation), d.id, checkup.checkup, recovery.recovery , avg(obs_iq_refccd), b.qname "
sql=sql+"FROM triple_members t JOIN bucket.exposure e ON t.expnum=e.expnum "
sql=sql+"JOIN bucket.blocks b ON b.expnum=e.expnum "
sql=sql+"JOIN bucket.circumstance c on e.expnum=c.expnum "
sql=sql+"LEFT JOIN discovery d ON t.triple=d.triple "
sql=sql+"LEFT JOIN checkup ON t.triple=checkup.triple "
sql=sql+"LEFT JOIN recovery ON t.triple=recovery.triple "
sql=sql+"WHERE t.triple=%s "
sql=sql+"GROUP BY t.triple ORDER BY t.triple "
cfeps.execute(sql,(triple, ) )
rows=cfeps.fetchall()
result={}
#import datetime
for idx in range(len(rows[0])):
result[col_names[idx]]=rows[0][idx]
return result | python | def getTripInfo(triple):
"""Return a dictionary of information about a particular triple"""
col_names=['mjdate', 'filter', 'elongation', 'discovery','checkup', 'recovery', 'iq','block' ]
sql="SELECT mjdate md,"
sql=sql+" filter, avg(elongation), d.id, checkup.checkup, recovery.recovery , avg(obs_iq_refccd), b.qname "
sql=sql+"FROM triple_members t JOIN bucket.exposure e ON t.expnum=e.expnum "
sql=sql+"JOIN bucket.blocks b ON b.expnum=e.expnum "
sql=sql+"JOIN bucket.circumstance c on e.expnum=c.expnum "
sql=sql+"LEFT JOIN discovery d ON t.triple=d.triple "
sql=sql+"LEFT JOIN checkup ON t.triple=checkup.triple "
sql=sql+"LEFT JOIN recovery ON t.triple=recovery.triple "
sql=sql+"WHERE t.triple=%s "
sql=sql+"GROUP BY t.triple ORDER BY t.triple "
cfeps.execute(sql,(triple, ) )
rows=cfeps.fetchall()
result={}
#import datetime
for idx in range(len(rows[0])):
result[col_names[idx]]=rows[0][idx]
return result | [
"def",
"getTripInfo",
"(",
"triple",
")",
":",
"col_names",
"=",
"[",
"'mjdate'",
",",
"'filter'",
",",
"'elongation'",
",",
"'discovery'",
",",
"'checkup'",
",",
"'recovery'",
",",
"'iq'",
",",
"'block'",
"]",
"sql",
"=",
"\"SELECT mjdate md,\"",
"sql",
"="... | Return a dictionary of information about a particular triple | [
"Return",
"a",
"dictionary",
"of",
"information",
"about",
"a",
"particular",
"triple"
] | 94f91d32ad5ec081d5a1ebd67604a838003465af | https://github.com/OSSOS/MOP/blob/94f91d32ad5ec081d5a1ebd67604a838003465af/src/jjk/preproc/findTriplets.py#L111-L132 | train | 47,958 |
OSSOS/MOP | src/jjk/preproc/findTriplets.py | getExpnums | def getExpnums(pointing,night=None):
"""Get all exposures of specified pointing ID.
Default is to return a list of all exposure numbers"""
if night:
night=" floor(e.mjdate-0.0833)=%d " % ( night )
else:
night=''
sql="SELECT e.expnum "
sql=sql+"FROM bucket.exposure e "
sql=sql+"JOIN bucket.association a on e.expnum=a.expnum "
sql=sql+"WHERE a.pointing="+str(pointing)+" AND "+night
sql=sql+" ORDER BY mjdate, uttime DESC "
cfeps.execute(sql)
return(cfeps.fetchall()) | python | def getExpnums(pointing,night=None):
"""Get all exposures of specified pointing ID.
Default is to return a list of all exposure numbers"""
if night:
night=" floor(e.mjdate-0.0833)=%d " % ( night )
else:
night=''
sql="SELECT e.expnum "
sql=sql+"FROM bucket.exposure e "
sql=sql+"JOIN bucket.association a on e.expnum=a.expnum "
sql=sql+"WHERE a.pointing="+str(pointing)+" AND "+night
sql=sql+" ORDER BY mjdate, uttime DESC "
cfeps.execute(sql)
return(cfeps.fetchall()) | [
"def",
"getExpnums",
"(",
"pointing",
",",
"night",
"=",
"None",
")",
":",
"if",
"night",
":",
"night",
"=",
"\" floor(e.mjdate-0.0833)=%d \"",
"%",
"(",
"night",
")",
"else",
":",
"night",
"=",
"''",
"sql",
"=",
"\"SELECT e.expnum \"",
"sql",
"=",
"sql",
... | Get all exposures of specified pointing ID.
Default is to return a list of all exposure numbers | [
"Get",
"all",
"exposures",
"of",
"specified",
"pointing",
"ID",
"."
] | 94f91d32ad5ec081d5a1ebd67604a838003465af | https://github.com/OSSOS/MOP/blob/94f91d32ad5ec081d5a1ebd67604a838003465af/src/jjk/preproc/findTriplets.py#L134-L151 | train | 47,959 |
OSSOS/MOP | src/jjk/preproc/findTriplets.py | getTriples | def getTriples(pointing):
"""Get all triples of a specified pointing ID.
Defaults is to return a complete list triples."""
sql="SELECT id FROM triples t join triple_members m ON t.id=m.triple"
sql+=" join bucket.exposure e on e.expnum=m.expnum "
sql+=" WHERE pointing=%s group by id order by e.expnum "
cfeps.execute(sql, ( pointing, ) )
return(cfeps.fetchall()) | python | def getTriples(pointing):
"""Get all triples of a specified pointing ID.
Defaults is to return a complete list triples."""
sql="SELECT id FROM triples t join triple_members m ON t.id=m.triple"
sql+=" join bucket.exposure e on e.expnum=m.expnum "
sql+=" WHERE pointing=%s group by id order by e.expnum "
cfeps.execute(sql, ( pointing, ) )
return(cfeps.fetchall()) | [
"def",
"getTriples",
"(",
"pointing",
")",
":",
"sql",
"=",
"\"SELECT id FROM triples t join triple_members m ON t.id=m.triple\"",
"sql",
"+=",
"\" join bucket.exposure e on e.expnum=m.expnum \"",
"sql",
"+=",
"\" WHERE pointing=%s group by id order by e.expnum \"",
"cfeps",
".",
... | Get all triples of a specified pointing ID.
Defaults is to return a complete list triples. | [
"Get",
"all",
"triples",
"of",
"a",
"specified",
"pointing",
"ID",
"."
] | 94f91d32ad5ec081d5a1ebd67604a838003465af | https://github.com/OSSOS/MOP/blob/94f91d32ad5ec081d5a1ebd67604a838003465af/src/jjk/preproc/findTriplets.py#L153-L162 | train | 47,960 |
OSSOS/MOP | src/jjk/preproc/findTriplets.py | createNewTriples | def createNewTriples(Win):
"""Add entries to the triples tables based on new images in the db"""
win.help("Building list of exposures to look for triples")
cols=('e.expnum', 'object',
'mjdate',
'uttime',
'elongation',
'filter',
'obs_iq_refccd','qso_status' )
header='%6s %-10s%-12s%10s%10s%10s%8s%10s' % cols
pointings=getNewTriples()
num_p=len(pointings)
for pointing in pointings:
pid=pointing[0]
mjd=pointing[1]
expnums=getExpnums(pointing=pid,night=mjd)
num_p=num_p-1
while (1):
### Loop over this pointing until keystroke gets us out
win.help("Select (space) members of triplets - %d remaining" % num_p )
## start with an empty list
explist=[]
choices=[]
current_date=''
for expnum in expnums:
info=getExpInfo(expnum[0])
row=()
if not str(info['triple'])=='None' :
continue
if str(info['obs_iq_refccd'])=='None':
info['obs_iq_refccd']=-1.0
choices.append('%6d %10s %15s %10s %8.2f %10s %8.2f %10s' % (
int(info['e.expnum']),
str(info['object']),
str(info['mjdate']),
str(info['uttime']),
float(str(info['elongation'])),
str(info['filter']),
float(str(info['obs_iq_refccd'])),
str(info['qso_status'])
))
explist.append(expnum[0])
if len(choices)<3:
### we need to provide at least 3 choices,
### otherwise this isn't a triple (is it)
break
### win.list returns the user's choices as a list.
choice_list=win.list(header,choices)
### zero length list implies were done.
if choice_list==None:
break
### is this actually a triple?
if len(choice_list)!=3:
win.help("Must have 3 members to make a tripple")
continue
### Create a new line in the triple table
sql = "INSERT INTO triples (id, pointing ) VALUES ( NULL, %s ) "
cfeps.execute(sql, ( pid, ) )
sql = "SELECT id FROM triples WHERE pointing=%s order by id desc"
cfeps.execute(sql, ( pid, ) )
ttt=cfeps.fetchall()
triple= ttt[0][0]
win.help(str(triple))
### record the members of this new triple.
sql = "INSERT INTO triple_members (triple, expnum) VALUES ( %s, %s)";
win.help(sql)
for exp in choice_list:
cfeps.execute(sql,(triple,explist[exp]))
return(0) | python | def createNewTriples(Win):
"""Add entries to the triples tables based on new images in the db"""
win.help("Building list of exposures to look for triples")
cols=('e.expnum', 'object',
'mjdate',
'uttime',
'elongation',
'filter',
'obs_iq_refccd','qso_status' )
header='%6s %-10s%-12s%10s%10s%10s%8s%10s' % cols
pointings=getNewTriples()
num_p=len(pointings)
for pointing in pointings:
pid=pointing[0]
mjd=pointing[1]
expnums=getExpnums(pointing=pid,night=mjd)
num_p=num_p-1
while (1):
### Loop over this pointing until keystroke gets us out
win.help("Select (space) members of triplets - %d remaining" % num_p )
## start with an empty list
explist=[]
choices=[]
current_date=''
for expnum in expnums:
info=getExpInfo(expnum[0])
row=()
if not str(info['triple'])=='None' :
continue
if str(info['obs_iq_refccd'])=='None':
info['obs_iq_refccd']=-1.0
choices.append('%6d %10s %15s %10s %8.2f %10s %8.2f %10s' % (
int(info['e.expnum']),
str(info['object']),
str(info['mjdate']),
str(info['uttime']),
float(str(info['elongation'])),
str(info['filter']),
float(str(info['obs_iq_refccd'])),
str(info['qso_status'])
))
explist.append(expnum[0])
if len(choices)<3:
### we need to provide at least 3 choices,
### otherwise this isn't a triple (is it)
break
### win.list returns the user's choices as a list.
choice_list=win.list(header,choices)
### zero length list implies were done.
if choice_list==None:
break
### is this actually a triple?
if len(choice_list)!=3:
win.help("Must have 3 members to make a tripple")
continue
### Create a new line in the triple table
sql = "INSERT INTO triples (id, pointing ) VALUES ( NULL, %s ) "
cfeps.execute(sql, ( pid, ) )
sql = "SELECT id FROM triples WHERE pointing=%s order by id desc"
cfeps.execute(sql, ( pid, ) )
ttt=cfeps.fetchall()
triple= ttt[0][0]
win.help(str(triple))
### record the members of this new triple.
sql = "INSERT INTO triple_members (triple, expnum) VALUES ( %s, %s)";
win.help(sql)
for exp in choice_list:
cfeps.execute(sql,(triple,explist[exp]))
return(0) | [
"def",
"createNewTriples",
"(",
"Win",
")",
":",
"win",
".",
"help",
"(",
"\"Building list of exposures to look for triples\"",
")",
"cols",
"=",
"(",
"'e.expnum'",
",",
"'object'",
",",
"'mjdate'",
",",
"'uttime'",
",",
"'elongation'",
",",
"'filter'",
",",
"'o... | Add entries to the triples tables based on new images in the db | [
"Add",
"entries",
"to",
"the",
"triples",
"tables",
"based",
"on",
"new",
"images",
"in",
"the",
"db"
] | 94f91d32ad5ec081d5a1ebd67604a838003465af | https://github.com/OSSOS/MOP/blob/94f91d32ad5ec081d5a1ebd67604a838003465af/src/jjk/preproc/findTriplets.py#L170-L255 | train | 47,961 |
OSSOS/MOP | src/jjk/preproc/findTriplets.py | setDiscoveryTriples | def setDiscoveryTriples(win,table="discovery"):
"""Provide user with a list of triples that could be discovery triples"""
win.help("Getting a list of pointings with triples from the CFEPS db")
pointings=getPointingsWithTriples()
win.help("Select the "+table+" triple form the list...")
import time
for pointing in pointings:
header="%10s %10s %8s %10s %8s" % (pointing[1],'mjdate','Elongation','Filter', 'IQ')
triples=getTriples(pointing=pointing[0])
choices=[]
triplist=[]
no_type=0
previous_list=[]
for triple in triples:
#win.help(str(triple))
tripinfo=getTripInfo(triple[0])
if not tripinfo[table]==None:
previous_list.append(triple[0])
#if not abs(180-tripinfo['elongation'])< 20:
# continue
triplist.append(triple)
if str(tripinfo['iq'])=='None':
tripinfo['iq']=-1.0
obs_type=' '
if tripinfo['discovery']:
obs_type='D'
elif tripinfo['checkup']:
obs_type='C'
elif tripinfo['recovery']:
obs_type='R'
if obs_type==' ':
no_type+=1
line=(obs_type,tripinfo['mjdate'], tripinfo['elongation'],
tripinfo['filter'], tripinfo['iq'], tripinfo['block'] )
choices.append('%10s %10s %8.2f %10s %8.2f %8s' % line)
if len(choices)==0 or no_type==0:
continue
#if len(previous_list)==1:
# continue
win.help("Choose a "+table+" triple (space) [no choice means skip] then press enter\n (q) to exit")
choice=win.list(header,choices)
if choice==None:
win.help("Loading next triple")
break
### Record which triplet is a discovery triplet
if len(choice)!=1:
win.help("Loading next triple\n")
continue
discovery_triple=triplist[choice[0]]
for triple in previous_list:
sql="DELETE FROM "+table+" WHERE triple=%s "
cfeps.execute(sql,triple)
sql="INSERT INTO "+table+" ( triple ) VALUES ( %s ) "
cfeps.execute(sql,discovery_triple) | python | def setDiscoveryTriples(win,table="discovery"):
"""Provide user with a list of triples that could be discovery triples"""
win.help("Getting a list of pointings with triples from the CFEPS db")
pointings=getPointingsWithTriples()
win.help("Select the "+table+" triple form the list...")
import time
for pointing in pointings:
header="%10s %10s %8s %10s %8s" % (pointing[1],'mjdate','Elongation','Filter', 'IQ')
triples=getTriples(pointing=pointing[0])
choices=[]
triplist=[]
no_type=0
previous_list=[]
for triple in triples:
#win.help(str(triple))
tripinfo=getTripInfo(triple[0])
if not tripinfo[table]==None:
previous_list.append(triple[0])
#if not abs(180-tripinfo['elongation'])< 20:
# continue
triplist.append(triple)
if str(tripinfo['iq'])=='None':
tripinfo['iq']=-1.0
obs_type=' '
if tripinfo['discovery']:
obs_type='D'
elif tripinfo['checkup']:
obs_type='C'
elif tripinfo['recovery']:
obs_type='R'
if obs_type==' ':
no_type+=1
line=(obs_type,tripinfo['mjdate'], tripinfo['elongation'],
tripinfo['filter'], tripinfo['iq'], tripinfo['block'] )
choices.append('%10s %10s %8.2f %10s %8.2f %8s' % line)
if len(choices)==0 or no_type==0:
continue
#if len(previous_list)==1:
# continue
win.help("Choose a "+table+" triple (space) [no choice means skip] then press enter\n (q) to exit")
choice=win.list(header,choices)
if choice==None:
win.help("Loading next triple")
break
### Record which triplet is a discovery triplet
if len(choice)!=1:
win.help("Loading next triple\n")
continue
discovery_triple=triplist[choice[0]]
for triple in previous_list:
sql="DELETE FROM "+table+" WHERE triple=%s "
cfeps.execute(sql,triple)
sql="INSERT INTO "+table+" ( triple ) VALUES ( %s ) "
cfeps.execute(sql,discovery_triple) | [
"def",
"setDiscoveryTriples",
"(",
"win",
",",
"table",
"=",
"\"discovery\"",
")",
":",
"win",
".",
"help",
"(",
"\"Getting a list of pointings with triples from the CFEPS db\"",
")",
"pointings",
"=",
"getPointingsWithTriples",
"(",
")",
"win",
".",
"help",
"(",
"\... | Provide user with a list of triples that could be discovery triples | [
"Provide",
"user",
"with",
"a",
"list",
"of",
"triples",
"that",
"could",
"be",
"discovery",
"triples"
] | 94f91d32ad5ec081d5a1ebd67604a838003465af | https://github.com/OSSOS/MOP/blob/94f91d32ad5ec081d5a1ebd67604a838003465af/src/jjk/preproc/findTriplets.py#L257-L312 | train | 47,962 |
OSSOS/MOP | src/jjk/preproc/MOPplot.py | fits_list | def fits_list(filter,root,fnames):
"""Get a list of files matching filter in directory root"""
import re, pyfits, wcsutil
for file in fnames:
if re.match(filter,file):
fh=pyfits.open(file)
for ext in fh:
obj=ext.header.get('OBJECT',file)
dx=ext.header.get('NAXIS1',None)
dy=ext.header.get('NAXIS2',None)
wcs=wcsutil.WCSObject(ext)
(x1,y1)=wcs.xy2rd((1,1,))
(x2,y2)=wcs.xy2rd((dx,dy))
ccds=[x1,y1,x2,y2]
pointing={'label': obj, 'camera': ccds}
return files | python | def fits_list(filter,root,fnames):
"""Get a list of files matching filter in directory root"""
import re, pyfits, wcsutil
for file in fnames:
if re.match(filter,file):
fh=pyfits.open(file)
for ext in fh:
obj=ext.header.get('OBJECT',file)
dx=ext.header.get('NAXIS1',None)
dy=ext.header.get('NAXIS2',None)
wcs=wcsutil.WCSObject(ext)
(x1,y1)=wcs.xy2rd((1,1,))
(x2,y2)=wcs.xy2rd((dx,dy))
ccds=[x1,y1,x2,y2]
pointing={'label': obj, 'camera': ccds}
return files | [
"def",
"fits_list",
"(",
"filter",
",",
"root",
",",
"fnames",
")",
":",
"import",
"re",
",",
"pyfits",
",",
"wcsutil",
"for",
"file",
"in",
"fnames",
":",
"if",
"re",
".",
"match",
"(",
"filter",
",",
"file",
")",
":",
"fh",
"=",
"pyfits",
".",
... | Get a list of files matching filter in directory root | [
"Get",
"a",
"list",
"of",
"files",
"matching",
"filter",
"in",
"directory",
"root"
] | 94f91d32ad5ec081d5a1ebd67604a838003465af | https://github.com/OSSOS/MOP/blob/94f91d32ad5ec081d5a1ebd67604a838003465af/src/jjk/preproc/MOPplot.py#L137-L152 | train | 47,963 |
OSSOS/MOP | src/jjk/preproc/MOPplot.py | load_fis | def load_fis(dir=None):
"""Load fits images in a directory"""
if dir is None:
import tkFileDialog
try:
dir=tkFileDialog.askdirectory()
except:
return
if dir is None:
return None
from os.path import walk
walk(dir,fits_list,"*.fits") | python | def load_fis(dir=None):
"""Load fits images in a directory"""
if dir is None:
import tkFileDialog
try:
dir=tkFileDialog.askdirectory()
except:
return
if dir is None:
return None
from os.path import walk
walk(dir,fits_list,"*.fits") | [
"def",
"load_fis",
"(",
"dir",
"=",
"None",
")",
":",
"if",
"dir",
"is",
"None",
":",
"import",
"tkFileDialog",
"try",
":",
"dir",
"=",
"tkFileDialog",
".",
"askdirectory",
"(",
")",
"except",
":",
"return",
"if",
"dir",
"is",
"None",
":",
"return",
... | Load fits images in a directory | [
"Load",
"fits",
"images",
"in",
"a",
"directory"
] | 94f91d32ad5ec081d5a1ebd67604a838003465af | https://github.com/OSSOS/MOP/blob/94f91d32ad5ec081d5a1ebd67604a838003465af/src/jjk/preproc/MOPplot.py#L155-L166 | train | 47,964 |
OSSOS/MOP | src/jjk/preproc/MOPplot.py | do_objs | def do_objs(kbos):
"""Draw the actual plot"""
import orbfit, ephem, math
import re
re_string=w.FilterVar.get()
vlist=[]
for name in kbos:
if not re.search(re_string,name):
continue
vlist.append(name)
if type(kbos[name])==type(ephem.EllipticalBody()):
kbos[name].compute(w.date.get())
ra=kbos[name].ra
dec=kbos[name].dec
a=math.radians(10.0/3600.0)
b=a
ang=0.0
color='blue'
yoffset=+10
xoffset=+10
else:
yoffset=-10
xoffset=-10
file=kbos[name]
jdate=ephem.julian_date(w.date.get())
obs=568
try:
position=orbfit.predict(file,jdate,obs)
except:
continue
ra=math.radians(position[0])
dec=math.radians(position[1])
a=math.radians(position[2]/3600.0)
b=math.radians(position[3]/3600.0)
ang=math.radians(position[4])
if ( a> math.radians(1.0) ):
color='green'
else:
color='black'
if w.show_ellipse.get()==1 :
if ( a < math.radians(5.0) ):
w.create_ellipse(ra,dec,a,b,ang)
if ( a < math.radians(1.0) ):
w.create_point(ra,dec,size=2,color=color)
if w.show_labels.get()==1:
w.label(ra,dec,name,offset=[xoffset,yoffset])
vlist.sort()
for v in vlist:
w.objList.insert(END,v)
w.plot_pointings() | python | def do_objs(kbos):
"""Draw the actual plot"""
import orbfit, ephem, math
import re
re_string=w.FilterVar.get()
vlist=[]
for name in kbos:
if not re.search(re_string,name):
continue
vlist.append(name)
if type(kbos[name])==type(ephem.EllipticalBody()):
kbos[name].compute(w.date.get())
ra=kbos[name].ra
dec=kbos[name].dec
a=math.radians(10.0/3600.0)
b=a
ang=0.0
color='blue'
yoffset=+10
xoffset=+10
else:
yoffset=-10
xoffset=-10
file=kbos[name]
jdate=ephem.julian_date(w.date.get())
obs=568
try:
position=orbfit.predict(file,jdate,obs)
except:
continue
ra=math.radians(position[0])
dec=math.radians(position[1])
a=math.radians(position[2]/3600.0)
b=math.radians(position[3]/3600.0)
ang=math.radians(position[4])
if ( a> math.radians(1.0) ):
color='green'
else:
color='black'
if w.show_ellipse.get()==1 :
if ( a < math.radians(5.0) ):
w.create_ellipse(ra,dec,a,b,ang)
if ( a < math.radians(1.0) ):
w.create_point(ra,dec,size=2,color=color)
if w.show_labels.get()==1:
w.label(ra,dec,name,offset=[xoffset,yoffset])
vlist.sort()
for v in vlist:
w.objList.insert(END,v)
w.plot_pointings() | [
"def",
"do_objs",
"(",
"kbos",
")",
":",
"import",
"orbfit",
",",
"ephem",
",",
"math",
"import",
"re",
"re_string",
"=",
"w",
".",
"FilterVar",
".",
"get",
"(",
")",
"vlist",
"=",
"[",
"]",
"for",
"name",
"in",
"kbos",
":",
"if",
"not",
"re",
".... | Draw the actual plot | [
"Draw",
"the",
"actual",
"plot"
] | 94f91d32ad5ec081d5a1ebd67604a838003465af | https://github.com/OSSOS/MOP/blob/94f91d32ad5ec081d5a1ebd67604a838003465af/src/jjk/preproc/MOPplot.py#L1201-L1251 | train | 47,965 |
OSSOS/MOP | src/jjk/preproc/MOPplot.py | plot.eps | def eps(self):
"""Print the canvas to a postscript file"""
import tkFileDialog,tkMessageBox
filename=tkFileDialog.asksaveasfilename(message="save postscript to file",filetypes=['eps','ps'])
if filename is None:
return
self.postscript(file=filename) | python | def eps(self):
"""Print the canvas to a postscript file"""
import tkFileDialog,tkMessageBox
filename=tkFileDialog.asksaveasfilename(message="save postscript to file",filetypes=['eps','ps'])
if filename is None:
return
self.postscript(file=filename) | [
"def",
"eps",
"(",
"self",
")",
":",
"import",
"tkFileDialog",
",",
"tkMessageBox",
"filename",
"=",
"tkFileDialog",
".",
"asksaveasfilename",
"(",
"message",
"=",
"\"save postscript to file\"",
",",
"filetypes",
"=",
"[",
"'eps'",
",",
"'ps'",
"]",
")",
"if",... | Print the canvas to a postscript file | [
"Print",
"the",
"canvas",
"to",
"a",
"postscript",
"file"
] | 94f91d32ad5ec081d5a1ebd67604a838003465af | https://github.com/OSSOS/MOP/blob/94f91d32ad5ec081d5a1ebd67604a838003465af/src/jjk/preproc/MOPplot.py#L208-L216 | train | 47,966 |
OSSOS/MOP | src/jjk/preproc/MOPplot.py | plot.relocate | def relocate(self):
"""Move to the postion of self.SearchVar"""
name=self.SearchVar.get()
if kbos.has_key(name):
import orbfit,ephem,math
jdate=ephem.julian_date(w.date.get())
try:
(ra,dec,a,b,ang)=orbfit.predict(kbos[name],jdate,568)
except:
return
ra=math.radians(ra)
dec=math.radians(dec)
elif mpc_objs.has_key(name):
ra=mpc_objs[name].ra
dec=mpc_objs[name].dec
self.recenter(ra,dec)
self.create_point(ra,dec,color='blue',size=4) | python | def relocate(self):
"""Move to the postion of self.SearchVar"""
name=self.SearchVar.get()
if kbos.has_key(name):
import orbfit,ephem,math
jdate=ephem.julian_date(w.date.get())
try:
(ra,dec,a,b,ang)=orbfit.predict(kbos[name],jdate,568)
except:
return
ra=math.radians(ra)
dec=math.radians(dec)
elif mpc_objs.has_key(name):
ra=mpc_objs[name].ra
dec=mpc_objs[name].dec
self.recenter(ra,dec)
self.create_point(ra,dec,color='blue',size=4) | [
"def",
"relocate",
"(",
"self",
")",
":",
"name",
"=",
"self",
".",
"SearchVar",
".",
"get",
"(",
")",
"if",
"kbos",
".",
"has_key",
"(",
"name",
")",
":",
"import",
"orbfit",
",",
"ephem",
",",
"math",
"jdate",
"=",
"ephem",
".",
"julian_date",
"(... | Move to the postion of self.SearchVar | [
"Move",
"to",
"the",
"postion",
"of",
"self",
".",
"SearchVar"
] | 94f91d32ad5ec081d5a1ebd67604a838003465af | https://github.com/OSSOS/MOP/blob/94f91d32ad5ec081d5a1ebd67604a838003465af/src/jjk/preproc/MOPplot.py#L462-L480 | train | 47,967 |
OSSOS/MOP | src/jjk/preproc/MOPplot.py | plot.create_ellipse | def create_ellipse(self,xcen,ycen,a,b,ang,resolution=40.0):
"""Plot ellipse at x,y with size a,b and orientation ang"""
import math
e1=[]
e2=[]
ang=ang-math.radians(90)
for i in range(0,int(resolution)+1):
x=(-1*a+2*a*float(i)/resolution)
y=1-(x/a)**2
if y < 1E-6:
y=1E-6
y=math.sqrt(y)*b
ptv=self.p2c((x*math.cos(ang)+y*math.sin(ang)+xcen,y*math.cos(ang)-x*math.sin(ang)+ycen))
y=-1*y
ntv=self.p2c((x*math.cos(ang)+y*math.sin(ang)+xcen,y*math.cos(ang)-x*math.sin(ang)+ycen))
e1.append(ptv)
e2.append(ntv)
e2.reverse()
e1.extend(e2)
self.create_line(e1,fill='red',width=1) | python | def create_ellipse(self,xcen,ycen,a,b,ang,resolution=40.0):
"""Plot ellipse at x,y with size a,b and orientation ang"""
import math
e1=[]
e2=[]
ang=ang-math.radians(90)
for i in range(0,int(resolution)+1):
x=(-1*a+2*a*float(i)/resolution)
y=1-(x/a)**2
if y < 1E-6:
y=1E-6
y=math.sqrt(y)*b
ptv=self.p2c((x*math.cos(ang)+y*math.sin(ang)+xcen,y*math.cos(ang)-x*math.sin(ang)+ycen))
y=-1*y
ntv=self.p2c((x*math.cos(ang)+y*math.sin(ang)+xcen,y*math.cos(ang)-x*math.sin(ang)+ycen))
e1.append(ptv)
e2.append(ntv)
e2.reverse()
e1.extend(e2)
self.create_line(e1,fill='red',width=1) | [
"def",
"create_ellipse",
"(",
"self",
",",
"xcen",
",",
"ycen",
",",
"a",
",",
"b",
",",
"ang",
",",
"resolution",
"=",
"40.0",
")",
":",
"import",
"math",
"e1",
"=",
"[",
"]",
"e2",
"=",
"[",
"]",
"ang",
"=",
"ang",
"-",
"math",
".",
"radians"... | Plot ellipse at x,y with size a,b and orientation ang | [
"Plot",
"ellipse",
"at",
"x",
"y",
"with",
"size",
"a",
"b",
"and",
"orientation",
"ang"
] | 94f91d32ad5ec081d5a1ebd67604a838003465af | https://github.com/OSSOS/MOP/blob/94f91d32ad5ec081d5a1ebd67604a838003465af/src/jjk/preproc/MOPplot.py#L532-L552 | train | 47,968 |
OSSOS/MOP | src/jjk/preproc/MOPplot.py | plot.create_pointing | def create_pointing(self,event):
"""Plot the sky coverage of pointing at event.x,event.y on the canavas"""
import math
(ra,dec)=self.c2p((self.canvasx(event.x),
self.canvasy(event.y)))
this_camera=camera(camera=self.camera.get())
ccds=this_camera.getGeometry(ra,dec)
items=[]
for ccd in ccds:
(x1,y1)=self.p2c((ccd[0],ccd[1]))
(x2,y2)=self.p2c((ccd[2],ccd[3]))
item=self.create_rectangle(x1,y1,x2,y2)
items.append(item)
label={}
label['text']=w.plabel.get()
label['id']=self.label(this_camera.ra,this_camera.dec,label['text'])
self.pointings.append({
"label": label,
"items": items,
"camera": this_camera} )
self.current_pointing(len(self.pointings)-1) | python | def create_pointing(self,event):
"""Plot the sky coverage of pointing at event.x,event.y on the canavas"""
import math
(ra,dec)=self.c2p((self.canvasx(event.x),
self.canvasy(event.y)))
this_camera=camera(camera=self.camera.get())
ccds=this_camera.getGeometry(ra,dec)
items=[]
for ccd in ccds:
(x1,y1)=self.p2c((ccd[0],ccd[1]))
(x2,y2)=self.p2c((ccd[2],ccd[3]))
item=self.create_rectangle(x1,y1,x2,y2)
items.append(item)
label={}
label['text']=w.plabel.get()
label['id']=self.label(this_camera.ra,this_camera.dec,label['text'])
self.pointings.append({
"label": label,
"items": items,
"camera": this_camera} )
self.current_pointing(len(self.pointings)-1) | [
"def",
"create_pointing",
"(",
"self",
",",
"event",
")",
":",
"import",
"math",
"(",
"ra",
",",
"dec",
")",
"=",
"self",
".",
"c2p",
"(",
"(",
"self",
".",
"canvasx",
"(",
"event",
".",
"x",
")",
",",
"self",
".",
"canvasy",
"(",
"event",
".",
... | Plot the sky coverage of pointing at event.x,event.y on the canavas | [
"Plot",
"the",
"sky",
"coverage",
"of",
"pointing",
"at",
"event",
".",
"x",
"event",
".",
"y",
"on",
"the",
"canavas"
] | 94f91d32ad5ec081d5a1ebd67604a838003465af | https://github.com/OSSOS/MOP/blob/94f91d32ad5ec081d5a1ebd67604a838003465af/src/jjk/preproc/MOPplot.py#L712-L733 | train | 47,969 |
OSSOS/MOP | src/jjk/preproc/MOPplot.py | camera.getGeometry | def getGeometry(self,ra=None,dec=None):
"""Return an array of rectangles that represent the 'ra,dec' corners of the FOV"""
import math,ephem
ccds=[]
if ra is None:
ra=self.ra
if dec is None:
dec=self.dec
self.ra=ephem.hours(ra)
self.dec=ephem.degrees(dec)
for geo in self.geometry[self.camera]:
ycen=math.radians(geo["dec"])+dec
xcen=math.radians(geo["ra"])/math.cos(ycen)+ra
dy=math.radians(geo["ddec"])
dx=math.radians(geo["dra"]/math.cos(ycen))
ccds.append([xcen-dx/2.0,ycen-dy/2.0,xcen+dx/2.0,ycen+dy/2.0])
return ccds | python | def getGeometry(self,ra=None,dec=None):
"""Return an array of rectangles that represent the 'ra,dec' corners of the FOV"""
import math,ephem
ccds=[]
if ra is None:
ra=self.ra
if dec is None:
dec=self.dec
self.ra=ephem.hours(ra)
self.dec=ephem.degrees(dec)
for geo in self.geometry[self.camera]:
ycen=math.radians(geo["dec"])+dec
xcen=math.radians(geo["ra"])/math.cos(ycen)+ra
dy=math.radians(geo["ddec"])
dx=math.radians(geo["dra"]/math.cos(ycen))
ccds.append([xcen-dx/2.0,ycen-dy/2.0,xcen+dx/2.0,ycen+dy/2.0])
return ccds | [
"def",
"getGeometry",
"(",
"self",
",",
"ra",
"=",
"None",
",",
"dec",
"=",
"None",
")",
":",
"import",
"math",
",",
"ephem",
"ccds",
"=",
"[",
"]",
"if",
"ra",
"is",
"None",
":",
"ra",
"=",
"self",
".",
"ra",
"if",
"dec",
"is",
"None",
":",
... | Return an array of rectangles that represent the 'ra,dec' corners of the FOV | [
"Return",
"an",
"array",
"of",
"rectangles",
"that",
"represent",
"the",
"ra",
"dec",
"corners",
"of",
"the",
"FOV"
] | 94f91d32ad5ec081d5a1ebd67604a838003465af | https://github.com/OSSOS/MOP/blob/94f91d32ad5ec081d5a1ebd67604a838003465af/src/jjk/preproc/MOPplot.py#L1017-L1036 | train | 47,970 |
JohnVinyard/zounds | examples/hamming_index.py | produce_fake_hash | def produce_fake_hash(x):
"""
Produce random, binary features, totally irrespective of the content of
x, but in the same shape as x.
"""
h = np.random.binomial(1, 0.5, (x.shape[0], 1024))
packed = np.packbits(h, axis=-1).view(np.uint64)
return zounds.ArrayWithUnits(
packed, [x.dimensions[0], zounds.IdentityDimension()]) | python | def produce_fake_hash(x):
"""
Produce random, binary features, totally irrespective of the content of
x, but in the same shape as x.
"""
h = np.random.binomial(1, 0.5, (x.shape[0], 1024))
packed = np.packbits(h, axis=-1).view(np.uint64)
return zounds.ArrayWithUnits(
packed, [x.dimensions[0], zounds.IdentityDimension()]) | [
"def",
"produce_fake_hash",
"(",
"x",
")",
":",
"h",
"=",
"np",
".",
"random",
".",
"binomial",
"(",
"1",
",",
"0.5",
",",
"(",
"x",
".",
"shape",
"[",
"0",
"]",
",",
"1024",
")",
")",
"packed",
"=",
"np",
".",
"packbits",
"(",
"h",
",",
"axi... | Produce random, binary features, totally irrespective of the content of
x, but in the same shape as x. | [
"Produce",
"random",
"binary",
"features",
"totally",
"irrespective",
"of",
"the",
"content",
"of",
"x",
"but",
"in",
"the",
"same",
"shape",
"as",
"x",
"."
] | 337b3f98753d09eaab1c72dcd37bb852a3fa5ac6 | https://github.com/JohnVinyard/zounds/blob/337b3f98753d09eaab1c72dcd37bb852a3fa5ac6/examples/hamming_index.py#L16-L24 | train | 47,971 |
openstack/python-scciclient | scciclient/irmc/ipmi.py | _parse_raw_bytes | def _parse_raw_bytes(raw_bytes):
"""Convert a string of hexadecimal values to decimal values parameters
Example: '0x2E 0xF1 0x80 0x28 0x00 0x1A 0x01 0x00' is converted to:
46, 241, [128, 40, 0, 26, 1, 0]
:param raw_bytes: string of hexadecimal values
:returns: 3 decimal values
"""
bytes_list = [int(x, base=16) for x in raw_bytes.split()]
return bytes_list[0], bytes_list[1], bytes_list[2:] | python | def _parse_raw_bytes(raw_bytes):
"""Convert a string of hexadecimal values to decimal values parameters
Example: '0x2E 0xF1 0x80 0x28 0x00 0x1A 0x01 0x00' is converted to:
46, 241, [128, 40, 0, 26, 1, 0]
:param raw_bytes: string of hexadecimal values
:returns: 3 decimal values
"""
bytes_list = [int(x, base=16) for x in raw_bytes.split()]
return bytes_list[0], bytes_list[1], bytes_list[2:] | [
"def",
"_parse_raw_bytes",
"(",
"raw_bytes",
")",
":",
"bytes_list",
"=",
"[",
"int",
"(",
"x",
",",
"base",
"=",
"16",
")",
"for",
"x",
"in",
"raw_bytes",
".",
"split",
"(",
")",
"]",
"return",
"bytes_list",
"[",
"0",
"]",
",",
"bytes_list",
"[",
... | Convert a string of hexadecimal values to decimal values parameters
Example: '0x2E 0xF1 0x80 0x28 0x00 0x1A 0x01 0x00' is converted to:
46, 241, [128, 40, 0, 26, 1, 0]
:param raw_bytes: string of hexadecimal values
:returns: 3 decimal values | [
"Convert",
"a",
"string",
"of",
"hexadecimal",
"values",
"to",
"decimal",
"values",
"parameters"
] | 4585ce2f76853b9773fb190ca0cfff0aa04a7cf8 | https://github.com/openstack/python-scciclient/blob/4585ce2f76853b9773fb190ca0cfff0aa04a7cf8/scciclient/irmc/ipmi.py#L47-L57 | train | 47,972 |
openstack/python-scciclient | scciclient/irmc/ipmi.py | _send_raw_command | def _send_raw_command(ipmicmd, raw_bytes):
"""Use IPMI command object to send raw ipmi command to BMC
:param ipmicmd: IPMI command object
:param raw_bytes: string of hexadecimal values. This is commonly used
for certain vendor specific commands.
:returns: dict -- The response from IPMI device
"""
netfn, command, data = _parse_raw_bytes(raw_bytes)
response = ipmicmd.raw_command(netfn, command, data=data)
return response | python | def _send_raw_command(ipmicmd, raw_bytes):
"""Use IPMI command object to send raw ipmi command to BMC
:param ipmicmd: IPMI command object
:param raw_bytes: string of hexadecimal values. This is commonly used
for certain vendor specific commands.
:returns: dict -- The response from IPMI device
"""
netfn, command, data = _parse_raw_bytes(raw_bytes)
response = ipmicmd.raw_command(netfn, command, data=data)
return response | [
"def",
"_send_raw_command",
"(",
"ipmicmd",
",",
"raw_bytes",
")",
":",
"netfn",
",",
"command",
",",
"data",
"=",
"_parse_raw_bytes",
"(",
"raw_bytes",
")",
"response",
"=",
"ipmicmd",
".",
"raw_command",
"(",
"netfn",
",",
"command",
",",
"data",
"=",
"d... | Use IPMI command object to send raw ipmi command to BMC
:param ipmicmd: IPMI command object
:param raw_bytes: string of hexadecimal values. This is commonly used
for certain vendor specific commands.
:returns: dict -- The response from IPMI device | [
"Use",
"IPMI",
"command",
"object",
"to",
"send",
"raw",
"ipmi",
"command",
"to",
"BMC"
] | 4585ce2f76853b9773fb190ca0cfff0aa04a7cf8 | https://github.com/openstack/python-scciclient/blob/4585ce2f76853b9773fb190ca0cfff0aa04a7cf8/scciclient/irmc/ipmi.py#L60-L72 | train | 47,973 |
openstack/python-scciclient | scciclient/irmc/ipmi.py | get_tpm_status | def get_tpm_status(d_info):
"""Get the TPM support status.
Get the TPM support status of the node.
:param d_info: the list of ipmitool parameters for accessing a node.
:returns: TPM support status
"""
# note:
# Get TPM support status : ipmi cmd '0xF5', valid flags '0xC0'
#
# $ ipmitool raw 0x2E 0xF5 0x80 0x28 0x00 0x81 0xC0
#
# Raw response:
# 80 28 00 C0 C0: True
# 80 28 00 -- --: False (other values than 'C0 C0')
ipmicmd = ipmi_command.Command(bmc=d_info['irmc_address'],
userid=d_info['irmc_username'],
password=d_info['irmc_password'])
try:
response = _send_raw_command(ipmicmd, GET_TPM_STATUS)
if response['code'] != 0:
raise IPMIFailure(
"IPMI operation '%(operation)s' failed: %(error)s" %
{'operation': "GET TMP status",
'error': response.get('error')})
out = ' '.join('{:02X}'.format(x) for x in response['data'])
return out is not None and out[-5:] == 'C0 C0'
except ipmi_exception.IpmiException as e:
raise IPMIFailure(
"IPMI operation '%(operation)s' failed: %(error)s" %
{'operation': "GET TMP status", 'error': e}) | python | def get_tpm_status(d_info):
"""Get the TPM support status.
Get the TPM support status of the node.
:param d_info: the list of ipmitool parameters for accessing a node.
:returns: TPM support status
"""
# note:
# Get TPM support status : ipmi cmd '0xF5', valid flags '0xC0'
#
# $ ipmitool raw 0x2E 0xF5 0x80 0x28 0x00 0x81 0xC0
#
# Raw response:
# 80 28 00 C0 C0: True
# 80 28 00 -- --: False (other values than 'C0 C0')
ipmicmd = ipmi_command.Command(bmc=d_info['irmc_address'],
userid=d_info['irmc_username'],
password=d_info['irmc_password'])
try:
response = _send_raw_command(ipmicmd, GET_TPM_STATUS)
if response['code'] != 0:
raise IPMIFailure(
"IPMI operation '%(operation)s' failed: %(error)s" %
{'operation': "GET TMP status",
'error': response.get('error')})
out = ' '.join('{:02X}'.format(x) for x in response['data'])
return out is not None and out[-5:] == 'C0 C0'
except ipmi_exception.IpmiException as e:
raise IPMIFailure(
"IPMI operation '%(operation)s' failed: %(error)s" %
{'operation': "GET TMP status", 'error': e}) | [
"def",
"get_tpm_status",
"(",
"d_info",
")",
":",
"# note:",
"# Get TPM support status : ipmi cmd '0xF5', valid flags '0xC0'",
"#",
"# $ ipmitool raw 0x2E 0xF5 0x80 0x28 0x00 0x81 0xC0",
"#",
"# Raw response:",
"# 80 28 00 C0 C0: True",
"# 80 28 00 -- --: False (other values than 'C0 C0')"... | Get the TPM support status.
Get the TPM support status of the node.
:param d_info: the list of ipmitool parameters for accessing a node.
:returns: TPM support status | [
"Get",
"the",
"TPM",
"support",
"status",
"."
] | 4585ce2f76853b9773fb190ca0cfff0aa04a7cf8 | https://github.com/openstack/python-scciclient/blob/4585ce2f76853b9773fb190ca0cfff0aa04a7cf8/scciclient/irmc/ipmi.py#L75-L109 | train | 47,974 |
openstack/python-scciclient | scciclient/irmc/ipmi.py | _pci_seq | def _pci_seq(ipmicmd):
"""Get output of ipmiraw command and the ordinal numbers.
:param ipmicmd: IPMI command object.
:returns: List of tuple contain ordinal number and output of ipmiraw
command.
"""
for i in range(1, 0xff + 1):
try:
res = _send_raw_command(ipmicmd, GET_PCI % hex(i))
yield i, res
except ipmi_exception.IpmiException as e:
raise IPMIFailure(
"IPMI operation '%(operation)s' failed: %(error)s" %
{'operation': "GET PCI device quantity", 'error': e}) | python | def _pci_seq(ipmicmd):
"""Get output of ipmiraw command and the ordinal numbers.
:param ipmicmd: IPMI command object.
:returns: List of tuple contain ordinal number and output of ipmiraw
command.
"""
for i in range(1, 0xff + 1):
try:
res = _send_raw_command(ipmicmd, GET_PCI % hex(i))
yield i, res
except ipmi_exception.IpmiException as e:
raise IPMIFailure(
"IPMI operation '%(operation)s' failed: %(error)s" %
{'operation': "GET PCI device quantity", 'error': e}) | [
"def",
"_pci_seq",
"(",
"ipmicmd",
")",
":",
"for",
"i",
"in",
"range",
"(",
"1",
",",
"0xff",
"+",
"1",
")",
":",
"try",
":",
"res",
"=",
"_send_raw_command",
"(",
"ipmicmd",
",",
"GET_PCI",
"%",
"hex",
"(",
"i",
")",
")",
"yield",
"i",
",",
"... | Get output of ipmiraw command and the ordinal numbers.
:param ipmicmd: IPMI command object.
:returns: List of tuple contain ordinal number and output of ipmiraw
command. | [
"Get",
"output",
"of",
"ipmiraw",
"command",
"and",
"the",
"ordinal",
"numbers",
"."
] | 4585ce2f76853b9773fb190ca0cfff0aa04a7cf8 | https://github.com/openstack/python-scciclient/blob/4585ce2f76853b9773fb190ca0cfff0aa04a7cf8/scciclient/irmc/ipmi.py#L112-L126 | train | 47,975 |
openstack/python-scciclient | scciclient/irmc/ipmi.py | get_pci_device | def get_pci_device(d_info, pci_device_ids):
"""Get quantity of PCI devices.
Get quantity of PCI devices of the node.
:param d_info: the list of ipmitool parameters for accessing a node.
:param pci_device_ids: the list contains pairs of <vendorID>/<deviceID> for
PCI devices.
:returns: the number of PCI devices.
"""
# note:
# Get quantity of PCI devices:
# ipmi cmd '0xF1'
#
# $ ipmitool raw 0x2E 0xF1 0x80 0x28 0x00 0x1A 0x01 0x00
#
# Raw response:
# 80 28 00 00 00 05 data1 data2 34 17 76 11 00 04
# 01
# data1: 2 octet of VendorID
# data2: 2 octet of DeviceID
ipmicmd = ipmi_command.Command(bmc=d_info['irmc_address'],
userid=d_info['irmc_username'],
password=d_info['irmc_password'])
response = itertools.takewhile(
lambda y: (y[1]['code'] != 0xC9 and y[1].get('error') is None),
_pci_seq(ipmicmd))
def _pci_count(accm, v):
out = v[1]['data']
# if system returns value, record id will be increased.
pci_id = "0x{:02x}{:02x}/0x{:02x}{:02x}".format(
out[7], out[6], out[9], out[8])
return accm + 1 if pci_id in pci_device_ids else accm
device_count = functools.reduce(_pci_count, response, 0)
return device_count | python | def get_pci_device(d_info, pci_device_ids):
"""Get quantity of PCI devices.
Get quantity of PCI devices of the node.
:param d_info: the list of ipmitool parameters for accessing a node.
:param pci_device_ids: the list contains pairs of <vendorID>/<deviceID> for
PCI devices.
:returns: the number of PCI devices.
"""
# note:
# Get quantity of PCI devices:
# ipmi cmd '0xF1'
#
# $ ipmitool raw 0x2E 0xF1 0x80 0x28 0x00 0x1A 0x01 0x00
#
# Raw response:
# 80 28 00 00 00 05 data1 data2 34 17 76 11 00 04
# 01
# data1: 2 octet of VendorID
# data2: 2 octet of DeviceID
ipmicmd = ipmi_command.Command(bmc=d_info['irmc_address'],
userid=d_info['irmc_username'],
password=d_info['irmc_password'])
response = itertools.takewhile(
lambda y: (y[1]['code'] != 0xC9 and y[1].get('error') is None),
_pci_seq(ipmicmd))
def _pci_count(accm, v):
out = v[1]['data']
# if system returns value, record id will be increased.
pci_id = "0x{:02x}{:02x}/0x{:02x}{:02x}".format(
out[7], out[6], out[9], out[8])
return accm + 1 if pci_id in pci_device_ids else accm
device_count = functools.reduce(_pci_count, response, 0)
return device_count | [
"def",
"get_pci_device",
"(",
"d_info",
",",
"pci_device_ids",
")",
":",
"# note:",
"# Get quantity of PCI devices:",
"# ipmi cmd '0xF1'",
"#",
"# $ ipmitool raw 0x2E 0xF1 0x80 0x28 0x00 0x1A 0x01 0x00",
"#",
"# Raw response:",
"# 80 28 00 00 00 05 data1 data2 34 17 76 11 00 04",
"# ... | Get quantity of PCI devices.
Get quantity of PCI devices of the node.
:param d_info: the list of ipmitool parameters for accessing a node.
:param pci_device_ids: the list contains pairs of <vendorID>/<deviceID> for
PCI devices.
:returns: the number of PCI devices. | [
"Get",
"quantity",
"of",
"PCI",
"devices",
"."
] | 4585ce2f76853b9773fb190ca0cfff0aa04a7cf8 | https://github.com/openstack/python-scciclient/blob/4585ce2f76853b9773fb190ca0cfff0aa04a7cf8/scciclient/irmc/ipmi.py#L129-L170 | train | 47,976 |
playpauseandstop/rororo | rororo/schemas/utils.py | defaults | def defaults(current: dict, *args: AnyMapping) -> dict:
r"""Override current dict with defaults values.
:param current: Current dict.
:param \*args: Sequence with default data dicts.
"""
for data in args:
for key, value in data.items():
current.setdefault(key, value)
return current | python | def defaults(current: dict, *args: AnyMapping) -> dict:
r"""Override current dict with defaults values.
:param current: Current dict.
:param \*args: Sequence with default data dicts.
"""
for data in args:
for key, value in data.items():
current.setdefault(key, value)
return current | [
"def",
"defaults",
"(",
"current",
":",
"dict",
",",
"*",
"args",
":",
"AnyMapping",
")",
"->",
"dict",
":",
"for",
"data",
"in",
"args",
":",
"for",
"key",
",",
"value",
"in",
"data",
".",
"items",
"(",
")",
":",
"current",
".",
"setdefault",
"(",... | r"""Override current dict with defaults values.
:param current: Current dict.
:param \*args: Sequence with default data dicts. | [
"r",
"Override",
"current",
"dict",
"with",
"defaults",
"values",
"."
] | 28a04e8028c29647941e727116335e9d6fd64c27 | https://github.com/playpauseandstop/rororo/blob/28a04e8028c29647941e727116335e9d6fd64c27/rororo/schemas/utils.py#L17-L26 | train | 47,977 |
playpauseandstop/rororo | rororo/schemas/utils.py | validate_func_factory | def validate_func_factory(validator_class: Any) -> ValidateFunc:
"""Provide default function for Schema validation.
:param validator_class: JSONSchema suitable validator class.
"""
def validate_func(schema: AnyMapping, pure_data: AnyMapping) -> AnyMapping:
"""Validate schema with given data.
:param schema: Schema representation to use.
:param pure_data: Pure data to validate.
"""
return validator_class(schema).validate(pure_data)
return validate_func | python | def validate_func_factory(validator_class: Any) -> ValidateFunc:
"""Provide default function for Schema validation.
:param validator_class: JSONSchema suitable validator class.
"""
def validate_func(schema: AnyMapping, pure_data: AnyMapping) -> AnyMapping:
"""Validate schema with given data.
:param schema: Schema representation to use.
:param pure_data: Pure data to validate.
"""
return validator_class(schema).validate(pure_data)
return validate_func | [
"def",
"validate_func_factory",
"(",
"validator_class",
":",
"Any",
")",
"->",
"ValidateFunc",
":",
"def",
"validate_func",
"(",
"schema",
":",
"AnyMapping",
",",
"pure_data",
":",
"AnyMapping",
")",
"->",
"AnyMapping",
":",
"\"\"\"Validate schema with given data.\n\n... | Provide default function for Schema validation.
:param validator_class: JSONSchema suitable validator class. | [
"Provide",
"default",
"function",
"for",
"Schema",
"validation",
"."
] | 28a04e8028c29647941e727116335e9d6fd64c27 | https://github.com/playpauseandstop/rororo/blob/28a04e8028c29647941e727116335e9d6fd64c27/rororo/schemas/utils.py#L29-L41 | train | 47,978 |
OSSOS/MOP | src/jjk/preproc/MOPdisplay.py | moreData | def moreData(ra,dec,box):
"""Search the CFHT archive for more images of this location"""
import cfhtCutout
cdata={'ra_deg': ra, 'dec_deg': dec, 'radius_deg': 0.2}
inter=cfhtCutout.find_images(cdata,0.2) | python | def moreData(ra,dec,box):
"""Search the CFHT archive for more images of this location"""
import cfhtCutout
cdata={'ra_deg': ra, 'dec_deg': dec, 'radius_deg': 0.2}
inter=cfhtCutout.find_images(cdata,0.2) | [
"def",
"moreData",
"(",
"ra",
",",
"dec",
",",
"box",
")",
":",
"import",
"cfhtCutout",
"cdata",
"=",
"{",
"'ra_deg'",
":",
"ra",
",",
"'dec_deg'",
":",
"dec",
",",
"'radius_deg'",
":",
"0.2",
"}",
"inter",
"=",
"cfhtCutout",
".",
"find_images",
"(",
... | Search the CFHT archive for more images of this location | [
"Search",
"the",
"CFHT",
"archive",
"for",
"more",
"images",
"of",
"this",
"location"
] | 94f91d32ad5ec081d5a1ebd67604a838003465af | https://github.com/OSSOS/MOP/blob/94f91d32ad5ec081d5a1ebd67604a838003465af/src/jjk/preproc/MOPdisplay.py#L33-L38 | train | 47,979 |
OSSOS/MOP | src/jjk/preproc/MOPdisplay.py | xpacheck | def xpacheck():
"""Check if xpa is running"""
import os
f=os.popen('xpaaccess ds9')
l=f.readline()
f.close()
if l.strip()!='yes':
logger.debug("\t Can't get ds9 access, xpaccess said: %s" % ( l.strip()))
return (False)
return(True) | python | def xpacheck():
"""Check if xpa is running"""
import os
f=os.popen('xpaaccess ds9')
l=f.readline()
f.close()
if l.strip()!='yes':
logger.debug("\t Can't get ds9 access, xpaccess said: %s" % ( l.strip()))
return (False)
return(True) | [
"def",
"xpacheck",
"(",
")",
":",
"import",
"os",
"f",
"=",
"os",
".",
"popen",
"(",
"'xpaaccess ds9'",
")",
"l",
"=",
"f",
".",
"readline",
"(",
")",
"f",
".",
"close",
"(",
")",
"if",
"l",
".",
"strip",
"(",
")",
"!=",
"'yes'",
":",
"logger",... | Check if xpa is running | [
"Check",
"if",
"xpa",
"is",
"running"
] | 94f91d32ad5ec081d5a1ebd67604a838003465af | https://github.com/OSSOS/MOP/blob/94f91d32ad5ec081d5a1ebd67604a838003465af/src/jjk/preproc/MOPdisplay.py#L40-L49 | train | 47,980 |
OSSOS/MOP | src/jjk/preproc/MOPdisplay.py | mark | def mark(x,y,label=None):
"""Mark a circle on the current image"""
if label is not None:
os.system("xpaset -p ds9 regions color red ")
cmd="echo 'image; text %d %d # text={%s}' | xpaset ds9 regions " % ( x,y,label)
else:
os.system("xpaset -p ds9 regions color blue")
cmd="echo 'image; circle %d %d 10 ' | xpaset ds9 regions " % (x,y)
os.system(cmd)
return | python | def mark(x,y,label=None):
"""Mark a circle on the current image"""
if label is not None:
os.system("xpaset -p ds9 regions color red ")
cmd="echo 'image; text %d %d # text={%s}' | xpaset ds9 regions " % ( x,y,label)
else:
os.system("xpaset -p ds9 regions color blue")
cmd="echo 'image; circle %d %d 10 ' | xpaset ds9 regions " % (x,y)
os.system(cmd)
return | [
"def",
"mark",
"(",
"x",
",",
"y",
",",
"label",
"=",
"None",
")",
":",
"if",
"label",
"is",
"not",
"None",
":",
"os",
".",
"system",
"(",
"\"xpaset -p ds9 regions color red \"",
")",
"cmd",
"=",
"\"echo 'image; text %d %d # text={%s}' | xpaset ds9 regions \"",
... | Mark a circle on the current image | [
"Mark",
"a",
"circle",
"on",
"the",
"current",
"image"
] | 94f91d32ad5ec081d5a1ebd67604a838003465af | https://github.com/OSSOS/MOP/blob/94f91d32ad5ec081d5a1ebd67604a838003465af/src/jjk/preproc/MOPdisplay.py#L72-L81 | train | 47,981 |
OSSOS/MOP | src/jjk/preproc/MOPdisplay.py | display | def display(url):
"""Display a file in ds9"""
import os
oscmd="curl --silent -g --fail --max-time 1800 --user jkavelaars '%s'" % (url)
logger.debug(oscmd)
os.system(oscmd+' | xpaset ds9 fits')
return | python | def display(url):
"""Display a file in ds9"""
import os
oscmd="curl --silent -g --fail --max-time 1800 --user jkavelaars '%s'" % (url)
logger.debug(oscmd)
os.system(oscmd+' | xpaset ds9 fits')
return | [
"def",
"display",
"(",
"url",
")",
":",
"import",
"os",
"oscmd",
"=",
"\"curl --silent -g --fail --max-time 1800 --user jkavelaars '%s'\"",
"%",
"(",
"url",
")",
"logger",
".",
"debug",
"(",
"oscmd",
")",
"os",
".",
"system",
"(",
"oscmd",
"+",
"' | xpaset ds9 f... | Display a file in ds9 | [
"Display",
"a",
"file",
"in",
"ds9"
] | 94f91d32ad5ec081d5a1ebd67604a838003465af | https://github.com/OSSOS/MOP/blob/94f91d32ad5ec081d5a1ebd67604a838003465af/src/jjk/preproc/MOPdisplay.py#L84-L90 | train | 47,982 |
eelregit/mcfit | mcfit/mcfit.py | mcfit.inv | def inv(self):
"""Invert the transform.
After calling this method, calling the instance will do the inverse
transform. Calling this twice return the instance to the original
transform.
"""
self.x, self.y = self.y, self.x
self._x_, self._y_ = self._y_, self._x_
self.xfac, self.yfac = 1 / self.yfac, 1 / self.xfac
self._xfac_, self._yfac_ = 1 / self._yfac_, 1 / self._xfac_
self._u = 1 / self._u.conj() | python | def inv(self):
"""Invert the transform.
After calling this method, calling the instance will do the inverse
transform. Calling this twice return the instance to the original
transform.
"""
self.x, self.y = self.y, self.x
self._x_, self._y_ = self._y_, self._x_
self.xfac, self.yfac = 1 / self.yfac, 1 / self.xfac
self._xfac_, self._yfac_ = 1 / self._yfac_, 1 / self._xfac_
self._u = 1 / self._u.conj() | [
"def",
"inv",
"(",
"self",
")",
":",
"self",
".",
"x",
",",
"self",
".",
"y",
"=",
"self",
".",
"y",
",",
"self",
".",
"x",
"self",
".",
"_x_",
",",
"self",
".",
"_y_",
"=",
"self",
".",
"_y_",
",",
"self",
".",
"_x_",
"self",
".",
"xfac",
... | Invert the transform.
After calling this method, calling the instance will do the inverse
transform. Calling this twice return the instance to the original
transform. | [
"Invert",
"the",
"transform",
"."
] | ef04b92df929425c44c62743c1ce7e0b81a26815 | https://github.com/eelregit/mcfit/blob/ef04b92df929425c44c62743c1ce7e0b81a26815/mcfit/mcfit.py#L248-L260 | train | 47,983 |
eelregit/mcfit | mcfit/mcfit.py | mcfit.matrix | def matrix(self, full=False, keeppads=True):
"""Return matrix form of the integral transform.
Parameters
----------
full : bool, optional
when False return two vector factors and convolution matrix
separately, otherwise return full transformation matrix
keeppads : bool, optional
whether to keep the padding in the output
Returns
-------
If full is False, output separately
a : (1, N) or (1, Nin) ndarray
"After" factor, `_yfac_` or `yfac`
b : (N,) or (Nin,) ndarray
"Before" factor, `_xfac_` or `xfac`
C : (N, N) or (Nin, Nin) ndarray
Convolution matrix, circulant
Otherwise, output the full matrix, combining `a`, `b`, and `C`
M : (N, N) or (Nin, Nin) ndarray
Full transformation matrix, `M = a * C * b`
Notes
-----
`M`, `a`, `b`, and `C` are padded by default. Pads can be discarded if
`keeppads` is set to False.
This is not meant for evaluation with matrix multiplication but in case
one is interested in the tranformation itself.
When `N` is even and `lowring` is False, :math:`C C^{-1}` and :math:`M
M^{-1}` can deviate from the identity matrix because the imaginary part
of the Nyquist modes are dropped.
The convolution matrix is a circulant matrix, with its first row and
first column being the Fourier transform of :math:`u_m`.
Indeed :math:`u_m` are the eigenvalues of the convolution matrix, that
are diagonalized by the DFT matrix.
Thus :math:`1/u_m` are the eigenvalues of the inverse convolution
matrix.
"""
v = np.fft.hfft(self._u, n=self.N) / self.N
idx = sum(np.ogrid[0:self.N, -self.N:0])
C = v[idx] # follow scipy.linalg.{circulant,toeplitz,hankel}
if keeppads:
a = self._yfac_.copy()
b = self._xfac_.copy()
else:
a = self.yfac.copy()
b = self.xfac.copy()
C = self._unpad(C, 0, True)
C = self._unpad(C, 1, False)
a = a.reshape(-1, 1)
if not full:
return a, b, C
else:
return a * C * b | python | def matrix(self, full=False, keeppads=True):
"""Return matrix form of the integral transform.
Parameters
----------
full : bool, optional
when False return two vector factors and convolution matrix
separately, otherwise return full transformation matrix
keeppads : bool, optional
whether to keep the padding in the output
Returns
-------
If full is False, output separately
a : (1, N) or (1, Nin) ndarray
"After" factor, `_yfac_` or `yfac`
b : (N,) or (Nin,) ndarray
"Before" factor, `_xfac_` or `xfac`
C : (N, N) or (Nin, Nin) ndarray
Convolution matrix, circulant
Otherwise, output the full matrix, combining `a`, `b`, and `C`
M : (N, N) or (Nin, Nin) ndarray
Full transformation matrix, `M = a * C * b`
Notes
-----
`M`, `a`, `b`, and `C` are padded by default. Pads can be discarded if
`keeppads` is set to False.
This is not meant for evaluation with matrix multiplication but in case
one is interested in the tranformation itself.
When `N` is even and `lowring` is False, :math:`C C^{-1}` and :math:`M
M^{-1}` can deviate from the identity matrix because the imaginary part
of the Nyquist modes are dropped.
The convolution matrix is a circulant matrix, with its first row and
first column being the Fourier transform of :math:`u_m`.
Indeed :math:`u_m` are the eigenvalues of the convolution matrix, that
are diagonalized by the DFT matrix.
Thus :math:`1/u_m` are the eigenvalues of the inverse convolution
matrix.
"""
v = np.fft.hfft(self._u, n=self.N) / self.N
idx = sum(np.ogrid[0:self.N, -self.N:0])
C = v[idx] # follow scipy.linalg.{circulant,toeplitz,hankel}
if keeppads:
a = self._yfac_.copy()
b = self._xfac_.copy()
else:
a = self.yfac.copy()
b = self.xfac.copy()
C = self._unpad(C, 0, True)
C = self._unpad(C, 1, False)
a = a.reshape(-1, 1)
if not full:
return a, b, C
else:
return a * C * b | [
"def",
"matrix",
"(",
"self",
",",
"full",
"=",
"False",
",",
"keeppads",
"=",
"True",
")",
":",
"v",
"=",
"np",
".",
"fft",
".",
"hfft",
"(",
"self",
".",
"_u",
",",
"n",
"=",
"self",
".",
"N",
")",
"/",
"self",
".",
"N",
"idx",
"=",
"sum"... | Return matrix form of the integral transform.
Parameters
----------
full : bool, optional
when False return two vector factors and convolution matrix
separately, otherwise return full transformation matrix
keeppads : bool, optional
whether to keep the padding in the output
Returns
-------
If full is False, output separately
a : (1, N) or (1, Nin) ndarray
"After" factor, `_yfac_` or `yfac`
b : (N,) or (Nin,) ndarray
"Before" factor, `_xfac_` or `xfac`
C : (N, N) or (Nin, Nin) ndarray
Convolution matrix, circulant
Otherwise, output the full matrix, combining `a`, `b`, and `C`
M : (N, N) or (Nin, Nin) ndarray
Full transformation matrix, `M = a * C * b`
Notes
-----
`M`, `a`, `b`, and `C` are padded by default. Pads can be discarded if
`keeppads` is set to False.
This is not meant for evaluation with matrix multiplication but in case
one is interested in the tranformation itself.
When `N` is even and `lowring` is False, :math:`C C^{-1}` and :math:`M
M^{-1}` can deviate from the identity matrix because the imaginary part
of the Nyquist modes are dropped.
The convolution matrix is a circulant matrix, with its first row and
first column being the Fourier transform of :math:`u_m`.
Indeed :math:`u_m` are the eigenvalues of the convolution matrix, that
are diagonalized by the DFT matrix.
Thus :math:`1/u_m` are the eigenvalues of the inverse convolution
matrix. | [
"Return",
"matrix",
"form",
"of",
"the",
"integral",
"transform",
"."
] | ef04b92df929425c44c62743c1ce7e0b81a26815 | https://github.com/eelregit/mcfit/blob/ef04b92df929425c44c62743c1ce7e0b81a26815/mcfit/mcfit.py#L263-L325 | train | 47,984 |
eelregit/mcfit | mcfit/mcfit.py | mcfit._pad | def _pad(self, a, axis, extrap, out):
"""Add padding to an array.
Parameters
----------
a : (..., Nin, ...) ndarray
array to be padded to size `N`
axis : int
axis along which to pad
extrap : {bool, 'const'} or 2-tuple
Method to extrapolate `a`.
For a 2-tuple, the two elements are for the left and right pads,
whereas a single value applies to both ends.
Options are:
* True: power-law extrapolation using the end segment
* False: zero padding
* 'const': constant padding with the end point value
out : bool
pad the output if True, otherwise the input; the two cases have
their left and right pad sizes reversed
"""
assert a.shape[axis] == self.Nin
axis %= a.ndim # to fix the indexing below with axis+1
to_axis = [1] * a.ndim
to_axis[axis] = -1
Npad = self.N - self.Nin
if out:
_Npad, Npad_ = Npad - Npad//2, Npad//2
else:
_Npad, Npad_ = Npad//2, Npad - Npad//2
try:
_extrap, extrap_ = extrap
except (TypeError, ValueError):
_extrap = extrap_ = extrap
if isinstance(_extrap, bool):
if _extrap:
end = np.take(a, [0], axis=axis)
ratio = np.take(a, [1], axis=axis) / end
exp = np.arange(-_Npad, 0).reshape(to_axis)
_a = end * ratio ** exp
else:
_a = np.zeros(a.shape[:axis] + (_Npad,) + a.shape[axis+1:])
elif _extrap == 'const':
end = np.take(a, [0], axis=axis)
_a = np.repeat(end, _Npad, axis=axis)
else:
raise ValueError("left extrap not supported")
if isinstance(extrap_, bool):
if extrap_:
end = np.take(a, [-1], axis=axis)
ratio = end / np.take(a, [-2], axis=axis)
exp = np.arange(1, Npad_ + 1).reshape(to_axis)
a_ = end * ratio ** exp
else:
a_ = np.zeros(a.shape[:axis] + (Npad_,) + a.shape[axis+1:])
elif extrap_ == 'const':
end = np.take(a, [-1], axis=axis)
a_ = np.repeat(end, Npad_, axis=axis)
else:
raise ValueError("right extrap not supported")
return np.concatenate((_a, a, a_), axis=axis) | python | def _pad(self, a, axis, extrap, out):
"""Add padding to an array.
Parameters
----------
a : (..., Nin, ...) ndarray
array to be padded to size `N`
axis : int
axis along which to pad
extrap : {bool, 'const'} or 2-tuple
Method to extrapolate `a`.
For a 2-tuple, the two elements are for the left and right pads,
whereas a single value applies to both ends.
Options are:
* True: power-law extrapolation using the end segment
* False: zero padding
* 'const': constant padding with the end point value
out : bool
pad the output if True, otherwise the input; the two cases have
their left and right pad sizes reversed
"""
assert a.shape[axis] == self.Nin
axis %= a.ndim # to fix the indexing below with axis+1
to_axis = [1] * a.ndim
to_axis[axis] = -1
Npad = self.N - self.Nin
if out:
_Npad, Npad_ = Npad - Npad//2, Npad//2
else:
_Npad, Npad_ = Npad//2, Npad - Npad//2
try:
_extrap, extrap_ = extrap
except (TypeError, ValueError):
_extrap = extrap_ = extrap
if isinstance(_extrap, bool):
if _extrap:
end = np.take(a, [0], axis=axis)
ratio = np.take(a, [1], axis=axis) / end
exp = np.arange(-_Npad, 0).reshape(to_axis)
_a = end * ratio ** exp
else:
_a = np.zeros(a.shape[:axis] + (_Npad,) + a.shape[axis+1:])
elif _extrap == 'const':
end = np.take(a, [0], axis=axis)
_a = np.repeat(end, _Npad, axis=axis)
else:
raise ValueError("left extrap not supported")
if isinstance(extrap_, bool):
if extrap_:
end = np.take(a, [-1], axis=axis)
ratio = end / np.take(a, [-2], axis=axis)
exp = np.arange(1, Npad_ + 1).reshape(to_axis)
a_ = end * ratio ** exp
else:
a_ = np.zeros(a.shape[:axis] + (Npad_,) + a.shape[axis+1:])
elif extrap_ == 'const':
end = np.take(a, [-1], axis=axis)
a_ = np.repeat(end, Npad_, axis=axis)
else:
raise ValueError("right extrap not supported")
return np.concatenate((_a, a, a_), axis=axis) | [
"def",
"_pad",
"(",
"self",
",",
"a",
",",
"axis",
",",
"extrap",
",",
"out",
")",
":",
"assert",
"a",
".",
"shape",
"[",
"axis",
"]",
"==",
"self",
".",
"Nin",
"axis",
"%=",
"a",
".",
"ndim",
"# to fix the indexing below with axis+1",
"to_axis",
"=",
... | Add padding to an array.
Parameters
----------
a : (..., Nin, ...) ndarray
array to be padded to size `N`
axis : int
axis along which to pad
extrap : {bool, 'const'} or 2-tuple
Method to extrapolate `a`.
For a 2-tuple, the two elements are for the left and right pads,
whereas a single value applies to both ends.
Options are:
* True: power-law extrapolation using the end segment
* False: zero padding
* 'const': constant padding with the end point value
out : bool
pad the output if True, otherwise the input; the two cases have
their left and right pad sizes reversed | [
"Add",
"padding",
"to",
"an",
"array",
"."
] | ef04b92df929425c44c62743c1ce7e0b81a26815 | https://github.com/eelregit/mcfit/blob/ef04b92df929425c44c62743c1ce7e0b81a26815/mcfit/mcfit.py#L328-L395 | train | 47,985 |
eelregit/mcfit | mcfit/mcfit.py | mcfit._unpad | def _unpad(self, a, axis, out):
"""Undo padding in an array.
Parameters
----------
a : (..., N, ...) ndarray
array to be trimmed to size `Nin`
axis : int
axis along which to unpad
out : bool
trim the output if True, otherwise the input; the two cases have
their left and right pad sizes reversed
"""
assert a.shape[axis] == self.N
Npad = self.N - self.Nin
if out:
_Npad, Npad_ = Npad - Npad//2, Npad//2
else:
_Npad, Npad_ = Npad//2, Npad - Npad//2
return np.take(a, range(_Npad, self.N - Npad_), axis=axis) | python | def _unpad(self, a, axis, out):
"""Undo padding in an array.
Parameters
----------
a : (..., N, ...) ndarray
array to be trimmed to size `Nin`
axis : int
axis along which to unpad
out : bool
trim the output if True, otherwise the input; the two cases have
their left and right pad sizes reversed
"""
assert a.shape[axis] == self.N
Npad = self.N - self.Nin
if out:
_Npad, Npad_ = Npad - Npad//2, Npad//2
else:
_Npad, Npad_ = Npad//2, Npad - Npad//2
return np.take(a, range(_Npad, self.N - Npad_), axis=axis) | [
"def",
"_unpad",
"(",
"self",
",",
"a",
",",
"axis",
",",
"out",
")",
":",
"assert",
"a",
".",
"shape",
"[",
"axis",
"]",
"==",
"self",
".",
"N",
"Npad",
"=",
"self",
".",
"N",
"-",
"self",
".",
"Nin",
"if",
"out",
":",
"_Npad",
",",
"Npad_",... | Undo padding in an array.
Parameters
----------
a : (..., N, ...) ndarray
array to be trimmed to size `Nin`
axis : int
axis along which to unpad
out : bool
trim the output if True, otherwise the input; the two cases have
their left and right pad sizes reversed | [
"Undo",
"padding",
"in",
"an",
"array",
"."
] | ef04b92df929425c44c62743c1ce7e0b81a26815 | https://github.com/eelregit/mcfit/blob/ef04b92df929425c44c62743c1ce7e0b81a26815/mcfit/mcfit.py#L398-L420 | train | 47,986 |
eelregit/mcfit | mcfit/mcfit.py | mcfit.check | def check(self, F):
"""Rough sanity checks on the input function.
"""
assert F.ndim == 1, "checker only supports 1D"
f = self.xfac * F
fabs = np.abs(f)
iQ1, iQ3 = np.searchsorted(fabs.cumsum(), np.array([0.25, 0.75]) * fabs.sum())
assert 0 != iQ1 != iQ3 != self.Nin, "checker giving up"
fabs_l = fabs[:iQ1].mean()
fabs_m = fabs[iQ1:iQ3].mean()
fabs_r = fabs[iQ3:].mean()
if fabs_l > fabs_m:
warnings.warn("left wing seems heavy: {:.2g} vs {:.2g}, "
"change tilt and mind convergence".format(fabs_l, fabs_m), RuntimeWarning)
if fabs_m < fabs_r:
warnings.warn("right wing seems heavy: {:.2g} vs {:.2g}, "
"change tilt and mind convergence".format(fabs_m, fabs_r), RuntimeWarning)
if fabs[0] > fabs[1]:
warnings.warn("left tail may blow up: {:.2g} vs {:.2g}, "
"change tilt or avoid extrapolation".format(f[0], f[1]), RuntimeWarning)
if fabs[-2] < fabs[-1]:
warnings.warn("right tail may blow up: {:.2g} vs {:.2g}, "
"change tilt or avoid extrapolation".format(f[-2], f[-1]), RuntimeWarning)
if f[0]*f[1] <= 0:
warnings.warn("left tail looks wiggly: {:.2g} vs {:.2g}, "
"avoid extrapolation".format(f[0], f[1]), RuntimeWarning)
if f[-2]*f[-1] <= 0:
warnings.warn("right tail looks wiggly: {:.2g} vs {:.2g}, "
"avoid extrapolation".format(f[-2], f[-1]), RuntimeWarning) | python | def check(self, F):
"""Rough sanity checks on the input function.
"""
assert F.ndim == 1, "checker only supports 1D"
f = self.xfac * F
fabs = np.abs(f)
iQ1, iQ3 = np.searchsorted(fabs.cumsum(), np.array([0.25, 0.75]) * fabs.sum())
assert 0 != iQ1 != iQ3 != self.Nin, "checker giving up"
fabs_l = fabs[:iQ1].mean()
fabs_m = fabs[iQ1:iQ3].mean()
fabs_r = fabs[iQ3:].mean()
if fabs_l > fabs_m:
warnings.warn("left wing seems heavy: {:.2g} vs {:.2g}, "
"change tilt and mind convergence".format(fabs_l, fabs_m), RuntimeWarning)
if fabs_m < fabs_r:
warnings.warn("right wing seems heavy: {:.2g} vs {:.2g}, "
"change tilt and mind convergence".format(fabs_m, fabs_r), RuntimeWarning)
if fabs[0] > fabs[1]:
warnings.warn("left tail may blow up: {:.2g} vs {:.2g}, "
"change tilt or avoid extrapolation".format(f[0], f[1]), RuntimeWarning)
if fabs[-2] < fabs[-1]:
warnings.warn("right tail may blow up: {:.2g} vs {:.2g}, "
"change tilt or avoid extrapolation".format(f[-2], f[-1]), RuntimeWarning)
if f[0]*f[1] <= 0:
warnings.warn("left tail looks wiggly: {:.2g} vs {:.2g}, "
"avoid extrapolation".format(f[0], f[1]), RuntimeWarning)
if f[-2]*f[-1] <= 0:
warnings.warn("right tail looks wiggly: {:.2g} vs {:.2g}, "
"avoid extrapolation".format(f[-2], f[-1]), RuntimeWarning) | [
"def",
"check",
"(",
"self",
",",
"F",
")",
":",
"assert",
"F",
".",
"ndim",
"==",
"1",
",",
"\"checker only supports 1D\"",
"f",
"=",
"self",
".",
"xfac",
"*",
"F",
"fabs",
"=",
"np",
".",
"abs",
"(",
"f",
")",
"iQ1",
",",
"iQ3",
"=",
"np",
".... | Rough sanity checks on the input function. | [
"Rough",
"sanity",
"checks",
"on",
"the",
"input",
"function",
"."
] | ef04b92df929425c44c62743c1ce7e0b81a26815 | https://github.com/eelregit/mcfit/blob/ef04b92df929425c44c62743c1ce7e0b81a26815/mcfit/mcfit.py#L423-L457 | train | 47,987 |
JohnVinyard/zounds | zounds/spectral/functional.py | fft | def fft(x, axis=-1, padding_samples=0):
"""
Apply an FFT along the given dimension, and with the specified amount of
zero-padding
Args:
x (ArrayWithUnits): an :class:`~zounds.core.ArrayWithUnits` instance
which has one or more :class:`~zounds.timeseries.TimeDimension`
axes
axis (int): The axis along which the fft should be applied
padding_samples (int): The number of padding zeros to apply along
axis before performing the FFT
"""
if padding_samples > 0:
padded = np.concatenate(
[x, np.zeros((len(x), padding_samples), dtype=x.dtype)],
axis=axis)
else:
padded = x
transformed = np.fft.rfft(padded, axis=axis, norm='ortho')
sr = audio_sample_rate(int(Seconds(1) / x.dimensions[axis].frequency))
scale = LinearScale.from_sample_rate(sr, transformed.shape[-1])
new_dimensions = list(x.dimensions)
new_dimensions[axis] = FrequencyDimension(scale)
return ArrayWithUnits(transformed, new_dimensions) | python | def fft(x, axis=-1, padding_samples=0):
"""
Apply an FFT along the given dimension, and with the specified amount of
zero-padding
Args:
x (ArrayWithUnits): an :class:`~zounds.core.ArrayWithUnits` instance
which has one or more :class:`~zounds.timeseries.TimeDimension`
axes
axis (int): The axis along which the fft should be applied
padding_samples (int): The number of padding zeros to apply along
axis before performing the FFT
"""
if padding_samples > 0:
padded = np.concatenate(
[x, np.zeros((len(x), padding_samples), dtype=x.dtype)],
axis=axis)
else:
padded = x
transformed = np.fft.rfft(padded, axis=axis, norm='ortho')
sr = audio_sample_rate(int(Seconds(1) / x.dimensions[axis].frequency))
scale = LinearScale.from_sample_rate(sr, transformed.shape[-1])
new_dimensions = list(x.dimensions)
new_dimensions[axis] = FrequencyDimension(scale)
return ArrayWithUnits(transformed, new_dimensions) | [
"def",
"fft",
"(",
"x",
",",
"axis",
"=",
"-",
"1",
",",
"padding_samples",
"=",
"0",
")",
":",
"if",
"padding_samples",
">",
"0",
":",
"padded",
"=",
"np",
".",
"concatenate",
"(",
"[",
"x",
",",
"np",
".",
"zeros",
"(",
"(",
"len",
"(",
"x",
... | Apply an FFT along the given dimension, and with the specified amount of
zero-padding
Args:
x (ArrayWithUnits): an :class:`~zounds.core.ArrayWithUnits` instance
which has one or more :class:`~zounds.timeseries.TimeDimension`
axes
axis (int): The axis along which the fft should be applied
padding_samples (int): The number of padding zeros to apply along
axis before performing the FFT | [
"Apply",
"an",
"FFT",
"along",
"the",
"given",
"dimension",
"and",
"with",
"the",
"specified",
"amount",
"of",
"zero",
"-",
"padding"
] | 337b3f98753d09eaab1c72dcd37bb852a3fa5ac6 | https://github.com/JohnVinyard/zounds/blob/337b3f98753d09eaab1c72dcd37bb852a3fa5ac6/zounds/spectral/functional.py#L20-L46 | train | 47,988 |
OSSOS/MOP | src/ossos/core/ossos/fitsviewer/colormap.py | GrayscaleColorMap.set_bias | def set_bias(self, bias):
"""
Adjusts the image bias.
Bias determines where the color changes start. At low bias, low
intensities (i.e., low pixel values) will have non-zero color
differences, while at high bias only high pixel values will have
non-zero differences
Args:
bias: float
A number between 0 and 1. Note that upon initialization the
colormap has a default bias of 0.5.
Returns: void
"""
self.x_offset += (bias - self._bias)
self._bias = bias
self._build_cdict() | python | def set_bias(self, bias):
"""
Adjusts the image bias.
Bias determines where the color changes start. At low bias, low
intensities (i.e., low pixel values) will have non-zero color
differences, while at high bias only high pixel values will have
non-zero differences
Args:
bias: float
A number between 0 and 1. Note that upon initialization the
colormap has a default bias of 0.5.
Returns: void
"""
self.x_offset += (bias - self._bias)
self._bias = bias
self._build_cdict() | [
"def",
"set_bias",
"(",
"self",
",",
"bias",
")",
":",
"self",
".",
"x_offset",
"+=",
"(",
"bias",
"-",
"self",
".",
"_bias",
")",
"self",
".",
"_bias",
"=",
"bias",
"self",
".",
"_build_cdict",
"(",
")"
] | Adjusts the image bias.
Bias determines where the color changes start. At low bias, low
intensities (i.e., low pixel values) will have non-zero color
differences, while at high bias only high pixel values will have
non-zero differences
Args:
bias: float
A number between 0 and 1. Note that upon initialization the
colormap has a default bias of 0.5.
Returns: void | [
"Adjusts",
"the",
"image",
"bias",
"."
] | 94f91d32ad5ec081d5a1ebd67604a838003465af | https://github.com/OSSOS/MOP/blob/94f91d32ad5ec081d5a1ebd67604a838003465af/src/ossos/core/ossos/fitsviewer/colormap.py#L59-L78 | train | 47,989 |
OSSOS/MOP | src/ossos/core/ossos/fitsviewer/colormap.py | GrayscaleColorMap.set_contrast | def set_contrast(self, contrast):
"""
Adjusts the image contrast.
Contrast refers to the rate of change of color with color level.
At low contrast, color changes gradually over many intensity
levels, while at high contrast it can change rapidly within a
few levels
Args:
contrast: float
A number between 0 and 1. Note that upon initialization the
colormap has a default contrast value of 0.5.
Returns: void
"""
self._contrast = contrast
self.x_spread = 2 * (1.0 - contrast)
self.y_spread = 2.0 - 2 * (1.0 - contrast)
self._build_cdict() | python | def set_contrast(self, contrast):
"""
Adjusts the image contrast.
Contrast refers to the rate of change of color with color level.
At low contrast, color changes gradually over many intensity
levels, while at high contrast it can change rapidly within a
few levels
Args:
contrast: float
A number between 0 and 1. Note that upon initialization the
colormap has a default contrast value of 0.5.
Returns: void
"""
self._contrast = contrast
self.x_spread = 2 * (1.0 - contrast)
self.y_spread = 2.0 - 2 * (1.0 - contrast)
self._build_cdict() | [
"def",
"set_contrast",
"(",
"self",
",",
"contrast",
")",
":",
"self",
".",
"_contrast",
"=",
"contrast",
"self",
".",
"x_spread",
"=",
"2",
"*",
"(",
"1.0",
"-",
"contrast",
")",
"self",
".",
"y_spread",
"=",
"2.0",
"-",
"2",
"*",
"(",
"1.0",
"-",... | Adjusts the image contrast.
Contrast refers to the rate of change of color with color level.
At low contrast, color changes gradually over many intensity
levels, while at high contrast it can change rapidly within a
few levels
Args:
contrast: float
A number between 0 and 1. Note that upon initialization the
colormap has a default contrast value of 0.5.
Returns: void | [
"Adjusts",
"the",
"image",
"contrast",
"."
] | 94f91d32ad5ec081d5a1ebd67604a838003465af | https://github.com/OSSOS/MOP/blob/94f91d32ad5ec081d5a1ebd67604a838003465af/src/ossos/core/ossos/fitsviewer/colormap.py#L83-L104 | train | 47,990 |
Accelize/pycosio | pycosio/_core/functions_shutil.py | _copy | def _copy(src, dst, src_is_storage, dst_is_storage):
"""
Copies file from source to destination
Args:
src (str or file-like object): Source file.
dst (str or file-like object): Destination file.
src_is_storage (bool): Source is storage.
dst_is_storage (bool): Destination is storage.
"""
# If both storage: Tries to perform same storage direct copy
if src_is_storage and dst_is_storage:
system_src = get_instance(src)
system_dst = get_instance(dst)
# Same storage copy
if system_src is system_dst:
# Checks if same file
if system_src.relpath(src) == system_dst.relpath(dst):
raise same_file_error(
"'%s' and '%s' are the same file" % (src, dst))
# Tries to copy
try:
return system_dst.copy(src, dst)
except (UnsupportedOperation, ObjectException):
pass
# Copy from compatible storage using "copy_from_<src_storage>" or
# "copy_to_<src_storage>" method if any
for caller, called, method in (
(system_dst, system_src, 'copy_from_%s'),
(system_src, system_dst, 'copy_to_%s')):
if hasattr(caller, method % called.storage):
try:
return getattr(caller, method % called.storage)(
src, dst, called)
except (UnsupportedOperation, ObjectException):
continue
# At least one storage object: copies streams
with cos_open(src, 'rb') as fsrc:
with cos_open(dst, 'wb') as fdst:
# Get stream buffer size
for stream in (fsrc, fdst):
try:
buffer_size = getattr(stream, '_buffer_size')
break
except AttributeError:
continue
else:
buffer_size = COPY_BUFSIZE
# Read and write
copyfileobj(fsrc, fdst, buffer_size) | python | def _copy(src, dst, src_is_storage, dst_is_storage):
"""
Copies file from source to destination
Args:
src (str or file-like object): Source file.
dst (str or file-like object): Destination file.
src_is_storage (bool): Source is storage.
dst_is_storage (bool): Destination is storage.
"""
# If both storage: Tries to perform same storage direct copy
if src_is_storage and dst_is_storage:
system_src = get_instance(src)
system_dst = get_instance(dst)
# Same storage copy
if system_src is system_dst:
# Checks if same file
if system_src.relpath(src) == system_dst.relpath(dst):
raise same_file_error(
"'%s' and '%s' are the same file" % (src, dst))
# Tries to copy
try:
return system_dst.copy(src, dst)
except (UnsupportedOperation, ObjectException):
pass
# Copy from compatible storage using "copy_from_<src_storage>" or
# "copy_to_<src_storage>" method if any
for caller, called, method in (
(system_dst, system_src, 'copy_from_%s'),
(system_src, system_dst, 'copy_to_%s')):
if hasattr(caller, method % called.storage):
try:
return getattr(caller, method % called.storage)(
src, dst, called)
except (UnsupportedOperation, ObjectException):
continue
# At least one storage object: copies streams
with cos_open(src, 'rb') as fsrc:
with cos_open(dst, 'wb') as fdst:
# Get stream buffer size
for stream in (fsrc, fdst):
try:
buffer_size = getattr(stream, '_buffer_size')
break
except AttributeError:
continue
else:
buffer_size = COPY_BUFSIZE
# Read and write
copyfileobj(fsrc, fdst, buffer_size) | [
"def",
"_copy",
"(",
"src",
",",
"dst",
",",
"src_is_storage",
",",
"dst_is_storage",
")",
":",
"# If both storage: Tries to perform same storage direct copy",
"if",
"src_is_storage",
"and",
"dst_is_storage",
":",
"system_src",
"=",
"get_instance",
"(",
"src",
")",
"s... | Copies file from source to destination
Args:
src (str or file-like object): Source file.
dst (str or file-like object): Destination file.
src_is_storage (bool): Source is storage.
dst_is_storage (bool): Destination is storage. | [
"Copies",
"file",
"from",
"source",
"to",
"destination"
] | 1cc1f8fdf5394d92918b7bae2bfa682169ccc48c | https://github.com/Accelize/pycosio/blob/1cc1f8fdf5394d92918b7bae2bfa682169ccc48c/pycosio/_core/functions_shutil.py#L17-L73 | train | 47,991 |
Accelize/pycosio | pycosio/_core/functions_shutil.py | copy | def copy(src, dst):
"""
Copies a source file to a destination file or directory.
Equivalent to "shutil.copy".
Source and destination can also be binary opened file-like objects.
Args:
src (path-like object or file-like object): Source file.
dst (path-like object or file-like object):
Destination file or directory.
Raises:
IOError: Destination directory not found.
"""
# Handles path-like objects and checks if storage
src, src_is_storage = format_and_is_storage(src)
dst, dst_is_storage = format_and_is_storage(dst)
# Local files: Redirects to "shutil.copy"
if not src_is_storage and not dst_is_storage:
return shutil_copy(src, dst)
with handle_os_exceptions():
# Checks destination
if not hasattr(dst, 'read'):
try:
# If destination is directory: defines an output file inside it
if isdir(dst):
dst = join(dst, basename(src))
# Checks if destination dir exists
elif not isdir(dirname(dst)):
raise IOError("No such file or directory: '%s'" % dst)
except ObjectPermissionError:
# Unable to check target directory due to missing read access,
# but do not raise to allow to write if possible
pass
# Performs copy
_copy(src, dst, src_is_storage, dst_is_storage) | python | def copy(src, dst):
"""
Copies a source file to a destination file or directory.
Equivalent to "shutil.copy".
Source and destination can also be binary opened file-like objects.
Args:
src (path-like object or file-like object): Source file.
dst (path-like object or file-like object):
Destination file or directory.
Raises:
IOError: Destination directory not found.
"""
# Handles path-like objects and checks if storage
src, src_is_storage = format_and_is_storage(src)
dst, dst_is_storage = format_and_is_storage(dst)
# Local files: Redirects to "shutil.copy"
if not src_is_storage and not dst_is_storage:
return shutil_copy(src, dst)
with handle_os_exceptions():
# Checks destination
if not hasattr(dst, 'read'):
try:
# If destination is directory: defines an output file inside it
if isdir(dst):
dst = join(dst, basename(src))
# Checks if destination dir exists
elif not isdir(dirname(dst)):
raise IOError("No such file or directory: '%s'" % dst)
except ObjectPermissionError:
# Unable to check target directory due to missing read access,
# but do not raise to allow to write if possible
pass
# Performs copy
_copy(src, dst, src_is_storage, dst_is_storage) | [
"def",
"copy",
"(",
"src",
",",
"dst",
")",
":",
"# Handles path-like objects and checks if storage",
"src",
",",
"src_is_storage",
"=",
"format_and_is_storage",
"(",
"src",
")",
"dst",
",",
"dst_is_storage",
"=",
"format_and_is_storage",
"(",
"dst",
")",
"# Local f... | Copies a source file to a destination file or directory.
Equivalent to "shutil.copy".
Source and destination can also be binary opened file-like objects.
Args:
src (path-like object or file-like object): Source file.
dst (path-like object or file-like object):
Destination file or directory.
Raises:
IOError: Destination directory not found. | [
"Copies",
"a",
"source",
"file",
"to",
"a",
"destination",
"file",
"or",
"directory",
"."
] | 1cc1f8fdf5394d92918b7bae2bfa682169ccc48c | https://github.com/Accelize/pycosio/blob/1cc1f8fdf5394d92918b7bae2bfa682169ccc48c/pycosio/_core/functions_shutil.py#L76-L118 | train | 47,992 |
Accelize/pycosio | pycosio/_core/functions_shutil.py | copyfile | def copyfile(src, dst, follow_symlinks=True):
"""
Copies a source file to a destination file.
Equivalent to "shutil.copyfile".
Source and destination can also be binary opened file-like objects.
Args:
src (path-like object or file-like object): Source file.
dst (path-like object or file-like object): Destination file.
follow_symlinks (bool): Follow symlinks.
Not supported on cloud storage objects.
Raises:
IOError: Destination directory not found.
"""
# Handles path-like objects and checks if storage
src, src_is_storage = format_and_is_storage(src)
dst, dst_is_storage = format_and_is_storage(dst)
# Local files: Redirects to "shutil.copyfile"
if not src_is_storage and not dst_is_storage:
return shutil_copyfile(src, dst, follow_symlinks=follow_symlinks)
with handle_os_exceptions():
# Checks destination
try:
if not hasattr(dst, 'read') and not isdir(dirname(dst)):
raise IOError("No such file or directory: '%s'" % dst)
except ObjectPermissionError:
# Unable to check target directory due to missing read access, but
# do not raise to allow to write if possible
pass
# Performs copy
_copy(src, dst, src_is_storage, dst_is_storage) | python | def copyfile(src, dst, follow_symlinks=True):
"""
Copies a source file to a destination file.
Equivalent to "shutil.copyfile".
Source and destination can also be binary opened file-like objects.
Args:
src (path-like object or file-like object): Source file.
dst (path-like object or file-like object): Destination file.
follow_symlinks (bool): Follow symlinks.
Not supported on cloud storage objects.
Raises:
IOError: Destination directory not found.
"""
# Handles path-like objects and checks if storage
src, src_is_storage = format_and_is_storage(src)
dst, dst_is_storage = format_and_is_storage(dst)
# Local files: Redirects to "shutil.copyfile"
if not src_is_storage and not dst_is_storage:
return shutil_copyfile(src, dst, follow_symlinks=follow_symlinks)
with handle_os_exceptions():
# Checks destination
try:
if not hasattr(dst, 'read') and not isdir(dirname(dst)):
raise IOError("No such file or directory: '%s'" % dst)
except ObjectPermissionError:
# Unable to check target directory due to missing read access, but
# do not raise to allow to write if possible
pass
# Performs copy
_copy(src, dst, src_is_storage, dst_is_storage) | [
"def",
"copyfile",
"(",
"src",
",",
"dst",
",",
"follow_symlinks",
"=",
"True",
")",
":",
"# Handles path-like objects and checks if storage",
"src",
",",
"src_is_storage",
"=",
"format_and_is_storage",
"(",
"src",
")",
"dst",
",",
"dst_is_storage",
"=",
"format_and... | Copies a source file to a destination file.
Equivalent to "shutil.copyfile".
Source and destination can also be binary opened file-like objects.
Args:
src (path-like object or file-like object): Source file.
dst (path-like object or file-like object): Destination file.
follow_symlinks (bool): Follow symlinks.
Not supported on cloud storage objects.
Raises:
IOError: Destination directory not found. | [
"Copies",
"a",
"source",
"file",
"to",
"a",
"destination",
"file",
"."
] | 1cc1f8fdf5394d92918b7bae2bfa682169ccc48c | https://github.com/Accelize/pycosio/blob/1cc1f8fdf5394d92918b7bae2bfa682169ccc48c/pycosio/_core/functions_shutil.py#L121-L158 | train | 47,993 |
Accelize/pycosio | pycosio/storage/s3.py | _handle_client_error | def _handle_client_error():
"""
Handle boto exception and convert to class
IO exceptions
Raises:
OSError subclasses: IO error.
"""
try:
yield
except _ClientError as exception:
error = exception.response['Error']
if error['Code'] in _ERROR_CODES:
raise _ERROR_CODES[error['Code']](error['Message'])
raise | python | def _handle_client_error():
"""
Handle boto exception and convert to class
IO exceptions
Raises:
OSError subclasses: IO error.
"""
try:
yield
except _ClientError as exception:
error = exception.response['Error']
if error['Code'] in _ERROR_CODES:
raise _ERROR_CODES[error['Code']](error['Message'])
raise | [
"def",
"_handle_client_error",
"(",
")",
":",
"try",
":",
"yield",
"except",
"_ClientError",
"as",
"exception",
":",
"error",
"=",
"exception",
".",
"response",
"[",
"'Error'",
"]",
"if",
"error",
"[",
"'Code'",
"]",
"in",
"_ERROR_CODES",
":",
"raise",
"_E... | Handle boto exception and convert to class
IO exceptions
Raises:
OSError subclasses: IO error. | [
"Handle",
"boto",
"exception",
"and",
"convert",
"to",
"class",
"IO",
"exceptions"
] | 1cc1f8fdf5394d92918b7bae2bfa682169ccc48c | https://github.com/Accelize/pycosio/blob/1cc1f8fdf5394d92918b7bae2bfa682169ccc48c/pycosio/storage/s3.py#L29-L44 | train | 47,994 |
Accelize/pycosio | pycosio/storage/s3.py | _S3System._get_session | def _get_session(self):
"""
S3 Boto3 Session.
Returns:
boto3.session.Session: session
"""
if self._session is None:
self._session = _boto3.session.Session(
**self._storage_parameters.get('session', dict()))
return self._session | python | def _get_session(self):
"""
S3 Boto3 Session.
Returns:
boto3.session.Session: session
"""
if self._session is None:
self._session = _boto3.session.Session(
**self._storage_parameters.get('session', dict()))
return self._session | [
"def",
"_get_session",
"(",
"self",
")",
":",
"if",
"self",
".",
"_session",
"is",
"None",
":",
"self",
".",
"_session",
"=",
"_boto3",
".",
"session",
".",
"Session",
"(",
"*",
"*",
"self",
".",
"_storage_parameters",
".",
"get",
"(",
"'session'",
","... | S3 Boto3 Session.
Returns:
boto3.session.Session: session | [
"S3",
"Boto3",
"Session",
"."
] | 1cc1f8fdf5394d92918b7bae2bfa682169ccc48c | https://github.com/Accelize/pycosio/blob/1cc1f8fdf5394d92918b7bae2bfa682169ccc48c/pycosio/storage/s3.py#L101-L111 | train | 47,995 |
Accelize/pycosio | pycosio/storage/s3.py | _S3System._get_client | def _get_client(self):
"""
S3 Boto3 client
Returns:
boto3.session.Session.client: client
"""
client_kwargs = self._storage_parameters.get('client', dict())
# Handles unsecure mode
if self._unsecure:
client_kwargs = client_kwargs.copy()
client_kwargs['use_ssl'] = False
return self._get_session().client("s3", **client_kwargs) | python | def _get_client(self):
"""
S3 Boto3 client
Returns:
boto3.session.Session.client: client
"""
client_kwargs = self._storage_parameters.get('client', dict())
# Handles unsecure mode
if self._unsecure:
client_kwargs = client_kwargs.copy()
client_kwargs['use_ssl'] = False
return self._get_session().client("s3", **client_kwargs) | [
"def",
"_get_client",
"(",
"self",
")",
":",
"client_kwargs",
"=",
"self",
".",
"_storage_parameters",
".",
"get",
"(",
"'client'",
",",
"dict",
"(",
")",
")",
"# Handles unsecure mode",
"if",
"self",
".",
"_unsecure",
":",
"client_kwargs",
"=",
"client_kwargs... | S3 Boto3 client
Returns:
boto3.session.Session.client: client | [
"S3",
"Boto3",
"client"
] | 1cc1f8fdf5394d92918b7bae2bfa682169ccc48c | https://github.com/Accelize/pycosio/blob/1cc1f8fdf5394d92918b7bae2bfa682169ccc48c/pycosio/storage/s3.py#L113-L127 | train | 47,996 |
Accelize/pycosio | pycosio/storage/azure.py | _handle_azure_exception | def _handle_azure_exception():
"""
Handles Azure exception and convert to class IO exceptions
Raises:
OSError subclasses: IO error.
"""
try:
yield
except _AzureHttpError as exception:
if exception.status_code in _ERROR_CODES:
raise _ERROR_CODES[exception.status_code](str(exception))
raise | python | def _handle_azure_exception():
"""
Handles Azure exception and convert to class IO exceptions
Raises:
OSError subclasses: IO error.
"""
try:
yield
except _AzureHttpError as exception:
if exception.status_code in _ERROR_CODES:
raise _ERROR_CODES[exception.status_code](str(exception))
raise | [
"def",
"_handle_azure_exception",
"(",
")",
":",
"try",
":",
"yield",
"except",
"_AzureHttpError",
"as",
"exception",
":",
"if",
"exception",
".",
"status_code",
"in",
"_ERROR_CODES",
":",
"raise",
"_ERROR_CODES",
"[",
"exception",
".",
"status_code",
"]",
"(",
... | Handles Azure exception and convert to class IO exceptions
Raises:
OSError subclasses: IO error. | [
"Handles",
"Azure",
"exception",
"and",
"convert",
"to",
"class",
"IO",
"exceptions"
] | 1cc1f8fdf5394d92918b7bae2bfa682169ccc48c | https://github.com/Accelize/pycosio/blob/1cc1f8fdf5394d92918b7bae2bfa682169ccc48c/pycosio/storage/azure.py#L32-L45 | train | 47,997 |
Accelize/pycosio | pycosio/storage/azure.py | _properties_model_to_dict | def _properties_model_to_dict(properties):
"""
Convert properties model to dict.
Args:
properties: Properties model.
Returns:
dict: Converted model.
"""
result = {}
for attr in properties.__dict__:
value = getattr(properties, attr)
if hasattr(value, '__module__') and 'models' in value.__module__:
value = _properties_model_to_dict(value)
if not (value is None or (isinstance(value, dict) and not value)):
result[attr] = value
return result | python | def _properties_model_to_dict(properties):
"""
Convert properties model to dict.
Args:
properties: Properties model.
Returns:
dict: Converted model.
"""
result = {}
for attr in properties.__dict__:
value = getattr(properties, attr)
if hasattr(value, '__module__') and 'models' in value.__module__:
value = _properties_model_to_dict(value)
if not (value is None or (isinstance(value, dict) and not value)):
result[attr] = value
return result | [
"def",
"_properties_model_to_dict",
"(",
"properties",
")",
":",
"result",
"=",
"{",
"}",
"for",
"attr",
"in",
"properties",
".",
"__dict__",
":",
"value",
"=",
"getattr",
"(",
"properties",
",",
"attr",
")",
"if",
"hasattr",
"(",
"value",
",",
"'__module_... | Convert properties model to dict.
Args:
properties: Properties model.
Returns:
dict: Converted model. | [
"Convert",
"properties",
"model",
"to",
"dict",
"."
] | 1cc1f8fdf5394d92918b7bae2bfa682169ccc48c | https://github.com/Accelize/pycosio/blob/1cc1f8fdf5394d92918b7bae2bfa682169ccc48c/pycosio/storage/azure.py#L48-L68 | train | 47,998 |
Accelize/pycosio | pycosio/storage/azure.py | _AzureBaseSystem._get_endpoint | def _get_endpoint(self, sub_domain):
"""
Get endpoint information from storage parameters.
Update system with endpoint information and return information required
to define roots.
Args:
self (pycosio._core.io_system.SystemBase subclass): System.
sub_domain (str): Azure storage sub-domain.
Returns:
tuple of str: account_name, endpoint_suffix
"""
storage_parameters = self._storage_parameters or dict()
account_name = storage_parameters.get('account_name')
if not account_name:
raise ValueError('"account_name" is required for Azure storage')
suffix = storage_parameters.get(
'endpoint_suffix', 'core.windows.net')
self._endpoint = 'http%s://%s.%s.%s' % (
'' if self._unsecure else 's', account_name, sub_domain, suffix)
return account_name, suffix.replace('.', r'\.') | python | def _get_endpoint(self, sub_domain):
"""
Get endpoint information from storage parameters.
Update system with endpoint information and return information required
to define roots.
Args:
self (pycosio._core.io_system.SystemBase subclass): System.
sub_domain (str): Azure storage sub-domain.
Returns:
tuple of str: account_name, endpoint_suffix
"""
storage_parameters = self._storage_parameters or dict()
account_name = storage_parameters.get('account_name')
if not account_name:
raise ValueError('"account_name" is required for Azure storage')
suffix = storage_parameters.get(
'endpoint_suffix', 'core.windows.net')
self._endpoint = 'http%s://%s.%s.%s' % (
'' if self._unsecure else 's', account_name, sub_domain, suffix)
return account_name, suffix.replace('.', r'\.') | [
"def",
"_get_endpoint",
"(",
"self",
",",
"sub_domain",
")",
":",
"storage_parameters",
"=",
"self",
".",
"_storage_parameters",
"or",
"dict",
"(",
")",
"account_name",
"=",
"storage_parameters",
".",
"get",
"(",
"'account_name'",
")",
"if",
"not",
"account_name... | Get endpoint information from storage parameters.
Update system with endpoint information and return information required
to define roots.
Args:
self (pycosio._core.io_system.SystemBase subclass): System.
sub_domain (str): Azure storage sub-domain.
Returns:
tuple of str: account_name, endpoint_suffix | [
"Get",
"endpoint",
"information",
"from",
"storage",
"parameters",
"."
] | 1cc1f8fdf5394d92918b7bae2bfa682169ccc48c | https://github.com/Accelize/pycosio/blob/1cc1f8fdf5394d92918b7bae2bfa682169ccc48c/pycosio/storage/azure.py#L112-L138 | train | 47,999 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.