repository_name
stringlengths
5
67
func_path_in_repository
stringlengths
4
234
func_name
stringlengths
0
314
whole_func_string
stringlengths
52
3.87M
language
stringclasses
6 values
func_code_string
stringlengths
52
3.87M
func_code_tokens
listlengths
15
672k
func_documentation_string
stringlengths
1
47.2k
func_documentation_tokens
listlengths
1
3.92k
split_name
stringclasses
1 value
func_code_url
stringlengths
85
339
rdireen/spherepy
spherepy/spherepy.py
vspht
def vspht(vsphere, nmax=None, mmax=None): """Returns a VectorCoefs object containt the vector spherical harmonic coefficients of the VectorPatternUniform object""" if nmax == None: nmax = vsphere.nrows - 2 mmax = int(vsphere.ncols / 2) - 1 elif mmax == None: mmax = nmax if mmax > nmax: raise ValueError(err_msg['nmax_g_mmax']) if nmax >= vsphere.nrows - 1: raise ValueError(err_msg['nmax_too_lrg']) if mmax >= vsphere.ncols / 2: raise ValueError(err_msg['mmax_too_lrg']) dnrows = vsphere._tdsphere.shape[0] ncols = vsphere._tdsphere.shape[1] if np.mod(ncols, 2) == 1: raise ValueError(err_msg['ncols_even']) ft = np.fft.fft2(vsphere._tdsphere) / (dnrows * ncols) ops.fix_even_row_data_fc(ft) ft_extended = np.zeros([dnrows + 2, ncols], dtype=np.complex128) ops.pad_rows_fdata(ft, ft_extended) pt = np.fft.fft2(vsphere._pdsphere) / (dnrows * ncols) ops.fix_even_row_data_fc(pt) pt_extended = np.zeros([dnrows + 2, ncols], dtype=np.complex128) ops.pad_rows_fdata(pt, pt_extended) ftmp = np.copy(ft_extended) ptmp = np.copy(pt_extended) Lf1 = ops.sinLdot_fc(ft_extended, pt_extended) Lf2 = ops.sinLdot_fc(-1j * ptmp, 1j * ftmp) # check if we are using c extended versions of the code or not if use_cext: N = nmax + 1; NC = N + mmax * (2 * N - mmax - 1); sc1 = np.zeros(NC, dtype=np.complex128) sc2 = np.zeros(NC, dtype=np.complex128) csphi.fc_to_sc(Lf1, sc1, nmax, mmax) csphi.fc_to_sc(Lf2, sc2, nmax, mmax) else: sc1 = pysphi.fc_to_sc(Lf1, nmax, mmax) sc2 = pysphi.fc_to_sc(Lf2, nmax, mmax) vcoefs = VectorCoefs(sc1, sc2, nmax, mmax) nvec = np.zeros(nmax + 1, dtype=np.complex128) for n in xrange(1, nmax + 1): nvec[n] = 1.0 / np.sqrt(n * (n + 1.0)) vcoefs.scoef1.window(nvec) vcoefs.scoef2.window(nvec) return vcoefs
python
def vspht(vsphere, nmax=None, mmax=None): """Returns a VectorCoefs object containt the vector spherical harmonic coefficients of the VectorPatternUniform object""" if nmax == None: nmax = vsphere.nrows - 2 mmax = int(vsphere.ncols / 2) - 1 elif mmax == None: mmax = nmax if mmax > nmax: raise ValueError(err_msg['nmax_g_mmax']) if nmax >= vsphere.nrows - 1: raise ValueError(err_msg['nmax_too_lrg']) if mmax >= vsphere.ncols / 2: raise ValueError(err_msg['mmax_too_lrg']) dnrows = vsphere._tdsphere.shape[0] ncols = vsphere._tdsphere.shape[1] if np.mod(ncols, 2) == 1: raise ValueError(err_msg['ncols_even']) ft = np.fft.fft2(vsphere._tdsphere) / (dnrows * ncols) ops.fix_even_row_data_fc(ft) ft_extended = np.zeros([dnrows + 2, ncols], dtype=np.complex128) ops.pad_rows_fdata(ft, ft_extended) pt = np.fft.fft2(vsphere._pdsphere) / (dnrows * ncols) ops.fix_even_row_data_fc(pt) pt_extended = np.zeros([dnrows + 2, ncols], dtype=np.complex128) ops.pad_rows_fdata(pt, pt_extended) ftmp = np.copy(ft_extended) ptmp = np.copy(pt_extended) Lf1 = ops.sinLdot_fc(ft_extended, pt_extended) Lf2 = ops.sinLdot_fc(-1j * ptmp, 1j * ftmp) # check if we are using c extended versions of the code or not if use_cext: N = nmax + 1; NC = N + mmax * (2 * N - mmax - 1); sc1 = np.zeros(NC, dtype=np.complex128) sc2 = np.zeros(NC, dtype=np.complex128) csphi.fc_to_sc(Lf1, sc1, nmax, mmax) csphi.fc_to_sc(Lf2, sc2, nmax, mmax) else: sc1 = pysphi.fc_to_sc(Lf1, nmax, mmax) sc2 = pysphi.fc_to_sc(Lf2, nmax, mmax) vcoefs = VectorCoefs(sc1, sc2, nmax, mmax) nvec = np.zeros(nmax + 1, dtype=np.complex128) for n in xrange(1, nmax + 1): nvec[n] = 1.0 / np.sqrt(n * (n + 1.0)) vcoefs.scoef1.window(nvec) vcoefs.scoef2.window(nvec) return vcoefs
[ "def", "vspht", "(", "vsphere", ",", "nmax", "=", "None", ",", "mmax", "=", "None", ")", ":", "if", "nmax", "==", "None", ":", "nmax", "=", "vsphere", ".", "nrows", "-", "2", "mmax", "=", "int", "(", "vsphere", ".", "ncols", "/", "2", ")", "-",...
Returns a VectorCoefs object containt the vector spherical harmonic coefficients of the VectorPatternUniform object
[ "Returns", "a", "VectorCoefs", "object", "containt", "the", "vector", "spherical", "harmonic", "coefficients", "of", "the", "VectorPatternUniform", "object" ]
train
https://github.com/rdireen/spherepy/blob/241521401d4d76851d4a1a564a365cfab8e98496/spherepy/spherepy.py#L1902-L1966
rdireen/spherepy
spherepy/spherepy.py
spht_slow
def spht_slow(ssphere, nmax, mmax): """(PURE PYTHON) Transforms ScalarPatternUniform object *ssphere* into a set of scalar spherical harmonics stored in ScalarCoefs. Example:: >>> p = spherepy.random_patt_uniform(6, 8) >>> c = spherepy.spht(p) >>> spherepy.pretty_coefs(c) Args: ssphere (ScalarPatternUniform): The pattern to be transformed. nmax (int, optional): The maximum number of *n* values required. If a value isn't passed, *nmax* is the number of rows in ssphere minus one. mmax (int, optional): The maximum number of *m* values required. If a value isn't passed, *mmax* is half the number of columns in ssphere minus one. Returns: ScalarCoefs: The object containing the coefficients of the scalar spherical harmonic transform. Raises: ValueError: If *nmax* and *mmax* are too large or *mmax* > *nmax*. """ if mmax > nmax: raise ValueError(err_msg['nmax_g_mmax']) nrows = ssphere._dsphere.shape[0] ncols = ssphere._dsphere.shape[1] if np.mod(nrows, 2) == 1 or np.mod(ncols, 2) == 1: raise ValueError(err_msg['ncols_even']) fdata = np.fft.fft2(ssphere._dsphere) / (nrows * ncols) ops.fix_even_row_data_fc(fdata) fdata_extended = np.zeros([nrows + 2, ncols], dtype=np.complex128) ops.pad_rows_fdata(fdata, fdata_extended) ops.sin_fc(fdata_extended) sc = pysphi.fc_to_sc(fdata_extended, nmax, mmax) return ScalarCoefs(sc, nmax, mmax)
python
def spht_slow(ssphere, nmax, mmax): """(PURE PYTHON) Transforms ScalarPatternUniform object *ssphere* into a set of scalar spherical harmonics stored in ScalarCoefs. Example:: >>> p = spherepy.random_patt_uniform(6, 8) >>> c = spherepy.spht(p) >>> spherepy.pretty_coefs(c) Args: ssphere (ScalarPatternUniform): The pattern to be transformed. nmax (int, optional): The maximum number of *n* values required. If a value isn't passed, *nmax* is the number of rows in ssphere minus one. mmax (int, optional): The maximum number of *m* values required. If a value isn't passed, *mmax* is half the number of columns in ssphere minus one. Returns: ScalarCoefs: The object containing the coefficients of the scalar spherical harmonic transform. Raises: ValueError: If *nmax* and *mmax* are too large or *mmax* > *nmax*. """ if mmax > nmax: raise ValueError(err_msg['nmax_g_mmax']) nrows = ssphere._dsphere.shape[0] ncols = ssphere._dsphere.shape[1] if np.mod(nrows, 2) == 1 or np.mod(ncols, 2) == 1: raise ValueError(err_msg['ncols_even']) fdata = np.fft.fft2(ssphere._dsphere) / (nrows * ncols) ops.fix_even_row_data_fc(fdata) fdata_extended = np.zeros([nrows + 2, ncols], dtype=np.complex128) ops.pad_rows_fdata(fdata, fdata_extended) ops.sin_fc(fdata_extended) sc = pysphi.fc_to_sc(fdata_extended, nmax, mmax) return ScalarCoefs(sc, nmax, mmax)
[ "def", "spht_slow", "(", "ssphere", ",", "nmax", ",", "mmax", ")", ":", "if", "mmax", ">", "nmax", ":", "raise", "ValueError", "(", "err_msg", "[", "'nmax_g_mmax'", "]", ")", "nrows", "=", "ssphere", ".", "_dsphere", ".", "shape", "[", "0", "]", "nco...
(PURE PYTHON) Transforms ScalarPatternUniform object *ssphere* into a set of scalar spherical harmonics stored in ScalarCoefs. Example:: >>> p = spherepy.random_patt_uniform(6, 8) >>> c = spherepy.spht(p) >>> spherepy.pretty_coefs(c) Args: ssphere (ScalarPatternUniform): The pattern to be transformed. nmax (int, optional): The maximum number of *n* values required. If a value isn't passed, *nmax* is the number of rows in ssphere minus one. mmax (int, optional): The maximum number of *m* values required. If a value isn't passed, *mmax* is half the number of columns in ssphere minus one. Returns: ScalarCoefs: The object containing the coefficients of the scalar spherical harmonic transform. Raises: ValueError: If *nmax* and *mmax* are too large or *mmax* > *nmax*.
[ "(", "PURE", "PYTHON", ")", "Transforms", "ScalarPatternUniform", "object", "*", "ssphere", "*", "into", "a", "set", "of", "scalar", "spherical", "harmonics", "stored", "in", "ScalarCoefs", ".", "Example", "::", ">>>", "p", "=", "spherepy", ".", "random_patt_u...
train
https://github.com/rdireen/spherepy/blob/241521401d4d76851d4a1a564a365cfab8e98496/spherepy/spherepy.py#L1968-L2018
rdireen/spherepy
spherepy/spherepy.py
ispht
def ispht(scoefs, nrows=None, ncols=None): """Transforms ScalarCoefs object *scoefs* into a scalar pattern ScalarPatternUniform. Example:: >>> c = spherepy.random_coefs(3,3) >>> p = spherepy.ispht(c) >>> print(p) Args: scoefs (ScalarCoefs): The coefficients to be transformed to pattern space. nrows (int): The number of rows desired in the pattern. ncols (int): The number of columns desired in the pattern. This must be an even number. Returns: ScalarPatternUniform: This is the pattern. It contains a NumPy array that can be viewed with *patt.cdata*. Raises: ValueError: Is raised if *ncols* isn't even. ValueError: Is raised if *nrows* < *nmax* + 2 or *ncols* < 2 * *mmax* + 2. """ if nrows == None: nrows = scoefs.nmax + 2 if ncols == None: ncols = 2 * scoefs.mmax + 2 if nrows <= scoefs.nmax: raise ValueError(err_msg['inverse_terr']) if ncols < 2 * scoefs.mmax + 2: raise ValueError(err_msg['inverse_terr']) dnrows = int(2 * nrows - 2) if np.mod(ncols, 2) == 1: raise ValueError(err_msg['ncols_even']) if use_cext: fdata = np.zeros([dnrows, ncols], dtype=np.complex128) csphi.sc_to_fc(fdata, scoefs._vec, scoefs._nmax, scoefs._mmax) else: fdata = pysphi.sc_to_fc(scoefs._vec, scoefs._nmax, scoefs._mmax, dnrows, ncols) ds = np.fft.ifft2(fdata) * dnrows * ncols return ScalarPatternUniform(ds, doublesphere=True)
python
def ispht(scoefs, nrows=None, ncols=None): """Transforms ScalarCoefs object *scoefs* into a scalar pattern ScalarPatternUniform. Example:: >>> c = spherepy.random_coefs(3,3) >>> p = spherepy.ispht(c) >>> print(p) Args: scoefs (ScalarCoefs): The coefficients to be transformed to pattern space. nrows (int): The number of rows desired in the pattern. ncols (int): The number of columns desired in the pattern. This must be an even number. Returns: ScalarPatternUniform: This is the pattern. It contains a NumPy array that can be viewed with *patt.cdata*. Raises: ValueError: Is raised if *ncols* isn't even. ValueError: Is raised if *nrows* < *nmax* + 2 or *ncols* < 2 * *mmax* + 2. """ if nrows == None: nrows = scoefs.nmax + 2 if ncols == None: ncols = 2 * scoefs.mmax + 2 if nrows <= scoefs.nmax: raise ValueError(err_msg['inverse_terr']) if ncols < 2 * scoefs.mmax + 2: raise ValueError(err_msg['inverse_terr']) dnrows = int(2 * nrows - 2) if np.mod(ncols, 2) == 1: raise ValueError(err_msg['ncols_even']) if use_cext: fdata = np.zeros([dnrows, ncols], dtype=np.complex128) csphi.sc_to_fc(fdata, scoefs._vec, scoefs._nmax, scoefs._mmax) else: fdata = pysphi.sc_to_fc(scoefs._vec, scoefs._nmax, scoefs._mmax, dnrows, ncols) ds = np.fft.ifft2(fdata) * dnrows * ncols return ScalarPatternUniform(ds, doublesphere=True)
[ "def", "ispht", "(", "scoefs", ",", "nrows", "=", "None", ",", "ncols", "=", "None", ")", ":", "if", "nrows", "==", "None", ":", "nrows", "=", "scoefs", ".", "nmax", "+", "2", "if", "ncols", "==", "None", ":", "ncols", "=", "2", "*", "scoefs", ...
Transforms ScalarCoefs object *scoefs* into a scalar pattern ScalarPatternUniform. Example:: >>> c = spherepy.random_coefs(3,3) >>> p = spherepy.ispht(c) >>> print(p) Args: scoefs (ScalarCoefs): The coefficients to be transformed to pattern space. nrows (int): The number of rows desired in the pattern. ncols (int): The number of columns desired in the pattern. This must be an even number. Returns: ScalarPatternUniform: This is the pattern. It contains a NumPy array that can be viewed with *patt.cdata*. Raises: ValueError: Is raised if *ncols* isn't even. ValueError: Is raised if *nrows* < *nmax* + 2 or *ncols* < 2 * *mmax* + 2.
[ "Transforms", "ScalarCoefs", "object", "*", "scoefs", "*", "into", "a", "scalar", "pattern", "ScalarPatternUniform", ".", "Example", "::", ">>>", "c", "=", "spherepy", ".", "random_coefs", "(", "3", "3", ")", ">>>", "p", "=", "spherepy", ".", "ispht", "(",...
train
https://github.com/rdireen/spherepy/blob/241521401d4d76851d4a1a564a365cfab8e98496/spherepy/spherepy.py#L2020-L2079
rdireen/spherepy
spherepy/spherepy.py
ispht_slow
def ispht_slow(scoefs, nrows, ncols): """(PURE PYTHON) Transforms ScalarCoefs object *scoefs* into a scalar pattern ScalarPatternUniform. Example:: >>> c = spherepy.random_coefs(3,3) >>> p = spherepy.ispht(c) >>> print(p) Args: scoefs (ScalarCoefs): The coefficients to be transformed to pattern space. nrows (int): The number of rows desired in the pattern. ncols (int): The number of columns desired in the pattern. This must be an even number. Returns: ScalarPatternUniform: This is the pattern. It contains a NumPy array that can be viewed with *patt.cdata*. Raises: ValueError: Is raised if *ncols* isn't even. """ dnrows = 2 * nrows - 2 if np.mod(ncols, 2) == 1: raise ValueError(err_msg['ncols_even']) fdata = pysphi.sc_to_fc(scoefs._vec, scoefs._nmax, scoefs._mmax, dnrows, ncols) ds = np.fft.ifft2(fdata) * dnrows * ncols return ScalarPatternUniform(ds, doublesphere=True)
python
def ispht_slow(scoefs, nrows, ncols): """(PURE PYTHON) Transforms ScalarCoefs object *scoefs* into a scalar pattern ScalarPatternUniform. Example:: >>> c = spherepy.random_coefs(3,3) >>> p = spherepy.ispht(c) >>> print(p) Args: scoefs (ScalarCoefs): The coefficients to be transformed to pattern space. nrows (int): The number of rows desired in the pattern. ncols (int): The number of columns desired in the pattern. This must be an even number. Returns: ScalarPatternUniform: This is the pattern. It contains a NumPy array that can be viewed with *patt.cdata*. Raises: ValueError: Is raised if *ncols* isn't even. """ dnrows = 2 * nrows - 2 if np.mod(ncols, 2) == 1: raise ValueError(err_msg['ncols_even']) fdata = pysphi.sc_to_fc(scoefs._vec, scoefs._nmax, scoefs._mmax, dnrows, ncols) ds = np.fft.ifft2(fdata) * dnrows * ncols return ScalarPatternUniform(ds, doublesphere=True)
[ "def", "ispht_slow", "(", "scoefs", ",", "nrows", ",", "ncols", ")", ":", "dnrows", "=", "2", "*", "nrows", "-", "2", "if", "np", ".", "mod", "(", "ncols", ",", "2", ")", "==", "1", ":", "raise", "ValueError", "(", "err_msg", "[", "'ncols_even'", ...
(PURE PYTHON) Transforms ScalarCoefs object *scoefs* into a scalar pattern ScalarPatternUniform. Example:: >>> c = spherepy.random_coefs(3,3) >>> p = spherepy.ispht(c) >>> print(p) Args: scoefs (ScalarCoefs): The coefficients to be transformed to pattern space. nrows (int): The number of rows desired in the pattern. ncols (int): The number of columns desired in the pattern. This must be an even number. Returns: ScalarPatternUniform: This is the pattern. It contains a NumPy array that can be viewed with *patt.cdata*. Raises: ValueError: Is raised if *ncols* isn't even.
[ "(", "PURE", "PYTHON", ")", "Transforms", "ScalarCoefs", "object", "*", "scoefs", "*", "into", "a", "scalar", "pattern", "ScalarPatternUniform", ".", "Example", "::", ">>>", "c", "=", "spherepy", ".", "random_coefs", "(", "3", "3", ")", ">>>", "p", "=", ...
train
https://github.com/rdireen/spherepy/blob/241521401d4d76851d4a1a564a365cfab8e98496/spherepy/spherepy.py#L2141-L2182
rdireen/spherepy
spherepy/spherepy.py
sph_harmonic_tp
def sph_harmonic_tp(nrows, ncols, n, m): """Produces Ynm(theta,phi) theta runs from 0 to pi and has 'nrows' points. phi runs from 0 to 2*pi - 2*pi/ncols and has 'ncols' points. """ nuvec = pysphi.ynunm(n, m, n + 1) num = nuvec[1:] * (-1) ** m num = num[::-1] yvec = np.concatenate([num, nuvec]) theta = np.linspace(0.0, np.pi, nrows) phi = np.linspace(0.0, 2.0 * np.pi - 2.0 * np.pi / ncols) nu = np.array(range(-n, n + 1), dtype=np.complex128) out = np.zeros([nrows, ncols], dtype=np.complex128) for nn in xrange(0, nrows): exp_vec = np.exp(1j * nu * theta[nn]) for mm in xrange(0, ncols): vl = np.sum(yvec * exp_vec) out[nn, mm] = 1j ** m * np.exp(1j * m * phi[mm]) * vl return out
python
def sph_harmonic_tp(nrows, ncols, n, m): """Produces Ynm(theta,phi) theta runs from 0 to pi and has 'nrows' points. phi runs from 0 to 2*pi - 2*pi/ncols and has 'ncols' points. """ nuvec = pysphi.ynunm(n, m, n + 1) num = nuvec[1:] * (-1) ** m num = num[::-1] yvec = np.concatenate([num, nuvec]) theta = np.linspace(0.0, np.pi, nrows) phi = np.linspace(0.0, 2.0 * np.pi - 2.0 * np.pi / ncols) nu = np.array(range(-n, n + 1), dtype=np.complex128) out = np.zeros([nrows, ncols], dtype=np.complex128) for nn in xrange(0, nrows): exp_vec = np.exp(1j * nu * theta[nn]) for mm in xrange(0, ncols): vl = np.sum(yvec * exp_vec) out[nn, mm] = 1j ** m * np.exp(1j * m * phi[mm]) * vl return out
[ "def", "sph_harmonic_tp", "(", "nrows", ",", "ncols", ",", "n", ",", "m", ")", ":", "nuvec", "=", "pysphi", ".", "ynunm", "(", "n", ",", "m", ",", "n", "+", "1", ")", "num", "=", "nuvec", "[", "1", ":", "]", "*", "(", "-", "1", ")", "**", ...
Produces Ynm(theta,phi) theta runs from 0 to pi and has 'nrows' points. phi runs from 0 to 2*pi - 2*pi/ncols and has 'ncols' points.
[ "Produces", "Ynm", "(", "theta", "phi", ")", "theta", "runs", "from", "0", "to", "pi", "and", "has", "nrows", "points", ".", "phi", "runs", "from", "0", "to", "2", "*", "pi", "-", "2", "*", "pi", "/", "ncols", "and", "has", "ncols", "points", "."...
train
https://github.com/rdireen/spherepy/blob/241521401d4d76851d4a1a564a365cfab8e98496/spherepy/spherepy.py#L2221-L2246
rdireen/spherepy
spherepy/spherepy.py
ScalarCoefs.size
def size(self): """Total number of coefficients in the ScalarCoefs structure. Example:: >>> sz = c.size >>> N = c.nmax + 1 >>> L = N+ c.mmax * (2 * N - c.mmax - 1); >>> assert sz == L """ N = self.nmax + 1; NC = N + self.mmax * (2 * N - self.mmax - 1); assert NC == len(self._vec) return NC
python
def size(self): """Total number of coefficients in the ScalarCoefs structure. Example:: >>> sz = c.size >>> N = c.nmax + 1 >>> L = N+ c.mmax * (2 * N - c.mmax - 1); >>> assert sz == L """ N = self.nmax + 1; NC = N + self.mmax * (2 * N - self.mmax - 1); assert NC == len(self._vec) return NC
[ "def", "size", "(", "self", ")", ":", "N", "=", "self", ".", "nmax", "+", "1", "NC", "=", "N", "+", "self", ".", "mmax", "*", "(", "2", "*", "N", "-", "self", ".", "mmax", "-", "1", ")", "assert", "NC", "==", "len", "(", "self", ".", "_ve...
Total number of coefficients in the ScalarCoefs structure. Example:: >>> sz = c.size >>> N = c.nmax + 1 >>> L = N+ c.mmax * (2 * N - c.mmax - 1); >>> assert sz == L
[ "Total", "number", "of", "coefficients", "in", "the", "ScalarCoefs", "structure", ".", "Example", "::", ">>>", "sz", "=", "c", ".", "size", ">>>", "N", "=", "c", ".", "nmax", "+", "1", ">>>", "L", "=", "N", "+", "c", ".", "mmax", "*", "(", "2", ...
train
https://github.com/rdireen/spherepy/blob/241521401d4d76851d4a1a564a365cfab8e98496/spherepy/spherepy.py#L219-L232
rdireen/spherepy
spherepy/spherepy.py
ScalarCoefs.copy
def copy(self): """Make a deep copy of this object. Example:: >>> c2 = c.copy() """ vec = np.copy(self._vec) return ScalarCoefs(vec, self.nmax, self.mmax)
python
def copy(self): """Make a deep copy of this object. Example:: >>> c2 = c.copy() """ vec = np.copy(self._vec) return ScalarCoefs(vec, self.nmax, self.mmax)
[ "def", "copy", "(", "self", ")", ":", "vec", "=", "np", ".", "copy", "(", "self", ".", "_vec", ")", "return", "ScalarCoefs", "(", "vec", ",", "self", ".", "nmax", ",", "self", ".", "mmax", ")" ]
Make a deep copy of this object. Example:: >>> c2 = c.copy()
[ "Make", "a", "deep", "copy", "of", "this", "object", ".", "Example", "::", ">>>", "c2", "=", "c", ".", "copy", "()" ]
train
https://github.com/rdireen/spherepy/blob/241521401d4d76851d4a1a564a365cfab8e98496/spherepy/spherepy.py#L234-L243
rdireen/spherepy
spherepy/spherepy.py
ScalarCoefs.window
def window(self, vec): """Apply a window to the coefficients defined by *vec*. *vec* must have length *nmax* + 1. This is good way to filter the pattern by windowing in the coefficient domain. Example:: >>> vec = numpy.linspace(0, 1, c.nmax + 1) >>> c.window(vec) Args: vec (numpy.array): Vector of values to apply in the n direction of the data. Has length *nmax* + 1. Returns: Nothing, applies the window to the data in place. """ slce = slice(None, None, None) self.__setitem__((slce, 0), self.__getitem__((slce, 0)) * vec) for m in xrange(1, self.mmax + 1): self.__setitem__((slce, -m), self.__getitem__((slce, -m)) * vec[m:]) self.__setitem__((slce, m), self.__getitem__((slce, m)) * vec[m:])
python
def window(self, vec): """Apply a window to the coefficients defined by *vec*. *vec* must have length *nmax* + 1. This is good way to filter the pattern by windowing in the coefficient domain. Example:: >>> vec = numpy.linspace(0, 1, c.nmax + 1) >>> c.window(vec) Args: vec (numpy.array): Vector of values to apply in the n direction of the data. Has length *nmax* + 1. Returns: Nothing, applies the window to the data in place. """ slce = slice(None, None, None) self.__setitem__((slce, 0), self.__getitem__((slce, 0)) * vec) for m in xrange(1, self.mmax + 1): self.__setitem__((slce, -m), self.__getitem__((slce, -m)) * vec[m:]) self.__setitem__((slce, m), self.__getitem__((slce, m)) * vec[m:])
[ "def", "window", "(", "self", ",", "vec", ")", ":", "slce", "=", "slice", "(", "None", ",", "None", ",", "None", ")", "self", ".", "__setitem__", "(", "(", "slce", ",", "0", ")", ",", "self", ".", "__getitem__", "(", "(", "slce", ",", "0", ")",...
Apply a window to the coefficients defined by *vec*. *vec* must have length *nmax* + 1. This is good way to filter the pattern by windowing in the coefficient domain. Example:: >>> vec = numpy.linspace(0, 1, c.nmax + 1) >>> c.window(vec) Args: vec (numpy.array): Vector of values to apply in the n direction of the data. Has length *nmax* + 1. Returns: Nothing, applies the window to the data in place.
[ "Apply", "a", "window", "to", "the", "coefficients", "defined", "by", "*", "vec", "*", ".", "*", "vec", "*", "must", "have", "length", "*", "nmax", "*", "+", "1", ".", "This", "is", "good", "way", "to", "filter", "the", "pattern", "by", "windowing", ...
train
https://github.com/rdireen/spherepy/blob/241521401d4d76851d4a1a564a365cfab8e98496/spherepy/spherepy.py#L245-L269
rdireen/spherepy
spherepy/spherepy.py
ScalarCoefs.angular_power_spectrum
def angular_power_spectrum(self): """Returns the angular power spectrum for the set of coefficients. That is, we compute n c_n = sum cnm * conj( cnm ) m=-n Returns: power_spectrum (numpy.array, dtype=double) spectrum as a function of n. """ # Added this routine as a result of my discussions with Ajinkya Nene #https://github.com/anene list_of_modes = self._reshape_m_vecs() Nmodes = len(list_of_modes) angular_power = np.zeros( Nmodes, dtype = np.double) for n in range(0, Nmodes): mode = np.array( list_of_modes[n], dtype = np.complex128 ) angular_power[n] = np.sum( np.abs(mode) ** 2 ) return angular_power
python
def angular_power_spectrum(self): """Returns the angular power spectrum for the set of coefficients. That is, we compute n c_n = sum cnm * conj( cnm ) m=-n Returns: power_spectrum (numpy.array, dtype=double) spectrum as a function of n. """ # Added this routine as a result of my discussions with Ajinkya Nene #https://github.com/anene list_of_modes = self._reshape_m_vecs() Nmodes = len(list_of_modes) angular_power = np.zeros( Nmodes, dtype = np.double) for n in range(0, Nmodes): mode = np.array( list_of_modes[n], dtype = np.complex128 ) angular_power[n] = np.sum( np.abs(mode) ** 2 ) return angular_power
[ "def", "angular_power_spectrum", "(", "self", ")", ":", "# Added this routine as a result of my discussions with Ajinkya Nene\t \r", "#https://github.com/anene\r", "list_of_modes", "=", "self", ".", "_reshape_m_vecs", "(", ")", "Nmodes", "=", "len", "(", "list_of_modes", ")",...
Returns the angular power spectrum for the set of coefficients. That is, we compute n c_n = sum cnm * conj( cnm ) m=-n Returns: power_spectrum (numpy.array, dtype=double) spectrum as a function of n.
[ "Returns", "the", "angular", "power", "spectrum", "for", "the", "set", "of", "coefficients", ".", "That", "is", "we", "compute", "n", "c_n", "=", "sum", "cnm", "*", "conj", "(", "cnm", ")", "m", "=", "-", "n", "Returns", ":", "power_spectrum", "(", "...
train
https://github.com/rdireen/spherepy/blob/241521401d4d76851d4a1a564a365cfab8e98496/spherepy/spherepy.py#L271-L294
rdireen/spherepy
spherepy/spherepy.py
ScalarCoefs._array_2d_repr
def _array_2d_repr(self): """creates a 2D array that has nmax + 1 rows and 2*mmax + 1 columns and provides a representation for the coefficients that makes plotting easier""" sc_array = np.zeros((self.nmax + 1, 2 * self.mmax + 1), dtype=np.complex128) lst = self._reshape_n_vecs() sc_array[0:self.nmax + 1, self.mmax] = lst[0] for m in xrange(1, self.mmax + 1): sc_array[m:self.nmax + 1, self.mmax - m] = lst[2 * m - 1] sc_array[m:self.nmax + 1, self.mmax + m] = lst[2 * m] return sc_array
python
def _array_2d_repr(self): """creates a 2D array that has nmax + 1 rows and 2*mmax + 1 columns and provides a representation for the coefficients that makes plotting easier""" sc_array = np.zeros((self.nmax + 1, 2 * self.mmax + 1), dtype=np.complex128) lst = self._reshape_n_vecs() sc_array[0:self.nmax + 1, self.mmax] = lst[0] for m in xrange(1, self.mmax + 1): sc_array[m:self.nmax + 1, self.mmax - m] = lst[2 * m - 1] sc_array[m:self.nmax + 1, self.mmax + m] = lst[2 * m] return sc_array
[ "def", "_array_2d_repr", "(", "self", ")", ":", "sc_array", "=", "np", ".", "zeros", "(", "(", "self", ".", "nmax", "+", "1", ",", "2", "*", "self", ".", "mmax", "+", "1", ")", ",", "dtype", "=", "np", ".", "complex128", ")", "lst", "=", "self"...
creates a 2D array that has nmax + 1 rows and 2*mmax + 1 columns and provides a representation for the coefficients that makes plotting easier
[ "creates", "a", "2D", "array", "that", "has", "nmax", "+", "1", "rows", "and", "2", "*", "mmax", "+", "1", "columns", "and", "provides", "a", "representation", "for", "the", "coefficients", "that", "makes", "plotting", "easier" ]
train
https://github.com/rdireen/spherepy/blob/241521401d4d76851d4a1a564a365cfab8e98496/spherepy/spherepy.py#L314-L328
rdireen/spherepy
spherepy/spherepy.py
ScalarCoefs._reshape_n_vecs
def _reshape_n_vecs(self): """return list of arrays, each array represents a different m mode""" lst = [] sl = slice(None, None, None) lst.append(self.__getitem__((sl, 0))) for m in xrange(1, self.mmax + 1): lst.append(self.__getitem__((sl, -m))) lst.append(self.__getitem__((sl, m))) return lst
python
def _reshape_n_vecs(self): """return list of arrays, each array represents a different m mode""" lst = [] sl = slice(None, None, None) lst.append(self.__getitem__((sl, 0))) for m in xrange(1, self.mmax + 1): lst.append(self.__getitem__((sl, -m))) lst.append(self.__getitem__((sl, m))) return lst
[ "def", "_reshape_n_vecs", "(", "self", ")", ":", "lst", "=", "[", "]", "sl", "=", "slice", "(", "None", ",", "None", ",", "None", ")", "lst", ".", "append", "(", "self", ".", "__getitem__", "(", "(", "sl", ",", "0", ")", ")", ")", "for", "m", ...
return list of arrays, each array represents a different m mode
[ "return", "list", "of", "arrays", "each", "array", "represents", "a", "different", "m", "mode" ]
train
https://github.com/rdireen/spherepy/blob/241521401d4d76851d4a1a564a365cfab8e98496/spherepy/spherepy.py#L330-L339
rdireen/spherepy
spherepy/spherepy.py
ScalarCoefs._reshape_m_vecs
def _reshape_m_vecs(self): """return list of arrays, each array represents a different n mode""" lst = [] for n in xrange(0, self.nmax + 1): mlst = [] if n <= self.mmax: nn = n else: nn = self.mmax for m in xrange(-nn, nn + 1): mlst.append(self.__getitem__((n, m))) lst.append(mlst) return lst
python
def _reshape_m_vecs(self): """return list of arrays, each array represents a different n mode""" lst = [] for n in xrange(0, self.nmax + 1): mlst = [] if n <= self.mmax: nn = n else: nn = self.mmax for m in xrange(-nn, nn + 1): mlst.append(self.__getitem__((n, m))) lst.append(mlst) return lst
[ "def", "_reshape_m_vecs", "(", "self", ")", ":", "lst", "=", "[", "]", "for", "n", "in", "xrange", "(", "0", ",", "self", ".", "nmax", "+", "1", ")", ":", "mlst", "=", "[", "]", "if", "n", "<=", "self", ".", "mmax", ":", "nn", "=", "n", "el...
return list of arrays, each array represents a different n mode
[ "return", "list", "of", "arrays", "each", "array", "represents", "a", "different", "n", "mode" ]
train
https://github.com/rdireen/spherepy/blob/241521401d4d76851d4a1a564a365cfab8e98496/spherepy/spherepy.py#L341-L354
rdireen/spherepy
spherepy/spherepy.py
ScalarCoefs._scalar_coef_op_left
def _scalar_coef_op_left(func): """decorator for operator overloading when ScalarCoef is on the left""" @wraps(func) def verif(self, scoef): if isinstance(scoef, ScalarCoefs): if len(self._vec) == len(scoef._vec): return ScalarCoefs(func(self, self._vec, scoef._vec), self.nmax, self.mmax) else: raise ValueError(err_msg['SC_sz_msmtch'] % \ (self.nmax, self.mmax, scoef.nmax, scoef.mmax)) elif isinstance(scoef, numbers.Number): return ScalarCoefs(func(self, self._vec, scoef), self.nmax, self.mmax) else: raise TypeError(err_msg['no_combi_SC']) return verif
python
def _scalar_coef_op_left(func): """decorator for operator overloading when ScalarCoef is on the left""" @wraps(func) def verif(self, scoef): if isinstance(scoef, ScalarCoefs): if len(self._vec) == len(scoef._vec): return ScalarCoefs(func(self, self._vec, scoef._vec), self.nmax, self.mmax) else: raise ValueError(err_msg['SC_sz_msmtch'] % \ (self.nmax, self.mmax, scoef.nmax, scoef.mmax)) elif isinstance(scoef, numbers.Number): return ScalarCoefs(func(self, self._vec, scoef), self.nmax, self.mmax) else: raise TypeError(err_msg['no_combi_SC']) return verif
[ "def", "_scalar_coef_op_left", "(", "func", ")", ":", "@", "wraps", "(", "func", ")", "def", "verif", "(", "self", ",", "scoef", ")", ":", "if", "isinstance", "(", "scoef", ",", "ScalarCoefs", ")", ":", "if", "len", "(", "self", ".", "_vec", ")", "...
decorator for operator overloading when ScalarCoef is on the left
[ "decorator", "for", "operator", "overloading", "when", "ScalarCoef", "is", "on", "the", "left" ]
train
https://github.com/rdireen/spherepy/blob/241521401d4d76851d4a1a564a365cfab8e98496/spherepy/spherepy.py#L542-L562
rdireen/spherepy
spherepy/spherepy.py
ScalarCoefs._scalar_coef_op_right
def _scalar_coef_op_right(func): """decorator for operator overloading when ScalarCoef is on the right""" @wraps(func) def verif(self, scoef): if isinstance(scoef, numbers.Number): return ScalarCoefs(func(self, self._vec, scoef), self.nmax, self.mmax) else: raise TypeError(err_msg['no_combi_SC']) return verif
python
def _scalar_coef_op_right(func): """decorator for operator overloading when ScalarCoef is on the right""" @wraps(func) def verif(self, scoef): if isinstance(scoef, numbers.Number): return ScalarCoefs(func(self, self._vec, scoef), self.nmax, self.mmax) else: raise TypeError(err_msg['no_combi_SC']) return verif
[ "def", "_scalar_coef_op_right", "(", "func", ")", ":", "@", "wraps", "(", "func", ")", "def", "verif", "(", "self", ",", "scoef", ")", ":", "if", "isinstance", "(", "scoef", ",", "numbers", ".", "Number", ")", ":", "return", "ScalarCoefs", "(", "func",...
decorator for operator overloading when ScalarCoef is on the right
[ "decorator", "for", "operator", "overloading", "when", "ScalarCoef", "is", "on", "the", "right" ]
train
https://github.com/rdireen/spherepy/blob/241521401d4d76851d4a1a564a365cfab8e98496/spherepy/spherepy.py#L564-L574
rdireen/spherepy
spherepy/spherepy.py
VectorCoefs.copy
def copy(self): """Make a deep copy of this object. Example:: >>> c2 = c.copy() """ vec1 = np.copy(self.scoef1._vec) vec2 = np.copy(self.scoef2._vec) return VectorCoefs(vec1, vec2, self.nmax, self.mmax)
python
def copy(self): """Make a deep copy of this object. Example:: >>> c2 = c.copy() """ vec1 = np.copy(self.scoef1._vec) vec2 = np.copy(self.scoef2._vec) return VectorCoefs(vec1, vec2, self.nmax, self.mmax)
[ "def", "copy", "(", "self", ")", ":", "vec1", "=", "np", ".", "copy", "(", "self", ".", "scoef1", ".", "_vec", ")", "vec2", "=", "np", ".", "copy", "(", "self", ".", "scoef2", ".", "_vec", ")", "return", "VectorCoefs", "(", "vec1", ",", "vec2", ...
Make a deep copy of this object. Example:: >>> c2 = c.copy()
[ "Make", "a", "deep", "copy", "of", "this", "object", ".", "Example", "::", ">>>", "c2", "=", "c", ".", "copy", "()" ]
train
https://github.com/rdireen/spherepy/blob/241521401d4d76851d4a1a564a365cfab8e98496/spherepy/spherepy.py#L681-L691
rdireen/spherepy
spherepy/spherepy.py
VectorCoefs._vector_coef_op_left
def _vector_coef_op_left(func): """decorator for operator overloading when VectorCoef is on the left""" @wraps(func) def verif(self, vcoef): if isinstance(vcoef, VectorCoefs): if len(vcoef.scoef1._vec) == len(vcoef.scoef1._vec): return VectorCoefs(func(self, self.scoef1._vec, vcoef.scoef1._vec), func(self, self.scoef2._vec, vcoef.scoef2._vec), self.nmax, self.mmax) else: raise ValueError(err_msg['VC_sz_msmtch'] % \ (self.nmax, self.mmax, vcoef.nmax, vcoef.mmax)) elif isinstance(vcoef, numbers.Number): return VectorCoefs(func(self, self.scoef1._vec, vcoef), func(self, self.scoef2._vec, vcoef), self.nmax, self.mmax) else: raise TypeError(err_msg['no_combi_VC']) return verif
python
def _vector_coef_op_left(func): """decorator for operator overloading when VectorCoef is on the left""" @wraps(func) def verif(self, vcoef): if isinstance(vcoef, VectorCoefs): if len(vcoef.scoef1._vec) == len(vcoef.scoef1._vec): return VectorCoefs(func(self, self.scoef1._vec, vcoef.scoef1._vec), func(self, self.scoef2._vec, vcoef.scoef2._vec), self.nmax, self.mmax) else: raise ValueError(err_msg['VC_sz_msmtch'] % \ (self.nmax, self.mmax, vcoef.nmax, vcoef.mmax)) elif isinstance(vcoef, numbers.Number): return VectorCoefs(func(self, self.scoef1._vec, vcoef), func(self, self.scoef2._vec, vcoef), self.nmax, self.mmax) else: raise TypeError(err_msg['no_combi_VC']) return verif
[ "def", "_vector_coef_op_left", "(", "func", ")", ":", "@", "wraps", "(", "func", ")", "def", "verif", "(", "self", ",", "vcoef", ")", ":", "if", "isinstance", "(", "vcoef", ",", "VectorCoefs", ")", ":", "if", "len", "(", "vcoef", ".", "scoef1", ".", ...
decorator for operator overloading when VectorCoef is on the left
[ "decorator", "for", "operator", "overloading", "when", "VectorCoef", "is", "on", "the", "left" ]
train
https://github.com/rdireen/spherepy/blob/241521401d4d76851d4a1a564a365cfab8e98496/spherepy/spherepy.py#L816-L841
rdireen/spherepy
spherepy/spherepy.py
VectorCoefs._vector_coef_op_right
def _vector_coef_op_right(func): """decorator for operator overloading when VectorCoefs is on the right""" @wraps(func) def verif(self, vcoef): if isinstance(vcoef, numbers.Number): return VectorCoefs(func(self, self.scoef1._vec, vcoef), func(self, self.scoef2._vec, vcoef), self.nmax, self.mmax) else: raise TypeError(err_msg['no_combi_VC']) return verif
python
def _vector_coef_op_right(func): """decorator for operator overloading when VectorCoefs is on the right""" @wraps(func) def verif(self, vcoef): if isinstance(vcoef, numbers.Number): return VectorCoefs(func(self, self.scoef1._vec, vcoef), func(self, self.scoef2._vec, vcoef), self.nmax, self.mmax) else: raise TypeError(err_msg['no_combi_VC']) return verif
[ "def", "_vector_coef_op_right", "(", "func", ")", ":", "@", "wraps", "(", "func", ")", "def", "verif", "(", "self", ",", "vcoef", ")", ":", "if", "isinstance", "(", "vcoef", ",", "numbers", ".", "Number", ")", ":", "return", "VectorCoefs", "(", "func",...
decorator for operator overloading when VectorCoefs is on the right
[ "decorator", "for", "operator", "overloading", "when", "VectorCoefs", "is", "on", "the", "right" ]
train
https://github.com/rdireen/spherepy/blob/241521401d4d76851d4a1a564a365cfab8e98496/spherepy/spherepy.py#L843-L854
rdireen/spherepy
spherepy/spherepy.py
ScalarPatternUniform._scalar_pattern_uniform_op_left
def _scalar_pattern_uniform_op_left(func): """Decorator for operator overloading when ScalarPatternUniform is on the left.""" @wraps(func) def verif(self, patt): if isinstance(patt, ScalarPatternUniform): if self._dsphere.shape == patt._dsphere.shape: return ScalarPatternUniform(func(self, self._dsphere, patt._dsphere), doublesphere=True) else: raise ValueError(err_msg['SP_sz_msmtch'] % \ (self.nrows, self.ncols, patt.nrows, patt.ncols)) elif isinstance(patt, numbers.Number): return ScalarPatternUniform(func(self, self._dsphere, patt), doublesphere=True) else: raise TypeError(err_msg['no_combi_SP']) return verif
python
def _scalar_pattern_uniform_op_left(func): """Decorator for operator overloading when ScalarPatternUniform is on the left.""" @wraps(func) def verif(self, patt): if isinstance(patt, ScalarPatternUniform): if self._dsphere.shape == patt._dsphere.shape: return ScalarPatternUniform(func(self, self._dsphere, patt._dsphere), doublesphere=True) else: raise ValueError(err_msg['SP_sz_msmtch'] % \ (self.nrows, self.ncols, patt.nrows, patt.ncols)) elif isinstance(patt, numbers.Number): return ScalarPatternUniform(func(self, self._dsphere, patt), doublesphere=True) else: raise TypeError(err_msg['no_combi_SP']) return verif
[ "def", "_scalar_pattern_uniform_op_left", "(", "func", ")", ":", "@", "wraps", "(", "func", ")", "def", "verif", "(", "self", ",", "patt", ")", ":", "if", "isinstance", "(", "patt", ",", "ScalarPatternUniform", ")", ":", "if", "self", ".", "_dsphere", "....
Decorator for operator overloading when ScalarPatternUniform is on the left.
[ "Decorator", "for", "operator", "overloading", "when", "ScalarPatternUniform", "is", "on", "the", "left", "." ]
train
https://github.com/rdireen/spherepy/blob/241521401d4d76851d4a1a564a365cfab8e98496/spherepy/spherepy.py#L1073-L1093
rdireen/spherepy
spherepy/spherepy.py
ScalarPatternUniform._scalar_pattern_uniform_op_right
def _scalar_pattern_uniform_op_right(func): """Decorator for operator overloading when ScalarPatternUniform is on the right.""" @wraps(func) def verif(self, patt): if isinstance(patt, numbers.Number): return ScalarPatternUniform(func(self, self._dsphere, patt), doublesphere=True) else: raise TypeError(err_msg['no_combi_SP']) return verif
python
def _scalar_pattern_uniform_op_right(func): """Decorator for operator overloading when ScalarPatternUniform is on the right.""" @wraps(func) def verif(self, patt): if isinstance(patt, numbers.Number): return ScalarPatternUniform(func(self, self._dsphere, patt), doublesphere=True) else: raise TypeError(err_msg['no_combi_SP']) return verif
[ "def", "_scalar_pattern_uniform_op_right", "(", "func", ")", ":", "@", "wraps", "(", "func", ")", "def", "verif", "(", "self", ",", "patt", ")", ":", "if", "isinstance", "(", "patt", ",", "numbers", ".", "Number", ")", ":", "return", "ScalarPatternUniform"...
Decorator for operator overloading when ScalarPatternUniform is on the right.
[ "Decorator", "for", "operator", "overloading", "when", "ScalarPatternUniform", "is", "on", "the", "right", "." ]
train
https://github.com/rdireen/spherepy/blob/241521401d4d76851d4a1a564a365cfab8e98496/spherepy/spherepy.py#L1095-L1105
rdireen/spherepy
spherepy/spherepy.py
TransversePatternUniform.single_val
def single_val(self): """return relative error of worst point that might make the data none symmetric. """ sv_t = self._sv(self._tdsphere) sv_p = self._sv(self._tdsphere) return (sv_t, sv_p)
python
def single_val(self): """return relative error of worst point that might make the data none symmetric. """ sv_t = self._sv(self._tdsphere) sv_p = self._sv(self._tdsphere) return (sv_t, sv_p)
[ "def", "single_val", "(", "self", ")", ":", "sv_t", "=", "self", ".", "_sv", "(", "self", ".", "_tdsphere", ")", "sv_p", "=", "self", ".", "_sv", "(", "self", ".", "_tdsphere", ")", "return", "(", "sv_t", ",", "sv_p", ")" ]
return relative error of worst point that might make the data none symmetric.
[ "return", "relative", "error", "of", "worst", "point", "that", "might", "make", "the", "data", "none", "symmetric", "." ]
train
https://github.com/rdireen/spherepy/blob/241521401d4d76851d4a1a564a365cfab8e98496/spherepy/spherepy.py#L1235-L1243
rdireen/spherepy
spherepy/spherepy.py
TransversePatternUniform._vector_pattern_uniform_op_left
def _vector_pattern_uniform_op_left(func): """decorator for operator overloading when VectorPatternUniform is on the left""" @wraps(func) def verif(self, patt): if isinstance(patt, TransversePatternUniform): if self._tdsphere.shape == patt._tdsphere.shape: return TransversePatternUniform(func(self, self._tdsphere, patt._tdsphere), func(self, self._pdsphere, patt._pdsphere), doublesphere=True) else: raise ValueError(err_msg['VP_sz_msmtch'] % \ (self.nrows, self.ncols, patt.nrows, patt.ncols)) elif isinstance(patt, numbers.Number): return TransversePatternUniform(func(self, self._tdsphere, patt), func(self, self._pdsphere, patt), doublesphere=True) else: raise TypeError(err_msg['no_combi_VP']) return verif
python
def _vector_pattern_uniform_op_left(func): """decorator for operator overloading when VectorPatternUniform is on the left""" @wraps(func) def verif(self, patt): if isinstance(patt, TransversePatternUniform): if self._tdsphere.shape == patt._tdsphere.shape: return TransversePatternUniform(func(self, self._tdsphere, patt._tdsphere), func(self, self._pdsphere, patt._pdsphere), doublesphere=True) else: raise ValueError(err_msg['VP_sz_msmtch'] % \ (self.nrows, self.ncols, patt.nrows, patt.ncols)) elif isinstance(patt, numbers.Number): return TransversePatternUniform(func(self, self._tdsphere, patt), func(self, self._pdsphere, patt), doublesphere=True) else: raise TypeError(err_msg['no_combi_VP']) return verif
[ "def", "_vector_pattern_uniform_op_left", "(", "func", ")", ":", "@", "wraps", "(", "func", ")", "def", "verif", "(", "self", ",", "patt", ")", ":", "if", "isinstance", "(", "patt", ",", "TransversePatternUniform", ")", ":", "if", "self", ".", "_tdsphere",...
decorator for operator overloading when VectorPatternUniform is on the left
[ "decorator", "for", "operator", "overloading", "when", "VectorPatternUniform", "is", "on", "the", "left" ]
train
https://github.com/rdireen/spherepy/blob/241521401d4d76851d4a1a564a365cfab8e98496/spherepy/spherepy.py#L1269-L1292
rdireen/spherepy
spherepy/spherepy.py
TransversePatternUniform._vector_pattern_uniform_op_right
def _vector_pattern_uniform_op_right(func): """decorator for operator overloading when VectorPatternUniform is on the right""" @wraps(func) def verif(self, patt): if isinstance(patt, numbers.Number): return TransversePatternUniform(func(self, self._tdsphere, patt), func(self, self._pdsphere, patt), doublesphere=True) else: raise TypeError(err_msg['no_combi_VP']) return verif
python
def _vector_pattern_uniform_op_right(func): """decorator for operator overloading when VectorPatternUniform is on the right""" @wraps(func) def verif(self, patt): if isinstance(patt, numbers.Number): return TransversePatternUniform(func(self, self._tdsphere, patt), func(self, self._pdsphere, patt), doublesphere=True) else: raise TypeError(err_msg['no_combi_VP']) return verif
[ "def", "_vector_pattern_uniform_op_right", "(", "func", ")", ":", "@", "wraps", "(", "func", ")", "def", "verif", "(", "self", ",", "patt", ")", ":", "if", "isinstance", "(", "patt", ",", "numbers", ".", "Number", ")", ":", "return", "TransversePatternUnif...
decorator for operator overloading when VectorPatternUniform is on the right
[ "decorator", "for", "operator", "overloading", "when", "VectorPatternUniform", "is", "on", "the", "right" ]
train
https://github.com/rdireen/spherepy/blob/241521401d4d76851d4a1a564a365cfab8e98496/spherepy/spherepy.py#L1294-L1305
Kane610/aiounifi
aiounifi/devices.py
Device.async_set_port_poe_mode
async def async_set_port_poe_mode(self, port_idx, mode): """Set port poe mode. Auto, 24v, passthrough, off. Make sure to not overwrite any existing configs. """ no_existing_config = True for port_override in self.port_overrides: if port_idx == port_override['port_idx']: port_override['poe_mode'] = mode no_existing_config = False break if no_existing_config: self.port_overrides.append({ 'port_idx': port_idx, 'portconf_id': self.ports[port_idx].portconf_id, 'poe_mode': mode }) url = 's/{site}/rest/device/' + self.id data = {'port_overrides': self.port_overrides} await self._request('put', url, json=data)
python
async def async_set_port_poe_mode(self, port_idx, mode): """Set port poe mode. Auto, 24v, passthrough, off. Make sure to not overwrite any existing configs. """ no_existing_config = True for port_override in self.port_overrides: if port_idx == port_override['port_idx']: port_override['poe_mode'] = mode no_existing_config = False break if no_existing_config: self.port_overrides.append({ 'port_idx': port_idx, 'portconf_id': self.ports[port_idx].portconf_id, 'poe_mode': mode }) url = 's/{site}/rest/device/' + self.id data = {'port_overrides': self.port_overrides} await self._request('put', url, json=data)
[ "async", "def", "async_set_port_poe_mode", "(", "self", ",", "port_idx", ",", "mode", ")", ":", "no_existing_config", "=", "True", "for", "port_override", "in", "self", ".", "port_overrides", ":", "if", "port_idx", "==", "port_override", "[", "'port_idx'", "]", ...
Set port poe mode. Auto, 24v, passthrough, off. Make sure to not overwrite any existing configs.
[ "Set", "port", "poe", "mode", "." ]
train
https://github.com/Kane610/aiounifi/blob/a1a871dc4c9158b48e2647b6c29f7c88965da389/aiounifi/devices.py#L62-L85
ChristopherRogers1991/python-irsend
py_irsend/irsend.py
list_remotes
def list_remotes(device=None, address=None): """ List the available remotes. All parameters are passed to irsend. See the man page for irsend for details about their usage. Parameters ---------- device: str address: str Returns ------- [str] Notes ----- No attempt is made to catch or handle errors. See the documentation for subprocess.check_output to see the types of exceptions it may raise. """ output = _call(["list", "", ""], None, device, address) remotes = [l.split()[-1] for l in output.splitlines() if l] return remotes
python
def list_remotes(device=None, address=None): """ List the available remotes. All parameters are passed to irsend. See the man page for irsend for details about their usage. Parameters ---------- device: str address: str Returns ------- [str] Notes ----- No attempt is made to catch or handle errors. See the documentation for subprocess.check_output to see the types of exceptions it may raise. """ output = _call(["list", "", ""], None, device, address) remotes = [l.split()[-1] for l in output.splitlines() if l] return remotes
[ "def", "list_remotes", "(", "device", "=", "None", ",", "address", "=", "None", ")", ":", "output", "=", "_call", "(", "[", "\"list\"", ",", "\"\"", ",", "\"\"", "]", ",", "None", ",", "device", ",", "address", ")", "remotes", "=", "[", "l", ".", ...
List the available remotes. All parameters are passed to irsend. See the man page for irsend for details about their usage. Parameters ---------- device: str address: str Returns ------- [str] Notes ----- No attempt is made to catch or handle errors. See the documentation for subprocess.check_output to see the types of exceptions it may raise.
[ "List", "the", "available", "remotes", "." ]
train
https://github.com/ChristopherRogers1991/python-irsend/blob/aab8ee05d47cc0e3c8c84d220bc6777aa720b232/py_irsend/irsend.py#L26-L50
ChristopherRogers1991/python-irsend
py_irsend/irsend.py
list_codes
def list_codes(remote, device=None, address=None): """ List the codes for a given remote. All parameters are passed to irsend. See the man page for irsend for details about their usage. Parameters ---------- remote: str device: str address: str Returns ------- [str] Notes ----- No attempt is made to catch or handle errors. See the documentation for subprocess.check_output to see the types of exceptions it may raise. """ output = _call(["list", remote, ""], None, device, address) codes = [l.split()[-1] for l in output.splitlines() if l] return codes
python
def list_codes(remote, device=None, address=None): """ List the codes for a given remote. All parameters are passed to irsend. See the man page for irsend for details about their usage. Parameters ---------- remote: str device: str address: str Returns ------- [str] Notes ----- No attempt is made to catch or handle errors. See the documentation for subprocess.check_output to see the types of exceptions it may raise. """ output = _call(["list", remote, ""], None, device, address) codes = [l.split()[-1] for l in output.splitlines() if l] return codes
[ "def", "list_codes", "(", "remote", ",", "device", "=", "None", ",", "address", "=", "None", ")", ":", "output", "=", "_call", "(", "[", "\"list\"", ",", "remote", ",", "\"\"", "]", ",", "None", ",", "device", ",", "address", ")", "codes", "=", "["...
List the codes for a given remote. All parameters are passed to irsend. See the man page for irsend for details about their usage. Parameters ---------- remote: str device: str address: str Returns ------- [str] Notes ----- No attempt is made to catch or handle errors. See the documentation for subprocess.check_output to see the types of exceptions it may raise.
[ "List", "the", "codes", "for", "a", "given", "remote", "." ]
train
https://github.com/ChristopherRogers1991/python-irsend/blob/aab8ee05d47cc0e3c8c84d220bc6777aa720b232/py_irsend/irsend.py#L53-L78
ChristopherRogers1991/python-irsend
py_irsend/irsend.py
send_once
def send_once(remote, codes, count=None, device=None, address=None): """ All parameters are passed to irsend. See the man page for irsend for details about their usage. Parameters ---------- remote: str codes: [str] count: int device: str address: str Notes ----- No attempt is made to catch or handle errors. See the documentation for subprocess.check_output to see the types of exceptions it may raise. """ args = ['send_once', remote] + codes _call(args, count, device, address)
python
def send_once(remote, codes, count=None, device=None, address=None): """ All parameters are passed to irsend. See the man page for irsend for details about their usage. Parameters ---------- remote: str codes: [str] count: int device: str address: str Notes ----- No attempt is made to catch or handle errors. See the documentation for subprocess.check_output to see the types of exceptions it may raise. """ args = ['send_once', remote] + codes _call(args, count, device, address)
[ "def", "send_once", "(", "remote", ",", "codes", ",", "count", "=", "None", ",", "device", "=", "None", ",", "address", "=", "None", ")", ":", "args", "=", "[", "'send_once'", ",", "remote", "]", "+", "codes", "_call", "(", "args", ",", "count", ",...
All parameters are passed to irsend. See the man page for irsend for details about their usage. Parameters ---------- remote: str codes: [str] count: int device: str address: str Notes ----- No attempt is made to catch or handle errors. See the documentation for subprocess.check_output to see the types of exceptions it may raise.
[ "All", "parameters", "are", "passed", "to", "irsend", ".", "See", "the", "man", "page", "for", "irsend", "for", "details", "about", "their", "usage", "." ]
train
https://github.com/ChristopherRogers1991/python-irsend/blob/aab8ee05d47cc0e3c8c84d220bc6777aa720b232/py_irsend/irsend.py#L92-L112
ChristopherRogers1991/python-irsend
py_irsend/irsend.py
send_start
def send_start(remote, code, device=None, address=None): """ All parameters are passed to irsend. See the man page for irsend for details about their usage. Parameters ---------- remote: str code: str device: str address: str Notes ----- No attempt is made to catch or handle errors. See the documentation for subprocess.check_output to see the types of exceptions it may raise. """ args = ['send_start', remote, code] _call(args, device, address)
python
def send_start(remote, code, device=None, address=None): """ All parameters are passed to irsend. See the man page for irsend for details about their usage. Parameters ---------- remote: str code: str device: str address: str Notes ----- No attempt is made to catch or handle errors. See the documentation for subprocess.check_output to see the types of exceptions it may raise. """ args = ['send_start', remote, code] _call(args, device, address)
[ "def", "send_start", "(", "remote", ",", "code", ",", "device", "=", "None", ",", "address", "=", "None", ")", ":", "args", "=", "[", "'send_start'", ",", "remote", ",", "code", "]", "_call", "(", "args", ",", "device", ",", "address", ")" ]
All parameters are passed to irsend. See the man page for irsend for details about their usage. Parameters ---------- remote: str code: str device: str address: str Notes ----- No attempt is made to catch or handle errors. See the documentation for subprocess.check_output to see the types of exceptions it may raise.
[ "All", "parameters", "are", "passed", "to", "irsend", ".", "See", "the", "man", "page", "for", "irsend", "for", "details", "about", "their", "usage", "." ]
train
https://github.com/ChristopherRogers1991/python-irsend/blob/aab8ee05d47cc0e3c8c84d220bc6777aa720b232/py_irsend/irsend.py#L115-L134
ChristopherRogers1991/python-irsend
py_irsend/irsend.py
send_stop
def send_stop(remote, code, device=None, address=None): """ All parameters are passed to irsend. See the man page for irsend for details about their usage. Parameters ---------- remote: str code: str device: str address: str Notes ----- No attempt is made to catch or handle errors. See the documentation for subprocess.check_output to see the types of exceptions it may raise. """ args = ['send_stop', remote, code] _call(args, None, device, address)
python
def send_stop(remote, code, device=None, address=None): """ All parameters are passed to irsend. See the man page for irsend for details about their usage. Parameters ---------- remote: str code: str device: str address: str Notes ----- No attempt is made to catch or handle errors. See the documentation for subprocess.check_output to see the types of exceptions it may raise. """ args = ['send_stop', remote, code] _call(args, None, device, address)
[ "def", "send_stop", "(", "remote", ",", "code", ",", "device", "=", "None", ",", "address", "=", "None", ")", ":", "args", "=", "[", "'send_stop'", ",", "remote", ",", "code", "]", "_call", "(", "args", ",", "None", ",", "device", ",", "address", "...
All parameters are passed to irsend. See the man page for irsend for details about their usage. Parameters ---------- remote: str code: str device: str address: str Notes ----- No attempt is made to catch or handle errors. See the documentation for subprocess.check_output to see the types of exceptions it may raise.
[ "All", "parameters", "are", "passed", "to", "irsend", ".", "See", "the", "man", "page", "for", "irsend", "for", "details", "about", "their", "usage", "." ]
train
https://github.com/ChristopherRogers1991/python-irsend/blob/aab8ee05d47cc0e3c8c84d220bc6777aa720b232/py_irsend/irsend.py#L137-L156
ChristopherRogers1991/python-irsend
py_irsend/irsend.py
set_transmitters
def set_transmitters(transmitters, device=None, address=None): """ All parameters are passed to irsend. See the man page for irsend for details about their usage. Parameters ---------- transmitters: iterable yielding ints device: str address: str Notes ----- No attempt is made to catch or handle errors. See the documentation for subprocess.check_output to see the types of exceptions it may raise. """ args = ['set_transmitters'] + [str(i) for i in transmitters] _call(args, None, device, address)
python
def set_transmitters(transmitters, device=None, address=None): """ All parameters are passed to irsend. See the man page for irsend for details about their usage. Parameters ---------- transmitters: iterable yielding ints device: str address: str Notes ----- No attempt is made to catch or handle errors. See the documentation for subprocess.check_output to see the types of exceptions it may raise. """ args = ['set_transmitters'] + [str(i) for i in transmitters] _call(args, None, device, address)
[ "def", "set_transmitters", "(", "transmitters", ",", "device", "=", "None", ",", "address", "=", "None", ")", ":", "args", "=", "[", "'set_transmitters'", "]", "+", "[", "str", "(", "i", ")", "for", "i", "in", "transmitters", "]", "_call", "(", "args",...
All parameters are passed to irsend. See the man page for irsend for details about their usage. Parameters ---------- transmitters: iterable yielding ints device: str address: str Notes ----- No attempt is made to catch or handle errors. See the documentation for subprocess.check_output to see the types of exceptions it may raise.
[ "All", "parameters", "are", "passed", "to", "irsend", ".", "See", "the", "man", "page", "for", "irsend", "for", "details", "about", "their", "usage", "." ]
train
https://github.com/ChristopherRogers1991/python-irsend/blob/aab8ee05d47cc0e3c8c84d220bc6777aa720b232/py_irsend/irsend.py#L159-L177
dslackw/sun
sun/cli/tool.py
check_updates
def check_updates(): """Check and display upgraded packages """ count, packages = fetch() message = "No news is good news !" if count > 0: message = ("{0} software updates are available\n".format(count)) return [message, count, packages]
python
def check_updates(): """Check and display upgraded packages """ count, packages = fetch() message = "No news is good news !" if count > 0: message = ("{0} software updates are available\n".format(count)) return [message, count, packages]
[ "def", "check_updates", "(", ")", ":", "count", ",", "packages", "=", "fetch", "(", ")", "message", "=", "\"No news is good news !\"", "if", "count", ">", "0", ":", "message", "=", "(", "\"{0} software updates are available\\n\"", ".", "format", "(", "count", ...
Check and display upgraded packages
[ "Check", "and", "display", "upgraded", "packages" ]
train
https://github.com/dslackw/sun/blob/ff3501757ce1cc2f0db195f7a6b1d23f601dce32/sun/cli/tool.py#L66-L73
dslackw/sun
sun/cli/tool.py
_init_check_upodates
def _init_check_upodates(): """Sub function for init """ message, count, packages = check_updates() if count > 0: print(message) for pkg in packages: print("{0}".format(pkg)) else: print(message)
python
def _init_check_upodates(): """Sub function for init """ message, count, packages = check_updates() if count > 0: print(message) for pkg in packages: print("{0}".format(pkg)) else: print(message)
[ "def", "_init_check_upodates", "(", ")", ":", "message", ",", "count", ",", "packages", "=", "check_updates", "(", ")", "if", "count", ">", "0", ":", "print", "(", "message", ")", "for", "pkg", "in", "packages", ":", "print", "(", "\"{0}\"", ".", "form...
Sub function for init
[ "Sub", "function", "for", "init" ]
train
https://github.com/dslackw/sun/blob/ff3501757ce1cc2f0db195f7a6b1d23f601dce32/sun/cli/tool.py#L86-L95
dslackw/sun
sun/cli/tool.py
init
def init(): """Initialization , all begin from here """ su() args = sys.argv args.pop(0) cmd = "{0}sun_daemon".format(bin_path) if len(args) == 1: if args[0] == "start": print("Starting SUN daemon: {0} &".format(cmd)) subprocess.call("{0} &".format(cmd), shell=True) elif args[0] == "stop": print("Stopping SUN daemon: {0}".format(cmd)) subprocess.call("killall sun_daemon", shell=True) elif args[0] == "restart": print("Stopping SUN daemon: {0}".format(cmd)) subprocess.call("killall sun_daemon", shell=True) print("Starting SUN daemon: {0} &".format(cmd)) subprocess.call("{0} &".format(cmd), shell=True) elif args[0] == "check": _init_check_upodates() elif args[0] == "status": print(daemon_status()) elif args[0] == "help": usage() elif args[0] == "info": print(os_info()) else: print("try: 'sun help'") elif len(args) == 2 and args[0] == "start" and args[1] == "--gtk": subprocess.call("{0} {1}".format(cmd, "start--gtk"), shell=True) else: print("try: 'sun help'")
python
def init(): """Initialization , all begin from here """ su() args = sys.argv args.pop(0) cmd = "{0}sun_daemon".format(bin_path) if len(args) == 1: if args[0] == "start": print("Starting SUN daemon: {0} &".format(cmd)) subprocess.call("{0} &".format(cmd), shell=True) elif args[0] == "stop": print("Stopping SUN daemon: {0}".format(cmd)) subprocess.call("killall sun_daemon", shell=True) elif args[0] == "restart": print("Stopping SUN daemon: {0}".format(cmd)) subprocess.call("killall sun_daemon", shell=True) print("Starting SUN daemon: {0} &".format(cmd)) subprocess.call("{0} &".format(cmd), shell=True) elif args[0] == "check": _init_check_upodates() elif args[0] == "status": print(daemon_status()) elif args[0] == "help": usage() elif args[0] == "info": print(os_info()) else: print("try: 'sun help'") elif len(args) == 2 and args[0] == "start" and args[1] == "--gtk": subprocess.call("{0} {1}".format(cmd, "start--gtk"), shell=True) else: print("try: 'sun help'")
[ "def", "init", "(", ")", ":", "su", "(", ")", "args", "=", "sys", ".", "argv", "args", ".", "pop", "(", "0", ")", "cmd", "=", "\"{0}sun_daemon\"", ".", "format", "(", "bin_path", ")", "if", "len", "(", "args", ")", "==", "1", ":", "if", "args",...
Initialization , all begin from here
[ "Initialization", "all", "begin", "from", "here" ]
train
https://github.com/dslackw/sun/blob/ff3501757ce1cc2f0db195f7a6b1d23f601dce32/sun/cli/tool.py#L98-L130
chbrown/pi
pi/commands/cleanup.py
cli
def cli(parser): ''' Uninstall inactive Python packages from all accessible site-packages directories. Inactive Python packages when multiple packages with the same name are installed ''' parser.add_argument('-n', '--dry-run', action='store_true', help='Print cleanup actions without running') opts = parser.parse_args() for sitedir in site.getsitepackages(): cleanup(sitedir, execute=not opts.dry_run, verbose=opts.verbose or opts.dry_run)
python
def cli(parser): ''' Uninstall inactive Python packages from all accessible site-packages directories. Inactive Python packages when multiple packages with the same name are installed ''' parser.add_argument('-n', '--dry-run', action='store_true', help='Print cleanup actions without running') opts = parser.parse_args() for sitedir in site.getsitepackages(): cleanup(sitedir, execute=not opts.dry_run, verbose=opts.verbose or opts.dry_run)
[ "def", "cli", "(", "parser", ")", ":", "parser", ".", "add_argument", "(", "'-n'", ",", "'--dry-run'", ",", "action", "=", "'store_true'", ",", "help", "=", "'Print cleanup actions without running'", ")", "opts", "=", "parser", ".", "parse_args", "(", ")", "...
Uninstall inactive Python packages from all accessible site-packages directories. Inactive Python packages when multiple packages with the same name are installed
[ "Uninstall", "inactive", "Python", "packages", "from", "all", "accessible", "site", "-", "packages", "directories", "." ]
train
https://github.com/chbrown/pi/blob/a3661eccf1c6f0105e34a0ee24328022bf4e6b92/pi/commands/cleanup.py#L21-L32
dslackw/sun
sun/gtk/status_icon.py
GtkStatusIcon.daemon_start
def daemon_start(self): """Start daemon when gtk loaded """ if daemon_status() == "SUN not running": subprocess.call("{0} &".format(self.cmd), shell=True)
python
def daemon_start(self): """Start daemon when gtk loaded """ if daemon_status() == "SUN not running": subprocess.call("{0} &".format(self.cmd), shell=True)
[ "def", "daemon_start", "(", "self", ")", ":", "if", "daemon_status", "(", ")", "==", "\"SUN not running\"", ":", "subprocess", ".", "call", "(", "\"{0} &\"", ".", "format", "(", "self", ".", "cmd", ")", ",", "shell", "=", "True", ")" ]
Start daemon when gtk loaded
[ "Start", "daemon", "when", "gtk", "loaded" ]
train
https://github.com/dslackw/sun/blob/ff3501757ce1cc2f0db195f7a6b1d23f601dce32/sun/gtk/status_icon.py#L65-L69
dslackw/sun
sun/gtk/status_icon.py
GtkStatusIcon.sub_menu
def sub_menu(self): """Create daemon submenu """ submenu = gtk.Menu() self.start = gtk.ImageMenuItem("Start") self.stop = gtk.ImageMenuItem("Stop") self.restart = gtk.ImageMenuItem("Restart") self.status = gtk.ImageMenuItem("Status") self.start.show() self.stop.show() self.restart.show() self.status.show() img_Start = gtk.image_new_from_stock(gtk.STOCK_MEDIA_PLAY, gtk.ICON_SIZE_MENU) img_Start.show() self.start.set_image(img_Start) img_Stop = gtk.image_new_from_stock(gtk.STOCK_STOP, gtk.ICON_SIZE_MENU) img_Stop.show() self.stop.set_image(img_Stop) img_Restart = gtk.image_new_from_stock(gtk.STOCK_REFRESH, gtk.ICON_SIZE_MENU) img_Restart.show() self.restart.set_image(img_Restart) img_Status = gtk.image_new_from_stock(gtk.STOCK_DIALOG_QUESTION, gtk.ICON_SIZE_MENU) img_Status.show() self.status.set_image(img_Status) submenu.append(self.start) submenu.append(self.stop) submenu.append(self.restart) submenu.append(self.status) self.daemon = gtk.ImageMenuItem("Daemon") self.img_daemon = gtk.image_new_from_stock(self.daemon_STOCK, gtk.ICON_SIZE_MENU) self.img_daemon.show() self.daemon.set_submenu(submenu)
python
def sub_menu(self): """Create daemon submenu """ submenu = gtk.Menu() self.start = gtk.ImageMenuItem("Start") self.stop = gtk.ImageMenuItem("Stop") self.restart = gtk.ImageMenuItem("Restart") self.status = gtk.ImageMenuItem("Status") self.start.show() self.stop.show() self.restart.show() self.status.show() img_Start = gtk.image_new_from_stock(gtk.STOCK_MEDIA_PLAY, gtk.ICON_SIZE_MENU) img_Start.show() self.start.set_image(img_Start) img_Stop = gtk.image_new_from_stock(gtk.STOCK_STOP, gtk.ICON_SIZE_MENU) img_Stop.show() self.stop.set_image(img_Stop) img_Restart = gtk.image_new_from_stock(gtk.STOCK_REFRESH, gtk.ICON_SIZE_MENU) img_Restart.show() self.restart.set_image(img_Restart) img_Status = gtk.image_new_from_stock(gtk.STOCK_DIALOG_QUESTION, gtk.ICON_SIZE_MENU) img_Status.show() self.status.set_image(img_Status) submenu.append(self.start) submenu.append(self.stop) submenu.append(self.restart) submenu.append(self.status) self.daemon = gtk.ImageMenuItem("Daemon") self.img_daemon = gtk.image_new_from_stock(self.daemon_STOCK, gtk.ICON_SIZE_MENU) self.img_daemon.show() self.daemon.set_submenu(submenu)
[ "def", "sub_menu", "(", "self", ")", ":", "submenu", "=", "gtk", ".", "Menu", "(", ")", "self", ".", "start", "=", "gtk", ".", "ImageMenuItem", "(", "\"Start\"", ")", "self", ".", "stop", "=", "gtk", ".", "ImageMenuItem", "(", "\"Stop\"", ")", "self"...
Create daemon submenu
[ "Create", "daemon", "submenu" ]
train
https://github.com/dslackw/sun/blob/ff3501757ce1cc2f0db195f7a6b1d23f601dce32/sun/gtk/status_icon.py#L71-L114
dslackw/sun
sun/gtk/status_icon.py
GtkStatusIcon.menu
def menu(self, event_button, event_time, data=None): """Create popup menu """ self.sub_menu() menu = gtk.Menu() menu.append(self.daemon) separator = gtk.SeparatorMenuItem() menu_Check = gtk.ImageMenuItem("Check updates") img_Check = gtk.image_new_from_stock(gtk.STOCK_OK, gtk.ICON_SIZE_MENU) img_Check.show() menu_Info = gtk.ImageMenuItem("OS Info") img_Info = gtk.image_new_from_stock(gtk.STOCK_INFO, gtk.ICON_SIZE_MENU) img_Info.show() menu_About = gtk.ImageMenuItem("About") img_About = gtk.image_new_from_stock(gtk.STOCK_ABOUT, gtk.ICON_SIZE_MENU) img_About.show() self.daemon.set_image(self.img_daemon) menu.append(self.daemon) self.daemon.show() menu_Quit = gtk.ImageMenuItem("Quit") img_Quit = gtk.image_new_from_stock(gtk.STOCK_QUIT, gtk.ICON_SIZE_MENU) img_Quit.show() menu_Check.set_image(img_Check) menu_Info.set_image(img_Info) menu_About.set_image(img_About) menu_Quit.set_image(img_Quit) menu.append(menu_Check) menu.append(menu_Info) menu.append(separator) menu.append(menu_About) menu.append(menu_Quit) separator.show() menu_Check.show() menu_Info.show() menu_About.show() menu_Quit.show() menu_Check.connect_object("activate", self._Check, " ") menu_Info.connect_object("activate", self._Info, "OS Info") menu_About.connect_object("activate", self._About, "SUN") self.start.connect_object("activate", self._start, "Start daemon ") self.stop.connect_object("activate", self._stop, "Stop daemon ") self.restart.connect_object("activate", self._restart, "Restart daemon ") self.status.connect_object("activate", self._status, daemon_status()) menu_Quit.connect_object("activate", self._Quit, "stop") menu.popup(None, None, None, event_button, event_time, data)
python
def menu(self, event_button, event_time, data=None): """Create popup menu """ self.sub_menu() menu = gtk.Menu() menu.append(self.daemon) separator = gtk.SeparatorMenuItem() menu_Check = gtk.ImageMenuItem("Check updates") img_Check = gtk.image_new_from_stock(gtk.STOCK_OK, gtk.ICON_SIZE_MENU) img_Check.show() menu_Info = gtk.ImageMenuItem("OS Info") img_Info = gtk.image_new_from_stock(gtk.STOCK_INFO, gtk.ICON_SIZE_MENU) img_Info.show() menu_About = gtk.ImageMenuItem("About") img_About = gtk.image_new_from_stock(gtk.STOCK_ABOUT, gtk.ICON_SIZE_MENU) img_About.show() self.daemon.set_image(self.img_daemon) menu.append(self.daemon) self.daemon.show() menu_Quit = gtk.ImageMenuItem("Quit") img_Quit = gtk.image_new_from_stock(gtk.STOCK_QUIT, gtk.ICON_SIZE_MENU) img_Quit.show() menu_Check.set_image(img_Check) menu_Info.set_image(img_Info) menu_About.set_image(img_About) menu_Quit.set_image(img_Quit) menu.append(menu_Check) menu.append(menu_Info) menu.append(separator) menu.append(menu_About) menu.append(menu_Quit) separator.show() menu_Check.show() menu_Info.show() menu_About.show() menu_Quit.show() menu_Check.connect_object("activate", self._Check, " ") menu_Info.connect_object("activate", self._Info, "OS Info") menu_About.connect_object("activate", self._About, "SUN") self.start.connect_object("activate", self._start, "Start daemon ") self.stop.connect_object("activate", self._stop, "Stop daemon ") self.restart.connect_object("activate", self._restart, "Restart daemon ") self.status.connect_object("activate", self._status, daemon_status()) menu_Quit.connect_object("activate", self._Quit, "stop") menu.popup(None, None, None, event_button, event_time, data)
[ "def", "menu", "(", "self", ",", "event_button", ",", "event_time", ",", "data", "=", "None", ")", ":", "self", ".", "sub_menu", "(", ")", "menu", "=", "gtk", ".", "Menu", "(", ")", "menu", ".", "append", "(", "self", ".", "daemon", ")", "separator...
Create popup menu
[ "Create", "popup", "menu" ]
train
https://github.com/dslackw/sun/blob/ff3501757ce1cc2f0db195f7a6b1d23f601dce32/sun/gtk/status_icon.py#L116-L175
dslackw/sun
sun/gtk/status_icon.py
GtkStatusIcon.message
def message(self, data): """Function to display messages to the user """ msg = gtk.MessageDialog(None, gtk.DIALOG_MODAL, gtk.MESSAGE_INFO, gtk.BUTTONS_CLOSE, data) msg.set_resizable(1) msg.set_title(self.dialog_title) self.img.set_from_file(self.sun_icon) msg.set_image(self.img) msg.show_all() msg.run() msg.destroy()
python
def message(self, data): """Function to display messages to the user """ msg = gtk.MessageDialog(None, gtk.DIALOG_MODAL, gtk.MESSAGE_INFO, gtk.BUTTONS_CLOSE, data) msg.set_resizable(1) msg.set_title(self.dialog_title) self.img.set_from_file(self.sun_icon) msg.set_image(self.img) msg.show_all() msg.run() msg.destroy()
[ "def", "message", "(", "self", ",", "data", ")", ":", "msg", "=", "gtk", ".", "MessageDialog", "(", "None", ",", "gtk", ".", "DIALOG_MODAL", ",", "gtk", ".", "MESSAGE_INFO", ",", "gtk", ".", "BUTTONS_CLOSE", ",", "data", ")", "msg", ".", "set_resizable...
Function to display messages to the user
[ "Function", "to", "display", "messages", "to", "the", "user" ]
train
https://github.com/dslackw/sun/blob/ff3501757ce1cc2f0db195f7a6b1d23f601dce32/sun/gtk/status_icon.py#L177-L188
dslackw/sun
sun/gtk/status_icon.py
GtkStatusIcon.right_click
def right_click(self, data, event_button, event_time): """Right click handler """ self.menu(event_button, event_time, data)
python
def right_click(self, data, event_button, event_time): """Right click handler """ self.menu(event_button, event_time, data)
[ "def", "right_click", "(", "self", ",", "data", ",", "event_button", ",", "event_time", ")", ":", "self", ".", "menu", "(", "event_button", ",", "event_time", ",", "data", ")" ]
Right click handler
[ "Right", "click", "handler" ]
train
https://github.com/dslackw/sun/blob/ff3501757ce1cc2f0db195f7a6b1d23f601dce32/sun/gtk/status_icon.py#L190-L193
snipsco/snipsmanagercore
snipsmanagercore/intent_parser.py
IntentParser.parse
def parse(payload, candidate_classes): """ Parse a json response into an intent. :param payload: a JSON object representing an intent. :param candidate_classes: a list of classes representing various intents, each having their own `parse` method to attempt parsing the JSON object into the given intent class. :return: An object version of the intent if one of the candidate classes managed to parse it, or None. """ for cls in candidate_classes: intent = cls.parse(payload) if intent: return intent return None
python
def parse(payload, candidate_classes): """ Parse a json response into an intent. :param payload: a JSON object representing an intent. :param candidate_classes: a list of classes representing various intents, each having their own `parse` method to attempt parsing the JSON object into the given intent class. :return: An object version of the intent if one of the candidate classes managed to parse it, or None. """ for cls in candidate_classes: intent = cls.parse(payload) if intent: return intent return None
[ "def", "parse", "(", "payload", ",", "candidate_classes", ")", ":", "for", "cls", "in", "candidate_classes", ":", "intent", "=", "cls", ".", "parse", "(", "payload", ")", "if", "intent", ":", "return", "intent", "return", "None" ]
Parse a json response into an intent. :param payload: a JSON object representing an intent. :param candidate_classes: a list of classes representing various intents, each having their own `parse` method to attempt parsing the JSON object into the given intent class. :return: An object version of the intent if one of the candidate classes managed to parse it, or None.
[ "Parse", "a", "json", "response", "into", "an", "intent", "." ]
train
https://github.com/snipsco/snipsmanagercore/blob/93eaaa665887f790a30ba86af5ffee394bfd8ede/snipsmanagercore/intent_parser.py#L14-L29
snipsco/snipsmanagercore
snipsmanagercore/intent_parser.py
IntentParser.get_slot_value
def get_slot_value(payload, slot_name): """ Return the parsed value of a slot. An intent has the form: { "text": "brew me a cappuccino with 3 sugars tomorrow", "slots": [ {"value": {"slotName": "coffee_type", "value": "cappuccino"}}, ... ] } This function extracts a slot value given its slot name, and parses it into a Python object if applicable (e.g. for dates). Slots can be of various forms, the simplest being just: {"slotName": "coffee_sugar_amout", "value": "3"} More complex examples are date times, where we distinguish between instant times, or intervals. Thus, a slot: { "slotName": "weatherForecastStartDatetime", "value": { "kind": "InstantTime", "value": { "value": "2017-07-14 00:00:00 +00:00", "grain": "Day", "precision": "Exact" } } } will be extracted as an `InstantTime` object, with datetime parsed and granularity set. Another example is a time interval: { "slotName": "weatherForecastStartDatetime", "value": { "kind": "TimeInterval", "value": { "from": "2017-07-14 12:00:00 +00:00", "to": "2017-07-14 19:00:00 +00:00" } }, } which will be extracted as a TimeInterval object. :param payload: the intent, in JSON format. :return: the parsed value, as described above. """ if not 'slots' in payload: return [] slots = [] for candidate in payload['slots']: if 'slotName' in candidate and candidate['slotName'] == slot_name: slots.append(candidate) result = [] for slot in slots: kind = IntentParser.get_dict_value(slot, ['value', 'kind']) if kind == "InstantTime": result.append(IntentParser.parse_instant_time(slot)) elif kind == "TimeInterval": result.append(IntentParser.parse_time_interval(slot)) else: result.append(IntentParser.get_dict_value(slot, ['value', 'value', 'value']) \ or IntentParser.get_dict_value(slot, ['value', 'value'])) return result
python
def get_slot_value(payload, slot_name): """ Return the parsed value of a slot. An intent has the form: { "text": "brew me a cappuccino with 3 sugars tomorrow", "slots": [ {"value": {"slotName": "coffee_type", "value": "cappuccino"}}, ... ] } This function extracts a slot value given its slot name, and parses it into a Python object if applicable (e.g. for dates). Slots can be of various forms, the simplest being just: {"slotName": "coffee_sugar_amout", "value": "3"} More complex examples are date times, where we distinguish between instant times, or intervals. Thus, a slot: { "slotName": "weatherForecastStartDatetime", "value": { "kind": "InstantTime", "value": { "value": "2017-07-14 00:00:00 +00:00", "grain": "Day", "precision": "Exact" } } } will be extracted as an `InstantTime` object, with datetime parsed and granularity set. Another example is a time interval: { "slotName": "weatherForecastStartDatetime", "value": { "kind": "TimeInterval", "value": { "from": "2017-07-14 12:00:00 +00:00", "to": "2017-07-14 19:00:00 +00:00" } }, } which will be extracted as a TimeInterval object. :param payload: the intent, in JSON format. :return: the parsed value, as described above. """ if not 'slots' in payload: return [] slots = [] for candidate in payload['slots']: if 'slotName' in candidate and candidate['slotName'] == slot_name: slots.append(candidate) result = [] for slot in slots: kind = IntentParser.get_dict_value(slot, ['value', 'kind']) if kind == "InstantTime": result.append(IntentParser.parse_instant_time(slot)) elif kind == "TimeInterval": result.append(IntentParser.parse_time_interval(slot)) else: result.append(IntentParser.get_dict_value(slot, ['value', 'value', 'value']) \ or IntentParser.get_dict_value(slot, ['value', 'value'])) return result
[ "def", "get_slot_value", "(", "payload", ",", "slot_name", ")", ":", "if", "not", "'slots'", "in", "payload", ":", "return", "[", "]", "slots", "=", "[", "]", "for", "candidate", "in", "payload", "[", "'slots'", "]", ":", "if", "'slotName'", "in", "can...
Return the parsed value of a slot. An intent has the form: { "text": "brew me a cappuccino with 3 sugars tomorrow", "slots": [ {"value": {"slotName": "coffee_type", "value": "cappuccino"}}, ... ] } This function extracts a slot value given its slot name, and parses it into a Python object if applicable (e.g. for dates). Slots can be of various forms, the simplest being just: {"slotName": "coffee_sugar_amout", "value": "3"} More complex examples are date times, where we distinguish between instant times, or intervals. Thus, a slot: { "slotName": "weatherForecastStartDatetime", "value": { "kind": "InstantTime", "value": { "value": "2017-07-14 00:00:00 +00:00", "grain": "Day", "precision": "Exact" } } } will be extracted as an `InstantTime` object, with datetime parsed and granularity set. Another example is a time interval: { "slotName": "weatherForecastStartDatetime", "value": { "kind": "TimeInterval", "value": { "from": "2017-07-14 12:00:00 +00:00", "to": "2017-07-14 19:00:00 +00:00" } }, } which will be extracted as a TimeInterval object. :param payload: the intent, in JSON format. :return: the parsed value, as described above.
[ "Return", "the", "parsed", "value", "of", "a", "slot", ".", "An", "intent", "has", "the", "form", ":" ]
train
https://github.com/snipsco/snipsmanagercore/blob/93eaaa665887f790a30ba86af5ffee394bfd8ede/snipsmanagercore/intent_parser.py#L59-L133
snipsco/snipsmanagercore
snipsmanagercore/intent_parser.py
IntentParser.parse_instant_time
def parse_instant_time(slot): """ Parse a slot into an InstantTime object. Sample response: { "entity": "snips/datetime", "range": { "end": 36, "start": 28 }, "rawValue": "tomorrow", "slotName": "weatherForecastStartDatetime", "value": { "grain": "Day", "kind": "InstantTime", "precision": "Exact", "value": "2017-09-15 00:00:00 +00:00" } } :param slot: a intent slot. :return: a parsed InstantTime object, or None. """ date = IntentParser.get_dict_value(slot, ['value', 'value']) if not date: return None date = parse(date) if not date: return None grain = InstantTime.parse_grain( IntentParser.get_dict_value(slot, ['value', 'grain'])) return InstantTime(date, grain)
python
def parse_instant_time(slot): """ Parse a slot into an InstantTime object. Sample response: { "entity": "snips/datetime", "range": { "end": 36, "start": 28 }, "rawValue": "tomorrow", "slotName": "weatherForecastStartDatetime", "value": { "grain": "Day", "kind": "InstantTime", "precision": "Exact", "value": "2017-09-15 00:00:00 +00:00" } } :param slot: a intent slot. :return: a parsed InstantTime object, or None. """ date = IntentParser.get_dict_value(slot, ['value', 'value']) if not date: return None date = parse(date) if not date: return None grain = InstantTime.parse_grain( IntentParser.get_dict_value(slot, ['value', 'grain'])) return InstantTime(date, grain)
[ "def", "parse_instant_time", "(", "slot", ")", ":", "date", "=", "IntentParser", ".", "get_dict_value", "(", "slot", ",", "[", "'value'", ",", "'value'", "]", ")", "if", "not", "date", ":", "return", "None", "date", "=", "parse", "(", "date", ")", "if"...
Parse a slot into an InstantTime object. Sample response: { "entity": "snips/datetime", "range": { "end": 36, "start": 28 }, "rawValue": "tomorrow", "slotName": "weatherForecastStartDatetime", "value": { "grain": "Day", "kind": "InstantTime", "precision": "Exact", "value": "2017-09-15 00:00:00 +00:00" } } :param slot: a intent slot. :return: a parsed InstantTime object, or None.
[ "Parse", "a", "slot", "into", "an", "InstantTime", "object", "." ]
train
https://github.com/snipsco/snipsmanagercore/blob/93eaaa665887f790a30ba86af5ffee394bfd8ede/snipsmanagercore/intent_parser.py#L136-L169
snipsco/snipsmanagercore
snipsmanagercore/intent_parser.py
IntentParser.parse_time_interval
def parse_time_interval(slot): """ Parse a slot into a TimeInterval object. Sample response: { "entity": "snips/datetime", "range": { "end": 42, "start": 13 }, "rawValue": "between tomorrow and saturday", "slotName": "weatherForecastStartDatetime", "value": { "from": "2017-09-15 00:00:00 +00:00", "kind": "TimeInterval", "to": "2017-09-17 00:00:00 +00:00" } } :param slot: a intent slot. :return: a parsed TimeInterval object, or None. """ start = IntentParser.get_dict_value( slot, ['value', 'from']) end = IntentParser.get_dict_value(slot, ['value', 'to']) if not start or not end: return None start = parse(start) end = parse(end) if not start or not end: return None return TimeInterval(start, end)
python
def parse_time_interval(slot): """ Parse a slot into a TimeInterval object. Sample response: { "entity": "snips/datetime", "range": { "end": 42, "start": 13 }, "rawValue": "between tomorrow and saturday", "slotName": "weatherForecastStartDatetime", "value": { "from": "2017-09-15 00:00:00 +00:00", "kind": "TimeInterval", "to": "2017-09-17 00:00:00 +00:00" } } :param slot: a intent slot. :return: a parsed TimeInterval object, or None. """ start = IntentParser.get_dict_value( slot, ['value', 'from']) end = IntentParser.get_dict_value(slot, ['value', 'to']) if not start or not end: return None start = parse(start) end = parse(end) if not start or not end: return None return TimeInterval(start, end)
[ "def", "parse_time_interval", "(", "slot", ")", ":", "start", "=", "IntentParser", ".", "get_dict_value", "(", "slot", ",", "[", "'value'", ",", "'from'", "]", ")", "end", "=", "IntentParser", ".", "get_dict_value", "(", "slot", ",", "[", "'value'", ",", ...
Parse a slot into a TimeInterval object. Sample response: { "entity": "snips/datetime", "range": { "end": 42, "start": 13 }, "rawValue": "between tomorrow and saturday", "slotName": "weatherForecastStartDatetime", "value": { "from": "2017-09-15 00:00:00 +00:00", "kind": "TimeInterval", "to": "2017-09-17 00:00:00 +00:00" } } :param slot: a intent slot. :return: a parsed TimeInterval object, or None.
[ "Parse", "a", "slot", "into", "a", "TimeInterval", "object", "." ]
train
https://github.com/snipsco/snipsmanagercore/blob/93eaaa665887f790a30ba86af5ffee394bfd8ede/snipsmanagercore/intent_parser.py#L172-L204
snipsco/snipsmanagercore
snipsmanagercore/intent_parser.py
IntentParser.get_dict_value
def get_dict_value(dictionary, path): """ Safely get the value of a dictionary given a key path. For instance, for the dictionary `{ 'a': { 'b': 1 } }`, the value at key path ['a'] is { 'b': 1 }, at key path ['a', 'b'] is 1, at key path ['a', 'b', 'c'] is None. :param dictionary: a dictionary. :param path: the key path. :return: The value of d at the given key path, or None if the key path does not exist. """ if len(path) == 0: return None temp_dictionary = dictionary try: for k in path: temp_dictionary = temp_dictionary[k] return temp_dictionary except (KeyError, TypeError): pass return None
python
def get_dict_value(dictionary, path): """ Safely get the value of a dictionary given a key path. For instance, for the dictionary `{ 'a': { 'b': 1 } }`, the value at key path ['a'] is { 'b': 1 }, at key path ['a', 'b'] is 1, at key path ['a', 'b', 'c'] is None. :param dictionary: a dictionary. :param path: the key path. :return: The value of d at the given key path, or None if the key path does not exist. """ if len(path) == 0: return None temp_dictionary = dictionary try: for k in path: temp_dictionary = temp_dictionary[k] return temp_dictionary except (KeyError, TypeError): pass return None
[ "def", "get_dict_value", "(", "dictionary", ",", "path", ")", ":", "if", "len", "(", "path", ")", "==", "0", ":", "return", "None", "temp_dictionary", "=", "dictionary", "try", ":", "for", "k", "in", "path", ":", "temp_dictionary", "=", "temp_dictionary", ...
Safely get the value of a dictionary given a key path. For instance, for the dictionary `{ 'a': { 'b': 1 } }`, the value at key path ['a'] is { 'b': 1 }, at key path ['a', 'b'] is 1, at key path ['a', 'b', 'c'] is None. :param dictionary: a dictionary. :param path: the key path. :return: The value of d at the given key path, or None if the key path does not exist.
[ "Safely", "get", "the", "value", "of", "a", "dictionary", "given", "a", "key", "path", ".", "For", "instance", "for", "the", "dictionary", "{", "a", ":", "{", "b", ":", "1", "}", "}", "the", "value", "at", "key", "path", "[", "a", "]", "is", "{",...
train
https://github.com/snipsco/snipsmanagercore/blob/93eaaa665887f790a30ba86af5ffee394bfd8ede/snipsmanagercore/intent_parser.py#L207-L227
MoseleyBioinformaticsLab/nmrstarlib
nmrstarlib/csviewer.py
CSViewer.csview
def csview(self, view=False): """View chemical shift values organized by amino acid residue. :param view: Open in default image viewer or save file in current working directory quietly. :type view: :py:obj:`True` or :py:obj:`False` :return: None :rtype: :py:obj:`None` """ for starfile in fileio.read_files(self.from_path): chains = starfile.chem_shifts_by_residue(amino_acids=self.amino_acids, atoms=self.atoms, amino_acids_and_atoms=self.amino_acids_and_atoms, nmrstar_version=self.nmrstar_version) for idx, chemshifts_dict in enumerate(chains): nodes = [] edges = [] for seq_id in chemshifts_dict: aaname = "{}_{}".format(chemshifts_dict[seq_id]["AA3Code"], seq_id) label = '"{{{}|{}}}"'.format(seq_id, chemshifts_dict[seq_id]["AA3Code"]) color = 8 aanode_entry = " {} [label={}, fillcolor={}]".format(aaname, label, color) nodes.append(aanode_entry) currnodename = aaname for atom_type in chemshifts_dict[seq_id]: if atom_type in ["AA3Code", "Seq_ID"]: continue else: atname = "{}_{}".format(aaname, atom_type) label = '"{{{}|{}}}"'.format(atom_type, chemshifts_dict[seq_id][atom_type]) if atom_type.startswith("H"): color = 4 elif atom_type.startswith("C"): color = 6 elif atom_type.startswith("N"): color = 10 else: color = 8 atnode_entry = "{} [label={}, fillcolor={}]".format(atname, label, color) nextnodename = atname nodes.append(atnode_entry) edges.append("{} -> {}".format(currnodename, nextnodename)) currnodename = nextnodename if self.filename is None: filename = "{}_{}".format(starfile.id, idx) else: filename = "{}_{}".format(self.filename, idx) src = Source(self.dot_template.format("\n".join(nodes), "\n".join(edges)), format=self.csview_format) src.render(filename=filename, view=view)
python
def csview(self, view=False): """View chemical shift values organized by amino acid residue. :param view: Open in default image viewer or save file in current working directory quietly. :type view: :py:obj:`True` or :py:obj:`False` :return: None :rtype: :py:obj:`None` """ for starfile in fileio.read_files(self.from_path): chains = starfile.chem_shifts_by_residue(amino_acids=self.amino_acids, atoms=self.atoms, amino_acids_and_atoms=self.amino_acids_and_atoms, nmrstar_version=self.nmrstar_version) for idx, chemshifts_dict in enumerate(chains): nodes = [] edges = [] for seq_id in chemshifts_dict: aaname = "{}_{}".format(chemshifts_dict[seq_id]["AA3Code"], seq_id) label = '"{{{}|{}}}"'.format(seq_id, chemshifts_dict[seq_id]["AA3Code"]) color = 8 aanode_entry = " {} [label={}, fillcolor={}]".format(aaname, label, color) nodes.append(aanode_entry) currnodename = aaname for atom_type in chemshifts_dict[seq_id]: if atom_type in ["AA3Code", "Seq_ID"]: continue else: atname = "{}_{}".format(aaname, atom_type) label = '"{{{}|{}}}"'.format(atom_type, chemshifts_dict[seq_id][atom_type]) if atom_type.startswith("H"): color = 4 elif atom_type.startswith("C"): color = 6 elif atom_type.startswith("N"): color = 10 else: color = 8 atnode_entry = "{} [label={}, fillcolor={}]".format(atname, label, color) nextnodename = atname nodes.append(atnode_entry) edges.append("{} -> {}".format(currnodename, nextnodename)) currnodename = nextnodename if self.filename is None: filename = "{}_{}".format(starfile.id, idx) else: filename = "{}_{}".format(self.filename, idx) src = Source(self.dot_template.format("\n".join(nodes), "\n".join(edges)), format=self.csview_format) src.render(filename=filename, view=view)
[ "def", "csview", "(", "self", ",", "view", "=", "False", ")", ":", "for", "starfile", "in", "fileio", ".", "read_files", "(", "self", ".", "from_path", ")", ":", "chains", "=", "starfile", ".", "chem_shifts_by_residue", "(", "amino_acids", "=", "self", "...
View chemical shift values organized by amino acid residue. :param view: Open in default image viewer or save file in current working directory quietly. :type view: :py:obj:`True` or :py:obj:`False` :return: None :rtype: :py:obj:`None`
[ "View", "chemical", "shift", "values", "organized", "by", "amino", "acid", "residue", "." ]
train
https://github.com/MoseleyBioinformaticsLab/nmrstarlib/blob/f2adabbca04d5a134ce6ba3211099d1457787ff2/nmrstarlib/csviewer.py#L70-L122
pletzer/pnumpy
src/pnDomainPartitionIter.py
DomainPartitionIter.getStringPartition
def getStringPartition(self): """ Get the string representation of the current partition @return string like ":-1,0:2" """ res = '' for s in self.partitions[self.index].getSlice(): start = '' stop = '' if s.start is not None: start = int(s.start) if s.stop is not None: stop = int(s.stop) res += '{0}:{1},'.format(start, stop) return res
python
def getStringPartition(self): """ Get the string representation of the current partition @return string like ":-1,0:2" """ res = '' for s in self.partitions[self.index].getSlice(): start = '' stop = '' if s.start is not None: start = int(s.start) if s.stop is not None: stop = int(s.stop) res += '{0}:{1},'.format(start, stop) return res
[ "def", "getStringPartition", "(", "self", ")", ":", "res", "=", "''", "for", "s", "in", "self", ".", "partitions", "[", "self", ".", "index", "]", ".", "getSlice", "(", ")", ":", "start", "=", "''", "stop", "=", "''", "if", "s", ".", "start", "is...
Get the string representation of the current partition @return string like ":-1,0:2"
[ "Get", "the", "string", "representation", "of", "the", "current", "partition" ]
train
https://github.com/pletzer/pnumpy/blob/9e6d308be94a42637466b91ab1a7b4d64b4c29ae/src/pnDomainPartitionIter.py#L122-L136
akissa/spamc
examples/example1.py
runit
def runit(): """run things""" parser = OptionParser() parser.add_option('-s', '--server', help='The spamassassin spamd server to connect to', dest='server', type='str', default='standalone.home.topdog-software.com') parser.add_option('-p', '--port', help='The spamassassin spamd server port to connect to', dest='port', type='int', default=783) parser.add_option('-u', '--unix-socket', help='The spamassassin spamd unix socket to connect to', dest='socket_path', type='str') parser.add_option('-t', '--tls', help='Use TLS', dest='tls', action='store_true', default=False) parser.add_option('-z', '--use-zlib-compression', help='Use Zlib compression', dest='gzip', action='store_true', default=False) parser.add_option('-l', '--zlib-compression-level', help='Zlib compression level', dest='compress_level', type='choice', choices=[str(val) for val in range(0, 10)], default=6) parser.add_option('-a', '--user', help=('''Username of the user on whose behalf''' '''this scan is being performed'''), dest='user', type='str', default='exim') options, _ = parser.parse_args() sslopts = {} if options.tls: sslopts = dict(ssl_version=PROTOCOL_TLSv1) if options.socket_path and os.path.exists(options.socket_path): options.server = None client = SpamC( options.server, port=options.port, socket_file=options.socket_path, user=options.user, gzip=options.gzip, compress_level=int(options.compress_level), is_ssl=options.tls, **sslopts) pprint.pprint(client.ping()) path = os.path.dirname(__file__) for test in FILES: filename = os.path.join(path, test['name']) print "File => %s" % filename fileobj = open(filename) print "=" * 10, "client.check()" pprint.pprint(client.check(fileobj)) print "=" * 10, "client.symbols()" pprint.pprint(client.symbols(fileobj)) print "=" * 10, "client.report()" pprint.pprint(client.report(fileobj)) print "=" * 10, "client.report_ifspam()" pprint.pprint(client.report_ifspam(fileobj)) print "=" * 10, "client.process()" pprint.pprint(client.process(fileobj)) print "=" * 10, "client.headers()" pprint.pprint(client.headers(fileobj)) print "=" * 10, "client.learn()" pprint.pprint(client.learn(fileobj, test['type'])) print "=" * 10, "client.tell()" pprint.pprint(client.tell(fileobj, 'forget')) print "=" * 10, "client.revoke()" pprint.pprint(client.revoke(fileobj))
python
def runit(): """run things""" parser = OptionParser() parser.add_option('-s', '--server', help='The spamassassin spamd server to connect to', dest='server', type='str', default='standalone.home.topdog-software.com') parser.add_option('-p', '--port', help='The spamassassin spamd server port to connect to', dest='port', type='int', default=783) parser.add_option('-u', '--unix-socket', help='The spamassassin spamd unix socket to connect to', dest='socket_path', type='str') parser.add_option('-t', '--tls', help='Use TLS', dest='tls', action='store_true', default=False) parser.add_option('-z', '--use-zlib-compression', help='Use Zlib compression', dest='gzip', action='store_true', default=False) parser.add_option('-l', '--zlib-compression-level', help='Zlib compression level', dest='compress_level', type='choice', choices=[str(val) for val in range(0, 10)], default=6) parser.add_option('-a', '--user', help=('''Username of the user on whose behalf''' '''this scan is being performed'''), dest='user', type='str', default='exim') options, _ = parser.parse_args() sslopts = {} if options.tls: sslopts = dict(ssl_version=PROTOCOL_TLSv1) if options.socket_path and os.path.exists(options.socket_path): options.server = None client = SpamC( options.server, port=options.port, socket_file=options.socket_path, user=options.user, gzip=options.gzip, compress_level=int(options.compress_level), is_ssl=options.tls, **sslopts) pprint.pprint(client.ping()) path = os.path.dirname(__file__) for test in FILES: filename = os.path.join(path, test['name']) print "File => %s" % filename fileobj = open(filename) print "=" * 10, "client.check()" pprint.pprint(client.check(fileobj)) print "=" * 10, "client.symbols()" pprint.pprint(client.symbols(fileobj)) print "=" * 10, "client.report()" pprint.pprint(client.report(fileobj)) print "=" * 10, "client.report_ifspam()" pprint.pprint(client.report_ifspam(fileobj)) print "=" * 10, "client.process()" pprint.pprint(client.process(fileobj)) print "=" * 10, "client.headers()" pprint.pprint(client.headers(fileobj)) print "=" * 10, "client.learn()" pprint.pprint(client.learn(fileobj, test['type'])) print "=" * 10, "client.tell()" pprint.pprint(client.tell(fileobj, 'forget')) print "=" * 10, "client.revoke()" pprint.pprint(client.revoke(fileobj))
[ "def", "runit", "(", ")", ":", "parser", "=", "OptionParser", "(", ")", "parser", ".", "add_option", "(", "'-s'", ",", "'--server'", ",", "help", "=", "'The spamassassin spamd server to connect to'", ",", "dest", "=", "'server'", ",", "type", "=", "'str'", "...
run things
[ "run", "things" ]
train
https://github.com/akissa/spamc/blob/da50732e276f7ed3d67cb75c31cb017d6a62f066/examples/example1.py#L32-L109
dslackw/sun
sun/utils.py
urlopen
def urlopen(link): """Return urllib2 urlopen """ try: return urllib2.urlopen(link) except urllib2.URLError: pass except ValueError: return "" except KeyboardInterrupt: print("") raise SystemExit()
python
def urlopen(link): """Return urllib2 urlopen """ try: return urllib2.urlopen(link) except urllib2.URLError: pass except ValueError: return "" except KeyboardInterrupt: print("") raise SystemExit()
[ "def", "urlopen", "(", "link", ")", ":", "try", ":", "return", "urllib2", ".", "urlopen", "(", "link", ")", "except", "urllib2", ".", "URLError", ":", "pass", "except", "ValueError", ":", "return", "\"\"", "except", "KeyboardInterrupt", ":", "print", "(", ...
Return urllib2 urlopen
[ "Return", "urllib2", "urlopen" ]
train
https://github.com/dslackw/sun/blob/ff3501757ce1cc2f0db195f7a6b1d23f601dce32/sun/utils.py#L38-L49
dslackw/sun
sun/utils.py
slack_ver
def slack_ver(): """Open file and read Slackware version """ dist = read_file("/etc/slackware-version") sv = re.findall(r"\d+", dist) if len(sv) > 2: version = (".".join(sv[:2])) else: version = (".".join(sv)) return dist.split()[0], version
python
def slack_ver(): """Open file and read Slackware version """ dist = read_file("/etc/slackware-version") sv = re.findall(r"\d+", dist) if len(sv) > 2: version = (".".join(sv[:2])) else: version = (".".join(sv)) return dist.split()[0], version
[ "def", "slack_ver", "(", ")", ":", "dist", "=", "read_file", "(", "\"/etc/slackware-version\"", ")", "sv", "=", "re", ".", "findall", "(", "r\"\\d+\"", ",", "dist", ")", "if", "len", "(", "sv", ")", ">", "2", ":", "version", "=", "(", "\".\"", ".", ...
Open file and read Slackware version
[ "Open", "file", "and", "read", "Slackware", "version" ]
train
https://github.com/dslackw/sun/blob/ff3501757ce1cc2f0db195f7a6b1d23f601dce32/sun/utils.py#L61-L70
dslackw/sun
sun/utils.py
ins_packages
def ins_packages(): """Count installed Slackware packages """ count = 0 for pkg in os.listdir(pkg_path): if not pkg.startswith("."): count += 1 return count
python
def ins_packages(): """Count installed Slackware packages """ count = 0 for pkg in os.listdir(pkg_path): if not pkg.startswith("."): count += 1 return count
[ "def", "ins_packages", "(", ")", ":", "count", "=", "0", "for", "pkg", "in", "os", ".", "listdir", "(", "pkg_path", ")", ":", "if", "not", "pkg", ".", "startswith", "(", "\".\"", ")", ":", "count", "+=", "1", "return", "count" ]
Count installed Slackware packages
[ "Count", "installed", "Slackware", "packages" ]
train
https://github.com/dslackw/sun/blob/ff3501757ce1cc2f0db195f7a6b1d23f601dce32/sun/utils.py#L73-L80
dslackw/sun
sun/utils.py
read_config
def read_config(config): """Read config file and return uncomment line """ for line in config.splitlines(): line = line.lstrip() if line and not line.startswith("#"): return line return ""
python
def read_config(config): """Read config file and return uncomment line """ for line in config.splitlines(): line = line.lstrip() if line and not line.startswith("#"): return line return ""
[ "def", "read_config", "(", "config", ")", ":", "for", "line", "in", "config", ".", "splitlines", "(", ")", ":", "line", "=", "line", ".", "lstrip", "(", ")", "if", "line", "and", "not", "line", ".", "startswith", "(", "\"#\"", ")", ":", "return", "...
Read config file and return uncomment line
[ "Read", "config", "file", "and", "return", "uncomment", "line" ]
train
https://github.com/dslackw/sun/blob/ff3501757ce1cc2f0db195f7a6b1d23f601dce32/sun/utils.py#L83-L90
dslackw/sun
sun/utils.py
mirror
def mirror(): """Get mirror from slackpkg mirrors file """ slack_mirror = read_config( read_file("{0}{1}".format(etc_slackpkg, "mirrors"))) if slack_mirror: return slack_mirror + changelog_txt else: print("\nYou do not have any mirror selected in /etc/slackpkg/mirrors" "\nPlease edit that file and uncomment ONE mirror.\n") return ""
python
def mirror(): """Get mirror from slackpkg mirrors file """ slack_mirror = read_config( read_file("{0}{1}".format(etc_slackpkg, "mirrors"))) if slack_mirror: return slack_mirror + changelog_txt else: print("\nYou do not have any mirror selected in /etc/slackpkg/mirrors" "\nPlease edit that file and uncomment ONE mirror.\n") return ""
[ "def", "mirror", "(", ")", ":", "slack_mirror", "=", "read_config", "(", "read_file", "(", "\"{0}{1}\"", ".", "format", "(", "etc_slackpkg", ",", "\"mirrors\"", ")", ")", ")", "if", "slack_mirror", ":", "return", "slack_mirror", "+", "changelog_txt", "else", ...
Get mirror from slackpkg mirrors file
[ "Get", "mirror", "from", "slackpkg", "mirrors", "file" ]
train
https://github.com/dslackw/sun/blob/ff3501757ce1cc2f0db195f7a6b1d23f601dce32/sun/utils.py#L93-L103
dslackw/sun
sun/utils.py
fetch
def fetch(): """Get ChangeLog.txt file size and counts upgraded packages """ mir, r, slackpkg_last_date = mirror(), "", "" count, upgraded = 0, [] if mir: tar = urlopen(mir) try: r = tar.read() except AttributeError: print("sun: error: can't read mirror") if os.path.isfile(var_lib_slackpkg + changelog_txt): slackpkg_last_date = read_file("{0}{1}".format( var_lib_slackpkg, changelog_txt)).split("\n", 1)[0].strip() else: return [count, upgraded] for line in r.splitlines(): if slackpkg_last_date == line.strip(): break if (line.endswith("z: Upgraded.") or line.endswith("z: Rebuilt.") or line.endswith("z: Added.") or line.endswith("z: Removed.")): upgraded.append(line.split("/")[-1]) count += 1 if (line.endswith("*: Upgraded.") or line.endswith("*: Rebuilt.") or line.endswith("*: Added.") or line.endswith("*: Removed.")): upgraded.append(line) count += 1 return [count, upgraded]
python
def fetch(): """Get ChangeLog.txt file size and counts upgraded packages """ mir, r, slackpkg_last_date = mirror(), "", "" count, upgraded = 0, [] if mir: tar = urlopen(mir) try: r = tar.read() except AttributeError: print("sun: error: can't read mirror") if os.path.isfile(var_lib_slackpkg + changelog_txt): slackpkg_last_date = read_file("{0}{1}".format( var_lib_slackpkg, changelog_txt)).split("\n", 1)[0].strip() else: return [count, upgraded] for line in r.splitlines(): if slackpkg_last_date == line.strip(): break if (line.endswith("z: Upgraded.") or line.endswith("z: Rebuilt.") or line.endswith("z: Added.") or line.endswith("z: Removed.")): upgraded.append(line.split("/")[-1]) count += 1 if (line.endswith("*: Upgraded.") or line.endswith("*: Rebuilt.") or line.endswith("*: Added.") or line.endswith("*: Removed.")): upgraded.append(line) count += 1 return [count, upgraded]
[ "def", "fetch", "(", ")", ":", "mir", ",", "r", ",", "slackpkg_last_date", "=", "mirror", "(", ")", ",", "\"\"", ",", "\"\"", "count", ",", "upgraded", "=", "0", ",", "[", "]", "if", "mir", ":", "tar", "=", "urlopen", "(", "mir", ")", "try", ":...
Get ChangeLog.txt file size and counts upgraded packages
[ "Get", "ChangeLog", ".", "txt", "file", "size", "and", "counts", "upgraded", "packages" ]
train
https://github.com/dslackw/sun/blob/ff3501757ce1cc2f0db195f7a6b1d23f601dce32/sun/utils.py#L106-L133
dslackw/sun
sun/utils.py
config
def config(): """Return sun configuration values """ conf_args = { "INTERVAL": 60, "STANDBY": 3 } config_file = read_file("{0}{1}".format(conf_path, "sun.conf")) for line in config_file.splitlines(): line = line.lstrip() if line and not line.startswith("#"): conf_args[line.split("=")[0]] = line.split("=")[1] return conf_args
python
def config(): """Return sun configuration values """ conf_args = { "INTERVAL": 60, "STANDBY": 3 } config_file = read_file("{0}{1}".format(conf_path, "sun.conf")) for line in config_file.splitlines(): line = line.lstrip() if line and not line.startswith("#"): conf_args[line.split("=")[0]] = line.split("=")[1] return conf_args
[ "def", "config", "(", ")", ":", "conf_args", "=", "{", "\"INTERVAL\"", ":", "60", ",", "\"STANDBY\"", ":", "3", "}", "config_file", "=", "read_file", "(", "\"{0}{1}\"", ".", "format", "(", "conf_path", ",", "\"sun.conf\"", ")", ")", "for", "line", "in", ...
Return sun configuration values
[ "Return", "sun", "configuration", "values" ]
train
https://github.com/dslackw/sun/blob/ff3501757ce1cc2f0db195f7a6b1d23f601dce32/sun/utils.py#L136-L148
dslackw/sun
sun/utils.py
os_info
def os_info(): """Get OS info """ stype = "" slack, ver = slack_ver() mir = mirror() if mir: if "current" in mir: stype = "Current" else: stype = "Stable" info = ( "User: {0}\n" "OS: {1}\n" "Version: {2}\n" "Type: {3}\n" "Arch: {4}\n" "Kernel: {5}\n" "Packages: {6}".format(getpass.getuser(), slack, ver, stype, os.uname()[4], os.uname()[2], ins_packages())) return info
python
def os_info(): """Get OS info """ stype = "" slack, ver = slack_ver() mir = mirror() if mir: if "current" in mir: stype = "Current" else: stype = "Stable" info = ( "User: {0}\n" "OS: {1}\n" "Version: {2}\n" "Type: {3}\n" "Arch: {4}\n" "Kernel: {5}\n" "Packages: {6}".format(getpass.getuser(), slack, ver, stype, os.uname()[4], os.uname()[2], ins_packages())) return info
[ "def", "os_info", "(", ")", ":", "stype", "=", "\"\"", "slack", ",", "ver", "=", "slack_ver", "(", ")", "mir", "=", "mirror", "(", ")", "if", "mir", ":", "if", "\"current\"", "in", "mir", ":", "stype", "=", "\"Current\"", "else", ":", "stype", "=",...
Get OS info
[ "Get", "OS", "info" ]
train
https://github.com/dslackw/sun/blob/ff3501757ce1cc2f0db195f7a6b1d23f601dce32/sun/utils.py#L151-L171
pletzer/pnumpy
src/pnCubeDecomp.py
getPrimeFactors
def getPrimeFactors(n): """ Get all the prime factor of given integer @param n integer @return list [1, ..., n] """ lo = [1] n2 = n // 2 k = 2 for k in range(2, n2 + 1): if (n // k)*k == n: lo.append(k) return lo + [n, ]
python
def getPrimeFactors(n): """ Get all the prime factor of given integer @param n integer @return list [1, ..., n] """ lo = [1] n2 = n // 2 k = 2 for k in range(2, n2 + 1): if (n // k)*k == n: lo.append(k) return lo + [n, ]
[ "def", "getPrimeFactors", "(", "n", ")", ":", "lo", "=", "[", "1", "]", "n2", "=", "n", "//", "2", "k", "=", "2", "for", "k", "in", "range", "(", "2", ",", "n2", "+", "1", ")", ":", "if", "(", "n", "//", "k", ")", "*", "k", "==", "n", ...
Get all the prime factor of given integer @param n integer @return list [1, ..., n]
[ "Get", "all", "the", "prime", "factor", "of", "given", "integer" ]
train
https://github.com/pletzer/pnumpy/blob/9e6d308be94a42637466b91ab1a7b4d64b4c29ae/src/pnCubeDecomp.py#L13-L25
pletzer/pnumpy
src/pnCubeDecomp.py
CubeDecomp.getNeighborProc
def getNeighborProc(self, proc, offset, periodic=None): """ Get the neighbor to a processor @param proc the reference processor rank @param offset displacement, e.g. (1, 0) for north, (0, -1) for west,... @param periodic boolean list of True/False values, True if axis is periodic, False otherwise @note will return None if there is no neighbor """ if self.mit is None: # no decomp, just exit return None inds = [self.mit.getIndicesFromBigIndex(proc)[d] + offset[d] for d in range(self.ndims)] if periodic is not None and self.decomp is not None: # apply modulo operation on periodic axes for d in range(self.ndims): if periodic[d]: inds[d] = inds[d] % self.decomp[d] if self.mit.areIndicesValid(inds): return self.mit.getBigIndexFromIndices(inds) else: return None
python
def getNeighborProc(self, proc, offset, periodic=None): """ Get the neighbor to a processor @param proc the reference processor rank @param offset displacement, e.g. (1, 0) for north, (0, -1) for west,... @param periodic boolean list of True/False values, True if axis is periodic, False otherwise @note will return None if there is no neighbor """ if self.mit is None: # no decomp, just exit return None inds = [self.mit.getIndicesFromBigIndex(proc)[d] + offset[d] for d in range(self.ndims)] if periodic is not None and self.decomp is not None: # apply modulo operation on periodic axes for d in range(self.ndims): if periodic[d]: inds[d] = inds[d] % self.decomp[d] if self.mit.areIndicesValid(inds): return self.mit.getBigIndexFromIndices(inds) else: return None
[ "def", "getNeighborProc", "(", "self", ",", "proc", ",", "offset", ",", "periodic", "=", "None", ")", ":", "if", "self", ".", "mit", "is", "None", ":", "# no decomp, just exit", "return", "None", "inds", "=", "[", "self", ".", "mit", ".", "getIndicesFrom...
Get the neighbor to a processor @param proc the reference processor rank @param offset displacement, e.g. (1, 0) for north, (0, -1) for west,... @param periodic boolean list of True/False values, True if axis is periodic, False otherwise @note will return None if there is no neighbor
[ "Get", "the", "neighbor", "to", "a", "processor" ]
train
https://github.com/pletzer/pnumpy/blob/9e6d308be94a42637466b91ab1a7b4d64b4c29ae/src/pnCubeDecomp.py#L93-L119
pletzer/pnumpy
src/pnCubeDecomp.py
CubeDecomp.__computeDecomp
def __computeDecomp(self): """ Compute optimal dedomposition, each sub-domain has the same volume in index space. @return list if successful, empty list if not successful """ primeNumbers = [getPrimeFactors(d) for d in self.globalDims] ns = [len(pns) for pns in primeNumbers] validDecomps = [] self.validProcs = [] for it in MultiArrayIter(ns): inds = it.getIndices() decomp = [primeNumbers[d][inds[d]] for d in range(self.ndims)] self.validProcs.append(reduce(operator.mul, decomp, 1)) if reduce(operator.mul, decomp, 1) == self.nprocs: validDecomps.append(decomp) # sort and remove duplicates self.validProcs.sort() vprocs = [] for vp in self.validProcs: if len(vprocs) == 0 or (len(vprocs) >= 1 and vp != vprocs[-1]): vprocs.append(vp) self.validProcs = vprocs if len(validDecomps) == 0: # no solution return # find the optimal decomp among all valid decomps minCost = float('inf') bestDecomp = validDecomps[0] for decomp in validDecomps: sizes = [self.globalDims[d]//decomp[d] for d in range(self.ndims)] volume = reduce(operator.mul, sizes, 1) surface = 0 for d in range(self.ndims): surface += 2*reduce(operator.mul, sizes[:d], 1) * \ reduce(operator.mul, sizes[d+1:], 1) cost = surface / float(volume) if cost < minCost: bestDecomp = decomp minCost = cost self.decomp = bestDecomp # ok, we have a valid decomp, now build the sub-domain iterator self.mit = MultiArrayIter(self.decomp, rowMajor=self.rowMajor) # fill in the proc to index set map procId = 0 self.proc2IndexSet = {} numCellsPerProc = [self.globalDims[d]//self.decomp[d] for d in range(self.ndims)] for it in self.mit: nps = it.getIndices() self.proc2IndexSet[procId] = [] for d in range(self.ndims): sbeg = nps[d]*numCellsPerProc[d] send = (nps[d] + 1)*numCellsPerProc[d] self.proc2IndexSet[procId].append(slice(sbeg, send)) procId += 1
python
def __computeDecomp(self): """ Compute optimal dedomposition, each sub-domain has the same volume in index space. @return list if successful, empty list if not successful """ primeNumbers = [getPrimeFactors(d) for d in self.globalDims] ns = [len(pns) for pns in primeNumbers] validDecomps = [] self.validProcs = [] for it in MultiArrayIter(ns): inds = it.getIndices() decomp = [primeNumbers[d][inds[d]] for d in range(self.ndims)] self.validProcs.append(reduce(operator.mul, decomp, 1)) if reduce(operator.mul, decomp, 1) == self.nprocs: validDecomps.append(decomp) # sort and remove duplicates self.validProcs.sort() vprocs = [] for vp in self.validProcs: if len(vprocs) == 0 or (len(vprocs) >= 1 and vp != vprocs[-1]): vprocs.append(vp) self.validProcs = vprocs if len(validDecomps) == 0: # no solution return # find the optimal decomp among all valid decomps minCost = float('inf') bestDecomp = validDecomps[0] for decomp in validDecomps: sizes = [self.globalDims[d]//decomp[d] for d in range(self.ndims)] volume = reduce(operator.mul, sizes, 1) surface = 0 for d in range(self.ndims): surface += 2*reduce(operator.mul, sizes[:d], 1) * \ reduce(operator.mul, sizes[d+1:], 1) cost = surface / float(volume) if cost < minCost: bestDecomp = decomp minCost = cost self.decomp = bestDecomp # ok, we have a valid decomp, now build the sub-domain iterator self.mit = MultiArrayIter(self.decomp, rowMajor=self.rowMajor) # fill in the proc to index set map procId = 0 self.proc2IndexSet = {} numCellsPerProc = [self.globalDims[d]//self.decomp[d] for d in range(self.ndims)] for it in self.mit: nps = it.getIndices() self.proc2IndexSet[procId] = [] for d in range(self.ndims): sbeg = nps[d]*numCellsPerProc[d] send = (nps[d] + 1)*numCellsPerProc[d] self.proc2IndexSet[procId].append(slice(sbeg, send)) procId += 1
[ "def", "__computeDecomp", "(", "self", ")", ":", "primeNumbers", "=", "[", "getPrimeFactors", "(", "d", ")", "for", "d", "in", "self", ".", "globalDims", "]", "ns", "=", "[", "len", "(", "pns", ")", "for", "pns", "in", "primeNumbers", "]", "validDecomp...
Compute optimal dedomposition, each sub-domain has the same volume in index space. @return list if successful, empty list if not successful
[ "Compute", "optimal", "dedomposition", "each", "sub", "-", "domain", "has", "the", "same", "volume", "in", "index", "space", "." ]
train
https://github.com/pletzer/pnumpy/blob/9e6d308be94a42637466b91ab1a7b4d64b4c29ae/src/pnCubeDecomp.py#L121-L182
ClimateImpactLab/DataFS
datafs/config/constructor.py
APIConstructor._generate_manager
def _generate_manager(manager_config): ''' Generate a manager from a manager_config dictionary Parameters ---------- manager_config : dict Configuration with keys class, args, and kwargs used to generate a new datafs.manager object Returns ------- manager : object datafs.managers.MongoDBManager or datafs.managers.DynamoDBManager object initialized with *args, **kwargs Examples -------- Generate a dynamo manager: .. code-block:: python >>> mgr = APIConstructor._generate_manager({ ... 'class': 'DynamoDBManager', ... 'kwargs': { ... 'table_name': 'data-from-yaml', ... 'session_args': { ... 'aws_access_key_id': "access-key-id-of-your-choice", ... 'aws_secret_access_key': "secret-key-of-your-choice"}, ... 'resource_args': { ... 'endpoint_url':'http://localhost:8000/', ... 'region_name':'us-east-1'} ... } ... }) >>> >>> from datafs.managers.manager_dynamo import DynamoDBManager >>> assert isinstance(mgr, DynamoDBManager) >>> >>> 'data-from-yaml' in mgr.table_names False >>> mgr.create_archive_table('data-from-yaml') >>> 'data-from-yaml' in mgr.table_names True >>> mgr.delete_table('data-from-yaml') ''' if 'class' not in manager_config: raise ValueError( 'Manager not fully specified. Give ' '"class:manager_name", e.g. "class:MongoDBManager".') mgr_class_name = manager_config['class'] if mgr_class_name.lower()[:5] == 'mongo': from datafs.managers.manager_mongo import ( MongoDBManager as mgr_class) elif mgr_class_name.lower()[:6] == 'dynamo': from datafs.managers.manager_dynamo import ( DynamoDBManager as mgr_class) else: raise KeyError( 'Manager class "{}" not recognized. Choose from {}'.format( mgr_class_name, 'MongoDBManager or DynamoDBManager')) manager = mgr_class( *manager_config.get('args', []), **manager_config.get('kwargs', {})) return manager
python
def _generate_manager(manager_config): ''' Generate a manager from a manager_config dictionary Parameters ---------- manager_config : dict Configuration with keys class, args, and kwargs used to generate a new datafs.manager object Returns ------- manager : object datafs.managers.MongoDBManager or datafs.managers.DynamoDBManager object initialized with *args, **kwargs Examples -------- Generate a dynamo manager: .. code-block:: python >>> mgr = APIConstructor._generate_manager({ ... 'class': 'DynamoDBManager', ... 'kwargs': { ... 'table_name': 'data-from-yaml', ... 'session_args': { ... 'aws_access_key_id': "access-key-id-of-your-choice", ... 'aws_secret_access_key': "secret-key-of-your-choice"}, ... 'resource_args': { ... 'endpoint_url':'http://localhost:8000/', ... 'region_name':'us-east-1'} ... } ... }) >>> >>> from datafs.managers.manager_dynamo import DynamoDBManager >>> assert isinstance(mgr, DynamoDBManager) >>> >>> 'data-from-yaml' in mgr.table_names False >>> mgr.create_archive_table('data-from-yaml') >>> 'data-from-yaml' in mgr.table_names True >>> mgr.delete_table('data-from-yaml') ''' if 'class' not in manager_config: raise ValueError( 'Manager not fully specified. Give ' '"class:manager_name", e.g. "class:MongoDBManager".') mgr_class_name = manager_config['class'] if mgr_class_name.lower()[:5] == 'mongo': from datafs.managers.manager_mongo import ( MongoDBManager as mgr_class) elif mgr_class_name.lower()[:6] == 'dynamo': from datafs.managers.manager_dynamo import ( DynamoDBManager as mgr_class) else: raise KeyError( 'Manager class "{}" not recognized. Choose from {}'.format( mgr_class_name, 'MongoDBManager or DynamoDBManager')) manager = mgr_class( *manager_config.get('args', []), **manager_config.get('kwargs', {})) return manager
[ "def", "_generate_manager", "(", "manager_config", ")", ":", "if", "'class'", "not", "in", "manager_config", ":", "raise", "ValueError", "(", "'Manager not fully specified. Give '", "'\"class:manager_name\", e.g. \"class:MongoDBManager\".'", ")", "mgr_class_name", "=", "manag...
Generate a manager from a manager_config dictionary Parameters ---------- manager_config : dict Configuration with keys class, args, and kwargs used to generate a new datafs.manager object Returns ------- manager : object datafs.managers.MongoDBManager or datafs.managers.DynamoDBManager object initialized with *args, **kwargs Examples -------- Generate a dynamo manager: .. code-block:: python >>> mgr = APIConstructor._generate_manager({ ... 'class': 'DynamoDBManager', ... 'kwargs': { ... 'table_name': 'data-from-yaml', ... 'session_args': { ... 'aws_access_key_id': "access-key-id-of-your-choice", ... 'aws_secret_access_key': "secret-key-of-your-choice"}, ... 'resource_args': { ... 'endpoint_url':'http://localhost:8000/', ... 'region_name':'us-east-1'} ... } ... }) >>> >>> from datafs.managers.manager_dynamo import DynamoDBManager >>> assert isinstance(mgr, DynamoDBManager) >>> >>> 'data-from-yaml' in mgr.table_names False >>> mgr.create_archive_table('data-from-yaml') >>> 'data-from-yaml' in mgr.table_names True >>> mgr.delete_table('data-from-yaml')
[ "Generate", "a", "manager", "from", "a", "manager_config", "dictionary" ]
train
https://github.com/ClimateImpactLab/DataFS/blob/0d32c2b4e18d300a11b748a552f6adbc3dd8f59d/datafs/config/constructor.py#L47-L122
ClimateImpactLab/DataFS
datafs/config/constructor.py
APIConstructor._generate_service
def _generate_service(service_config): ''' Generate a service from a service_config dictionary Parameters ---------- service_config : dict Configuration with keys service, args, and kwargs used to generate a new fs service object Returns ------- service : object fs service object initialized with *args, **kwargs Examples -------- Generate a temporary filesystem (no arguments required): .. code-block:: python >>> tmp = APIConstructor._generate_service( ... {'service': 'TempFS'}) ... >>> from fs.tempfs import TempFS >>> assert isinstance(tmp, TempFS) >>> import os >>> assert os.path.isdir(tmp.getsyspath('/')) >>> tmp.close() Generate a system filesystem in a temporary directory: .. code-block:: python >>> import tempfile >>> tempdir = tempfile.mkdtemp() >>> local = APIConstructor._generate_service( ... { ... 'service': 'OSFS', ... 'args': [tempdir] ... }) ... >>> from fs.osfs import OSFS >>> assert isinstance(local, OSFS) >>> import os >>> assert os.path.isdir(local.getsyspath('/')) >>> local.close() >>> import shutil >>> shutil.rmtree(tempdir) Mock an S3 filesystem with moto: .. code-block:: python >>> import moto >>> m = moto.mock_s3() >>> m.start() >>> s3 = APIConstructor._generate_service( ... { ... 'service': 'S3FS', ... 'args': ['bucket-name'], ... 'kwargs': { ... 'aws_access_key':'MY_KEY', ... 'aws_secret_key':'MY_SECRET_KEY' ... } ... }) ... >>> from fs.s3fs import S3FS >>> assert isinstance(s3, S3FS) >>> m.stop() ''' filesystems = [] for _, modname, _ in pkgutil.iter_modules(fs.__path__): if modname.endswith('fs'): filesystems.append(modname) service_mod_name = service_config['service'].lower() assert_msg = 'Filesystem "{}" not found in pyFilesystem {}'.format( service_mod_name, fs.__version__) assert service_mod_name in filesystems, assert_msg svc_module = importlib.import_module('fs.{}'.format(service_mod_name)) svc_class = svc_module.__dict__[service_config['service']] service = svc_class(*service_config.get('args', []), **service_config.get('kwargs', {})) return service
python
def _generate_service(service_config): ''' Generate a service from a service_config dictionary Parameters ---------- service_config : dict Configuration with keys service, args, and kwargs used to generate a new fs service object Returns ------- service : object fs service object initialized with *args, **kwargs Examples -------- Generate a temporary filesystem (no arguments required): .. code-block:: python >>> tmp = APIConstructor._generate_service( ... {'service': 'TempFS'}) ... >>> from fs.tempfs import TempFS >>> assert isinstance(tmp, TempFS) >>> import os >>> assert os.path.isdir(tmp.getsyspath('/')) >>> tmp.close() Generate a system filesystem in a temporary directory: .. code-block:: python >>> import tempfile >>> tempdir = tempfile.mkdtemp() >>> local = APIConstructor._generate_service( ... { ... 'service': 'OSFS', ... 'args': [tempdir] ... }) ... >>> from fs.osfs import OSFS >>> assert isinstance(local, OSFS) >>> import os >>> assert os.path.isdir(local.getsyspath('/')) >>> local.close() >>> import shutil >>> shutil.rmtree(tempdir) Mock an S3 filesystem with moto: .. code-block:: python >>> import moto >>> m = moto.mock_s3() >>> m.start() >>> s3 = APIConstructor._generate_service( ... { ... 'service': 'S3FS', ... 'args': ['bucket-name'], ... 'kwargs': { ... 'aws_access_key':'MY_KEY', ... 'aws_secret_key':'MY_SECRET_KEY' ... } ... }) ... >>> from fs.s3fs import S3FS >>> assert isinstance(s3, S3FS) >>> m.stop() ''' filesystems = [] for _, modname, _ in pkgutil.iter_modules(fs.__path__): if modname.endswith('fs'): filesystems.append(modname) service_mod_name = service_config['service'].lower() assert_msg = 'Filesystem "{}" not found in pyFilesystem {}'.format( service_mod_name, fs.__version__) assert service_mod_name in filesystems, assert_msg svc_module = importlib.import_module('fs.{}'.format(service_mod_name)) svc_class = svc_module.__dict__[service_config['service']] service = svc_class(*service_config.get('args', []), **service_config.get('kwargs', {})) return service
[ "def", "_generate_service", "(", "service_config", ")", ":", "filesystems", "=", "[", "]", "for", "_", ",", "modname", ",", "_", "in", "pkgutil", ".", "iter_modules", "(", "fs", ".", "__path__", ")", ":", "if", "modname", ".", "endswith", "(", "'fs'", ...
Generate a service from a service_config dictionary Parameters ---------- service_config : dict Configuration with keys service, args, and kwargs used to generate a new fs service object Returns ------- service : object fs service object initialized with *args, **kwargs Examples -------- Generate a temporary filesystem (no arguments required): .. code-block:: python >>> tmp = APIConstructor._generate_service( ... {'service': 'TempFS'}) ... >>> from fs.tempfs import TempFS >>> assert isinstance(tmp, TempFS) >>> import os >>> assert os.path.isdir(tmp.getsyspath('/')) >>> tmp.close() Generate a system filesystem in a temporary directory: .. code-block:: python >>> import tempfile >>> tempdir = tempfile.mkdtemp() >>> local = APIConstructor._generate_service( ... { ... 'service': 'OSFS', ... 'args': [tempdir] ... }) ... >>> from fs.osfs import OSFS >>> assert isinstance(local, OSFS) >>> import os >>> assert os.path.isdir(local.getsyspath('/')) >>> local.close() >>> import shutil >>> shutil.rmtree(tempdir) Mock an S3 filesystem with moto: .. code-block:: python >>> import moto >>> m = moto.mock_s3() >>> m.start() >>> s3 = APIConstructor._generate_service( ... { ... 'service': 'S3FS', ... 'args': ['bucket-name'], ... 'kwargs': { ... 'aws_access_key':'MY_KEY', ... 'aws_secret_key':'MY_SECRET_KEY' ... } ... }) ... >>> from fs.s3fs import S3FS >>> assert isinstance(s3, S3FS) >>> m.stop()
[ "Generate", "a", "service", "from", "a", "service_config", "dictionary" ]
train
https://github.com/ClimateImpactLab/DataFS/blob/0d32c2b4e18d300a11b748a552f6adbc3dd8f59d/datafs/config/constructor.py#L125-L224
pletzer/pnumpy
src/pnStencilOperator.py
StencilOperator.addStencilBranch
def addStencilBranch(self, disp, weight): """ Set or overwrite the stencil weight for the given direction @param disp displacement vector @param weight stencil weight """ self.stencil[tuple(disp)] = weight self.__setPartionLogic(disp)
python
def addStencilBranch(self, disp, weight): """ Set or overwrite the stencil weight for the given direction @param disp displacement vector @param weight stencil weight """ self.stencil[tuple(disp)] = weight self.__setPartionLogic(disp)
[ "def", "addStencilBranch", "(", "self", ",", "disp", ",", "weight", ")", ":", "self", ".", "stencil", "[", "tuple", "(", "disp", ")", "]", "=", "weight", "self", ".", "__setPartionLogic", "(", "disp", ")" ]
Set or overwrite the stencil weight for the given direction @param disp displacement vector @param weight stencil weight
[ "Set", "or", "overwrite", "the", "stencil", "weight", "for", "the", "given", "direction" ]
train
https://github.com/pletzer/pnumpy/blob/9e6d308be94a42637466b91ab1a7b4d64b4c29ae/src/pnStencilOperator.py#L41-L48
pletzer/pnumpy
src/pnStencilOperator.py
StencilOperator.apply
def apply(self, localArray): """ Apply stencil to data @param localArray local array @return new array on local proc """ # input dist array inp = daZeros(localArray.shape, localArray.dtype) inp[...] = localArray inp.setComm(self.comm) # output array out = numpy.zeros(localArray.shape, localArray.dtype) # expose the dist array windows for disp, dpi in self.dpis.items(): srcs = dpi['srcs'] remoteWinIds = dpi['remoteWinIds'] numParts = len(srcs) for i in range(numParts): inp.expose(srcs[i], winID=remoteWinIds[i]) # apply the stencil for disp, weight in self.stencil.items(): dpi = self.dpis[disp] dpi = self.dpis[disp] srcs = dpi['srcs'] dsts = dpi['dsts'] remoteRanks = dpi['remoteRanks'] remoteWinIds = dpi['remoteWinIds'] numParts = len(srcs) for i in range(numParts): srcSlce = srcs[i] dstSlce = dsts[i] remoteRank = remoteRanks[i] remoteWinId = remoteWinIds[i] # now apply the stencil if remoteRank == self.myRank: # local updates out[dstSlce] += weight*inp[srcSlce] else: # remote fetch out[dstSlce] += weight*inp.getData(remoteRank, remoteWinId) # some implementations require this inp.free() return out
python
def apply(self, localArray): """ Apply stencil to data @param localArray local array @return new array on local proc """ # input dist array inp = daZeros(localArray.shape, localArray.dtype) inp[...] = localArray inp.setComm(self.comm) # output array out = numpy.zeros(localArray.shape, localArray.dtype) # expose the dist array windows for disp, dpi in self.dpis.items(): srcs = dpi['srcs'] remoteWinIds = dpi['remoteWinIds'] numParts = len(srcs) for i in range(numParts): inp.expose(srcs[i], winID=remoteWinIds[i]) # apply the stencil for disp, weight in self.stencil.items(): dpi = self.dpis[disp] dpi = self.dpis[disp] srcs = dpi['srcs'] dsts = dpi['dsts'] remoteRanks = dpi['remoteRanks'] remoteWinIds = dpi['remoteWinIds'] numParts = len(srcs) for i in range(numParts): srcSlce = srcs[i] dstSlce = dsts[i] remoteRank = remoteRanks[i] remoteWinId = remoteWinIds[i] # now apply the stencil if remoteRank == self.myRank: # local updates out[dstSlce] += weight*inp[srcSlce] else: # remote fetch out[dstSlce] += weight*inp.getData(remoteRank, remoteWinId) # some implementations require this inp.free() return out
[ "def", "apply", "(", "self", ",", "localArray", ")", ":", "# input dist array", "inp", "=", "daZeros", "(", "localArray", ".", "shape", ",", "localArray", ".", "dtype", ")", "inp", "[", "...", "]", "=", "localArray", "inp", ".", "setComm", "(", "self", ...
Apply stencil to data @param localArray local array @return new array on local proc
[ "Apply", "stencil", "to", "data" ]
train
https://github.com/pletzer/pnumpy/blob/9e6d308be94a42637466b91ab1a7b4d64b4c29ae/src/pnStencilOperator.py#L85-L138
pletzer/pnumpy
src/pnMultiArrayIter.py
MultiArrayIter.getIndicesFromBigIndex
def getIndicesFromBigIndex(self, bigIndex): """ Get index set from given big index @param bigIndex @return index set @note no checks are performed to ensure that the returned big index is valid """ indices = numpy.array([0 for i in range(self.ndims)]) for i in range(self.ndims): indices[i] = bigIndex // self.dimProd[i] % self.dims[i] return indices
python
def getIndicesFromBigIndex(self, bigIndex): """ Get index set from given big index @param bigIndex @return index set @note no checks are performed to ensure that the returned big index is valid """ indices = numpy.array([0 for i in range(self.ndims)]) for i in range(self.ndims): indices[i] = bigIndex // self.dimProd[i] % self.dims[i] return indices
[ "def", "getIndicesFromBigIndex", "(", "self", ",", "bigIndex", ")", ":", "indices", "=", "numpy", ".", "array", "(", "[", "0", "for", "i", "in", "range", "(", "self", ".", "ndims", ")", "]", ")", "for", "i", "in", "range", "(", "self", ".", "ndims"...
Get index set from given big index @param bigIndex @return index set @note no checks are performed to ensure that the returned big index is valid
[ "Get", "index", "set", "from", "given", "big", "index" ]
train
https://github.com/pletzer/pnumpy/blob/9e6d308be94a42637466b91ab1a7b4d64b4c29ae/src/pnMultiArrayIter.py#L61-L72
pletzer/pnumpy
src/pnMultiArrayIter.py
MultiArrayIter.getBigIndexFromIndices
def getBigIndexFromIndices(self, indices): """ Get the big index from a given set of indices @param indices @return big index @note no checks are performed to ensure that the returned indices are valid """ return reduce(operator.add, [self.dimProd[i]*indices[i] for i in range(self.ndims)], 0)
python
def getBigIndexFromIndices(self, indices): """ Get the big index from a given set of indices @param indices @return big index @note no checks are performed to ensure that the returned indices are valid """ return reduce(operator.add, [self.dimProd[i]*indices[i] for i in range(self.ndims)], 0)
[ "def", "getBigIndexFromIndices", "(", "self", ",", "indices", ")", ":", "return", "reduce", "(", "operator", ".", "add", ",", "[", "self", ".", "dimProd", "[", "i", "]", "*", "indices", "[", "i", "]", "for", "i", "in", "range", "(", "self", ".", "n...
Get the big index from a given set of indices @param indices @return big index @note no checks are performed to ensure that the returned indices are valid
[ "Get", "the", "big", "index", "from", "a", "given", "set", "of", "indices" ]
train
https://github.com/pletzer/pnumpy/blob/9e6d308be94a42637466b91ab1a7b4d64b4c29ae/src/pnMultiArrayIter.py#L74-L83
pletzer/pnumpy
src/pnMultiArrayIter.py
MultiArrayIter.areIndicesValid
def areIndicesValid(self, inds): """ Test if indices are valid @param inds index set @return True if valid, False otherwise """ return reduce(operator.and_, [0 <= inds[d] < self.dims[d] for d in range(self.ndims)], True)
python
def areIndicesValid(self, inds): """ Test if indices are valid @param inds index set @return True if valid, False otherwise """ return reduce(operator.and_, [0 <= inds[d] < self.dims[d] for d in range(self.ndims)], True)
[ "def", "areIndicesValid", "(", "self", ",", "inds", ")", ":", "return", "reduce", "(", "operator", ".", "and_", ",", "[", "0", "<=", "inds", "[", "d", "]", "<", "self", ".", "dims", "[", "d", "]", "for", "d", "in", "range", "(", "self", ".", "n...
Test if indices are valid @param inds index set @return True if valid, False otherwise
[ "Test", "if", "indices", "are", "valid" ]
train
https://github.com/pletzer/pnumpy/blob/9e6d308be94a42637466b91ab1a7b4d64b4c29ae/src/pnMultiArrayIter.py#L106-L113
orcasgit/django-template-field
templatefield/settings.py
get_setting
def get_setting(setting): """ Get the specified django setting, or it's default value """ defaults = { # The context to use for rendering fields 'TEMPLATE_FIELD_CONTEXT': {}, # When this is False, don't do any TemplateField rendering 'TEMPLATE_FIELD_RENDER': True } try: return getattr(settings, setting, defaults[setting]) except KeyError: msg = "{0} is not specified in your settings".format(setting) raise ImproperlyConfigured(msg)
python
def get_setting(setting): """ Get the specified django setting, or it's default value """ defaults = { # The context to use for rendering fields 'TEMPLATE_FIELD_CONTEXT': {}, # When this is False, don't do any TemplateField rendering 'TEMPLATE_FIELD_RENDER': True } try: return getattr(settings, setting, defaults[setting]) except KeyError: msg = "{0} is not specified in your settings".format(setting) raise ImproperlyConfigured(msg)
[ "def", "get_setting", "(", "setting", ")", ":", "defaults", "=", "{", "# The context to use for rendering fields", "'TEMPLATE_FIELD_CONTEXT'", ":", "{", "}", ",", "# When this is False, don't do any TemplateField rendering", "'TEMPLATE_FIELD_RENDER'", ":", "True", "}", "try",...
Get the specified django setting, or it's default value
[ "Get", "the", "specified", "django", "setting", "or", "it", "s", "default", "value" ]
train
https://github.com/orcasgit/django-template-field/blob/1b72f1767edb3cfbb70fbcf07fa39a974995961c/templatefield/settings.py#L5-L17
GildedHonour/harvest-api-client
harvest_api_client/harvest.py
Invoice.csv_line_items
def csv_line_items(self): ''' Invoices from lists omit csv-line-items ''' if not hasattr(self, '_csv_line_items'): url = '{}/{}'.format(self.base_url, self.id) self._csv_line_items = self.harvest._get_element_values(url, self.element_name).next().get('csv-line-items', '') return self._csv_line_items
python
def csv_line_items(self): ''' Invoices from lists omit csv-line-items ''' if not hasattr(self, '_csv_line_items'): url = '{}/{}'.format(self.base_url, self.id) self._csv_line_items = self.harvest._get_element_values(url, self.element_name).next().get('csv-line-items', '') return self._csv_line_items
[ "def", "csv_line_items", "(", "self", ")", ":", "if", "not", "hasattr", "(", "self", ",", "'_csv_line_items'", ")", ":", "url", "=", "'{}/{}'", ".", "format", "(", "self", ".", "base_url", ",", "self", ".", "id", ")", "self", ".", "_csv_line_items", "=...
Invoices from lists omit csv-line-items
[ "Invoices", "from", "lists", "omit", "csv", "-", "line", "-", "items" ]
train
https://github.com/GildedHonour/harvest-api-client/blob/82ff51c51dc081ae6116131ae28b3d3bee16674e/harvest_api_client/harvest.py#L157-L165
GildedHonour/harvest-api-client
harvest_api_client/harvest.py
Harvest._create_getters
def _create_getters(self, klass): ''' This method creates both the singular and plural getters for various Harvest object classes. ''' flag_name = '_got_' + klass.element_name cache_name = '_' + klass.element_name setattr(self, cache_name, {}) setattr(self, flag_name, False) cache = getattr(self, cache_name) def _get_item(id): if id in cache: return cache[id] else: url = '{}/{}'.format(klass.base_url, id) item = self._get_element_values(url, klass.element_name).next() item = klass(self, item) cache[id] = item return item setattr(self, klass.element_name, _get_item) def _get_items(): if getattr(self, flag_name): for item in cache.values(): yield item else: for element in self._get_element_values(klass.base_url, klass.element_name): item = klass(self, element) cache[item.id] = item yield item setattr(self, flag_name, True) setattr(self, klass.plural_name, _get_items)
python
def _create_getters(self, klass): ''' This method creates both the singular and plural getters for various Harvest object classes. ''' flag_name = '_got_' + klass.element_name cache_name = '_' + klass.element_name setattr(self, cache_name, {}) setattr(self, flag_name, False) cache = getattr(self, cache_name) def _get_item(id): if id in cache: return cache[id] else: url = '{}/{}'.format(klass.base_url, id) item = self._get_element_values(url, klass.element_name).next() item = klass(self, item) cache[id] = item return item setattr(self, klass.element_name, _get_item) def _get_items(): if getattr(self, flag_name): for item in cache.values(): yield item else: for element in self._get_element_values(klass.base_url, klass.element_name): item = klass(self, element) cache[item.id] = item yield item setattr(self, flag_name, True) setattr(self, klass.plural_name, _get_items)
[ "def", "_create_getters", "(", "self", ",", "klass", ")", ":", "flag_name", "=", "'_got_'", "+", "klass", ".", "element_name", "cache_name", "=", "'_'", "+", "klass", ".", "element_name", "setattr", "(", "self", ",", "cache_name", ",", "{", "}", ")", "se...
This method creates both the singular and plural getters for various Harvest object classes.
[ "This", "method", "creates", "both", "the", "singular", "and", "plural", "getters", "for", "various", "Harvest", "object", "classes", "." ]
train
https://github.com/GildedHonour/harvest-api-client/blob/82ff51c51dc081ae6116131ae28b3d3bee16674e/harvest_api_client/harvest.py#L188-L224
carter-j-h/iterable-python-wrapper
iterablepythonwrapper/client.py
IterableApi.api_call
def api_call(self, call, method, params=None, headers=None, data=None, json=None): """ This is our generic api call function. We will route all calls except requests that do not return JSON ('Export' and 'Experiment Metrics' are examples where this is the case). This is beneficial because: 1. Allows for easier debugging if a request fails 2. Currently, Iterable only needs the API key from a security standpoint. In the future, if it were to require an access token for each request we could easily manage the granting and expiration management of such a token. """ # params(optional) Dictionary or bytes to be sent in the query string for the Request. if params is None: params = {} # data- dict or list of tuples to be sent in body of Request if data is None: data = {} # json- data to be sent in body of Request if json is None: json ={} # make the request following the 'requests.request' method r = requests.request(method=method, url=self.base_uri+call, params=params, headers=self.headers, data=data, json=json) response = { "body": r.json(), "code": r.status_code, "headers": r.headers, "url": r.url } return response
python
def api_call(self, call, method, params=None, headers=None, data=None, json=None): """ This is our generic api call function. We will route all calls except requests that do not return JSON ('Export' and 'Experiment Metrics' are examples where this is the case). This is beneficial because: 1. Allows for easier debugging if a request fails 2. Currently, Iterable only needs the API key from a security standpoint. In the future, if it were to require an access token for each request we could easily manage the granting and expiration management of such a token. """ # params(optional) Dictionary or bytes to be sent in the query string for the Request. if params is None: params = {} # data- dict or list of tuples to be sent in body of Request if data is None: data = {} # json- data to be sent in body of Request if json is None: json ={} # make the request following the 'requests.request' method r = requests.request(method=method, url=self.base_uri+call, params=params, headers=self.headers, data=data, json=json) response = { "body": r.json(), "code": r.status_code, "headers": r.headers, "url": r.url } return response
[ "def", "api_call", "(", "self", ",", "call", ",", "method", ",", "params", "=", "None", ",", "headers", "=", "None", ",", "data", "=", "None", ",", "json", "=", "None", ")", ":", "# params(optional) Dictionary or bytes to be sent in the query string for the Reques...
This is our generic api call function. We will route all calls except requests that do not return JSON ('Export' and 'Experiment Metrics' are examples where this is the case). This is beneficial because: 1. Allows for easier debugging if a request fails 2. Currently, Iterable only needs the API key from a security standpoint. In the future, if it were to require an access token for each request we could easily manage the granting and expiration management of such a token.
[ "This", "is", "our", "generic", "api", "call", "function", ".", "We", "will", "route", "all", "calls", "except", "requests", "that", "do", "not", "return", "JSON", "(", "Export", "and", "Experiment", "Metrics", "are", "examples", "where", "this", "is", "th...
train
https://github.com/carter-j-h/iterable-python-wrapper/blob/10d5db034ddfdfc3333efeee07fc9228b6a998c4/iterablepythonwrapper/client.py#L36-L71
carter-j-h/iterable-python-wrapper
iterablepythonwrapper/client.py
IterableApi.track_purchase
def track_purchase(self, user, items, total, purchase_id= None, campaign_id=None, template_id=None, created_at=None, data_fields=None): """ The 'purchase_id' argument maps to 'id' for this API endpoint. This name is used to distinguish it from other instances where 'id' is a part of the API request with other Iterable endpoints. """ call="/api/commerce/trackPurchase" payload ={} if isinstance(user, dict): payload["user"]= user else: raise TypeError('user key is not in Dictionary format') if isinstance(items, list): payload["items"]= items else: raise TypeError('items are not in Array format') if isinstance(total, float): payload["total"]= total else: raise TypeError('total is not in correct format') if purchase_id is not None: payload["id"]= str(purchase_id) if campaign_id is not None: payload["campaignId"]= campaign_id if template_id is not None: payload["templateId"]= template_id if created_at is not None: payload["createdAt"]= created_at if data_fields is not None: payload["data_fields"]= data_fields return self.api_call(call=call, method="POST", json=payload)
python
def track_purchase(self, user, items, total, purchase_id= None, campaign_id=None, template_id=None, created_at=None, data_fields=None): """ The 'purchase_id' argument maps to 'id' for this API endpoint. This name is used to distinguish it from other instances where 'id' is a part of the API request with other Iterable endpoints. """ call="/api/commerce/trackPurchase" payload ={} if isinstance(user, dict): payload["user"]= user else: raise TypeError('user key is not in Dictionary format') if isinstance(items, list): payload["items"]= items else: raise TypeError('items are not in Array format') if isinstance(total, float): payload["total"]= total else: raise TypeError('total is not in correct format') if purchase_id is not None: payload["id"]= str(purchase_id) if campaign_id is not None: payload["campaignId"]= campaign_id if template_id is not None: payload["templateId"]= template_id if created_at is not None: payload["createdAt"]= created_at if data_fields is not None: payload["data_fields"]= data_fields return self.api_call(call=call, method="POST", json=payload)
[ "def", "track_purchase", "(", "self", ",", "user", ",", "items", ",", "total", ",", "purchase_id", "=", "None", ",", "campaign_id", "=", "None", ",", "template_id", "=", "None", ",", "created_at", "=", "None", ",", "data_fields", "=", "None", ")", ":", ...
The 'purchase_id' argument maps to 'id' for this API endpoint. This name is used to distinguish it from other instances where 'id' is a part of the API request with other Iterable endpoints.
[ "The", "purchase_id", "argument", "maps", "to", "id", "for", "this", "API", "endpoint", ".", "This", "name", "is", "used", "to", "distinguish", "it", "from", "other", "instances", "where", "id", "is", "a", "part", "of", "the", "API", "request", "with", "...
train
https://github.com/carter-j-h/iterable-python-wrapper/blob/10d5db034ddfdfc3333efeee07fc9228b6a998c4/iterablepythonwrapper/client.py#L212-L255
carter-j-h/iterable-python-wrapper
iterablepythonwrapper/client.py
IterableApi.get_experiment_metrics
def get_experiment_metrics(self, path, return_response_object= None, experiment_id=None, campaign_id=None, start_date_time=None, end_date_time=None ): """ This endpoint doesn't return a JSON object, instead it returns a series of rows, each its own object. Given this setup, it makes sense to treat it how we handle our Bulk Export reqeusts. Arguments: path: the directory on your computer you wish the file to be downloaded into. return_response_object: recommended to be set to 'False'. If set to 'True', will just return the response object as defined by the 'python-requests' module. """ call="/api/experiments/metrics" if isinstance(return_response_object, bool) is False: raise ValueError("'return_iterator_object'parameter must be a boolean") payload={} if experiment_id is not None: payload["experimentId"]=experiment_id if campaign_id is not None: payload["campaignId"]=campaign_id if start_date_time is not None: payload["startDateTime"]=start_date_time if end_date_time is not None: payload["endDateTime"]=end_date_time return self.export_data_api(call=call, path=path, params=payload)
python
def get_experiment_metrics(self, path, return_response_object= None, experiment_id=None, campaign_id=None, start_date_time=None, end_date_time=None ): """ This endpoint doesn't return a JSON object, instead it returns a series of rows, each its own object. Given this setup, it makes sense to treat it how we handle our Bulk Export reqeusts. Arguments: path: the directory on your computer you wish the file to be downloaded into. return_response_object: recommended to be set to 'False'. If set to 'True', will just return the response object as defined by the 'python-requests' module. """ call="/api/experiments/metrics" if isinstance(return_response_object, bool) is False: raise ValueError("'return_iterator_object'parameter must be a boolean") payload={} if experiment_id is not None: payload["experimentId"]=experiment_id if campaign_id is not None: payload["campaignId"]=campaign_id if start_date_time is not None: payload["startDateTime"]=start_date_time if end_date_time is not None: payload["endDateTime"]=end_date_time return self.export_data_api(call=call, path=path, params=payload)
[ "def", "get_experiment_metrics", "(", "self", ",", "path", ",", "return_response_object", "=", "None", ",", "experiment_id", "=", "None", ",", "campaign_id", "=", "None", ",", "start_date_time", "=", "None", ",", "end_date_time", "=", "None", ")", ":", "call",...
This endpoint doesn't return a JSON object, instead it returns a series of rows, each its own object. Given this setup, it makes sense to treat it how we handle our Bulk Export reqeusts. Arguments: path: the directory on your computer you wish the file to be downloaded into. return_response_object: recommended to be set to 'False'. If set to 'True', will just return the response object as defined by the 'python-requests' module.
[ "This", "endpoint", "doesn", "t", "return", "a", "JSON", "object", "instead", "it", "returns", "a", "series", "of", "rows", "each", "its", "own", "object", ".", "Given", "this", "setup", "it", "makes", "sense", "to", "treat", "it", "how", "we", "handle",...
train
https://github.com/carter-j-h/iterable-python-wrapper/blob/10d5db034ddfdfc3333efeee07fc9228b6a998c4/iterablepythonwrapper/client.py#L495-L531
carter-j-h/iterable-python-wrapper
iterablepythonwrapper/client.py
IterableApi.export_data_json
def export_data_json(self, return_response_object, chunk_size=1024, path=None, data_type_name=None, date_range=None, delimiter=None, start_date_time=None, end_date_time=None, omit_fields=None, only_fields=None, campaign_id=None): """ Custom Keyword arguments: 1. return_response_object: if set to 'True', the 'r' response object will be returned. The benefit of this is that you can manipulate the data in any way you want. If set to false, we will write the response to a file where each Iterable activity you're exporting is a single-line JSON object. 2. chunk_size: Chunk size is used as a paremeter in the r.iter_content(chunk_size) method that controls how big the response chunks are (in bytes). Depending on the device used to make the request, this might change depending on the user. Default is set to 1 MB. 3. path: Allows you to choose the directory where the file is downloaded into. Example: "/Users/username/Desktop/" If not set the file will download into the current directory. """ call="/api/export/data.json" # make sure correct ranges are being used date_ranges = ["Today", "Yesterday", "BeforeToday", "All"] if isinstance(return_response_object, bool) is False: raise ValueError("'return_iterator_object'parameter must be a boolean") if chunk_size is not None and isinstance(chunk_size, int): pass else: raise ValueError("'chunk_size' parameter must be a integer") payload={} if data_type_name is not None: payload["dataTypeName"]= data_type_name if date_range is not None and date_range in date_ranges: payload["range"]= date_range if start_date_time is not None: payload["startDateTime"]= start_date_time if end_date_time is not None: payload["endDateTime"]= end_date_time if omit_fields is not None: payload["omitFields"]= omit_fields if only_fields is not None and isinstance(only_fields, list): payload["onlyFields"]= only_fields if campaign_id is not None: payload["campaignId"]= campaign_id return self.export_data_api(call=call, chunk_size=chunk_size, params=payload, path=path, return_response_object=return_response_object)
python
def export_data_json(self, return_response_object, chunk_size=1024, path=None, data_type_name=None, date_range=None, delimiter=None, start_date_time=None, end_date_time=None, omit_fields=None, only_fields=None, campaign_id=None): """ Custom Keyword arguments: 1. return_response_object: if set to 'True', the 'r' response object will be returned. The benefit of this is that you can manipulate the data in any way you want. If set to false, we will write the response to a file where each Iterable activity you're exporting is a single-line JSON object. 2. chunk_size: Chunk size is used as a paremeter in the r.iter_content(chunk_size) method that controls how big the response chunks are (in bytes). Depending on the device used to make the request, this might change depending on the user. Default is set to 1 MB. 3. path: Allows you to choose the directory where the file is downloaded into. Example: "/Users/username/Desktop/" If not set the file will download into the current directory. """ call="/api/export/data.json" # make sure correct ranges are being used date_ranges = ["Today", "Yesterday", "BeforeToday", "All"] if isinstance(return_response_object, bool) is False: raise ValueError("'return_iterator_object'parameter must be a boolean") if chunk_size is not None and isinstance(chunk_size, int): pass else: raise ValueError("'chunk_size' parameter must be a integer") payload={} if data_type_name is not None: payload["dataTypeName"]= data_type_name if date_range is not None and date_range in date_ranges: payload["range"]= date_range if start_date_time is not None: payload["startDateTime"]= start_date_time if end_date_time is not None: payload["endDateTime"]= end_date_time if omit_fields is not None: payload["omitFields"]= omit_fields if only_fields is not None and isinstance(only_fields, list): payload["onlyFields"]= only_fields if campaign_id is not None: payload["campaignId"]= campaign_id return self.export_data_api(call=call, chunk_size=chunk_size, params=payload, path=path, return_response_object=return_response_object)
[ "def", "export_data_json", "(", "self", ",", "return_response_object", ",", "chunk_size", "=", "1024", ",", "path", "=", "None", ",", "data_type_name", "=", "None", ",", "date_range", "=", "None", ",", "delimiter", "=", "None", ",", "start_date_time", "=", "...
Custom Keyword arguments: 1. return_response_object: if set to 'True', the 'r' response object will be returned. The benefit of this is that you can manipulate the data in any way you want. If set to false, we will write the response to a file where each Iterable activity you're exporting is a single-line JSON object. 2. chunk_size: Chunk size is used as a paremeter in the r.iter_content(chunk_size) method that controls how big the response chunks are (in bytes). Depending on the device used to make the request, this might change depending on the user. Default is set to 1 MB. 3. path: Allows you to choose the directory where the file is downloaded into. Example: "/Users/username/Desktop/" If not set the file will download into the current directory.
[ "Custom", "Keyword", "arguments", ":" ]
train
https://github.com/carter-j-h/iterable-python-wrapper/blob/10d5db034ddfdfc3333efeee07fc9228b6a998c4/iterablepythonwrapper/client.py#L575-L640
carter-j-h/iterable-python-wrapper
iterablepythonwrapper/client.py
IterableApi.delete_user_by_email
def delete_user_by_email(self, email): """ This call will delete a user from the Iterable database. This call requires a path parameter to be passed in, 'email' in this case, which is why we're just adding this to the 'call' argument that goes into the 'api_call' request. """ call = "/api/users/"+ str(email) return self.api_call(call=call, method="DELETE")
python
def delete_user_by_email(self, email): """ This call will delete a user from the Iterable database. This call requires a path parameter to be passed in, 'email' in this case, which is why we're just adding this to the 'call' argument that goes into the 'api_call' request. """ call = "/api/users/"+ str(email) return self.api_call(call=call, method="DELETE")
[ "def", "delete_user_by_email", "(", "self", ",", "email", ")", ":", "call", "=", "\"/api/users/\"", "+", "str", "(", "email", ")", "return", "self", ".", "api_call", "(", "call", "=", "call", ",", "method", "=", "\"DELETE\"", ")" ]
This call will delete a user from the Iterable database. This call requires a path parameter to be passed in, 'email' in this case, which is why we're just adding this to the 'call' argument that goes into the 'api_call' request.
[ "This", "call", "will", "delete", "a", "user", "from", "the", "Iterable", "database", ".", "This", "call", "requires", "a", "path", "parameter", "to", "be", "passed", "in", "email", "in", "this", "case", "which", "is", "why", "we", "re", "just", "adding"...
train
https://github.com/carter-j-h/iterable-python-wrapper/blob/10d5db034ddfdfc3333efeee07fc9228b6a998c4/iterablepythonwrapper/client.py#L1358-L1368
carter-j-h/iterable-python-wrapper
iterablepythonwrapper/client.py
IterableApi.get_user_by_email
def get_user_by_email(self, email): """This function gets a user's data field and info""" call = "/api/users/"+ str(email) return self.api_call(call=call, method="GET")
python
def get_user_by_email(self, email): """This function gets a user's data field and info""" call = "/api/users/"+ str(email) return self.api_call(call=call, method="GET")
[ "def", "get_user_by_email", "(", "self", ",", "email", ")", ":", "call", "=", "\"/api/users/\"", "+", "str", "(", "email", ")", "return", "self", ".", "api_call", "(", "call", "=", "call", ",", "method", "=", "\"GET\"", ")" ]
This function gets a user's data field and info
[ "This", "function", "gets", "a", "user", "s", "data", "field", "and", "info" ]
train
https://github.com/carter-j-h/iterable-python-wrapper/blob/10d5db034ddfdfc3333efeee07fc9228b6a998c4/iterablepythonwrapper/client.py#L1370-L1375
carter-j-h/iterable-python-wrapper
iterablepythonwrapper/client.py
IterableApi.bulk_update_user
def bulk_update_user(self, users): """ The Iterable 'Bulk User Update' api Bulk update user data or adds it if does not exist. Data is merged - missing fields are not deleted The body of the request takes 1 keys: 1. users -- in the form of an array -- which is the list of users that we're updating in sets of 50 users at a time, which is the most that can be batched in a single request. """ call = "/api/users/bulkUpdate" payload = {} if isinstance(users, list): payload["users"] = users else: raise TypeError ('users are not in Arrary format') return self.api_call(call=call, method="POST", json=payload)
python
def bulk_update_user(self, users): """ The Iterable 'Bulk User Update' api Bulk update user data or adds it if does not exist. Data is merged - missing fields are not deleted The body of the request takes 1 keys: 1. users -- in the form of an array -- which is the list of users that we're updating in sets of 50 users at a time, which is the most that can be batched in a single request. """ call = "/api/users/bulkUpdate" payload = {} if isinstance(users, list): payload["users"] = users else: raise TypeError ('users are not in Arrary format') return self.api_call(call=call, method="POST", json=payload)
[ "def", "bulk_update_user", "(", "self", ",", "users", ")", ":", "call", "=", "\"/api/users/bulkUpdate\"", "payload", "=", "{", "}", "if", "isinstance", "(", "users", ",", "list", ")", ":", "payload", "[", "\"users\"", "]", "=", "users", "else", ":", "rai...
The Iterable 'Bulk User Update' api Bulk update user data or adds it if does not exist. Data is merged - missing fields are not deleted The body of the request takes 1 keys: 1. users -- in the form of an array -- which is the list of users that we're updating in sets of 50 users at a time, which is the most that can be batched in a single request.
[ "The", "Iterable", "Bulk", "User", "Update", "api", "Bulk", "update", "user", "data", "or", "adds", "it", "if", "does", "not", "exist", ".", "Data", "is", "merged", "-", "missing", "fields", "are", "not", "deleted" ]
train
https://github.com/carter-j-h/iterable-python-wrapper/blob/10d5db034ddfdfc3333efeee07fc9228b6a998c4/iterablepythonwrapper/client.py#L1377-L1398
carter-j-h/iterable-python-wrapper
iterablepythonwrapper/client.py
IterableApi.disable_device
def disable_device(self, token, email=None, user_id=None): """ This request manually disable pushes to a device until it comes online again. """ call = "/api/users/disableDevice" payload ={} payload["token"] = str(token) if email is not None: payload["email"] = str(email) if user_id is not None: payload["userId"] = str(user_id) return self.api_call(call= call, method="POST", json=payload)
python
def disable_device(self, token, email=None, user_id=None): """ This request manually disable pushes to a device until it comes online again. """ call = "/api/users/disableDevice" payload ={} payload["token"] = str(token) if email is not None: payload["email"] = str(email) if user_id is not None: payload["userId"] = str(user_id) return self.api_call(call= call, method="POST", json=payload)
[ "def", "disable_device", "(", "self", ",", "token", ",", "email", "=", "None", ",", "user_id", "=", "None", ")", ":", "call", "=", "\"/api/users/disableDevice\"", "payload", "=", "{", "}", "payload", "[", "\"token\"", "]", "=", "str", "(", "token", ")", ...
This request manually disable pushes to a device until it comes online again.
[ "This", "request", "manually", "disable", "pushes", "to", "a", "device", "until", "it", "comes", "online", "again", "." ]
train
https://github.com/carter-j-h/iterable-python-wrapper/blob/10d5db034ddfdfc3333efeee07fc9228b6a998c4/iterablepythonwrapper/client.py#L1435-L1454
carter-j-h/iterable-python-wrapper
iterablepythonwrapper/client.py
IterableApi.update_user
def update_user(self, email=None, data_fields=None, user_id=None, prefer_userId= None, merge_nested_objects=None): """ The Iterable 'User Update' api updates a user profile with new data fields. Missing fields are not deleted and new data is merged. The body of the request takes 4 keys: 1. email-- in the form of a string -- used as the unique identifier by the Iterable database. 2. data fields-- in the form of an object-- these are the additional attributes of the user that we want to add or update 3. userId- in the form of a string-- another field we can use as a lookup of the user. 4. mergeNestedObjects-- in the form of an object-- used to merge top level objects instead of overwriting. """ call = "/api/users/update" payload = {} if email is not None: payload["email"] = str(email) if data_fields is not None: payload["dataFields"] = data_fields if user_id is not None: payload["userId"] = str(user_id) if prefer_userId is not None: payload["preferUserId"]= prefer_userId if merge_nested_objects is not None: payload["mergeNestedObjects"] = merge_nested_objects return self.api_call(call=call, method="POST", json=payload)
python
def update_user(self, email=None, data_fields=None, user_id=None, prefer_userId= None, merge_nested_objects=None): """ The Iterable 'User Update' api updates a user profile with new data fields. Missing fields are not deleted and new data is merged. The body of the request takes 4 keys: 1. email-- in the form of a string -- used as the unique identifier by the Iterable database. 2. data fields-- in the form of an object-- these are the additional attributes of the user that we want to add or update 3. userId- in the form of a string-- another field we can use as a lookup of the user. 4. mergeNestedObjects-- in the form of an object-- used to merge top level objects instead of overwriting. """ call = "/api/users/update" payload = {} if email is not None: payload["email"] = str(email) if data_fields is not None: payload["dataFields"] = data_fields if user_id is not None: payload["userId"] = str(user_id) if prefer_userId is not None: payload["preferUserId"]= prefer_userId if merge_nested_objects is not None: payload["mergeNestedObjects"] = merge_nested_objects return self.api_call(call=call, method="POST", json=payload)
[ "def", "update_user", "(", "self", ",", "email", "=", "None", ",", "data_fields", "=", "None", ",", "user_id", "=", "None", ",", "prefer_userId", "=", "None", ",", "merge_nested_objects", "=", "None", ")", ":", "call", "=", "\"/api/users/update\"", "payload"...
The Iterable 'User Update' api updates a user profile with new data fields. Missing fields are not deleted and new data is merged. The body of the request takes 4 keys: 1. email-- in the form of a string -- used as the unique identifier by the Iterable database. 2. data fields-- in the form of an object-- these are the additional attributes of the user that we want to add or update 3. userId- in the form of a string-- another field we can use as a lookup of the user. 4. mergeNestedObjects-- in the form of an object-- used to merge top level objects instead of overwriting.
[ "The", "Iterable", "User", "Update", "api", "updates", "a", "user", "profile", "with", "new", "data", "fields", ".", "Missing", "fields", "are", "not", "deleted", "and", "new", "data", "is", "merged", "." ]
train
https://github.com/carter-j-h/iterable-python-wrapper/blob/10d5db034ddfdfc3333efeee07fc9228b6a998c4/iterablepythonwrapper/client.py#L1543-L1580
ClimateImpactLab/DataFS
datafs/datafs.py
cli
def cli( ctx, config_file=None, requirements=None, profile=None): ''' An abstraction layer for data storage systems DataFS is a package manager for data. It manages file versions, dependencies, and metadata for individual use or large organizations. For more information, see the docs at https://datafs.readthedocs.io ''' ctx.obj = _DataFSInterface() ctx.obj.config_file = config_file ctx.obj.requirements = requirements ctx.obj.profile = profile def teardown(): if hasattr(ctx.obj, 'api'): ctx.obj.api.close() ctx.call_on_close(teardown)
python
def cli( ctx, config_file=None, requirements=None, profile=None): ''' An abstraction layer for data storage systems DataFS is a package manager for data. It manages file versions, dependencies, and metadata for individual use or large organizations. For more information, see the docs at https://datafs.readthedocs.io ''' ctx.obj = _DataFSInterface() ctx.obj.config_file = config_file ctx.obj.requirements = requirements ctx.obj.profile = profile def teardown(): if hasattr(ctx.obj, 'api'): ctx.obj.api.close() ctx.call_on_close(teardown)
[ "def", "cli", "(", "ctx", ",", "config_file", "=", "None", ",", "requirements", "=", "None", ",", "profile", "=", "None", ")", ":", "ctx", ".", "obj", "=", "_DataFSInterface", "(", ")", "ctx", ".", "obj", ".", "config_file", "=", "config_file", "ctx", ...
An abstraction layer for data storage systems DataFS is a package manager for data. It manages file versions, dependencies, and metadata for individual use or large organizations. For more information, see the docs at https://datafs.readthedocs.io
[ "An", "abstraction", "layer", "for", "data", "storage", "systems" ]
train
https://github.com/ClimateImpactLab/DataFS/blob/0d32c2b4e18d300a11b748a552f6adbc3dd8f59d/datafs/datafs.py#L96-L120
ClimateImpactLab/DataFS
datafs/datafs.py
configure
def configure(ctx, helper, edit): ''' Update configuration ''' ctx.obj.config = ConfigFile(ctx.obj.config_file) if edit: ctx.obj.config.edit_config_file() return if os.path.isfile(ctx.obj.config.config_file): ctx.obj.config.read_config() if ctx.obj.profile is None: ctx.obj.profile = ctx.obj.config.default_profile args, kwargs = _parse_args_and_kwargs(ctx.args) assert len(args) == 0, 'Unrecognized arguments: "{}"'.format(args) if ctx.obj.profile not in ctx.obj.config.config['profiles']: ctx.obj.config.config['profiles'][ctx.obj.profile] = { 'api': {'user_config': {}}, 'manager': {}, 'authorities': {}} profile_config = ctx.obj.config.config['profiles'][ctx.obj.profile] profile_config['api']['user_config'].update(kwargs) ctx.obj.config.write_config(ctx.obj.config_file) _generate_api(ctx) if ctx.obj.api.manager is not None: check_requirements( to_populate=profile_config['api']['user_config'], prompts=ctx.obj.api.manager.required_user_config, helper=helper) ctx.obj.config.write_config(ctx.obj.config_file)
python
def configure(ctx, helper, edit): ''' Update configuration ''' ctx.obj.config = ConfigFile(ctx.obj.config_file) if edit: ctx.obj.config.edit_config_file() return if os.path.isfile(ctx.obj.config.config_file): ctx.obj.config.read_config() if ctx.obj.profile is None: ctx.obj.profile = ctx.obj.config.default_profile args, kwargs = _parse_args_and_kwargs(ctx.args) assert len(args) == 0, 'Unrecognized arguments: "{}"'.format(args) if ctx.obj.profile not in ctx.obj.config.config['profiles']: ctx.obj.config.config['profiles'][ctx.obj.profile] = { 'api': {'user_config': {}}, 'manager': {}, 'authorities': {}} profile_config = ctx.obj.config.config['profiles'][ctx.obj.profile] profile_config['api']['user_config'].update(kwargs) ctx.obj.config.write_config(ctx.obj.config_file) _generate_api(ctx) if ctx.obj.api.manager is not None: check_requirements( to_populate=profile_config['api']['user_config'], prompts=ctx.obj.api.manager.required_user_config, helper=helper) ctx.obj.config.write_config(ctx.obj.config_file)
[ "def", "configure", "(", "ctx", ",", "helper", ",", "edit", ")", ":", "ctx", ".", "obj", ".", "config", "=", "ConfigFile", "(", "ctx", ".", "obj", ".", "config_file", ")", "if", "edit", ":", "ctx", ".", "obj", ".", "config", ".", "edit_config_file", ...
Update configuration
[ "Update", "configuration" ]
train
https://github.com/ClimateImpactLab/DataFS/blob/0d32c2b4e18d300a11b748a552f6adbc3dd8f59d/datafs/datafs.py#L130-L167
ClimateImpactLab/DataFS
datafs/datafs.py
create
def create( ctx, archive_name, authority_name, versioned=True, tag=None, helper=False): ''' Create an archive ''' tags = list(tag) _generate_api(ctx) args, kwargs = _parse_args_and_kwargs(ctx.args) assert len(args) == 0, 'Unrecognized arguments: "{}"'.format(args) var = ctx.obj.api.create( archive_name, authority_name=authority_name, versioned=versioned, metadata=kwargs, tags=tags, helper=helper) verstring = 'versioned archive' if versioned else 'archive' click.echo('created {} {}'.format(verstring, var))
python
def create( ctx, archive_name, authority_name, versioned=True, tag=None, helper=False): ''' Create an archive ''' tags = list(tag) _generate_api(ctx) args, kwargs = _parse_args_and_kwargs(ctx.args) assert len(args) == 0, 'Unrecognized arguments: "{}"'.format(args) var = ctx.obj.api.create( archive_name, authority_name=authority_name, versioned=versioned, metadata=kwargs, tags=tags, helper=helper) verstring = 'versioned archive' if versioned else 'archive' click.echo('created {} {}'.format(verstring, var))
[ "def", "create", "(", "ctx", ",", "archive_name", ",", "authority_name", ",", "versioned", "=", "True", ",", "tag", "=", "None", ",", "helper", "=", "False", ")", ":", "tags", "=", "list", "(", "tag", ")", "_generate_api", "(", "ctx", ")", "args", ",...
Create an archive
[ "Create", "an", "archive" ]
train
https://github.com/ClimateImpactLab/DataFS/blob/0d32c2b4e18d300a11b748a552f6adbc3dd8f59d/datafs/datafs.py#L181-L207
ClimateImpactLab/DataFS
datafs/datafs.py
update
def update( ctx, archive_name, bumpversion='patch', prerelease=None, dependency=None, message=None, string=False, file=None): ''' Update an archive with new contents ''' _generate_api(ctx) args, kwargs = _parse_args_and_kwargs(ctx.args) assert len(args) == 0, 'Unrecognized arguments: "{}"'.format(args) dependencies_dict = _parse_dependencies(dependency) var = ctx.obj.api.get_archive(archive_name) latest_version = var.get_latest_version() if string: with var.open( 'w+', bumpversion=bumpversion, prerelease=prerelease, dependencies=dependencies_dict, metadata=kwargs, message=message) as f: if file is None: for line in sys.stdin: f.write(u(line)) else: f.write(u(file)) else: if file is None: file = click.prompt('enter filepath') var.update( file, bumpversion=bumpversion, prerelease=prerelease, dependencies=dependencies_dict, metadata=kwargs, message=message) new_version = var.get_latest_version() if latest_version is None and new_version is not None: bumpmsg = ' new version {} created.'.format( new_version) elif new_version != latest_version: bumpmsg = ' version bumped {} --> {}.'.format( latest_version, new_version) elif var.versioned: bumpmsg = ' version remains {}.'.format(latest_version) else: bumpmsg = '' click.echo('uploaded data to {}.{}'.format(var, bumpmsg))
python
def update( ctx, archive_name, bumpversion='patch', prerelease=None, dependency=None, message=None, string=False, file=None): ''' Update an archive with new contents ''' _generate_api(ctx) args, kwargs = _parse_args_and_kwargs(ctx.args) assert len(args) == 0, 'Unrecognized arguments: "{}"'.format(args) dependencies_dict = _parse_dependencies(dependency) var = ctx.obj.api.get_archive(archive_name) latest_version = var.get_latest_version() if string: with var.open( 'w+', bumpversion=bumpversion, prerelease=prerelease, dependencies=dependencies_dict, metadata=kwargs, message=message) as f: if file is None: for line in sys.stdin: f.write(u(line)) else: f.write(u(file)) else: if file is None: file = click.prompt('enter filepath') var.update( file, bumpversion=bumpversion, prerelease=prerelease, dependencies=dependencies_dict, metadata=kwargs, message=message) new_version = var.get_latest_version() if latest_version is None and new_version is not None: bumpmsg = ' new version {} created.'.format( new_version) elif new_version != latest_version: bumpmsg = ' version bumped {} --> {}.'.format( latest_version, new_version) elif var.versioned: bumpmsg = ' version remains {}.'.format(latest_version) else: bumpmsg = '' click.echo('uploaded data to {}.{}'.format(var, bumpmsg))
[ "def", "update", "(", "ctx", ",", "archive_name", ",", "bumpversion", "=", "'patch'", ",", "prerelease", "=", "None", ",", "dependency", "=", "None", ",", "message", "=", "None", ",", "string", "=", "False", ",", "file", "=", "None", ")", ":", "_genera...
Update an archive with new contents
[ "Update", "an", "archive", "with", "new", "contents" ]
train
https://github.com/ClimateImpactLab/DataFS/blob/0d32c2b4e18d300a11b748a552f6adbc3dd8f59d/datafs/datafs.py#L223-L289
ClimateImpactLab/DataFS
datafs/datafs.py
update_metadata
def update_metadata(ctx, archive_name): ''' Update an archive's metadata ''' _generate_api(ctx) args, kwargs = _parse_args_and_kwargs(ctx.args) assert len(args) == 0, 'Unrecognized arguments: "{}"'.format(args) var = ctx.obj.api.get_archive(archive_name) var.update_metadata(metadata=kwargs)
python
def update_metadata(ctx, archive_name): ''' Update an archive's metadata ''' _generate_api(ctx) args, kwargs = _parse_args_and_kwargs(ctx.args) assert len(args) == 0, 'Unrecognized arguments: "{}"'.format(args) var = ctx.obj.api.get_archive(archive_name) var.update_metadata(metadata=kwargs)
[ "def", "update_metadata", "(", "ctx", ",", "archive_name", ")", ":", "_generate_api", "(", "ctx", ")", "args", ",", "kwargs", "=", "_parse_args_and_kwargs", "(", "ctx", ".", "args", ")", "assert", "len", "(", "args", ")", "==", "0", ",", "'Unrecognized arg...
Update an archive's metadata
[ "Update", "an", "archive", "s", "metadata" ]
train
https://github.com/ClimateImpactLab/DataFS/blob/0d32c2b4e18d300a11b748a552f6adbc3dd8f59d/datafs/datafs.py#L299-L310
ClimateImpactLab/DataFS
datafs/datafs.py
set_dependencies
def set_dependencies(ctx, archive_name, dependency=None): ''' Set the dependencies of an archive ''' _generate_api(ctx) kwargs = _parse_dependencies(dependency) var = ctx.obj.api.get_archive(archive_name) var.set_dependencies(dependencies=kwargs)
python
def set_dependencies(ctx, archive_name, dependency=None): ''' Set the dependencies of an archive ''' _generate_api(ctx) kwargs = _parse_dependencies(dependency) var = ctx.obj.api.get_archive(archive_name) var.set_dependencies(dependencies=kwargs)
[ "def", "set_dependencies", "(", "ctx", ",", "archive_name", ",", "dependency", "=", "None", ")", ":", "_generate_api", "(", "ctx", ")", "kwargs", "=", "_parse_dependencies", "(", "dependency", ")", "var", "=", "ctx", ".", "obj", ".", "api", ".", "get_archi...
Set the dependencies of an archive
[ "Set", "the", "dependencies", "of", "an", "archive" ]
train
https://github.com/ClimateImpactLab/DataFS/blob/0d32c2b4e18d300a11b748a552f6adbc3dd8f59d/datafs/datafs.py#L321-L331
ClimateImpactLab/DataFS
datafs/datafs.py
get_dependencies
def get_dependencies(ctx, archive_name, version): ''' List the dependencies of an archive ''' _generate_api(ctx) var = ctx.obj.api.get_archive(archive_name) deps = [] dependencies = var.get_dependencies(version=version) for arch, dep in dependencies.items(): if dep is None: deps.append(arch) else: deps.append('{}=={}'.format(arch, dep)) click.echo('\n'.join(deps))
python
def get_dependencies(ctx, archive_name, version): ''' List the dependencies of an archive ''' _generate_api(ctx) var = ctx.obj.api.get_archive(archive_name) deps = [] dependencies = var.get_dependencies(version=version) for arch, dep in dependencies.items(): if dep is None: deps.append(arch) else: deps.append('{}=={}'.format(arch, dep)) click.echo('\n'.join(deps))
[ "def", "get_dependencies", "(", "ctx", ",", "archive_name", ",", "version", ")", ":", "_generate_api", "(", "ctx", ")", "var", "=", "ctx", ".", "obj", ".", "api", ".", "get_archive", "(", "archive_name", ")", "deps", "=", "[", "]", "dependencies", "=", ...
List the dependencies of an archive
[ "List", "the", "dependencies", "of", "an", "archive" ]
train
https://github.com/ClimateImpactLab/DataFS/blob/0d32c2b4e18d300a11b748a552f6adbc3dd8f59d/datafs/datafs.py#L342-L360
ClimateImpactLab/DataFS
datafs/datafs.py
add_tags
def add_tags(ctx, archive_name, tags): ''' Add tags to an archive ''' _generate_api(ctx) var = ctx.obj.api.get_archive(archive_name) var.add_tags(*tags)
python
def add_tags(ctx, archive_name, tags): ''' Add tags to an archive ''' _generate_api(ctx) var = ctx.obj.api.get_archive(archive_name) var.add_tags(*tags)
[ "def", "add_tags", "(", "ctx", ",", "archive_name", ",", "tags", ")", ":", "_generate_api", "(", "ctx", ")", "var", "=", "ctx", ".", "obj", ".", "api", ".", "get_archive", "(", "archive_name", ")", "var", ".", "add_tags", "(", "*", "tags", ")" ]
Add tags to an archive
[ "Add", "tags", "to", "an", "archive" ]
train
https://github.com/ClimateImpactLab/DataFS/blob/0d32c2b4e18d300a11b748a552f6adbc3dd8f59d/datafs/datafs.py#L367-L376
ClimateImpactLab/DataFS
datafs/datafs.py
get_tags
def get_tags(ctx, archive_name): ''' Print tags assigned to an archive ''' _generate_api(ctx) var = ctx.obj.api.get_archive(archive_name) click.echo(' '.join(var.get_tags()), nl=False) print('')
python
def get_tags(ctx, archive_name): ''' Print tags assigned to an archive ''' _generate_api(ctx) var = ctx.obj.api.get_archive(archive_name) click.echo(' '.join(var.get_tags()), nl=False) print('')
[ "def", "get_tags", "(", "ctx", ",", "archive_name", ")", ":", "_generate_api", "(", "ctx", ")", "var", "=", "ctx", ".", "obj", ".", "api", ".", "get_archive", "(", "archive_name", ")", "click", ".", "echo", "(", "' '", ".", "join", "(", "var", ".", ...
Print tags assigned to an archive
[ "Print", "tags", "assigned", "to", "an", "archive" ]
train
https://github.com/ClimateImpactLab/DataFS/blob/0d32c2b4e18d300a11b748a552f6adbc3dd8f59d/datafs/datafs.py#L398-L408
ClimateImpactLab/DataFS
datafs/datafs.py
download
def download(ctx, archive_name, filepath, version): ''' Download an archive ''' _generate_api(ctx) var = ctx.obj.api.get_archive(archive_name) if version is None: version = var.get_default_version() var.download(filepath, version=version) archstr = var.archive_name +\ '' if (not var.versioned) else ' v{}'.format(version) click.echo('downloaded{} to {}'.format(archstr, filepath))
python
def download(ctx, archive_name, filepath, version): ''' Download an archive ''' _generate_api(ctx) var = ctx.obj.api.get_archive(archive_name) if version is None: version = var.get_default_version() var.download(filepath, version=version) archstr = var.archive_name +\ '' if (not var.versioned) else ' v{}'.format(version) click.echo('downloaded{} to {}'.format(archstr, filepath))
[ "def", "download", "(", "ctx", ",", "archive_name", ",", "filepath", ",", "version", ")", ":", "_generate_api", "(", "ctx", ")", "var", "=", "ctx", ".", "obj", ".", "api", ".", "get_archive", "(", "archive_name", ")", "if", "version", "is", "None", ":"...
Download an archive
[ "Download", "an", "archive" ]
train
https://github.com/ClimateImpactLab/DataFS/blob/0d32c2b4e18d300a11b748a552f6adbc3dd8f59d/datafs/datafs.py#L416-L432
ClimateImpactLab/DataFS
datafs/datafs.py
cat
def cat(ctx, archive_name, version): ''' Echo the contents of an archive ''' _generate_api(ctx) var = ctx.obj.api.get_archive(archive_name) with var.open('r', version=version) as f: for chunk in iter(lambda: f.read(1024 * 1024), ''): click.echo(chunk)
python
def cat(ctx, archive_name, version): ''' Echo the contents of an archive ''' _generate_api(ctx) var = ctx.obj.api.get_archive(archive_name) with var.open('r', version=version) as f: for chunk in iter(lambda: f.read(1024 * 1024), ''): click.echo(chunk)
[ "def", "cat", "(", "ctx", ",", "archive_name", ",", "version", ")", ":", "_generate_api", "(", "ctx", ")", "var", "=", "ctx", ".", "obj", ".", "api", ".", "get_archive", "(", "archive_name", ")", "with", "var", ".", "open", "(", "'r'", ",", "version"...
Echo the contents of an archive
[ "Echo", "the", "contents", "of", "an", "archive" ]
train
https://github.com/ClimateImpactLab/DataFS/blob/0d32c2b4e18d300a11b748a552f6adbc3dd8f59d/datafs/datafs.py#L439-L449
ClimateImpactLab/DataFS
datafs/datafs.py
log
def log(ctx, archive_name): ''' Get the version log for an archive ''' _generate_api(ctx) ctx.obj.api.get_archive(archive_name).log()
python
def log(ctx, archive_name): ''' Get the version log for an archive ''' _generate_api(ctx) ctx.obj.api.get_archive(archive_name).log()
[ "def", "log", "(", "ctx", ",", "archive_name", ")", ":", "_generate_api", "(", "ctx", ")", "ctx", ".", "obj", ".", "api", ".", "get_archive", "(", "archive_name", ")", ".", "log", "(", ")" ]
Get the version log for an archive
[ "Get", "the", "version", "log", "for", "an", "archive" ]
train
https://github.com/ClimateImpactLab/DataFS/blob/0d32c2b4e18d300a11b748a552f6adbc3dd8f59d/datafs/datafs.py#L455-L461
ClimateImpactLab/DataFS
datafs/datafs.py
metadata
def metadata(ctx, archive_name): ''' Get an archive's metadata ''' _generate_api(ctx) var = ctx.obj.api.get_archive(archive_name) click.echo(pprint.pformat(var.get_metadata()))
python
def metadata(ctx, archive_name): ''' Get an archive's metadata ''' _generate_api(ctx) var = ctx.obj.api.get_archive(archive_name) click.echo(pprint.pformat(var.get_metadata()))
[ "def", "metadata", "(", "ctx", ",", "archive_name", ")", ":", "_generate_api", "(", "ctx", ")", "var", "=", "ctx", ".", "obj", ".", "api", ".", "get_archive", "(", "archive_name", ")", "click", ".", "echo", "(", "pprint", ".", "pformat", "(", "var", ...
Get an archive's metadata
[ "Get", "an", "archive", "s", "metadata" ]
train
https://github.com/ClimateImpactLab/DataFS/blob/0d32c2b4e18d300a11b748a552f6adbc3dd8f59d/datafs/datafs.py#L467-L474
ClimateImpactLab/DataFS
datafs/datafs.py
history
def history(ctx, archive_name): ''' Get archive history ''' _generate_api(ctx) var = ctx.obj.api.get_archive(archive_name) click.echo(pprint.pformat(var.get_history()))
python
def history(ctx, archive_name): ''' Get archive history ''' _generate_api(ctx) var = ctx.obj.api.get_archive(archive_name) click.echo(pprint.pformat(var.get_history()))
[ "def", "history", "(", "ctx", ",", "archive_name", ")", ":", "_generate_api", "(", "ctx", ")", "var", "=", "ctx", ".", "obj", ".", "api", ".", "get_archive", "(", "archive_name", ")", "click", ".", "echo", "(", "pprint", ".", "pformat", "(", "var", "...
Get archive history
[ "Get", "archive", "history" ]
train
https://github.com/ClimateImpactLab/DataFS/blob/0d32c2b4e18d300a11b748a552f6adbc3dd8f59d/datafs/datafs.py#L480-L487
ClimateImpactLab/DataFS
datafs/datafs.py
versions
def versions(ctx, archive_name): ''' Get an archive's versions ''' _generate_api(ctx) var = ctx.obj.api.get_archive(archive_name) click.echo(pprint.pformat(map(str, var.get_versions())))
python
def versions(ctx, archive_name): ''' Get an archive's versions ''' _generate_api(ctx) var = ctx.obj.api.get_archive(archive_name) click.echo(pprint.pformat(map(str, var.get_versions())))
[ "def", "versions", "(", "ctx", ",", "archive_name", ")", ":", "_generate_api", "(", "ctx", ")", "var", "=", "ctx", ".", "obj", ".", "api", ".", "get_archive", "(", "archive_name", ")", "click", ".", "echo", "(", "pprint", ".", "pformat", "(", "map", ...
Get an archive's versions
[ "Get", "an", "archive", "s", "versions" ]
train
https://github.com/ClimateImpactLab/DataFS/blob/0d32c2b4e18d300a11b748a552f6adbc3dd8f59d/datafs/datafs.py#L493-L501
ClimateImpactLab/DataFS
datafs/datafs.py
filter_archives
def filter_archives(ctx, prefix, pattern, engine): ''' List all archives matching filter criteria ''' _generate_api(ctx) # want to achieve behavior like click.echo(' '.join(matches)) for i, match in enumerate(ctx.obj.api.filter( pattern, engine, prefix=prefix)): click.echo(match, nl=False) print('')
python
def filter_archives(ctx, prefix, pattern, engine): ''' List all archives matching filter criteria ''' _generate_api(ctx) # want to achieve behavior like click.echo(' '.join(matches)) for i, match in enumerate(ctx.obj.api.filter( pattern, engine, prefix=prefix)): click.echo(match, nl=False) print('')
[ "def", "filter_archives", "(", "ctx", ",", "prefix", ",", "pattern", ",", "engine", ")", ":", "_generate_api", "(", "ctx", ")", "# want to achieve behavior like click.echo(' '.join(matches))", "for", "i", ",", "match", "in", "enumerate", "(", "ctx", ".", "obj", ...
List all archives matching filter criteria
[ "List", "all", "archives", "matching", "filter", "criteria" ]
train
https://github.com/ClimateImpactLab/DataFS/blob/0d32c2b4e18d300a11b748a552f6adbc3dd8f59d/datafs/datafs.py#L518-L531
ClimateImpactLab/DataFS
datafs/datafs.py
search
def search(ctx, tags, prefix=None): ''' List all archives matching tag search criteria ''' _generate_api(ctx) for i, match in enumerate(ctx.obj.api.search(*tags, prefix=prefix)): click.echo(match, nl=False) print('')
python
def search(ctx, tags, prefix=None): ''' List all archives matching tag search criteria ''' _generate_api(ctx) for i, match in enumerate(ctx.obj.api.search(*tags, prefix=prefix)): click.echo(match, nl=False) print('')
[ "def", "search", "(", "ctx", ",", "tags", ",", "prefix", "=", "None", ")", ":", "_generate_api", "(", "ctx", ")", "for", "i", ",", "match", "in", "enumerate", "(", "ctx", ".", "obj", ".", "api", ".", "search", "(", "*", "tags", ",", "prefix", "="...
List all archives matching tag search criteria
[ "List", "all", "archives", "matching", "tag", "search", "criteria" ]
train
https://github.com/ClimateImpactLab/DataFS/blob/0d32c2b4e18d300a11b748a552f6adbc3dd8f59d/datafs/datafs.py#L544-L554
ClimateImpactLab/DataFS
datafs/datafs.py
listdir
def listdir(ctx, location, authority_name=None): ''' List archive path components at a given location Note: When using listdir on versioned archives, listdir will provide the version numbers when a full archive path is supplied as the location argument. This is because DataFS stores the archive path as a directory and the versions as the actual files when versioning is on. Parameters ---------- location : str Path of the "directory" to search `location` can be a path relative to the authority root (e.g `/MyFiles/Data`) or can include authority as a protocol (e.g. `my_auth://MyFiles/Data`). If the authority is specified as a protocol, the `authority_name` argument is ignored. authority_name : str Name of the authority to search (optional) If no authority is specified, the default authority is used (if only one authority is attached or if :py:attr:`DefaultAuthorityName` is assigned). Returns ------- list Archive path components that exist at the given "directory" location on the specified authority Raises ------ ValueError A ValueError is raised if the authority is ambiguous or invalid ''' _generate_api(ctx) for path_component in ctx.obj.api.listdir( location, authority_name=authority_name): click.echo(path_component, nl=False) print('')
python
def listdir(ctx, location, authority_name=None): ''' List archive path components at a given location Note: When using listdir on versioned archives, listdir will provide the version numbers when a full archive path is supplied as the location argument. This is because DataFS stores the archive path as a directory and the versions as the actual files when versioning is on. Parameters ---------- location : str Path of the "directory" to search `location` can be a path relative to the authority root (e.g `/MyFiles/Data`) or can include authority as a protocol (e.g. `my_auth://MyFiles/Data`). If the authority is specified as a protocol, the `authority_name` argument is ignored. authority_name : str Name of the authority to search (optional) If no authority is specified, the default authority is used (if only one authority is attached or if :py:attr:`DefaultAuthorityName` is assigned). Returns ------- list Archive path components that exist at the given "directory" location on the specified authority Raises ------ ValueError A ValueError is raised if the authority is ambiguous or invalid ''' _generate_api(ctx) for path_component in ctx.obj.api.listdir( location, authority_name=authority_name): click.echo(path_component, nl=False) print('')
[ "def", "listdir", "(", "ctx", ",", "location", ",", "authority_name", "=", "None", ")", ":", "_generate_api", "(", "ctx", ")", "for", "path_component", "in", "ctx", ".", "obj", ".", "api", ".", "listdir", "(", "location", ",", "authority_name", "=", "aut...
List archive path components at a given location Note: When using listdir on versioned archives, listdir will provide the version numbers when a full archive path is supplied as the location argument. This is because DataFS stores the archive path as a directory and the versions as the actual files when versioning is on. Parameters ---------- location : str Path of the "directory" to search `location` can be a path relative to the authority root (e.g `/MyFiles/Data`) or can include authority as a protocol (e.g. `my_auth://MyFiles/Data`). If the authority is specified as a protocol, the `authority_name` argument is ignored. authority_name : str Name of the authority to search (optional) If no authority is specified, the default authority is used (if only one authority is attached or if :py:attr:`DefaultAuthorityName` is assigned). Returns ------- list Archive path components that exist at the given "directory" location on the specified authority Raises ------ ValueError A ValueError is raised if the authority is ambiguous or invalid
[ "List", "archive", "path", "components", "at", "a", "given", "location" ]
train
https://github.com/ClimateImpactLab/DataFS/blob/0d32c2b4e18d300a11b748a552f6adbc3dd8f59d/datafs/datafs.py#L565-L620
ClimateImpactLab/DataFS
datafs/datafs.py
delete
def delete(ctx, archive_name): ''' Delete an archive ''' _generate_api(ctx) var = ctx.obj.api.get_archive(archive_name) var.delete() click.echo('deleted archive {}'.format(var))
python
def delete(ctx, archive_name): ''' Delete an archive ''' _generate_api(ctx) var = ctx.obj.api.get_archive(archive_name) var.delete() click.echo('deleted archive {}'.format(var))
[ "def", "delete", "(", "ctx", ",", "archive_name", ")", ":", "_generate_api", "(", "ctx", ")", "var", "=", "ctx", ".", "obj", ".", "api", ".", "get_archive", "(", "archive_name", ")", "var", ".", "delete", "(", ")", "click", ".", "echo", "(", "'delete...
Delete an archive
[ "Delete", "an", "archive" ]
train
https://github.com/ClimateImpactLab/DataFS/blob/0d32c2b4e18d300a11b748a552f6adbc3dd8f59d/datafs/datafs.py#L626-L635
THLO/map
map/mapper.py
MapInputHandler.getDirectoryDictionary
def getDirectoryDictionary(self,args): """ This is an internal method to compute a dictionary containing all the directories that potentially contain (more) input. The dictionary 'table' indicates which of its contents are part of the input: table[directory] == 'ALL' means that its entire content must be mapped table[directory] == 'ext' means that only content with the extension 'ext' are mapped table[directory] == 'ext1,ext2' means that only content with either extension 'ext1' or 'ext2' are mapped Note that there is a special symbol MapConstants.placeholderNoExtensionFilter that enables the filtering for files without an extension. """ table = {} for element in args.path: # If the element is a directory, the dictionary entry is set to 'ALL': if os.path.isdir(element): if element not in table: table[element] = 'ALL' # If the element is a file, its extension is added to the dictionary entry: else: path = os.path.dirname(element) extension = os.path.splitext(element)[1] # If there is no extension, a '.' was missing. This happens when calling: # map -r [command] path/to/folder/*ext # and the folder 'folder' DOES NOT contain files with the extension 'ext'. # In this case, there is no wildcard expansion and we must create the # proper extension manually: if extension == '': extension = '.' + os.path.basename(element).split("*")[-1] if path not in table: table[path] = extension elif table[path] != 'ALL' and extension not in table[path]: table[path] = table[path] + "," + extension return table
python
def getDirectoryDictionary(self,args): """ This is an internal method to compute a dictionary containing all the directories that potentially contain (more) input. The dictionary 'table' indicates which of its contents are part of the input: table[directory] == 'ALL' means that its entire content must be mapped table[directory] == 'ext' means that only content with the extension 'ext' are mapped table[directory] == 'ext1,ext2' means that only content with either extension 'ext1' or 'ext2' are mapped Note that there is a special symbol MapConstants.placeholderNoExtensionFilter that enables the filtering for files without an extension. """ table = {} for element in args.path: # If the element is a directory, the dictionary entry is set to 'ALL': if os.path.isdir(element): if element not in table: table[element] = 'ALL' # If the element is a file, its extension is added to the dictionary entry: else: path = os.path.dirname(element) extension = os.path.splitext(element)[1] # If there is no extension, a '.' was missing. This happens when calling: # map -r [command] path/to/folder/*ext # and the folder 'folder' DOES NOT contain files with the extension 'ext'. # In this case, there is no wildcard expansion and we must create the # proper extension manually: if extension == '': extension = '.' + os.path.basename(element).split("*")[-1] if path not in table: table[path] = extension elif table[path] != 'ALL' and extension not in table[path]: table[path] = table[path] + "," + extension return table
[ "def", "getDirectoryDictionary", "(", "self", ",", "args", ")", ":", "table", "=", "{", "}", "for", "element", "in", "args", ".", "path", ":", "# If the element is a directory, the dictionary entry is set to 'ALL':", "if", "os", ".", "path", ".", "isdir", "(", "...
This is an internal method to compute a dictionary containing all the directories that potentially contain (more) input. The dictionary 'table' indicates which of its contents are part of the input: table[directory] == 'ALL' means that its entire content must be mapped table[directory] == 'ext' means that only content with the extension 'ext' are mapped table[directory] == 'ext1,ext2' means that only content with either extension 'ext1' or 'ext2' are mapped Note that there is a special symbol MapConstants.placeholderNoExtensionFilter that enables the filtering for files without an extension.
[ "This", "is", "an", "internal", "method", "to", "compute", "a", "dictionary", "containing", "all", "the", "directories", "that", "potentially", "contain", "(", "more", ")", "input", ".", "The", "dictionary", "table", "indicates", "which", "of", "its", "content...
train
https://github.com/THLO/map/blob/6c1571187662bbf2e66faaf96b11a3e151ed4c87/map/mapper.py#L27-L62
THLO/map
map/mapper.py
MapInputHandler.createListRecursively
def createListRecursively(self,args): """ This is an internal method to create the list of input files (or directories) recursively, starting at the provided directory or directories. """ resultList = [] dirDict = self.getDirectoryDictionary(args) for key in dirDict: for path,dirs,files in os.walk(key): # Walk through the directory to find al l input for d in dirs: resultList.append(os.path.join(path,d)) for f in files: # Append the file if 'ALL' are allowed or the extension is allowed pattern = dirDict[key].split(',') if 'ALL' in pattern or os.path.splitext(f)[1] in pattern: resultList.append(os.path.join(path,f)) return list(set(resultList))
python
def createListRecursively(self,args): """ This is an internal method to create the list of input files (or directories) recursively, starting at the provided directory or directories. """ resultList = [] dirDict = self.getDirectoryDictionary(args) for key in dirDict: for path,dirs,files in os.walk(key): # Walk through the directory to find al l input for d in dirs: resultList.append(os.path.join(path,d)) for f in files: # Append the file if 'ALL' are allowed or the extension is allowed pattern = dirDict[key].split(',') if 'ALL' in pattern or os.path.splitext(f)[1] in pattern: resultList.append(os.path.join(path,f)) return list(set(resultList))
[ "def", "createListRecursively", "(", "self", ",", "args", ")", ":", "resultList", "=", "[", "]", "dirDict", "=", "self", ".", "getDirectoryDictionary", "(", "args", ")", "for", "key", "in", "dirDict", ":", "for", "path", ",", "dirs", ",", "files", "in", ...
This is an internal method to create the list of input files (or directories) recursively, starting at the provided directory or directories.
[ "This", "is", "an", "internal", "method", "to", "create", "the", "list", "of", "input", "files", "(", "or", "directories", ")", "recursively", "starting", "at", "the", "provided", "directory", "or", "directories", "." ]
train
https://github.com/THLO/map/blob/6c1571187662bbf2e66faaf96b11a3e151ed4c87/map/mapper.py#L64-L79
THLO/map
map/mapper.py
MapInputHandler.createList
def createList(self,args): """ This is an internal method to create the list of input files (or directories) contained in the provided directory or directories. """ resultList = [] if len(args.path) == 1 and os.path.isdir(args.path[0]): resultList = [os.path.join(args.path[0], f) for f in os.listdir(args.path[0])] else: # If there are multiple items, wildcard expansion has already created the list of files resultList = args.path return list(set(resultList))
python
def createList(self,args): """ This is an internal method to create the list of input files (or directories) contained in the provided directory or directories. """ resultList = [] if len(args.path) == 1 and os.path.isdir(args.path[0]): resultList = [os.path.join(args.path[0], f) for f in os.listdir(args.path[0])] else: # If there are multiple items, wildcard expansion has already created the list of files resultList = args.path return list(set(resultList))
[ "def", "createList", "(", "self", ",", "args", ")", ":", "resultList", "=", "[", "]", "if", "len", "(", "args", ".", "path", ")", "==", "1", "and", "os", ".", "path", ".", "isdir", "(", "args", ".", "path", "[", "0", "]", ")", ":", "resultList"...
This is an internal method to create the list of input files (or directories) contained in the provided directory or directories.
[ "This", "is", "an", "internal", "method", "to", "create", "the", "list", "of", "input", "files", "(", "or", "directories", ")", "contained", "in", "the", "provided", "directory", "or", "directories", "." ]
train
https://github.com/THLO/map/blob/6c1571187662bbf2e66faaf96b11a3e151ed4c87/map/mapper.py#L81-L91
THLO/map
map/mapper.py
MapInputHandler.getExtensionList
def getExtensionList(self,extensions): """ This is an internal method that transforms the comma-separated extensions string into a list of extensions, e.g., "ext1,ext2,ext3" gets turned into ['.ext1','.ext2','.ext3']. If MapConstants.placeholderNoExtensionFilter is part of the string, the resulting list will also contain '', i.e., files without extensions are permitted. """ basicList = extensions.split(',') extensionList = [] for ext in basicList: if ext == MapConstants.placeholderNoExtensionFilter: # Files without an extension are permitted: extensionList.append('') elif ext != '': # The '.' is prepended if ext does not start with '.' already: extWithDot = ext if ext.startswith('.') else '.'+ext extensionList.append(extWithDot) return list(set(extensionList))
python
def getExtensionList(self,extensions): """ This is an internal method that transforms the comma-separated extensions string into a list of extensions, e.g., "ext1,ext2,ext3" gets turned into ['.ext1','.ext2','.ext3']. If MapConstants.placeholderNoExtensionFilter is part of the string, the resulting list will also contain '', i.e., files without extensions are permitted. """ basicList = extensions.split(',') extensionList = [] for ext in basicList: if ext == MapConstants.placeholderNoExtensionFilter: # Files without an extension are permitted: extensionList.append('') elif ext != '': # The '.' is prepended if ext does not start with '.' already: extWithDot = ext if ext.startswith('.') else '.'+ext extensionList.append(extWithDot) return list(set(extensionList))
[ "def", "getExtensionList", "(", "self", ",", "extensions", ")", ":", "basicList", "=", "extensions", ".", "split", "(", "','", ")", "extensionList", "=", "[", "]", "for", "ext", "in", "basicList", ":", "if", "ext", "==", "MapConstants", ".", "placeholderNo...
This is an internal method that transforms the comma-separated extensions string into a list of extensions, e.g., "ext1,ext2,ext3" gets turned into ['.ext1','.ext2','.ext3']. If MapConstants.placeholderNoExtensionFilter is part of the string, the resulting list will also contain '', i.e., files without extensions are permitted.
[ "This", "is", "an", "internal", "method", "that", "transforms", "the", "comma", "-", "separated", "extensions", "string", "into", "a", "list", "of", "extensions", "e", ".", "g", ".", "ext1", "ext2", "ext3", "gets", "turned", "into", "[", ".", "ext1", "."...
train
https://github.com/THLO/map/blob/6c1571187662bbf2e66faaf96b11a3e151ed4c87/map/mapper.py#L93-L110
THLO/map
map/mapper.py
MapInputHandler.getFiles
def getFiles(self,args): """ This is the main method of the class. Given the arguments, the corresponding list of all files (or directories if the -d option is used) are returned. """ fileList = [] if args.recursive: # The list is created by going through the folder(s) recursively: fileList = self.createListRecursively(args) else: # The list is created by going through the provided folder(s): fileList = self.createList(args) if args.directories: # If directories are returned, the list is sorted in reverse order. # This allows the processing of subfolders before the processing of the parent folder. # Processing the parent folder first may not work because the command may remove # or rename the folder, which would affect the subfolders. fileList = [element for element in fileList if os.path.isdir(element)] return sorted(fileList,reverse=True) else: # Filter out all directories: fileList = [element for element in fileList if os.path.isfile(element)] if args.extensions != None: # Files are filtered based on their extensions: extensionList = self.getExtensionList(args.extensions) fileList = [element for element in fileList if os.path.splitext(element)[1] in extensionList] # The files in the list are sorted in lexicographical order: return sorted(fileList)
python
def getFiles(self,args): """ This is the main method of the class. Given the arguments, the corresponding list of all files (or directories if the -d option is used) are returned. """ fileList = [] if args.recursive: # The list is created by going through the folder(s) recursively: fileList = self.createListRecursively(args) else: # The list is created by going through the provided folder(s): fileList = self.createList(args) if args.directories: # If directories are returned, the list is sorted in reverse order. # This allows the processing of subfolders before the processing of the parent folder. # Processing the parent folder first may not work because the command may remove # or rename the folder, which would affect the subfolders. fileList = [element for element in fileList if os.path.isdir(element)] return sorted(fileList,reverse=True) else: # Filter out all directories: fileList = [element for element in fileList if os.path.isfile(element)] if args.extensions != None: # Files are filtered based on their extensions: extensionList = self.getExtensionList(args.extensions) fileList = [element for element in fileList if os.path.splitext(element)[1] in extensionList] # The files in the list are sorted in lexicographical order: return sorted(fileList)
[ "def", "getFiles", "(", "self", ",", "args", ")", ":", "fileList", "=", "[", "]", "if", "args", ".", "recursive", ":", "# The list is created by going through the folder(s) recursively:", "fileList", "=", "self", ".", "createListRecursively", "(", "args", ")", "el...
This is the main method of the class. Given the arguments, the corresponding list of all files (or directories if the -d option is used) are returned.
[ "This", "is", "the", "main", "method", "of", "the", "class", ".", "Given", "the", "arguments", "the", "corresponding", "list", "of", "all", "files", "(", "or", "directories", "if", "the", "-", "d", "option", "is", "used", ")", "are", "returned", "." ]
train
https://github.com/THLO/map/blob/6c1571187662bbf2e66faaf96b11a3e151ed4c87/map/mapper.py#L112-L137