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
casacore/python-casacore
casacore/images/image.py
image.getdata
def getdata(self, blc=(), trc=(), inc=()): """Get image data. Using the arguments blc (bottom left corner), trc (top right corner), and inc (stride) it is possible to get a data slice. The data is returned as a numpy array. Its dimensionality is the same as the dimensionality of the image, even if an axis has length 1. """ return self._getdata(self._adjustBlc(blc), self._adjustTrc(trc), self._adjustInc(inc))
python
def getdata(self, blc=(), trc=(), inc=()): """Get image data. Using the arguments blc (bottom left corner), trc (top right corner), and inc (stride) it is possible to get a data slice. The data is returned as a numpy array. Its dimensionality is the same as the dimensionality of the image, even if an axis has length 1. """ return self._getdata(self._adjustBlc(blc), self._adjustTrc(trc), self._adjustInc(inc))
[ "def", "getdata", "(", "self", ",", "blc", "=", "(", ")", ",", "trc", "=", "(", ")", ",", "inc", "=", "(", ")", ")", ":", "return", "self", ".", "_getdata", "(", "self", ".", "_adjustBlc", "(", "blc", ")", ",", "self", ".", "_adjustTrc", "(", ...
Get image data. Using the arguments blc (bottom left corner), trc (top right corner), and inc (stride) it is possible to get a data slice. The data is returned as a numpy array. Its dimensionality is the same as the dimensionality of the image, even if an axis has length 1.
[ "Get", "image", "data", "." ]
975510861ea005f7919dd9e438b5f98a1682eebe
https://github.com/casacore/python-casacore/blob/975510861ea005f7919dd9e438b5f98a1682eebe/casacore/images/image.py#L292-L304
train
23,000
casacore/python-casacore
casacore/images/image.py
image.getmask
def getmask(self, blc=(), trc=(), inc=()): """Get image mask. Using the arguments blc (bottom left corner), trc (top right corner), and inc (stride) it is possible to get a mask slice. Not all axes need to be specified. Missing values default to begin, end, and 1. The mask is returned as a numpy array. Its dimensionality is the same as the dimensionality of the image, even if an axis has length 1. Note that the casacore images use the convention that a mask value True means good and False means bad. However, numpy uses the opposite. Therefore the mask will be negated, so it can be used directly in numpy operations. If the image has no mask, an array will be returned with all values set to False. """ return numpy.logical_not(self._getmask(self._adjustBlc(blc), self._adjustTrc(trc), self._adjustInc(inc)))
python
def getmask(self, blc=(), trc=(), inc=()): """Get image mask. Using the arguments blc (bottom left corner), trc (top right corner), and inc (stride) it is possible to get a mask slice. Not all axes need to be specified. Missing values default to begin, end, and 1. The mask is returned as a numpy array. Its dimensionality is the same as the dimensionality of the image, even if an axis has length 1. Note that the casacore images use the convention that a mask value True means good and False means bad. However, numpy uses the opposite. Therefore the mask will be negated, so it can be used directly in numpy operations. If the image has no mask, an array will be returned with all values set to False. """ return numpy.logical_not(self._getmask(self._adjustBlc(blc), self._adjustTrc(trc), self._adjustInc(inc)))
[ "def", "getmask", "(", "self", ",", "blc", "=", "(", ")", ",", "trc", "=", "(", ")", ",", "inc", "=", "(", ")", ")", ":", "return", "numpy", ".", "logical_not", "(", "self", ".", "_getmask", "(", "self", ".", "_adjustBlc", "(", "blc", ")", ",",...
Get image mask. Using the arguments blc (bottom left corner), trc (top right corner), and inc (stride) it is possible to get a mask slice. Not all axes need to be specified. Missing values default to begin, end, and 1. The mask is returned as a numpy array. Its dimensionality is the same as the dimensionality of the image, even if an axis has length 1. Note that the casacore images use the convention that a mask value True means good and False means bad. However, numpy uses the opposite. Therefore the mask will be negated, so it can be used directly in numpy operations. If the image has no mask, an array will be returned with all values set to False.
[ "Get", "image", "mask", "." ]
975510861ea005f7919dd9e438b5f98a1682eebe
https://github.com/casacore/python-casacore/blob/975510861ea005f7919dd9e438b5f98a1682eebe/casacore/images/image.py#L307-L327
train
23,001
casacore/python-casacore
casacore/images/image.py
image.get
def get(self, blc=(), trc=(), inc=()): """Get image data and mask. Get the image data and mask (see ::func:`getdata` and :func:`getmask`) as a numpy masked array. """ return nma.masked_array(self.getdata(blc, trc, inc), self.getmask(blc, trc, inc))
python
def get(self, blc=(), trc=(), inc=()): """Get image data and mask. Get the image data and mask (see ::func:`getdata` and :func:`getmask`) as a numpy masked array. """ return nma.masked_array(self.getdata(blc, trc, inc), self.getmask(blc, trc, inc))
[ "def", "get", "(", "self", ",", "blc", "=", "(", ")", ",", "trc", "=", "(", ")", ",", "inc", "=", "(", ")", ")", ":", "return", "nma", ".", "masked_array", "(", "self", ".", "getdata", "(", "blc", ",", "trc", ",", "inc", ")", ",", "self", "...
Get image data and mask. Get the image data and mask (see ::func:`getdata` and :func:`getmask`) as a numpy masked array.
[ "Get", "image", "data", "and", "mask", "." ]
975510861ea005f7919dd9e438b5f98a1682eebe
https://github.com/casacore/python-casacore/blob/975510861ea005f7919dd9e438b5f98a1682eebe/casacore/images/image.py#L330-L338
train
23,002
casacore/python-casacore
casacore/images/image.py
image.putdata
def putdata(self, value, blc=(), trc=(), inc=()): """Put image data. Using the arguments blc (bottom left corner), trc (top right corner), and inc (stride) it is possible to put a data slice. Not all axes need to be specified. Missing values default to begin, end, and 1. The data should be a numpy array. Its dimensionality must be the same as the dimensionality of the image. """ return self._putdata(value, self._adjustBlc(blc), self._adjustInc(inc))
python
def putdata(self, value, blc=(), trc=(), inc=()): """Put image data. Using the arguments blc (bottom left corner), trc (top right corner), and inc (stride) it is possible to put a data slice. Not all axes need to be specified. Missing values default to begin, end, and 1. The data should be a numpy array. Its dimensionality must be the same as the dimensionality of the image. """ return self._putdata(value, self._adjustBlc(blc), self._adjustInc(inc))
[ "def", "putdata", "(", "self", ",", "value", ",", "blc", "=", "(", ")", ",", "trc", "=", "(", ")", ",", "inc", "=", "(", ")", ")", ":", "return", "self", ".", "_putdata", "(", "value", ",", "self", ".", "_adjustBlc", "(", "blc", ")", ",", "se...
Put image data. Using the arguments blc (bottom left corner), trc (top right corner), and inc (stride) it is possible to put a data slice. Not all axes need to be specified. Missing values default to begin, end, and 1. The data should be a numpy array. Its dimensionality must be the same as the dimensionality of the image.
[ "Put", "image", "data", "." ]
975510861ea005f7919dd9e438b5f98a1682eebe
https://github.com/casacore/python-casacore/blob/975510861ea005f7919dd9e438b5f98a1682eebe/casacore/images/image.py#L340-L352
train
23,003
casacore/python-casacore
casacore/images/image.py
image.putmask
def putmask(self, value, blc=(), trc=(), inc=()): """Put image mask. Using the arguments blc (bottom left corner), trc (top right corner), and inc (stride) it is possible to put a data slice. Not all axes need to be specified. Missing values default to begin, end, and 1. The data should be a numpy array. Its dimensionality must be the same as the dimensionality of the image. Note that the casacore images use the convention that a mask value True means good and False means bad. However, numpy uses the opposite. Therefore the mask will be negated, so a numoy masked can be given directly. The mask is not written if the image has no mask and if it the entire mask is False. In that case the mask most likely comes from a getmask operation on an image without a mask. """ # casa and numpy have opposite flags return self._putmask(~value, self._adjustBlc(blc), self._adjustInc(inc))
python
def putmask(self, value, blc=(), trc=(), inc=()): """Put image mask. Using the arguments blc (bottom left corner), trc (top right corner), and inc (stride) it is possible to put a data slice. Not all axes need to be specified. Missing values default to begin, end, and 1. The data should be a numpy array. Its dimensionality must be the same as the dimensionality of the image. Note that the casacore images use the convention that a mask value True means good and False means bad. However, numpy uses the opposite. Therefore the mask will be negated, so a numoy masked can be given directly. The mask is not written if the image has no mask and if it the entire mask is False. In that case the mask most likely comes from a getmask operation on an image without a mask. """ # casa and numpy have opposite flags return self._putmask(~value, self._adjustBlc(blc), self._adjustInc(inc))
[ "def", "putmask", "(", "self", ",", "value", ",", "blc", "=", "(", ")", ",", "trc", "=", "(", ")", ",", "inc", "=", "(", ")", ")", ":", "# casa and numpy have opposite flags", "return", "self", ".", "_putmask", "(", "~", "value", ",", "self", ".", ...
Put image mask. Using the arguments blc (bottom left corner), trc (top right corner), and inc (stride) it is possible to put a data slice. Not all axes need to be specified. Missing values default to begin, end, and 1. The data should be a numpy array. Its dimensionality must be the same as the dimensionality of the image. Note that the casacore images use the convention that a mask value True means good and False means bad. However, numpy uses the opposite. Therefore the mask will be negated, so a numoy masked can be given directly. The mask is not written if the image has no mask and if it the entire mask is False. In that case the mask most likely comes from a getmask operation on an image without a mask.
[ "Put", "image", "mask", "." ]
975510861ea005f7919dd9e438b5f98a1682eebe
https://github.com/casacore/python-casacore/blob/975510861ea005f7919dd9e438b5f98a1682eebe/casacore/images/image.py#L354-L375
train
23,004
casacore/python-casacore
casacore/images/image.py
image.put
def put(self, value, blc=(), trc=(), inc=()): """Put image data and mask. Put the image data and optionally the mask (see ::func:`getdata` and :func:`getmask`). If the `value` argument is a numpy masked array, but data and mask will bw written. If it is a normal numpy array, only the data will be written. """ if isinstance(value, nma.MaskedArray): self.putdata(value.data, blc, trc, inc) self.putmask(nma.getmaskarray(value), blc, trc, inc) else: self.putdata(value, blc, trc, inc)
python
def put(self, value, blc=(), trc=(), inc=()): """Put image data and mask. Put the image data and optionally the mask (see ::func:`getdata` and :func:`getmask`). If the `value` argument is a numpy masked array, but data and mask will bw written. If it is a normal numpy array, only the data will be written. """ if isinstance(value, nma.MaskedArray): self.putdata(value.data, blc, trc, inc) self.putmask(nma.getmaskarray(value), blc, trc, inc) else: self.putdata(value, blc, trc, inc)
[ "def", "put", "(", "self", ",", "value", ",", "blc", "=", "(", ")", ",", "trc", "=", "(", ")", ",", "inc", "=", "(", ")", ")", ":", "if", "isinstance", "(", "value", ",", "nma", ".", "MaskedArray", ")", ":", "self", ".", "putdata", "(", "valu...
Put image data and mask. Put the image data and optionally the mask (see ::func:`getdata` and :func:`getmask`). If the `value` argument is a numpy masked array, but data and mask will bw written. If it is a normal numpy array, only the data will be written.
[ "Put", "image", "data", "and", "mask", "." ]
975510861ea005f7919dd9e438b5f98a1682eebe
https://github.com/casacore/python-casacore/blob/975510861ea005f7919dd9e438b5f98a1682eebe/casacore/images/image.py#L377-L391
train
23,005
casacore/python-casacore
casacore/images/image.py
image.subimage
def subimage(self, blc=(), trc=(), inc=(), dropdegenerate=True): """Form a subimage. An image object containing a subset of an image is returned. The arguments blc (bottom left corner), trc (top right corner), and inc (stride) define the subset. Not all axes need to be specified. Missing values default to begin, end, and 1. By default axes with length 1 are left out. A subimage is a so-called virtual image. It is not stored, but only references the original image. It can be made persistent using the :func:`saveas` method. """ return image(self._subimage(self._adjustBlc(blc), self._adjustTrc(trc), self._adjustInc(inc), dropdegenerate))
python
def subimage(self, blc=(), trc=(), inc=(), dropdegenerate=True): """Form a subimage. An image object containing a subset of an image is returned. The arguments blc (bottom left corner), trc (top right corner), and inc (stride) define the subset. Not all axes need to be specified. Missing values default to begin, end, and 1. By default axes with length 1 are left out. A subimage is a so-called virtual image. It is not stored, but only references the original image. It can be made persistent using the :func:`saveas` method. """ return image(self._subimage(self._adjustBlc(blc), self._adjustTrc(trc), self._adjustInc(inc), dropdegenerate))
[ "def", "subimage", "(", "self", ",", "blc", "=", "(", ")", ",", "trc", "=", "(", ")", ",", "inc", "=", "(", ")", ",", "dropdegenerate", "=", "True", ")", ":", "return", "image", "(", "self", ".", "_subimage", "(", "self", ".", "_adjustBlc", "(", ...
Form a subimage. An image object containing a subset of an image is returned. The arguments blc (bottom left corner), trc (top right corner), and inc (stride) define the subset. Not all axes need to be specified. Missing values default to begin, end, and 1. By default axes with length 1 are left out. A subimage is a so-called virtual image. It is not stored, but only references the original image. It can be made persistent using the :func:`saveas` method.
[ "Form", "a", "subimage", "." ]
975510861ea005f7919dd9e438b5f98a1682eebe
https://github.com/casacore/python-casacore/blob/975510861ea005f7919dd9e438b5f98a1682eebe/casacore/images/image.py#L426-L444
train
23,006
casacore/python-casacore
casacore/images/image.py
image.info
def info(self): """Get coordinates, image info, and unit".""" return {'coordinates': self._coordinates(), 'imageinfo': self._imageinfo(), 'miscinfo': self._miscinfo(), 'unit': self._unit() }
python
def info(self): """Get coordinates, image info, and unit".""" return {'coordinates': self._coordinates(), 'imageinfo': self._imageinfo(), 'miscinfo': self._miscinfo(), 'unit': self._unit() }
[ "def", "info", "(", "self", ")", ":", "return", "{", "'coordinates'", ":", "self", ".", "_coordinates", "(", ")", ",", "'imageinfo'", ":", "self", ".", "_imageinfo", "(", ")", ",", "'miscinfo'", ":", "self", ".", "_miscinfo", "(", ")", ",", "'unit'", ...
Get coordinates, image info, and unit".
[ "Get", "coordinates", "image", "info", "and", "unit", "." ]
975510861ea005f7919dd9e438b5f98a1682eebe
https://github.com/casacore/python-casacore/blob/975510861ea005f7919dd9e438b5f98a1682eebe/casacore/images/image.py#L484-L490
train
23,007
casacore/python-casacore
casacore/images/image.py
image.tofits
def tofits(self, filename, overwrite=True, velocity=True, optical=True, bitpix=-32, minpix=1, maxpix=-1): """Write the image to a file in FITS format. `filename` FITS file name `overwrite` If False, an exception is raised if the new image file already exists. Default is True. `velocity` By default a velocity primary spectral axis is written if possible. `optical` If writing a velocity, use the optical definition (otherwise use radio). `bitpix` can be set to -32 (float) or 16 (short) only. When `bitpix` is 16 it will write BSCALE and BZERO into the FITS file. If minPix `minpix` and `maxpix` are used to determine BSCALE and BZERO if `bitpix=16`. If `minpix` is greater than `maxpix` (which is the default), the minimum and maximum pixel values will be determined from the ddta. Oherwise the supplied values will be used and pixels outside that range will be clipped to the minimum and maximum pixel values. Note that this truncation does not occur for `bitpix=-32`. """ return self._tofits(filename, overwrite, velocity, optical, bitpix, minpix, maxpix)
python
def tofits(self, filename, overwrite=True, velocity=True, optical=True, bitpix=-32, minpix=1, maxpix=-1): """Write the image to a file in FITS format. `filename` FITS file name `overwrite` If False, an exception is raised if the new image file already exists. Default is True. `velocity` By default a velocity primary spectral axis is written if possible. `optical` If writing a velocity, use the optical definition (otherwise use radio). `bitpix` can be set to -32 (float) or 16 (short) only. When `bitpix` is 16 it will write BSCALE and BZERO into the FITS file. If minPix `minpix` and `maxpix` are used to determine BSCALE and BZERO if `bitpix=16`. If `minpix` is greater than `maxpix` (which is the default), the minimum and maximum pixel values will be determined from the ddta. Oherwise the supplied values will be used and pixels outside that range will be clipped to the minimum and maximum pixel values. Note that this truncation does not occur for `bitpix=-32`. """ return self._tofits(filename, overwrite, velocity, optical, bitpix, minpix, maxpix)
[ "def", "tofits", "(", "self", ",", "filename", ",", "overwrite", "=", "True", ",", "velocity", "=", "True", ",", "optical", "=", "True", ",", "bitpix", "=", "-", "32", ",", "minpix", "=", "1", ",", "maxpix", "=", "-", "1", ")", ":", "return", "se...
Write the image to a file in FITS format. `filename` FITS file name `overwrite` If False, an exception is raised if the new image file already exists. Default is True. `velocity` By default a velocity primary spectral axis is written if possible. `optical` If writing a velocity, use the optical definition (otherwise use radio). `bitpix` can be set to -32 (float) or 16 (short) only. When `bitpix` is 16 it will write BSCALE and BZERO into the FITS file. If minPix `minpix` and `maxpix` are used to determine BSCALE and BZERO if `bitpix=16`. If `minpix` is greater than `maxpix` (which is the default), the minimum and maximum pixel values will be determined from the ddta. Oherwise the supplied values will be used and pixels outside that range will be clipped to the minimum and maximum pixel values. Note that this truncation does not occur for `bitpix=-32`.
[ "Write", "the", "image", "to", "a", "file", "in", "FITS", "format", "." ]
975510861ea005f7919dd9e438b5f98a1682eebe
https://github.com/casacore/python-casacore/blob/975510861ea005f7919dd9e438b5f98a1682eebe/casacore/images/image.py#L492-L519
train
23,008
casacore/python-casacore
casacore/images/image.py
image.saveas
def saveas(self, filename, overwrite=True, hdf5=False, copymask=True, newmaskname="", newtileshape=()): """Write the image to disk. Note that the created disk file is a snapshot, so it is not updated for possible later changes in the image object. `overwrite` If False, an exception is raised if the new image file already exists. Default is True. `ashdf5` If True, the image is created in HDF5 format, otherwise in casacore format. Default is casacore format. `copymask` By default the mask is written as well if the image has a mask. 'newmaskname` If the mask is written, the name is the same the original or `mask0` if the original mask has no name. Using this argument a different mask name can be given. `tileshape` Advanced users can give a new tile shape. See the :mod:`tables` module for more information about Tiled Storage Managers. """ self._saveas(filename, overwrite, hdf5, copymask, newmaskname, newtileshape)
python
def saveas(self, filename, overwrite=True, hdf5=False, copymask=True, newmaskname="", newtileshape=()): """Write the image to disk. Note that the created disk file is a snapshot, so it is not updated for possible later changes in the image object. `overwrite` If False, an exception is raised if the new image file already exists. Default is True. `ashdf5` If True, the image is created in HDF5 format, otherwise in casacore format. Default is casacore format. `copymask` By default the mask is written as well if the image has a mask. 'newmaskname` If the mask is written, the name is the same the original or `mask0` if the original mask has no name. Using this argument a different mask name can be given. `tileshape` Advanced users can give a new tile shape. See the :mod:`tables` module for more information about Tiled Storage Managers. """ self._saveas(filename, overwrite, hdf5, copymask, newmaskname, newtileshape)
[ "def", "saveas", "(", "self", ",", "filename", ",", "overwrite", "=", "True", ",", "hdf5", "=", "False", ",", "copymask", "=", "True", ",", "newmaskname", "=", "\"\"", ",", "newtileshape", "=", "(", ")", ")", ":", "self", ".", "_saveas", "(", "filena...
Write the image to disk. Note that the created disk file is a snapshot, so it is not updated for possible later changes in the image object. `overwrite` If False, an exception is raised if the new image file already exists. Default is True. `ashdf5` If True, the image is created in HDF5 format, otherwise in casacore format. Default is casacore format. `copymask` By default the mask is written as well if the image has a mask. 'newmaskname` If the mask is written, the name is the same the original or `mask0` if the original mask has no name. Using this argument a different mask name can be given. `tileshape` Advanced users can give a new tile shape. See the :mod:`tables` module for more information about Tiled Storage Managers.
[ "Write", "the", "image", "to", "disk", "." ]
975510861ea005f7919dd9e438b5f98a1682eebe
https://github.com/casacore/python-casacore/blob/975510861ea005f7919dd9e438b5f98a1682eebe/casacore/images/image.py#L521-L547
train
23,009
casacore/python-casacore
casacore/images/image.py
image.statistics
def statistics(self, axes=(), minmaxvalues=(), exclude=False, robust=True): """Calculate statistics for the image. Statistics are returned in a dict for the given axes. E.g. if axes [0,1] is given in a 3-dim image, the statistics are calculated for each plane along the 3rd axis. By default statistics are calculated for the entire image. `minmaxvalues` can be given to include or exclude pixels with values in the given range. If only one value is given, min=-abs(val) and max=abs(val). By default robust statistics (Median, MedAbsDevMed, and Quartile) are calculated too. """ return self._statistics(self._adaptAxes(axes), "", minmaxvalues, exclude, robust)
python
def statistics(self, axes=(), minmaxvalues=(), exclude=False, robust=True): """Calculate statistics for the image. Statistics are returned in a dict for the given axes. E.g. if axes [0,1] is given in a 3-dim image, the statistics are calculated for each plane along the 3rd axis. By default statistics are calculated for the entire image. `minmaxvalues` can be given to include or exclude pixels with values in the given range. If only one value is given, min=-abs(val) and max=abs(val). By default robust statistics (Median, MedAbsDevMed, and Quartile) are calculated too. """ return self._statistics(self._adaptAxes(axes), "", minmaxvalues, exclude, robust)
[ "def", "statistics", "(", "self", ",", "axes", "=", "(", ")", ",", "minmaxvalues", "=", "(", ")", ",", "exclude", "=", "False", ",", "robust", "=", "True", ")", ":", "return", "self", ".", "_statistics", "(", "self", ".", "_adaptAxes", "(", "axes", ...
Calculate statistics for the image. Statistics are returned in a dict for the given axes. E.g. if axes [0,1] is given in a 3-dim image, the statistics are calculated for each plane along the 3rd axis. By default statistics are calculated for the entire image. `minmaxvalues` can be given to include or exclude pixels with values in the given range. If only one value is given, min=-abs(val) and max=abs(val). By default robust statistics (Median, MedAbsDevMed, and Quartile) are calculated too.
[ "Calculate", "statistics", "for", "the", "image", "." ]
975510861ea005f7919dd9e438b5f98a1682eebe
https://github.com/casacore/python-casacore/blob/975510861ea005f7919dd9e438b5f98a1682eebe/casacore/images/image.py#L549-L565
train
23,010
casacore/python-casacore
casacore/images/image.py
image.regrid
def regrid(self, axes, coordsys, outname="", overwrite=True, outshape=(), interpolation="linear", decimate=10, replicate=False, refchange=True, forceregrid=False): """Regrid the image to a new image object. Regrid the image on the given axes to the given coordinate system. The output is stored in the given file; it no file name is given a temporary image is made. If the output shape is empty, the old shape is used. `replicate=True` means replication rather than regridding. """ return image(self._regrid(self._adaptAxes(axes), outname, overwrite, outshape, coordsys.dict(), interpolation, decimate, replicate, refchange, forceregrid))
python
def regrid(self, axes, coordsys, outname="", overwrite=True, outshape=(), interpolation="linear", decimate=10, replicate=False, refchange=True, forceregrid=False): """Regrid the image to a new image object. Regrid the image on the given axes to the given coordinate system. The output is stored in the given file; it no file name is given a temporary image is made. If the output shape is empty, the old shape is used. `replicate=True` means replication rather than regridding. """ return image(self._regrid(self._adaptAxes(axes), outname, overwrite, outshape, coordsys.dict(), interpolation, decimate, replicate, refchange, forceregrid))
[ "def", "regrid", "(", "self", ",", "axes", ",", "coordsys", ",", "outname", "=", "\"\"", ",", "overwrite", "=", "True", ",", "outshape", "=", "(", ")", ",", "interpolation", "=", "\"linear\"", ",", "decimate", "=", "10", ",", "replicate", "=", "False",...
Regrid the image to a new image object. Regrid the image on the given axes to the given coordinate system. The output is stored in the given file; it no file name is given a temporary image is made. If the output shape is empty, the old shape is used. `replicate=True` means replication rather than regridding.
[ "Regrid", "the", "image", "to", "a", "new", "image", "object", "." ]
975510861ea005f7919dd9e438b5f98a1682eebe
https://github.com/casacore/python-casacore/blob/975510861ea005f7919dd9e438b5f98a1682eebe/casacore/images/image.py#L567-L584
train
23,011
casacore/python-casacore
casacore/images/image.py
image.view
def view(self, tempname='/tmp/tempimage'): """Display the image using casaviewer. If the image is not persistent, a copy will be made that the user has to delete once viewing has finished. The name of the copy can be given in argument `tempname`. Default is '/tmp/tempimage'. """ import os # Test if casaviewer can be found. # On OS-X 'which' always returns 0, so use test on top of it. if os.system('test -x `which casaviewer` > /dev/null 2>&1') == 0: six.print_("Starting casaviewer in the background ...") self.unlock() if self.ispersistent(): os.system('casaviewer ' + self.name() + ' &') elif len(tempname) > 0: six.print_(" making a persistent copy in " + tempname) six.print_(" which should be deleted after the viewer has ended") self.saveas(tempname) os.system('casaviewer ' + tempname + ' &') else: six.print_("Cannot view because the image is in memory only.") six.print_("You can browse a persistent copy of the image like:") six.print_(" t.view('/tmp/tempimage')") else: six.print_("casaviewer cannot be found")
python
def view(self, tempname='/tmp/tempimage'): """Display the image using casaviewer. If the image is not persistent, a copy will be made that the user has to delete once viewing has finished. The name of the copy can be given in argument `tempname`. Default is '/tmp/tempimage'. """ import os # Test if casaviewer can be found. # On OS-X 'which' always returns 0, so use test on top of it. if os.system('test -x `which casaviewer` > /dev/null 2>&1') == 0: six.print_("Starting casaviewer in the background ...") self.unlock() if self.ispersistent(): os.system('casaviewer ' + self.name() + ' &') elif len(tempname) > 0: six.print_(" making a persistent copy in " + tempname) six.print_(" which should be deleted after the viewer has ended") self.saveas(tempname) os.system('casaviewer ' + tempname + ' &') else: six.print_("Cannot view because the image is in memory only.") six.print_("You can browse a persistent copy of the image like:") six.print_(" t.view('/tmp/tempimage')") else: six.print_("casaviewer cannot be found")
[ "def", "view", "(", "self", ",", "tempname", "=", "'/tmp/tempimage'", ")", ":", "import", "os", "# Test if casaviewer can be found.", "# On OS-X 'which' always returns 0, so use test on top of it.", "if", "os", ".", "system", "(", "'test -x `which casaviewer` > /dev/null 2>&1'"...
Display the image using casaviewer. If the image is not persistent, a copy will be made that the user has to delete once viewing has finished. The name of the copy can be given in argument `tempname`. Default is '/tmp/tempimage'.
[ "Display", "the", "image", "using", "casaviewer", "." ]
975510861ea005f7919dd9e438b5f98a1682eebe
https://github.com/casacore/python-casacore/blob/975510861ea005f7919dd9e438b5f98a1682eebe/casacore/images/image.py#L586-L612
train
23,012
casacore/python-casacore
setup.py
find_library_file
def find_library_file(libname): """ Try to get the directory of the specified library. It adds to the search path the library paths given to distutil's build_ext. """ # Use a dummy argument parser to get user specified library dirs parser = argparse.ArgumentParser(add_help=False) parser.add_argument("--library-dirs", "-L", default='') args, unknown = parser.parse_known_args() user_lib_dirs = args.library_dirs.split(':') # Append default search path (not a complete list) lib_dirs = user_lib_dirs + [os.path.join(sys.prefix, 'lib'), '/usr/local/lib', '/usr/lib', '/usr/lib/x86_64-linux-gnu'] compiler = ccompiler.new_compiler() return compiler.find_library_file(lib_dirs, libname)
python
def find_library_file(libname): """ Try to get the directory of the specified library. It adds to the search path the library paths given to distutil's build_ext. """ # Use a dummy argument parser to get user specified library dirs parser = argparse.ArgumentParser(add_help=False) parser.add_argument("--library-dirs", "-L", default='') args, unknown = parser.parse_known_args() user_lib_dirs = args.library_dirs.split(':') # Append default search path (not a complete list) lib_dirs = user_lib_dirs + [os.path.join(sys.prefix, 'lib'), '/usr/local/lib', '/usr/lib', '/usr/lib/x86_64-linux-gnu'] compiler = ccompiler.new_compiler() return compiler.find_library_file(lib_dirs, libname)
[ "def", "find_library_file", "(", "libname", ")", ":", "# Use a dummy argument parser to get user specified library dirs", "parser", "=", "argparse", ".", "ArgumentParser", "(", "add_help", "=", "False", ")", "parser", ".", "add_argument", "(", "\"--library-dirs\"", ",", ...
Try to get the directory of the specified library. It adds to the search path the library paths given to distutil's build_ext.
[ "Try", "to", "get", "the", "directory", "of", "the", "specified", "library", ".", "It", "adds", "to", "the", "search", "path", "the", "library", "paths", "given", "to", "distutil", "s", "build_ext", "." ]
975510861ea005f7919dd9e438b5f98a1682eebe
https://github.com/casacore/python-casacore/blob/975510861ea005f7919dd9e438b5f98a1682eebe/setup.py#L40-L57
train
23,013
casacore/python-casacore
setup.py
find_boost
def find_boost(): """Find the name of the boost-python library. Returns None if none is found.""" short_version = "{}{}".format(sys.version_info[0], sys.version_info[1]) boostlibnames = ['boost_python-py' + short_version, 'boost_python' + short_version, 'boost_python', ] if sys.version_info[0] == 2: boostlibnames += ["boost_python-mt"] else: boostlibnames += ["boost_python3-mt"] for libboostname in boostlibnames: if find_library_file(libboostname): return libboostname warnings.warn(no_boost_error) return boostlibnames[0]
python
def find_boost(): """Find the name of the boost-python library. Returns None if none is found.""" short_version = "{}{}".format(sys.version_info[0], sys.version_info[1]) boostlibnames = ['boost_python-py' + short_version, 'boost_python' + short_version, 'boost_python', ] if sys.version_info[0] == 2: boostlibnames += ["boost_python-mt"] else: boostlibnames += ["boost_python3-mt"] for libboostname in boostlibnames: if find_library_file(libboostname): return libboostname warnings.warn(no_boost_error) return boostlibnames[0]
[ "def", "find_boost", "(", ")", ":", "short_version", "=", "\"{}{}\"", ".", "format", "(", "sys", ".", "version_info", "[", "0", "]", ",", "sys", ".", "version_info", "[", "1", "]", ")", "boostlibnames", "=", "[", "'boost_python-py'", "+", "short_version", ...
Find the name of the boost-python library. Returns None if none is found.
[ "Find", "the", "name", "of", "the", "boost", "-", "python", "library", ".", "Returns", "None", "if", "none", "is", "found", "." ]
975510861ea005f7919dd9e438b5f98a1682eebe
https://github.com/casacore/python-casacore/blob/975510861ea005f7919dd9e438b5f98a1682eebe/setup.py#L64-L80
train
23,014
casacore/python-casacore
casacore/tables/tablerow.py
_tablerow.put
def put(self, rownr, value, matchingfields=True): """Put the values into the given row. The value should be a dict (as returned by method :func:`get`. The names of the fields in the dict should match the names of the columns used in the `tablerow` object. `matchingfields=True` means that the value may contain more fields and only fields matching a column name will be used. """ self._put(rownr, value, matchingfields)
python
def put(self, rownr, value, matchingfields=True): """Put the values into the given row. The value should be a dict (as returned by method :func:`get`. The names of the fields in the dict should match the names of the columns used in the `tablerow` object. `matchingfields=True` means that the value may contain more fields and only fields matching a column name will be used. """ self._put(rownr, value, matchingfields)
[ "def", "put", "(", "self", ",", "rownr", ",", "value", ",", "matchingfields", "=", "True", ")", ":", "self", ".", "_put", "(", "rownr", ",", "value", ",", "matchingfields", ")" ]
Put the values into the given row. The value should be a dict (as returned by method :func:`get`. The names of the fields in the dict should match the names of the columns used in the `tablerow` object. `matchingfields=True` means that the value may contain more fields and only fields matching a column name will be used.
[ "Put", "the", "values", "into", "the", "given", "row", "." ]
975510861ea005f7919dd9e438b5f98a1682eebe
https://github.com/casacore/python-casacore/blob/975510861ea005f7919dd9e438b5f98a1682eebe/casacore/tables/tablerow.py#L52-L63
train
23,015
casacore/python-casacore
casacore/quanta/quantity.py
quantity
def quantity(*args): """Create a quantity. This can be from a scalar or vector. Example:: q1 = quantity(1.0, "km/s") q2 = quantity("1km/s") q1 = quantity([1.0,2.0], "km/s") """ if len(args) == 1: if isinstance(args[0], str): # use copy constructor to create quantity from string return Quantity(from_string(args[0])) elif isinstance(args[0], dict): if hasattr(args[0]["value"], "__len__"): return QuantVec(from_dict_v(args[0])) else: return Quantity(from_dict(args[0])) elif isinstance(args[0], Quantity) or isinstance(args[0], QuantVec): return args[0] else: raise TypeError("Invalid argument type for") else: if hasattr(args[0], "__len__"): return QuantVec(*args) else: return Quantity(*args)
python
def quantity(*args): """Create a quantity. This can be from a scalar or vector. Example:: q1 = quantity(1.0, "km/s") q2 = quantity("1km/s") q1 = quantity([1.0,2.0], "km/s") """ if len(args) == 1: if isinstance(args[0], str): # use copy constructor to create quantity from string return Quantity(from_string(args[0])) elif isinstance(args[0], dict): if hasattr(args[0]["value"], "__len__"): return QuantVec(from_dict_v(args[0])) else: return Quantity(from_dict(args[0])) elif isinstance(args[0], Quantity) or isinstance(args[0], QuantVec): return args[0] else: raise TypeError("Invalid argument type for") else: if hasattr(args[0], "__len__"): return QuantVec(*args) else: return Quantity(*args)
[ "def", "quantity", "(", "*", "args", ")", ":", "if", "len", "(", "args", ")", "==", "1", ":", "if", "isinstance", "(", "args", "[", "0", "]", ",", "str", ")", ":", "# use copy constructor to create quantity from string", "return", "Quantity", "(", "from_st...
Create a quantity. This can be from a scalar or vector. Example:: q1 = quantity(1.0, "km/s") q2 = quantity("1km/s") q1 = quantity([1.0,2.0], "km/s")
[ "Create", "a", "quantity", ".", "This", "can", "be", "from", "a", "scalar", "or", "vector", "." ]
975510861ea005f7919dd9e438b5f98a1682eebe
https://github.com/casacore/python-casacore/blob/975510861ea005f7919dd9e438b5f98a1682eebe/casacore/quanta/quantity.py#L43-L70
train
23,016
casacore/python-casacore
casacore/util/substitute.py
getvariable
def getvariable(name): """Get the value of a local variable somewhere in the call stack.""" import inspect fr = inspect.currentframe() try: while fr: fr = fr.f_back vars = fr.f_locals if name in vars: return vars[name] except: pass return None
python
def getvariable(name): """Get the value of a local variable somewhere in the call stack.""" import inspect fr = inspect.currentframe() try: while fr: fr = fr.f_back vars = fr.f_locals if name in vars: return vars[name] except: pass return None
[ "def", "getvariable", "(", "name", ")", ":", "import", "inspect", "fr", "=", "inspect", ".", "currentframe", "(", ")", "try", ":", "while", "fr", ":", "fr", "=", "fr", ".", "f_back", "vars", "=", "fr", ".", "f_locals", "if", "name", "in", "vars", "...
Get the value of a local variable somewhere in the call stack.
[ "Get", "the", "value", "of", "a", "local", "variable", "somewhere", "in", "the", "call", "stack", "." ]
975510861ea005f7919dd9e438b5f98a1682eebe
https://github.com/casacore/python-casacore/blob/975510861ea005f7919dd9e438b5f98a1682eebe/casacore/util/substitute.py#L47-L59
train
23,017
casacore/python-casacore
casacore/util/substitute.py
substitute
def substitute(s, objlist=(), globals={}, locals={}): """Substitute global python variables in a command string. This function parses a string and tries to substitute parts like `$name` by their value. It is uses by :mod:`image` and :mod:`table` to handle image and table objects in a command, but also other variables (integers, strings, etc.) can be substituted. The following rules apply: 1. A name must start with an underscore or alphabetic, followed by zero or more alphanumerics and underscores. 2. String parts enclosed in single or double quotes are literals and are left untouched. Furthermore a $ can be escaped by a backslash, which is useful if an environment variable is used. Note that an extra backslash is required in Python to escape the backslash. The output contains the quotes and backslashes. 3. A variable is looked up in the given local and global namespaces. 4. If the variable `name` has a vector value, its substitution is enclosed in square brackets and separated by commas. 5. A string value is enclosed in double quotes. If the value contains a double quote, that quote is enclosed in single quotes. 6. If the name's value has a type mentioned in the argument `objlist`, it is substituted by `$n` (where n is a sequence number) and its value is added to the objects of that type in `objlist`. 7. If the name is unknown or has an unknown type, it is left untouched. The `objlist` argument is a list of tuples or lists where each tuple or list has three fields: 1. The first field is the object type (e.g. `table`) 2. The second field is a prefix for the sequence number (usually empty). E.g. regions could have prefix 'r' resulting in a substitution like `$r1`. 3. The third field is a list of objects to be substituted. New objects get appended to it. Usually the list is initially empty. Apart from substituting variables, it also substitutes `$(expression)` by the expression result. It correctly handles parentheses and quotes in the expression. For example:: >>> a = 2 >>> b = 3 >>> substitute('$(a+b)+$a') '5+2' >>> substitute('$(a+b+a)') '7' >>> substitute('$((a+b)+$a)') '$((a+b)+$a)' >>> substitute('$((a+b)*(a+b))') '25' >>> substitute('$(len("ab cd( de"))') '9' Substitution is NOT recursive. E.g. if a=1 and b="$a", the result of substitute("$b") is "$a" and not 1. """ # Get the local variables at the caller level if not given. if not locals: locals = getlocals(3) # Initialize some variables. backslash = False dollar = False nparen = 0 name = '' evalstr = '' squote = False dquote = False out = '' # Loop through the entire string. for tmp in s: if backslash: out += tmp backslash = False continue # If a dollar is found, we might have a name or expression. # Alphabetics and underscore are always part of name. if dollar and nparen == 0: if tmp == '_' or ('a' <= tmp <= 'z') or ('A' <= tmp <= 'Z'): name += tmp continue # Numerics are only part if not first character. if '0' <= tmp <= '9' and name != '': name += tmp continue # $( indicates the start of an expression to evaluate. if tmp == '(' and name == '': nparen = 1 evalstr = '' continue # End of name found. Try to substitute. out += substitutename(name, objlist, globals, locals) dollar = False # Handle possible single or double quotes. if tmp == '"' and not squote: dquote = not dquote elif tmp == "'" and not dquote: squote = not squote if not dquote and not squote: # Count the number of balanced parentheses # (outside quoted strings) in the subexpression. if nparen > 0: if tmp == '(': nparen += 1 elif tmp == ')': nparen -= 1 if nparen == 0: # The last closing parenthese is found. # Evaluate the subexpression. # Add the result to the output. out += substituteexpr(evalstr, globals, locals) dollar = False evalstr += tmp continue # Set a switch if we have a dollar (outside quoted # and eval strings). if tmp == '$': dollar = True name = '' continue # No special character; add it to output or evalstr. # Set a switch if we have a backslash. if nparen == 0: out += tmp else: evalstr += tmp if tmp == '\\': backslash = True # The entire string has been handled. # Substitute a possible last name. # Insert a possible incomplete eval string as such. if dollar: out += substitutename(name, objlist, globals, locals) else: if nparen > 0: out += '$(' + evalstr return out
python
def substitute(s, objlist=(), globals={}, locals={}): """Substitute global python variables in a command string. This function parses a string and tries to substitute parts like `$name` by their value. It is uses by :mod:`image` and :mod:`table` to handle image and table objects in a command, but also other variables (integers, strings, etc.) can be substituted. The following rules apply: 1. A name must start with an underscore or alphabetic, followed by zero or more alphanumerics and underscores. 2. String parts enclosed in single or double quotes are literals and are left untouched. Furthermore a $ can be escaped by a backslash, which is useful if an environment variable is used. Note that an extra backslash is required in Python to escape the backslash. The output contains the quotes and backslashes. 3. A variable is looked up in the given local and global namespaces. 4. If the variable `name` has a vector value, its substitution is enclosed in square brackets and separated by commas. 5. A string value is enclosed in double quotes. If the value contains a double quote, that quote is enclosed in single quotes. 6. If the name's value has a type mentioned in the argument `objlist`, it is substituted by `$n` (where n is a sequence number) and its value is added to the objects of that type in `objlist`. 7. If the name is unknown or has an unknown type, it is left untouched. The `objlist` argument is a list of tuples or lists where each tuple or list has three fields: 1. The first field is the object type (e.g. `table`) 2. The second field is a prefix for the sequence number (usually empty). E.g. regions could have prefix 'r' resulting in a substitution like `$r1`. 3. The third field is a list of objects to be substituted. New objects get appended to it. Usually the list is initially empty. Apart from substituting variables, it also substitutes `$(expression)` by the expression result. It correctly handles parentheses and quotes in the expression. For example:: >>> a = 2 >>> b = 3 >>> substitute('$(a+b)+$a') '5+2' >>> substitute('$(a+b+a)') '7' >>> substitute('$((a+b)+$a)') '$((a+b)+$a)' >>> substitute('$((a+b)*(a+b))') '25' >>> substitute('$(len("ab cd( de"))') '9' Substitution is NOT recursive. E.g. if a=1 and b="$a", the result of substitute("$b") is "$a" and not 1. """ # Get the local variables at the caller level if not given. if not locals: locals = getlocals(3) # Initialize some variables. backslash = False dollar = False nparen = 0 name = '' evalstr = '' squote = False dquote = False out = '' # Loop through the entire string. for tmp in s: if backslash: out += tmp backslash = False continue # If a dollar is found, we might have a name or expression. # Alphabetics and underscore are always part of name. if dollar and nparen == 0: if tmp == '_' or ('a' <= tmp <= 'z') or ('A' <= tmp <= 'Z'): name += tmp continue # Numerics are only part if not first character. if '0' <= tmp <= '9' and name != '': name += tmp continue # $( indicates the start of an expression to evaluate. if tmp == '(' and name == '': nparen = 1 evalstr = '' continue # End of name found. Try to substitute. out += substitutename(name, objlist, globals, locals) dollar = False # Handle possible single or double quotes. if tmp == '"' and not squote: dquote = not dquote elif tmp == "'" and not dquote: squote = not squote if not dquote and not squote: # Count the number of balanced parentheses # (outside quoted strings) in the subexpression. if nparen > 0: if tmp == '(': nparen += 1 elif tmp == ')': nparen -= 1 if nparen == 0: # The last closing parenthese is found. # Evaluate the subexpression. # Add the result to the output. out += substituteexpr(evalstr, globals, locals) dollar = False evalstr += tmp continue # Set a switch if we have a dollar (outside quoted # and eval strings). if tmp == '$': dollar = True name = '' continue # No special character; add it to output or evalstr. # Set a switch if we have a backslash. if nparen == 0: out += tmp else: evalstr += tmp if tmp == '\\': backslash = True # The entire string has been handled. # Substitute a possible last name. # Insert a possible incomplete eval string as such. if dollar: out += substitutename(name, objlist, globals, locals) else: if nparen > 0: out += '$(' + evalstr return out
[ "def", "substitute", "(", "s", ",", "objlist", "=", "(", ")", ",", "globals", "=", "{", "}", ",", "locals", "=", "{", "}", ")", ":", "# Get the local variables at the caller level if not given.", "if", "not", "locals", ":", "locals", "=", "getlocals", "(", ...
Substitute global python variables in a command string. This function parses a string and tries to substitute parts like `$name` by their value. It is uses by :mod:`image` and :mod:`table` to handle image and table objects in a command, but also other variables (integers, strings, etc.) can be substituted. The following rules apply: 1. A name must start with an underscore or alphabetic, followed by zero or more alphanumerics and underscores. 2. String parts enclosed in single or double quotes are literals and are left untouched. Furthermore a $ can be escaped by a backslash, which is useful if an environment variable is used. Note that an extra backslash is required in Python to escape the backslash. The output contains the quotes and backslashes. 3. A variable is looked up in the given local and global namespaces. 4. If the variable `name` has a vector value, its substitution is enclosed in square brackets and separated by commas. 5. A string value is enclosed in double quotes. If the value contains a double quote, that quote is enclosed in single quotes. 6. If the name's value has a type mentioned in the argument `objlist`, it is substituted by `$n` (where n is a sequence number) and its value is added to the objects of that type in `objlist`. 7. If the name is unknown or has an unknown type, it is left untouched. The `objlist` argument is a list of tuples or lists where each tuple or list has three fields: 1. The first field is the object type (e.g. `table`) 2. The second field is a prefix for the sequence number (usually empty). E.g. regions could have prefix 'r' resulting in a substitution like `$r1`. 3. The third field is a list of objects to be substituted. New objects get appended to it. Usually the list is initially empty. Apart from substituting variables, it also substitutes `$(expression)` by the expression result. It correctly handles parentheses and quotes in the expression. For example:: >>> a = 2 >>> b = 3 >>> substitute('$(a+b)+$a') '5+2' >>> substitute('$(a+b+a)') '7' >>> substitute('$((a+b)+$a)') '$((a+b)+$a)' >>> substitute('$((a+b)*(a+b))') '25' >>> substitute('$(len("ab cd( de"))') '9' Substitution is NOT recursive. E.g. if a=1 and b="$a", the result of substitute("$b") is "$a" and not 1.
[ "Substitute", "global", "python", "variables", "in", "a", "command", "string", "." ]
975510861ea005f7919dd9e438b5f98a1682eebe
https://github.com/casacore/python-casacore/blob/975510861ea005f7919dd9e438b5f98a1682eebe/casacore/util/substitute.py#L62-L206
train
23,018
casacore/python-casacore
casacore/tables/table.py
taql
def taql(command, style='Python', tables=[], globals={}, locals={}): """Execute a TaQL command and return a table object. A `TaQL <../../doc/199.html>`_ command is an SQL-like command to do a selection of rows and/or columns in a table. The default style used in a TaQL command is python, which means 0-based indexing, C-ordered arrays, and non-inclusive end in ranges. It is possible to use python variables directly in the command using `$var` where `var` is the name of the variable to use. For example:: t = table('3c343.MS') value = 5.1 t1 = taql('select from $t where COL > $value') In this example the table `$t` is replaced by a sequence number (such as `$1`) and `$value` by its value 5.1. The table object of `t` will be appended to a copy of the `tables` argument such that the sequence number inserted matches the table object in the list. The more advanced user can already use `$n` in the query string and supply the associated table object in the `tables` argument (where `n` represents the (n-1)th `tables` element). The :func:`query` command makes use of this feature. The arguments `globals` and `locals` can be used to pass in a dict containing the possible variables used in the TaQL command. They can be obtained with the python functions locals() and globals(). If `locals` is empty, the local variables in the calling function will be used, so normally one does not need to use these arguments. """ # Substitute possible tables given as $name. cmd = command # Copy the tables argument and make sure it is a list tabs = [] for tab in tables: tabs += [tab] try: import casacore.util if len(locals) == 0: # local variables in caller are 3 levels up from getlocals locals = casacore.util.getlocals(3) cmd = casacore.util.substitute(cmd, [(table, '', tabs)], globals, locals) except Exception: pass if style: cmd = 'using style ' + style + ' ' + cmd tab = table(cmd, tabs, _oper=2) result = tab._getcalcresult() # If result is empty, it was a normal TaQL command resulting in a table. # Otherwise it is a record containing calc values. if len(result) == 0: return tab return result['values']
python
def taql(command, style='Python', tables=[], globals={}, locals={}): """Execute a TaQL command and return a table object. A `TaQL <../../doc/199.html>`_ command is an SQL-like command to do a selection of rows and/or columns in a table. The default style used in a TaQL command is python, which means 0-based indexing, C-ordered arrays, and non-inclusive end in ranges. It is possible to use python variables directly in the command using `$var` where `var` is the name of the variable to use. For example:: t = table('3c343.MS') value = 5.1 t1 = taql('select from $t where COL > $value') In this example the table `$t` is replaced by a sequence number (such as `$1`) and `$value` by its value 5.1. The table object of `t` will be appended to a copy of the `tables` argument such that the sequence number inserted matches the table object in the list. The more advanced user can already use `$n` in the query string and supply the associated table object in the `tables` argument (where `n` represents the (n-1)th `tables` element). The :func:`query` command makes use of this feature. The arguments `globals` and `locals` can be used to pass in a dict containing the possible variables used in the TaQL command. They can be obtained with the python functions locals() and globals(). If `locals` is empty, the local variables in the calling function will be used, so normally one does not need to use these arguments. """ # Substitute possible tables given as $name. cmd = command # Copy the tables argument and make sure it is a list tabs = [] for tab in tables: tabs += [tab] try: import casacore.util if len(locals) == 0: # local variables in caller are 3 levels up from getlocals locals = casacore.util.getlocals(3) cmd = casacore.util.substitute(cmd, [(table, '', tabs)], globals, locals) except Exception: pass if style: cmd = 'using style ' + style + ' ' + cmd tab = table(cmd, tabs, _oper=2) result = tab._getcalcresult() # If result is empty, it was a normal TaQL command resulting in a table. # Otherwise it is a record containing calc values. if len(result) == 0: return tab return result['values']
[ "def", "taql", "(", "command", ",", "style", "=", "'Python'", ",", "tables", "=", "[", "]", ",", "globals", "=", "{", "}", ",", "locals", "=", "{", "}", ")", ":", "# Substitute possible tables given as $name.", "cmd", "=", "command", "# Copy the tables argum...
Execute a TaQL command and return a table object. A `TaQL <../../doc/199.html>`_ command is an SQL-like command to do a selection of rows and/or columns in a table. The default style used in a TaQL command is python, which means 0-based indexing, C-ordered arrays, and non-inclusive end in ranges. It is possible to use python variables directly in the command using `$var` where `var` is the name of the variable to use. For example:: t = table('3c343.MS') value = 5.1 t1 = taql('select from $t where COL > $value') In this example the table `$t` is replaced by a sequence number (such as `$1`) and `$value` by its value 5.1. The table object of `t` will be appended to a copy of the `tables` argument such that the sequence number inserted matches the table object in the list. The more advanced user can already use `$n` in the query string and supply the associated table object in the `tables` argument (where `n` represents the (n-1)th `tables` element). The :func:`query` command makes use of this feature. The arguments `globals` and `locals` can be used to pass in a dict containing the possible variables used in the TaQL command. They can be obtained with the python functions locals() and globals(). If `locals` is empty, the local variables in the calling function will be used, so normally one does not need to use these arguments.
[ "Execute", "a", "TaQL", "command", "and", "return", "a", "table", "object", "." ]
975510861ea005f7919dd9e438b5f98a1682eebe
https://github.com/casacore/python-casacore/blob/975510861ea005f7919dd9e438b5f98a1682eebe/casacore/tables/table.py#L104-L162
train
23,019
casacore/python-casacore
casacore/tables/table.py
table.iter
def iter(self, columnnames, order='', sort=True): """Return a tableiter object. :class:`tableiter` lets one iterate over a table by returning in each iteration step a reference table containing equal values for the given columns. By default a sort is done on the given columns to get the correct iteration order. `order` | 'ascending' is iterate in ascending order (is the default). | 'descending' is iterate in descending order. `sort=False` do not sort (because table is already in correct order). For example, iterate by time through a measurementset table:: t = table('3c343.MS') for ts in t.iter('TIME'): print ts.nrows() """ from .tableiter import tableiter return tableiter(self, columnnames, order, sort)
python
def iter(self, columnnames, order='', sort=True): """Return a tableiter object. :class:`tableiter` lets one iterate over a table by returning in each iteration step a reference table containing equal values for the given columns. By default a sort is done on the given columns to get the correct iteration order. `order` | 'ascending' is iterate in ascending order (is the default). | 'descending' is iterate in descending order. `sort=False` do not sort (because table is already in correct order). For example, iterate by time through a measurementset table:: t = table('3c343.MS') for ts in t.iter('TIME'): print ts.nrows() """ from .tableiter import tableiter return tableiter(self, columnnames, order, sort)
[ "def", "iter", "(", "self", ",", "columnnames", ",", "order", "=", "''", ",", "sort", "=", "True", ")", ":", "from", ".", "tableiter", "import", "tableiter", "return", "tableiter", "(", "self", ",", "columnnames", ",", "order", ",", "sort", ")" ]
Return a tableiter object. :class:`tableiter` lets one iterate over a table by returning in each iteration step a reference table containing equal values for the given columns. By default a sort is done on the given columns to get the correct iteration order. `order` | 'ascending' is iterate in ascending order (is the default). | 'descending' is iterate in descending order. `sort=False` do not sort (because table is already in correct order). For example, iterate by time through a measurementset table:: t = table('3c343.MS') for ts in t.iter('TIME'): print ts.nrows()
[ "Return", "a", "tableiter", "object", "." ]
975510861ea005f7919dd9e438b5f98a1682eebe
https://github.com/casacore/python-casacore/blob/975510861ea005f7919dd9e438b5f98a1682eebe/casacore/tables/table.py#L507-L530
train
23,020
casacore/python-casacore
casacore/tables/table.py
table.index
def index(self, columnnames, sort=True): """Return a tableindex object. :class:`tableindex` lets one get the row numbers of the rows holding given values for the columns for which the index is created. It uses an in-memory index on which a binary search is done. By default the table is sorted on the given columns to get the correct index order. For example:: t = table('3c343.MS') tinx = t.index('ANTENNA1') print tinx.rownumbers(0) # print rownrs containing ANTENNA1=0 """ from .tableindex import tableindex return tableindex(self, columnnames, sort)
python
def index(self, columnnames, sort=True): """Return a tableindex object. :class:`tableindex` lets one get the row numbers of the rows holding given values for the columns for which the index is created. It uses an in-memory index on which a binary search is done. By default the table is sorted on the given columns to get the correct index order. For example:: t = table('3c343.MS') tinx = t.index('ANTENNA1') print tinx.rownumbers(0) # print rownrs containing ANTENNA1=0 """ from .tableindex import tableindex return tableindex(self, columnnames, sort)
[ "def", "index", "(", "self", ",", "columnnames", ",", "sort", "=", "True", ")", ":", "from", ".", "tableindex", "import", "tableindex", "return", "tableindex", "(", "self", ",", "columnnames", ",", "sort", ")" ]
Return a tableindex object. :class:`tableindex` lets one get the row numbers of the rows holding given values for the columns for which the index is created. It uses an in-memory index on which a binary search is done. By default the table is sorted on the given columns to get the correct index order. For example:: t = table('3c343.MS') tinx = t.index('ANTENNA1') print tinx.rownumbers(0) # print rownrs containing ANTENNA1=0
[ "Return", "a", "tableindex", "object", "." ]
975510861ea005f7919dd9e438b5f98a1682eebe
https://github.com/casacore/python-casacore/blob/975510861ea005f7919dd9e438b5f98a1682eebe/casacore/tables/table.py#L532-L549
train
23,021
casacore/python-casacore
casacore/tables/table.py
table.toascii
def toascii(self, asciifile, headerfile='', columnnames=(), sep=' ', precision=(), usebrackets=True): """Write the table in ASCII format. It is approximately the inverse of the from-ASCII-contructor. `asciifile` The name of the resulting ASCII file. `headerfile` The name of an optional file containing the header info. If not given or if equal to argument `asciifile`, the headers are written at the beginning of the ASCII file. `columnnames` The names of the columns to be written. If not given or if the first name is empty, all columns are written. `sep` The separator to be used between values. Only the first character of a string is used. If not given or mepty, a blank is used. `precision` For each column the precision can be given. It is only used for columns containing floating point numbers. A value <=0 means using the default which is 9 for single and 18 for double precision. `usebrackets` If True, arrays and records are written enclosed in []. Multi-dimensional arrays have [] per dimension. In this way variable shaped array can be read back correctly. However, it is not supported by :func:`tablefromascii`. If False, records are not written and arrays are written linearly with the shape defined in the header as supported byI :func:`tablefromascii`. Note that columns containing records or variable shaped arrays are ignored, because they cannot be written to ASCII. It is told which columns are ignored. For example:: t = table('3c343.MS') t1 = t.query('ANTENNA1 != ANTENNA2') # do row selection t1.toascii ('3c343.txt') # write selection as ASCII """ msg = self._toascii(asciifile, headerfile, columnnames, sep, precision, usebrackets) if len(msg) > 0: six.print_(msg)
python
def toascii(self, asciifile, headerfile='', columnnames=(), sep=' ', precision=(), usebrackets=True): """Write the table in ASCII format. It is approximately the inverse of the from-ASCII-contructor. `asciifile` The name of the resulting ASCII file. `headerfile` The name of an optional file containing the header info. If not given or if equal to argument `asciifile`, the headers are written at the beginning of the ASCII file. `columnnames` The names of the columns to be written. If not given or if the first name is empty, all columns are written. `sep` The separator to be used between values. Only the first character of a string is used. If not given or mepty, a blank is used. `precision` For each column the precision can be given. It is only used for columns containing floating point numbers. A value <=0 means using the default which is 9 for single and 18 for double precision. `usebrackets` If True, arrays and records are written enclosed in []. Multi-dimensional arrays have [] per dimension. In this way variable shaped array can be read back correctly. However, it is not supported by :func:`tablefromascii`. If False, records are not written and arrays are written linearly with the shape defined in the header as supported byI :func:`tablefromascii`. Note that columns containing records or variable shaped arrays are ignored, because they cannot be written to ASCII. It is told which columns are ignored. For example:: t = table('3c343.MS') t1 = t.query('ANTENNA1 != ANTENNA2') # do row selection t1.toascii ('3c343.txt') # write selection as ASCII """ msg = self._toascii(asciifile, headerfile, columnnames, sep, precision, usebrackets) if len(msg) > 0: six.print_(msg)
[ "def", "toascii", "(", "self", ",", "asciifile", ",", "headerfile", "=", "''", ",", "columnnames", "=", "(", ")", ",", "sep", "=", "' '", ",", "precision", "=", "(", ")", ",", "usebrackets", "=", "True", ")", ":", "msg", "=", "self", ".", "_toascii...
Write the table in ASCII format. It is approximately the inverse of the from-ASCII-contructor. `asciifile` The name of the resulting ASCII file. `headerfile` The name of an optional file containing the header info. If not given or if equal to argument `asciifile`, the headers are written at the beginning of the ASCII file. `columnnames` The names of the columns to be written. If not given or if the first name is empty, all columns are written. `sep` The separator to be used between values. Only the first character of a string is used. If not given or mepty, a blank is used. `precision` For each column the precision can be given. It is only used for columns containing floating point numbers. A value <=0 means using the default which is 9 for single and 18 for double precision. `usebrackets` If True, arrays and records are written enclosed in []. Multi-dimensional arrays have [] per dimension. In this way variable shaped array can be read back correctly. However, it is not supported by :func:`tablefromascii`. If False, records are not written and arrays are written linearly with the shape defined in the header as supported byI :func:`tablefromascii`. Note that columns containing records or variable shaped arrays are ignored, because they cannot be written to ASCII. It is told which columns are ignored. For example:: t = table('3c343.MS') t1 = t.query('ANTENNA1 != ANTENNA2') # do row selection t1.toascii ('3c343.txt') # write selection as ASCII
[ "Write", "the", "table", "in", "ASCII", "format", "." ]
975510861ea005f7919dd9e438b5f98a1682eebe
https://github.com/casacore/python-casacore/blob/975510861ea005f7919dd9e438b5f98a1682eebe/casacore/tables/table.py#L582-L627
train
23,022
casacore/python-casacore
casacore/tables/table.py
table.copy
def copy(self, newtablename, deep=False, valuecopy=False, dminfo={}, endian='aipsrc', memorytable=False, copynorows=False): """Copy the table and return a table object for the copy. It copies all data in the columns and keywords. Besides the table, all its subtables are copied too. By default a shallow copy is made (usually by copying files). It means that the copy of a reference table is also a reference table. Use `deep=True` to make a deep copy which turns a reference table into a normal table. `deep=True` a deep copy of a reference table is made. `valuecopy=True` values are copied, which reorganizes normal tables and removes wasted space. It implies `deep=True`. It is slower than a normal copy. `dminfo` gives the option to specify data managers to change the way columns are stored. This is a dict as returned by method :func:`getdminfo`. `endian` specifies the endianness of the new table when a deep copy is made: | 'little' = as little endian | 'big' = as big endian | 'local' = use the endianness of the machine being used | 'aipsrc' = use as defined in an .aipsrc file (defaults to local) `memorytable=True` do not copy to disk, but to a table kept in memory. `copynorows=True` only copy the column layout and keywords, but no data. For example:: t = table('3c343.MS') t1 = t.query('ANTENNA1 != ANTENNA2') # do row selection t2 = t1.copy ('3c343.sel', True) # make deep copy t2 = t.copy ('new.tab', True, True) # reorganize storage """ t = self._copy(newtablename, memorytable, deep, valuecopy, endian, dminfo, copynorows) # copy returns a Table object, so turn that into table. return table(t, _oper=3)
python
def copy(self, newtablename, deep=False, valuecopy=False, dminfo={}, endian='aipsrc', memorytable=False, copynorows=False): """Copy the table and return a table object for the copy. It copies all data in the columns and keywords. Besides the table, all its subtables are copied too. By default a shallow copy is made (usually by copying files). It means that the copy of a reference table is also a reference table. Use `deep=True` to make a deep copy which turns a reference table into a normal table. `deep=True` a deep copy of a reference table is made. `valuecopy=True` values are copied, which reorganizes normal tables and removes wasted space. It implies `deep=True`. It is slower than a normal copy. `dminfo` gives the option to specify data managers to change the way columns are stored. This is a dict as returned by method :func:`getdminfo`. `endian` specifies the endianness of the new table when a deep copy is made: | 'little' = as little endian | 'big' = as big endian | 'local' = use the endianness of the machine being used | 'aipsrc' = use as defined in an .aipsrc file (defaults to local) `memorytable=True` do not copy to disk, but to a table kept in memory. `copynorows=True` only copy the column layout and keywords, but no data. For example:: t = table('3c343.MS') t1 = t.query('ANTENNA1 != ANTENNA2') # do row selection t2 = t1.copy ('3c343.sel', True) # make deep copy t2 = t.copy ('new.tab', True, True) # reorganize storage """ t = self._copy(newtablename, memorytable, deep, valuecopy, endian, dminfo, copynorows) # copy returns a Table object, so turn that into table. return table(t, _oper=3)
[ "def", "copy", "(", "self", ",", "newtablename", ",", "deep", "=", "False", ",", "valuecopy", "=", "False", ",", "dminfo", "=", "{", "}", ",", "endian", "=", "'aipsrc'", ",", "memorytable", "=", "False", ",", "copynorows", "=", "False", ")", ":", "t"...
Copy the table and return a table object for the copy. It copies all data in the columns and keywords. Besides the table, all its subtables are copied too. By default a shallow copy is made (usually by copying files). It means that the copy of a reference table is also a reference table. Use `deep=True` to make a deep copy which turns a reference table into a normal table. `deep=True` a deep copy of a reference table is made. `valuecopy=True` values are copied, which reorganizes normal tables and removes wasted space. It implies `deep=True`. It is slower than a normal copy. `dminfo` gives the option to specify data managers to change the way columns are stored. This is a dict as returned by method :func:`getdminfo`. `endian` specifies the endianness of the new table when a deep copy is made: | 'little' = as little endian | 'big' = as big endian | 'local' = use the endianness of the machine being used | 'aipsrc' = use as defined in an .aipsrc file (defaults to local) `memorytable=True` do not copy to disk, but to a table kept in memory. `copynorows=True` only copy the column layout and keywords, but no data. For example:: t = table('3c343.MS') t1 = t.query('ANTENNA1 != ANTENNA2') # do row selection t2 = t1.copy ('3c343.sel', True) # make deep copy t2 = t.copy ('new.tab', True, True) # reorganize storage
[ "Copy", "the", "table", "and", "return", "a", "table", "object", "for", "the", "copy", "." ]
975510861ea005f7919dd9e438b5f98a1682eebe
https://github.com/casacore/python-casacore/blob/975510861ea005f7919dd9e438b5f98a1682eebe/casacore/tables/table.py#L638-L679
train
23,023
casacore/python-casacore
casacore/tables/table.py
table.copyrows
def copyrows(self, outtable, startrowin=0, startrowout=-1, nrow=-1): """Copy the contents of rows from this table to outtable. The contents of the columns with matching names are copied. The other arguments can be used to specify where to start copying. By default the entire input table is appended to the output table. Rows are added to the output table if needed. `startrowin` Row where to start in the input table. `startrowout` Row where to start in the output table, | -1 means write at the end of the output table. `nrow` Number of rows to copy | -1 means from startrowin till the end of the input table The following example appends row to the table itself, thus doubles the number of rows:: t:=table('test.ms',readonly=F) t.copyrows(t) """ self._copyrows(outtable, startrowin, startrowout, nrow)
python
def copyrows(self, outtable, startrowin=0, startrowout=-1, nrow=-1): """Copy the contents of rows from this table to outtable. The contents of the columns with matching names are copied. The other arguments can be used to specify where to start copying. By default the entire input table is appended to the output table. Rows are added to the output table if needed. `startrowin` Row where to start in the input table. `startrowout` Row where to start in the output table, | -1 means write at the end of the output table. `nrow` Number of rows to copy | -1 means from startrowin till the end of the input table The following example appends row to the table itself, thus doubles the number of rows:: t:=table('test.ms',readonly=F) t.copyrows(t) """ self._copyrows(outtable, startrowin, startrowout, nrow)
[ "def", "copyrows", "(", "self", ",", "outtable", ",", "startrowin", "=", "0", ",", "startrowout", "=", "-", "1", ",", "nrow", "=", "-", "1", ")", ":", "self", ".", "_copyrows", "(", "outtable", ",", "startrowin", ",", "startrowout", ",", "nrow", ")" ...
Copy the contents of rows from this table to outtable. The contents of the columns with matching names are copied. The other arguments can be used to specify where to start copying. By default the entire input table is appended to the output table. Rows are added to the output table if needed. `startrowin` Row where to start in the input table. `startrowout` Row where to start in the output table, | -1 means write at the end of the output table. `nrow` Number of rows to copy | -1 means from startrowin till the end of the input table The following example appends row to the table itself, thus doubles the number of rows:: t:=table('test.ms',readonly=F) t.copyrows(t)
[ "Copy", "the", "contents", "of", "rows", "from", "this", "table", "to", "outtable", "." ]
975510861ea005f7919dd9e438b5f98a1682eebe
https://github.com/casacore/python-casacore/blob/975510861ea005f7919dd9e438b5f98a1682eebe/casacore/tables/table.py#L681-L705
train
23,024
casacore/python-casacore
casacore/tables/table.py
table.rownumbers
def rownumbers(self, table=None): """Return a list containing the row numbers of this table. This method can be useful after a selection or a sort. It returns the row numbers of the rows in this table with respect to the given table. If no table is given, the original table is used. For example:: t = table('W53.MS') t1 = t.selectrows([1,3,5,7,9]) # select a few rows t1.rownumbers(t) # [1 3 5 7 9] t2 = t1.selectrows([2,5]) # select rows from the selection t2.rownumbers(t1) # [2 5] # rownrs of t2 in table t1 t2.rownumbers(t) # [3 9] # rownrs of t2 in t t2.rownumbers() # [3 9] The last statements show that the method returns the row numbers referring to the given table. Table t2 contains rows 2 and 5 in table t1, which are rows 3 and 9 in table t. """ if table is None: return self._rownumbers(Table()) return self._rownumbers(table)
python
def rownumbers(self, table=None): """Return a list containing the row numbers of this table. This method can be useful after a selection or a sort. It returns the row numbers of the rows in this table with respect to the given table. If no table is given, the original table is used. For example:: t = table('W53.MS') t1 = t.selectrows([1,3,5,7,9]) # select a few rows t1.rownumbers(t) # [1 3 5 7 9] t2 = t1.selectrows([2,5]) # select rows from the selection t2.rownumbers(t1) # [2 5] # rownrs of t2 in table t1 t2.rownumbers(t) # [3 9] # rownrs of t2 in t t2.rownumbers() # [3 9] The last statements show that the method returns the row numbers referring to the given table. Table t2 contains rows 2 and 5 in table t1, which are rows 3 and 9 in table t. """ if table is None: return self._rownumbers(Table()) return self._rownumbers(table)
[ "def", "rownumbers", "(", "self", ",", "table", "=", "None", ")", ":", "if", "table", "is", "None", ":", "return", "self", ".", "_rownumbers", "(", "Table", "(", ")", ")", "return", "self", ".", "_rownumbers", "(", "table", ")" ]
Return a list containing the row numbers of this table. This method can be useful after a selection or a sort. It returns the row numbers of the rows in this table with respect to the given table. If no table is given, the original table is used. For example:: t = table('W53.MS') t1 = t.selectrows([1,3,5,7,9]) # select a few rows t1.rownumbers(t) # [1 3 5 7 9] t2 = t1.selectrows([2,5]) # select rows from the selection t2.rownumbers(t1) # [2 5] # rownrs of t2 in table t1 t2.rownumbers(t) # [3 9] # rownrs of t2 in t t2.rownumbers() # [3 9] The last statements show that the method returns the row numbers referring to the given table. Table t2 contains rows 2 and 5 in table t1, which are rows 3 and 9 in table t.
[ "Return", "a", "list", "containing", "the", "row", "numbers", "of", "this", "table", "." ]
975510861ea005f7919dd9e438b5f98a1682eebe
https://github.com/casacore/python-casacore/blob/975510861ea005f7919dd9e438b5f98a1682eebe/casacore/tables/table.py#L819-L847
train
23,025
casacore/python-casacore
casacore/tables/table.py
table.getcolshapestring
def getcolshapestring(self, columnname, startrow=0, nrow=-1, rowincr=1): """Get the shapes of all cells in the column in string format. It returns the shape in a string like [10,20,30]. If the column contains fixed shape arrays, a single shape is returned. Otherwise a list of shape strings is returned. The column can be sliced by giving a start row (default 0), number of rows (default all), and row stride (default 1). """ return self._getcolshapestring(columnname, startrow, nrow, rowincr, True)
python
def getcolshapestring(self, columnname, startrow=0, nrow=-1, rowincr=1): """Get the shapes of all cells in the column in string format. It returns the shape in a string like [10,20,30]. If the column contains fixed shape arrays, a single shape is returned. Otherwise a list of shape strings is returned. The column can be sliced by giving a start row (default 0), number of rows (default all), and row stride (default 1). """ return self._getcolshapestring(columnname, startrow, nrow, rowincr, True)
[ "def", "getcolshapestring", "(", "self", ",", "columnname", ",", "startrow", "=", "0", ",", "nrow", "=", "-", "1", ",", "rowincr", "=", "1", ")", ":", "return", "self", ".", "_getcolshapestring", "(", "columnname", ",", "startrow", ",", "nrow", ",", "r...
Get the shapes of all cells in the column in string format. It returns the shape in a string like [10,20,30]. If the column contains fixed shape arrays, a single shape is returned. Otherwise a list of shape strings is returned. The column can be sliced by giving a start row (default 0), number of rows (default all), and row stride (default 1).
[ "Get", "the", "shapes", "of", "all", "cells", "in", "the", "column", "in", "string", "format", "." ]
975510861ea005f7919dd9e438b5f98a1682eebe
https://github.com/casacore/python-casacore/blob/975510861ea005f7919dd9e438b5f98a1682eebe/casacore/tables/table.py#L921-L936
train
23,026
casacore/python-casacore
casacore/tables/table.py
table.getcellnp
def getcellnp(self, columnname, rownr, nparray): """Get data from a column cell into the given numpy array . Get the contents of a cell containing an array into the given numpy array. The numpy array has to be C-contiguous with a shape matching the shape of the column cell. Data type coercion will be done as needed. """ if not nparray.flags.c_contiguous or nparray.size == 0: raise ValueError("Argument 'nparray' has to be a contiguous " + "numpy array") return self._getcellvh(columnname, rownr, nparray)
python
def getcellnp(self, columnname, rownr, nparray): """Get data from a column cell into the given numpy array . Get the contents of a cell containing an array into the given numpy array. The numpy array has to be C-contiguous with a shape matching the shape of the column cell. Data type coercion will be done as needed. """ if not nparray.flags.c_contiguous or nparray.size == 0: raise ValueError("Argument 'nparray' has to be a contiguous " + "numpy array") return self._getcellvh(columnname, rownr, nparray)
[ "def", "getcellnp", "(", "self", ",", "columnname", ",", "rownr", ",", "nparray", ")", ":", "if", "not", "nparray", ".", "flags", ".", "c_contiguous", "or", "nparray", ".", "size", "==", "0", ":", "raise", "ValueError", "(", "\"Argument 'nparray' has to be a...
Get data from a column cell into the given numpy array . Get the contents of a cell containing an array into the given numpy array. The numpy array has to be C-contiguous with a shape matching the shape of the column cell. Data type coercion will be done as needed.
[ "Get", "data", "from", "a", "column", "cell", "into", "the", "given", "numpy", "array", "." ]
975510861ea005f7919dd9e438b5f98a1682eebe
https://github.com/casacore/python-casacore/blob/975510861ea005f7919dd9e438b5f98a1682eebe/casacore/tables/table.py#L963-L975
train
23,027
casacore/python-casacore
casacore/tables/table.py
table.getcellslice
def getcellslice(self, columnname, rownr, blc, trc, inc=[]): """Get a slice from a column cell holding an array. The columnname and (0-relative) rownr indicate the table cell. The slice to get is defined by the blc, trc, and optional inc arguments (blc = bottom-left corner, trc=top-right corner, inc=stride). Not all axes have to be filled in for blc, trc, and inc. Missing axes default to begin, end, and 1. A negative blc or trc defaults to begin or end. Note that trc is inclusive (unlike python indexing). """ return self._getcellslice(columnname, rownr, blc, trc, inc)
python
def getcellslice(self, columnname, rownr, blc, trc, inc=[]): """Get a slice from a column cell holding an array. The columnname and (0-relative) rownr indicate the table cell. The slice to get is defined by the blc, trc, and optional inc arguments (blc = bottom-left corner, trc=top-right corner, inc=stride). Not all axes have to be filled in for blc, trc, and inc. Missing axes default to begin, end, and 1. A negative blc or trc defaults to begin or end. Note that trc is inclusive (unlike python indexing). """ return self._getcellslice(columnname, rownr, blc, trc, inc)
[ "def", "getcellslice", "(", "self", ",", "columnname", ",", "rownr", ",", "blc", ",", "trc", ",", "inc", "=", "[", "]", ")", ":", "return", "self", ".", "_getcellslice", "(", "columnname", ",", "rownr", ",", "blc", ",", "trc", ",", "inc", ")" ]
Get a slice from a column cell holding an array. The columnname and (0-relative) rownr indicate the table cell. The slice to get is defined by the blc, trc, and optional inc arguments (blc = bottom-left corner, trc=top-right corner, inc=stride). Not all axes have to be filled in for blc, trc, and inc. Missing axes default to begin, end, and 1. A negative blc or trc defaults to begin or end. Note that trc is inclusive (unlike python indexing).
[ "Get", "a", "slice", "from", "a", "column", "cell", "holding", "an", "array", "." ]
975510861ea005f7919dd9e438b5f98a1682eebe
https://github.com/casacore/python-casacore/blob/975510861ea005f7919dd9e438b5f98a1682eebe/casacore/tables/table.py#L977-L990
train
23,028
casacore/python-casacore
casacore/tables/table.py
table.getcellslicenp
def getcellslicenp(self, columnname, nparray, rownr, blc, trc, inc=[]): """Get a slice from a column cell into the given numpy array. The columnname and (0-relative) rownr indicate the table cell. The numpy array has to be C-contiguous with a shape matching the shape of the slice. Data type coercion will be done as needed. The slice to get is defined by the blc, trc, and optional inc arguments (blc = bottom-left corner, trc=top-right corner, inc=stride). Not all axes have to be filled in for blc, trc, and inc. Missing axes default to begin, end, and 1. A negative blc or trc defaults to begin or end. Note that trc is inclusive (unlike python indexing). """ if not nparray.flags.c_contiguous or nparray.size == 0: raise ValueError("Argument 'nparray' has to be a contiguous " + "numpy array") return self._getcellslicevh(columnname, rownr, blc, trc, inc, nparray)
python
def getcellslicenp(self, columnname, nparray, rownr, blc, trc, inc=[]): """Get a slice from a column cell into the given numpy array. The columnname and (0-relative) rownr indicate the table cell. The numpy array has to be C-contiguous with a shape matching the shape of the slice. Data type coercion will be done as needed. The slice to get is defined by the blc, trc, and optional inc arguments (blc = bottom-left corner, trc=top-right corner, inc=stride). Not all axes have to be filled in for blc, trc, and inc. Missing axes default to begin, end, and 1. A negative blc or trc defaults to begin or end. Note that trc is inclusive (unlike python indexing). """ if not nparray.flags.c_contiguous or nparray.size == 0: raise ValueError("Argument 'nparray' has to be a contiguous " + "numpy array") return self._getcellslicevh(columnname, rownr, blc, trc, inc, nparray)
[ "def", "getcellslicenp", "(", "self", ",", "columnname", ",", "nparray", ",", "rownr", ",", "blc", ",", "trc", ",", "inc", "=", "[", "]", ")", ":", "if", "not", "nparray", ".", "flags", ".", "c_contiguous", "or", "nparray", ".", "size", "==", "0", ...
Get a slice from a column cell into the given numpy array. The columnname and (0-relative) rownr indicate the table cell. The numpy array has to be C-contiguous with a shape matching the shape of the slice. Data type coercion will be done as needed. The slice to get is defined by the blc, trc, and optional inc arguments (blc = bottom-left corner, trc=top-right corner, inc=stride). Not all axes have to be filled in for blc, trc, and inc. Missing axes default to begin, end, and 1. A negative blc or trc defaults to begin or end. Note that trc is inclusive (unlike python indexing).
[ "Get", "a", "slice", "from", "a", "column", "cell", "into", "the", "given", "numpy", "array", "." ]
975510861ea005f7919dd9e438b5f98a1682eebe
https://github.com/casacore/python-casacore/blob/975510861ea005f7919dd9e438b5f98a1682eebe/casacore/tables/table.py#L992-L1011
train
23,029
casacore/python-casacore
casacore/tables/table.py
table.getcolnp
def getcolnp(self, columnname, nparray, startrow=0, nrow=-1, rowincr=1): """Get the contents of a column or part of it into the given numpy array. The numpy array has to be C-contiguous with a shape matching the shape of the column (part). Data type coercion will be done as needed. If the column contains arrays, they should all have the same shape. An exception is thrown if they differ in shape. In that case the method :func:`getvarcol` should be used instead. The column can be sliced by giving a start row (default 0), number of rows (default all), and row stride (default 1). """ if (not nparray.flags.c_contiguous) or nparray.size == 0: raise ValueError("Argument 'nparray' has to be a contiguous " + "numpy array") return self._getcolvh(columnname, startrow, nrow, rowincr, nparray)
python
def getcolnp(self, columnname, nparray, startrow=0, nrow=-1, rowincr=1): """Get the contents of a column or part of it into the given numpy array. The numpy array has to be C-contiguous with a shape matching the shape of the column (part). Data type coercion will be done as needed. If the column contains arrays, they should all have the same shape. An exception is thrown if they differ in shape. In that case the method :func:`getvarcol` should be used instead. The column can be sliced by giving a start row (default 0), number of rows (default all), and row stride (default 1). """ if (not nparray.flags.c_contiguous) or nparray.size == 0: raise ValueError("Argument 'nparray' has to be a contiguous " + "numpy array") return self._getcolvh(columnname, startrow, nrow, rowincr, nparray)
[ "def", "getcolnp", "(", "self", ",", "columnname", ",", "nparray", ",", "startrow", "=", "0", ",", "nrow", "=", "-", "1", ",", "rowincr", "=", "1", ")", ":", "if", "(", "not", "nparray", ".", "flags", ".", "c_contiguous", ")", "or", "nparray", ".",...
Get the contents of a column or part of it into the given numpy array. The numpy array has to be C-contiguous with a shape matching the shape of the column (part). Data type coercion will be done as needed. If the column contains arrays, they should all have the same shape. An exception is thrown if they differ in shape. In that case the method :func:`getvarcol` should be used instead. The column can be sliced by giving a start row (default 0), number of rows (default all), and row stride (default 1).
[ "Get", "the", "contents", "of", "a", "column", "or", "part", "of", "it", "into", "the", "given", "numpy", "array", "." ]
975510861ea005f7919dd9e438b5f98a1682eebe
https://github.com/casacore/python-casacore/blob/975510861ea005f7919dd9e438b5f98a1682eebe/casacore/tables/table.py#L1036-L1054
train
23,030
casacore/python-casacore
casacore/tables/table.py
table.getcolslice
def getcolslice(self, columnname, blc, trc, inc=[], startrow=0, nrow=-1, rowincr=1): """Get a slice from a table column holding arrays. The slice in each array is given by blc, trc, and inc (as in getcellslice). The column can be sliced by giving a start row (default 0), number of rows (default all), and row stride (default 1). It returns a numpy array where the first axis is formed by the column cells. The other axes are the array axes. """ return self._getcolslice(columnname, blc, trc, inc, startrow, nrow, rowincr)
python
def getcolslice(self, columnname, blc, trc, inc=[], startrow=0, nrow=-1, rowincr=1): """Get a slice from a table column holding arrays. The slice in each array is given by blc, trc, and inc (as in getcellslice). The column can be sliced by giving a start row (default 0), number of rows (default all), and row stride (default 1). It returns a numpy array where the first axis is formed by the column cells. The other axes are the array axes. """ return self._getcolslice(columnname, blc, trc, inc, startrow, nrow, rowincr)
[ "def", "getcolslice", "(", "self", ",", "columnname", ",", "blc", ",", "trc", ",", "inc", "=", "[", "]", ",", "startrow", "=", "0", ",", "nrow", "=", "-", "1", ",", "rowincr", "=", "1", ")", ":", "return", "self", ".", "_getcolslice", "(", "colum...
Get a slice from a table column holding arrays. The slice in each array is given by blc, trc, and inc (as in getcellslice). The column can be sliced by giving a start row (default 0), number of rows (default all), and row stride (default 1). It returns a numpy array where the first axis is formed by the column cells. The other axes are the array axes.
[ "Get", "a", "slice", "from", "a", "table", "column", "holding", "arrays", "." ]
975510861ea005f7919dd9e438b5f98a1682eebe
https://github.com/casacore/python-casacore/blob/975510861ea005f7919dd9e438b5f98a1682eebe/casacore/tables/table.py#L1066-L1080
train
23,031
casacore/python-casacore
casacore/tables/table.py
table.getcolslicenp
def getcolslicenp(self, columnname, nparray, blc, trc, inc=[], startrow=0, nrow=-1, rowincr=1): """Get a slice from a table column into the given numpy array. The numpy array has to be C-contiguous with a shape matching the shape of the column (slice). Data type coercion will be done as needed. The slice in each array is given by blc, trc, and inc (as in getcellslice). The column can be sliced by giving a start row (default 0), number of rows (default all), and row stride (default 1). It returns a numpy array where the first axis is formed by the column cells. The other axes are the array axes. """ if not nparray.flags.c_contiguous or nparray.size == 0: raise ValueError("Argument 'nparray' has to be a contiguous " + "numpy array") return self._getcolslicevh(columnname, blc, trc, inc, startrow, nrow, rowincr, nparray)
python
def getcolslicenp(self, columnname, nparray, blc, trc, inc=[], startrow=0, nrow=-1, rowincr=1): """Get a slice from a table column into the given numpy array. The numpy array has to be C-contiguous with a shape matching the shape of the column (slice). Data type coercion will be done as needed. The slice in each array is given by blc, trc, and inc (as in getcellslice). The column can be sliced by giving a start row (default 0), number of rows (default all), and row stride (default 1). It returns a numpy array where the first axis is formed by the column cells. The other axes are the array axes. """ if not nparray.flags.c_contiguous or nparray.size == 0: raise ValueError("Argument 'nparray' has to be a contiguous " + "numpy array") return self._getcolslicevh(columnname, blc, trc, inc, startrow, nrow, rowincr, nparray)
[ "def", "getcolslicenp", "(", "self", ",", "columnname", ",", "nparray", ",", "blc", ",", "trc", ",", "inc", "=", "[", "]", ",", "startrow", "=", "0", ",", "nrow", "=", "-", "1", ",", "rowincr", "=", "1", ")", ":", "if", "not", "nparray", ".", "...
Get a slice from a table column into the given numpy array. The numpy array has to be C-contiguous with a shape matching the shape of the column (slice). Data type coercion will be done as needed. The slice in each array is given by blc, trc, and inc (as in getcellslice). The column can be sliced by giving a start row (default 0), number of rows (default all), and row stride (default 1). It returns a numpy array where the first axis is formed by the column cells. The other axes are the array axes.
[ "Get", "a", "slice", "from", "a", "table", "column", "into", "the", "given", "numpy", "array", "." ]
975510861ea005f7919dd9e438b5f98a1682eebe
https://github.com/casacore/python-casacore/blob/975510861ea005f7919dd9e438b5f98a1682eebe/casacore/tables/table.py#L1082-L1102
train
23,032
casacore/python-casacore
casacore/tables/table.py
table.putcell
def putcell(self, columnname, rownr, value): """Put a value into one or more table cells. The columnname and (0-relative) rownrs indicate the table cells. rownr can be a single row number or a sequence of row numbers. If multiple rownrs are given, the given value is put in all those rows. The given value has to be convertible to the data type of the column. If the column contains scalar values, the given value must be a scalar. The value for a column holding arrays can be given as: - a scalar resulting in a 1-dim array of 1 element - a sequence (list, tuple) resulting in a 1-dim array - a numpy array of any dimensionality Note that the arrays in a column may have a fixed dimensionality or shape. In that case the dimensionality or shape of the array to put has to conform. """ self._putcell(columnname, rownr, value)
python
def putcell(self, columnname, rownr, value): """Put a value into one or more table cells. The columnname and (0-relative) rownrs indicate the table cells. rownr can be a single row number or a sequence of row numbers. If multiple rownrs are given, the given value is put in all those rows. The given value has to be convertible to the data type of the column. If the column contains scalar values, the given value must be a scalar. The value for a column holding arrays can be given as: - a scalar resulting in a 1-dim array of 1 element - a sequence (list, tuple) resulting in a 1-dim array - a numpy array of any dimensionality Note that the arrays in a column may have a fixed dimensionality or shape. In that case the dimensionality or shape of the array to put has to conform. """ self._putcell(columnname, rownr, value)
[ "def", "putcell", "(", "self", ",", "columnname", ",", "rownr", ",", "value", ")", ":", "self", ".", "_putcell", "(", "columnname", ",", "rownr", ",", "value", ")" ]
Put a value into one or more table cells. The columnname and (0-relative) rownrs indicate the table cells. rownr can be a single row number or a sequence of row numbers. If multiple rownrs are given, the given value is put in all those rows. The given value has to be convertible to the data type of the column. If the column contains scalar values, the given value must be a scalar. The value for a column holding arrays can be given as: - a scalar resulting in a 1-dim array of 1 element - a sequence (list, tuple) resulting in a 1-dim array - a numpy array of any dimensionality Note that the arrays in a column may have a fixed dimensionality or shape. In that case the dimensionality or shape of the array to put has to conform.
[ "Put", "a", "value", "into", "one", "or", "more", "table", "cells", "." ]
975510861ea005f7919dd9e438b5f98a1682eebe
https://github.com/casacore/python-casacore/blob/975510861ea005f7919dd9e438b5f98a1682eebe/casacore/tables/table.py#L1104-L1124
train
23,033
casacore/python-casacore
casacore/tables/table.py
table.putcellslice
def putcellslice(self, columnname, rownr, value, blc, trc, inc=[]): """Put into a slice of a table cell holding an array. The columnname and (0-relative) rownr indicate the table cell. Unlike putcell only a single row can be given. The slice to put is defined by the blc, trc, and optional inc arguments (blc = bottom-left corner, trc=top-right corner, inc=stride). Not all axes have to be filled in for blc, trc, and inc. Missing axes default to begin, end, and 1. A negative blc or trc defaults to begin or end. Note that trc is inclusive (unlike python indexing). As in putcell the array can be given by a scalar, sequence, or numpy array. The shape of the array to put has to match the slice shape. """ self._putcellslice(columnname, rownr, value, blc, trc, inc)
python
def putcellslice(self, columnname, rownr, value, blc, trc, inc=[]): """Put into a slice of a table cell holding an array. The columnname and (0-relative) rownr indicate the table cell. Unlike putcell only a single row can be given. The slice to put is defined by the blc, trc, and optional inc arguments (blc = bottom-left corner, trc=top-right corner, inc=stride). Not all axes have to be filled in for blc, trc, and inc. Missing axes default to begin, end, and 1. A negative blc or trc defaults to begin or end. Note that trc is inclusive (unlike python indexing). As in putcell the array can be given by a scalar, sequence, or numpy array. The shape of the array to put has to match the slice shape. """ self._putcellslice(columnname, rownr, value, blc, trc, inc)
[ "def", "putcellslice", "(", "self", ",", "columnname", ",", "rownr", ",", "value", ",", "blc", ",", "trc", ",", "inc", "=", "[", "]", ")", ":", "self", ".", "_putcellslice", "(", "columnname", ",", "rownr", ",", "value", ",", "blc", ",", "trc", ","...
Put into a slice of a table cell holding an array. The columnname and (0-relative) rownr indicate the table cell. Unlike putcell only a single row can be given. The slice to put is defined by the blc, trc, and optional inc arguments (blc = bottom-left corner, trc=top-right corner, inc=stride). Not all axes have to be filled in for blc, trc, and inc. Missing axes default to begin, end, and 1. A negative blc or trc defaults to begin or end. Note that trc is inclusive (unlike python indexing). As in putcell the array can be given by a scalar, sequence, or numpy array. The shape of the array to put has to match the slice shape.
[ "Put", "into", "a", "slice", "of", "a", "table", "cell", "holding", "an", "array", "." ]
975510861ea005f7919dd9e438b5f98a1682eebe
https://github.com/casacore/python-casacore/blob/975510861ea005f7919dd9e438b5f98a1682eebe/casacore/tables/table.py#L1126-L1144
train
23,034
casacore/python-casacore
casacore/tables/table.py
table.putcolslice
def putcolslice(self, columnname, value, blc, trc, inc=[], startrow=0, nrow=-1, rowincr=1): """Put into a slice in a table column holding arrays. Its arguments are the same as for getcolslice and putcellslice. """ self._putcolslice(columnname, value, blc, trc, inc, startrow, nrow, rowincr)
python
def putcolslice(self, columnname, value, blc, trc, inc=[], startrow=0, nrow=-1, rowincr=1): """Put into a slice in a table column holding arrays. Its arguments are the same as for getcolslice and putcellslice. """ self._putcolslice(columnname, value, blc, trc, inc, startrow, nrow, rowincr)
[ "def", "putcolslice", "(", "self", ",", "columnname", ",", "value", ",", "blc", ",", "trc", ",", "inc", "=", "[", "]", ",", "startrow", "=", "0", ",", "nrow", "=", "-", "1", ",", "rowincr", "=", "1", ")", ":", "self", ".", "_putcolslice", "(", ...
Put into a slice in a table column holding arrays. Its arguments are the same as for getcolslice and putcellslice.
[ "Put", "into", "a", "slice", "in", "a", "table", "column", "holding", "arrays", "." ]
975510861ea005f7919dd9e438b5f98a1682eebe
https://github.com/casacore/python-casacore/blob/975510861ea005f7919dd9e438b5f98a1682eebe/casacore/tables/table.py#L1171-L1179
train
23,035
casacore/python-casacore
casacore/tables/table.py
table.addcols
def addcols(self, desc, dminfo={}, addtoparent=True): """Add one or more columns. Columns can always be added to a normal table. They can also be added to a reference table and optionally to its parent table. `desc` contains a description of the column(s) to be added. It can be given in three ways: - a dict created by :func:`maketabdesc`. In this way multiple columns can be added. - a dict created by :func:`makescacoldesc`, :func:`makearrcoldesc`, or :func:`makecoldesc`. In this way a single column can be added. - a dict created by :func:`getcoldesc`. The key 'name' containing the column name has to be defined in such a dict. `dminfo` can be used to provide detailed data manager info to tell how the column(s) have to be stored. The dminfo of an existing column can be obtained using method :func:`getdminfo`. `addtoparent` defines if the column should also be added to the parent table in case the current table is a reference table (result of selection). If True, it will be added to the parent if it does not exist yet. For example, add a column using the same data manager type as another column:: coldmi = t.getdminfo('colarrtsm') # get dminfo of existing column coldmi["NAME"] = 'tsm2' # give it a unique name t.addcols (maketabdesc(makearrcoldesc("colarrtsm2",0., ndim=2)), coldmi) """ tdesc = desc # Create a tabdesc if only a coldesc is given. if 'name' in desc: import casacore.tables.tableutil as pt if len(desc) == 2 and 'desc' in desc: # Given as output from makecoldesc tdesc = pt.maketabdesc(desc) elif 'valueType' in desc: # Given as output of getcoldesc (with a name field added) cd = pt.makecoldesc(desc['name'], desc) tdesc = pt.maketabdesc(cd) self._addcols(tdesc, dminfo, addtoparent) self._makerow()
python
def addcols(self, desc, dminfo={}, addtoparent=True): """Add one or more columns. Columns can always be added to a normal table. They can also be added to a reference table and optionally to its parent table. `desc` contains a description of the column(s) to be added. It can be given in three ways: - a dict created by :func:`maketabdesc`. In this way multiple columns can be added. - a dict created by :func:`makescacoldesc`, :func:`makearrcoldesc`, or :func:`makecoldesc`. In this way a single column can be added. - a dict created by :func:`getcoldesc`. The key 'name' containing the column name has to be defined in such a dict. `dminfo` can be used to provide detailed data manager info to tell how the column(s) have to be stored. The dminfo of an existing column can be obtained using method :func:`getdminfo`. `addtoparent` defines if the column should also be added to the parent table in case the current table is a reference table (result of selection). If True, it will be added to the parent if it does not exist yet. For example, add a column using the same data manager type as another column:: coldmi = t.getdminfo('colarrtsm') # get dminfo of existing column coldmi["NAME"] = 'tsm2' # give it a unique name t.addcols (maketabdesc(makearrcoldesc("colarrtsm2",0., ndim=2)), coldmi) """ tdesc = desc # Create a tabdesc if only a coldesc is given. if 'name' in desc: import casacore.tables.tableutil as pt if len(desc) == 2 and 'desc' in desc: # Given as output from makecoldesc tdesc = pt.maketabdesc(desc) elif 'valueType' in desc: # Given as output of getcoldesc (with a name field added) cd = pt.makecoldesc(desc['name'], desc) tdesc = pt.maketabdesc(cd) self._addcols(tdesc, dminfo, addtoparent) self._makerow()
[ "def", "addcols", "(", "self", ",", "desc", ",", "dminfo", "=", "{", "}", ",", "addtoparent", "=", "True", ")", ":", "tdesc", "=", "desc", "# Create a tabdesc if only a coldesc is given.", "if", "'name'", "in", "desc", ":", "import", "casacore", ".", "tables...
Add one or more columns. Columns can always be added to a normal table. They can also be added to a reference table and optionally to its parent table. `desc` contains a description of the column(s) to be added. It can be given in three ways: - a dict created by :func:`maketabdesc`. In this way multiple columns can be added. - a dict created by :func:`makescacoldesc`, :func:`makearrcoldesc`, or :func:`makecoldesc`. In this way a single column can be added. - a dict created by :func:`getcoldesc`. The key 'name' containing the column name has to be defined in such a dict. `dminfo` can be used to provide detailed data manager info to tell how the column(s) have to be stored. The dminfo of an existing column can be obtained using method :func:`getdminfo`. `addtoparent` defines if the column should also be added to the parent table in case the current table is a reference table (result of selection). If True, it will be added to the parent if it does not exist yet. For example, add a column using the same data manager type as another column:: coldmi = t.getdminfo('colarrtsm') # get dminfo of existing column coldmi["NAME"] = 'tsm2' # give it a unique name t.addcols (maketabdesc(makearrcoldesc("colarrtsm2",0., ndim=2)), coldmi)
[ "Add", "one", "or", "more", "columns", "." ]
975510861ea005f7919dd9e438b5f98a1682eebe
https://github.com/casacore/python-casacore/blob/975510861ea005f7919dd9e438b5f98a1682eebe/casacore/tables/table.py#L1181-L1229
train
23,036
casacore/python-casacore
casacore/tables/table.py
table.renamecol
def renamecol(self, oldname, newname): """Rename a single table column. Renaming a column in a reference table does NOT rename the column in the referenced table. """ self._renamecol(oldname, newname) self._makerow()
python
def renamecol(self, oldname, newname): """Rename a single table column. Renaming a column in a reference table does NOT rename the column in the referenced table. """ self._renamecol(oldname, newname) self._makerow()
[ "def", "renamecol", "(", "self", ",", "oldname", ",", "newname", ")", ":", "self", ".", "_renamecol", "(", "oldname", ",", "newname", ")", "self", ".", "_makerow", "(", ")" ]
Rename a single table column. Renaming a column in a reference table does NOT rename the column in the referenced table.
[ "Rename", "a", "single", "table", "column", "." ]
975510861ea005f7919dd9e438b5f98a1682eebe
https://github.com/casacore/python-casacore/blob/975510861ea005f7919dd9e438b5f98a1682eebe/casacore/tables/table.py#L1231-L1239
train
23,037
casacore/python-casacore
casacore/tables/table.py
table.fieldnames
def fieldnames(self, keyword=''): """Get the names of the fields in a table keyword value. The value of a keyword can be a struct (python dict). This method returns the names of the fields in that struct. Each field in a struct can be a struct in itself. Names of fields in a sub-struct can be obtained by giving a keyword name consisting of multiple parts separated by dots (e.g. 'key1.sub1.sub2'). If an empty keyword name is given (which is the default), all table keyword names are shown and its behaviour is the same as :func:`keywordnames`. Instead of a keyword name an index can be given which returns the names of the struct value of the i-th keyword. """ if isinstance(keyword, str): return self._getfieldnames('', keyword, -1) else: return self._getfieldnames('', '', keyword)
python
def fieldnames(self, keyword=''): """Get the names of the fields in a table keyword value. The value of a keyword can be a struct (python dict). This method returns the names of the fields in that struct. Each field in a struct can be a struct in itself. Names of fields in a sub-struct can be obtained by giving a keyword name consisting of multiple parts separated by dots (e.g. 'key1.sub1.sub2'). If an empty keyword name is given (which is the default), all table keyword names are shown and its behaviour is the same as :func:`keywordnames`. Instead of a keyword name an index can be given which returns the names of the struct value of the i-th keyword. """ if isinstance(keyword, str): return self._getfieldnames('', keyword, -1) else: return self._getfieldnames('', '', keyword)
[ "def", "fieldnames", "(", "self", ",", "keyword", "=", "''", ")", ":", "if", "isinstance", "(", "keyword", ",", "str", ")", ":", "return", "self", ".", "_getfieldnames", "(", "''", ",", "keyword", ",", "-", "1", ")", "else", ":", "return", "self", ...
Get the names of the fields in a table keyword value. The value of a keyword can be a struct (python dict). This method returns the names of the fields in that struct. Each field in a struct can be a struct in itself. Names of fields in a sub-struct can be obtained by giving a keyword name consisting of multiple parts separated by dots (e.g. 'key1.sub1.sub2'). If an empty keyword name is given (which is the default), all table keyword names are shown and its behaviour is the same as :func:`keywordnames`. Instead of a keyword name an index can be given which returns the names of the struct value of the i-th keyword.
[ "Get", "the", "names", "of", "the", "fields", "in", "a", "table", "keyword", "value", "." ]
975510861ea005f7919dd9e438b5f98a1682eebe
https://github.com/casacore/python-casacore/blob/975510861ea005f7919dd9e438b5f98a1682eebe/casacore/tables/table.py#L1263-L1283
train
23,038
casacore/python-casacore
casacore/tables/table.py
table.colfieldnames
def colfieldnames(self, columnname, keyword=''): """Get the names of the fields in a column keyword value. The value of a keyword can be a struct (python dict). This method returns the names of the fields in that struct. Each field in a struct can be a struct in itself. Names of fields in a sub-struct can be obtained by giving a keyword name consisting of multiple parts separated by dots (e.g. 'key1.sub1.sub2'). If an empty keyword name is given (which is the default), all keyword names of the column are shown and its behaviour is the same as :func:`colkeywordnames`. Instead of a keyword name an index can be given which returns the names of the struct value of the i-th keyword. """ if isinstance(keyword, str): return self._getfieldnames(columnname, keyword, -1) else: return self._getfieldnames(columnname, '', keyword)
python
def colfieldnames(self, columnname, keyword=''): """Get the names of the fields in a column keyword value. The value of a keyword can be a struct (python dict). This method returns the names of the fields in that struct. Each field in a struct can be a struct in itself. Names of fields in a sub-struct can be obtained by giving a keyword name consisting of multiple parts separated by dots (e.g. 'key1.sub1.sub2'). If an empty keyword name is given (which is the default), all keyword names of the column are shown and its behaviour is the same as :func:`colkeywordnames`. Instead of a keyword name an index can be given which returns the names of the struct value of the i-th keyword. """ if isinstance(keyword, str): return self._getfieldnames(columnname, keyword, -1) else: return self._getfieldnames(columnname, '', keyword)
[ "def", "colfieldnames", "(", "self", ",", "columnname", ",", "keyword", "=", "''", ")", ":", "if", "isinstance", "(", "keyword", ",", "str", ")", ":", "return", "self", ".", "_getfieldnames", "(", "columnname", ",", "keyword", ",", "-", "1", ")", "else...
Get the names of the fields in a column keyword value. The value of a keyword can be a struct (python dict). This method returns the names of the fields in that struct. Each field in a struct can be a struct in itself. Names of fields in a sub-struct can be obtained by giving a keyword name consisting of multiple parts separated by dots (e.g. 'key1.sub1.sub2'). If an empty keyword name is given (which is the default), all keyword names of the column are shown and its behaviour is the same as :func:`colkeywordnames`. Instead of a keyword name an index can be given which returns the names of the struct value of the i-th keyword.
[ "Get", "the", "names", "of", "the", "fields", "in", "a", "column", "keyword", "value", "." ]
975510861ea005f7919dd9e438b5f98a1682eebe
https://github.com/casacore/python-casacore/blob/975510861ea005f7919dd9e438b5f98a1682eebe/casacore/tables/table.py#L1285-L1305
train
23,039
casacore/python-casacore
casacore/tables/table.py
table.getkeyword
def getkeyword(self, keyword): """Get the value of a table keyword. The value of a keyword can be a: - scalar which is returned as a normal python scalar. - an array which is returned as a numpy array. - a reference to a table which is returned as a string containing its name prefixed by 'Table :'. It can be opened using the normal table constructor which will remove the prefix. - a struct which is returned as a dict. A struct is fully nestable, thus each field in the struct can have one of the values described here. Similar to method :func:`fieldnames` a keyword name can be given consisting of multiple parts separated by dots. This represents nested structs, thus gives the value of a field in a struct (in a struct, etc.). Instead of a keyword name an index can be given which returns the value of the i-th keyword. """ if isinstance(keyword, str): return self._getkeyword('', keyword, -1) else: return self._getkeyword('', '', keyword)
python
def getkeyword(self, keyword): """Get the value of a table keyword. The value of a keyword can be a: - scalar which is returned as a normal python scalar. - an array which is returned as a numpy array. - a reference to a table which is returned as a string containing its name prefixed by 'Table :'. It can be opened using the normal table constructor which will remove the prefix. - a struct which is returned as a dict. A struct is fully nestable, thus each field in the struct can have one of the values described here. Similar to method :func:`fieldnames` a keyword name can be given consisting of multiple parts separated by dots. This represents nested structs, thus gives the value of a field in a struct (in a struct, etc.). Instead of a keyword name an index can be given which returns the value of the i-th keyword. """ if isinstance(keyword, str): return self._getkeyword('', keyword, -1) else: return self._getkeyword('', '', keyword)
[ "def", "getkeyword", "(", "self", ",", "keyword", ")", ":", "if", "isinstance", "(", "keyword", ",", "str", ")", ":", "return", "self", ".", "_getkeyword", "(", "''", ",", "keyword", ",", "-", "1", ")", "else", ":", "return", "self", ".", "_getkeywor...
Get the value of a table keyword. The value of a keyword can be a: - scalar which is returned as a normal python scalar. - an array which is returned as a numpy array. - a reference to a table which is returned as a string containing its name prefixed by 'Table :'. It can be opened using the normal table constructor which will remove the prefix. - a struct which is returned as a dict. A struct is fully nestable, thus each field in the struct can have one of the values described here. Similar to method :func:`fieldnames` a keyword name can be given consisting of multiple parts separated by dots. This represents nested structs, thus gives the value of a field in a struct (in a struct, etc.). Instead of a keyword name an index can be given which returns the value of the i-th keyword.
[ "Get", "the", "value", "of", "a", "table", "keyword", "." ]
975510861ea005f7919dd9e438b5f98a1682eebe
https://github.com/casacore/python-casacore/blob/975510861ea005f7919dd9e438b5f98a1682eebe/casacore/tables/table.py#L1307-L1333
train
23,040
casacore/python-casacore
casacore/tables/table.py
table.getcolkeyword
def getcolkeyword(self, columnname, keyword): """Get the value of a column keyword. It is similar to :func:`getkeyword`. """ if isinstance(keyword, str): return self._getkeyword(columnname, keyword, -1) else: return self._getkeyword(columnname, '', keyword)
python
def getcolkeyword(self, columnname, keyword): """Get the value of a column keyword. It is similar to :func:`getkeyword`. """ if isinstance(keyword, str): return self._getkeyword(columnname, keyword, -1) else: return self._getkeyword(columnname, '', keyword)
[ "def", "getcolkeyword", "(", "self", ",", "columnname", ",", "keyword", ")", ":", "if", "isinstance", "(", "keyword", ",", "str", ")", ":", "return", "self", ".", "_getkeyword", "(", "columnname", ",", "keyword", ",", "-", "1", ")", "else", ":", "retur...
Get the value of a column keyword. It is similar to :func:`getkeyword`.
[ "Get", "the", "value", "of", "a", "column", "keyword", "." ]
975510861ea005f7919dd9e438b5f98a1682eebe
https://github.com/casacore/python-casacore/blob/975510861ea005f7919dd9e438b5f98a1682eebe/casacore/tables/table.py#L1335-L1344
train
23,041
casacore/python-casacore
casacore/tables/table.py
table.getsubtables
def getsubtables(self): """Get the names of all subtables.""" keyset = self.getkeywords() names = [] for key, value in keyset.items(): if isinstance(value, str) and value.find('Table: ') == 0: names.append(_do_remove_prefix(value)) return names
python
def getsubtables(self): """Get the names of all subtables.""" keyset = self.getkeywords() names = [] for key, value in keyset.items(): if isinstance(value, str) and value.find('Table: ') == 0: names.append(_do_remove_prefix(value)) return names
[ "def", "getsubtables", "(", "self", ")", ":", "keyset", "=", "self", ".", "getkeywords", "(", ")", "names", "=", "[", "]", "for", "key", ",", "value", "in", "keyset", ".", "items", "(", ")", ":", "if", "isinstance", "(", "value", ",", "str", ")", ...
Get the names of all subtables.
[ "Get", "the", "names", "of", "all", "subtables", "." ]
975510861ea005f7919dd9e438b5f98a1682eebe
https://github.com/casacore/python-casacore/blob/975510861ea005f7919dd9e438b5f98a1682eebe/casacore/tables/table.py#L1364-L1371
train
23,042
casacore/python-casacore
casacore/tables/table.py
table.putkeyword
def putkeyword(self, keyword, value, makesubrecord=False): """Put the value of a table keyword. The value of a keyword can be a: - scalar which can be given a normal python scalar or numpy scalar. - an array which can be given as a numpy array. A 1-dimensional array can also be given as a sequence (tuple or list). - a reference to a table which can be given as a table object or as a string containing its name prefixed by 'Table :'. - a struct which can be given as a dict. A struct is fully nestable, thus each field in the dict can be one of the values described here. The only exception is that a table value can only be given by the string. If the keyword already exists, the type of the new value should match the existing one (e.g. a scalar cannot be replaced by an array). Similar to method :func:`getkeyword` a keyword name can be given consisting of multiple parts separated by dots. This represents nested structs, thus puts the value into a field in a struct (in a struct, etc.). If `makesubrecord=True` structs will be created for the keyword name parts that do not exist. Instead of a keyword name an index can be given which returns the value of the i-th keyword. """ val = value if isinstance(val, table): val = _add_prefix(val.name()) if isinstance(keyword, str): return self._putkeyword('', keyword, -1, makesubrecord, val) else: return self._putkeyword('', '', keyword, makesubrecord, val)
python
def putkeyword(self, keyword, value, makesubrecord=False): """Put the value of a table keyword. The value of a keyword can be a: - scalar which can be given a normal python scalar or numpy scalar. - an array which can be given as a numpy array. A 1-dimensional array can also be given as a sequence (tuple or list). - a reference to a table which can be given as a table object or as a string containing its name prefixed by 'Table :'. - a struct which can be given as a dict. A struct is fully nestable, thus each field in the dict can be one of the values described here. The only exception is that a table value can only be given by the string. If the keyword already exists, the type of the new value should match the existing one (e.g. a scalar cannot be replaced by an array). Similar to method :func:`getkeyword` a keyword name can be given consisting of multiple parts separated by dots. This represents nested structs, thus puts the value into a field in a struct (in a struct, etc.). If `makesubrecord=True` structs will be created for the keyword name parts that do not exist. Instead of a keyword name an index can be given which returns the value of the i-th keyword. """ val = value if isinstance(val, table): val = _add_prefix(val.name()) if isinstance(keyword, str): return self._putkeyword('', keyword, -1, makesubrecord, val) else: return self._putkeyword('', '', keyword, makesubrecord, val)
[ "def", "putkeyword", "(", "self", ",", "keyword", ",", "value", ",", "makesubrecord", "=", "False", ")", ":", "val", "=", "value", "if", "isinstance", "(", "val", ",", "table", ")", ":", "val", "=", "_add_prefix", "(", "val", ".", "name", "(", ")", ...
Put the value of a table keyword. The value of a keyword can be a: - scalar which can be given a normal python scalar or numpy scalar. - an array which can be given as a numpy array. A 1-dimensional array can also be given as a sequence (tuple or list). - a reference to a table which can be given as a table object or as a string containing its name prefixed by 'Table :'. - a struct which can be given as a dict. A struct is fully nestable, thus each field in the dict can be one of the values described here. The only exception is that a table value can only be given by the string. If the keyword already exists, the type of the new value should match the existing one (e.g. a scalar cannot be replaced by an array). Similar to method :func:`getkeyword` a keyword name can be given consisting of multiple parts separated by dots. This represents nested structs, thus puts the value into a field in a struct (in a struct, etc.). If `makesubrecord=True` structs will be created for the keyword name parts that do not exist. Instead of a keyword name an index can be given which returns the value of the i-th keyword.
[ "Put", "the", "value", "of", "a", "table", "keyword", "." ]
975510861ea005f7919dd9e438b5f98a1682eebe
https://github.com/casacore/python-casacore/blob/975510861ea005f7919dd9e438b5f98a1682eebe/casacore/tables/table.py#L1373-L1408
train
23,043
casacore/python-casacore
casacore/tables/table.py
table.removekeyword
def removekeyword(self, keyword): """Remove a table keyword. Similar to :func:`getkeyword` the name can consist of multiple parts. In that case a field in a struct will be removed. Instead of a keyword name an index can be given which removes the i-th keyword. """ if isinstance(keyword, str): self._removekeyword('', keyword, -1) else: self._removekeyword('', '', keyword)
python
def removekeyword(self, keyword): """Remove a table keyword. Similar to :func:`getkeyword` the name can consist of multiple parts. In that case a field in a struct will be removed. Instead of a keyword name an index can be given which removes the i-th keyword. """ if isinstance(keyword, str): self._removekeyword('', keyword, -1) else: self._removekeyword('', '', keyword)
[ "def", "removekeyword", "(", "self", ",", "keyword", ")", ":", "if", "isinstance", "(", "keyword", ",", "str", ")", ":", "self", ".", "_removekeyword", "(", "''", ",", "keyword", ",", "-", "1", ")", "else", ":", "self", ".", "_removekeyword", "(", "'...
Remove a table keyword. Similar to :func:`getkeyword` the name can consist of multiple parts. In that case a field in a struct will be removed. Instead of a keyword name an index can be given which removes the i-th keyword.
[ "Remove", "a", "table", "keyword", "." ]
975510861ea005f7919dd9e438b5f98a1682eebe
https://github.com/casacore/python-casacore/blob/975510861ea005f7919dd9e438b5f98a1682eebe/casacore/tables/table.py#L1444-L1457
train
23,044
casacore/python-casacore
casacore/tables/table.py
table.removecolkeyword
def removecolkeyword(self, columnname, keyword): """Remove a column keyword. It is similar to :func:`removekeyword`. """ if isinstance(keyword, str): self._removekeyword(columnname, keyword, -1) else: self._removekeyword(columnname, '', keyword)
python
def removecolkeyword(self, columnname, keyword): """Remove a column keyword. It is similar to :func:`removekeyword`. """ if isinstance(keyword, str): self._removekeyword(columnname, keyword, -1) else: self._removekeyword(columnname, '', keyword)
[ "def", "removecolkeyword", "(", "self", ",", "columnname", ",", "keyword", ")", ":", "if", "isinstance", "(", "keyword", ",", "str", ")", ":", "self", ".", "_removekeyword", "(", "columnname", ",", "keyword", ",", "-", "1", ")", "else", ":", "self", "....
Remove a column keyword. It is similar to :func:`removekeyword`.
[ "Remove", "a", "column", "keyword", "." ]
975510861ea005f7919dd9e438b5f98a1682eebe
https://github.com/casacore/python-casacore/blob/975510861ea005f7919dd9e438b5f98a1682eebe/casacore/tables/table.py#L1459-L1468
train
23,045
casacore/python-casacore
casacore/tables/table.py
table.getdesc
def getdesc(self, actual=True): """Get the table description. By default it returns the actual description (thus telling the actual array shapes and data managers used). `actual=False` means that the original description as made by :func:`maketabdesc` is returned. """ tabledesc = self._getdesc(actual, True) # Strip out 0 length "HCcoordnames" and "HCidnames" # as these aren't valid. (See tabledefinehypercolumn) hcdefs = tabledesc.get('_define_hypercolumn_', {}) for c, hcdef in hcdefs.iteritems(): if "HCcoordnames" in hcdef and len(hcdef["HCcoordnames"]) == 0: del hcdef["HCcoordnames"] if "HCidnames" in hcdef and len(hcdef["HCidnames"]) == 0: del hcdef["HCidnames"] return tabledesc
python
def getdesc(self, actual=True): """Get the table description. By default it returns the actual description (thus telling the actual array shapes and data managers used). `actual=False` means that the original description as made by :func:`maketabdesc` is returned. """ tabledesc = self._getdesc(actual, True) # Strip out 0 length "HCcoordnames" and "HCidnames" # as these aren't valid. (See tabledefinehypercolumn) hcdefs = tabledesc.get('_define_hypercolumn_', {}) for c, hcdef in hcdefs.iteritems(): if "HCcoordnames" in hcdef and len(hcdef["HCcoordnames"]) == 0: del hcdef["HCcoordnames"] if "HCidnames" in hcdef and len(hcdef["HCidnames"]) == 0: del hcdef["HCidnames"] return tabledesc
[ "def", "getdesc", "(", "self", ",", "actual", "=", "True", ")", ":", "tabledesc", "=", "self", ".", "_getdesc", "(", "actual", ",", "True", ")", "# Strip out 0 length \"HCcoordnames\" and \"HCidnames\"", "# as these aren't valid. (See tabledefinehypercolumn)", "hcdefs", ...
Get the table description. By default it returns the actual description (thus telling the actual array shapes and data managers used). `actual=False` means that the original description as made by :func:`maketabdesc` is returned.
[ "Get", "the", "table", "description", "." ]
975510861ea005f7919dd9e438b5f98a1682eebe
https://github.com/casacore/python-casacore/blob/975510861ea005f7919dd9e438b5f98a1682eebe/casacore/tables/table.py#L1470-L1491
train
23,046
casacore/python-casacore
casacore/tables/table.py
table.getcoldesc
def getcoldesc(self, columnname, actual=True): """Get the description of a column. By default it returns the actual description (thus telling the actual array shapes and data managers used). `actual=False` means that the original description as made by :func:`makescacoldesc` or :func:`makearrcoldesc` is returned. """ return self._getcoldesc(columnname, actual, True)
python
def getcoldesc(self, columnname, actual=True): """Get the description of a column. By default it returns the actual description (thus telling the actual array shapes and data managers used). `actual=False` means that the original description as made by :func:`makescacoldesc` or :func:`makearrcoldesc` is returned. """ return self._getcoldesc(columnname, actual, True)
[ "def", "getcoldesc", "(", "self", ",", "columnname", ",", "actual", "=", "True", ")", ":", "return", "self", ".", "_getcoldesc", "(", "columnname", ",", "actual", ",", "True", ")" ]
Get the description of a column. By default it returns the actual description (thus telling the actual array shapes and data managers used). `actual=False` means that the original description as made by :func:`makescacoldesc` or :func:`makearrcoldesc` is returned.
[ "Get", "the", "description", "of", "a", "column", "." ]
975510861ea005f7919dd9e438b5f98a1682eebe
https://github.com/casacore/python-casacore/blob/975510861ea005f7919dd9e438b5f98a1682eebe/casacore/tables/table.py#L1493-L1502
train
23,047
casacore/python-casacore
casacore/tables/table.py
table.coldesc
def coldesc(self, columnname, actual=True): """Make the description of a column. Make the description object of the given column as :func:`makecoldesc` is doing with the description given by :func:`getcoldesc`. """ import casacore.tables.tableutil as pt return pt.makecoldesc(columnname, self.getcoldesc(columnname, actual))
python
def coldesc(self, columnname, actual=True): """Make the description of a column. Make the description object of the given column as :func:`makecoldesc` is doing with the description given by :func:`getcoldesc`. """ import casacore.tables.tableutil as pt return pt.makecoldesc(columnname, self.getcoldesc(columnname, actual))
[ "def", "coldesc", "(", "self", ",", "columnname", ",", "actual", "=", "True", ")", ":", "import", "casacore", ".", "tables", ".", "tableutil", "as", "pt", "return", "pt", ".", "makecoldesc", "(", "columnname", ",", "self", ".", "getcoldesc", "(", "column...
Make the description of a column. Make the description object of the given column as :func:`makecoldesc` is doing with the description given by :func:`getcoldesc`.
[ "Make", "the", "description", "of", "a", "column", "." ]
975510861ea005f7919dd9e438b5f98a1682eebe
https://github.com/casacore/python-casacore/blob/975510861ea005f7919dd9e438b5f98a1682eebe/casacore/tables/table.py#L1504-L1513
train
23,048
casacore/python-casacore
casacore/tables/table.py
table.getdminfo
def getdminfo(self, columnname=None): """Get data manager info. Each column in a table is stored using a data manager. A storage manager is a data manager storing the physically in a file. A virtual column engine is a data manager that does not store data but calculates it on the fly (e.g. scaling floats to short to reduce storage needs). By default this method returns a dict telling the data managers used. Each field in the dict is a dict containing: - NAME telling the (unique) name of the data manager - TYPE telling the type of data manager (e.g. TiledShapeStMan) - SEQNR telling the sequence number of the data manager (is ''i'' in table.f<i> for storage managers) - SPEC is a dict holding the data manager specification - COLUMNS is a list giving the columns stored by this data manager When giving a column name the data manager info of that particular column is returned (without the COLUMNS field). It can, for instance, be used when adding a column using :func:`addcols` that should use the same data manager type as an existing column. However, when doing that care should be taken to change the NAME because each data manager name has to be unique. """ dminfo = self._getdminfo() if columnname is None: return dminfo # Find the info for the given column for fld in dminfo.values(): if columnname in fld["COLUMNS"]: fldc = fld.copy() del fldc['COLUMNS'] # remove COLUMNS field return fldc raise KeyError("Column " + columnname + " does not exist")
python
def getdminfo(self, columnname=None): """Get data manager info. Each column in a table is stored using a data manager. A storage manager is a data manager storing the physically in a file. A virtual column engine is a data manager that does not store data but calculates it on the fly (e.g. scaling floats to short to reduce storage needs). By default this method returns a dict telling the data managers used. Each field in the dict is a dict containing: - NAME telling the (unique) name of the data manager - TYPE telling the type of data manager (e.g. TiledShapeStMan) - SEQNR telling the sequence number of the data manager (is ''i'' in table.f<i> for storage managers) - SPEC is a dict holding the data manager specification - COLUMNS is a list giving the columns stored by this data manager When giving a column name the data manager info of that particular column is returned (without the COLUMNS field). It can, for instance, be used when adding a column using :func:`addcols` that should use the same data manager type as an existing column. However, when doing that care should be taken to change the NAME because each data manager name has to be unique. """ dminfo = self._getdminfo() if columnname is None: return dminfo # Find the info for the given column for fld in dminfo.values(): if columnname in fld["COLUMNS"]: fldc = fld.copy() del fldc['COLUMNS'] # remove COLUMNS field return fldc raise KeyError("Column " + columnname + " does not exist")
[ "def", "getdminfo", "(", "self", ",", "columnname", "=", "None", ")", ":", "dminfo", "=", "self", ".", "_getdminfo", "(", ")", "if", "columnname", "is", "None", ":", "return", "dminfo", "# Find the info for the given column", "for", "fld", "in", "dminfo", "....
Get data manager info. Each column in a table is stored using a data manager. A storage manager is a data manager storing the physically in a file. A virtual column engine is a data manager that does not store data but calculates it on the fly (e.g. scaling floats to short to reduce storage needs). By default this method returns a dict telling the data managers used. Each field in the dict is a dict containing: - NAME telling the (unique) name of the data manager - TYPE telling the type of data manager (e.g. TiledShapeStMan) - SEQNR telling the sequence number of the data manager (is ''i'' in table.f<i> for storage managers) - SPEC is a dict holding the data manager specification - COLUMNS is a list giving the columns stored by this data manager When giving a column name the data manager info of that particular column is returned (without the COLUMNS field). It can, for instance, be used when adding a column using :func:`addcols` that should use the same data manager type as an existing column. However, when doing that care should be taken to change the NAME because each data manager name has to be unique.
[ "Get", "data", "manager", "info", "." ]
975510861ea005f7919dd9e438b5f98a1682eebe
https://github.com/casacore/python-casacore/blob/975510861ea005f7919dd9e438b5f98a1682eebe/casacore/tables/table.py#L1515-L1551
train
23,049
casacore/python-casacore
casacore/tables/table.py
table.setdmprop
def setdmprop(self, name, properties, bycolumn=True): """Set properties of a data manager. Properties (e.g. cachesize) of a data manager can be changed by defining them appropriately in the properties argument (a dict). Current values can be obtained using function :func:`getdmprop` which also serves as a template. The dict can contain more fields; only the fields with the names as returned by getdmprop are handled. The data manager can be specified in two ways: by data manager name or by the name of a column using the data manager. The argument `bycolumn` defines which way is used (default is by column name). """ return self._setdmprop(name, properties, bycolumn)
python
def setdmprop(self, name, properties, bycolumn=True): """Set properties of a data manager. Properties (e.g. cachesize) of a data manager can be changed by defining them appropriately in the properties argument (a dict). Current values can be obtained using function :func:`getdmprop` which also serves as a template. The dict can contain more fields; only the fields with the names as returned by getdmprop are handled. The data manager can be specified in two ways: by data manager name or by the name of a column using the data manager. The argument `bycolumn` defines which way is used (default is by column name). """ return self._setdmprop(name, properties, bycolumn)
[ "def", "setdmprop", "(", "self", ",", "name", ",", "properties", ",", "bycolumn", "=", "True", ")", ":", "return", "self", ".", "_setdmprop", "(", "name", ",", "properties", ",", "bycolumn", ")" ]
Set properties of a data manager. Properties (e.g. cachesize) of a data manager can be changed by defining them appropriately in the properties argument (a dict). Current values can be obtained using function :func:`getdmprop` which also serves as a template. The dict can contain more fields; only the fields with the names as returned by getdmprop are handled. The data manager can be specified in two ways: by data manager name or by the name of a column using the data manager. The argument `bycolumn` defines which way is used (default is by column name).
[ "Set", "properties", "of", "a", "data", "manager", "." ]
975510861ea005f7919dd9e438b5f98a1682eebe
https://github.com/casacore/python-casacore/blob/975510861ea005f7919dd9e438b5f98a1682eebe/casacore/tables/table.py#L1575-L1589
train
23,050
casacore/python-casacore
casacore/tables/table.py
table.showstructure
def showstructure(self, dataman=True, column=True, subtable=False, sort=False): """Show table structure in a formatted string. The structure of this table and optionally its subtables is shown. It shows the data manager info and column descriptions. Optionally the columns are sorted in alphabetical order. `dataman` Show data manager info? If False, only column info is shown. If True, data manager info and columns per data manager are shown. `column` Show column description per data manager? Only takes effect if dataman=True. `subtable` Show the structure of all subtables (recursively). The names of subtables are always shown. 'sort' Sort the columns in alphabetical order? """ return self._showstructure(dataman, column, subtable, sort)
python
def showstructure(self, dataman=True, column=True, subtable=False, sort=False): """Show table structure in a formatted string. The structure of this table and optionally its subtables is shown. It shows the data manager info and column descriptions. Optionally the columns are sorted in alphabetical order. `dataman` Show data manager info? If False, only column info is shown. If True, data manager info and columns per data manager are shown. `column` Show column description per data manager? Only takes effect if dataman=True. `subtable` Show the structure of all subtables (recursively). The names of subtables are always shown. 'sort' Sort the columns in alphabetical order? """ return self._showstructure(dataman, column, subtable, sort)
[ "def", "showstructure", "(", "self", ",", "dataman", "=", "True", ",", "column", "=", "True", ",", "subtable", "=", "False", ",", "sort", "=", "False", ")", ":", "return", "self", ".", "_showstructure", "(", "dataman", ",", "column", ",", "subtable", "...
Show table structure in a formatted string. The structure of this table and optionally its subtables is shown. It shows the data manager info and column descriptions. Optionally the columns are sorted in alphabetical order. `dataman` Show data manager info? If False, only column info is shown. If True, data manager info and columns per data manager are shown. `column` Show column description per data manager? Only takes effect if dataman=True. `subtable` Show the structure of all subtables (recursively). The names of subtables are always shown. 'sort' Sort the columns in alphabetical order?
[ "Show", "table", "structure", "in", "a", "formatted", "string", "." ]
975510861ea005f7919dd9e438b5f98a1682eebe
https://github.com/casacore/python-casacore/blob/975510861ea005f7919dd9e438b5f98a1682eebe/casacore/tables/table.py#L1591-L1612
train
23,051
casacore/python-casacore
casacore/tables/table.py
table.summary
def summary(self, recurse=False): """Print a summary of the table. It prints the number of columns and rows, column names, and table and column keywords. If `recurse=True` it also prints the summary of all subtables, i.e. tables referenced by table keywords. """ six.print_('Table summary:', self.name()) six.print_('Shape:', self.ncols(), 'columns by', self.nrows(), 'rows') six.print_('Info:', self.info()) tkeys = self.getkeywords() if (len(tkeys) > 0): six.print_('Table keywords:', tkeys) columns = self.colnames() if (len(columns) > 0): six.print_('Columns:', columns) for column in columns: ckeys = self.getcolkeywords(column) if (len(ckeys) > 0): six.print_(column, 'keywords:', ckeys) if (recurse): for key, value in tkeys.items(): tabname = _remove_prefix(value) six.print_('Summarizing subtable:', tabname) lt = table(tabname) if (not lt.summary(recurse)): break return True
python
def summary(self, recurse=False): """Print a summary of the table. It prints the number of columns and rows, column names, and table and column keywords. If `recurse=True` it also prints the summary of all subtables, i.e. tables referenced by table keywords. """ six.print_('Table summary:', self.name()) six.print_('Shape:', self.ncols(), 'columns by', self.nrows(), 'rows') six.print_('Info:', self.info()) tkeys = self.getkeywords() if (len(tkeys) > 0): six.print_('Table keywords:', tkeys) columns = self.colnames() if (len(columns) > 0): six.print_('Columns:', columns) for column in columns: ckeys = self.getcolkeywords(column) if (len(ckeys) > 0): six.print_(column, 'keywords:', ckeys) if (recurse): for key, value in tkeys.items(): tabname = _remove_prefix(value) six.print_('Summarizing subtable:', tabname) lt = table(tabname) if (not lt.summary(recurse)): break return True
[ "def", "summary", "(", "self", ",", "recurse", "=", "False", ")", ":", "six", ".", "print_", "(", "'Table summary:'", ",", "self", ".", "name", "(", ")", ")", "six", ".", "print_", "(", "'Shape:'", ",", "self", ".", "ncols", "(", ")", ",", "'column...
Print a summary of the table. It prints the number of columns and rows, column names, and table and column keywords. If `recurse=True` it also prints the summary of all subtables, i.e. tables referenced by table keywords.
[ "Print", "a", "summary", "of", "the", "table", "." ]
975510861ea005f7919dd9e438b5f98a1682eebe
https://github.com/casacore/python-casacore/blob/975510861ea005f7919dd9e438b5f98a1682eebe/casacore/tables/table.py#L1614-L1643
train
23,052
casacore/python-casacore
casacore/tables/table.py
table.selectrows
def selectrows(self, rownrs): """Return a reference table containing the given rows.""" t = self._selectrows(rownrs, name='') # selectrows returns a Table object, so turn that into table. return table(t, _oper=3)
python
def selectrows(self, rownrs): """Return a reference table containing the given rows.""" t = self._selectrows(rownrs, name='') # selectrows returns a Table object, so turn that into table. return table(t, _oper=3)
[ "def", "selectrows", "(", "self", ",", "rownrs", ")", ":", "t", "=", "self", ".", "_selectrows", "(", "rownrs", ",", "name", "=", "''", ")", "# selectrows returns a Table object, so turn that into table.", "return", "table", "(", "t", ",", "_oper", "=", "3", ...
Return a reference table containing the given rows.
[ "Return", "a", "reference", "table", "containing", "the", "given", "rows", "." ]
975510861ea005f7919dd9e438b5f98a1682eebe
https://github.com/casacore/python-casacore/blob/975510861ea005f7919dd9e438b5f98a1682eebe/casacore/tables/table.py#L1645-L1649
train
23,053
casacore/python-casacore
casacore/tables/table.py
table.query
def query(self, query='', name='', sortlist='', columns='', limit=0, offset=0, style='Python'): """Query the table and return the result as a reference table. This method queries the table. It forms a `TaQL <../../doc/199.html>`_ command from the given arguments and executes it using the :func:`taql` function. The result is returned in a so-called reference table which references the selected columns and rows in the original table. Usually a reference table is temporary, but it can be made persistent by giving it a name. Note that a reference table is handled as any table, thus can be queried again. All arguments are optional, but at least one of `query`, `name`, `sortlist`, and `columns` should be used. See the `TaQL note <../../doc/199.html>`_ for the detailed description of the the arguments representing the various parts of a TaQL command. `query` The WHERE part of a TaQL command. `name` The name of the reference table if it is to be made persistent. `sortlist` The ORDERBY part of a TaQL command. It is a single string in which commas have to be used to separate sort keys. `columns` The columns to be selected (projection in data base terms). It is a single string in which commas have to be used to separate column names. Apart from column names, expressions can be given as well. `limit` If > 0, maximum number of rows to be selected. `offset` If > 0, ignore the first N matches. `style` The TaQL syntax style to be used (defaults to Python). """ if not query and not sortlist and not columns and \ limit <= 0 and offset <= 0: raise ValueError('No selection done (arguments query, ' + 'sortlist, columns, limit, and offset are empty)') command = 'select ' if columns: command += columns command += ' from $1' if query: command += ' where ' + query if sortlist: command += ' orderby ' + sortlist if limit > 0: command += ' limit %d' % limit if offset > 0: command += ' offset %d' % offset if name: command += ' giving ' + name return tablecommand(command, style, [self])
python
def query(self, query='', name='', sortlist='', columns='', limit=0, offset=0, style='Python'): """Query the table and return the result as a reference table. This method queries the table. It forms a `TaQL <../../doc/199.html>`_ command from the given arguments and executes it using the :func:`taql` function. The result is returned in a so-called reference table which references the selected columns and rows in the original table. Usually a reference table is temporary, but it can be made persistent by giving it a name. Note that a reference table is handled as any table, thus can be queried again. All arguments are optional, but at least one of `query`, `name`, `sortlist`, and `columns` should be used. See the `TaQL note <../../doc/199.html>`_ for the detailed description of the the arguments representing the various parts of a TaQL command. `query` The WHERE part of a TaQL command. `name` The name of the reference table if it is to be made persistent. `sortlist` The ORDERBY part of a TaQL command. It is a single string in which commas have to be used to separate sort keys. `columns` The columns to be selected (projection in data base terms). It is a single string in which commas have to be used to separate column names. Apart from column names, expressions can be given as well. `limit` If > 0, maximum number of rows to be selected. `offset` If > 0, ignore the first N matches. `style` The TaQL syntax style to be used (defaults to Python). """ if not query and not sortlist and not columns and \ limit <= 0 and offset <= 0: raise ValueError('No selection done (arguments query, ' + 'sortlist, columns, limit, and offset are empty)') command = 'select ' if columns: command += columns command += ' from $1' if query: command += ' where ' + query if sortlist: command += ' orderby ' + sortlist if limit > 0: command += ' limit %d' % limit if offset > 0: command += ' offset %d' % offset if name: command += ' giving ' + name return tablecommand(command, style, [self])
[ "def", "query", "(", "self", ",", "query", "=", "''", ",", "name", "=", "''", ",", "sortlist", "=", "''", ",", "columns", "=", "''", ",", "limit", "=", "0", ",", "offset", "=", "0", ",", "style", "=", "'Python'", ")", ":", "if", "not", "query",...
Query the table and return the result as a reference table. This method queries the table. It forms a `TaQL <../../doc/199.html>`_ command from the given arguments and executes it using the :func:`taql` function. The result is returned in a so-called reference table which references the selected columns and rows in the original table. Usually a reference table is temporary, but it can be made persistent by giving it a name. Note that a reference table is handled as any table, thus can be queried again. All arguments are optional, but at least one of `query`, `name`, `sortlist`, and `columns` should be used. See the `TaQL note <../../doc/199.html>`_ for the detailed description of the the arguments representing the various parts of a TaQL command. `query` The WHERE part of a TaQL command. `name` The name of the reference table if it is to be made persistent. `sortlist` The ORDERBY part of a TaQL command. It is a single string in which commas have to be used to separate sort keys. `columns` The columns to be selected (projection in data base terms). It is a single string in which commas have to be used to separate column names. Apart from column names, expressions can be given as well. `limit` If > 0, maximum number of rows to be selected. `offset` If > 0, ignore the first N matches. `style` The TaQL syntax style to be used (defaults to Python).
[ "Query", "the", "table", "and", "return", "the", "result", "as", "a", "reference", "table", "." ]
975510861ea005f7919dd9e438b5f98a1682eebe
https://github.com/casacore/python-casacore/blob/975510861ea005f7919dd9e438b5f98a1682eebe/casacore/tables/table.py#L1651-L1709
train
23,054
casacore/python-casacore
casacore/tables/table.py
table.sort
def sort(self, sortlist, name='', limit=0, offset=0, style='Python'): """Sort the table and return the result as a reference table. This method sorts the table. It forms a `TaQL <../../doc/199.html>`_ command from the given arguments and executes it using the :func:`taql` function. The result is returned in a so-called reference table which references the columns and rows in the original table. Usually a reference table is temporary, but it can be made persistent by giving it a name. Note that a reference table is handled as any table, thus can be queried again. `sortlist` The ORDERBY part of a TaQL command. It is a single string in which commas have to be used to separate sort keys. A sort key can be the name of a column, but it can be an expression as well. `name` The name of the reference table if it is to be made persistent. `limit` If > 0, maximum number of rows to be selected after the sort step. It can, for instance, be used to select the N highest values. `offset` If > 0, ignore the first `offset` matches after the sort step. `style` The TaQL syntax style to be used (defaults to Python). """ command = 'select from $1 orderby ' + sortlist if limit > 0: command += ' limit %d' % limit if offset > 0: command += ' offset %d' % offset if name: command += ' giving ' + name return tablecommand(command, style, [self])
python
def sort(self, sortlist, name='', limit=0, offset=0, style='Python'): """Sort the table and return the result as a reference table. This method sorts the table. It forms a `TaQL <../../doc/199.html>`_ command from the given arguments and executes it using the :func:`taql` function. The result is returned in a so-called reference table which references the columns and rows in the original table. Usually a reference table is temporary, but it can be made persistent by giving it a name. Note that a reference table is handled as any table, thus can be queried again. `sortlist` The ORDERBY part of a TaQL command. It is a single string in which commas have to be used to separate sort keys. A sort key can be the name of a column, but it can be an expression as well. `name` The name of the reference table if it is to be made persistent. `limit` If > 0, maximum number of rows to be selected after the sort step. It can, for instance, be used to select the N highest values. `offset` If > 0, ignore the first `offset` matches after the sort step. `style` The TaQL syntax style to be used (defaults to Python). """ command = 'select from $1 orderby ' + sortlist if limit > 0: command += ' limit %d' % limit if offset > 0: command += ' offset %d' % offset if name: command += ' giving ' + name return tablecommand(command, style, [self])
[ "def", "sort", "(", "self", ",", "sortlist", ",", "name", "=", "''", ",", "limit", "=", "0", ",", "offset", "=", "0", ",", "style", "=", "'Python'", ")", ":", "command", "=", "'select from $1 orderby '", "+", "sortlist", "if", "limit", ">", "0", ":",...
Sort the table and return the result as a reference table. This method sorts the table. It forms a `TaQL <../../doc/199.html>`_ command from the given arguments and executes it using the :func:`taql` function. The result is returned in a so-called reference table which references the columns and rows in the original table. Usually a reference table is temporary, but it can be made persistent by giving it a name. Note that a reference table is handled as any table, thus can be queried again. `sortlist` The ORDERBY part of a TaQL command. It is a single string in which commas have to be used to separate sort keys. A sort key can be the name of a column, but it can be an expression as well. `name` The name of the reference table if it is to be made persistent. `limit` If > 0, maximum number of rows to be selected after the sort step. It can, for instance, be used to select the N highest values. `offset` If > 0, ignore the first `offset` matches after the sort step. `style` The TaQL syntax style to be used (defaults to Python).
[ "Sort", "the", "table", "and", "return", "the", "result", "as", "a", "reference", "table", "." ]
975510861ea005f7919dd9e438b5f98a1682eebe
https://github.com/casacore/python-casacore/blob/975510861ea005f7919dd9e438b5f98a1682eebe/casacore/tables/table.py#L1711-L1747
train
23,055
casacore/python-casacore
casacore/tables/table.py
table.select
def select(self, columns, name='', style='Python'): """Select columns and return the result as a reference table. This method represents the SELECT part of a TaQL command using the given columns (or column expressions). It forms a `TaQL <../../doc/199.html>`_ command from the given arguments and executes it using the :func:`taql` function. The result is returned in a so-called reference table which references the columns and rows in the original table. Usually a reference table is temporary, but it can be made persistent by giving it a name. Note that a reference table is handled as any table, thus can be queried again. `columns` The columns to be selected (projection in data base terms). It is a single string in which commas have to be used to separate column names. Apart from column names, expressions can be given as well. `name` The name of the reference table if it is to be made persistent. `style` The TaQL syntax style to be used (defaults to Python). """ command = 'select ' + columns + ' from $1' if name: command += ' giving ' + name return tablecommand(command, style, [self])
python
def select(self, columns, name='', style='Python'): """Select columns and return the result as a reference table. This method represents the SELECT part of a TaQL command using the given columns (or column expressions). It forms a `TaQL <../../doc/199.html>`_ command from the given arguments and executes it using the :func:`taql` function. The result is returned in a so-called reference table which references the columns and rows in the original table. Usually a reference table is temporary, but it can be made persistent by giving it a name. Note that a reference table is handled as any table, thus can be queried again. `columns` The columns to be selected (projection in data base terms). It is a single string in which commas have to be used to separate column names. Apart from column names, expressions can be given as well. `name` The name of the reference table if it is to be made persistent. `style` The TaQL syntax style to be used (defaults to Python). """ command = 'select ' + columns + ' from $1' if name: command += ' giving ' + name return tablecommand(command, style, [self])
[ "def", "select", "(", "self", ",", "columns", ",", "name", "=", "''", ",", "style", "=", "'Python'", ")", ":", "command", "=", "'select '", "+", "columns", "+", "' from $1'", "if", "name", ":", "command", "+=", "' giving '", "+", "name", "return", "tab...
Select columns and return the result as a reference table. This method represents the SELECT part of a TaQL command using the given columns (or column expressions). It forms a `TaQL <../../doc/199.html>`_ command from the given arguments and executes it using the :func:`taql` function. The result is returned in a so-called reference table which references the columns and rows in the original table. Usually a reference table is temporary, but it can be made persistent by giving it a name. Note that a reference table is handled as any table, thus can be queried again. `columns` The columns to be selected (projection in data base terms). It is a single string in which commas have to be used to separate column names. Apart from column names, expressions can be given as well. `name` The name of the reference table if it is to be made persistent. `style` The TaQL syntax style to be used (defaults to Python).
[ "Select", "columns", "and", "return", "the", "result", "as", "a", "reference", "table", "." ]
975510861ea005f7919dd9e438b5f98a1682eebe
https://github.com/casacore/python-casacore/blob/975510861ea005f7919dd9e438b5f98a1682eebe/casacore/tables/table.py#L1749-L1776
train
23,056
casacore/python-casacore
casacore/tables/table.py
table.browse
def browse(self, wait=True, tempname="/tmp/seltable"): """ Browse a table using casabrowser or a simple wxwidget based browser. By default the casabrowser is used if it can be found (in your PATH). Otherwise the wxwidget one is used if wx can be loaded. The casabrowser can only browse tables that are persistent on disk. This gives problems for tables resulting from a query because they are held in memory only (unless an output table name was given). To make browsing of such tables possible, the argument `tempname` can be used to specify a table name that will be used to form a persistent table that can be browsed. Note that such a table is very small as it does not contain data, but only references to rows in the original table. The default for `tempname` is '/tmp/seltable'. If needed, the table can be deleted using the :func:`tabledelete` function. If `wait=False`, the casabrowser is started in the background. In that case the user should delete a possibly created copy of a temporary table. """ import os # Test if casabrowser can be found. # On OS-X 'which' always returns 0, so use test on top of it. # Nothing is written on stdout if not found. if os.system('test `which casabrowser`x != x') == 0: waitstr1 = "" waitstr2 = "foreground ..." if not wait: waitstr1 = " &" waitstr2 = "background ..." if self.iswritable(): six.print_("Flushing data and starting casabrowser in the " + waitstr2) else: six.print_("Starting casabrowser in the " + waitstr2) self.flush() self.unlock() if os.system('test -e ' + self.name() + '/table.dat') == 0: os.system('casabrowser ' + self.name() + waitstr1) elif len(tempname) > 0: six.print_(" making a persistent copy in table " + tempname) self.copy(tempname) os.system('casabrowser ' + tempname + waitstr1) if wait: from casacore.tables import tabledelete six.print_(" finished browsing") tabledelete(tempname) else: six.print_(" after browsing use tabledelete('" + tempname + "') to delete the copy") else: six.print_("Cannot browse because the table is in memory only") six.print_("You can browse a (shallow) persistent copy " + "of the table like: ") six.print_(" t.browse(True, '/tmp/tab1')") else: try: import wxPython except ImportError: six.print_('casabrowser nor wxPython can be found') return from wxPython.wx import wxPySimpleApp import sys app = wxPySimpleApp() from wxtablebrowser import CasaTestFrame frame = CasaTestFrame(None, sys.stdout, self) frame.Show(True) app.MainLoop()
python
def browse(self, wait=True, tempname="/tmp/seltable"): """ Browse a table using casabrowser or a simple wxwidget based browser. By default the casabrowser is used if it can be found (in your PATH). Otherwise the wxwidget one is used if wx can be loaded. The casabrowser can only browse tables that are persistent on disk. This gives problems for tables resulting from a query because they are held in memory only (unless an output table name was given). To make browsing of such tables possible, the argument `tempname` can be used to specify a table name that will be used to form a persistent table that can be browsed. Note that such a table is very small as it does not contain data, but only references to rows in the original table. The default for `tempname` is '/tmp/seltable'. If needed, the table can be deleted using the :func:`tabledelete` function. If `wait=False`, the casabrowser is started in the background. In that case the user should delete a possibly created copy of a temporary table. """ import os # Test if casabrowser can be found. # On OS-X 'which' always returns 0, so use test on top of it. # Nothing is written on stdout if not found. if os.system('test `which casabrowser`x != x') == 0: waitstr1 = "" waitstr2 = "foreground ..." if not wait: waitstr1 = " &" waitstr2 = "background ..." if self.iswritable(): six.print_("Flushing data and starting casabrowser in the " + waitstr2) else: six.print_("Starting casabrowser in the " + waitstr2) self.flush() self.unlock() if os.system('test -e ' + self.name() + '/table.dat') == 0: os.system('casabrowser ' + self.name() + waitstr1) elif len(tempname) > 0: six.print_(" making a persistent copy in table " + tempname) self.copy(tempname) os.system('casabrowser ' + tempname + waitstr1) if wait: from casacore.tables import tabledelete six.print_(" finished browsing") tabledelete(tempname) else: six.print_(" after browsing use tabledelete('" + tempname + "') to delete the copy") else: six.print_("Cannot browse because the table is in memory only") six.print_("You can browse a (shallow) persistent copy " + "of the table like: ") six.print_(" t.browse(True, '/tmp/tab1')") else: try: import wxPython except ImportError: six.print_('casabrowser nor wxPython can be found') return from wxPython.wx import wxPySimpleApp import sys app = wxPySimpleApp() from wxtablebrowser import CasaTestFrame frame = CasaTestFrame(None, sys.stdout, self) frame.Show(True) app.MainLoop()
[ "def", "browse", "(", "self", ",", "wait", "=", "True", ",", "tempname", "=", "\"/tmp/seltable\"", ")", ":", "import", "os", "# Test if casabrowser can be found.", "# On OS-X 'which' always returns 0, so use test on top of it.", "# Nothing is written on stdout if not found.", "...
Browse a table using casabrowser or a simple wxwidget based browser. By default the casabrowser is used if it can be found (in your PATH). Otherwise the wxwidget one is used if wx can be loaded. The casabrowser can only browse tables that are persistent on disk. This gives problems for tables resulting from a query because they are held in memory only (unless an output table name was given). To make browsing of such tables possible, the argument `tempname` can be used to specify a table name that will be used to form a persistent table that can be browsed. Note that such a table is very small as it does not contain data, but only references to rows in the original table. The default for `tempname` is '/tmp/seltable'. If needed, the table can be deleted using the :func:`tabledelete` function. If `wait=False`, the casabrowser is started in the background. In that case the user should delete a possibly created copy of a temporary table.
[ "Browse", "a", "table", "using", "casabrowser", "or", "a", "simple", "wxwidget", "based", "browser", "." ]
975510861ea005f7919dd9e438b5f98a1682eebe
https://github.com/casacore/python-casacore/blob/975510861ea005f7919dd9e438b5f98a1682eebe/casacore/tables/table.py#L1797-L1871
train
23,057
casacore/python-casacore
casacore/tables/table.py
table.view
def view(self, wait=True, tempname="/tmp/seltable"): """ View a table using casaviewer, casabrowser, or wxwidget based browser. The table is viewed depending on the type: MeasurementSet is viewed using casaviewer. Image is viewed using casaviewer. other are browsed using the :func:`browse` function. If the casaviewer cannot be found, all tables are browsed. The casaviewer can only display tables that are persistent on disk. This gives problems for tables resulting from a query because they are held in memory only (unless an output table name was given). To make viewing of such tables possible, the argument `tempname` can be used to specify a table name that will be used to form a persistent table that can be browsed. Note that such a table is very small as it does not contain data, but only references to rows in the original table. The default for `tempname` is '/tmp/seltable'. If needed, the table can be deleted using the :func:`tabledelete` function. If `wait=False`, the casaviewer is started in the background. In that case the user should delete a possibly created copy of a temporary table. """ import os # Determine the table type. # Test if casaviewer can be found. # On OS-X 'which' always returns 0, so use test on top of it. viewed = False type = self.info()["type"] if type == "Measurement Set" or type == "Image": if os.system('test -x `which casaviewer` > /dev/null 2>&1') == 0: waitstr1 = "" waitstr2 = "foreground ..." if not wait: waitstr1 = " &" waitstr2 = "background ..." if self.iswritable(): six.print_("Flushing data and starting casaviewer " + "in the " + waitstr2) else: six.print_("Starting casaviewer in the " + waitstr2) self.flush() self.unlock() if os.system('test -e ' + self.name() + '/table.dat') == 0: os.system('casaviewer ' + self.name() + waitstr1) viewed = True elif len(tempname) > 0: six.print_(" making a persistent copy in table " + tempname) self.copy(tempname) os.system('casaviewer ' + tempname + waitstr1) viewed = True if wait: from casacore.tables import tabledelete six.print_(" finished viewing") tabledelete(tempname) else: six.print_(" after viewing use tabledelete('" + tempname + "') to delete the copy") else: six.print_("Cannot browse because the table is " + "in memory only.") six.print_("You can browse a (shallow) persistent " + "copy of the table like:") six.print_(" t.view(True, '/tmp/tab1')") # Could not view the table, so browse it. if not viewed: self.browse(wait, tempname)
python
def view(self, wait=True, tempname="/tmp/seltable"): """ View a table using casaviewer, casabrowser, or wxwidget based browser. The table is viewed depending on the type: MeasurementSet is viewed using casaviewer. Image is viewed using casaviewer. other are browsed using the :func:`browse` function. If the casaviewer cannot be found, all tables are browsed. The casaviewer can only display tables that are persistent on disk. This gives problems for tables resulting from a query because they are held in memory only (unless an output table name was given). To make viewing of such tables possible, the argument `tempname` can be used to specify a table name that will be used to form a persistent table that can be browsed. Note that such a table is very small as it does not contain data, but only references to rows in the original table. The default for `tempname` is '/tmp/seltable'. If needed, the table can be deleted using the :func:`tabledelete` function. If `wait=False`, the casaviewer is started in the background. In that case the user should delete a possibly created copy of a temporary table. """ import os # Determine the table type. # Test if casaviewer can be found. # On OS-X 'which' always returns 0, so use test on top of it. viewed = False type = self.info()["type"] if type == "Measurement Set" or type == "Image": if os.system('test -x `which casaviewer` > /dev/null 2>&1') == 0: waitstr1 = "" waitstr2 = "foreground ..." if not wait: waitstr1 = " &" waitstr2 = "background ..." if self.iswritable(): six.print_("Flushing data and starting casaviewer " + "in the " + waitstr2) else: six.print_("Starting casaviewer in the " + waitstr2) self.flush() self.unlock() if os.system('test -e ' + self.name() + '/table.dat') == 0: os.system('casaviewer ' + self.name() + waitstr1) viewed = True elif len(tempname) > 0: six.print_(" making a persistent copy in table " + tempname) self.copy(tempname) os.system('casaviewer ' + tempname + waitstr1) viewed = True if wait: from casacore.tables import tabledelete six.print_(" finished viewing") tabledelete(tempname) else: six.print_(" after viewing use tabledelete('" + tempname + "') to delete the copy") else: six.print_("Cannot browse because the table is " + "in memory only.") six.print_("You can browse a (shallow) persistent " + "copy of the table like:") six.print_(" t.view(True, '/tmp/tab1')") # Could not view the table, so browse it. if not viewed: self.browse(wait, tempname)
[ "def", "view", "(", "self", ",", "wait", "=", "True", ",", "tempname", "=", "\"/tmp/seltable\"", ")", ":", "import", "os", "# Determine the table type.", "# Test if casaviewer can be found.", "# On OS-X 'which' always returns 0, so use test on top of it.", "viewed", "=", "F...
View a table using casaviewer, casabrowser, or wxwidget based browser. The table is viewed depending on the type: MeasurementSet is viewed using casaviewer. Image is viewed using casaviewer. other are browsed using the :func:`browse` function. If the casaviewer cannot be found, all tables are browsed. The casaviewer can only display tables that are persistent on disk. This gives problems for tables resulting from a query because they are held in memory only (unless an output table name was given). To make viewing of such tables possible, the argument `tempname` can be used to specify a table name that will be used to form a persistent table that can be browsed. Note that such a table is very small as it does not contain data, but only references to rows in the original table. The default for `tempname` is '/tmp/seltable'. If needed, the table can be deleted using the :func:`tabledelete` function. If `wait=False`, the casaviewer is started in the background. In that case the user should delete a possibly created copy of a temporary table.
[ "View", "a", "table", "using", "casaviewer", "casabrowser", "or", "wxwidget", "based", "browser", "." ]
975510861ea005f7919dd9e438b5f98a1682eebe
https://github.com/casacore/python-casacore/blob/975510861ea005f7919dd9e438b5f98a1682eebe/casacore/tables/table.py#L1873-L1950
train
23,058
casacore/python-casacore
casacore/tables/table.py
table._repr_html_
def _repr_html_(self): """Give a nice representation of tables in notebooks.""" out = "<table class='taqltable' style='overflow-x:auto'>\n" # Print column names (not if they are all auto-generated) if not(all([colname[:4] == "Col_" for colname in self.colnames()])): out += "<tr>" for colname in self.colnames(): out += "<th><b>"+colname+"</b></th>" out += "</tr>" cropped = False rowcount = 0 for row in self: rowout = _format_row(row, self.colnames(), self) rowcount += 1 out += rowout if "\n" in rowout: # Double space after multiline rows out += "\n" out += "\n" if rowcount >= 20: cropped = True break if out[-2:] == "\n\n": out = out[:-1] out += "</table>" if cropped: out += ("<p style='text-align:center'>(" + str(self.nrows()-20)+" more rows)</p>\n") return out
python
def _repr_html_(self): """Give a nice representation of tables in notebooks.""" out = "<table class='taqltable' style='overflow-x:auto'>\n" # Print column names (not if they are all auto-generated) if not(all([colname[:4] == "Col_" for colname in self.colnames()])): out += "<tr>" for colname in self.colnames(): out += "<th><b>"+colname+"</b></th>" out += "</tr>" cropped = False rowcount = 0 for row in self: rowout = _format_row(row, self.colnames(), self) rowcount += 1 out += rowout if "\n" in rowout: # Double space after multiline rows out += "\n" out += "\n" if rowcount >= 20: cropped = True break if out[-2:] == "\n\n": out = out[:-1] out += "</table>" if cropped: out += ("<p style='text-align:center'>(" + str(self.nrows()-20)+" more rows)</p>\n") return out
[ "def", "_repr_html_", "(", "self", ")", ":", "out", "=", "\"<table class='taqltable' style='overflow-x:auto'>\\n\"", "# Print column names (not if they are all auto-generated)", "if", "not", "(", "all", "(", "[", "colname", "[", ":", "4", "]", "==", "\"Col_\"", "for", ...
Give a nice representation of tables in notebooks.
[ "Give", "a", "nice", "representation", "of", "tables", "in", "notebooks", "." ]
975510861ea005f7919dd9e438b5f98a1682eebe
https://github.com/casacore/python-casacore/blob/975510861ea005f7919dd9e438b5f98a1682eebe/casacore/tables/table.py#L1952-L1985
train
23,059
Kronuz/pyScss
scss/extension/core.py
nth
def nth(lst, n): """Return the nth item in the list.""" expect_type(n, (String, Number), unit=None) if isinstance(n, String): if n.value.lower() == 'first': i = 0 elif n.value.lower() == 'last': i = -1 else: raise ValueError("Invalid index %r" % (n,)) else: # DEVIATION: nth treats lists as circular lists i = n.to_python_index(len(lst), circular=True) return lst[i]
python
def nth(lst, n): """Return the nth item in the list.""" expect_type(n, (String, Number), unit=None) if isinstance(n, String): if n.value.lower() == 'first': i = 0 elif n.value.lower() == 'last': i = -1 else: raise ValueError("Invalid index %r" % (n,)) else: # DEVIATION: nth treats lists as circular lists i = n.to_python_index(len(lst), circular=True) return lst[i]
[ "def", "nth", "(", "lst", ",", "n", ")", ":", "expect_type", "(", "n", ",", "(", "String", ",", "Number", ")", ",", "unit", "=", "None", ")", "if", "isinstance", "(", "n", ",", "String", ")", ":", "if", "n", ".", "value", ".", "lower", "(", "...
Return the nth item in the list.
[ "Return", "the", "nth", "item", "in", "the", "list", "." ]
fb32b317f6e2b4b4aad2b86a74844658ac4aa11e
https://github.com/Kronuz/pyScss/blob/fb32b317f6e2b4b4aad2b86a74844658ac4aa11e/scss/extension/core.py#L657-L672
train
23,060
Kronuz/pyScss
scss/extension/core.py
CoreExtension.handle_import
def handle_import(self, name, compilation, rule): """Implementation of the core Sass import mechanism, which just looks for files on disk. """ # TODO this is all not terribly well-specified by Sass. at worst, # it's unclear how far "upwards" we should be allowed to go. but i'm # also a little fuzzy on e.g. how relative imports work from within a # file that's not actually in the search path. # TODO i think with the new origin semantics, i've made it possible to # import relative to the current file even if the current file isn't # anywhere in the search path. is that right? path = PurePosixPath(name) search_exts = list(compilation.compiler.dynamic_extensions) if path.suffix and path.suffix in search_exts: basename = path.stem else: basename = path.name relative_to = path.parent search_path = [] # tuple of (origin, start_from) if relative_to.is_absolute(): relative_to = PurePosixPath(*relative_to.parts[1:]) elif rule.source_file.origin: # Search relative to the current file first, only if not doing an # absolute import search_path.append(( rule.source_file.origin, rule.source_file.relpath.parent / relative_to, )) search_path.extend( (origin, relative_to) for origin in compilation.compiler.search_path ) for prefix, suffix in product(('_', ''), search_exts): filename = prefix + basename + suffix for origin, relative_to in search_path: relpath = relative_to / filename # Lexically (ignoring symlinks!) eliminate .. from the part # of the path that exists within Sass-space. pathlib # deliberately doesn't do this, but os.path does. relpath = PurePosixPath(os.path.normpath(str(relpath))) if rule.source_file.key == (origin, relpath): # Avoid self-import # TODO is this what ruby does? continue path = origin / relpath if not path.exists(): continue # All good! # TODO if this file has already been imported, we'll do the # source preparation twice. make it lazy. return SourceFile.read(origin, relpath)
python
def handle_import(self, name, compilation, rule): """Implementation of the core Sass import mechanism, which just looks for files on disk. """ # TODO this is all not terribly well-specified by Sass. at worst, # it's unclear how far "upwards" we should be allowed to go. but i'm # also a little fuzzy on e.g. how relative imports work from within a # file that's not actually in the search path. # TODO i think with the new origin semantics, i've made it possible to # import relative to the current file even if the current file isn't # anywhere in the search path. is that right? path = PurePosixPath(name) search_exts = list(compilation.compiler.dynamic_extensions) if path.suffix and path.suffix in search_exts: basename = path.stem else: basename = path.name relative_to = path.parent search_path = [] # tuple of (origin, start_from) if relative_to.is_absolute(): relative_to = PurePosixPath(*relative_to.parts[1:]) elif rule.source_file.origin: # Search relative to the current file first, only if not doing an # absolute import search_path.append(( rule.source_file.origin, rule.source_file.relpath.parent / relative_to, )) search_path.extend( (origin, relative_to) for origin in compilation.compiler.search_path ) for prefix, suffix in product(('_', ''), search_exts): filename = prefix + basename + suffix for origin, relative_to in search_path: relpath = relative_to / filename # Lexically (ignoring symlinks!) eliminate .. from the part # of the path that exists within Sass-space. pathlib # deliberately doesn't do this, but os.path does. relpath = PurePosixPath(os.path.normpath(str(relpath))) if rule.source_file.key == (origin, relpath): # Avoid self-import # TODO is this what ruby does? continue path = origin / relpath if not path.exists(): continue # All good! # TODO if this file has already been imported, we'll do the # source preparation twice. make it lazy. return SourceFile.read(origin, relpath)
[ "def", "handle_import", "(", "self", ",", "name", ",", "compilation", ",", "rule", ")", ":", "# TODO this is all not terribly well-specified by Sass. at worst,", "# it's unclear how far \"upwards\" we should be allowed to go. but i'm", "# also a little fuzzy on e.g. how relative import...
Implementation of the core Sass import mechanism, which just looks for files on disk.
[ "Implementation", "of", "the", "core", "Sass", "import", "mechanism", "which", "just", "looks", "for", "files", "on", "disk", "." ]
fb32b317f6e2b4b4aad2b86a74844658ac4aa11e
https://github.com/Kronuz/pyScss/blob/fb32b317f6e2b4b4aad2b86a74844658ac4aa11e/scss/extension/core.py#L25-L80
train
23,061
Kronuz/pyScss
yapps2.py
print_error
def print_error(input, err, scanner): """This is a really dumb long function to print error messages nicely.""" p = err.pos # Figure out the line number line = input[:p].count('\n') print err.msg + " on line " + repr(line + 1) + ":" # Now try printing part of the line text = input[max(p - 80, 0): p + 80] p = p - max(p - 80, 0) # Strip to the left i = text[:p].rfind('\n') j = text[:p].rfind('\r') if i < 0 or (0 <= j < i): i = j if 0 <= i < p: p = p - i - 1 text = text[i + 1:] # Strip to the right i = text.find('\n', p) j = text.find('\r', p) if i < 0 or (0 <= j < i): i = j if i >= 0: text = text[:i] # Now shorten the text while len(text) > 70 and p > 60: # Cut off 10 chars text = "..." + text[10:] p = p - 7 # Now print the string, along with an indicator print '> ', text print '> ', ' ' * p + '^' print 'List of nearby tokens:', scanner
python
def print_error(input, err, scanner): """This is a really dumb long function to print error messages nicely.""" p = err.pos # Figure out the line number line = input[:p].count('\n') print err.msg + " on line " + repr(line + 1) + ":" # Now try printing part of the line text = input[max(p - 80, 0): p + 80] p = p - max(p - 80, 0) # Strip to the left i = text[:p].rfind('\n') j = text[:p].rfind('\r') if i < 0 or (0 <= j < i): i = j if 0 <= i < p: p = p - i - 1 text = text[i + 1:] # Strip to the right i = text.find('\n', p) j = text.find('\r', p) if i < 0 or (0 <= j < i): i = j if i >= 0: text = text[:i] # Now shorten the text while len(text) > 70 and p > 60: # Cut off 10 chars text = "..." + text[10:] p = p - 7 # Now print the string, along with an indicator print '> ', text print '> ', ' ' * p + '^' print 'List of nearby tokens:', scanner
[ "def", "print_error", "(", "input", ",", "err", ",", "scanner", ")", ":", "p", "=", "err", ".", "pos", "# Figure out the line number", "line", "=", "input", "[", ":", "p", "]", ".", "count", "(", "'\\n'", ")", "print", "err", ".", "msg", "+", "\" on ...
This is a really dumb long function to print error messages nicely.
[ "This", "is", "a", "really", "dumb", "long", "function", "to", "print", "error", "messages", "nicely", "." ]
fb32b317f6e2b4b4aad2b86a74844658ac4aa11e
https://github.com/Kronuz/pyScss/blob/fb32b317f6e2b4b4aad2b86a74844658ac4aa11e/yapps2.py#L892-L929
train
23,062
Kronuz/pyScss
yapps2.py
Generator.equal_set
def equal_set(self, a, b): "See if a and b have the same elements" if len(a) != len(b): return 0 if a == b: return 1 return self.subset(a, b) and self.subset(b, a)
python
def equal_set(self, a, b): "See if a and b have the same elements" if len(a) != len(b): return 0 if a == b: return 1 return self.subset(a, b) and self.subset(b, a)
[ "def", "equal_set", "(", "self", ",", "a", ",", "b", ")", ":", "if", "len", "(", "a", ")", "!=", "len", "(", "b", ")", ":", "return", "0", "if", "a", "==", "b", ":", "return", "1", "return", "self", ".", "subset", "(", "a", ",", "b", ")", ...
See if a and b have the same elements
[ "See", "if", "a", "and", "b", "have", "the", "same", "elements" ]
fb32b317f6e2b4b4aad2b86a74844658ac4aa11e
https://github.com/Kronuz/pyScss/blob/fb32b317f6e2b4b4aad2b86a74844658ac4aa11e/yapps2.py#L111-L117
train
23,063
Kronuz/pyScss
yapps2.py
Generator.add_to
def add_to(self, parent, additions): "Modify parent to include all elements in additions" for x in additions: if x not in parent: parent.append(x) self.changed()
python
def add_to(self, parent, additions): "Modify parent to include all elements in additions" for x in additions: if x not in parent: parent.append(x) self.changed()
[ "def", "add_to", "(", "self", ",", "parent", ",", "additions", ")", ":", "for", "x", "in", "additions", ":", "if", "x", "not", "in", "parent", ":", "parent", ".", "append", "(", "x", ")", "self", ".", "changed", "(", ")" ]
Modify parent to include all elements in additions
[ "Modify", "parent", "to", "include", "all", "elements", "in", "additions" ]
fb32b317f6e2b4b4aad2b86a74844658ac4aa11e
https://github.com/Kronuz/pyScss/blob/fb32b317f6e2b4b4aad2b86a74844658ac4aa11e/yapps2.py#L119-L124
train
23,064
Kronuz/pyScss
scss/namespace.py
Namespace.declare_alias
def declare_alias(self, name): """Insert a Python function into this Namespace with an explicitly-given name, but detect its argument count automatically. """ def decorator(f): self._auto_register_function(f, name) return f return decorator
python
def declare_alias(self, name): """Insert a Python function into this Namespace with an explicitly-given name, but detect its argument count automatically. """ def decorator(f): self._auto_register_function(f, name) return f return decorator
[ "def", "declare_alias", "(", "self", ",", "name", ")", ":", "def", "decorator", "(", "f", ")", ":", "self", ".", "_auto_register_function", "(", "f", ",", "name", ")", "return", "f", "return", "decorator" ]
Insert a Python function into this Namespace with an explicitly-given name, but detect its argument count automatically.
[ "Insert", "a", "Python", "function", "into", "this", "Namespace", "with", "an", "explicitly", "-", "given", "name", "but", "detect", "its", "argument", "count", "automatically", "." ]
fb32b317f6e2b4b4aad2b86a74844658ac4aa11e
https://github.com/Kronuz/pyScss/blob/fb32b317f6e2b4b4aad2b86a74844658ac4aa11e/scss/namespace.py#L150-L158
train
23,065
Kronuz/pyScss
scss/util.py
tmemoize.collect
def collect(self): """Clear cache of results which have timed out""" for func in self._caches: cache = {} for key in self._caches[func]: if (time.time() - self._caches[func][key][1]) < self._timeouts[func]: cache[key] = self._caches[func][key] self._caches[func] = cache
python
def collect(self): """Clear cache of results which have timed out""" for func in self._caches: cache = {} for key in self._caches[func]: if (time.time() - self._caches[func][key][1]) < self._timeouts[func]: cache[key] = self._caches[func][key] self._caches[func] = cache
[ "def", "collect", "(", "self", ")", ":", "for", "func", "in", "self", ".", "_caches", ":", "cache", "=", "{", "}", "for", "key", "in", "self", ".", "_caches", "[", "func", "]", ":", "if", "(", "time", ".", "time", "(", ")", "-", "self", ".", ...
Clear cache of results which have timed out
[ "Clear", "cache", "of", "results", "which", "have", "timed", "out" ]
fb32b317f6e2b4b4aad2b86a74844658ac4aa11e
https://github.com/Kronuz/pyScss/blob/fb32b317f6e2b4b4aad2b86a74844658ac4aa11e/scss/util.py#L206-L213
train
23,066
Kronuz/pyScss
scss/rule.py
extend_unique
def extend_unique(seq, more): """Return a new sequence containing the items in `seq` plus any items in `more` that aren't already in `seq`, preserving the order of both. """ seen = set(seq) new = [] for item in more: if item not in seen: seen.add(item) new.append(item) return seq + type(seq)(new)
python
def extend_unique(seq, more): """Return a new sequence containing the items in `seq` plus any items in `more` that aren't already in `seq`, preserving the order of both. """ seen = set(seq) new = [] for item in more: if item not in seen: seen.add(item) new.append(item) return seq + type(seq)(new)
[ "def", "extend_unique", "(", "seq", ",", "more", ")", ":", "seen", "=", "set", "(", "seq", ")", "new", "=", "[", "]", "for", "item", "in", "more", ":", "if", "item", "not", "in", "seen", ":", "seen", ".", "add", "(", "item", ")", "new", ".", ...
Return a new sequence containing the items in `seq` plus any items in `more` that aren't already in `seq`, preserving the order of both.
[ "Return", "a", "new", "sequence", "containing", "the", "items", "in", "seq", "plus", "any", "items", "in", "more", "that", "aren", "t", "already", "in", "seq", "preserving", "the", "order", "of", "both", "." ]
fb32b317f6e2b4b4aad2b86a74844658ac4aa11e
https://github.com/Kronuz/pyScss/blob/fb32b317f6e2b4b4aad2b86a74844658ac4aa11e/scss/rule.py#L17-L28
train
23,067
Kronuz/pyScss
scss/rule.py
RuleAncestry.with_more_selectors
def with_more_selectors(self, selectors): """Return a new ancestry that also matches the given selectors. No nesting is done. """ if self.headers and self.headers[-1].is_selector: new_selectors = extend_unique( self.headers[-1].selectors, selectors) new_headers = self.headers[:-1] + ( BlockSelectorHeader(new_selectors),) return RuleAncestry(new_headers) else: new_headers = self.headers + (BlockSelectorHeader(selectors),) return RuleAncestry(new_headers)
python
def with_more_selectors(self, selectors): """Return a new ancestry that also matches the given selectors. No nesting is done. """ if self.headers and self.headers[-1].is_selector: new_selectors = extend_unique( self.headers[-1].selectors, selectors) new_headers = self.headers[:-1] + ( BlockSelectorHeader(new_selectors),) return RuleAncestry(new_headers) else: new_headers = self.headers + (BlockSelectorHeader(selectors),) return RuleAncestry(new_headers)
[ "def", "with_more_selectors", "(", "self", ",", "selectors", ")", ":", "if", "self", ".", "headers", "and", "self", ".", "headers", "[", "-", "1", "]", ".", "is_selector", ":", "new_selectors", "=", "extend_unique", "(", "self", ".", "headers", "[", "-",...
Return a new ancestry that also matches the given selectors. No nesting is done.
[ "Return", "a", "new", "ancestry", "that", "also", "matches", "the", "given", "selectors", ".", "No", "nesting", "is", "done", "." ]
fb32b317f6e2b4b4aad2b86a74844658ac4aa11e
https://github.com/Kronuz/pyScss/blob/fb32b317f6e2b4b4aad2b86a74844658ac4aa11e/scss/rule.py#L194-L207
train
23,068
Kronuz/pyScss
scss/calculator.py
Calculator.parse_interpolations
def parse_interpolations(self, string): """Parse a string for interpolations, but don't treat anything else as Sass syntax. Returns an AST node. """ # Shortcut: if there are no #s in the string in the first place, it # must not have any interpolations, right? if '#' not in string: return Literal(String.unquoted(string)) return self.parse_expression(string, 'goal_interpolated_literal')
python
def parse_interpolations(self, string): """Parse a string for interpolations, but don't treat anything else as Sass syntax. Returns an AST node. """ # Shortcut: if there are no #s in the string in the first place, it # must not have any interpolations, right? if '#' not in string: return Literal(String.unquoted(string)) return self.parse_expression(string, 'goal_interpolated_literal')
[ "def", "parse_interpolations", "(", "self", ",", "string", ")", ":", "# Shortcut: if there are no #s in the string in the first place, it", "# must not have any interpolations, right?", "if", "'#'", "not", "in", "string", ":", "return", "Literal", "(", "String", ".", "unquo...
Parse a string for interpolations, but don't treat anything else as Sass syntax. Returns an AST node.
[ "Parse", "a", "string", "for", "interpolations", "but", "don", "t", "treat", "anything", "else", "as", "Sass", "syntax", ".", "Returns", "an", "AST", "node", "." ]
fb32b317f6e2b4b4aad2b86a74844658ac4aa11e
https://github.com/Kronuz/pyScss/blob/fb32b317f6e2b4b4aad2b86a74844658ac4aa11e/scss/calculator.py#L174-L182
train
23,069
Kronuz/pyScss
scss/calculator.py
Calculator.parse_vars_and_interpolations
def parse_vars_and_interpolations(self, string): """Parse a string for variables and interpolations, but don't treat anything else as Sass syntax. Returns an AST node. """ # Shortcut: if there are no #s or $s in the string in the first place, # it must not have anything of interest. if '#' not in string and '$' not in string: return Literal(String.unquoted(string)) return self.parse_expression( string, 'goal_interpolated_literal_with_vars')
python
def parse_vars_and_interpolations(self, string): """Parse a string for variables and interpolations, but don't treat anything else as Sass syntax. Returns an AST node. """ # Shortcut: if there are no #s or $s in the string in the first place, # it must not have anything of interest. if '#' not in string and '$' not in string: return Literal(String.unquoted(string)) return self.parse_expression( string, 'goal_interpolated_literal_with_vars')
[ "def", "parse_vars_and_interpolations", "(", "self", ",", "string", ")", ":", "# Shortcut: if there are no #s or $s in the string in the first place,", "# it must not have anything of interest.", "if", "'#'", "not", "in", "string", "and", "'$'", "not", "in", "string", ":", ...
Parse a string for variables and interpolations, but don't treat anything else as Sass syntax. Returns an AST node.
[ "Parse", "a", "string", "for", "variables", "and", "interpolations", "but", "don", "t", "treat", "anything", "else", "as", "Sass", "syntax", ".", "Returns", "an", "AST", "node", "." ]
fb32b317f6e2b4b4aad2b86a74844658ac4aa11e
https://github.com/Kronuz/pyScss/blob/fb32b317f6e2b4b4aad2b86a74844658ac4aa11e/scss/calculator.py#L184-L193
train
23,070
Kronuz/pyScss
scss/extension/compass/helpers.py
reject
def reject(lst, *values): """Removes the given values from the list""" lst = List.from_maybe(lst) values = frozenset(List.from_maybe_starargs(values)) ret = [] for item in lst: if item not in values: ret.append(item) return List(ret, use_comma=lst.use_comma)
python
def reject(lst, *values): """Removes the given values from the list""" lst = List.from_maybe(lst) values = frozenset(List.from_maybe_starargs(values)) ret = [] for item in lst: if item not in values: ret.append(item) return List(ret, use_comma=lst.use_comma)
[ "def", "reject", "(", "lst", ",", "*", "values", ")", ":", "lst", "=", "List", ".", "from_maybe", "(", "lst", ")", "values", "=", "frozenset", "(", "List", ".", "from_maybe_starargs", "(", "values", ")", ")", "ret", "=", "[", "]", "for", "item", "i...
Removes the given values from the list
[ "Removes", "the", "given", "values", "from", "the", "list" ]
fb32b317f6e2b4b4aad2b86a74844658ac4aa11e
https://github.com/Kronuz/pyScss/blob/fb32b317f6e2b4b4aad2b86a74844658ac4aa11e/scss/extension/compass/helpers.py#L87-L96
train
23,071
Kronuz/pyScss
scss/errors.py
add_error_marker
def add_error_marker(text, position, start_line=1): """Add a caret marking a given position in a string of input. Returns (new_text, caret_line). """ indent = " " lines = [] caret_line = start_line for line in text.split("\n"): lines.append(indent + line) if 0 <= position <= len(line): lines.append(indent + (" " * position) + "^") caret_line = start_line position -= len(line) position -= 1 # for the newline start_line += 1 return "\n".join(lines), caret_line
python
def add_error_marker(text, position, start_line=1): """Add a caret marking a given position in a string of input. Returns (new_text, caret_line). """ indent = " " lines = [] caret_line = start_line for line in text.split("\n"): lines.append(indent + line) if 0 <= position <= len(line): lines.append(indent + (" " * position) + "^") caret_line = start_line position -= len(line) position -= 1 # for the newline start_line += 1 return "\n".join(lines), caret_line
[ "def", "add_error_marker", "(", "text", ",", "position", ",", "start_line", "=", "1", ")", ":", "indent", "=", "\" \"", "lines", "=", "[", "]", "caret_line", "=", "start_line", "for", "line", "in", "text", ".", "split", "(", "\"\\n\"", ")", ":", "li...
Add a caret marking a given position in a string of input. Returns (new_text, caret_line).
[ "Add", "a", "caret", "marking", "a", "given", "position", "in", "a", "string", "of", "input", "." ]
fb32b317f6e2b4b4aad2b86a74844658ac4aa11e
https://github.com/Kronuz/pyScss/blob/fb32b317f6e2b4b4aad2b86a74844658ac4aa11e/scss/errors.py#L34-L53
train
23,072
Kronuz/pyScss
scss/errors.py
SassBaseError.format_sass_stack
def format_sass_stack(self): """Return a "traceback" of Sass imports.""" if not self.rule_stack: return "" ret = ["on ", self.format_file_and_line(self.rule_stack[0]), "\n"] last_file = self.rule_stack[0].source_file # TODO this could go away if rules knew their import chains... # TODO this doesn't mention mixins or function calls. really need to # track the call stack better. atm we skip other calls in the same # file because most of them are just nesting, but they might not be! # TODO the line number is wrong here for @imports, because we don't # have access to the UnparsedBlock representing the import! # TODO @content is completely broken; it's basically textual inclusion for rule in self.rule_stack[1:]: if rule.source_file is not last_file: ret.extend(( "imported from ", self.format_file_and_line(rule), "\n")) last_file = rule.source_file return "".join(ret)
python
def format_sass_stack(self): """Return a "traceback" of Sass imports.""" if not self.rule_stack: return "" ret = ["on ", self.format_file_and_line(self.rule_stack[0]), "\n"] last_file = self.rule_stack[0].source_file # TODO this could go away if rules knew their import chains... # TODO this doesn't mention mixins or function calls. really need to # track the call stack better. atm we skip other calls in the same # file because most of them are just nesting, but they might not be! # TODO the line number is wrong here for @imports, because we don't # have access to the UnparsedBlock representing the import! # TODO @content is completely broken; it's basically textual inclusion for rule in self.rule_stack[1:]: if rule.source_file is not last_file: ret.extend(( "imported from ", self.format_file_and_line(rule), "\n")) last_file = rule.source_file return "".join(ret)
[ "def", "format_sass_stack", "(", "self", ")", ":", "if", "not", "self", ".", "rule_stack", ":", "return", "\"\"", "ret", "=", "[", "\"on \"", ",", "self", ".", "format_file_and_line", "(", "self", ".", "rule_stack", "[", "0", "]", ")", ",", "\"\\n\"", ...
Return a "traceback" of Sass imports.
[ "Return", "a", "traceback", "of", "Sass", "imports", "." ]
fb32b317f6e2b4b4aad2b86a74844658ac4aa11e
https://github.com/Kronuz/pyScss/blob/fb32b317f6e2b4b4aad2b86a74844658ac4aa11e/scss/errors.py#L80-L101
train
23,073
Kronuz/pyScss
scss/errors.py
SassError.format_python_stack
def format_python_stack(self): """Return a traceback of Python frames, from where the error occurred to where it was first caught and wrapped. """ ret = ["Traceback:\n"] ret.extend(traceback.format_tb(self.original_traceback)) return "".join(ret)
python
def format_python_stack(self): """Return a traceback of Python frames, from where the error occurred to where it was first caught and wrapped. """ ret = ["Traceback:\n"] ret.extend(traceback.format_tb(self.original_traceback)) return "".join(ret)
[ "def", "format_python_stack", "(", "self", ")", ":", "ret", "=", "[", "\"Traceback:\\n\"", "]", "ret", ".", "extend", "(", "traceback", ".", "format_tb", "(", "self", ".", "original_traceback", ")", ")", "return", "\"\"", ".", "join", "(", "ret", ")" ]
Return a traceback of Python frames, from where the error occurred to where it was first caught and wrapped.
[ "Return", "a", "traceback", "of", "Python", "frames", "from", "where", "the", "error", "occurred", "to", "where", "it", "was", "first", "caught", "and", "wrapped", "." ]
fb32b317f6e2b4b4aad2b86a74844658ac4aa11e
https://github.com/Kronuz/pyScss/blob/fb32b317f6e2b4b4aad2b86a74844658ac4aa11e/scss/errors.py#L217-L223
train
23,074
Kronuz/pyScss
scss/errors.py
SassError.to_css
def to_css(self): """Return a stylesheet that will show the wrapped error at the top of the browser window. """ # TODO should this include the traceback? any security concerns? prefix = self.format_prefix() original_error = self.format_original_error() sass_stack = self.format_sass_stack() message = prefix + "\n" + sass_stack + original_error # Super simple escaping: only quotes and newlines are illegal in css # strings message = message.replace('\\', '\\\\') message = message.replace('"', '\\"') # use the maximum six digits here so it doesn't eat any following # characters that happen to look like hex message = message.replace('\n', '\\00000A') return BROWSER_ERROR_TEMPLATE.format('"' + message + '"')
python
def to_css(self): """Return a stylesheet that will show the wrapped error at the top of the browser window. """ # TODO should this include the traceback? any security concerns? prefix = self.format_prefix() original_error = self.format_original_error() sass_stack = self.format_sass_stack() message = prefix + "\n" + sass_stack + original_error # Super simple escaping: only quotes and newlines are illegal in css # strings message = message.replace('\\', '\\\\') message = message.replace('"', '\\"') # use the maximum six digits here so it doesn't eat any following # characters that happen to look like hex message = message.replace('\n', '\\00000A') return BROWSER_ERROR_TEMPLATE.format('"' + message + '"')
[ "def", "to_css", "(", "self", ")", ":", "# TODO should this include the traceback? any security concerns?", "prefix", "=", "self", ".", "format_prefix", "(", ")", "original_error", "=", "self", ".", "format_original_error", "(", ")", "sass_stack", "=", "self", ".", ...
Return a stylesheet that will show the wrapped error at the top of the browser window.
[ "Return", "a", "stylesheet", "that", "will", "show", "the", "wrapped", "error", "at", "the", "top", "of", "the", "browser", "window", "." ]
fb32b317f6e2b4b4aad2b86a74844658ac4aa11e
https://github.com/Kronuz/pyScss/blob/fb32b317f6e2b4b4aad2b86a74844658ac4aa11e/scss/errors.py#L249-L268
train
23,075
Kronuz/pyScss
scss/compiler.py
compile_string
def compile_string(string, compiler_class=Compiler, **kwargs): """Compile a single string, and return a string of CSS. Keyword arguments are passed along to the underlying `Compiler`. """ compiler = compiler_class(**kwargs) return compiler.compile_string(string)
python
def compile_string(string, compiler_class=Compiler, **kwargs): """Compile a single string, and return a string of CSS. Keyword arguments are passed along to the underlying `Compiler`. """ compiler = compiler_class(**kwargs) return compiler.compile_string(string)
[ "def", "compile_string", "(", "string", ",", "compiler_class", "=", "Compiler", ",", "*", "*", "kwargs", ")", ":", "compiler", "=", "compiler_class", "(", "*", "*", "kwargs", ")", "return", "compiler", ".", "compile_string", "(", "string", ")" ]
Compile a single string, and return a string of CSS. Keyword arguments are passed along to the underlying `Compiler`.
[ "Compile", "a", "single", "string", "and", "return", "a", "string", "of", "CSS", "." ]
fb32b317f6e2b4b4aad2b86a74844658ac4aa11e
https://github.com/Kronuz/pyScss/blob/fb32b317f6e2b4b4aad2b86a74844658ac4aa11e/scss/compiler.py#L240-L246
train
23,076
Kronuz/pyScss
scss/compiler.py
Compilation.parse_selectors
def parse_selectors(self, raw_selectors): """ Parses out the old xCSS "foo extends bar" syntax. Returns a 2-tuple: a set of selectors, and a set of extended selectors. """ # Fix tabs and spaces in selectors raw_selectors = _spaces_re.sub(' ', raw_selectors) parts = _xcss_extends_re.split(raw_selectors, 1) # handle old xCSS extends if len(parts) > 1: unparsed_selectors, unsplit_parents = parts # Multiple `extends` are delimited by `&` unparsed_parents = unsplit_parents.split('&') else: unparsed_selectors, = parts unparsed_parents = () selectors = Selector.parse_many(unparsed_selectors) parents = [Selector.parse_one(parent) for parent in unparsed_parents] return selectors, parents
python
def parse_selectors(self, raw_selectors): """ Parses out the old xCSS "foo extends bar" syntax. Returns a 2-tuple: a set of selectors, and a set of extended selectors. """ # Fix tabs and spaces in selectors raw_selectors = _spaces_re.sub(' ', raw_selectors) parts = _xcss_extends_re.split(raw_selectors, 1) # handle old xCSS extends if len(parts) > 1: unparsed_selectors, unsplit_parents = parts # Multiple `extends` are delimited by `&` unparsed_parents = unsplit_parents.split('&') else: unparsed_selectors, = parts unparsed_parents = () selectors = Selector.parse_many(unparsed_selectors) parents = [Selector.parse_one(parent) for parent in unparsed_parents] return selectors, parents
[ "def", "parse_selectors", "(", "self", ",", "raw_selectors", ")", ":", "# Fix tabs and spaces in selectors", "raw_selectors", "=", "_spaces_re", ".", "sub", "(", "' '", ",", "raw_selectors", ")", "parts", "=", "_xcss_extends_re", ".", "split", "(", "raw_selectors", ...
Parses out the old xCSS "foo extends bar" syntax. Returns a 2-tuple: a set of selectors, and a set of extended selectors.
[ "Parses", "out", "the", "old", "xCSS", "foo", "extends", "bar", "syntax", "." ]
fb32b317f6e2b4b4aad2b86a74844658ac4aa11e
https://github.com/Kronuz/pyScss/blob/fb32b317f6e2b4b4aad2b86a74844658ac4aa11e/scss/compiler.py#L308-L329
train
23,077
Kronuz/pyScss
scss/compiler.py
Compilation._get_properties
def _get_properties(self, rule, scope, block): """ Implements properties and variables extraction and assignment """ prop, raw_value = (_prop_split_re.split(block.prop, 1) + [None])[:2] if raw_value is not None: raw_value = raw_value.strip() try: is_var = (block.prop[len(prop)] == '=') except IndexError: is_var = False if is_var: warn_deprecated(rule, "Assignment with = is deprecated; use : instead.") calculator = self._make_calculator(rule.namespace) prop = prop.strip() prop = calculator.do_glob_math(prop) if not prop: return _prop = (scope or '') + prop if is_var or prop.startswith('$') and raw_value is not None: # Pop off any flags: !default, !global is_default = False is_global = True # eventually sass will default this to false while True: splits = raw_value.rsplit(None, 1) if len(splits) < 2 or not splits[1].startswith('!'): break raw_value, flag = splits if flag == '!default': is_default = True elif flag == '!global': is_global = True else: raise ValueError("Unrecognized flag: {0}".format(flag)) # Variable assignment _prop = normalize_var(_prop) try: existing_value = rule.namespace.variable(_prop) except KeyError: existing_value = None is_defined = existing_value is not None and not existing_value.is_null if is_default and is_defined: pass else: if is_defined and prop.startswith('$') and prop[1].isupper(): log.warn("Constant %r redefined", prop) # Variable assignment is an expression, so it always performs # real division value = calculator.calculate(raw_value, divide=True) rule.namespace.set_variable( _prop, value, local_only=not is_global) else: # Regular property destined for output _prop = calculator.apply_vars(_prop) if raw_value is None: value = None else: value = calculator.calculate(raw_value) if value is None: pass elif isinstance(value, six.string_types): # TODO kill this branch pass else: if value.is_null: return style = rule.legacy_compiler_options.get( 'style', self.compiler.output_style) compress = style == 'compressed' value = value.render(compress=compress) rule.properties.append((_prop, value))
python
def _get_properties(self, rule, scope, block): """ Implements properties and variables extraction and assignment """ prop, raw_value = (_prop_split_re.split(block.prop, 1) + [None])[:2] if raw_value is not None: raw_value = raw_value.strip() try: is_var = (block.prop[len(prop)] == '=') except IndexError: is_var = False if is_var: warn_deprecated(rule, "Assignment with = is deprecated; use : instead.") calculator = self._make_calculator(rule.namespace) prop = prop.strip() prop = calculator.do_glob_math(prop) if not prop: return _prop = (scope or '') + prop if is_var or prop.startswith('$') and raw_value is not None: # Pop off any flags: !default, !global is_default = False is_global = True # eventually sass will default this to false while True: splits = raw_value.rsplit(None, 1) if len(splits) < 2 or not splits[1].startswith('!'): break raw_value, flag = splits if flag == '!default': is_default = True elif flag == '!global': is_global = True else: raise ValueError("Unrecognized flag: {0}".format(flag)) # Variable assignment _prop = normalize_var(_prop) try: existing_value = rule.namespace.variable(_prop) except KeyError: existing_value = None is_defined = existing_value is not None and not existing_value.is_null if is_default and is_defined: pass else: if is_defined and prop.startswith('$') and prop[1].isupper(): log.warn("Constant %r redefined", prop) # Variable assignment is an expression, so it always performs # real division value = calculator.calculate(raw_value, divide=True) rule.namespace.set_variable( _prop, value, local_only=not is_global) else: # Regular property destined for output _prop = calculator.apply_vars(_prop) if raw_value is None: value = None else: value = calculator.calculate(raw_value) if value is None: pass elif isinstance(value, six.string_types): # TODO kill this branch pass else: if value.is_null: return style = rule.legacy_compiler_options.get( 'style', self.compiler.output_style) compress = style == 'compressed' value = value.render(compress=compress) rule.properties.append((_prop, value))
[ "def", "_get_properties", "(", "self", ",", "rule", ",", "scope", ",", "block", ")", ":", "prop", ",", "raw_value", "=", "(", "_prop_split_re", ".", "split", "(", "block", ".", "prop", ",", "1", ")", "+", "[", "None", "]", ")", "[", ":", "2", "]"...
Implements properties and variables extraction and assignment
[ "Implements", "properties", "and", "variables", "extraction", "and", "assignment" ]
fb32b317f6e2b4b4aad2b86a74844658ac4aa11e
https://github.com/Kronuz/pyScss/blob/fb32b317f6e2b4b4aad2b86a74844658ac4aa11e/scss/compiler.py#L1027-L1105
train
23,078
Kronuz/pyScss
scss/types.py
_constrain
def _constrain(value, lb=0, ub=1): """Helper for Color constructors. Constrains a value to a range.""" if value < lb: return lb elif value > ub: return ub else: return value
python
def _constrain(value, lb=0, ub=1): """Helper for Color constructors. Constrains a value to a range.""" if value < lb: return lb elif value > ub: return ub else: return value
[ "def", "_constrain", "(", "value", ",", "lb", "=", "0", ",", "ub", "=", "1", ")", ":", "if", "value", "<", "lb", ":", "return", "lb", "elif", "value", ">", "ub", ":", "return", "ub", "else", ":", "return", "value" ]
Helper for Color constructors. Constrains a value to a range.
[ "Helper", "for", "Color", "constructors", ".", "Constrains", "a", "value", "to", "a", "range", "." ]
fb32b317f6e2b4b4aad2b86a74844658ac4aa11e
https://github.com/Kronuz/pyScss/blob/fb32b317f6e2b4b4aad2b86a74844658ac4aa11e/scss/types.py#L808-L815
train
23,079
Kronuz/pyScss
scss/types.py
Number._add_sub
def _add_sub(self, other, op): """Implements both addition and subtraction.""" if not isinstance(other, Number): return NotImplemented # If either side is unitless, inherit the other side's units. Skip all # the rest of the conversion math, too. if self.is_unitless or other.is_unitless: return Number( op(self.value, other.value), unit_numer=self.unit_numer or other.unit_numer, unit_denom=self.unit_denom or other.unit_denom, ) # Likewise, if either side is zero, it can auto-cast to any units if self.value == 0: return Number( op(self.value, other.value), unit_numer=other.unit_numer, unit_denom=other.unit_denom, ) elif other.value == 0: return Number( op(self.value, other.value), unit_numer=self.unit_numer, unit_denom=self.unit_denom, ) # Reduce both operands to the same units left = self.to_base_units() right = other.to_base_units() if left.unit_numer != right.unit_numer or left.unit_denom != right.unit_denom: raise ValueError("Can't reconcile units: %r and %r" % (self, other)) new_amount = op(left.value, right.value) # Convert back to the left side's units if left.value != 0: new_amount = new_amount * self.value / left.value return Number(new_amount, unit_numer=self.unit_numer, unit_denom=self.unit_denom)
python
def _add_sub(self, other, op): """Implements both addition and subtraction.""" if not isinstance(other, Number): return NotImplemented # If either side is unitless, inherit the other side's units. Skip all # the rest of the conversion math, too. if self.is_unitless or other.is_unitless: return Number( op(self.value, other.value), unit_numer=self.unit_numer or other.unit_numer, unit_denom=self.unit_denom or other.unit_denom, ) # Likewise, if either side is zero, it can auto-cast to any units if self.value == 0: return Number( op(self.value, other.value), unit_numer=other.unit_numer, unit_denom=other.unit_denom, ) elif other.value == 0: return Number( op(self.value, other.value), unit_numer=self.unit_numer, unit_denom=self.unit_denom, ) # Reduce both operands to the same units left = self.to_base_units() right = other.to_base_units() if left.unit_numer != right.unit_numer or left.unit_denom != right.unit_denom: raise ValueError("Can't reconcile units: %r and %r" % (self, other)) new_amount = op(left.value, right.value) # Convert back to the left side's units if left.value != 0: new_amount = new_amount * self.value / left.value return Number(new_amount, unit_numer=self.unit_numer, unit_denom=self.unit_denom)
[ "def", "_add_sub", "(", "self", ",", "other", ",", "op", ")", ":", "if", "not", "isinstance", "(", "other", ",", "Number", ")", ":", "return", "NotImplemented", "# If either side is unitless, inherit the other side's units. Skip all", "# the rest of the conversion math, ...
Implements both addition and subtraction.
[ "Implements", "both", "addition", "and", "subtraction", "." ]
fb32b317f6e2b4b4aad2b86a74844658ac4aa11e
https://github.com/Kronuz/pyScss/blob/fb32b317f6e2b4b4aad2b86a74844658ac4aa11e/scss/types.py#L442-L483
train
23,080
Kronuz/pyScss
scss/types.py
Number.to_base_units
def to_base_units(self): """Convert to a fixed set of "base" units. The particular units are arbitrary; what's important is that they're consistent. Used for addition and comparisons. """ # Convert to "standard" units, as defined by the conversions dict above amount = self.value numer_factor, numer_units = convert_units_to_base_units(self.unit_numer) denom_factor, denom_units = convert_units_to_base_units(self.unit_denom) return Number( amount * numer_factor / denom_factor, unit_numer=numer_units, unit_denom=denom_units, )
python
def to_base_units(self): """Convert to a fixed set of "base" units. The particular units are arbitrary; what's important is that they're consistent. Used for addition and comparisons. """ # Convert to "standard" units, as defined by the conversions dict above amount = self.value numer_factor, numer_units = convert_units_to_base_units(self.unit_numer) denom_factor, denom_units = convert_units_to_base_units(self.unit_denom) return Number( amount * numer_factor / denom_factor, unit_numer=numer_units, unit_denom=denom_units, )
[ "def", "to_base_units", "(", "self", ")", ":", "# Convert to \"standard\" units, as defined by the conversions dict above", "amount", "=", "self", ".", "value", "numer_factor", ",", "numer_units", "=", "convert_units_to_base_units", "(", "self", ".", "unit_numer", ")", "d...
Convert to a fixed set of "base" units. The particular units are arbitrary; what's important is that they're consistent. Used for addition and comparisons.
[ "Convert", "to", "a", "fixed", "set", "of", "base", "units", ".", "The", "particular", "units", "are", "arbitrary", ";", "what", "s", "important", "is", "that", "they", "re", "consistent", "." ]
fb32b317f6e2b4b4aad2b86a74844658ac4aa11e
https://github.com/Kronuz/pyScss/blob/fb32b317f6e2b4b4aad2b86a74844658ac4aa11e/scss/types.py#L487-L503
train
23,081
Kronuz/pyScss
scss/types.py
Number.wrap_python_function
def wrap_python_function(cls, fn): """Wraps an unary Python math function, translating the argument from Sass to Python on the way in, and vice versa for the return value. Used to wrap simple Python functions like `ceil`, `floor`, etc. """ def wrapped(sass_arg): # TODO enforce no units for trig? python_arg = sass_arg.value python_ret = fn(python_arg) sass_ret = cls( python_ret, unit_numer=sass_arg.unit_numer, unit_denom=sass_arg.unit_denom) return sass_ret return wrapped
python
def wrap_python_function(cls, fn): """Wraps an unary Python math function, translating the argument from Sass to Python on the way in, and vice versa for the return value. Used to wrap simple Python functions like `ceil`, `floor`, etc. """ def wrapped(sass_arg): # TODO enforce no units for trig? python_arg = sass_arg.value python_ret = fn(python_arg) sass_ret = cls( python_ret, unit_numer=sass_arg.unit_numer, unit_denom=sass_arg.unit_denom) return sass_ret return wrapped
[ "def", "wrap_python_function", "(", "cls", ",", "fn", ")", ":", "def", "wrapped", "(", "sass_arg", ")", ":", "# TODO enforce no units for trig?", "python_arg", "=", "sass_arg", ".", "value", "python_ret", "=", "fn", "(", "python_arg", ")", "sass_ret", "=", "cl...
Wraps an unary Python math function, translating the argument from Sass to Python on the way in, and vice versa for the return value. Used to wrap simple Python functions like `ceil`, `floor`, etc.
[ "Wraps", "an", "unary", "Python", "math", "function", "translating", "the", "argument", "from", "Sass", "to", "Python", "on", "the", "way", "in", "and", "vice", "versa", "for", "the", "return", "value", "." ]
fb32b317f6e2b4b4aad2b86a74844658ac4aa11e
https://github.com/Kronuz/pyScss/blob/fb32b317f6e2b4b4aad2b86a74844658ac4aa11e/scss/types.py#L508-L524
train
23,082
Kronuz/pyScss
scss/types.py
Number.to_python_index
def to_python_index(self, length, check_bounds=True, circular=False): """Return a plain Python integer appropriate for indexing a sequence of the given length. Raise if this is impossible for any reason whatsoever. """ if not self.is_unitless: raise ValueError("Index cannot have units: {0!r}".format(self)) ret = int(self.value) if ret != self.value: raise ValueError("Index must be an integer: {0!r}".format(ret)) if ret == 0: raise ValueError("Index cannot be zero") if check_bounds and not circular and abs(ret) > length: raise ValueError("Index {0!r} out of bounds for length {1}".format(ret, length)) if ret > 0: ret -= 1 if circular: ret = ret % length return ret
python
def to_python_index(self, length, check_bounds=True, circular=False): """Return a plain Python integer appropriate for indexing a sequence of the given length. Raise if this is impossible for any reason whatsoever. """ if not self.is_unitless: raise ValueError("Index cannot have units: {0!r}".format(self)) ret = int(self.value) if ret != self.value: raise ValueError("Index must be an integer: {0!r}".format(ret)) if ret == 0: raise ValueError("Index cannot be zero") if check_bounds and not circular and abs(ret) > length: raise ValueError("Index {0!r} out of bounds for length {1}".format(ret, length)) if ret > 0: ret -= 1 if circular: ret = ret % length return ret
[ "def", "to_python_index", "(", "self", ",", "length", ",", "check_bounds", "=", "True", ",", "circular", "=", "False", ")", ":", "if", "not", "self", ".", "is_unitless", ":", "raise", "ValueError", "(", "\"Index cannot have units: {0!r}\"", ".", "format", "(",...
Return a plain Python integer appropriate for indexing a sequence of the given length. Raise if this is impossible for any reason whatsoever.
[ "Return", "a", "plain", "Python", "integer", "appropriate", "for", "indexing", "a", "sequence", "of", "the", "given", "length", ".", "Raise", "if", "this", "is", "impossible", "for", "any", "reason", "whatsoever", "." ]
fb32b317f6e2b4b4aad2b86a74844658ac4aa11e
https://github.com/Kronuz/pyScss/blob/fb32b317f6e2b4b4aad2b86a74844658ac4aa11e/scss/types.py#L526-L550
train
23,083
Kronuz/pyScss
scss/types.py
List.maybe_new
def maybe_new(cls, values, use_comma=True): """If `values` contains only one item, return that item. Otherwise, return a List as normal. """ if len(values) == 1: return values[0] else: return cls(values, use_comma=use_comma)
python
def maybe_new(cls, values, use_comma=True): """If `values` contains only one item, return that item. Otherwise, return a List as normal. """ if len(values) == 1: return values[0] else: return cls(values, use_comma=use_comma)
[ "def", "maybe_new", "(", "cls", ",", "values", ",", "use_comma", "=", "True", ")", ":", "if", "len", "(", "values", ")", "==", "1", ":", "return", "values", "[", "0", "]", "else", ":", "return", "cls", "(", "values", ",", "use_comma", "=", "use_com...
If `values` contains only one item, return that item. Otherwise, return a List as normal.
[ "If", "values", "contains", "only", "one", "item", "return", "that", "item", ".", "Otherwise", "return", "a", "List", "as", "normal", "." ]
fb32b317f6e2b4b4aad2b86a74844658ac4aa11e
https://github.com/Kronuz/pyScss/blob/fb32b317f6e2b4b4aad2b86a74844658ac4aa11e/scss/types.py#L636-L643
train
23,084
Kronuz/pyScss
scss/types.py
List.from_maybe_starargs
def from_maybe_starargs(cls, args, use_comma=True): """If `args` has one element which appears to be a list, return it. Otherwise, return a list as normal. Mainly used by Sass function implementations that predate `...` support, so they can accept both a list of arguments and a single list stored in a variable. """ if len(args) == 1: if isinstance(args[0], cls): return args[0] elif isinstance(args[0], (list, tuple)): return cls(args[0], use_comma=use_comma) return cls(args, use_comma=use_comma)
python
def from_maybe_starargs(cls, args, use_comma=True): """If `args` has one element which appears to be a list, return it. Otherwise, return a list as normal. Mainly used by Sass function implementations that predate `...` support, so they can accept both a list of arguments and a single list stored in a variable. """ if len(args) == 1: if isinstance(args[0], cls): return args[0] elif isinstance(args[0], (list, tuple)): return cls(args[0], use_comma=use_comma) return cls(args, use_comma=use_comma)
[ "def", "from_maybe_starargs", "(", "cls", ",", "args", ",", "use_comma", "=", "True", ")", ":", "if", "len", "(", "args", ")", "==", "1", ":", "if", "isinstance", "(", "args", "[", "0", "]", ",", "cls", ")", ":", "return", "args", "[", "0", "]", ...
If `args` has one element which appears to be a list, return it. Otherwise, return a list as normal. Mainly used by Sass function implementations that predate `...` support, so they can accept both a list of arguments and a single list stored in a variable.
[ "If", "args", "has", "one", "element", "which", "appears", "to", "be", "a", "list", "return", "it", ".", "Otherwise", "return", "a", "list", "as", "normal", "." ]
fb32b317f6e2b4b4aad2b86a74844658ac4aa11e
https://github.com/Kronuz/pyScss/blob/fb32b317f6e2b4b4aad2b86a74844658ac4aa11e/scss/types.py#L664-L678
train
23,085
Kronuz/pyScss
scss/types.py
Color.from_name
def from_name(cls, name): """Build a Color from a CSS color name.""" self = cls.__new__(cls) # TODO self.original_literal = name r, g, b, a = COLOR_NAMES[name] self.value = r, g, b, a return self
python
def from_name(cls, name): """Build a Color from a CSS color name.""" self = cls.__new__(cls) # TODO self.original_literal = name r, g, b, a = COLOR_NAMES[name] self.value = r, g, b, a return self
[ "def", "from_name", "(", "cls", ",", "name", ")", ":", "self", "=", "cls", ".", "__new__", "(", "cls", ")", "# TODO", "self", ".", "original_literal", "=", "name", "r", ",", "g", ",", "b", ",", "a", "=", "COLOR_NAMES", "[", "name", "]", "self", "...
Build a Color from a CSS color name.
[ "Build", "a", "Color", "from", "a", "CSS", "color", "name", "." ]
fb32b317f6e2b4b4aad2b86a74844658ac4aa11e
https://github.com/Kronuz/pyScss/blob/fb32b317f6e2b4b4aad2b86a74844658ac4aa11e/scss/types.py#L893-L901
train
23,086
Kronuz/pyScss
scss/types.py
String.unquoted
def unquoted(cls, value, literal=False): """Helper to create a string with no quotes.""" return cls(value, quotes=None, literal=literal)
python
def unquoted(cls, value, literal=False): """Helper to create a string with no quotes.""" return cls(value, quotes=None, literal=literal)
[ "def", "unquoted", "(", "cls", ",", "value", ",", "literal", "=", "False", ")", ":", "return", "cls", "(", "value", ",", "quotes", "=", "None", ",", "literal", "=", "literal", ")" ]
Helper to create a string with no quotes.
[ "Helper", "to", "create", "a", "string", "with", "no", "quotes", "." ]
fb32b317f6e2b4b4aad2b86a74844658ac4aa11e
https://github.com/Kronuz/pyScss/blob/fb32b317f6e2b4b4aad2b86a74844658ac4aa11e/scss/types.py#L1096-L1098
train
23,087
Kronuz/pyScss
scss/selector.py
_is_combinator_subset_of
def _is_combinator_subset_of(specific, general, is_first=True): """Return whether `specific` matches a non-strict subset of what `general` matches. """ if is_first and general == ' ': # First selector always has a space to mean "descendent of root", which # still holds if any other selector appears above it return True if specific == general: return True if specific == '>' and general == ' ': return True if specific == '+' and general == '~': return True return False
python
def _is_combinator_subset_of(specific, general, is_first=True): """Return whether `specific` matches a non-strict subset of what `general` matches. """ if is_first and general == ' ': # First selector always has a space to mean "descendent of root", which # still holds if any other selector appears above it return True if specific == general: return True if specific == '>' and general == ' ': return True if specific == '+' and general == '~': return True return False
[ "def", "_is_combinator_subset_of", "(", "specific", ",", "general", ",", "is_first", "=", "True", ")", ":", "if", "is_first", "and", "general", "==", "' '", ":", "# First selector always has a space to mean \"descendent of root\", which", "# still holds if any other selector ...
Return whether `specific` matches a non-strict subset of what `general` matches.
[ "Return", "whether", "specific", "matches", "a", "non", "-", "strict", "subset", "of", "what", "general", "matches", "." ]
fb32b317f6e2b4b4aad2b86a74844658ac4aa11e
https://github.com/Kronuz/pyScss/blob/fb32b317f6e2b4b4aad2b86a74844658ac4aa11e/scss/selector.py#L62-L80
train
23,088
Kronuz/pyScss
scss/selector.py
_weave_conflicting_selectors
def _weave_conflicting_selectors(prefixes, a, b, suffix=()): """Part of the selector merge algorithm above. Not useful on its own. Pay no attention to the man behind the curtain. """ # OK, what this actually does: given a list of selector chains, two # "conflicting" selector chains, and an optional suffix, return a new list # of chains like this: # prefix[0] + a + b + suffix, # prefix[0] + b + a + suffix, # prefix[1] + a + b + suffix, # ... # In other words, this just appends a new chain to each of a list of given # chains, except that the new chain might be the superposition of two # other incompatible chains. both = a and b for prefix in prefixes: yield prefix + a + b + suffix if both: # Only use both orderings if there's an actual conflict! yield prefix + b + a + suffix
python
def _weave_conflicting_selectors(prefixes, a, b, suffix=()): """Part of the selector merge algorithm above. Not useful on its own. Pay no attention to the man behind the curtain. """ # OK, what this actually does: given a list of selector chains, two # "conflicting" selector chains, and an optional suffix, return a new list # of chains like this: # prefix[0] + a + b + suffix, # prefix[0] + b + a + suffix, # prefix[1] + a + b + suffix, # ... # In other words, this just appends a new chain to each of a list of given # chains, except that the new chain might be the superposition of two # other incompatible chains. both = a and b for prefix in prefixes: yield prefix + a + b + suffix if both: # Only use both orderings if there's an actual conflict! yield prefix + b + a + suffix
[ "def", "_weave_conflicting_selectors", "(", "prefixes", ",", "a", ",", "b", ",", "suffix", "=", "(", ")", ")", ":", "# OK, what this actually does: given a list of selector chains, two", "# \"conflicting\" selector chains, and an optional suffix, return a new list", "# of chains li...
Part of the selector merge algorithm above. Not useful on its own. Pay no attention to the man behind the curtain.
[ "Part", "of", "the", "selector", "merge", "algorithm", "above", ".", "Not", "useful", "on", "its", "own", ".", "Pay", "no", "attention", "to", "the", "man", "behind", "the", "curtain", "." ]
fb32b317f6e2b4b4aad2b86a74844658ac4aa11e
https://github.com/Kronuz/pyScss/blob/fb32b317f6e2b4b4aad2b86a74844658ac4aa11e/scss/selector.py#L550-L569
train
23,089
Kronuz/pyScss
scss/selector.py
_merge_simple_selectors
def _merge_simple_selectors(a, b): """Merge two simple selectors, for the purposes of the LCS algorithm below. In practice this returns the more specific selector if one is a subset of the other, else it returns None. """ # TODO what about combinators if a.is_superset_of(b): return b elif b.is_superset_of(a): return a else: return None
python
def _merge_simple_selectors(a, b): """Merge two simple selectors, for the purposes of the LCS algorithm below. In practice this returns the more specific selector if one is a subset of the other, else it returns None. """ # TODO what about combinators if a.is_superset_of(b): return b elif b.is_superset_of(a): return a else: return None
[ "def", "_merge_simple_selectors", "(", "a", ",", "b", ")", ":", "# TODO what about combinators", "if", "a", ".", "is_superset_of", "(", "b", ")", ":", "return", "b", "elif", "b", ".", "is_superset_of", "(", "a", ")", ":", "return", "a", "else", ":", "ret...
Merge two simple selectors, for the purposes of the LCS algorithm below. In practice this returns the more specific selector if one is a subset of the other, else it returns None.
[ "Merge", "two", "simple", "selectors", "for", "the", "purposes", "of", "the", "LCS", "algorithm", "below", "." ]
fb32b317f6e2b4b4aad2b86a74844658ac4aa11e
https://github.com/Kronuz/pyScss/blob/fb32b317f6e2b4b4aad2b86a74844658ac4aa11e/scss/selector.py#L572-L584
train
23,090
Kronuz/pyScss
scss/selector.py
longest_common_subsequence
def longest_common_subsequence(a, b, mergefunc=None): """Find the longest common subsequence between two iterables. The longest common subsequence is the core of any diff algorithm: it's the longest sequence of elements that appears in both parent sequences in the same order, but NOT necessarily consecutively. Original algorithm borrowed from Wikipedia: http://en.wikipedia.org/wiki/Longest_common_subsequence_problem#Code_for_the_dynamic_programming_solution This function is used only to implement @extend, largely because that's what the Ruby implementation does. Thus it's been extended slightly from the simple diff-friendly algorithm given above. What @extend wants to know is whether two simple selectors are compatible, not just equal. To that end, you must pass in a "merge" function to compare a pair of elements manually. It should return `None` if they are incompatible, and a MERGED element if they are compatible -- in the case of selectors, this is whichever one is more specific. Because of this fuzzier notion of equality, the return value is a list of ``(a_index, b_index, value)`` tuples rather than items alone. """ if mergefunc is None: # Stupid default, just in case def mergefunc(a, b): if a == b: return a return None # Precalculate equality, since it can be a tad expensive and every pair is # compared at least once eq = {} for ai, aval in enumerate(a): for bi, bval in enumerate(b): eq[ai, bi] = mergefunc(aval, bval) # Build the "length" matrix, which provides the length of the LCS for # arbitrary-length prefixes. -1 exists only to support the base case prefix_lcs_length = {} for ai in range(-1, len(a)): for bi in range(-1, len(b)): if ai == -1 or bi == -1: l = 0 elif eq[ai, bi]: l = prefix_lcs_length[ai - 1, bi - 1] + 1 else: l = max( prefix_lcs_length[ai, bi - 1], prefix_lcs_length[ai - 1, bi]) prefix_lcs_length[ai, bi] = l # The interesting part. The key insight is that the bottom-right value in # the length matrix must be the length of the LCS because of how the matrix # is defined, so all that's left to do is backtrack from the ends of both # sequences in whatever way keeps the LCS as long as possible, and keep # track of the equal pairs of elements we see along the way. # Wikipedia does this with recursion, but the algorithm is trivial to # rewrite as a loop, as below. ai = len(a) - 1 bi = len(b) - 1 ret = [] while ai >= 0 and bi >= 0: merged = eq[ai, bi] if merged is not None: ret.append((ai, bi, merged)) ai -= 1 bi -= 1 elif prefix_lcs_length[ai, bi - 1] > prefix_lcs_length[ai - 1, bi]: bi -= 1 else: ai -= 1 # ret has the latest items first, which is backwards ret.reverse() return ret
python
def longest_common_subsequence(a, b, mergefunc=None): """Find the longest common subsequence between two iterables. The longest common subsequence is the core of any diff algorithm: it's the longest sequence of elements that appears in both parent sequences in the same order, but NOT necessarily consecutively. Original algorithm borrowed from Wikipedia: http://en.wikipedia.org/wiki/Longest_common_subsequence_problem#Code_for_the_dynamic_programming_solution This function is used only to implement @extend, largely because that's what the Ruby implementation does. Thus it's been extended slightly from the simple diff-friendly algorithm given above. What @extend wants to know is whether two simple selectors are compatible, not just equal. To that end, you must pass in a "merge" function to compare a pair of elements manually. It should return `None` if they are incompatible, and a MERGED element if they are compatible -- in the case of selectors, this is whichever one is more specific. Because of this fuzzier notion of equality, the return value is a list of ``(a_index, b_index, value)`` tuples rather than items alone. """ if mergefunc is None: # Stupid default, just in case def mergefunc(a, b): if a == b: return a return None # Precalculate equality, since it can be a tad expensive and every pair is # compared at least once eq = {} for ai, aval in enumerate(a): for bi, bval in enumerate(b): eq[ai, bi] = mergefunc(aval, bval) # Build the "length" matrix, which provides the length of the LCS for # arbitrary-length prefixes. -1 exists only to support the base case prefix_lcs_length = {} for ai in range(-1, len(a)): for bi in range(-1, len(b)): if ai == -1 or bi == -1: l = 0 elif eq[ai, bi]: l = prefix_lcs_length[ai - 1, bi - 1] + 1 else: l = max( prefix_lcs_length[ai, bi - 1], prefix_lcs_length[ai - 1, bi]) prefix_lcs_length[ai, bi] = l # The interesting part. The key insight is that the bottom-right value in # the length matrix must be the length of the LCS because of how the matrix # is defined, so all that's left to do is backtrack from the ends of both # sequences in whatever way keeps the LCS as long as possible, and keep # track of the equal pairs of elements we see along the way. # Wikipedia does this with recursion, but the algorithm is trivial to # rewrite as a loop, as below. ai = len(a) - 1 bi = len(b) - 1 ret = [] while ai >= 0 and bi >= 0: merged = eq[ai, bi] if merged is not None: ret.append((ai, bi, merged)) ai -= 1 bi -= 1 elif prefix_lcs_length[ai, bi - 1] > prefix_lcs_length[ai - 1, bi]: bi -= 1 else: ai -= 1 # ret has the latest items first, which is backwards ret.reverse() return ret
[ "def", "longest_common_subsequence", "(", "a", ",", "b", ",", "mergefunc", "=", "None", ")", ":", "if", "mergefunc", "is", "None", ":", "# Stupid default, just in case", "def", "mergefunc", "(", "a", ",", "b", ")", ":", "if", "a", "==", "b", ":", "return...
Find the longest common subsequence between two iterables. The longest common subsequence is the core of any diff algorithm: it's the longest sequence of elements that appears in both parent sequences in the same order, but NOT necessarily consecutively. Original algorithm borrowed from Wikipedia: http://en.wikipedia.org/wiki/Longest_common_subsequence_problem#Code_for_the_dynamic_programming_solution This function is used only to implement @extend, largely because that's what the Ruby implementation does. Thus it's been extended slightly from the simple diff-friendly algorithm given above. What @extend wants to know is whether two simple selectors are compatible, not just equal. To that end, you must pass in a "merge" function to compare a pair of elements manually. It should return `None` if they are incompatible, and a MERGED element if they are compatible -- in the case of selectors, this is whichever one is more specific. Because of this fuzzier notion of equality, the return value is a list of ``(a_index, b_index, value)`` tuples rather than items alone.
[ "Find", "the", "longest", "common", "subsequence", "between", "two", "iterables", "." ]
fb32b317f6e2b4b4aad2b86a74844658ac4aa11e
https://github.com/Kronuz/pyScss/blob/fb32b317f6e2b4b4aad2b86a74844658ac4aa11e/scss/selector.py#L587-L664
train
23,091
Kronuz/pyScss
scss/selector.py
SimpleSelector.is_superset_of
def is_superset_of(self, other, soft_combinator=False): """Return True iff this selector matches the same elements as `other`, and perhaps others. That is, ``.foo`` is a superset of ``.foo.bar``, because the latter is more specific. Set `soft_combinator` true to ignore the specific case of this selector having a descendent combinator and `other` having anything else. This is for superset checking for ``@extend``, where a space combinator really means "none". """ # Combinators must match, OR be compatible -- space is a superset of >, # ~ is a superset of + if soft_combinator and self.combinator == ' ': combinator_superset = True else: combinator_superset = ( self.combinator == other.combinator or (self.combinator == ' ' and other.combinator == '>') or (self.combinator == '~' and other.combinator == '+')) return ( combinator_superset and set(self.tokens) <= set(other.tokens))
python
def is_superset_of(self, other, soft_combinator=False): """Return True iff this selector matches the same elements as `other`, and perhaps others. That is, ``.foo`` is a superset of ``.foo.bar``, because the latter is more specific. Set `soft_combinator` true to ignore the specific case of this selector having a descendent combinator and `other` having anything else. This is for superset checking for ``@extend``, where a space combinator really means "none". """ # Combinators must match, OR be compatible -- space is a superset of >, # ~ is a superset of + if soft_combinator and self.combinator == ' ': combinator_superset = True else: combinator_superset = ( self.combinator == other.combinator or (self.combinator == ' ' and other.combinator == '>') or (self.combinator == '~' and other.combinator == '+')) return ( combinator_superset and set(self.tokens) <= set(other.tokens))
[ "def", "is_superset_of", "(", "self", ",", "other", ",", "soft_combinator", "=", "False", ")", ":", "# Combinators must match, OR be compatible -- space is a superset of >,", "# ~ is a superset of +", "if", "soft_combinator", "and", "self", ".", "combinator", "==", "' '", ...
Return True iff this selector matches the same elements as `other`, and perhaps others. That is, ``.foo`` is a superset of ``.foo.bar``, because the latter is more specific. Set `soft_combinator` true to ignore the specific case of this selector having a descendent combinator and `other` having anything else. This is for superset checking for ``@extend``, where a space combinator really means "none".
[ "Return", "True", "iff", "this", "selector", "matches", "the", "same", "elements", "as", "other", "and", "perhaps", "others", "." ]
fb32b317f6e2b4b4aad2b86a74844658ac4aa11e
https://github.com/Kronuz/pyScss/blob/fb32b317f6e2b4b4aad2b86a74844658ac4aa11e/scss/selector.py#L136-L160
train
23,092
Kronuz/pyScss
scss/selector.py
Selector.substitute
def substitute(self, target, replacement): """Return a list of selectors obtained by replacing the `target` selector with `replacement`. Herein lie the guts of the Sass @extend directive. In general, for a selector ``a X b Y c``, a target ``X Y``, and a replacement ``q Z``, return the selectors ``a q X b Z c`` and ``q a X b Z c``. Note in particular that no more than two selectors will be returned, and the permutation of ancestors will never insert new simple selectors "inside" the target selector. """ # Find the target in the parent selector, and split it into # before/after p_before, p_extras, p_after = self.break_around(target.simple_selectors) # The replacement has no hinge; it only has the most specific simple # selector (which is the part that replaces "self" in the parent) and # whatever preceding simple selectors there may be r_trail = replacement.simple_selectors[:-1] r_extras = replacement.simple_selectors[-1] # TODO what if the prefix doesn't match? who wins? should we even get # this far? focal_nodes = (p_extras.merge_into(r_extras),) befores = _merge_selectors(p_before, r_trail) cls = type(self) return [ cls(before + focal_nodes + p_after) for before in befores]
python
def substitute(self, target, replacement): """Return a list of selectors obtained by replacing the `target` selector with `replacement`. Herein lie the guts of the Sass @extend directive. In general, for a selector ``a X b Y c``, a target ``X Y``, and a replacement ``q Z``, return the selectors ``a q X b Z c`` and ``q a X b Z c``. Note in particular that no more than two selectors will be returned, and the permutation of ancestors will never insert new simple selectors "inside" the target selector. """ # Find the target in the parent selector, and split it into # before/after p_before, p_extras, p_after = self.break_around(target.simple_selectors) # The replacement has no hinge; it only has the most specific simple # selector (which is the part that replaces "self" in the parent) and # whatever preceding simple selectors there may be r_trail = replacement.simple_selectors[:-1] r_extras = replacement.simple_selectors[-1] # TODO what if the prefix doesn't match? who wins? should we even get # this far? focal_nodes = (p_extras.merge_into(r_extras),) befores = _merge_selectors(p_before, r_trail) cls = type(self) return [ cls(before + focal_nodes + p_after) for before in befores]
[ "def", "substitute", "(", "self", ",", "target", ",", "replacement", ")", ":", "# Find the target in the parent selector, and split it into", "# before/after", "p_before", ",", "p_extras", ",", "p_after", "=", "self", ".", "break_around", "(", "target", ".", "simple_s...
Return a list of selectors obtained by replacing the `target` selector with `replacement`. Herein lie the guts of the Sass @extend directive. In general, for a selector ``a X b Y c``, a target ``X Y``, and a replacement ``q Z``, return the selectors ``a q X b Z c`` and ``q a X b Z c``. Note in particular that no more than two selectors will be returned, and the permutation of ancestors will never insert new simple selectors "inside" the target selector.
[ "Return", "a", "list", "of", "selectors", "obtained", "by", "replacing", "the", "target", "selector", "with", "replacement", "." ]
fb32b317f6e2b4b4aad2b86a74844658ac4aa11e
https://github.com/Kronuz/pyScss/blob/fb32b317f6e2b4b4aad2b86a74844658ac4aa11e/scss/selector.py#L428-L459
train
23,093
Kronuz/pyScss
scss/cssdefs.py
convert_units_to_base_units
def convert_units_to_base_units(units): """Convert a set of units into a set of "base" units. Returns a 2-tuple of `factor, new_units`. """ total_factor = 1 new_units = [] for unit in units: if unit not in BASE_UNIT_CONVERSIONS: continue factor, new_unit = BASE_UNIT_CONVERSIONS[unit] total_factor *= factor new_units.append(new_unit) new_units.sort() return total_factor, tuple(new_units)
python
def convert_units_to_base_units(units): """Convert a set of units into a set of "base" units. Returns a 2-tuple of `factor, new_units`. """ total_factor = 1 new_units = [] for unit in units: if unit not in BASE_UNIT_CONVERSIONS: continue factor, new_unit = BASE_UNIT_CONVERSIONS[unit] total_factor *= factor new_units.append(new_unit) new_units.sort() return total_factor, tuple(new_units)
[ "def", "convert_units_to_base_units", "(", "units", ")", ":", "total_factor", "=", "1", "new_units", "=", "[", "]", "for", "unit", "in", "units", ":", "if", "unit", "not", "in", "BASE_UNIT_CONVERSIONS", ":", "continue", "factor", ",", "new_unit", "=", "BASE_...
Convert a set of units into a set of "base" units. Returns a 2-tuple of `factor, new_units`.
[ "Convert", "a", "set", "of", "units", "into", "a", "set", "of", "base", "units", "." ]
fb32b317f6e2b4b4aad2b86a74844658ac4aa11e
https://github.com/Kronuz/pyScss/blob/fb32b317f6e2b4b4aad2b86a74844658ac4aa11e/scss/cssdefs.py#L208-L224
train
23,094
Kronuz/pyScss
scss/cssdefs.py
count_base_units
def count_base_units(units): """Returns a dict mapping names of base units to how many times they appear in the given iterable of units. Effectively this counts how many length units you have, how many time units, and so forth. """ ret = {} for unit in units: factor, base_unit = get_conversion_factor(unit) ret.setdefault(base_unit, 0) ret[base_unit] += 1 return ret
python
def count_base_units(units): """Returns a dict mapping names of base units to how many times they appear in the given iterable of units. Effectively this counts how many length units you have, how many time units, and so forth. """ ret = {} for unit in units: factor, base_unit = get_conversion_factor(unit) ret.setdefault(base_unit, 0) ret[base_unit] += 1 return ret
[ "def", "count_base_units", "(", "units", ")", ":", "ret", "=", "{", "}", "for", "unit", "in", "units", ":", "factor", ",", "base_unit", "=", "get_conversion_factor", "(", "unit", ")", "ret", ".", "setdefault", "(", "base_unit", ",", "0", ")", "ret", "[...
Returns a dict mapping names of base units to how many times they appear in the given iterable of units. Effectively this counts how many length units you have, how many time units, and so forth.
[ "Returns", "a", "dict", "mapping", "names", "of", "base", "units", "to", "how", "many", "times", "they", "appear", "in", "the", "given", "iterable", "of", "units", ".", "Effectively", "this", "counts", "how", "many", "length", "units", "you", "have", "how"...
fb32b317f6e2b4b4aad2b86a74844658ac4aa11e
https://github.com/Kronuz/pyScss/blob/fb32b317f6e2b4b4aad2b86a74844658ac4aa11e/scss/cssdefs.py#L227-L239
train
23,095
Kronuz/pyScss
scss/cssdefs.py
cancel_base_units
def cancel_base_units(units, to_remove): """Given a list of units, remove a specified number of each base unit. Arguments: units: an iterable of units to_remove: a mapping of base_unit => count, such as that returned from count_base_units Returns a 2-tuple of (factor, remaining_units). """ # Copy the dict since we're about to mutate it to_remove = to_remove.copy() remaining_units = [] total_factor = Fraction(1) for unit in units: factor, base_unit = get_conversion_factor(unit) if not to_remove.get(base_unit, 0): remaining_units.append(unit) continue total_factor *= factor to_remove[base_unit] -= 1 return total_factor, remaining_units
python
def cancel_base_units(units, to_remove): """Given a list of units, remove a specified number of each base unit. Arguments: units: an iterable of units to_remove: a mapping of base_unit => count, such as that returned from count_base_units Returns a 2-tuple of (factor, remaining_units). """ # Copy the dict since we're about to mutate it to_remove = to_remove.copy() remaining_units = [] total_factor = Fraction(1) for unit in units: factor, base_unit = get_conversion_factor(unit) if not to_remove.get(base_unit, 0): remaining_units.append(unit) continue total_factor *= factor to_remove[base_unit] -= 1 return total_factor, remaining_units
[ "def", "cancel_base_units", "(", "units", ",", "to_remove", ")", ":", "# Copy the dict since we're about to mutate it", "to_remove", "=", "to_remove", ".", "copy", "(", ")", "remaining_units", "=", "[", "]", "total_factor", "=", "Fraction", "(", "1", ")", "for", ...
Given a list of units, remove a specified number of each base unit. Arguments: units: an iterable of units to_remove: a mapping of base_unit => count, such as that returned from count_base_units Returns a 2-tuple of (factor, remaining_units).
[ "Given", "a", "list", "of", "units", "remove", "a", "specified", "number", "of", "each", "base", "unit", "." ]
fb32b317f6e2b4b4aad2b86a74844658ac4aa11e
https://github.com/Kronuz/pyScss/blob/fb32b317f6e2b4b4aad2b86a74844658ac4aa11e/scss/cssdefs.py#L242-L267
train
23,096
Kronuz/pyScss
scss/cssdefs.py
is_builtin_css_function
def is_builtin_css_function(name): """Returns whether the given `name` looks like the name of a builtin CSS function. Unrecognized functions not in this list produce warnings. """ name = name.replace('_', '-') if name in BUILTIN_FUNCTIONS: return True # Vendor-specific functions (-foo-bar) are always okay if name[0] == '-' and '-' in name[1:]: return True return False
python
def is_builtin_css_function(name): """Returns whether the given `name` looks like the name of a builtin CSS function. Unrecognized functions not in this list produce warnings. """ name = name.replace('_', '-') if name in BUILTIN_FUNCTIONS: return True # Vendor-specific functions (-foo-bar) are always okay if name[0] == '-' and '-' in name[1:]: return True return False
[ "def", "is_builtin_css_function", "(", "name", ")", ":", "name", "=", "name", ".", "replace", "(", "'_'", ",", "'-'", ")", "if", "name", "in", "BUILTIN_FUNCTIONS", ":", "return", "True", "# Vendor-specific functions (-foo-bar) are always okay", "if", "name", "[", ...
Returns whether the given `name` looks like the name of a builtin CSS function. Unrecognized functions not in this list produce warnings.
[ "Returns", "whether", "the", "given", "name", "looks", "like", "the", "name", "of", "a", "builtin", "CSS", "function", "." ]
fb32b317f6e2b4b4aad2b86a74844658ac4aa11e
https://github.com/Kronuz/pyScss/blob/fb32b317f6e2b4b4aad2b86a74844658ac4aa11e/scss/cssdefs.py#L336-L351
train
23,097
Kronuz/pyScss
scss/cssdefs.py
determine_encoding
def determine_encoding(buf): """Return the appropriate encoding for the given CSS source, according to the CSS charset rules. `buf` may be either a string or bytes. """ # The ultimate default is utf8; bravo, W3C bom_encoding = 'UTF-8' if not buf: # What return bom_encoding if isinstance(buf, six.text_type): # We got a file that, for whatever reason, produces already-decoded # text. Check for the BOM (which is useless now) and believe # whatever's in the @charset. if buf[0] == '\ufeff': buf = buf[0:] # This is pretty similar to the code below, but without any encoding # double-checking. charset_start = '@charset "' charset_end = '";' if buf.startswith(charset_start): start = len(charset_start) end = buf.index(charset_end, start) return buf[start:end] else: return bom_encoding # BOMs if buf[:3] == b'\xef\xbb\xbf': bom_encoding = 'UTF-8' buf = buf[3:] if buf[:4] == b'\x00\x00\xfe\xff': bom_encoding = 'UTF-32BE' buf = buf[4:] elif buf[:4] == b'\xff\xfe\x00\x00': bom_encoding = 'UTF-32LE' buf = buf[4:] if buf[:4] == b'\x00\x00\xff\xfe': raise UnicodeError("UTF-32-2143 is not supported") elif buf[:4] == b'\xfe\xff\x00\x00': raise UnicodeError("UTF-32-2143 is not supported") elif buf[:2] == b'\xfe\xff': bom_encoding = 'UTF-16BE' buf = buf[2:] elif buf[:2] == b'\xff\xfe': bom_encoding = 'UTF-16LE' buf = buf[2:] # The spec requires exactly this syntax; no escapes or extra spaces or # other shenanigans, thank goodness. charset_start = '@charset "'.encode(bom_encoding) charset_end = '";'.encode(bom_encoding) if buf.startswith(charset_start): start = len(charset_start) end = buf.index(charset_end, start) encoded_encoding = buf[start:end] encoding = encoded_encoding.decode(bom_encoding) # Ensure that decoding with the specified encoding actually produces # the same @charset rule encoded_charset = buf[:end + len(charset_end)] if (encoded_charset.decode(encoding) != encoded_charset.decode(bom_encoding)): raise UnicodeError( "@charset {0} is incompatible with detected encoding {1}" .format(bom_encoding, encoding)) else: # With no @charset, believe the BOM encoding = bom_encoding return encoding
python
def determine_encoding(buf): """Return the appropriate encoding for the given CSS source, according to the CSS charset rules. `buf` may be either a string or bytes. """ # The ultimate default is utf8; bravo, W3C bom_encoding = 'UTF-8' if not buf: # What return bom_encoding if isinstance(buf, six.text_type): # We got a file that, for whatever reason, produces already-decoded # text. Check for the BOM (which is useless now) and believe # whatever's in the @charset. if buf[0] == '\ufeff': buf = buf[0:] # This is pretty similar to the code below, but without any encoding # double-checking. charset_start = '@charset "' charset_end = '";' if buf.startswith(charset_start): start = len(charset_start) end = buf.index(charset_end, start) return buf[start:end] else: return bom_encoding # BOMs if buf[:3] == b'\xef\xbb\xbf': bom_encoding = 'UTF-8' buf = buf[3:] if buf[:4] == b'\x00\x00\xfe\xff': bom_encoding = 'UTF-32BE' buf = buf[4:] elif buf[:4] == b'\xff\xfe\x00\x00': bom_encoding = 'UTF-32LE' buf = buf[4:] if buf[:4] == b'\x00\x00\xff\xfe': raise UnicodeError("UTF-32-2143 is not supported") elif buf[:4] == b'\xfe\xff\x00\x00': raise UnicodeError("UTF-32-2143 is not supported") elif buf[:2] == b'\xfe\xff': bom_encoding = 'UTF-16BE' buf = buf[2:] elif buf[:2] == b'\xff\xfe': bom_encoding = 'UTF-16LE' buf = buf[2:] # The spec requires exactly this syntax; no escapes or extra spaces or # other shenanigans, thank goodness. charset_start = '@charset "'.encode(bom_encoding) charset_end = '";'.encode(bom_encoding) if buf.startswith(charset_start): start = len(charset_start) end = buf.index(charset_end, start) encoded_encoding = buf[start:end] encoding = encoded_encoding.decode(bom_encoding) # Ensure that decoding with the specified encoding actually produces # the same @charset rule encoded_charset = buf[:end + len(charset_end)] if (encoded_charset.decode(encoding) != encoded_charset.decode(bom_encoding)): raise UnicodeError( "@charset {0} is incompatible with detected encoding {1}" .format(bom_encoding, encoding)) else: # With no @charset, believe the BOM encoding = bom_encoding return encoding
[ "def", "determine_encoding", "(", "buf", ")", ":", "# The ultimate default is utf8; bravo, W3C", "bom_encoding", "=", "'UTF-8'", "if", "not", "buf", ":", "# What", "return", "bom_encoding", "if", "isinstance", "(", "buf", ",", "six", ".", "text_type", ")", ":", ...
Return the appropriate encoding for the given CSS source, according to the CSS charset rules. `buf` may be either a string or bytes.
[ "Return", "the", "appropriate", "encoding", "for", "the", "given", "CSS", "source", "according", "to", "the", "CSS", "charset", "rules", "." ]
fb32b317f6e2b4b4aad2b86a74844658ac4aa11e
https://github.com/Kronuz/pyScss/blob/fb32b317f6e2b4b4aad2b86a74844658ac4aa11e/scss/cssdefs.py#L358-L432
train
23,098
Kronuz/pyScss
scss/ast.py
Interpolation.maybe
def maybe(cls, parts, quotes=None, type=String, **kwargs): """Returns an interpolation if there are multiple parts, otherwise a plain Literal. This keeps the AST somewhat simpler, but also is the only way `Literal.from_bareword` gets called. """ if len(parts) > 1: return cls(parts, quotes=quotes, type=type, **kwargs) if quotes is None and type is String: return Literal.from_bareword(parts[0]) return Literal(type(parts[0], quotes=quotes, **kwargs))
python
def maybe(cls, parts, quotes=None, type=String, **kwargs): """Returns an interpolation if there are multiple parts, otherwise a plain Literal. This keeps the AST somewhat simpler, but also is the only way `Literal.from_bareword` gets called. """ if len(parts) > 1: return cls(parts, quotes=quotes, type=type, **kwargs) if quotes is None and type is String: return Literal.from_bareword(parts[0]) return Literal(type(parts[0], quotes=quotes, **kwargs))
[ "def", "maybe", "(", "cls", ",", "parts", ",", "quotes", "=", "None", ",", "type", "=", "String", ",", "*", "*", "kwargs", ")", ":", "if", "len", "(", "parts", ")", ">", "1", ":", "return", "cls", "(", "parts", ",", "quotes", "=", "quotes", ","...
Returns an interpolation if there are multiple parts, otherwise a plain Literal. This keeps the AST somewhat simpler, but also is the only way `Literal.from_bareword` gets called.
[ "Returns", "an", "interpolation", "if", "there", "are", "multiple", "parts", "otherwise", "a", "plain", "Literal", ".", "This", "keeps", "the", "AST", "somewhat", "simpler", "but", "also", "is", "the", "only", "way", "Literal", ".", "from_bareword", "gets", ...
fb32b317f6e2b4b4aad2b86a74844658ac4aa11e
https://github.com/Kronuz/pyScss/blob/fb32b317f6e2b4b4aad2b86a74844658ac4aa11e/scss/ast.py#L274-L285
train
23,099