code
string
signature
string
docstring
string
loss_without_docstring
float64
loss_with_docstring
float64
factor
float64
convtype = convtype.lower() # Retrieve the appropriate transformation matrix from the constants. rgb_matrix = rgb_type.conversion_matrices[convtype] logger.debug(" \* Applying RGB conversion matrix: %s->%s", rgb_type.__class__.__name__, convtype) # Stuff the RGB/XYZ values into a NumPy matrix for conversion. var_matrix = numpy.array(( var1, var2, var3 )) # Perform the adaptation via matrix multiplication. result_matrix = numpy.dot(rgb_matrix, var_matrix) rgb_r, rgb_g, rgb_b = result_matrix # Clamp these values to a valid range. rgb_r = max(rgb_r, 0.0) rgb_g = max(rgb_g, 0.0) rgb_b = max(rgb_b, 0.0) return rgb_r, rgb_g, rgb_b
def apply_RGB_matrix(var1, var2, var3, rgb_type, convtype="xyz_to_rgb")
Applies an RGB working matrix to convert from XYZ to RGB. The arguments are tersely named var1, var2, and var3 to allow for the passing of XYZ _or_ RGB values. var1 is X for XYZ, and R for RGB. var2 and var3 follow suite.
3.465915
3.502999
0.989414
def decorator(f): f.start_type = start_type f.target_type = target_type _conversion_manager.add_type_conversion(start_type, target_type, f) return f return decorator
def color_conversion_function(start_type, target_type)
Decorator to indicate a function that performs a conversion from one color space to another. This decorator will return the original function unmodified, however it will be registered in the _conversion_manager so it can be used to perform color space transformations between color spaces that do not have direct conversion functions (e.g., Luv to CMYK). Note: For a conversion to/from RGB supply the BaseRGBColor class. :param start_type: Starting color space type :param target_type: Target color space type
2.876948
2.635455
1.091632
# If the user provides an illuminant_override numpy array, use it. if illuminant_override: reference_illum = illuminant_override else: # Otherwise, look up the illuminant from known standards based # on the value of 'illuminant' pulled from the SpectralColor object. try: reference_illum = spectral_constants.REF_ILLUM_TABLE[cobj.illuminant] except KeyError: raise InvalidIlluminantError(cobj.illuminant) # Get the spectral distribution of the selected standard observer. if cobj.observer == '10': std_obs_x = spectral_constants.STDOBSERV_X10 std_obs_y = spectral_constants.STDOBSERV_Y10 std_obs_z = spectral_constants.STDOBSERV_Z10 else: # Assume 2 degree, since it is theoretically the only other possibility. std_obs_x = spectral_constants.STDOBSERV_X2 std_obs_y = spectral_constants.STDOBSERV_Y2 std_obs_z = spectral_constants.STDOBSERV_Z2 # This is a NumPy array containing the spectral distribution of the color. sample = cobj.get_numpy_array() # The denominator is constant throughout the entire calculation for X, # Y, and Z coordinates. Calculate it once and re-use. denom = std_obs_y * reference_illum # This is also a common element in the calculation whereby the sample # NumPy array is multiplied by the reference illuminant's power distribution # (which is also a NumPy array). sample_by_ref_illum = sample * reference_illum # Calculate the numerator of the equation to find X. x_numerator = sample_by_ref_illum * std_obs_x y_numerator = sample_by_ref_illum * std_obs_y z_numerator = sample_by_ref_illum * std_obs_z xyz_x = x_numerator.sum() / denom.sum() xyz_y = y_numerator.sum() / denom.sum() xyz_z = z_numerator.sum() / denom.sum() return XYZColor( xyz_x, xyz_y, xyz_z, observer=cobj.observer, illuminant=cobj.illuminant)
def Spectral_to_XYZ(cobj, illuminant_override=None, *args, **kwargs)
Converts spectral readings to XYZ.
3.07688
3.101881
0.99194
lch_l = cobj.lab_l lch_c = math.sqrt( math.pow(float(cobj.lab_a), 2) + math.pow(float(cobj.lab_b), 2)) lch_h = math.atan2(float(cobj.lab_b), float(cobj.lab_a)) if lch_h > 0: lch_h = (lch_h / math.pi) * 180 else: lch_h = 360 - (math.fabs(lch_h) / math.pi) * 180 return LCHabColor( lch_l, lch_c, lch_h, observer=cobj.observer, illuminant=cobj.illuminant)
def Lab_to_LCHab(cobj, *args, **kwargs)
Convert from CIE Lab to LCH(ab).
1.844006
1.772666
1.040244
illum = cobj.get_illuminant_xyz() xyz_y = (cobj.lab_l + 16.0) / 116.0 xyz_x = cobj.lab_a / 500.0 + xyz_y xyz_z = xyz_y - cobj.lab_b / 200.0 if math.pow(xyz_y, 3) > color_constants.CIE_E: xyz_y = math.pow(xyz_y, 3) else: xyz_y = (xyz_y - 16.0 / 116.0) / 7.787 if math.pow(xyz_x, 3) > color_constants.CIE_E: xyz_x = math.pow(xyz_x, 3) else: xyz_x = (xyz_x - 16.0 / 116.0) / 7.787 if math.pow(xyz_z, 3) > color_constants.CIE_E: xyz_z = math.pow(xyz_z, 3) else: xyz_z = (xyz_z - 16.0 / 116.0) / 7.787 xyz_x = (illum["X"] * xyz_x) xyz_y = (illum["Y"] * xyz_y) xyz_z = (illum["Z"] * xyz_z) return XYZColor( xyz_x, xyz_y, xyz_z, observer=cobj.observer, illuminant=cobj.illuminant)
def Lab_to_XYZ(cobj, *args, **kwargs)
Convert from Lab to XYZ
1.600641
1.579539
1.01336
lch_l = cobj.luv_l lch_c = math.sqrt(math.pow(cobj.luv_u, 2.0) + math.pow(cobj.luv_v, 2.0)) lch_h = math.atan2(float(cobj.luv_v), float(cobj.luv_u)) if lch_h > 0: lch_h = (lch_h / math.pi) * 180 else: lch_h = 360 - (math.fabs(lch_h) / math.pi) * 180 return LCHuvColor( lch_l, lch_c, lch_h, observer=cobj.observer, illuminant=cobj.illuminant)
def Luv_to_LCHuv(cobj, *args, **kwargs)
Convert from CIE Luv to LCH(uv).
1.866609
1.822403
1.024257
illum = cobj.get_illuminant_xyz() # Without Light, there is no color. Short-circuit this and avoid some # zero division errors in the var_a_frac calculation. if cobj.luv_l <= 0.0: xyz_x = 0.0 xyz_y = 0.0 xyz_z = 0.0 return XYZColor( xyz_x, xyz_y, xyz_z, observer=cobj.observer, illuminant=cobj.illuminant) # Various variables used throughout the conversion. cie_k_times_e = color_constants.CIE_K * color_constants.CIE_E u_sub_0 = (4.0 * illum["X"]) / (illum["X"] + 15.0 * illum["Y"] + 3.0 * illum["Z"]) v_sub_0 = (9.0 * illum["Y"]) / (illum["X"] + 15.0 * illum["Y"] + 3.0 * illum["Z"]) var_u = cobj.luv_u / (13.0 * cobj.luv_l) + u_sub_0 var_v = cobj.luv_v / (13.0 * cobj.luv_l) + v_sub_0 # Y-coordinate calculations. if cobj.luv_l > cie_k_times_e: xyz_y = math.pow((cobj.luv_l + 16.0) / 116.0, 3.0) else: xyz_y = cobj.luv_l / color_constants.CIE_K # X-coordinate calculation. xyz_x = xyz_y * 9.0 * var_u / (4.0 * var_v) # Z-coordinate calculation. xyz_z = xyz_y * (12.0 - 3.0 * var_u - 20.0 * var_v) / (4.0 * var_v) return XYZColor( xyz_x, xyz_y, xyz_z, illuminant=cobj.illuminant, observer=cobj.observer)
def Luv_to_XYZ(cobj, *args, **kwargs)
Convert from Luv to XYZ.
2.536748
2.514584
1.008814
lab_l = cobj.lch_l lab_a = math.cos(math.radians(cobj.lch_h)) * cobj.lch_c lab_b = math.sin(math.radians(cobj.lch_h)) * cobj.lch_c return LabColor( lab_l, lab_a, lab_b, illuminant=cobj.illuminant, observer=cobj.observer)
def LCHab_to_Lab(cobj, *args, **kwargs)
Convert from LCH(ab) to Lab.
2.128231
2.006357
1.060744
luv_l = cobj.lch_l luv_u = math.cos(math.radians(cobj.lch_h)) * cobj.lch_c luv_v = math.sin(math.radians(cobj.lch_h)) * cobj.lch_c return LuvColor( luv_l, luv_u, luv_v, illuminant=cobj.illuminant, observer=cobj.observer)
def LCHuv_to_Luv(cobj, *args, **kwargs)
Convert from LCH(uv) to Luv.
2.12271
2.059794
1.030545
# avoid division by zero if cobj.xyy_y == 0.0: xyz_x = 0.0 xyz_y = 0.0 xyz_z = 0.0 else: xyz_x = (cobj.xyy_x * cobj.xyy_Y) / cobj.xyy_y xyz_y = cobj.xyy_Y xyz_z = ((1.0 - cobj.xyy_x - cobj.xyy_y) * xyz_y) / cobj.xyy_y return XYZColor( xyz_x, xyz_y, xyz_z, illuminant=cobj.illuminant, observer=cobj.observer)
def xyY_to_XYZ(cobj, *args, **kwargs)
Convert from xyY to XYZ.
2.13675
2.048082
1.043293
xyz_sum = cobj.xyz_x + cobj.xyz_y + cobj.xyz_z # avoid division by zero if xyz_sum == 0.0: xyy_x = 0.0 xyy_y = 0.0 else: xyy_x = cobj.xyz_x / xyz_sum xyy_y = cobj.xyz_y / xyz_sum xyy_Y = cobj.xyz_y return xyYColor( xyy_x, xyy_y, xyy_Y, observer=cobj.observer, illuminant=cobj.illuminant)
def XYZ_to_xyY(cobj, *args, **kwargs)
Convert from XYZ to xyY.
2.520478
2.399095
1.050595
temp_x = cobj.xyz_x temp_y = cobj.xyz_y temp_z = cobj.xyz_z denom = temp_x + (15.0 * temp_y) + (3.0 * temp_z) # avoid division by zero if denom == 0.0: luv_u = 0.0 luv_v = 0.0 else: luv_u = (4.0 * temp_x) / denom luv_v = (9.0 * temp_y) / denom illum = cobj.get_illuminant_xyz() temp_y = temp_y / illum["Y"] if temp_y > color_constants.CIE_E: temp_y = math.pow(temp_y, (1.0 / 3.0)) else: temp_y = (7.787 * temp_y) + (16.0 / 116.0) ref_U = (4.0 * illum["X"]) / (illum["X"] + (15.0 * illum["Y"]) + (3.0 * illum["Z"])) ref_V = (9.0 * illum["Y"]) / (illum["X"] + (15.0 * illum["Y"]) + (3.0 * illum["Z"])) luv_l = (116.0 * temp_y) - 16.0 luv_u = 13.0 * luv_l * (luv_u - ref_U) luv_v = 13.0 * luv_l * (luv_v - ref_V) return LuvColor( luv_l, luv_u, luv_v, observer=cobj.observer, illuminant=cobj.illuminant)
def XYZ_to_Luv(cobj, *args, **kwargs)
Convert from XYZ to Luv
1.825283
1.790285
1.019549
illum = cobj.get_illuminant_xyz() temp_x = cobj.xyz_x / illum["X"] temp_y = cobj.xyz_y / illum["Y"] temp_z = cobj.xyz_z / illum["Z"] if temp_x > color_constants.CIE_E: temp_x = math.pow(temp_x, (1.0 / 3.0)) else: temp_x = (7.787 * temp_x) + (16.0 / 116.0) if temp_y > color_constants.CIE_E: temp_y = math.pow(temp_y, (1.0 / 3.0)) else: temp_y = (7.787 * temp_y) + (16.0 / 116.0) if temp_z > color_constants.CIE_E: temp_z = math.pow(temp_z, (1.0 / 3.0)) else: temp_z = (7.787 * temp_z) + (16.0 / 116.0) lab_l = (116.0 * temp_y) - 16.0 lab_a = 500.0 * (temp_x - temp_y) lab_b = 200.0 * (temp_y - temp_z) return LabColor( lab_l, lab_a, lab_b, observer=cobj.observer, illuminant=cobj.illuminant)
def XYZ_to_Lab(cobj, *args, **kwargs)
Converts XYZ to Lab.
1.514771
1.487149
1.018574
temp_X = cobj.xyz_x temp_Y = cobj.xyz_y temp_Z = cobj.xyz_z logger.debug(" \- Target RGB space: %s", target_rgb) target_illum = target_rgb.native_illuminant logger.debug(" \- Target native illuminant: %s", target_illum) logger.debug(" \- XYZ color's illuminant: %s", cobj.illuminant) # If the XYZ values were taken with a different reference white than the # native reference white of the target RGB space, a transformation matrix # must be applied. if cobj.illuminant != target_illum: logger.debug(" \* Applying transformation from %s to %s ", cobj.illuminant, target_illum) # Get the adjusted XYZ values, adapted for the target illuminant. temp_X, temp_Y, temp_Z = apply_chromatic_adaptation( temp_X, temp_Y, temp_Z, orig_illum=cobj.illuminant, targ_illum=target_illum) logger.debug(" \* New values: %.3f, %.3f, %.3f", temp_X, temp_Y, temp_Z) # Apply an RGB working space matrix to the XYZ values (matrix mul). rgb_r, rgb_g, rgb_b = apply_RGB_matrix( temp_X, temp_Y, temp_Z, rgb_type=target_rgb, convtype="xyz_to_rgb") # v linear_channels = dict(r=rgb_r, g=rgb_g, b=rgb_b) # V nonlinear_channels = {} if target_rgb == sRGBColor: for channel in ['r', 'g', 'b']: v = linear_channels[channel] if v <= 0.0031308: nonlinear_channels[channel] = v * 12.92 else: nonlinear_channels[channel] = 1.055 * math.pow(v, 1 / 2.4) - 0.055 elif target_rgb == BT2020Color: if kwargs.get('is_12_bits_system'): a, b = 1.0993, 0.0181 else: a, b = 1.099, 0.018 for channel in ['r', 'g', 'b']: v = linear_channels[channel] if v < b: nonlinear_channels[channel] = v * 4.5 else: nonlinear_channels[channel] = a * math.pow(v, 0.45) - (a - 1) else: # If it's not sRGB... for channel in ['r', 'g', 'b']: v = linear_channels[channel] nonlinear_channels[channel] = math.pow(v, 1 / target_rgb.rgb_gamma) return target_rgb( nonlinear_channels['r'], nonlinear_channels['g'], nonlinear_channels['b'])
def XYZ_to_RGB(cobj, target_rgb, *args, **kwargs)
XYZ to RGB conversion.
2.72084
2.708026
1.004732
# Will contain linearized RGB channels (removed the gamma func). linear_channels = {} if isinstance(cobj, sRGBColor): for channel in ['r', 'g', 'b']: V = getattr(cobj, 'rgb_' + channel) if V <= 0.04045: linear_channels[channel] = V / 12.92 else: linear_channels[channel] = math.pow((V + 0.055) / 1.055, 2.4) elif isinstance(cobj, BT2020Color): if kwargs.get('is_12_bits_system'): a, b, c = 1.0993, 0.0181, 0.081697877417347 else: a, b, c = 1.099, 0.018, 0.08124794403514049 for channel in ['r', 'g', 'b']: V = getattr(cobj, 'rgb_' + channel) if V <= c: linear_channels[channel] = V / 4.5 else: linear_channels[channel] = math.pow((V + (a - 1)) / a, 1 / 0.45) else: # If it's not sRGB... gamma = cobj.rgb_gamma for channel in ['r', 'g', 'b']: V = getattr(cobj, 'rgb_' + channel) linear_channels[channel] = math.pow(V, gamma) # Apply an RGB working space matrix to the XYZ values (matrix mul). xyz_x, xyz_y, xyz_z = apply_RGB_matrix( linear_channels['r'], linear_channels['g'], linear_channels['b'], rgb_type=cobj, convtype="rgb_to_xyz") if target_illuminant is None: target_illuminant = cobj.native_illuminant # The illuminant of the original RGB object. This will always match # the RGB colorspace's native illuminant. illuminant = cobj.native_illuminant xyzcolor = XYZColor(xyz_x, xyz_y, xyz_z, illuminant=illuminant) # This will take care of any illuminant changes for us (if source # illuminant != target illuminant). xyzcolor.apply_adaptation(target_illuminant) return xyzcolor
def RGB_to_XYZ(cobj, target_illuminant=None, *args, **kwargs)
RGB to XYZ conversion. Expects 0-255 RGB values. Based off of: http://www.brucelindbloom.com/index.html?Eqn_RGB_to_XYZ.html
3.444238
3.471826
0.992054
if var_max == var_min: return 0.0 elif var_max == var_R: return (60.0 * ((var_G - var_B) / (var_max - var_min)) + 360) % 360.0 elif var_max == var_G: return 60.0 * ((var_B - var_R) / (var_max - var_min)) + 120 elif var_max == var_B: return 60.0 * ((var_R - var_G) / (var_max - var_min)) + 240.0
def __RGB_to_Hue(var_R, var_G, var_B, var_min, var_max)
For RGB_to_HSL and RGB_to_HSV, the Hue (H) component is calculated in the same way.
1.442036
1.432919
1.006362
var_R = cobj.rgb_r var_G = cobj.rgb_g var_B = cobj.rgb_b var_max = max(var_R, var_G, var_B) var_min = min(var_R, var_G, var_B) var_H = __RGB_to_Hue(var_R, var_G, var_B, var_min, var_max) if var_max == 0: var_S = 0 else: var_S = 1.0 - (var_min / var_max) var_V = var_max return HSVColor( var_H, var_S, var_V)
def RGB_to_HSV(cobj, *args, **kwargs)
Converts from RGB to HSV. H values are in degrees and are 0 to 360. S values are a percentage, 0.0 to 1.0. V values are a percentage, 0.0 to 1.0.
1.835212
1.809898
1.013986
var_R = cobj.rgb_r var_G = cobj.rgb_g var_B = cobj.rgb_b var_max = max(var_R, var_G, var_B) var_min = min(var_R, var_G, var_B) var_H = __RGB_to_Hue(var_R, var_G, var_B, var_min, var_max) var_L = 0.5 * (var_max + var_min) if var_max == var_min: var_S = 0 elif var_L <= 0.5: var_S = (var_max - var_min) / (2.0 * var_L) else: var_S = (var_max - var_min) / (2.0 - (2.0 * var_L)) return HSLColor( var_H, var_S, var_L)
def RGB_to_HSL(cobj, *args, **kwargs)
Converts from RGB to HSL. H values are in degrees and are 0 to 360. S values are a percentage, 0.0 to 1.0. L values are a percentage, 0.0 to 1.0.
1.685922
1.680215
1.003397
if C < 0: C += 1.0 if C > 1: C -= 1.0 # Computing C of vector (Color R, Color G, Color B) if C < (1.0 / 6.0): return var_p + ((var_q - var_p) * 6.0 * C) elif (1.0 / 6.0) <= C < 0.5: return var_q elif 0.5 <= C < (2.0 / 3.0): return var_p + ((var_q - var_p) * 6.0 * ((2.0 / 3.0) - C)) else: return var_p
def __Calc_HSL_to_RGB_Components(var_q, var_p, C)
This is used in HSL_to_RGB conversions on R, G, and B.
1.981281
1.939689
1.021442
H = cobj.hsv_h S = cobj.hsv_s V = cobj.hsv_v h_floored = int(math.floor(H)) h_sub_i = int(h_floored / 60) % 6 var_f = (H / 60.0) - (h_floored // 60) var_p = V * (1.0 - S) var_q = V * (1.0 - var_f * S) var_t = V * (1.0 - (1.0 - var_f) * S) if h_sub_i == 0: rgb_r = V rgb_g = var_t rgb_b = var_p elif h_sub_i == 1: rgb_r = var_q rgb_g = V rgb_b = var_p elif h_sub_i == 2: rgb_r = var_p rgb_g = V rgb_b = var_t elif h_sub_i == 3: rgb_r = var_p rgb_g = var_q rgb_b = V elif h_sub_i == 4: rgb_r = var_t rgb_g = var_p rgb_b = V elif h_sub_i == 5: rgb_r = V rgb_g = var_p rgb_b = var_q else: raise ValueError("Unable to convert HSL->RGB due to value error.") # TODO: Investigate intent of following code block. # In the event that they define an HSV color and want to convert it to # a particular RGB space, let them override it here. # if target_rgb is not None: # rgb_type = target_rgb # else: # rgb_type = cobj.rgb_type return target_rgb(rgb_r, rgb_g, rgb_b)
def HSV_to_RGB(cobj, target_rgb, *args, **kwargs)
HSV to RGB conversion. H values are in degrees and are 0 to 360. S values are a percentage, 0.0 to 1.0. V values are a percentage, 0.0 to 1.0.
1.980422
2.025763
0.977618
H = cobj.hsl_h S = cobj.hsl_s L = cobj.hsl_l if L < 0.5: var_q = L * (1.0 + S) else: var_q = L + S - (L * S) var_p = 2.0 * L - var_q # H normalized to range [0,1] h_sub_k = (H / 360.0) t_sub_R = h_sub_k + (1.0 / 3.0) t_sub_G = h_sub_k t_sub_B = h_sub_k - (1.0 / 3.0) rgb_r = __Calc_HSL_to_RGB_Components(var_q, var_p, t_sub_R) rgb_g = __Calc_HSL_to_RGB_Components(var_q, var_p, t_sub_G) rgb_b = __Calc_HSL_to_RGB_Components(var_q, var_p, t_sub_B) # TODO: Investigate intent of following code block. # In the event that they define an HSV color and want to convert it to # a particular RGB space, let them override it here. # if target_rgb is not None: # rgb_type = target_rgb # else: # rgb_type = cobj.rgb_type return target_rgb(rgb_r, rgb_g, rgb_b)
def HSL_to_RGB(cobj, target_rgb, *args, **kwargs)
HSL to RGB conversion.
2.500054
2.476748
1.00941
cmy_c = 1.0 - cobj.rgb_r cmy_m = 1.0 - cobj.rgb_g cmy_y = 1.0 - cobj.rgb_b return CMYColor(cmy_c, cmy_m, cmy_y)
def RGB_to_CMY(cobj, *args, **kwargs)
RGB to CMY conversion. NOTE: CMYK and CMY values range from 0.0 to 1.0
2.122521
2.175787
0.975519
rgb_r = 1.0 - cobj.cmy_c rgb_g = 1.0 - cobj.cmy_m rgb_b = 1.0 - cobj.cmy_y return target_rgb(rgb_r, rgb_g, rgb_b)
def CMY_to_RGB(cobj, target_rgb, *args, **kwargs)
Converts CMY to RGB via simple subtraction. NOTE: Returned values are in the range of 0-255.
2.240873
2.387104
0.938741
var_k = 1.0 if cobj.cmy_c < var_k: var_k = cobj.cmy_c if cobj.cmy_m < var_k: var_k = cobj.cmy_m if cobj.cmy_y < var_k: var_k = cobj.cmy_y if var_k == 1: cmyk_c = 0.0 cmyk_m = 0.0 cmyk_y = 0.0 else: cmyk_c = (cobj.cmy_c - var_k) / (1.0 - var_k) cmyk_m = (cobj.cmy_m - var_k) / (1.0 - var_k) cmyk_y = (cobj.cmy_y - var_k) / (1.0 - var_k) cmyk_k = var_k return CMYKColor(cmyk_c, cmyk_m, cmyk_y, cmyk_k)
def CMY_to_CMYK(cobj, *args, **kwargs)
Converts from CMY to CMYK. NOTE: CMYK and CMY values range from 0.0 to 1.0
1.496423
1.449818
1.032145
cmy_c = cobj.cmyk_c * (1.0 - cobj.cmyk_k) + cobj.cmyk_k cmy_m = cobj.cmyk_m * (1.0 - cobj.cmyk_k) + cobj.cmyk_k cmy_y = cobj.cmyk_y * (1.0 - cobj.cmyk_k) + cobj.cmyk_k return CMYColor(cmy_c, cmy_m, cmy_y)
def CMYK_to_CMY(cobj, *args, **kwargs)
Converts CMYK to CMY. NOTE: CMYK and CMY values range from 0.0 to 1.0
1.546685
1.545515
1.000757
if cobj.illuminant != 'd65' or cobj.observer != '2': raise ValueError('XYZColor for XYZ->IPT conversion needs to be D65 adapted.') xyz_values = numpy.array(cobj.get_value_tuple()) lms_values = numpy.dot( IPTColor.conversion_matrices['xyz_to_lms'], xyz_values) lms_prime = numpy.sign(lms_values) * numpy.abs(lms_values) ** 0.43 ipt_values = numpy.dot( IPTColor.conversion_matrices['lms_to_ipt'], lms_prime) return IPTColor(*ipt_values)
def XYZ_to_IPT(cobj, *args, **kwargs)
Converts XYZ to IPT. NOTE: XYZ values need to be adapted to 2 degree D65 Reference: Fairchild, M. D. (2013). Color appearance models, 3rd Ed. (pp. 271-272). John Wiley & Sons.
4.140429
3.936113
1.051908
ipt_values = numpy.array(cobj.get_value_tuple()) lms_values = numpy.dot( numpy.linalg.inv(IPTColor.conversion_matrices['lms_to_ipt']), ipt_values) lms_prime = numpy.sign(lms_values) * numpy.abs(lms_values) ** (1 / 0.43) xyz_values = numpy.dot( numpy.linalg.inv(IPTColor.conversion_matrices['xyz_to_lms']), lms_prime) return XYZColor(*xyz_values, observer='2', illuminant='d65')
def IPT_to_XYZ(cobj, *args, **kwargs)
Converts IPT to XYZ.
3.772263
3.670654
1.027681
if isinstance(target_cs, str): raise ValueError("target_cs parameter must be a Color object.") if not issubclass(target_cs, ColorBase): raise ValueError("target_cs parameter must be a Color object.") conversions = _conversion_manager.get_conversion_path(color.__class__, target_cs) logger.debug('Converting %s to %s', color, target_cs) logger.debug(' @ Conversion path: %s', conversions) # Start with original color in case we convert to the same color space. new_color = color if issubclass(target_cs, BaseRGBColor): # If the target_cs is an RGB color space of some sort, then we # have to set our through_rgb_type to make sure the conversion returns # the expected RGB colorspace (instead of defaulting to sRGBColor). through_rgb_type = target_cs # We have to be careful to use the same RGB color space that created # an object (if it was created by a conversion) in order to get correct # results. For example, XYZ->HSL via Adobe RGB should default to Adobe # RGB when taking that generated HSL object back to XYZ. # noinspection PyProtectedMember if through_rgb_type != sRGBColor: # User overrides take priority over everything. # noinspection PyProtectedMember target_rgb = through_rgb_type elif color._through_rgb_type: # Otherwise, a value on the color object is the next best thing, # when available. # noinspection PyProtectedMember target_rgb = color._through_rgb_type else: # We could collapse this into a single if statement above, # but I think this reads better. target_rgb = through_rgb_type # Iterate through the list of functions for the conversion path, storing # the results in a dictionary via update(). This way the user has access # to all of the variables involved in the conversion. for func in conversions: # Execute the function in this conversion step and store the resulting # Color object. logger.debug(' * Conversion: %s passed to %s()', new_color.__class__.__name__, func) logger.debug(' |-> in %s', new_color) if func: # This can be None if you try to convert a color to the color # space that is already in. IE: XYZ->XYZ. new_color = func( new_color, target_rgb=target_rgb, target_illuminant=target_illuminant, *args, **kwargs) logger.debug(' |-< out %s', new_color) # If this conversion had something other than the default sRGB color space # requested, if through_rgb_type != sRGBColor: new_color._through_rgb_type = through_rgb_type return new_color
def convert_color(color, target_cs, through_rgb_type=sRGBColor, target_illuminant=None, *args, **kwargs)
Converts the color to the designated color space. :param color: A Color instance to convert. :param target_cs: The Color class to convert to. Note that this is not an instance, but a class. :keyword BaseRGBColor through_rgb_type: If during your conversion between your original and target color spaces you have to pass through RGB, this determines which kind of RGB to use. For example, XYZ->HSL. You probably don't need to specify this unless you have a special usage case. :type target_illuminant: None or str :keyword target_illuminant: If during conversion from RGB to a reflective color space you want to explicitly end up with a certain illuminant, pass this here. Otherwise the RGB space's native illuminant will be used. :returns: An instance of the type passed in as ``target_cs``. :raises: :py:exc:`colormath.color_exceptions.UndefinedConversionError` if conversion between the two color spaces isn't possible.
5.281705
5.132921
1.028986
self.registered_color_spaces.add(start_type) self.registered_color_spaces.add(target_type) logger.debug( 'Registered conversion from %s to %s', start_type, target_type)
def add_type_conversion(self, start_type, target_type, conversion_function)
Register a conversion function between two color spaces. :param start_type: Starting color space. :param target_type: Target color space. :param conversion_function: Conversion function.
3.43312
2.949264
1.16406
rgb = self.xyz_to_rgb(xyz) logger.debug('RGB: {}'.format(rgb)) rgb_w = self.xyz_to_rgb(xyz_w) logger.debug('RGB_W: {}'.format(rgb_w)) y_w = xyz_w[1] y_b = xyz_b[1] h_rgb = 3 * rgb_w / (rgb_w.sum()) logger.debug('H_RGB: {}'.format(h_rgb)) # Chromatic adaptation factors if not discount_illuminant: f_rgb = (1 + (l_a ** (1 / 3)) + h_rgb) / (1 + (l_a ** (1 / 3)) + (1 / h_rgb)) else: f_rgb = numpy.ones(numpy.shape(h_rgb)) logger.debug('F_RGB: {}'.format(f_rgb)) # Adaptation factor if helson_judd: d_rgb = self._f_n((y_b / y_w) * f_l * f_rgb[1]) - self._f_n((y_b / y_w) * f_l * f_rgb) assert d_rgb[1] == 0 else: d_rgb = numpy.zeros(numpy.shape(f_rgb)) logger.debug('D_RGB: {}'.format(d_rgb)) # Cone bleaching factors rgb_b = (10 ** 7) / ((10 ** 7) + 5 * l_a * (rgb_w / 100)) logger.debug('B_RGB: {}'.format(rgb_b)) if xyz_p is not None and p is not None: logger.debug('Account for simultaneous chromatic contrast') rgb_p = self.xyz_to_rgb(xyz_p) rgb_w = self.adjust_white_for_scc(rgb_p, rgb_b, rgb_w, p) # Adapt rgb using modified rgb_a = 1 + rgb_b * (self._f_n(f_l * f_rgb * rgb / rgb_w) + d_rgb) logger.debug('RGB_A: {}'.format(rgb_a)) return rgb_a
def _adaptation(self, f_l, l_a, xyz, xyz_w, xyz_b, xyz_p=None, p=None, helson_judd=False, discount_illuminant=True)
:param f_l: Luminance adaptation factor :param l_a: Adapting luminance :param xyz: Stimulus color in XYZ :param xyz_w: Reference white color in XYZ :param xyz_b: Background color in XYZ :param xyz_p: Proxima field color in XYZ :param p: Simultaneous contrast/assimilation parameter.
2.953449
2.886516
1.023188
p_rgb = rgb_p / rgb_b rgb_w = rgb_w * (((1 - p) * p_rgb + (1 + p) / p_rgb) ** 0.5) / (((1 + p) * p_rgb + (1 - p) / p_rgb) ** 0.5) return rgb_w
def adjust_white_for_scc(cls, rgb_p, rgb_b, rgb_w, p)
Adjust the white point for simultaneous chromatic contrast. :param rgb_p: Cone signals of proxima field. :param rgb_b: Cone signals of background. :param rgb_w: Cone signals of reference white. :param p: Simultaneous contrast/assimilation parameter. :return: Adjusted cone signals for reference white.
3.004231
3.058972
0.982105
x_e = 0.3320 y_e = 0.1858 n = ((x / (x + z + z)) - x_e) / ((y / (x + z + z)) - y_e) a_0 = -949.86315 a_1 = 6253.80338 a_2 = 28.70599 a_3 = 0.00004 t_1 = 0.92159 t_2 = 0.20039 t_3 = 0.07125 cct = a_0 + a_1 * numpy.exp(-n / t_1) + a_2 * numpy.exp(-n / t_2) + a_3 * numpy.exp(-n / t_3) return cct
def _get_cct(x, y, z)
Reference Hernandez-Andres, J., Lee, R. L., & Romero, J. (1999). Calculating correlated color temperatures across the entire gamut of daylight and skylight chromaticities. Applied Optics, 38(27), 5703-5709.
3.796291
3.73003
1.017764
# Transform input colors to cone responses rgb = self._xyz_to_rgb(xyz) logger.debug("RGB: {}".format(rgb)) rgb_b = self._xyz_to_rgb(self._xyz_b) rgb_w = self._xyz_to_rgb(xyz_w) rgb_w = Hunt.adjust_white_for_scc(rgb, rgb_b, rgb_w, self._p) logger.debug("RGB_W: {}".format(rgb_w)) # Compute adapted tristimulus-responses rgb_c = self._white_adaption(rgb, rgb_w, d) logger.debug("RGB_C: {}".format(rgb_c)) rgb_cw = self._white_adaption(rgb_w, rgb_w, d) logger.debug("RGB_CW: {}".format(rgb_cw)) # Convert adapted tristimulus-responses to Hunt-Pointer-Estevez fundamentals rgb_p = self._compute_hunt_pointer_estevez_fundamentals(rgb_c) logger.debug("RGB': {}".format(rgb_p)) rgb_wp = self._compute_hunt_pointer_estevez_fundamentals(rgb_cw) logger.debug("RGB'_W: {}".format(rgb_wp)) # Compute post-adaptation non-linearities rgb_ap = self._compute_nonlinearities(f_l, rgb_p) rgb_awp = self._compute_nonlinearities(f_l, rgb_wp) return rgb_ap, rgb_awp
def _compute_adaptation(self, xyz, xyz_w, f_l, d)
Modified adaptation procedure incorporating simultaneous chromatic contrast from Hunt model. :param xyz: Stimulus XYZ. :param xyz_w: Reference white XYZ. :param f_l: Luminance adaptation factor :param d: Degree of adaptation. :return: Tuple of adapted rgb and rgb_w arrays.
3.020088
2.857865
1.056764
if self.ok(): return {} errors = self.content if(not isinstance(errors, dict)): errors = {"error": errors} # convert to dict for consistency elif('errors' in errors): errors = errors['errors'] return errors
def errors(self)
:return error dict if no success:
6.657571
5.167547
1.288343
data = { "user": { "email": email, "cellphone": phone, "country_code": country_code }, 'send_install_link_via_sms': send_install_link_via_sms } resp = self.post("/protected/json/users/new", data) return User(self, resp)
def create(self, email, phone, country_code=1, send_install_link_via_sms=False)
sends request to create new user. :param string email: :param string phone: :param string country_code: :param bool send_install_link_via_sms: :return:
2.93059
3.166289
0.92556
if via != 'sms' and via != 'call': raise AuthyFormatException("Invalid Via. Expected 'sms' or 'call'.") options = { 'phone_number': phone_number, 'country_code': country_code, 'via': via } if locale: options['locale'] = locale try: cl = int(code_length) if cl < 4 or cl > 10: raise ValueError options['code_length'] = cl except ValueError: raise AuthyFormatException( "Invalid code_length. Expected numeric value from 4-10.") resp = self.post("/protected/json/phones/verification/start", options) return Phone(self, resp)
def verification_start(self, phone_number, country_code, via='sms', locale=None, code_length=4)
:param string phone_number: stored in your databse or you provided while creating new user. :param string country_code: stored in your databse or you provided while creating new user. :param string via: verification method either sms or call :param string locale: optional default none :param number code_length: optional default 4 :return:
2.545279
2.767469
0.919714
options = { 'phone_number': phone_number, 'country_code': country_code, 'verification_code': verification_code } resp = self.get("/protected/json/phones/verification/check", options) return Phone(self, resp)
def verification_check(self, phone_number, country_code, verification_code)
:param phone_number: :param country_code: :param verification_code: :return:
3.373508
3.511585
0.96068
self._validate_request(user_id, message) data = { "message": message[:MAX_STRING_SIZE], "seconds_to_expire": seconds_to_expire, "details": self.__clean_inputs(details), 'hidden_details': self.__clean_inputs(hidden_details), 'logos': self.clean_logos(logos) } request_url = "/onetouch/json/users/{0}/approval_requests".format( user_id) response = self.post(request_url, data) return OneTouchResponse(self, response)
def send_request(self, user_id, message, seconds_to_expire=None, details={}, hidden_details={}, logos=[])
OneTouch verification request. Sends a request for Auth App. For more info https://www.twilio.com/docs/api/authy/authy-onetouch-api :param string user_id: user_id User's authy id stored in your database :param string message: Required, the message shown to the user when the approval request arrives. :param number seconds_to_expire: Optional, defaults to 120 (two minutes). :param dict details: For example details['Requested by'] = 'MacBook Pro, Chrome'; it will be displayed on Authy app :param dict hidden_details: Same usage as detail except this detail is not shown in Authy app :param list logos: Contains the logos that will be shown to user. The logos parameter is expected to be an array of objects, each object with two fields: res (values are default,low,med,high) and url :return OneTouchResponse: the server response Json Object
3.912548
3.111479
1.257456
if not len(logos): return logos # Allow nil hash if not isinstance(logos, list): raise AuthyFormatException( 'Invalid logos list. Only res and url required') temp_array = {} clean_logos = [] for logo in logos: if not isinstance(logo, dict): raise AuthyFormatException('Invalid logo type') for l in logo: # We ignore any additional parameter on the logos, and truncate # string size to the maximum allowed. if l == 'res': temp_array['res'] = logo[l][:MAX_STRING_SIZE] elif l == 'url': temp_array['url'] = logo[l][:MAX_STRING_SIZE] else: raise AuthyFormatException( 'Invalid logos list. Only res and url required') clean_logos.append(temp_array) temp_array = {} return clean_logos
def clean_logos(self, logos)
Validate logos input. :param list logos: :return list logos:
4.048343
3.987535
1.015249
request_url = "/onetouch/json/approval_requests/{0}".format(uuid) response = self.get(request_url) return OneTouchResponse(self, response)
def get_approval_status(self, uuid)
OneTouch verification request. Sends a request for Auth App. For more info https://www.twilio.com/docs/api/authy/authy-onetouch-api :param string uuid Required. The approval request ID. (Obtained from the response to an ApprovalRequest): :return OneTouchResponse the server response Json Object:
5.990862
3.834054
1.56254
if not signature or not isinstance(signature, str): raise AuthyFormatException( "Invalid signature - should not be empty. It is required") if not nonce: raise AuthyFormatException( "Invalid nonce - should not be empty. It is required") if not method or not ('get' == method.lower() or 'post' == method.lower()): raise AuthyFormatException( "Invalid method - should not be empty. It is required") if not params or not isinstance(params, dict): raise AuthyFormatException( "Invalid params - should not be empty. It is required") query_params = self.__make_http_query(params) # Sort and replace encoded params in case-sensitive order sorted_params = '&'.join(sorted(query_params.replace( '/', '%2F').replace('%20', '+').split('&'))) sorted_params = re.sub("\\%5B([0-9])*\\%5D", "%5B%5D", sorted_params) sorted_params = re.sub("\\=None", "=", sorted_params) data = nonce + "|" + method + "|" + url + "|" + sorted_params try: calculated_signature = base64.b64encode( hmac.new(self.api_key.encode(), data.encode(), hashlib.sha256).digest()) return calculated_signature.decode() == signature except: calculated_signature = base64.b64encode( hmac.new(self.api_key, data, hashlib.sha256).digest()) return calculated_signature == signature
def validate_one_touch_signature(self, signature, nonce, method, url, params)
Function to validate signature in X-Authy-Signature key of headers. :param string signature: X-Authy-Signature key of headers. :param string nonce: X-Authy-Signature-Nonce key of headers. :param string method: GET or POST - configured in app settings for OneTouch. :param string url: base callback url. :param dict params: params sent by Authy. :return bool: True if calculated signature and X-Authy-Signature are identical else False.
2.701158
2.701816
0.999757
if len(params) == 0: return "" result = "" # is a dictionary? if type(params) is dict: for key in params.keys(): newkey = quote(key) if topkey != '': newkey = topkey + quote('[' + key + ']') if type(params[key]) is dict: result += self.__make_http_query(params[key], newkey) elif type(params[key]) is list: i = 0 for val in params[key]: if type(val) is dict: result += self.__make_http_query( val, newkey + quote('['+str(i)+']')) else: result += newkey + \ quote('['+str(i)+']') + "=" + \ quote(str(val)) + "&" i = i + 1 # boolean should have special treatment as well elif type(params[key]) is bool: result += newkey + "=" + \ quote(str(params[key]).lower()) + "&" # assume string (integers and floats work well) else: result += newkey + "=" + quote(str(params[key])) + "&" # remove the last '&' if (result) and (topkey == '') and (result[-1] == '&'): result = result[:-1] return result
def __make_http_query(self, params, topkey='')
Function to covert params into url encoded query string :param dict params: Json string sent by Authy. :param string topkey: params key :return string: url encoded Query.
2.241817
2.259954
0.991974
return _pyjq.Script(script.encode('utf-8'), vars=vars, library_paths=library_paths)
def compile(script, vars={}, library_paths=[])
Compile a jq script, retuning a script object. library_paths is a list of strings that defines the module search path.
7.470723
5.354401
1.395249
return all(script, value, vars, url, opener, library_paths)
def apply(script, value=None, vars={}, url=None, opener=default_opener, library_paths=[])
Transform value by script, returning all results as list.
5.65082
4.71187
1.199273
return compile(script, vars, library_paths).first(_get_value(value, url, opener), default)
def first(script, value=None, default=None, vars={}, url=None, opener=default_opener, library_paths=[])
Transform object by jq script, returning the first result. Return default if result is empty.
7.959636
9.199601
0.865215
return compile(script, vars, library_paths).one(_get_value(value, url, opener))
def one(script, value=None, vars={}, url=None, opener=default_opener, library_paths=[])
Transform object by jq script, returning the first result. Raise ValueError unless results does not include exactly one element.
9.037998
8.813081
1.025521
typeshed_root = None count = 0 started = time.time() for parent in itertools.chain( # Look in current script's parents, useful for zipapps. Path(__file__).parents, # Look around site-packages, useful for virtualenvs. Path(mypy.api.__file__).parents, # Look in global paths, useful for globally installed. Path(os.__file__).parents, ): count += 1 candidate = parent / 'lib' / 'mypy' / 'typeshed' if candidate.is_dir(): typeshed_root = candidate break # Also check the non-installed path, useful for `setup.py develop`. candidate = parent / 'typeshed' if candidate.is_dir(): typeshed_root = candidate break LOG.debug( 'Checked %d paths in %.2fs looking for typeshed. Found %s', count, time.time() - started, typeshed_root, ) if not typeshed_root: return [] stdlib_dirs = ('3.7', '3.6', '3.5', '3.4', '3.3', '3.2', '3', '2and3') stdlib_stubs = [ typeshed_root / 'stdlib' / stdlib_dir for stdlib_dir in stdlib_dirs ] third_party_dirs = ('3.7', '3.6', '3', '2and3') third_party_stubs = [ typeshed_root / 'third_party' / tp_dir for tp_dir in third_party_dirs ] return [ str(p) for p in stdlib_stubs + third_party_stubs ]
def calculate_mypypath() -> List[str]
Return MYPYPATH so that stubs have precedence over local sources.
3.127836
3.046356
1.026747
pubnub = Pubnub( publish_key=settings.PUBNUB_PUB_KEY, subscribe_key=settings.PUBNUB_SUB_KEY, secret_key=settings.PUBNUB_SEC_KEY, ssl_on=kwargs.pop('ssl_on', False), **kwargs) return pubnub.publish(channel=channel, message={"text": message})
def send(channel, message, **kwargs)
Site: http://www.pubnub.com/ API: https://www.mashape.com/pubnub/pubnub-network Desc: real-time browser notifications Installation and usage: pip install -U pubnub Tests for browser notification http://127.0.0.1:8000/browser_notification/
2.594577
2.596315
0.99933
headers = { "Content-type": "application/x-www-form-urlencoded", "User-Agent": "DBMail/%s" % get_version(), } data = { "user_credentials": token, "notification[title]": from_unicode(title), "notification[sound]": "notifier-2" } for k, v in kwargs.items(): data['notification[%s]' % k] = from_unicode(v) http = HTTPSConnection(kwargs.pop("api_url", "new.boxcar.io")) http.request( "POST", "/api/notifications", headers=headers, body=urlencode(data)) response = http.getresponse() if response.status != 201: raise BoxcarError(response.reason) return True
def send(token, title, **kwargs)
Site: https://boxcar.io/ API: http://help.boxcar.io/knowledgebase/topics/48115-boxcar-api Desc: Best app for system administrators
3.53307
3.341724
1.05726
headers = { "Content-type": "application/x-www-form-urlencoded", "User-Agent": "DBMail/%s" % get_version(), } username = from_unicode(kwargs.pop("username", settings.SLACK_USERNAME)) hook_url = from_unicode(kwargs.pop("hook_url", settings.SLACK_HOOCK_URL)) channel = from_unicode(channel or settings.SLACK_CHANNEL) emoji = from_unicode(kwargs.pop("emoji", "")) message = from_unicode(message) data = { "channel": channel, "username": username, "text": message, "icon_emoji": emoji, } _data = kwargs.pop('data', None) if _data is not None: data.update(_data) up = urlparse(hook_url) http = HTTPSConnection(up.netloc) http.request( "POST", up.path, headers=headers, body=urlencode({"payload": dumps(data)})) response = http.getresponse() if response.status != 200: raise SlackError(response.reason) body = response.read() if body != "ok": raise SlackError(repr(body)) return True
def send(channel, message, **kwargs)
Site: https://slack.com API: https://api.slack.com Desc: real-time messaging
2.505296
2.489625
1.006295
headers = { "User-Agent": "DBMail/%s" % get_version(), } kwargs.update({ 'user': settings.SMSAERO_LOGIN, 'password': settings.SMSAERO_MD5_PASSWORD, 'from': kwargs.pop('sms_from', settings.SMSAERO_FROM), 'to': sms_to.replace('+', ''), 'text': from_unicode(sms_body), 'answer': 'json', }) http = HTTPConnection(kwargs.pop("api_url", "gate.smsaero.ru")) http.request("GET", "/send/?" + urlencode(kwargs), headers=headers) response = http.getresponse() if response.status != 200: raise AeroSmsError(response.reason) read = response.read().decode(response.headers.get_content_charset()) data = json.loads(read) status = None if 'result' in data: status = data['result'] sms_id = None if 'id' in data: sms_id = data['id'] if sms_id and status == 'accepted': return True return False
def send(sms_to, sms_body, **kwargs)
Site: http://smsaero.ru/ API: http://smsaero.ru/api/
3.345101
3.024513
1.105997
if email_list is None: return {} result = {} for value in email_list: realname, address = email.utils.parseaddr(value) result[address] = realname if realname and address else address return result
def email_list_to_email_dict(email_list)
Convert a list of email to a dict of email.
3.906044
3.598722
1.085397
realname, address = email.utils.parseaddr(email_address) return ( [address, realname] if realname and address else [email_address, email_address] )
def email_address_to_list(email_address)
Convert an email address to a list.
4.550618
4.463261
1.019572
m = Mailin( "https://api.sendinblue.com/v2.0", sender_instance._kwargs.get("api_key") ) data = { "to": email_list_to_email_dict(sender_instance._recipient_list), "cc": email_list_to_email_dict(sender_instance._cc), "bcc": email_list_to_email_dict(sender_instance._bcc), "from": email_address_to_list(sender_instance._from_email), "subject": sender_instance._subject, } if sender_instance._template.is_html: data.update({ "html": sender_instance._message, "headers": {"Content-Type": "text/html; charset=utf-8"} }) else: data.update({"text": sender_instance._message}) if "attachments" in sender_instance._kwargs: data["attachment"] = {} for attachment in sender_instance._kwargs["attachments"]: data["attachment"][attachment[0]] = base64.b64encode(attachment[1]) result = m.send_email(data) if result["code"] != "success": raise SendInBlueError(result["message"])
def send(sender_instance)
Send a transactional email using SendInBlue API. Site: https://www.sendinblue.com API: https://apidocs.sendinblue.com/
2.398588
2.459944
0.975058
headers = { "User-Agent": "DBMail/%s" % get_version(), 'Authorization': 'Basic %s' % b64encode( "%s:%s" % ( settings.IQSMS_API_LOGIN, settings.IQSMS_API_PASSWORD )).decode("ascii") } kwargs.update({ 'phone': sms_to, 'text': from_unicode(sms_body), 'sender': kwargs.pop('sms_from', settings.IQSMS_FROM) }) http = HTTPConnection(kwargs.pop("api_url", "gate.iqsms.ru")) http.request("GET", "/send/?" + urlencode(kwargs), headers=headers) response = http.getresponse() if response.status != 200: raise IQSMSError(response.reason) body = response.read().strip() if '=accepted' not in body: raise IQSMSError(body) return int(body.split('=')[0])
def send(sms_to, sms_body, **kwargs)
Site: http://iqsms.ru/ API: http://iqsms.ru/api/
3.350757
3.092829
1.083396
headers = { "X-Parse-Application-Id": settings.PARSE_APP_ID, "X-Parse-REST-API-Key": settings.PARSE_API_KEY, "User-Agent": "DBMail/%s" % get_version(), "Content-type": "application/json", } data = { "where": { "user_id": device_id, }, "data": { "alert": description, "title": kwargs.pop("event") } } _data = kwargs.pop('data', None) if _data is not None: data.update(_data) http = HTTPSConnection(kwargs.pop("api_url", "api.parse.com")) http.request( "POST", "/1/push", headers=headers, body=dumps(data)) response = http.getresponse() if response.status != 200: raise ParseComError(response.reason) body = loads(response.read()) if body['error']: raise ParseComError(body['error']) return True
def send(device_id, description, **kwargs)
Site: http://parse.com API: https://www.parse.com/docs/push_guide#scheduled/REST Desc: Best app for system administrators
2.719523
2.590833
1.049671
headers = { "User-Agent": "DBMail/%s" % get_version(), "Content-type": "application/x-www-form-urlencoded" } application = from_unicode(kwargs.pop("app", settings.PROWL_APP), 256) event = from_unicode(kwargs.pop("event", 'Alert'), 1024) description = from_unicode(description, 10000) data = { "apikey": api_key, "application": application, "event": event, "description": description, "priority": kwargs.pop("priority", 1) } provider_key = kwargs.pop("providerkey", None) url = kwargs.pop('url', None) if provider_key is not None: data["providerkey"] = provider_key if url is not None: data["url"] = url[0:512] http = HTTPSConnection(kwargs.pop("api_url", "api.prowlapp.com")) http.request( "POST", "/publicapi/add", headers=headers, body=urlencode(data)) response = http.getresponse() if response.status != 200: raise ProwlError(response.reason) return True
def send(api_key, description, **kwargs)
Site: http://prowlapp.com API: http://prowlapp.com/api.php Desc: Best app for system administrators
2.945827
2.854258
1.032082
is_enhanced = kwargs.pop('is_enhanced', False) identifier = kwargs.pop('identifier', 0) expiry = kwargs.pop('expiry', 0) alert = { "title": kwargs.pop("event"), "body": message, "action": kwargs.pop( 'apns_action', defaults.APNS_PROVIDER_DEFAULT_ACTION) } data = { "aps": { 'alert': alert, 'content-available': kwargs.pop('content_available', 0) and 1 } } data['aps'].update(kwargs) payload = dumps(data, separators=(',', ':')) token = a2b_hex(token_hex) if is_enhanced is True: fmt = '!BIIH32sH%ds' % len(payload) expiry = expiry and time() + expiry notification = pack( fmt, 1, identifier, expiry, 32, token, len(payload), payload) else: token_length_bin = pack('>H', len(token)) payload_length_bin = pack('>H', len(payload)) zero_byte = bytes('\0', 'utf-8') if PY3 is True else '\0' payload = bytes(payload, 'utf-8') if PY3 is True else payload notification = ( zero_byte + token_length_bin + token + payload_length_bin + payload) sock = socket(AF_INET, SOCK_STREAM) sock.settimeout(3) sock.connect((settings.APNS_GW_HOST, settings.APNS_GW_PORT)) ssl = wrap_socket( sock, settings.APNS_KEY_FILE, settings.APNS_CERT_FILE, do_handshake_on_connect=False) result = ssl.write(notification) sock.close() ssl.close() if not result: raise APNsError return True
def send(token_hex, message, **kwargs)
Site: https://apple.com API: https://developer.apple.com Desc: iOS notifications
3.279423
3.140258
1.044317
params = { 'type': kwargs.pop('req_type', 'self'), 'key': settings.PUSHALL_API_KEYS[ch]['key'], 'id': settings.PUSHALL_API_KEYS[ch]['id'], 'title': kwargs.pop( "title", settings.PUSHALL_API_KEYS[ch].get('title') or ""), 'text': message, 'priority': kwargs.pop( "priority", settings.PUSHALL_API_KEYS[ch].get('priority') or "0"), } if kwargs: params.update(**kwargs) response = urlopen( Request('https://pushall.ru/api.php'), urlencode(params), timeout=10 ) if response.code != 200: raise PushAllError(response.read()) json = loads(response.read()) if json.get('error'): raise PushAllError(json.get('error')) return True
def send(ch, message, **kwargs)
Site: https://pushall.ru API: https://pushall.ru/blog/api Desc: App for notification to devices/browsers and messaging apps
3.007177
2.879387
1.044381
available_kwargs_keys = [ 'parse_mode', 'disable_web_page_preview', 'disable_notification', 'reply_to_message_id', 'reply_markup' ] available_kwargs = { k: v for k, v in kwargs.iteritems() if k in available_kwargs_keys } bot = telepot.Bot(settings.TELEGRAM_BOT_TOKEN) return bot.sendMessage(to, message, **available_kwargs)
def send(to, message, **kwargs)
SITE: https://github.com/nickoala/telepot TELEGRAM API: https://core.telegram.org/bots/api Installation: pip install 'telepot>=10.4'
2.321199
2.165656
1.071823
subscription_info = kwargs.pop('subscription_info') payload = { "title": kwargs.pop("event"), "body": message, "url": kwargs.pop("push_url", None) } payload.update(kwargs) wp = WebPusher(subscription_info) response = wp.send( dumps(payload), gcm_key=settings.GCM_KEY, ttl=kwargs.pop("ttl", 60)) if not response.ok or ( response.text and loads(response.text).get("failure") > 0): raise GCMError(response.text) return True
def send(reg_id, message, **kwargs)
Site: https://developers.google.com API: https://developers.google.com/web/updates/2016/03/web-push-encryption Desc: Web Push notifications for Chrome and FireFox Installation: pip install 'pywebpush>=0.4.0'
4.745979
4.390978
1.080848
priority = kwargs.pop('priority', 10) topic = kwargs.pop('topic', None) alert = { "title": kwargs.pop("event"), "body": message, "action": kwargs.pop( 'apns_action', defaults.APNS_PROVIDER_DEFAULT_ACTION) } data = { "aps": { 'alert': alert, 'content-available': kwargs.pop('content_available', 0) and 1 } } data['aps'].update(kwargs) payload = dumps(data, separators=(',', ':')) headers = { 'apns-priority': priority } if topic is not None: headers['apns-topic'] = topic ssl_context = init_context() ssl_context.load_cert_chain(settings.APNS_CERT_FILE) connection = HTTP20Connection( settings.APNS_GW_HOST, settings.APNS_GW_PORT, ssl_context=ssl_context) stream_id = connection.request( 'POST', '/3/device/{}'.format(token_hex), payload, headers) response = connection.get_response(stream_id) if response.status != 200: raise APNsError(response.read()) return True
def send(token_hex, message, **kwargs)
Site: https://apple.com API: https://developer.apple.com Desc: iOS notifications Installation and usage: pip install hyper
3.043861
2.990183
1.017951
headers = { "Content-type": "application/x-www-form-urlencoded", "User-Agent": "DBMail/%s" % get_version(), 'Authorization': 'Basic %s' % b64encode( "%s:%s" % ( settings.TWILIO_ACCOUNT_SID, settings.TWILIO_AUTH_TOKEN )).decode("ascii") } kwargs.update({ 'From': kwargs.pop('sms_from', settings.TWILIO_FROM), 'To': sms_to, 'Body': from_unicode(sms_body) }) http = HTTPSConnection(kwargs.pop("api_url", "api.twilio.com")) http.request( "POST", "/2010-04-01/Accounts/%s/Messages.json" % settings.TWILIO_ACCOUNT_SID, headers=headers, body=urlencode(kwargs)) response = http.getresponse() if response.status != 201: raise TwilioSmsError(response.reason) return loads(response.read()).get('sid')
def send(sms_to, sms_body, **kwargs)
Site: https://www.twilio.com/ API: https://www.twilio.com/docs/api/rest/sending-messages
2.300442
2.246383
1.024065
headers = { "Content-type": "application/x-www-form-urlencoded", "User-Agent": "DBMail/%s" % get_version(), } title = from_unicode(kwargs.pop("title", settings.PUSHOVER_APP)) message = from_unicode(message) data = { "token": settings.PUSHOVER_TOKEN, "user": user, "message": message, "title": title, "priority": kwargs.pop("priority", 0) } _data = kwargs.pop('data', None) if _data is not None: data.update(_data) http = HTTPSConnection(kwargs.pop("api_url", "api.pushover.net")) http.request( "POST", "/1/messages.json", headers=headers, body=urlencode(data)) response = http.getresponse() if response.status != 200: raise PushOverError(response.reason) body = loads(response.read()) if body.get('status') != 1: raise PushOverError(repr(body)) return True
def send(user, message, **kwargs)
Site: https://pushover.net/ API: https://pushover.net/api Desc: real-time notifications
2.531093
2.431394
1.041005
headers = { "Content-type": "application/json", "Authorization": "key=" + kwargs.pop("gcm_key", settings.GCM_KEY) } hook_url = 'https://android.googleapis.com/gcm/send' data = { "registration_ids": [user], "data": { "title": kwargs.pop("event"), 'message': message, } } data['data'].update(kwargs) up = urlparse(hook_url) http = HTTPSConnection(up.netloc) http.request( "POST", up.path, headers=headers, body=dumps(data)) response = http.getresponse() if response.status != 200: raise GCMError(response.reason) body = response.read() if loads(body).get("failure") > 0: raise GCMError(repr(body)) return True
def send(user, message, **kwargs)
Site: https://developers.google.com API: https://developers.google.com/cloud-messaging/ Desc: Android notifications
2.888012
2.753041
1.049026
if type(value) is bytes: return value; elif type(value) is bool: return b'yes' if value else b'no' elif proptype in (str, int, float): return str(proptype(value)).encode('utf-8') else: raise TypeError('Cannot coax value of type {} into property type {}'.format(type(value), proptype))
def _mpv_coax_proptype(value, proptype=str)
Intelligently coax the given python value into something that can be understood as a proptype property.
2.995792
2.797375
1.07093
char_ps = [ c_char_p(_mpv_coax_proptype(e, str)) for e in l ] node_list = MpvNodeList( num=len(l), keys=None, values=( MpvNode * len(l))( *[ MpvNode( format=MpvFormat.STRING, val=MpvNodeUnion(string=p)) for p in char_ps ])) node = MpvNode( format=MpvFormat.NODE_ARRAY, val=MpvNodeUnion(list=pointer(node_list))) return char_ps, node_list, node, cast(pointer(node), c_void_p)
def _make_node_str_list(l)
Take a list of python objects and make a MPV string node array from it. As an example, the python list ``l = [ "foo", 23, false ]`` will result in the following MPV node object:: struct mpv_node { .format = MPV_NODE_ARRAY, .u.list = *(struct mpv_node_array){ .num = len(l), .keys = NULL, .values = struct mpv_node[len(l)] { { .format = MPV_NODE_STRING, .u.string = l[0] }, { .format = MPV_NODE_STRING, .u.string = l[1] }, ... } } }
7.323416
5.861599
1.249389
sema = threading.Semaphore(value=0) def observer(name, val): if cond(val): sema.release() self.observe_property(name, observer) if not level_sensitive or not cond(getattr(self, name.replace('-', '_'))): sema.acquire() self.unobserve_property(name, observer)
def wait_for_property(self, name, cond=lambda val: val, level_sensitive=True)
Waits until ``cond`` evaluates to a truthy value on the named property. This can be used to wait for properties such as ``idle_active`` indicating the player is done with regular playback and just idling around
3.248705
3.403034
0.95465
self.handle, handle = None, self.handle if threading.current_thread() is self._event_thread: # Handle special case to allow event handle to be detached. # This is necessary since otherwise the event thread would deadlock itself. grim_reaper = threading.Thread(target=lambda: _mpv_terminate_destroy(handle)) grim_reaper.start() else: _mpv_terminate_destroy(handle) if self._event_thread: self._event_thread.join()
def terminate(self)
Properly terminates this player instance. Preferably use this instead of relying on python's garbage collector to cause this to be called from the object's destructor.
6.327427
5.805365
1.089928
args = [name.encode('utf-8')] + [ (arg if type(arg) is bytes else str(arg).encode('utf-8')) for arg in args if arg is not None ] + [None] _mpv_command(self.handle, (c_char_p*len(args))(*args))
def command(self, name, *args)
Execute a raw command.
4.032624
3.87291
1.041239
self.command('seek', amount, reference, precision)
def seek(self, amount, reference="relative", precision="default-precise")
Mapped mpv seek command, see man mpv(1).
9.735962
6.157121
1.581252
self.command('screenshot_to_file', filename.encode(fs_enc), includes)
def screenshot_to_file(self, filename, includes='subtitles')
Mapped mpv screenshot_to_file command, see man mpv(1).
10.85138
6.9567
1.559846
from PIL import Image res = self.node_command('screenshot-raw', includes) if res['format'] != 'bgr0': raise ValueError('Screenshot in unknown format "{}". Currently, only bgr0 is supported.' .format(res['format'])) img = Image.frombytes('RGBA', (res['w'], res['h']), res['data']) b,g,r,a = img.split() return Image.merge('RGB', (r,g,b))
def screenshot_raw(self, includes='subtitles')
Mapped mpv screenshot_raw command, see man mpv(1). Returns a pillow Image object.
4.173707
3.648211
1.144042
self.command('loadfile', filename.encode(fs_enc), mode, MPV._encode_options(options))
def loadfile(self, filename, mode='replace', **options)
Mapped mpv loadfile command, see man mpv(1).
17.043818
9.498684
1.794335
self.command('loadlist', playlist.encode(fs_enc), mode)
def loadlist(self, playlist, mode='replace')
Mapped mpv loadlist command, see man mpv(1).
14.261093
9.598764
1.485722
self.command('overlay_add', overlay_id, x, y, file_or_fd, offset, fmt, w, h, stride)
def overlay_add(self, overlay_id, x, y, file_or_fd, offset, fmt, w, h, stride)
Mapped mpv overlay_add command, see man mpv(1).
2.048541
1.846817
1.109228
self._property_handlers[name].append(handler) _mpv_observe_property(self._event_handle, hash(name)&0xffffffffffffffff, name.encode('utf-8'), MpvFormat.NODE)
def observe_property(self, name, handler)
Register an observer on the named property. An observer is a function that is called with the new property value every time the property's value is changed. The basic function signature is ``fun(property_name, new_value)`` with new_value being the decoded property value as a python object. This function can be used as a function decorator if no handler is given. To unregister the observer, call either of ``mpv.unobserve_property(name, handler)``, ``mpv.unobserve_all_properties(handler)`` or the handler's ``unregister_mpv_properties`` attribute:: @player.observe_property('volume') def my_handler(new_volume, *): print("It's loud!", volume) my_handler.unregister_mpv_properties()
9.93284
11.346714
0.875394
def wrapper(fun): self.observe_property(name, fun) fun.unobserve_mpv_properties = lambda: self.unobserve_property(name, fun) return fun return wrapper
def property_observer(self, name)
Function decorator to register a property observer. See ``MPV.observe_property`` for details.
5.315235
4.039326
1.315872
self._property_handlers[name].remove(handler) if not self._property_handlers[name]: _mpv_unobserve_property(self._event_handle, hash(name)&0xffffffffffffffff)
def unobserve_property(self, name, handler)
Unregister a property observer. This requires both the observed property's name and the handler function that was originally registered as one handler could be registered for several properties. To unregister a handler from *all* observed properties see ``unobserve_all_properties``.
6.008145
6.245312
0.962025
for name in self._property_handlers: self.unobserve_property(name, handler)
def unobserve_all_properties(self, handler)
Unregister a property observer from *all* observed properties.
3.984673
3.88842
1.024754
if isinstance(target_or_handler, str): del self._message_handlers[target_or_handler] else: for key, val in self._message_handlers.items(): if val == target_or_handler: del self._message_handlers[key]
def unregister_message_handler(self, target_or_handler)
Unregister a mpv script message handler for the given script message target name. You can also call the ``unregister_mpv_messages`` function attribute set on the handler function when it is registered.
1.778835
1.895436
0.938483
def register(handler): self._register_message_handler_internal(target, handler) handler.unregister_mpv_messages = lambda: self.unregister_message_handler(handler) return handler return register
def message_handler(self, target)
Decorator to register a mpv script message handler. WARNING: Only one handler can be registered at a time for any given target. To unregister the message handler, call its ``unregister_mpv_messages`` function:: player = mpv.MPV() @player.message_handler('foo') def my_handler(some, args): print(args) my_handler.unregister_mpv_messages()
6.683736
5.039685
1.326221
def register(callback): types = [MpvEventID.from_str(t) if isinstance(t, str) else t for t in event_types] or MpvEventID.ANY @wraps(callback) def wrapper(event, *args, **kwargs): if event['event_id'] in types: callback(event, *args, **kwargs) self._event_callbacks.append(wrapper) wrapper.unregister_mpv_events = partial(self.unregister_event_callback, wrapper) return wrapper return register
def event_callback(self, *event_types)
Function decorator to register a blanket event callback for the given event types. Event types can be given as str (e.g. 'start-file'), integer or MpvEventID object. WARNING: Due to the way this is filtering events, this decorator cannot be chained with itself. To unregister the event callback, call its ``unregister_mpv_events`` function:: player = mpv.MPV() @player.event_callback('shutdown') def my_handler(event): print('It ded.') my_handler.unregister_mpv_events()
3.677584
2.916621
1.260906
def register(fun): @self.key_binding(keydef, mode) @wraps(fun) def wrapper(state='p-', name=None): if state[0] in ('d', 'p'): fun() return wrapper return register
def on_key_press(self, keydef, mode='force')
Function decorator to register a simplified key binding. The callback is called whenever the key given is *pressed*. To unregister the callback function, you can call its ``unregister_mpv_key_bindings`` attribute:: player = mpv.MPV() @player.on_key_press('Q') def binding(): print('blep') binding.unregister_mpv_key_bindings() WARNING: For a single keydef only a single callback/command can be registered at the same time. If you register a binding multiple times older bindings will be overwritten and there is a possibility of references leaking. So don't do that. The BIG FAT WARNING regarding untrusted keydefs from the key_binding method applies here as well.
8.643715
8.345836
1.035692
def register(fun): fun.mpv_key_bindings = getattr(fun, 'mpv_key_bindings', []) + [keydef] def unregister_all(): for keydef in fun.mpv_key_bindings: self.unregister_key_binding(keydef) fun.unregister_mpv_key_bindings = unregister_all self.register_key_binding(keydef, fun, mode) return fun return register
def key_binding(self, keydef, mode='force')
Function decorator to register a low-level key binding. The callback function signature is ``fun(key_state, key_name)`` where ``key_state`` is either ``'U'`` for "key up" or ``'D'`` for "key down". The keydef format is: ``[Shift+][Ctrl+][Alt+][Meta+]<key>`` where ``<key>`` is either the literal character the key produces (ASCII or Unicode character), or a symbolic name (as printed by ``mpv --input-keylist``). To unregister the callback function, you can call its ``unregister_mpv_key_bindings`` attribute:: player = mpv.MPV() @player.key_binding('Q') def binding(state, name): print('blep') binding.unregister_mpv_key_bindings() WARNING: For a single keydef only a single callback/command can be registered at the same time. If you register a binding multiple times older bindings will be overwritten and there is a possibility of references leaking. So don't do that. BIG FAT WARNING: mpv's key binding mechanism is pretty powerful. This means, you essentially get arbitrary code exectution through key bindings. This interface makes some limited effort to sanitize the keydef given in the first parameter, but YOU SHOULD NOT RELY ON THIS IN FOR SECURITY. If your input comes from config files, this is completely fine--but, if you are about to pass untrusted input into this parameter, better double-check whether this is secure in your case.
3.189981
2.780843
1.147127
if not re.match(r'(Shift+)?(Ctrl+)?(Alt+)?(Meta+)?(.|\w+)', keydef): raise ValueError('Invalid keydef. Expected format: [Shift+][Ctrl+][Alt+][Meta+]<key>\n' '<key> is either the literal character the key produces (ASCII or Unicode character), or a ' 'symbolic name (as printed by --input-keylist') binding_name = MPV._binding_name(keydef) if callable(callback_or_cmd): self._key_binding_handlers[binding_name] = callback_or_cmd self.register_message_handler('key-binding', self._handle_key_binding_message) self.command('define-section', binding_name, '{} script-binding py_event_handler/{}'.format(keydef, binding_name), mode) elif isinstance(callback_or_cmd, str): self.command('define-section', binding_name, '{} {}'.format(keydef, callback_or_cmd), mode) else: raise TypeError('register_key_binding expects either an str with an mpv command or a python callable.') self.command('enable-section', binding_name, 'allow-hide-cursor+allow-vo-dragging')
def register_key_binding(self, keydef, callback_or_cmd, mode='force')
Register a key binding. This takes an mpv keydef and either a string containing a mpv command or a python callback function. See ``MPV.key_binding`` for details.
6.242805
5.663828
1.102224
binding_name = MPV._binding_name(keydef) self.command('disable-section', binding_name) self.command('define-section', binding_name, '') if binding_name in self._key_binding_handlers: del self._key_binding_handlers[binding_name] if not self._key_binding_handlers: self.unregister_message_handler('key-binding')
def unregister_key_binding(self, keydef)
Unregister a key binding by keydef.
4.443965
4.296601
1.034298
if self._cors_config['allow_all_origins']: if self.supports_credentials: self._set_allow_origin(resp, origin) else: self._set_allow_origin(resp, '*') return True if origin in self._cors_config['allow_origins_list']: self._set_allow_origin(resp, origin) return True regex = self._cors_config['allow_origins_regex'] if regex is not None: if regex.match(origin): self._set_allow_origin(resp, origin) return True return False
def _process_origin(self, req, resp, origin)
Inspects the request and adds the Access-Control-Allow-Origin header if the requested origin is allowed. Returns: ``True`` if the header was added and the requested origin is allowed, ``False`` if the origin is not allowed and the header has not been added.
2.204908
2.186218
1.008549
if not requested_headers: return True elif self._cors_config['allow_all_headers']: self._set_allowed_headers(resp, requested_headers) return True approved_headers = [] for header in requested_headers: if header.lower() in self._cors_config['allow_headers_list']: approved_headers.append(header) elif self._cors_config.get('allow_headers_regex'): if self._cors_config['allow_headers_regex'].match(header): approved_headers.append(header) if len(approved_headers) == len(requested_headers): self._set_allowed_headers(resp, approved_headers) return True return False
def _process_allow_headers(self, req, resp, requested_headers)
Adds the Access-Control-Allow-Headers header to the response, using the cors settings to determine which headers are allowed. Returns: True if all the headers the client requested are allowed. False if some or none of the headers the client requested are allowed.
1.941505
1.900282
1.021693
requested_method = self._get_requested_method(req) if not requested_method: return False if self._cors_config['allow_all_methods']: allowed_methods = self._get_resource_methods(resource) self._set_allowed_methods(resp, allowed_methods) if requested_method in allowed_methods: return True elif requested_method in self._cors_config['allow_methods_list']: resource_methods = self._get_resource_methods(resource) # Only list methods as allowed if they exist # on the resource AND are in the allowed_methods_list allowed_methods = [ method for method in resource_methods if method in self._cors_config['allow_methods_list'] ] self._set_allowed_methods(resp, allowed_methods) if requested_method in allowed_methods: return True return False
def _process_methods(self, req, resp, resource)
Adds the Access-Control-Allow-Methods header to the response, using the cors settings to determine which methods are allowed.
2.42519
2.302843
1.053129
if self._cors_config['allow_credentials_all_origins']: self._set_allow_credentials(resp) return True if origin in self._cors_config['allow_credentials_origins_list']: self._set_allow_credentials(resp) return True credentials_regex = self._cors_config['allow_credentials_origins_regex'] if credentials_regex: if credentials_regex.match(origin): self._set_allow_credentials(resp) return True return False
def _process_credentials(self, req, resp, origin)
Adds the Access-Control-Allow-Credentials to the response if the cors settings indicates it should be set.
2.235342
2.113016
1.057892
if not email_messages: return sent_message_count = 0 for email_message in email_messages: if self._send(email_message): sent_message_count += 1 return sent_message_count
def send_messages(self, email_messages)
Sends one or more EmailMessage objects and returns the number of email messages sent. Args: email_messages: A list of Django EmailMessage objects. Returns: An integer count of the messages sent. Raises: ClientError: An interaction with the Amazon SES HTTP API failed.
2.661186
2.815229
0.945282
pre_send.send(self.__class__, message=email_message) if not email_message.recipients(): return False from_email = sanitize_address(email_message.from_email, email_message.encoding) recipients = [sanitize_address(addr, email_message.encoding) for addr in email_message.recipients()] message = email_message.message().as_bytes(linesep='\r\n') try: result = self.conn.send_raw_email( Source=from_email, Destinations=recipients, RawMessage={ 'Data': message } ) message_id = result['MessageId'] post_send.send( self.__class__, message=email_message, message_id=message_id ) except ClientError: if not self.fail_silently: raise return False return True
def _send(self, email_message)
Sends an individual message via the Amazon SES HTTP API. Args: email_message: A single Django EmailMessage object. Returns: True if the EmailMessage was sent successfully, otherwise False. Raises: ClientError: An interaction with the Amazon SES HTTP API failed.
2.236418
2.229188
1.003243
# Clean up given path to only allow serving files below document_root. path = posixpath.normpath(unquote(path)) path = path.lstrip('/') newpath = '' for part in path.split('/'): if not part: # Strip empty path components. continue drive, part = os.path.splitdrive(part) head, part = os.path.split(part) if part in (os.curdir, os.pardir): # Strip '.' and '..' in path. continue newpath = os.path.join(newpath, part).replace('\\', '/') if newpath and path != newpath: return HttpResponseRedirect(newpath) fullpath = os.path.join(document_root, newpath) if os.path.isdir(fullpath) and default: defaultpath = os.path.join(fullpath, default) if os.path.exists(defaultpath): fullpath = defaultpath if os.path.isdir(fullpath): if show_indexes: return directory_index(newpath, fullpath) raise Http404("Directory indexes are not allowed here.") if not os.path.exists(fullpath): raise Http404('"%s" does not exist' % fullpath) # Respect the If-Modified-Since header. statobj = os.stat(fullpath) mimetype = mimetypes.guess_type(fullpath)[0] or 'application/octet-stream' if not was_modified_since(request.META.get('HTTP_IF_MODIFIED_SINCE'), statobj[stat.ST_MTIME], statobj[stat.ST_SIZE]): if django.VERSION > (1, 6): return HttpResponseNotModified(content_type=mimetype) else: return HttpResponseNotModified(mimetype=mimetype) contents = open(fullpath, 'rb').read() if django.VERSION > (1, 6): response = HttpResponse(contents, content_type=mimetype) else: response = HttpResponse(contents, mimetype=mimetype) response["Last-Modified"] = http_date(statobj[stat.ST_MTIME]) response["Content-Length"] = len(contents) return response
def serve(request, path, document_root=None, show_indexes=False, default='')
Serve static files below a given point in the directory structure. To use, put a URL pattern such as:: (r'^(?P<path>.*)$', 'django.views.static.serve', {'document_root' : '/path/to/my/files/'}) in your URLconf. You must provide the ``document_root`` param. You may also set ``show_indexes`` to ``True`` if you'd like to serve a basic index of the directory. This index view will use the template hardcoded below, but if you'd like to override it, you can create a template called ``static/directory_index.html``. Modified by ticket #1013 to serve index.html files in the same manner as Apache and other web servers. https://code.djangoproject.com/ticket/1013
1.785824
1.755063
1.017527
try: if header is None: raise ValueError matches = re.match(r"^([^;]+)(; length=([0-9]+))?$", header, re.IGNORECASE) header_mtime = parse_http_date(matches.group(1)) header_len = matches.group(3) if header_len and int(header_len) != size: raise ValueError if int(mtime) > header_mtime: raise ValueError except (AttributeError, ValueError, OverflowError): return True return False
def was_modified_since(header=None, mtime=0, size=0)
Was something modified since the user last downloaded it? header This is the value of the If-Modified-Since header. If this is None, I'll just return True. mtime This is the modification time of the item we're talking about. size This is the size of the item we're talking about.
2.83815
2.754362
1.03042
if not hasattr(obj, 'get_absolute_url') or not obj.get_absolute_url(): raise ImproperlyConfigured("No URL configured. You must either \ set a ``get_absolute_url`` method on the %s model or override the %s view's \ ``get_url`` method" % (obj.__class__.__name__, self.__class__.__name__)) return obj.get_absolute_url()
def get_url(self, obj)
The URL at which the detail page should appear.
2.910111
2.745966
1.059777
logger.debug("Unbuilding %s" % obj) target_path = os.path.split(self.get_build_path(obj))[0] if self.fs.exists(target_path): logger.debug("Removing {}".format(target_path)) self.fs.removetree(target_path)
def unbuild_object(self, obj)
Deletes the directory at self.get_build_path.
3.005653
2.656514
1.131428
ct = ContentType.objects.get_for_id(content_type_pk) obj = ct.get_object_for_this_type(pk=obj_pk) try: # Unbuild the object logger.info("unpublish_object task has received %s" % obj) obj.unbuild() # Run the `publish` management command unless the # ALLOW_BAKERY_AUTO_PUBLISHING variable is explictly set to False. if not getattr(settings, 'ALLOW_BAKERY_AUTO_PUBLISHING', True): logger.info("Not running publish command because \ ALLOW_BAKERY_AUTO_PUBLISHING is False") else: management.call_command("publish") except Exception: # Log the error if this crashes logger.error("Task Error: unpublish_object", exc_info=True)
def unpublish_object(content_type_pk, obj_pk)
Unbuild all views related to a object and then sync to S3. Accepts primary keys to retrieve a model object that inherits bakery's BuildableModel class.
3.900465
3.76661
1.035537
dirname = path.dirname(target_dir) if dirname: dirname = path.join(settings.BUILD_DIR, dirname) if not self.fs.exists(dirname): logger.debug("Creating directory at {}{}".format(self.fs_name, dirname)) self.fs.makedirs(dirname)
def prep_directory(self, target_dir)
Prepares a new directory to store the file at the provided path, if needed.
4.230923
4.033233
1.049015
logger.debug("Building to {}{}".format(self.fs_name, target_path)) with self.fs.open(smart_text(target_path), 'wb') as outfile: outfile.write(six.binary_type(html)) outfile.close()
def write_file(self, target_path, html)
Writes out the provided HTML to the provided path.
5.579644
5.438468
1.025959