repo
stringlengths
7
55
path
stringlengths
4
127
func_name
stringlengths
1
88
original_string
stringlengths
75
19.8k
language
stringclasses
1 value
code
stringlengths
75
19.8k
code_tokens
listlengths
20
707
docstring
stringlengths
3
17.3k
docstring_tokens
listlengths
3
222
sha
stringlengths
40
40
url
stringlengths
87
242
partition
stringclasses
1 value
idx
int64
0
252k
jobovy/galpy
galpy/df/streamdf.py
streamdf._find_closest_trackpoint
def _find_closest_trackpoint(self,R,vR,vT,z,vz,phi,interp=True,xy=False, usev=False): """For backward compatibility""" return self.find_closest_trackpoint(R,vR,vT,z,vz,phi, interp=interp,xy=xy, usev=usev)
python
def _find_closest_trackpoint(self,R,vR,vT,z,vz,phi,interp=True,xy=False, usev=False): """For backward compatibility""" return self.find_closest_trackpoint(R,vR,vT,z,vz,phi, interp=interp,xy=xy, usev=usev)
[ "def", "_find_closest_trackpoint", "(", "self", ",", "R", ",", "vR", ",", "vT", ",", "z", ",", "vz", ",", "phi", ",", "interp", "=", "True", ",", "xy", "=", "False", ",", "usev", "=", "False", ")", ":", "return", "self", ".", "find_closest_trackpoint...
For backward compatibility
[ "For", "backward", "compatibility" ]
9c5b9fe65d58835624dffe432be282060918ee08
https://github.com/jobovy/galpy/blob/9c5b9fe65d58835624dffe432be282060918ee08/galpy/df/streamdf.py#L1556-L1561
train
27,900
jobovy/galpy
galpy/df/streamdf.py
streamdf._density_par
def _density_par(self,dangle,tdisrupt=None): """The raw density as a function of parallel angle""" if tdisrupt is None: tdisrupt= self._tdisrupt dOmin= dangle/tdisrupt # Normalize to 1 close to progenitor return 0.5\ *(1.+special.erf((self._meandO-dOmin)\ /numpy.sqrt(2.*self._sortedSigOEig[2])))
python
def _density_par(self,dangle,tdisrupt=None): """The raw density as a function of parallel angle""" if tdisrupt is None: tdisrupt= self._tdisrupt dOmin= dangle/tdisrupt # Normalize to 1 close to progenitor return 0.5\ *(1.+special.erf((self._meandO-dOmin)\ /numpy.sqrt(2.*self._sortedSigOEig[2])))
[ "def", "_density_par", "(", "self", ",", "dangle", ",", "tdisrupt", "=", "None", ")", ":", "if", "tdisrupt", "is", "None", ":", "tdisrupt", "=", "self", ".", "_tdisrupt", "dOmin", "=", "dangle", "/", "tdisrupt", "# Normalize to 1 close to progenitor", "return"...
The raw density as a function of parallel angle
[ "The", "raw", "density", "as", "a", "function", "of", "parallel", "angle" ]
9c5b9fe65d58835624dffe432be282060918ee08
https://github.com/jobovy/galpy/blob/9c5b9fe65d58835624dffe432be282060918ee08/galpy/df/streamdf.py#L1896-L1903
train
27,901
jobovy/galpy
galpy/df/streamdf.py
streamdf._sample_aAt
def _sample_aAt(self,n): """Sampling frequencies, angles, and times part of sampling""" #Sample frequency along largest eigenvalue using ARS dO1s=\ bovy_ars.bovy_ars([0.,0.],[True,False], [self._meandO-numpy.sqrt(self._sortedSigOEig[2]), self._meandO+numpy.sqrt(self._sortedSigOEig[2])], _h_ars,_hp_ars,nsamples=n, hxparams=(self._meandO,self._sortedSigOEig[2]), maxn=100) dO1s= numpy.array(dO1s)*self._sigMeanSign dO2s= numpy.random.normal(size=n)*numpy.sqrt(self._sortedSigOEig[1]) dO3s= numpy.random.normal(size=n)*numpy.sqrt(self._sortedSigOEig[0]) #Rotate into dOs in R,phi,z coordinates dO= numpy.vstack((dO3s,dO2s,dO1s)) dO= numpy.dot(self._sigomatrixEig[1][:,self._sigomatrixEigsortIndx], dO) Om= dO+numpy.tile(self._progenitor_Omega.T,(n,1)).T #Also generate angles da= numpy.random.normal(size=(3,n))*self._sigangle #And a random time dt= self.sample_t(n) #Integrate the orbits relative to the progenitor da+= dO*numpy.tile(dt,(3,1)) angle= da+numpy.tile(self._progenitor_angle.T,(n,1)).T return (Om,angle,dt)
python
def _sample_aAt(self,n): """Sampling frequencies, angles, and times part of sampling""" #Sample frequency along largest eigenvalue using ARS dO1s=\ bovy_ars.bovy_ars([0.,0.],[True,False], [self._meandO-numpy.sqrt(self._sortedSigOEig[2]), self._meandO+numpy.sqrt(self._sortedSigOEig[2])], _h_ars,_hp_ars,nsamples=n, hxparams=(self._meandO,self._sortedSigOEig[2]), maxn=100) dO1s= numpy.array(dO1s)*self._sigMeanSign dO2s= numpy.random.normal(size=n)*numpy.sqrt(self._sortedSigOEig[1]) dO3s= numpy.random.normal(size=n)*numpy.sqrt(self._sortedSigOEig[0]) #Rotate into dOs in R,phi,z coordinates dO= numpy.vstack((dO3s,dO2s,dO1s)) dO= numpy.dot(self._sigomatrixEig[1][:,self._sigomatrixEigsortIndx], dO) Om= dO+numpy.tile(self._progenitor_Omega.T,(n,1)).T #Also generate angles da= numpy.random.normal(size=(3,n))*self._sigangle #And a random time dt= self.sample_t(n) #Integrate the orbits relative to the progenitor da+= dO*numpy.tile(dt,(3,1)) angle= da+numpy.tile(self._progenitor_angle.T,(n,1)).T return (Om,angle,dt)
[ "def", "_sample_aAt", "(", "self", ",", "n", ")", ":", "#Sample frequency along largest eigenvalue using ARS", "dO1s", "=", "bovy_ars", ".", "bovy_ars", "(", "[", "0.", ",", "0.", "]", ",", "[", "True", ",", "False", "]", ",", "[", "self", ".", "_meandO", ...
Sampling frequencies, angles, and times part of sampling
[ "Sampling", "frequencies", "angles", "and", "times", "part", "of", "sampling" ]
9c5b9fe65d58835624dffe432be282060918ee08
https://github.com/jobovy/galpy/blob/9c5b9fe65d58835624dffe432be282060918ee08/galpy/df/streamdf.py#L3050-L3075
train
27,902
jobovy/galpy
galpy/actionAngle/actionAngle.py
actionAngle._check_consistent_units
def _check_consistent_units(self): """Internal function to check that the set of units for this object is consistent with that for the potential""" if isinstance(self._pot,list): if self._roSet and self._pot[0]._roSet: assert m.fabs(self._ro-self._pot[0]._ro) < 10.**-10., 'Physical conversion for the actionAngle object is not consistent with that of the Potential given to it' if self._voSet and self._pot[0]._voSet: assert m.fabs(self._vo-self._pot[0]._vo) < 10.**-10., 'Physical conversion for the actionAngle object is not consistent with that of the Potential given to it' else: if self._roSet and self._pot._roSet: assert m.fabs(self._ro-self._pot._ro) < 10.**-10., 'Physical conversion for the actionAngle object is not consistent with that of the Potential given to it' if self._voSet and self._pot._voSet: assert m.fabs(self._vo-self._pot._vo) < 10.**-10., 'Physical conversion for the actionAngle object is not consistent with that of the Potential given to it' return None
python
def _check_consistent_units(self): """Internal function to check that the set of units for this object is consistent with that for the potential""" if isinstance(self._pot,list): if self._roSet and self._pot[0]._roSet: assert m.fabs(self._ro-self._pot[0]._ro) < 10.**-10., 'Physical conversion for the actionAngle object is not consistent with that of the Potential given to it' if self._voSet and self._pot[0]._voSet: assert m.fabs(self._vo-self._pot[0]._vo) < 10.**-10., 'Physical conversion for the actionAngle object is not consistent with that of the Potential given to it' else: if self._roSet and self._pot._roSet: assert m.fabs(self._ro-self._pot._ro) < 10.**-10., 'Physical conversion for the actionAngle object is not consistent with that of the Potential given to it' if self._voSet and self._pot._voSet: assert m.fabs(self._vo-self._pot._vo) < 10.**-10., 'Physical conversion for the actionAngle object is not consistent with that of the Potential given to it' return None
[ "def", "_check_consistent_units", "(", "self", ")", ":", "if", "isinstance", "(", "self", ".", "_pot", ",", "list", ")", ":", "if", "self", ".", "_roSet", "and", "self", ".", "_pot", "[", "0", "]", ".", "_roSet", ":", "assert", "m", ".", "fabs", "(...
Internal function to check that the set of units for this object is consistent with that for the potential
[ "Internal", "function", "to", "check", "that", "the", "set", "of", "units", "for", "this", "object", "is", "consistent", "with", "that", "for", "the", "potential" ]
9c5b9fe65d58835624dffe432be282060918ee08
https://github.com/jobovy/galpy/blob/9c5b9fe65d58835624dffe432be282060918ee08/galpy/actionAngle/actionAngle.py#L71-L83
train
27,903
jobovy/galpy
galpy/actionAngle/actionAngle.py
actionAngle._check_consistent_units_orbitInput
def _check_consistent_units_orbitInput(self,orb): """Internal function to check that the set of units for this object is consistent with that for an input orbit""" if self._roSet and orb._roSet: assert m.fabs(self._ro-orb._ro) < 10.**-10., 'Physical conversion for the actionAngle object is not consistent with that of the Orbit given to it' if self._voSet and orb._voSet: assert m.fabs(self._vo-orb._vo) < 10.**-10., 'Physical conversion for the actionAngle object is not consistent with that of the Orbit given to it' return None
python
def _check_consistent_units_orbitInput(self,orb): """Internal function to check that the set of units for this object is consistent with that for an input orbit""" if self._roSet and orb._roSet: assert m.fabs(self._ro-orb._ro) < 10.**-10., 'Physical conversion for the actionAngle object is not consistent with that of the Orbit given to it' if self._voSet and orb._voSet: assert m.fabs(self._vo-orb._vo) < 10.**-10., 'Physical conversion for the actionAngle object is not consistent with that of the Orbit given to it' return None
[ "def", "_check_consistent_units_orbitInput", "(", "self", ",", "orb", ")", ":", "if", "self", ".", "_roSet", "and", "orb", ".", "_roSet", ":", "assert", "m", ".", "fabs", "(", "self", ".", "_ro", "-", "orb", ".", "_ro", ")", "<", "10.", "**", "-", ...
Internal function to check that the set of units for this object is consistent with that for an input orbit
[ "Internal", "function", "to", "check", "that", "the", "set", "of", "units", "for", "this", "object", "is", "consistent", "with", "that", "for", "an", "input", "orbit" ]
9c5b9fe65d58835624dffe432be282060918ee08
https://github.com/jobovy/galpy/blob/9c5b9fe65d58835624dffe432be282060918ee08/galpy/actionAngle/actionAngle.py#L85-L91
train
27,904
jobovy/galpy
galpy/potential/SpiralArmsPotential.py
check_inputs_not_arrays
def check_inputs_not_arrays(func): """ Decorator to check inputs and throw TypeError if any of the inputs are arrays. Methods potentially return with silent errors if inputs are not checked. """ @wraps(func) def func_wrapper(self, R, z, phi, t): if (hasattr(R, '__len__') and len(R) > 1) \ or (hasattr(z, '__len__') and len(z) > 1) \ or (hasattr(phi, '__len__') and len(phi) > 1) \ or (hasattr(t, '__len__') and len(t) > 1): raise TypeError('Methods in SpiralArmsPotential do not accept array inputs. Please input scalars.') return func(self, R, z, phi, t) return func_wrapper
python
def check_inputs_not_arrays(func): """ Decorator to check inputs and throw TypeError if any of the inputs are arrays. Methods potentially return with silent errors if inputs are not checked. """ @wraps(func) def func_wrapper(self, R, z, phi, t): if (hasattr(R, '__len__') and len(R) > 1) \ or (hasattr(z, '__len__') and len(z) > 1) \ or (hasattr(phi, '__len__') and len(phi) > 1) \ or (hasattr(t, '__len__') and len(t) > 1): raise TypeError('Methods in SpiralArmsPotential do not accept array inputs. Please input scalars.') return func(self, R, z, phi, t) return func_wrapper
[ "def", "check_inputs_not_arrays", "(", "func", ")", ":", "@", "wraps", "(", "func", ")", "def", "func_wrapper", "(", "self", ",", "R", ",", "z", ",", "phi", ",", "t", ")", ":", "if", "(", "hasattr", "(", "R", ",", "'__len__'", ")", "and", "len", ...
Decorator to check inputs and throw TypeError if any of the inputs are arrays. Methods potentially return with silent errors if inputs are not checked.
[ "Decorator", "to", "check", "inputs", "and", "throw", "TypeError", "if", "any", "of", "the", "inputs", "are", "arrays", ".", "Methods", "potentially", "return", "with", "silent", "errors", "if", "inputs", "are", "not", "checked", "." ]
9c5b9fe65d58835624dffe432be282060918ee08
https://github.com/jobovy/galpy/blob/9c5b9fe65d58835624dffe432be282060918ee08/galpy/potential/SpiralArmsPotential.py#L21-L35
train
27,905
jobovy/galpy
galpy/actionAngle/actionAngleAxi.py
_JRAxiIntegrand
def _JRAxiIntegrand(r,E,L,pot): """The J_R integrand""" return nu.sqrt(2.*(E-potentialAxi(r,pot))-L**2./r**2.)
python
def _JRAxiIntegrand(r,E,L,pot): """The J_R integrand""" return nu.sqrt(2.*(E-potentialAxi(r,pot))-L**2./r**2.)
[ "def", "_JRAxiIntegrand", "(", "r", ",", "E", ",", "L", ",", "pot", ")", ":", "return", "nu", ".", "sqrt", "(", "2.", "*", "(", "E", "-", "potentialAxi", "(", "r", ",", "pot", ")", ")", "-", "L", "**", "2.", "/", "r", "**", "2.", ")" ]
The J_R integrand
[ "The", "J_R", "integrand" ]
9c5b9fe65d58835624dffe432be282060918ee08
https://github.com/jobovy/galpy/blob/9c5b9fe65d58835624dffe432be282060918ee08/galpy/actionAngle/actionAngleAxi.py#L367-L369
train
27,906
jobovy/galpy
galpy/actionAngle/actionAngleAxi.py
_rapRperiAxiEq
def _rapRperiAxiEq(R,E,L,pot): """The vr=0 equation that needs to be solved to find apo- and pericenter""" return E-potentialAxi(R,pot)-L**2./2./R**2.
python
def _rapRperiAxiEq(R,E,L,pot): """The vr=0 equation that needs to be solved to find apo- and pericenter""" return E-potentialAxi(R,pot)-L**2./2./R**2.
[ "def", "_rapRperiAxiEq", "(", "R", ",", "E", ",", "L", ",", "pot", ")", ":", "return", "E", "-", "potentialAxi", "(", "R", ",", "pot", ")", "-", "L", "**", "2.", "/", "2.", "/", "R", "**", "2." ]
The vr=0 equation that needs to be solved to find apo- and pericenter
[ "The", "vr", "=", "0", "equation", "that", "needs", "to", "be", "solved", "to", "find", "apo", "-", "and", "pericenter" ]
9c5b9fe65d58835624dffe432be282060918ee08
https://github.com/jobovy/galpy/blob/9c5b9fe65d58835624dffe432be282060918ee08/galpy/actionAngle/actionAngleAxi.py#L387-L389
train
27,907
jobovy/galpy
galpy/potential/Potential.py
_rlfunc
def _rlfunc(rl,lz,pot): """Function that gives rvc-lz""" thisvcirc= vcirc(pot,rl,use_physical=False) return rl*thisvcirc-lz
python
def _rlfunc(rl,lz,pot): """Function that gives rvc-lz""" thisvcirc= vcirc(pot,rl,use_physical=False) return rl*thisvcirc-lz
[ "def", "_rlfunc", "(", "rl", ",", "lz", ",", "pot", ")", ":", "thisvcirc", "=", "vcirc", "(", "pot", ",", "rl", ",", "use_physical", "=", "False", ")", "return", "rl", "*", "thisvcirc", "-", "lz" ]
Function that gives rvc-lz
[ "Function", "that", "gives", "rvc", "-", "lz" ]
9c5b9fe65d58835624dffe432be282060918ee08
https://github.com/jobovy/galpy/blob/9c5b9fe65d58835624dffe432be282060918ee08/galpy/potential/Potential.py#L2678-L2681
train
27,908
jobovy/galpy
galpy/potential/Potential.py
_rlFindStart
def _rlFindStart(rl,lz,pot,lower=False): """find a starting interval for rl""" rtry= 2.*rl while (2.*lower-1.)*_rlfunc(rtry,lz,pot) > 0.: if lower: rtry/= 2. else: rtry*= 2. return rtry
python
def _rlFindStart(rl,lz,pot,lower=False): """find a starting interval for rl""" rtry= 2.*rl while (2.*lower-1.)*_rlfunc(rtry,lz,pot) > 0.: if lower: rtry/= 2. else: rtry*= 2. return rtry
[ "def", "_rlFindStart", "(", "rl", ",", "lz", ",", "pot", ",", "lower", "=", "False", ")", ":", "rtry", "=", "2.", "*", "rl", "while", "(", "2.", "*", "lower", "-", "1.", ")", "*", "_rlfunc", "(", "rtry", ",", "lz", ",", "pot", ")", ">", "0.",...
find a starting interval for rl
[ "find", "a", "starting", "interval", "for", "rl" ]
9c5b9fe65d58835624dffe432be282060918ee08
https://github.com/jobovy/galpy/blob/9c5b9fe65d58835624dffe432be282060918ee08/galpy/potential/Potential.py#L2683-L2691
train
27,909
jobovy/galpy
galpy/orbit/OrbitTop.py
_check_roSet
def _check_roSet(orb,kwargs,funcName): """Function to check whether ro is set, because it's required for funcName""" if not orb._roSet and kwargs.get('ro',None) is None: warnings.warn("Method %s(.) requires ro to be given at Orbit initialization or at method evaluation; using default ro which is %f kpc" % (funcName,orb._ro), galpyWarning)
python
def _check_roSet(orb,kwargs,funcName): """Function to check whether ro is set, because it's required for funcName""" if not orb._roSet and kwargs.get('ro',None) is None: warnings.warn("Method %s(.) requires ro to be given at Orbit initialization or at method evaluation; using default ro which is %f kpc" % (funcName,orb._ro), galpyWarning)
[ "def", "_check_roSet", "(", "orb", ",", "kwargs", ",", "funcName", ")", ":", "if", "not", "orb", ".", "_roSet", "and", "kwargs", ".", "get", "(", "'ro'", ",", "None", ")", "is", "None", ":", "warnings", ".", "warn", "(", "\"Method %s(.) requires ro to be...
Function to check whether ro is set, because it's required for funcName
[ "Function", "to", "check", "whether", "ro", "is", "set", "because", "it", "s", "required", "for", "funcName" ]
9c5b9fe65d58835624dffe432be282060918ee08
https://github.com/jobovy/galpy/blob/9c5b9fe65d58835624dffe432be282060918ee08/galpy/orbit/OrbitTop.py#L2398-L2402
train
27,910
jobovy/galpy
galpy/orbit/OrbitTop.py
_check_voSet
def _check_voSet(orb,kwargs,funcName): """Function to check whether vo is set, because it's required for funcName""" if not orb._voSet and kwargs.get('vo',None) is None: warnings.warn("Method %s(.) requires vo to be given at Orbit initialization or at method evaluation; using default vo which is %f km/s" % (funcName,orb._vo), galpyWarning)
python
def _check_voSet(orb,kwargs,funcName): """Function to check whether vo is set, because it's required for funcName""" if not orb._voSet and kwargs.get('vo',None) is None: warnings.warn("Method %s(.) requires vo to be given at Orbit initialization or at method evaluation; using default vo which is %f km/s" % (funcName,orb._vo), galpyWarning)
[ "def", "_check_voSet", "(", "orb", ",", "kwargs", ",", "funcName", ")", ":", "if", "not", "orb", ".", "_voSet", "and", "kwargs", ".", "get", "(", "'vo'", ",", "None", ")", "is", "None", ":", "warnings", ".", "warn", "(", "\"Method %s(.) requires vo to be...
Function to check whether vo is set, because it's required for funcName
[ "Function", "to", "check", "whether", "vo", "is", "set", "because", "it", "s", "required", "for", "funcName" ]
9c5b9fe65d58835624dffe432be282060918ee08
https://github.com/jobovy/galpy/blob/9c5b9fe65d58835624dffe432be282060918ee08/galpy/orbit/OrbitTop.py#L2404-L2408
train
27,911
jobovy/galpy
galpy/orbit/OrbitTop.py
OrbitTop._radec
def _radec(self,*args,**kwargs): """Calculate ra and dec""" lbd= self._lbd(*args,**kwargs) return coords.lb_to_radec(lbd[:,0],lbd[:,1],degree=True,epoch=None)
python
def _radec(self,*args,**kwargs): """Calculate ra and dec""" lbd= self._lbd(*args,**kwargs) return coords.lb_to_radec(lbd[:,0],lbd[:,1],degree=True,epoch=None)
[ "def", "_radec", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "lbd", "=", "self", ".", "_lbd", "(", "*", "args", ",", "*", "*", "kwargs", ")", "return", "coords", ".", "lb_to_radec", "(", "lbd", "[", ":", ",", "0", "]", "...
Calculate ra and dec
[ "Calculate", "ra", "and", "dec" ]
9c5b9fe65d58835624dffe432be282060918ee08
https://github.com/jobovy/galpy/blob/9c5b9fe65d58835624dffe432be282060918ee08/galpy/orbit/OrbitTop.py#L919-L922
train
27,912
jobovy/galpy
galpy/orbit/OrbitTop.py
OrbitTop._pmrapmdec
def _pmrapmdec(self,*args,**kwargs): """Calculate pmra and pmdec""" lbdvrpmllpmbb= self._lbdvrpmllpmbb(*args,**kwargs) return coords.pmllpmbb_to_pmrapmdec(lbdvrpmllpmbb[:,4], lbdvrpmllpmbb[:,5], lbdvrpmllpmbb[:,0], lbdvrpmllpmbb[:,1],degree=True, epoch=None)
python
def _pmrapmdec(self,*args,**kwargs): """Calculate pmra and pmdec""" lbdvrpmllpmbb= self._lbdvrpmllpmbb(*args,**kwargs) return coords.pmllpmbb_to_pmrapmdec(lbdvrpmllpmbb[:,4], lbdvrpmllpmbb[:,5], lbdvrpmllpmbb[:,0], lbdvrpmllpmbb[:,1],degree=True, epoch=None)
[ "def", "_pmrapmdec", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "lbdvrpmllpmbb", "=", "self", ".", "_lbdvrpmllpmbb", "(", "*", "args", ",", "*", "*", "kwargs", ")", "return", "coords", ".", "pmllpmbb_to_pmrapmdec", "(", "lbdvrpmllp...
Calculate pmra and pmdec
[ "Calculate", "pmra", "and", "pmdec" ]
9c5b9fe65d58835624dffe432be282060918ee08
https://github.com/jobovy/galpy/blob/9c5b9fe65d58835624dffe432be282060918ee08/galpy/orbit/OrbitTop.py#L924-L931
train
27,913
jobovy/galpy
galpy/orbit/OrbitTop.py
OrbitTop._lbd
def _lbd(self,*args,**kwargs): """Calculate l,b, and d""" obs, ro, vo= self._parse_radec_kwargs(kwargs,dontpop=True) X,Y,Z= self._helioXYZ(*args,**kwargs) bad_indx= (X == 0.)*(Y == 0.)*(Z == 0.) if True in bad_indx: X[bad_indx]+= ro/10000. return coords.XYZ_to_lbd(X,Y,Z,degree=True)
python
def _lbd(self,*args,**kwargs): """Calculate l,b, and d""" obs, ro, vo= self._parse_radec_kwargs(kwargs,dontpop=True) X,Y,Z= self._helioXYZ(*args,**kwargs) bad_indx= (X == 0.)*(Y == 0.)*(Z == 0.) if True in bad_indx: X[bad_indx]+= ro/10000. return coords.XYZ_to_lbd(X,Y,Z,degree=True)
[ "def", "_lbd", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "obs", ",", "ro", ",", "vo", "=", "self", ".", "_parse_radec_kwargs", "(", "kwargs", ",", "dontpop", "=", "True", ")", "X", ",", "Y", ",", "Z", "=", "self", ".", ...
Calculate l,b, and d
[ "Calculate", "l", "b", "and", "d" ]
9c5b9fe65d58835624dffe432be282060918ee08
https://github.com/jobovy/galpy/blob/9c5b9fe65d58835624dffe432be282060918ee08/galpy/orbit/OrbitTop.py#L933-L940
train
27,914
jobovy/galpy
galpy/orbit/OrbitTop.py
OrbitTop._lbdvrpmllpmbb
def _lbdvrpmllpmbb(self,*args,**kwargs): """Calculate l,b,d,vr,pmll,pmbb""" obs, ro, vo= self._parse_radec_kwargs(kwargs,dontpop=True) X,Y,Z,vX,vY,vZ= self._XYZvxvyvz(*args,**kwargs) bad_indx= (X == 0.)*(Y == 0.)*(Z == 0.) if True in bad_indx: X[bad_indx]+= ro/10000. return coords.rectgal_to_sphergal(X,Y,Z,vX,vY,vZ,degree=True)
python
def _lbdvrpmllpmbb(self,*args,**kwargs): """Calculate l,b,d,vr,pmll,pmbb""" obs, ro, vo= self._parse_radec_kwargs(kwargs,dontpop=True) X,Y,Z,vX,vY,vZ= self._XYZvxvyvz(*args,**kwargs) bad_indx= (X == 0.)*(Y == 0.)*(Z == 0.) if True in bad_indx: X[bad_indx]+= ro/10000. return coords.rectgal_to_sphergal(X,Y,Z,vX,vY,vZ,degree=True)
[ "def", "_lbdvrpmllpmbb", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "obs", ",", "ro", ",", "vo", "=", "self", ".", "_parse_radec_kwargs", "(", "kwargs", ",", "dontpop", "=", "True", ")", "X", ",", "Y", ",", "Z", ",", "vX", ...
Calculate l,b,d,vr,pmll,pmbb
[ "Calculate", "l", "b", "d", "vr", "pmll", "pmbb" ]
9c5b9fe65d58835624dffe432be282060918ee08
https://github.com/jobovy/galpy/blob/9c5b9fe65d58835624dffe432be282060918ee08/galpy/orbit/OrbitTop.py#L992-L999
train
27,915
jobovy/galpy
galpy/orbit/OrbitTop.py
OrbitTop._parse_plot_quantity
def _parse_plot_quantity(self,quant,**kwargs): """Internal function to parse a quantity to be plotted based on input data""" # Cannot be using Quantity output kwargs['quantity']= False if callable(quant): return quant(self.t) def _eval(q): # Check those that don't have the exact name of the function if q == 't': return self.time(self.t,**kwargs) elif q == 'Enorm': return self.E(self.t,**kwargs)/self.E(0.,**kwargs) elif q == 'Eznorm': return self.Ez(self.t,**kwargs)/self.Ez(0.,**kwargs) elif q == 'ERnorm': return self.ER(self.t,**kwargs)/self.ER(0.,**kwargs) elif q == 'Jacobinorm': return self.Jacobi(self.t,**kwargs)/self.Jacobi(0.,**kwargs) else: # these are exact, e.g., 'x' for self.x return self.__getattribute__(q)(self.t,**kwargs) try: return _eval(quant) except AttributeError: pass try: import numexpr except ImportError: #pragma: no cover raise ImportError('Parsing the quantity to be plotted failed; if you are trying to plot an expression, please make sure to install numexpr first') # Figure out the variables in the expression to be computed to plot try: vars= numexpr.NumExpr(quant).input_names except TypeError as err: raise TypeError('Parsing the expression {} failed, with error message:\n"{}"'.format(quant,err)) # Construct dictionary of necessary parameters vars_dict= {} for var in vars: vars_dict[var]= _eval(var) return numexpr.evaluate(quant,local_dict=vars_dict)
python
def _parse_plot_quantity(self,quant,**kwargs): """Internal function to parse a quantity to be plotted based on input data""" # Cannot be using Quantity output kwargs['quantity']= False if callable(quant): return quant(self.t) def _eval(q): # Check those that don't have the exact name of the function if q == 't': return self.time(self.t,**kwargs) elif q == 'Enorm': return self.E(self.t,**kwargs)/self.E(0.,**kwargs) elif q == 'Eznorm': return self.Ez(self.t,**kwargs)/self.Ez(0.,**kwargs) elif q == 'ERnorm': return self.ER(self.t,**kwargs)/self.ER(0.,**kwargs) elif q == 'Jacobinorm': return self.Jacobi(self.t,**kwargs)/self.Jacobi(0.,**kwargs) else: # these are exact, e.g., 'x' for self.x return self.__getattribute__(q)(self.t,**kwargs) try: return _eval(quant) except AttributeError: pass try: import numexpr except ImportError: #pragma: no cover raise ImportError('Parsing the quantity to be plotted failed; if you are trying to plot an expression, please make sure to install numexpr first') # Figure out the variables in the expression to be computed to plot try: vars= numexpr.NumExpr(quant).input_names except TypeError as err: raise TypeError('Parsing the expression {} failed, with error message:\n"{}"'.format(quant,err)) # Construct dictionary of necessary parameters vars_dict= {} for var in vars: vars_dict[var]= _eval(var) return numexpr.evaluate(quant,local_dict=vars_dict)
[ "def", "_parse_plot_quantity", "(", "self", ",", "quant", ",", "*", "*", "kwargs", ")", ":", "# Cannot be using Quantity output", "kwargs", "[", "'quantity'", "]", "=", "False", "if", "callable", "(", "quant", ")", ":", "return", "quant", "(", "self", ".", ...
Internal function to parse a quantity to be plotted based on input data
[ "Internal", "function", "to", "parse", "a", "quantity", "to", "be", "plotted", "based", "on", "input", "data" ]
9c5b9fe65d58835624dffe432be282060918ee08
https://github.com/jobovy/galpy/blob/9c5b9fe65d58835624dffe432be282060918ee08/galpy/orbit/OrbitTop.py#L1631-L1667
train
27,916
jobovy/galpy
galpy/df/quasiisothermaldf.py
quasiisothermaldf._jmomentdensity
def _jmomentdensity(self,R,z,n,m,o,nsigma=None,mc=True,nmc=10000, _returnmc=False,_vrs=None,_vts=None,_vzs=None, **kwargs): """Non-physical version of jmomentdensity, otherwise the same""" if nsigma == None: nsigma= _NSIGMA sigmaR1= self._sr*numpy.exp((self._refr-R)/self._hsr) sigmaz1= self._sz*numpy.exp((self._refr-R)/self._hsz) thisvc= potential.vcirc(self._pot,R,use_physical=False) #Use the asymmetric drift equation to estimate va gamma= numpy.sqrt(0.5) va= sigmaR1**2./2./thisvc\ *(gamma**2.-1. #Assume close to flat rotation curve, sigphi2/sigR2 =~ 0.5 +R*(1./self._hr+2./self._hsr)) if math.fabs(va) > sigmaR1: va = 0.#To avoid craziness near the center if mc: mvT= (thisvc-va)/gamma/sigmaR1 if _vrs is None: vrs= numpy.random.normal(size=nmc) else: vrs= _vrs if _vts is None: vts= numpy.random.normal(size=nmc)+mvT else: vts= _vts if _vzs is None: vzs= numpy.random.normal(size=nmc) else: vzs= _vzs Is= _jmomentsurfaceMCIntegrand(vzs,vrs,vts,numpy.ones(nmc)*R,numpy.ones(nmc)*z,self,sigmaR1,gamma,sigmaz1,mvT,n,m,o) if _returnmc: return (numpy.mean(Is)*sigmaR1**2.*gamma*sigmaz1, vrs,vts,vzs) else: return numpy.mean(Is)*sigmaR1**2.*gamma*sigmaz1 else: #pragma: no cover because this is too slow; a warning is shown warnings.warn("Calculations using direct numerical integration using tplquad is not recommended and extremely slow; it has also not been carefully tested",galpyWarning) return integrate.tplquad(_jmomentsurfaceIntegrand, 1./gamma*(thisvc-va)/sigmaR1-nsigma, 1./gamma*(thisvc-va)/sigmaR1+nsigma, lambda x: 0., lambda x: nsigma, lambda x,y: 0., lambda x,y: nsigma, (R,z,self,sigmaR1,gamma,sigmaz1,n,m,o), **kwargs)[0]*sigmaR1**2.*gamma*sigmaz1
python
def _jmomentdensity(self,R,z,n,m,o,nsigma=None,mc=True,nmc=10000, _returnmc=False,_vrs=None,_vts=None,_vzs=None, **kwargs): """Non-physical version of jmomentdensity, otherwise the same""" if nsigma == None: nsigma= _NSIGMA sigmaR1= self._sr*numpy.exp((self._refr-R)/self._hsr) sigmaz1= self._sz*numpy.exp((self._refr-R)/self._hsz) thisvc= potential.vcirc(self._pot,R,use_physical=False) #Use the asymmetric drift equation to estimate va gamma= numpy.sqrt(0.5) va= sigmaR1**2./2./thisvc\ *(gamma**2.-1. #Assume close to flat rotation curve, sigphi2/sigR2 =~ 0.5 +R*(1./self._hr+2./self._hsr)) if math.fabs(va) > sigmaR1: va = 0.#To avoid craziness near the center if mc: mvT= (thisvc-va)/gamma/sigmaR1 if _vrs is None: vrs= numpy.random.normal(size=nmc) else: vrs= _vrs if _vts is None: vts= numpy.random.normal(size=nmc)+mvT else: vts= _vts if _vzs is None: vzs= numpy.random.normal(size=nmc) else: vzs= _vzs Is= _jmomentsurfaceMCIntegrand(vzs,vrs,vts,numpy.ones(nmc)*R,numpy.ones(nmc)*z,self,sigmaR1,gamma,sigmaz1,mvT,n,m,o) if _returnmc: return (numpy.mean(Is)*sigmaR1**2.*gamma*sigmaz1, vrs,vts,vzs) else: return numpy.mean(Is)*sigmaR1**2.*gamma*sigmaz1 else: #pragma: no cover because this is too slow; a warning is shown warnings.warn("Calculations using direct numerical integration using tplquad is not recommended and extremely slow; it has also not been carefully tested",galpyWarning) return integrate.tplquad(_jmomentsurfaceIntegrand, 1./gamma*(thisvc-va)/sigmaR1-nsigma, 1./gamma*(thisvc-va)/sigmaR1+nsigma, lambda x: 0., lambda x: nsigma, lambda x,y: 0., lambda x,y: nsigma, (R,z,self,sigmaR1,gamma,sigmaz1,n,m,o), **kwargs)[0]*sigmaR1**2.*gamma*sigmaz1
[ "def", "_jmomentdensity", "(", "self", ",", "R", ",", "z", ",", "n", ",", "m", ",", "o", ",", "nsigma", "=", "None", ",", "mc", "=", "True", ",", "nmc", "=", "10000", ",", "_returnmc", "=", "False", ",", "_vrs", "=", "None", ",", "_vts", "=", ...
Non-physical version of jmomentdensity, otherwise the same
[ "Non", "-", "physical", "version", "of", "jmomentdensity", "otherwise", "the", "same" ]
9c5b9fe65d58835624dffe432be282060918ee08
https://github.com/jobovy/galpy/blob/9c5b9fe65d58835624dffe432be282060918ee08/galpy/df/quasiisothermaldf.py#L811-L854
train
27,917
jobovy/galpy
galpy/df/streamgapdf.py
impact_check_range
def impact_check_range(func): """Decorator to check the range of interpolated kicks""" @wraps(func) def impact_wrapper(*args,**kwargs): if isinstance(args[1],numpy.ndarray): out= numpy.zeros(len(args[1])) goodIndx= (args[1] < args[0]._deltaAngleTrackImpact)*(args[1] > 0.) out[goodIndx]= func(args[0],args[1][goodIndx]) return out elif args[1] >= args[0]._deltaAngleTrackImpact or args[1] <= 0.: return 0. else: return func(*args,**kwargs) return impact_wrapper
python
def impact_check_range(func): """Decorator to check the range of interpolated kicks""" @wraps(func) def impact_wrapper(*args,**kwargs): if isinstance(args[1],numpy.ndarray): out= numpy.zeros(len(args[1])) goodIndx= (args[1] < args[0]._deltaAngleTrackImpact)*(args[1] > 0.) out[goodIndx]= func(args[0],args[1][goodIndx]) return out elif args[1] >= args[0]._deltaAngleTrackImpact or args[1] <= 0.: return 0. else: return func(*args,**kwargs) return impact_wrapper
[ "def", "impact_check_range", "(", "func", ")", ":", "@", "wraps", "(", "func", ")", "def", "impact_wrapper", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "isinstance", "(", "args", "[", "1", "]", ",", "numpy", ".", "ndarray", ")", ":"...
Decorator to check the range of interpolated kicks
[ "Decorator", "to", "check", "the", "range", "of", "interpolated", "kicks" ]
9c5b9fe65d58835624dffe432be282060918ee08
https://github.com/jobovy/galpy/blob/9c5b9fe65d58835624dffe432be282060918ee08/galpy/df/streamgapdf.py#L20-L33
train
27,918
jobovy/galpy
galpy/df/streamgapdf.py
streamgapdf._density_par
def _density_par(self,dangle,tdisrupt=None,approx=True, higherorder=None): """The raw density as a function of parallel angle, approx= use faster method that directly integrates the spline representation""" if higherorder is None: higherorder= self._higherorderTrack if tdisrupt is None: tdisrupt= self._tdisrupt if approx: return self._density_par_approx(dangle,tdisrupt, higherorder=higherorder) else: return integrate.quad(lambda T: numpy.sqrt(self._sortedSigOEig[2])\ *(1+T*T)/(1-T*T)**2.\ *self.pOparapar(T/(1-T*T)\ *numpy.sqrt(self._sortedSigOEig[2])\ +self._meandO,dangle), -1.,1.)[0]
python
def _density_par(self,dangle,tdisrupt=None,approx=True, higherorder=None): """The raw density as a function of parallel angle, approx= use faster method that directly integrates the spline representation""" if higherorder is None: higherorder= self._higherorderTrack if tdisrupt is None: tdisrupt= self._tdisrupt if approx: return self._density_par_approx(dangle,tdisrupt, higherorder=higherorder) else: return integrate.quad(lambda T: numpy.sqrt(self._sortedSigOEig[2])\ *(1+T*T)/(1-T*T)**2.\ *self.pOparapar(T/(1-T*T)\ *numpy.sqrt(self._sortedSigOEig[2])\ +self._meandO,dangle), -1.,1.)[0]
[ "def", "_density_par", "(", "self", ",", "dangle", ",", "tdisrupt", "=", "None", ",", "approx", "=", "True", ",", "higherorder", "=", "None", ")", ":", "if", "higherorder", "is", "None", ":", "higherorder", "=", "self", ".", "_higherorderTrack", "if", "t...
The raw density as a function of parallel angle, approx= use faster method that directly integrates the spline representation
[ "The", "raw", "density", "as", "a", "function", "of", "parallel", "angle", "approx", "=", "use", "faster", "method", "that", "directly", "integrates", "the", "spline", "representation" ]
9c5b9fe65d58835624dffe432be282060918ee08
https://github.com/jobovy/galpy/blob/9c5b9fe65d58835624dffe432be282060918ee08/galpy/df/streamgapdf.py#L225-L241
train
27,919
jobovy/galpy
galpy/df/streamgapdf.py
streamgapdf._density_par_approx
def _density_par_approx(self,dangle,tdisrupt,_return_array=False, higherorder=False): """Compute the density as a function of parallel angle using the spline representation + approximations""" # First construct the breakpoints for this dangle Oparb= (dangle-self._kick_interpdOpar_poly.x)/self._timpact # Find the lower limit of the integration in the pw-linear-kick approx. lowbindx,lowx= self.minOpar(dangle,tdisrupt,_return_raw=True) lowbindx= numpy.arange(len(Oparb)-1)[lowbindx] Oparb[lowbindx+1]= Oparb[lowbindx]-lowx # Now integrate between breakpoints out= (0.5/(1.+self._kick_interpdOpar_poly.c[-2]*self._timpact)\ *(special.erf(1./numpy.sqrt(2.*self._sortedSigOEig[2])\ *(Oparb[:-1]-self._kick_interpdOpar_poly.c[-1]-self._meandO))\ -special.erf(1./numpy.sqrt(2.*self._sortedSigOEig[2])*(numpy.roll(Oparb,-1)[:-1]-self._kick_interpdOpar_poly.c[-1]-self._meandO\ -self._kick_interpdOpar_poly.c[-2]*self._timpact*(Oparb-numpy.roll(Oparb,-1))[:-1])))) if _return_array: return out out= numpy.sum(out[:lowbindx+1]) if higherorder: # Add higher-order contribution out+= self._density_par_approx_higherorder(Oparb,lowbindx) # Add integration to infinity out+= 0.5*(1.+special.erf((self._meandO-Oparb[0])\ /numpy.sqrt(2.*self._sortedSigOEig[2]))) return out
python
def _density_par_approx(self,dangle,tdisrupt,_return_array=False, higherorder=False): """Compute the density as a function of parallel angle using the spline representation + approximations""" # First construct the breakpoints for this dangle Oparb= (dangle-self._kick_interpdOpar_poly.x)/self._timpact # Find the lower limit of the integration in the pw-linear-kick approx. lowbindx,lowx= self.minOpar(dangle,tdisrupt,_return_raw=True) lowbindx= numpy.arange(len(Oparb)-1)[lowbindx] Oparb[lowbindx+1]= Oparb[lowbindx]-lowx # Now integrate between breakpoints out= (0.5/(1.+self._kick_interpdOpar_poly.c[-2]*self._timpact)\ *(special.erf(1./numpy.sqrt(2.*self._sortedSigOEig[2])\ *(Oparb[:-1]-self._kick_interpdOpar_poly.c[-1]-self._meandO))\ -special.erf(1./numpy.sqrt(2.*self._sortedSigOEig[2])*(numpy.roll(Oparb,-1)[:-1]-self._kick_interpdOpar_poly.c[-1]-self._meandO\ -self._kick_interpdOpar_poly.c[-2]*self._timpact*(Oparb-numpy.roll(Oparb,-1))[:-1])))) if _return_array: return out out= numpy.sum(out[:lowbindx+1]) if higherorder: # Add higher-order contribution out+= self._density_par_approx_higherorder(Oparb,lowbindx) # Add integration to infinity out+= 0.5*(1.+special.erf((self._meandO-Oparb[0])\ /numpy.sqrt(2.*self._sortedSigOEig[2]))) return out
[ "def", "_density_par_approx", "(", "self", ",", "dangle", ",", "tdisrupt", ",", "_return_array", "=", "False", ",", "higherorder", "=", "False", ")", ":", "# First construct the breakpoints for this dangle", "Oparb", "=", "(", "dangle", "-", "self", ".", "_kick_in...
Compute the density as a function of parallel angle using the spline representation + approximations
[ "Compute", "the", "density", "as", "a", "function", "of", "parallel", "angle", "using", "the", "spline", "representation", "+", "approximations" ]
9c5b9fe65d58835624dffe432be282060918ee08
https://github.com/jobovy/galpy/blob/9c5b9fe65d58835624dffe432be282060918ee08/galpy/df/streamgapdf.py#L243-L268
train
27,920
jobovy/galpy
galpy/df/streamgapdf.py
streamgapdf._density_par_approx_higherorder
def _density_par_approx_higherorder(self,Oparb,lowbindx, _return_array=False, gaussxpolyInt=None): """Contribution from non-linear spline terms""" spline_order= self._kick_interpdOpar_raw._eval_args[2] if spline_order == 1: return 0. # Form all Gaussian-like integrals necessary ll= (numpy.roll(Oparb,-1)[:-1]-self._kick_interpdOpar_poly.c[-1]\ -self._meandO\ -self._kick_interpdOpar_poly.c[-2]*self._timpact\ *(Oparb-numpy.roll(Oparb,-1))[:-1])\ /numpy.sqrt(2.*self._sortedSigOEig[2]) ul= (Oparb[:-1]-self._kick_interpdOpar_poly.c[-1]-self._meandO)\ /numpy.sqrt(2.*self._sortedSigOEig[2]) if gaussxpolyInt is None: gaussxpolyInt=\ self._densMoments_approx_higherorder_gaussxpolyInts(\ ll,ul,spline_order+1) # Now multiply in the coefficients for each order powers= numpy.tile(numpy.arange(spline_order+1)[::-1], (len(ul),1)).T gaussxpolyInt*= -0.5*(-numpy.sqrt(2.))**(powers+1)\ *self._sortedSigOEig[2]**(0.5*(powers-1)) powers= numpy.tile(numpy.arange(spline_order+1)[::-1][:-2], (len(ul),1)).T for jj in range(spline_order+1): gaussxpolyInt[-jj-1]*= numpy.sum(\ self._kick_interpdOpar_poly.c[:-2] *self._timpact**powers /(1.+self._kick_interpdOpar_poly.c[-2]*self._timpact) **(powers+1) *special.binom(powers,jj) *(Oparb[:-1]-self._kick_interpdOpar_poly.c[-1]-self._meandO) **(powers-jj),axis=0) if _return_array: return numpy.sum(gaussxpolyInt,axis=0) else: return numpy.sum(gaussxpolyInt[:,:lowbindx+1])
python
def _density_par_approx_higherorder(self,Oparb,lowbindx, _return_array=False, gaussxpolyInt=None): """Contribution from non-linear spline terms""" spline_order= self._kick_interpdOpar_raw._eval_args[2] if spline_order == 1: return 0. # Form all Gaussian-like integrals necessary ll= (numpy.roll(Oparb,-1)[:-1]-self._kick_interpdOpar_poly.c[-1]\ -self._meandO\ -self._kick_interpdOpar_poly.c[-2]*self._timpact\ *(Oparb-numpy.roll(Oparb,-1))[:-1])\ /numpy.sqrt(2.*self._sortedSigOEig[2]) ul= (Oparb[:-1]-self._kick_interpdOpar_poly.c[-1]-self._meandO)\ /numpy.sqrt(2.*self._sortedSigOEig[2]) if gaussxpolyInt is None: gaussxpolyInt=\ self._densMoments_approx_higherorder_gaussxpolyInts(\ ll,ul,spline_order+1) # Now multiply in the coefficients for each order powers= numpy.tile(numpy.arange(spline_order+1)[::-1], (len(ul),1)).T gaussxpolyInt*= -0.5*(-numpy.sqrt(2.))**(powers+1)\ *self._sortedSigOEig[2]**(0.5*(powers-1)) powers= numpy.tile(numpy.arange(spline_order+1)[::-1][:-2], (len(ul),1)).T for jj in range(spline_order+1): gaussxpolyInt[-jj-1]*= numpy.sum(\ self._kick_interpdOpar_poly.c[:-2] *self._timpact**powers /(1.+self._kick_interpdOpar_poly.c[-2]*self._timpact) **(powers+1) *special.binom(powers,jj) *(Oparb[:-1]-self._kick_interpdOpar_poly.c[-1]-self._meandO) **(powers-jj),axis=0) if _return_array: return numpy.sum(gaussxpolyInt,axis=0) else: return numpy.sum(gaussxpolyInt[:,:lowbindx+1])
[ "def", "_density_par_approx_higherorder", "(", "self", ",", "Oparb", ",", "lowbindx", ",", "_return_array", "=", "False", ",", "gaussxpolyInt", "=", "None", ")", ":", "spline_order", "=", "self", ".", "_kick_interpdOpar_raw", ".", "_eval_args", "[", "2", "]", ...
Contribution from non-linear spline terms
[ "Contribution", "from", "non", "-", "linear", "spline", "terms" ]
9c5b9fe65d58835624dffe432be282060918ee08
https://github.com/jobovy/galpy/blob/9c5b9fe65d58835624dffe432be282060918ee08/galpy/df/streamgapdf.py#L270-L307
train
27,921
jobovy/galpy
galpy/df/streamgapdf.py
streamgapdf._densMoments_approx_higherorder_gaussxpolyInts
def _densMoments_approx_higherorder_gaussxpolyInts(self,ll,ul,maxj): """Calculate all of the polynomial x Gaussian integrals occuring in the higher-order terms, recursively""" gaussxpolyInt= numpy.zeros((maxj,len(ul))) gaussxpolyInt[-1]= 1./numpy.sqrt(numpy.pi)\ *(numpy.exp(-ll**2.)-numpy.exp(-ul**2.)) gaussxpolyInt[-2]= 1./numpy.sqrt(numpy.pi)\ *(numpy.exp(-ll**2.)*ll-numpy.exp(-ul**2.)*ul)\ +0.5*(special.erf(ul)-special.erf(ll)) for jj in range(maxj-2): gaussxpolyInt[-jj-3]= 1./numpy.sqrt(numpy.pi)\ *(numpy.exp(-ll**2.)*ll**(jj+2)-numpy.exp(-ul**2.)*ul**(jj+2))\ +0.5*(jj+2)*gaussxpolyInt[-jj-1] return gaussxpolyInt
python
def _densMoments_approx_higherorder_gaussxpolyInts(self,ll,ul,maxj): """Calculate all of the polynomial x Gaussian integrals occuring in the higher-order terms, recursively""" gaussxpolyInt= numpy.zeros((maxj,len(ul))) gaussxpolyInt[-1]= 1./numpy.sqrt(numpy.pi)\ *(numpy.exp(-ll**2.)-numpy.exp(-ul**2.)) gaussxpolyInt[-2]= 1./numpy.sqrt(numpy.pi)\ *(numpy.exp(-ll**2.)*ll-numpy.exp(-ul**2.)*ul)\ +0.5*(special.erf(ul)-special.erf(ll)) for jj in range(maxj-2): gaussxpolyInt[-jj-3]= 1./numpy.sqrt(numpy.pi)\ *(numpy.exp(-ll**2.)*ll**(jj+2)-numpy.exp(-ul**2.)*ul**(jj+2))\ +0.5*(jj+2)*gaussxpolyInt[-jj-1] return gaussxpolyInt
[ "def", "_densMoments_approx_higherorder_gaussxpolyInts", "(", "self", ",", "ll", ",", "ul", ",", "maxj", ")", ":", "gaussxpolyInt", "=", "numpy", ".", "zeros", "(", "(", "maxj", ",", "len", "(", "ul", ")", ")", ")", "gaussxpolyInt", "[", "-", "1", "]", ...
Calculate all of the polynomial x Gaussian integrals occuring in the higher-order terms, recursively
[ "Calculate", "all", "of", "the", "polynomial", "x", "Gaussian", "integrals", "occuring", "in", "the", "higher", "-", "order", "terms", "recursively" ]
9c5b9fe65d58835624dffe432be282060918ee08
https://github.com/jobovy/galpy/blob/9c5b9fe65d58835624dffe432be282060918ee08/galpy/df/streamgapdf.py#L309-L322
train
27,922
jobovy/galpy
galpy/df/streamgapdf.py
streamgapdf._meanOmega_num_approx
def _meanOmega_num_approx(self,dangle,tdisrupt,higherorder=False): """Compute the numerator going into meanOmega using the direct integration of the spline representation""" # First construct the breakpoints for this dangle Oparb= (dangle-self._kick_interpdOpar_poly.x)/self._timpact # Find the lower limit of the integration in the pw-linear-kick approx. lowbindx,lowx= self.minOpar(dangle,tdisrupt,_return_raw=True) lowbindx= numpy.arange(len(Oparb)-1)[lowbindx] Oparb[lowbindx+1]= Oparb[lowbindx]-lowx # Now integrate between breakpoints out= numpy.sum(((Oparb[:-1] +(self._meandO+self._kick_interpdOpar_poly.c[-1] -Oparb[:-1])/ (1.+self._kick_interpdOpar_poly.c[-2]*self._timpact)) *self._density_par_approx(dangle,tdisrupt, _return_array=True) +numpy.sqrt(self._sortedSigOEig[2]/2./numpy.pi)/ (1.+self._kick_interpdOpar_poly.c[-2]*self._timpact)**2. *(numpy.exp(-0.5*(Oparb[:-1] -self._kick_interpdOpar_poly.c[-1] -(1.+self._kick_interpdOpar_poly.c[-2]*self._timpact) *(Oparb-numpy.roll(Oparb,-1))[:-1] -self._meandO)**2. /self._sortedSigOEig[2]) -numpy.exp(-0.5*(Oparb[:-1]-self._kick_interpdOpar_poly.c[-1] -self._meandO)**2. /self._sortedSigOEig[2])))[:lowbindx+1]) if higherorder: # Add higher-order contribution out+= self._meanOmega_num_approx_higherorder(Oparb,lowbindx) # Add integration to infinity out+= 0.5*(numpy.sqrt(2./numpy.pi)*numpy.sqrt(self._sortedSigOEig[2])\ *numpy.exp(-0.5*(self._meandO-Oparb[0])**2.\ /self._sortedSigOEig[2]) +self._meandO *(1.+special.erf((self._meandO-Oparb[0]) /numpy.sqrt(2.*self._sortedSigOEig[2])))) return out
python
def _meanOmega_num_approx(self,dangle,tdisrupt,higherorder=False): """Compute the numerator going into meanOmega using the direct integration of the spline representation""" # First construct the breakpoints for this dangle Oparb= (dangle-self._kick_interpdOpar_poly.x)/self._timpact # Find the lower limit of the integration in the pw-linear-kick approx. lowbindx,lowx= self.minOpar(dangle,tdisrupt,_return_raw=True) lowbindx= numpy.arange(len(Oparb)-1)[lowbindx] Oparb[lowbindx+1]= Oparb[lowbindx]-lowx # Now integrate between breakpoints out= numpy.sum(((Oparb[:-1] +(self._meandO+self._kick_interpdOpar_poly.c[-1] -Oparb[:-1])/ (1.+self._kick_interpdOpar_poly.c[-2]*self._timpact)) *self._density_par_approx(dangle,tdisrupt, _return_array=True) +numpy.sqrt(self._sortedSigOEig[2]/2./numpy.pi)/ (1.+self._kick_interpdOpar_poly.c[-2]*self._timpact)**2. *(numpy.exp(-0.5*(Oparb[:-1] -self._kick_interpdOpar_poly.c[-1] -(1.+self._kick_interpdOpar_poly.c[-2]*self._timpact) *(Oparb-numpy.roll(Oparb,-1))[:-1] -self._meandO)**2. /self._sortedSigOEig[2]) -numpy.exp(-0.5*(Oparb[:-1]-self._kick_interpdOpar_poly.c[-1] -self._meandO)**2. /self._sortedSigOEig[2])))[:lowbindx+1]) if higherorder: # Add higher-order contribution out+= self._meanOmega_num_approx_higherorder(Oparb,lowbindx) # Add integration to infinity out+= 0.5*(numpy.sqrt(2./numpy.pi)*numpy.sqrt(self._sortedSigOEig[2])\ *numpy.exp(-0.5*(self._meandO-Oparb[0])**2.\ /self._sortedSigOEig[2]) +self._meandO *(1.+special.erf((self._meandO-Oparb[0]) /numpy.sqrt(2.*self._sortedSigOEig[2])))) return out
[ "def", "_meanOmega_num_approx", "(", "self", ",", "dangle", ",", "tdisrupt", ",", "higherorder", "=", "False", ")", ":", "# First construct the breakpoints for this dangle", "Oparb", "=", "(", "dangle", "-", "self", ".", "_kick_interpdOpar_poly", ".", "x", ")", "/...
Compute the numerator going into meanOmega using the direct integration of the spline representation
[ "Compute", "the", "numerator", "going", "into", "meanOmega", "using", "the", "direct", "integration", "of", "the", "spline", "representation" ]
9c5b9fe65d58835624dffe432be282060918ee08
https://github.com/jobovy/galpy/blob/9c5b9fe65d58835624dffe432be282060918ee08/galpy/df/streamgapdf.py#L418-L454
train
27,923
jobovy/galpy
galpy/df/streamgapdf.py
streamgapdf._interpolate_stream_track_kick_aA
def _interpolate_stream_track_kick_aA(self): """Build interpolations of the stream track near the impact in action-angle coordinates""" if hasattr(self,'_kick_interpolatedObsTrackAA'): #pragma: no cover return None #Already did this #Calculate 1D meanOmega on a fine grid in angle and interpolate dmOs= numpy.array([\ super(streamgapdf,self).meanOmega(da,oned=True, tdisrupt=self._tdisrupt -self._timpact, use_physical=False) for da in self._kick_interpolatedThetasTrack]) self._kick_interpTrackAAdmeanOmegaOneD=\ interpolate.InterpolatedUnivariateSpline(\ self._kick_interpolatedThetasTrack,dmOs,k=3) #Build the interpolated AA self._kick_interpolatedObsTrackAA=\ numpy.empty((len(self._kick_interpolatedThetasTrack),6)) for ii in range(len(self._kick_interpolatedThetasTrack)): self._kick_interpolatedObsTrackAA[ii,:3]=\ self._progenitor_Omega+dmOs[ii]*self._dsigomeanProgDirection\ *self._gap_sigMeanSign self._kick_interpolatedObsTrackAA[ii,3:]=\ self._progenitor_angle+self._kick_interpolatedThetasTrack[ii]\ *self._dsigomeanProgDirection*self._gap_sigMeanSign\ -self._timpact*self._progenitor_Omega self._kick_interpolatedObsTrackAA[ii,3:]=\ numpy.mod(self._kick_interpolatedObsTrackAA[ii,3:],2.*numpy.pi) return None
python
def _interpolate_stream_track_kick_aA(self): """Build interpolations of the stream track near the impact in action-angle coordinates""" if hasattr(self,'_kick_interpolatedObsTrackAA'): #pragma: no cover return None #Already did this #Calculate 1D meanOmega on a fine grid in angle and interpolate dmOs= numpy.array([\ super(streamgapdf,self).meanOmega(da,oned=True, tdisrupt=self._tdisrupt -self._timpact, use_physical=False) for da in self._kick_interpolatedThetasTrack]) self._kick_interpTrackAAdmeanOmegaOneD=\ interpolate.InterpolatedUnivariateSpline(\ self._kick_interpolatedThetasTrack,dmOs,k=3) #Build the interpolated AA self._kick_interpolatedObsTrackAA=\ numpy.empty((len(self._kick_interpolatedThetasTrack),6)) for ii in range(len(self._kick_interpolatedThetasTrack)): self._kick_interpolatedObsTrackAA[ii,:3]=\ self._progenitor_Omega+dmOs[ii]*self._dsigomeanProgDirection\ *self._gap_sigMeanSign self._kick_interpolatedObsTrackAA[ii,3:]=\ self._progenitor_angle+self._kick_interpolatedThetasTrack[ii]\ *self._dsigomeanProgDirection*self._gap_sigMeanSign\ -self._timpact*self._progenitor_Omega self._kick_interpolatedObsTrackAA[ii,3:]=\ numpy.mod(self._kick_interpolatedObsTrackAA[ii,3:],2.*numpy.pi) return None
[ "def", "_interpolate_stream_track_kick_aA", "(", "self", ")", ":", "if", "hasattr", "(", "self", ",", "'_kick_interpolatedObsTrackAA'", ")", ":", "#pragma: no cover", "return", "None", "#Already did this", "#Calculate 1D meanOmega on a fine grid in angle and interpolate", "dmOs...
Build interpolations of the stream track near the impact in action-angle coordinates
[ "Build", "interpolations", "of", "the", "stream", "track", "near", "the", "impact", "in", "action", "-", "angle", "coordinates" ]
9c5b9fe65d58835624dffe432be282060918ee08
https://github.com/jobovy/galpy/blob/9c5b9fe65d58835624dffe432be282060918ee08/galpy/df/streamgapdf.py#L753-L780
train
27,924
jobovy/galpy
galpy/df/streamgapdf.py
streamgapdf._gap_progenitor_setup
def _gap_progenitor_setup(self): """Setup an Orbit instance that's the progenitor integrated backwards""" self._gap_progenitor= self._progenitor().flip() # new orbit, flip velocities # Make sure we do not use physical coordinates self._gap_progenitor.turn_physical_off() # Now integrate backward in time until tdisrupt ts= numpy.linspace(0.,self._tdisrupt,1001) self._gap_progenitor.integrate(ts,self._pot) # Flip its velocities, should really write a function for this self._gap_progenitor._orb.orbit[:,1]= -self._gap_progenitor._orb.orbit[:,1] self._gap_progenitor._orb.orbit[:,2]= -self._gap_progenitor._orb.orbit[:,2] self._gap_progenitor._orb.orbit[:,4]= -self._gap_progenitor._orb.orbit[:,4] return None
python
def _gap_progenitor_setup(self): """Setup an Orbit instance that's the progenitor integrated backwards""" self._gap_progenitor= self._progenitor().flip() # new orbit, flip velocities # Make sure we do not use physical coordinates self._gap_progenitor.turn_physical_off() # Now integrate backward in time until tdisrupt ts= numpy.linspace(0.,self._tdisrupt,1001) self._gap_progenitor.integrate(ts,self._pot) # Flip its velocities, should really write a function for this self._gap_progenitor._orb.orbit[:,1]= -self._gap_progenitor._orb.orbit[:,1] self._gap_progenitor._orb.orbit[:,2]= -self._gap_progenitor._orb.orbit[:,2] self._gap_progenitor._orb.orbit[:,4]= -self._gap_progenitor._orb.orbit[:,4] return None
[ "def", "_gap_progenitor_setup", "(", "self", ")", ":", "self", ".", "_gap_progenitor", "=", "self", ".", "_progenitor", "(", ")", ".", "flip", "(", ")", "# new orbit, flip velocities", "# Make sure we do not use physical coordinates", "self", ".", "_gap_progenitor", "...
Setup an Orbit instance that's the progenitor integrated backwards
[ "Setup", "an", "Orbit", "instance", "that", "s", "the", "progenitor", "integrated", "backwards" ]
9c5b9fe65d58835624dffe432be282060918ee08
https://github.com/jobovy/galpy/blob/9c5b9fe65d58835624dffe432be282060918ee08/galpy/df/streamgapdf.py#L963-L975
train
27,925
jobovy/galpy
galpy/df/streamgapdf.py
streamgapdf._sample_aAt
def _sample_aAt(self,n): """Sampling frequencies, angles, and times part of sampling, for stream with gap""" # Use streamdf's _sample_aAt to generate unperturbed frequencies, # angles Om,angle,dt= super(streamgapdf,self)._sample_aAt(n) # Now rewind angles by timpact, apply the kicks, and run forward again dangle_at_impact= angle-numpy.tile(self._progenitor_angle.T,(n,1)).T\ -(Om-numpy.tile(self._progenitor_Omega.T,(n,1)).T)*self._timpact dangle_par_at_impact= numpy.dot(dangle_at_impact.T, self._dsigomeanProgDirection)\ *self._gap_sigMeanSign # Calculate and apply kicks (points not yet released have zero kick) dOr= self._kick_interpdOr(dangle_par_at_impact) dOp= self._kick_interpdOp(dangle_par_at_impact) dOz= self._kick_interpdOz(dangle_par_at_impact) Om[0,:]+= dOr Om[1,:]+= dOp Om[2,:]+= dOz angle[0,:]+=\ self._kick_interpdar(dangle_par_at_impact)+dOr*self._timpact angle[1,:]+=\ self._kick_interpdap(dangle_par_at_impact)+dOp*self._timpact angle[2,:]+=\ self._kick_interpdaz(dangle_par_at_impact)+dOz*self._timpact return (Om,angle,dt)
python
def _sample_aAt(self,n): """Sampling frequencies, angles, and times part of sampling, for stream with gap""" # Use streamdf's _sample_aAt to generate unperturbed frequencies, # angles Om,angle,dt= super(streamgapdf,self)._sample_aAt(n) # Now rewind angles by timpact, apply the kicks, and run forward again dangle_at_impact= angle-numpy.tile(self._progenitor_angle.T,(n,1)).T\ -(Om-numpy.tile(self._progenitor_Omega.T,(n,1)).T)*self._timpact dangle_par_at_impact= numpy.dot(dangle_at_impact.T, self._dsigomeanProgDirection)\ *self._gap_sigMeanSign # Calculate and apply kicks (points not yet released have zero kick) dOr= self._kick_interpdOr(dangle_par_at_impact) dOp= self._kick_interpdOp(dangle_par_at_impact) dOz= self._kick_interpdOz(dangle_par_at_impact) Om[0,:]+= dOr Om[1,:]+= dOp Om[2,:]+= dOz angle[0,:]+=\ self._kick_interpdar(dangle_par_at_impact)+dOr*self._timpact angle[1,:]+=\ self._kick_interpdap(dangle_par_at_impact)+dOp*self._timpact angle[2,:]+=\ self._kick_interpdaz(dangle_par_at_impact)+dOz*self._timpact return (Om,angle,dt)
[ "def", "_sample_aAt", "(", "self", ",", "n", ")", ":", "# Use streamdf's _sample_aAt to generate unperturbed frequencies,", "# angles", "Om", ",", "angle", ",", "dt", "=", "super", "(", "streamgapdf", ",", "self", ")", ".", "_sample_aAt", "(", "n", ")", "# Now r...
Sampling frequencies, angles, and times part of sampling, for stream with gap
[ "Sampling", "frequencies", "angles", "and", "times", "part", "of", "sampling", "for", "stream", "with", "gap" ]
9c5b9fe65d58835624dffe432be282060918ee08
https://github.com/jobovy/galpy/blob/9c5b9fe65d58835624dffe432be282060918ee08/galpy/df/streamgapdf.py#L978-L1002
train
27,926
jobovy/galpy
galpy/util/multi.py
worker
def worker(f, ii, chunk, out_q, err_q, lock): """ A worker function that maps an input function over a slice of the input iterable. :param f : callable function that accepts argument from iterable :param ii : process ID :param chunk: slice of input iterable :param out_q: thread-safe output queue :param err_q: thread-safe queue to populate on exception :param lock : thread-safe lock to protect a resource ( useful in extending parallel_map() ) """ vals = [] # iterate over slice for val in chunk: try: result = f(val) except Exception as e: err_q.put(e) return vals.append(result) # output the result and task ID to output queue out_q.put( (ii, vals) )
python
def worker(f, ii, chunk, out_q, err_q, lock): """ A worker function that maps an input function over a slice of the input iterable. :param f : callable function that accepts argument from iterable :param ii : process ID :param chunk: slice of input iterable :param out_q: thread-safe output queue :param err_q: thread-safe queue to populate on exception :param lock : thread-safe lock to protect a resource ( useful in extending parallel_map() ) """ vals = [] # iterate over slice for val in chunk: try: result = f(val) except Exception as e: err_q.put(e) return vals.append(result) # output the result and task ID to output queue out_q.put( (ii, vals) )
[ "def", "worker", "(", "f", ",", "ii", ",", "chunk", ",", "out_q", ",", "err_q", ",", "lock", ")", ":", "vals", "=", "[", "]", "# iterate over slice ", "for", "val", "in", "chunk", ":", "try", ":", "result", "=", "f", "(", "val", ")", "except", "E...
A worker function that maps an input function over a slice of the input iterable. :param f : callable function that accepts argument from iterable :param ii : process ID :param chunk: slice of input iterable :param out_q: thread-safe output queue :param err_q: thread-safe queue to populate on exception :param lock : thread-safe lock to protect a resource ( useful in extending parallel_map() )
[ "A", "worker", "function", "that", "maps", "an", "input", "function", "over", "a", "slice", "of", "the", "input", "iterable", "." ]
9c5b9fe65d58835624dffe432be282060918ee08
https://github.com/jobovy/galpy/blob/9c5b9fe65d58835624dffe432be282060918ee08/galpy/util/multi.py#L53-L79
train
27,927
jobovy/galpy
galpy/util/multi.py
run_tasks
def run_tasks(procs, err_q, out_q, num): """ A function that executes populated processes and processes the resultant array. Checks error queue for any exceptions. :param procs: list of Process objects :param out_q: thread-safe output queue :param err_q: thread-safe queue to populate on exception :param num : length of resultant array """ # function to terminate processes that are still running. die = (lambda vals : [val.terminate() for val in vals if val.exitcode is None]) try: for proc in procs: proc.start() for proc in procs: proc.join() except Exception as e: # kill all slave processes on ctrl-C try: die(procs) finally: raise e if not err_q.empty(): # kill all on any exception from any one slave try: die(procs) finally: raise err_q.get() # Processes finish in arbitrary order. Process IDs double # as index in the resultant array. results=[None]*num; while not out_q.empty(): idx, result = out_q.get() results[idx] = result # Remove extra dimension added by array_split return list(numpy.concatenate(results))
python
def run_tasks(procs, err_q, out_q, num): """ A function that executes populated processes and processes the resultant array. Checks error queue for any exceptions. :param procs: list of Process objects :param out_q: thread-safe output queue :param err_q: thread-safe queue to populate on exception :param num : length of resultant array """ # function to terminate processes that are still running. die = (lambda vals : [val.terminate() for val in vals if val.exitcode is None]) try: for proc in procs: proc.start() for proc in procs: proc.join() except Exception as e: # kill all slave processes on ctrl-C try: die(procs) finally: raise e if not err_q.empty(): # kill all on any exception from any one slave try: die(procs) finally: raise err_q.get() # Processes finish in arbitrary order. Process IDs double # as index in the resultant array. results=[None]*num; while not out_q.empty(): idx, result = out_q.get() results[idx] = result # Remove extra dimension added by array_split return list(numpy.concatenate(results))
[ "def", "run_tasks", "(", "procs", ",", "err_q", ",", "out_q", ",", "num", ")", ":", "# function to terminate processes that are still running.", "die", "=", "(", "lambda", "vals", ":", "[", "val", ".", "terminate", "(", ")", "for", "val", "in", "vals", "if",...
A function that executes populated processes and processes the resultant array. Checks error queue for any exceptions. :param procs: list of Process objects :param out_q: thread-safe output queue :param err_q: thread-safe queue to populate on exception :param num : length of resultant array
[ "A", "function", "that", "executes", "populated", "processes", "and", "processes", "the", "resultant", "array", ".", "Checks", "error", "queue", "for", "any", "exceptions", "." ]
9c5b9fe65d58835624dffe432be282060918ee08
https://github.com/jobovy/galpy/blob/9c5b9fe65d58835624dffe432be282060918ee08/galpy/util/multi.py#L82-L126
train
27,928
jobovy/galpy
galpy/util/multi.py
parallel_map
def parallel_map(function, sequence, numcores=None): """ A parallelized version of the native Python map function that utilizes the Python multiprocessing module to divide and conquer sequence. parallel_map does not yet support multiple argument sequences. :param function: callable function that accepts argument from iterable :param sequence: iterable sequence :param numcores: number of cores to use """ if not callable(function): raise TypeError("input function '%s' is not callable" % repr(function)) if not numpy.iterable(sequence): raise TypeError("input '%s' is not iterable" % repr(sequence)) size = len(sequence) if not _multi or size == 1: return map(function, sequence) if numcores is None: numcores = _ncpus if platform.system() == 'Windows': # JB: don't think this works on Win return list(map(function,sequence)) # Returns a started SyncManager object which can be used for sharing # objects between processes. The returned manager object corresponds # to a spawned child process and has methods which will create shared # objects and return corresponding proxies. manager = multiprocessing.Manager() # Create FIFO queue and lock shared objects and return proxies to them. # The managers handles a server process that manages shared objects that # each slave process has access to. Bottom line -- thread-safe. out_q = manager.Queue() err_q = manager.Queue() lock = manager.Lock() # if sequence is less than numcores, only use len sequence number of # processes if size < numcores: numcores = size # group sequence into numcores-worth of chunks sequence = numpy.array_split(sequence, numcores) procs = [multiprocessing.Process(target=worker, args=(function, ii, chunk, out_q, err_q, lock)) for ii, chunk in enumerate(sequence)] return run_tasks(procs, err_q, out_q, numcores)
python
def parallel_map(function, sequence, numcores=None): """ A parallelized version of the native Python map function that utilizes the Python multiprocessing module to divide and conquer sequence. parallel_map does not yet support multiple argument sequences. :param function: callable function that accepts argument from iterable :param sequence: iterable sequence :param numcores: number of cores to use """ if not callable(function): raise TypeError("input function '%s' is not callable" % repr(function)) if not numpy.iterable(sequence): raise TypeError("input '%s' is not iterable" % repr(sequence)) size = len(sequence) if not _multi or size == 1: return map(function, sequence) if numcores is None: numcores = _ncpus if platform.system() == 'Windows': # JB: don't think this works on Win return list(map(function,sequence)) # Returns a started SyncManager object which can be used for sharing # objects between processes. The returned manager object corresponds # to a spawned child process and has methods which will create shared # objects and return corresponding proxies. manager = multiprocessing.Manager() # Create FIFO queue and lock shared objects and return proxies to them. # The managers handles a server process that manages shared objects that # each slave process has access to. Bottom line -- thread-safe. out_q = manager.Queue() err_q = manager.Queue() lock = manager.Lock() # if sequence is less than numcores, only use len sequence number of # processes if size < numcores: numcores = size # group sequence into numcores-worth of chunks sequence = numpy.array_split(sequence, numcores) procs = [multiprocessing.Process(target=worker, args=(function, ii, chunk, out_q, err_q, lock)) for ii, chunk in enumerate(sequence)] return run_tasks(procs, err_q, out_q, numcores)
[ "def", "parallel_map", "(", "function", ",", "sequence", ",", "numcores", "=", "None", ")", ":", "if", "not", "callable", "(", "function", ")", ":", "raise", "TypeError", "(", "\"input function '%s' is not callable\"", "%", "repr", "(", "function", ")", ")", ...
A parallelized version of the native Python map function that utilizes the Python multiprocessing module to divide and conquer sequence. parallel_map does not yet support multiple argument sequences. :param function: callable function that accepts argument from iterable :param sequence: iterable sequence :param numcores: number of cores to use
[ "A", "parallelized", "version", "of", "the", "native", "Python", "map", "function", "that", "utilizes", "the", "Python", "multiprocessing", "module", "to", "divide", "and", "conquer", "sequence", "." ]
9c5b9fe65d58835624dffe432be282060918ee08
https://github.com/jobovy/galpy/blob/9c5b9fe65d58835624dffe432be282060918ee08/galpy/util/multi.py#L129-L185
train
27,929
jobovy/galpy
galpy/actionAngle/actionAngleStaeckelGrid.py
_u0Eq
def _u0Eq(logu,delta,pot,E,Lz22): """The equation that needs to be minimized to find u0""" u= numpy.exp(logu) sinh2u= numpy.sinh(u)**2. cosh2u= numpy.cosh(u)**2. dU= cosh2u*actionAngleStaeckel.potentialStaeckel(u,numpy.pi/2.,pot,delta) return -(E*sinh2u-dU-Lz22/delta**2./sinh2u)
python
def _u0Eq(logu,delta,pot,E,Lz22): """The equation that needs to be minimized to find u0""" u= numpy.exp(logu) sinh2u= numpy.sinh(u)**2. cosh2u= numpy.cosh(u)**2. dU= cosh2u*actionAngleStaeckel.potentialStaeckel(u,numpy.pi/2.,pot,delta) return -(E*sinh2u-dU-Lz22/delta**2./sinh2u)
[ "def", "_u0Eq", "(", "logu", ",", "delta", ",", "pot", ",", "E", ",", "Lz22", ")", ":", "u", "=", "numpy", ".", "exp", "(", "logu", ")", "sinh2u", "=", "numpy", ".", "sinh", "(", "u", ")", "**", "2.", "cosh2u", "=", "numpy", ".", "cosh", "(",...
The equation that needs to be minimized to find u0
[ "The", "equation", "that", "needs", "to", "be", "minimized", "to", "find", "u0" ]
9c5b9fe65d58835624dffe432be282060918ee08
https://github.com/jobovy/galpy/blob/9c5b9fe65d58835624dffe432be282060918ee08/galpy/actionAngle/actionAngleStaeckelGrid.py#L672-L678
train
27,930
jobovy/galpy
galpy/actionAngle/actionAngleSpherical.py
_JrSphericalIntegrand
def _JrSphericalIntegrand(r,E,L,pot): """The J_r integrand""" return nu.sqrt(2.*(E-potentialAxi(r,pot))-L**2./r**2.)
python
def _JrSphericalIntegrand(r,E,L,pot): """The J_r integrand""" return nu.sqrt(2.*(E-potentialAxi(r,pot))-L**2./r**2.)
[ "def", "_JrSphericalIntegrand", "(", "r", ",", "E", ",", "L", ",", "pot", ")", ":", "return", "nu", ".", "sqrt", "(", "2.", "*", "(", "E", "-", "potentialAxi", "(", "r", ",", "pot", ")", ")", "-", "L", "**", "2.", "/", "r", "**", "2.", ")" ]
The J_r integrand
[ "The", "J_r", "integrand" ]
9c5b9fe65d58835624dffe432be282060918ee08
https://github.com/jobovy/galpy/blob/9c5b9fe65d58835624dffe432be282060918ee08/galpy/actionAngle/actionAngleSpherical.py#L538-L540
train
27,931
jobovy/galpy
galpy/potential/FerrersPotential.py
FerrersPotential.rot
def rot(self, t=0., transposed=False): """2D Rotation matrix for non-zero pa or pattern speed to goto the aligned coordinates """ rotmat = np.array( [[np.cos(self._pa+self._omegab*t),np.sin(self._pa+self._omegab*t)], [-np.sin(self._pa+self._omegab*t),np.cos(self._pa+self._omegab*t)]]) if transposed: return rotmat.T else: return rotmat
python
def rot(self, t=0., transposed=False): """2D Rotation matrix for non-zero pa or pattern speed to goto the aligned coordinates """ rotmat = np.array( [[np.cos(self._pa+self._omegab*t),np.sin(self._pa+self._omegab*t)], [-np.sin(self._pa+self._omegab*t),np.cos(self._pa+self._omegab*t)]]) if transposed: return rotmat.T else: return rotmat
[ "def", "rot", "(", "self", ",", "t", "=", "0.", ",", "transposed", "=", "False", ")", ":", "rotmat", "=", "np", ".", "array", "(", "[", "[", "np", ".", "cos", "(", "self", ".", "_pa", "+", "self", ".", "_omegab", "*", "t", ")", ",", "np", "...
2D Rotation matrix for non-zero pa or pattern speed to goto the aligned coordinates
[ "2D", "Rotation", "matrix", "for", "non", "-", "zero", "pa", "or", "pattern", "speed", "to", "goto", "the", "aligned", "coordinates" ]
9c5b9fe65d58835624dffe432be282060918ee08
https://github.com/jobovy/galpy/blob/9c5b9fe65d58835624dffe432be282060918ee08/galpy/potential/FerrersPotential.py#L407-L417
train
27,932
jobovy/galpy
galpy/actionAngle/actionAngleVertical.py
_JzIntegrand
def _JzIntegrand(z,Ez,pot): """The J_z integrand""" return nu.sqrt(2.*(Ez-potentialVertical(z,pot)))
python
def _JzIntegrand(z,Ez,pot): """The J_z integrand""" return nu.sqrt(2.*(Ez-potentialVertical(z,pot)))
[ "def", "_JzIntegrand", "(", "z", ",", "Ez", ",", "pot", ")", ":", "return", "nu", ".", "sqrt", "(", "2.", "*", "(", "Ez", "-", "potentialVertical", "(", "z", ",", "pot", ")", ")", ")" ]
The J_z integrand
[ "The", "J_z", "integrand" ]
9c5b9fe65d58835624dffe432be282060918ee08
https://github.com/jobovy/galpy/blob/9c5b9fe65d58835624dffe432be282060918ee08/galpy/actionAngle/actionAngleVertical.py#L187-L189
train
27,933
ContinuumIO/menuinst
menuinst/win32.py
quoted
def quoted(s): """ quotes a string if necessary. """ # strip any existing quotes s = s.strip(u'"') # don't add quotes for minus or leading space if s[0] in (u'-', u' '): return s if u' ' in s or u'/' in s: return u'"%s"' % s else: return s
python
def quoted(s): """ quotes a string if necessary. """ # strip any existing quotes s = s.strip(u'"') # don't add quotes for minus or leading space if s[0] in (u'-', u' '): return s if u' ' in s or u'/' in s: return u'"%s"' % s else: return s
[ "def", "quoted", "(", "s", ")", ":", "# strip any existing quotes", "s", "=", "s", ".", "strip", "(", "u'\"'", ")", "# don't add quotes for minus or leading space", "if", "s", "[", "0", "]", "in", "(", "u'-'", ",", "u' '", ")", ":", "return", "s", "if", ...
quotes a string if necessary.
[ "quotes", "a", "string", "if", "necessary", "." ]
dae53065e9e82a3352b817cca5895a9b271ddfdb
https://github.com/ContinuumIO/menuinst/blob/dae53065e9e82a3352b817cca5895a9b271ddfdb/menuinst/win32.py#L106-L118
train
27,934
ContinuumIO/menuinst
menuinst/__init__.py
install
def install(path, remove=False, prefix=sys.prefix, recursing=False): """ install Menu and shortcuts """ # this sys.prefix is intentional. We want to reflect the state of the root installation. if sys.platform == 'win32' and not exists(join(sys.prefix, '.nonadmin')): if isUserAdmin(): _install(path, remove, prefix, mode='system') else: from pywintypes import error try: if not recursing: retcode = runAsAdmin([join(sys.prefix, 'python'), '-c', "import menuinst; menuinst.install(%r, %r, %r, %r)" % ( path, bool(remove), prefix, True)]) else: retcode = 1 except error: retcode = 1 if retcode != 0: logging.warn("Insufficient permissions to write menu folder. " "Falling back to user location") _install(path, remove, prefix, mode='user') else: _install(path, remove, prefix, mode='user')
python
def install(path, remove=False, prefix=sys.prefix, recursing=False): """ install Menu and shortcuts """ # this sys.prefix is intentional. We want to reflect the state of the root installation. if sys.platform == 'win32' and not exists(join(sys.prefix, '.nonadmin')): if isUserAdmin(): _install(path, remove, prefix, mode='system') else: from pywintypes import error try: if not recursing: retcode = runAsAdmin([join(sys.prefix, 'python'), '-c', "import menuinst; menuinst.install(%r, %r, %r, %r)" % ( path, bool(remove), prefix, True)]) else: retcode = 1 except error: retcode = 1 if retcode != 0: logging.warn("Insufficient permissions to write menu folder. " "Falling back to user location") _install(path, remove, prefix, mode='user') else: _install(path, remove, prefix, mode='user')
[ "def", "install", "(", "path", ",", "remove", "=", "False", ",", "prefix", "=", "sys", ".", "prefix", ",", "recursing", "=", "False", ")", ":", "# this sys.prefix is intentional. We want to reflect the state of the root installation.", "if", "sys", ".", "platform", ...
install Menu and shortcuts
[ "install", "Menu", "and", "shortcuts" ]
dae53065e9e82a3352b817cca5895a9b271ddfdb
https://github.com/ContinuumIO/menuinst/blob/dae53065e9e82a3352b817cca5895a9b271ddfdb/menuinst/__init__.py#L51-L76
train
27,935
ContinuumIO/menuinst
menuinst/linux.py
add_child
def add_child(parent, tag, text=None): """ Add a child element of specified tag type to parent. The new child element is returned. """ elem = ET.SubElement(parent, tag) if text is not None: elem.text = text return elem
python
def add_child(parent, tag, text=None): """ Add a child element of specified tag type to parent. The new child element is returned. """ elem = ET.SubElement(parent, tag) if text is not None: elem.text = text return elem
[ "def", "add_child", "(", "parent", ",", "tag", ",", "text", "=", "None", ")", ":", "elem", "=", "ET", ".", "SubElement", "(", "parent", ",", "tag", ")", "if", "text", "is", "not", "None", ":", "elem", ".", "text", "=", "text", "return", "elem" ]
Add a child element of specified tag type to parent. The new child element is returned.
[ "Add", "a", "child", "element", "of", "specified", "tag", "type", "to", "parent", ".", "The", "new", "child", "element", "is", "returned", "." ]
dae53065e9e82a3352b817cca5895a9b271ddfdb
https://github.com/ContinuumIO/menuinst/blob/dae53065e9e82a3352b817cca5895a9b271ddfdb/menuinst/linux.py#L61-L69
train
27,936
ContinuumIO/menuinst
menuinst/darwin.py
Application._writePlistInfo
def _writePlistInfo(self): """ Writes the Info.plist file in the Contests directory. """ pl = Plist( CFBundleExecutable=self.executable, CFBundleGetInfoString='%s-1.0.0' % self.name, CFBundleIconFile=basename(self.icns), CFBundleIdentifier='com.%s' % self.name, CFBundlePackageType='APPL', CFBundleVersion='1.0.0', CFBundleShortVersionString='1.0.0', ) writePlist(pl, join(self.contents_dir, 'Info.plist'))
python
def _writePlistInfo(self): """ Writes the Info.plist file in the Contests directory. """ pl = Plist( CFBundleExecutable=self.executable, CFBundleGetInfoString='%s-1.0.0' % self.name, CFBundleIconFile=basename(self.icns), CFBundleIdentifier='com.%s' % self.name, CFBundlePackageType='APPL', CFBundleVersion='1.0.0', CFBundleShortVersionString='1.0.0', ) writePlist(pl, join(self.contents_dir, 'Info.plist'))
[ "def", "_writePlistInfo", "(", "self", ")", ":", "pl", "=", "Plist", "(", "CFBundleExecutable", "=", "self", ".", "executable", ",", "CFBundleGetInfoString", "=", "'%s-1.0.0'", "%", "self", ".", "name", ",", "CFBundleIconFile", "=", "basename", "(", "self", ...
Writes the Info.plist file in the Contests directory.
[ "Writes", "the", "Info", ".", "plist", "file", "in", "the", "Contests", "directory", "." ]
dae53065e9e82a3352b817cca5895a9b271ddfdb
https://github.com/ContinuumIO/menuinst/blob/dae53065e9e82a3352b817cca5895a9b271ddfdb/menuinst/darwin.py#L93-L106
train
27,937
SuperCowPowers/bat
bat/utils/file_tailer.py
FileTailer.readlines
def readlines(self, offset=0): """Open the file for reading and yield lines as they are added""" try: with open(self._filepath) as fp: # For full read go through existing lines in file if self._full_read: fp.seek(offset) for row in fp: yield row # Okay now dynamically tail the file if self._tail: while True: current = fp.tell() row = fp.readline() if row: yield row else: fp.seek(current) time.sleep(self._sleep) except IOError as err: print('Error reading the file {0}: {1}'.format(self._filepath, err)) return
python
def readlines(self, offset=0): """Open the file for reading and yield lines as they are added""" try: with open(self._filepath) as fp: # For full read go through existing lines in file if self._full_read: fp.seek(offset) for row in fp: yield row # Okay now dynamically tail the file if self._tail: while True: current = fp.tell() row = fp.readline() if row: yield row else: fp.seek(current) time.sleep(self._sleep) except IOError as err: print('Error reading the file {0}: {1}'.format(self._filepath, err)) return
[ "def", "readlines", "(", "self", ",", "offset", "=", "0", ")", ":", "try", ":", "with", "open", "(", "self", ".", "_filepath", ")", "as", "fp", ":", "# For full read go through existing lines in file", "if", "self", ".", "_full_read", ":", "fp", ".", "seek...
Open the file for reading and yield lines as they are added
[ "Open", "the", "file", "for", "reading", "and", "yield", "lines", "as", "they", "are", "added" ]
069e6bc52843dc07760969c531cc442ca7da8e0c
https://github.com/SuperCowPowers/bat/blob/069e6bc52843dc07760969c531cc442ca7da8e0c/bat/utils/file_tailer.py#L27-L50
train
27,938
SuperCowPowers/bat
setup.py
get_files
def get_files(dir_name): """Simple directory walker""" return [(os.path.join('.', d), [os.path.join(d, f) for f in files]) for d, _, files in os.walk(dir_name)]
python
def get_files(dir_name): """Simple directory walker""" return [(os.path.join('.', d), [os.path.join(d, f) for f in files]) for d, _, files in os.walk(dir_name)]
[ "def", "get_files", "(", "dir_name", ")", ":", "return", "[", "(", "os", ".", "path", ".", "join", "(", "'.'", ",", "d", ")", ",", "[", "os", ".", "path", ".", "join", "(", "d", ",", "f", ")", "for", "f", "in", "files", "]", ")", "for", "d"...
Simple directory walker
[ "Simple", "directory", "walker" ]
069e6bc52843dc07760969c531cc442ca7da8e0c
https://github.com/SuperCowPowers/bat/blob/069e6bc52843dc07760969c531cc442ca7da8e0c/setup.py#L19-L21
train
27,939
SuperCowPowers/bat
bat/bro_multi_log_reader.py
BroMultiLogReader.readrows
def readrows(self): """The readrows method reads simply 'combines' the rows of multiple files OR gunzips the file and then reads the rows """ # For each file (may be just one) create a BroLogReader and use it for self._filepath in self._files: # Check if the file is zipped tmp = None if self._filepath.endswith('.gz'): tmp = tempfile.NamedTemporaryFile(delete=False) with gzip.open(self._filepath, 'rb') as f_in, open(tmp.name, 'wb') as f_out: shutil.copyfileobj(f_in, f_out) # Set the file path to the new temp file self._filepath = tmp.name # Create a BroLogReader reader = bro_log_reader.BroLogReader(self._filepath) for row in reader.readrows(): yield row # Clean up any temp files try: if tmp: os.remove(tmp.name) print('Removed temporary file {:s}...'.format(tmp.name)) except IOError: pass
python
def readrows(self): """The readrows method reads simply 'combines' the rows of multiple files OR gunzips the file and then reads the rows """ # For each file (may be just one) create a BroLogReader and use it for self._filepath in self._files: # Check if the file is zipped tmp = None if self._filepath.endswith('.gz'): tmp = tempfile.NamedTemporaryFile(delete=False) with gzip.open(self._filepath, 'rb') as f_in, open(tmp.name, 'wb') as f_out: shutil.copyfileobj(f_in, f_out) # Set the file path to the new temp file self._filepath = tmp.name # Create a BroLogReader reader = bro_log_reader.BroLogReader(self._filepath) for row in reader.readrows(): yield row # Clean up any temp files try: if tmp: os.remove(tmp.name) print('Removed temporary file {:s}...'.format(tmp.name)) except IOError: pass
[ "def", "readrows", "(", "self", ")", ":", "# For each file (may be just one) create a BroLogReader and use it", "for", "self", ".", "_filepath", "in", "self", ".", "_files", ":", "# Check if the file is zipped", "tmp", "=", "None", "if", "self", ".", "_filepath", ".",...
The readrows method reads simply 'combines' the rows of multiple files OR gunzips the file and then reads the rows
[ "The", "readrows", "method", "reads", "simply", "combines", "the", "rows", "of", "multiple", "files", "OR", "gunzips", "the", "file", "and", "then", "reads", "the", "rows" ]
069e6bc52843dc07760969c531cc442ca7da8e0c
https://github.com/SuperCowPowers/bat/blob/069e6bc52843dc07760969c531cc442ca7da8e0c/bat/bro_multi_log_reader.py#L30-L59
train
27,940
SuperCowPowers/bat
bat/utils/file_utils.py
most_recent
def most_recent(path, startswith=None, endswith=None): """Recursively inspect all files under a directory and return the most recent Args: path (str): the path of the directory to traverse startswith (str): the file name start with (optional) endswith (str): the file name ends with (optional) Returns: the most recent file within the subdirectory """ candidate_files = [] for filename in all_files_in_directory(path): if startswith and not os.path.basename(filename).startswith(startswith): continue if endswith and not filename.endswith(endswith): continue candidate_files.append({'name': filename, 'modtime': os.path.getmtime(filename)}) # Return the most recent modtime most_recent = sorted(candidate_files, key=lambda k: k['modtime'], reverse=True) return most_recent[0]['name'] if most_recent else None
python
def most_recent(path, startswith=None, endswith=None): """Recursively inspect all files under a directory and return the most recent Args: path (str): the path of the directory to traverse startswith (str): the file name start with (optional) endswith (str): the file name ends with (optional) Returns: the most recent file within the subdirectory """ candidate_files = [] for filename in all_files_in_directory(path): if startswith and not os.path.basename(filename).startswith(startswith): continue if endswith and not filename.endswith(endswith): continue candidate_files.append({'name': filename, 'modtime': os.path.getmtime(filename)}) # Return the most recent modtime most_recent = sorted(candidate_files, key=lambda k: k['modtime'], reverse=True) return most_recent[0]['name'] if most_recent else None
[ "def", "most_recent", "(", "path", ",", "startswith", "=", "None", ",", "endswith", "=", "None", ")", ":", "candidate_files", "=", "[", "]", "for", "filename", "in", "all_files_in_directory", "(", "path", ")", ":", "if", "startswith", "and", "not", "os", ...
Recursively inspect all files under a directory and return the most recent Args: path (str): the path of the directory to traverse startswith (str): the file name start with (optional) endswith (str): the file name ends with (optional) Returns: the most recent file within the subdirectory
[ "Recursively", "inspect", "all", "files", "under", "a", "directory", "and", "return", "the", "most", "recent" ]
069e6bc52843dc07760969c531cc442ca7da8e0c
https://github.com/SuperCowPowers/bat/blob/069e6bc52843dc07760969c531cc442ca7da8e0c/bat/utils/file_utils.py#L23-L43
train
27,941
SuperCowPowers/bat
examples/yara_matches.py
yara_match
def yara_match(file_path, rules): """Callback for a newly extracted file""" print('New Extracted File: {:s}'.format(file_path)) print('Mathes:') pprint(rules.match(file_path))
python
def yara_match(file_path, rules): """Callback for a newly extracted file""" print('New Extracted File: {:s}'.format(file_path)) print('Mathes:') pprint(rules.match(file_path))
[ "def", "yara_match", "(", "file_path", ",", "rules", ")", ":", "print", "(", "'New Extracted File: {:s}'", ".", "format", "(", "file_path", ")", ")", "print", "(", "'Mathes:'", ")", "pprint", "(", "rules", ".", "match", "(", "file_path", ")", ")" ]
Callback for a newly extracted file
[ "Callback", "for", "a", "newly", "extracted", "file" ]
069e6bc52843dc07760969c531cc442ca7da8e0c
https://github.com/SuperCowPowers/bat/blob/069e6bc52843dc07760969c531cc442ca7da8e0c/examples/yara_matches.py#L23-L27
train
27,942
SuperCowPowers/bat
bat/live_simulator.py
LiveSimulator.readrows
def readrows(self): """Using the BroLogReader this method yields each row of the log file replacing timestamps, looping and emitting rows based on EPS rate """ # Loop forever or until max_rows is reached num_rows = 0 while True: # Yield the rows from the internal reader for row in self.log_reader.readrows(): yield self.replace_timestamp(row) # Sleep and count rows time.sleep(next(self.eps_timer)) num_rows += 1 # Check for max_rows if self.max_rows and (num_rows >= self.max_rows): return
python
def readrows(self): """Using the BroLogReader this method yields each row of the log file replacing timestamps, looping and emitting rows based on EPS rate """ # Loop forever or until max_rows is reached num_rows = 0 while True: # Yield the rows from the internal reader for row in self.log_reader.readrows(): yield self.replace_timestamp(row) # Sleep and count rows time.sleep(next(self.eps_timer)) num_rows += 1 # Check for max_rows if self.max_rows and (num_rows >= self.max_rows): return
[ "def", "readrows", "(", "self", ")", ":", "# Loop forever or until max_rows is reached", "num_rows", "=", "0", "while", "True", ":", "# Yield the rows from the internal reader", "for", "row", "in", "self", ".", "log_reader", ".", "readrows", "(", ")", ":", "yield", ...
Using the BroLogReader this method yields each row of the log file replacing timestamps, looping and emitting rows based on EPS rate
[ "Using", "the", "BroLogReader", "this", "method", "yields", "each", "row", "of", "the", "log", "file", "replacing", "timestamps", "looping", "and", "emitting", "rows", "based", "on", "EPS", "rate" ]
069e6bc52843dc07760969c531cc442ca7da8e0c
https://github.com/SuperCowPowers/bat/blob/069e6bc52843dc07760969c531cc442ca7da8e0c/bat/live_simulator.py#L48-L67
train
27,943
SuperCowPowers/bat
bat/bro_log_reader.py
BroLogReader._parse_bro_header
def _parse_bro_header(self, bro_log): """Parse the Bro log header section. Format example: #separator \x09 #set_separator , #empty_field (empty) #unset_field - #path httpheader_recon #fields ts origin useragent header_events_json #types time string string string """ # Open the Bro logfile with open(bro_log, 'r') as bro_file: # Skip until you find the #fields line _line = bro_file.readline() while not _line.startswith('#fields'): _line = bro_file.readline() # Read in the field names field_names = _line.strip().split(self._delimiter)[1:] # Read in the types _line = bro_file.readline() field_types = _line.strip().split(self._delimiter)[1:] # Setup the type converters type_converters = [] for field_type in field_types: type_converters.append(self.type_mapper.get(field_type, self.type_mapper['unknown'])) # Keep the header offset offset = bro_file.tell() # Return the header info return offset, field_names, field_types, type_converters
python
def _parse_bro_header(self, bro_log): """Parse the Bro log header section. Format example: #separator \x09 #set_separator , #empty_field (empty) #unset_field - #path httpheader_recon #fields ts origin useragent header_events_json #types time string string string """ # Open the Bro logfile with open(bro_log, 'r') as bro_file: # Skip until you find the #fields line _line = bro_file.readline() while not _line.startswith('#fields'): _line = bro_file.readline() # Read in the field names field_names = _line.strip().split(self._delimiter)[1:] # Read in the types _line = bro_file.readline() field_types = _line.strip().split(self._delimiter)[1:] # Setup the type converters type_converters = [] for field_type in field_types: type_converters.append(self.type_mapper.get(field_type, self.type_mapper['unknown'])) # Keep the header offset offset = bro_file.tell() # Return the header info return offset, field_names, field_types, type_converters
[ "def", "_parse_bro_header", "(", "self", ",", "bro_log", ")", ":", "# Open the Bro logfile", "with", "open", "(", "bro_log", ",", "'r'", ")", "as", "bro_file", ":", "# Skip until you find the #fields line", "_line", "=", "bro_file", ".", "readline", "(", ")", "w...
Parse the Bro log header section. Format example: #separator \x09 #set_separator , #empty_field (empty) #unset_field - #path httpheader_recon #fields ts origin useragent header_events_json #types time string string string
[ "Parse", "the", "Bro", "log", "header", "section", "." ]
069e6bc52843dc07760969c531cc442ca7da8e0c
https://github.com/SuperCowPowers/bat/blob/069e6bc52843dc07760969c531cc442ca7da8e0c/bat/bro_log_reader.py#L115-L152
train
27,944
SuperCowPowers/bat
bat/bro_log_reader.py
BroLogReader.make_dict
def make_dict(self, field_values): ''' Internal method that makes sure any dictionary elements are properly cast into the correct types. ''' data_dict = {} for key, value, field_type, converter in zip(self.field_names, field_values, self.field_types, self.type_converters): try: # We have to deal with the '-' based on the field_type data_dict[key] = self.dash_mapper.get(field_type, '-') if value == '-' else converter(value) except ValueError as exc: print('Conversion Issue for key:{:s} value:{:s}\n{:s}'.format(key, str(value), str(exc))) data_dict[key] = value if self._strict: raise exc return data_dict
python
def make_dict(self, field_values): ''' Internal method that makes sure any dictionary elements are properly cast into the correct types. ''' data_dict = {} for key, value, field_type, converter in zip(self.field_names, field_values, self.field_types, self.type_converters): try: # We have to deal with the '-' based on the field_type data_dict[key] = self.dash_mapper.get(field_type, '-') if value == '-' else converter(value) except ValueError as exc: print('Conversion Issue for key:{:s} value:{:s}\n{:s}'.format(key, str(value), str(exc))) data_dict[key] = value if self._strict: raise exc return data_dict
[ "def", "make_dict", "(", "self", ",", "field_values", ")", ":", "data_dict", "=", "{", "}", "for", "key", ",", "value", ",", "field_type", ",", "converter", "in", "zip", "(", "self", ".", "field_names", ",", "field_values", ",", "self", ".", "field_types...
Internal method that makes sure any dictionary elements are properly cast into the correct types.
[ "Internal", "method", "that", "makes", "sure", "any", "dictionary", "elements", "are", "properly", "cast", "into", "the", "correct", "types", "." ]
069e6bc52843dc07760969c531cc442ca7da8e0c
https://github.com/SuperCowPowers/bat/blob/069e6bc52843dc07760969c531cc442ca7da8e0c/bat/bro_log_reader.py#L154-L169
train
27,945
SuperCowPowers/bat
bat/utils/net_utils.py
str_to_mac
def str_to_mac(mac_string): """Convert a readable string to a MAC address Args: mac_string (str): a readable string (e.g. '01:02:03:04:05:06') Returns: str: a MAC address in hex form """ sp = mac_string.split(':') mac_string = ''.join(sp) return binascii.unhexlify(mac_string)
python
def str_to_mac(mac_string): """Convert a readable string to a MAC address Args: mac_string (str): a readable string (e.g. '01:02:03:04:05:06') Returns: str: a MAC address in hex form """ sp = mac_string.split(':') mac_string = ''.join(sp) return binascii.unhexlify(mac_string)
[ "def", "str_to_mac", "(", "mac_string", ")", ":", "sp", "=", "mac_string", ".", "split", "(", "':'", ")", "mac_string", "=", "''", ".", "join", "(", "sp", ")", "return", "binascii", ".", "unhexlify", "(", "mac_string", ")" ]
Convert a readable string to a MAC address Args: mac_string (str): a readable string (e.g. '01:02:03:04:05:06') Returns: str: a MAC address in hex form
[ "Convert", "a", "readable", "string", "to", "a", "MAC", "address" ]
069e6bc52843dc07760969c531cc442ca7da8e0c
https://github.com/SuperCowPowers/bat/blob/069e6bc52843dc07760969c531cc442ca7da8e0c/bat/utils/net_utils.py#L22-L32
train
27,946
SuperCowPowers/bat
bat/utils/net_utils.py
inet_to_str
def inet_to_str(inet): """Convert inet object to a string Args: inet (inet struct): inet network address Returns: str: Printable/readable IP address """ # First try ipv4 and then ipv6 try: return socket.inet_ntop(socket.AF_INET, inet) except ValueError: return socket.inet_ntop(socket.AF_INET6, inet)
python
def inet_to_str(inet): """Convert inet object to a string Args: inet (inet struct): inet network address Returns: str: Printable/readable IP address """ # First try ipv4 and then ipv6 try: return socket.inet_ntop(socket.AF_INET, inet) except ValueError: return socket.inet_ntop(socket.AF_INET6, inet)
[ "def", "inet_to_str", "(", "inet", ")", ":", "# First try ipv4 and then ipv6", "try", ":", "return", "socket", ".", "inet_ntop", "(", "socket", ".", "AF_INET", ",", "inet", ")", "except", "ValueError", ":", "return", "socket", ".", "inet_ntop", "(", "socket", ...
Convert inet object to a string Args: inet (inet struct): inet network address Returns: str: Printable/readable IP address
[ "Convert", "inet", "object", "to", "a", "string" ]
069e6bc52843dc07760969c531cc442ca7da8e0c
https://github.com/SuperCowPowers/bat/blob/069e6bc52843dc07760969c531cc442ca7da8e0c/bat/utils/net_utils.py#L35-L47
train
27,947
SuperCowPowers/bat
bat/utils/net_utils.py
str_to_inet
def str_to_inet(address): """Convert an a string IP address to a inet struct Args: address (str): String representation of address Returns: inet: Inet network address """ # First try ipv4 and then ipv6 try: return socket.inet_pton(socket.AF_INET, address) except socket.error: return socket.inet_pton(socket.AF_INET6, address)
python
def str_to_inet(address): """Convert an a string IP address to a inet struct Args: address (str): String representation of address Returns: inet: Inet network address """ # First try ipv4 and then ipv6 try: return socket.inet_pton(socket.AF_INET, address) except socket.error: return socket.inet_pton(socket.AF_INET6, address)
[ "def", "str_to_inet", "(", "address", ")", ":", "# First try ipv4 and then ipv6", "try", ":", "return", "socket", ".", "inet_pton", "(", "socket", ".", "AF_INET", ",", "address", ")", "except", "socket", ".", "error", ":", "return", "socket", ".", "inet_pton",...
Convert an a string IP address to a inet struct Args: address (str): String representation of address Returns: inet: Inet network address
[ "Convert", "an", "a", "string", "IP", "address", "to", "a", "inet", "struct" ]
069e6bc52843dc07760969c531cc442ca7da8e0c
https://github.com/SuperCowPowers/bat/blob/069e6bc52843dc07760969c531cc442ca7da8e0c/bat/utils/net_utils.py#L50-L62
train
27,948
SuperCowPowers/bat
bat/utils/signal_utils.py
signal_catcher
def signal_catcher(callback): """Catch signals and invoke the callback method""" def _catch_exit_signal(sig_num, _frame): print('Received signal {:d} invoking callback...'.format(sig_num)) callback() signal.signal(signal.SIGINT, _catch_exit_signal) signal.signal(signal.SIGQUIT, _catch_exit_signal) signal.signal(signal.SIGTERM, _catch_exit_signal) yield
python
def signal_catcher(callback): """Catch signals and invoke the callback method""" def _catch_exit_signal(sig_num, _frame): print('Received signal {:d} invoking callback...'.format(sig_num)) callback() signal.signal(signal.SIGINT, _catch_exit_signal) signal.signal(signal.SIGQUIT, _catch_exit_signal) signal.signal(signal.SIGTERM, _catch_exit_signal) yield
[ "def", "signal_catcher", "(", "callback", ")", ":", "def", "_catch_exit_signal", "(", "sig_num", ",", "_frame", ")", ":", "print", "(", "'Received signal {:d} invoking callback...'", ".", "format", "(", "sig_num", ")", ")", "callback", "(", ")", "signal", ".", ...
Catch signals and invoke the callback method
[ "Catch", "signals", "and", "invoke", "the", "callback", "method" ]
069e6bc52843dc07760969c531cc442ca7da8e0c
https://github.com/SuperCowPowers/bat/blob/069e6bc52843dc07760969c531cc442ca7da8e0c/bat/utils/signal_utils.py#L11-L20
train
27,949
SuperCowPowers/bat
examples/anomaly_detection.py
entropy
def entropy(string): """Compute entropy on the string""" p, lns = Counter(string), float(len(string)) return -sum(count/lns * math.log(count/lns, 2) for count in p.values())
python
def entropy(string): """Compute entropy on the string""" p, lns = Counter(string), float(len(string)) return -sum(count/lns * math.log(count/lns, 2) for count in p.values())
[ "def", "entropy", "(", "string", ")", ":", "p", ",", "lns", "=", "Counter", "(", "string", ")", ",", "float", "(", "len", "(", "string", ")", ")", "return", "-", "sum", "(", "count", "/", "lns", "*", "math", ".", "log", "(", "count", "/", "lns"...
Compute entropy on the string
[ "Compute", "entropy", "on", "the", "string" ]
069e6bc52843dc07760969c531cc442ca7da8e0c
https://github.com/SuperCowPowers/bat/blob/069e6bc52843dc07760969c531cc442ca7da8e0c/examples/anomaly_detection.py#L18-L21
train
27,950
SuperCowPowers/bat
bat/utils/dir_watcher.py
DirWatcher.on_any_event
def on_any_event(self, event): """File created or modified""" if os.path.isfile(event.src_path): self.callback(event.src_path, **self.kwargs)
python
def on_any_event(self, event): """File created or modified""" if os.path.isfile(event.src_path): self.callback(event.src_path, **self.kwargs)
[ "def", "on_any_event", "(", "self", ",", "event", ")", ":", "if", "os", ".", "path", ".", "isfile", "(", "event", ".", "src_path", ")", ":", "self", ".", "callback", "(", "event", ".", "src_path", ",", "*", "*", "self", ".", "kwargs", ")" ]
File created or modified
[ "File", "created", "or", "modified" ]
069e6bc52843dc07760969c531cc442ca7da8e0c
https://github.com/SuperCowPowers/bat/blob/069e6bc52843dc07760969c531cc442ca7da8e0c/bat/utils/dir_watcher.py#L27-L30
train
27,951
SuperCowPowers/bat
bat/utils/reverse_dns.py
ReverseDNS.lookup
def lookup(self, ip_address): """Try to do a reverse dns lookup on the given ip_address""" # Is this already in our cache if self.ip_lookup_cache.get(ip_address): domain = self.ip_lookup_cache.get(ip_address) # Is the ip_address local or special elif not self.lookup_internal and net_utils.is_internal(ip_address): domain = 'internal' elif net_utils.is_special(ip_address): domain = net_utils.is_special(ip_address) # Look it up at this point else: domain = self._reverse_dns_lookup(ip_address) # Cache it self.ip_lookup_cache.set(ip_address, domain) # Return the domain return domain
python
def lookup(self, ip_address): """Try to do a reverse dns lookup on the given ip_address""" # Is this already in our cache if self.ip_lookup_cache.get(ip_address): domain = self.ip_lookup_cache.get(ip_address) # Is the ip_address local or special elif not self.lookup_internal and net_utils.is_internal(ip_address): domain = 'internal' elif net_utils.is_special(ip_address): domain = net_utils.is_special(ip_address) # Look it up at this point else: domain = self._reverse_dns_lookup(ip_address) # Cache it self.ip_lookup_cache.set(ip_address, domain) # Return the domain return domain
[ "def", "lookup", "(", "self", ",", "ip_address", ")", ":", "# Is this already in our cache", "if", "self", ".", "ip_lookup_cache", ".", "get", "(", "ip_address", ")", ":", "domain", "=", "self", ".", "ip_lookup_cache", ".", "get", "(", "ip_address", ")", "# ...
Try to do a reverse dns lookup on the given ip_address
[ "Try", "to", "do", "a", "reverse", "dns", "lookup", "on", "the", "given", "ip_address" ]
069e6bc52843dc07760969c531cc442ca7da8e0c
https://github.com/SuperCowPowers/bat/blob/069e6bc52843dc07760969c531cc442ca7da8e0c/bat/utils/reverse_dns.py#L17-L38
train
27,952
SuperCowPowers/bat
bat/dataframe_cache.py
DataFrameCache.add_rows
def add_rows(self, list_of_rows): """Add a list of rows to the DataFrameCache class""" for row in list_of_rows: self.row_deque.append(row) self.time_deque.append(time.time()) # Update the data structure self.update()
python
def add_rows(self, list_of_rows): """Add a list of rows to the DataFrameCache class""" for row in list_of_rows: self.row_deque.append(row) self.time_deque.append(time.time()) # Update the data structure self.update()
[ "def", "add_rows", "(", "self", ",", "list_of_rows", ")", ":", "for", "row", "in", "list_of_rows", ":", "self", ".", "row_deque", ".", "append", "(", "row", ")", "self", ".", "time_deque", ".", "append", "(", "time", ".", "time", "(", ")", ")", "# Up...
Add a list of rows to the DataFrameCache class
[ "Add", "a", "list", "of", "rows", "to", "the", "DataFrameCache", "class" ]
069e6bc52843dc07760969c531cc442ca7da8e0c
https://github.com/SuperCowPowers/bat/blob/069e6bc52843dc07760969c531cc442ca7da8e0c/bat/dataframe_cache.py#L27-L33
train
27,953
SuperCowPowers/bat
bat/dataframe_cache.py
DataFrameCache.update
def update(self): """Update the deque, removing rows based on time""" expire_time = time.time() - self.max_time while self.row_deque and self.time_deque[0] < expire_time: self.row_deque.popleft() # FIFO self.time_deque.popleft()
python
def update(self): """Update the deque, removing rows based on time""" expire_time = time.time() - self.max_time while self.row_deque and self.time_deque[0] < expire_time: self.row_deque.popleft() # FIFO self.time_deque.popleft()
[ "def", "update", "(", "self", ")", ":", "expire_time", "=", "time", ".", "time", "(", ")", "-", "self", ".", "max_time", "while", "self", ".", "row_deque", "and", "self", ".", "time_deque", "[", "0", "]", "<", "expire_time", ":", "self", ".", "row_de...
Update the deque, removing rows based on time
[ "Update", "the", "deque", "removing", "rows", "based", "on", "time" ]
069e6bc52843dc07760969c531cc442ca7da8e0c
https://github.com/SuperCowPowers/bat/blob/069e6bc52843dc07760969c531cc442ca7da8e0c/bat/dataframe_cache.py#L41-L46
train
27,954
SuperCowPowers/bat
bat/utils/cache.py
Cache._compress
def _compress(self): """Internal method to compress the cache. This method will expire any old items in the cache, making the cache smaller""" # Don't compress too often now = time.time() if self._last_compression + self._compression_timer < now: self._last_compression = now for key in list(self._store.keys()): self.get(key)
python
def _compress(self): """Internal method to compress the cache. This method will expire any old items in the cache, making the cache smaller""" # Don't compress too often now = time.time() if self._last_compression + self._compression_timer < now: self._last_compression = now for key in list(self._store.keys()): self.get(key)
[ "def", "_compress", "(", "self", ")", ":", "# Don't compress too often", "now", "=", "time", ".", "time", "(", ")", "if", "self", ".", "_last_compression", "+", "self", ".", "_compression_timer", "<", "now", ":", "self", ".", "_last_compression", "=", "now",...
Internal method to compress the cache. This method will expire any old items in the cache, making the cache smaller
[ "Internal", "method", "to", "compress", "the", "cache", ".", "This", "method", "will", "expire", "any", "old", "items", "in", "the", "cache", "making", "the", "cache", "smaller" ]
069e6bc52843dc07760969c531cc442ca7da8e0c
https://github.com/SuperCowPowers/bat/blob/069e6bc52843dc07760969c531cc442ca7da8e0c/bat/utils/cache.py#L77-L86
train
27,955
SuperCowPowers/bat
examples/risky_dns.py
save_vtq
def save_vtq(): """Exit on Signal""" global vtq print('Saving VirusTotal Query Cache...') pickle.dump(vtq, open('vtq.pkl', 'wb'), protocol=pickle.HIGHEST_PROTOCOL) sys.exit()
python
def save_vtq(): """Exit on Signal""" global vtq print('Saving VirusTotal Query Cache...') pickle.dump(vtq, open('vtq.pkl', 'wb'), protocol=pickle.HIGHEST_PROTOCOL) sys.exit()
[ "def", "save_vtq", "(", ")", ":", "global", "vtq", "print", "(", "'Saving VirusTotal Query Cache...'", ")", "pickle", ".", "dump", "(", "vtq", ",", "open", "(", "'vtq.pkl'", ",", "'wb'", ")", ",", "protocol", "=", "pickle", ".", "HIGHEST_PROTOCOL", ")", "s...
Exit on Signal
[ "Exit", "on", "Signal" ]
069e6bc52843dc07760969c531cc442ca7da8e0c
https://github.com/SuperCowPowers/bat/blob/069e6bc52843dc07760969c531cc442ca7da8e0c/examples/risky_dns.py#L20-L26
train
27,956
SuperCowPowers/bat
bat/utils/dummy_encoder.py
DummyEncoder.fit_transform
def fit_transform(self, df): """Fit method for the DummyEncoder""" self.index_ = df.index self.columns_ = df.columns self.cat_columns_ = df.select_dtypes(include=['category']).columns self.non_cat_columns_ = df.columns.drop(self.cat_columns_) self.cat_map_ = {col: df[col].cat for col in self.cat_columns_} # Store all the information about categories/values so we can 'back map' later left = len(self.non_cat_columns_) self.cat_blocks_ = {} for col in self.cat_columns_: right = left + len(df[col].cat.categories) self.cat_blocks_[col], left = slice(left, right), right # This is to ensure that transform always produces the same columns in the same order df_with_dummies = pd.get_dummies(df) self.columns_in_order = df_with_dummies.columns.tolist() # Return the numpy matrix return np.asarray(df_with_dummies)
python
def fit_transform(self, df): """Fit method for the DummyEncoder""" self.index_ = df.index self.columns_ = df.columns self.cat_columns_ = df.select_dtypes(include=['category']).columns self.non_cat_columns_ = df.columns.drop(self.cat_columns_) self.cat_map_ = {col: df[col].cat for col in self.cat_columns_} # Store all the information about categories/values so we can 'back map' later left = len(self.non_cat_columns_) self.cat_blocks_ = {} for col in self.cat_columns_: right = left + len(df[col].cat.categories) self.cat_blocks_[col], left = slice(left, right), right # This is to ensure that transform always produces the same columns in the same order df_with_dummies = pd.get_dummies(df) self.columns_in_order = df_with_dummies.columns.tolist() # Return the numpy matrix return np.asarray(df_with_dummies)
[ "def", "fit_transform", "(", "self", ",", "df", ")", ":", "self", ".", "index_", "=", "df", ".", "index", "self", ".", "columns_", "=", "df", ".", "columns", "self", ".", "cat_columns_", "=", "df", ".", "select_dtypes", "(", "include", "=", "[", "'ca...
Fit method for the DummyEncoder
[ "Fit", "method", "for", "the", "DummyEncoder" ]
069e6bc52843dc07760969c531cc442ca7da8e0c
https://github.com/SuperCowPowers/bat/blob/069e6bc52843dc07760969c531cc442ca7da8e0c/bat/utils/dummy_encoder.py#L24-L44
train
27,957
SuperCowPowers/bat
bat/log_to_parquet.py
_make_df
def _make_df(rows): """Internal Method to make and clean the dataframe in preparation for sending to Parquet""" # Make DataFrame df = pd.DataFrame(rows).set_index('ts') # TimeDelta Support: https://issues.apache.org/jira/browse/ARROW-835 for column in df.columns: if(df[column].dtype == 'timedelta64[ns]'): print('Converting timedelta column {:s}...'.format(column)) df[column] = df[column].astype(str) return df
python
def _make_df(rows): """Internal Method to make and clean the dataframe in preparation for sending to Parquet""" # Make DataFrame df = pd.DataFrame(rows).set_index('ts') # TimeDelta Support: https://issues.apache.org/jira/browse/ARROW-835 for column in df.columns: if(df[column].dtype == 'timedelta64[ns]'): print('Converting timedelta column {:s}...'.format(column)) df[column] = df[column].astype(str) return df
[ "def", "_make_df", "(", "rows", ")", ":", "# Make DataFrame", "df", "=", "pd", ".", "DataFrame", "(", "rows", ")", ".", "set_index", "(", "'ts'", ")", "# TimeDelta Support: https://issues.apache.org/jira/browse/ARROW-835", "for", "column", "in", "df", ".", "column...
Internal Method to make and clean the dataframe in preparation for sending to Parquet
[ "Internal", "Method", "to", "make", "and", "clean", "the", "dataframe", "in", "preparation", "for", "sending", "to", "Parquet" ]
069e6bc52843dc07760969c531cc442ca7da8e0c
https://github.com/SuperCowPowers/bat/blob/069e6bc52843dc07760969c531cc442ca7da8e0c/bat/log_to_parquet.py#L17-L28
train
27,958
mozilla-releng/scriptworker
scriptworker/context.py
Context.create_queue
def create_queue(self, credentials): """Create a taskcluster queue. Args: credentials (dict): taskcluster credentials. """ if credentials: session = self.session or aiohttp.ClientSession(loop=self.event_loop) return Queue( options={ 'credentials': credentials, 'rootUrl': self.config['taskcluster_root_url'], }, session=session )
python
def create_queue(self, credentials): """Create a taskcluster queue. Args: credentials (dict): taskcluster credentials. """ if credentials: session = self.session or aiohttp.ClientSession(loop=self.event_loop) return Queue( options={ 'credentials': credentials, 'rootUrl': self.config['taskcluster_root_url'], }, session=session )
[ "def", "create_queue", "(", "self", ",", "credentials", ")", ":", "if", "credentials", ":", "session", "=", "self", ".", "session", "or", "aiohttp", ".", "ClientSession", "(", "loop", "=", "self", ".", "event_loop", ")", "return", "Queue", "(", "options", ...
Create a taskcluster queue. Args: credentials (dict): taskcluster credentials.
[ "Create", "a", "taskcluster", "queue", "." ]
8e97bbd83b9b578565ec57904c966dd6ae4ef0ae
https://github.com/mozilla-releng/scriptworker/blob/8e97bbd83b9b578565ec57904c966dd6ae4ef0ae/scriptworker/context.py#L111-L126
train
27,959
mozilla-releng/scriptworker
scriptworker/context.py
Context.write_json
def write_json(self, path, contents, message): """Write json to disk. Args: path (str): the path to write to contents (dict): the contents of the json blob message (str): the message to log """ log.debug(message.format(path=path)) makedirs(os.path.dirname(path)) with open(path, "w") as fh: json.dump(contents, fh, indent=2, sort_keys=True)
python
def write_json(self, path, contents, message): """Write json to disk. Args: path (str): the path to write to contents (dict): the contents of the json blob message (str): the message to log """ log.debug(message.format(path=path)) makedirs(os.path.dirname(path)) with open(path, "w") as fh: json.dump(contents, fh, indent=2, sort_keys=True)
[ "def", "write_json", "(", "self", ",", "path", ",", "contents", ",", "message", ")", ":", "log", ".", "debug", "(", "message", ".", "format", "(", "path", "=", "path", ")", ")", "makedirs", "(", "os", ".", "path", ".", "dirname", "(", "path", ")", ...
Write json to disk. Args: path (str): the path to write to contents (dict): the contents of the json blob message (str): the message to log
[ "Write", "json", "to", "disk", "." ]
8e97bbd83b9b578565ec57904c966dd6ae4ef0ae
https://github.com/mozilla-releng/scriptworker/blob/8e97bbd83b9b578565ec57904c966dd6ae4ef0ae/scriptworker/context.py#L164-L176
train
27,960
mozilla-releng/scriptworker
scriptworker/context.py
Context.populate_projects
async def populate_projects(self, force=False): """Download the ``projects.yml`` file and populate ``self.projects``. This only sets it once, unless ``force`` is set. Args: force (bool, optional): Re-run the download, even if ``self.projects`` is already defined. Defaults to False. """ if force or not self.projects: with tempfile.TemporaryDirectory() as tmpdirname: self.projects = await load_json_or_yaml_from_url( self, self.config['project_configuration_url'], os.path.join(tmpdirname, 'projects.yml') )
python
async def populate_projects(self, force=False): """Download the ``projects.yml`` file and populate ``self.projects``. This only sets it once, unless ``force`` is set. Args: force (bool, optional): Re-run the download, even if ``self.projects`` is already defined. Defaults to False. """ if force or not self.projects: with tempfile.TemporaryDirectory() as tmpdirname: self.projects = await load_json_or_yaml_from_url( self, self.config['project_configuration_url'], os.path.join(tmpdirname, 'projects.yml') )
[ "async", "def", "populate_projects", "(", "self", ",", "force", "=", "False", ")", ":", "if", "force", "or", "not", "self", ".", "projects", ":", "with", "tempfile", ".", "TemporaryDirectory", "(", ")", "as", "tmpdirname", ":", "self", ".", "projects", "...
Download the ``projects.yml`` file and populate ``self.projects``. This only sets it once, unless ``force`` is set. Args: force (bool, optional): Re-run the download, even if ``self.projects`` is already defined. Defaults to False.
[ "Download", "the", "projects", ".", "yml", "file", "and", "populate", "self", ".", "projects", "." ]
8e97bbd83b9b578565ec57904c966dd6ae4ef0ae
https://github.com/mozilla-releng/scriptworker/blob/8e97bbd83b9b578565ec57904c966dd6ae4ef0ae/scriptworker/context.py#L208-L223
train
27,961
mozilla-releng/scriptworker
scriptworker/worker.py
do_run_task
async def do_run_task(context, run_cancellable, to_cancellable_process): """Run the task logic. Returns the integer status of the task. args: context (scriptworker.context.Context): the scriptworker context. run_cancellable (typing.Callable): wraps future such that it'll cancel upon worker shutdown to_cancellable_process (typing.Callable): wraps ``TaskProcess`` such that it will stop if the worker is shutting down Raises: Exception: on unexpected exception. Returns: int: exit status """ status = 0 try: if context.config['verify_chain_of_trust']: chain = ChainOfTrust(context, context.config['cot_job_type']) await run_cancellable(verify_chain_of_trust(chain)) status = await run_task(context, to_cancellable_process) generate_cot(context) except asyncio.CancelledError: log.info("CoT cancelled asynchronously") raise WorkerShutdownDuringTask except ScriptWorkerException as e: status = worst_level(status, e.exit_code) log.error("Hit ScriptWorkerException: {}".format(e)) except Exception as e: log.exception("SCRIPTWORKER_UNEXPECTED_EXCEPTION task {}".format(e)) raise return status
python
async def do_run_task(context, run_cancellable, to_cancellable_process): """Run the task logic. Returns the integer status of the task. args: context (scriptworker.context.Context): the scriptworker context. run_cancellable (typing.Callable): wraps future such that it'll cancel upon worker shutdown to_cancellable_process (typing.Callable): wraps ``TaskProcess`` such that it will stop if the worker is shutting down Raises: Exception: on unexpected exception. Returns: int: exit status """ status = 0 try: if context.config['verify_chain_of_trust']: chain = ChainOfTrust(context, context.config['cot_job_type']) await run_cancellable(verify_chain_of_trust(chain)) status = await run_task(context, to_cancellable_process) generate_cot(context) except asyncio.CancelledError: log.info("CoT cancelled asynchronously") raise WorkerShutdownDuringTask except ScriptWorkerException as e: status = worst_level(status, e.exit_code) log.error("Hit ScriptWorkerException: {}".format(e)) except Exception as e: log.exception("SCRIPTWORKER_UNEXPECTED_EXCEPTION task {}".format(e)) raise return status
[ "async", "def", "do_run_task", "(", "context", ",", "run_cancellable", ",", "to_cancellable_process", ")", ":", "status", "=", "0", "try", ":", "if", "context", ".", "config", "[", "'verify_chain_of_trust'", "]", ":", "chain", "=", "ChainOfTrust", "(", "contex...
Run the task logic. Returns the integer status of the task. args: context (scriptworker.context.Context): the scriptworker context. run_cancellable (typing.Callable): wraps future such that it'll cancel upon worker shutdown to_cancellable_process (typing.Callable): wraps ``TaskProcess`` such that it will stop if the worker is shutting down Raises: Exception: on unexpected exception. Returns: int: exit status
[ "Run", "the", "task", "logic", "." ]
8e97bbd83b9b578565ec57904c966dd6ae4ef0ae
https://github.com/mozilla-releng/scriptworker/blob/8e97bbd83b9b578565ec57904c966dd6ae4ef0ae/scriptworker/worker.py#L32-L66
train
27,962
mozilla-releng/scriptworker
scriptworker/worker.py
do_upload
async def do_upload(context, files): """Upload artifacts and return status. Returns the integer status of the upload. args: context (scriptworker.context.Context): the scriptworker context. files (list of str): list of files to be uploaded as artifacts Raises: Exception: on unexpected exception. Returns: int: exit status """ status = 0 try: await upload_artifacts(context, files) except ScriptWorkerException as e: status = worst_level(status, e.exit_code) log.error("Hit ScriptWorkerException: {}".format(e)) except aiohttp.ClientError as e: status = worst_level(status, STATUSES['intermittent-task']) log.error("Hit aiohttp error: {}".format(e)) except Exception as e: log.exception("SCRIPTWORKER_UNEXPECTED_EXCEPTION upload {}".format(e)) raise return status
python
async def do_upload(context, files): """Upload artifacts and return status. Returns the integer status of the upload. args: context (scriptworker.context.Context): the scriptworker context. files (list of str): list of files to be uploaded as artifacts Raises: Exception: on unexpected exception. Returns: int: exit status """ status = 0 try: await upload_artifacts(context, files) except ScriptWorkerException as e: status = worst_level(status, e.exit_code) log.error("Hit ScriptWorkerException: {}".format(e)) except aiohttp.ClientError as e: status = worst_level(status, STATUSES['intermittent-task']) log.error("Hit aiohttp error: {}".format(e)) except Exception as e: log.exception("SCRIPTWORKER_UNEXPECTED_EXCEPTION upload {}".format(e)) raise return status
[ "async", "def", "do_upload", "(", "context", ",", "files", ")", ":", "status", "=", "0", "try", ":", "await", "upload_artifacts", "(", "context", ",", "files", ")", "except", "ScriptWorkerException", "as", "e", ":", "status", "=", "worst_level", "(", "stat...
Upload artifacts and return status. Returns the integer status of the upload. args: context (scriptworker.context.Context): the scriptworker context. files (list of str): list of files to be uploaded as artifacts Raises: Exception: on unexpected exception. Returns: int: exit status
[ "Upload", "artifacts", "and", "return", "status", "." ]
8e97bbd83b9b578565ec57904c966dd6ae4ef0ae
https://github.com/mozilla-releng/scriptworker/blob/8e97bbd83b9b578565ec57904c966dd6ae4ef0ae/scriptworker/worker.py#L70-L98
train
27,963
mozilla-releng/scriptworker
scriptworker/worker.py
run_tasks
async def run_tasks(context): """Run any tasks returned by claimWork. Returns the integer status of the task that was run, or None if no task was run. args: context (scriptworker.context.Context): the scriptworker context. Raises: Exception: on unexpected exception. Returns: int: exit status None: if no task run. """ running_tasks = RunTasks() context.running_tasks = running_tasks status = await running_tasks.invoke(context) context.running_tasks = None return status
python
async def run_tasks(context): """Run any tasks returned by claimWork. Returns the integer status of the task that was run, or None if no task was run. args: context (scriptworker.context.Context): the scriptworker context. Raises: Exception: on unexpected exception. Returns: int: exit status None: if no task run. """ running_tasks = RunTasks() context.running_tasks = running_tasks status = await running_tasks.invoke(context) context.running_tasks = None return status
[ "async", "def", "run_tasks", "(", "context", ")", ":", "running_tasks", "=", "RunTasks", "(", ")", "context", ".", "running_tasks", "=", "running_tasks", "status", "=", "await", "running_tasks", ".", "invoke", "(", "context", ")", "context", ".", "running_task...
Run any tasks returned by claimWork. Returns the integer status of the task that was run, or None if no task was run. args: context (scriptworker.context.Context): the scriptworker context. Raises: Exception: on unexpected exception. Returns: int: exit status None: if no task run.
[ "Run", "any", "tasks", "returned", "by", "claimWork", "." ]
8e97bbd83b9b578565ec57904c966dd6ae4ef0ae
https://github.com/mozilla-releng/scriptworker/blob/8e97bbd83b9b578565ec57904c966dd6ae4ef0ae/scriptworker/worker.py#L180-L201
train
27,964
mozilla-releng/scriptworker
scriptworker/worker.py
async_main
async def async_main(context, credentials): """Set up and run tasks for this iteration. http://docs.taskcluster.net/queue/worker-interaction/ Args: context (scriptworker.context.Context): the scriptworker context. """ conn = aiohttp.TCPConnector(limit=context.config['aiohttp_max_connections']) async with aiohttp.ClientSession(connector=conn) as session: context.session = session context.credentials = credentials await run_tasks(context)
python
async def async_main(context, credentials): """Set up and run tasks for this iteration. http://docs.taskcluster.net/queue/worker-interaction/ Args: context (scriptworker.context.Context): the scriptworker context. """ conn = aiohttp.TCPConnector(limit=context.config['aiohttp_max_connections']) async with aiohttp.ClientSession(connector=conn) as session: context.session = session context.credentials = credentials await run_tasks(context)
[ "async", "def", "async_main", "(", "context", ",", "credentials", ")", ":", "conn", "=", "aiohttp", ".", "TCPConnector", "(", "limit", "=", "context", ".", "config", "[", "'aiohttp_max_connections'", "]", ")", "async", "with", "aiohttp", ".", "ClientSession", ...
Set up and run tasks for this iteration. http://docs.taskcluster.net/queue/worker-interaction/ Args: context (scriptworker.context.Context): the scriptworker context.
[ "Set", "up", "and", "run", "tasks", "for", "this", "iteration", "." ]
8e97bbd83b9b578565ec57904c966dd6ae4ef0ae
https://github.com/mozilla-releng/scriptworker/blob/8e97bbd83b9b578565ec57904c966dd6ae4ef0ae/scriptworker/worker.py#L205-L217
train
27,965
mozilla-releng/scriptworker
scriptworker/worker.py
RunTasks.invoke
async def invoke(self, context): """Claims and processes Taskcluster work. Args: context (scriptworker.context.Context): context of worker Returns: status code of build """ try: # Note: claim_work(...) might not be safely interruptible! See # https://bugzilla.mozilla.org/show_bug.cgi?id=1524069 tasks = await self._run_cancellable(claim_work(context)) if not tasks or not tasks.get('tasks', []): await self._run_cancellable(asyncio.sleep(context.config['poll_interval'])) return None # Assume only a single task, but should more than one fall through, # run them sequentially. A side effect is our return status will # be the status of the final task run. status = None for task_defn in tasks.get('tasks', []): prepare_to_run_task(context, task_defn) reclaim_fut = context.event_loop.create_task(reclaim_task(context, context.task)) try: status = await do_run_task(context, self._run_cancellable, self._to_cancellable_process) artifacts_paths = filepaths_in_dir(context.config['artifact_dir']) except WorkerShutdownDuringTask: shutdown_artifact_paths = [os.path.join('public', 'logs', log_file) for log_file in ['chain_of_trust.log', 'live_backing.log']] artifacts_paths = [path for path in shutdown_artifact_paths if os.path.isfile(os.path.join(context.config['artifact_dir'], path))] status = STATUSES['worker-shutdown'] status = worst_level(status, await do_upload(context, artifacts_paths)) await complete_task(context, status) reclaim_fut.cancel() cleanup(context) return status except asyncio.CancelledError: return None
python
async def invoke(self, context): """Claims and processes Taskcluster work. Args: context (scriptworker.context.Context): context of worker Returns: status code of build """ try: # Note: claim_work(...) might not be safely interruptible! See # https://bugzilla.mozilla.org/show_bug.cgi?id=1524069 tasks = await self._run_cancellable(claim_work(context)) if not tasks or not tasks.get('tasks', []): await self._run_cancellable(asyncio.sleep(context.config['poll_interval'])) return None # Assume only a single task, but should more than one fall through, # run them sequentially. A side effect is our return status will # be the status of the final task run. status = None for task_defn in tasks.get('tasks', []): prepare_to_run_task(context, task_defn) reclaim_fut = context.event_loop.create_task(reclaim_task(context, context.task)) try: status = await do_run_task(context, self._run_cancellable, self._to_cancellable_process) artifacts_paths = filepaths_in_dir(context.config['artifact_dir']) except WorkerShutdownDuringTask: shutdown_artifact_paths = [os.path.join('public', 'logs', log_file) for log_file in ['chain_of_trust.log', 'live_backing.log']] artifacts_paths = [path for path in shutdown_artifact_paths if os.path.isfile(os.path.join(context.config['artifact_dir'], path))] status = STATUSES['worker-shutdown'] status = worst_level(status, await do_upload(context, artifacts_paths)) await complete_task(context, status) reclaim_fut.cancel() cleanup(context) return status except asyncio.CancelledError: return None
[ "async", "def", "invoke", "(", "self", ",", "context", ")", ":", "try", ":", "# Note: claim_work(...) might not be safely interruptible! See", "# https://bugzilla.mozilla.org/show_bug.cgi?id=1524069", "tasks", "=", "await", "self", ".", "_run_cancellable", "(", "claim_work", ...
Claims and processes Taskcluster work. Args: context (scriptworker.context.Context): context of worker Returns: status code of build
[ "Claims", "and", "processes", "Taskcluster", "work", "." ]
8e97bbd83b9b578565ec57904c966dd6ae4ef0ae
https://github.com/mozilla-releng/scriptworker/blob/8e97bbd83b9b578565ec57904c966dd6ae4ef0ae/scriptworker/worker.py#L110-L151
train
27,966
mozilla-releng/scriptworker
scriptworker/worker.py
RunTasks.cancel
async def cancel(self): """Cancel current work.""" self.is_cancelled = True if self.future is not None: self.future.cancel() if self.task_process is not None: log.warning("Worker is shutting down, but a task is running. Terminating task") await self.task_process.worker_shutdown_stop()
python
async def cancel(self): """Cancel current work.""" self.is_cancelled = True if self.future is not None: self.future.cancel() if self.task_process is not None: log.warning("Worker is shutting down, but a task is running. Terminating task") await self.task_process.worker_shutdown_stop()
[ "async", "def", "cancel", "(", "self", ")", ":", "self", ".", "is_cancelled", "=", "True", "if", "self", ".", "future", "is", "not", "None", ":", "self", ".", "future", ".", "cancel", "(", ")", "if", "self", ".", "task_process", "is", "not", "None", ...
Cancel current work.
[ "Cancel", "current", "work", "." ]
8e97bbd83b9b578565ec57904c966dd6ae4ef0ae
https://github.com/mozilla-releng/scriptworker/blob/8e97bbd83b9b578565ec57904c966dd6ae4ef0ae/scriptworker/worker.py#L169-L176
train
27,967
mozilla-releng/scriptworker
scriptworker/utils.py
request
async def request(context, url, timeout=60, method='get', good=(200, ), retry=tuple(range(500, 512)), return_type='text', **kwargs): """Async aiohttp request wrapper. Args: context (scriptworker.context.Context): the scriptworker context. url (str): the url to request timeout (int, optional): timeout after this many seconds. Default is 60. method (str, optional): The request method to use. Default is 'get'. good (list, optional): the set of good status codes. Default is (200, ) retry (list, optional): the set of status codes that result in a retry. Default is tuple(range(500, 512)). return_type (str, optional): The type of value to return. Takes 'json' or 'text'; other values will return the response object. Default is text. **kwargs: the kwargs to send to the aiohttp request function. Returns: object: the response text() if return_type is 'text'; the response json() if return_type is 'json'; the aiohttp request response object otherwise. Raises: ScriptWorkerRetryException: if the status code is in the retry list. ScriptWorkerException: if the status code is not in the retry list or good list. """ session = context.session loggable_url = get_loggable_url(url) async with async_timeout.timeout(timeout): log.debug("{} {}".format(method.upper(), loggable_url)) async with session.request(method, url, **kwargs) as resp: log.debug("Status {}".format(resp.status)) message = "Bad status {}".format(resp.status) if resp.status in retry: raise ScriptWorkerRetryException(message) if resp.status not in good: raise ScriptWorkerException(message) if return_type == 'text': return await resp.text() elif return_type == 'json': return await resp.json() else: return resp
python
async def request(context, url, timeout=60, method='get', good=(200, ), retry=tuple(range(500, 512)), return_type='text', **kwargs): """Async aiohttp request wrapper. Args: context (scriptworker.context.Context): the scriptworker context. url (str): the url to request timeout (int, optional): timeout after this many seconds. Default is 60. method (str, optional): The request method to use. Default is 'get'. good (list, optional): the set of good status codes. Default is (200, ) retry (list, optional): the set of status codes that result in a retry. Default is tuple(range(500, 512)). return_type (str, optional): The type of value to return. Takes 'json' or 'text'; other values will return the response object. Default is text. **kwargs: the kwargs to send to the aiohttp request function. Returns: object: the response text() if return_type is 'text'; the response json() if return_type is 'json'; the aiohttp request response object otherwise. Raises: ScriptWorkerRetryException: if the status code is in the retry list. ScriptWorkerException: if the status code is not in the retry list or good list. """ session = context.session loggable_url = get_loggable_url(url) async with async_timeout.timeout(timeout): log.debug("{} {}".format(method.upper(), loggable_url)) async with session.request(method, url, **kwargs) as resp: log.debug("Status {}".format(resp.status)) message = "Bad status {}".format(resp.status) if resp.status in retry: raise ScriptWorkerRetryException(message) if resp.status not in good: raise ScriptWorkerException(message) if return_type == 'text': return await resp.text() elif return_type == 'json': return await resp.json() else: return resp
[ "async", "def", "request", "(", "context", ",", "url", ",", "timeout", "=", "60", ",", "method", "=", "'get'", ",", "good", "=", "(", "200", ",", ")", ",", "retry", "=", "tuple", "(", "range", "(", "500", ",", "512", ")", ")", ",", "return_type",...
Async aiohttp request wrapper. Args: context (scriptworker.context.Context): the scriptworker context. url (str): the url to request timeout (int, optional): timeout after this many seconds. Default is 60. method (str, optional): The request method to use. Default is 'get'. good (list, optional): the set of good status codes. Default is (200, ) retry (list, optional): the set of status codes that result in a retry. Default is tuple(range(500, 512)). return_type (str, optional): The type of value to return. Takes 'json' or 'text'; other values will return the response object. Default is text. **kwargs: the kwargs to send to the aiohttp request function. Returns: object: the response text() if return_type is 'text'; the response json() if return_type is 'json'; the aiohttp request response object otherwise. Raises: ScriptWorkerRetryException: if the status code is in the retry list. ScriptWorkerException: if the status code is not in the retry list or good list.
[ "Async", "aiohttp", "request", "wrapper", "." ]
8e97bbd83b9b578565ec57904c966dd6ae4ef0ae
https://github.com/mozilla-releng/scriptworker/blob/8e97bbd83b9b578565ec57904c966dd6ae4ef0ae/scriptworker/utils.py#L36-L80
train
27,968
mozilla-releng/scriptworker
scriptworker/utils.py
retry_request
async def retry_request(*args, retry_exceptions=(asyncio.TimeoutError, ScriptWorkerRetryException), retry_async_kwargs=None, **kwargs): """Retry the ``request`` function. Args: *args: the args to send to request() through retry_async(). retry_exceptions (list, optional): the exceptions to retry on. Defaults to (ScriptWorkerRetryException, ). retry_async_kwargs (dict, optional): the kwargs for retry_async. If None, use {}. Defaults to None. **kwargs: the kwargs to send to request() through retry_async(). Returns: object: the value from request(). """ retry_async_kwargs = retry_async_kwargs or {} return await retry_async(request, retry_exceptions=retry_exceptions, args=args, kwargs=kwargs, **retry_async_kwargs)
python
async def retry_request(*args, retry_exceptions=(asyncio.TimeoutError, ScriptWorkerRetryException), retry_async_kwargs=None, **kwargs): """Retry the ``request`` function. Args: *args: the args to send to request() through retry_async(). retry_exceptions (list, optional): the exceptions to retry on. Defaults to (ScriptWorkerRetryException, ). retry_async_kwargs (dict, optional): the kwargs for retry_async. If None, use {}. Defaults to None. **kwargs: the kwargs to send to request() through retry_async(). Returns: object: the value from request(). """ retry_async_kwargs = retry_async_kwargs or {} return await retry_async(request, retry_exceptions=retry_exceptions, args=args, kwargs=kwargs, **retry_async_kwargs)
[ "async", "def", "retry_request", "(", "*", "args", ",", "retry_exceptions", "=", "(", "asyncio", ".", "TimeoutError", ",", "ScriptWorkerRetryException", ")", ",", "retry_async_kwargs", "=", "None", ",", "*", "*", "kwargs", ")", ":", "retry_async_kwargs", "=", ...
Retry the ``request`` function. Args: *args: the args to send to request() through retry_async(). retry_exceptions (list, optional): the exceptions to retry on. Defaults to (ScriptWorkerRetryException, ). retry_async_kwargs (dict, optional): the kwargs for retry_async. If None, use {}. Defaults to None. **kwargs: the kwargs to send to request() through retry_async(). Returns: object: the value from request().
[ "Retry", "the", "request", "function", "." ]
8e97bbd83b9b578565ec57904c966dd6ae4ef0ae
https://github.com/mozilla-releng/scriptworker/blob/8e97bbd83b9b578565ec57904c966dd6ae4ef0ae/scriptworker/utils.py#L84-L103
train
27,969
mozilla-releng/scriptworker
scriptworker/utils.py
makedirs
def makedirs(path): """Equivalent to mkdir -p. Args: path (str): the path to mkdir -p Raises: ScriptWorkerException: if path exists already and the realpath is not a dir. """ if path: if not os.path.exists(path): log.debug("makedirs({})".format(path)) os.makedirs(path) else: realpath = os.path.realpath(path) if not os.path.isdir(realpath): raise ScriptWorkerException( "makedirs: {} already exists and is not a directory!".format(path) )
python
def makedirs(path): """Equivalent to mkdir -p. Args: path (str): the path to mkdir -p Raises: ScriptWorkerException: if path exists already and the realpath is not a dir. """ if path: if not os.path.exists(path): log.debug("makedirs({})".format(path)) os.makedirs(path) else: realpath = os.path.realpath(path) if not os.path.isdir(realpath): raise ScriptWorkerException( "makedirs: {} already exists and is not a directory!".format(path) )
[ "def", "makedirs", "(", "path", ")", ":", "if", "path", ":", "if", "not", "os", ".", "path", ".", "exists", "(", "path", ")", ":", "log", ".", "debug", "(", "\"makedirs({})\"", ".", "format", "(", "path", ")", ")", "os", ".", "makedirs", "(", "pa...
Equivalent to mkdir -p. Args: path (str): the path to mkdir -p Raises: ScriptWorkerException: if path exists already and the realpath is not a dir.
[ "Equivalent", "to", "mkdir", "-", "p", "." ]
8e97bbd83b9b578565ec57904c966dd6ae4ef0ae
https://github.com/mozilla-releng/scriptworker/blob/8e97bbd83b9b578565ec57904c966dd6ae4ef0ae/scriptworker/utils.py#L141-L160
train
27,970
mozilla-releng/scriptworker
scriptworker/utils.py
rm
def rm(path): """Equivalent to rm -rf. Make sure ``path`` doesn't exist after this call. If it's a dir, shutil.rmtree(); if it's a file, os.remove(); if it doesn't exist, ignore. Args: path (str): the path to nuke. """ if path and os.path.exists(path): if os.path.isdir(path): shutil.rmtree(path) else: os.remove(path)
python
def rm(path): """Equivalent to rm -rf. Make sure ``path`` doesn't exist after this call. If it's a dir, shutil.rmtree(); if it's a file, os.remove(); if it doesn't exist, ignore. Args: path (str): the path to nuke. """ if path and os.path.exists(path): if os.path.isdir(path): shutil.rmtree(path) else: os.remove(path)
[ "def", "rm", "(", "path", ")", ":", "if", "path", "and", "os", ".", "path", ".", "exists", "(", "path", ")", ":", "if", "os", ".", "path", ".", "isdir", "(", "path", ")", ":", "shutil", ".", "rmtree", "(", "path", ")", "else", ":", "os", ".",...
Equivalent to rm -rf. Make sure ``path`` doesn't exist after this call. If it's a dir, shutil.rmtree(); if it's a file, os.remove(); if it doesn't exist, ignore. Args: path (str): the path to nuke.
[ "Equivalent", "to", "rm", "-", "rf", "." ]
8e97bbd83b9b578565ec57904c966dd6ae4ef0ae
https://github.com/mozilla-releng/scriptworker/blob/8e97bbd83b9b578565ec57904c966dd6ae4ef0ae/scriptworker/utils.py#L164-L179
train
27,971
mozilla-releng/scriptworker
scriptworker/utils.py
cleanup
def cleanup(context): """Clean up the work_dir and artifact_dir between task runs, then recreate. Args: context (scriptworker.context.Context): the scriptworker context. """ for name in 'work_dir', 'artifact_dir', 'task_log_dir': path = context.config[name] if os.path.exists(path): log.debug("rm({})".format(path)) rm(path) makedirs(path)
python
def cleanup(context): """Clean up the work_dir and artifact_dir between task runs, then recreate. Args: context (scriptworker.context.Context): the scriptworker context. """ for name in 'work_dir', 'artifact_dir', 'task_log_dir': path = context.config[name] if os.path.exists(path): log.debug("rm({})".format(path)) rm(path) makedirs(path)
[ "def", "cleanup", "(", "context", ")", ":", "for", "name", "in", "'work_dir'", ",", "'artifact_dir'", ",", "'task_log_dir'", ":", "path", "=", "context", ".", "config", "[", "name", "]", "if", "os", ".", "path", ".", "exists", "(", "path", ")", ":", ...
Clean up the work_dir and artifact_dir between task runs, then recreate. Args: context (scriptworker.context.Context): the scriptworker context.
[ "Clean", "up", "the", "work_dir", "and", "artifact_dir", "between", "task", "runs", "then", "recreate", "." ]
8e97bbd83b9b578565ec57904c966dd6ae4ef0ae
https://github.com/mozilla-releng/scriptworker/blob/8e97bbd83b9b578565ec57904c966dd6ae4ef0ae/scriptworker/utils.py#L183-L195
train
27,972
mozilla-releng/scriptworker
scriptworker/utils.py
calculate_sleep_time
def calculate_sleep_time(attempt, delay_factor=5.0, randomization_factor=.5, max_delay=120): """Calculate the sleep time between retries, in seconds. Based off of `taskcluster.utils.calculateSleepTime`, but with kwargs instead of constant `delay_factor`/`randomization_factor`/`max_delay`. The taskcluster function generally slept for less than a second, which didn't always get past server issues. Args: attempt (int): the retry attempt number delay_factor (float, optional): a multiplier for the delay time. Defaults to 5. randomization_factor (float, optional): a randomization multiplier for the delay time. Defaults to .5. max_delay (float, optional): the max delay to sleep. Defaults to 120 (seconds). Returns: float: the time to sleep, in seconds. """ if attempt <= 0: return 0 # We subtract one to get exponents: 1, 2, 3, 4, 5, .. delay = float(2 ** (attempt - 1)) * float(delay_factor) # Apply randomization factor. Only increase the delay here. delay = delay * (randomization_factor * random.random() + 1) # Always limit with a maximum delay return min(delay, max_delay)
python
def calculate_sleep_time(attempt, delay_factor=5.0, randomization_factor=.5, max_delay=120): """Calculate the sleep time between retries, in seconds. Based off of `taskcluster.utils.calculateSleepTime`, but with kwargs instead of constant `delay_factor`/`randomization_factor`/`max_delay`. The taskcluster function generally slept for less than a second, which didn't always get past server issues. Args: attempt (int): the retry attempt number delay_factor (float, optional): a multiplier for the delay time. Defaults to 5. randomization_factor (float, optional): a randomization multiplier for the delay time. Defaults to .5. max_delay (float, optional): the max delay to sleep. Defaults to 120 (seconds). Returns: float: the time to sleep, in seconds. """ if attempt <= 0: return 0 # We subtract one to get exponents: 1, 2, 3, 4, 5, .. delay = float(2 ** (attempt - 1)) * float(delay_factor) # Apply randomization factor. Only increase the delay here. delay = delay * (randomization_factor * random.random() + 1) # Always limit with a maximum delay return min(delay, max_delay)
[ "def", "calculate_sleep_time", "(", "attempt", ",", "delay_factor", "=", "5.0", ",", "randomization_factor", "=", ".5", ",", "max_delay", "=", "120", ")", ":", "if", "attempt", "<=", "0", ":", "return", "0", "# We subtract one to get exponents: 1, 2, 3, 4, 5, ..", ...
Calculate the sleep time between retries, in seconds. Based off of `taskcluster.utils.calculateSleepTime`, but with kwargs instead of constant `delay_factor`/`randomization_factor`/`max_delay`. The taskcluster function generally slept for less than a second, which didn't always get past server issues. Args: attempt (int): the retry attempt number delay_factor (float, optional): a multiplier for the delay time. Defaults to 5. randomization_factor (float, optional): a randomization multiplier for the delay time. Defaults to .5. max_delay (float, optional): the max delay to sleep. Defaults to 120 (seconds). Returns: float: the time to sleep, in seconds.
[ "Calculate", "the", "sleep", "time", "between", "retries", "in", "seconds", "." ]
8e97bbd83b9b578565ec57904c966dd6ae4ef0ae
https://github.com/mozilla-releng/scriptworker/blob/8e97bbd83b9b578565ec57904c966dd6ae4ef0ae/scriptworker/utils.py#L199-L226
train
27,973
mozilla-releng/scriptworker
scriptworker/utils.py
retry_async
async def retry_async(func, attempts=5, sleeptime_callback=calculate_sleep_time, retry_exceptions=Exception, args=(), kwargs=None, sleeptime_kwargs=None): """Retry ``func``, where ``func`` is an awaitable. Args: func (function): an awaitable function. attempts (int, optional): the number of attempts to make. Default is 5. sleeptime_callback (function, optional): the function to use to determine how long to sleep after each attempt. Defaults to ``calculateSleepTime``. retry_exceptions (list or exception, optional): the exception(s) to retry on. Defaults to ``Exception``. args (list, optional): the args to pass to ``function``. Defaults to () kwargs (dict, optional): the kwargs to pass to ``function``. Defaults to {}. sleeptime_kwargs (dict, optional): the kwargs to pass to ``sleeptime_callback``. If None, use {}. Defaults to None. Returns: object: the value from a successful ``function`` call Raises: Exception: the exception from a failed ``function`` call, either outside of the retry_exceptions, or one of those if we pass the max ``attempts``. """ kwargs = kwargs or {} attempt = 1 while True: try: return await func(*args, **kwargs) except retry_exceptions: attempt += 1 if attempt > attempts: log.warning("retry_async: {}: too many retries!".format(func.__name__)) raise sleeptime_kwargs = sleeptime_kwargs or {} sleep_time = sleeptime_callback(attempt, **sleeptime_kwargs) log.debug("retry_async: {}: sleeping {} seconds before retry".format(func.__name__, sleep_time)) await asyncio.sleep(sleep_time)
python
async def retry_async(func, attempts=5, sleeptime_callback=calculate_sleep_time, retry_exceptions=Exception, args=(), kwargs=None, sleeptime_kwargs=None): """Retry ``func``, where ``func`` is an awaitable. Args: func (function): an awaitable function. attempts (int, optional): the number of attempts to make. Default is 5. sleeptime_callback (function, optional): the function to use to determine how long to sleep after each attempt. Defaults to ``calculateSleepTime``. retry_exceptions (list or exception, optional): the exception(s) to retry on. Defaults to ``Exception``. args (list, optional): the args to pass to ``function``. Defaults to () kwargs (dict, optional): the kwargs to pass to ``function``. Defaults to {}. sleeptime_kwargs (dict, optional): the kwargs to pass to ``sleeptime_callback``. If None, use {}. Defaults to None. Returns: object: the value from a successful ``function`` call Raises: Exception: the exception from a failed ``function`` call, either outside of the retry_exceptions, or one of those if we pass the max ``attempts``. """ kwargs = kwargs or {} attempt = 1 while True: try: return await func(*args, **kwargs) except retry_exceptions: attempt += 1 if attempt > attempts: log.warning("retry_async: {}: too many retries!".format(func.__name__)) raise sleeptime_kwargs = sleeptime_kwargs or {} sleep_time = sleeptime_callback(attempt, **sleeptime_kwargs) log.debug("retry_async: {}: sleeping {} seconds before retry".format(func.__name__, sleep_time)) await asyncio.sleep(sleep_time)
[ "async", "def", "retry_async", "(", "func", ",", "attempts", "=", "5", ",", "sleeptime_callback", "=", "calculate_sleep_time", ",", "retry_exceptions", "=", "Exception", ",", "args", "=", "(", ")", ",", "kwargs", "=", "None", ",", "sleeptime_kwargs", "=", "N...
Retry ``func``, where ``func`` is an awaitable. Args: func (function): an awaitable function. attempts (int, optional): the number of attempts to make. Default is 5. sleeptime_callback (function, optional): the function to use to determine how long to sleep after each attempt. Defaults to ``calculateSleepTime``. retry_exceptions (list or exception, optional): the exception(s) to retry on. Defaults to ``Exception``. args (list, optional): the args to pass to ``function``. Defaults to () kwargs (dict, optional): the kwargs to pass to ``function``. Defaults to {}. sleeptime_kwargs (dict, optional): the kwargs to pass to ``sleeptime_callback``. If None, use {}. Defaults to None. Returns: object: the value from a successful ``function`` call Raises: Exception: the exception from a failed ``function`` call, either outside of the retry_exceptions, or one of those if we pass the max ``attempts``.
[ "Retry", "func", "where", "func", "is", "an", "awaitable", "." ]
8e97bbd83b9b578565ec57904c966dd6ae4ef0ae
https://github.com/mozilla-releng/scriptworker/blob/8e97bbd83b9b578565ec57904c966dd6ae4ef0ae/scriptworker/utils.py#L230-L270
train
27,974
mozilla-releng/scriptworker
scriptworker/utils.py
create_temp_creds
def create_temp_creds(client_id, access_token, start=None, expires=None, scopes=None, name=None): """Request temp TC creds with our permanent creds. Args: client_id (str): the taskcluster client_id to use access_token (str): the taskcluster access_token to use start (str, optional): the datetime string when the credentials will start to be valid. Defaults to 10 minutes ago, for clock skew. expires (str, optional): the datetime string when the credentials will expire. Defaults to 31 days after 10 minutes ago. scopes (list, optional): The list of scopes to request for the temp creds. Defaults to ['assume:project:taskcluster:worker-test-scopes', ] name (str, optional): the name to associate with the creds. Returns: dict: the temporary taskcluster credentials. """ now = arrow.utcnow().replace(minutes=-10) start = start or now.datetime expires = expires or now.replace(days=31).datetime scopes = scopes or ['assume:project:taskcluster:worker-test-scopes', ] creds = createTemporaryCredentials(client_id, access_token, start, expires, scopes, name=name) for key, value in creds.items(): try: creds[key] = value.decode('utf-8') except (AttributeError, UnicodeDecodeError): pass return creds
python
def create_temp_creds(client_id, access_token, start=None, expires=None, scopes=None, name=None): """Request temp TC creds with our permanent creds. Args: client_id (str): the taskcluster client_id to use access_token (str): the taskcluster access_token to use start (str, optional): the datetime string when the credentials will start to be valid. Defaults to 10 minutes ago, for clock skew. expires (str, optional): the datetime string when the credentials will expire. Defaults to 31 days after 10 minutes ago. scopes (list, optional): The list of scopes to request for the temp creds. Defaults to ['assume:project:taskcluster:worker-test-scopes', ] name (str, optional): the name to associate with the creds. Returns: dict: the temporary taskcluster credentials. """ now = arrow.utcnow().replace(minutes=-10) start = start or now.datetime expires = expires or now.replace(days=31).datetime scopes = scopes or ['assume:project:taskcluster:worker-test-scopes', ] creds = createTemporaryCredentials(client_id, access_token, start, expires, scopes, name=name) for key, value in creds.items(): try: creds[key] = value.decode('utf-8') except (AttributeError, UnicodeDecodeError): pass return creds
[ "def", "create_temp_creds", "(", "client_id", ",", "access_token", ",", "start", "=", "None", ",", "expires", "=", "None", ",", "scopes", "=", "None", ",", "name", "=", "None", ")", ":", "now", "=", "arrow", ".", "utcnow", "(", ")", ".", "replace", "...
Request temp TC creds with our permanent creds. Args: client_id (str): the taskcluster client_id to use access_token (str): the taskcluster access_token to use start (str, optional): the datetime string when the credentials will start to be valid. Defaults to 10 minutes ago, for clock skew. expires (str, optional): the datetime string when the credentials will expire. Defaults to 31 days after 10 minutes ago. scopes (list, optional): The list of scopes to request for the temp creds. Defaults to ['assume:project:taskcluster:worker-test-scopes', ] name (str, optional): the name to associate with the creds. Returns: dict: the temporary taskcluster credentials.
[ "Request", "temp", "TC", "creds", "with", "our", "permanent", "creds", "." ]
8e97bbd83b9b578565ec57904c966dd6ae4ef0ae
https://github.com/mozilla-releng/scriptworker/blob/8e97bbd83b9b578565ec57904c966dd6ae4ef0ae/scriptworker/utils.py#L274-L304
train
27,975
mozilla-releng/scriptworker
scriptworker/utils.py
filepaths_in_dir
def filepaths_in_dir(path): """Find all files in a directory, and return the relative paths to those files. Args: path (str): the directory path to walk Returns: list: the list of relative paths to all files inside of ``path`` or its subdirectories. """ filepaths = [] for root, directories, filenames in os.walk(path): for filename in filenames: filepath = os.path.join(root, filename) filepath = filepath.replace(path, '').lstrip('/') filepaths.append(filepath) return filepaths
python
def filepaths_in_dir(path): """Find all files in a directory, and return the relative paths to those files. Args: path (str): the directory path to walk Returns: list: the list of relative paths to all files inside of ``path`` or its subdirectories. """ filepaths = [] for root, directories, filenames in os.walk(path): for filename in filenames: filepath = os.path.join(root, filename) filepath = filepath.replace(path, '').lstrip('/') filepaths.append(filepath) return filepaths
[ "def", "filepaths_in_dir", "(", "path", ")", ":", "filepaths", "=", "[", "]", "for", "root", ",", "directories", ",", "filenames", "in", "os", ".", "walk", "(", "path", ")", ":", "for", "filename", "in", "filenames", ":", "filepath", "=", "os", ".", ...
Find all files in a directory, and return the relative paths to those files. Args: path (str): the directory path to walk Returns: list: the list of relative paths to all files inside of ``path`` or its subdirectories.
[ "Find", "all", "files", "in", "a", "directory", "and", "return", "the", "relative", "paths", "to", "those", "files", "." ]
8e97bbd83b9b578565ec57904c966dd6ae4ef0ae
https://github.com/mozilla-releng/scriptworker/blob/8e97bbd83b9b578565ec57904c966dd6ae4ef0ae/scriptworker/utils.py#L372-L389
train
27,976
mozilla-releng/scriptworker
scriptworker/utils.py
get_hash
def get_hash(path, hash_alg="sha256"): """Get the hash of the file at ``path``. I'd love to make this async, but evidently file i/o is always ready Args: path (str): the path to the file to hash. hash_alg (str, optional): the algorithm to use. Defaults to 'sha256'. Returns: str: the hexdigest of the hash. """ h = hashlib.new(hash_alg) with open(path, "rb") as f: for chunk in iter(functools.partial(f.read, 4096), b''): h.update(chunk) return h.hexdigest()
python
def get_hash(path, hash_alg="sha256"): """Get the hash of the file at ``path``. I'd love to make this async, but evidently file i/o is always ready Args: path (str): the path to the file to hash. hash_alg (str, optional): the algorithm to use. Defaults to 'sha256'. Returns: str: the hexdigest of the hash. """ h = hashlib.new(hash_alg) with open(path, "rb") as f: for chunk in iter(functools.partial(f.read, 4096), b''): h.update(chunk) return h.hexdigest()
[ "def", "get_hash", "(", "path", ",", "hash_alg", "=", "\"sha256\"", ")", ":", "h", "=", "hashlib", ".", "new", "(", "hash_alg", ")", "with", "open", "(", "path", ",", "\"rb\"", ")", "as", "f", ":", "for", "chunk", "in", "iter", "(", "functools", "....
Get the hash of the file at ``path``. I'd love to make this async, but evidently file i/o is always ready Args: path (str): the path to the file to hash. hash_alg (str, optional): the algorithm to use. Defaults to 'sha256'. Returns: str: the hexdigest of the hash.
[ "Get", "the", "hash", "of", "the", "file", "at", "path", "." ]
8e97bbd83b9b578565ec57904c966dd6ae4ef0ae
https://github.com/mozilla-releng/scriptworker/blob/8e97bbd83b9b578565ec57904c966dd6ae4ef0ae/scriptworker/utils.py#L393-L410
train
27,977
mozilla-releng/scriptworker
scriptworker/utils.py
load_json_or_yaml
def load_json_or_yaml(string, is_path=False, file_type='json', exception=ScriptWorkerTaskException, message="Failed to load %(file_type)s: %(exc)s"): """Load json or yaml from a filehandle or string, and raise a custom exception on failure. Args: string (str): json/yaml body or a path to open is_path (bool, optional): if ``string`` is a path. Defaults to False. file_type (str, optional): either "json" or "yaml". Defaults to "json". exception (exception, optional): the exception to raise on failure. If None, don't raise an exception. Defaults to ScriptWorkerTaskException. message (str, optional): the message to use for the exception. Defaults to "Failed to load %(file_type)s: %(exc)s" Returns: dict: the data from the string. Raises: Exception: as specified, on failure """ if file_type == 'json': _load_fh = json.load _load_str = json.loads else: _load_fh = yaml.safe_load _load_str = yaml.safe_load try: if is_path: with open(string, 'r') as fh: contents = _load_fh(fh) else: contents = _load_str(string) return contents except (OSError, ValueError, yaml.scanner.ScannerError) as exc: if exception is not None: repl_dict = {'exc': str(exc), 'file_type': file_type} raise exception(message % repl_dict)
python
def load_json_or_yaml(string, is_path=False, file_type='json', exception=ScriptWorkerTaskException, message="Failed to load %(file_type)s: %(exc)s"): """Load json or yaml from a filehandle or string, and raise a custom exception on failure. Args: string (str): json/yaml body or a path to open is_path (bool, optional): if ``string`` is a path. Defaults to False. file_type (str, optional): either "json" or "yaml". Defaults to "json". exception (exception, optional): the exception to raise on failure. If None, don't raise an exception. Defaults to ScriptWorkerTaskException. message (str, optional): the message to use for the exception. Defaults to "Failed to load %(file_type)s: %(exc)s" Returns: dict: the data from the string. Raises: Exception: as specified, on failure """ if file_type == 'json': _load_fh = json.load _load_str = json.loads else: _load_fh = yaml.safe_load _load_str = yaml.safe_load try: if is_path: with open(string, 'r') as fh: contents = _load_fh(fh) else: contents = _load_str(string) return contents except (OSError, ValueError, yaml.scanner.ScannerError) as exc: if exception is not None: repl_dict = {'exc': str(exc), 'file_type': file_type} raise exception(message % repl_dict)
[ "def", "load_json_or_yaml", "(", "string", ",", "is_path", "=", "False", ",", "file_type", "=", "'json'", ",", "exception", "=", "ScriptWorkerTaskException", ",", "message", "=", "\"Failed to load %(file_type)s: %(exc)s\"", ")", ":", "if", "file_type", "==", "'json'...
Load json or yaml from a filehandle or string, and raise a custom exception on failure. Args: string (str): json/yaml body or a path to open is_path (bool, optional): if ``string`` is a path. Defaults to False. file_type (str, optional): either "json" or "yaml". Defaults to "json". exception (exception, optional): the exception to raise on failure. If None, don't raise an exception. Defaults to ScriptWorkerTaskException. message (str, optional): the message to use for the exception. Defaults to "Failed to load %(file_type)s: %(exc)s" Returns: dict: the data from the string. Raises: Exception: as specified, on failure
[ "Load", "json", "or", "yaml", "from", "a", "filehandle", "or", "string", "and", "raise", "a", "custom", "exception", "on", "failure", "." ]
8e97bbd83b9b578565ec57904c966dd6ae4ef0ae
https://github.com/mozilla-releng/scriptworker/blob/8e97bbd83b9b578565ec57904c966dd6ae4ef0ae/scriptworker/utils.py#L428-L466
train
27,978
mozilla-releng/scriptworker
scriptworker/utils.py
write_to_file
def write_to_file(path, contents, file_type='text'): """Write ``contents`` to ``path`` with optional formatting. Small helper function to write ``contents`` to ``file`` with optional formatting. Args: path (str): the path to write to contents (str, object, or bytes): the contents to write to the file file_type (str, optional): the type of file. Currently accepts ``text`` or ``binary`` (contents are unchanged) or ``json`` (contents are formatted). Defaults to ``text``. Raises: ScriptWorkerException: with an unknown ``file_type`` TypeError: if ``file_type`` is ``json`` and ``contents`` isn't JSON serializable """ FILE_TYPES = ('json', 'text', 'binary') if file_type not in FILE_TYPES: raise ScriptWorkerException("Unknown file_type {} not in {}!".format(file_type, FILE_TYPES)) if file_type == 'json': contents = format_json(contents) if file_type == 'binary': with open(path, 'wb') as fh: fh.write(contents) else: with open(path, 'w') as fh: print(contents, file=fh, end="")
python
def write_to_file(path, contents, file_type='text'): """Write ``contents`` to ``path`` with optional formatting. Small helper function to write ``contents`` to ``file`` with optional formatting. Args: path (str): the path to write to contents (str, object, or bytes): the contents to write to the file file_type (str, optional): the type of file. Currently accepts ``text`` or ``binary`` (contents are unchanged) or ``json`` (contents are formatted). Defaults to ``text``. Raises: ScriptWorkerException: with an unknown ``file_type`` TypeError: if ``file_type`` is ``json`` and ``contents`` isn't JSON serializable """ FILE_TYPES = ('json', 'text', 'binary') if file_type not in FILE_TYPES: raise ScriptWorkerException("Unknown file_type {} not in {}!".format(file_type, FILE_TYPES)) if file_type == 'json': contents = format_json(contents) if file_type == 'binary': with open(path, 'wb') as fh: fh.write(contents) else: with open(path, 'w') as fh: print(contents, file=fh, end="")
[ "def", "write_to_file", "(", "path", ",", "contents", ",", "file_type", "=", "'text'", ")", ":", "FILE_TYPES", "=", "(", "'json'", ",", "'text'", ",", "'binary'", ")", "if", "file_type", "not", "in", "FILE_TYPES", ":", "raise", "ScriptWorkerException", "(", ...
Write ``contents`` to ``path`` with optional formatting. Small helper function to write ``contents`` to ``file`` with optional formatting. Args: path (str): the path to write to contents (str, object, or bytes): the contents to write to the file file_type (str, optional): the type of file. Currently accepts ``text`` or ``binary`` (contents are unchanged) or ``json`` (contents are formatted). Defaults to ``text``. Raises: ScriptWorkerException: with an unknown ``file_type`` TypeError: if ``file_type`` is ``json`` and ``contents`` isn't JSON serializable
[ "Write", "contents", "to", "path", "with", "optional", "formatting", "." ]
8e97bbd83b9b578565ec57904c966dd6ae4ef0ae
https://github.com/mozilla-releng/scriptworker/blob/8e97bbd83b9b578565ec57904c966dd6ae4ef0ae/scriptworker/utils.py#L470-L497
train
27,979
mozilla-releng/scriptworker
scriptworker/utils.py
read_from_file
def read_from_file(path, file_type='text', exception=ScriptWorkerException): """Read from ``path``. Small helper function to read from ``file``. Args: path (str): the path to read from. file_type (str, optional): the type of file. Currently accepts ``text`` or ``binary``. Defaults to ``text``. exception (Exception, optional): the exception to raise if unable to read from the file. Defaults to ``ScriptWorkerException``. Returns: None: if unable to read from ``path`` and ``exception`` is ``None`` str or bytes: the contents of ``path`` Raises: Exception: if ``exception`` is set. """ FILE_TYPE_MAP = {'text': 'r', 'binary': 'rb'} if file_type not in FILE_TYPE_MAP: raise exception("Unknown file_type {} not in {}!".format(file_type, FILE_TYPE_MAP)) try: with open(path, FILE_TYPE_MAP[file_type]) as fh: return fh.read() except (OSError, FileNotFoundError) as exc: raise exception("Can't read_from_file {}: {}".format(path, str(exc)))
python
def read_from_file(path, file_type='text', exception=ScriptWorkerException): """Read from ``path``. Small helper function to read from ``file``. Args: path (str): the path to read from. file_type (str, optional): the type of file. Currently accepts ``text`` or ``binary``. Defaults to ``text``. exception (Exception, optional): the exception to raise if unable to read from the file. Defaults to ``ScriptWorkerException``. Returns: None: if unable to read from ``path`` and ``exception`` is ``None`` str or bytes: the contents of ``path`` Raises: Exception: if ``exception`` is set. """ FILE_TYPE_MAP = {'text': 'r', 'binary': 'rb'} if file_type not in FILE_TYPE_MAP: raise exception("Unknown file_type {} not in {}!".format(file_type, FILE_TYPE_MAP)) try: with open(path, FILE_TYPE_MAP[file_type]) as fh: return fh.read() except (OSError, FileNotFoundError) as exc: raise exception("Can't read_from_file {}: {}".format(path, str(exc)))
[ "def", "read_from_file", "(", "path", ",", "file_type", "=", "'text'", ",", "exception", "=", "ScriptWorkerException", ")", ":", "FILE_TYPE_MAP", "=", "{", "'text'", ":", "'r'", ",", "'binary'", ":", "'rb'", "}", "if", "file_type", "not", "in", "FILE_TYPE_MA...
Read from ``path``. Small helper function to read from ``file``. Args: path (str): the path to read from. file_type (str, optional): the type of file. Currently accepts ``text`` or ``binary``. Defaults to ``text``. exception (Exception, optional): the exception to raise if unable to read from the file. Defaults to ``ScriptWorkerException``. Returns: None: if unable to read from ``path`` and ``exception`` is ``None`` str or bytes: the contents of ``path`` Raises: Exception: if ``exception`` is set.
[ "Read", "from", "path", "." ]
8e97bbd83b9b578565ec57904c966dd6ae4ef0ae
https://github.com/mozilla-releng/scriptworker/blob/8e97bbd83b9b578565ec57904c966dd6ae4ef0ae/scriptworker/utils.py#L501-L528
train
27,980
mozilla-releng/scriptworker
scriptworker/utils.py
download_file
async def download_file(context, url, abs_filename, session=None, chunk_size=128): """Download a file, async. Args: context (scriptworker.context.Context): the scriptworker context. url (str): the url to download abs_filename (str): the path to download to session (aiohttp.ClientSession, optional): the session to use. If None, use context.session. Defaults to None. chunk_size (int, optional): the chunk size to read from the response at a time. Default is 128. """ session = session or context.session loggable_url = get_loggable_url(url) log.info("Downloading %s", loggable_url) parent_dir = os.path.dirname(abs_filename) async with session.get(url) as resp: if resp.status == 404: await _log_download_error(resp, "404 downloading %(url)s: %(status)s; body=%(body)s") raise Download404("{} status {}!".format(loggable_url, resp.status)) elif resp.status != 200: await _log_download_error(resp, "Failed to download %(url)s: %(status)s; body=%(body)s") raise DownloadError("{} status {} is not 200!".format(loggable_url, resp.status)) makedirs(parent_dir) with open(abs_filename, "wb") as fd: while True: chunk = await resp.content.read(chunk_size) if not chunk: break fd.write(chunk) log.info("Done")
python
async def download_file(context, url, abs_filename, session=None, chunk_size=128): """Download a file, async. Args: context (scriptworker.context.Context): the scriptworker context. url (str): the url to download abs_filename (str): the path to download to session (aiohttp.ClientSession, optional): the session to use. If None, use context.session. Defaults to None. chunk_size (int, optional): the chunk size to read from the response at a time. Default is 128. """ session = session or context.session loggable_url = get_loggable_url(url) log.info("Downloading %s", loggable_url) parent_dir = os.path.dirname(abs_filename) async with session.get(url) as resp: if resp.status == 404: await _log_download_error(resp, "404 downloading %(url)s: %(status)s; body=%(body)s") raise Download404("{} status {}!".format(loggable_url, resp.status)) elif resp.status != 200: await _log_download_error(resp, "Failed to download %(url)s: %(status)s; body=%(body)s") raise DownloadError("{} status {} is not 200!".format(loggable_url, resp.status)) makedirs(parent_dir) with open(abs_filename, "wb") as fd: while True: chunk = await resp.content.read(chunk_size) if not chunk: break fd.write(chunk) log.info("Done")
[ "async", "def", "download_file", "(", "context", ",", "url", ",", "abs_filename", ",", "session", "=", "None", ",", "chunk_size", "=", "128", ")", ":", "session", "=", "session", "or", "context", ".", "session", "loggable_url", "=", "get_loggable_url", "(", ...
Download a file, async. Args: context (scriptworker.context.Context): the scriptworker context. url (str): the url to download abs_filename (str): the path to download to session (aiohttp.ClientSession, optional): the session to use. If None, use context.session. Defaults to None. chunk_size (int, optional): the chunk size to read from the response at a time. Default is 128.
[ "Download", "a", "file", "async", "." ]
8e97bbd83b9b578565ec57904c966dd6ae4ef0ae
https://github.com/mozilla-releng/scriptworker/blob/8e97bbd83b9b578565ec57904c966dd6ae4ef0ae/scriptworker/utils.py#L538-L569
train
27,981
mozilla-releng/scriptworker
scriptworker/utils.py
get_loggable_url
def get_loggable_url(url): """Strip out secrets from taskcluster urls. Args: url (str): the url to strip Returns: str: the loggable url """ loggable_url = url or "" for secret_string in ("bewit=", "AWSAccessKeyId=", "access_token="): parts = loggable_url.split(secret_string) loggable_url = parts[0] if loggable_url != url: loggable_url = "{}<snip>".format(loggable_url) return loggable_url
python
def get_loggable_url(url): """Strip out secrets from taskcluster urls. Args: url (str): the url to strip Returns: str: the loggable url """ loggable_url = url or "" for secret_string in ("bewit=", "AWSAccessKeyId=", "access_token="): parts = loggable_url.split(secret_string) loggable_url = parts[0] if loggable_url != url: loggable_url = "{}<snip>".format(loggable_url) return loggable_url
[ "def", "get_loggable_url", "(", "url", ")", ":", "loggable_url", "=", "url", "or", "\"\"", "for", "secret_string", "in", "(", "\"bewit=\"", ",", "\"AWSAccessKeyId=\"", ",", "\"access_token=\"", ")", ":", "parts", "=", "loggable_url", ".", "split", "(", "secret...
Strip out secrets from taskcluster urls. Args: url (str): the url to strip Returns: str: the loggable url
[ "Strip", "out", "secrets", "from", "taskcluster", "urls", "." ]
8e97bbd83b9b578565ec57904c966dd6ae4ef0ae
https://github.com/mozilla-releng/scriptworker/blob/8e97bbd83b9b578565ec57904c966dd6ae4ef0ae/scriptworker/utils.py#L573-L589
train
27,982
mozilla-releng/scriptworker
scriptworker/utils.py
match_url_regex
def match_url_regex(rules, url, callback): """Given rules and a callback, find the rule that matches the url. Rules look like:: ( { 'schemes': ['https', 'ssh'], 'netlocs': ['hg.mozilla.org'], 'path_regexes': [ "^(?P<path>/mozilla-(central|unified))(/|$)", ] }, ... ) Args: rules (list): a list of dictionaries specifying lists of ``schemes``, ``netlocs``, and ``path_regexes``. url (str): the url to test callback (function): a callback that takes an ``re.MatchObject``. If it returns None, continue searching. Otherwise, return the value from the callback. Returns: value: the value from the callback, or None if no match. """ parts = urlparse(url) path = unquote(parts.path) for rule in rules: if parts.scheme not in rule['schemes']: continue if parts.netloc not in rule['netlocs']: continue for regex in rule['path_regexes']: m = re.search(regex, path) if m is None: continue result = callback(m) if result is not None: return result
python
def match_url_regex(rules, url, callback): """Given rules and a callback, find the rule that matches the url. Rules look like:: ( { 'schemes': ['https', 'ssh'], 'netlocs': ['hg.mozilla.org'], 'path_regexes': [ "^(?P<path>/mozilla-(central|unified))(/|$)", ] }, ... ) Args: rules (list): a list of dictionaries specifying lists of ``schemes``, ``netlocs``, and ``path_regexes``. url (str): the url to test callback (function): a callback that takes an ``re.MatchObject``. If it returns None, continue searching. Otherwise, return the value from the callback. Returns: value: the value from the callback, or None if no match. """ parts = urlparse(url) path = unquote(parts.path) for rule in rules: if parts.scheme not in rule['schemes']: continue if parts.netloc not in rule['netlocs']: continue for regex in rule['path_regexes']: m = re.search(regex, path) if m is None: continue result = callback(m) if result is not None: return result
[ "def", "match_url_regex", "(", "rules", ",", "url", ",", "callback", ")", ":", "parts", "=", "urlparse", "(", "url", ")", "path", "=", "unquote", "(", "parts", ".", "path", ")", "for", "rule", "in", "rules", ":", "if", "parts", ".", "scheme", "not", ...
Given rules and a callback, find the rule that matches the url. Rules look like:: ( { 'schemes': ['https', 'ssh'], 'netlocs': ['hg.mozilla.org'], 'path_regexes': [ "^(?P<path>/mozilla-(central|unified))(/|$)", ] }, ... ) Args: rules (list): a list of dictionaries specifying lists of ``schemes``, ``netlocs``, and ``path_regexes``. url (str): the url to test callback (function): a callback that takes an ``re.MatchObject``. If it returns None, continue searching. Otherwise, return the value from the callback. Returns: value: the value from the callback, or None if no match.
[ "Given", "rules", "and", "a", "callback", "find", "the", "rule", "that", "matches", "the", "url", "." ]
8e97bbd83b9b578565ec57904c966dd6ae4ef0ae
https://github.com/mozilla-releng/scriptworker/blob/8e97bbd83b9b578565ec57904c966dd6ae4ef0ae/scriptworker/utils.py#L654-L695
train
27,983
mozilla-releng/scriptworker
scriptworker/utils.py
add_enumerable_item_to_dict
def add_enumerable_item_to_dict(dict_, key, item): """Add an item to a list contained in a dict. For example: If the dict is ``{'some_key': ['an_item']}``, then calling this function will alter the dict to ``{'some_key': ['an_item', 'another_item']}``. If the key doesn't exist yet, the function initializes it with a list containing the item. List-like items are allowed. In this case, the existing list will be extended. Args: dict_ (dict): the dict to modify key (str): the key to add the item to item (whatever): The item to add to the list associated to the key """ dict_.setdefault(key, []) if isinstance(item, (list, tuple)): dict_[key].extend(item) else: dict_[key].append(item)
python
def add_enumerable_item_to_dict(dict_, key, item): """Add an item to a list contained in a dict. For example: If the dict is ``{'some_key': ['an_item']}``, then calling this function will alter the dict to ``{'some_key': ['an_item', 'another_item']}``. If the key doesn't exist yet, the function initializes it with a list containing the item. List-like items are allowed. In this case, the existing list will be extended. Args: dict_ (dict): the dict to modify key (str): the key to add the item to item (whatever): The item to add to the list associated to the key """ dict_.setdefault(key, []) if isinstance(item, (list, tuple)): dict_[key].extend(item) else: dict_[key].append(item)
[ "def", "add_enumerable_item_to_dict", "(", "dict_", ",", "key", ",", "item", ")", ":", "dict_", ".", "setdefault", "(", "key", ",", "[", "]", ")", "if", "isinstance", "(", "item", ",", "(", "list", ",", "tuple", ")", ")", ":", "dict_", "[", "key", ...
Add an item to a list contained in a dict. For example: If the dict is ``{'some_key': ['an_item']}``, then calling this function will alter the dict to ``{'some_key': ['an_item', 'another_item']}``. If the key doesn't exist yet, the function initializes it with a list containing the item. List-like items are allowed. In this case, the existing list will be extended. Args: dict_ (dict): the dict to modify key (str): the key to add the item to item (whatever): The item to add to the list associated to the key
[ "Add", "an", "item", "to", "a", "list", "contained", "in", "a", "dict", "." ]
8e97bbd83b9b578565ec57904c966dd6ae4ef0ae
https://github.com/mozilla-releng/scriptworker/blob/8e97bbd83b9b578565ec57904c966dd6ae4ef0ae/scriptworker/utils.py#L699-L720
train
27,984
mozilla-releng/scriptworker
scriptworker/utils.py
get_single_item_from_sequence
def get_single_item_from_sequence( sequence, condition, ErrorClass=ValueError, no_item_error_message='No item matched condition', too_many_item_error_message='Too many items matched condition', append_sequence_to_error_message=True ): """Return an item from a python sequence based on the given condition. Args: sequence (sequence): The sequence to filter condition: A function that serves to filter items from `sequence`. Function must have one argument (a single item from the sequence) and return a boolean. ErrorClass (Exception): The error type raised in case the item isn't unique no_item_error_message (str): The message raised when no item matched the condtion too_many_item_error_message (str): The message raised when more than one item matched the condition append_sequence_to_error_message (bool): Show or hide what was the tested sequence in the error message. Hiding it may prevent sensitive data (such as password) to be exposed to public logs Returns: The only item in the sequence which matched the condition """ filtered_sequence = [item for item in sequence if condition(item)] number_of_items_in_filtered_sequence = len(filtered_sequence) if number_of_items_in_filtered_sequence == 0: error_message = no_item_error_message elif number_of_items_in_filtered_sequence > 1: error_message = too_many_item_error_message else: return filtered_sequence[0] if append_sequence_to_error_message: error_message = '{}. Given: {}'.format(error_message, sequence) raise ErrorClass(error_message)
python
def get_single_item_from_sequence( sequence, condition, ErrorClass=ValueError, no_item_error_message='No item matched condition', too_many_item_error_message='Too many items matched condition', append_sequence_to_error_message=True ): """Return an item from a python sequence based on the given condition. Args: sequence (sequence): The sequence to filter condition: A function that serves to filter items from `sequence`. Function must have one argument (a single item from the sequence) and return a boolean. ErrorClass (Exception): The error type raised in case the item isn't unique no_item_error_message (str): The message raised when no item matched the condtion too_many_item_error_message (str): The message raised when more than one item matched the condition append_sequence_to_error_message (bool): Show or hide what was the tested sequence in the error message. Hiding it may prevent sensitive data (such as password) to be exposed to public logs Returns: The only item in the sequence which matched the condition """ filtered_sequence = [item for item in sequence if condition(item)] number_of_items_in_filtered_sequence = len(filtered_sequence) if number_of_items_in_filtered_sequence == 0: error_message = no_item_error_message elif number_of_items_in_filtered_sequence > 1: error_message = too_many_item_error_message else: return filtered_sequence[0] if append_sequence_to_error_message: error_message = '{}. Given: {}'.format(error_message, sequence) raise ErrorClass(error_message)
[ "def", "get_single_item_from_sequence", "(", "sequence", ",", "condition", ",", "ErrorClass", "=", "ValueError", ",", "no_item_error_message", "=", "'No item matched condition'", ",", "too_many_item_error_message", "=", "'Too many items matched condition'", ",", "append_sequenc...
Return an item from a python sequence based on the given condition. Args: sequence (sequence): The sequence to filter condition: A function that serves to filter items from `sequence`. Function must have one argument (a single item from the sequence) and return a boolean. ErrorClass (Exception): The error type raised in case the item isn't unique no_item_error_message (str): The message raised when no item matched the condtion too_many_item_error_message (str): The message raised when more than one item matched the condition append_sequence_to_error_message (bool): Show or hide what was the tested sequence in the error message. Hiding it may prevent sensitive data (such as password) to be exposed to public logs Returns: The only item in the sequence which matched the condition
[ "Return", "an", "item", "from", "a", "python", "sequence", "based", "on", "the", "given", "condition", "." ]
8e97bbd83b9b578565ec57904c966dd6ae4ef0ae
https://github.com/mozilla-releng/scriptworker/blob/8e97bbd83b9b578565ec57904c966dd6ae4ef0ae/scriptworker/utils.py#L748-L782
train
27,985
mozilla-releng/scriptworker
scriptworker/client.py
get_task
def get_task(config): """Read the task.json from work_dir. Args: config (dict): the running config, to find work_dir. Returns: dict: the contents of task.json Raises: ScriptWorkerTaskException: on error. """ path = os.path.join(config['work_dir'], "task.json") message = "Can't read task from {}!\n%(exc)s".format(path) contents = load_json_or_yaml(path, is_path=True, message=message) return contents
python
def get_task(config): """Read the task.json from work_dir. Args: config (dict): the running config, to find work_dir. Returns: dict: the contents of task.json Raises: ScriptWorkerTaskException: on error. """ path = os.path.join(config['work_dir'], "task.json") message = "Can't read task from {}!\n%(exc)s".format(path) contents = load_json_or_yaml(path, is_path=True, message=message) return contents
[ "def", "get_task", "(", "config", ")", ":", "path", "=", "os", ".", "path", ".", "join", "(", "config", "[", "'work_dir'", "]", ",", "\"task.json\"", ")", "message", "=", "\"Can't read task from {}!\\n%(exc)s\"", ".", "format", "(", "path", ")", "contents", ...
Read the task.json from work_dir. Args: config (dict): the running config, to find work_dir. Returns: dict: the contents of task.json Raises: ScriptWorkerTaskException: on error.
[ "Read", "the", "task", ".", "json", "from", "work_dir", "." ]
8e97bbd83b9b578565ec57904c966dd6ae4ef0ae
https://github.com/mozilla-releng/scriptworker/blob/8e97bbd83b9b578565ec57904c966dd6ae4ef0ae/scriptworker/client.py#L28-L44
train
27,986
mozilla-releng/scriptworker
scriptworker/client.py
validate_json_schema
def validate_json_schema(data, schema, name="task"): """Given data and a jsonschema, let's validate it. This happens for tasks and chain of trust artifacts. Args: data (dict): the json to validate. schema (dict): the jsonschema to validate against. name (str, optional): the name of the json, for exception messages. Defaults to "task". Raises: ScriptWorkerTaskException: on failure """ try: jsonschema.validate(data, schema) except jsonschema.exceptions.ValidationError as exc: raise ScriptWorkerTaskException( "Can't validate {} schema!\n{}".format(name, str(exc)), exit_code=STATUSES['malformed-payload'] )
python
def validate_json_schema(data, schema, name="task"): """Given data and a jsonschema, let's validate it. This happens for tasks and chain of trust artifacts. Args: data (dict): the json to validate. schema (dict): the jsonschema to validate against. name (str, optional): the name of the json, for exception messages. Defaults to "task". Raises: ScriptWorkerTaskException: on failure """ try: jsonschema.validate(data, schema) except jsonschema.exceptions.ValidationError as exc: raise ScriptWorkerTaskException( "Can't validate {} schema!\n{}".format(name, str(exc)), exit_code=STATUSES['malformed-payload'] )
[ "def", "validate_json_schema", "(", "data", ",", "schema", ",", "name", "=", "\"task\"", ")", ":", "try", ":", "jsonschema", ".", "validate", "(", "data", ",", "schema", ")", "except", "jsonschema", ".", "exceptions", ".", "ValidationError", "as", "exc", "...
Given data and a jsonschema, let's validate it. This happens for tasks and chain of trust artifacts. Args: data (dict): the json to validate. schema (dict): the jsonschema to validate against. name (str, optional): the name of the json, for exception messages. Defaults to "task". Raises: ScriptWorkerTaskException: on failure
[ "Given", "data", "and", "a", "jsonschema", "let", "s", "validate", "it", "." ]
8e97bbd83b9b578565ec57904c966dd6ae4ef0ae
https://github.com/mozilla-releng/scriptworker/blob/8e97bbd83b9b578565ec57904c966dd6ae4ef0ae/scriptworker/client.py#L47-L68
train
27,987
mozilla-releng/scriptworker
scriptworker/client.py
validate_task_schema
def validate_task_schema(context, schema_key='schema_file'): """Validate the task definition. Args: context (scriptworker.context.Context): the scriptworker context. It must contain a task and the config pointing to the schema file schema_key: the key in `context.config` where the path to the schema file is. Key can contain dots (e.g.: 'schema_files.file_a'), in which case Raises: TaskVerificationError: if the task doesn't match the schema """ schema_path = context.config schema_keys = schema_key.split('.') for key in schema_keys: schema_path = schema_path[key] task_schema = load_json_or_yaml(schema_path, is_path=True) log.debug('Task is validated against this schema: {}'.format(task_schema)) try: validate_json_schema(context.task, task_schema) except ScriptWorkerTaskException as e: raise TaskVerificationError('Cannot validate task against schema. Task: {}.'.format(context.task)) from e
python
def validate_task_schema(context, schema_key='schema_file'): """Validate the task definition. Args: context (scriptworker.context.Context): the scriptworker context. It must contain a task and the config pointing to the schema file schema_key: the key in `context.config` where the path to the schema file is. Key can contain dots (e.g.: 'schema_files.file_a'), in which case Raises: TaskVerificationError: if the task doesn't match the schema """ schema_path = context.config schema_keys = schema_key.split('.') for key in schema_keys: schema_path = schema_path[key] task_schema = load_json_or_yaml(schema_path, is_path=True) log.debug('Task is validated against this schema: {}'.format(task_schema)) try: validate_json_schema(context.task, task_schema) except ScriptWorkerTaskException as e: raise TaskVerificationError('Cannot validate task against schema. Task: {}.'.format(context.task)) from e
[ "def", "validate_task_schema", "(", "context", ",", "schema_key", "=", "'schema_file'", ")", ":", "schema_path", "=", "context", ".", "config", "schema_keys", "=", "schema_key", ".", "split", "(", "'.'", ")", "for", "key", "in", "schema_keys", ":", "schema_pat...
Validate the task definition. Args: context (scriptworker.context.Context): the scriptworker context. It must contain a task and the config pointing to the schema file schema_key: the key in `context.config` where the path to the schema file is. Key can contain dots (e.g.: 'schema_files.file_a'), in which case Raises: TaskVerificationError: if the task doesn't match the schema
[ "Validate", "the", "task", "definition", "." ]
8e97bbd83b9b578565ec57904c966dd6ae4ef0ae
https://github.com/mozilla-releng/scriptworker/blob/8e97bbd83b9b578565ec57904c966dd6ae4ef0ae/scriptworker/client.py#L71-L95
train
27,988
mozilla-releng/scriptworker
scriptworker/client.py
validate_artifact_url
def validate_artifact_url(valid_artifact_rules, valid_artifact_task_ids, url): """Ensure a URL fits in given scheme, netloc, and path restrictions. If we fail any checks, raise a ScriptWorkerTaskException with ``malformed-payload``. Args: valid_artifact_rules (tuple): the tests to run, with ``schemas``, ``netlocs``, and ``path_regexes``. valid_artifact_task_ids (list): the list of valid task IDs to download from. url (str): the url of the artifact. Returns: str: the ``filepath`` of the path regex. Raises: ScriptWorkerTaskException: on failure to validate. """ def callback(match): path_info = match.groupdict() # make sure we're pointing at a valid task ID if 'taskId' in path_info and \ path_info['taskId'] not in valid_artifact_task_ids: return if 'filepath' not in path_info: return return path_info['filepath'] filepath = match_url_regex(valid_artifact_rules, url, callback) if filepath is None: raise ScriptWorkerTaskException( "Can't validate url {}".format(url), exit_code=STATUSES['malformed-payload'] ) return unquote(filepath).lstrip('/')
python
def validate_artifact_url(valid_artifact_rules, valid_artifact_task_ids, url): """Ensure a URL fits in given scheme, netloc, and path restrictions. If we fail any checks, raise a ScriptWorkerTaskException with ``malformed-payload``. Args: valid_artifact_rules (tuple): the tests to run, with ``schemas``, ``netlocs``, and ``path_regexes``. valid_artifact_task_ids (list): the list of valid task IDs to download from. url (str): the url of the artifact. Returns: str: the ``filepath`` of the path regex. Raises: ScriptWorkerTaskException: on failure to validate. """ def callback(match): path_info = match.groupdict() # make sure we're pointing at a valid task ID if 'taskId' in path_info and \ path_info['taskId'] not in valid_artifact_task_ids: return if 'filepath' not in path_info: return return path_info['filepath'] filepath = match_url_regex(valid_artifact_rules, url, callback) if filepath is None: raise ScriptWorkerTaskException( "Can't validate url {}".format(url), exit_code=STATUSES['malformed-payload'] ) return unquote(filepath).lstrip('/')
[ "def", "validate_artifact_url", "(", "valid_artifact_rules", ",", "valid_artifact_task_ids", ",", "url", ")", ":", "def", "callback", "(", "match", ")", ":", "path_info", "=", "match", ".", "groupdict", "(", ")", "# make sure we're pointing at a valid task ID", "if", ...
Ensure a URL fits in given scheme, netloc, and path restrictions. If we fail any checks, raise a ScriptWorkerTaskException with ``malformed-payload``. Args: valid_artifact_rules (tuple): the tests to run, with ``schemas``, ``netlocs``, and ``path_regexes``. valid_artifact_task_ids (list): the list of valid task IDs to download from. url (str): the url of the artifact. Returns: str: the ``filepath`` of the path regex. Raises: ScriptWorkerTaskException: on failure to validate.
[ "Ensure", "a", "URL", "fits", "in", "given", "scheme", "netloc", "and", "path", "restrictions", "." ]
8e97bbd83b9b578565ec57904c966dd6ae4ef0ae
https://github.com/mozilla-releng/scriptworker/blob/8e97bbd83b9b578565ec57904c966dd6ae4ef0ae/scriptworker/client.py#L98-L133
train
27,989
mozilla-releng/scriptworker
scriptworker/client.py
sync_main
def sync_main(async_main, config_path=None, default_config=None, should_validate_task=True, loop_function=asyncio.get_event_loop): """Entry point for scripts using scriptworker. This function sets up the basic needs for a script to run. More specifically: * it creates the scriptworker context and initializes it with the provided config * the path to the config file is either taken from `config_path` or from `sys.argv[1]`. * it verifies `sys.argv` doesn't have more arguments than the config path. * it creates the asyncio event loop so that `async_main` can run Args: async_main (function): The function to call once everything is set up config_path (str, optional): The path to the file to load the config from. Loads from ``sys.argv[1]`` if ``None``. Defaults to None. default_config (dict, optional): the default config to use for ``_init_context``. defaults to None. should_validate_task (bool, optional): whether we should validate the task schema. Defaults to True. loop_function (function, optional): the function to call to get the event loop; here for testing purposes. Defaults to ``asyncio.get_event_loop``. """ context = _init_context(config_path, default_config) _init_logging(context) if should_validate_task: validate_task_schema(context) loop = loop_function() loop.run_until_complete(_handle_asyncio_loop(async_main, context))
python
def sync_main(async_main, config_path=None, default_config=None, should_validate_task=True, loop_function=asyncio.get_event_loop): """Entry point for scripts using scriptworker. This function sets up the basic needs for a script to run. More specifically: * it creates the scriptworker context and initializes it with the provided config * the path to the config file is either taken from `config_path` or from `sys.argv[1]`. * it verifies `sys.argv` doesn't have more arguments than the config path. * it creates the asyncio event loop so that `async_main` can run Args: async_main (function): The function to call once everything is set up config_path (str, optional): The path to the file to load the config from. Loads from ``sys.argv[1]`` if ``None``. Defaults to None. default_config (dict, optional): the default config to use for ``_init_context``. defaults to None. should_validate_task (bool, optional): whether we should validate the task schema. Defaults to True. loop_function (function, optional): the function to call to get the event loop; here for testing purposes. Defaults to ``asyncio.get_event_loop``. """ context = _init_context(config_path, default_config) _init_logging(context) if should_validate_task: validate_task_schema(context) loop = loop_function() loop.run_until_complete(_handle_asyncio_loop(async_main, context))
[ "def", "sync_main", "(", "async_main", ",", "config_path", "=", "None", ",", "default_config", "=", "None", ",", "should_validate_task", "=", "True", ",", "loop_function", "=", "asyncio", ".", "get_event_loop", ")", ":", "context", "=", "_init_context", "(", "...
Entry point for scripts using scriptworker. This function sets up the basic needs for a script to run. More specifically: * it creates the scriptworker context and initializes it with the provided config * the path to the config file is either taken from `config_path` or from `sys.argv[1]`. * it verifies `sys.argv` doesn't have more arguments than the config path. * it creates the asyncio event loop so that `async_main` can run Args: async_main (function): The function to call once everything is set up config_path (str, optional): The path to the file to load the config from. Loads from ``sys.argv[1]`` if ``None``. Defaults to None. default_config (dict, optional): the default config to use for ``_init_context``. defaults to None. should_validate_task (bool, optional): whether we should validate the task schema. Defaults to True. loop_function (function, optional): the function to call to get the event loop; here for testing purposes. Defaults to ``asyncio.get_event_loop``.
[ "Entry", "point", "for", "scripts", "using", "scriptworker", "." ]
8e97bbd83b9b578565ec57904c966dd6ae4ef0ae
https://github.com/mozilla-releng/scriptworker/blob/8e97bbd83b9b578565ec57904c966dd6ae4ef0ae/scriptworker/client.py#L136-L164
train
27,990
mozilla-releng/scriptworker
scriptworker/task_process.py
TaskProcess.stop
async def stop(self): """Stop the current task process. Starts with SIGTERM, gives the process 1 second to terminate, then kills it """ # negate pid so that signals apply to process group pgid = -self.process.pid try: os.kill(pgid, signal.SIGTERM) await asyncio.sleep(1) os.kill(pgid, signal.SIGKILL) except (OSError, ProcessLookupError): return
python
async def stop(self): """Stop the current task process. Starts with SIGTERM, gives the process 1 second to terminate, then kills it """ # negate pid so that signals apply to process group pgid = -self.process.pid try: os.kill(pgid, signal.SIGTERM) await asyncio.sleep(1) os.kill(pgid, signal.SIGKILL) except (OSError, ProcessLookupError): return
[ "async", "def", "stop", "(", "self", ")", ":", "# negate pid so that signals apply to process group", "pgid", "=", "-", "self", ".", "process", ".", "pid", "try", ":", "os", ".", "kill", "(", "pgid", ",", "signal", ".", "SIGTERM", ")", "await", "asyncio", ...
Stop the current task process. Starts with SIGTERM, gives the process 1 second to terminate, then kills it
[ "Stop", "the", "current", "task", "process", "." ]
8e97bbd83b9b578565ec57904c966dd6ae4ef0ae
https://github.com/mozilla-releng/scriptworker/blob/8e97bbd83b9b578565ec57904c966dd6ae4ef0ae/scriptworker/task_process.py#L35-L47
train
27,991
mozilla-releng/scriptworker
scriptworker/ed25519.py
ed25519_private_key_from_string
def ed25519_private_key_from_string(string): """Create an ed25519 private key from ``string``, which is a seed. Args: string (str): the string to use as a seed. Returns: Ed25519PrivateKey: the private key """ try: return Ed25519PrivateKey.from_private_bytes( base64.b64decode(string) ) except (UnsupportedAlgorithm, Base64Error) as exc: raise ScriptWorkerEd25519Error("Can't create Ed25519PrivateKey: {}!".format(str(exc)))
python
def ed25519_private_key_from_string(string): """Create an ed25519 private key from ``string``, which is a seed. Args: string (str): the string to use as a seed. Returns: Ed25519PrivateKey: the private key """ try: return Ed25519PrivateKey.from_private_bytes( base64.b64decode(string) ) except (UnsupportedAlgorithm, Base64Error) as exc: raise ScriptWorkerEd25519Error("Can't create Ed25519PrivateKey: {}!".format(str(exc)))
[ "def", "ed25519_private_key_from_string", "(", "string", ")", ":", "try", ":", "return", "Ed25519PrivateKey", ".", "from_private_bytes", "(", "base64", ".", "b64decode", "(", "string", ")", ")", "except", "(", "UnsupportedAlgorithm", ",", "Base64Error", ")", "as",...
Create an ed25519 private key from ``string``, which is a seed. Args: string (str): the string to use as a seed. Returns: Ed25519PrivateKey: the private key
[ "Create", "an", "ed25519", "private", "key", "from", "string", "which", "is", "a", "seed", "." ]
8e97bbd83b9b578565ec57904c966dd6ae4ef0ae
https://github.com/mozilla-releng/scriptworker/blob/8e97bbd83b9b578565ec57904c966dd6ae4ef0ae/scriptworker/ed25519.py#L24-L39
train
27,992
mozilla-releng/scriptworker
scriptworker/ed25519.py
ed25519_public_key_from_string
def ed25519_public_key_from_string(string): """Create an ed25519 public key from ``string``, which is a seed. Args: string (str): the string to use as a seed. Returns: Ed25519PublicKey: the public key """ try: return Ed25519PublicKey.from_public_bytes( base64.b64decode(string) ) except (UnsupportedAlgorithm, Base64Error) as exc: raise ScriptWorkerEd25519Error("Can't create Ed25519PublicKey: {}!".format(str(exc)))
python
def ed25519_public_key_from_string(string): """Create an ed25519 public key from ``string``, which is a seed. Args: string (str): the string to use as a seed. Returns: Ed25519PublicKey: the public key """ try: return Ed25519PublicKey.from_public_bytes( base64.b64decode(string) ) except (UnsupportedAlgorithm, Base64Error) as exc: raise ScriptWorkerEd25519Error("Can't create Ed25519PublicKey: {}!".format(str(exc)))
[ "def", "ed25519_public_key_from_string", "(", "string", ")", ":", "try", ":", "return", "Ed25519PublicKey", ".", "from_public_bytes", "(", "base64", ".", "b64decode", "(", "string", ")", ")", "except", "(", "UnsupportedAlgorithm", ",", "Base64Error", ")", "as", ...
Create an ed25519 public key from ``string``, which is a seed. Args: string (str): the string to use as a seed. Returns: Ed25519PublicKey: the public key
[ "Create", "an", "ed25519", "public", "key", "from", "string", "which", "is", "a", "seed", "." ]
8e97bbd83b9b578565ec57904c966dd6ae4ef0ae
https://github.com/mozilla-releng/scriptworker/blob/8e97bbd83b9b578565ec57904c966dd6ae4ef0ae/scriptworker/ed25519.py#L42-L57
train
27,993
mozilla-releng/scriptworker
scriptworker/ed25519.py
_ed25519_key_from_file
def _ed25519_key_from_file(fn, path): """Create an ed25519 key from the contents of ``path``. ``path`` is a filepath containing a base64-encoded ed25519 key seed. Args: fn (callable): the function to call with the contents from ``path`` path (str): the file path to the base64-encoded key seed. Returns: obj: the appropriate key type from ``path`` Raises: ScriptWorkerEd25519Error """ try: return fn(read_from_file(path, exception=ScriptWorkerEd25519Error)) except ScriptWorkerException as exc: raise ScriptWorkerEd25519Error("Failed calling {} for {}: {}!".format(fn, path, str(exc)))
python
def _ed25519_key_from_file(fn, path): """Create an ed25519 key from the contents of ``path``. ``path`` is a filepath containing a base64-encoded ed25519 key seed. Args: fn (callable): the function to call with the contents from ``path`` path (str): the file path to the base64-encoded key seed. Returns: obj: the appropriate key type from ``path`` Raises: ScriptWorkerEd25519Error """ try: return fn(read_from_file(path, exception=ScriptWorkerEd25519Error)) except ScriptWorkerException as exc: raise ScriptWorkerEd25519Error("Failed calling {} for {}: {}!".format(fn, path, str(exc)))
[ "def", "_ed25519_key_from_file", "(", "fn", ",", "path", ")", ":", "try", ":", "return", "fn", "(", "read_from_file", "(", "path", ",", "exception", "=", "ScriptWorkerEd25519Error", ")", ")", "except", "ScriptWorkerException", "as", "exc", ":", "raise", "Scrip...
Create an ed25519 key from the contents of ``path``. ``path`` is a filepath containing a base64-encoded ed25519 key seed. Args: fn (callable): the function to call with the contents from ``path`` path (str): the file path to the base64-encoded key seed. Returns: obj: the appropriate key type from ``path`` Raises: ScriptWorkerEd25519Error
[ "Create", "an", "ed25519", "key", "from", "the", "contents", "of", "path", "." ]
8e97bbd83b9b578565ec57904c966dd6ae4ef0ae
https://github.com/mozilla-releng/scriptworker/blob/8e97bbd83b9b578565ec57904c966dd6ae4ef0ae/scriptworker/ed25519.py#L60-L79
train
27,994
mozilla-releng/scriptworker
scriptworker/ed25519.py
ed25519_private_key_to_string
def ed25519_private_key_to_string(key): """Convert an ed25519 private key to a base64-encoded string. Args: key (Ed25519PrivateKey): the key to write to the file. Returns: str: the key representation as a str """ return base64.b64encode(key.private_bytes( encoding=serialization.Encoding.Raw, format=serialization.PrivateFormat.Raw, encryption_algorithm=serialization.NoEncryption() ), None).decode('utf-8')
python
def ed25519_private_key_to_string(key): """Convert an ed25519 private key to a base64-encoded string. Args: key (Ed25519PrivateKey): the key to write to the file. Returns: str: the key representation as a str """ return base64.b64encode(key.private_bytes( encoding=serialization.Encoding.Raw, format=serialization.PrivateFormat.Raw, encryption_algorithm=serialization.NoEncryption() ), None).decode('utf-8')
[ "def", "ed25519_private_key_to_string", "(", "key", ")", ":", "return", "base64", ".", "b64encode", "(", "key", ".", "private_bytes", "(", "encoding", "=", "serialization", ".", "Encoding", ".", "Raw", ",", "format", "=", "serialization", ".", "PrivateFormat", ...
Convert an ed25519 private key to a base64-encoded string. Args: key (Ed25519PrivateKey): the key to write to the file. Returns: str: the key representation as a str
[ "Convert", "an", "ed25519", "private", "key", "to", "a", "base64", "-", "encoded", "string", "." ]
8e97bbd83b9b578565ec57904c966dd6ae4ef0ae
https://github.com/mozilla-releng/scriptworker/blob/8e97bbd83b9b578565ec57904c966dd6ae4ef0ae/scriptworker/ed25519.py#L86-L100
train
27,995
mozilla-releng/scriptworker
scriptworker/ed25519.py
ed25519_public_key_to_string
def ed25519_public_key_to_string(key): """Convert an ed25519 public key to a base64-encoded string. Args: key (Ed25519PublicKey): the key to write to the file. Returns: str: the key representation as a str """ return base64.b64encode(key.public_bytes( encoding=serialization.Encoding.Raw, format=serialization.PublicFormat.Raw, ), None).decode('utf-8')
python
def ed25519_public_key_to_string(key): """Convert an ed25519 public key to a base64-encoded string. Args: key (Ed25519PublicKey): the key to write to the file. Returns: str: the key representation as a str """ return base64.b64encode(key.public_bytes( encoding=serialization.Encoding.Raw, format=serialization.PublicFormat.Raw, ), None).decode('utf-8')
[ "def", "ed25519_public_key_to_string", "(", "key", ")", ":", "return", "base64", ".", "b64encode", "(", "key", ".", "public_bytes", "(", "encoding", "=", "serialization", ".", "Encoding", ".", "Raw", ",", "format", "=", "serialization", ".", "PublicFormat", "....
Convert an ed25519 public key to a base64-encoded string. Args: key (Ed25519PublicKey): the key to write to the file. Returns: str: the key representation as a str
[ "Convert", "an", "ed25519", "public", "key", "to", "a", "base64", "-", "encoded", "string", "." ]
8e97bbd83b9b578565ec57904c966dd6ae4ef0ae
https://github.com/mozilla-releng/scriptworker/blob/8e97bbd83b9b578565ec57904c966dd6ae4ef0ae/scriptworker/ed25519.py#L103-L116
train
27,996
mozilla-releng/scriptworker
scriptworker/ed25519.py
verify_ed25519_signature
def verify_ed25519_signature(public_key, contents, signature, message): """Verify that ``signature`` comes from ``public_key`` and ``contents``. Args: public_key (Ed25519PublicKey): the key to verify the signature contents (bytes): the contents that was signed signature (bytes): the signature to verify message (str): the error message to raise. Raises: ScriptWorkerEd25519Error: on failure """ try: public_key.verify(signature, contents) except InvalidSignature as exc: raise ScriptWorkerEd25519Error(message % {'exc': str(exc)})
python
def verify_ed25519_signature(public_key, contents, signature, message): """Verify that ``signature`` comes from ``public_key`` and ``contents``. Args: public_key (Ed25519PublicKey): the key to verify the signature contents (bytes): the contents that was signed signature (bytes): the signature to verify message (str): the error message to raise. Raises: ScriptWorkerEd25519Error: on failure """ try: public_key.verify(signature, contents) except InvalidSignature as exc: raise ScriptWorkerEd25519Error(message % {'exc': str(exc)})
[ "def", "verify_ed25519_signature", "(", "public_key", ",", "contents", ",", "signature", ",", "message", ")", ":", "try", ":", "public_key", ".", "verify", "(", "signature", ",", "contents", ")", "except", "InvalidSignature", "as", "exc", ":", "raise", "Script...
Verify that ``signature`` comes from ``public_key`` and ``contents``. Args: public_key (Ed25519PublicKey): the key to verify the signature contents (bytes): the contents that was signed signature (bytes): the signature to verify message (str): the error message to raise. Raises: ScriptWorkerEd25519Error: on failure
[ "Verify", "that", "signature", "comes", "from", "public_key", "and", "contents", "." ]
8e97bbd83b9b578565ec57904c966dd6ae4ef0ae
https://github.com/mozilla-releng/scriptworker/blob/8e97bbd83b9b578565ec57904c966dd6ae4ef0ae/scriptworker/ed25519.py#L119-L135
train
27,997
mozilla-releng/scriptworker
scriptworker/constants.py
get_reversed_statuses
def get_reversed_statuses(context): """Return a mapping of exit codes to status strings. Args: context (scriptworker.context.Context): the scriptworker context Returns: dict: the mapping of exit codes to status strings. """ _rev = {v: k for k, v in STATUSES.items()} _rev.update(dict(context.config['reversed_statuses'])) return _rev
python
def get_reversed_statuses(context): """Return a mapping of exit codes to status strings. Args: context (scriptworker.context.Context): the scriptworker context Returns: dict: the mapping of exit codes to status strings. """ _rev = {v: k for k, v in STATUSES.items()} _rev.update(dict(context.config['reversed_statuses'])) return _rev
[ "def", "get_reversed_statuses", "(", "context", ")", ":", "_rev", "=", "{", "v", ":", "k", "for", "k", ",", "v", "in", "STATUSES", ".", "items", "(", ")", "}", "_rev", ".", "update", "(", "dict", "(", "context", ".", "config", "[", "'reversed_statuse...
Return a mapping of exit codes to status strings. Args: context (scriptworker.context.Context): the scriptworker context Returns: dict: the mapping of exit codes to status strings.
[ "Return", "a", "mapping", "of", "exit", "codes", "to", "status", "strings", "." ]
8e97bbd83b9b578565ec57904c966dd6ae4ef0ae
https://github.com/mozilla-releng/scriptworker/blob/8e97bbd83b9b578565ec57904c966dd6ae4ef0ae/scriptworker/constants.py#L463-L475
train
27,998
mozilla-releng/scriptworker
scriptworker/task.py
get_repo
def get_repo(task, source_env_prefix): """Get the repo for a task. Args: task (ChainOfTrust or LinkOfTrust): the trust object to inspect source_env_prefix (str): The environment variable prefix that is used to get repository information. Returns: str: the source url. None: if not defined for this task. """ repo = _extract_from_env_in_payload(task, source_env_prefix + '_HEAD_REPOSITORY') if repo is not None: repo = repo.rstrip('/') return repo
python
def get_repo(task, source_env_prefix): """Get the repo for a task. Args: task (ChainOfTrust or LinkOfTrust): the trust object to inspect source_env_prefix (str): The environment variable prefix that is used to get repository information. Returns: str: the source url. None: if not defined for this task. """ repo = _extract_from_env_in_payload(task, source_env_prefix + '_HEAD_REPOSITORY') if repo is not None: repo = repo.rstrip('/') return repo
[ "def", "get_repo", "(", "task", ",", "source_env_prefix", ")", ":", "repo", "=", "_extract_from_env_in_payload", "(", "task", ",", "source_env_prefix", "+", "'_HEAD_REPOSITORY'", ")", "if", "repo", "is", "not", "None", ":", "repo", "=", "repo", ".", "rstrip", ...
Get the repo for a task. Args: task (ChainOfTrust or LinkOfTrust): the trust object to inspect source_env_prefix (str): The environment variable prefix that is used to get repository information. Returns: str: the source url. None: if not defined for this task.
[ "Get", "the", "repo", "for", "a", "task", "." ]
8e97bbd83b9b578565ec57904c966dd6ae4ef0ae
https://github.com/mozilla-releng/scriptworker/blob/8e97bbd83b9b578565ec57904c966dd6ae4ef0ae/scriptworker/task.py#L151-L167
train
27,999