id
int32
0
252k
repo
stringlengths
7
55
path
stringlengths
4
127
func_name
stringlengths
1
88
original_string
stringlengths
75
19.8k
language
stringclasses
1 value
code
stringlengths
75
19.8k
code_tokens
list
docstring
stringlengths
3
17.3k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
87
242
8,300
CalebBell/fluids
fluids/drag.py
integrate_drag_sphere
def integrate_drag_sphere(D, rhop, rho, mu, t, V=0, Method=None, distance=False): r'''Integrates the velocity and distance traveled by a particle moving at a speed which will converge to its terminal velocity. Performs an integration of the following expression for acceleration: .. math:: a = \frac{g(\rho_p-\rho_f)}{\rho_p} - \frac{3C_D \rho_f u^2}{4D \rho_p} Parameters ---------- D : float Diameter of the sphere, [m] rhop : float Particle density, [kg/m^3] rho : float Density of the surrounding fluid, [kg/m^3] mu : float Viscosity of the surrounding fluid [Pa*s] t : float Time to integrate the particle to, [s] V : float Initial velocity of the particle, [m/s] Method : string, optional A string of the function name to use, as in the dictionary drag_sphere_correlations distance : bool, optional Whether or not to calculate the distance traveled and return it as well Returns ------- v : float Velocity of falling sphere after time `t` [m/s] x : float, returned only if `distance` == True Distance traveled by the falling sphere in time `t`, [m] Notes ----- This can be relatively slow as drag correlations can be complex. There are analytical solutions available for the Stokes law regime (Re < 0.3). They were obtained from Wolfram Alpha. [1]_ was not used in the derivation, but also describes the derivation fully. .. math:: V(t) = \frac{\exp(-at) (V_0 a + b(\exp(at) - 1))}{a} .. math:: x(t) = \frac{\exp(-a t)\left[V_0 a(\exp(a t) - 1) + b\exp(a t)(a t-1) + b\right]}{a^2} .. math:: a = \frac{18\mu_f}{D^2\rho_p} .. math:: b = \frac{g(\rho_p-\rho_f)}{\rho_p} The analytical solution will automatically be used if the initial and terminal velocity is show the particle's behavior to be laminar. Note that this behavior requires that the terminal velocity of the particle be solved for - this adds slight (1%) overhead for the cases where particles are not laminar. Examples -------- >>> integrate_drag_sphere(D=0.001, rhop=2200., rho=1.2, mu=1.78E-5, t=0.5, ... V=30, distance=True) (9.686465044053476, 7.8294546436299175) References ---------- .. [1] Timmerman, Peter, and Jacobus P. van der Weele. "On the Rise and Fall of a Ball with Linear or Quadratic Drag." American Journal of Physics 67, no. 6 (June 1999): 538-46. https://doi.org/10.1119/1.19320. ''' laminar_initial = Reynolds(V=V, rho=rho, D=D, mu=mu) < 0.01 v_laminar_end_assumed = v_terminal(D=D, rhop=rhop, rho=rho, mu=mu, Method=Method) laminar_end = Reynolds(V=v_laminar_end_assumed, rho=rho, D=D, mu=mu) < 0.01 if Method == 'Stokes' or (laminar_initial and laminar_end and Method is None): try: t1 = 18.0*mu/(D*D*rhop) t2 = g*(rhop-rho)/rhop V_end = exp(-t1*t)*(t1*V + t2*(exp(t1*t) - 1.0))/t1 x_end = exp(-t1*t)*(V*t1*(exp(t1*t) - 1.0) + t2*exp(t1*t)*(t1*t - 1.0) + t2)/(t1*t1) if distance: return V_end, x_end else: return V_end except OverflowError: # It is only necessary to integrate to terminal velocity t_to_terminal = time_v_terminal_Stokes(D, rhop, rho, mu, V0=V, tol=1e-9) if t_to_terminal > t: raise Exception('Should never happen') V_end, x_end = integrate_drag_sphere(D=D, rhop=rhop, rho=rho, mu=mu, t=t_to_terminal, V=V, Method='Stokes', distance=True) # terminal velocity has been reached - V does not change, but x does # No reason to believe this isn't working even though it isn't # matching the ode solver if distance: return V_end, x_end + V_end*(t - t_to_terminal) else: return V_end # This is a serious problem for small diameters # It would be possible to step slowly, using smaller increments # of time to avlid overflows. However, this unfortunately quickly # gets much, exponentially, slower than just using odeint because # for example solving 10000 seconds might require steps of .0001 # seconds at a diameter of 1e-7 meters. # x = 0.0 # subdivisions = 10 # dt = t/subdivisions # for i in range(subdivisions): # V, dx = integrate_drag_sphere(D=D, rhop=rhop, rho=rho, mu=mu, # t=dt, V=V, distance=True, # Method=Method) # x += dx # if distance: # return V, x # else: # return V Re_ish = rho*D/mu c1 = g*(rhop-rho)/rhop c2 = -0.75*rho/(D*rhop) def dv_dt(V, t): if V == 0: # 64/Re goes to infinity, but gets multiplied by 0 squared. t2 = 0.0 else: # t2 = c2*V*V*Stokes(Re_ish*V) t2 = c2*V*V*drag_sphere(Re_ish*V, Method=Method) return c1 + t2 # Number of intervals for the solution to be solved for; the integrator # doesn't care what we give it, but a large number of intervals are needed # For an accurate integration of the particle's distance traveled pts = 1000 if distance else 2 ts = np.linspace(0, t, pts) # Delayed import of necessaray functions from scipy.integrate import odeint, cumtrapz # Perform the integration Vs = odeint(dv_dt, [V], ts) # V_end = float(Vs[-1]) if distance: # Calculate the distance traveled x = float(cumtrapz(np.ravel(Vs), ts)[-1]) return V_end, x else: return V_end
python
def integrate_drag_sphere(D, rhop, rho, mu, t, V=0, Method=None, distance=False): r'''Integrates the velocity and distance traveled by a particle moving at a speed which will converge to its terminal velocity. Performs an integration of the following expression for acceleration: .. math:: a = \frac{g(\rho_p-\rho_f)}{\rho_p} - \frac{3C_D \rho_f u^2}{4D \rho_p} Parameters ---------- D : float Diameter of the sphere, [m] rhop : float Particle density, [kg/m^3] rho : float Density of the surrounding fluid, [kg/m^3] mu : float Viscosity of the surrounding fluid [Pa*s] t : float Time to integrate the particle to, [s] V : float Initial velocity of the particle, [m/s] Method : string, optional A string of the function name to use, as in the dictionary drag_sphere_correlations distance : bool, optional Whether or not to calculate the distance traveled and return it as well Returns ------- v : float Velocity of falling sphere after time `t` [m/s] x : float, returned only if `distance` == True Distance traveled by the falling sphere in time `t`, [m] Notes ----- This can be relatively slow as drag correlations can be complex. There are analytical solutions available for the Stokes law regime (Re < 0.3). They were obtained from Wolfram Alpha. [1]_ was not used in the derivation, but also describes the derivation fully. .. math:: V(t) = \frac{\exp(-at) (V_0 a + b(\exp(at) - 1))}{a} .. math:: x(t) = \frac{\exp(-a t)\left[V_0 a(\exp(a t) - 1) + b\exp(a t)(a t-1) + b\right]}{a^2} .. math:: a = \frac{18\mu_f}{D^2\rho_p} .. math:: b = \frac{g(\rho_p-\rho_f)}{\rho_p} The analytical solution will automatically be used if the initial and terminal velocity is show the particle's behavior to be laminar. Note that this behavior requires that the terminal velocity of the particle be solved for - this adds slight (1%) overhead for the cases where particles are not laminar. Examples -------- >>> integrate_drag_sphere(D=0.001, rhop=2200., rho=1.2, mu=1.78E-5, t=0.5, ... V=30, distance=True) (9.686465044053476, 7.8294546436299175) References ---------- .. [1] Timmerman, Peter, and Jacobus P. van der Weele. "On the Rise and Fall of a Ball with Linear or Quadratic Drag." American Journal of Physics 67, no. 6 (June 1999): 538-46. https://doi.org/10.1119/1.19320. ''' laminar_initial = Reynolds(V=V, rho=rho, D=D, mu=mu) < 0.01 v_laminar_end_assumed = v_terminal(D=D, rhop=rhop, rho=rho, mu=mu, Method=Method) laminar_end = Reynolds(V=v_laminar_end_assumed, rho=rho, D=D, mu=mu) < 0.01 if Method == 'Stokes' or (laminar_initial and laminar_end and Method is None): try: t1 = 18.0*mu/(D*D*rhop) t2 = g*(rhop-rho)/rhop V_end = exp(-t1*t)*(t1*V + t2*(exp(t1*t) - 1.0))/t1 x_end = exp(-t1*t)*(V*t1*(exp(t1*t) - 1.0) + t2*exp(t1*t)*(t1*t - 1.0) + t2)/(t1*t1) if distance: return V_end, x_end else: return V_end except OverflowError: # It is only necessary to integrate to terminal velocity t_to_terminal = time_v_terminal_Stokes(D, rhop, rho, mu, V0=V, tol=1e-9) if t_to_terminal > t: raise Exception('Should never happen') V_end, x_end = integrate_drag_sphere(D=D, rhop=rhop, rho=rho, mu=mu, t=t_to_terminal, V=V, Method='Stokes', distance=True) # terminal velocity has been reached - V does not change, but x does # No reason to believe this isn't working even though it isn't # matching the ode solver if distance: return V_end, x_end + V_end*(t - t_to_terminal) else: return V_end # This is a serious problem for small diameters # It would be possible to step slowly, using smaller increments # of time to avlid overflows. However, this unfortunately quickly # gets much, exponentially, slower than just using odeint because # for example solving 10000 seconds might require steps of .0001 # seconds at a diameter of 1e-7 meters. # x = 0.0 # subdivisions = 10 # dt = t/subdivisions # for i in range(subdivisions): # V, dx = integrate_drag_sphere(D=D, rhop=rhop, rho=rho, mu=mu, # t=dt, V=V, distance=True, # Method=Method) # x += dx # if distance: # return V, x # else: # return V Re_ish = rho*D/mu c1 = g*(rhop-rho)/rhop c2 = -0.75*rho/(D*rhop) def dv_dt(V, t): if V == 0: # 64/Re goes to infinity, but gets multiplied by 0 squared. t2 = 0.0 else: # t2 = c2*V*V*Stokes(Re_ish*V) t2 = c2*V*V*drag_sphere(Re_ish*V, Method=Method) return c1 + t2 # Number of intervals for the solution to be solved for; the integrator # doesn't care what we give it, but a large number of intervals are needed # For an accurate integration of the particle's distance traveled pts = 1000 if distance else 2 ts = np.linspace(0, t, pts) # Delayed import of necessaray functions from scipy.integrate import odeint, cumtrapz # Perform the integration Vs = odeint(dv_dt, [V], ts) # V_end = float(Vs[-1]) if distance: # Calculate the distance traveled x = float(cumtrapz(np.ravel(Vs), ts)[-1]) return V_end, x else: return V_end
[ "def", "integrate_drag_sphere", "(", "D", ",", "rhop", ",", "rho", ",", "mu", ",", "t", ",", "V", "=", "0", ",", "Method", "=", "None", ",", "distance", "=", "False", ")", ":", "laminar_initial", "=", "Reynolds", "(", "V", "=", "V", ",", "rho", "=", "rho", ",", "D", "=", "D", ",", "mu", "=", "mu", ")", "<", "0.01", "v_laminar_end_assumed", "=", "v_terminal", "(", "D", "=", "D", ",", "rhop", "=", "rhop", ",", "rho", "=", "rho", ",", "mu", "=", "mu", ",", "Method", "=", "Method", ")", "laminar_end", "=", "Reynolds", "(", "V", "=", "v_laminar_end_assumed", ",", "rho", "=", "rho", ",", "D", "=", "D", ",", "mu", "=", "mu", ")", "<", "0.01", "if", "Method", "==", "'Stokes'", "or", "(", "laminar_initial", "and", "laminar_end", "and", "Method", "is", "None", ")", ":", "try", ":", "t1", "=", "18.0", "*", "mu", "/", "(", "D", "*", "D", "*", "rhop", ")", "t2", "=", "g", "*", "(", "rhop", "-", "rho", ")", "/", "rhop", "V_end", "=", "exp", "(", "-", "t1", "*", "t", ")", "*", "(", "t1", "*", "V", "+", "t2", "*", "(", "exp", "(", "t1", "*", "t", ")", "-", "1.0", ")", ")", "/", "t1", "x_end", "=", "exp", "(", "-", "t1", "*", "t", ")", "*", "(", "V", "*", "t1", "*", "(", "exp", "(", "t1", "*", "t", ")", "-", "1.0", ")", "+", "t2", "*", "exp", "(", "t1", "*", "t", ")", "*", "(", "t1", "*", "t", "-", "1.0", ")", "+", "t2", ")", "/", "(", "t1", "*", "t1", ")", "if", "distance", ":", "return", "V_end", ",", "x_end", "else", ":", "return", "V_end", "except", "OverflowError", ":", "# It is only necessary to integrate to terminal velocity", "t_to_terminal", "=", "time_v_terminal_Stokes", "(", "D", ",", "rhop", ",", "rho", ",", "mu", ",", "V0", "=", "V", ",", "tol", "=", "1e-9", ")", "if", "t_to_terminal", ">", "t", ":", "raise", "Exception", "(", "'Should never happen'", ")", "V_end", ",", "x_end", "=", "integrate_drag_sphere", "(", "D", "=", "D", ",", "rhop", "=", "rhop", ",", "rho", "=", "rho", ",", "mu", "=", "mu", ",", "t", "=", "t_to_terminal", ",", "V", "=", "V", ",", "Method", "=", "'Stokes'", ",", "distance", "=", "True", ")", "# terminal velocity has been reached - V does not change, but x does", "# No reason to believe this isn't working even though it isn't", "# matching the ode solver", "if", "distance", ":", "return", "V_end", ",", "x_end", "+", "V_end", "*", "(", "t", "-", "t_to_terminal", ")", "else", ":", "return", "V_end", "# This is a serious problem for small diameters", "# It would be possible to step slowly, using smaller increments", "# of time to avlid overflows. However, this unfortunately quickly", "# gets much, exponentially, slower than just using odeint because", "# for example solving 10000 seconds might require steps of .0001", "# seconds at a diameter of 1e-7 meters.", "# x = 0.0", "# subdivisions = 10", "# dt = t/subdivisions", "# for i in range(subdivisions):", "# V, dx = integrate_drag_sphere(D=D, rhop=rhop, rho=rho, mu=mu,", "# t=dt, V=V, distance=True,", "# Method=Method)", "# x += dx", "# if distance:", "# return V, x", "# else:", "# return V", "Re_ish", "=", "rho", "*", "D", "/", "mu", "c1", "=", "g", "*", "(", "rhop", "-", "rho", ")", "/", "rhop", "c2", "=", "-", "0.75", "*", "rho", "/", "(", "D", "*", "rhop", ")", "def", "dv_dt", "(", "V", ",", "t", ")", ":", "if", "V", "==", "0", ":", "# 64/Re goes to infinity, but gets multiplied by 0 squared.", "t2", "=", "0.0", "else", ":", "# t2 = c2*V*V*Stokes(Re_ish*V)", "t2", "=", "c2", "*", "V", "*", "V", "*", "drag_sphere", "(", "Re_ish", "*", "V", ",", "Method", "=", "Method", ")", "return", "c1", "+", "t2", "# Number of intervals for the solution to be solved for; the integrator", "# doesn't care what we give it, but a large number of intervals are needed", "# For an accurate integration of the particle's distance traveled", "pts", "=", "1000", "if", "distance", "else", "2", "ts", "=", "np", ".", "linspace", "(", "0", ",", "t", ",", "pts", ")", "# Delayed import of necessaray functions", "from", "scipy", ".", "integrate", "import", "odeint", ",", "cumtrapz", "# Perform the integration", "Vs", "=", "odeint", "(", "dv_dt", ",", "[", "V", "]", ",", "ts", ")", "#", "V_end", "=", "float", "(", "Vs", "[", "-", "1", "]", ")", "if", "distance", ":", "# Calculate the distance traveled", "x", "=", "float", "(", "cumtrapz", "(", "np", ".", "ravel", "(", "Vs", ")", ",", "ts", ")", "[", "-", "1", "]", ")", "return", "V_end", ",", "x", "else", ":", "return", "V_end" ]
r'''Integrates the velocity and distance traveled by a particle moving at a speed which will converge to its terminal velocity. Performs an integration of the following expression for acceleration: .. math:: a = \frac{g(\rho_p-\rho_f)}{\rho_p} - \frac{3C_D \rho_f u^2}{4D \rho_p} Parameters ---------- D : float Diameter of the sphere, [m] rhop : float Particle density, [kg/m^3] rho : float Density of the surrounding fluid, [kg/m^3] mu : float Viscosity of the surrounding fluid [Pa*s] t : float Time to integrate the particle to, [s] V : float Initial velocity of the particle, [m/s] Method : string, optional A string of the function name to use, as in the dictionary drag_sphere_correlations distance : bool, optional Whether or not to calculate the distance traveled and return it as well Returns ------- v : float Velocity of falling sphere after time `t` [m/s] x : float, returned only if `distance` == True Distance traveled by the falling sphere in time `t`, [m] Notes ----- This can be relatively slow as drag correlations can be complex. There are analytical solutions available for the Stokes law regime (Re < 0.3). They were obtained from Wolfram Alpha. [1]_ was not used in the derivation, but also describes the derivation fully. .. math:: V(t) = \frac{\exp(-at) (V_0 a + b(\exp(at) - 1))}{a} .. math:: x(t) = \frac{\exp(-a t)\left[V_0 a(\exp(a t) - 1) + b\exp(a t)(a t-1) + b\right]}{a^2} .. math:: a = \frac{18\mu_f}{D^2\rho_p} .. math:: b = \frac{g(\rho_p-\rho_f)}{\rho_p} The analytical solution will automatically be used if the initial and terminal velocity is show the particle's behavior to be laminar. Note that this behavior requires that the terminal velocity of the particle be solved for - this adds slight (1%) overhead for the cases where particles are not laminar. Examples -------- >>> integrate_drag_sphere(D=0.001, rhop=2200., rho=1.2, mu=1.78E-5, t=0.5, ... V=30, distance=True) (9.686465044053476, 7.8294546436299175) References ---------- .. [1] Timmerman, Peter, and Jacobus P. van der Weele. "On the Rise and Fall of a Ball with Linear or Quadratic Drag." American Journal of Physics 67, no. 6 (June 1999): 538-46. https://doi.org/10.1119/1.19320.
[ "r", "Integrates", "the", "velocity", "and", "distance", "traveled", "by", "a", "particle", "moving", "at", "a", "speed", "which", "will", "converge", "to", "its", "terminal", "velocity", "." ]
57f556752e039f1d3e5a822f408c184783db2828
https://github.com/CalebBell/fluids/blob/57f556752e039f1d3e5a822f408c184783db2828/fluids/drag.py#L1260-L1414
8,301
CalebBell/fluids
fluids/fittings.py
bend_rounded_Ito
def bend_rounded_Ito(Di, angle, Re, rc=None, bend_diameters=None, roughness=0.0): '''Ito method as shown in Blevins. Curved friction factor as given in Blevins, with minor tweaks to be more accurate to the original methods. ''' if not rc: if bend_diameters is None: bend_diameters = 5.0 rc = Di*bend_diameters radius_ratio = rc/Di angle_rad = radians(angle) De2 = Re*(Di/rc)**2.0 if rc > 50.0*Di: alpha = 1.0 else: # Alpha is up to 6, as ratio gets higher, can go down to 1 alpha_45 = 1.0 + 5.13*(Di/rc)**1.47 alpha_90 = 0.95 + 4.42*(Di/rc)**1.96 if rc/Di < 9.85 else 1.0 alpha_180 = 1.0 + 5.06*(Di/rc)**4.52 alpha = interp(angle, _Ito_angles, [alpha_45, alpha_90, alpha_180]) if De2 <= 360.0: fc = friction_factor_curved(Re=Re, Di=Di, Dc=2.0*rc, roughness=roughness, Rec_method='Srinivasan', laminar_method='White', turbulent_method='Srinivasan turbulent') K = 0.0175*alpha*fc*angle*rc/Di else: K = 0.00431*alpha*angle*Re**-0.17*(rc/Di)**0.84 return K
python
def bend_rounded_Ito(Di, angle, Re, rc=None, bend_diameters=None, roughness=0.0): '''Ito method as shown in Blevins. Curved friction factor as given in Blevins, with minor tweaks to be more accurate to the original methods. ''' if not rc: if bend_diameters is None: bend_diameters = 5.0 rc = Di*bend_diameters radius_ratio = rc/Di angle_rad = radians(angle) De2 = Re*(Di/rc)**2.0 if rc > 50.0*Di: alpha = 1.0 else: # Alpha is up to 6, as ratio gets higher, can go down to 1 alpha_45 = 1.0 + 5.13*(Di/rc)**1.47 alpha_90 = 0.95 + 4.42*(Di/rc)**1.96 if rc/Di < 9.85 else 1.0 alpha_180 = 1.0 + 5.06*(Di/rc)**4.52 alpha = interp(angle, _Ito_angles, [alpha_45, alpha_90, alpha_180]) if De2 <= 360.0: fc = friction_factor_curved(Re=Re, Di=Di, Dc=2.0*rc, roughness=roughness, Rec_method='Srinivasan', laminar_method='White', turbulent_method='Srinivasan turbulent') K = 0.0175*alpha*fc*angle*rc/Di else: K = 0.00431*alpha*angle*Re**-0.17*(rc/Di)**0.84 return K
[ "def", "bend_rounded_Ito", "(", "Di", ",", "angle", ",", "Re", ",", "rc", "=", "None", ",", "bend_diameters", "=", "None", ",", "roughness", "=", "0.0", ")", ":", "if", "not", "rc", ":", "if", "bend_diameters", "is", "None", ":", "bend_diameters", "=", "5.0", "rc", "=", "Di", "*", "bend_diameters", "radius_ratio", "=", "rc", "/", "Di", "angle_rad", "=", "radians", "(", "angle", ")", "De2", "=", "Re", "*", "(", "Di", "/", "rc", ")", "**", "2.0", "if", "rc", ">", "50.0", "*", "Di", ":", "alpha", "=", "1.0", "else", ":", "# Alpha is up to 6, as ratio gets higher, can go down to 1", "alpha_45", "=", "1.0", "+", "5.13", "*", "(", "Di", "/", "rc", ")", "**", "1.47", "alpha_90", "=", "0.95", "+", "4.42", "*", "(", "Di", "/", "rc", ")", "**", "1.96", "if", "rc", "/", "Di", "<", "9.85", "else", "1.0", "alpha_180", "=", "1.0", "+", "5.06", "*", "(", "Di", "/", "rc", ")", "**", "4.52", "alpha", "=", "interp", "(", "angle", ",", "_Ito_angles", ",", "[", "alpha_45", ",", "alpha_90", ",", "alpha_180", "]", ")", "if", "De2", "<=", "360.0", ":", "fc", "=", "friction_factor_curved", "(", "Re", "=", "Re", ",", "Di", "=", "Di", ",", "Dc", "=", "2.0", "*", "rc", ",", "roughness", "=", "roughness", ",", "Rec_method", "=", "'Srinivasan'", ",", "laminar_method", "=", "'White'", ",", "turbulent_method", "=", "'Srinivasan turbulent'", ")", "K", "=", "0.0175", "*", "alpha", "*", "fc", "*", "angle", "*", "rc", "/", "Di", "else", ":", "K", "=", "0.00431", "*", "alpha", "*", "angle", "*", "Re", "**", "-", "0.17", "*", "(", "rc", "/", "Di", ")", "**", "0.84", "return", "K" ]
Ito method as shown in Blevins. Curved friction factor as given in Blevins, with minor tweaks to be more accurate to the original methods.
[ "Ito", "method", "as", "shown", "in", "Blevins", ".", "Curved", "friction", "factor", "as", "given", "in", "Blevins", "with", "minor", "tweaks", "to", "be", "more", "accurate", "to", "the", "original", "methods", "." ]
57f556752e039f1d3e5a822f408c184783db2828
https://github.com/CalebBell/fluids/blob/57f556752e039f1d3e5a822f408c184783db2828/fluids/fittings.py#L1193-L1224
8,302
CalebBell/fluids
fluids/design_climate.py
geopy_geolocator
def geopy_geolocator(): '''Lazy loader for geocoder from geopy. This currently loads the `Nominatim` geocode and returns an instance of it, taking ~2 us. ''' global geolocator if geolocator is None: try: from geopy.geocoders import Nominatim except ImportError: return None geolocator = Nominatim(user_agent=geolocator_user_agent) return geolocator return geolocator
python
def geopy_geolocator(): '''Lazy loader for geocoder from geopy. This currently loads the `Nominatim` geocode and returns an instance of it, taking ~2 us. ''' global geolocator if geolocator is None: try: from geopy.geocoders import Nominatim except ImportError: return None geolocator = Nominatim(user_agent=geolocator_user_agent) return geolocator return geolocator
[ "def", "geopy_geolocator", "(", ")", ":", "global", "geolocator", "if", "geolocator", "is", "None", ":", "try", ":", "from", "geopy", ".", "geocoders", "import", "Nominatim", "except", "ImportError", ":", "return", "None", "geolocator", "=", "Nominatim", "(", "user_agent", "=", "geolocator_user_agent", ")", "return", "geolocator", "return", "geolocator" ]
Lazy loader for geocoder from geopy. This currently loads the `Nominatim` geocode and returns an instance of it, taking ~2 us.
[ "Lazy", "loader", "for", "geocoder", "from", "geopy", ".", "This", "currently", "loads", "the", "Nominatim", "geocode", "and", "returns", "an", "instance", "of", "it", "taking", "~2", "us", "." ]
57f556752e039f1d3e5a822f408c184783db2828
https://github.com/CalebBell/fluids/blob/57f556752e039f1d3e5a822f408c184783db2828/fluids/design_climate.py#L86-L98
8,303
CalebBell/fluids
fluids/design_climate.py
heating_degree_days
def heating_degree_days(T, T_base=F2K(65), truncate=True): r'''Calculates the heating degree days for a period of time. .. math:: \text{heating degree days} = max(T - T_{base}, 0) Parameters ---------- T : float Measured temperature; sometimes an average over a length of time is used, other times the average of the lowest and highest temperature in a period are used, [K] T_base : float, optional Reference temperature for the degree day calculation, defaults to 65 °F (18.33 °C, 291.483 K), the value most used in the US, [K] truncate : bool If truncate is True, no negative values will be returned; if negative, the value is truncated to 0, [-] Returns ------- heating_degree_days : float Degree above the base temperature multiplied by the length of time of the measurement, normally days [day*K] Notes ----- Some common base temperatures are 18 °C (Canada), 15.5 °C (EU), 17 °C (Denmark, Finland), 12 °C Switzerland. The base temperature should always be presented with the results. The time unit does not have to be days; it can be any time unit, and the calculation behaves the same. Examples -------- >>> heating_degree_days(303.8) 12.31666666666672 >>> heating_degree_days(273) 0.0 >>> heating_degree_days(322, T_base=300) 22 References ---------- .. [1] "Heating Degree Day." Wikipedia, January 24, 2018. https://en.wikipedia.org/w/index.php?title=Heating_degree_day&oldid=822187764. ''' dd = T - T_base if truncate and dd < 0.0: dd = 0.0 return dd
python
def heating_degree_days(T, T_base=F2K(65), truncate=True): r'''Calculates the heating degree days for a period of time. .. math:: \text{heating degree days} = max(T - T_{base}, 0) Parameters ---------- T : float Measured temperature; sometimes an average over a length of time is used, other times the average of the lowest and highest temperature in a period are used, [K] T_base : float, optional Reference temperature for the degree day calculation, defaults to 65 °F (18.33 °C, 291.483 K), the value most used in the US, [K] truncate : bool If truncate is True, no negative values will be returned; if negative, the value is truncated to 0, [-] Returns ------- heating_degree_days : float Degree above the base temperature multiplied by the length of time of the measurement, normally days [day*K] Notes ----- Some common base temperatures are 18 °C (Canada), 15.5 °C (EU), 17 °C (Denmark, Finland), 12 °C Switzerland. The base temperature should always be presented with the results. The time unit does not have to be days; it can be any time unit, and the calculation behaves the same. Examples -------- >>> heating_degree_days(303.8) 12.31666666666672 >>> heating_degree_days(273) 0.0 >>> heating_degree_days(322, T_base=300) 22 References ---------- .. [1] "Heating Degree Day." Wikipedia, January 24, 2018. https://en.wikipedia.org/w/index.php?title=Heating_degree_day&oldid=822187764. ''' dd = T - T_base if truncate and dd < 0.0: dd = 0.0 return dd
[ "def", "heating_degree_days", "(", "T", ",", "T_base", "=", "F2K", "(", "65", ")", ",", "truncate", "=", "True", ")", ":", "dd", "=", "T", "-", "T_base", "if", "truncate", "and", "dd", "<", "0.0", ":", "dd", "=", "0.0", "return", "dd" ]
r'''Calculates the heating degree days for a period of time. .. math:: \text{heating degree days} = max(T - T_{base}, 0) Parameters ---------- T : float Measured temperature; sometimes an average over a length of time is used, other times the average of the lowest and highest temperature in a period are used, [K] T_base : float, optional Reference temperature for the degree day calculation, defaults to 65 °F (18.33 °C, 291.483 K), the value most used in the US, [K] truncate : bool If truncate is True, no negative values will be returned; if negative, the value is truncated to 0, [-] Returns ------- heating_degree_days : float Degree above the base temperature multiplied by the length of time of the measurement, normally days [day*K] Notes ----- Some common base temperatures are 18 °C (Canada), 15.5 °C (EU), 17 °C (Denmark, Finland), 12 °C Switzerland. The base temperature should always be presented with the results. The time unit does not have to be days; it can be any time unit, and the calculation behaves the same. Examples -------- >>> heating_degree_days(303.8) 12.31666666666672 >>> heating_degree_days(273) 0.0 >>> heating_degree_days(322, T_base=300) 22 References ---------- .. [1] "Heating Degree Day." Wikipedia, January 24, 2018. https://en.wikipedia.org/w/index.php?title=Heating_degree_day&oldid=822187764.
[ "r", "Calculates", "the", "heating", "degree", "days", "for", "a", "period", "of", "time", "." ]
57f556752e039f1d3e5a822f408c184783db2828
https://github.com/CalebBell/fluids/blob/57f556752e039f1d3e5a822f408c184783db2828/fluids/design_climate.py#L193-L246
8,304
CalebBell/fluids
fluids/design_climate.py
cooling_degree_days
def cooling_degree_days(T, T_base=283.15, truncate=True): r'''Calculates the cooling degree days for a period of time. .. math:: \text{cooling degree days} = max(T_{base} - T, 0) Parameters ---------- T : float Measured temperature; sometimes an average over a length of time is used, other times the average of the lowest and highest temperature in a period are used, [K] T_base : float, optional Reference temperature for the degree day calculation, defaults to 10 °C, 283.15 K, a common value, [K] truncate : bool If truncate is True, no negative values will be returned; if negative, the value is truncated to 0, [-] Returns ------- cooling_degree_days : float Degree below the base temperature multiplied by the length of time of the measurement, normally days [day*K] Notes ----- The base temperature should always be presented with the results. The time unit does not have to be days; it can be time unit, and the calculation behaves the same. Examples -------- >>> cooling_degree_days(250) 33.14999999999998 >>> cooling_degree_days(300) 0.0 >>> cooling_degree_days(250, T_base=300) 50 References ---------- .. [1] "Heating Degree Day." Wikipedia, January 24, 2018. https://en.wikipedia.org/w/index.php?title=Heating_degree_day&oldid=822187764. ''' dd = T_base - T if truncate and dd < 0.0: dd = 0.0 return dd
python
def cooling_degree_days(T, T_base=283.15, truncate=True): r'''Calculates the cooling degree days for a period of time. .. math:: \text{cooling degree days} = max(T_{base} - T, 0) Parameters ---------- T : float Measured temperature; sometimes an average over a length of time is used, other times the average of the lowest and highest temperature in a period are used, [K] T_base : float, optional Reference temperature for the degree day calculation, defaults to 10 °C, 283.15 K, a common value, [K] truncate : bool If truncate is True, no negative values will be returned; if negative, the value is truncated to 0, [-] Returns ------- cooling_degree_days : float Degree below the base temperature multiplied by the length of time of the measurement, normally days [day*K] Notes ----- The base temperature should always be presented with the results. The time unit does not have to be days; it can be time unit, and the calculation behaves the same. Examples -------- >>> cooling_degree_days(250) 33.14999999999998 >>> cooling_degree_days(300) 0.0 >>> cooling_degree_days(250, T_base=300) 50 References ---------- .. [1] "Heating Degree Day." Wikipedia, January 24, 2018. https://en.wikipedia.org/w/index.php?title=Heating_degree_day&oldid=822187764. ''' dd = T_base - T if truncate and dd < 0.0: dd = 0.0 return dd
[ "def", "cooling_degree_days", "(", "T", ",", "T_base", "=", "283.15", ",", "truncate", "=", "True", ")", ":", "dd", "=", "T_base", "-", "T", "if", "truncate", "and", "dd", "<", "0.0", ":", "dd", "=", "0.0", "return", "dd" ]
r'''Calculates the cooling degree days for a period of time. .. math:: \text{cooling degree days} = max(T_{base} - T, 0) Parameters ---------- T : float Measured temperature; sometimes an average over a length of time is used, other times the average of the lowest and highest temperature in a period are used, [K] T_base : float, optional Reference temperature for the degree day calculation, defaults to 10 °C, 283.15 K, a common value, [K] truncate : bool If truncate is True, no negative values will be returned; if negative, the value is truncated to 0, [-] Returns ------- cooling_degree_days : float Degree below the base temperature multiplied by the length of time of the measurement, normally days [day*K] Notes ----- The base temperature should always be presented with the results. The time unit does not have to be days; it can be time unit, and the calculation behaves the same. Examples -------- >>> cooling_degree_days(250) 33.14999999999998 >>> cooling_degree_days(300) 0.0 >>> cooling_degree_days(250, T_base=300) 50 References ---------- .. [1] "Heating Degree Day." Wikipedia, January 24, 2018. https://en.wikipedia.org/w/index.php?title=Heating_degree_day&oldid=822187764.
[ "r", "Calculates", "the", "cooling", "degree", "days", "for", "a", "period", "of", "time", "." ]
57f556752e039f1d3e5a822f408c184783db2828
https://github.com/CalebBell/fluids/blob/57f556752e039f1d3e5a822f408c184783db2828/fluids/design_climate.py#L249-L300
8,305
CalebBell/fluids
fluids/design_climate.py
get_station_year_text
def get_station_year_text(WMO, WBAN, year): '''Basic method to download data from the GSOD database, given a station identifier and year. Parameters ---------- WMO : int or None World Meteorological Organization (WMO) identifiers, [-] WBAN : int or None Weather Bureau Army Navy (WBAN) weather station identifier, [-] year : int Year data should be retrieved from, [year] Returns ------- data : str Downloaded data file ''' if WMO is None: WMO = 999999 if WBAN is None: WBAN = 99999 station = str(int(WMO)) + '-' + str(int(WBAN)) gsod_year_dir = os.path.join(data_dir, 'gsod', str(year)) path = os.path.join(gsod_year_dir, station + '.op') if os.path.exists(path): data = open(path).read() if data and data != 'Exception': return data else: raise Exception(data) toget = ('ftp://ftp.ncdc.noaa.gov/pub/data/gsod/' + str(year) + '/' + station + '-' + str(year) +'.op.gz') try: data = urlopen(toget, timeout=5) except Exception as e: if not os.path.exists(gsod_year_dir): os.makedirs(gsod_year_dir) open(path, 'w').write('Exception') raise Exception('Could not obtain desired data; check ' 'if the year has data published for the ' 'specified station and the station was specified ' 'in the correct form. The full error is %s' %(e)) data = data.read() data_thing = StringIO(data) f = gzip.GzipFile(fileobj=data_thing, mode="r") year_station_data = f.read() try: year_station_data = year_station_data.decode('utf-8') except: pass # Cache the data for future use if not os.path.exists(gsod_year_dir): os.makedirs(gsod_year_dir) open(path, 'w').write(year_station_data) return year_station_data
python
def get_station_year_text(WMO, WBAN, year): '''Basic method to download data from the GSOD database, given a station identifier and year. Parameters ---------- WMO : int or None World Meteorological Organization (WMO) identifiers, [-] WBAN : int or None Weather Bureau Army Navy (WBAN) weather station identifier, [-] year : int Year data should be retrieved from, [year] Returns ------- data : str Downloaded data file ''' if WMO is None: WMO = 999999 if WBAN is None: WBAN = 99999 station = str(int(WMO)) + '-' + str(int(WBAN)) gsod_year_dir = os.path.join(data_dir, 'gsod', str(year)) path = os.path.join(gsod_year_dir, station + '.op') if os.path.exists(path): data = open(path).read() if data and data != 'Exception': return data else: raise Exception(data) toget = ('ftp://ftp.ncdc.noaa.gov/pub/data/gsod/' + str(year) + '/' + station + '-' + str(year) +'.op.gz') try: data = urlopen(toget, timeout=5) except Exception as e: if not os.path.exists(gsod_year_dir): os.makedirs(gsod_year_dir) open(path, 'w').write('Exception') raise Exception('Could not obtain desired data; check ' 'if the year has data published for the ' 'specified station and the station was specified ' 'in the correct form. The full error is %s' %(e)) data = data.read() data_thing = StringIO(data) f = gzip.GzipFile(fileobj=data_thing, mode="r") year_station_data = f.read() try: year_station_data = year_station_data.decode('utf-8') except: pass # Cache the data for future use if not os.path.exists(gsod_year_dir): os.makedirs(gsod_year_dir) open(path, 'w').write(year_station_data) return year_station_data
[ "def", "get_station_year_text", "(", "WMO", ",", "WBAN", ",", "year", ")", ":", "if", "WMO", "is", "None", ":", "WMO", "=", "999999", "if", "WBAN", "is", "None", ":", "WBAN", "=", "99999", "station", "=", "str", "(", "int", "(", "WMO", ")", ")", "+", "'-'", "+", "str", "(", "int", "(", "WBAN", ")", ")", "gsod_year_dir", "=", "os", ".", "path", ".", "join", "(", "data_dir", ",", "'gsod'", ",", "str", "(", "year", ")", ")", "path", "=", "os", ".", "path", ".", "join", "(", "gsod_year_dir", ",", "station", "+", "'.op'", ")", "if", "os", ".", "path", ".", "exists", "(", "path", ")", ":", "data", "=", "open", "(", "path", ")", ".", "read", "(", ")", "if", "data", "and", "data", "!=", "'Exception'", ":", "return", "data", "else", ":", "raise", "Exception", "(", "data", ")", "toget", "=", "(", "'ftp://ftp.ncdc.noaa.gov/pub/data/gsod/'", "+", "str", "(", "year", ")", "+", "'/'", "+", "station", "+", "'-'", "+", "str", "(", "year", ")", "+", "'.op.gz'", ")", "try", ":", "data", "=", "urlopen", "(", "toget", ",", "timeout", "=", "5", ")", "except", "Exception", "as", "e", ":", "if", "not", "os", ".", "path", ".", "exists", "(", "gsod_year_dir", ")", ":", "os", ".", "makedirs", "(", "gsod_year_dir", ")", "open", "(", "path", ",", "'w'", ")", ".", "write", "(", "'Exception'", ")", "raise", "Exception", "(", "'Could not obtain desired data; check '", "'if the year has data published for the '", "'specified station and the station was specified '", "'in the correct form. The full error is %s'", "%", "(", "e", ")", ")", "data", "=", "data", ".", "read", "(", ")", "data_thing", "=", "StringIO", "(", "data", ")", "f", "=", "gzip", ".", "GzipFile", "(", "fileobj", "=", "data_thing", ",", "mode", "=", "\"r\"", ")", "year_station_data", "=", "f", ".", "read", "(", ")", "try", ":", "year_station_data", "=", "year_station_data", ".", "decode", "(", "'utf-8'", ")", "except", ":", "pass", "# Cache the data for future use", "if", "not", "os", ".", "path", ".", "exists", "(", "gsod_year_dir", ")", ":", "os", ".", "makedirs", "(", "gsod_year_dir", ")", "open", "(", "path", ",", "'w'", ")", ".", "write", "(", "year_station_data", ")", "return", "year_station_data" ]
Basic method to download data from the GSOD database, given a station identifier and year. Parameters ---------- WMO : int or None World Meteorological Organization (WMO) identifiers, [-] WBAN : int or None Weather Bureau Army Navy (WBAN) weather station identifier, [-] year : int Year data should be retrieved from, [year] Returns ------- data : str Downloaded data file
[ "Basic", "method", "to", "download", "data", "from", "the", "GSOD", "database", "given", "a", "station", "identifier", "and", "year", "." ]
57f556752e039f1d3e5a822f408c184783db2828
https://github.com/CalebBell/fluids/blob/57f556752e039f1d3e5a822f408c184783db2828/fluids/design_climate.py#L699-L760
8,306
CalebBell/fluids
fluids/packed_tower.py
_Stichlmair_flood_f
def _Stichlmair_flood_f(inputs, Vl, rhog, rhol, mug, voidage, specific_area, C1, C2, C3, H): '''Internal function which calculates the errors of the two Stichlmair objective functions, and their jacobian. ''' Vg, dP_irr = float(inputs[0]), float(inputs[1]) dp = 6.0*(1.0 - voidage)/specific_area Re = Vg*rhog*dp/mug f0 = C1/Re + C2/Re**0.5 + C3 dP_dry = 0.75*f0*(1.0 - voidage)/voidage**4.65*rhog*H/dp*Vg*Vg c = (-C1/Re - 0.5*C2*Re**-0.5)/f0 Frl = Vl*Vl*specific_area/(g*voidage**4.65) h0 = 0.555*Frl**(1/3.) hT = h0*(1.0 + 20.0*(dP_irr/H/rhol/g)**2) err1 = dP_dry/H*((1.0 - voidage + hT)/(1.0 - voidage))**((2.0 + c)/3.)*(voidage/(voidage-hT))**4.65 - dP_irr/H term = (dP_irr/(rhol*g*H))**2 err2 = (1./term - 40.0*((2.0+c)/3.)*h0/(1.0 - voidage + h0*(1.0 + 20.0*term)) - 186.0*h0/(voidage - h0*(1.0 + 20.0*term))) return err1, err2
python
def _Stichlmair_flood_f(inputs, Vl, rhog, rhol, mug, voidage, specific_area, C1, C2, C3, H): '''Internal function which calculates the errors of the two Stichlmair objective functions, and their jacobian. ''' Vg, dP_irr = float(inputs[0]), float(inputs[1]) dp = 6.0*(1.0 - voidage)/specific_area Re = Vg*rhog*dp/mug f0 = C1/Re + C2/Re**0.5 + C3 dP_dry = 0.75*f0*(1.0 - voidage)/voidage**4.65*rhog*H/dp*Vg*Vg c = (-C1/Re - 0.5*C2*Re**-0.5)/f0 Frl = Vl*Vl*specific_area/(g*voidage**4.65) h0 = 0.555*Frl**(1/3.) hT = h0*(1.0 + 20.0*(dP_irr/H/rhol/g)**2) err1 = dP_dry/H*((1.0 - voidage + hT)/(1.0 - voidage))**((2.0 + c)/3.)*(voidage/(voidage-hT))**4.65 - dP_irr/H term = (dP_irr/(rhol*g*H))**2 err2 = (1./term - 40.0*((2.0+c)/3.)*h0/(1.0 - voidage + h0*(1.0 + 20.0*term)) - 186.0*h0/(voidage - h0*(1.0 + 20.0*term))) return err1, err2
[ "def", "_Stichlmair_flood_f", "(", "inputs", ",", "Vl", ",", "rhog", ",", "rhol", ",", "mug", ",", "voidage", ",", "specific_area", ",", "C1", ",", "C2", ",", "C3", ",", "H", ")", ":", "Vg", ",", "dP_irr", "=", "float", "(", "inputs", "[", "0", "]", ")", ",", "float", "(", "inputs", "[", "1", "]", ")", "dp", "=", "6.0", "*", "(", "1.0", "-", "voidage", ")", "/", "specific_area", "Re", "=", "Vg", "*", "rhog", "*", "dp", "/", "mug", "f0", "=", "C1", "/", "Re", "+", "C2", "/", "Re", "**", "0.5", "+", "C3", "dP_dry", "=", "0.75", "*", "f0", "*", "(", "1.0", "-", "voidage", ")", "/", "voidage", "**", "4.65", "*", "rhog", "*", "H", "/", "dp", "*", "Vg", "*", "Vg", "c", "=", "(", "-", "C1", "/", "Re", "-", "0.5", "*", "C2", "*", "Re", "**", "-", "0.5", ")", "/", "f0", "Frl", "=", "Vl", "*", "Vl", "*", "specific_area", "/", "(", "g", "*", "voidage", "**", "4.65", ")", "h0", "=", "0.555", "*", "Frl", "**", "(", "1", "/", "3.", ")", "hT", "=", "h0", "*", "(", "1.0", "+", "20.0", "*", "(", "dP_irr", "/", "H", "/", "rhol", "/", "g", ")", "**", "2", ")", "err1", "=", "dP_dry", "/", "H", "*", "(", "(", "1.0", "-", "voidage", "+", "hT", ")", "/", "(", "1.0", "-", "voidage", ")", ")", "**", "(", "(", "2.0", "+", "c", ")", "/", "3.", ")", "*", "(", "voidage", "/", "(", "voidage", "-", "hT", ")", ")", "**", "4.65", "-", "dP_irr", "/", "H", "term", "=", "(", "dP_irr", "/", "(", "rhol", "*", "g", "*", "H", ")", ")", "**", "2", "err2", "=", "(", "1.", "/", "term", "-", "40.0", "*", "(", "(", "2.0", "+", "c", ")", "/", "3.", ")", "*", "h0", "/", "(", "1.0", "-", "voidage", "+", "h0", "*", "(", "1.0", "+", "20.0", "*", "term", ")", ")", "-", "186.0", "*", "h0", "/", "(", "voidage", "-", "h0", "*", "(", "1.0", "+", "20.0", "*", "term", ")", ")", ")", "return", "err1", ",", "err2" ]
Internal function which calculates the errors of the two Stichlmair objective functions, and their jacobian.
[ "Internal", "function", "which", "calculates", "the", "errors", "of", "the", "two", "Stichlmair", "objective", "functions", "and", "their", "jacobian", "." ]
57f556752e039f1d3e5a822f408c184783db2828
https://github.com/CalebBell/fluids/blob/57f556752e039f1d3e5a822f408c184783db2828/fluids/packed_tower.py#L568-L586
8,307
CalebBell/fluids
fluids/packed_tower.py
Robbins
def Robbins(L, G, rhol, rhog, mul, H=1.0, Fpd=24.0): r'''Calculates pressure drop across a packed column, using the Robbins equation. Pressure drop is given by: .. math:: \Delta P = C_3 G_f^2 10^{C_4L_f}+0.4[L_f/20000]^{0.1}[C_3G_f^210^{C_4L_f}]^4 .. math:: G_f=G[0.075/\rho_g]^{0.5}[F_{pd}/20]^{0.5}=986F_s[F_{pd}/20]^{0.5} .. math:: L_f=L[62.4/\rho_L][F_{pd}/20]^{0.5}\mu^{0.1} .. math:: F_s=V_s\rho_g^{0.5} Parameters ---------- L : float Specific liquid mass flow rate [kg/s/m^2] G : float Specific gas mass flow rate [kg/s/m^2] rhol : float Density of liquid [kg/m^3] rhog : float Density of gas [kg/m^3] mul : float Viscosity of liquid [Pa*s] H : float Height of packing [m] Fpd : float Robbins packing factor (tabulated for packings) [1/ft] Returns ------- dP : float Pressure drop across packing [Pa] Notes ----- Perry's displayed equation has a typo in a superscript. This model is based on the example in Perry's. Examples -------- >>> Robbins(L=12.2, G=2.03, rhol=1000., rhog=1.1853, mul=0.001, H=2.0, Fpd=24.0) 619.6624593438102 References ---------- .. [1] Robbins [Chem. Eng. Progr., p. 87 (May 1991) Improved Pressure Drop Prediction with a New Correlation. ''' # Convert SI units to imperial for use in correlation L = L*737.33812 # kg/s/m^2 to lb/hr/ft^2 G = G*737.33812 # kg/s/m^2 to lb/hr/ft^2 rhol = rhol*0.062427961 # kg/m^3 to lb/ft^3 rhog = rhog*0.062427961 # kg/m^3 to lb/ft^3 mul = mul*1000.0 # Pa*s to cP C3 = 7.4E-8 C4 = 2.7E-5 Fpd_root_term = (.05*Fpd)**0.5 Lf = L*(62.4/rhol)*Fpd_root_term*mul**0.1 Gf = G*(0.075/rhog)**0.5*Fpd_root_term Gf2 = Gf*Gf C4LF_10_GF2_C3 = C3*Gf2*10.0**(C4*Lf) C4LF_10_GF2_C3_2 = C4LF_10_GF2_C3*C4LF_10_GF2_C3 dP = C4LF_10_GF2_C3 + 0.4*(5e-5*Lf)**0.1*(C4LF_10_GF2_C3_2*C4LF_10_GF2_C3_2) return dP*817.22083*H
python
def Robbins(L, G, rhol, rhog, mul, H=1.0, Fpd=24.0): r'''Calculates pressure drop across a packed column, using the Robbins equation. Pressure drop is given by: .. math:: \Delta P = C_3 G_f^2 10^{C_4L_f}+0.4[L_f/20000]^{0.1}[C_3G_f^210^{C_4L_f}]^4 .. math:: G_f=G[0.075/\rho_g]^{0.5}[F_{pd}/20]^{0.5}=986F_s[F_{pd}/20]^{0.5} .. math:: L_f=L[62.4/\rho_L][F_{pd}/20]^{0.5}\mu^{0.1} .. math:: F_s=V_s\rho_g^{0.5} Parameters ---------- L : float Specific liquid mass flow rate [kg/s/m^2] G : float Specific gas mass flow rate [kg/s/m^2] rhol : float Density of liquid [kg/m^3] rhog : float Density of gas [kg/m^3] mul : float Viscosity of liquid [Pa*s] H : float Height of packing [m] Fpd : float Robbins packing factor (tabulated for packings) [1/ft] Returns ------- dP : float Pressure drop across packing [Pa] Notes ----- Perry's displayed equation has a typo in a superscript. This model is based on the example in Perry's. Examples -------- >>> Robbins(L=12.2, G=2.03, rhol=1000., rhog=1.1853, mul=0.001, H=2.0, Fpd=24.0) 619.6624593438102 References ---------- .. [1] Robbins [Chem. Eng. Progr., p. 87 (May 1991) Improved Pressure Drop Prediction with a New Correlation. ''' # Convert SI units to imperial for use in correlation L = L*737.33812 # kg/s/m^2 to lb/hr/ft^2 G = G*737.33812 # kg/s/m^2 to lb/hr/ft^2 rhol = rhol*0.062427961 # kg/m^3 to lb/ft^3 rhog = rhog*0.062427961 # kg/m^3 to lb/ft^3 mul = mul*1000.0 # Pa*s to cP C3 = 7.4E-8 C4 = 2.7E-5 Fpd_root_term = (.05*Fpd)**0.5 Lf = L*(62.4/rhol)*Fpd_root_term*mul**0.1 Gf = G*(0.075/rhog)**0.5*Fpd_root_term Gf2 = Gf*Gf C4LF_10_GF2_C3 = C3*Gf2*10.0**(C4*Lf) C4LF_10_GF2_C3_2 = C4LF_10_GF2_C3*C4LF_10_GF2_C3 dP = C4LF_10_GF2_C3 + 0.4*(5e-5*Lf)**0.1*(C4LF_10_GF2_C3_2*C4LF_10_GF2_C3_2) return dP*817.22083*H
[ "def", "Robbins", "(", "L", ",", "G", ",", "rhol", ",", "rhog", ",", "mul", ",", "H", "=", "1.0", ",", "Fpd", "=", "24.0", ")", ":", "# Convert SI units to imperial for use in correlation", "L", "=", "L", "*", "737.33812", "# kg/s/m^2 to lb/hr/ft^2", "G", "=", "G", "*", "737.33812", "# kg/s/m^2 to lb/hr/ft^2", "rhol", "=", "rhol", "*", "0.062427961", "# kg/m^3 to lb/ft^3", "rhog", "=", "rhog", "*", "0.062427961", "# kg/m^3 to lb/ft^3", "mul", "=", "mul", "*", "1000.0", "# Pa*s to cP", "C3", "=", "7.4E-8", "C4", "=", "2.7E-5", "Fpd_root_term", "=", "(", ".05", "*", "Fpd", ")", "**", "0.5", "Lf", "=", "L", "*", "(", "62.4", "/", "rhol", ")", "*", "Fpd_root_term", "*", "mul", "**", "0.1", "Gf", "=", "G", "*", "(", "0.075", "/", "rhog", ")", "**", "0.5", "*", "Fpd_root_term", "Gf2", "=", "Gf", "*", "Gf", "C4LF_10_GF2_C3", "=", "C3", "*", "Gf2", "*", "10.0", "**", "(", "C4", "*", "Lf", ")", "C4LF_10_GF2_C3_2", "=", "C4LF_10_GF2_C3", "*", "C4LF_10_GF2_C3", "dP", "=", "C4LF_10_GF2_C3", "+", "0.4", "*", "(", "5e-5", "*", "Lf", ")", "**", "0.1", "*", "(", "C4LF_10_GF2_C3_2", "*", "C4LF_10_GF2_C3_2", ")", "return", "dP", "*", "817.22083", "*", "H" ]
r'''Calculates pressure drop across a packed column, using the Robbins equation. Pressure drop is given by: .. math:: \Delta P = C_3 G_f^2 10^{C_4L_f}+0.4[L_f/20000]^{0.1}[C_3G_f^210^{C_4L_f}]^4 .. math:: G_f=G[0.075/\rho_g]^{0.5}[F_{pd}/20]^{0.5}=986F_s[F_{pd}/20]^{0.5} .. math:: L_f=L[62.4/\rho_L][F_{pd}/20]^{0.5}\mu^{0.1} .. math:: F_s=V_s\rho_g^{0.5} Parameters ---------- L : float Specific liquid mass flow rate [kg/s/m^2] G : float Specific gas mass flow rate [kg/s/m^2] rhol : float Density of liquid [kg/m^3] rhog : float Density of gas [kg/m^3] mul : float Viscosity of liquid [Pa*s] H : float Height of packing [m] Fpd : float Robbins packing factor (tabulated for packings) [1/ft] Returns ------- dP : float Pressure drop across packing [Pa] Notes ----- Perry's displayed equation has a typo in a superscript. This model is based on the example in Perry's. Examples -------- >>> Robbins(L=12.2, G=2.03, rhol=1000., rhog=1.1853, mul=0.001, H=2.0, Fpd=24.0) 619.6624593438102 References ---------- .. [1] Robbins [Chem. Eng. Progr., p. 87 (May 1991) Improved Pressure Drop Prediction with a New Correlation.
[ "r", "Calculates", "pressure", "drop", "across", "a", "packed", "column", "using", "the", "Robbins", "equation", "." ]
57f556752e039f1d3e5a822f408c184783db2828
https://github.com/CalebBell/fluids/blob/57f556752e039f1d3e5a822f408c184783db2828/fluids/packed_tower.py#L741-L812
8,308
CalebBell/fluids
fluids/packed_bed.py
dP_packed_bed
def dP_packed_bed(dp, voidage, vs, rho, mu, L=1, Dt=None, sphericity=None, Method=None, AvailableMethods=False): r'''This function handles choosing which pressure drop in a packed bed correlation is used. Automatically select which correlation to use if none is provided. Returns None if insufficient information is provided. Preferred correlations are 'Erdim, Akgiray & Demir' when tube diameter is not provided, and 'Harrison, Brunner & Hecker' when tube diameter is provided. If you are using a particles in a narrow tube between 2 and 3 particle diameters, expect higher than normal voidages (0.4-0.5) and used the method 'Guo, Sun, Zhang, Ding & Liu'. Examples -------- >>> dP_packed_bed(dp=8E-4, voidage=0.4, vs=1E-3, rho=1E3, mu=1E-3) 1438.2826958844414 >>> dP_packed_bed(dp=8E-4, voidage=0.4, vs=1E-3, rho=1E3, mu=1E-3, Dt=0.01) 1255.1625662548427 >>> dP_packed_bed(dp=0.05, voidage=0.492, vs=0.1, rho=1E3, mu=1E-3, Dt=0.015, Method='Guo, Sun, Zhang, Ding & Liu') 18782.499710673364 Parameters ---------- dp : float Particle diameter of spheres [m] voidage : float Void fraction of bed packing [-] vs : float Superficial velocity of the fluid (volumetric flow rate/cross-sectional area) [m/s] rho : float Density of the fluid [kg/m^3] mu : float Viscosity of the fluid, [Pa*s] L : float, optional Length the fluid flows in the packed bed [m] Dt : float, optional Diameter of the tube, [m] sphericity : float, optional Sphericity of the particles [-] Returns ------- dP : float Pressure drop across the bed [Pa] methods : list, only returned if AvailableMethods == True List of methods which can be used to calculate `dP` with the given inputs Other Parameters ---------------- Method : string, optional A string of the function name to use, as in the dictionary packed_beds_correlations AvailableMethods : bool, optional If True, function will consider which methods which can be used to calculate `dP` with the given inputs and return them as a list ''' def list_methods(): methods = [] if all((dp, voidage, vs, rho, mu, L)): for key, values in packed_beds_correlations.items(): if Dt or not values[1]: methods.append(key) if 'Harrison, Brunner & Hecker' in methods: methods.remove('Harrison, Brunner & Hecker') methods.insert(0, 'Harrison, Brunner & Hecker') elif 'Erdim, Akgiray & Demir' in methods: methods.remove('Erdim, Akgiray & Demir') methods.insert(0, 'Erdim, Akgiray & Demir') return methods if AvailableMethods: return list_methods() if not Method: Method = list_methods()[0] if dp and sphericity: dp = dp*sphericity if Method in packed_beds_correlations: if packed_beds_correlations[Method][1]: return packed_beds_correlations[Method][0](dp=dp, voidage=voidage, vs=vs, rho=rho, mu=mu, L=L, Dt=Dt) else: return packed_beds_correlations[Method][0](dp=dp, voidage=voidage, vs=vs, rho=rho, mu=mu, L=L) else: raise Exception('Failure in in function')
python
def dP_packed_bed(dp, voidage, vs, rho, mu, L=1, Dt=None, sphericity=None, Method=None, AvailableMethods=False): r'''This function handles choosing which pressure drop in a packed bed correlation is used. Automatically select which correlation to use if none is provided. Returns None if insufficient information is provided. Preferred correlations are 'Erdim, Akgiray & Demir' when tube diameter is not provided, and 'Harrison, Brunner & Hecker' when tube diameter is provided. If you are using a particles in a narrow tube between 2 and 3 particle diameters, expect higher than normal voidages (0.4-0.5) and used the method 'Guo, Sun, Zhang, Ding & Liu'. Examples -------- >>> dP_packed_bed(dp=8E-4, voidage=0.4, vs=1E-3, rho=1E3, mu=1E-3) 1438.2826958844414 >>> dP_packed_bed(dp=8E-4, voidage=0.4, vs=1E-3, rho=1E3, mu=1E-3, Dt=0.01) 1255.1625662548427 >>> dP_packed_bed(dp=0.05, voidage=0.492, vs=0.1, rho=1E3, mu=1E-3, Dt=0.015, Method='Guo, Sun, Zhang, Ding & Liu') 18782.499710673364 Parameters ---------- dp : float Particle diameter of spheres [m] voidage : float Void fraction of bed packing [-] vs : float Superficial velocity of the fluid (volumetric flow rate/cross-sectional area) [m/s] rho : float Density of the fluid [kg/m^3] mu : float Viscosity of the fluid, [Pa*s] L : float, optional Length the fluid flows in the packed bed [m] Dt : float, optional Diameter of the tube, [m] sphericity : float, optional Sphericity of the particles [-] Returns ------- dP : float Pressure drop across the bed [Pa] methods : list, only returned if AvailableMethods == True List of methods which can be used to calculate `dP` with the given inputs Other Parameters ---------------- Method : string, optional A string of the function name to use, as in the dictionary packed_beds_correlations AvailableMethods : bool, optional If True, function will consider which methods which can be used to calculate `dP` with the given inputs and return them as a list ''' def list_methods(): methods = [] if all((dp, voidage, vs, rho, mu, L)): for key, values in packed_beds_correlations.items(): if Dt or not values[1]: methods.append(key) if 'Harrison, Brunner & Hecker' in methods: methods.remove('Harrison, Brunner & Hecker') methods.insert(0, 'Harrison, Brunner & Hecker') elif 'Erdim, Akgiray & Demir' in methods: methods.remove('Erdim, Akgiray & Demir') methods.insert(0, 'Erdim, Akgiray & Demir') return methods if AvailableMethods: return list_methods() if not Method: Method = list_methods()[0] if dp and sphericity: dp = dp*sphericity if Method in packed_beds_correlations: if packed_beds_correlations[Method][1]: return packed_beds_correlations[Method][0](dp=dp, voidage=voidage, vs=vs, rho=rho, mu=mu, L=L, Dt=Dt) else: return packed_beds_correlations[Method][0](dp=dp, voidage=voidage, vs=vs, rho=rho, mu=mu, L=L) else: raise Exception('Failure in in function')
[ "def", "dP_packed_bed", "(", "dp", ",", "voidage", ",", "vs", ",", "rho", ",", "mu", ",", "L", "=", "1", ",", "Dt", "=", "None", ",", "sphericity", "=", "None", ",", "Method", "=", "None", ",", "AvailableMethods", "=", "False", ")", ":", "def", "list_methods", "(", ")", ":", "methods", "=", "[", "]", "if", "all", "(", "(", "dp", ",", "voidage", ",", "vs", ",", "rho", ",", "mu", ",", "L", ")", ")", ":", "for", "key", ",", "values", "in", "packed_beds_correlations", ".", "items", "(", ")", ":", "if", "Dt", "or", "not", "values", "[", "1", "]", ":", "methods", ".", "append", "(", "key", ")", "if", "'Harrison, Brunner & Hecker'", "in", "methods", ":", "methods", ".", "remove", "(", "'Harrison, Brunner & Hecker'", ")", "methods", ".", "insert", "(", "0", ",", "'Harrison, Brunner & Hecker'", ")", "elif", "'Erdim, Akgiray & Demir'", "in", "methods", ":", "methods", ".", "remove", "(", "'Erdim, Akgiray & Demir'", ")", "methods", ".", "insert", "(", "0", ",", "'Erdim, Akgiray & Demir'", ")", "return", "methods", "if", "AvailableMethods", ":", "return", "list_methods", "(", ")", "if", "not", "Method", ":", "Method", "=", "list_methods", "(", ")", "[", "0", "]", "if", "dp", "and", "sphericity", ":", "dp", "=", "dp", "*", "sphericity", "if", "Method", "in", "packed_beds_correlations", ":", "if", "packed_beds_correlations", "[", "Method", "]", "[", "1", "]", ":", "return", "packed_beds_correlations", "[", "Method", "]", "[", "0", "]", "(", "dp", "=", "dp", ",", "voidage", "=", "voidage", ",", "vs", "=", "vs", ",", "rho", "=", "rho", ",", "mu", "=", "mu", ",", "L", "=", "L", ",", "Dt", "=", "Dt", ")", "else", ":", "return", "packed_beds_correlations", "[", "Method", "]", "[", "0", "]", "(", "dp", "=", "dp", ",", "voidage", "=", "voidage", ",", "vs", "=", "vs", ",", "rho", "=", "rho", ",", "mu", "=", "mu", ",", "L", "=", "L", ")", "else", ":", "raise", "Exception", "(", "'Failure in in function'", ")" ]
r'''This function handles choosing which pressure drop in a packed bed correlation is used. Automatically select which correlation to use if none is provided. Returns None if insufficient information is provided. Preferred correlations are 'Erdim, Akgiray & Demir' when tube diameter is not provided, and 'Harrison, Brunner & Hecker' when tube diameter is provided. If you are using a particles in a narrow tube between 2 and 3 particle diameters, expect higher than normal voidages (0.4-0.5) and used the method 'Guo, Sun, Zhang, Ding & Liu'. Examples -------- >>> dP_packed_bed(dp=8E-4, voidage=0.4, vs=1E-3, rho=1E3, mu=1E-3) 1438.2826958844414 >>> dP_packed_bed(dp=8E-4, voidage=0.4, vs=1E-3, rho=1E3, mu=1E-3, Dt=0.01) 1255.1625662548427 >>> dP_packed_bed(dp=0.05, voidage=0.492, vs=0.1, rho=1E3, mu=1E-3, Dt=0.015, Method='Guo, Sun, Zhang, Ding & Liu') 18782.499710673364 Parameters ---------- dp : float Particle diameter of spheres [m] voidage : float Void fraction of bed packing [-] vs : float Superficial velocity of the fluid (volumetric flow rate/cross-sectional area) [m/s] rho : float Density of the fluid [kg/m^3] mu : float Viscosity of the fluid, [Pa*s] L : float, optional Length the fluid flows in the packed bed [m] Dt : float, optional Diameter of the tube, [m] sphericity : float, optional Sphericity of the particles [-] Returns ------- dP : float Pressure drop across the bed [Pa] methods : list, only returned if AvailableMethods == True List of methods which can be used to calculate `dP` with the given inputs Other Parameters ---------------- Method : string, optional A string of the function name to use, as in the dictionary packed_beds_correlations AvailableMethods : bool, optional If True, function will consider which methods which can be used to calculate `dP` with the given inputs and return them as a list
[ "r", "This", "function", "handles", "choosing", "which", "pressure", "drop", "in", "a", "packed", "bed", "correlation", "is", "used", ".", "Automatically", "select", "which", "correlation", "to", "use", "if", "none", "is", "provided", ".", "Returns", "None", "if", "insufficient", "information", "is", "provided", "." ]
57f556752e039f1d3e5a822f408c184783db2828
https://github.com/CalebBell/fluids/blob/57f556752e039f1d3e5a822f408c184783db2828/fluids/packed_bed.py#L994-L1079
8,309
CalebBell/fluids
fluids/two_phase.py
Friedel
def Friedel(m, x, rhol, rhog, mul, mug, sigma, D, roughness=0, L=1): r'''Calculates two-phase pressure drop with the Friedel correlation. .. math:: \Delta P_{friction} = \Delta P_{lo} \phi_{lo}^2 .. math:: \phi_{lo}^2 = E + \frac{3.24FH}{Fr^{0.0454} We^{0.035}} .. math:: H = \left(\frac{\rho_l}{\rho_g}\right)^{0.91}\left(\frac{\mu_g}{\mu_l} \right)^{0.19}\left(1 - \frac{\mu_g}{\mu_l}\right)^{0.7} .. math:: F = x^{0.78}(1 - x)^{0.224} .. math:: E = (1-x)^2 + x^2\left(\frac{\rho_l f_{d,go}}{\rho_g f_{d,lo}}\right) .. math:: Fr = \frac{G_{tp}^2}{gD\rho_H^2} .. math:: We = \frac{G_{tp}^2 D}{\sigma \rho_H} .. math:: \rho_H = \left(\frac{x}{\rho_g} + \frac{1-x}{\rho_l}\right)^{-1} Parameters ---------- m : float Mass flow rate of fluid, [kg/s] x : float Quality of fluid, [-] rhol : float Liquid density, [kg/m^3] rhog : float Gas density, [kg/m^3] mul : float Viscosity of liquid, [Pa*s] mug : float Viscosity of gas, [Pa*s] sigma : float Surface tension, [N/m] D : float Diameter of pipe, [m] roughness : float, optional Roughness of pipe for use in calculating friction factor, [m] L : float, optional Length of pipe, [m] Returns ------- dP : float Pressure drop of the two-phase flow, [Pa] Notes ----- Applicable to vertical upflow and horizontal flow. Known to work poorly when mul/mug > 1000. Gives mean errors on the order of 40%. Tested on data with diameters as small as 4 mm. The power of 0.0454 is given as 0.045 in [2]_, [3]_, [4]_, and [5]_; [6]_ and [2]_ give 0.0454 and [2]_ also gives a similar correlation said to be presented in [1]_, so it is believed this 0.0454 was the original power. [6]_ also gives an expression for friction factor claimed to be presented in [1]_; it is not used here. Examples -------- Example 4 in [6]_: >>> Friedel(m=0.6, x=0.1, rhol=915., rhog=2.67, mul=180E-6, mug=14E-6, ... sigma=0.0487, D=0.05, roughness=0, L=1) 738.6500525002245 References ---------- .. [1] Friedel, L. "Improved Friction Pressure Drop Correlations for Horizontal and Vertical Two-Phase Pipe Flow." , in: Proceedings, European Two Phase Flow Group Meeting, Ispra, Italy, 1979: 485-481. .. [2] Whalley, P. B. Boiling, Condensation, and Gas-Liquid Flow. Oxford: Oxford University Press, 1987. .. [3] Triplett, K. A., S. M. Ghiaasiaan, S. I. Abdel-Khalik, A. LeMouel, and B. N. McCord. "Gas-liquid Two-Phase Flow in Microchannels: Part II: Void Fraction and Pressure Drop.” International Journal of Multiphase Flow 25, no. 3 (April 1999): 395-410. doi:10.1016/S0301-9322(98)00055-X. .. [4] Mekisso, Henock Mateos. "Comparison of Frictional Pressure Drop Correlations for Isothermal Two-Phase Horizontal Flow." Thesis, Oklahoma State University, 2013. https://shareok.org/handle/11244/11109. .. [5] Thome, John R. "Engineering Data Book III." Wolverine Tube Inc (2004). http://www.wlv.com/heat-transfer-databook/ .. [6] Ghiaasiaan, S. Mostafa. Two-Phase Flow, Boiling, and Condensation: In Conventional and Miniature Systems. Cambridge University Press, 2007. ''' # Liquid-only properties, for calculation of E, dP_lo v_lo = m/rhol/(pi/4*D**2) Re_lo = Reynolds(V=v_lo, rho=rhol, mu=mul, D=D) fd_lo = friction_factor(Re=Re_lo, eD=roughness/D) dP_lo = fd_lo*L/D*(0.5*rhol*v_lo**2) # Gas-only properties, for calculation of E v_go = m/rhog/(pi/4*D**2) Re_go = Reynolds(V=v_go, rho=rhog, mu=mug, D=D) fd_go = friction_factor(Re=Re_go, eD=roughness/D) F = x**0.78*(1-x)**0.224 H = (rhol/rhog)**0.91*(mug/mul)**0.19*(1 - mug/mul)**0.7 E = (1-x)**2 + x**2*(rhol*fd_go/(rhog*fd_lo)) # Homogeneous properties, for Froude/Weber numbers voidage_h = homogeneous(x, rhol, rhog) rho_h = rhol*(1-voidage_h) + rhog*voidage_h Q_h = m/rho_h v_h = Q_h/(pi/4*D**2) Fr = Froude(V=v_h, L=D, squared=True) # checked with (m/(pi/4*D**2))**2/g/D/rho_h**2 We = Weber(V=v_h, L=D, rho=rho_h, sigma=sigma) # checked with (m/(pi/4*D**2))**2*D/sigma/rho_h phi_lo2 = E + 3.24*F*H/(Fr**0.0454*We**0.035) return phi_lo2*dP_lo
python
def Friedel(m, x, rhol, rhog, mul, mug, sigma, D, roughness=0, L=1): r'''Calculates two-phase pressure drop with the Friedel correlation. .. math:: \Delta P_{friction} = \Delta P_{lo} \phi_{lo}^2 .. math:: \phi_{lo}^2 = E + \frac{3.24FH}{Fr^{0.0454} We^{0.035}} .. math:: H = \left(\frac{\rho_l}{\rho_g}\right)^{0.91}\left(\frac{\mu_g}{\mu_l} \right)^{0.19}\left(1 - \frac{\mu_g}{\mu_l}\right)^{0.7} .. math:: F = x^{0.78}(1 - x)^{0.224} .. math:: E = (1-x)^2 + x^2\left(\frac{\rho_l f_{d,go}}{\rho_g f_{d,lo}}\right) .. math:: Fr = \frac{G_{tp}^2}{gD\rho_H^2} .. math:: We = \frac{G_{tp}^2 D}{\sigma \rho_H} .. math:: \rho_H = \left(\frac{x}{\rho_g} + \frac{1-x}{\rho_l}\right)^{-1} Parameters ---------- m : float Mass flow rate of fluid, [kg/s] x : float Quality of fluid, [-] rhol : float Liquid density, [kg/m^3] rhog : float Gas density, [kg/m^3] mul : float Viscosity of liquid, [Pa*s] mug : float Viscosity of gas, [Pa*s] sigma : float Surface tension, [N/m] D : float Diameter of pipe, [m] roughness : float, optional Roughness of pipe for use in calculating friction factor, [m] L : float, optional Length of pipe, [m] Returns ------- dP : float Pressure drop of the two-phase flow, [Pa] Notes ----- Applicable to vertical upflow and horizontal flow. Known to work poorly when mul/mug > 1000. Gives mean errors on the order of 40%. Tested on data with diameters as small as 4 mm. The power of 0.0454 is given as 0.045 in [2]_, [3]_, [4]_, and [5]_; [6]_ and [2]_ give 0.0454 and [2]_ also gives a similar correlation said to be presented in [1]_, so it is believed this 0.0454 was the original power. [6]_ also gives an expression for friction factor claimed to be presented in [1]_; it is not used here. Examples -------- Example 4 in [6]_: >>> Friedel(m=0.6, x=0.1, rhol=915., rhog=2.67, mul=180E-6, mug=14E-6, ... sigma=0.0487, D=0.05, roughness=0, L=1) 738.6500525002245 References ---------- .. [1] Friedel, L. "Improved Friction Pressure Drop Correlations for Horizontal and Vertical Two-Phase Pipe Flow." , in: Proceedings, European Two Phase Flow Group Meeting, Ispra, Italy, 1979: 485-481. .. [2] Whalley, P. B. Boiling, Condensation, and Gas-Liquid Flow. Oxford: Oxford University Press, 1987. .. [3] Triplett, K. A., S. M. Ghiaasiaan, S. I. Abdel-Khalik, A. LeMouel, and B. N. McCord. "Gas-liquid Two-Phase Flow in Microchannels: Part II: Void Fraction and Pressure Drop.” International Journal of Multiphase Flow 25, no. 3 (April 1999): 395-410. doi:10.1016/S0301-9322(98)00055-X. .. [4] Mekisso, Henock Mateos. "Comparison of Frictional Pressure Drop Correlations for Isothermal Two-Phase Horizontal Flow." Thesis, Oklahoma State University, 2013. https://shareok.org/handle/11244/11109. .. [5] Thome, John R. "Engineering Data Book III." Wolverine Tube Inc (2004). http://www.wlv.com/heat-transfer-databook/ .. [6] Ghiaasiaan, S. Mostafa. Two-Phase Flow, Boiling, and Condensation: In Conventional and Miniature Systems. Cambridge University Press, 2007. ''' # Liquid-only properties, for calculation of E, dP_lo v_lo = m/rhol/(pi/4*D**2) Re_lo = Reynolds(V=v_lo, rho=rhol, mu=mul, D=D) fd_lo = friction_factor(Re=Re_lo, eD=roughness/D) dP_lo = fd_lo*L/D*(0.5*rhol*v_lo**2) # Gas-only properties, for calculation of E v_go = m/rhog/(pi/4*D**2) Re_go = Reynolds(V=v_go, rho=rhog, mu=mug, D=D) fd_go = friction_factor(Re=Re_go, eD=roughness/D) F = x**0.78*(1-x)**0.224 H = (rhol/rhog)**0.91*(mug/mul)**0.19*(1 - mug/mul)**0.7 E = (1-x)**2 + x**2*(rhol*fd_go/(rhog*fd_lo)) # Homogeneous properties, for Froude/Weber numbers voidage_h = homogeneous(x, rhol, rhog) rho_h = rhol*(1-voidage_h) + rhog*voidage_h Q_h = m/rho_h v_h = Q_h/(pi/4*D**2) Fr = Froude(V=v_h, L=D, squared=True) # checked with (m/(pi/4*D**2))**2/g/D/rho_h**2 We = Weber(V=v_h, L=D, rho=rho_h, sigma=sigma) # checked with (m/(pi/4*D**2))**2*D/sigma/rho_h phi_lo2 = E + 3.24*F*H/(Fr**0.0454*We**0.035) return phi_lo2*dP_lo
[ "def", "Friedel", "(", "m", ",", "x", ",", "rhol", ",", "rhog", ",", "mul", ",", "mug", ",", "sigma", ",", "D", ",", "roughness", "=", "0", ",", "L", "=", "1", ")", ":", "# Liquid-only properties, for calculation of E, dP_lo", "v_lo", "=", "m", "/", "rhol", "/", "(", "pi", "/", "4", "*", "D", "**", "2", ")", "Re_lo", "=", "Reynolds", "(", "V", "=", "v_lo", ",", "rho", "=", "rhol", ",", "mu", "=", "mul", ",", "D", "=", "D", ")", "fd_lo", "=", "friction_factor", "(", "Re", "=", "Re_lo", ",", "eD", "=", "roughness", "/", "D", ")", "dP_lo", "=", "fd_lo", "*", "L", "/", "D", "*", "(", "0.5", "*", "rhol", "*", "v_lo", "**", "2", ")", "# Gas-only properties, for calculation of E", "v_go", "=", "m", "/", "rhog", "/", "(", "pi", "/", "4", "*", "D", "**", "2", ")", "Re_go", "=", "Reynolds", "(", "V", "=", "v_go", ",", "rho", "=", "rhog", ",", "mu", "=", "mug", ",", "D", "=", "D", ")", "fd_go", "=", "friction_factor", "(", "Re", "=", "Re_go", ",", "eD", "=", "roughness", "/", "D", ")", "F", "=", "x", "**", "0.78", "*", "(", "1", "-", "x", ")", "**", "0.224", "H", "=", "(", "rhol", "/", "rhog", ")", "**", "0.91", "*", "(", "mug", "/", "mul", ")", "**", "0.19", "*", "(", "1", "-", "mug", "/", "mul", ")", "**", "0.7", "E", "=", "(", "1", "-", "x", ")", "**", "2", "+", "x", "**", "2", "*", "(", "rhol", "*", "fd_go", "/", "(", "rhog", "*", "fd_lo", ")", ")", "# Homogeneous properties, for Froude/Weber numbers", "voidage_h", "=", "homogeneous", "(", "x", ",", "rhol", ",", "rhog", ")", "rho_h", "=", "rhol", "*", "(", "1", "-", "voidage_h", ")", "+", "rhog", "*", "voidage_h", "Q_h", "=", "m", "/", "rho_h", "v_h", "=", "Q_h", "/", "(", "pi", "/", "4", "*", "D", "**", "2", ")", "Fr", "=", "Froude", "(", "V", "=", "v_h", ",", "L", "=", "D", ",", "squared", "=", "True", ")", "# checked with (m/(pi/4*D**2))**2/g/D/rho_h**2", "We", "=", "Weber", "(", "V", "=", "v_h", ",", "L", "=", "D", ",", "rho", "=", "rho_h", ",", "sigma", "=", "sigma", ")", "# checked with (m/(pi/4*D**2))**2*D/sigma/rho_h", "phi_lo2", "=", "E", "+", "3.24", "*", "F", "*", "H", "/", "(", "Fr", "**", "0.0454", "*", "We", "**", "0.035", ")", "return", "phi_lo2", "*", "dP_lo" ]
r'''Calculates two-phase pressure drop with the Friedel correlation. .. math:: \Delta P_{friction} = \Delta P_{lo} \phi_{lo}^2 .. math:: \phi_{lo}^2 = E + \frac{3.24FH}{Fr^{0.0454} We^{0.035}} .. math:: H = \left(\frac{\rho_l}{\rho_g}\right)^{0.91}\left(\frac{\mu_g}{\mu_l} \right)^{0.19}\left(1 - \frac{\mu_g}{\mu_l}\right)^{0.7} .. math:: F = x^{0.78}(1 - x)^{0.224} .. math:: E = (1-x)^2 + x^2\left(\frac{\rho_l f_{d,go}}{\rho_g f_{d,lo}}\right) .. math:: Fr = \frac{G_{tp}^2}{gD\rho_H^2} .. math:: We = \frac{G_{tp}^2 D}{\sigma \rho_H} .. math:: \rho_H = \left(\frac{x}{\rho_g} + \frac{1-x}{\rho_l}\right)^{-1} Parameters ---------- m : float Mass flow rate of fluid, [kg/s] x : float Quality of fluid, [-] rhol : float Liquid density, [kg/m^3] rhog : float Gas density, [kg/m^3] mul : float Viscosity of liquid, [Pa*s] mug : float Viscosity of gas, [Pa*s] sigma : float Surface tension, [N/m] D : float Diameter of pipe, [m] roughness : float, optional Roughness of pipe for use in calculating friction factor, [m] L : float, optional Length of pipe, [m] Returns ------- dP : float Pressure drop of the two-phase flow, [Pa] Notes ----- Applicable to vertical upflow and horizontal flow. Known to work poorly when mul/mug > 1000. Gives mean errors on the order of 40%. Tested on data with diameters as small as 4 mm. The power of 0.0454 is given as 0.045 in [2]_, [3]_, [4]_, and [5]_; [6]_ and [2]_ give 0.0454 and [2]_ also gives a similar correlation said to be presented in [1]_, so it is believed this 0.0454 was the original power. [6]_ also gives an expression for friction factor claimed to be presented in [1]_; it is not used here. Examples -------- Example 4 in [6]_: >>> Friedel(m=0.6, x=0.1, rhol=915., rhog=2.67, mul=180E-6, mug=14E-6, ... sigma=0.0487, D=0.05, roughness=0, L=1) 738.6500525002245 References ---------- .. [1] Friedel, L. "Improved Friction Pressure Drop Correlations for Horizontal and Vertical Two-Phase Pipe Flow." , in: Proceedings, European Two Phase Flow Group Meeting, Ispra, Italy, 1979: 485-481. .. [2] Whalley, P. B. Boiling, Condensation, and Gas-Liquid Flow. Oxford: Oxford University Press, 1987. .. [3] Triplett, K. A., S. M. Ghiaasiaan, S. I. Abdel-Khalik, A. LeMouel, and B. N. McCord. "Gas-liquid Two-Phase Flow in Microchannels: Part II: Void Fraction and Pressure Drop.” International Journal of Multiphase Flow 25, no. 3 (April 1999): 395-410. doi:10.1016/S0301-9322(98)00055-X. .. [4] Mekisso, Henock Mateos. "Comparison of Frictional Pressure Drop Correlations for Isothermal Two-Phase Horizontal Flow." Thesis, Oklahoma State University, 2013. https://shareok.org/handle/11244/11109. .. [5] Thome, John R. "Engineering Data Book III." Wolverine Tube Inc (2004). http://www.wlv.com/heat-transfer-databook/ .. [6] Ghiaasiaan, S. Mostafa. Two-Phase Flow, Boiling, and Condensation: In Conventional and Miniature Systems. Cambridge University Press, 2007.
[ "r", "Calculates", "two", "-", "phase", "pressure", "drop", "with", "the", "Friedel", "correlation", "." ]
57f556752e039f1d3e5a822f408c184783db2828
https://github.com/CalebBell/fluids/blob/57f556752e039f1d3e5a822f408c184783db2828/fluids/two_phase.py#L204-L324
8,310
CalebBell/fluids
fluids/atmosphere.py
airmass
def airmass(func, angle, H_max=86400.0, R_planet=6.371229E6, RI=1.000276): r'''Calculates mass of air per square meter in the atmosphere using a provided atmospheric model. The lowest air mass is calculated straight up; as the angle is lowered to nearer and nearer the horizon, the air mass increases, and can approach 40x or more the minimum airmass. .. math:: m(\gamma) = \int_0^\infty \rho \left\{1 - \left[1 + 2(\text{RI}-1) (1-\rho/\rho_0)\right] \left[\frac{\cos \gamma}{(1+h/R)}\right]^2\right\}^{-1/2} dH Parameters ---------- func : float Function which returns the density of the atmosphere as a function of elevation angle : float Degrees above the horizon (90 = straight up), [degrees] H_max : float, optional Maximum height to compute the integration up to before the contribution of density becomes negligible, [m] R_planet : float, optional The radius of the planet for which the integration is being performed, [m] RI : float, optional The refractive index of the atmosphere (air on earth at 0.7 um as default) assumed a constant, [-] Returns ------- m : float Mass of air per square meter in the atmosphere, [kg/m^2] Notes ----- Numerical integration via SciPy's `quad` is used to perform the calculation. Examples -------- >>> airmass(lambda Z : ATMOSPHERE_1976(Z).rho, 90) 10356.127665863998 References ---------- .. [1] Kasten, Fritz, and Andrew T. Young. "Revised Optical Air Mass Tables and Approximation Formula." Applied Optics 28, no. 22 (November 15, 1989): 4735-38. https://doi.org/10.1364/AO.28.004735. ''' delta0 = RI - 1.0 rho0 = func(0.0) angle_term = cos(radians(angle)) def to_int(Z): rho = func(Z) t1 = (1.0 + 2.0*delta0*(1.0 - rho/rho0)) t2 = (angle_term/(1.0 + Z/R_planet))**2 t3 = (1.0 - t1*t2)**-0.5 return rho*t3 from scipy.integrate import quad return float(quad(to_int, 0, 86400.0)[0])
python
def airmass(func, angle, H_max=86400.0, R_planet=6.371229E6, RI=1.000276): r'''Calculates mass of air per square meter in the atmosphere using a provided atmospheric model. The lowest air mass is calculated straight up; as the angle is lowered to nearer and nearer the horizon, the air mass increases, and can approach 40x or more the minimum airmass. .. math:: m(\gamma) = \int_0^\infty \rho \left\{1 - \left[1 + 2(\text{RI}-1) (1-\rho/\rho_0)\right] \left[\frac{\cos \gamma}{(1+h/R)}\right]^2\right\}^{-1/2} dH Parameters ---------- func : float Function which returns the density of the atmosphere as a function of elevation angle : float Degrees above the horizon (90 = straight up), [degrees] H_max : float, optional Maximum height to compute the integration up to before the contribution of density becomes negligible, [m] R_planet : float, optional The radius of the planet for which the integration is being performed, [m] RI : float, optional The refractive index of the atmosphere (air on earth at 0.7 um as default) assumed a constant, [-] Returns ------- m : float Mass of air per square meter in the atmosphere, [kg/m^2] Notes ----- Numerical integration via SciPy's `quad` is used to perform the calculation. Examples -------- >>> airmass(lambda Z : ATMOSPHERE_1976(Z).rho, 90) 10356.127665863998 References ---------- .. [1] Kasten, Fritz, and Andrew T. Young. "Revised Optical Air Mass Tables and Approximation Formula." Applied Optics 28, no. 22 (November 15, 1989): 4735-38. https://doi.org/10.1364/AO.28.004735. ''' delta0 = RI - 1.0 rho0 = func(0.0) angle_term = cos(radians(angle)) def to_int(Z): rho = func(Z) t1 = (1.0 + 2.0*delta0*(1.0 - rho/rho0)) t2 = (angle_term/(1.0 + Z/R_planet))**2 t3 = (1.0 - t1*t2)**-0.5 return rho*t3 from scipy.integrate import quad return float(quad(to_int, 0, 86400.0)[0])
[ "def", "airmass", "(", "func", ",", "angle", ",", "H_max", "=", "86400.0", ",", "R_planet", "=", "6.371229E6", ",", "RI", "=", "1.000276", ")", ":", "delta0", "=", "RI", "-", "1.0", "rho0", "=", "func", "(", "0.0", ")", "angle_term", "=", "cos", "(", "radians", "(", "angle", ")", ")", "def", "to_int", "(", "Z", ")", ":", "rho", "=", "func", "(", "Z", ")", "t1", "=", "(", "1.0", "+", "2.0", "*", "delta0", "*", "(", "1.0", "-", "rho", "/", "rho0", ")", ")", "t2", "=", "(", "angle_term", "/", "(", "1.0", "+", "Z", "/", "R_planet", ")", ")", "**", "2", "t3", "=", "(", "1.0", "-", "t1", "*", "t2", ")", "**", "-", "0.5", "return", "rho", "*", "t3", "from", "scipy", ".", "integrate", "import", "quad", "return", "float", "(", "quad", "(", "to_int", ",", "0", ",", "86400.0", ")", "[", "0", "]", ")" ]
r'''Calculates mass of air per square meter in the atmosphere using a provided atmospheric model. The lowest air mass is calculated straight up; as the angle is lowered to nearer and nearer the horizon, the air mass increases, and can approach 40x or more the minimum airmass. .. math:: m(\gamma) = \int_0^\infty \rho \left\{1 - \left[1 + 2(\text{RI}-1) (1-\rho/\rho_0)\right] \left[\frac{\cos \gamma}{(1+h/R)}\right]^2\right\}^{-1/2} dH Parameters ---------- func : float Function which returns the density of the atmosphere as a function of elevation angle : float Degrees above the horizon (90 = straight up), [degrees] H_max : float, optional Maximum height to compute the integration up to before the contribution of density becomes negligible, [m] R_planet : float, optional The radius of the planet for which the integration is being performed, [m] RI : float, optional The refractive index of the atmosphere (air on earth at 0.7 um as default) assumed a constant, [-] Returns ------- m : float Mass of air per square meter in the atmosphere, [kg/m^2] Notes ----- Numerical integration via SciPy's `quad` is used to perform the calculation. Examples -------- >>> airmass(lambda Z : ATMOSPHERE_1976(Z).rho, 90) 10356.127665863998 References ---------- .. [1] Kasten, Fritz, and Andrew T. Young. "Revised Optical Air Mass Tables and Approximation Formula." Applied Optics 28, no. 22 (November 15, 1989): 4735-38. https://doi.org/10.1364/AO.28.004735.
[ "r", "Calculates", "mass", "of", "air", "per", "square", "meter", "in", "the", "atmosphere", "using", "a", "provided", "atmospheric", "model", ".", "The", "lowest", "air", "mass", "is", "calculated", "straight", "up", ";", "as", "the", "angle", "is", "lowered", "to", "nearer", "and", "nearer", "the", "horizon", "the", "air", "mass", "increases", "and", "can", "approach", "40x", "or", "more", "the", "minimum", "airmass", "." ]
57f556752e039f1d3e5a822f408c184783db2828
https://github.com/CalebBell/fluids/blob/57f556752e039f1d3e5a822f408c184783db2828/fluids/atmosphere.py#L689-L750
8,311
CalebBell/fluids
fluids/atmosphere.py
ATMOSPHERE_1976._get_ind_from_H
def _get_ind_from_H(H): r'''Method defined in the US Standard Atmosphere 1976 for determining the index of the layer a specified elevation is above. Levels are 0, 11E3, 20E3, 32E3, 47E3, 51E3, 71E3, 84852 meters respectively. ''' if H <= 0: return 0 for ind, Hi in enumerate(H_std): if Hi >= H : return ind-1 return 7
python
def _get_ind_from_H(H): r'''Method defined in the US Standard Atmosphere 1976 for determining the index of the layer a specified elevation is above. Levels are 0, 11E3, 20E3, 32E3, 47E3, 51E3, 71E3, 84852 meters respectively. ''' if H <= 0: return 0 for ind, Hi in enumerate(H_std): if Hi >= H : return ind-1 return 7
[ "def", "_get_ind_from_H", "(", "H", ")", ":", "if", "H", "<=", "0", ":", "return", "0", "for", "ind", ",", "Hi", "in", "enumerate", "(", "H_std", ")", ":", "if", "Hi", ">=", "H", ":", "return", "ind", "-", "1", "return", "7" ]
r'''Method defined in the US Standard Atmosphere 1976 for determining the index of the layer a specified elevation is above. Levels are 0, 11E3, 20E3, 32E3, 47E3, 51E3, 71E3, 84852 meters respectively.
[ "r", "Method", "defined", "in", "the", "US", "Standard", "Atmosphere", "1976", "for", "determining", "the", "index", "of", "the", "layer", "a", "specified", "elevation", "is", "above", ".", "Levels", "are", "0", "11E3", "20E3", "32E3", "47E3", "51E3", "71E3", "84852", "meters", "respectively", "." ]
57f556752e039f1d3e5a822f408c184783db2828
https://github.com/CalebBell/fluids/blob/57f556752e039f1d3e5a822f408c184783db2828/fluids/atmosphere.py#L154-L164
8,312
CalebBell/fluids
fluids/piping.py
gauge_from_t
def gauge_from_t(t, SI=True, schedule='BWG'): r'''Looks up the gauge of a given wire thickness of given schedule. Values are all non-linear, and tabulated internally. Parameters ---------- t : float Thickness, [m] SI : bool, optional If False, requires that the thickness is given in inches not meters schedule : str Gauge schedule, one of 'BWG', 'AWG', 'SWG', 'MWG', 'BSWG', or 'SSWG' Returns ------- gauge : float-like Wire Gauge, [-] Notes ----- An internal variable, tol, is used in the selection of the wire gauge. If the next smaller wire gauge is within 10% of the difference between it and the previous wire gauge, the smaller wire gauge is selected. Accordingly, this function can return a gauge with a thickness smaller than desired in some circumstances. * Birmingham Wire Gauge (BWG) ranges from 0.2 (0.5 inch) to 36 (0.004 inch). * American Wire Gauge (AWG) ranges from 0.167 (0.58 inch) to 51 (0.00099 inch). These are used for electrical wires. * Steel Wire Gauge (SWG) ranges from 0.143 (0.49 inch) to 51 (0.0044 inch). Also called Washburn & Moen wire gauge, American Steel gauge, Wire Co. gauge, and Roebling wire gauge. * Music Wire Gauge (MWG) ranges from 0.167 (0.004 inch) to 46 (0.18 inch). Also called Piano Wire Gauge. * British Standard Wire Gage (BSWG) ranges from 0.143 (0.5 inch) to 51 (0.001 inch). Also called Imperial Wire Gage (IWG). * Stub's Steel Wire Gage (SSWG) ranges from 1 (0.227 inch) to 80 (0.013 inch) Examples -------- >>> gauge_from_t(.5, SI=False, schedule='BWG') 0.2 References ---------- .. [1] Oberg, Erik, Franklin D. Jones, and Henry H. Ryffel. Machinery's Handbook. Industrial Press, Incorporated, 2012. ''' tol = 0.1 # Handle units if SI: t_inch = round(t/inch, 9) # all schedules are in inches else: t_inch = t # Get the schedule try: sch_integers, sch_inch, sch_SI, decreasing = wire_schedules[schedule] except: raise ValueError('Wire gauge schedule not found') # Check if outside limits sch_max, sch_min = sch_inch[0], sch_inch[-1] if t_inch > sch_max: raise ValueError('Input thickness is above the largest in the selected schedule') # If given thickness is exactly in the index, be happy if t_inch in sch_inch: gauge = sch_integers[sch_inch.index(t_inch)] else: for i in range(len(sch_inch)): if sch_inch[i] >= t_inch: larger = sch_inch[i] else: break if larger == sch_min: gauge = sch_min # If t is under the lowest schedule, be happy else: smaller = sch_inch[i] if (t_inch - smaller) <= tol*(larger - smaller): gauge = sch_integers[i] else: gauge = sch_integers[i-1] return gauge
python
def gauge_from_t(t, SI=True, schedule='BWG'): r'''Looks up the gauge of a given wire thickness of given schedule. Values are all non-linear, and tabulated internally. Parameters ---------- t : float Thickness, [m] SI : bool, optional If False, requires that the thickness is given in inches not meters schedule : str Gauge schedule, one of 'BWG', 'AWG', 'SWG', 'MWG', 'BSWG', or 'SSWG' Returns ------- gauge : float-like Wire Gauge, [-] Notes ----- An internal variable, tol, is used in the selection of the wire gauge. If the next smaller wire gauge is within 10% of the difference between it and the previous wire gauge, the smaller wire gauge is selected. Accordingly, this function can return a gauge with a thickness smaller than desired in some circumstances. * Birmingham Wire Gauge (BWG) ranges from 0.2 (0.5 inch) to 36 (0.004 inch). * American Wire Gauge (AWG) ranges from 0.167 (0.58 inch) to 51 (0.00099 inch). These are used for electrical wires. * Steel Wire Gauge (SWG) ranges from 0.143 (0.49 inch) to 51 (0.0044 inch). Also called Washburn & Moen wire gauge, American Steel gauge, Wire Co. gauge, and Roebling wire gauge. * Music Wire Gauge (MWG) ranges from 0.167 (0.004 inch) to 46 (0.18 inch). Also called Piano Wire Gauge. * British Standard Wire Gage (BSWG) ranges from 0.143 (0.5 inch) to 51 (0.001 inch). Also called Imperial Wire Gage (IWG). * Stub's Steel Wire Gage (SSWG) ranges from 1 (0.227 inch) to 80 (0.013 inch) Examples -------- >>> gauge_from_t(.5, SI=False, schedule='BWG') 0.2 References ---------- .. [1] Oberg, Erik, Franklin D. Jones, and Henry H. Ryffel. Machinery's Handbook. Industrial Press, Incorporated, 2012. ''' tol = 0.1 # Handle units if SI: t_inch = round(t/inch, 9) # all schedules are in inches else: t_inch = t # Get the schedule try: sch_integers, sch_inch, sch_SI, decreasing = wire_schedules[schedule] except: raise ValueError('Wire gauge schedule not found') # Check if outside limits sch_max, sch_min = sch_inch[0], sch_inch[-1] if t_inch > sch_max: raise ValueError('Input thickness is above the largest in the selected schedule') # If given thickness is exactly in the index, be happy if t_inch in sch_inch: gauge = sch_integers[sch_inch.index(t_inch)] else: for i in range(len(sch_inch)): if sch_inch[i] >= t_inch: larger = sch_inch[i] else: break if larger == sch_min: gauge = sch_min # If t is under the lowest schedule, be happy else: smaller = sch_inch[i] if (t_inch - smaller) <= tol*(larger - smaller): gauge = sch_integers[i] else: gauge = sch_integers[i-1] return gauge
[ "def", "gauge_from_t", "(", "t", ",", "SI", "=", "True", ",", "schedule", "=", "'BWG'", ")", ":", "tol", "=", "0.1", "# Handle units", "if", "SI", ":", "t_inch", "=", "round", "(", "t", "/", "inch", ",", "9", ")", "# all schedules are in inches", "else", ":", "t_inch", "=", "t", "# Get the schedule", "try", ":", "sch_integers", ",", "sch_inch", ",", "sch_SI", ",", "decreasing", "=", "wire_schedules", "[", "schedule", "]", "except", ":", "raise", "ValueError", "(", "'Wire gauge schedule not found'", ")", "# Check if outside limits", "sch_max", ",", "sch_min", "=", "sch_inch", "[", "0", "]", ",", "sch_inch", "[", "-", "1", "]", "if", "t_inch", ">", "sch_max", ":", "raise", "ValueError", "(", "'Input thickness is above the largest in the selected schedule'", ")", "# If given thickness is exactly in the index, be happy", "if", "t_inch", "in", "sch_inch", ":", "gauge", "=", "sch_integers", "[", "sch_inch", ".", "index", "(", "t_inch", ")", "]", "else", ":", "for", "i", "in", "range", "(", "len", "(", "sch_inch", ")", ")", ":", "if", "sch_inch", "[", "i", "]", ">=", "t_inch", ":", "larger", "=", "sch_inch", "[", "i", "]", "else", ":", "break", "if", "larger", "==", "sch_min", ":", "gauge", "=", "sch_min", "# If t is under the lowest schedule, be happy", "else", ":", "smaller", "=", "sch_inch", "[", "i", "]", "if", "(", "t_inch", "-", "smaller", ")", "<=", "tol", "*", "(", "larger", "-", "smaller", ")", ":", "gauge", "=", "sch_integers", "[", "i", "]", "else", ":", "gauge", "=", "sch_integers", "[", "i", "-", "1", "]", "return", "gauge" ]
r'''Looks up the gauge of a given wire thickness of given schedule. Values are all non-linear, and tabulated internally. Parameters ---------- t : float Thickness, [m] SI : bool, optional If False, requires that the thickness is given in inches not meters schedule : str Gauge schedule, one of 'BWG', 'AWG', 'SWG', 'MWG', 'BSWG', or 'SSWG' Returns ------- gauge : float-like Wire Gauge, [-] Notes ----- An internal variable, tol, is used in the selection of the wire gauge. If the next smaller wire gauge is within 10% of the difference between it and the previous wire gauge, the smaller wire gauge is selected. Accordingly, this function can return a gauge with a thickness smaller than desired in some circumstances. * Birmingham Wire Gauge (BWG) ranges from 0.2 (0.5 inch) to 36 (0.004 inch). * American Wire Gauge (AWG) ranges from 0.167 (0.58 inch) to 51 (0.00099 inch). These are used for electrical wires. * Steel Wire Gauge (SWG) ranges from 0.143 (0.49 inch) to 51 (0.0044 inch). Also called Washburn & Moen wire gauge, American Steel gauge, Wire Co. gauge, and Roebling wire gauge. * Music Wire Gauge (MWG) ranges from 0.167 (0.004 inch) to 46 (0.18 inch). Also called Piano Wire Gauge. * British Standard Wire Gage (BSWG) ranges from 0.143 (0.5 inch) to 51 (0.001 inch). Also called Imperial Wire Gage (IWG). * Stub's Steel Wire Gage (SSWG) ranges from 1 (0.227 inch) to 80 (0.013 inch) Examples -------- >>> gauge_from_t(.5, SI=False, schedule='BWG') 0.2 References ---------- .. [1] Oberg, Erik, Franklin D. Jones, and Henry H. Ryffel. Machinery's Handbook. Industrial Press, Incorporated, 2012.
[ "r", "Looks", "up", "the", "gauge", "of", "a", "given", "wire", "thickness", "of", "given", "schedule", ".", "Values", "are", "all", "non", "-", "linear", "and", "tabulated", "internally", "." ]
57f556752e039f1d3e5a822f408c184783db2828
https://github.com/CalebBell/fluids/blob/57f556752e039f1d3e5a822f408c184783db2828/fluids/piping.py#L349-L434
8,313
CalebBell/fluids
fluids/piping.py
t_from_gauge
def t_from_gauge(gauge, SI=True, schedule='BWG'): r'''Looks up the thickness of a given wire gauge of given schedule. Values are all non-linear, and tabulated internally. Parameters ---------- gauge : float-like Wire Gauge, [] SI : bool, optional If False, will return a thickness in inches not meters schedule : str Gauge schedule, one of 'BWG', 'AWG', 'SWG', 'MWG', 'BSWG', or 'SSWG' Returns ------- t : float Thickness, [m] Notes ----- * Birmingham Wire Gauge (BWG) ranges from 0.2 (0.5 inch) to 36 (0.004 inch). * American Wire Gauge (AWG) ranges from 0.167 (0.58 inch) to 51 (0.00099 inch). These are used for electrical wires. * Steel Wire Gauge (SWG) ranges from 0.143 (0.49 inch) to 51 (0.0044 inch). Also called Washburn & Moen wire gauge, American Steel gauge, Wire Co. gauge, and Roebling wire gauge. * Music Wire Gauge (MWG) ranges from 0.167 (0.004 inch) to 46 (0.18 inch). Also called Piano Wire Gauge. * British Standard Wire Gage (BSWG) ranges from 0.143 (0.5 inch) to 51 (0.001 inch). Also called Imperial Wire Gage (IWG). * Stub's Steel Wire Gage (SSWG) ranges from 1 (0.227 inch) to 80 (0.013 inch) Examples -------- >>> t_from_gauge(.2, False, 'BWG') 0.5 References ---------- .. [1] Oberg, Erik, Franklin D. Jones, and Henry H. Ryffel. Machinery's Handbook. Industrial Press, Incorporated, 2012. ''' try: sch_integers, sch_inch, sch_SI, decreasing = wire_schedules[schedule] except: raise ValueError("Wire gauge schedule not found; supported gauges are \ 'BWG', 'AWG', 'SWG', 'MWG', 'BSWG', and 'SSWG'.") try: i = sch_integers.index(gauge) except: raise ValueError('Input gauge not found in selected schedule') if SI: return sch_SI[i] # returns thickness in m else: return sch_inch[i]
python
def t_from_gauge(gauge, SI=True, schedule='BWG'): r'''Looks up the thickness of a given wire gauge of given schedule. Values are all non-linear, and tabulated internally. Parameters ---------- gauge : float-like Wire Gauge, [] SI : bool, optional If False, will return a thickness in inches not meters schedule : str Gauge schedule, one of 'BWG', 'AWG', 'SWG', 'MWG', 'BSWG', or 'SSWG' Returns ------- t : float Thickness, [m] Notes ----- * Birmingham Wire Gauge (BWG) ranges from 0.2 (0.5 inch) to 36 (0.004 inch). * American Wire Gauge (AWG) ranges from 0.167 (0.58 inch) to 51 (0.00099 inch). These are used for electrical wires. * Steel Wire Gauge (SWG) ranges from 0.143 (0.49 inch) to 51 (0.0044 inch). Also called Washburn & Moen wire gauge, American Steel gauge, Wire Co. gauge, and Roebling wire gauge. * Music Wire Gauge (MWG) ranges from 0.167 (0.004 inch) to 46 (0.18 inch). Also called Piano Wire Gauge. * British Standard Wire Gage (BSWG) ranges from 0.143 (0.5 inch) to 51 (0.001 inch). Also called Imperial Wire Gage (IWG). * Stub's Steel Wire Gage (SSWG) ranges from 1 (0.227 inch) to 80 (0.013 inch) Examples -------- >>> t_from_gauge(.2, False, 'BWG') 0.5 References ---------- .. [1] Oberg, Erik, Franklin D. Jones, and Henry H. Ryffel. Machinery's Handbook. Industrial Press, Incorporated, 2012. ''' try: sch_integers, sch_inch, sch_SI, decreasing = wire_schedules[schedule] except: raise ValueError("Wire gauge schedule not found; supported gauges are \ 'BWG', 'AWG', 'SWG', 'MWG', 'BSWG', and 'SSWG'.") try: i = sch_integers.index(gauge) except: raise ValueError('Input gauge not found in selected schedule') if SI: return sch_SI[i] # returns thickness in m else: return sch_inch[i]
[ "def", "t_from_gauge", "(", "gauge", ",", "SI", "=", "True", ",", "schedule", "=", "'BWG'", ")", ":", "try", ":", "sch_integers", ",", "sch_inch", ",", "sch_SI", ",", "decreasing", "=", "wire_schedules", "[", "schedule", "]", "except", ":", "raise", "ValueError", "(", "\"Wire gauge schedule not found; supported gauges are \\\n'BWG', 'AWG', 'SWG', 'MWG', 'BSWG', and 'SSWG'.\"", ")", "try", ":", "i", "=", "sch_integers", ".", "index", "(", "gauge", ")", "except", ":", "raise", "ValueError", "(", "'Input gauge not found in selected schedule'", ")", "if", "SI", ":", "return", "sch_SI", "[", "i", "]", "# returns thickness in m", "else", ":", "return", "sch_inch", "[", "i", "]" ]
r'''Looks up the thickness of a given wire gauge of given schedule. Values are all non-linear, and tabulated internally. Parameters ---------- gauge : float-like Wire Gauge, [] SI : bool, optional If False, will return a thickness in inches not meters schedule : str Gauge schedule, one of 'BWG', 'AWG', 'SWG', 'MWG', 'BSWG', or 'SSWG' Returns ------- t : float Thickness, [m] Notes ----- * Birmingham Wire Gauge (BWG) ranges from 0.2 (0.5 inch) to 36 (0.004 inch). * American Wire Gauge (AWG) ranges from 0.167 (0.58 inch) to 51 (0.00099 inch). These are used for electrical wires. * Steel Wire Gauge (SWG) ranges from 0.143 (0.49 inch) to 51 (0.0044 inch). Also called Washburn & Moen wire gauge, American Steel gauge, Wire Co. gauge, and Roebling wire gauge. * Music Wire Gauge (MWG) ranges from 0.167 (0.004 inch) to 46 (0.18 inch). Also called Piano Wire Gauge. * British Standard Wire Gage (BSWG) ranges from 0.143 (0.5 inch) to 51 (0.001 inch). Also called Imperial Wire Gage (IWG). * Stub's Steel Wire Gage (SSWG) ranges from 1 (0.227 inch) to 80 (0.013 inch) Examples -------- >>> t_from_gauge(.2, False, 'BWG') 0.5 References ---------- .. [1] Oberg, Erik, Franklin D. Jones, and Henry H. Ryffel. Machinery's Handbook. Industrial Press, Incorporated, 2012.
[ "r", "Looks", "up", "the", "thickness", "of", "a", "given", "wire", "gauge", "of", "given", "schedule", ".", "Values", "are", "all", "non", "-", "linear", "and", "tabulated", "internally", "." ]
57f556752e039f1d3e5a822f408c184783db2828
https://github.com/CalebBell/fluids/blob/57f556752e039f1d3e5a822f408c184783db2828/fluids/piping.py#L437-L493
8,314
CalebBell/fluids
fluids/safety_valve.py
API520_F2
def API520_F2(k, P1, P2): r'''Calculates coefficient F2 for subcritical flow for use in API 520 subcritical flow relief valve sizing. .. math:: F_2 = \sqrt{\left(\frac{k}{k-1}\right)r^\frac{2}{k} \left[\frac{1-r^\frac{k-1}{k}}{1-r}\right]} .. math:: r = \frac{P_2}{P_1} Parameters ---------- k : float Isentropic coefficient or ideal gas heat capacity ratio [-] P1 : float Upstream relieving pressure; the set pressure plus the allowable overpressure, plus atmospheric pressure, [Pa] P2 : float Built-up backpressure; the increase in pressure during flow at the outlet of a pressure-relief device after it opens, [Pa] Returns ------- F2 : float Subcritical flow coefficient `F2` [-] Notes ----- F2 is completely dimensionless. Examples -------- From [1]_ example 2, matches. >>> API520_F2(1.8, 1E6, 7E5) 0.8600724121105563 References ---------- .. [1] API Standard 520, Part 1 - Sizing and Selection. ''' r = P2/P1 return ( k/(k-1)*r**(2./k) * ((1-r**((k-1.)/k))/(1.-r)) )**0.5
python
def API520_F2(k, P1, P2): r'''Calculates coefficient F2 for subcritical flow for use in API 520 subcritical flow relief valve sizing. .. math:: F_2 = \sqrt{\left(\frac{k}{k-1}\right)r^\frac{2}{k} \left[\frac{1-r^\frac{k-1}{k}}{1-r}\right]} .. math:: r = \frac{P_2}{P_1} Parameters ---------- k : float Isentropic coefficient or ideal gas heat capacity ratio [-] P1 : float Upstream relieving pressure; the set pressure plus the allowable overpressure, plus atmospheric pressure, [Pa] P2 : float Built-up backpressure; the increase in pressure during flow at the outlet of a pressure-relief device after it opens, [Pa] Returns ------- F2 : float Subcritical flow coefficient `F2` [-] Notes ----- F2 is completely dimensionless. Examples -------- From [1]_ example 2, matches. >>> API520_F2(1.8, 1E6, 7E5) 0.8600724121105563 References ---------- .. [1] API Standard 520, Part 1 - Sizing and Selection. ''' r = P2/P1 return ( k/(k-1)*r**(2./k) * ((1-r**((k-1.)/k))/(1.-r)) )**0.5
[ "def", "API520_F2", "(", "k", ",", "P1", ",", "P2", ")", ":", "r", "=", "P2", "/", "P1", "return", "(", "k", "/", "(", "k", "-", "1", ")", "*", "r", "**", "(", "2.", "/", "k", ")", "*", "(", "(", "1", "-", "r", "**", "(", "(", "k", "-", "1.", ")", "/", "k", ")", ")", "/", "(", "1.", "-", "r", ")", ")", ")", "**", "0.5" ]
r'''Calculates coefficient F2 for subcritical flow for use in API 520 subcritical flow relief valve sizing. .. math:: F_2 = \sqrt{\left(\frac{k}{k-1}\right)r^\frac{2}{k} \left[\frac{1-r^\frac{k-1}{k}}{1-r}\right]} .. math:: r = \frac{P_2}{P_1} Parameters ---------- k : float Isentropic coefficient or ideal gas heat capacity ratio [-] P1 : float Upstream relieving pressure; the set pressure plus the allowable overpressure, plus atmospheric pressure, [Pa] P2 : float Built-up backpressure; the increase in pressure during flow at the outlet of a pressure-relief device after it opens, [Pa] Returns ------- F2 : float Subcritical flow coefficient `F2` [-] Notes ----- F2 is completely dimensionless. Examples -------- From [1]_ example 2, matches. >>> API520_F2(1.8, 1E6, 7E5) 0.8600724121105563 References ---------- .. [1] API Standard 520, Part 1 - Sizing and Selection.
[ "r", "Calculates", "coefficient", "F2", "for", "subcritical", "flow", "for", "use", "in", "API", "520", "subcritical", "flow", "relief", "valve", "sizing", "." ]
57f556752e039f1d3e5a822f408c184783db2828
https://github.com/CalebBell/fluids/blob/57f556752e039f1d3e5a822f408c184783db2828/fluids/safety_valve.py#L130-L173
8,315
CalebBell/fluids
fluids/safety_valve.py
API520_SH
def API520_SH(T1, P1): r'''Calculates correction due to steam superheat for steam flow for use in API 520 relief valve sizing. 2D interpolation among a table with 28 pressures and 10 temperatures is performed. Parameters ---------- T1 : float Temperature of the fluid entering the valve [K] P1 : float Upstream relieving pressure; the set pressure plus the allowable overpressure, plus atmospheric pressure, [Pa] Returns ------- KSH : float Correction due to steam superheat [-] Notes ----- For P above 20679 kPag, use the critical flow model. Superheat cannot be above 649 degrees Celsius. If T1 is above 149 degrees Celsius, returns 1. Examples -------- Custom example from table 9: >>> API520_SH(593+273.15, 1066.325E3) 0.7201800000000002 References ---------- .. [1] API Standard 520, Part 1 - Sizing and Selection. ''' if P1 > 20780325.0: # 20679E3+atm raise Exception('For P above 20679 kPag, use the critical flow model') if T1 > 922.15: raise Exception('Superheat cannot be above 649 degrees Celcius') if T1 < 422.15: return 1. # No superheat under 15 psig return float(bisplev(T1, P1, API520_KSH_tck))
python
def API520_SH(T1, P1): r'''Calculates correction due to steam superheat for steam flow for use in API 520 relief valve sizing. 2D interpolation among a table with 28 pressures and 10 temperatures is performed. Parameters ---------- T1 : float Temperature of the fluid entering the valve [K] P1 : float Upstream relieving pressure; the set pressure plus the allowable overpressure, plus atmospheric pressure, [Pa] Returns ------- KSH : float Correction due to steam superheat [-] Notes ----- For P above 20679 kPag, use the critical flow model. Superheat cannot be above 649 degrees Celsius. If T1 is above 149 degrees Celsius, returns 1. Examples -------- Custom example from table 9: >>> API520_SH(593+273.15, 1066.325E3) 0.7201800000000002 References ---------- .. [1] API Standard 520, Part 1 - Sizing and Selection. ''' if P1 > 20780325.0: # 20679E3+atm raise Exception('For P above 20679 kPag, use the critical flow model') if T1 > 922.15: raise Exception('Superheat cannot be above 649 degrees Celcius') if T1 < 422.15: return 1. # No superheat under 15 psig return float(bisplev(T1, P1, API520_KSH_tck))
[ "def", "API520_SH", "(", "T1", ",", "P1", ")", ":", "if", "P1", ">", "20780325.0", ":", "# 20679E3+atm", "raise", "Exception", "(", "'For P above 20679 kPag, use the critical flow model'", ")", "if", "T1", ">", "922.15", ":", "raise", "Exception", "(", "'Superheat cannot be above 649 degrees Celcius'", ")", "if", "T1", "<", "422.15", ":", "return", "1.", "# No superheat under 15 psig", "return", "float", "(", "bisplev", "(", "T1", ",", "P1", ",", "API520_KSH_tck", ")", ")" ]
r'''Calculates correction due to steam superheat for steam flow for use in API 520 relief valve sizing. 2D interpolation among a table with 28 pressures and 10 temperatures is performed. Parameters ---------- T1 : float Temperature of the fluid entering the valve [K] P1 : float Upstream relieving pressure; the set pressure plus the allowable overpressure, plus atmospheric pressure, [Pa] Returns ------- KSH : float Correction due to steam superheat [-] Notes ----- For P above 20679 kPag, use the critical flow model. Superheat cannot be above 649 degrees Celsius. If T1 is above 149 degrees Celsius, returns 1. Examples -------- Custom example from table 9: >>> API520_SH(593+273.15, 1066.325E3) 0.7201800000000002 References ---------- .. [1] API Standard 520, Part 1 - Sizing and Selection.
[ "r", "Calculates", "correction", "due", "to", "steam", "superheat", "for", "steam", "flow", "for", "use", "in", "API", "520", "relief", "valve", "sizing", ".", "2D", "interpolation", "among", "a", "table", "with", "28", "pressures", "and", "10", "temperatures", "is", "performed", "." ]
57f556752e039f1d3e5a822f408c184783db2828
https://github.com/CalebBell/fluids/blob/57f556752e039f1d3e5a822f408c184783db2828/fluids/safety_valve.py#L319-L361
8,316
CalebBell/fluids
fluids/safety_valve.py
API520_W
def API520_W(Pset, Pback): r'''Calculates capacity correction due to backpressure on balanced spring-loaded PRVs in liquid service. For pilot operated valves, this is always 1. Applicable up to 50% of the percent gauge backpressure, For use in API 520 relief valve sizing. 1D interpolation among a table with 53 backpressures is performed. Parameters ---------- Pset : float Set pressure for relief [Pa] Pback : float Backpressure, [Pa] Returns ------- KW : float Correction due to liquid backpressure [-] Notes ----- If the calculated gauge backpressure is less than 15%, a value of 1 is returned. Examples -------- Custom example from figure 31: >>> API520_W(1E6, 3E5) # 22% overpressure 0.9511471848008564 References ---------- .. [1] API Standard 520, Part 1 - Sizing and Selection. ''' gauge_backpressure = (Pback-atm)/(Pset-atm)*100.0 # in percent if gauge_backpressure < 15.0: return 1.0 return interp(gauge_backpressure, Kw_x, Kw_y)
python
def API520_W(Pset, Pback): r'''Calculates capacity correction due to backpressure on balanced spring-loaded PRVs in liquid service. For pilot operated valves, this is always 1. Applicable up to 50% of the percent gauge backpressure, For use in API 520 relief valve sizing. 1D interpolation among a table with 53 backpressures is performed. Parameters ---------- Pset : float Set pressure for relief [Pa] Pback : float Backpressure, [Pa] Returns ------- KW : float Correction due to liquid backpressure [-] Notes ----- If the calculated gauge backpressure is less than 15%, a value of 1 is returned. Examples -------- Custom example from figure 31: >>> API520_W(1E6, 3E5) # 22% overpressure 0.9511471848008564 References ---------- .. [1] API Standard 520, Part 1 - Sizing and Selection. ''' gauge_backpressure = (Pback-atm)/(Pset-atm)*100.0 # in percent if gauge_backpressure < 15.0: return 1.0 return interp(gauge_backpressure, Kw_x, Kw_y)
[ "def", "API520_W", "(", "Pset", ",", "Pback", ")", ":", "gauge_backpressure", "=", "(", "Pback", "-", "atm", ")", "/", "(", "Pset", "-", "atm", ")", "*", "100.0", "# in percent", "if", "gauge_backpressure", "<", "15.0", ":", "return", "1.0", "return", "interp", "(", "gauge_backpressure", ",", "Kw_x", ",", "Kw_y", ")" ]
r'''Calculates capacity correction due to backpressure on balanced spring-loaded PRVs in liquid service. For pilot operated valves, this is always 1. Applicable up to 50% of the percent gauge backpressure, For use in API 520 relief valve sizing. 1D interpolation among a table with 53 backpressures is performed. Parameters ---------- Pset : float Set pressure for relief [Pa] Pback : float Backpressure, [Pa] Returns ------- KW : float Correction due to liquid backpressure [-] Notes ----- If the calculated gauge backpressure is less than 15%, a value of 1 is returned. Examples -------- Custom example from figure 31: >>> API520_W(1E6, 3E5) # 22% overpressure 0.9511471848008564 References ---------- .. [1] API Standard 520, Part 1 - Sizing and Selection.
[ "r", "Calculates", "capacity", "correction", "due", "to", "backpressure", "on", "balanced", "spring", "-", "loaded", "PRVs", "in", "liquid", "service", ".", "For", "pilot", "operated", "valves", "this", "is", "always", "1", ".", "Applicable", "up", "to", "50%", "of", "the", "percent", "gauge", "backpressure", "For", "use", "in", "API", "520", "relief", "valve", "sizing", ".", "1D", "interpolation", "among", "a", "table", "with", "53", "backpressures", "is", "performed", "." ]
57f556752e039f1d3e5a822f408c184783db2828
https://github.com/CalebBell/fluids/blob/57f556752e039f1d3e5a822f408c184783db2828/fluids/safety_valve.py#L383-L421
8,317
CalebBell/fluids
fluids/safety_valve.py
API520_B
def API520_B(Pset, Pback, overpressure=0.1): r'''Calculates capacity correction due to backpressure on balanced spring-loaded PRVs in vapor service. For pilot operated valves, this is always 1. Applicable up to 50% of the percent gauge backpressure, For use in API 520 relief valve sizing. 1D interpolation among a table with 53 backpressures is performed. Parameters ---------- Pset : float Set pressure for relief [Pa] Pback : float Backpressure, [Pa] overpressure : float, optional The maximum fraction overpressure; one of 0.1, 0.16, or 0.21, [] Returns ------- Kb : float Correction due to vapor backpressure [-] Notes ----- If the calculated gauge backpressure is less than 30%, 38%, or 50% for overpressures of 0.1, 0.16, or 0.21, a value of 1 is returned. Percent gauge backpressure must be under 50%. Examples -------- Custom examples from figure 30: >>> API520_B(1E6, 5E5) 0.7929945420944432 References ---------- .. [1] API Standard 520, Part 1 - Sizing and Selection. ''' gauge_backpressure = (Pback-atm)/(Pset-atm)*100 # in percent if overpressure not in [0.1, 0.16, 0.21]: raise Exception('Only overpressure of 10%, 16%, or 21% are permitted') if (overpressure == 0.1 and gauge_backpressure < 30) or ( overpressure == 0.16 and gauge_backpressure < 38) or ( overpressure == 0.21 and gauge_backpressure < 50): return 1 elif gauge_backpressure > 50: raise Exception('Gauge pressure must be < 50%') if overpressure == 0.16: Kb = interp(gauge_backpressure, Kb_16_over_x, Kb_16_over_y) elif overpressure == 0.1: Kb = interp(gauge_backpressure, Kb_10_over_x, Kb_10_over_y) return Kb
python
def API520_B(Pset, Pback, overpressure=0.1): r'''Calculates capacity correction due to backpressure on balanced spring-loaded PRVs in vapor service. For pilot operated valves, this is always 1. Applicable up to 50% of the percent gauge backpressure, For use in API 520 relief valve sizing. 1D interpolation among a table with 53 backpressures is performed. Parameters ---------- Pset : float Set pressure for relief [Pa] Pback : float Backpressure, [Pa] overpressure : float, optional The maximum fraction overpressure; one of 0.1, 0.16, or 0.21, [] Returns ------- Kb : float Correction due to vapor backpressure [-] Notes ----- If the calculated gauge backpressure is less than 30%, 38%, or 50% for overpressures of 0.1, 0.16, or 0.21, a value of 1 is returned. Percent gauge backpressure must be under 50%. Examples -------- Custom examples from figure 30: >>> API520_B(1E6, 5E5) 0.7929945420944432 References ---------- .. [1] API Standard 520, Part 1 - Sizing and Selection. ''' gauge_backpressure = (Pback-atm)/(Pset-atm)*100 # in percent if overpressure not in [0.1, 0.16, 0.21]: raise Exception('Only overpressure of 10%, 16%, or 21% are permitted') if (overpressure == 0.1 and gauge_backpressure < 30) or ( overpressure == 0.16 and gauge_backpressure < 38) or ( overpressure == 0.21 and gauge_backpressure < 50): return 1 elif gauge_backpressure > 50: raise Exception('Gauge pressure must be < 50%') if overpressure == 0.16: Kb = interp(gauge_backpressure, Kb_16_over_x, Kb_16_over_y) elif overpressure == 0.1: Kb = interp(gauge_backpressure, Kb_10_over_x, Kb_10_over_y) return Kb
[ "def", "API520_B", "(", "Pset", ",", "Pback", ",", "overpressure", "=", "0.1", ")", ":", "gauge_backpressure", "=", "(", "Pback", "-", "atm", ")", "/", "(", "Pset", "-", "atm", ")", "*", "100", "# in percent", "if", "overpressure", "not", "in", "[", "0.1", ",", "0.16", ",", "0.21", "]", ":", "raise", "Exception", "(", "'Only overpressure of 10%, 16%, or 21% are permitted'", ")", "if", "(", "overpressure", "==", "0.1", "and", "gauge_backpressure", "<", "30", ")", "or", "(", "overpressure", "==", "0.16", "and", "gauge_backpressure", "<", "38", ")", "or", "(", "overpressure", "==", "0.21", "and", "gauge_backpressure", "<", "50", ")", ":", "return", "1", "elif", "gauge_backpressure", ">", "50", ":", "raise", "Exception", "(", "'Gauge pressure must be < 50%'", ")", "if", "overpressure", "==", "0.16", ":", "Kb", "=", "interp", "(", "gauge_backpressure", ",", "Kb_16_over_x", ",", "Kb_16_over_y", ")", "elif", "overpressure", "==", "0.1", ":", "Kb", "=", "interp", "(", "gauge_backpressure", ",", "Kb_10_over_x", ",", "Kb_10_over_y", ")", "return", "Kb" ]
r'''Calculates capacity correction due to backpressure on balanced spring-loaded PRVs in vapor service. For pilot operated valves, this is always 1. Applicable up to 50% of the percent gauge backpressure, For use in API 520 relief valve sizing. 1D interpolation among a table with 53 backpressures is performed. Parameters ---------- Pset : float Set pressure for relief [Pa] Pback : float Backpressure, [Pa] overpressure : float, optional The maximum fraction overpressure; one of 0.1, 0.16, or 0.21, [] Returns ------- Kb : float Correction due to vapor backpressure [-] Notes ----- If the calculated gauge backpressure is less than 30%, 38%, or 50% for overpressures of 0.1, 0.16, or 0.21, a value of 1 is returned. Percent gauge backpressure must be under 50%. Examples -------- Custom examples from figure 30: >>> API520_B(1E6, 5E5) 0.7929945420944432 References ---------- .. [1] API Standard 520, Part 1 - Sizing and Selection.
[ "r", "Calculates", "capacity", "correction", "due", "to", "backpressure", "on", "balanced", "spring", "-", "loaded", "PRVs", "in", "vapor", "service", ".", "For", "pilot", "operated", "valves", "this", "is", "always", "1", ".", "Applicable", "up", "to", "50%", "of", "the", "percent", "gauge", "backpressure", "For", "use", "in", "API", "520", "relief", "valve", "sizing", ".", "1D", "interpolation", "among", "a", "table", "with", "53", "backpressures", "is", "performed", "." ]
57f556752e039f1d3e5a822f408c184783db2828
https://github.com/CalebBell/fluids/blob/57f556752e039f1d3e5a822f408c184783db2828/fluids/safety_valve.py#L452-L504
8,318
CalebBell/fluids
fluids/safety_valve.py
API520_A_g
def API520_A_g(m, T, Z, MW, k, P1, P2=101325, Kd=0.975, Kb=1, Kc=1): r'''Calculates required relief valve area for an API 520 valve passing a gas or a vapor, at either critical or sub-critical flow. For critical flow: .. math:: A = \frac{m}{CK_dP_1K_bK_c}\sqrt{\frac{TZ}{M}} For sub-critical flow: .. math:: A = \frac{17.9m}{F_2K_dK_c}\sqrt{\frac{TZ}{MP_1(P_1-P_2)}} Parameters ---------- m : float Mass flow rate of vapor through the valve, [kg/s] T : float Temperature of vapor entering the valve, [K] Z : float Compressibility factor of the vapor, [-] MW : float Molecular weight of the vapor, [g/mol] k : float Isentropic coefficient or ideal gas heat capacity ratio [-] P1 : float Upstream relieving pressure; the set pressure plus the allowable overpressure, plus atmospheric pressure, [Pa] P2 : float, optional Built-up backpressure; the increase in pressure during flow at the outlet of a pressure-relief device after it opens, [Pa] Kd : float, optional The effective coefficient of discharge, from the manufacturer or for preliminary sizing, using 0.975 normally or 0.62 when used with a rupture disc as described in [1]_, [] Kb : float, optional Correction due to vapor backpressure [-] Kc : float, optional Combination correction factor for installation with a ruture disk upstream of the PRV, [] Returns ------- A : float Minimum area for relief valve according to [1]_, [m^2] Notes ----- Units are interlally kg/hr, kPa, and mm^2 to match [1]_. Examples -------- Example 1 from [1]_ for critical flow, matches: >>> API520_A_g(m=24270/3600., T=348., Z=0.90, MW=51., k=1.11, P1=670E3, Kb=1, Kc=1) 0.0036990460646834414 Example 2 from [1]_ for sub-critical flow, matches: >>> API520_A_g(m=24270/3600., T=348., Z=0.90, MW=51., k=1.11, P1=670E3, P2=532E3, Kd=0.975, Kb=1, Kc=1) 0.004248358775943481 References ---------- .. [1] API Standard 520, Part 1 - Sizing and Selection. ''' P1, P2 = P1/1000., P2/1000. # Pa to Kpa in the standard m = m*3600. # kg/s to kg/hr if is_critical_flow(P1, P2, k): C = API520_C(k) A = m/(C*Kd*Kb*Kc*P1)*(T*Z/MW)**0.5 else: F2 = API520_F2(k, P1, P2) A = 17.9*m/(F2*Kd*Kc)*(T*Z/(MW*P1*(P1-P2)))**0.5 return A*0.001**2
python
def API520_A_g(m, T, Z, MW, k, P1, P2=101325, Kd=0.975, Kb=1, Kc=1): r'''Calculates required relief valve area for an API 520 valve passing a gas or a vapor, at either critical or sub-critical flow. For critical flow: .. math:: A = \frac{m}{CK_dP_1K_bK_c}\sqrt{\frac{TZ}{M}} For sub-critical flow: .. math:: A = \frac{17.9m}{F_2K_dK_c}\sqrt{\frac{TZ}{MP_1(P_1-P_2)}} Parameters ---------- m : float Mass flow rate of vapor through the valve, [kg/s] T : float Temperature of vapor entering the valve, [K] Z : float Compressibility factor of the vapor, [-] MW : float Molecular weight of the vapor, [g/mol] k : float Isentropic coefficient or ideal gas heat capacity ratio [-] P1 : float Upstream relieving pressure; the set pressure plus the allowable overpressure, plus atmospheric pressure, [Pa] P2 : float, optional Built-up backpressure; the increase in pressure during flow at the outlet of a pressure-relief device after it opens, [Pa] Kd : float, optional The effective coefficient of discharge, from the manufacturer or for preliminary sizing, using 0.975 normally or 0.62 when used with a rupture disc as described in [1]_, [] Kb : float, optional Correction due to vapor backpressure [-] Kc : float, optional Combination correction factor for installation with a ruture disk upstream of the PRV, [] Returns ------- A : float Minimum area for relief valve according to [1]_, [m^2] Notes ----- Units are interlally kg/hr, kPa, and mm^2 to match [1]_. Examples -------- Example 1 from [1]_ for critical flow, matches: >>> API520_A_g(m=24270/3600., T=348., Z=0.90, MW=51., k=1.11, P1=670E3, Kb=1, Kc=1) 0.0036990460646834414 Example 2 from [1]_ for sub-critical flow, matches: >>> API520_A_g(m=24270/3600., T=348., Z=0.90, MW=51., k=1.11, P1=670E3, P2=532E3, Kd=0.975, Kb=1, Kc=1) 0.004248358775943481 References ---------- .. [1] API Standard 520, Part 1 - Sizing and Selection. ''' P1, P2 = P1/1000., P2/1000. # Pa to Kpa in the standard m = m*3600. # kg/s to kg/hr if is_critical_flow(P1, P2, k): C = API520_C(k) A = m/(C*Kd*Kb*Kc*P1)*(T*Z/MW)**0.5 else: F2 = API520_F2(k, P1, P2) A = 17.9*m/(F2*Kd*Kc)*(T*Z/(MW*P1*(P1-P2)))**0.5 return A*0.001**2
[ "def", "API520_A_g", "(", "m", ",", "T", ",", "Z", ",", "MW", ",", "k", ",", "P1", ",", "P2", "=", "101325", ",", "Kd", "=", "0.975", ",", "Kb", "=", "1", ",", "Kc", "=", "1", ")", ":", "P1", ",", "P2", "=", "P1", "/", "1000.", ",", "P2", "/", "1000.", "# Pa to Kpa in the standard", "m", "=", "m", "*", "3600.", "# kg/s to kg/hr", "if", "is_critical_flow", "(", "P1", ",", "P2", ",", "k", ")", ":", "C", "=", "API520_C", "(", "k", ")", "A", "=", "m", "/", "(", "C", "*", "Kd", "*", "Kb", "*", "Kc", "*", "P1", ")", "*", "(", "T", "*", "Z", "/", "MW", ")", "**", "0.5", "else", ":", "F2", "=", "API520_F2", "(", "k", ",", "P1", ",", "P2", ")", "A", "=", "17.9", "*", "m", "/", "(", "F2", "*", "Kd", "*", "Kc", ")", "*", "(", "T", "*", "Z", "/", "(", "MW", "*", "P1", "*", "(", "P1", "-", "P2", ")", ")", ")", "**", "0.5", "return", "A", "*", "0.001", "**", "2" ]
r'''Calculates required relief valve area for an API 520 valve passing a gas or a vapor, at either critical or sub-critical flow. For critical flow: .. math:: A = \frac{m}{CK_dP_1K_bK_c}\sqrt{\frac{TZ}{M}} For sub-critical flow: .. math:: A = \frac{17.9m}{F_2K_dK_c}\sqrt{\frac{TZ}{MP_1(P_1-P_2)}} Parameters ---------- m : float Mass flow rate of vapor through the valve, [kg/s] T : float Temperature of vapor entering the valve, [K] Z : float Compressibility factor of the vapor, [-] MW : float Molecular weight of the vapor, [g/mol] k : float Isentropic coefficient or ideal gas heat capacity ratio [-] P1 : float Upstream relieving pressure; the set pressure plus the allowable overpressure, plus atmospheric pressure, [Pa] P2 : float, optional Built-up backpressure; the increase in pressure during flow at the outlet of a pressure-relief device after it opens, [Pa] Kd : float, optional The effective coefficient of discharge, from the manufacturer or for preliminary sizing, using 0.975 normally or 0.62 when used with a rupture disc as described in [1]_, [] Kb : float, optional Correction due to vapor backpressure [-] Kc : float, optional Combination correction factor for installation with a ruture disk upstream of the PRV, [] Returns ------- A : float Minimum area for relief valve according to [1]_, [m^2] Notes ----- Units are interlally kg/hr, kPa, and mm^2 to match [1]_. Examples -------- Example 1 from [1]_ for critical flow, matches: >>> API520_A_g(m=24270/3600., T=348., Z=0.90, MW=51., k=1.11, P1=670E3, Kb=1, Kc=1) 0.0036990460646834414 Example 2 from [1]_ for sub-critical flow, matches: >>> API520_A_g(m=24270/3600., T=348., Z=0.90, MW=51., k=1.11, P1=670E3, P2=532E3, Kd=0.975, Kb=1, Kc=1) 0.004248358775943481 References ---------- .. [1] API Standard 520, Part 1 - Sizing and Selection.
[ "r", "Calculates", "required", "relief", "valve", "area", "for", "an", "API", "520", "valve", "passing", "a", "gas", "or", "a", "vapor", "at", "either", "critical", "or", "sub", "-", "critical", "flow", "." ]
57f556752e039f1d3e5a822f408c184783db2828
https://github.com/CalebBell/fluids/blob/57f556752e039f1d3e5a822f408c184783db2828/fluids/safety_valve.py#L507-L582
8,319
CalebBell/fluids
fluids/safety_valve.py
API520_A_steam
def API520_A_steam(m, T, P1, Kd=0.975, Kb=1, Kc=1): r'''Calculates required relief valve area for an API 520 valve passing a steam, at either saturation or superheat but not partially condensed. .. math:: A = \frac{190.5m}{P_1 K_d K_b K_c K_N K_{SH}} Parameters ---------- m : float Mass flow rate of steam through the valve, [kg/s] T : float Temperature of steam entering the valve, [K] P1 : float Upstream relieving pressure; the set pressure plus the allowable overpressure, plus atmospheric pressure, [Pa] Kd : float, optional The effective coefficient of discharge, from the manufacturer or for preliminary sizing, using 0.975 normally or 0.62 when used with a rupture disc as described in [1]_, [] Kb : float, optional Correction due to vapor backpressure [-] Kc : float, optional Combination correction factor for installation with a rupture disk upstream of the PRV, [] Returns ------- A : float Minimum area for relief valve according to [1]_, [m^2] Notes ----- Units are interlally kg/hr, kPa, and mm^2 to match [1]_. With the provided temperature and pressure, the KN coefficient is calculated with the function API520_N; as is the superheat correction KSH, with the function API520_SH. Examples -------- Example 4 from [1]_, matches: >>> API520_A_steam(m=69615/3600., T=592.5, P1=12236E3, Kd=0.975, Kb=1, Kc=1) 0.0011034712423692733 References ---------- .. [1] API Standard 520, Part 1 - Sizing and Selection. ''' KN = API520_N(P1) KSH = API520_SH(T, P1) P1 = P1/1000. # Pa to kPa m = m*3600. # kg/s to kg/hr A = 190.5*m/(P1*Kd*Kb*Kc*KN*KSH) return A*0.001**2
python
def API520_A_steam(m, T, P1, Kd=0.975, Kb=1, Kc=1): r'''Calculates required relief valve area for an API 520 valve passing a steam, at either saturation or superheat but not partially condensed. .. math:: A = \frac{190.5m}{P_1 K_d K_b K_c K_N K_{SH}} Parameters ---------- m : float Mass flow rate of steam through the valve, [kg/s] T : float Temperature of steam entering the valve, [K] P1 : float Upstream relieving pressure; the set pressure plus the allowable overpressure, plus atmospheric pressure, [Pa] Kd : float, optional The effective coefficient of discharge, from the manufacturer or for preliminary sizing, using 0.975 normally or 0.62 when used with a rupture disc as described in [1]_, [] Kb : float, optional Correction due to vapor backpressure [-] Kc : float, optional Combination correction factor for installation with a rupture disk upstream of the PRV, [] Returns ------- A : float Minimum area for relief valve according to [1]_, [m^2] Notes ----- Units are interlally kg/hr, kPa, and mm^2 to match [1]_. With the provided temperature and pressure, the KN coefficient is calculated with the function API520_N; as is the superheat correction KSH, with the function API520_SH. Examples -------- Example 4 from [1]_, matches: >>> API520_A_steam(m=69615/3600., T=592.5, P1=12236E3, Kd=0.975, Kb=1, Kc=1) 0.0011034712423692733 References ---------- .. [1] API Standard 520, Part 1 - Sizing and Selection. ''' KN = API520_N(P1) KSH = API520_SH(T, P1) P1 = P1/1000. # Pa to kPa m = m*3600. # kg/s to kg/hr A = 190.5*m/(P1*Kd*Kb*Kc*KN*KSH) return A*0.001**2
[ "def", "API520_A_steam", "(", "m", ",", "T", ",", "P1", ",", "Kd", "=", "0.975", ",", "Kb", "=", "1", ",", "Kc", "=", "1", ")", ":", "KN", "=", "API520_N", "(", "P1", ")", "KSH", "=", "API520_SH", "(", "T", ",", "P1", ")", "P1", "=", "P1", "/", "1000.", "# Pa to kPa", "m", "=", "m", "*", "3600.", "# kg/s to kg/hr", "A", "=", "190.5", "*", "m", "/", "(", "P1", "*", "Kd", "*", "Kb", "*", "Kc", "*", "KN", "*", "KSH", ")", "return", "A", "*", "0.001", "**", "2" ]
r'''Calculates required relief valve area for an API 520 valve passing a steam, at either saturation or superheat but not partially condensed. .. math:: A = \frac{190.5m}{P_1 K_d K_b K_c K_N K_{SH}} Parameters ---------- m : float Mass flow rate of steam through the valve, [kg/s] T : float Temperature of steam entering the valve, [K] P1 : float Upstream relieving pressure; the set pressure plus the allowable overpressure, plus atmospheric pressure, [Pa] Kd : float, optional The effective coefficient of discharge, from the manufacturer or for preliminary sizing, using 0.975 normally or 0.62 when used with a rupture disc as described in [1]_, [] Kb : float, optional Correction due to vapor backpressure [-] Kc : float, optional Combination correction factor for installation with a rupture disk upstream of the PRV, [] Returns ------- A : float Minimum area for relief valve according to [1]_, [m^2] Notes ----- Units are interlally kg/hr, kPa, and mm^2 to match [1]_. With the provided temperature and pressure, the KN coefficient is calculated with the function API520_N; as is the superheat correction KSH, with the function API520_SH. Examples -------- Example 4 from [1]_, matches: >>> API520_A_steam(m=69615/3600., T=592.5, P1=12236E3, Kd=0.975, Kb=1, Kc=1) 0.0011034712423692733 References ---------- .. [1] API Standard 520, Part 1 - Sizing and Selection.
[ "r", "Calculates", "required", "relief", "valve", "area", "for", "an", "API", "520", "valve", "passing", "a", "steam", "at", "either", "saturation", "or", "superheat", "but", "not", "partially", "condensed", "." ]
57f556752e039f1d3e5a822f408c184783db2828
https://github.com/CalebBell/fluids/blob/57f556752e039f1d3e5a822f408c184783db2828/fluids/safety_valve.py#L585-L639
8,320
xhtml2pdf/xhtml2pdf
xhtml2pdf/context.py
pisaContext.getFile
def getFile(self, name, relative=None): """ Returns a file name or None """ if self.pathCallback is not None: return getFile(self._getFileDeprecated(name, relative)) return getFile(name, relative or self.pathDirectory)
python
def getFile(self, name, relative=None): """ Returns a file name or None """ if self.pathCallback is not None: return getFile(self._getFileDeprecated(name, relative)) return getFile(name, relative or self.pathDirectory)
[ "def", "getFile", "(", "self", ",", "name", ",", "relative", "=", "None", ")", ":", "if", "self", ".", "pathCallback", "is", "not", "None", ":", "return", "getFile", "(", "self", ".", "_getFileDeprecated", "(", "name", ",", "relative", ")", ")", "return", "getFile", "(", "name", ",", "relative", "or", "self", ".", "pathDirectory", ")" ]
Returns a file name or None
[ "Returns", "a", "file", "name", "or", "None" ]
230357a392f48816532d3c2fa082a680b80ece48
https://github.com/xhtml2pdf/xhtml2pdf/blob/230357a392f48816532d3c2fa082a680b80ece48/xhtml2pdf/context.py#L812-L818
8,321
xhtml2pdf/xhtml2pdf
xhtml2pdf/context.py
pisaContext.getFontName
def getFontName(self, names, default="helvetica"): """ Name of a font """ # print names, self.fontList if type(names) is not ListType: if type(names) not in six.string_types: names = str(names) names = names.strip().split(",") for name in names: if type(name) not in six.string_types: name = str(name) font = self.fontList.get(name.strip().lower(), None) if font is not None: return font return self.fontList.get(default, None)
python
def getFontName(self, names, default="helvetica"): """ Name of a font """ # print names, self.fontList if type(names) is not ListType: if type(names) not in six.string_types: names = str(names) names = names.strip().split(",") for name in names: if type(name) not in six.string_types: name = str(name) font = self.fontList.get(name.strip().lower(), None) if font is not None: return font return self.fontList.get(default, None)
[ "def", "getFontName", "(", "self", ",", "names", ",", "default", "=", "\"helvetica\"", ")", ":", "# print names, self.fontList", "if", "type", "(", "names", ")", "is", "not", "ListType", ":", "if", "type", "(", "names", ")", "not", "in", "six", ".", "string_types", ":", "names", "=", "str", "(", "names", ")", "names", "=", "names", ".", "strip", "(", ")", ".", "split", "(", "\",\"", ")", "for", "name", "in", "names", ":", "if", "type", "(", "name", ")", "not", "in", "six", ".", "string_types", ":", "name", "=", "str", "(", "name", ")", "font", "=", "self", ".", "fontList", ".", "get", "(", "name", ".", "strip", "(", ")", ".", "lower", "(", ")", ",", "None", ")", "if", "font", "is", "not", "None", ":", "return", "font", "return", "self", ".", "fontList", ".", "get", "(", "default", ",", "None", ")" ]
Name of a font
[ "Name", "of", "a", "font" ]
230357a392f48816532d3c2fa082a680b80ece48
https://github.com/xhtml2pdf/xhtml2pdf/blob/230357a392f48816532d3c2fa082a680b80ece48/xhtml2pdf/context.py#L820-L835
8,322
xhtml2pdf/xhtml2pdf
xhtml2pdf/parser.py
pisaPreLoop
def pisaPreLoop(node, context, collect=False): """ Collect all CSS definitions """ data = u"" if node.nodeType == Node.TEXT_NODE and collect: data = node.data elif node.nodeType == Node.ELEMENT_NODE: name = node.tagName.lower() if name in ("style", "link"): attr = pisaGetAttributes(context, name, node.attributes) media = [x.strip() for x in attr.media.lower().split(",") if x.strip()] if attr.get("type", "").lower() in ("", "text/css") and \ (not media or "all" in media or "print" in media or "pdf" in media): if name == "style": for node in node.childNodes: data += pisaPreLoop(node, context, collect=True) context.addCSS(data) return u"" if name == "link" and attr.href and attr.rel.lower() == "stylesheet": # print "CSS LINK", attr context.addCSS('\n@import "%s" %s;' % (attr.href, ",".join(media))) for node in node.childNodes: result = pisaPreLoop(node, context, collect=collect) if collect: data += result return data
python
def pisaPreLoop(node, context, collect=False): """ Collect all CSS definitions """ data = u"" if node.nodeType == Node.TEXT_NODE and collect: data = node.data elif node.nodeType == Node.ELEMENT_NODE: name = node.tagName.lower() if name in ("style", "link"): attr = pisaGetAttributes(context, name, node.attributes) media = [x.strip() for x in attr.media.lower().split(",") if x.strip()] if attr.get("type", "").lower() in ("", "text/css") and \ (not media or "all" in media or "print" in media or "pdf" in media): if name == "style": for node in node.childNodes: data += pisaPreLoop(node, context, collect=True) context.addCSS(data) return u"" if name == "link" and attr.href and attr.rel.lower() == "stylesheet": # print "CSS LINK", attr context.addCSS('\n@import "%s" %s;' % (attr.href, ",".join(media))) for node in node.childNodes: result = pisaPreLoop(node, context, collect=collect) if collect: data += result return data
[ "def", "pisaPreLoop", "(", "node", ",", "context", ",", "collect", "=", "False", ")", ":", "data", "=", "u\"\"", "if", "node", ".", "nodeType", "==", "Node", ".", "TEXT_NODE", "and", "collect", ":", "data", "=", "node", ".", "data", "elif", "node", ".", "nodeType", "==", "Node", ".", "ELEMENT_NODE", ":", "name", "=", "node", ".", "tagName", ".", "lower", "(", ")", "if", "name", "in", "(", "\"style\"", ",", "\"link\"", ")", ":", "attr", "=", "pisaGetAttributes", "(", "context", ",", "name", ",", "node", ".", "attributes", ")", "media", "=", "[", "x", ".", "strip", "(", ")", "for", "x", "in", "attr", ".", "media", ".", "lower", "(", ")", ".", "split", "(", "\",\"", ")", "if", "x", ".", "strip", "(", ")", "]", "if", "attr", ".", "get", "(", "\"type\"", ",", "\"\"", ")", ".", "lower", "(", ")", "in", "(", "\"\"", ",", "\"text/css\"", ")", "and", "(", "not", "media", "or", "\"all\"", "in", "media", "or", "\"print\"", "in", "media", "or", "\"pdf\"", "in", "media", ")", ":", "if", "name", "==", "\"style\"", ":", "for", "node", "in", "node", ".", "childNodes", ":", "data", "+=", "pisaPreLoop", "(", "node", ",", "context", ",", "collect", "=", "True", ")", "context", ".", "addCSS", "(", "data", ")", "return", "u\"\"", "if", "name", "==", "\"link\"", "and", "attr", ".", "href", "and", "attr", ".", "rel", ".", "lower", "(", ")", "==", "\"stylesheet\"", ":", "# print \"CSS LINK\", attr", "context", ".", "addCSS", "(", "'\\n@import \"%s\" %s;'", "%", "(", "attr", ".", "href", ",", "\",\"", ".", "join", "(", "media", ")", ")", ")", "for", "node", "in", "node", ".", "childNodes", ":", "result", "=", "pisaPreLoop", "(", "node", ",", "context", ",", "collect", "=", "collect", ")", "if", "collect", ":", "data", "+=", "result", "return", "data" ]
Collect all CSS definitions
[ "Collect", "all", "CSS", "definitions" ]
230357a392f48816532d3c2fa082a680b80ece48
https://github.com/xhtml2pdf/xhtml2pdf/blob/230357a392f48816532d3c2fa082a680b80ece48/xhtml2pdf/parser.py#L440-L476
8,323
xhtml2pdf/xhtml2pdf
xhtml2pdf/parser.py
pisaParser
def pisaParser(src, context, default_css="", xhtml=False, encoding=None, xml_output=None): """ - Parse HTML and get miniDOM - Extract CSS informations, add default CSS, parse CSS - Handle the document DOM itself and build reportlab story - Return Context object """ global CSSAttrCache CSSAttrCache = {} if xhtml: # TODO: XHTMLParser doesn't see to exist... parser = html5lib.XHTMLParser(tree=treebuilders.getTreeBuilder("dom")) else: parser = html5lib.HTMLParser(tree=treebuilders.getTreeBuilder("dom")) if isinstance(src, six.text_type): # If an encoding was provided, do not change it. if not encoding: encoding = "utf-8" src = src.encode(encoding) src = pisaTempFile(src, capacity=context.capacity) # # Test for the restrictions of html5lib # if encoding: # # Workaround for html5lib<0.11.1 # if hasattr(inputstream, "isValidEncoding"): # if encoding.strip().lower() == "utf8": # encoding = "utf-8" # if not inputstream.isValidEncoding(encoding): # log.error("%r is not a valid encoding e.g. 'utf8' is not valid but 'utf-8' is!", encoding) # else: # if inputstream.codecName(encoding) is None: # log.error("%r is not a valid encoding", encoding) document = parser.parse( src, ) # encoding=encoding) if xml_output: if encoding: xml_output.write(document.toprettyxml(encoding=encoding)) else: xml_output.write(document.toprettyxml(encoding="utf8")) if default_css: context.addDefaultCSS(default_css) pisaPreLoop(document, context) # try: context.parseCSS() # except: # context.cssText = DEFAULT_CSS # context.parseCSS() # context.debug(9, pprint.pformat(context.css)) pisaLoop(document, context) return context
python
def pisaParser(src, context, default_css="", xhtml=False, encoding=None, xml_output=None): """ - Parse HTML and get miniDOM - Extract CSS informations, add default CSS, parse CSS - Handle the document DOM itself and build reportlab story - Return Context object """ global CSSAttrCache CSSAttrCache = {} if xhtml: # TODO: XHTMLParser doesn't see to exist... parser = html5lib.XHTMLParser(tree=treebuilders.getTreeBuilder("dom")) else: parser = html5lib.HTMLParser(tree=treebuilders.getTreeBuilder("dom")) if isinstance(src, six.text_type): # If an encoding was provided, do not change it. if not encoding: encoding = "utf-8" src = src.encode(encoding) src = pisaTempFile(src, capacity=context.capacity) # # Test for the restrictions of html5lib # if encoding: # # Workaround for html5lib<0.11.1 # if hasattr(inputstream, "isValidEncoding"): # if encoding.strip().lower() == "utf8": # encoding = "utf-8" # if not inputstream.isValidEncoding(encoding): # log.error("%r is not a valid encoding e.g. 'utf8' is not valid but 'utf-8' is!", encoding) # else: # if inputstream.codecName(encoding) is None: # log.error("%r is not a valid encoding", encoding) document = parser.parse( src, ) # encoding=encoding) if xml_output: if encoding: xml_output.write(document.toprettyxml(encoding=encoding)) else: xml_output.write(document.toprettyxml(encoding="utf8")) if default_css: context.addDefaultCSS(default_css) pisaPreLoop(document, context) # try: context.parseCSS() # except: # context.cssText = DEFAULT_CSS # context.parseCSS() # context.debug(9, pprint.pformat(context.css)) pisaLoop(document, context) return context
[ "def", "pisaParser", "(", "src", ",", "context", ",", "default_css", "=", "\"\"", ",", "xhtml", "=", "False", ",", "encoding", "=", "None", ",", "xml_output", "=", "None", ")", ":", "global", "CSSAttrCache", "CSSAttrCache", "=", "{", "}", "if", "xhtml", ":", "# TODO: XHTMLParser doesn't see to exist...", "parser", "=", "html5lib", ".", "XHTMLParser", "(", "tree", "=", "treebuilders", ".", "getTreeBuilder", "(", "\"dom\"", ")", ")", "else", ":", "parser", "=", "html5lib", ".", "HTMLParser", "(", "tree", "=", "treebuilders", ".", "getTreeBuilder", "(", "\"dom\"", ")", ")", "if", "isinstance", "(", "src", ",", "six", ".", "text_type", ")", ":", "# If an encoding was provided, do not change it.", "if", "not", "encoding", ":", "encoding", "=", "\"utf-8\"", "src", "=", "src", ".", "encode", "(", "encoding", ")", "src", "=", "pisaTempFile", "(", "src", ",", "capacity", "=", "context", ".", "capacity", ")", "# # Test for the restrictions of html5lib", "# if encoding:", "# # Workaround for html5lib<0.11.1", "# if hasattr(inputstream, \"isValidEncoding\"):", "# if encoding.strip().lower() == \"utf8\":", "# encoding = \"utf-8\"", "# if not inputstream.isValidEncoding(encoding):", "# log.error(\"%r is not a valid encoding e.g. 'utf8' is not valid but 'utf-8' is!\", encoding)", "# else:", "# if inputstream.codecName(encoding) is None:", "# log.error(\"%r is not a valid encoding\", encoding)", "document", "=", "parser", ".", "parse", "(", "src", ",", ")", "# encoding=encoding)", "if", "xml_output", ":", "if", "encoding", ":", "xml_output", ".", "write", "(", "document", ".", "toprettyxml", "(", "encoding", "=", "encoding", ")", ")", "else", ":", "xml_output", ".", "write", "(", "document", ".", "toprettyxml", "(", "encoding", "=", "\"utf8\"", ")", ")", "if", "default_css", ":", "context", ".", "addDefaultCSS", "(", "default_css", ")", "pisaPreLoop", "(", "document", ",", "context", ")", "# try:", "context", ".", "parseCSS", "(", ")", "# except:", "# context.cssText = DEFAULT_CSS", "# context.parseCSS()", "# context.debug(9, pprint.pformat(context.css))", "pisaLoop", "(", "document", ",", "context", ")", "return", "context" ]
- Parse HTML and get miniDOM - Extract CSS informations, add default CSS, parse CSS - Handle the document DOM itself and build reportlab story - Return Context object
[ "-", "Parse", "HTML", "and", "get", "miniDOM", "-", "Extract", "CSS", "informations", "add", "default", "CSS", "parse", "CSS", "-", "Handle", "the", "document", "DOM", "itself", "and", "build", "reportlab", "story", "-", "Return", "Context", "object" ]
230357a392f48816532d3c2fa082a680b80ece48
https://github.com/xhtml2pdf/xhtml2pdf/blob/230357a392f48816532d3c2fa082a680b80ece48/xhtml2pdf/parser.py#L703-L760
8,324
xhtml2pdf/xhtml2pdf
xhtml2pdf/paragraph.py
Line.doLayout
def doLayout(self, width): """ Align words in previous line. """ # Calculate dimensions self.width = width font_sizes = [0] + [frag.get("fontSize", 0) for frag in self] self.fontSize = max(font_sizes) self.height = self.lineHeight = max(frag * self.LINEHEIGHT for frag in font_sizes) # Apply line height y = (self.lineHeight - self.fontSize) # / 2 for frag in self: frag["y"] = y return self.height
python
def doLayout(self, width): """ Align words in previous line. """ # Calculate dimensions self.width = width font_sizes = [0] + [frag.get("fontSize", 0) for frag in self] self.fontSize = max(font_sizes) self.height = self.lineHeight = max(frag * self.LINEHEIGHT for frag in font_sizes) # Apply line height y = (self.lineHeight - self.fontSize) # / 2 for frag in self: frag["y"] = y return self.height
[ "def", "doLayout", "(", "self", ",", "width", ")", ":", "# Calculate dimensions", "self", ".", "width", "=", "width", "font_sizes", "=", "[", "0", "]", "+", "[", "frag", ".", "get", "(", "\"fontSize\"", ",", "0", ")", "for", "frag", "in", "self", "]", "self", ".", "fontSize", "=", "max", "(", "font_sizes", ")", "self", ".", "height", "=", "self", ".", "lineHeight", "=", "max", "(", "frag", "*", "self", ".", "LINEHEIGHT", "for", "frag", "in", "font_sizes", ")", "# Apply line height", "y", "=", "(", "self", ".", "lineHeight", "-", "self", ".", "fontSize", ")", "# / 2", "for", "frag", "in", "self", ":", "frag", "[", "\"y\"", "]", "=", "y", "return", "self", ".", "height" ]
Align words in previous line.
[ "Align", "words", "in", "previous", "line", "." ]
230357a392f48816532d3c2fa082a680b80ece48
https://github.com/xhtml2pdf/xhtml2pdf/blob/230357a392f48816532d3c2fa082a680b80ece48/xhtml2pdf/paragraph.py#L276-L293
8,325
xhtml2pdf/xhtml2pdf
xhtml2pdf/paragraph.py
Text.splitIntoLines
def splitIntoLines(self, maxWidth, maxHeight, splitted=False): """ Split text into lines and calculate X positions. If we need more space in height than available we return the rest of the text """ self.lines = [] self.height = 0 self.maxWidth = self.width = maxWidth self.maxHeight = maxHeight boxStack = [] style = self.style x = 0 # Start with indent in first line of text if not splitted: x = style["textIndent"] lenText = len(self) pos = 0 while pos < lenText: # Reset values for new line posBegin = pos line = Line(style) # Update boxes for next line for box in copy.copy(boxStack): box["x"] = 0 line.append(BoxBegin(box)) while pos < lenText: # Get fragment, its width and set X frag = self[pos] fragWidth = frag["width"] frag["x"] = x pos += 1 # Keep in mind boxes for next lines if isinstance(frag, BoxBegin): boxStack.append(frag) elif isinstance(frag, BoxEnd): boxStack.pop() # If space or linebreak handle special way if frag.isSoft: if frag.isLF: line.append(frag) break # First element of line should not be a space if x == 0: continue # Keep in mind last possible line break # The elements exceed the current line elif fragWidth + x > maxWidth: break # Add fragment to line and update x x += fragWidth line.append(frag) # Remove trailing white spaces while line and line[-1].name in ("space", "br"): line.pop() # Add line to list line.dumpFragments() # if line: self.height += line.doLayout(self.width) self.lines.append(line) # If not enough space for current line force to split if self.height > maxHeight: return posBegin # Reset variables x = 0 # Apply alignment self.lines[- 1].isLast = True for line in self.lines: line.doAlignment(maxWidth, style["textAlign"]) return None
python
def splitIntoLines(self, maxWidth, maxHeight, splitted=False): """ Split text into lines and calculate X positions. If we need more space in height than available we return the rest of the text """ self.lines = [] self.height = 0 self.maxWidth = self.width = maxWidth self.maxHeight = maxHeight boxStack = [] style = self.style x = 0 # Start with indent in first line of text if not splitted: x = style["textIndent"] lenText = len(self) pos = 0 while pos < lenText: # Reset values for new line posBegin = pos line = Line(style) # Update boxes for next line for box in copy.copy(boxStack): box["x"] = 0 line.append(BoxBegin(box)) while pos < lenText: # Get fragment, its width and set X frag = self[pos] fragWidth = frag["width"] frag["x"] = x pos += 1 # Keep in mind boxes for next lines if isinstance(frag, BoxBegin): boxStack.append(frag) elif isinstance(frag, BoxEnd): boxStack.pop() # If space or linebreak handle special way if frag.isSoft: if frag.isLF: line.append(frag) break # First element of line should not be a space if x == 0: continue # Keep in mind last possible line break # The elements exceed the current line elif fragWidth + x > maxWidth: break # Add fragment to line and update x x += fragWidth line.append(frag) # Remove trailing white spaces while line and line[-1].name in ("space", "br"): line.pop() # Add line to list line.dumpFragments() # if line: self.height += line.doLayout(self.width) self.lines.append(line) # If not enough space for current line force to split if self.height > maxHeight: return posBegin # Reset variables x = 0 # Apply alignment self.lines[- 1].isLast = True for line in self.lines: line.doAlignment(maxWidth, style["textAlign"]) return None
[ "def", "splitIntoLines", "(", "self", ",", "maxWidth", ",", "maxHeight", ",", "splitted", "=", "False", ")", ":", "self", ".", "lines", "=", "[", "]", "self", ".", "height", "=", "0", "self", ".", "maxWidth", "=", "self", ".", "width", "=", "maxWidth", "self", ".", "maxHeight", "=", "maxHeight", "boxStack", "=", "[", "]", "style", "=", "self", ".", "style", "x", "=", "0", "# Start with indent in first line of text", "if", "not", "splitted", ":", "x", "=", "style", "[", "\"textIndent\"", "]", "lenText", "=", "len", "(", "self", ")", "pos", "=", "0", "while", "pos", "<", "lenText", ":", "# Reset values for new line", "posBegin", "=", "pos", "line", "=", "Line", "(", "style", ")", "# Update boxes for next line", "for", "box", "in", "copy", ".", "copy", "(", "boxStack", ")", ":", "box", "[", "\"x\"", "]", "=", "0", "line", ".", "append", "(", "BoxBegin", "(", "box", ")", ")", "while", "pos", "<", "lenText", ":", "# Get fragment, its width and set X", "frag", "=", "self", "[", "pos", "]", "fragWidth", "=", "frag", "[", "\"width\"", "]", "frag", "[", "\"x\"", "]", "=", "x", "pos", "+=", "1", "# Keep in mind boxes for next lines", "if", "isinstance", "(", "frag", ",", "BoxBegin", ")", ":", "boxStack", ".", "append", "(", "frag", ")", "elif", "isinstance", "(", "frag", ",", "BoxEnd", ")", ":", "boxStack", ".", "pop", "(", ")", "# If space or linebreak handle special way", "if", "frag", ".", "isSoft", ":", "if", "frag", ".", "isLF", ":", "line", ".", "append", "(", "frag", ")", "break", "# First element of line should not be a space", "if", "x", "==", "0", ":", "continue", "# Keep in mind last possible line break", "# The elements exceed the current line", "elif", "fragWidth", "+", "x", ">", "maxWidth", ":", "break", "# Add fragment to line and update x", "x", "+=", "fragWidth", "line", ".", "append", "(", "frag", ")", "# Remove trailing white spaces", "while", "line", "and", "line", "[", "-", "1", "]", ".", "name", "in", "(", "\"space\"", ",", "\"br\"", ")", ":", "line", ".", "pop", "(", ")", "# Add line to list", "line", ".", "dumpFragments", "(", ")", "# if line:", "self", ".", "height", "+=", "line", ".", "doLayout", "(", "self", ".", "width", ")", "self", ".", "lines", ".", "append", "(", "line", ")", "# If not enough space for current line force to split", "if", "self", ".", "height", ">", "maxHeight", ":", "return", "posBegin", "# Reset variables", "x", "=", "0", "# Apply alignment", "self", ".", "lines", "[", "-", "1", "]", ".", "isLast", "=", "True", "for", "line", "in", "self", ".", "lines", ":", "line", ".", "doAlignment", "(", "maxWidth", ",", "style", "[", "\"textAlign\"", "]", ")", "return", "None" ]
Split text into lines and calculate X positions. If we need more space in height than available we return the rest of the text
[ "Split", "text", "into", "lines", "and", "calculate", "X", "positions", ".", "If", "we", "need", "more", "space", "in", "height", "than", "available", "we", "return", "the", "rest", "of", "the", "text" ]
230357a392f48816532d3c2fa082a680b80ece48
https://github.com/xhtml2pdf/xhtml2pdf/blob/230357a392f48816532d3c2fa082a680b80ece48/xhtml2pdf/paragraph.py#L330-L415
8,326
xhtml2pdf/xhtml2pdf
xhtml2pdf/paragraph.py
Text.dumpLines
def dumpLines(self): """ For debugging dump all line and their content """ for i, line in enumerate(self.lines): logger.debug("Line %d:", i) logger.debug(line.dumpFragments())
python
def dumpLines(self): """ For debugging dump all line and their content """ for i, line in enumerate(self.lines): logger.debug("Line %d:", i) logger.debug(line.dumpFragments())
[ "def", "dumpLines", "(", "self", ")", ":", "for", "i", ",", "line", "in", "enumerate", "(", "self", ".", "lines", ")", ":", "logger", ".", "debug", "(", "\"Line %d:\"", ",", "i", ")", "logger", ".", "debug", "(", "line", ".", "dumpFragments", "(", ")", ")" ]
For debugging dump all line and their content
[ "For", "debugging", "dump", "all", "line", "and", "their", "content" ]
230357a392f48816532d3c2fa082a680b80ece48
https://github.com/xhtml2pdf/xhtml2pdf/blob/230357a392f48816532d3c2fa082a680b80ece48/xhtml2pdf/paragraph.py#L417-L423
8,327
xhtml2pdf/xhtml2pdf
xhtml2pdf/paragraph.py
Paragraph.wrap
def wrap(self, availWidth, availHeight): """ Determine the rectangle this paragraph really needs. """ # memorize available space self.avWidth = availWidth self.avHeight = availHeight logger.debug("*** wrap (%f, %f)", availWidth, availHeight) if not self.text: logger.debug("*** wrap (%f, %f) needed", 0, 0) return 0, 0 # Split lines width = availWidth self.splitIndex = self.text.splitIntoLines(width, availHeight) self.width, self.height = availWidth, self.text.height logger.debug("*** wrap (%f, %f) needed, splitIndex %r", self.width, self.height, self.splitIndex) return self.width, self.height
python
def wrap(self, availWidth, availHeight): """ Determine the rectangle this paragraph really needs. """ # memorize available space self.avWidth = availWidth self.avHeight = availHeight logger.debug("*** wrap (%f, %f)", availWidth, availHeight) if not self.text: logger.debug("*** wrap (%f, %f) needed", 0, 0) return 0, 0 # Split lines width = availWidth self.splitIndex = self.text.splitIntoLines(width, availHeight) self.width, self.height = availWidth, self.text.height logger.debug("*** wrap (%f, %f) needed, splitIndex %r", self.width, self.height, self.splitIndex) return self.width, self.height
[ "def", "wrap", "(", "self", ",", "availWidth", ",", "availHeight", ")", ":", "# memorize available space", "self", ".", "avWidth", "=", "availWidth", "self", ".", "avHeight", "=", "availHeight", "logger", ".", "debug", "(", "\"*** wrap (%f, %f)\"", ",", "availWidth", ",", "availHeight", ")", "if", "not", "self", ".", "text", ":", "logger", ".", "debug", "(", "\"*** wrap (%f, %f) needed\"", ",", "0", ",", "0", ")", "return", "0", ",", "0", "# Split lines", "width", "=", "availWidth", "self", ".", "splitIndex", "=", "self", ".", "text", ".", "splitIntoLines", "(", "width", ",", "availHeight", ")", "self", ".", "width", ",", "self", ".", "height", "=", "availWidth", ",", "self", ".", "text", ".", "height", "logger", ".", "debug", "(", "\"*** wrap (%f, %f) needed, splitIndex %r\"", ",", "self", ".", "width", ",", "self", ".", "height", ",", "self", ".", "splitIndex", ")", "return", "self", ".", "width", ",", "self", ".", "height" ]
Determine the rectangle this paragraph really needs.
[ "Determine", "the", "rectangle", "this", "paragraph", "really", "needs", "." ]
230357a392f48816532d3c2fa082a680b80ece48
https://github.com/xhtml2pdf/xhtml2pdf/blob/230357a392f48816532d3c2fa082a680b80ece48/xhtml2pdf/paragraph.py#L458-L481
8,328
xhtml2pdf/xhtml2pdf
xhtml2pdf/paragraph.py
Paragraph.split
def split(self, availWidth, availHeight): """ Split ourselves in two paragraphs. """ logger.debug("*** split (%f, %f)", availWidth, availHeight) splitted = [] if self.splitIndex: text1 = self.text[:self.splitIndex] text2 = self.text[self.splitIndex:] p1 = Paragraph(Text(text1), self.style, debug=self.debug) p2 = Paragraph(Text(text2), self.style, debug=self.debug, splitted=True) splitted = [p1, p2] logger.debug("*** text1 %s / text %s", len(text1), len(text2)) logger.debug('*** return %s', self.splitted) return splitted
python
def split(self, availWidth, availHeight): """ Split ourselves in two paragraphs. """ logger.debug("*** split (%f, %f)", availWidth, availHeight) splitted = [] if self.splitIndex: text1 = self.text[:self.splitIndex] text2 = self.text[self.splitIndex:] p1 = Paragraph(Text(text1), self.style, debug=self.debug) p2 = Paragraph(Text(text2), self.style, debug=self.debug, splitted=True) splitted = [p1, p2] logger.debug("*** text1 %s / text %s", len(text1), len(text2)) logger.debug('*** return %s', self.splitted) return splitted
[ "def", "split", "(", "self", ",", "availWidth", ",", "availHeight", ")", ":", "logger", ".", "debug", "(", "\"*** split (%f, %f)\"", ",", "availWidth", ",", "availHeight", ")", "splitted", "=", "[", "]", "if", "self", ".", "splitIndex", ":", "text1", "=", "self", ".", "text", "[", ":", "self", ".", "splitIndex", "]", "text2", "=", "self", ".", "text", "[", "self", ".", "splitIndex", ":", "]", "p1", "=", "Paragraph", "(", "Text", "(", "text1", ")", ",", "self", ".", "style", ",", "debug", "=", "self", ".", "debug", ")", "p2", "=", "Paragraph", "(", "Text", "(", "text2", ")", ",", "self", ".", "style", ",", "debug", "=", "self", ".", "debug", ",", "splitted", "=", "True", ")", "splitted", "=", "[", "p1", ",", "p2", "]", "logger", ".", "debug", "(", "\"*** text1 %s / text %s\"", ",", "len", "(", "text1", ")", ",", "len", "(", "text2", ")", ")", "logger", ".", "debug", "(", "'*** return %s'", ",", "self", ".", "splitted", ")", "return", "splitted" ]
Split ourselves in two paragraphs.
[ "Split", "ourselves", "in", "two", "paragraphs", "." ]
230357a392f48816532d3c2fa082a680b80ece48
https://github.com/xhtml2pdf/xhtml2pdf/blob/230357a392f48816532d3c2fa082a680b80ece48/xhtml2pdf/paragraph.py#L483-L502
8,329
xhtml2pdf/xhtml2pdf
xhtml2pdf/paragraph.py
Paragraph.draw
def draw(self): """ Render the content of the paragraph. """ logger.debug("*** draw") if not self.text: return canvas = self.canv style = self.style canvas.saveState() # Draw box arround paragraph for debugging if self.debug: bw = 0.5 bc = Color(1, 1, 0) bg = Color(0.9, 0.9, 0.9) canvas.setStrokeColor(bc) canvas.setLineWidth(bw) canvas.setFillColor(bg) canvas.rect( style.leftIndent, 0, self.width, self.height, fill=1, stroke=1) y = 0 dy = self.height for line in self.text.lines: y += line.height for frag in line: # Box if hasattr(frag, "draw"): frag.draw(canvas, dy - y) # Text if frag.get("text", ""): canvas.setFont(frag["fontName"], frag["fontSize"]) canvas.setFillColor(frag.get("color", style["color"])) canvas.drawString(frag["x"], dy - y + frag["y"], frag["text"]) # XXX LINK link = frag.get("link", None) if link: _scheme_re = re.compile('^[a-zA-Z][-+a-zA-Z0-9]+$') x, y, w, h = frag["x"], dy - y, frag["width"], frag["fontSize"] rect = (x, y, w, h) if isinstance(link, six.text_type): link = link.encode('utf8') parts = link.split(':', 1) scheme = len(parts) == 2 and parts[0].lower() or '' if _scheme_re.match(scheme) and scheme != 'document': kind = scheme.lower() == 'pdf' and 'GoToR' or 'URI' if kind == 'GoToR': link = parts[1] canvas.linkURL(link, rect, relative=1, kind=kind) else: if link[0] == '#': link = link[1:] scheme = '' canvas.linkRect("", scheme != 'document' and link or parts[1], rect, relative=1) canvas.restoreState()
python
def draw(self): """ Render the content of the paragraph. """ logger.debug("*** draw") if not self.text: return canvas = self.canv style = self.style canvas.saveState() # Draw box arround paragraph for debugging if self.debug: bw = 0.5 bc = Color(1, 1, 0) bg = Color(0.9, 0.9, 0.9) canvas.setStrokeColor(bc) canvas.setLineWidth(bw) canvas.setFillColor(bg) canvas.rect( style.leftIndent, 0, self.width, self.height, fill=1, stroke=1) y = 0 dy = self.height for line in self.text.lines: y += line.height for frag in line: # Box if hasattr(frag, "draw"): frag.draw(canvas, dy - y) # Text if frag.get("text", ""): canvas.setFont(frag["fontName"], frag["fontSize"]) canvas.setFillColor(frag.get("color", style["color"])) canvas.drawString(frag["x"], dy - y + frag["y"], frag["text"]) # XXX LINK link = frag.get("link", None) if link: _scheme_re = re.compile('^[a-zA-Z][-+a-zA-Z0-9]+$') x, y, w, h = frag["x"], dy - y, frag["width"], frag["fontSize"] rect = (x, y, w, h) if isinstance(link, six.text_type): link = link.encode('utf8') parts = link.split(':', 1) scheme = len(parts) == 2 and parts[0].lower() or '' if _scheme_re.match(scheme) and scheme != 'document': kind = scheme.lower() == 'pdf' and 'GoToR' or 'URI' if kind == 'GoToR': link = parts[1] canvas.linkURL(link, rect, relative=1, kind=kind) else: if link[0] == '#': link = link[1:] scheme = '' canvas.linkRect("", scheme != 'document' and link or parts[1], rect, relative=1) canvas.restoreState()
[ "def", "draw", "(", "self", ")", ":", "logger", ".", "debug", "(", "\"*** draw\"", ")", "if", "not", "self", ".", "text", ":", "return", "canvas", "=", "self", ".", "canv", "style", "=", "self", ".", "style", "canvas", ".", "saveState", "(", ")", "# Draw box arround paragraph for debugging", "if", "self", ".", "debug", ":", "bw", "=", "0.5", "bc", "=", "Color", "(", "1", ",", "1", ",", "0", ")", "bg", "=", "Color", "(", "0.9", ",", "0.9", ",", "0.9", ")", "canvas", ".", "setStrokeColor", "(", "bc", ")", "canvas", ".", "setLineWidth", "(", "bw", ")", "canvas", ".", "setFillColor", "(", "bg", ")", "canvas", ".", "rect", "(", "style", ".", "leftIndent", ",", "0", ",", "self", ".", "width", ",", "self", ".", "height", ",", "fill", "=", "1", ",", "stroke", "=", "1", ")", "y", "=", "0", "dy", "=", "self", ".", "height", "for", "line", "in", "self", ".", "text", ".", "lines", ":", "y", "+=", "line", ".", "height", "for", "frag", "in", "line", ":", "# Box", "if", "hasattr", "(", "frag", ",", "\"draw\"", ")", ":", "frag", ".", "draw", "(", "canvas", ",", "dy", "-", "y", ")", "# Text", "if", "frag", ".", "get", "(", "\"text\"", ",", "\"\"", ")", ":", "canvas", ".", "setFont", "(", "frag", "[", "\"fontName\"", "]", ",", "frag", "[", "\"fontSize\"", "]", ")", "canvas", ".", "setFillColor", "(", "frag", ".", "get", "(", "\"color\"", ",", "style", "[", "\"color\"", "]", ")", ")", "canvas", ".", "drawString", "(", "frag", "[", "\"x\"", "]", ",", "dy", "-", "y", "+", "frag", "[", "\"y\"", "]", ",", "frag", "[", "\"text\"", "]", ")", "# XXX LINK", "link", "=", "frag", ".", "get", "(", "\"link\"", ",", "None", ")", "if", "link", ":", "_scheme_re", "=", "re", ".", "compile", "(", "'^[a-zA-Z][-+a-zA-Z0-9]+$'", ")", "x", ",", "y", ",", "w", ",", "h", "=", "frag", "[", "\"x\"", "]", ",", "dy", "-", "y", ",", "frag", "[", "\"width\"", "]", ",", "frag", "[", "\"fontSize\"", "]", "rect", "=", "(", "x", ",", "y", ",", "w", ",", "h", ")", "if", "isinstance", "(", "link", ",", "six", ".", "text_type", ")", ":", "link", "=", "link", ".", "encode", "(", "'utf8'", ")", "parts", "=", "link", ".", "split", "(", "':'", ",", "1", ")", "scheme", "=", "len", "(", "parts", ")", "==", "2", "and", "parts", "[", "0", "]", ".", "lower", "(", ")", "or", "''", "if", "_scheme_re", ".", "match", "(", "scheme", ")", "and", "scheme", "!=", "'document'", ":", "kind", "=", "scheme", ".", "lower", "(", ")", "==", "'pdf'", "and", "'GoToR'", "or", "'URI'", "if", "kind", "==", "'GoToR'", ":", "link", "=", "parts", "[", "1", "]", "canvas", ".", "linkURL", "(", "link", ",", "rect", ",", "relative", "=", "1", ",", "kind", "=", "kind", ")", "else", ":", "if", "link", "[", "0", "]", "==", "'#'", ":", "link", "=", "link", "[", "1", ":", "]", "scheme", "=", "''", "canvas", ".", "linkRect", "(", "\"\"", ",", "scheme", "!=", "'document'", "and", "link", "or", "parts", "[", "1", "]", ",", "rect", ",", "relative", "=", "1", ")", "canvas", ".", "restoreState", "(", ")" ]
Render the content of the paragraph.
[ "Render", "the", "content", "of", "the", "paragraph", "." ]
230357a392f48816532d3c2fa082a680b80ece48
https://github.com/xhtml2pdf/xhtml2pdf/blob/230357a392f48816532d3c2fa082a680b80ece48/xhtml2pdf/paragraph.py#L504-L573
8,330
xhtml2pdf/xhtml2pdf
xhtml2pdf/pisa.py
showLogging
def showLogging(debug=False): """ Shortcut for enabling log dump """ try: log_level = logging.WARN log_format = LOG_FORMAT_DEBUG if debug: log_level = logging.DEBUG logging.basicConfig( level=log_level, format=log_format) except: logging.basicConfig()
python
def showLogging(debug=False): """ Shortcut for enabling log dump """ try: log_level = logging.WARN log_format = LOG_FORMAT_DEBUG if debug: log_level = logging.DEBUG logging.basicConfig( level=log_level, format=log_format) except: logging.basicConfig()
[ "def", "showLogging", "(", "debug", "=", "False", ")", ":", "try", ":", "log_level", "=", "logging", ".", "WARN", "log_format", "=", "LOG_FORMAT_DEBUG", "if", "debug", ":", "log_level", "=", "logging", ".", "DEBUG", "logging", ".", "basicConfig", "(", "level", "=", "log_level", ",", "format", "=", "log_format", ")", "except", ":", "logging", ".", "basicConfig", "(", ")" ]
Shortcut for enabling log dump
[ "Shortcut", "for", "enabling", "log", "dump" ]
230357a392f48816532d3c2fa082a680b80ece48
https://github.com/xhtml2pdf/xhtml2pdf/blob/230357a392f48816532d3c2fa082a680b80ece48/xhtml2pdf/pisa.py#L420-L434
8,331
xhtml2pdf/xhtml2pdf
xhtml2pdf/w3c/cssParser.py
CSSParser.parseFile
def parseFile(self, srcFile, closeFile=False): """Parses CSS file-like objects using the current cssBuilder. Use for external stylesheets.""" try: result = self.parse(srcFile.read()) finally: if closeFile: srcFile.close() return result
python
def parseFile(self, srcFile, closeFile=False): """Parses CSS file-like objects using the current cssBuilder. Use for external stylesheets.""" try: result = self.parse(srcFile.read()) finally: if closeFile: srcFile.close() return result
[ "def", "parseFile", "(", "self", ",", "srcFile", ",", "closeFile", "=", "False", ")", ":", "try", ":", "result", "=", "self", ".", "parse", "(", "srcFile", ".", "read", "(", ")", ")", "finally", ":", "if", "closeFile", ":", "srcFile", ".", "close", "(", ")", "return", "result" ]
Parses CSS file-like objects using the current cssBuilder. Use for external stylesheets.
[ "Parses", "CSS", "file", "-", "like", "objects", "using", "the", "current", "cssBuilder", ".", "Use", "for", "external", "stylesheets", "." ]
230357a392f48816532d3c2fa082a680b80ece48
https://github.com/xhtml2pdf/xhtml2pdf/blob/230357a392f48816532d3c2fa082a680b80ece48/xhtml2pdf/w3c/cssParser.py#L427-L436
8,332
xhtml2pdf/xhtml2pdf
xhtml2pdf/w3c/cssParser.py
CSSParser.parse
def parse(self, src): """Parses CSS string source using the current cssBuilder. Use for embedded stylesheets.""" self.cssBuilder.beginStylesheet() try: # XXX Some simple preprocessing src = cssSpecial.cleanupCSS(src) try: src, stylesheet = self._parseStylesheet(src) except self.ParseError as err: err.setFullCSSSource(src) raise finally: self.cssBuilder.endStylesheet() return stylesheet
python
def parse(self, src): """Parses CSS string source using the current cssBuilder. Use for embedded stylesheets.""" self.cssBuilder.beginStylesheet() try: # XXX Some simple preprocessing src = cssSpecial.cleanupCSS(src) try: src, stylesheet = self._parseStylesheet(src) except self.ParseError as err: err.setFullCSSSource(src) raise finally: self.cssBuilder.endStylesheet() return stylesheet
[ "def", "parse", "(", "self", ",", "src", ")", ":", "self", ".", "cssBuilder", ".", "beginStylesheet", "(", ")", "try", ":", "# XXX Some simple preprocessing", "src", "=", "cssSpecial", ".", "cleanupCSS", "(", "src", ")", "try", ":", "src", ",", "stylesheet", "=", "self", ".", "_parseStylesheet", "(", "src", ")", "except", "self", ".", "ParseError", "as", "err", ":", "err", ".", "setFullCSSSource", "(", "src", ")", "raise", "finally", ":", "self", ".", "cssBuilder", ".", "endStylesheet", "(", ")", "return", "stylesheet" ]
Parses CSS string source using the current cssBuilder. Use for embedded stylesheets.
[ "Parses", "CSS", "string", "source", "using", "the", "current", "cssBuilder", ".", "Use", "for", "embedded", "stylesheets", "." ]
230357a392f48816532d3c2fa082a680b80ece48
https://github.com/xhtml2pdf/xhtml2pdf/blob/230357a392f48816532d3c2fa082a680b80ece48/xhtml2pdf/w3c/cssParser.py#L439-L456
8,333
xhtml2pdf/xhtml2pdf
xhtml2pdf/w3c/cssParser.py
CSSParser.parseInline
def parseInline(self, src): """Parses CSS inline source string using the current cssBuilder. Use to parse a tag's 'sytle'-like attribute.""" self.cssBuilder.beginInline() try: try: src, properties = self._parseDeclarationGroup(src.strip(), braces=False) except self.ParseError as err: err.setFullCSSSource(src, inline=True) raise result = self.cssBuilder.inline(properties) finally: self.cssBuilder.endInline() return result
python
def parseInline(self, src): """Parses CSS inline source string using the current cssBuilder. Use to parse a tag's 'sytle'-like attribute.""" self.cssBuilder.beginInline() try: try: src, properties = self._parseDeclarationGroup(src.strip(), braces=False) except self.ParseError as err: err.setFullCSSSource(src, inline=True) raise result = self.cssBuilder.inline(properties) finally: self.cssBuilder.endInline() return result
[ "def", "parseInline", "(", "self", ",", "src", ")", ":", "self", ".", "cssBuilder", ".", "beginInline", "(", ")", "try", ":", "try", ":", "src", ",", "properties", "=", "self", ".", "_parseDeclarationGroup", "(", "src", ".", "strip", "(", ")", ",", "braces", "=", "False", ")", "except", "self", ".", "ParseError", "as", "err", ":", "err", ".", "setFullCSSSource", "(", "src", ",", "inline", "=", "True", ")", "raise", "result", "=", "self", ".", "cssBuilder", ".", "inline", "(", "properties", ")", "finally", ":", "self", ".", "cssBuilder", ".", "endInline", "(", ")", "return", "result" ]
Parses CSS inline source string using the current cssBuilder. Use to parse a tag's 'sytle'-like attribute.
[ "Parses", "CSS", "inline", "source", "string", "using", "the", "current", "cssBuilder", ".", "Use", "to", "parse", "a", "tag", "s", "sytle", "-", "like", "attribute", "." ]
230357a392f48816532d3c2fa082a680b80ece48
https://github.com/xhtml2pdf/xhtml2pdf/blob/230357a392f48816532d3c2fa082a680b80ece48/xhtml2pdf/w3c/cssParser.py#L459-L474
8,334
xhtml2pdf/xhtml2pdf
xhtml2pdf/w3c/cssParser.py
CSSParser.parseAttributes
def parseAttributes(self, attributes=None, **kwAttributes): """Parses CSS attribute source strings, and return as an inline stylesheet. Use to parse a tag's highly CSS-based attributes like 'font'. See also: parseSingleAttr """ attributes = attributes if attributes is not None else {} if attributes: kwAttributes.update(attributes) self.cssBuilder.beginInline() try: properties = [] try: for propertyName, src in six.iteritems(kwAttributes): src, property = self._parseDeclarationProperty(src.strip(), propertyName) properties.append(property) except self.ParseError as err: err.setFullCSSSource(src, inline=True) raise result = self.cssBuilder.inline(properties) finally: self.cssBuilder.endInline() return result
python
def parseAttributes(self, attributes=None, **kwAttributes): """Parses CSS attribute source strings, and return as an inline stylesheet. Use to parse a tag's highly CSS-based attributes like 'font'. See also: parseSingleAttr """ attributes = attributes if attributes is not None else {} if attributes: kwAttributes.update(attributes) self.cssBuilder.beginInline() try: properties = [] try: for propertyName, src in six.iteritems(kwAttributes): src, property = self._parseDeclarationProperty(src.strip(), propertyName) properties.append(property) except self.ParseError as err: err.setFullCSSSource(src, inline=True) raise result = self.cssBuilder.inline(properties) finally: self.cssBuilder.endInline() return result
[ "def", "parseAttributes", "(", "self", ",", "attributes", "=", "None", ",", "*", "*", "kwAttributes", ")", ":", "attributes", "=", "attributes", "if", "attributes", "is", "not", "None", "else", "{", "}", "if", "attributes", ":", "kwAttributes", ".", "update", "(", "attributes", ")", "self", ".", "cssBuilder", ".", "beginInline", "(", ")", "try", ":", "properties", "=", "[", "]", "try", ":", "for", "propertyName", ",", "src", "in", "six", ".", "iteritems", "(", "kwAttributes", ")", ":", "src", ",", "property", "=", "self", ".", "_parseDeclarationProperty", "(", "src", ".", "strip", "(", ")", ",", "propertyName", ")", "properties", ".", "append", "(", "property", ")", "except", "self", ".", "ParseError", "as", "err", ":", "err", ".", "setFullCSSSource", "(", "src", ",", "inline", "=", "True", ")", "raise", "result", "=", "self", ".", "cssBuilder", ".", "inline", "(", "properties", ")", "finally", ":", "self", ".", "cssBuilder", ".", "endInline", "(", ")", "return", "result" ]
Parses CSS attribute source strings, and return as an inline stylesheet. Use to parse a tag's highly CSS-based attributes like 'font'. See also: parseSingleAttr
[ "Parses", "CSS", "attribute", "source", "strings", "and", "return", "as", "an", "inline", "stylesheet", ".", "Use", "to", "parse", "a", "tag", "s", "highly", "CSS", "-", "based", "attributes", "like", "font", "." ]
230357a392f48816532d3c2fa082a680b80ece48
https://github.com/xhtml2pdf/xhtml2pdf/blob/230357a392f48816532d3c2fa082a680b80ece48/xhtml2pdf/w3c/cssParser.py#L476-L501
8,335
xhtml2pdf/xhtml2pdf
xhtml2pdf/w3c/cssParser.py
CSSParser.parseSingleAttr
def parseSingleAttr(self, attrValue): """Parse a single CSS attribute source string, and returns the built CSS expression. Use to parse a tag's highly CSS-based attributes like 'font'. See also: parseAttributes """ results = self.parseAttributes(temp=attrValue) if 'temp' in results[1]: return results[1]['temp'] else: return results[0]['temp']
python
def parseSingleAttr(self, attrValue): """Parse a single CSS attribute source string, and returns the built CSS expression. Use to parse a tag's highly CSS-based attributes like 'font'. See also: parseAttributes """ results = self.parseAttributes(temp=attrValue) if 'temp' in results[1]: return results[1]['temp'] else: return results[0]['temp']
[ "def", "parseSingleAttr", "(", "self", ",", "attrValue", ")", ":", "results", "=", "self", ".", "parseAttributes", "(", "temp", "=", "attrValue", ")", "if", "'temp'", "in", "results", "[", "1", "]", ":", "return", "results", "[", "1", "]", "[", "'temp'", "]", "else", ":", "return", "results", "[", "0", "]", "[", "'temp'", "]" ]
Parse a single CSS attribute source string, and returns the built CSS expression. Use to parse a tag's highly CSS-based attributes like 'font'. See also: parseAttributes
[ "Parse", "a", "single", "CSS", "attribute", "source", "string", "and", "returns", "the", "built", "CSS", "expression", ".", "Use", "to", "parse", "a", "tag", "s", "highly", "CSS", "-", "based", "attributes", "like", "font", "." ]
230357a392f48816532d3c2fa082a680b80ece48
https://github.com/xhtml2pdf/xhtml2pdf/blob/230357a392f48816532d3c2fa082a680b80ece48/xhtml2pdf/w3c/cssParser.py#L504-L515
8,336
xhtml2pdf/xhtml2pdf
xhtml2pdf/w3c/cssParser.py
CSSParser._parseAtFrame
def _parseAtFrame(self, src): """ XXX Proprietary for PDF """ src = src[len('@frame '):].lstrip() box, src = self._getIdent(src) src, properties = self._parseDeclarationGroup(src.lstrip()) result = [self.cssBuilder.atFrame(box, properties)] return src.lstrip(), result
python
def _parseAtFrame(self, src): """ XXX Proprietary for PDF """ src = src[len('@frame '):].lstrip() box, src = self._getIdent(src) src, properties = self._parseDeclarationGroup(src.lstrip()) result = [self.cssBuilder.atFrame(box, properties)] return src.lstrip(), result
[ "def", "_parseAtFrame", "(", "self", ",", "src", ")", ":", "src", "=", "src", "[", "len", "(", "'@frame '", ")", ":", "]", ".", "lstrip", "(", ")", "box", ",", "src", "=", "self", ".", "_getIdent", "(", "src", ")", "src", ",", "properties", "=", "self", ".", "_parseDeclarationGroup", "(", "src", ".", "lstrip", "(", ")", ")", "result", "=", "[", "self", ".", "cssBuilder", ".", "atFrame", "(", "box", ",", "properties", ")", "]", "return", "src", ".", "lstrip", "(", ")", ",", "result" ]
XXX Proprietary for PDF
[ "XXX", "Proprietary", "for", "PDF" ]
230357a392f48816532d3c2fa082a680b80ece48
https://github.com/xhtml2pdf/xhtml2pdf/blob/230357a392f48816532d3c2fa082a680b80ece48/xhtml2pdf/w3c/cssParser.py#L788-L796
8,337
xhtml2pdf/xhtml2pdf
xhtml2pdf/util.py
ErrorMsg
def ErrorMsg(): """ Helper to get a nice traceback as string """ import traceback limit = None _type, value, tb = sys.exc_info() _list = traceback.format_tb(tb, limit) + \ traceback.format_exception_only(_type, value) return "Traceback (innermost last):\n" + "%-20s %s" % ( " ".join(_list[:-1]), _list[-1])
python
def ErrorMsg(): """ Helper to get a nice traceback as string """ import traceback limit = None _type, value, tb = sys.exc_info() _list = traceback.format_tb(tb, limit) + \ traceback.format_exception_only(_type, value) return "Traceback (innermost last):\n" + "%-20s %s" % ( " ".join(_list[:-1]), _list[-1])
[ "def", "ErrorMsg", "(", ")", ":", "import", "traceback", "limit", "=", "None", "_type", ",", "value", ",", "tb", "=", "sys", ".", "exc_info", "(", ")", "_list", "=", "traceback", ".", "format_tb", "(", "tb", ",", "limit", ")", "+", "traceback", ".", "format_exception_only", "(", "_type", ",", "value", ")", "return", "\"Traceback (innermost last):\\n\"", "+", "\"%-20s %s\"", "%", "(", "\" \"", ".", "join", "(", "_list", "[", ":", "-", "1", "]", ")", ",", "_list", "[", "-", "1", "]", ")" ]
Helper to get a nice traceback as string
[ "Helper", "to", "get", "a", "nice", "traceback", "as", "string" ]
230357a392f48816532d3c2fa082a680b80ece48
https://github.com/xhtml2pdf/xhtml2pdf/blob/230357a392f48816532d3c2fa082a680b80ece48/xhtml2pdf/util.py#L119-L131
8,338
xhtml2pdf/xhtml2pdf
xhtml2pdf/util.py
transform_attrs
def transform_attrs(obj, keys, container, func, extras=None): """ Allows to apply one function to set of keys cheching if key is in container, also trasform ccs key to report lab keys. extras = Are extra params for func, it will be call like func(*[param1, param2]) obj = frag keys = [(reportlab, css), ... ] container = cssAttr """ cpextras = extras for reportlab, css in keys: extras = cpextras if extras is None: extras = [] elif not isinstance(extras, list): extras = [extras] if css in container: extras.insert(0, container[css]) setattr(obj, reportlab, func(*extras) )
python
def transform_attrs(obj, keys, container, func, extras=None): """ Allows to apply one function to set of keys cheching if key is in container, also trasform ccs key to report lab keys. extras = Are extra params for func, it will be call like func(*[param1, param2]) obj = frag keys = [(reportlab, css), ... ] container = cssAttr """ cpextras = extras for reportlab, css in keys: extras = cpextras if extras is None: extras = [] elif not isinstance(extras, list): extras = [extras] if css in container: extras.insert(0, container[css]) setattr(obj, reportlab, func(*extras) )
[ "def", "transform_attrs", "(", "obj", ",", "keys", ",", "container", ",", "func", ",", "extras", "=", "None", ")", ":", "cpextras", "=", "extras", "for", "reportlab", ",", "css", "in", "keys", ":", "extras", "=", "cpextras", "if", "extras", "is", "None", ":", "extras", "=", "[", "]", "elif", "not", "isinstance", "(", "extras", ",", "list", ")", ":", "extras", "=", "[", "extras", "]", "if", "css", "in", "container", ":", "extras", ".", "insert", "(", "0", ",", "container", "[", "css", "]", ")", "setattr", "(", "obj", ",", "reportlab", ",", "func", "(", "*", "extras", ")", ")" ]
Allows to apply one function to set of keys cheching if key is in container, also trasform ccs key to report lab keys. extras = Are extra params for func, it will be call like func(*[param1, param2]) obj = frag keys = [(reportlab, css), ... ] container = cssAttr
[ "Allows", "to", "apply", "one", "function", "to", "set", "of", "keys", "cheching", "if", "key", "is", "in", "container", "also", "trasform", "ccs", "key", "to", "report", "lab", "keys", "." ]
230357a392f48816532d3c2fa082a680b80ece48
https://github.com/xhtml2pdf/xhtml2pdf/blob/230357a392f48816532d3c2fa082a680b80ece48/xhtml2pdf/util.py#L140-L164
8,339
xhtml2pdf/xhtml2pdf
xhtml2pdf/util.py
copy_attrs
def copy_attrs(obj1, obj2, attrs): """ Allows copy a list of attributes from object2 to object1. Useful for copy ccs attributes to fragment """ for attr in attrs: value = getattr(obj2, attr) if hasattr(obj2, attr) else None if value is None and isinstance(obj2, dict) and attr in obj2: value = obj2[attr] setattr(obj1, attr, value)
python
def copy_attrs(obj1, obj2, attrs): """ Allows copy a list of attributes from object2 to object1. Useful for copy ccs attributes to fragment """ for attr in attrs: value = getattr(obj2, attr) if hasattr(obj2, attr) else None if value is None and isinstance(obj2, dict) and attr in obj2: value = obj2[attr] setattr(obj1, attr, value)
[ "def", "copy_attrs", "(", "obj1", ",", "obj2", ",", "attrs", ")", ":", "for", "attr", "in", "attrs", ":", "value", "=", "getattr", "(", "obj2", ",", "attr", ")", "if", "hasattr", "(", "obj2", ",", "attr", ")", "else", "None", "if", "value", "is", "None", "and", "isinstance", "(", "obj2", ",", "dict", ")", "and", "attr", "in", "obj2", ":", "value", "=", "obj2", "[", "attr", "]", "setattr", "(", "obj1", ",", "attr", ",", "value", ")" ]
Allows copy a list of attributes from object2 to object1. Useful for copy ccs attributes to fragment
[ "Allows", "copy", "a", "list", "of", "attributes", "from", "object2", "to", "object1", ".", "Useful", "for", "copy", "ccs", "attributes", "to", "fragment" ]
230357a392f48816532d3c2fa082a680b80ece48
https://github.com/xhtml2pdf/xhtml2pdf/blob/230357a392f48816532d3c2fa082a680b80ece48/xhtml2pdf/util.py#L167-L176
8,340
xhtml2pdf/xhtml2pdf
xhtml2pdf/util.py
set_value
def set_value(obj, attrs, value, _copy=False): """ Allows set the same value to a list of attributes """ for attr in attrs: if _copy: value = copy(value) setattr(obj, attr, value)
python
def set_value(obj, attrs, value, _copy=False): """ Allows set the same value to a list of attributes """ for attr in attrs: if _copy: value = copy(value) setattr(obj, attr, value)
[ "def", "set_value", "(", "obj", ",", "attrs", ",", "value", ",", "_copy", "=", "False", ")", ":", "for", "attr", "in", "attrs", ":", "if", "_copy", ":", "value", "=", "copy", "(", "value", ")", "setattr", "(", "obj", ",", "attr", ",", "value", ")" ]
Allows set the same value to a list of attributes
[ "Allows", "set", "the", "same", "value", "to", "a", "list", "of", "attributes" ]
230357a392f48816532d3c2fa082a680b80ece48
https://github.com/xhtml2pdf/xhtml2pdf/blob/230357a392f48816532d3c2fa082a680b80ece48/xhtml2pdf/util.py#L179-L186
8,341
xhtml2pdf/xhtml2pdf
xhtml2pdf/util.py
getColor
def getColor(value, default=None): """ Convert to color value. This returns a Color object instance from a text bit. """ if isinstance(value, Color): return value value = str(value).strip().lower() if value == "transparent" or value == "none": return default if value in COLOR_BY_NAME: return COLOR_BY_NAME[value] if value.startswith("#") and len(value) == 4: value = "#" + value[1] + value[1] + \ value[2] + value[2] + value[3] + value[3] elif rgb_re.search(value): # e.g., value = "<css function: rgb(153, 51, 153)>", go figure: r, g, b = [int(x) for x in rgb_re.search(value).groups()] value = "#%02x%02x%02x" % (r, g, b) else: # Shrug pass return toColor(value, default)
python
def getColor(value, default=None): """ Convert to color value. This returns a Color object instance from a text bit. """ if isinstance(value, Color): return value value = str(value).strip().lower() if value == "transparent" or value == "none": return default if value in COLOR_BY_NAME: return COLOR_BY_NAME[value] if value.startswith("#") and len(value) == 4: value = "#" + value[1] + value[1] + \ value[2] + value[2] + value[3] + value[3] elif rgb_re.search(value): # e.g., value = "<css function: rgb(153, 51, 153)>", go figure: r, g, b = [int(x) for x in rgb_re.search(value).groups()] value = "#%02x%02x%02x" % (r, g, b) else: # Shrug pass return toColor(value, default)
[ "def", "getColor", "(", "value", ",", "default", "=", "None", ")", ":", "if", "isinstance", "(", "value", ",", "Color", ")", ":", "return", "value", "value", "=", "str", "(", "value", ")", ".", "strip", "(", ")", ".", "lower", "(", ")", "if", "value", "==", "\"transparent\"", "or", "value", "==", "\"none\"", ":", "return", "default", "if", "value", "in", "COLOR_BY_NAME", ":", "return", "COLOR_BY_NAME", "[", "value", "]", "if", "value", ".", "startswith", "(", "\"#\"", ")", "and", "len", "(", "value", ")", "==", "4", ":", "value", "=", "\"#\"", "+", "value", "[", "1", "]", "+", "value", "[", "1", "]", "+", "value", "[", "2", "]", "+", "value", "[", "2", "]", "+", "value", "[", "3", "]", "+", "value", "[", "3", "]", "elif", "rgb_re", ".", "search", "(", "value", ")", ":", "# e.g., value = \"<css function: rgb(153, 51, 153)>\", go figure:", "r", ",", "g", ",", "b", "=", "[", "int", "(", "x", ")", "for", "x", "in", "rgb_re", ".", "search", "(", "value", ")", ".", "groups", "(", ")", "]", "value", "=", "\"#%02x%02x%02x\"", "%", "(", "r", ",", "g", ",", "b", ")", "else", ":", "# Shrug", "pass", "return", "toColor", "(", "value", ",", "default", ")" ]
Convert to color value. This returns a Color object instance from a text bit.
[ "Convert", "to", "color", "value", ".", "This", "returns", "a", "Color", "object", "instance", "from", "a", "text", "bit", "." ]
230357a392f48816532d3c2fa082a680b80ece48
https://github.com/xhtml2pdf/xhtml2pdf/blob/230357a392f48816532d3c2fa082a680b80ece48/xhtml2pdf/util.py#L190-L214
8,342
xhtml2pdf/xhtml2pdf
xhtml2pdf/util.py
getCoords
def getCoords(x, y, w, h, pagesize): """ As a stupid programmer I like to use the upper left corner of the document as the 0,0 coords therefore we need to do some fancy calculations """ #~ print pagesize ax, ay = pagesize if x < 0: x = ax + x if y < 0: y = ay + y if w is not None and h is not None: if w <= 0: w = (ax - x + w) if h <= 0: h = (ay - y + h) return x, (ay - y - h), w, h return x, (ay - y)
python
def getCoords(x, y, w, h, pagesize): """ As a stupid programmer I like to use the upper left corner of the document as the 0,0 coords therefore we need to do some fancy calculations """ #~ print pagesize ax, ay = pagesize if x < 0: x = ax + x if y < 0: y = ay + y if w is not None and h is not None: if w <= 0: w = (ax - x + w) if h <= 0: h = (ay - y + h) return x, (ay - y - h), w, h return x, (ay - y)
[ "def", "getCoords", "(", "x", ",", "y", ",", "w", ",", "h", ",", "pagesize", ")", ":", "#~ print pagesize", "ax", ",", "ay", "=", "pagesize", "if", "x", "<", "0", ":", "x", "=", "ax", "+", "x", "if", "y", "<", "0", ":", "y", "=", "ay", "+", "y", "if", "w", "is", "not", "None", "and", "h", "is", "not", "None", ":", "if", "w", "<=", "0", ":", "w", "=", "(", "ax", "-", "x", "+", "w", ")", "if", "h", "<=", "0", ":", "h", "=", "(", "ay", "-", "y", "+", "h", ")", "return", "x", ",", "(", "ay", "-", "y", "-", "h", ")", ",", "w", ",", "h", "return", "x", ",", "(", "ay", "-", "y", ")" ]
As a stupid programmer I like to use the upper left corner of the document as the 0,0 coords therefore we need to do some fancy calculations
[ "As", "a", "stupid", "programmer", "I", "like", "to", "use", "the", "upper", "left", "corner", "of", "the", "document", "as", "the", "0", "0", "coords", "therefore", "we", "need", "to", "do", "some", "fancy", "calculations" ]
230357a392f48816532d3c2fa082a680b80ece48
https://github.com/xhtml2pdf/xhtml2pdf/blob/230357a392f48816532d3c2fa082a680b80ece48/xhtml2pdf/util.py#L336-L354
8,343
xhtml2pdf/xhtml2pdf
xhtml2pdf/util.py
getFrameDimensions
def getFrameDimensions(data, page_width, page_height): """Calculate dimensions of a frame Returns left, top, width and height of the frame in points. """ box = data.get("-pdf-frame-box", []) if len(box) == 4: return [getSize(x) for x in box] top = getSize(data.get("top", 0)) left = getSize(data.get("left", 0)) bottom = getSize(data.get("bottom", 0)) right = getSize(data.get("right", 0)) if "height" in data: height = getSize(data["height"]) if "top" in data: top = getSize(data["top"]) bottom = page_height - (top + height) elif "bottom" in data: bottom = getSize(data["bottom"]) top = page_height - (bottom + height) if "width" in data: width = getSize(data["width"]) if "left" in data: left = getSize(data["left"]) right = page_width - (left + width) elif "right" in data: right = getSize(data["right"]) left = page_width - (right + width) top += getSize(data.get("margin-top", 0)) left += getSize(data.get("margin-left", 0)) bottom += getSize(data.get("margin-bottom", 0)) right += getSize(data.get("margin-right", 0)) width = page_width - (left + right) height = page_height - (top + bottom) return left, top, width, height
python
def getFrameDimensions(data, page_width, page_height): """Calculate dimensions of a frame Returns left, top, width and height of the frame in points. """ box = data.get("-pdf-frame-box", []) if len(box) == 4: return [getSize(x) for x in box] top = getSize(data.get("top", 0)) left = getSize(data.get("left", 0)) bottom = getSize(data.get("bottom", 0)) right = getSize(data.get("right", 0)) if "height" in data: height = getSize(data["height"]) if "top" in data: top = getSize(data["top"]) bottom = page_height - (top + height) elif "bottom" in data: bottom = getSize(data["bottom"]) top = page_height - (bottom + height) if "width" in data: width = getSize(data["width"]) if "left" in data: left = getSize(data["left"]) right = page_width - (left + width) elif "right" in data: right = getSize(data["right"]) left = page_width - (right + width) top += getSize(data.get("margin-top", 0)) left += getSize(data.get("margin-left", 0)) bottom += getSize(data.get("margin-bottom", 0)) right += getSize(data.get("margin-right", 0)) width = page_width - (left + right) height = page_height - (top + bottom) return left, top, width, height
[ "def", "getFrameDimensions", "(", "data", ",", "page_width", ",", "page_height", ")", ":", "box", "=", "data", ".", "get", "(", "\"-pdf-frame-box\"", ",", "[", "]", ")", "if", "len", "(", "box", ")", "==", "4", ":", "return", "[", "getSize", "(", "x", ")", "for", "x", "in", "box", "]", "top", "=", "getSize", "(", "data", ".", "get", "(", "\"top\"", ",", "0", ")", ")", "left", "=", "getSize", "(", "data", ".", "get", "(", "\"left\"", ",", "0", ")", ")", "bottom", "=", "getSize", "(", "data", ".", "get", "(", "\"bottom\"", ",", "0", ")", ")", "right", "=", "getSize", "(", "data", ".", "get", "(", "\"right\"", ",", "0", ")", ")", "if", "\"height\"", "in", "data", ":", "height", "=", "getSize", "(", "data", "[", "\"height\"", "]", ")", "if", "\"top\"", "in", "data", ":", "top", "=", "getSize", "(", "data", "[", "\"top\"", "]", ")", "bottom", "=", "page_height", "-", "(", "top", "+", "height", ")", "elif", "\"bottom\"", "in", "data", ":", "bottom", "=", "getSize", "(", "data", "[", "\"bottom\"", "]", ")", "top", "=", "page_height", "-", "(", "bottom", "+", "height", ")", "if", "\"width\"", "in", "data", ":", "width", "=", "getSize", "(", "data", "[", "\"width\"", "]", ")", "if", "\"left\"", "in", "data", ":", "left", "=", "getSize", "(", "data", "[", "\"left\"", "]", ")", "right", "=", "page_width", "-", "(", "left", "+", "width", ")", "elif", "\"right\"", "in", "data", ":", "right", "=", "getSize", "(", "data", "[", "\"right\"", "]", ")", "left", "=", "page_width", "-", "(", "right", "+", "width", ")", "top", "+=", "getSize", "(", "data", ".", "get", "(", "\"margin-top\"", ",", "0", ")", ")", "left", "+=", "getSize", "(", "data", ".", "get", "(", "\"margin-left\"", ",", "0", ")", ")", "bottom", "+=", "getSize", "(", "data", ".", "get", "(", "\"margin-bottom\"", ",", "0", ")", ")", "right", "+=", "getSize", "(", "data", ".", "get", "(", "\"margin-right\"", ",", "0", ")", ")", "width", "=", "page_width", "-", "(", "left", "+", "right", ")", "height", "=", "page_height", "-", "(", "top", "+", "bottom", ")", "return", "left", ",", "top", ",", "width", ",", "height" ]
Calculate dimensions of a frame Returns left, top, width and height of the frame in points.
[ "Calculate", "dimensions", "of", "a", "frame" ]
230357a392f48816532d3c2fa082a680b80ece48
https://github.com/xhtml2pdf/xhtml2pdf/blob/230357a392f48816532d3c2fa082a680b80ece48/xhtml2pdf/util.py#L372-L407
8,344
xhtml2pdf/xhtml2pdf
xhtml2pdf/util.py
getPos
def getPos(position, pagesize): """ Pair of coordinates """ position = str(position).split() if len(position) != 2: raise Exception("position not defined right way") x, y = [getSize(pos) for pos in position] return getCoords(x, y, None, None, pagesize)
python
def getPos(position, pagesize): """ Pair of coordinates """ position = str(position).split() if len(position) != 2: raise Exception("position not defined right way") x, y = [getSize(pos) for pos in position] return getCoords(x, y, None, None, pagesize)
[ "def", "getPos", "(", "position", ",", "pagesize", ")", ":", "position", "=", "str", "(", "position", ")", ".", "split", "(", ")", "if", "len", "(", "position", ")", "!=", "2", ":", "raise", "Exception", "(", "\"position not defined right way\"", ")", "x", ",", "y", "=", "[", "getSize", "(", "pos", ")", "for", "pos", "in", "position", "]", "return", "getCoords", "(", "x", ",", "y", ",", "None", ",", "None", ",", "pagesize", ")" ]
Pair of coordinates
[ "Pair", "of", "coordinates" ]
230357a392f48816532d3c2fa082a680b80ece48
https://github.com/xhtml2pdf/xhtml2pdf/blob/230357a392f48816532d3c2fa082a680b80ece48/xhtml2pdf/util.py#L411-L419
8,345
xhtml2pdf/xhtml2pdf
xhtml2pdf/util.py
pisaTempFile.makeTempFile
def makeTempFile(self): """ Switch to next startegy. If an error occured, stay with the first strategy """ if self.strategy == 0: try: new_delegate = self.STRATEGIES[1]() new_delegate.write(self.getvalue()) self._delegate = new_delegate self.strategy = 1 log.warn("Created temporary file %s", self.name) except: self.capacity = - 1
python
def makeTempFile(self): """ Switch to next startegy. If an error occured, stay with the first strategy """ if self.strategy == 0: try: new_delegate = self.STRATEGIES[1]() new_delegate.write(self.getvalue()) self._delegate = new_delegate self.strategy = 1 log.warn("Created temporary file %s", self.name) except: self.capacity = - 1
[ "def", "makeTempFile", "(", "self", ")", ":", "if", "self", ".", "strategy", "==", "0", ":", "try", ":", "new_delegate", "=", "self", ".", "STRATEGIES", "[", "1", "]", "(", ")", "new_delegate", ".", "write", "(", "self", ".", "getvalue", "(", ")", ")", "self", ".", "_delegate", "=", "new_delegate", "self", ".", "strategy", "=", "1", "log", ".", "warn", "(", "\"Created temporary file %s\"", ",", "self", ".", "name", ")", "except", ":", "self", ".", "capacity", "=", "-", "1" ]
Switch to next startegy. If an error occured, stay with the first strategy
[ "Switch", "to", "next", "startegy", ".", "If", "an", "error", "occured", "stay", "with", "the", "first", "strategy" ]
230357a392f48816532d3c2fa082a680b80ece48
https://github.com/xhtml2pdf/xhtml2pdf/blob/230357a392f48816532d3c2fa082a680b80ece48/xhtml2pdf/util.py#L497-L511
8,346
xhtml2pdf/xhtml2pdf
xhtml2pdf/util.py
pisaTempFile.getvalue
def getvalue(self): """ Get value of file. Work around for second strategy. Always returns bytes """ if self.strategy == 0: return self._delegate.getvalue() self._delegate.flush() self._delegate.seek(0) value = self._delegate.read() if not isinstance(value, six.binary_type): value = value.encode('utf-8') return value
python
def getvalue(self): """ Get value of file. Work around for second strategy. Always returns bytes """ if self.strategy == 0: return self._delegate.getvalue() self._delegate.flush() self._delegate.seek(0) value = self._delegate.read() if not isinstance(value, six.binary_type): value = value.encode('utf-8') return value
[ "def", "getvalue", "(", "self", ")", ":", "if", "self", ".", "strategy", "==", "0", ":", "return", "self", ".", "_delegate", ".", "getvalue", "(", ")", "self", ".", "_delegate", ".", "flush", "(", ")", "self", ".", "_delegate", ".", "seek", "(", "0", ")", "value", "=", "self", ".", "_delegate", ".", "read", "(", ")", "if", "not", "isinstance", "(", "value", ",", "six", ".", "binary_type", ")", ":", "value", "=", "value", ".", "encode", "(", "'utf-8'", ")", "return", "value" ]
Get value of file. Work around for second strategy. Always returns bytes
[ "Get", "value", "of", "file", ".", "Work", "around", "for", "second", "strategy", ".", "Always", "returns", "bytes" ]
230357a392f48816532d3c2fa082a680b80ece48
https://github.com/xhtml2pdf/xhtml2pdf/blob/230357a392f48816532d3c2fa082a680b80ece48/xhtml2pdf/util.py#L529-L542
8,347
xhtml2pdf/xhtml2pdf
xhtml2pdf/util.py
pisaTempFile.write
def write(self, value): """ If capacity != -1 and length of file > capacity it is time to switch """ if self.capacity > 0 and self.strategy == 0: len_value = len(value) if len_value >= self.capacity: needs_new_strategy = True else: self.seek(0, 2) # find end of file needs_new_strategy = \ (self.tell() + len_value) >= self.capacity if needs_new_strategy: self.makeTempFile() if not isinstance(value, six.binary_type): value = value.encode('utf-8') self._delegate.write(value)
python
def write(self, value): """ If capacity != -1 and length of file > capacity it is time to switch """ if self.capacity > 0 and self.strategy == 0: len_value = len(value) if len_value >= self.capacity: needs_new_strategy = True else: self.seek(0, 2) # find end of file needs_new_strategy = \ (self.tell() + len_value) >= self.capacity if needs_new_strategy: self.makeTempFile() if not isinstance(value, six.binary_type): value = value.encode('utf-8') self._delegate.write(value)
[ "def", "write", "(", "self", ",", "value", ")", ":", "if", "self", ".", "capacity", ">", "0", "and", "self", ".", "strategy", "==", "0", ":", "len_value", "=", "len", "(", "value", ")", "if", "len_value", ">=", "self", ".", "capacity", ":", "needs_new_strategy", "=", "True", "else", ":", "self", ".", "seek", "(", "0", ",", "2", ")", "# find end of file", "needs_new_strategy", "=", "(", "self", ".", "tell", "(", ")", "+", "len_value", ")", ">=", "self", ".", "capacity", "if", "needs_new_strategy", ":", "self", ".", "makeTempFile", "(", ")", "if", "not", "isinstance", "(", "value", ",", "six", ".", "binary_type", ")", ":", "value", "=", "value", ".", "encode", "(", "'utf-8'", ")", "self", ".", "_delegate", ".", "write", "(", "value", ")" ]
If capacity != -1 and length of file > capacity it is time to switch
[ "If", "capacity", "!", "=", "-", "1", "and", "length", "of", "file", ">", "capacity", "it", "is", "time", "to", "switch" ]
230357a392f48816532d3c2fa082a680b80ece48
https://github.com/xhtml2pdf/xhtml2pdf/blob/230357a392f48816532d3c2fa082a680b80ece48/xhtml2pdf/util.py#L544-L563
8,348
xhtml2pdf/xhtml2pdf
xhtml2pdf/util.py
pisaFileObject.setMimeTypeByName
def setMimeTypeByName(self, name): " Guess the mime type " mimetype = mimetypes.guess_type(name)[0] if mimetype is not None: self.mimetype = mimetypes.guess_type(name)[0].split(";")[0]
python
def setMimeTypeByName(self, name): " Guess the mime type " mimetype = mimetypes.guess_type(name)[0] if mimetype is not None: self.mimetype = mimetypes.guess_type(name)[0].split(";")[0]
[ "def", "setMimeTypeByName", "(", "self", ",", "name", ")", ":", "mimetype", "=", "mimetypes", ".", "guess_type", "(", "name", ")", "[", "0", "]", "if", "mimetype", "is", "not", "None", ":", "self", ".", "mimetype", "=", "mimetypes", ".", "guess_type", "(", "name", ")", "[", "0", "]", ".", "split", "(", "\";\"", ")", "[", "0", "]" ]
Guess the mime type
[ "Guess", "the", "mime", "type" ]
230357a392f48816532d3c2fa082a680b80ece48
https://github.com/xhtml2pdf/xhtml2pdf/blob/230357a392f48816532d3c2fa082a680b80ece48/xhtml2pdf/util.py#L732-L736
8,349
xhtml2pdf/xhtml2pdf
xhtml2pdf/reportlab_paragraph.py
_sameFrag
def _sameFrag(f, g): """ returns 1 if two ParaFrags map out the same """ if (hasattr(f, 'cbDefn') or hasattr(g, 'cbDefn') or hasattr(f, 'lineBreak') or hasattr(g, 'lineBreak')): return 0 for a in ('fontName', 'fontSize', 'textColor', 'backColor', 'rise', 'underline', 'strike', 'link'): if getattr(f, a, None) != getattr(g, a, None): return 0 return 1
python
def _sameFrag(f, g): """ returns 1 if two ParaFrags map out the same """ if (hasattr(f, 'cbDefn') or hasattr(g, 'cbDefn') or hasattr(f, 'lineBreak') or hasattr(g, 'lineBreak')): return 0 for a in ('fontName', 'fontSize', 'textColor', 'backColor', 'rise', 'underline', 'strike', 'link'): if getattr(f, a, None) != getattr(g, a, None): return 0 return 1
[ "def", "_sameFrag", "(", "f", ",", "g", ")", ":", "if", "(", "hasattr", "(", "f", ",", "'cbDefn'", ")", "or", "hasattr", "(", "g", ",", "'cbDefn'", ")", "or", "hasattr", "(", "f", ",", "'lineBreak'", ")", "or", "hasattr", "(", "g", ",", "'lineBreak'", ")", ")", ":", "return", "0", "for", "a", "in", "(", "'fontName'", ",", "'fontSize'", ",", "'textColor'", ",", "'backColor'", ",", "'rise'", ",", "'underline'", ",", "'strike'", ",", "'link'", ")", ":", "if", "getattr", "(", "f", ",", "a", ",", "None", ")", "!=", "getattr", "(", "g", ",", "a", ",", "None", ")", ":", "return", "0", "return", "1" ]
returns 1 if two ParaFrags map out the same
[ "returns", "1", "if", "two", "ParaFrags", "map", "out", "the", "same" ]
230357a392f48816532d3c2fa082a680b80ece48
https://github.com/xhtml2pdf/xhtml2pdf/blob/230357a392f48816532d3c2fa082a680b80ece48/xhtml2pdf/reportlab_paragraph.py#L417-L426
8,350
xhtml2pdf/xhtml2pdf
xhtml2pdf/reportlab_paragraph.py
_drawBullet
def _drawBullet(canvas, offset, cur_y, bulletText, style): """ draw a bullet text could be a simple string or a frag list """ tx2 = canvas.beginText(style.bulletIndent, cur_y + getattr(style, "bulletOffsetY", 0)) tx2.setFont(style.bulletFontName, style.bulletFontSize) tx2.setFillColor(hasattr(style, 'bulletColor') and style.bulletColor or style.textColor) if isinstance(bulletText, basestring): tx2.textOut(bulletText) else: for f in bulletText: if hasattr(f, "image"): image = f.image width = image.drawWidth height = image.drawHeight gap = style.bulletFontSize * 0.25 img = image.getImage() # print style.bulletIndent, offset, width canvas.drawImage( img, style.leftIndent - width - gap, cur_y + getattr(style, "bulletOffsetY", 0), width, height) else: tx2.setFont(f.fontName, f.fontSize) tx2.setFillColor(f.textColor) tx2.textOut(f.text) canvas.drawText(tx2) #AR making definition lists a bit less ugly #bulletEnd = tx2.getX() bulletEnd = tx2.getX() + style.bulletFontSize * 0.6 offset = max(offset, bulletEnd - style.leftIndent) return offset
python
def _drawBullet(canvas, offset, cur_y, bulletText, style): """ draw a bullet text could be a simple string or a frag list """ tx2 = canvas.beginText(style.bulletIndent, cur_y + getattr(style, "bulletOffsetY", 0)) tx2.setFont(style.bulletFontName, style.bulletFontSize) tx2.setFillColor(hasattr(style, 'bulletColor') and style.bulletColor or style.textColor) if isinstance(bulletText, basestring): tx2.textOut(bulletText) else: for f in bulletText: if hasattr(f, "image"): image = f.image width = image.drawWidth height = image.drawHeight gap = style.bulletFontSize * 0.25 img = image.getImage() # print style.bulletIndent, offset, width canvas.drawImage( img, style.leftIndent - width - gap, cur_y + getattr(style, "bulletOffsetY", 0), width, height) else: tx2.setFont(f.fontName, f.fontSize) tx2.setFillColor(f.textColor) tx2.textOut(f.text) canvas.drawText(tx2) #AR making definition lists a bit less ugly #bulletEnd = tx2.getX() bulletEnd = tx2.getX() + style.bulletFontSize * 0.6 offset = max(offset, bulletEnd - style.leftIndent) return offset
[ "def", "_drawBullet", "(", "canvas", ",", "offset", ",", "cur_y", ",", "bulletText", ",", "style", ")", ":", "tx2", "=", "canvas", ".", "beginText", "(", "style", ".", "bulletIndent", ",", "cur_y", "+", "getattr", "(", "style", ",", "\"bulletOffsetY\"", ",", "0", ")", ")", "tx2", ".", "setFont", "(", "style", ".", "bulletFontName", ",", "style", ".", "bulletFontSize", ")", "tx2", ".", "setFillColor", "(", "hasattr", "(", "style", ",", "'bulletColor'", ")", "and", "style", ".", "bulletColor", "or", "style", ".", "textColor", ")", "if", "isinstance", "(", "bulletText", ",", "basestring", ")", ":", "tx2", ".", "textOut", "(", "bulletText", ")", "else", ":", "for", "f", "in", "bulletText", ":", "if", "hasattr", "(", "f", ",", "\"image\"", ")", ":", "image", "=", "f", ".", "image", "width", "=", "image", ".", "drawWidth", "height", "=", "image", ".", "drawHeight", "gap", "=", "style", ".", "bulletFontSize", "*", "0.25", "img", "=", "image", ".", "getImage", "(", ")", "# print style.bulletIndent, offset, width", "canvas", ".", "drawImage", "(", "img", ",", "style", ".", "leftIndent", "-", "width", "-", "gap", ",", "cur_y", "+", "getattr", "(", "style", ",", "\"bulletOffsetY\"", ",", "0", ")", ",", "width", ",", "height", ")", "else", ":", "tx2", ".", "setFont", "(", "f", ".", "fontName", ",", "f", ".", "fontSize", ")", "tx2", ".", "setFillColor", "(", "f", ".", "textColor", ")", "tx2", ".", "textOut", "(", "f", ".", "text", ")", "canvas", ".", "drawText", "(", "tx2", ")", "#AR making definition lists a bit less ugly", "#bulletEnd = tx2.getX()", "bulletEnd", "=", "tx2", ".", "getX", "(", ")", "+", "style", ".", "bulletFontSize", "*", "0.6", "offset", "=", "max", "(", "offset", ",", "bulletEnd", "-", "style", ".", "leftIndent", ")", "return", "offset" ]
draw a bullet text could be a simple string or a frag list
[ "draw", "a", "bullet", "text", "could", "be", "a", "simple", "string", "or", "a", "frag", "list" ]
230357a392f48816532d3c2fa082a680b80ece48
https://github.com/xhtml2pdf/xhtml2pdf/blob/230357a392f48816532d3c2fa082a680b80ece48/xhtml2pdf/reportlab_paragraph.py#L536-L570
8,351
xhtml2pdf/xhtml2pdf
xhtml2pdf/reportlab_paragraph.py
splitLines0
def splitLines0(frags, widths): """ given a list of ParaFrags we return a list of ParaLines each ParaLine has 1) ExtraSpace 2) blankCount 3) [textDefns....] each text definition is a (ParaFrag, start, limit) triplet """ #initialise the algorithm lineNum = 0 maxW = widths[lineNum] i = -1 l = len(frags) lim = start = 0 text = frags[0] while 1: #find a non whitespace character while i < l: while start < lim and text[start] == ' ': start += 1 if start == lim: i += 1 if i == l: break start = 0 f = frags[i] text = f.text lim = len(text) else: break # we found one if start == lim: break # if we didn't find one we are done #start of a line g = (None, None, None) line = [] cLen = 0 nSpaces = 0 while cLen < maxW: j = text.find(' ', start) if j < 0: j == lim w = stringWidth(text[start:j], f.fontName, f.fontSize) cLen += w if cLen > maxW and line != []: cLen = cLen - w #this is the end of the line while g.text[lim] == ' ': lim -= 1 nSpaces -= 1 break if j < 0: j = lim if g[0] is f: g[2] = j #extend else: g = (f, start, j) line.append(g) if j == lim: i += 1
python
def splitLines0(frags, widths): """ given a list of ParaFrags we return a list of ParaLines each ParaLine has 1) ExtraSpace 2) blankCount 3) [textDefns....] each text definition is a (ParaFrag, start, limit) triplet """ #initialise the algorithm lineNum = 0 maxW = widths[lineNum] i = -1 l = len(frags) lim = start = 0 text = frags[0] while 1: #find a non whitespace character while i < l: while start < lim and text[start] == ' ': start += 1 if start == lim: i += 1 if i == l: break start = 0 f = frags[i] text = f.text lim = len(text) else: break # we found one if start == lim: break # if we didn't find one we are done #start of a line g = (None, None, None) line = [] cLen = 0 nSpaces = 0 while cLen < maxW: j = text.find(' ', start) if j < 0: j == lim w = stringWidth(text[start:j], f.fontName, f.fontSize) cLen += w if cLen > maxW and line != []: cLen = cLen - w #this is the end of the line while g.text[lim] == ' ': lim -= 1 nSpaces -= 1 break if j < 0: j = lim if g[0] is f: g[2] = j #extend else: g = (f, start, j) line.append(g) if j == lim: i += 1
[ "def", "splitLines0", "(", "frags", ",", "widths", ")", ":", "#initialise the algorithm", "lineNum", "=", "0", "maxW", "=", "widths", "[", "lineNum", "]", "i", "=", "-", "1", "l", "=", "len", "(", "frags", ")", "lim", "=", "start", "=", "0", "text", "=", "frags", "[", "0", "]", "while", "1", ":", "#find a non whitespace character", "while", "i", "<", "l", ":", "while", "start", "<", "lim", "and", "text", "[", "start", "]", "==", "' '", ":", "start", "+=", "1", "if", "start", "==", "lim", ":", "i", "+=", "1", "if", "i", "==", "l", ":", "break", "start", "=", "0", "f", "=", "frags", "[", "i", "]", "text", "=", "f", ".", "text", "lim", "=", "len", "(", "text", ")", "else", ":", "break", "# we found one", "if", "start", "==", "lim", ":", "break", "# if we didn't find one we are done", "#start of a line", "g", "=", "(", "None", ",", "None", ",", "None", ")", "line", "=", "[", "]", "cLen", "=", "0", "nSpaces", "=", "0", "while", "cLen", "<", "maxW", ":", "j", "=", "text", ".", "find", "(", "' '", ",", "start", ")", "if", "j", "<", "0", ":", "j", "==", "lim", "w", "=", "stringWidth", "(", "text", "[", "start", ":", "j", "]", ",", "f", ".", "fontName", ",", "f", ".", "fontSize", ")", "cLen", "+=", "w", "if", "cLen", ">", "maxW", "and", "line", "!=", "[", "]", ":", "cLen", "=", "cLen", "-", "w", "#this is the end of the line", "while", "g", ".", "text", "[", "lim", "]", "==", "' '", ":", "lim", "-=", "1", "nSpaces", "-=", "1", "break", "if", "j", "<", "0", ":", "j", "=", "lim", "if", "g", "[", "0", "]", "is", "f", ":", "g", "[", "2", "]", "=", "j", "#extend", "else", ":", "g", "=", "(", "f", ",", "start", ",", "j", ")", "line", ".", "append", "(", "g", ")", "if", "j", "==", "lim", ":", "i", "+=", "1" ]
given a list of ParaFrags we return a list of ParaLines each ParaLine has 1) ExtraSpace 2) blankCount 3) [textDefns....] each text definition is a (ParaFrag, start, limit) triplet
[ "given", "a", "list", "of", "ParaFrags", "we", "return", "a", "list", "of", "ParaLines" ]
230357a392f48816532d3c2fa082a680b80ece48
https://github.com/xhtml2pdf/xhtml2pdf/blob/230357a392f48816532d3c2fa082a680b80ece48/xhtml2pdf/reportlab_paragraph.py#L592-L652
8,352
xhtml2pdf/xhtml2pdf
xhtml2pdf/reportlab_paragraph.py
cjkFragSplit
def cjkFragSplit(frags, maxWidths, calcBounds, encoding='utf8'): """ This attempts to be wordSplit for frags using the dumb algorithm """ from reportlab.rl_config import _FUZZ U = [] # get a list of single glyphs with their widths etc etc for f in frags: text = f.text if not isinstance(text, unicode): text = text.decode(encoding) if text: U.extend([cjkU(t, f, encoding) for t in text]) else: U.append(cjkU(text, f, encoding)) lines = [] widthUsed = lineStartPos = 0 maxWidth = maxWidths[0] for i, u in enumerate(U): w = u.width widthUsed += w lineBreak = hasattr(u.frag, 'lineBreak') endLine = (widthUsed > maxWidth + _FUZZ and widthUsed > 0) or lineBreak if endLine: if lineBreak: continue extraSpace = maxWidth - widthUsed + w #This is the most important of the Japanese typography rules. #if next character cannot start a line, wrap it up to this line so it hangs #in the right margin. We won't do two or more though - that's unlikely and #would result in growing ugliness. nextChar = U[i] if nextChar in ALL_CANNOT_START: extraSpace -= w i += 1 lines.append(makeCJKParaLine(U[lineStartPos:i], extraSpace, calcBounds)) try: maxWidth = maxWidths[len(lines)] except IndexError: maxWidth = maxWidths[-1] # use the last one lineStartPos = i widthUsed = w i -= 1 #any characters left? if widthUsed > 0: lines.append(makeCJKParaLine(U[lineStartPos:], maxWidth - widthUsed, calcBounds)) return ParaLines(kind=1, lines=lines)
python
def cjkFragSplit(frags, maxWidths, calcBounds, encoding='utf8'): """ This attempts to be wordSplit for frags using the dumb algorithm """ from reportlab.rl_config import _FUZZ U = [] # get a list of single glyphs with their widths etc etc for f in frags: text = f.text if not isinstance(text, unicode): text = text.decode(encoding) if text: U.extend([cjkU(t, f, encoding) for t in text]) else: U.append(cjkU(text, f, encoding)) lines = [] widthUsed = lineStartPos = 0 maxWidth = maxWidths[0] for i, u in enumerate(U): w = u.width widthUsed += w lineBreak = hasattr(u.frag, 'lineBreak') endLine = (widthUsed > maxWidth + _FUZZ and widthUsed > 0) or lineBreak if endLine: if lineBreak: continue extraSpace = maxWidth - widthUsed + w #This is the most important of the Japanese typography rules. #if next character cannot start a line, wrap it up to this line so it hangs #in the right margin. We won't do two or more though - that's unlikely and #would result in growing ugliness. nextChar = U[i] if nextChar in ALL_CANNOT_START: extraSpace -= w i += 1 lines.append(makeCJKParaLine(U[lineStartPos:i], extraSpace, calcBounds)) try: maxWidth = maxWidths[len(lines)] except IndexError: maxWidth = maxWidths[-1] # use the last one lineStartPos = i widthUsed = w i -= 1 #any characters left? if widthUsed > 0: lines.append(makeCJKParaLine(U[lineStartPos:], maxWidth - widthUsed, calcBounds)) return ParaLines(kind=1, lines=lines)
[ "def", "cjkFragSplit", "(", "frags", ",", "maxWidths", ",", "calcBounds", ",", "encoding", "=", "'utf8'", ")", ":", "from", "reportlab", ".", "rl_config", "import", "_FUZZ", "U", "=", "[", "]", "# get a list of single glyphs with their widths etc etc", "for", "f", "in", "frags", ":", "text", "=", "f", ".", "text", "if", "not", "isinstance", "(", "text", ",", "unicode", ")", ":", "text", "=", "text", ".", "decode", "(", "encoding", ")", "if", "text", ":", "U", ".", "extend", "(", "[", "cjkU", "(", "t", ",", "f", ",", "encoding", ")", "for", "t", "in", "text", "]", ")", "else", ":", "U", ".", "append", "(", "cjkU", "(", "text", ",", "f", ",", "encoding", ")", ")", "lines", "=", "[", "]", "widthUsed", "=", "lineStartPos", "=", "0", "maxWidth", "=", "maxWidths", "[", "0", "]", "for", "i", ",", "u", "in", "enumerate", "(", "U", ")", ":", "w", "=", "u", ".", "width", "widthUsed", "+=", "w", "lineBreak", "=", "hasattr", "(", "u", ".", "frag", ",", "'lineBreak'", ")", "endLine", "=", "(", "widthUsed", ">", "maxWidth", "+", "_FUZZ", "and", "widthUsed", ">", "0", ")", "or", "lineBreak", "if", "endLine", ":", "if", "lineBreak", ":", "continue", "extraSpace", "=", "maxWidth", "-", "widthUsed", "+", "w", "#This is the most important of the Japanese typography rules.", "#if next character cannot start a line, wrap it up to this line so it hangs", "#in the right margin. We won't do two or more though - that's unlikely and", "#would result in growing ugliness.", "nextChar", "=", "U", "[", "i", "]", "if", "nextChar", "in", "ALL_CANNOT_START", ":", "extraSpace", "-=", "w", "i", "+=", "1", "lines", ".", "append", "(", "makeCJKParaLine", "(", "U", "[", "lineStartPos", ":", "i", "]", ",", "extraSpace", ",", "calcBounds", ")", ")", "try", ":", "maxWidth", "=", "maxWidths", "[", "len", "(", "lines", ")", "]", "except", "IndexError", ":", "maxWidth", "=", "maxWidths", "[", "-", "1", "]", "# use the last one", "lineStartPos", "=", "i", "widthUsed", "=", "w", "i", "-=", "1", "#any characters left?", "if", "widthUsed", ">", "0", ":", "lines", ".", "append", "(", "makeCJKParaLine", "(", "U", "[", "lineStartPos", ":", "]", ",", "maxWidth", "-", "widthUsed", ",", "calcBounds", ")", ")", "return", "ParaLines", "(", "kind", "=", "1", ",", "lines", "=", "lines", ")" ]
This attempts to be wordSplit for frags using the dumb algorithm
[ "This", "attempts", "to", "be", "wordSplit", "for", "frags", "using", "the", "dumb", "algorithm" ]
230357a392f48816532d3c2fa082a680b80ece48
https://github.com/xhtml2pdf/xhtml2pdf/blob/230357a392f48816532d3c2fa082a680b80ece48/xhtml2pdf/reportlab_paragraph.py#L854-L904
8,353
xhtml2pdf/xhtml2pdf
xhtml2pdf/reportlab_paragraph.py
Paragraph.minWidth
def minWidth(self): """ Attempt to determine a minimum sensible width """ frags = self.frags nFrags = len(frags) if not nFrags: return 0 if nFrags == 1: f = frags[0] fS = f.fontSize fN = f.fontName words = hasattr(f, 'text') and split(f.text, ' ') or f.words func = lambda w, fS=fS, fN=fN: stringWidth(w, fN, fS) else: words = _getFragWords(frags) func = lambda x: x[0] return max(map(func, words))
python
def minWidth(self): """ Attempt to determine a minimum sensible width """ frags = self.frags nFrags = len(frags) if not nFrags: return 0 if nFrags == 1: f = frags[0] fS = f.fontSize fN = f.fontName words = hasattr(f, 'text') and split(f.text, ' ') or f.words func = lambda w, fS=fS, fN=fN: stringWidth(w, fN, fS) else: words = _getFragWords(frags) func = lambda x: x[0] return max(map(func, words))
[ "def", "minWidth", "(", "self", ")", ":", "frags", "=", "self", ".", "frags", "nFrags", "=", "len", "(", "frags", ")", "if", "not", "nFrags", ":", "return", "0", "if", "nFrags", "==", "1", ":", "f", "=", "frags", "[", "0", "]", "fS", "=", "f", ".", "fontSize", "fN", "=", "f", ".", "fontName", "words", "=", "hasattr", "(", "f", ",", "'text'", ")", "and", "split", "(", "f", ".", "text", ",", "' '", ")", "or", "f", ".", "words", "func", "=", "lambda", "w", ",", "fS", "=", "fS", ",", "fN", "=", "fN", ":", "stringWidth", "(", "w", ",", "fN", ",", "fS", ")", "else", ":", "words", "=", "_getFragWords", "(", "frags", ")", "func", "=", "lambda", "x", ":", "x", "[", "0", "]", "return", "max", "(", "map", "(", "func", ",", "words", ")", ")" ]
Attempt to determine a minimum sensible width
[ "Attempt", "to", "determine", "a", "minimum", "sensible", "width" ]
230357a392f48816532d3c2fa082a680b80ece48
https://github.com/xhtml2pdf/xhtml2pdf/blob/230357a392f48816532d3c2fa082a680b80ece48/xhtml2pdf/reportlab_paragraph.py#L1043-L1060
8,354
xhtml2pdf/xhtml2pdf
xhtml2pdf/reportlab_paragraph.py
Paragraph.breakLinesCJK
def breakLinesCJK(self, width): """Initially, the dumbest possible wrapping algorithm. Cannot handle font variations.""" if self.debug: print (id(self), "breakLinesCJK") if not isinstance(width, (list, tuple)): maxWidths = [width] else: maxWidths = width style = self.style #for bullets, work out width and ensure we wrap the right amount onto line one _handleBulletWidth(self.bulletText, style, maxWidths) if len(self.frags) > 1: autoLeading = getattr(self, 'autoLeading', getattr(style, 'autoLeading', '')) calcBounds = autoLeading not in ('', 'off') return cjkFragSplit(self.frags, maxWidths, calcBounds, self.encoding) elif not len(self.frags): return ParaLines(kind=0, fontSize=style.fontSize, fontName=style.fontName, textColor=style.textColor, lines=[], ascent=style.fontSize, descent=-0.2 * style.fontSize) f = self.frags[0] if 1 and hasattr(self, 'blPara') and getattr(self, '_splitpara', 0): #NB this is an utter hack that awaits the proper information #preserving splitting algorithm return f.clone(kind=0, lines=self.blPara.lines) lines = [] self.height = 0 f = self.frags[0] if hasattr(f, 'text'): text = f.text else: text = ''.join(getattr(f, 'words', [])) from reportlab.lib.textsplit import wordSplit lines = wordSplit(text, maxWidths[0], f.fontName, f.fontSize) #the paragraph drawing routine assumes multiple frags per line, so we need an #extra list like this # [space, [text]] # wrappedLines = [(sp, [line]) for (sp, line) in lines] return f.clone(kind=0, lines=wrappedLines, ascent=f.fontSize, descent=-0.2 * f.fontSize)
python
def breakLinesCJK(self, width): """Initially, the dumbest possible wrapping algorithm. Cannot handle font variations.""" if self.debug: print (id(self), "breakLinesCJK") if not isinstance(width, (list, tuple)): maxWidths = [width] else: maxWidths = width style = self.style #for bullets, work out width and ensure we wrap the right amount onto line one _handleBulletWidth(self.bulletText, style, maxWidths) if len(self.frags) > 1: autoLeading = getattr(self, 'autoLeading', getattr(style, 'autoLeading', '')) calcBounds = autoLeading not in ('', 'off') return cjkFragSplit(self.frags, maxWidths, calcBounds, self.encoding) elif not len(self.frags): return ParaLines(kind=0, fontSize=style.fontSize, fontName=style.fontName, textColor=style.textColor, lines=[], ascent=style.fontSize, descent=-0.2 * style.fontSize) f = self.frags[0] if 1 and hasattr(self, 'blPara') and getattr(self, '_splitpara', 0): #NB this is an utter hack that awaits the proper information #preserving splitting algorithm return f.clone(kind=0, lines=self.blPara.lines) lines = [] self.height = 0 f = self.frags[0] if hasattr(f, 'text'): text = f.text else: text = ''.join(getattr(f, 'words', [])) from reportlab.lib.textsplit import wordSplit lines = wordSplit(text, maxWidths[0], f.fontName, f.fontSize) #the paragraph drawing routine assumes multiple frags per line, so we need an #extra list like this # [space, [text]] # wrappedLines = [(sp, [line]) for (sp, line) in lines] return f.clone(kind=0, lines=wrappedLines, ascent=f.fontSize, descent=-0.2 * f.fontSize)
[ "def", "breakLinesCJK", "(", "self", ",", "width", ")", ":", "if", "self", ".", "debug", ":", "print", "(", "id", "(", "self", ")", ",", "\"breakLinesCJK\"", ")", "if", "not", "isinstance", "(", "width", ",", "(", "list", ",", "tuple", ")", ")", ":", "maxWidths", "=", "[", "width", "]", "else", ":", "maxWidths", "=", "width", "style", "=", "self", ".", "style", "#for bullets, work out width and ensure we wrap the right amount onto line one", "_handleBulletWidth", "(", "self", ".", "bulletText", ",", "style", ",", "maxWidths", ")", "if", "len", "(", "self", ".", "frags", ")", ">", "1", ":", "autoLeading", "=", "getattr", "(", "self", ",", "'autoLeading'", ",", "getattr", "(", "style", ",", "'autoLeading'", ",", "''", ")", ")", "calcBounds", "=", "autoLeading", "not", "in", "(", "''", ",", "'off'", ")", "return", "cjkFragSplit", "(", "self", ".", "frags", ",", "maxWidths", ",", "calcBounds", ",", "self", ".", "encoding", ")", "elif", "not", "len", "(", "self", ".", "frags", ")", ":", "return", "ParaLines", "(", "kind", "=", "0", ",", "fontSize", "=", "style", ".", "fontSize", ",", "fontName", "=", "style", ".", "fontName", ",", "textColor", "=", "style", ".", "textColor", ",", "lines", "=", "[", "]", ",", "ascent", "=", "style", ".", "fontSize", ",", "descent", "=", "-", "0.2", "*", "style", ".", "fontSize", ")", "f", "=", "self", ".", "frags", "[", "0", "]", "if", "1", "and", "hasattr", "(", "self", ",", "'blPara'", ")", "and", "getattr", "(", "self", ",", "'_splitpara'", ",", "0", ")", ":", "#NB this is an utter hack that awaits the proper information", "#preserving splitting algorithm", "return", "f", ".", "clone", "(", "kind", "=", "0", ",", "lines", "=", "self", ".", "blPara", ".", "lines", ")", "lines", "=", "[", "]", "self", ".", "height", "=", "0", "f", "=", "self", ".", "frags", "[", "0", "]", "if", "hasattr", "(", "f", ",", "'text'", ")", ":", "text", "=", "f", ".", "text", "else", ":", "text", "=", "''", ".", "join", "(", "getattr", "(", "f", ",", "'words'", ",", "[", "]", ")", ")", "from", "reportlab", ".", "lib", ".", "textsplit", "import", "wordSplit", "lines", "=", "wordSplit", "(", "text", ",", "maxWidths", "[", "0", "]", ",", "f", ".", "fontName", ",", "f", ".", "fontSize", ")", "#the paragraph drawing routine assumes multiple frags per line, so we need an", "#extra list like this", "# [space, [text]]", "#", "wrappedLines", "=", "[", "(", "sp", ",", "[", "line", "]", ")", "for", "(", "sp", ",", "line", ")", "in", "lines", "]", "return", "f", ".", "clone", "(", "kind", "=", "0", ",", "lines", "=", "wrappedLines", ",", "ascent", "=", "f", ".", "fontSize", ",", "descent", "=", "-", "0.2", "*", "f", ".", "fontSize", ")" ]
Initially, the dumbest possible wrapping algorithm. Cannot handle font variations.
[ "Initially", "the", "dumbest", "possible", "wrapping", "algorithm", ".", "Cannot", "handle", "font", "variations", "." ]
230357a392f48816532d3c2fa082a680b80ece48
https://github.com/xhtml2pdf/xhtml2pdf/blob/230357a392f48816532d3c2fa082a680b80ece48/xhtml2pdf/reportlab_paragraph.py#L1409-L1456
8,355
xhtml2pdf/xhtml2pdf
xhtml2pdf/reportlab_paragraph.py
Paragraph.getPlainText
def getPlainText(self, identify=None): """ Convenience function for templates which want access to the raw text, without XML tags. """ frags = getattr(self, 'frags', None) if frags: plains = [] for frag in frags: if hasattr(frag, 'text'): plains.append(frag.text) return ''.join(plains) elif identify: text = getattr(self, 'text', None) if text is None: text = repr(self) return text else: return ''
python
def getPlainText(self, identify=None): """ Convenience function for templates which want access to the raw text, without XML tags. """ frags = getattr(self, 'frags', None) if frags: plains = [] for frag in frags: if hasattr(frag, 'text'): plains.append(frag.text) return ''.join(plains) elif identify: text = getattr(self, 'text', None) if text is None: text = repr(self) return text else: return ''
[ "def", "getPlainText", "(", "self", ",", "identify", "=", "None", ")", ":", "frags", "=", "getattr", "(", "self", ",", "'frags'", ",", "None", ")", "if", "frags", ":", "plains", "=", "[", "]", "for", "frag", "in", "frags", ":", "if", "hasattr", "(", "frag", ",", "'text'", ")", ":", "plains", ".", "append", "(", "frag", ".", "text", ")", "return", "''", ".", "join", "(", "plains", ")", "elif", "identify", ":", "text", "=", "getattr", "(", "self", ",", "'text'", ",", "None", ")", "if", "text", "is", "None", ":", "text", "=", "repr", "(", "self", ")", "return", "text", "else", ":", "return", "''" ]
Convenience function for templates which want access to the raw text, without XML tags.
[ "Convenience", "function", "for", "templates", "which", "want", "access", "to", "the", "raw", "text", "without", "XML", "tags", "." ]
230357a392f48816532d3c2fa082a680b80ece48
https://github.com/xhtml2pdf/xhtml2pdf/blob/230357a392f48816532d3c2fa082a680b80ece48/xhtml2pdf/reportlab_paragraph.py#L1657-L1675
8,356
xhtml2pdf/xhtml2pdf
xhtml2pdf/reportlab_paragraph.py
Paragraph.getActualLineWidths0
def getActualLineWidths0(self): """ Convenience function; tells you how wide each line actually is. For justified styles, this will be the same as the wrap width; for others it might be useful for seeing if paragraphs will fit in spaces. """ assert hasattr(self, 'width'), "Cannot call this method before wrap()" if self.blPara.kind: func = lambda frag, w=self.width: w - frag.extraSpace else: func = lambda frag, w=self.width: w - frag[0] return map(func, self.blPara.lines)
python
def getActualLineWidths0(self): """ Convenience function; tells you how wide each line actually is. For justified styles, this will be the same as the wrap width; for others it might be useful for seeing if paragraphs will fit in spaces. """ assert hasattr(self, 'width'), "Cannot call this method before wrap()" if self.blPara.kind: func = lambda frag, w=self.width: w - frag.extraSpace else: func = lambda frag, w=self.width: w - frag[0] return map(func, self.blPara.lines)
[ "def", "getActualLineWidths0", "(", "self", ")", ":", "assert", "hasattr", "(", "self", ",", "'width'", ")", ",", "\"Cannot call this method before wrap()\"", "if", "self", ".", "blPara", ".", "kind", ":", "func", "=", "lambda", "frag", ",", "w", "=", "self", ".", "width", ":", "w", "-", "frag", ".", "extraSpace", "else", ":", "func", "=", "lambda", "frag", ",", "w", "=", "self", ".", "width", ":", "w", "-", "frag", "[", "0", "]", "return", "map", "(", "func", ",", "self", ".", "blPara", ".", "lines", ")" ]
Convenience function; tells you how wide each line actually is. For justified styles, this will be the same as the wrap width; for others it might be useful for seeing if paragraphs will fit in spaces.
[ "Convenience", "function", ";", "tells", "you", "how", "wide", "each", "line", "actually", "is", ".", "For", "justified", "styles", "this", "will", "be", "the", "same", "as", "the", "wrap", "width", ";", "for", "others", "it", "might", "be", "useful", "for", "seeing", "if", "paragraphs", "will", "fit", "in", "spaces", "." ]
230357a392f48816532d3c2fa082a680b80ece48
https://github.com/xhtml2pdf/xhtml2pdf/blob/230357a392f48816532d3c2fa082a680b80ece48/xhtml2pdf/reportlab_paragraph.py#L1677-L1690
8,357
xhtml2pdf/xhtml2pdf
demo/djangoproject/views.py
link_callback
def link_callback(uri, rel): """ Convert HTML URIs to absolute system paths so xhtml2pdf can access those resources """ # use short variable names sUrl = settings.STATIC_URL # Typically /static/ sRoot = settings.STATIC_ROOT # Typically /home/userX/project_static/ mUrl = settings.MEDIA_URL # Typically /static/media/ # Typically /home/userX/project_static/media/ mRoot = settings.MEDIA_ROOT # convert URIs to absolute system paths if uri.startswith(mUrl): path = os.path.join(mRoot, uri.replace(mUrl, "")) elif uri.startswith(sUrl): path = os.path.join(sRoot, uri.replace(sUrl, "")) else: return uri # handle absolute uri (ie: http://some.tld/foo.png) # make sure that file exists if not os.path.isfile(path): raise Exception( 'media URI must start with %s or %s' % (sUrl, mUrl) ) return path
python
def link_callback(uri, rel): """ Convert HTML URIs to absolute system paths so xhtml2pdf can access those resources """ # use short variable names sUrl = settings.STATIC_URL # Typically /static/ sRoot = settings.STATIC_ROOT # Typically /home/userX/project_static/ mUrl = settings.MEDIA_URL # Typically /static/media/ # Typically /home/userX/project_static/media/ mRoot = settings.MEDIA_ROOT # convert URIs to absolute system paths if uri.startswith(mUrl): path = os.path.join(mRoot, uri.replace(mUrl, "")) elif uri.startswith(sUrl): path = os.path.join(sRoot, uri.replace(sUrl, "")) else: return uri # handle absolute uri (ie: http://some.tld/foo.png) # make sure that file exists if not os.path.isfile(path): raise Exception( 'media URI must start with %s or %s' % (sUrl, mUrl) ) return path
[ "def", "link_callback", "(", "uri", ",", "rel", ")", ":", "# use short variable names", "sUrl", "=", "settings", ".", "STATIC_URL", "# Typically /static/", "sRoot", "=", "settings", ".", "STATIC_ROOT", "# Typically /home/userX/project_static/", "mUrl", "=", "settings", ".", "MEDIA_URL", "# Typically /static/media/", "# Typically /home/userX/project_static/media/", "mRoot", "=", "settings", ".", "MEDIA_ROOT", "# convert URIs to absolute system paths", "if", "uri", ".", "startswith", "(", "mUrl", ")", ":", "path", "=", "os", ".", "path", ".", "join", "(", "mRoot", ",", "uri", ".", "replace", "(", "mUrl", ",", "\"\"", ")", ")", "elif", "uri", ".", "startswith", "(", "sUrl", ")", ":", "path", "=", "os", ".", "path", ".", "join", "(", "sRoot", ",", "uri", ".", "replace", "(", "sUrl", ",", "\"\"", ")", ")", "else", ":", "return", "uri", "# handle absolute uri (ie: http://some.tld/foo.png)", "# make sure that file exists", "if", "not", "os", ".", "path", ".", "isfile", "(", "path", ")", ":", "raise", "Exception", "(", "'media URI must start with %s or %s'", "%", "(", "sUrl", ",", "mUrl", ")", ")", "return", "path" ]
Convert HTML URIs to absolute system paths so xhtml2pdf can access those resources
[ "Convert", "HTML", "URIs", "to", "absolute", "system", "paths", "so", "xhtml2pdf", "can", "access", "those", "resources" ]
230357a392f48816532d3c2fa082a680b80ece48
https://github.com/xhtml2pdf/xhtml2pdf/blob/230357a392f48816532d3c2fa082a680b80ece48/demo/djangoproject/views.py#L23-L48
8,358
xhtml2pdf/xhtml2pdf
demo/tgpisa/tgpisa/commands.py
start
def start(): """Start the CherryPy application server.""" setupdir = dirname(dirname(__file__)) curdir = os.getcwd() # First look on the command line for a desired config file, # if it's not on the command line, then look for 'setup.py' # in the current directory. If there, load configuration # from a file called 'dev.cfg'. If it's not there, the project # is probably installed and we'll look first for a file called # 'prod.cfg' in the current directory and then for a default # config file called 'default.cfg' packaged in the egg. if len(sys.argv) > 1: configfile = sys.argv[1] elif exists(join(setupdir, "setup.py")): configfile = join(setupdir, "dev.cfg") elif exists(join(curdir, "prod.cfg")): configfile = join(curdir, "prod.cfg") else: try: configfile = pkg_resources.resource_filename( pkg_resources.Requirement.parse("tgpisa"), "config/default.cfg") except pkg_resources.DistributionNotFound: raise ConfigurationError("Could not find default configuration.") turbogears.update_config(configfile=configfile, modulename="tgpisa.config") from tgpisa.controllers import Root turbogears.start_server(Root())
python
def start(): """Start the CherryPy application server.""" setupdir = dirname(dirname(__file__)) curdir = os.getcwd() # First look on the command line for a desired config file, # if it's not on the command line, then look for 'setup.py' # in the current directory. If there, load configuration # from a file called 'dev.cfg'. If it's not there, the project # is probably installed and we'll look first for a file called # 'prod.cfg' in the current directory and then for a default # config file called 'default.cfg' packaged in the egg. if len(sys.argv) > 1: configfile = sys.argv[1] elif exists(join(setupdir, "setup.py")): configfile = join(setupdir, "dev.cfg") elif exists(join(curdir, "prod.cfg")): configfile = join(curdir, "prod.cfg") else: try: configfile = pkg_resources.resource_filename( pkg_resources.Requirement.parse("tgpisa"), "config/default.cfg") except pkg_resources.DistributionNotFound: raise ConfigurationError("Could not find default configuration.") turbogears.update_config(configfile=configfile, modulename="tgpisa.config") from tgpisa.controllers import Root turbogears.start_server(Root())
[ "def", "start", "(", ")", ":", "setupdir", "=", "dirname", "(", "dirname", "(", "__file__", ")", ")", "curdir", "=", "os", ".", "getcwd", "(", ")", "# First look on the command line for a desired config file,", "# if it's not on the command line, then look for 'setup.py'", "# in the current directory. If there, load configuration", "# from a file called 'dev.cfg'. If it's not there, the project", "# is probably installed and we'll look first for a file called", "# 'prod.cfg' in the current directory and then for a default", "# config file called 'default.cfg' packaged in the egg.", "if", "len", "(", "sys", ".", "argv", ")", ">", "1", ":", "configfile", "=", "sys", ".", "argv", "[", "1", "]", "elif", "exists", "(", "join", "(", "setupdir", ",", "\"setup.py\"", ")", ")", ":", "configfile", "=", "join", "(", "setupdir", ",", "\"dev.cfg\"", ")", "elif", "exists", "(", "join", "(", "curdir", ",", "\"prod.cfg\"", ")", ")", ":", "configfile", "=", "join", "(", "curdir", ",", "\"prod.cfg\"", ")", "else", ":", "try", ":", "configfile", "=", "pkg_resources", ".", "resource_filename", "(", "pkg_resources", ".", "Requirement", ".", "parse", "(", "\"tgpisa\"", ")", ",", "\"config/default.cfg\"", ")", "except", "pkg_resources", ".", "DistributionNotFound", ":", "raise", "ConfigurationError", "(", "\"Could not find default configuration.\"", ")", "turbogears", ".", "update_config", "(", "configfile", "=", "configfile", ",", "modulename", "=", "\"tgpisa.config\"", ")", "from", "tgpisa", ".", "controllers", "import", "Root", "turbogears", ".", "start_server", "(", "Root", "(", ")", ")" ]
Start the CherryPy application server.
[ "Start", "the", "CherryPy", "application", "server", "." ]
230357a392f48816532d3c2fa082a680b80ece48
https://github.com/xhtml2pdf/xhtml2pdf/blob/230357a392f48816532d3c2fa082a680b80ece48/demo/tgpisa/tgpisa/commands.py#L20-L52
8,359
xhtml2pdf/xhtml2pdf
xhtml2pdf/w3c/css.py
CSSRuleset.mergeStyles
def mergeStyles(self, styles): " XXX Bugfix for use in PISA " for k, v in six.iteritems(styles): if k in self and self[k]: self[k] = copy.copy(self[k]) self[k].update(v) else: self[k] = v
python
def mergeStyles(self, styles): " XXX Bugfix for use in PISA " for k, v in six.iteritems(styles): if k in self and self[k]: self[k] = copy.copy(self[k]) self[k].update(v) else: self[k] = v
[ "def", "mergeStyles", "(", "self", ",", "styles", ")", ":", "for", "k", ",", "v", "in", "six", ".", "iteritems", "(", "styles", ")", ":", "if", "k", "in", "self", "and", "self", "[", "k", "]", ":", "self", "[", "k", "]", "=", "copy", ".", "copy", "(", "self", "[", "k", "]", ")", "self", "[", "k", "]", ".", "update", "(", "v", ")", "else", ":", "self", "[", "k", "]", "=", "v" ]
XXX Bugfix for use in PISA
[ "XXX", "Bugfix", "for", "use", "in", "PISA" ]
230357a392f48816532d3c2fa082a680b80ece48
https://github.com/xhtml2pdf/xhtml2pdf/blob/230357a392f48816532d3c2fa082a680b80ece48/xhtml2pdf/w3c/css.py#L697-L704
8,360
xhtml2pdf/xhtml2pdf
xhtml2pdf/w3c/css.py
CSSBuilder.atPage
def atPage(self, page, pseudopage, declarations): """ This is overriden by xhtml2pdf.context.pisaCSSBuilder """ return self.ruleset([self.selector('*')], declarations)
python
def atPage(self, page, pseudopage, declarations): """ This is overriden by xhtml2pdf.context.pisaCSSBuilder """ return self.ruleset([self.selector('*')], declarations)
[ "def", "atPage", "(", "self", ",", "page", ",", "pseudopage", ",", "declarations", ")", ":", "return", "self", ".", "ruleset", "(", "[", "self", ".", "selector", "(", "'*'", ")", "]", ",", "declarations", ")" ]
This is overriden by xhtml2pdf.context.pisaCSSBuilder
[ "This", "is", "overriden", "by", "xhtml2pdf", ".", "context", ".", "pisaCSSBuilder" ]
230357a392f48816532d3c2fa082a680b80ece48
https://github.com/xhtml2pdf/xhtml2pdf/blob/230357a392f48816532d3c2fa082a680b80ece48/xhtml2pdf/w3c/css.py#L905-L909
8,361
xhtml2pdf/xhtml2pdf
xhtml2pdf/xhtml2pdf_reportlab.py
PmlBaseDoc.handle_nextPageTemplate
def handle_nextPageTemplate(self, pt): ''' if pt has also templates for even and odd page convert it to list ''' has_left_template = self._has_template_for_name(pt + '_left') has_right_template = self._has_template_for_name(pt + '_right') if has_left_template and has_right_template: pt = [pt + '_left', pt + '_right'] '''On endPage change to the page template with name or index pt''' if isinstance(pt, str): if hasattr(self, '_nextPageTemplateCycle'): del self._nextPageTemplateCycle for t in self.pageTemplates: if t.id == pt: self._nextPageTemplateIndex = self.pageTemplates.index(t) return raise ValueError("can't find template('%s')" % pt) elif isinstance(pt, int): if hasattr(self, '_nextPageTemplateCycle'): del self._nextPageTemplateCycle self._nextPageTemplateIndex = pt elif isinstance(pt, (list, tuple)): #used for alternating left/right pages #collect the refs to the template objects, complain if any are bad c = PTCycle() for ptn in pt: #special case name used to short circuit the iteration if ptn == '*': c._restart = len(c) continue for t in self.pageTemplates: if t.id == ptn.strip(): c.append(t) break if not c: raise ValueError("No valid page templates in cycle") elif c._restart > len(c): raise ValueError("Invalid cycle restart position") #ensure we start on the first one$ self._nextPageTemplateCycle = c.cyclicIterator() else: raise TypeError("Argument pt should be string or integer or list")
python
def handle_nextPageTemplate(self, pt): ''' if pt has also templates for even and odd page convert it to list ''' has_left_template = self._has_template_for_name(pt + '_left') has_right_template = self._has_template_for_name(pt + '_right') if has_left_template and has_right_template: pt = [pt + '_left', pt + '_right'] '''On endPage change to the page template with name or index pt''' if isinstance(pt, str): if hasattr(self, '_nextPageTemplateCycle'): del self._nextPageTemplateCycle for t in self.pageTemplates: if t.id == pt: self._nextPageTemplateIndex = self.pageTemplates.index(t) return raise ValueError("can't find template('%s')" % pt) elif isinstance(pt, int): if hasattr(self, '_nextPageTemplateCycle'): del self._nextPageTemplateCycle self._nextPageTemplateIndex = pt elif isinstance(pt, (list, tuple)): #used for alternating left/right pages #collect the refs to the template objects, complain if any are bad c = PTCycle() for ptn in pt: #special case name used to short circuit the iteration if ptn == '*': c._restart = len(c) continue for t in self.pageTemplates: if t.id == ptn.strip(): c.append(t) break if not c: raise ValueError("No valid page templates in cycle") elif c._restart > len(c): raise ValueError("Invalid cycle restart position") #ensure we start on the first one$ self._nextPageTemplateCycle = c.cyclicIterator() else: raise TypeError("Argument pt should be string or integer or list")
[ "def", "handle_nextPageTemplate", "(", "self", ",", "pt", ")", ":", "has_left_template", "=", "self", ".", "_has_template_for_name", "(", "pt", "+", "'_left'", ")", "has_right_template", "=", "self", ".", "_has_template_for_name", "(", "pt", "+", "'_right'", ")", "if", "has_left_template", "and", "has_right_template", ":", "pt", "=", "[", "pt", "+", "'_left'", ",", "pt", "+", "'_right'", "]", "'''On endPage change to the page template with name or index pt'''", "if", "isinstance", "(", "pt", ",", "str", ")", ":", "if", "hasattr", "(", "self", ",", "'_nextPageTemplateCycle'", ")", ":", "del", "self", ".", "_nextPageTemplateCycle", "for", "t", "in", "self", ".", "pageTemplates", ":", "if", "t", ".", "id", "==", "pt", ":", "self", ".", "_nextPageTemplateIndex", "=", "self", ".", "pageTemplates", ".", "index", "(", "t", ")", "return", "raise", "ValueError", "(", "\"can't find template('%s')\"", "%", "pt", ")", "elif", "isinstance", "(", "pt", ",", "int", ")", ":", "if", "hasattr", "(", "self", ",", "'_nextPageTemplateCycle'", ")", ":", "del", "self", ".", "_nextPageTemplateCycle", "self", ".", "_nextPageTemplateIndex", "=", "pt", "elif", "isinstance", "(", "pt", ",", "(", "list", ",", "tuple", ")", ")", ":", "#used for alternating left/right pages", "#collect the refs to the template objects, complain if any are bad", "c", "=", "PTCycle", "(", ")", "for", "ptn", "in", "pt", ":", "#special case name used to short circuit the iteration", "if", "ptn", "==", "'*'", ":", "c", ".", "_restart", "=", "len", "(", "c", ")", "continue", "for", "t", "in", "self", ".", "pageTemplates", ":", "if", "t", ".", "id", "==", "ptn", ".", "strip", "(", ")", ":", "c", ".", "append", "(", "t", ")", "break", "if", "not", "c", ":", "raise", "ValueError", "(", "\"No valid page templates in cycle\"", ")", "elif", "c", ".", "_restart", ">", "len", "(", "c", ")", ":", "raise", "ValueError", "(", "\"Invalid cycle restart position\"", ")", "#ensure we start on the first one$", "self", ".", "_nextPageTemplateCycle", "=", "c", ".", "cyclicIterator", "(", ")", "else", ":", "raise", "TypeError", "(", "\"Argument pt should be string or integer or list\"", ")" ]
if pt has also templates for even and odd page convert it to list
[ "if", "pt", "has", "also", "templates", "for", "even", "and", "odd", "page", "convert", "it", "to", "list" ]
230357a392f48816532d3c2fa082a680b80ece48
https://github.com/xhtml2pdf/xhtml2pdf/blob/230357a392f48816532d3c2fa082a680b80ece48/xhtml2pdf/xhtml2pdf_reportlab.py#L125-L169
8,362
xhtml2pdf/xhtml2pdf
xhtml2pdf/xhtml2pdf_reportlab.py
PmlImageReader.getRGBData
def getRGBData(self): "Return byte array of RGB data as string" if self._data is None: self._dataA = None if sys.platform[0:4] == 'java': import jarray # TODO: Move to top. from java.awt.image import PixelGrabber width, height = self.getSize() buffer = jarray.zeros(width * height, 'i') pg = PixelGrabber(self._image, 0, 0, width, height, buffer, 0, width) pg.grabPixels() # there must be a way to do this with a cast not a byte-level loop, # I just haven't found it yet... pixels = [] a = pixels.append for rgb in buffer: a(chr((rgb >> 16) & 0xff)) a(chr((rgb >> 8) & 0xff)) a(chr(rgb & 0xff)) self._data = ''.join(pixels) self.mode = 'RGB' else: im = self._image mode = self.mode = im.mode if mode == 'RGBA': im.load() self._dataA = PmlImageReader(im.split()[3]) im = im.convert('RGB') self.mode = 'RGB' elif mode not in ('L', 'RGB', 'CMYK'): im = im.convert('RGB') self.mode = 'RGB' if hasattr(im, 'tobytes'): self._data = im.tobytes() else: # PIL compatibility self._data = im.tostring() return self._data
python
def getRGBData(self): "Return byte array of RGB data as string" if self._data is None: self._dataA = None if sys.platform[0:4] == 'java': import jarray # TODO: Move to top. from java.awt.image import PixelGrabber width, height = self.getSize() buffer = jarray.zeros(width * height, 'i') pg = PixelGrabber(self._image, 0, 0, width, height, buffer, 0, width) pg.grabPixels() # there must be a way to do this with a cast not a byte-level loop, # I just haven't found it yet... pixels = [] a = pixels.append for rgb in buffer: a(chr((rgb >> 16) & 0xff)) a(chr((rgb >> 8) & 0xff)) a(chr(rgb & 0xff)) self._data = ''.join(pixels) self.mode = 'RGB' else: im = self._image mode = self.mode = im.mode if mode == 'RGBA': im.load() self._dataA = PmlImageReader(im.split()[3]) im = im.convert('RGB') self.mode = 'RGB' elif mode not in ('L', 'RGB', 'CMYK'): im = im.convert('RGB') self.mode = 'RGB' if hasattr(im, 'tobytes'): self._data = im.tobytes() else: # PIL compatibility self._data = im.tostring() return self._data
[ "def", "getRGBData", "(", "self", ")", ":", "if", "self", ".", "_data", "is", "None", ":", "self", ".", "_dataA", "=", "None", "if", "sys", ".", "platform", "[", "0", ":", "4", "]", "==", "'java'", ":", "import", "jarray", "# TODO: Move to top.", "from", "java", ".", "awt", ".", "image", "import", "PixelGrabber", "width", ",", "height", "=", "self", ".", "getSize", "(", ")", "buffer", "=", "jarray", ".", "zeros", "(", "width", "*", "height", ",", "'i'", ")", "pg", "=", "PixelGrabber", "(", "self", ".", "_image", ",", "0", ",", "0", ",", "width", ",", "height", ",", "buffer", ",", "0", ",", "width", ")", "pg", ".", "grabPixels", "(", ")", "# there must be a way to do this with a cast not a byte-level loop,", "# I just haven't found it yet...", "pixels", "=", "[", "]", "a", "=", "pixels", ".", "append", "for", "rgb", "in", "buffer", ":", "a", "(", "chr", "(", "(", "rgb", ">>", "16", ")", "&", "0xff", ")", ")", "a", "(", "chr", "(", "(", "rgb", ">>", "8", ")", "&", "0xff", ")", ")", "a", "(", "chr", "(", "rgb", "&", "0xff", ")", ")", "self", ".", "_data", "=", "''", ".", "join", "(", "pixels", ")", "self", ".", "mode", "=", "'RGB'", "else", ":", "im", "=", "self", ".", "_image", "mode", "=", "self", ".", "mode", "=", "im", ".", "mode", "if", "mode", "==", "'RGBA'", ":", "im", ".", "load", "(", ")", "self", ".", "_dataA", "=", "PmlImageReader", "(", "im", ".", "split", "(", ")", "[", "3", "]", ")", "im", "=", "im", ".", "convert", "(", "'RGB'", ")", "self", ".", "mode", "=", "'RGB'", "elif", "mode", "not", "in", "(", "'L'", ",", "'RGB'", ",", "'CMYK'", ")", ":", "im", "=", "im", ".", "convert", "(", "'RGB'", ")", "self", ".", "mode", "=", "'RGB'", "if", "hasattr", "(", "im", ",", "'tobytes'", ")", ":", "self", ".", "_data", "=", "im", ".", "tobytes", "(", ")", "else", ":", "# PIL compatibility", "self", ".", "_data", "=", "im", ".", "tostring", "(", ")", "return", "self", ".", "_data" ]
Return byte array of RGB data as string
[ "Return", "byte", "array", "of", "RGB", "data", "as", "string" ]
230357a392f48816532d3c2fa082a680b80ece48
https://github.com/xhtml2pdf/xhtml2pdf/blob/230357a392f48816532d3c2fa082a680b80ece48/xhtml2pdf/xhtml2pdf_reportlab.py#L396-L434
8,363
xhtml2pdf/xhtml2pdf
xhtml2pdf/xhtml2pdf_reportlab.py
PmlImage.wrap
def wrap(self, availWidth, availHeight): " This can be called more than once! Do not overwrite important data like drawWidth " availHeight = self.setMaxHeight(availHeight) # print "image wrap", id(self), availWidth, availHeight, self.drawWidth, self.drawHeight width = min(self.drawWidth, availWidth) wfactor = float(width) / self.drawWidth height = min(self.drawHeight, availHeight * MAX_IMAGE_RATIO) hfactor = float(height) / self.drawHeight factor = min(wfactor, hfactor) self.dWidth = self.drawWidth * factor self.dHeight = self.drawHeight * factor # print "imgage result", factor, self.dWidth, self.dHeight return self.dWidth, self.dHeight
python
def wrap(self, availWidth, availHeight): " This can be called more than once! Do not overwrite important data like drawWidth " availHeight = self.setMaxHeight(availHeight) # print "image wrap", id(self), availWidth, availHeight, self.drawWidth, self.drawHeight width = min(self.drawWidth, availWidth) wfactor = float(width) / self.drawWidth height = min(self.drawHeight, availHeight * MAX_IMAGE_RATIO) hfactor = float(height) / self.drawHeight factor = min(wfactor, hfactor) self.dWidth = self.drawWidth * factor self.dHeight = self.drawHeight * factor # print "imgage result", factor, self.dWidth, self.dHeight return self.dWidth, self.dHeight
[ "def", "wrap", "(", "self", ",", "availWidth", ",", "availHeight", ")", ":", "availHeight", "=", "self", ".", "setMaxHeight", "(", "availHeight", ")", "# print \"image wrap\", id(self), availWidth, availHeight, self.drawWidth, self.drawHeight", "width", "=", "min", "(", "self", ".", "drawWidth", ",", "availWidth", ")", "wfactor", "=", "float", "(", "width", ")", "/", "self", ".", "drawWidth", "height", "=", "min", "(", "self", ".", "drawHeight", ",", "availHeight", "*", "MAX_IMAGE_RATIO", ")", "hfactor", "=", "float", "(", "height", ")", "/", "self", ".", "drawHeight", "factor", "=", "min", "(", "wfactor", ",", "hfactor", ")", "self", ".", "dWidth", "=", "self", ".", "drawWidth", "*", "factor", "self", ".", "dHeight", "=", "self", ".", "drawHeight", "*", "factor", "# print \"imgage result\", factor, self.dWidth, self.dHeight", "return", "self", ".", "dWidth", ",", "self", ".", "dHeight" ]
This can be called more than once! Do not overwrite important data like drawWidth
[ "This", "can", "be", "called", "more", "than", "once!", "Do", "not", "overwrite", "important", "data", "like", "drawWidth" ]
230357a392f48816532d3c2fa082a680b80ece48
https://github.com/xhtml2pdf/xhtml2pdf/blob/230357a392f48816532d3c2fa082a680b80ece48/xhtml2pdf/xhtml2pdf_reportlab.py#L490-L502
8,364
xhtml2pdf/xhtml2pdf
xhtml2pdf/xhtml2pdf_reportlab.py
PmlTable._normWidth
def _normWidth(self, w, maxw): """ Helper for calculating percentages """ if type(w) == type(""): w = ((maxw / 100.0) * float(w[: - 1])) elif (w is None) or (w == "*"): w = maxw return min(w, maxw)
python
def _normWidth(self, w, maxw): """ Helper for calculating percentages """ if type(w) == type(""): w = ((maxw / 100.0) * float(w[: - 1])) elif (w is None) or (w == "*"): w = maxw return min(w, maxw)
[ "def", "_normWidth", "(", "self", ",", "w", ",", "maxw", ")", ":", "if", "type", "(", "w", ")", "==", "type", "(", "\"\"", ")", ":", "w", "=", "(", "(", "maxw", "/", "100.0", ")", "*", "float", "(", "w", "[", ":", "-", "1", "]", ")", ")", "elif", "(", "w", "is", "None", ")", "or", "(", "w", "==", "\"*\"", ")", ":", "w", "=", "maxw", "return", "min", "(", "w", ",", "maxw", ")" ]
Helper for calculating percentages
[ "Helper", "for", "calculating", "percentages" ]
230357a392f48816532d3c2fa082a680b80ece48
https://github.com/xhtml2pdf/xhtml2pdf/blob/230357a392f48816532d3c2fa082a680b80ece48/xhtml2pdf/xhtml2pdf_reportlab.py#L707-L715
8,365
xhtml2pdf/xhtml2pdf
xhtml2pdf/xhtml2pdf_reportlab.py
PmlTableOfContents.wrap
def wrap(self, availWidth, availHeight): """ All table properties should be known by now. """ widths = (availWidth - self.rightColumnWidth, self.rightColumnWidth) # makes an internal table which does all the work. # we draw the LAST RUN's entries! If there are # none, we make some dummy data to keep the table # from complaining if len(self._lastEntries) == 0: _tempEntries = [(0, 'Placeholder for table of contents', 0)] else: _tempEntries = self._lastEntries lastMargin = 0 tableData = [] tableStyle = [ ('VALIGN', (0, 0), (- 1, - 1), 'TOP'), ('LEFTPADDING', (0, 0), (- 1, - 1), 0), ('RIGHTPADDING', (0, 0), (- 1, - 1), 0), ('TOPPADDING', (0, 0), (- 1, - 1), 0), ('BOTTOMPADDING', (0, 0), (- 1, - 1), 0), ] for i, entry in enumerate(_tempEntries): level, text, pageNum = entry[:3] leftColStyle = self.levelStyles[level] if i: # Not for first element tableStyle.append(( 'TOPPADDING', (0, i), (- 1, i), max(lastMargin, leftColStyle.spaceBefore))) # print leftColStyle.leftIndent lastMargin = leftColStyle.spaceAfter #right col style is right aligned rightColStyle = ParagraphStyle(name='leftColLevel%d' % level, parent=leftColStyle, leftIndent=0, alignment=TA_RIGHT) leftPara = Paragraph(text, leftColStyle) rightPara = Paragraph(str(pageNum), rightColStyle) tableData.append([leftPara, rightPara]) self._table = Table( tableData, colWidths=widths, style=TableStyle(tableStyle)) self.width, self.height = self._table.wrapOn(self.canv, availWidth, availHeight) return self.width, self.height
python
def wrap(self, availWidth, availHeight): """ All table properties should be known by now. """ widths = (availWidth - self.rightColumnWidth, self.rightColumnWidth) # makes an internal table which does all the work. # we draw the LAST RUN's entries! If there are # none, we make some dummy data to keep the table # from complaining if len(self._lastEntries) == 0: _tempEntries = [(0, 'Placeholder for table of contents', 0)] else: _tempEntries = self._lastEntries lastMargin = 0 tableData = [] tableStyle = [ ('VALIGN', (0, 0), (- 1, - 1), 'TOP'), ('LEFTPADDING', (0, 0), (- 1, - 1), 0), ('RIGHTPADDING', (0, 0), (- 1, - 1), 0), ('TOPPADDING', (0, 0), (- 1, - 1), 0), ('BOTTOMPADDING', (0, 0), (- 1, - 1), 0), ] for i, entry in enumerate(_tempEntries): level, text, pageNum = entry[:3] leftColStyle = self.levelStyles[level] if i: # Not for first element tableStyle.append(( 'TOPPADDING', (0, i), (- 1, i), max(lastMargin, leftColStyle.spaceBefore))) # print leftColStyle.leftIndent lastMargin = leftColStyle.spaceAfter #right col style is right aligned rightColStyle = ParagraphStyle(name='leftColLevel%d' % level, parent=leftColStyle, leftIndent=0, alignment=TA_RIGHT) leftPara = Paragraph(text, leftColStyle) rightPara = Paragraph(str(pageNum), rightColStyle) tableData.append([leftPara, rightPara]) self._table = Table( tableData, colWidths=widths, style=TableStyle(tableStyle)) self.width, self.height = self._table.wrapOn(self.canv, availWidth, availHeight) return self.width, self.height
[ "def", "wrap", "(", "self", ",", "availWidth", ",", "availHeight", ")", ":", "widths", "=", "(", "availWidth", "-", "self", ".", "rightColumnWidth", ",", "self", ".", "rightColumnWidth", ")", "# makes an internal table which does all the work.", "# we draw the LAST RUN's entries! If there are", "# none, we make some dummy data to keep the table", "# from complaining", "if", "len", "(", "self", ".", "_lastEntries", ")", "==", "0", ":", "_tempEntries", "=", "[", "(", "0", ",", "'Placeholder for table of contents'", ",", "0", ")", "]", "else", ":", "_tempEntries", "=", "self", ".", "_lastEntries", "lastMargin", "=", "0", "tableData", "=", "[", "]", "tableStyle", "=", "[", "(", "'VALIGN'", ",", "(", "0", ",", "0", ")", ",", "(", "-", "1", ",", "-", "1", ")", ",", "'TOP'", ")", ",", "(", "'LEFTPADDING'", ",", "(", "0", ",", "0", ")", ",", "(", "-", "1", ",", "-", "1", ")", ",", "0", ")", ",", "(", "'RIGHTPADDING'", ",", "(", "0", ",", "0", ")", ",", "(", "-", "1", ",", "-", "1", ")", ",", "0", ")", ",", "(", "'TOPPADDING'", ",", "(", "0", ",", "0", ")", ",", "(", "-", "1", ",", "-", "1", ")", ",", "0", ")", ",", "(", "'BOTTOMPADDING'", ",", "(", "0", ",", "0", ")", ",", "(", "-", "1", ",", "-", "1", ")", ",", "0", ")", ",", "]", "for", "i", ",", "entry", "in", "enumerate", "(", "_tempEntries", ")", ":", "level", ",", "text", ",", "pageNum", "=", "entry", "[", ":", "3", "]", "leftColStyle", "=", "self", ".", "levelStyles", "[", "level", "]", "if", "i", ":", "# Not for first element", "tableStyle", ".", "append", "(", "(", "'TOPPADDING'", ",", "(", "0", ",", "i", ")", ",", "(", "-", "1", ",", "i", ")", ",", "max", "(", "lastMargin", ",", "leftColStyle", ".", "spaceBefore", ")", ")", ")", "# print leftColStyle.leftIndent", "lastMargin", "=", "leftColStyle", ".", "spaceAfter", "#right col style is right aligned", "rightColStyle", "=", "ParagraphStyle", "(", "name", "=", "'leftColLevel%d'", "%", "level", ",", "parent", "=", "leftColStyle", ",", "leftIndent", "=", "0", ",", "alignment", "=", "TA_RIGHT", ")", "leftPara", "=", "Paragraph", "(", "text", ",", "leftColStyle", ")", "rightPara", "=", "Paragraph", "(", "str", "(", "pageNum", ")", ",", "rightColStyle", ")", "tableData", ".", "append", "(", "[", "leftPara", ",", "rightPara", "]", ")", "self", ".", "_table", "=", "Table", "(", "tableData", ",", "colWidths", "=", "widths", ",", "style", "=", "TableStyle", "(", "tableStyle", ")", ")", "self", ".", "width", ",", "self", ".", "height", "=", "self", ".", "_table", ".", "wrapOn", "(", "self", ".", "canv", ",", "availWidth", ",", "availHeight", ")", "return", "self", ".", "width", ",", "self", ".", "height" ]
All table properties should be known by now.
[ "All", "table", "properties", "should", "be", "known", "by", "now", "." ]
230357a392f48816532d3c2fa082a680b80ece48
https://github.com/xhtml2pdf/xhtml2pdf/blob/230357a392f48816532d3c2fa082a680b80ece48/xhtml2pdf/xhtml2pdf_reportlab.py#L788-L839
8,366
ianmiell/shutit
shutit_pexpect.py
ShutItPexpectSession._spawn_child
def _spawn_child(self, command, args=None, timeout=shutit_global.shutit_global_object.default_timeout, maxread=2000, searchwindowsize=None, env=None, ignore_sighup=False, echo=True, preexec_fn=None, encoding=None, codec_errors='strict', dimensions=None, delaybeforesend=shutit_global.shutit_global_object.delaybeforesend): """spawn a child, and manage the delaybefore send setting to 0 """ shutit = self.shutit args = args or [] pexpect_child = pexpect.spawn(command, args=args, timeout=timeout, maxread=maxread, searchwindowsize=searchwindowsize, env=env, ignore_sighup=ignore_sighup, echo=echo, preexec_fn=preexec_fn, encoding=encoding, codec_errors=codec_errors, dimensions=dimensions) # Set the winsize to the theoretical maximum to reduce risk of trouble from terminal line wraps. # Other things have been attempted, eg tput rmam/smam without success. pexpect_child.setwinsize(shutit_global.shutit_global_object.pexpect_window_size[0],shutit_global.shutit_global_object.pexpect_window_size[1]) pexpect_child.delaybeforesend=delaybeforesend shutit.log('sessions before: ' + str(shutit.shutit_pexpect_sessions), level=logging.DEBUG) shutit.shutit_pexpect_sessions.update({self.pexpect_session_id:self}) shutit.log('sessions after: ' + str(shutit.shutit_pexpect_sessions), level=logging.DEBUG) return pexpect_child
python
def _spawn_child(self, command, args=None, timeout=shutit_global.shutit_global_object.default_timeout, maxread=2000, searchwindowsize=None, env=None, ignore_sighup=False, echo=True, preexec_fn=None, encoding=None, codec_errors='strict', dimensions=None, delaybeforesend=shutit_global.shutit_global_object.delaybeforesend): """spawn a child, and manage the delaybefore send setting to 0 """ shutit = self.shutit args = args or [] pexpect_child = pexpect.spawn(command, args=args, timeout=timeout, maxread=maxread, searchwindowsize=searchwindowsize, env=env, ignore_sighup=ignore_sighup, echo=echo, preexec_fn=preexec_fn, encoding=encoding, codec_errors=codec_errors, dimensions=dimensions) # Set the winsize to the theoretical maximum to reduce risk of trouble from terminal line wraps. # Other things have been attempted, eg tput rmam/smam without success. pexpect_child.setwinsize(shutit_global.shutit_global_object.pexpect_window_size[0],shutit_global.shutit_global_object.pexpect_window_size[1]) pexpect_child.delaybeforesend=delaybeforesend shutit.log('sessions before: ' + str(shutit.shutit_pexpect_sessions), level=logging.DEBUG) shutit.shutit_pexpect_sessions.update({self.pexpect_session_id:self}) shutit.log('sessions after: ' + str(shutit.shutit_pexpect_sessions), level=logging.DEBUG) return pexpect_child
[ "def", "_spawn_child", "(", "self", ",", "command", ",", "args", "=", "None", ",", "timeout", "=", "shutit_global", ".", "shutit_global_object", ".", "default_timeout", ",", "maxread", "=", "2000", ",", "searchwindowsize", "=", "None", ",", "env", "=", "None", ",", "ignore_sighup", "=", "False", ",", "echo", "=", "True", ",", "preexec_fn", "=", "None", ",", "encoding", "=", "None", ",", "codec_errors", "=", "'strict'", ",", "dimensions", "=", "None", ",", "delaybeforesend", "=", "shutit_global", ".", "shutit_global_object", ".", "delaybeforesend", ")", ":", "shutit", "=", "self", ".", "shutit", "args", "=", "args", "or", "[", "]", "pexpect_child", "=", "pexpect", ".", "spawn", "(", "command", ",", "args", "=", "args", ",", "timeout", "=", "timeout", ",", "maxread", "=", "maxread", ",", "searchwindowsize", "=", "searchwindowsize", ",", "env", "=", "env", ",", "ignore_sighup", "=", "ignore_sighup", ",", "echo", "=", "echo", ",", "preexec_fn", "=", "preexec_fn", ",", "encoding", "=", "encoding", ",", "codec_errors", "=", "codec_errors", ",", "dimensions", "=", "dimensions", ")", "# Set the winsize to the theoretical maximum to reduce risk of trouble from terminal line wraps.", "# Other things have been attempted, eg tput rmam/smam without success.", "pexpect_child", ".", "setwinsize", "(", "shutit_global", ".", "shutit_global_object", ".", "pexpect_window_size", "[", "0", "]", ",", "shutit_global", ".", "shutit_global_object", ".", "pexpect_window_size", "[", "1", "]", ")", "pexpect_child", ".", "delaybeforesend", "=", "delaybeforesend", "shutit", ".", "log", "(", "'sessions before: '", "+", "str", "(", "shutit", ".", "shutit_pexpect_sessions", ")", ",", "level", "=", "logging", ".", "DEBUG", ")", "shutit", ".", "shutit_pexpect_sessions", ".", "update", "(", "{", "self", ".", "pexpect_session_id", ":", "self", "}", ")", "shutit", ".", "log", "(", "'sessions after: '", "+", "str", "(", "shutit", ".", "shutit_pexpect_sessions", ")", ",", "level", "=", "logging", ".", "DEBUG", ")", "return", "pexpect_child" ]
spawn a child, and manage the delaybefore send setting to 0
[ "spawn", "a", "child", "and", "manage", "the", "delaybefore", "send", "setting", "to", "0" ]
19cd64cdfb23515b106b40213dccff4101617076
https://github.com/ianmiell/shutit/blob/19cd64cdfb23515b106b40213dccff4101617076/shutit_pexpect.py#L149-L186
8,367
ianmiell/shutit
shutit_pexpect.py
ShutItPexpectSession.sendline
def sendline(self, sendspec): """Sends line, handling background and newline directives. True means: 'all handled here ok' False means: you'll need to 'expect' the right thing from here. """ assert not sendspec.started, shutit_util.print_debug() shutit = self.shutit shutit.log('Sending in pexpect session (' + str(id(self)) + '): ' + str(sendspec.send), level=logging.DEBUG) if sendspec.expect: shutit.log('Expecting: ' + str(sendspec.expect), level=logging.DEBUG) else: shutit.log('Not expecting anything', level=logging.DEBUG) try: # Check there are no background commands running that have block_other_commands set iff # this sendspec says if self._check_blocked(sendspec) and sendspec.ignore_background != True: shutit.log('sendline: blocked', level=logging.DEBUG) return False # If this is marked as in the background, create a background object and run in the background. if sendspec.run_in_background: shutit.log('sendline: run_in_background', level=logging.DEBUG) # If this is marked as in the background, create a background object and run in the background after newlines sorted. shutit_background_command_object = self.login_stack.get_current_login_item().append_background_send(sendspec) # Makes no sense to check exit for a background command. sendspec.check_exit = False if sendspec.nonewline != True: sendspec.send += '\n' # sendspec has newline added now, so no need to keep marker sendspec.nonewline = True if sendspec.run_in_background: shutit_background_command_object.run_background_command() return True #shutit.log('sendline: actually sending: ' + sendspec.send, level=logging.DEBUG) self.pexpect_child.send(sendspec.send) return False except OSError: self.shutit.fail('Caught failure to send, assuming user has exited from pause point.')
python
def sendline(self, sendspec): """Sends line, handling background and newline directives. True means: 'all handled here ok' False means: you'll need to 'expect' the right thing from here. """ assert not sendspec.started, shutit_util.print_debug() shutit = self.shutit shutit.log('Sending in pexpect session (' + str(id(self)) + '): ' + str(sendspec.send), level=logging.DEBUG) if sendspec.expect: shutit.log('Expecting: ' + str(sendspec.expect), level=logging.DEBUG) else: shutit.log('Not expecting anything', level=logging.DEBUG) try: # Check there are no background commands running that have block_other_commands set iff # this sendspec says if self._check_blocked(sendspec) and sendspec.ignore_background != True: shutit.log('sendline: blocked', level=logging.DEBUG) return False # If this is marked as in the background, create a background object and run in the background. if sendspec.run_in_background: shutit.log('sendline: run_in_background', level=logging.DEBUG) # If this is marked as in the background, create a background object and run in the background after newlines sorted. shutit_background_command_object = self.login_stack.get_current_login_item().append_background_send(sendspec) # Makes no sense to check exit for a background command. sendspec.check_exit = False if sendspec.nonewline != True: sendspec.send += '\n' # sendspec has newline added now, so no need to keep marker sendspec.nonewline = True if sendspec.run_in_background: shutit_background_command_object.run_background_command() return True #shutit.log('sendline: actually sending: ' + sendspec.send, level=logging.DEBUG) self.pexpect_child.send(sendspec.send) return False except OSError: self.shutit.fail('Caught failure to send, assuming user has exited from pause point.')
[ "def", "sendline", "(", "self", ",", "sendspec", ")", ":", "assert", "not", "sendspec", ".", "started", ",", "shutit_util", ".", "print_debug", "(", ")", "shutit", "=", "self", ".", "shutit", "shutit", ".", "log", "(", "'Sending in pexpect session ('", "+", "str", "(", "id", "(", "self", ")", ")", "+", "'): '", "+", "str", "(", "sendspec", ".", "send", ")", ",", "level", "=", "logging", ".", "DEBUG", ")", "if", "sendspec", ".", "expect", ":", "shutit", ".", "log", "(", "'Expecting: '", "+", "str", "(", "sendspec", ".", "expect", ")", ",", "level", "=", "logging", ".", "DEBUG", ")", "else", ":", "shutit", ".", "log", "(", "'Not expecting anything'", ",", "level", "=", "logging", ".", "DEBUG", ")", "try", ":", "# Check there are no background commands running that have block_other_commands set iff", "# this sendspec says", "if", "self", ".", "_check_blocked", "(", "sendspec", ")", "and", "sendspec", ".", "ignore_background", "!=", "True", ":", "shutit", ".", "log", "(", "'sendline: blocked'", ",", "level", "=", "logging", ".", "DEBUG", ")", "return", "False", "# If this is marked as in the background, create a background object and run in the background.", "if", "sendspec", ".", "run_in_background", ":", "shutit", ".", "log", "(", "'sendline: run_in_background'", ",", "level", "=", "logging", ".", "DEBUG", ")", "# If this is marked as in the background, create a background object and run in the background after newlines sorted.", "shutit_background_command_object", "=", "self", ".", "login_stack", ".", "get_current_login_item", "(", ")", ".", "append_background_send", "(", "sendspec", ")", "# Makes no sense to check exit for a background command.", "sendspec", ".", "check_exit", "=", "False", "if", "sendspec", ".", "nonewline", "!=", "True", ":", "sendspec", ".", "send", "+=", "'\\n'", "# sendspec has newline added now, so no need to keep marker", "sendspec", ".", "nonewline", "=", "True", "if", "sendspec", ".", "run_in_background", ":", "shutit_background_command_object", ".", "run_background_command", "(", ")", "return", "True", "#shutit.log('sendline: actually sending: ' + sendspec.send, level=logging.DEBUG)", "self", ".", "pexpect_child", ".", "send", "(", "sendspec", ".", "send", ")", "return", "False", "except", "OSError", ":", "self", ".", "shutit", ".", "fail", "(", "'Caught failure to send, assuming user has exited from pause point.'", ")" ]
Sends line, handling background and newline directives. True means: 'all handled here ok' False means: you'll need to 'expect' the right thing from here.
[ "Sends", "line", "handling", "background", "and", "newline", "directives", "." ]
19cd64cdfb23515b106b40213dccff4101617076
https://github.com/ianmiell/shutit/blob/19cd64cdfb23515b106b40213dccff4101617076/shutit_pexpect.py#L189-L226
8,368
ianmiell/shutit
shutit_pexpect.py
ShutItPexpectSession.wait
def wait(self, cadence=2, sendspec=None): """Does not return until all background commands are completed. """ shutit = self.shutit shutit.log('In wait.', level=logging.DEBUG) if sendspec: cadence = sendspec.wait_cadence shutit.log('Login stack is:\n' + str(self.login_stack), level=logging.DEBUG) while True: # go through each background child checking whether they've finished res, res_str, background_object = self.login_stack.get_current_login_item().check_background_commands_complete() shutit.log('Checking: ' + str(background_object) + '\nres: ' + str(res) + '\nres_str' + str(res_str), level=logging.DEBUG) if res: # When all have completed, break return the background command objects. break elif res_str in ('S','N'): # Do nothing, this is an started or not-running task. pass elif res_str == 'F': assert background_object is not None, shutit_util.print_debug() assert isinstance(background_object, ShutItBackgroundCommand), shutit_util.print_debug() shutit.log('Failure in: ' + str(self.login_stack), level=logging.DEBUG) self.pause_point('Background task: ' + background_object.sendspec.original_send + ' :failed.') return False else: self.shutit.fail('Un-handled exit code: ' + res_str) # pragma: no cover time.sleep(cadence) shutit.log('Wait complete.', level=logging.DEBUG) return True
python
def wait(self, cadence=2, sendspec=None): """Does not return until all background commands are completed. """ shutit = self.shutit shutit.log('In wait.', level=logging.DEBUG) if sendspec: cadence = sendspec.wait_cadence shutit.log('Login stack is:\n' + str(self.login_stack), level=logging.DEBUG) while True: # go through each background child checking whether they've finished res, res_str, background_object = self.login_stack.get_current_login_item().check_background_commands_complete() shutit.log('Checking: ' + str(background_object) + '\nres: ' + str(res) + '\nres_str' + str(res_str), level=logging.DEBUG) if res: # When all have completed, break return the background command objects. break elif res_str in ('S','N'): # Do nothing, this is an started or not-running task. pass elif res_str == 'F': assert background_object is not None, shutit_util.print_debug() assert isinstance(background_object, ShutItBackgroundCommand), shutit_util.print_debug() shutit.log('Failure in: ' + str(self.login_stack), level=logging.DEBUG) self.pause_point('Background task: ' + background_object.sendspec.original_send + ' :failed.') return False else: self.shutit.fail('Un-handled exit code: ' + res_str) # pragma: no cover time.sleep(cadence) shutit.log('Wait complete.', level=logging.DEBUG) return True
[ "def", "wait", "(", "self", ",", "cadence", "=", "2", ",", "sendspec", "=", "None", ")", ":", "shutit", "=", "self", ".", "shutit", "shutit", ".", "log", "(", "'In wait.'", ",", "level", "=", "logging", ".", "DEBUG", ")", "if", "sendspec", ":", "cadence", "=", "sendspec", ".", "wait_cadence", "shutit", ".", "log", "(", "'Login stack is:\\n'", "+", "str", "(", "self", ".", "login_stack", ")", ",", "level", "=", "logging", ".", "DEBUG", ")", "while", "True", ":", "# go through each background child checking whether they've finished", "res", ",", "res_str", ",", "background_object", "=", "self", ".", "login_stack", ".", "get_current_login_item", "(", ")", ".", "check_background_commands_complete", "(", ")", "shutit", ".", "log", "(", "'Checking: '", "+", "str", "(", "background_object", ")", "+", "'\\nres: '", "+", "str", "(", "res", ")", "+", "'\\nres_str'", "+", "str", "(", "res_str", ")", ",", "level", "=", "logging", ".", "DEBUG", ")", "if", "res", ":", "# When all have completed, break return the background command objects.", "break", "elif", "res_str", "in", "(", "'S'", ",", "'N'", ")", ":", "# Do nothing, this is an started or not-running task.", "pass", "elif", "res_str", "==", "'F'", ":", "assert", "background_object", "is", "not", "None", ",", "shutit_util", ".", "print_debug", "(", ")", "assert", "isinstance", "(", "background_object", ",", "ShutItBackgroundCommand", ")", ",", "shutit_util", ".", "print_debug", "(", ")", "shutit", ".", "log", "(", "'Failure in: '", "+", "str", "(", "self", ".", "login_stack", ")", ",", "level", "=", "logging", ".", "DEBUG", ")", "self", ".", "pause_point", "(", "'Background task: '", "+", "background_object", ".", "sendspec", ".", "original_send", "+", "' :failed.'", ")", "return", "False", "else", ":", "self", ".", "shutit", ".", "fail", "(", "'Un-handled exit code: '", "+", "res_str", ")", "# pragma: no cover", "time", ".", "sleep", "(", "cadence", ")", "shutit", ".", "log", "(", "'Wait complete.'", ",", "level", "=", "logging", ".", "DEBUG", ")", "return", "True" ]
Does not return until all background commands are completed.
[ "Does", "not", "return", "until", "all", "background", "commands", "are", "completed", "." ]
19cd64cdfb23515b106b40213dccff4101617076
https://github.com/ianmiell/shutit/blob/19cd64cdfb23515b106b40213dccff4101617076/shutit_pexpect.py#L271-L299
8,369
ianmiell/shutit
shutit_pexpect.py
ShutItPexpectSession.expect
def expect(self, expect, searchwindowsize=None, maxread=None, timeout=None, iteration_n=1): """Handle child expects, with EOF and TIMEOUT handled iteration_n - Number of times this expect has been called for the send. If 1, (the default) then it gets added to the pane of output (if applicable to this run) """ if isinstance(expect, str): expect = [expect] if searchwindowsize != None: old_searchwindowsize = self.pexpect_child.searchwindowsize self.pexpect_child.searchwindowsize = searchwindowsize if maxread != None: old_maxread = self.pexpect_child.maxread self.pexpect_child.maxread = maxread res = self.pexpect_child.expect(expect + [pexpect.TIMEOUT] + [pexpect.EOF], timeout=timeout) if searchwindowsize != None: self.pexpect_child.searchwindowsize = old_searchwindowsize if maxread != None: self.pexpect_child.maxread = old_maxread # Add to session lines only if pane manager exists. if shutit_global.shutit_global_object.pane_manager and iteration_n == 1: time_seen = time.time() lines_to_add = [] if isinstance(self.pexpect_child.before, (str,unicode)): for line_str in self.pexpect_child.before.split('\n'): lines_to_add.append(line_str) if isinstance(self.pexpect_child.after, (str,unicode)): for line_str in self.pexpect_child.after.split('\n'): lines_to_add.append(line_str) # If first or last line is empty, remove it. #if len(lines_to_add) > 0 and lines_to_add[1] == '': # lines_to_add = lines_to_add[1:] #if len(lines_to_add) > 0 and lines_to_add[-1] == '': # lines_to_add = lines_to_add[:-1] for line in lines_to_add: self.session_output_lines.append(SessionPaneLine(line_str=line, time_seen=time_seen, line_type='output')) return res
python
def expect(self, expect, searchwindowsize=None, maxread=None, timeout=None, iteration_n=1): """Handle child expects, with EOF and TIMEOUT handled iteration_n - Number of times this expect has been called for the send. If 1, (the default) then it gets added to the pane of output (if applicable to this run) """ if isinstance(expect, str): expect = [expect] if searchwindowsize != None: old_searchwindowsize = self.pexpect_child.searchwindowsize self.pexpect_child.searchwindowsize = searchwindowsize if maxread != None: old_maxread = self.pexpect_child.maxread self.pexpect_child.maxread = maxread res = self.pexpect_child.expect(expect + [pexpect.TIMEOUT] + [pexpect.EOF], timeout=timeout) if searchwindowsize != None: self.pexpect_child.searchwindowsize = old_searchwindowsize if maxread != None: self.pexpect_child.maxread = old_maxread # Add to session lines only if pane manager exists. if shutit_global.shutit_global_object.pane_manager and iteration_n == 1: time_seen = time.time() lines_to_add = [] if isinstance(self.pexpect_child.before, (str,unicode)): for line_str in self.pexpect_child.before.split('\n'): lines_to_add.append(line_str) if isinstance(self.pexpect_child.after, (str,unicode)): for line_str in self.pexpect_child.after.split('\n'): lines_to_add.append(line_str) # If first or last line is empty, remove it. #if len(lines_to_add) > 0 and lines_to_add[1] == '': # lines_to_add = lines_to_add[1:] #if len(lines_to_add) > 0 and lines_to_add[-1] == '': # lines_to_add = lines_to_add[:-1] for line in lines_to_add: self.session_output_lines.append(SessionPaneLine(line_str=line, time_seen=time_seen, line_type='output')) return res
[ "def", "expect", "(", "self", ",", "expect", ",", "searchwindowsize", "=", "None", ",", "maxread", "=", "None", ",", "timeout", "=", "None", ",", "iteration_n", "=", "1", ")", ":", "if", "isinstance", "(", "expect", ",", "str", ")", ":", "expect", "=", "[", "expect", "]", "if", "searchwindowsize", "!=", "None", ":", "old_searchwindowsize", "=", "self", ".", "pexpect_child", ".", "searchwindowsize", "self", ".", "pexpect_child", ".", "searchwindowsize", "=", "searchwindowsize", "if", "maxread", "!=", "None", ":", "old_maxread", "=", "self", ".", "pexpect_child", ".", "maxread", "self", ".", "pexpect_child", ".", "maxread", "=", "maxread", "res", "=", "self", ".", "pexpect_child", ".", "expect", "(", "expect", "+", "[", "pexpect", ".", "TIMEOUT", "]", "+", "[", "pexpect", ".", "EOF", "]", ",", "timeout", "=", "timeout", ")", "if", "searchwindowsize", "!=", "None", ":", "self", ".", "pexpect_child", ".", "searchwindowsize", "=", "old_searchwindowsize", "if", "maxread", "!=", "None", ":", "self", ".", "pexpect_child", ".", "maxread", "=", "old_maxread", "# Add to session lines only if pane manager exists.", "if", "shutit_global", ".", "shutit_global_object", ".", "pane_manager", "and", "iteration_n", "==", "1", ":", "time_seen", "=", "time", ".", "time", "(", ")", "lines_to_add", "=", "[", "]", "if", "isinstance", "(", "self", ".", "pexpect_child", ".", "before", ",", "(", "str", ",", "unicode", ")", ")", ":", "for", "line_str", "in", "self", ".", "pexpect_child", ".", "before", ".", "split", "(", "'\\n'", ")", ":", "lines_to_add", ".", "append", "(", "line_str", ")", "if", "isinstance", "(", "self", ".", "pexpect_child", ".", "after", ",", "(", "str", ",", "unicode", ")", ")", ":", "for", "line_str", "in", "self", ".", "pexpect_child", ".", "after", ".", "split", "(", "'\\n'", ")", ":", "lines_to_add", ".", "append", "(", "line_str", ")", "# If first or last line is empty, remove it.", "#if len(lines_to_add) > 0 and lines_to_add[1] == '':", "#\tlines_to_add = lines_to_add[1:]", "#if len(lines_to_add) > 0 and lines_to_add[-1] == '':", "#\tlines_to_add = lines_to_add[:-1]", "for", "line", "in", "lines_to_add", ":", "self", ".", "session_output_lines", ".", "append", "(", "SessionPaneLine", "(", "line_str", "=", "line", ",", "time_seen", "=", "time_seen", ",", "line_type", "=", "'output'", ")", ")", "return", "res" ]
Handle child expects, with EOF and TIMEOUT handled iteration_n - Number of times this expect has been called for the send. If 1, (the default) then it gets added to the pane of output (if applicable to this run)
[ "Handle", "child", "expects", "with", "EOF", "and", "TIMEOUT", "handled" ]
19cd64cdfb23515b106b40213dccff4101617076
https://github.com/ianmiell/shutit/blob/19cd64cdfb23515b106b40213dccff4101617076/shutit_pexpect.py#L585-L627
8,370
ianmiell/shutit
shutit_pexpect.py
ShutItPexpectSession.replace_container
def replace_container(self, new_target_image_name, go_home=None): """Replaces a container. Assumes we are in Docker context. """ shutit = self.shutit shutit.log('Replacing container with ' + new_target_image_name + ', please wait...', level=logging.DEBUG) shutit.log(shutit.print_session_state(), level=logging.DEBUG) # Destroy existing container. conn_module = None for mod in shutit.conn_modules: if mod.module_id == shutit.build['conn_module']: conn_module = mod break if conn_module is None: shutit.fail('''Couldn't find conn_module ''' + shutit.build['conn_module']) # pragma: no cover container_id = shutit.target['container_id'] conn_module.destroy_container(shutit, 'host_child', 'target_child', container_id) # Start up a new container. shutit.target['docker_image'] = new_target_image_name target_child = conn_module.start_container(shutit, self.pexpect_session_id) conn_module.setup_target_child(shutit, target_child) shutit.log('Container replaced', level=logging.DEBUG) shutit.log(shutit.print_session_state(), level=logging.DEBUG) # New session - log in. This makes the assumption that we are nested # the same level in in terms of shells (root shell + 1 new login shell). target_child = shutit.get_shutit_pexpect_session_from_id('target_child') if go_home != None: target_child.login(ShutItSendSpec(self, send=shutit_global.shutit_global_object.bash_startup_command, check_exit=False, echo=False, go_home=go_home)) else: target_child.login(ShutItSendSpec(self, send=shutit_global.shutit_global_object.bash_startup_command, check_exit=False, echo=False)) return True
python
def replace_container(self, new_target_image_name, go_home=None): """Replaces a container. Assumes we are in Docker context. """ shutit = self.shutit shutit.log('Replacing container with ' + new_target_image_name + ', please wait...', level=logging.DEBUG) shutit.log(shutit.print_session_state(), level=logging.DEBUG) # Destroy existing container. conn_module = None for mod in shutit.conn_modules: if mod.module_id == shutit.build['conn_module']: conn_module = mod break if conn_module is None: shutit.fail('''Couldn't find conn_module ''' + shutit.build['conn_module']) # pragma: no cover container_id = shutit.target['container_id'] conn_module.destroy_container(shutit, 'host_child', 'target_child', container_id) # Start up a new container. shutit.target['docker_image'] = new_target_image_name target_child = conn_module.start_container(shutit, self.pexpect_session_id) conn_module.setup_target_child(shutit, target_child) shutit.log('Container replaced', level=logging.DEBUG) shutit.log(shutit.print_session_state(), level=logging.DEBUG) # New session - log in. This makes the assumption that we are nested # the same level in in terms of shells (root shell + 1 new login shell). target_child = shutit.get_shutit_pexpect_session_from_id('target_child') if go_home != None: target_child.login(ShutItSendSpec(self, send=shutit_global.shutit_global_object.bash_startup_command, check_exit=False, echo=False, go_home=go_home)) else: target_child.login(ShutItSendSpec(self, send=shutit_global.shutit_global_object.bash_startup_command, check_exit=False, echo=False)) return True
[ "def", "replace_container", "(", "self", ",", "new_target_image_name", ",", "go_home", "=", "None", ")", ":", "shutit", "=", "self", ".", "shutit", "shutit", ".", "log", "(", "'Replacing container with '", "+", "new_target_image_name", "+", "', please wait...'", ",", "level", "=", "logging", ".", "DEBUG", ")", "shutit", ".", "log", "(", "shutit", ".", "print_session_state", "(", ")", ",", "level", "=", "logging", ".", "DEBUG", ")", "# Destroy existing container.", "conn_module", "=", "None", "for", "mod", "in", "shutit", ".", "conn_modules", ":", "if", "mod", ".", "module_id", "==", "shutit", ".", "build", "[", "'conn_module'", "]", ":", "conn_module", "=", "mod", "break", "if", "conn_module", "is", "None", ":", "shutit", ".", "fail", "(", "'''Couldn't find conn_module '''", "+", "shutit", ".", "build", "[", "'conn_module'", "]", ")", "# pragma: no cover", "container_id", "=", "shutit", ".", "target", "[", "'container_id'", "]", "conn_module", ".", "destroy_container", "(", "shutit", ",", "'host_child'", ",", "'target_child'", ",", "container_id", ")", "# Start up a new container.", "shutit", ".", "target", "[", "'docker_image'", "]", "=", "new_target_image_name", "target_child", "=", "conn_module", ".", "start_container", "(", "shutit", ",", "self", ".", "pexpect_session_id", ")", "conn_module", ".", "setup_target_child", "(", "shutit", ",", "target_child", ")", "shutit", ".", "log", "(", "'Container replaced'", ",", "level", "=", "logging", ".", "DEBUG", ")", "shutit", ".", "log", "(", "shutit", ".", "print_session_state", "(", ")", ",", "level", "=", "logging", ".", "DEBUG", ")", "# New session - log in. This makes the assumption that we are nested", "# the same level in in terms of shells (root shell + 1 new login shell).", "target_child", "=", "shutit", ".", "get_shutit_pexpect_session_from_id", "(", "'target_child'", ")", "if", "go_home", "!=", "None", ":", "target_child", ".", "login", "(", "ShutItSendSpec", "(", "self", ",", "send", "=", "shutit_global", ".", "shutit_global_object", ".", "bash_startup_command", ",", "check_exit", "=", "False", ",", "echo", "=", "False", ",", "go_home", "=", "go_home", ")", ")", "else", ":", "target_child", ".", "login", "(", "ShutItSendSpec", "(", "self", ",", "send", "=", "shutit_global", ".", "shutit_global_object", ".", "bash_startup_command", ",", "check_exit", "=", "False", ",", "echo", "=", "False", ")", ")", "return", "True" ]
Replaces a container. Assumes we are in Docker context.
[ "Replaces", "a", "container", ".", "Assumes", "we", "are", "in", "Docker", "context", "." ]
19cd64cdfb23515b106b40213dccff4101617076
https://github.com/ianmiell/shutit/blob/19cd64cdfb23515b106b40213dccff4101617076/shutit_pexpect.py#L630-L668
8,371
ianmiell/shutit
shutit_pexpect.py
ShutItPexpectSession.whoami
def whoami(self, note=None, loglevel=logging.DEBUG): """Returns the current user by executing "whoami". @param note: See send() @return: the output of "whoami" @rtype: string """ shutit = self.shutit shutit.handle_note(note) res = self.send_and_get_output(' command whoami', echo=False, loglevel=loglevel).strip() if res == '': res = self.send_and_get_output(' command id -u -n', echo=False, loglevel=loglevel).strip() shutit.handle_note_after(note=note) return res
python
def whoami(self, note=None, loglevel=logging.DEBUG): """Returns the current user by executing "whoami". @param note: See send() @return: the output of "whoami" @rtype: string """ shutit = self.shutit shutit.handle_note(note) res = self.send_and_get_output(' command whoami', echo=False, loglevel=loglevel).strip() if res == '': res = self.send_and_get_output(' command id -u -n', echo=False, loglevel=loglevel).strip() shutit.handle_note_after(note=note) return res
[ "def", "whoami", "(", "self", ",", "note", "=", "None", ",", "loglevel", "=", "logging", ".", "DEBUG", ")", ":", "shutit", "=", "self", ".", "shutit", "shutit", ".", "handle_note", "(", "note", ")", "res", "=", "self", ".", "send_and_get_output", "(", "' command whoami'", ",", "echo", "=", "False", ",", "loglevel", "=", "loglevel", ")", ".", "strip", "(", ")", "if", "res", "==", "''", ":", "res", "=", "self", ".", "send_and_get_output", "(", "' command id -u -n'", ",", "echo", "=", "False", ",", "loglevel", "=", "loglevel", ")", ".", "strip", "(", ")", "shutit", ".", "handle_note_after", "(", "note", "=", "note", ")", "return", "res" ]
Returns the current user by executing "whoami". @param note: See send() @return: the output of "whoami" @rtype: string
[ "Returns", "the", "current", "user", "by", "executing", "whoami", "." ]
19cd64cdfb23515b106b40213dccff4101617076
https://github.com/ianmiell/shutit/blob/19cd64cdfb23515b106b40213dccff4101617076/shutit_pexpect.py#L671-L691
8,372
ianmiell/shutit
shutit_pexpect.py
ShutItPexpectSession.check_last_exit_values
def check_last_exit_values(self, send, check_exit=True, expect=None, exit_values=None, retry=0, retbool=False): """Internal function to check the exit value of the shell. Do not use. """ shutit = self.shutit expect = expect or self.default_expect if not self.check_exit or not check_exit: shutit.log('check_exit configured off, returning', level=logging.DEBUG) return True if exit_values is None: exit_values = ['0'] if isinstance(exit_values, int): exit_values = [str(exit_values)] # Don't use send here (will mess up last_output)! # Space before "echo" here is sic - we don't need this to show up in bash history send_exit_code = ' echo EXIT_CODE:$?' shutit.log('Sending with sendline: ' + str(send_exit_code), level=logging.DEBUG) assert not self.sendline(ShutItSendSpec(self, send=send_exit_code, ignore_background=True)), shutit_util.print_debug() shutit.log('Expecting: ' + str(expect), level=logging.DEBUG) self.expect(expect,timeout=10) shutit.log('before: ' + str(self.pexpect_child.before), level=logging.DEBUG) res = shutit.match_string(str(self.pexpect_child.before), '^EXIT_CODE:([0-9][0-9]?[0-9]?)$') if res not in exit_values or res is None: # pragma: no cover res_str = res or str(res) shutit.log('shutit_pexpect_child.after: ' + str(self.pexpect_child.after), level=logging.DEBUG) shutit.log('Exit value from command: ' + str(send) + ' was:' + res_str, level=logging.DEBUG) msg = ('\nWARNING: command:\n' + send + '\nreturned unaccepted exit code: ' + res_str + '\nIf this is expected, pass in check_exit=False or an exit_values array into the send function call.') shutit.build['report'] += msg if retbool: return False elif retry == 1 and shutit_global.shutit_global_object.interactive >= 1: # This is a failure, so we pass in level=0 shutit.pause_point(msg + '\n\nInteractive, so not retrying.\nPause point on exit_code != 0 (' + res_str + '). CTRL-C to quit', shutit_pexpect_child=self.pexpect_child, level=0) elif retry == 1: shutit.fail('Exit value from command\n' + send + '\nwas:\n' + res_str, throw_exception=False) # pragma: no cover else: return False return True
python
def check_last_exit_values(self, send, check_exit=True, expect=None, exit_values=None, retry=0, retbool=False): """Internal function to check the exit value of the shell. Do not use. """ shutit = self.shutit expect = expect or self.default_expect if not self.check_exit or not check_exit: shutit.log('check_exit configured off, returning', level=logging.DEBUG) return True if exit_values is None: exit_values = ['0'] if isinstance(exit_values, int): exit_values = [str(exit_values)] # Don't use send here (will mess up last_output)! # Space before "echo" here is sic - we don't need this to show up in bash history send_exit_code = ' echo EXIT_CODE:$?' shutit.log('Sending with sendline: ' + str(send_exit_code), level=logging.DEBUG) assert not self.sendline(ShutItSendSpec(self, send=send_exit_code, ignore_background=True)), shutit_util.print_debug() shutit.log('Expecting: ' + str(expect), level=logging.DEBUG) self.expect(expect,timeout=10) shutit.log('before: ' + str(self.pexpect_child.before), level=logging.DEBUG) res = shutit.match_string(str(self.pexpect_child.before), '^EXIT_CODE:([0-9][0-9]?[0-9]?)$') if res not in exit_values or res is None: # pragma: no cover res_str = res or str(res) shutit.log('shutit_pexpect_child.after: ' + str(self.pexpect_child.after), level=logging.DEBUG) shutit.log('Exit value from command: ' + str(send) + ' was:' + res_str, level=logging.DEBUG) msg = ('\nWARNING: command:\n' + send + '\nreturned unaccepted exit code: ' + res_str + '\nIf this is expected, pass in check_exit=False or an exit_values array into the send function call.') shutit.build['report'] += msg if retbool: return False elif retry == 1 and shutit_global.shutit_global_object.interactive >= 1: # This is a failure, so we pass in level=0 shutit.pause_point(msg + '\n\nInteractive, so not retrying.\nPause point on exit_code != 0 (' + res_str + '). CTRL-C to quit', shutit_pexpect_child=self.pexpect_child, level=0) elif retry == 1: shutit.fail('Exit value from command\n' + send + '\nwas:\n' + res_str, throw_exception=False) # pragma: no cover else: return False return True
[ "def", "check_last_exit_values", "(", "self", ",", "send", ",", "check_exit", "=", "True", ",", "expect", "=", "None", ",", "exit_values", "=", "None", ",", "retry", "=", "0", ",", "retbool", "=", "False", ")", ":", "shutit", "=", "self", ".", "shutit", "expect", "=", "expect", "or", "self", ".", "default_expect", "if", "not", "self", ".", "check_exit", "or", "not", "check_exit", ":", "shutit", ".", "log", "(", "'check_exit configured off, returning'", ",", "level", "=", "logging", ".", "DEBUG", ")", "return", "True", "if", "exit_values", "is", "None", ":", "exit_values", "=", "[", "'0'", "]", "if", "isinstance", "(", "exit_values", ",", "int", ")", ":", "exit_values", "=", "[", "str", "(", "exit_values", ")", "]", "# Don't use send here (will mess up last_output)!", "# Space before \"echo\" here is sic - we don't need this to show up in bash history", "send_exit_code", "=", "' echo EXIT_CODE:$?'", "shutit", ".", "log", "(", "'Sending with sendline: '", "+", "str", "(", "send_exit_code", ")", ",", "level", "=", "logging", ".", "DEBUG", ")", "assert", "not", "self", ".", "sendline", "(", "ShutItSendSpec", "(", "self", ",", "send", "=", "send_exit_code", ",", "ignore_background", "=", "True", ")", ")", ",", "shutit_util", ".", "print_debug", "(", ")", "shutit", ".", "log", "(", "'Expecting: '", "+", "str", "(", "expect", ")", ",", "level", "=", "logging", ".", "DEBUG", ")", "self", ".", "expect", "(", "expect", ",", "timeout", "=", "10", ")", "shutit", ".", "log", "(", "'before: '", "+", "str", "(", "self", ".", "pexpect_child", ".", "before", ")", ",", "level", "=", "logging", ".", "DEBUG", ")", "res", "=", "shutit", ".", "match_string", "(", "str", "(", "self", ".", "pexpect_child", ".", "before", ")", ",", "'^EXIT_CODE:([0-9][0-9]?[0-9]?)$'", ")", "if", "res", "not", "in", "exit_values", "or", "res", "is", "None", ":", "# pragma: no cover", "res_str", "=", "res", "or", "str", "(", "res", ")", "shutit", ".", "log", "(", "'shutit_pexpect_child.after: '", "+", "str", "(", "self", ".", "pexpect_child", ".", "after", ")", ",", "level", "=", "logging", ".", "DEBUG", ")", "shutit", ".", "log", "(", "'Exit value from command: '", "+", "str", "(", "send", ")", "+", "' was:'", "+", "res_str", ",", "level", "=", "logging", ".", "DEBUG", ")", "msg", "=", "(", "'\\nWARNING: command:\\n'", "+", "send", "+", "'\\nreturned unaccepted exit code: '", "+", "res_str", "+", "'\\nIf this is expected, pass in check_exit=False or an exit_values array into the send function call.'", ")", "shutit", ".", "build", "[", "'report'", "]", "+=", "msg", "if", "retbool", ":", "return", "False", "elif", "retry", "==", "1", "and", "shutit_global", ".", "shutit_global_object", ".", "interactive", ">=", "1", ":", "# This is a failure, so we pass in level=0", "shutit", ".", "pause_point", "(", "msg", "+", "'\\n\\nInteractive, so not retrying.\\nPause point on exit_code != 0 ('", "+", "res_str", "+", "'). CTRL-C to quit'", ",", "shutit_pexpect_child", "=", "self", ".", "pexpect_child", ",", "level", "=", "0", ")", "elif", "retry", "==", "1", ":", "shutit", ".", "fail", "(", "'Exit value from command\\n'", "+", "send", "+", "'\\nwas:\\n'", "+", "res_str", ",", "throw_exception", "=", "False", ")", "# pragma: no cover", "else", ":", "return", "False", "return", "True" ]
Internal function to check the exit value of the shell. Do not use.
[ "Internal", "function", "to", "check", "the", "exit", "value", "of", "the", "shell", ".", "Do", "not", "use", "." ]
19cd64cdfb23515b106b40213dccff4101617076
https://github.com/ianmiell/shutit/blob/19cd64cdfb23515b106b40213dccff4101617076/shutit_pexpect.py#L695-L739
8,373
ianmiell/shutit
shutit_pexpect.py
ShutItPexpectSession.get_file_perms
def get_file_perms(self, filename, note=None, loglevel=logging.DEBUG): """Returns the permissions of the file on the target as an octal string triplet. @param filename: Filename to get permissions of. @param note: See send() @type filename: string @rtype: string """ shutit = self.shutit shutit.handle_note(note) cmd = ' command stat -c %a ' + filename self.send(ShutItSendSpec(self, send=' ' + cmd, check_exit=False, echo=False, loglevel=loglevel, ignore_background=True)) res = shutit.match_string(self.pexpect_child.before, '([0-9][0-9][0-9])') shutit.handle_note_after(note=note) return res
python
def get_file_perms(self, filename, note=None, loglevel=logging.DEBUG): """Returns the permissions of the file on the target as an octal string triplet. @param filename: Filename to get permissions of. @param note: See send() @type filename: string @rtype: string """ shutit = self.shutit shutit.handle_note(note) cmd = ' command stat -c %a ' + filename self.send(ShutItSendSpec(self, send=' ' + cmd, check_exit=False, echo=False, loglevel=loglevel, ignore_background=True)) res = shutit.match_string(self.pexpect_child.before, '([0-9][0-9][0-9])') shutit.handle_note_after(note=note) return res
[ "def", "get_file_perms", "(", "self", ",", "filename", ",", "note", "=", "None", ",", "loglevel", "=", "logging", ".", "DEBUG", ")", ":", "shutit", "=", "self", ".", "shutit", "shutit", ".", "handle_note", "(", "note", ")", "cmd", "=", "' command stat -c %a '", "+", "filename", "self", ".", "send", "(", "ShutItSendSpec", "(", "self", ",", "send", "=", "' '", "+", "cmd", ",", "check_exit", "=", "False", ",", "echo", "=", "False", ",", "loglevel", "=", "loglevel", ",", "ignore_background", "=", "True", ")", ")", "res", "=", "shutit", ".", "match_string", "(", "self", ".", "pexpect_child", ".", "before", ",", "'([0-9][0-9][0-9])'", ")", "shutit", ".", "handle_note_after", "(", "note", "=", "note", ")", "return", "res" ]
Returns the permissions of the file on the target as an octal string triplet. @param filename: Filename to get permissions of. @param note: See send() @type filename: string @rtype: string
[ "Returns", "the", "permissions", "of", "the", "file", "on", "the", "target", "as", "an", "octal", "string", "triplet", "." ]
19cd64cdfb23515b106b40213dccff4101617076
https://github.com/ianmiell/shutit/blob/19cd64cdfb23515b106b40213dccff4101617076/shutit_pexpect.py#L956-L981
8,374
ianmiell/shutit
shutit_pexpect.py
ShutItPexpectSession.is_user_id_available
def is_user_id_available(self, user_id, note=None, loglevel=logging.DEBUG): """Determine whether the specified user_id available. @param user_id: User id to be checked. @param note: See send() @type user_id: integer @rtype: boolean @return: True is the specified user id is not used yet, False if it's already been assigned to a user. """ shutit = self.shutit shutit.handle_note(note) # v the space is intentional, to avoid polluting bash history. self.send(ShutItSendSpec(self, send=' command cut -d: -f3 /etc/paswd | grep -w ^' + user_id + '$ | wc -l', expect=self.default_expect, echo=False, loglevel=loglevel, ignore_background=True)) shutit.handle_note_after(note=note) if shutit.match_string(self.pexpect_child.before, '^([0-9]+)$') == '1': return False return True
python
def is_user_id_available(self, user_id, note=None, loglevel=logging.DEBUG): """Determine whether the specified user_id available. @param user_id: User id to be checked. @param note: See send() @type user_id: integer @rtype: boolean @return: True is the specified user id is not used yet, False if it's already been assigned to a user. """ shutit = self.shutit shutit.handle_note(note) # v the space is intentional, to avoid polluting bash history. self.send(ShutItSendSpec(self, send=' command cut -d: -f3 /etc/paswd | grep -w ^' + user_id + '$ | wc -l', expect=self.default_expect, echo=False, loglevel=loglevel, ignore_background=True)) shutit.handle_note_after(note=note) if shutit.match_string(self.pexpect_child.before, '^([0-9]+)$') == '1': return False return True
[ "def", "is_user_id_available", "(", "self", ",", "user_id", ",", "note", "=", "None", ",", "loglevel", "=", "logging", ".", "DEBUG", ")", ":", "shutit", "=", "self", ".", "shutit", "shutit", ".", "handle_note", "(", "note", ")", "# v the space is intentional, to avoid polluting bash history.", "self", ".", "send", "(", "ShutItSendSpec", "(", "self", ",", "send", "=", "' command cut -d: -f3 /etc/paswd | grep -w ^'", "+", "user_id", "+", "'$ | wc -l'", ",", "expect", "=", "self", ".", "default_expect", ",", "echo", "=", "False", ",", "loglevel", "=", "loglevel", ",", "ignore_background", "=", "True", ")", ")", "shutit", ".", "handle_note_after", "(", "note", "=", "note", ")", "if", "shutit", ".", "match_string", "(", "self", ".", "pexpect_child", ".", "before", ",", "'^([0-9]+)$'", ")", "==", "'1'", ":", "return", "False", "return", "True" ]
Determine whether the specified user_id available. @param user_id: User id to be checked. @param note: See send() @type user_id: integer @rtype: boolean @return: True is the specified user id is not used yet, False if it's already been assigned to a user.
[ "Determine", "whether", "the", "specified", "user_id", "available", "." ]
19cd64cdfb23515b106b40213dccff4101617076
https://github.com/ianmiell/shutit/blob/19cd64cdfb23515b106b40213dccff4101617076/shutit_pexpect.py#L1011-L1037
8,375
ianmiell/shutit
shutit_pexpect.py
ShutItPexpectSession.lsb_release
def lsb_release(self, loglevel=logging.DEBUG): """Get distro information from lsb_release. """ # v the space is intentional, to avoid polluting bash history. shutit = self.shutit d = {} self.send(ShutItSendSpec(self, send=' command lsb_release -a', check_exit=False, echo=False, loglevel=loglevel, ignore_background=True)) res = shutit.match_string(self.pexpect_child.before, r'^Distributor[\s]*ID:[\s]*(.*)$') if isinstance(res, str): dist_string = res d['distro'] = dist_string.lower().strip() try: d['install_type'] = (package_map.INSTALL_TYPE_MAP[dist_string.lower()]) except KeyError: raise Exception("Distribution '%s' is not supported." % dist_string) else: return d res = shutit.match_string(self.pexpect_child.before, r'^Release:[\s*](.*)$') if isinstance(res, str): version_string = res d['distro_version'] = version_string return d
python
def lsb_release(self, loglevel=logging.DEBUG): """Get distro information from lsb_release. """ # v the space is intentional, to avoid polluting bash history. shutit = self.shutit d = {} self.send(ShutItSendSpec(self, send=' command lsb_release -a', check_exit=False, echo=False, loglevel=loglevel, ignore_background=True)) res = shutit.match_string(self.pexpect_child.before, r'^Distributor[\s]*ID:[\s]*(.*)$') if isinstance(res, str): dist_string = res d['distro'] = dist_string.lower().strip() try: d['install_type'] = (package_map.INSTALL_TYPE_MAP[dist_string.lower()]) except KeyError: raise Exception("Distribution '%s' is not supported." % dist_string) else: return d res = shutit.match_string(self.pexpect_child.before, r'^Release:[\s*](.*)$') if isinstance(res, str): version_string = res d['distro_version'] = version_string return d
[ "def", "lsb_release", "(", "self", ",", "loglevel", "=", "logging", ".", "DEBUG", ")", ":", "# v the space is intentional, to avoid polluting bash history.", "shutit", "=", "self", ".", "shutit", "d", "=", "{", "}", "self", ".", "send", "(", "ShutItSendSpec", "(", "self", ",", "send", "=", "' command lsb_release -a'", ",", "check_exit", "=", "False", ",", "echo", "=", "False", ",", "loglevel", "=", "loglevel", ",", "ignore_background", "=", "True", ")", ")", "res", "=", "shutit", ".", "match_string", "(", "self", ".", "pexpect_child", ".", "before", ",", "r'^Distributor[\\s]*ID:[\\s]*(.*)$'", ")", "if", "isinstance", "(", "res", ",", "str", ")", ":", "dist_string", "=", "res", "d", "[", "'distro'", "]", "=", "dist_string", ".", "lower", "(", ")", ".", "strip", "(", ")", "try", ":", "d", "[", "'install_type'", "]", "=", "(", "package_map", ".", "INSTALL_TYPE_MAP", "[", "dist_string", ".", "lower", "(", ")", "]", ")", "except", "KeyError", ":", "raise", "Exception", "(", "\"Distribution '%s' is not supported.\"", "%", "dist_string", ")", "else", ":", "return", "d", "res", "=", "shutit", ".", "match_string", "(", "self", ".", "pexpect_child", ".", "before", ",", "r'^Release:[\\s*](.*)$'", ")", "if", "isinstance", "(", "res", ",", "str", ")", ":", "version_string", "=", "res", "d", "[", "'distro_version'", "]", "=", "version_string", "return", "d" ]
Get distro information from lsb_release.
[ "Get", "distro", "information", "from", "lsb_release", "." ]
19cd64cdfb23515b106b40213dccff4101617076
https://github.com/ianmiell/shutit/blob/19cd64cdfb23515b106b40213dccff4101617076/shutit_pexpect.py#L1115-L1142
8,376
ianmiell/shutit
shutit_pexpect.py
ShutItPexpectSession.user_exists
def user_exists(self, user, note=None, loglevel=logging.DEBUG): """Returns true if the specified username exists. @param user: username to check for @param note: See send() @type user: string @rtype: boolean """ shutit = self.shutit shutit.handle_note(note) exists = False if user == '': return exists # v the space is intentional, to avoid polluting bash history. # The quotes before XIST are deliberate, to prevent the command from matching the expect. ret = self.send(ShutItSendSpec(self, send=' command id %s && echo E""XIST || echo N""XIST' % user, expect=['NXIST', 'EXIST'], echo=False, loglevel=loglevel, ignore_background=True)) if ret: exists = True # sync with the prompt self.expect(self.default_expect) shutit.handle_note_after(note=note) return exists
python
def user_exists(self, user, note=None, loglevel=logging.DEBUG): """Returns true if the specified username exists. @param user: username to check for @param note: See send() @type user: string @rtype: boolean """ shutit = self.shutit shutit.handle_note(note) exists = False if user == '': return exists # v the space is intentional, to avoid polluting bash history. # The quotes before XIST are deliberate, to prevent the command from matching the expect. ret = self.send(ShutItSendSpec(self, send=' command id %s && echo E""XIST || echo N""XIST' % user, expect=['NXIST', 'EXIST'], echo=False, loglevel=loglevel, ignore_background=True)) if ret: exists = True # sync with the prompt self.expect(self.default_expect) shutit.handle_note_after(note=note) return exists
[ "def", "user_exists", "(", "self", ",", "user", ",", "note", "=", "None", ",", "loglevel", "=", "logging", ".", "DEBUG", ")", ":", "shutit", "=", "self", ".", "shutit", "shutit", ".", "handle_note", "(", "note", ")", "exists", "=", "False", "if", "user", "==", "''", ":", "return", "exists", "# v the space is intentional, to avoid polluting bash history.", "# The quotes before XIST are deliberate, to prevent the command from matching the expect.", "ret", "=", "self", ".", "send", "(", "ShutItSendSpec", "(", "self", ",", "send", "=", "' command id %s && echo E\"\"XIST || echo N\"\"XIST'", "%", "user", ",", "expect", "=", "[", "'NXIST'", ",", "'EXIST'", "]", ",", "echo", "=", "False", ",", "loglevel", "=", "loglevel", ",", "ignore_background", "=", "True", ")", ")", "if", "ret", ":", "exists", "=", "True", "# sync with the prompt", "self", ".", "expect", "(", "self", ".", "default_expect", ")", "shutit", ".", "handle_note_after", "(", "note", "=", "note", ")", "return", "exists" ]
Returns true if the specified username exists. @param user: username to check for @param note: See send() @type user: string @rtype: boolean
[ "Returns", "true", "if", "the", "specified", "username", "exists", "." ]
19cd64cdfb23515b106b40213dccff4101617076
https://github.com/ianmiell/shutit/blob/19cd64cdfb23515b106b40213dccff4101617076/shutit_pexpect.py#L1228-L1259
8,377
ianmiell/shutit
shutit_pexpect.py
ShutItPexpectSession.quick_send
def quick_send(self, send, echo=None, loglevel=logging.INFO): """Quick and dirty send that ignores background tasks. Intended for internal use. """ shutit = self.shutit shutit.log('Quick send: ' + send, level=loglevel) res = self.sendline(ShutItSendSpec(self, send=send, check_exit=False, echo=echo, fail_on_empty_before=False, record_command=False, ignore_background=True)) if not res: self.expect(self.default_expect)
python
def quick_send(self, send, echo=None, loglevel=logging.INFO): """Quick and dirty send that ignores background tasks. Intended for internal use. """ shutit = self.shutit shutit.log('Quick send: ' + send, level=loglevel) res = self.sendline(ShutItSendSpec(self, send=send, check_exit=False, echo=echo, fail_on_empty_before=False, record_command=False, ignore_background=True)) if not res: self.expect(self.default_expect)
[ "def", "quick_send", "(", "self", ",", "send", ",", "echo", "=", "None", ",", "loglevel", "=", "logging", ".", "INFO", ")", ":", "shutit", "=", "self", ".", "shutit", "shutit", ".", "log", "(", "'Quick send: '", "+", "send", ",", "level", "=", "loglevel", ")", "res", "=", "self", ".", "sendline", "(", "ShutItSendSpec", "(", "self", ",", "send", "=", "send", ",", "check_exit", "=", "False", ",", "echo", "=", "echo", ",", "fail_on_empty_before", "=", "False", ",", "record_command", "=", "False", ",", "ignore_background", "=", "True", ")", ")", "if", "not", "res", ":", "self", ".", "expect", "(", "self", ".", "default_expect", ")" ]
Quick and dirty send that ignores background tasks. Intended for internal use.
[ "Quick", "and", "dirty", "send", "that", "ignores", "background", "tasks", ".", "Intended", "for", "internal", "use", "." ]
19cd64cdfb23515b106b40213dccff4101617076
https://github.com/ianmiell/shutit/blob/19cd64cdfb23515b106b40213dccff4101617076/shutit_pexpect.py#L2938-L2951
8,378
ianmiell/shutit
shutit_pexpect.py
ShutItPexpectSession._create_command_file
def _create_command_file(self, expect, send): """Internal function. Do not use. Takes a long command, and puts it in an executable file ready to run. Returns the filename. """ shutit = self.shutit random_id = shutit_util.random_id() fname = shutit_global.shutit_global_object.shutit_state_dir + '/tmp_' + random_id working_str = send # truncate -s must be used as --size is not supported everywhere (eg busybox) assert not self.sendline(ShutItSendSpec(self, send=' truncate -s 0 '+ fname, ignore_background=True)), shutit_util.print_debug() self.expect(expect) size = shutit_global.shutit_global_object.line_limit while working_str: curr_str = working_str[:size] working_str = working_str[size:] assert not self.sendline(ShutItSendSpec(self, send=' ' + shutit.get_command('head') + ''' -c -1 >> ''' + fname + """ << 'END_""" + random_id + """'\n""" + curr_str + """\nEND_""" + random_id, ignore_background=True)), shutit_util.print_debug() self.expect(expect) assert not self.sendline(ShutItSendSpec(self, send=' chmod +x ' + fname, ignore_background=True)), shutit_util.print_debug() self.expect(expect) return fname
python
def _create_command_file(self, expect, send): """Internal function. Do not use. Takes a long command, and puts it in an executable file ready to run. Returns the filename. """ shutit = self.shutit random_id = shutit_util.random_id() fname = shutit_global.shutit_global_object.shutit_state_dir + '/tmp_' + random_id working_str = send # truncate -s must be used as --size is not supported everywhere (eg busybox) assert not self.sendline(ShutItSendSpec(self, send=' truncate -s 0 '+ fname, ignore_background=True)), shutit_util.print_debug() self.expect(expect) size = shutit_global.shutit_global_object.line_limit while working_str: curr_str = working_str[:size] working_str = working_str[size:] assert not self.sendline(ShutItSendSpec(self, send=' ' + shutit.get_command('head') + ''' -c -1 >> ''' + fname + """ << 'END_""" + random_id + """'\n""" + curr_str + """\nEND_""" + random_id, ignore_background=True)), shutit_util.print_debug() self.expect(expect) assert not self.sendline(ShutItSendSpec(self, send=' chmod +x ' + fname, ignore_background=True)), shutit_util.print_debug() self.expect(expect) return fname
[ "def", "_create_command_file", "(", "self", ",", "expect", ",", "send", ")", ":", "shutit", "=", "self", ".", "shutit", "random_id", "=", "shutit_util", ".", "random_id", "(", ")", "fname", "=", "shutit_global", ".", "shutit_global_object", ".", "shutit_state_dir", "+", "'/tmp_'", "+", "random_id", "working_str", "=", "send", "# truncate -s must be used as --size is not supported everywhere (eg busybox)", "assert", "not", "self", ".", "sendline", "(", "ShutItSendSpec", "(", "self", ",", "send", "=", "' truncate -s 0 '", "+", "fname", ",", "ignore_background", "=", "True", ")", ")", ",", "shutit_util", ".", "print_debug", "(", ")", "self", ".", "expect", "(", "expect", ")", "size", "=", "shutit_global", ".", "shutit_global_object", ".", "line_limit", "while", "working_str", ":", "curr_str", "=", "working_str", "[", ":", "size", "]", "working_str", "=", "working_str", "[", "size", ":", "]", "assert", "not", "self", ".", "sendline", "(", "ShutItSendSpec", "(", "self", ",", "send", "=", "' '", "+", "shutit", ".", "get_command", "(", "'head'", ")", "+", "''' -c -1 >> '''", "+", "fname", "+", "\"\"\" << 'END_\"\"\"", "+", "random_id", "+", "\"\"\"'\\n\"\"\"", "+", "curr_str", "+", "\"\"\"\\nEND_\"\"\"", "+", "random_id", ",", "ignore_background", "=", "True", ")", ")", ",", "shutit_util", ".", "print_debug", "(", ")", "self", ".", "expect", "(", "expect", ")", "assert", "not", "self", ".", "sendline", "(", "ShutItSendSpec", "(", "self", ",", "send", "=", "' chmod +x '", "+", "fname", ",", "ignore_background", "=", "True", ")", ")", ",", "shutit_util", ".", "print_debug", "(", ")", "self", ".", "expect", "(", "expect", ")", "return", "fname" ]
Internal function. Do not use. Takes a long command, and puts it in an executable file ready to run. Returns the filename.
[ "Internal", "function", ".", "Do", "not", "use", "." ]
19cd64cdfb23515b106b40213dccff4101617076
https://github.com/ianmiell/shutit/blob/19cd64cdfb23515b106b40213dccff4101617076/shutit_pexpect.py#L3535-L3561
8,379
ianmiell/shutit
shutit_class.py
check_dependee_order
def check_dependee_order(depender, dependee, dependee_id): """Checks whether run orders are in the appropriate order. """ # If it depends on a module id, then the module id should be higher up # in the run order. shutit_global.shutit_global_object.yield_to_draw() if dependee.run_order > depender.run_order: return 'depender module id:\n\n' + depender.module_id + '\n\n(run order: ' + str(depender.run_order) + ') ' + 'depends on dependee module_id:\n\n' + dependee_id + '\n\n(run order: ' + str(dependee.run_order) + ') ' + 'but the latter is configured to run after the former' return ''
python
def check_dependee_order(depender, dependee, dependee_id): """Checks whether run orders are in the appropriate order. """ # If it depends on a module id, then the module id should be higher up # in the run order. shutit_global.shutit_global_object.yield_to_draw() if dependee.run_order > depender.run_order: return 'depender module id:\n\n' + depender.module_id + '\n\n(run order: ' + str(depender.run_order) + ') ' + 'depends on dependee module_id:\n\n' + dependee_id + '\n\n(run order: ' + str(dependee.run_order) + ') ' + 'but the latter is configured to run after the former' return ''
[ "def", "check_dependee_order", "(", "depender", ",", "dependee", ",", "dependee_id", ")", ":", "# If it depends on a module id, then the module id should be higher up", "# in the run order.", "shutit_global", ".", "shutit_global_object", ".", "yield_to_draw", "(", ")", "if", "dependee", ".", "run_order", ">", "depender", ".", "run_order", ":", "return", "'depender module id:\\n\\n'", "+", "depender", ".", "module_id", "+", "'\\n\\n(run order: '", "+", "str", "(", "depender", ".", "run_order", ")", "+", "') '", "+", "'depends on dependee module_id:\\n\\n'", "+", "dependee_id", "+", "'\\n\\n(run order: '", "+", "str", "(", "dependee", ".", "run_order", ")", "+", "') '", "+", "'but the latter is configured to run after the former'", "return", "''" ]
Checks whether run orders are in the appropriate order.
[ "Checks", "whether", "run", "orders", "are", "in", "the", "appropriate", "order", "." ]
19cd64cdfb23515b106b40213dccff4101617076
https://github.com/ianmiell/shutit/blob/19cd64cdfb23515b106b40213dccff4101617076/shutit_class.py#L4869-L4877
8,380
ianmiell/shutit
shutit_class.py
make_dep_graph
def make_dep_graph(depender): """Returns a digraph string fragment based on the passed-in module """ shutit_global.shutit_global_object.yield_to_draw() digraph = '' for dependee_id in depender.depends_on: digraph = (digraph + '"' + depender.module_id + '"->"' + dependee_id + '";\n') return digraph
python
def make_dep_graph(depender): """Returns a digraph string fragment based on the passed-in module """ shutit_global.shutit_global_object.yield_to_draw() digraph = '' for dependee_id in depender.depends_on: digraph = (digraph + '"' + depender.module_id + '"->"' + dependee_id + '";\n') return digraph
[ "def", "make_dep_graph", "(", "depender", ")", ":", "shutit_global", ".", "shutit_global_object", ".", "yield_to_draw", "(", ")", "digraph", "=", "''", "for", "dependee_id", "in", "depender", ".", "depends_on", ":", "digraph", "=", "(", "digraph", "+", "'\"'", "+", "depender", ".", "module_id", "+", "'\"->\"'", "+", "dependee_id", "+", "'\";\\n'", ")", "return", "digraph" ]
Returns a digraph string fragment based on the passed-in module
[ "Returns", "a", "digraph", "string", "fragment", "based", "on", "the", "passed", "-", "in", "module" ]
19cd64cdfb23515b106b40213dccff4101617076
https://github.com/ianmiell/shutit/blob/19cd64cdfb23515b106b40213dccff4101617076/shutit_class.py#L4880-L4887
8,381
ianmiell/shutit
shutit_class.py
LayerConfigParser.get_config_set
def get_config_set(self, section, option): """Returns a set with each value per config file in it. """ values = set() for cp, filename, fp in self.layers: filename = filename # pylint fp = fp # pylint if cp.has_option(section, option): values.add(cp.get(section, option)) return values
python
def get_config_set(self, section, option): """Returns a set with each value per config file in it. """ values = set() for cp, filename, fp in self.layers: filename = filename # pylint fp = fp # pylint if cp.has_option(section, option): values.add(cp.get(section, option)) return values
[ "def", "get_config_set", "(", "self", ",", "section", ",", "option", ")", ":", "values", "=", "set", "(", ")", "for", "cp", ",", "filename", ",", "fp", "in", "self", ".", "layers", ":", "filename", "=", "filename", "# pylint", "fp", "=", "fp", "# pylint", "if", "cp", ".", "has_option", "(", "section", ",", "option", ")", ":", "values", ".", "add", "(", "cp", ".", "get", "(", "section", ",", "option", ")", ")", "return", "values" ]
Returns a set with each value per config file in it.
[ "Returns", "a", "set", "with", "each", "value", "per", "config", "file", "in", "it", "." ]
19cd64cdfb23515b106b40213dccff4101617076
https://github.com/ianmiell/shutit/blob/19cd64cdfb23515b106b40213dccff4101617076/shutit_class.py#L117-L126
8,382
ianmiell/shutit
shutit_class.py
LayerConfigParser.reload
def reload(self): """ Re-reads all layers again. In theory this should overwrite all the old values with any newer ones. It assumes we never delete a config item before reload. """ oldlayers = self.layers self.layers = [] for cp, filename, fp in oldlayers: cp = cp # pylint if fp is None: self.read(filename) else: self.readfp(fp, filename)
python
def reload(self): """ Re-reads all layers again. In theory this should overwrite all the old values with any newer ones. It assumes we never delete a config item before reload. """ oldlayers = self.layers self.layers = [] for cp, filename, fp in oldlayers: cp = cp # pylint if fp is None: self.read(filename) else: self.readfp(fp, filename)
[ "def", "reload", "(", "self", ")", ":", "oldlayers", "=", "self", ".", "layers", "self", ".", "layers", "=", "[", "]", "for", "cp", ",", "filename", ",", "fp", "in", "oldlayers", ":", "cp", "=", "cp", "# pylint", "if", "fp", "is", "None", ":", "self", ".", "read", "(", "filename", ")", "else", ":", "self", ".", "readfp", "(", "fp", ",", "filename", ")" ]
Re-reads all layers again. In theory this should overwrite all the old values with any newer ones. It assumes we never delete a config item before reload.
[ "Re", "-", "reads", "all", "layers", "again", ".", "In", "theory", "this", "should", "overwrite", "all", "the", "old", "values", "with", "any", "newer", "ones", ".", "It", "assumes", "we", "never", "delete", "a", "config", "item", "before", "reload", "." ]
19cd64cdfb23515b106b40213dccff4101617076
https://github.com/ianmiell/shutit/blob/19cd64cdfb23515b106b40213dccff4101617076/shutit_class.py#L128-L141
8,383
ianmiell/shutit
shutit_class.py
ShutIt.get_shutit_pexpect_session_environment
def get_shutit_pexpect_session_environment(self, environment_id): """Returns the first shutit_pexpect_session object related to the given environment-id """ if not isinstance(environment_id, str): self.fail('Wrong argument type in get_shutit_pexpect_session_environment') # pragma: no cover for env in shutit_global.shutit_global_object.shutit_pexpect_session_environments: if env.environment_id == environment_id: return env return None
python
def get_shutit_pexpect_session_environment(self, environment_id): """Returns the first shutit_pexpect_session object related to the given environment-id """ if not isinstance(environment_id, str): self.fail('Wrong argument type in get_shutit_pexpect_session_environment') # pragma: no cover for env in shutit_global.shutit_global_object.shutit_pexpect_session_environments: if env.environment_id == environment_id: return env return None
[ "def", "get_shutit_pexpect_session_environment", "(", "self", ",", "environment_id", ")", ":", "if", "not", "isinstance", "(", "environment_id", ",", "str", ")", ":", "self", ".", "fail", "(", "'Wrong argument type in get_shutit_pexpect_session_environment'", ")", "# pragma: no cover", "for", "env", "in", "shutit_global", ".", "shutit_global_object", ".", "shutit_pexpect_session_environments", ":", "if", "env", ".", "environment_id", "==", "environment_id", ":", "return", "env", "return", "None" ]
Returns the first shutit_pexpect_session object related to the given environment-id
[ "Returns", "the", "first", "shutit_pexpect_session", "object", "related", "to", "the", "given", "environment", "-", "id" ]
19cd64cdfb23515b106b40213dccff4101617076
https://github.com/ianmiell/shutit/blob/19cd64cdfb23515b106b40213dccff4101617076/shutit_class.py#L515-L524
8,384
ianmiell/shutit
shutit_class.py
ShutIt.get_current_shutit_pexpect_session_environment
def get_current_shutit_pexpect_session_environment(self, note=None): """Returns the current environment from the currently-set default pexpect child. """ self.handle_note(note) current_session = self.get_current_shutit_pexpect_session() if current_session is not None: res = current_session.current_environment else: res = None self.handle_note_after(note) return res
python
def get_current_shutit_pexpect_session_environment(self, note=None): """Returns the current environment from the currently-set default pexpect child. """ self.handle_note(note) current_session = self.get_current_shutit_pexpect_session() if current_session is not None: res = current_session.current_environment else: res = None self.handle_note_after(note) return res
[ "def", "get_current_shutit_pexpect_session_environment", "(", "self", ",", "note", "=", "None", ")", ":", "self", ".", "handle_note", "(", "note", ")", "current_session", "=", "self", ".", "get_current_shutit_pexpect_session", "(", ")", "if", "current_session", "is", "not", "None", ":", "res", "=", "current_session", ".", "current_environment", "else", ":", "res", "=", "None", "self", ".", "handle_note_after", "(", "note", ")", "return", "res" ]
Returns the current environment from the currently-set default pexpect child.
[ "Returns", "the", "current", "environment", "from", "the", "currently", "-", "set", "default", "pexpect", "child", "." ]
19cd64cdfb23515b106b40213dccff4101617076
https://github.com/ianmiell/shutit/blob/19cd64cdfb23515b106b40213dccff4101617076/shutit_class.py#L527-L538
8,385
ianmiell/shutit
shutit_class.py
ShutIt.get_current_shutit_pexpect_session
def get_current_shutit_pexpect_session(self, note=None): """Returns the currently-set default pexpect child. @return: default shutit pexpect child object """ self.handle_note(note) res = self.current_shutit_pexpect_session self.handle_note_after(note) return res
python
def get_current_shutit_pexpect_session(self, note=None): """Returns the currently-set default pexpect child. @return: default shutit pexpect child object """ self.handle_note(note) res = self.current_shutit_pexpect_session self.handle_note_after(note) return res
[ "def", "get_current_shutit_pexpect_session", "(", "self", ",", "note", "=", "None", ")", ":", "self", ".", "handle_note", "(", "note", ")", "res", "=", "self", ".", "current_shutit_pexpect_session", "self", ".", "handle_note_after", "(", "note", ")", "return", "res" ]
Returns the currently-set default pexpect child. @return: default shutit pexpect child object
[ "Returns", "the", "currently", "-", "set", "default", "pexpect", "child", "." ]
19cd64cdfb23515b106b40213dccff4101617076
https://github.com/ianmiell/shutit/blob/19cd64cdfb23515b106b40213dccff4101617076/shutit_class.py#L541-L549
8,386
ianmiell/shutit
shutit_class.py
ShutIt.get_shutit_pexpect_sessions
def get_shutit_pexpect_sessions(self, note=None): """Returns all the shutit_pexpect_session keys for this object. @return: list of all shutit_pexpect_session keys (pexpect_session_ids) """ self.handle_note(note) sessions = [] for key in self.shutit_pexpect_sessions: sessions.append(shutit_object.shutit_pexpect_sessions[key]) self.handle_note_after(note) return sessions
python
def get_shutit_pexpect_sessions(self, note=None): """Returns all the shutit_pexpect_session keys for this object. @return: list of all shutit_pexpect_session keys (pexpect_session_ids) """ self.handle_note(note) sessions = [] for key in self.shutit_pexpect_sessions: sessions.append(shutit_object.shutit_pexpect_sessions[key]) self.handle_note_after(note) return sessions
[ "def", "get_shutit_pexpect_sessions", "(", "self", ",", "note", "=", "None", ")", ":", "self", ".", "handle_note", "(", "note", ")", "sessions", "=", "[", "]", "for", "key", "in", "self", ".", "shutit_pexpect_sessions", ":", "sessions", ".", "append", "(", "shutit_object", ".", "shutit_pexpect_sessions", "[", "key", "]", ")", "self", ".", "handle_note_after", "(", "note", ")", "return", "sessions" ]
Returns all the shutit_pexpect_session keys for this object. @return: list of all shutit_pexpect_session keys (pexpect_session_ids)
[ "Returns", "all", "the", "shutit_pexpect_session", "keys", "for", "this", "object", "." ]
19cd64cdfb23515b106b40213dccff4101617076
https://github.com/ianmiell/shutit/blob/19cd64cdfb23515b106b40213dccff4101617076/shutit_class.py#L552-L562
8,387
ianmiell/shutit
shutit_class.py
ShutIt.set_default_shutit_pexpect_session
def set_default_shutit_pexpect_session(self, shutit_pexpect_session): """Sets the default pexpect child. @param shutit_pexpect_session: pexpect child to set as default """ assert isinstance(shutit_pexpect_session, ShutItPexpectSession), shutit_util.print_debug() self.current_shutit_pexpect_session = shutit_pexpect_session return True
python
def set_default_shutit_pexpect_session(self, shutit_pexpect_session): """Sets the default pexpect child. @param shutit_pexpect_session: pexpect child to set as default """ assert isinstance(shutit_pexpect_session, ShutItPexpectSession), shutit_util.print_debug() self.current_shutit_pexpect_session = shutit_pexpect_session return True
[ "def", "set_default_shutit_pexpect_session", "(", "self", ",", "shutit_pexpect_session", ")", ":", "assert", "isinstance", "(", "shutit_pexpect_session", ",", "ShutItPexpectSession", ")", ",", "shutit_util", ".", "print_debug", "(", ")", "self", ".", "current_shutit_pexpect_session", "=", "shutit_pexpect_session", "return", "True" ]
Sets the default pexpect child. @param shutit_pexpect_session: pexpect child to set as default
[ "Sets", "the", "default", "pexpect", "child", "." ]
19cd64cdfb23515b106b40213dccff4101617076
https://github.com/ianmiell/shutit/blob/19cd64cdfb23515b106b40213dccff4101617076/shutit_class.py#L582-L589
8,388
ianmiell/shutit
shutit_class.py
ShutIt.fail
def fail(self, msg, shutit_pexpect_child=None, throw_exception=False): """Handles a failure, pausing if a pexpect child object is passed in. @param shutit_pexpect_child: pexpect child to work on @param throw_exception: Whether to throw an exception. @type throw_exception: boolean """ shutit_global.shutit_global_object.yield_to_draw() # Note: we must not default to a child here if shutit_pexpect_child is not None: shutit_pexpect_session = self.get_shutit_pexpect_session_from_child(shutit_pexpect_child) shutit_util.print_debug(sys.exc_info()) shutit_pexpect_session.pause_point('Pause point on fail: ' + msg, color='31') if throw_exception: sys.stderr.write('Error caught: ' + msg + '\n') sys.stderr.write('\n') shutit_util.print_debug(sys.exc_info()) raise ShutItFailException(msg) else: # This is an "OK" failure, ie we don't need to throw an exception. # However, it's still a "failure", so return 1 shutit_global.shutit_global_object.handle_exit(exit_code=1,msg=msg) shutit_global.shutit_global_object.yield_to_draw()
python
def fail(self, msg, shutit_pexpect_child=None, throw_exception=False): """Handles a failure, pausing if a pexpect child object is passed in. @param shutit_pexpect_child: pexpect child to work on @param throw_exception: Whether to throw an exception. @type throw_exception: boolean """ shutit_global.shutit_global_object.yield_to_draw() # Note: we must not default to a child here if shutit_pexpect_child is not None: shutit_pexpect_session = self.get_shutit_pexpect_session_from_child(shutit_pexpect_child) shutit_util.print_debug(sys.exc_info()) shutit_pexpect_session.pause_point('Pause point on fail: ' + msg, color='31') if throw_exception: sys.stderr.write('Error caught: ' + msg + '\n') sys.stderr.write('\n') shutit_util.print_debug(sys.exc_info()) raise ShutItFailException(msg) else: # This is an "OK" failure, ie we don't need to throw an exception. # However, it's still a "failure", so return 1 shutit_global.shutit_global_object.handle_exit(exit_code=1,msg=msg) shutit_global.shutit_global_object.yield_to_draw()
[ "def", "fail", "(", "self", ",", "msg", ",", "shutit_pexpect_child", "=", "None", ",", "throw_exception", "=", "False", ")", ":", "shutit_global", ".", "shutit_global_object", ".", "yield_to_draw", "(", ")", "# Note: we must not default to a child here", "if", "shutit_pexpect_child", "is", "not", "None", ":", "shutit_pexpect_session", "=", "self", ".", "get_shutit_pexpect_session_from_child", "(", "shutit_pexpect_child", ")", "shutit_util", ".", "print_debug", "(", "sys", ".", "exc_info", "(", ")", ")", "shutit_pexpect_session", ".", "pause_point", "(", "'Pause point on fail: '", "+", "msg", ",", "color", "=", "'31'", ")", "if", "throw_exception", ":", "sys", ".", "stderr", ".", "write", "(", "'Error caught: '", "+", "msg", "+", "'\\n'", ")", "sys", ".", "stderr", ".", "write", "(", "'\\n'", ")", "shutit_util", ".", "print_debug", "(", "sys", ".", "exc_info", "(", ")", ")", "raise", "ShutItFailException", "(", "msg", ")", "else", ":", "# This is an \"OK\" failure, ie we don't need to throw an exception.", "# However, it's still a \"failure\", so return 1", "shutit_global", ".", "shutit_global_object", ".", "handle_exit", "(", "exit_code", "=", "1", ",", "msg", "=", "msg", ")", "shutit_global", ".", "shutit_global_object", ".", "yield_to_draw", "(", ")" ]
Handles a failure, pausing if a pexpect child object is passed in. @param shutit_pexpect_child: pexpect child to work on @param throw_exception: Whether to throw an exception. @type throw_exception: boolean
[ "Handles", "a", "failure", "pausing", "if", "a", "pexpect", "child", "object", "is", "passed", "in", "." ]
19cd64cdfb23515b106b40213dccff4101617076
https://github.com/ianmiell/shutit/blob/19cd64cdfb23515b106b40213dccff4101617076/shutit_class.py#L607-L629
8,389
ianmiell/shutit
shutit_class.py
ShutIt.get_current_environment
def get_current_environment(self, note=None): """Returns the current environment id from the current shutit_pexpect_session """ shutit_global.shutit_global_object.yield_to_draw() self.handle_note(note) res = self.get_current_shutit_pexpect_session_environment().environment_id self.handle_note_after(note) return res
python
def get_current_environment(self, note=None): """Returns the current environment id from the current shutit_pexpect_session """ shutit_global.shutit_global_object.yield_to_draw() self.handle_note(note) res = self.get_current_shutit_pexpect_session_environment().environment_id self.handle_note_after(note) return res
[ "def", "get_current_environment", "(", "self", ",", "note", "=", "None", ")", ":", "shutit_global", ".", "shutit_global_object", ".", "yield_to_draw", "(", ")", "self", ".", "handle_note", "(", "note", ")", "res", "=", "self", ".", "get_current_shutit_pexpect_session_environment", "(", ")", ".", "environment_id", "self", ".", "handle_note_after", "(", "note", ")", "return", "res" ]
Returns the current environment id from the current shutit_pexpect_session
[ "Returns", "the", "current", "environment", "id", "from", "the", "current", "shutit_pexpect_session" ]
19cd64cdfb23515b106b40213dccff4101617076
https://github.com/ianmiell/shutit/blob/19cd64cdfb23515b106b40213dccff4101617076/shutit_class.py#L632-L640
8,390
ianmiell/shutit
shutit_class.py
ShutIt.handle_note
def handle_note(self, note, command='', training_input=''): """Handle notes and walkthrough option. @param note: See send() """ shutit_global.shutit_global_object.yield_to_draw() if self.build['walkthrough'] and note != None and note != '': assert isinstance(note, str), shutit_util.print_debug() wait = self.build['walkthrough_wait'] wrap = '\n' + 80*'=' + '\n' message = wrap + note + wrap if command != '': message += 'Command to be run is:\n\t' + command + wrap if wait >= 0: self.pause_point(message, color=31, wait=wait) else: if training_input != '' and self.build['training']: if len(training_input.split('\n')) == 1: shutit_global.shutit_global_object.shutit_print(shutit_util.colorise('31',message)) while shutit_util.util_raw_input(prompt=shutit_util.colorise('32','Enter the command to continue (or "s" to skip typing it in): ')) not in (training_input,'s'): shutit_global.shutit_global_object.shutit_print('Wrong! Try again!') shutit_global.shutit_global_object.shutit_print(shutit_util.colorise('31','OK!')) else: self.pause_point(message + '\nToo long to use for training, so skipping the option to type in!\nHit CTRL-] to continue', color=31) else: self.pause_point(message + '\nHit CTRL-] to continue', color=31) return True
python
def handle_note(self, note, command='', training_input=''): """Handle notes and walkthrough option. @param note: See send() """ shutit_global.shutit_global_object.yield_to_draw() if self.build['walkthrough'] and note != None and note != '': assert isinstance(note, str), shutit_util.print_debug() wait = self.build['walkthrough_wait'] wrap = '\n' + 80*'=' + '\n' message = wrap + note + wrap if command != '': message += 'Command to be run is:\n\t' + command + wrap if wait >= 0: self.pause_point(message, color=31, wait=wait) else: if training_input != '' and self.build['training']: if len(training_input.split('\n')) == 1: shutit_global.shutit_global_object.shutit_print(shutit_util.colorise('31',message)) while shutit_util.util_raw_input(prompt=shutit_util.colorise('32','Enter the command to continue (or "s" to skip typing it in): ')) not in (training_input,'s'): shutit_global.shutit_global_object.shutit_print('Wrong! Try again!') shutit_global.shutit_global_object.shutit_print(shutit_util.colorise('31','OK!')) else: self.pause_point(message + '\nToo long to use for training, so skipping the option to type in!\nHit CTRL-] to continue', color=31) else: self.pause_point(message + '\nHit CTRL-] to continue', color=31) return True
[ "def", "handle_note", "(", "self", ",", "note", ",", "command", "=", "''", ",", "training_input", "=", "''", ")", ":", "shutit_global", ".", "shutit_global_object", ".", "yield_to_draw", "(", ")", "if", "self", ".", "build", "[", "'walkthrough'", "]", "and", "note", "!=", "None", "and", "note", "!=", "''", ":", "assert", "isinstance", "(", "note", ",", "str", ")", ",", "shutit_util", ".", "print_debug", "(", ")", "wait", "=", "self", ".", "build", "[", "'walkthrough_wait'", "]", "wrap", "=", "'\\n'", "+", "80", "*", "'='", "+", "'\\n'", "message", "=", "wrap", "+", "note", "+", "wrap", "if", "command", "!=", "''", ":", "message", "+=", "'Command to be run is:\\n\\t'", "+", "command", "+", "wrap", "if", "wait", ">=", "0", ":", "self", ".", "pause_point", "(", "message", ",", "color", "=", "31", ",", "wait", "=", "wait", ")", "else", ":", "if", "training_input", "!=", "''", "and", "self", ".", "build", "[", "'training'", "]", ":", "if", "len", "(", "training_input", ".", "split", "(", "'\\n'", ")", ")", "==", "1", ":", "shutit_global", ".", "shutit_global_object", ".", "shutit_print", "(", "shutit_util", ".", "colorise", "(", "'31'", ",", "message", ")", ")", "while", "shutit_util", ".", "util_raw_input", "(", "prompt", "=", "shutit_util", ".", "colorise", "(", "'32'", ",", "'Enter the command to continue (or \"s\" to skip typing it in): '", ")", ")", "not", "in", "(", "training_input", ",", "'s'", ")", ":", "shutit_global", ".", "shutit_global_object", ".", "shutit_print", "(", "'Wrong! Try again!'", ")", "shutit_global", ".", "shutit_global_object", ".", "shutit_print", "(", "shutit_util", ".", "colorise", "(", "'31'", ",", "'OK!'", ")", ")", "else", ":", "self", ".", "pause_point", "(", "message", "+", "'\\nToo long to use for training, so skipping the option to type in!\\nHit CTRL-] to continue'", ",", "color", "=", "31", ")", "else", ":", "self", ".", "pause_point", "(", "message", "+", "'\\nHit CTRL-] to continue'", ",", "color", "=", "31", ")", "return", "True" ]
Handle notes and walkthrough option. @param note: See send()
[ "Handle", "notes", "and", "walkthrough", "option", "." ]
19cd64cdfb23515b106b40213dccff4101617076
https://github.com/ianmiell/shutit/blob/19cd64cdfb23515b106b40213dccff4101617076/shutit_class.py#L938-L964
8,391
ianmiell/shutit
shutit_class.py
ShutIt.expect_allow_interrupt
def expect_allow_interrupt(self, shutit_pexpect_child, expect, timeout, iteration_s=1): """This function allows you to interrupt the run at more or less any point by breaking up the timeout into interactive chunks. """ shutit_global.shutit_global_object.yield_to_draw() shutit_pexpect_session = self.get_shutit_pexpect_session_from_child(shutit_pexpect_child) accum_timeout = 0 if isinstance(expect, str): expect = [expect] if timeout < 1: timeout = 1 if iteration_s > timeout: iteration_s = timeout - 1 if iteration_s < 1: iteration_s = 1 timed_out = True iteration_n = 0 while accum_timeout < timeout: iteration_n+=1 res = shutit_pexpect_session.expect(expect, timeout=iteration_s, iteration_n=iteration_n) if res == len(expect): if self.build['ctrlc_stop']: timed_out = False self.build['ctrlc_stop'] = False break accum_timeout += iteration_s else: return res if timed_out and not shutit_global.shutit_global_object.determine_interactive(): self.log('Command timed out, trying to get terminal back for you', level=logging.DEBUG) self.fail('Timed out and could not recover') # pragma: no cover else: if shutit_global.shutit_global_object.determine_interactive(): shutit_pexpect_child.send('\x03') res = shutit_pexpect_session.expect(expect,timeout=1) if res == len(expect): shutit_pexpect_child.send('\x1a') res = shutit_pexpect_session.expect(expect,timeout=1) if res == len(expect): self.fail('CTRL-C sent by ShutIt following a timeout, and could not recover') # pragma: no cover shutit_pexpect_session.pause_point('CTRL-C sent by ShutIt following a timeout; the command has been cancelled') return res else: if timed_out: self.fail('Timed out and interactive, but could not recover') # pragma: no cover else: self.fail('CTRL-C hit and could not recover') # pragma: no cover self.fail('Should not get here (expect_allow_interrupt)') # pragma: no cover return True
python
def expect_allow_interrupt(self, shutit_pexpect_child, expect, timeout, iteration_s=1): """This function allows you to interrupt the run at more or less any point by breaking up the timeout into interactive chunks. """ shutit_global.shutit_global_object.yield_to_draw() shutit_pexpect_session = self.get_shutit_pexpect_session_from_child(shutit_pexpect_child) accum_timeout = 0 if isinstance(expect, str): expect = [expect] if timeout < 1: timeout = 1 if iteration_s > timeout: iteration_s = timeout - 1 if iteration_s < 1: iteration_s = 1 timed_out = True iteration_n = 0 while accum_timeout < timeout: iteration_n+=1 res = shutit_pexpect_session.expect(expect, timeout=iteration_s, iteration_n=iteration_n) if res == len(expect): if self.build['ctrlc_stop']: timed_out = False self.build['ctrlc_stop'] = False break accum_timeout += iteration_s else: return res if timed_out and not shutit_global.shutit_global_object.determine_interactive(): self.log('Command timed out, trying to get terminal back for you', level=logging.DEBUG) self.fail('Timed out and could not recover') # pragma: no cover else: if shutit_global.shutit_global_object.determine_interactive(): shutit_pexpect_child.send('\x03') res = shutit_pexpect_session.expect(expect,timeout=1) if res == len(expect): shutit_pexpect_child.send('\x1a') res = shutit_pexpect_session.expect(expect,timeout=1) if res == len(expect): self.fail('CTRL-C sent by ShutIt following a timeout, and could not recover') # pragma: no cover shutit_pexpect_session.pause_point('CTRL-C sent by ShutIt following a timeout; the command has been cancelled') return res else: if timed_out: self.fail('Timed out and interactive, but could not recover') # pragma: no cover else: self.fail('CTRL-C hit and could not recover') # pragma: no cover self.fail('Should not get here (expect_allow_interrupt)') # pragma: no cover return True
[ "def", "expect_allow_interrupt", "(", "self", ",", "shutit_pexpect_child", ",", "expect", ",", "timeout", ",", "iteration_s", "=", "1", ")", ":", "shutit_global", ".", "shutit_global_object", ".", "yield_to_draw", "(", ")", "shutit_pexpect_session", "=", "self", ".", "get_shutit_pexpect_session_from_child", "(", "shutit_pexpect_child", ")", "accum_timeout", "=", "0", "if", "isinstance", "(", "expect", ",", "str", ")", ":", "expect", "=", "[", "expect", "]", "if", "timeout", "<", "1", ":", "timeout", "=", "1", "if", "iteration_s", ">", "timeout", ":", "iteration_s", "=", "timeout", "-", "1", "if", "iteration_s", "<", "1", ":", "iteration_s", "=", "1", "timed_out", "=", "True", "iteration_n", "=", "0", "while", "accum_timeout", "<", "timeout", ":", "iteration_n", "+=", "1", "res", "=", "shutit_pexpect_session", ".", "expect", "(", "expect", ",", "timeout", "=", "iteration_s", ",", "iteration_n", "=", "iteration_n", ")", "if", "res", "==", "len", "(", "expect", ")", ":", "if", "self", ".", "build", "[", "'ctrlc_stop'", "]", ":", "timed_out", "=", "False", "self", ".", "build", "[", "'ctrlc_stop'", "]", "=", "False", "break", "accum_timeout", "+=", "iteration_s", "else", ":", "return", "res", "if", "timed_out", "and", "not", "shutit_global", ".", "shutit_global_object", ".", "determine_interactive", "(", ")", ":", "self", ".", "log", "(", "'Command timed out, trying to get terminal back for you'", ",", "level", "=", "logging", ".", "DEBUG", ")", "self", ".", "fail", "(", "'Timed out and could not recover'", ")", "# pragma: no cover", "else", ":", "if", "shutit_global", ".", "shutit_global_object", ".", "determine_interactive", "(", ")", ":", "shutit_pexpect_child", ".", "send", "(", "'\\x03'", ")", "res", "=", "shutit_pexpect_session", ".", "expect", "(", "expect", ",", "timeout", "=", "1", ")", "if", "res", "==", "len", "(", "expect", ")", ":", "shutit_pexpect_child", ".", "send", "(", "'\\x1a'", ")", "res", "=", "shutit_pexpect_session", ".", "expect", "(", "expect", ",", "timeout", "=", "1", ")", "if", "res", "==", "len", "(", "expect", ")", ":", "self", ".", "fail", "(", "'CTRL-C sent by ShutIt following a timeout, and could not recover'", ")", "# pragma: no cover", "shutit_pexpect_session", ".", "pause_point", "(", "'CTRL-C sent by ShutIt following a timeout; the command has been cancelled'", ")", "return", "res", "else", ":", "if", "timed_out", ":", "self", ".", "fail", "(", "'Timed out and interactive, but could not recover'", ")", "# pragma: no cover", "else", ":", "self", ".", "fail", "(", "'CTRL-C hit and could not recover'", ")", "# pragma: no cover", "self", ".", "fail", "(", "'Should not get here (expect_allow_interrupt)'", ")", "# pragma: no cover", "return", "True" ]
This function allows you to interrupt the run at more or less any point by breaking up the timeout into interactive chunks.
[ "This", "function", "allows", "you", "to", "interrupt", "the", "run", "at", "more", "or", "less", "any", "point", "by", "breaking", "up", "the", "timeout", "into", "interactive", "chunks", "." ]
19cd64cdfb23515b106b40213dccff4101617076
https://github.com/ianmiell/shutit/blob/19cd64cdfb23515b106b40213dccff4101617076/shutit_class.py#L978-L1030
8,392
ianmiell/shutit
shutit_class.py
ShutIt.send_host_file
def send_host_file(self, path, hostfilepath, expect=None, shutit_pexpect_child=None, note=None, user=None, group=None, loglevel=logging.INFO): """Send file from host machine to given path @param path: Path to send file to. @param hostfilepath: Path to file from host to send to target. @param expect: See send() @param shutit_pexpect_child: See send() @param note: See send() @param user: Set ownership to this user (defaults to whoami) @param group: Set group to this user (defaults to first group in groups) @type path: string @type hostfilepath: string """ shutit_global.shutit_global_object.yield_to_draw() shutit_pexpect_child = shutit_pexpect_child or self.get_current_shutit_pexpect_session().pexpect_child expect = expect or self.get_current_shutit_pexpect_session().default_expect shutit_pexpect_session = self.get_shutit_pexpect_session_from_child(shutit_pexpect_child) self.handle_note(note, 'Sending file from host: ' + hostfilepath + ' to target path: ' + path) self.log('Sending file from host: ' + hostfilepath + ' to: ' + path, level=loglevel) if user is None: user = shutit_pexpect_session.whoami() if group is None: group = self.whoarewe() # TODO: use gz for both if os.path.isfile(hostfilepath): shutit_pexpect_session.send_file(path, codecs.open(hostfilepath,mode='rb',encoding='iso-8859-1').read(), user=user, group=group, loglevel=loglevel, encoding='iso-8859-1') elif os.path.isdir(hostfilepath): # Need a binary type encoding for gzip(?) self.send_host_dir(path, hostfilepath, user=user, group=group, loglevel=loglevel) else: self.fail('send_host_file - file: ' + hostfilepath + ' does not exist as file or dir. cwd is: ' + os.getcwd(), shutit_pexpect_child=shutit_pexpect_child, throw_exception=False) # pragma: no cover self.handle_note_after(note=note) return True
python
def send_host_file(self, path, hostfilepath, expect=None, shutit_pexpect_child=None, note=None, user=None, group=None, loglevel=logging.INFO): """Send file from host machine to given path @param path: Path to send file to. @param hostfilepath: Path to file from host to send to target. @param expect: See send() @param shutit_pexpect_child: See send() @param note: See send() @param user: Set ownership to this user (defaults to whoami) @param group: Set group to this user (defaults to first group in groups) @type path: string @type hostfilepath: string """ shutit_global.shutit_global_object.yield_to_draw() shutit_pexpect_child = shutit_pexpect_child or self.get_current_shutit_pexpect_session().pexpect_child expect = expect or self.get_current_shutit_pexpect_session().default_expect shutit_pexpect_session = self.get_shutit_pexpect_session_from_child(shutit_pexpect_child) self.handle_note(note, 'Sending file from host: ' + hostfilepath + ' to target path: ' + path) self.log('Sending file from host: ' + hostfilepath + ' to: ' + path, level=loglevel) if user is None: user = shutit_pexpect_session.whoami() if group is None: group = self.whoarewe() # TODO: use gz for both if os.path.isfile(hostfilepath): shutit_pexpect_session.send_file(path, codecs.open(hostfilepath,mode='rb',encoding='iso-8859-1').read(), user=user, group=group, loglevel=loglevel, encoding='iso-8859-1') elif os.path.isdir(hostfilepath): # Need a binary type encoding for gzip(?) self.send_host_dir(path, hostfilepath, user=user, group=group, loglevel=loglevel) else: self.fail('send_host_file - file: ' + hostfilepath + ' does not exist as file or dir. cwd is: ' + os.getcwd(), shutit_pexpect_child=shutit_pexpect_child, throw_exception=False) # pragma: no cover self.handle_note_after(note=note) return True
[ "def", "send_host_file", "(", "self", ",", "path", ",", "hostfilepath", ",", "expect", "=", "None", ",", "shutit_pexpect_child", "=", "None", ",", "note", "=", "None", ",", "user", "=", "None", ",", "group", "=", "None", ",", "loglevel", "=", "logging", ".", "INFO", ")", ":", "shutit_global", ".", "shutit_global_object", ".", "yield_to_draw", "(", ")", "shutit_pexpect_child", "=", "shutit_pexpect_child", "or", "self", ".", "get_current_shutit_pexpect_session", "(", ")", ".", "pexpect_child", "expect", "=", "expect", "or", "self", ".", "get_current_shutit_pexpect_session", "(", ")", ".", "default_expect", "shutit_pexpect_session", "=", "self", ".", "get_shutit_pexpect_session_from_child", "(", "shutit_pexpect_child", ")", "self", ".", "handle_note", "(", "note", ",", "'Sending file from host: '", "+", "hostfilepath", "+", "' to target path: '", "+", "path", ")", "self", ".", "log", "(", "'Sending file from host: '", "+", "hostfilepath", "+", "' to: '", "+", "path", ",", "level", "=", "loglevel", ")", "if", "user", "is", "None", ":", "user", "=", "shutit_pexpect_session", ".", "whoami", "(", ")", "if", "group", "is", "None", ":", "group", "=", "self", ".", "whoarewe", "(", ")", "# TODO: use gz for both", "if", "os", ".", "path", ".", "isfile", "(", "hostfilepath", ")", ":", "shutit_pexpect_session", ".", "send_file", "(", "path", ",", "codecs", ".", "open", "(", "hostfilepath", ",", "mode", "=", "'rb'", ",", "encoding", "=", "'iso-8859-1'", ")", ".", "read", "(", ")", ",", "user", "=", "user", ",", "group", "=", "group", ",", "loglevel", "=", "loglevel", ",", "encoding", "=", "'iso-8859-1'", ")", "elif", "os", ".", "path", ".", "isdir", "(", "hostfilepath", ")", ":", "# Need a binary type encoding for gzip(?)", "self", ".", "send_host_dir", "(", "path", ",", "hostfilepath", ",", "user", "=", "user", ",", "group", "=", "group", ",", "loglevel", "=", "loglevel", ")", "else", ":", "self", ".", "fail", "(", "'send_host_file - file: '", "+", "hostfilepath", "+", "' does not exist as file or dir. cwd is: '", "+", "os", ".", "getcwd", "(", ")", ",", "shutit_pexpect_child", "=", "shutit_pexpect_child", ",", "throw_exception", "=", "False", ")", "# pragma: no cover", "self", ".", "handle_note_after", "(", "note", "=", "note", ")", "return", "True" ]
Send file from host machine to given path @param path: Path to send file to. @param hostfilepath: Path to file from host to send to target. @param expect: See send() @param shutit_pexpect_child: See send() @param note: See send() @param user: Set ownership to this user (defaults to whoami) @param group: Set group to this user (defaults to first group in groups) @type path: string @type hostfilepath: string
[ "Send", "file", "from", "host", "machine", "to", "given", "path" ]
19cd64cdfb23515b106b40213dccff4101617076
https://github.com/ianmiell/shutit/blob/19cd64cdfb23515b106b40213dccff4101617076/shutit_class.py#L1118-L1168
8,393
ianmiell/shutit
shutit_class.py
ShutIt.send_host_dir
def send_host_dir(self, path, hostfilepath, expect=None, shutit_pexpect_child=None, note=None, user=None, group=None, loglevel=logging.DEBUG): """Send directory and all contents recursively from host machine to given path. It will automatically make directories on the target. @param path: Path to send directory to (places hostfilepath inside path as a subfolder) @param hostfilepath: Path to file from host to send to target @param expect: See send() @param shutit_pexpect_child: See send() @param note: See send() @param user: Set ownership to this user (defaults to whoami) @param group: Set group to this user (defaults to first group in groups) @type path: string @type hostfilepath: string """ shutit_global.shutit_global_object.yield_to_draw() shutit_pexpect_child = shutit_pexpect_child or self.get_current_shutit_pexpect_session().pexpect_child expect = expect or self.get_current_shutit_pexpect_session().default_expect shutit_pexpect_session = self.get_shutit_pexpect_session_from_child(shutit_pexpect_child) self.handle_note(note, 'Sending host directory: ' + hostfilepath + ' to target path: ' + path) self.log('Sending host directory: ' + hostfilepath + ' to: ' + path, level=logging.INFO) shutit_pexpect_session.send(ShutItSendSpec(shutit_pexpect_session, send=' command mkdir -p ' + path, echo=False, loglevel=loglevel)) if user is None: user = shutit_pexpect_session.whoami() if group is None: group = self.whoarewe() # Create gzip of folder #import pdb #pdb.set_trace() if shutit_pexpect_session.command_available('tar'): gzipfname = '/tmp/shutit_tar_tmp.tar.gz' with tarfile.open(gzipfname, 'w:gz') as tar: tar.add(hostfilepath, arcname=os.path.basename(hostfilepath)) shutit_pexpect_session.send_file(gzipfname, codecs.open(gzipfname,mode='rb',encoding='iso-8859-1').read(), user=user, group=group, loglevel=loglevel, encoding='iso-8859-1') shutit_pexpect_session.send(ShutItSendSpec(shutit_pexpect_session, send=' command mkdir -p ' + path + ' && command tar -C ' + path + ' -zxf ' + gzipfname)) else: # If no gunzip, fall back to old slow method. for root, subfolders, files in os.walk(hostfilepath): subfolders.sort() files.sort() for subfolder in subfolders: shutit_pexpect_session.send(ShutItSendSpec(shutit_pexpect_session, send=' command mkdir -p ' + path + '/' + subfolder, echo=False, loglevel=loglevel)) self.log('send_host_dir recursing to: ' + hostfilepath + '/' + subfolder, level=logging.DEBUG) self.send_host_dir(path + '/' + subfolder, hostfilepath + '/' + subfolder, expect=expect, shutit_pexpect_child=shutit_pexpect_child, loglevel=loglevel) for fname in files: hostfullfname = os.path.join(root, fname) targetfname = os.path.join(path, fname) self.log('send_host_dir sending file ' + hostfullfname + ' to ' + 'target file: ' + targetfname, level=logging.DEBUG) shutit_pexpect_session.send_file(targetfname, codecs.open(hostfullfname,mode='rb',encoding='iso-8859-1').read(), user=user, group=group, loglevel=loglevel, encoding='iso-8859-1') self.handle_note_after(note=note) return True
python
def send_host_dir(self, path, hostfilepath, expect=None, shutit_pexpect_child=None, note=None, user=None, group=None, loglevel=logging.DEBUG): """Send directory and all contents recursively from host machine to given path. It will automatically make directories on the target. @param path: Path to send directory to (places hostfilepath inside path as a subfolder) @param hostfilepath: Path to file from host to send to target @param expect: See send() @param shutit_pexpect_child: See send() @param note: See send() @param user: Set ownership to this user (defaults to whoami) @param group: Set group to this user (defaults to first group in groups) @type path: string @type hostfilepath: string """ shutit_global.shutit_global_object.yield_to_draw() shutit_pexpect_child = shutit_pexpect_child or self.get_current_shutit_pexpect_session().pexpect_child expect = expect or self.get_current_shutit_pexpect_session().default_expect shutit_pexpect_session = self.get_shutit_pexpect_session_from_child(shutit_pexpect_child) self.handle_note(note, 'Sending host directory: ' + hostfilepath + ' to target path: ' + path) self.log('Sending host directory: ' + hostfilepath + ' to: ' + path, level=logging.INFO) shutit_pexpect_session.send(ShutItSendSpec(shutit_pexpect_session, send=' command mkdir -p ' + path, echo=False, loglevel=loglevel)) if user is None: user = shutit_pexpect_session.whoami() if group is None: group = self.whoarewe() # Create gzip of folder #import pdb #pdb.set_trace() if shutit_pexpect_session.command_available('tar'): gzipfname = '/tmp/shutit_tar_tmp.tar.gz' with tarfile.open(gzipfname, 'w:gz') as tar: tar.add(hostfilepath, arcname=os.path.basename(hostfilepath)) shutit_pexpect_session.send_file(gzipfname, codecs.open(gzipfname,mode='rb',encoding='iso-8859-1').read(), user=user, group=group, loglevel=loglevel, encoding='iso-8859-1') shutit_pexpect_session.send(ShutItSendSpec(shutit_pexpect_session, send=' command mkdir -p ' + path + ' && command tar -C ' + path + ' -zxf ' + gzipfname)) else: # If no gunzip, fall back to old slow method. for root, subfolders, files in os.walk(hostfilepath): subfolders.sort() files.sort() for subfolder in subfolders: shutit_pexpect_session.send(ShutItSendSpec(shutit_pexpect_session, send=' command mkdir -p ' + path + '/' + subfolder, echo=False, loglevel=loglevel)) self.log('send_host_dir recursing to: ' + hostfilepath + '/' + subfolder, level=logging.DEBUG) self.send_host_dir(path + '/' + subfolder, hostfilepath + '/' + subfolder, expect=expect, shutit_pexpect_child=shutit_pexpect_child, loglevel=loglevel) for fname in files: hostfullfname = os.path.join(root, fname) targetfname = os.path.join(path, fname) self.log('send_host_dir sending file ' + hostfullfname + ' to ' + 'target file: ' + targetfname, level=logging.DEBUG) shutit_pexpect_session.send_file(targetfname, codecs.open(hostfullfname,mode='rb',encoding='iso-8859-1').read(), user=user, group=group, loglevel=loglevel, encoding='iso-8859-1') self.handle_note_after(note=note) return True
[ "def", "send_host_dir", "(", "self", ",", "path", ",", "hostfilepath", ",", "expect", "=", "None", ",", "shutit_pexpect_child", "=", "None", ",", "note", "=", "None", ",", "user", "=", "None", ",", "group", "=", "None", ",", "loglevel", "=", "logging", ".", "DEBUG", ")", ":", "shutit_global", ".", "shutit_global_object", ".", "yield_to_draw", "(", ")", "shutit_pexpect_child", "=", "shutit_pexpect_child", "or", "self", ".", "get_current_shutit_pexpect_session", "(", ")", ".", "pexpect_child", "expect", "=", "expect", "or", "self", ".", "get_current_shutit_pexpect_session", "(", ")", ".", "default_expect", "shutit_pexpect_session", "=", "self", ".", "get_shutit_pexpect_session_from_child", "(", "shutit_pexpect_child", ")", "self", ".", "handle_note", "(", "note", ",", "'Sending host directory: '", "+", "hostfilepath", "+", "' to target path: '", "+", "path", ")", "self", ".", "log", "(", "'Sending host directory: '", "+", "hostfilepath", "+", "' to: '", "+", "path", ",", "level", "=", "logging", ".", "INFO", ")", "shutit_pexpect_session", ".", "send", "(", "ShutItSendSpec", "(", "shutit_pexpect_session", ",", "send", "=", "' command mkdir -p '", "+", "path", ",", "echo", "=", "False", ",", "loglevel", "=", "loglevel", ")", ")", "if", "user", "is", "None", ":", "user", "=", "shutit_pexpect_session", ".", "whoami", "(", ")", "if", "group", "is", "None", ":", "group", "=", "self", ".", "whoarewe", "(", ")", "# Create gzip of folder", "#import pdb", "#pdb.set_trace()", "if", "shutit_pexpect_session", ".", "command_available", "(", "'tar'", ")", ":", "gzipfname", "=", "'/tmp/shutit_tar_tmp.tar.gz'", "with", "tarfile", ".", "open", "(", "gzipfname", ",", "'w:gz'", ")", "as", "tar", ":", "tar", ".", "add", "(", "hostfilepath", ",", "arcname", "=", "os", ".", "path", ".", "basename", "(", "hostfilepath", ")", ")", "shutit_pexpect_session", ".", "send_file", "(", "gzipfname", ",", "codecs", ".", "open", "(", "gzipfname", ",", "mode", "=", "'rb'", ",", "encoding", "=", "'iso-8859-1'", ")", ".", "read", "(", ")", ",", "user", "=", "user", ",", "group", "=", "group", ",", "loglevel", "=", "loglevel", ",", "encoding", "=", "'iso-8859-1'", ")", "shutit_pexpect_session", ".", "send", "(", "ShutItSendSpec", "(", "shutit_pexpect_session", ",", "send", "=", "' command mkdir -p '", "+", "path", "+", "' && command tar -C '", "+", "path", "+", "' -zxf '", "+", "gzipfname", ")", ")", "else", ":", "# If no gunzip, fall back to old slow method.", "for", "root", ",", "subfolders", ",", "files", "in", "os", ".", "walk", "(", "hostfilepath", ")", ":", "subfolders", ".", "sort", "(", ")", "files", ".", "sort", "(", ")", "for", "subfolder", "in", "subfolders", ":", "shutit_pexpect_session", ".", "send", "(", "ShutItSendSpec", "(", "shutit_pexpect_session", ",", "send", "=", "' command mkdir -p '", "+", "path", "+", "'/'", "+", "subfolder", ",", "echo", "=", "False", ",", "loglevel", "=", "loglevel", ")", ")", "self", ".", "log", "(", "'send_host_dir recursing to: '", "+", "hostfilepath", "+", "'/'", "+", "subfolder", ",", "level", "=", "logging", ".", "DEBUG", ")", "self", ".", "send_host_dir", "(", "path", "+", "'/'", "+", "subfolder", ",", "hostfilepath", "+", "'/'", "+", "subfolder", ",", "expect", "=", "expect", ",", "shutit_pexpect_child", "=", "shutit_pexpect_child", ",", "loglevel", "=", "loglevel", ")", "for", "fname", "in", "files", ":", "hostfullfname", "=", "os", ".", "path", ".", "join", "(", "root", ",", "fname", ")", "targetfname", "=", "os", ".", "path", ".", "join", "(", "path", ",", "fname", ")", "self", ".", "log", "(", "'send_host_dir sending file '", "+", "hostfullfname", "+", "' to '", "+", "'target file: '", "+", "targetfname", ",", "level", "=", "logging", ".", "DEBUG", ")", "shutit_pexpect_session", ".", "send_file", "(", "targetfname", ",", "codecs", ".", "open", "(", "hostfullfname", ",", "mode", "=", "'rb'", ",", "encoding", "=", "'iso-8859-1'", ")", ".", "read", "(", ")", ",", "user", "=", "user", ",", "group", "=", "group", ",", "loglevel", "=", "loglevel", ",", "encoding", "=", "'iso-8859-1'", ")", "self", ".", "handle_note_after", "(", "note", "=", "note", ")", "return", "True" ]
Send directory and all contents recursively from host machine to given path. It will automatically make directories on the target. @param path: Path to send directory to (places hostfilepath inside path as a subfolder) @param hostfilepath: Path to file from host to send to target @param expect: See send() @param shutit_pexpect_child: See send() @param note: See send() @param user: Set ownership to this user (defaults to whoami) @param group: Set group to this user (defaults to first group in groups) @type path: string @type hostfilepath: string
[ "Send", "directory", "and", "all", "contents", "recursively", "from", "host", "machine", "to", "given", "path", ".", "It", "will", "automatically", "make", "directories", "on", "the", "target", "." ]
19cd64cdfb23515b106b40213dccff4101617076
https://github.com/ianmiell/shutit/blob/19cd64cdfb23515b106b40213dccff4101617076/shutit_class.py#L1171-L1250
8,394
ianmiell/shutit
shutit_class.py
ShutIt.delete_text
def delete_text(self, text, fname, pattern=None, expect=None, shutit_pexpect_child=None, note=None, before=False, force=False, line_oriented=True, loglevel=logging.DEBUG): """Delete a chunk of text from a file. See insert_text. """ shutit_global.shutit_global_object.yield_to_draw() return self.change_text(text, fname, pattern, expect, shutit_pexpect_child, before, force, note=note, delete=True, line_oriented=line_oriented, loglevel=loglevel)
python
def delete_text(self, text, fname, pattern=None, expect=None, shutit_pexpect_child=None, note=None, before=False, force=False, line_oriented=True, loglevel=logging.DEBUG): """Delete a chunk of text from a file. See insert_text. """ shutit_global.shutit_global_object.yield_to_draw() return self.change_text(text, fname, pattern, expect, shutit_pexpect_child, before, force, note=note, delete=True, line_oriented=line_oriented, loglevel=loglevel)
[ "def", "delete_text", "(", "self", ",", "text", ",", "fname", ",", "pattern", "=", "None", ",", "expect", "=", "None", ",", "shutit_pexpect_child", "=", "None", ",", "note", "=", "None", ",", "before", "=", "False", ",", "force", "=", "False", ",", "line_oriented", "=", "True", ",", "loglevel", "=", "logging", ".", "DEBUG", ")", ":", "shutit_global", ".", "shutit_global_object", ".", "yield_to_draw", "(", ")", "return", "self", ".", "change_text", "(", "text", ",", "fname", ",", "pattern", ",", "expect", ",", "shutit_pexpect_child", ",", "before", ",", "force", ",", "note", "=", "note", ",", "delete", "=", "True", ",", "line_oriented", "=", "line_oriented", ",", "loglevel", "=", "loglevel", ")" ]
Delete a chunk of text from a file. See insert_text.
[ "Delete", "a", "chunk", "of", "text", "from", "a", "file", ".", "See", "insert_text", "." ]
19cd64cdfb23515b106b40213dccff4101617076
https://github.com/ianmiell/shutit/blob/19cd64cdfb23515b106b40213dccff4101617076/shutit_class.py#L1422-L1447
8,395
ianmiell/shutit
shutit_class.py
ShutIt.get_file
def get_file(self, target_path, host_path, note=None, loglevel=logging.DEBUG): """Copy a file from the target machine to the host machine @param target_path: path to file in the target @param host_path: path to file on the host machine (e.g. copy test) @param note: See send() @type target_path: string @type host_path: string @return: boolean @rtype: string """ shutit_global.shutit_global_object.yield_to_draw() self.handle_note(note) # Only handle for docker initially, return false in case we care if self.build['delivery'] != 'docker': return False # on the host, run: #Usage: docker cp [OPTIONS] CONTAINER:PATH LOCALPATH|- # Need: host env, container id, path from and path to shutit_pexpect_child = self.get_shutit_pexpect_session_from_id('host_child').pexpect_child expect = self.expect_prompts['ORIGIN_ENV'] self.send('docker cp ' + self.target['container_id'] + ':' + target_path + ' ' + host_path, shutit_pexpect_child=shutit_pexpect_child, expect=expect, check_exit=False, echo=False, loglevel=loglevel) self.handle_note_after(note=note) return True
python
def get_file(self, target_path, host_path, note=None, loglevel=logging.DEBUG): """Copy a file from the target machine to the host machine @param target_path: path to file in the target @param host_path: path to file on the host machine (e.g. copy test) @param note: See send() @type target_path: string @type host_path: string @return: boolean @rtype: string """ shutit_global.shutit_global_object.yield_to_draw() self.handle_note(note) # Only handle for docker initially, return false in case we care if self.build['delivery'] != 'docker': return False # on the host, run: #Usage: docker cp [OPTIONS] CONTAINER:PATH LOCALPATH|- # Need: host env, container id, path from and path to shutit_pexpect_child = self.get_shutit_pexpect_session_from_id('host_child').pexpect_child expect = self.expect_prompts['ORIGIN_ENV'] self.send('docker cp ' + self.target['container_id'] + ':' + target_path + ' ' + host_path, shutit_pexpect_child=shutit_pexpect_child, expect=expect, check_exit=False, echo=False, loglevel=loglevel) self.handle_note_after(note=note) return True
[ "def", "get_file", "(", "self", ",", "target_path", ",", "host_path", ",", "note", "=", "None", ",", "loglevel", "=", "logging", ".", "DEBUG", ")", ":", "shutit_global", ".", "shutit_global_object", ".", "yield_to_draw", "(", ")", "self", ".", "handle_note", "(", "note", ")", "# Only handle for docker initially, return false in case we care", "if", "self", ".", "build", "[", "'delivery'", "]", "!=", "'docker'", ":", "return", "False", "# on the host, run:", "#Usage: docker cp [OPTIONS] CONTAINER:PATH LOCALPATH|-", "# Need: host env, container id, path from and path to", "shutit_pexpect_child", "=", "self", ".", "get_shutit_pexpect_session_from_id", "(", "'host_child'", ")", ".", "pexpect_child", "expect", "=", "self", ".", "expect_prompts", "[", "'ORIGIN_ENV'", "]", "self", ".", "send", "(", "'docker cp '", "+", "self", ".", "target", "[", "'container_id'", "]", "+", "':'", "+", "target_path", "+", "' '", "+", "host_path", ",", "shutit_pexpect_child", "=", "shutit_pexpect_child", ",", "expect", "=", "expect", ",", "check_exit", "=", "False", ",", "echo", "=", "False", ",", "loglevel", "=", "loglevel", ")", "self", ".", "handle_note_after", "(", "note", "=", "note", ")", "return", "True" ]
Copy a file from the target machine to the host machine @param target_path: path to file in the target @param host_path: path to file on the host machine (e.g. copy test) @param note: See send() @type target_path: string @type host_path: string @return: boolean @rtype: string
[ "Copy", "a", "file", "from", "the", "target", "machine", "to", "the", "host", "machine" ]
19cd64cdfb23515b106b40213dccff4101617076
https://github.com/ianmiell/shutit/blob/19cd64cdfb23515b106b40213dccff4101617076/shutit_class.py#L1673-L1707
8,396
ianmiell/shutit
shutit_class.py
ShutIt.prompt_cfg
def prompt_cfg(self, msg, sec, name, ispass=False): """Prompt for a config value, optionally saving it to the user-level cfg. Only runs if we are in an interactive mode. @param msg: Message to display to user. @param sec: Section of config to add to. @param name: Config item name. @param ispass: If True, hide the input from the terminal. Default: False. @type msg: string @type sec: string @type name: string @type ispass: boolean @return: the value entered by the user @rtype: string """ shutit_global.shutit_global_object.yield_to_draw() cfgstr = '[%s]/%s' % (sec, name) config_parser = self.config_parser usercfg = os.path.join(self.host['shutit_path'], 'config') self.log('\nPROMPTING FOR CONFIG: %s' % (cfgstr,),transient=True,level=logging.INFO) self.log('\n' + msg + '\n',transient=True,level=logging.INFO) if not shutit_global.shutit_global_object.determine_interactive(): self.fail('ShutIt is not in a terminal so cannot prompt for values.', throw_exception=False) # pragma: no cover if config_parser.has_option(sec, name): whereset = config_parser.whereset(sec, name) if usercfg == whereset: self.fail(cfgstr + ' has already been set in the user config, edit ' + usercfg + ' directly to change it', throw_exception=False) # pragma: no cover for subcp, filename, _ in reversed(config_parser.layers): # Is the config file loaded after the user config file? if filename == whereset: self.fail(cfgstr + ' is being set in ' + filename + ', unable to override on a user config level', throw_exception=False) # pragma: no cover elif filename == usercfg: break else: # The item is not currently set so we're fine to do so pass if ispass: val = getpass.getpass('>> ') else: val = shutit_util.util_raw_input(prompt='>> ') is_excluded = ( config_parser.has_option('save_exclude', sec) and name in config_parser.get('save_exclude', sec).split() ) # TODO: ideally we would remember the prompted config item for this invocation of shutit if not is_excluded: usercp = [ subcp for subcp, filename, _ in config_parser.layers if filename == usercfg ][0] if shutit_util.util_raw_input(prompt=shutit_util.colorise('32', 'Do you want to save this to your user settings? y/n: '),default='y') == 'y': sec_toset, name_toset, val_toset = sec, name, val else: # Never save it if config_parser.has_option('save_exclude', sec): excluded = config_parser.get('save_exclude', sec).split() else: excluded = [] excluded.append(name) excluded = ' '.join(excluded) sec_toset, name_toset, val_toset = 'save_exclude', sec, excluded if not usercp.has_section(sec_toset): usercp.add_section(sec_toset) usercp.set(sec_toset, name_toset, val_toset) usercp.write(open(usercfg, 'w')) config_parser.reload() return val
python
def prompt_cfg(self, msg, sec, name, ispass=False): """Prompt for a config value, optionally saving it to the user-level cfg. Only runs if we are in an interactive mode. @param msg: Message to display to user. @param sec: Section of config to add to. @param name: Config item name. @param ispass: If True, hide the input from the terminal. Default: False. @type msg: string @type sec: string @type name: string @type ispass: boolean @return: the value entered by the user @rtype: string """ shutit_global.shutit_global_object.yield_to_draw() cfgstr = '[%s]/%s' % (sec, name) config_parser = self.config_parser usercfg = os.path.join(self.host['shutit_path'], 'config') self.log('\nPROMPTING FOR CONFIG: %s' % (cfgstr,),transient=True,level=logging.INFO) self.log('\n' + msg + '\n',transient=True,level=logging.INFO) if not shutit_global.shutit_global_object.determine_interactive(): self.fail('ShutIt is not in a terminal so cannot prompt for values.', throw_exception=False) # pragma: no cover if config_parser.has_option(sec, name): whereset = config_parser.whereset(sec, name) if usercfg == whereset: self.fail(cfgstr + ' has already been set in the user config, edit ' + usercfg + ' directly to change it', throw_exception=False) # pragma: no cover for subcp, filename, _ in reversed(config_parser.layers): # Is the config file loaded after the user config file? if filename == whereset: self.fail(cfgstr + ' is being set in ' + filename + ', unable to override on a user config level', throw_exception=False) # pragma: no cover elif filename == usercfg: break else: # The item is not currently set so we're fine to do so pass if ispass: val = getpass.getpass('>> ') else: val = shutit_util.util_raw_input(prompt='>> ') is_excluded = ( config_parser.has_option('save_exclude', sec) and name in config_parser.get('save_exclude', sec).split() ) # TODO: ideally we would remember the prompted config item for this invocation of shutit if not is_excluded: usercp = [ subcp for subcp, filename, _ in config_parser.layers if filename == usercfg ][0] if shutit_util.util_raw_input(prompt=shutit_util.colorise('32', 'Do you want to save this to your user settings? y/n: '),default='y') == 'y': sec_toset, name_toset, val_toset = sec, name, val else: # Never save it if config_parser.has_option('save_exclude', sec): excluded = config_parser.get('save_exclude', sec).split() else: excluded = [] excluded.append(name) excluded = ' '.join(excluded) sec_toset, name_toset, val_toset = 'save_exclude', sec, excluded if not usercp.has_section(sec_toset): usercp.add_section(sec_toset) usercp.set(sec_toset, name_toset, val_toset) usercp.write(open(usercfg, 'w')) config_parser.reload() return val
[ "def", "prompt_cfg", "(", "self", ",", "msg", ",", "sec", ",", "name", ",", "ispass", "=", "False", ")", ":", "shutit_global", ".", "shutit_global_object", ".", "yield_to_draw", "(", ")", "cfgstr", "=", "'[%s]/%s'", "%", "(", "sec", ",", "name", ")", "config_parser", "=", "self", ".", "config_parser", "usercfg", "=", "os", ".", "path", ".", "join", "(", "self", ".", "host", "[", "'shutit_path'", "]", ",", "'config'", ")", "self", ".", "log", "(", "'\\nPROMPTING FOR CONFIG: %s'", "%", "(", "cfgstr", ",", ")", ",", "transient", "=", "True", ",", "level", "=", "logging", ".", "INFO", ")", "self", ".", "log", "(", "'\\n'", "+", "msg", "+", "'\\n'", ",", "transient", "=", "True", ",", "level", "=", "logging", ".", "INFO", ")", "if", "not", "shutit_global", ".", "shutit_global_object", ".", "determine_interactive", "(", ")", ":", "self", ".", "fail", "(", "'ShutIt is not in a terminal so cannot prompt for values.'", ",", "throw_exception", "=", "False", ")", "# pragma: no cover", "if", "config_parser", ".", "has_option", "(", "sec", ",", "name", ")", ":", "whereset", "=", "config_parser", ".", "whereset", "(", "sec", ",", "name", ")", "if", "usercfg", "==", "whereset", ":", "self", ".", "fail", "(", "cfgstr", "+", "' has already been set in the user config, edit '", "+", "usercfg", "+", "' directly to change it'", ",", "throw_exception", "=", "False", ")", "# pragma: no cover", "for", "subcp", ",", "filename", ",", "_", "in", "reversed", "(", "config_parser", ".", "layers", ")", ":", "# Is the config file loaded after the user config file?", "if", "filename", "==", "whereset", ":", "self", ".", "fail", "(", "cfgstr", "+", "' is being set in '", "+", "filename", "+", "', unable to override on a user config level'", ",", "throw_exception", "=", "False", ")", "# pragma: no cover", "elif", "filename", "==", "usercfg", ":", "break", "else", ":", "# The item is not currently set so we're fine to do so", "pass", "if", "ispass", ":", "val", "=", "getpass", ".", "getpass", "(", "'>> '", ")", "else", ":", "val", "=", "shutit_util", ".", "util_raw_input", "(", "prompt", "=", "'>> '", ")", "is_excluded", "=", "(", "config_parser", ".", "has_option", "(", "'save_exclude'", ",", "sec", ")", "and", "name", "in", "config_parser", ".", "get", "(", "'save_exclude'", ",", "sec", ")", ".", "split", "(", ")", ")", "# TODO: ideally we would remember the prompted config item for this invocation of shutit", "if", "not", "is_excluded", ":", "usercp", "=", "[", "subcp", "for", "subcp", ",", "filename", ",", "_", "in", "config_parser", ".", "layers", "if", "filename", "==", "usercfg", "]", "[", "0", "]", "if", "shutit_util", ".", "util_raw_input", "(", "prompt", "=", "shutit_util", ".", "colorise", "(", "'32'", ",", "'Do you want to save this to your user settings? y/n: '", ")", ",", "default", "=", "'y'", ")", "==", "'y'", ":", "sec_toset", ",", "name_toset", ",", "val_toset", "=", "sec", ",", "name", ",", "val", "else", ":", "# Never save it", "if", "config_parser", ".", "has_option", "(", "'save_exclude'", ",", "sec", ")", ":", "excluded", "=", "config_parser", ".", "get", "(", "'save_exclude'", ",", "sec", ")", ".", "split", "(", ")", "else", ":", "excluded", "=", "[", "]", "excluded", ".", "append", "(", "name", ")", "excluded", "=", "' '", ".", "join", "(", "excluded", ")", "sec_toset", ",", "name_toset", ",", "val_toset", "=", "'save_exclude'", ",", "sec", ",", "excluded", "if", "not", "usercp", ".", "has_section", "(", "sec_toset", ")", ":", "usercp", ".", "add_section", "(", "sec_toset", ")", "usercp", ".", "set", "(", "sec_toset", ",", "name_toset", ",", "val_toset", ")", "usercp", ".", "write", "(", "open", "(", "usercfg", ",", "'w'", ")", ")", "config_parser", ".", "reload", "(", ")", "return", "val" ]
Prompt for a config value, optionally saving it to the user-level cfg. Only runs if we are in an interactive mode. @param msg: Message to display to user. @param sec: Section of config to add to. @param name: Config item name. @param ispass: If True, hide the input from the terminal. Default: False. @type msg: string @type sec: string @type name: string @type ispass: boolean @return: the value entered by the user @rtype: string
[ "Prompt", "for", "a", "config", "value", "optionally", "saving", "it", "to", "the", "user", "-", "level", "cfg", ".", "Only", "runs", "if", "we", "are", "in", "an", "interactive", "mode", "." ]
19cd64cdfb23515b106b40213dccff4101617076
https://github.com/ianmiell/shutit/blob/19cd64cdfb23515b106b40213dccff4101617076/shutit_class.py#L1710-L1782
8,397
ianmiell/shutit
shutit_class.py
ShutIt.step_through
def step_through(self, msg='', shutit_pexpect_child=None, level=1, print_input=True, value=True): """Implements a step-through function, using pause_point. """ shutit_global.shutit_global_object.yield_to_draw() shutit_pexpect_child = shutit_pexpect_child or self.get_current_shutit_pexpect_session().pexpect_child shutit_pexpect_session = self.get_shutit_pexpect_session_from_child(shutit_pexpect_child) if (not shutit_global.shutit_global_object.determine_interactive() or not shutit_global.shutit_global_object.interactive or shutit_global.shutit_global_object.interactive < level): return True self.build['step_through'] = value shutit_pexpect_session.pause_point(msg, print_input=print_input, level=level) return True
python
def step_through(self, msg='', shutit_pexpect_child=None, level=1, print_input=True, value=True): """Implements a step-through function, using pause_point. """ shutit_global.shutit_global_object.yield_to_draw() shutit_pexpect_child = shutit_pexpect_child or self.get_current_shutit_pexpect_session().pexpect_child shutit_pexpect_session = self.get_shutit_pexpect_session_from_child(shutit_pexpect_child) if (not shutit_global.shutit_global_object.determine_interactive() or not shutit_global.shutit_global_object.interactive or shutit_global.shutit_global_object.interactive < level): return True self.build['step_through'] = value shutit_pexpect_session.pause_point(msg, print_input=print_input, level=level) return True
[ "def", "step_through", "(", "self", ",", "msg", "=", "''", ",", "shutit_pexpect_child", "=", "None", ",", "level", "=", "1", ",", "print_input", "=", "True", ",", "value", "=", "True", ")", ":", "shutit_global", ".", "shutit_global_object", ".", "yield_to_draw", "(", ")", "shutit_pexpect_child", "=", "shutit_pexpect_child", "or", "self", ".", "get_current_shutit_pexpect_session", "(", ")", ".", "pexpect_child", "shutit_pexpect_session", "=", "self", ".", "get_shutit_pexpect_session_from_child", "(", "shutit_pexpect_child", ")", "if", "(", "not", "shutit_global", ".", "shutit_global_object", ".", "determine_interactive", "(", ")", "or", "not", "shutit_global", ".", "shutit_global_object", ".", "interactive", "or", "shutit_global", ".", "shutit_global_object", ".", "interactive", "<", "level", ")", ":", "return", "True", "self", ".", "build", "[", "'step_through'", "]", "=", "value", "shutit_pexpect_session", ".", "pause_point", "(", "msg", ",", "print_input", "=", "print_input", ",", "level", "=", "level", ")", "return", "True" ]
Implements a step-through function, using pause_point.
[ "Implements", "a", "step", "-", "through", "function", "using", "pause_point", "." ]
19cd64cdfb23515b106b40213dccff4101617076
https://github.com/ianmiell/shutit/blob/19cd64cdfb23515b106b40213dccff4101617076/shutit_class.py#L1785-L1796
8,398
ianmiell/shutit
shutit_class.py
ShutIt.interact
def interact(self, msg='SHUTIT PAUSE POINT', shutit_pexpect_child=None, print_input=True, level=1, resize=True, color='32', default_msg=None, wait=-1): """Same as pause_point, but sets up the terminal ready for unmediated interaction.""" shutit_global.shutit_global_object.yield_to_draw() self.pause_point(msg=msg, shutit_pexpect_child=shutit_pexpect_child, print_input=print_input, level=level, resize=resize, color=color, default_msg=default_msg, interact=True, wait=wait)
python
def interact(self, msg='SHUTIT PAUSE POINT', shutit_pexpect_child=None, print_input=True, level=1, resize=True, color='32', default_msg=None, wait=-1): """Same as pause_point, but sets up the terminal ready for unmediated interaction.""" shutit_global.shutit_global_object.yield_to_draw() self.pause_point(msg=msg, shutit_pexpect_child=shutit_pexpect_child, print_input=print_input, level=level, resize=resize, color=color, default_msg=default_msg, interact=True, wait=wait)
[ "def", "interact", "(", "self", ",", "msg", "=", "'SHUTIT PAUSE POINT'", ",", "shutit_pexpect_child", "=", "None", ",", "print_input", "=", "True", ",", "level", "=", "1", ",", "resize", "=", "True", ",", "color", "=", "'32'", ",", "default_msg", "=", "None", ",", "wait", "=", "-", "1", ")", ":", "shutit_global", ".", "shutit_global_object", ".", "yield_to_draw", "(", ")", "self", ".", "pause_point", "(", "msg", "=", "msg", ",", "shutit_pexpect_child", "=", "shutit_pexpect_child", ",", "print_input", "=", "print_input", ",", "level", "=", "level", ",", "resize", "=", "resize", ",", "color", "=", "color", ",", "default_msg", "=", "default_msg", ",", "interact", "=", "True", ",", "wait", "=", "wait", ")" ]
Same as pause_point, but sets up the terminal ready for unmediated interaction.
[ "Same", "as", "pause_point", "but", "sets", "up", "the", "terminal", "ready", "for", "unmediated", "interaction", "." ]
19cd64cdfb23515b106b40213dccff4101617076
https://github.com/ianmiell/shutit/blob/19cd64cdfb23515b106b40213dccff4101617076/shutit_class.py#L1799-L1819
8,399
ianmiell/shutit
shutit_class.py
ShutIt.pause_point
def pause_point(self, msg='SHUTIT PAUSE POINT', shutit_pexpect_child=None, print_input=True, level=1, resize=True, color='32', default_msg=None, interact=False, wait=-1): """Inserts a pause in the build session, which allows the user to try things out before continuing. Ignored if we are not in an interactive mode, or the interactive level is less than the passed-in one. Designed to help debug the build, or drop to on failure so the situation can be debugged. @param msg: Message to display to user on pause point. @param shutit_pexpect_child: See send() @param print_input: Whether to take input at this point (i.e. interact), or simply pause pending any input. Default: True @param level: Minimum level to invoke the pause_point at. Default: 1 @param resize: If True, try to resize terminal. Default: False @param color: Color to print message (typically 31 for red, 32 for green) @param default_msg: Whether to print the standard blurb @param wait: Wait a few seconds rather than for input @type msg: string @type print_input: boolean @type level: integer @type resize: boolean @type wait: decimal @return: True if pause point handled ok, else false """ shutit_global.shutit_global_object.yield_to_draw() if (not shutit_global.shutit_global_object.determine_interactive() or shutit_global.shutit_global_object.interactive < 1 or shutit_global.shutit_global_object.interactive < level): return True shutit_pexpect_child = shutit_pexpect_child or self.get_current_shutit_pexpect_session().pexpect_child # Don't log log traces while in interactive log_trace_when_idle_original_value = shutit_global.shutit_global_object.log_trace_when_idle shutit_global.shutit_global_object.log_trace_when_idle = False if shutit_pexpect_child: if shutit_global.shutit_global_object.pane_manager is not None: shutit_global.shutit_global_object.pane_manager.draw_screen(draw_type='clearscreen') shutit_global.shutit_global_object.pane_manager.do_render = False shutit_pexpect_session = self.get_shutit_pexpect_session_from_child(shutit_pexpect_child) # TODO: context added to pause point message shutit_pexpect_session.pause_point(msg=msg, print_input=print_input, resize=resize, color=color, default_msg=default_msg, wait=wait, interact=interact) else: self.log(msg,level=logging.DEBUG) self.log('Nothing to interact with, so quitting to presumably the original shell',level=logging.DEBUG) shutit_global.shutit_global_object.handle_exit(exit_code=1) if shutit_pexpect_child: if shutit_global.shutit_global_object.pane_manager is not None: shutit_global.shutit_global_object.pane_manager.do_render = True shutit_global.shutit_global_object.pane_manager.draw_screen(draw_type='clearscreen') self.build['ctrlc_stop'] = False # Revert value of log_trace_when_idle shutit_global.shutit_global_object.log_trace_when_idle = log_trace_when_idle_original_value return True
python
def pause_point(self, msg='SHUTIT PAUSE POINT', shutit_pexpect_child=None, print_input=True, level=1, resize=True, color='32', default_msg=None, interact=False, wait=-1): """Inserts a pause in the build session, which allows the user to try things out before continuing. Ignored if we are not in an interactive mode, or the interactive level is less than the passed-in one. Designed to help debug the build, or drop to on failure so the situation can be debugged. @param msg: Message to display to user on pause point. @param shutit_pexpect_child: See send() @param print_input: Whether to take input at this point (i.e. interact), or simply pause pending any input. Default: True @param level: Minimum level to invoke the pause_point at. Default: 1 @param resize: If True, try to resize terminal. Default: False @param color: Color to print message (typically 31 for red, 32 for green) @param default_msg: Whether to print the standard blurb @param wait: Wait a few seconds rather than for input @type msg: string @type print_input: boolean @type level: integer @type resize: boolean @type wait: decimal @return: True if pause point handled ok, else false """ shutit_global.shutit_global_object.yield_to_draw() if (not shutit_global.shutit_global_object.determine_interactive() or shutit_global.shutit_global_object.interactive < 1 or shutit_global.shutit_global_object.interactive < level): return True shutit_pexpect_child = shutit_pexpect_child or self.get_current_shutit_pexpect_session().pexpect_child # Don't log log traces while in interactive log_trace_when_idle_original_value = shutit_global.shutit_global_object.log_trace_when_idle shutit_global.shutit_global_object.log_trace_when_idle = False if shutit_pexpect_child: if shutit_global.shutit_global_object.pane_manager is not None: shutit_global.shutit_global_object.pane_manager.draw_screen(draw_type='clearscreen') shutit_global.shutit_global_object.pane_manager.do_render = False shutit_pexpect_session = self.get_shutit_pexpect_session_from_child(shutit_pexpect_child) # TODO: context added to pause point message shutit_pexpect_session.pause_point(msg=msg, print_input=print_input, resize=resize, color=color, default_msg=default_msg, wait=wait, interact=interact) else: self.log(msg,level=logging.DEBUG) self.log('Nothing to interact with, so quitting to presumably the original shell',level=logging.DEBUG) shutit_global.shutit_global_object.handle_exit(exit_code=1) if shutit_pexpect_child: if shutit_global.shutit_global_object.pane_manager is not None: shutit_global.shutit_global_object.pane_manager.do_render = True shutit_global.shutit_global_object.pane_manager.draw_screen(draw_type='clearscreen') self.build['ctrlc_stop'] = False # Revert value of log_trace_when_idle shutit_global.shutit_global_object.log_trace_when_idle = log_trace_when_idle_original_value return True
[ "def", "pause_point", "(", "self", ",", "msg", "=", "'SHUTIT PAUSE POINT'", ",", "shutit_pexpect_child", "=", "None", ",", "print_input", "=", "True", ",", "level", "=", "1", ",", "resize", "=", "True", ",", "color", "=", "'32'", ",", "default_msg", "=", "None", ",", "interact", "=", "False", ",", "wait", "=", "-", "1", ")", ":", "shutit_global", ".", "shutit_global_object", ".", "yield_to_draw", "(", ")", "if", "(", "not", "shutit_global", ".", "shutit_global_object", ".", "determine_interactive", "(", ")", "or", "shutit_global", ".", "shutit_global_object", ".", "interactive", "<", "1", "or", "shutit_global", ".", "shutit_global_object", ".", "interactive", "<", "level", ")", ":", "return", "True", "shutit_pexpect_child", "=", "shutit_pexpect_child", "or", "self", ".", "get_current_shutit_pexpect_session", "(", ")", ".", "pexpect_child", "# Don't log log traces while in interactive", "log_trace_when_idle_original_value", "=", "shutit_global", ".", "shutit_global_object", ".", "log_trace_when_idle", "shutit_global", ".", "shutit_global_object", ".", "log_trace_when_idle", "=", "False", "if", "shutit_pexpect_child", ":", "if", "shutit_global", ".", "shutit_global_object", ".", "pane_manager", "is", "not", "None", ":", "shutit_global", ".", "shutit_global_object", ".", "pane_manager", ".", "draw_screen", "(", "draw_type", "=", "'clearscreen'", ")", "shutit_global", ".", "shutit_global_object", ".", "pane_manager", ".", "do_render", "=", "False", "shutit_pexpect_session", "=", "self", ".", "get_shutit_pexpect_session_from_child", "(", "shutit_pexpect_child", ")", "# TODO: context added to pause point message", "shutit_pexpect_session", ".", "pause_point", "(", "msg", "=", "msg", ",", "print_input", "=", "print_input", ",", "resize", "=", "resize", ",", "color", "=", "color", ",", "default_msg", "=", "default_msg", ",", "wait", "=", "wait", ",", "interact", "=", "interact", ")", "else", ":", "self", ".", "log", "(", "msg", ",", "level", "=", "logging", ".", "DEBUG", ")", "self", ".", "log", "(", "'Nothing to interact with, so quitting to presumably the original shell'", ",", "level", "=", "logging", ".", "DEBUG", ")", "shutit_global", ".", "shutit_global_object", ".", "handle_exit", "(", "exit_code", "=", "1", ")", "if", "shutit_pexpect_child", ":", "if", "shutit_global", ".", "shutit_global_object", ".", "pane_manager", "is", "not", "None", ":", "shutit_global", ".", "shutit_global_object", ".", "pane_manager", ".", "do_render", "=", "True", "shutit_global", ".", "shutit_global_object", ".", "pane_manager", ".", "draw_screen", "(", "draw_type", "=", "'clearscreen'", ")", "self", ".", "build", "[", "'ctrlc_stop'", "]", "=", "False", "# Revert value of log_trace_when_idle", "shutit_global", ".", "shutit_global_object", ".", "log_trace_when_idle", "=", "log_trace_when_idle_original_value", "return", "True" ]
Inserts a pause in the build session, which allows the user to try things out before continuing. Ignored if we are not in an interactive mode, or the interactive level is less than the passed-in one. Designed to help debug the build, or drop to on failure so the situation can be debugged. @param msg: Message to display to user on pause point. @param shutit_pexpect_child: See send() @param print_input: Whether to take input at this point (i.e. interact), or simply pause pending any input. Default: True @param level: Minimum level to invoke the pause_point at. Default: 1 @param resize: If True, try to resize terminal. Default: False @param color: Color to print message (typically 31 for red, 32 for green) @param default_msg: Whether to print the standard blurb @param wait: Wait a few seconds rather than for input @type msg: string @type print_input: boolean @type level: integer @type resize: boolean @type wait: decimal @return: True if pause point handled ok, else false
[ "Inserts", "a", "pause", "in", "the", "build", "session", "which", "allows", "the", "user", "to", "try", "things", "out", "before", "continuing", ".", "Ignored", "if", "we", "are", "not", "in", "an", "interactive", "mode", "or", "the", "interactive", "level", "is", "less", "than", "the", "passed", "-", "in", "one", ".", "Designed", "to", "help", "debug", "the", "build", "or", "drop", "to", "on", "failure", "so", "the", "situation", "can", "be", "debugged", "." ]
19cd64cdfb23515b106b40213dccff4101617076
https://github.com/ianmiell/shutit/blob/19cd64cdfb23515b106b40213dccff4101617076/shutit_class.py#L1822-L1891