Search is not available for this dataset
repository_name
stringlengths 5
67
| func_path_in_repository
stringlengths 4
234
| func_name
stringlengths 0
314
| whole_func_string
stringlengths 52
3.87M
| language
stringclasses 6
values | func_code_string
stringlengths 52
3.87M
| func_code_tokens
sequence | func_documentation_string
stringlengths 1
47.2k
| func_documentation_tokens
sequence | split_name
stringclasses 1
value | func_code_url
stringlengths 85
339
| parameters
sequence | question
stringlengths 9
114
| answer
sequence |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|
gtaylor/python-colormath | colormath/color_conversions.py | RGB_to_XYZ | 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
"""
# 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 | python | 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
"""
# 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",
")",
":",
"# 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"
] | RGB to XYZ conversion. Expects 0-255 RGB values.
Based off of: http://www.brucelindbloom.com/index.html?Eqn_RGB_to_XYZ.html | [
"RGB",
"to",
"XYZ",
"conversion",
".",
"Expects",
"0",
"-",
"255",
"RGB",
"values",
"."
] | train | https://github.com/gtaylor/python-colormath/blob/1d168613718d2d7d31ec4230524e987ef66823c7/colormath/color_conversions.py#L542-L593 | [
"cobj",
"target_illuminant",
"args",
"kwargs"
] | What does this function do? | [
"RGB",
"to",
"XYZ",
"conversion",
".",
"Expects",
"0",
"-",
"255",
"RGB",
"values",
"."
] |
gtaylor/python-colormath | colormath/color_conversions.py | __RGB_to_Hue | 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.
"""
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 | python | 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.
"""
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",
")",
":",
"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"
] | For RGB_to_HSL and RGB_to_HSV, the Hue (H) component is calculated in
the same way. | [
"For",
"RGB_to_HSL",
"and",
"RGB_to_HSV",
"the",
"Hue",
"(",
"H",
")",
"component",
"is",
"calculated",
"in",
"the",
"same",
"way",
"."
] | train | https://github.com/gtaylor/python-colormath/blob/1d168613718d2d7d31ec4230524e987ef66823c7/colormath/color_conversions.py#L597-L609 | [
"var_R",
"var_G",
"var_B",
"var_min",
"var_max"
] | What does this function do? | [
"For",
"RGB_to_HSL",
"and",
"RGB_to_HSV",
"the",
"Hue",
"(",
"H",
")",
"component",
"is",
"calculated",
"in",
"the",
"same",
"way",
"."
] |
gtaylor/python-colormath | colormath/color_conversions.py | RGB_to_HSV | 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.
"""
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) | python | 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.
"""
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",
")",
":",
"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",
")"
] | 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. | [
"Converts",
"from",
"RGB",
"to",
"HSV",
"."
] | train | https://github.com/gtaylor/python-colormath/blob/1d168613718d2d7d31ec4230524e987ef66823c7/colormath/color_conversions.py#L614-L639 | [
"cobj",
"args",
"kwargs"
] | What does this function do? | [
"Converts",
"from",
"RGB",
"to",
"HSV",
"."
] |
gtaylor/python-colormath | colormath/color_conversions.py | RGB_to_HSL | 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.
"""
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) | python | 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.
"""
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",
")",
":",
"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",
")"
] | 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. | [
"Converts",
"from",
"RGB",
"to",
"HSL",
"."
] | train | https://github.com/gtaylor/python-colormath/blob/1d168613718d2d7d31ec4230524e987ef66823c7/colormath/color_conversions.py#L644-L670 | [
"cobj",
"args",
"kwargs"
] | What does this function do? | [
"Converts",
"from",
"RGB",
"to",
"HSL",
"."
] |
gtaylor/python-colormath | colormath/color_conversions.py | __Calc_HSL_to_RGB_Components | def __Calc_HSL_to_RGB_Components(var_q, var_p, C):
"""
This is used in HSL_to_RGB conversions on R, G, and B.
"""
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 | python | def __Calc_HSL_to_RGB_Components(var_q, var_p, C):
"""
This is used in HSL_to_RGB conversions on R, G, and B.
"""
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",
")",
":",
"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"
] | This is used in HSL_to_RGB conversions on R, G, and B. | [
"This",
"is",
"used",
"in",
"HSL_to_RGB",
"conversions",
"on",
"R",
"G",
"and",
"B",
"."
] | train | https://github.com/gtaylor/python-colormath/blob/1d168613718d2d7d31ec4230524e987ef66823c7/colormath/color_conversions.py#L674-L691 | [
"var_q",
"var_p",
"C"
] | What does this function do? | [
"This",
"is",
"used",
"in",
"HSL_to_RGB",
"conversions",
"on",
"R",
"G",
"and",
"B",
"."
] |
gtaylor/python-colormath | colormath/color_conversions.py | HSV_to_RGB | 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.
"""
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) | python | 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.
"""
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",
")",
":",
"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",
")"
] | 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. | [
"HSV",
"to",
"RGB",
"conversion",
"."
] | train | https://github.com/gtaylor/python-colormath/blob/1d168613718d2d7d31ec4230524e987ef66823c7/colormath/color_conversions.py#L696-L750 | [
"cobj",
"target_rgb",
"args",
"kwargs"
] | What does this function do? | [
"HSV",
"to",
"RGB",
"conversion",
"."
] |
gtaylor/python-colormath | colormath/color_conversions.py | HSL_to_RGB | def HSL_to_RGB(cobj, target_rgb, *args, **kwargs):
"""
HSL to RGB conversion.
"""
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) | python | def HSL_to_RGB(cobj, target_rgb, *args, **kwargs):
"""
HSL to RGB conversion.
"""
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",
")",
":",
"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",
")"
] | HSL to RGB conversion. | [
"HSL",
"to",
"RGB",
"conversion",
"."
] | train | https://github.com/gtaylor/python-colormath/blob/1d168613718d2d7d31ec4230524e987ef66823c7/colormath/color_conversions.py#L755-L789 | [
"cobj",
"target_rgb",
"args",
"kwargs"
] | What does this function do? | [
"HSL",
"to",
"RGB",
"conversion",
"."
] |
gtaylor/python-colormath | colormath/color_conversions.py | RGB_to_CMY | def RGB_to_CMY(cobj, *args, **kwargs):
"""
RGB to CMY conversion.
NOTE: CMYK and CMY values range from 0.0 to 1.0
"""
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) | python | def RGB_to_CMY(cobj, *args, **kwargs):
"""
RGB to CMY conversion.
NOTE: CMYK and CMY values range from 0.0 to 1.0
"""
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",
")",
":",
"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",
")"
] | RGB to CMY conversion.
NOTE: CMYK and CMY values range from 0.0 to 1.0 | [
"RGB",
"to",
"CMY",
"conversion",
"."
] | train | https://github.com/gtaylor/python-colormath/blob/1d168613718d2d7d31ec4230524e987ef66823c7/colormath/color_conversions.py#L794-L804 | [
"cobj",
"args",
"kwargs"
] | What does this function do? | [
"RGB",
"to",
"CMY",
"conversion",
"."
] |
gtaylor/python-colormath | colormath/color_conversions.py | CMY_to_RGB | 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.
"""
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) | python | 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.
"""
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",
")",
":",
"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",
")"
] | Converts CMY to RGB via simple subtraction.
NOTE: Returned values are in the range of 0-255. | [
"Converts",
"CMY",
"to",
"RGB",
"via",
"simple",
"subtraction",
"."
] | train | https://github.com/gtaylor/python-colormath/blob/1d168613718d2d7d31ec4230524e987ef66823c7/colormath/color_conversions.py#L809-L819 | [
"cobj",
"target_rgb",
"args",
"kwargs"
] | What does this function do? | [
"Converts",
"CMY",
"to",
"RGB",
"via",
"simple",
"subtraction",
"."
] |
gtaylor/python-colormath | colormath/color_conversions.py | CMY_to_CMYK | def CMY_to_CMYK(cobj, *args, **kwargs):
"""
Converts from CMY to CMYK.
NOTE: CMYK and CMY values range from 0.0 to 1.0
"""
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) | python | def CMY_to_CMYK(cobj, *args, **kwargs):
"""
Converts from CMY to CMYK.
NOTE: CMYK and CMY values range from 0.0 to 1.0
"""
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",
")",
":",
"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",
")"
] | Converts from CMY to CMYK.
NOTE: CMYK and CMY values range from 0.0 to 1.0 | [
"Converts",
"from",
"CMY",
"to",
"CMYK",
"."
] | train | https://github.com/gtaylor/python-colormath/blob/1d168613718d2d7d31ec4230524e987ef66823c7/colormath/color_conversions.py#L824-L848 | [
"cobj",
"args",
"kwargs"
] | What does this function do? | [
"Converts",
"from",
"CMY",
"to",
"CMYK",
"."
] |
gtaylor/python-colormath | colormath/color_conversions.py | CMYK_to_CMY | def CMYK_to_CMY(cobj, *args, **kwargs):
"""
Converts CMYK to CMY.
NOTE: CMYK and CMY values range from 0.0 to 1.0
"""
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) | python | def CMYK_to_CMY(cobj, *args, **kwargs):
"""
Converts CMYK to CMY.
NOTE: CMYK and CMY values range from 0.0 to 1.0
"""
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",
")",
":",
"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",
")"
] | Converts CMYK to CMY.
NOTE: CMYK and CMY values range from 0.0 to 1.0 | [
"Converts",
"CMYK",
"to",
"CMY",
"."
] | train | https://github.com/gtaylor/python-colormath/blob/1d168613718d2d7d31ec4230524e987ef66823c7/colormath/color_conversions.py#L853-L863 | [
"cobj",
"args",
"kwargs"
] | What does this function do? | [
"Converts",
"CMYK",
"to",
"CMY",
"."
] |
gtaylor/python-colormath | colormath/color_conversions.py | XYZ_to_IPT | 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.
"""
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) | python | 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.
"""
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",
")",
":",
"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",
")"
] | 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. | [
"Converts",
"XYZ",
"to",
"IPT",
"."
] | train | https://github.com/gtaylor/python-colormath/blob/1d168613718d2d7d31ec4230524e987ef66823c7/colormath/color_conversions.py#L868-L889 | [
"cobj",
"args",
"kwargs"
] | What does this function do? | [
"Converts",
"XYZ",
"to",
"IPT",
"."
] |
gtaylor/python-colormath | colormath/color_conversions.py | IPT_to_XYZ | def IPT_to_XYZ(cobj, *args, **kwargs):
"""
Converts IPT to XYZ.
"""
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') | python | def IPT_to_XYZ(cobj, *args, **kwargs):
"""
Converts IPT to XYZ.
"""
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",
")",
":",
"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'",
")"
] | Converts IPT to XYZ. | [
"Converts",
"IPT",
"to",
"XYZ",
"."
] | train | https://github.com/gtaylor/python-colormath/blob/1d168613718d2d7d31ec4230524e987ef66823c7/colormath/color_conversions.py#L894-L908 | [
"cobj",
"args",
"kwargs"
] | What does this function do? | [
"Converts",
"IPT",
"to",
"XYZ",
"."
] |
gtaylor/python-colormath | colormath/color_conversions.py | convert_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.
"""
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 | python | 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.
"""
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",
")",
":",
"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"
] | 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. | [
"Converts",
"the",
"color",
"to",
"the",
"designated",
"color",
"space",
"."
] | train | https://github.com/gtaylor/python-colormath/blob/1d168613718d2d7d31ec4230524e987ef66823c7/colormath/color_conversions.py#L929-L1015 | [
"color",
"target_cs",
"through_rgb_type",
"target_illuminant",
"args",
"kwargs"
] | What does this function do? | [
"Converts",
"the",
"color",
"to",
"the",
"designated",
"color",
"space",
"."
] |
gtaylor/python-colormath | colormath/color_conversions.py | ConversionManager.add_type_conversion | 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.
"""
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) | python | 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.
"""
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",
")",
":",
"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",
")"
] | 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. | [
"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",
"."
] | train | https://github.com/gtaylor/python-colormath/blob/1d168613718d2d7d31ec4230524e987ef66823c7/colormath/color_conversions.py#L64-L74 | [
"start_type",
"target_type",
"conversion_function"
] | What does this function do? | [
"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",
"."
] |
gtaylor/python-colormath | colormath/color_appearance_models.py | Hunt._adaptation | 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.
"""
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 | python | 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.
"""
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",
")",
":",
"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"
] | :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. | [
":",
"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",
"."
] | train | https://github.com/gtaylor/python-colormath/blob/1d168613718d2d7d31ec4230524e987ef66823c7/colormath/color_appearance_models.py#L497-L545 | [
"f_l",
"l_a",
"xyz",
"xyz_w",
"xyz_b",
"xyz_p",
"p",
"helson_judd",
"discount_illuminant"
] | What does this function do? | [
":",
"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",
"."
] |
gtaylor/python-colormath | colormath/color_appearance_models.py | Hunt.adjust_white_for_scc | 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.
"""
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 | python | 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.
"""
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",
")",
":",
"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"
] | 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. | [
"Adjust",
"the",
"white",
"point",
"for",
"simultaneous",
"chromatic",
"contrast",
"."
] | train | https://github.com/gtaylor/python-colormath/blob/1d168613718d2d7d31ec4230524e987ef66823c7/colormath/color_appearance_models.py#L548-L560 | [
"cls",
"rgb_p",
"rgb_b",
"rgb_w",
"p"
] | What does this function do? | [
"Adjust",
"the",
"white",
"point",
"for",
"simultaneous",
"chromatic",
"contrast",
"."
] |
gtaylor/python-colormath | colormath/color_appearance_models.py | Hunt._get_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.
"""
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 | python | 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.
"""
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",
")",
":",
"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"
] | 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. | [
"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",
"."
] | train | https://github.com/gtaylor/python-colormath/blob/1d168613718d2d7d31ec4230524e987ef66823c7/colormath/color_appearance_models.py#L563-L585 | [
"x",
"y",
"z"
] | What does this function do? | [
"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",
"."
] |
gtaylor/python-colormath | colormath/color_appearance_models.py | CIECAM02m1._compute_adaptation | 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.
"""
# 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 | python | 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.
"""
# 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",
")",
":",
"# 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"
] | 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. | [
"Modified",
"adaptation",
"procedure",
"incorporating",
"simultaneous",
"chromatic",
"contrast",
"from",
"Hunt",
"model",
"."
] | train | https://github.com/gtaylor/python-colormath/blob/1d168613718d2d7d31ec4230524e987ef66823c7/colormath/color_appearance_models.py#L1245-L1280 | [
"xyz",
"xyz_w",
"f_l",
"d"
] | What does this function do? | [
"Modified",
"adaptation",
"procedure",
"incorporating",
"simultaneous",
"chromatic",
"contrast",
"from",
"Hunt",
"model",
"."
] |
twilio/authy-python | authy/api/resources.py | Instance.errors | def errors(self):
"""
:return error dict if no success:
"""
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 | python | def errors(self):
"""
:return error dict if no success:
"""
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",
")",
":",
"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"
] | :return error dict if no success: | [
":",
"return",
"error",
"dict",
"if",
"no",
"success",
":"
] | train | https://github.com/twilio/authy-python/blob/7a0073b39a56bac495b10e4b4fca3f09982de6ed/authy/api/resources.py#L151-L165 | [] | What does this function do? | [
":",
"return",
"error",
"dict",
"if",
"no",
"success",
":"
] |
twilio/authy-python | authy/api/resources.py | Users.create | 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:
"""
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) | python | 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:
"""
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",
")",
":",
"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",
")"
] | sends request to create new user.
:param string email:
:param string phone:
:param string country_code:
:param bool send_install_link_via_sms:
:return: | [
"sends",
"request",
"to",
"create",
"new",
"user",
".",
":",
"param",
"string",
"email",
":",
":",
"param",
"string",
"phone",
":",
":",
"param",
"string",
"country_code",
":",
":",
"param",
"bool",
"send_install_link_via_sms",
":",
":",
"return",
":"
] | train | https://github.com/twilio/authy-python/blob/7a0073b39a56bac495b10e4b4fca3f09982de6ed/authy/api/resources.py#L220-L241 | [
"email",
"phone",
"country_code",
"send_install_link_via_sms"
] | What does this function do? | [
"sends",
"request",
"to",
"create",
"new",
"user",
".",
":",
"param",
"string",
"email",
":",
":",
"param",
"string",
"phone",
":",
":",
"param",
"string",
"country_code",
":",
":",
"param",
"bool",
"send_install_link_via_sms",
":",
":",
"return",
":"
] |
twilio/authy-python | authy/api/resources.py | Phones.verification_start | 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:
"""
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) | python | 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:
"""
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",
")",
":",
"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",
")"
] | :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: | [
":",
"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",
":"
] | train | https://github.com/twilio/authy-python/blob/7a0073b39a56bac495b10e4b4fca3f09982de6ed/authy/api/resources.py#L327-L360 | [
"phone_number",
"country_code",
"via",
"locale",
"code_length"
] | What does this function do? | [
":",
"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",
":"
] |
twilio/authy-python | authy/api/resources.py | Phones.verification_check | def verification_check(self, phone_number, country_code, verification_code):
"""
:param phone_number:
:param country_code:
:param verification_code:
:return:
"""
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) | python | def verification_check(self, phone_number, country_code, verification_code):
"""
:param phone_number:
:param country_code:
:param verification_code:
:return:
"""
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",
")",
":",
"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",
")"
] | :param phone_number:
:param country_code:
:param verification_code:
:return: | [
":",
"param",
"phone_number",
":",
":",
"param",
"country_code",
":",
":",
"param",
"verification_code",
":",
":",
"return",
":"
] | train | https://github.com/twilio/authy-python/blob/7a0073b39a56bac495b10e4b4fca3f09982de6ed/authy/api/resources.py#L362-L375 | [
"phone_number",
"country_code",
"verification_code"
] | What does this function do? | [
":",
"param",
"phone_number",
":",
":",
"param",
"country_code",
":",
":",
"param",
"verification_code",
":",
":",
"return",
":"
] |
twilio/authy-python | authy/api/resources.py | OneTouch.send_request | 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
"""
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) | python | 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
"""
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",
"=",
"[",
"]",
")",
":",
"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",
")"
] | 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 | [
"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"
] | train | https://github.com/twilio/authy-python/blob/7a0073b39a56bac495b10e4b4fca3f09982de6ed/authy/api/resources.py#L427-L452 | [
"user_id",
"message",
"seconds_to_expire",
"details",
"hidden_details",
"logos"
] | What does this function do? | [
"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"
] |
twilio/authy-python | authy/api/resources.py | OneTouch.clean_logos | def clean_logos(self, logos):
"""
Validate logos input.
:param list logos:
:return list logos:
"""
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 | python | def clean_logos(self, logos):
"""
Validate logos input.
:param list logos:
:return list logos:
"""
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",
")",
":",
"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"
] | Validate logos input.
:param list logos:
:return list logos: | [
"Validate",
"logos",
"input",
".",
":",
"param",
"list",
"logos",
":",
":",
"return",
"list",
"logos",
":"
] | train | https://github.com/twilio/authy-python/blob/7a0073b39a56bac495b10e4b4fca3f09982de6ed/authy/api/resources.py#L454-L488 | [
"logos"
] | What does this function do? | [
"Validate",
"logos",
"input",
".",
":",
"param",
"list",
"logos",
":",
":",
"return",
"list",
"logos",
":"
] |
twilio/authy-python | authy/api/resources.py | OneTouch.get_approval_status | 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:
"""
request_url = "/onetouch/json/approval_requests/{0}".format(uuid)
response = self.get(request_url)
return OneTouchResponse(self, response) | python | 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:
"""
request_url = "/onetouch/json/approval_requests/{0}".format(uuid)
response = self.get(request_url)
return OneTouchResponse(self, response) | [
"def",
"get_approval_status",
"(",
"self",
",",
"uuid",
")",
":",
"request_url",
"=",
"\"/onetouch/json/approval_requests/{0}\"",
".",
"format",
"(",
"uuid",
")",
"response",
"=",
"self",
".",
"get",
"(",
"request_url",
")",
"return",
"OneTouchResponse",
"(",
"self",
",",
"response",
")"
] | 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: | [
"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",
":"
] | train | https://github.com/twilio/authy-python/blob/7a0073b39a56bac495b10e4b4fca3f09982de6ed/authy/api/resources.py#L490-L498 | [
"uuid"
] | What does this function do? | [
"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",
":"
] |
twilio/authy-python | authy/api/resources.py | OneTouch.validate_one_touch_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.
"""
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 | python | 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.
"""
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",
")",
":",
"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"
] | 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. | [
"Function",
"to",
"validate",
"signature",
"in",
"X",
"-",
"Authy",
"-",
"Signature",
"key",
"of",
"headers",
"."
] | train | https://github.com/twilio/authy-python/blob/7a0073b39a56bac495b10e4b4fca3f09982de6ed/authy/api/resources.py#L500-L541 | [
"signature",
"nonce",
"method",
"url",
"params"
] | What does this function do? | [
"Function",
"to",
"validate",
"signature",
"in",
"X",
"-",
"Authy",
"-",
"Signature",
"key",
"of",
"headers",
"."
] |
twilio/authy-python | authy/api/resources.py | OneTouch.__make_http_query | 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.
"""
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 | python | 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.
"""
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",
"=",
"''",
")",
":",
"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"
] | 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. | [
"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",
"."
] | train | https://github.com/twilio/authy-python/blob/7a0073b39a56bac495b10e4b4fca3f09982de6ed/authy/api/resources.py#L543-L582 | [
"params",
"topkey"
] | What does this function do? | [
"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",
"."
] |
doloopwhile/pyjq | pyjq.py | compile | 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.
"""
return _pyjq.Script(script.encode('utf-8'), vars=vars,
library_paths=library_paths) | python | 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.
"""
return _pyjq.Script(script.encode('utf-8'), vars=vars,
library_paths=library_paths) | [
"def",
"compile",
"(",
"script",
",",
"vars",
"=",
"{",
"}",
",",
"library_paths",
"=",
"[",
"]",
")",
":",
"return",
"_pyjq",
".",
"Script",
"(",
"script",
".",
"encode",
"(",
"'utf-8'",
")",
",",
"vars",
"=",
"vars",
",",
"library_paths",
"=",
"library_paths",
")"
] | Compile a jq script, retuning a script object.
library_paths is a list of strings that defines the module search path. | [
"Compile",
"a",
"jq",
"script",
"retuning",
"a",
"script",
"object",
"."
] | train | https://github.com/doloopwhile/pyjq/blob/003144e636af20e20862d4a191f05ec9ed9017b7/pyjq.py#L11-L19 | [
"script",
"vars",
"library_paths"
] | What does this function do? | [
"Compile",
"a",
"jq",
"script",
"retuning",
"a",
"script",
"object",
"."
] |
doloopwhile/pyjq | pyjq.py | apply | def apply(script, value=None, vars={}, url=None, opener=default_opener, library_paths=[]):
"""
Transform value by script, returning all results as list.
"""
return all(script, value, vars, url, opener, library_paths) | python | def apply(script, value=None, vars={}, url=None, opener=default_opener, library_paths=[]):
"""
Transform value by script, returning all results as list.
"""
return all(script, value, vars, url, opener, library_paths) | [
"def",
"apply",
"(",
"script",
",",
"value",
"=",
"None",
",",
"vars",
"=",
"{",
"}",
",",
"url",
"=",
"None",
",",
"opener",
"=",
"default_opener",
",",
"library_paths",
"=",
"[",
"]",
")",
":",
"return",
"all",
"(",
"script",
",",
"value",
",",
"vars",
",",
"url",
",",
"opener",
",",
"library_paths",
")"
] | Transform value by script, returning all results as list. | [
"Transform",
"value",
"by",
"script",
"returning",
"all",
"results",
"as",
"list",
"."
] | train | https://github.com/doloopwhile/pyjq/blob/003144e636af20e20862d4a191f05ec9ed9017b7/pyjq.py#L52-L56 | [
"script",
"value",
"vars",
"url",
"opener",
"library_paths"
] | What does this function do? | [
"Transform",
"value",
"by",
"script",
"returning",
"all",
"results",
"as",
"list",
"."
] |
doloopwhile/pyjq | pyjq.py | first | 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.
"""
return compile(script, vars, library_paths).first(_get_value(value, url, opener), default) | python | 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.
"""
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",
"=",
"[",
"]",
")",
":",
"return",
"compile",
"(",
"script",
",",
"vars",
",",
"library_paths",
")",
".",
"first",
"(",
"_get_value",
"(",
"value",
",",
"url",
",",
"opener",
")",
",",
"default",
")"
] | Transform object by jq script, returning the first result.
Return default if result is empty. | [
"Transform",
"object",
"by",
"jq",
"script",
"returning",
"the",
"first",
"result",
".",
"Return",
"default",
"if",
"result",
"is",
"empty",
"."
] | train | https://github.com/doloopwhile/pyjq/blob/003144e636af20e20862d4a191f05ec9ed9017b7/pyjq.py#L61-L66 | [
"script",
"value",
"default",
"vars",
"url",
"opener",
"library_paths"
] | What does this function do? | [
"Transform",
"object",
"by",
"jq",
"script",
"returning",
"the",
"first",
"result",
".",
"Return",
"default",
"if",
"result",
"is",
"empty",
"."
] |
doloopwhile/pyjq | pyjq.py | one | 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.
"""
return compile(script, vars, library_paths).one(_get_value(value, url, opener)) | python | 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.
"""
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",
"=",
"[",
"]",
")",
":",
"return",
"compile",
"(",
"script",
",",
"vars",
",",
"library_paths",
")",
".",
"one",
"(",
"_get_value",
"(",
"value",
",",
"url",
",",
"opener",
")",
")"
] | Transform object by jq script, returning the first result.
Raise ValueError unless results does not include exactly one element. | [
"Transform",
"object",
"by",
"jq",
"script",
"returning",
"the",
"first",
"result",
".",
"Raise",
"ValueError",
"unless",
"results",
"does",
"not",
"include",
"exactly",
"one",
"element",
"."
] | train | https://github.com/doloopwhile/pyjq/blob/003144e636af20e20862d4a191f05ec9ed9017b7/pyjq.py#L69-L74 | [
"script",
"value",
"vars",
"url",
"opener",
"library_paths"
] | What does this function do? | [
"Transform",
"object",
"by",
"jq",
"script",
"returning",
"the",
"first",
"result",
".",
"Raise",
"ValueError",
"unless",
"results",
"does",
"not",
"include",
"exactly",
"one",
"element",
"."
] |
ambv/flake8-mypy | flake8_mypy.py | calculate_mypypath | def calculate_mypypath() -> List[str]:
"""Return MYPYPATH so that stubs have precedence over local sources."""
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
] | python | def calculate_mypypath() -> List[str]:
"""Return MYPYPATH so that stubs have precedence over local sources."""
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",
"]",
":",
"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",
"]"
] | Return MYPYPATH so that stubs have precedence over local sources. | [
"Return",
"MYPYPATH",
"so",
"that",
"stubs",
"have",
"precedence",
"over",
"local",
"sources",
"."
] | train | https://github.com/ambv/flake8-mypy/blob/616eeb98092edfa0affc00c6cf4f7073f4de26a6/flake8_mypy.py#L52-L100 | [] | What does this function do? | [
"Return",
"MYPYPATH",
"so",
"that",
"stubs",
"have",
"precedence",
"over",
"local",
"sources",
"."
] |
LPgenerator/django-db-mailer | dbmail/providers/pubnub/push.py | send | 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/
"""
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}) | python | 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/
"""
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",
")",
":",
"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",
"}",
")"
] | 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/ | [
"Site",
":",
"http",
":",
"//",
"www",
".",
"pubnub",
".",
"com",
"/",
"API",
":",
"https",
":",
"//",
"www",
".",
"mashape",
".",
"com",
"/",
"pubnub",
"/",
"pubnub",
"-",
"network",
"Desc",
":",
"real",
"-",
"time",
"browser",
"notifications"
] | train | https://github.com/LPgenerator/django-db-mailer/blob/217a73c21ba5c6b68738f74b2c55a6dd2c1afe35/dbmail/providers/pubnub/push.py#L11-L27 | [
"channel",
"message",
"kwargs"
] | What does this function do? | [
"Site",
":",
"http",
":",
"//",
"www",
".",
"pubnub",
".",
"com",
"/",
"API",
":",
"https",
":",
"//",
"www",
".",
"mashape",
".",
"com",
"/",
"pubnub",
"/",
"pubnub",
"-",
"network",
"Desc",
":",
"real",
"-",
"time",
"browser",
"notifications"
] |
LPgenerator/django-db-mailer | dbmail/providers/boxcar/push.py | send | 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
"""
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 | python | 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
"""
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",
")",
":",
"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"
] | Site: https://boxcar.io/
API: http://help.boxcar.io/knowledgebase/topics/48115-boxcar-api
Desc: Best app for system administrators | [
"Site",
":",
"https",
":",
"//",
"boxcar",
".",
"io",
"/",
"API",
":",
"http",
":",
"//",
"help",
".",
"boxcar",
".",
"io",
"/",
"knowledgebase",
"/",
"topics",
"/",
"48115",
"-",
"boxcar",
"-",
"api",
"Desc",
":",
"Best",
"app",
"for",
"system",
"administrators"
] | train | https://github.com/LPgenerator/django-db-mailer/blob/217a73c21ba5c6b68738f74b2c55a6dd2c1afe35/dbmail/providers/boxcar/push.py#L19-L48 | [
"token",
"title",
"kwargs"
] | What does this function do? | [
"Site",
":",
"https",
":",
"//",
"boxcar",
".",
"io",
"/",
"API",
":",
"http",
":",
"//",
"help",
".",
"boxcar",
".",
"io",
"/",
"knowledgebase",
"/",
"topics",
"/",
"48115",
"-",
"boxcar",
"-",
"api",
"Desc",
":",
"Best",
"app",
"for",
"system",
"administrators"
] |
LPgenerator/django-db-mailer | dbmail/providers/slack/push.py | send | def send(channel, message, **kwargs):
"""
Site: https://slack.com
API: https://api.slack.com
Desc: real-time messaging
"""
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 | python | def send(channel, message, **kwargs):
"""
Site: https://slack.com
API: https://api.slack.com
Desc: real-time messaging
"""
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",
")",
":",
"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"
] | Site: https://slack.com
API: https://api.slack.com
Desc: real-time messaging | [
"Site",
":",
"https",
":",
"//",
"slack",
".",
"com",
"API",
":",
"https",
":",
"//",
"api",
".",
"slack",
".",
"com",
"Desc",
":",
"real",
"-",
"time",
"messaging"
] | train | https://github.com/LPgenerator/django-db-mailer/blob/217a73c21ba5c6b68738f74b2c55a6dd2c1afe35/dbmail/providers/slack/push.py#L23-L65 | [
"channel",
"message",
"kwargs"
] | What does this function do? | [
"Site",
":",
"https",
":",
"//",
"slack",
".",
"com",
"API",
":",
"https",
":",
"//",
"api",
".",
"slack",
".",
"com",
"Desc",
":",
"real",
"-",
"time",
"messaging"
] |
LPgenerator/django-db-mailer | dbmail/providers/smsaero/sms.py | send | def send(sms_to, sms_body, **kwargs):
"""
Site: http://smsaero.ru/
API: http://smsaero.ru/api/
"""
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 | python | def send(sms_to, sms_body, **kwargs):
"""
Site: http://smsaero.ru/
API: http://smsaero.ru/api/
"""
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",
")",
":",
"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"
] | Site: http://smsaero.ru/
API: http://smsaero.ru/api/ | [
"Site",
":",
"http",
":",
"//",
"smsaero",
".",
"ru",
"/",
"API",
":",
"http",
":",
"//",
"smsaero",
".",
"ru",
"/",
"api",
"/"
] | train | https://github.com/LPgenerator/django-db-mailer/blob/217a73c21ba5c6b68738f74b2c55a6dd2c1afe35/dbmail/providers/smsaero/sms.py#L23-L61 | [
"sms_to",
"sms_body",
"kwargs"
] | What does this function do? | [
"Site",
":",
"http",
":",
"//",
"smsaero",
".",
"ru",
"/",
"API",
":",
"http",
":",
"//",
"smsaero",
".",
"ru",
"/",
"api",
"/"
] |
LPgenerator/django-db-mailer | dbmail/providers/sendinblue/mail.py | email_list_to_email_dict | def email_list_to_email_dict(email_list):
"""Convert a list of email to a dict of email."""
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 | python | def email_list_to_email_dict(email_list):
"""Convert a list of email to a dict of email."""
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",
")",
":",
"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"
] | Convert a list of email to a dict of email. | [
"Convert",
"a",
"list",
"of",
"email",
"to",
"a",
"dict",
"of",
"email",
"."
] | train | https://github.com/LPgenerator/django-db-mailer/blob/217a73c21ba5c6b68738f74b2c55a6dd2c1afe35/dbmail/providers/sendinblue/mail.py#L15-L23 | [
"email_list"
] | What does this function do? | [
"Convert",
"a",
"list",
"of",
"email",
"to",
"a",
"dict",
"of",
"email",
"."
] |
LPgenerator/django-db-mailer | dbmail/providers/sendinblue/mail.py | email_address_to_list | def email_address_to_list(email_address):
"""Convert an email address to a list."""
realname, address = email.utils.parseaddr(email_address)
return (
[address, realname] if realname and address else
[email_address, email_address]
) | python | def email_address_to_list(email_address):
"""Convert an email address to a list."""
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",
")",
":",
"realname",
",",
"address",
"=",
"email",
".",
"utils",
".",
"parseaddr",
"(",
"email_address",
")",
"return",
"(",
"[",
"address",
",",
"realname",
"]",
"if",
"realname",
"and",
"address",
"else",
"[",
"email_address",
",",
"email_address",
"]",
")"
] | Convert an email address to a list. | [
"Convert",
"an",
"email",
"address",
"to",
"a",
"list",
"."
] | train | https://github.com/LPgenerator/django-db-mailer/blob/217a73c21ba5c6b68738f74b2c55a6dd2c1afe35/dbmail/providers/sendinblue/mail.py#L26-L32 | [
"email_address"
] | What does this function do? | [
"Convert",
"an",
"email",
"address",
"to",
"a",
"list",
"."
] |
LPgenerator/django-db-mailer | dbmail/providers/sendinblue/mail.py | send | def send(sender_instance):
"""Send a transactional email using SendInBlue API.
Site: https://www.sendinblue.com
API: https://apidocs.sendinblue.com/
"""
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"]) | python | def send(sender_instance):
"""Send a transactional email using SendInBlue API.
Site: https://www.sendinblue.com
API: https://apidocs.sendinblue.com/
"""
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",
")",
":",
"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\"",
"]",
")"
] | Send a transactional email using SendInBlue API.
Site: https://www.sendinblue.com
API: https://apidocs.sendinblue.com/ | [
"Send",
"a",
"transactional",
"email",
"using",
"SendInBlue",
"API",
"."
] | train | https://github.com/LPgenerator/django-db-mailer/blob/217a73c21ba5c6b68738f74b2c55a6dd2c1afe35/dbmail/providers/sendinblue/mail.py#L35-L65 | [
"sender_instance"
] | What does this function do? | [
"Send",
"a",
"transactional",
"email",
"using",
"SendInBlue",
"API",
"."
] |
LPgenerator/django-db-mailer | dbmail/providers/iqsms/sms.py | send | def send(sms_to, sms_body, **kwargs):
"""
Site: http://iqsms.ru/
API: http://iqsms.ru/api/
"""
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]) | python | def send(sms_to, sms_body, **kwargs):
"""
Site: http://iqsms.ru/
API: http://iqsms.ru/api/
"""
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",
")",
":",
"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",
"]",
")"
] | Site: http://iqsms.ru/
API: http://iqsms.ru/api/ | [
"Site",
":",
"http",
":",
"//",
"iqsms",
".",
"ru",
"/",
"API",
":",
"http",
":",
"//",
"iqsms",
".",
"ru",
"/",
"api",
"/"
] | train | https://github.com/LPgenerator/django-db-mailer/blob/217a73c21ba5c6b68738f74b2c55a6dd2c1afe35/dbmail/providers/iqsms/sms.py#L22-L52 | [
"sms_to",
"sms_body",
"kwargs"
] | What does this function do? | [
"Site",
":",
"http",
":",
"//",
"iqsms",
".",
"ru",
"/",
"API",
":",
"http",
":",
"//",
"iqsms",
".",
"ru",
"/",
"api",
"/"
] |
LPgenerator/django-db-mailer | dbmail/providers/parse_com/push.py | send | 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
"""
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 | python | 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
"""
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",
")",
":",
"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"
] | Site: http://parse.com
API: https://www.parse.com/docs/push_guide#scheduled/REST
Desc: Best app for system administrators | [
"Site",
":",
"http",
":",
"//",
"parse",
".",
"com",
"API",
":",
"https",
":",
"//",
"www",
".",
"parse",
".",
"com",
"/",
"docs",
"/",
"push_guide#scheduled",
"/",
"REST",
"Desc",
":",
"Best",
"app",
"for",
"system",
"administrators"
] | train | https://github.com/LPgenerator/django-db-mailer/blob/217a73c21ba5c6b68738f74b2c55a6dd2c1afe35/dbmail/providers/parse_com/push.py#L19-L59 | [
"device_id",
"description",
"kwargs"
] | What does this function do? | [
"Site",
":",
"http",
":",
"//",
"parse",
".",
"com",
"API",
":",
"https",
":",
"//",
"www",
".",
"parse",
".",
"com",
"/",
"docs",
"/",
"push_guide#scheduled",
"/",
"REST",
"Desc",
":",
"Best",
"app",
"for",
"system",
"administrators"
] |
LPgenerator/django-db-mailer | dbmail/providers/prowl/push.py | send | def send(api_key, description, **kwargs):
"""
Site: http://prowlapp.com
API: http://prowlapp.com/api.php
Desc: Best app for system administrators
"""
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 | python | def send(api_key, description, **kwargs):
"""
Site: http://prowlapp.com
API: http://prowlapp.com/api.php
Desc: Best app for system administrators
"""
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",
")",
":",
"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"
] | Site: http://prowlapp.com
API: http://prowlapp.com/api.php
Desc: Best app for system administrators | [
"Site",
":",
"http",
":",
"//",
"prowlapp",
".",
"com",
"API",
":",
"http",
":",
"//",
"prowlapp",
".",
"com",
"/",
"api",
".",
"php",
"Desc",
":",
"Best",
"app",
"for",
"system",
"administrators"
] | train | https://github.com/LPgenerator/django-db-mailer/blob/217a73c21ba5c6b68738f74b2c55a6dd2c1afe35/dbmail/providers/prowl/push.py#L30-L71 | [
"api_key",
"description",
"kwargs"
] | What does this function do? | [
"Site",
":",
"http",
":",
"//",
"prowlapp",
".",
"com",
"API",
":",
"http",
":",
"//",
"prowlapp",
".",
"com",
"/",
"api",
".",
"php",
"Desc",
":",
"Best",
"app",
"for",
"system",
"administrators"
] |
LPgenerator/django-db-mailer | dbmail/providers/apple/apns.py | send | def send(token_hex, message, **kwargs):
"""
Site: https://apple.com
API: https://developer.apple.com
Desc: iOS notifications
"""
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 | python | def send(token_hex, message, **kwargs):
"""
Site: https://apple.com
API: https://developer.apple.com
Desc: iOS notifications
"""
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",
")",
":",
"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"
] | Site: https://apple.com
API: https://developer.apple.com
Desc: iOS notifications | [
"Site",
":",
"https",
":",
"//",
"apple",
".",
"com",
"API",
":",
"https",
":",
"//",
"developer",
".",
"apple",
".",
"com",
"Desc",
":",
"iOS",
"notifications"
] | train | https://github.com/LPgenerator/django-db-mailer/blob/217a73c21ba5c6b68738f74b2c55a6dd2c1afe35/dbmail/providers/apple/apns.py#L21-L79 | [
"token_hex",
"message",
"kwargs"
] | What does this function do? | [
"Site",
":",
"https",
":",
"//",
"apple",
".",
"com",
"API",
":",
"https",
":",
"//",
"developer",
".",
"apple",
".",
"com",
"Desc",
":",
"iOS",
"notifications"
] |
LPgenerator/django-db-mailer | dbmail/providers/pushall/push.py | send | 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
"""
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 | python | 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
"""
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",
")",
":",
"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"
] | Site: https://pushall.ru
API: https://pushall.ru/blog/api
Desc: App for notification to devices/browsers and messaging apps | [
"Site",
":",
"https",
":",
"//",
"pushall",
".",
"ru",
"API",
":",
"https",
":",
"//",
"pushall",
".",
"ru",
"/",
"blog",
"/",
"api",
"Desc",
":",
"App",
"for",
"notification",
"to",
"devices",
"/",
"browsers",
"and",
"messaging",
"apps"
] | train | https://github.com/LPgenerator/django-db-mailer/blob/217a73c21ba5c6b68738f74b2c55a6dd2c1afe35/dbmail/providers/pushall/push.py#L14-L46 | [
"ch",
"message",
"kwargs"
] | What does this function do? | [
"Site",
":",
"https",
":",
"//",
"pushall",
".",
"ru",
"API",
":",
"https",
":",
"//",
"pushall",
".",
"ru",
"/",
"blog",
"/",
"api",
"Desc",
":",
"App",
"for",
"notification",
"to",
"devices",
"/",
"browsers",
"and",
"messaging",
"apps"
] |
LPgenerator/django-db-mailer | dbmail/providers/telegram/bot.py | send | 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'
"""
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) | python | 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'
"""
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",
")",
":",
"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",
")"
] | SITE: https://github.com/nickoala/telepot
TELEGRAM API: https://core.telegram.org/bots/api
Installation:
pip install 'telepot>=10.4' | [
"SITE",
":",
"https",
":",
"//",
"github",
".",
"com",
"/",
"nickoala",
"/",
"telepot",
"TELEGRAM",
"API",
":",
"https",
":",
"//",
"core",
".",
"telegram",
".",
"org",
"/",
"bots",
"/",
"api"
] | train | https://github.com/LPgenerator/django-db-mailer/blob/217a73c21ba5c6b68738f74b2c55a6dd2c1afe35/dbmail/providers/telegram/bot.py#L7-L29 | [
"to",
"message",
"kwargs"
] | What does this function do? | [
"SITE",
":",
"https",
":",
"//",
"github",
".",
"com",
"/",
"nickoala",
"/",
"telepot",
"TELEGRAM",
"API",
":",
"https",
":",
"//",
"core",
".",
"telegram",
".",
"org",
"/",
"bots",
"/",
"api"
] |
LPgenerator/django-db-mailer | dbmail/providers/google/browser.py | send | 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'
"""
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 | python | 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'
"""
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",
")",
":",
"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"
] | 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' | [
"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"
] | train | https://github.com/LPgenerator/django-db-mailer/blob/217a73c21ba5c6b68738f74b2c55a6dd2c1afe35/dbmail/providers/google/browser.py#L13-L40 | [
"reg_id",
"message",
"kwargs"
] | What does this function do? | [
"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"
] |
LPgenerator/django-db-mailer | dbmail/providers/apple/apns2.py | send | def send(token_hex, message, **kwargs):
"""
Site: https://apple.com
API: https://developer.apple.com
Desc: iOS notifications
Installation and usage:
pip install hyper
"""
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 | python | def send(token_hex, message, **kwargs):
"""
Site: https://apple.com
API: https://developer.apple.com
Desc: iOS notifications
Installation and usage:
pip install hyper
"""
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",
")",
":",
"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"
] | Site: https://apple.com
API: https://developer.apple.com
Desc: iOS notifications
Installation and usage:
pip install hyper | [
"Site",
":",
"https",
":",
"//",
"apple",
".",
"com",
"API",
":",
"https",
":",
"//",
"developer",
".",
"apple",
".",
"com",
"Desc",
":",
"iOS",
"notifications"
] | train | https://github.com/LPgenerator/django-db-mailer/blob/217a73c21ba5c6b68738f74b2c55a6dd2c1afe35/dbmail/providers/apple/apns2.py#L11-L56 | [
"token_hex",
"message",
"kwargs"
] | What does this function do? | [
"Site",
":",
"https",
":",
"//",
"apple",
".",
"com",
"API",
":",
"https",
":",
"//",
"developer",
".",
"apple",
".",
"com",
"Desc",
":",
"iOS",
"notifications"
] |
LPgenerator/django-db-mailer | dbmail/providers/twilio/sms.py | send | def send(sms_to, sms_body, **kwargs):
"""
Site: https://www.twilio.com/
API: https://www.twilio.com/docs/api/rest/sending-messages
"""
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') | python | def send(sms_to, sms_body, **kwargs):
"""
Site: https://www.twilio.com/
API: https://www.twilio.com/docs/api/rest/sending-messages
"""
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",
")",
":",
"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'",
")"
] | Site: https://www.twilio.com/
API: https://www.twilio.com/docs/api/rest/sending-messages | [
"Site",
":",
"https",
":",
"//",
"www",
".",
"twilio",
".",
"com",
"/",
"API",
":",
"https",
":",
"//",
"www",
".",
"twilio",
".",
"com",
"/",
"docs",
"/",
"api",
"/",
"rest",
"/",
"sending",
"-",
"messages"
] | train | https://github.com/LPgenerator/django-db-mailer/blob/217a73c21ba5c6b68738f74b2c55a6dd2c1afe35/dbmail/providers/twilio/sms.py#L23-L55 | [
"sms_to",
"sms_body",
"kwargs"
] | What does this function do? | [
"Site",
":",
"https",
":",
"//",
"www",
".",
"twilio",
".",
"com",
"/",
"API",
":",
"https",
":",
"//",
"www",
".",
"twilio",
".",
"com",
"/",
"docs",
"/",
"api",
"/",
"rest",
"/",
"sending",
"-",
"messages"
] |
LPgenerator/django-db-mailer | dbmail/providers/pushover/push.py | send | def send(user, message, **kwargs):
"""
Site: https://pushover.net/
API: https://pushover.net/api
Desc: real-time notifications
"""
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 | python | def send(user, message, **kwargs):
"""
Site: https://pushover.net/
API: https://pushover.net/api
Desc: real-time notifications
"""
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",
")",
":",
"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"
] | Site: https://pushover.net/
API: https://pushover.net/api
Desc: real-time notifications | [
"Site",
":",
"https",
":",
"//",
"pushover",
".",
"net",
"/",
"API",
":",
"https",
":",
"//",
"pushover",
".",
"net",
"/",
"api",
"Desc",
":",
"real",
"-",
"time",
"notifications"
] | train | https://github.com/LPgenerator/django-db-mailer/blob/217a73c21ba5c6b68738f74b2c55a6dd2c1afe35/dbmail/providers/pushover/push.py#L22-L61 | [
"user",
"message",
"kwargs"
] | What does this function do? | [
"Site",
":",
"https",
":",
"//",
"pushover",
".",
"net",
"/",
"API",
":",
"https",
":",
"//",
"pushover",
".",
"net",
"/",
"api",
"Desc",
":",
"real",
"-",
"time",
"notifications"
] |
LPgenerator/django-db-mailer | dbmail/providers/google/android.py | send | def send(user, message, **kwargs):
"""
Site: https://developers.google.com
API: https://developers.google.com/cloud-messaging/
Desc: Android notifications
"""
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 | python | def send(user, message, **kwargs):
"""
Site: https://developers.google.com
API: https://developers.google.com/cloud-messaging/
Desc: Android notifications
"""
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",
")",
":",
"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"
] | Site: https://developers.google.com
API: https://developers.google.com/cloud-messaging/
Desc: Android notifications | [
"Site",
":",
"https",
":",
"//",
"developers",
".",
"google",
".",
"com",
"API",
":",
"https",
":",
"//",
"developers",
".",
"google",
".",
"com",
"/",
"cloud",
"-",
"messaging",
"/",
"Desc",
":",
"Android",
"notifications"
] | train | https://github.com/LPgenerator/django-db-mailer/blob/217a73c21ba5c6b68738f74b2c55a6dd2c1afe35/dbmail/providers/google/android.py#L18-L55 | [
"user",
"message",
"kwargs"
] | What does this function do? | [
"Site",
":",
"https",
":",
"//",
"developers",
".",
"google",
".",
"com",
"API",
":",
"https",
":",
"//",
"developers",
".",
"google",
".",
"com",
"/",
"cloud",
"-",
"messaging",
"/",
"Desc",
":",
"Android",
"notifications"
] |
g2p/blocks | blocks/__main__.py | rotate_lv | def rotate_lv(*, device, size, debug, forward):
"""Rotate a logical volume by a single PE.
If forward:
Move the first physical extent of an LV to the end
else:
Move the last physical extent of a LV to the start
then poke LVM to refresh the mapping.
"""
import augeas
class Augeas(augeas.Augeas):
def get_int(self, key):
return int(self.get(key + '/int'))
def set_int(self, key, val):
return self.set(key + '/int', '%d' % val)
def incr(self, key, by=1):
orig = self.get_int(key)
self.set_int(key, orig + by)
def decr(self, key):
self.incr(key, by=-1)
lv_info = subprocess.check_output(
'lvm lvs --noheadings --rows --units=b --nosuffix '
'-o vg_name,vg_uuid,lv_name,lv_uuid,lv_attr --'.split()
+ [device.devpath], universal_newlines=True).splitlines()
vgname, vg_uuid, lvname, lv_uuid, lv_attr = (fi.lstrip() for fi in lv_info)
active = lv_attr[4] == 'a'
# Make sure the volume isn't in use by unmapping it
quiet_call(
['lvm', 'lvchange', '-an', '--', '{}/{}'.format(vgname, lvname)])
with tempfile.TemporaryDirectory(suffix='.blocks') as tdname:
vgcfgname = tdname + '/vg.cfg'
print('Loading LVM metadata... ', end='', flush=True)
quiet_call(
['lvm', 'vgcfgbackup', '--file', vgcfgname, '--', vgname])
aug = Augeas(
loadpath=pkg_resources.resource_filename('blocks', 'augeas'),
root='/dev/null',
flags=augeas.Augeas.NO_MODL_AUTOLOAD | augeas.Augeas.SAVE_NEWFILE)
vgcfg = open(vgcfgname)
vgcfg_orig = vgcfg.read()
aug.set('/raw/vgcfg', vgcfg_orig)
aug.text_store('LVM.lns', '/raw/vgcfg', '/vg')
print('ok')
# There is no easy way to quote for XPath, so whitelist
assert all(ch in ASCII_ALNUM_WHITELIST for ch in vgname), vgname
assert all(ch in ASCII_ALNUM_WHITELIST for ch in lvname), lvname
aug.defvar('vg', '/vg/{}/dict'.format(vgname))
assert aug.get('$vg/id/str') == vg_uuid
aug.defvar('lv', '$vg/logical_volumes/dict/{}/dict'.format(lvname))
assert aug.get('$lv/id/str') == lv_uuid
rotate_aug(aug, forward, size)
aug.text_retrieve('LVM.lns', '/raw/vgcfg', '/vg', '/raw/vgcfg.new')
open(vgcfgname + '.new', 'w').write(aug.get('/raw/vgcfg.new'))
rotate_aug(aug, not forward, size)
aug.text_retrieve('LVM.lns', '/raw/vgcfg', '/vg', '/raw/vgcfg.backagain')
open(vgcfgname + '.backagain', 'w').write(aug.get('/raw/vgcfg.backagain'))
if debug:
print('CHECK STABILITY')
subprocess.call(
['git', '--no-pager', 'diff', '--no-index', '--patience', '--color-words',
'--', vgcfgname, vgcfgname + '.backagain'])
if forward:
print('CHECK CORRECTNESS (forward)')
else:
print('CHECK CORRECTNESS (backward)')
subprocess.call(
['git', '--no-pager', 'diff', '--no-index', '--patience', '--color-words',
'--', vgcfgname, vgcfgname + '.new'])
if forward:
print(
'Rotating the second extent to be the first... ',
end='', flush=True)
else:
print(
'Rotating the last extent to be the first... ',
end='', flush=True)
quiet_call(
['lvm', 'vgcfgrestore', '--file', vgcfgname + '.new', '--', vgname])
# Make sure LVM updates the mapping, this is pretty critical
quiet_call(
['lvm', 'lvchange', '--refresh', '--', '{}/{}'.format(vgname, lvname)])
if active:
quiet_call(
['lvm', 'lvchange', '-ay', '--', '{}/{}'.format(vgname, lvname)])
print('ok') | python | def rotate_lv(*, device, size, debug, forward):
"""Rotate a logical volume by a single PE.
If forward:
Move the first physical extent of an LV to the end
else:
Move the last physical extent of a LV to the start
then poke LVM to refresh the mapping.
"""
import augeas
class Augeas(augeas.Augeas):
def get_int(self, key):
return int(self.get(key + '/int'))
def set_int(self, key, val):
return self.set(key + '/int', '%d' % val)
def incr(self, key, by=1):
orig = self.get_int(key)
self.set_int(key, orig + by)
def decr(self, key):
self.incr(key, by=-1)
lv_info = subprocess.check_output(
'lvm lvs --noheadings --rows --units=b --nosuffix '
'-o vg_name,vg_uuid,lv_name,lv_uuid,lv_attr --'.split()
+ [device.devpath], universal_newlines=True).splitlines()
vgname, vg_uuid, lvname, lv_uuid, lv_attr = (fi.lstrip() for fi in lv_info)
active = lv_attr[4] == 'a'
# Make sure the volume isn't in use by unmapping it
quiet_call(
['lvm', 'lvchange', '-an', '--', '{}/{}'.format(vgname, lvname)])
with tempfile.TemporaryDirectory(suffix='.blocks') as tdname:
vgcfgname = tdname + '/vg.cfg'
print('Loading LVM metadata... ', end='', flush=True)
quiet_call(
['lvm', 'vgcfgbackup', '--file', vgcfgname, '--', vgname])
aug = Augeas(
loadpath=pkg_resources.resource_filename('blocks', 'augeas'),
root='/dev/null',
flags=augeas.Augeas.NO_MODL_AUTOLOAD | augeas.Augeas.SAVE_NEWFILE)
vgcfg = open(vgcfgname)
vgcfg_orig = vgcfg.read()
aug.set('/raw/vgcfg', vgcfg_orig)
aug.text_store('LVM.lns', '/raw/vgcfg', '/vg')
print('ok')
# There is no easy way to quote for XPath, so whitelist
assert all(ch in ASCII_ALNUM_WHITELIST for ch in vgname), vgname
assert all(ch in ASCII_ALNUM_WHITELIST for ch in lvname), lvname
aug.defvar('vg', '/vg/{}/dict'.format(vgname))
assert aug.get('$vg/id/str') == vg_uuid
aug.defvar('lv', '$vg/logical_volumes/dict/{}/dict'.format(lvname))
assert aug.get('$lv/id/str') == lv_uuid
rotate_aug(aug, forward, size)
aug.text_retrieve('LVM.lns', '/raw/vgcfg', '/vg', '/raw/vgcfg.new')
open(vgcfgname + '.new', 'w').write(aug.get('/raw/vgcfg.new'))
rotate_aug(aug, not forward, size)
aug.text_retrieve('LVM.lns', '/raw/vgcfg', '/vg', '/raw/vgcfg.backagain')
open(vgcfgname + '.backagain', 'w').write(aug.get('/raw/vgcfg.backagain'))
if debug:
print('CHECK STABILITY')
subprocess.call(
['git', '--no-pager', 'diff', '--no-index', '--patience', '--color-words',
'--', vgcfgname, vgcfgname + '.backagain'])
if forward:
print('CHECK CORRECTNESS (forward)')
else:
print('CHECK CORRECTNESS (backward)')
subprocess.call(
['git', '--no-pager', 'diff', '--no-index', '--patience', '--color-words',
'--', vgcfgname, vgcfgname + '.new'])
if forward:
print(
'Rotating the second extent to be the first... ',
end='', flush=True)
else:
print(
'Rotating the last extent to be the first... ',
end='', flush=True)
quiet_call(
['lvm', 'vgcfgrestore', '--file', vgcfgname + '.new', '--', vgname])
# Make sure LVM updates the mapping, this is pretty critical
quiet_call(
['lvm', 'lvchange', '--refresh', '--', '{}/{}'.format(vgname, lvname)])
if active:
quiet_call(
['lvm', 'lvchange', '-ay', '--', '{}/{}'.format(vgname, lvname)])
print('ok') | [
"def",
"rotate_lv",
"(",
"*",
",",
"device",
",",
"size",
",",
"debug",
",",
"forward",
")",
":",
"import",
"augeas",
"class",
"Augeas",
"(",
"augeas",
".",
"Augeas",
")",
":",
"def",
"get_int",
"(",
"self",
",",
"key",
")",
":",
"return",
"int",
"(",
"self",
".",
"get",
"(",
"key",
"+",
"'/int'",
")",
")",
"def",
"set_int",
"(",
"self",
",",
"key",
",",
"val",
")",
":",
"return",
"self",
".",
"set",
"(",
"key",
"+",
"'/int'",
",",
"'%d'",
"%",
"val",
")",
"def",
"incr",
"(",
"self",
",",
"key",
",",
"by",
"=",
"1",
")",
":",
"orig",
"=",
"self",
".",
"get_int",
"(",
"key",
")",
"self",
".",
"set_int",
"(",
"key",
",",
"orig",
"+",
"by",
")",
"def",
"decr",
"(",
"self",
",",
"key",
")",
":",
"self",
".",
"incr",
"(",
"key",
",",
"by",
"=",
"-",
"1",
")",
"lv_info",
"=",
"subprocess",
".",
"check_output",
"(",
"'lvm lvs --noheadings --rows --units=b --nosuffix '",
"'-o vg_name,vg_uuid,lv_name,lv_uuid,lv_attr --'",
".",
"split",
"(",
")",
"+",
"[",
"device",
".",
"devpath",
"]",
",",
"universal_newlines",
"=",
"True",
")",
".",
"splitlines",
"(",
")",
"vgname",
",",
"vg_uuid",
",",
"lvname",
",",
"lv_uuid",
",",
"lv_attr",
"=",
"(",
"fi",
".",
"lstrip",
"(",
")",
"for",
"fi",
"in",
"lv_info",
")",
"active",
"=",
"lv_attr",
"[",
"4",
"]",
"==",
"'a'",
"# Make sure the volume isn't in use by unmapping it",
"quiet_call",
"(",
"[",
"'lvm'",
",",
"'lvchange'",
",",
"'-an'",
",",
"'--'",
",",
"'{}/{}'",
".",
"format",
"(",
"vgname",
",",
"lvname",
")",
"]",
")",
"with",
"tempfile",
".",
"TemporaryDirectory",
"(",
"suffix",
"=",
"'.blocks'",
")",
"as",
"tdname",
":",
"vgcfgname",
"=",
"tdname",
"+",
"'/vg.cfg'",
"print",
"(",
"'Loading LVM metadata... '",
",",
"end",
"=",
"''",
",",
"flush",
"=",
"True",
")",
"quiet_call",
"(",
"[",
"'lvm'",
",",
"'vgcfgbackup'",
",",
"'--file'",
",",
"vgcfgname",
",",
"'--'",
",",
"vgname",
"]",
")",
"aug",
"=",
"Augeas",
"(",
"loadpath",
"=",
"pkg_resources",
".",
"resource_filename",
"(",
"'blocks'",
",",
"'augeas'",
")",
",",
"root",
"=",
"'/dev/null'",
",",
"flags",
"=",
"augeas",
".",
"Augeas",
".",
"NO_MODL_AUTOLOAD",
"|",
"augeas",
".",
"Augeas",
".",
"SAVE_NEWFILE",
")",
"vgcfg",
"=",
"open",
"(",
"vgcfgname",
")",
"vgcfg_orig",
"=",
"vgcfg",
".",
"read",
"(",
")",
"aug",
".",
"set",
"(",
"'/raw/vgcfg'",
",",
"vgcfg_orig",
")",
"aug",
".",
"text_store",
"(",
"'LVM.lns'",
",",
"'/raw/vgcfg'",
",",
"'/vg'",
")",
"print",
"(",
"'ok'",
")",
"# There is no easy way to quote for XPath, so whitelist",
"assert",
"all",
"(",
"ch",
"in",
"ASCII_ALNUM_WHITELIST",
"for",
"ch",
"in",
"vgname",
")",
",",
"vgname",
"assert",
"all",
"(",
"ch",
"in",
"ASCII_ALNUM_WHITELIST",
"for",
"ch",
"in",
"lvname",
")",
",",
"lvname",
"aug",
".",
"defvar",
"(",
"'vg'",
",",
"'/vg/{}/dict'",
".",
"format",
"(",
"vgname",
")",
")",
"assert",
"aug",
".",
"get",
"(",
"'$vg/id/str'",
")",
"==",
"vg_uuid",
"aug",
".",
"defvar",
"(",
"'lv'",
",",
"'$vg/logical_volumes/dict/{}/dict'",
".",
"format",
"(",
"lvname",
")",
")",
"assert",
"aug",
".",
"get",
"(",
"'$lv/id/str'",
")",
"==",
"lv_uuid",
"rotate_aug",
"(",
"aug",
",",
"forward",
",",
"size",
")",
"aug",
".",
"text_retrieve",
"(",
"'LVM.lns'",
",",
"'/raw/vgcfg'",
",",
"'/vg'",
",",
"'/raw/vgcfg.new'",
")",
"open",
"(",
"vgcfgname",
"+",
"'.new'",
",",
"'w'",
")",
".",
"write",
"(",
"aug",
".",
"get",
"(",
"'/raw/vgcfg.new'",
")",
")",
"rotate_aug",
"(",
"aug",
",",
"not",
"forward",
",",
"size",
")",
"aug",
".",
"text_retrieve",
"(",
"'LVM.lns'",
",",
"'/raw/vgcfg'",
",",
"'/vg'",
",",
"'/raw/vgcfg.backagain'",
")",
"open",
"(",
"vgcfgname",
"+",
"'.backagain'",
",",
"'w'",
")",
".",
"write",
"(",
"aug",
".",
"get",
"(",
"'/raw/vgcfg.backagain'",
")",
")",
"if",
"debug",
":",
"print",
"(",
"'CHECK STABILITY'",
")",
"subprocess",
".",
"call",
"(",
"[",
"'git'",
",",
"'--no-pager'",
",",
"'diff'",
",",
"'--no-index'",
",",
"'--patience'",
",",
"'--color-words'",
",",
"'--'",
",",
"vgcfgname",
",",
"vgcfgname",
"+",
"'.backagain'",
"]",
")",
"if",
"forward",
":",
"print",
"(",
"'CHECK CORRECTNESS (forward)'",
")",
"else",
":",
"print",
"(",
"'CHECK CORRECTNESS (backward)'",
")",
"subprocess",
".",
"call",
"(",
"[",
"'git'",
",",
"'--no-pager'",
",",
"'diff'",
",",
"'--no-index'",
",",
"'--patience'",
",",
"'--color-words'",
",",
"'--'",
",",
"vgcfgname",
",",
"vgcfgname",
"+",
"'.new'",
"]",
")",
"if",
"forward",
":",
"print",
"(",
"'Rotating the second extent to be the first... '",
",",
"end",
"=",
"''",
",",
"flush",
"=",
"True",
")",
"else",
":",
"print",
"(",
"'Rotating the last extent to be the first... '",
",",
"end",
"=",
"''",
",",
"flush",
"=",
"True",
")",
"quiet_call",
"(",
"[",
"'lvm'",
",",
"'vgcfgrestore'",
",",
"'--file'",
",",
"vgcfgname",
"+",
"'.new'",
",",
"'--'",
",",
"vgname",
"]",
")",
"# Make sure LVM updates the mapping, this is pretty critical",
"quiet_call",
"(",
"[",
"'lvm'",
",",
"'lvchange'",
",",
"'--refresh'",
",",
"'--'",
",",
"'{}/{}'",
".",
"format",
"(",
"vgname",
",",
"lvname",
")",
"]",
")",
"if",
"active",
":",
"quiet_call",
"(",
"[",
"'lvm'",
",",
"'lvchange'",
",",
"'-ay'",
",",
"'--'",
",",
"'{}/{}'",
".",
"format",
"(",
"vgname",
",",
"lvname",
")",
"]",
")",
"print",
"(",
"'ok'",
")"
] | Rotate a logical volume by a single PE.
If forward:
Move the first physical extent of an LV to the end
else:
Move the last physical extent of a LV to the start
then poke LVM to refresh the mapping. | [
"Rotate",
"a",
"logical",
"volume",
"by",
"a",
"single",
"PE",
"."
] | train | https://github.com/g2p/blocks/blob/d00d8aa2bcb64ef5113de9500220e57049b836b4/blocks/__main__.py#L1380-L1478 | [
"",
"device",
"size",
"debug",
"forward"
] | What does this function do? | [
"Rotate",
"a",
"logical",
"volume",
"by",
"a",
"single",
"PE",
"."
] |
jaseg/python-mpv | mpv.py | _mpv_coax_proptype | def _mpv_coax_proptype(value, proptype=str):
"""Intelligently coax the given python value into something that can be understood as a proptype property."""
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)) | python | def _mpv_coax_proptype(value, proptype=str):
"""Intelligently coax the given python value into something that can be understood as a proptype property."""
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",
")",
":",
"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",
")",
")"
] | Intelligently coax the given python value into something that can be understood as a proptype property. | [
"Intelligently",
"coax",
"the",
"given",
"python",
"value",
"into",
"something",
"that",
"can",
"be",
"understood",
"as",
"a",
"proptype",
"property",
"."
] | train | https://github.com/jaseg/python-mpv/blob/7117de4005cc470a45efd9cf2e9657bdf63a9079/mpv.py#L400-L409 | [
"value",
"proptype"
] | What does this function do? | [
"Intelligently",
"coax",
"the",
"given",
"python",
"value",
"into",
"something",
"that",
"can",
"be",
"understood",
"as",
"a",
"proptype",
"property",
"."
] |
jaseg/python-mpv | mpv.py | _make_node_str_list | 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] },
...
}
}
}
"""
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) | python | 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] },
...
}
}
}
"""
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",
")",
":",
"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",
")"
] | 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] },
...
}
}
} | [
"Take",
"a",
"list",
"of",
"python",
"objects",
"and",
"make",
"a",
"MPV",
"string",
"node",
"array",
"from",
"it",
"."
] | train | https://github.com/jaseg/python-mpv/blob/7117de4005cc470a45efd9cf2e9657bdf63a9079/mpv.py#L411-L440 | [
"l"
] | What does this function do? | [
"Take",
"a",
"list",
"of",
"python",
"objects",
"and",
"make",
"a",
"MPV",
"string",
"node",
"array",
"from",
"it",
"."
] |
jaseg/python-mpv | mpv.py | MPV.wait_for_property | 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
"""
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) | python | 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
"""
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",
")",
":",
"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",
")"
] | 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 | [
"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"
] | train | https://github.com/jaseg/python-mpv/blob/7117de4005cc470a45efd9cf2e9657bdf63a9079/mpv.py#L582-L593 | [
"name",
"cond",
"level_sensitive"
] | What does this function do? | [
"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"
] |
jaseg/python-mpv | mpv.py | MPV.terminate | 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.
"""
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() | python | 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.
"""
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",
")",
":",
"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",
"(",
")"
] | 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. | [
"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",
"."
] | train | https://github.com/jaseg/python-mpv/blob/7117de4005cc470a45efd9cf2e9657bdf63a9079/mpv.py#L599-L612 | [] | What does this function do? | [
"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",
"."
] |
jaseg/python-mpv | mpv.py | MPV.command | def command(self, name, *args):
"""Execute a raw command."""
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)) | python | def command(self, name, *args):
"""Execute a raw command."""
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",
")",
":",
"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",
")",
")"
] | Execute a raw command. | [
"Execute",
"a",
"raw",
"command",
"."
] | train | https://github.com/jaseg/python-mpv/blob/7117de4005cc470a45efd9cf2e9657bdf63a9079/mpv.py#L624-L628 | [
"name",
"args"
] | What does this function do? | [
"Execute",
"a",
"raw",
"command",
"."
] |
jaseg/python-mpv | mpv.py | MPV.seek | def seek(self, amount, reference="relative", precision="default-precise"):
"""Mapped mpv seek command, see man mpv(1)."""
self.command('seek', amount, reference, precision) | python | def seek(self, amount, reference="relative", precision="default-precise"):
"""Mapped mpv seek command, see man mpv(1)."""
self.command('seek', amount, reference, precision) | [
"def",
"seek",
"(",
"self",
",",
"amount",
",",
"reference",
"=",
"\"relative\"",
",",
"precision",
"=",
"\"default-precise\"",
")",
":",
"self",
".",
"command",
"(",
"'seek'",
",",
"amount",
",",
"reference",
",",
"precision",
")"
] | Mapped mpv seek command, see man mpv(1). | [
"Mapped",
"mpv",
"seek",
"command",
"see",
"man",
"mpv",
"(",
"1",
")",
"."
] | train | https://github.com/jaseg/python-mpv/blob/7117de4005cc470a45efd9cf2e9657bdf63a9079/mpv.py#L639-L641 | [
"amount",
"reference",
"precision"
] | What does this function do? | [
"Mapped",
"mpv",
"seek",
"command",
"see",
"man",
"mpv",
"(",
"1",
")",
"."
] |
jaseg/python-mpv | mpv.py | MPV.screenshot_to_file | def screenshot_to_file(self, filename, includes='subtitles'):
"""Mapped mpv screenshot_to_file command, see man mpv(1)."""
self.command('screenshot_to_file', filename.encode(fs_enc), includes) | python | def screenshot_to_file(self, filename, includes='subtitles'):
"""Mapped mpv screenshot_to_file command, see man mpv(1)."""
self.command('screenshot_to_file', filename.encode(fs_enc), includes) | [
"def",
"screenshot_to_file",
"(",
"self",
",",
"filename",
",",
"includes",
"=",
"'subtitles'",
")",
":",
"self",
".",
"command",
"(",
"'screenshot_to_file'",
",",
"filename",
".",
"encode",
"(",
"fs_enc",
")",
",",
"includes",
")"
] | Mapped mpv screenshot_to_file command, see man mpv(1). | [
"Mapped",
"mpv",
"screenshot_to_file",
"command",
"see",
"man",
"mpv",
"(",
"1",
")",
"."
] | train | https://github.com/jaseg/python-mpv/blob/7117de4005cc470a45efd9cf2e9657bdf63a9079/mpv.py#L675-L677 | [
"filename",
"includes"
] | What does this function do? | [
"Mapped",
"mpv",
"screenshot_to_file",
"command",
"see",
"man",
"mpv",
"(",
"1",
")",
"."
] |
jaseg/python-mpv | mpv.py | MPV.screenshot_raw | def screenshot_raw(self, includes='subtitles'):
"""Mapped mpv screenshot_raw command, see man mpv(1). Returns a pillow Image object."""
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)) | python | def screenshot_raw(self, includes='subtitles'):
"""Mapped mpv screenshot_raw command, see man mpv(1). Returns a pillow Image object."""
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'",
")",
":",
"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",
")",
")"
] | Mapped mpv screenshot_raw command, see man mpv(1). Returns a pillow Image object. | [
"Mapped",
"mpv",
"screenshot_raw",
"command",
"see",
"man",
"mpv",
"(",
"1",
")",
".",
"Returns",
"a",
"pillow",
"Image",
"object",
"."
] | train | https://github.com/jaseg/python-mpv/blob/7117de4005cc470a45efd9cf2e9657bdf63a9079/mpv.py#L679-L688 | [
"includes"
] | What does this function do? | [
"Mapped",
"mpv",
"screenshot_raw",
"command",
"see",
"man",
"mpv",
"(",
"1",
")",
".",
"Returns",
"a",
"pillow",
"Image",
"object",
"."
] |
jaseg/python-mpv | mpv.py | MPV.loadfile | def loadfile(self, filename, mode='replace', **options):
"""Mapped mpv loadfile command, see man mpv(1)."""
self.command('loadfile', filename.encode(fs_enc), mode, MPV._encode_options(options)) | python | def loadfile(self, filename, mode='replace', **options):
"""Mapped mpv loadfile command, see man mpv(1)."""
self.command('loadfile', filename.encode(fs_enc), mode, MPV._encode_options(options)) | [
"def",
"loadfile",
"(",
"self",
",",
"filename",
",",
"mode",
"=",
"'replace'",
",",
"*",
"*",
"options",
")",
":",
"self",
".",
"command",
"(",
"'loadfile'",
",",
"filename",
".",
"encode",
"(",
"fs_enc",
")",
",",
"mode",
",",
"MPV",
".",
"_encode_options",
"(",
"options",
")",
")"
] | Mapped mpv loadfile command, see man mpv(1). | [
"Mapped",
"mpv",
"loadfile",
"command",
"see",
"man",
"mpv",
"(",
"1",
")",
"."
] | train | https://github.com/jaseg/python-mpv/blob/7117de4005cc470a45efd9cf2e9657bdf63a9079/mpv.py#L702-L704 | [
"filename",
"mode",
"options"
] | What does this function do? | [
"Mapped",
"mpv",
"loadfile",
"command",
"see",
"man",
"mpv",
"(",
"1",
")",
"."
] |
jaseg/python-mpv | mpv.py | MPV.loadlist | def loadlist(self, playlist, mode='replace'):
"""Mapped mpv loadlist command, see man mpv(1)."""
self.command('loadlist', playlist.encode(fs_enc), mode) | python | def loadlist(self, playlist, mode='replace'):
"""Mapped mpv loadlist command, see man mpv(1)."""
self.command('loadlist', playlist.encode(fs_enc), mode) | [
"def",
"loadlist",
"(",
"self",
",",
"playlist",
",",
"mode",
"=",
"'replace'",
")",
":",
"self",
".",
"command",
"(",
"'loadlist'",
",",
"playlist",
".",
"encode",
"(",
"fs_enc",
")",
",",
"mode",
")"
] | Mapped mpv loadlist command, see man mpv(1). | [
"Mapped",
"mpv",
"loadlist",
"command",
"see",
"man",
"mpv",
"(",
"1",
")",
"."
] | train | https://github.com/jaseg/python-mpv/blob/7117de4005cc470a45efd9cf2e9657bdf63a9079/mpv.py#L706-L708 | [
"playlist",
"mode"
] | What does this function do? | [
"Mapped",
"mpv",
"loadlist",
"command",
"see",
"man",
"mpv",
"(",
"1",
")",
"."
] |
jaseg/python-mpv | mpv.py | MPV.overlay_add | 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)."""
self.command('overlay_add', overlay_id, x, y, file_or_fd, offset, fmt, w, h, stride) | python | 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)."""
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",
")",
":",
"self",
".",
"command",
"(",
"'overlay_add'",
",",
"overlay_id",
",",
"x",
",",
"y",
",",
"file_or_fd",
",",
"offset",
",",
"fmt",
",",
"w",
",",
"h",
",",
"stride",
")"
] | Mapped mpv overlay_add command, see man mpv(1). | [
"Mapped",
"mpv",
"overlay_add",
"command",
"see",
"man",
"mpv",
"(",
"1",
")",
"."
] | train | https://github.com/jaseg/python-mpv/blob/7117de4005cc470a45efd9cf2e9657bdf63a9079/mpv.py#L774-L776 | [
"overlay_id",
"x",
"y",
"file_or_fd",
"offset",
"fmt",
"w",
"h",
"stride"
] | What does this function do? | [
"Mapped",
"mpv",
"overlay_add",
"command",
"see",
"man",
"mpv",
"(",
"1",
")",
"."
] |
jaseg/python-mpv | mpv.py | MPV.observe_property | 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()
"""
self._property_handlers[name].append(handler)
_mpv_observe_property(self._event_handle, hash(name)&0xffffffffffffffff, name.encode('utf-8'), MpvFormat.NODE) | python | 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()
"""
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",
")",
":",
"self",
".",
"_property_handlers",
"[",
"name",
"]",
".",
"append",
"(",
"handler",
")",
"_mpv_observe_property",
"(",
"self",
".",
"_event_handle",
",",
"hash",
"(",
"name",
")",
"&",
"0xffffffffffffffff",
",",
"name",
".",
"encode",
"(",
"'utf-8'",
")",
",",
"MpvFormat",
".",
"NODE",
")"
] | 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() | [
"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",
"."
] | train | https://github.com/jaseg/python-mpv/blob/7117de4005cc470a45efd9cf2e9657bdf63a9079/mpv.py#L790-L806 | [
"name",
"handler"
] | What does this function do? | [
"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",
"."
] |
jaseg/python-mpv | mpv.py | MPV.property_observer | def property_observer(self, name):
"""Function decorator to register a property observer. See ``MPV.observe_property`` for details."""
def wrapper(fun):
self.observe_property(name, fun)
fun.unobserve_mpv_properties = lambda: self.unobserve_property(name, fun)
return fun
return wrapper | python | def property_observer(self, name):
"""Function decorator to register a property observer. See ``MPV.observe_property`` for details."""
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",
")",
":",
"def",
"wrapper",
"(",
"fun",
")",
":",
"self",
".",
"observe_property",
"(",
"name",
",",
"fun",
")",
"fun",
".",
"unobserve_mpv_properties",
"=",
"lambda",
":",
"self",
".",
"unobserve_property",
"(",
"name",
",",
"fun",
")",
"return",
"fun",
"return",
"wrapper"
] | Function decorator to register a property observer. See ``MPV.observe_property`` for details. | [
"Function",
"decorator",
"to",
"register",
"a",
"property",
"observer",
".",
"See",
"MPV",
".",
"observe_property",
"for",
"details",
"."
] | train | https://github.com/jaseg/python-mpv/blob/7117de4005cc470a45efd9cf2e9657bdf63a9079/mpv.py#L808-L814 | [
"name"
] | What does this function do? | [
"Function",
"decorator",
"to",
"register",
"a",
"property",
"observer",
".",
"See",
"MPV",
".",
"observe_property",
"for",
"details",
"."
] |
jaseg/python-mpv | mpv.py | MPV.unobserve_property | 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``.
"""
self._property_handlers[name].remove(handler)
if not self._property_handlers[name]:
_mpv_unobserve_property(self._event_handle, hash(name)&0xffffffffffffffff) | python | 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``.
"""
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",
")",
":",
"self",
".",
"_property_handlers",
"[",
"name",
"]",
".",
"remove",
"(",
"handler",
")",
"if",
"not",
"self",
".",
"_property_handlers",
"[",
"name",
"]",
":",
"_mpv_unobserve_property",
"(",
"self",
".",
"_event_handle",
",",
"hash",
"(",
"name",
")",
"&",
"0xffffffffffffffff",
")"
] | 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``. | [
"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",
"."
] | train | https://github.com/jaseg/python-mpv/blob/7117de4005cc470a45efd9cf2e9657bdf63a9079/mpv.py#L816-L823 | [
"name",
"handler"
] | What does this function do? | [
"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",
"."
] |
jaseg/python-mpv | mpv.py | MPV.unobserve_all_properties | def unobserve_all_properties(self, handler):
"""Unregister a property observer from *all* observed properties."""
for name in self._property_handlers:
self.unobserve_property(name, handler) | python | def unobserve_all_properties(self, handler):
"""Unregister a property observer from *all* observed properties."""
for name in self._property_handlers:
self.unobserve_property(name, handler) | [
"def",
"unobserve_all_properties",
"(",
"self",
",",
"handler",
")",
":",
"for",
"name",
"in",
"self",
".",
"_property_handlers",
":",
"self",
".",
"unobserve_property",
"(",
"name",
",",
"handler",
")"
] | Unregister a property observer from *all* observed properties. | [
"Unregister",
"a",
"property",
"observer",
"from",
"*",
"all",
"*",
"observed",
"properties",
"."
] | train | https://github.com/jaseg/python-mpv/blob/7117de4005cc470a45efd9cf2e9657bdf63a9079/mpv.py#L825-L828 | [
"handler"
] | What does this function do? | [
"Unregister",
"a",
"property",
"observer",
"from",
"*",
"all",
"*",
"observed",
"properties",
"."
] |
jaseg/python-mpv | mpv.py | MPV.unregister_message_handler | 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.
"""
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] | python | 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.
"""
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",
")",
":",
"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",
"]"
] | 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. | [
"Unregister",
"a",
"mpv",
"script",
"message",
"handler",
"for",
"the",
"given",
"script",
"message",
"target",
"name",
"."
] | train | https://github.com/jaseg/python-mpv/blob/7117de4005cc470a45efd9cf2e9657bdf63a9079/mpv.py#L850-L861 | [
"target_or_handler"
] | What does this function do? | [
"Unregister",
"a",
"mpv",
"script",
"message",
"handler",
"for",
"the",
"given",
"script",
"message",
"target",
"name",
"."
] |
jaseg/python-mpv | mpv.py | MPV.message_handler | 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()
"""
def register(handler):
self._register_message_handler_internal(target, handler)
handler.unregister_mpv_messages = lambda: self.unregister_message_handler(handler)
return handler
return register | python | 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()
"""
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",
")",
":",
"def",
"register",
"(",
"handler",
")",
":",
"self",
".",
"_register_message_handler_internal",
"(",
"target",
",",
"handler",
")",
"handler",
".",
"unregister_mpv_messages",
"=",
"lambda",
":",
"self",
".",
"unregister_message_handler",
"(",
"handler",
")",
"return",
"handler",
"return",
"register"
] | 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() | [
"Decorator",
"to",
"register",
"a",
"mpv",
"script",
"message",
"handler",
"."
] | train | https://github.com/jaseg/python-mpv/blob/7117de4005cc470a45efd9cf2e9657bdf63a9079/mpv.py#L863-L881 | [
"target"
] | What does this function do? | [
"Decorator",
"to",
"register",
"a",
"mpv",
"script",
"message",
"handler",
"."
] |
jaseg/python-mpv | mpv.py | MPV.event_callback | 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()
"""
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 | python | 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()
"""
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",
")",
":",
"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"
] | 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() | [
"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",
"."
] | train | https://github.com/jaseg/python-mpv/blob/7117de4005cc470a45efd9cf2e9657bdf63a9079/mpv.py#L901-L925 | [
"event_types"
] | What does this function do? | [
"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",
"."
] |
jaseg/python-mpv | mpv.py | MPV.on_key_press | 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.
"""
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 | python | 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.
"""
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'",
")",
":",
"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"
] | 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. | [
"Function",
"decorator",
"to",
"register",
"a",
"simplified",
"key",
"binding",
".",
"The",
"callback",
"is",
"called",
"whenever",
"the",
"key",
"given",
"is",
"*",
"pressed",
"*",
"."
] | train | https://github.com/jaseg/python-mpv/blob/7117de4005cc470a45efd9cf2e9657bdf63a9079/mpv.py#L931-L957 | [
"keydef",
"mode"
] | What does this function do? | [
"Function",
"decorator",
"to",
"register",
"a",
"simplified",
"key",
"binding",
".",
"The",
"callback",
"is",
"called",
"whenever",
"the",
"key",
"given",
"is",
"*",
"pressed",
"*",
"."
] |
jaseg/python-mpv | mpv.py | MPV.key_binding | 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.
"""
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 | python | 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.
"""
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'",
")",
":",
"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"
] | 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. | [
"Function",
"decorator",
"to",
"register",
"a",
"low",
"-",
"level",
"key",
"binding",
"."
] | train | https://github.com/jaseg/python-mpv/blob/7117de4005cc470a45efd9cf2e9657bdf63a9079/mpv.py#L959-L996 | [
"keydef",
"mode"
] | What does this function do? | [
"Function",
"decorator",
"to",
"register",
"a",
"low",
"-",
"level",
"key",
"binding",
"."
] |
jaseg/python-mpv | mpv.py | MPV.register_key_binding | 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.
"""
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') | python | 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.
"""
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'",
")",
":",
"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'",
")"
] | 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. | [
"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",
"."
] | train | https://github.com/jaseg/python-mpv/blob/7117de4005cc470a45efd9cf2e9657bdf63a9079/mpv.py#L998-L1016 | [
"keydef",
"callback_or_cmd",
"mode"
] | What does this function do? | [
"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",
"."
] |
jaseg/python-mpv | mpv.py | MPV.unregister_key_binding | def unregister_key_binding(self, keydef):
"""Unregister a key binding by keydef."""
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') | python | def unregister_key_binding(self, keydef):
"""Unregister a key binding by keydef."""
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",
")",
":",
"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'",
")"
] | Unregister a key binding by keydef. | [
"Unregister",
"a",
"key",
"binding",
"by",
"keydef",
"."
] | train | https://github.com/jaseg/python-mpv/blob/7117de4005cc470a45efd9cf2e9657bdf63a9079/mpv.py#L1021-L1029 | [
"keydef"
] | What does this function do? | [
"Unregister",
"a",
"key",
"binding",
"by",
"keydef",
"."
] |
lwcolton/falcon-cors | src/falcon_cors/__init__.py | CORS._process_origin | 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.
"""
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 | python | 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.
"""
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",
")",
":",
"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"
] | 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. | [
"Inspects",
"the",
"request",
"and",
"adds",
"the",
"Access",
"-",
"Control",
"-",
"Allow",
"-",
"Origin",
"header",
"if",
"the",
"requested",
"origin",
"is",
"allowed",
"."
] | train | https://github.com/lwcolton/falcon-cors/blob/9e1243829078e4c6f8fb8bb895b5cad62bce9d6b/src/falcon_cors/__init__.py#L303-L329 | [
"req",
"resp",
"origin"
] | What does this function do? | [
"Inspects",
"the",
"request",
"and",
"adds",
"the",
"Access",
"-",
"Control",
"-",
"Allow",
"-",
"Origin",
"header",
"if",
"the",
"requested",
"origin",
"is",
"allowed",
"."
] |
lwcolton/falcon-cors | src/falcon_cors/__init__.py | CORS._process_allow_headers | 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.
"""
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 | python | 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.
"""
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",
")",
":",
"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"
] | 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. | [
"Adds",
"the",
"Access",
"-",
"Control",
"-",
"Allow",
"-",
"Headers",
"header",
"to",
"the",
"response",
"using",
"the",
"cors",
"settings",
"to",
"determine",
"which",
"headers",
"are",
"allowed",
"."
] | train | https://github.com/lwcolton/falcon-cors/blob/9e1243829078e4c6f8fb8bb895b5cad62bce9d6b/src/falcon_cors/__init__.py#L331-L357 | [
"req",
"resp",
"requested_headers"
] | What does this function do? | [
"Adds",
"the",
"Access",
"-",
"Control",
"-",
"Allow",
"-",
"Headers",
"header",
"to",
"the",
"response",
"using",
"the",
"cors",
"settings",
"to",
"determine",
"which",
"headers",
"are",
"allowed",
"."
] |
lwcolton/falcon-cors | src/falcon_cors/__init__.py | CORS._process_methods | 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.
"""
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 | python | 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.
"""
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",
")",
":",
"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"
] | Adds the Access-Control-Allow-Methods header to the response,
using the cors settings to determine which methods are allowed. | [
"Adds",
"the",
"Access",
"-",
"Control",
"-",
"Allow",
"-",
"Methods",
"header",
"to",
"the",
"response",
"using",
"the",
"cors",
"settings",
"to",
"determine",
"which",
"methods",
"are",
"allowed",
"."
] | train | https://github.com/lwcolton/falcon-cors/blob/9e1243829078e4c6f8fb8bb895b5cad62bce9d6b/src/falcon_cors/__init__.py#L359-L384 | [
"req",
"resp",
"resource"
] | What does this function do? | [
"Adds",
"the",
"Access",
"-",
"Control",
"-",
"Allow",
"-",
"Methods",
"header",
"to",
"the",
"response",
"using",
"the",
"cors",
"settings",
"to",
"determine",
"which",
"methods",
"are",
"allowed",
"."
] |
lwcolton/falcon-cors | src/falcon_cors/__init__.py | CORS._process_credentials | 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.
"""
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 | python | 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.
"""
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",
")",
":",
"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"
] | Adds the Access-Control-Allow-Credentials to the response
if the cors settings indicates it should be set. | [
"Adds",
"the",
"Access",
"-",
"Control",
"-",
"Allow",
"-",
"Credentials",
"to",
"the",
"response",
"if",
"the",
"cors",
"settings",
"indicates",
"it",
"should",
"be",
"set",
"."
] | train | https://github.com/lwcolton/falcon-cors/blob/9e1243829078e4c6f8fb8bb895b5cad62bce9d6b/src/falcon_cors/__init__.py#L396-L414 | [
"req",
"resp",
"origin"
] | What does this function do? | [
"Adds",
"the",
"Access",
"-",
"Control",
"-",
"Allow",
"-",
"Credentials",
"to",
"the",
"response",
"if",
"the",
"cors",
"settings",
"indicates",
"it",
"should",
"be",
"set",
"."
] |
azavea/django-amazon-ses | django_amazon_ses.py | EmailBackend.send_messages | 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.
"""
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 | python | 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.
"""
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",
")",
":",
"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"
] | 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. | [
"Sends",
"one",
"or",
"more",
"EmailMessage",
"objects",
"and",
"returns",
"the",
"number",
"of",
"email",
"messages",
"sent",
"."
] | train | https://github.com/azavea/django-amazon-ses/blob/668c2e240ee643d02294d28966a9d44cf30dfc7f/django_amazon_ses.py#L58-L78 | [
"email_messages"
] | What does this function do? | [
"Sends",
"one",
"or",
"more",
"EmailMessage",
"objects",
"and",
"returns",
"the",
"number",
"of",
"email",
"messages",
"sent",
"."
] |
azavea/django-amazon-ses | django_amazon_ses.py | EmailBackend._send | 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.
"""
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 | python | 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.
"""
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",
")",
":",
"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"
] | 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. | [
"Sends",
"an",
"individual",
"message",
"via",
"the",
"Amazon",
"SES",
"HTTP",
"API",
"."
] | train | https://github.com/azavea/django-amazon-ses/blob/668c2e240ee643d02294d28966a9d44cf30dfc7f/django_amazon_ses.py#L80-L120 | [
"email_message"
] | What does this function do? | [
"Sends",
"an",
"individual",
"message",
"via",
"the",
"Amazon",
"SES",
"HTTP",
"API",
"."
] |
datadesk/django-bakery | bakery/static_views.py | serve | 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
"""
# 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 | python | 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
"""
# 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",
"=",
"''",
")",
":",
"# 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"
] | 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 | [
"Serve",
"static",
"files",
"below",
"a",
"given",
"point",
"in",
"the",
"directory",
"structure",
"."
] | train | https://github.com/datadesk/django-bakery/blob/e2feb13a66552a388fbcfaaacdd504bba08d3c69/bakery/static_views.py#L19-L83 | [
"request",
"path",
"document_root",
"show_indexes",
"default"
] | What does this function do? | [
"Serve",
"static",
"files",
"below",
"a",
"given",
"point",
"in",
"the",
"directory",
"structure",
"."
] |
datadesk/django-bakery | bakery/static_views.py | was_modified_since | 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.
"""
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 | python | 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.
"""
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",
")",
":",
"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"
] | 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. | [
"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",
"."
] | train | https://github.com/datadesk/django-bakery/blob/e2feb13a66552a388fbcfaaacdd504bba08d3c69/bakery/static_views.py#L135-L159 | [
"header",
"mtime",
"size"
] | What does this function do? | [
"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",
"."
] |
datadesk/django-bakery | bakery/views/detail.py | BuildableDetailView.get_url | def get_url(self, obj):
"""
The URL at which the detail page should appear.
"""
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() | python | def get_url(self, obj):
"""
The URL at which the detail page should appear.
"""
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",
")",
":",
"if",
"not",
"hasattr",
"(",
"obj",
",",
"'get_absolute_url'",
")",
"or",
"not",
"obj",
".",
"get_absolute_url",
"(",
")",
":",
"raise",
"ImproperlyConfigured",
"(",
"\"No URL configured. You must either \\\nset a ``get_absolute_url`` method on the %s model or override the %s view's \\\n``get_url`` method\"",
"%",
"(",
"obj",
".",
"__class__",
".",
"__name__",
",",
"self",
".",
"__class__",
".",
"__name__",
")",
")",
"return",
"obj",
".",
"get_absolute_url",
"(",
")"
] | The URL at which the detail page should appear. | [
"The",
"URL",
"at",
"which",
"the",
"detail",
"page",
"should",
"appear",
"."
] | train | https://github.com/datadesk/django-bakery/blob/e2feb13a66552a388fbcfaaacdd504bba08d3c69/bakery/views/detail.py#L32-L40 | [
"obj"
] | What does this function do? | [
"The",
"URL",
"at",
"which",
"the",
"detail",
"page",
"should",
"appear",
"."
] |
datadesk/django-bakery | bakery/views/detail.py | BuildableDetailView.unbuild_object | def unbuild_object(self, obj):
"""
Deletes the directory at self.get_build_path.
"""
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) | python | def unbuild_object(self, obj):
"""
Deletes the directory at self.get_build_path.
"""
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",
")",
":",
"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",
")"
] | Deletes the directory at self.get_build_path. | [
"Deletes",
"the",
"directory",
"at",
"self",
".",
"get_build_path",
"."
] | train | https://github.com/datadesk/django-bakery/blob/e2feb13a66552a388fbcfaaacdd504bba08d3c69/bakery/views/detail.py#L74-L82 | [
"obj"
] | What does this function do? | [
"Deletes",
"the",
"directory",
"at",
"self",
".",
"get_build_path",
"."
] |
datadesk/django-bakery | bakery/tasks.py | unpublish_object | 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.
"""
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) | python | 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.
"""
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",
")",
":",
"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 \\\nALLOW_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",
")"
] | 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. | [
"Unbuild",
"all",
"views",
"related",
"to",
"a",
"object",
"and",
"then",
"sync",
"to",
"S3",
"."
] | train | https://github.com/datadesk/django-bakery/blob/e2feb13a66552a388fbcfaaacdd504bba08d3c69/bakery/tasks.py#L39-L61 | [
"content_type_pk",
"obj_pk"
] | What does this function do? | [
"Unbuild",
"all",
"views",
"related",
"to",
"a",
"object",
"and",
"then",
"sync",
"to",
"S3",
"."
] |
datadesk/django-bakery | bakery/views/base.py | BuildableMixin.prep_directory | def prep_directory(self, target_dir):
"""
Prepares a new directory to store the file at the provided path, if needed.
"""
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) | python | def prep_directory(self, target_dir):
"""
Prepares a new directory to store the file at the provided path, if needed.
"""
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",
")",
":",
"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",
")"
] | Prepares a new directory to store the file at the provided path, if needed. | [
"Prepares",
"a",
"new",
"directory",
"to",
"store",
"the",
"file",
"at",
"the",
"provided",
"path",
"if",
"needed",
"."
] | train | https://github.com/datadesk/django-bakery/blob/e2feb13a66552a388fbcfaaacdd504bba08d3c69/bakery/views/base.py#L55-L64 | [
"target_dir"
] | What does this function do? | [
"Prepares",
"a",
"new",
"directory",
"to",
"store",
"the",
"file",
"at",
"the",
"provided",
"path",
"if",
"needed",
"."
] |
datadesk/django-bakery | bakery/views/base.py | BuildableMixin.write_file | def write_file(self, target_path, html):
"""
Writes out the provided HTML to the provided path.
"""
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() | python | def write_file(self, target_path, html):
"""
Writes out the provided HTML to the provided path.
"""
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",
")",
":",
"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",
"(",
")"
] | Writes out the provided HTML to the provided path. | [
"Writes",
"out",
"the",
"provided",
"HTML",
"to",
"the",
"provided",
"path",
"."
] | train | https://github.com/datadesk/django-bakery/blob/e2feb13a66552a388fbcfaaacdd504bba08d3c69/bakery/views/base.py#L72-L79 | [
"target_path",
"html"
] | What does this function do? | [
"Writes",
"out",
"the",
"provided",
"HTML",
"to",
"the",
"provided",
"path",
"."
] |
datadesk/django-bakery | bakery/views/base.py | BuildableMixin.is_gzippable | def is_gzippable(self, path):
"""
Returns a boolean indicating if the provided file path is a candidate
for gzipping.
"""
# First check if gzipping is allowed by the global setting
if not getattr(settings, 'BAKERY_GZIP', False):
return False
# Then check if the content type of this particular file is gzippable
whitelist = getattr(
settings,
'GZIP_CONTENT_TYPES',
DEFAULT_GZIP_CONTENT_TYPES
)
return mimetypes.guess_type(path)[0] in whitelist | python | def is_gzippable(self, path):
"""
Returns a boolean indicating if the provided file path is a candidate
for gzipping.
"""
# First check if gzipping is allowed by the global setting
if not getattr(settings, 'BAKERY_GZIP', False):
return False
# Then check if the content type of this particular file is gzippable
whitelist = getattr(
settings,
'GZIP_CONTENT_TYPES',
DEFAULT_GZIP_CONTENT_TYPES
)
return mimetypes.guess_type(path)[0] in whitelist | [
"def",
"is_gzippable",
"(",
"self",
",",
"path",
")",
":",
"# First check if gzipping is allowed by the global setting",
"if",
"not",
"getattr",
"(",
"settings",
",",
"'BAKERY_GZIP'",
",",
"False",
")",
":",
"return",
"False",
"# Then check if the content type of this particular file is gzippable",
"whitelist",
"=",
"getattr",
"(",
"settings",
",",
"'GZIP_CONTENT_TYPES'",
",",
"DEFAULT_GZIP_CONTENT_TYPES",
")",
"return",
"mimetypes",
".",
"guess_type",
"(",
"path",
")",
"[",
"0",
"]",
"in",
"whitelist"
] | Returns a boolean indicating if the provided file path is a candidate
for gzipping. | [
"Returns",
"a",
"boolean",
"indicating",
"if",
"the",
"provided",
"file",
"path",
"is",
"a",
"candidate",
"for",
"gzipping",
"."
] | train | https://github.com/datadesk/django-bakery/blob/e2feb13a66552a388fbcfaaacdd504bba08d3c69/bakery/views/base.py#L81-L95 | [
"path"
] | What does this function do? | [
"Returns",
"a",
"boolean",
"indicating",
"if",
"the",
"provided",
"file",
"path",
"is",
"a",
"candidate",
"for",
"gzipping",
"."
] |
datadesk/django-bakery | bakery/views/base.py | BuildableMixin.gzip_file | def gzip_file(self, target_path, html):
"""
Zips up the provided HTML as a companion for the provided path.
Intended to take advantage of the peculiarities of
Amazon S3's GZIP service.
mtime, an option that writes a timestamp to the output file
is set to 0, to avoid having s3cmd do unnecessary uploads because
of differences in the timestamp
"""
logger.debug("Gzipping to {}{}".format(self.fs_name, target_path))
# Write GZIP data to an in-memory buffer
data_buffer = six.BytesIO()
kwargs = dict(
filename=path.basename(target_path),
mode='wb',
fileobj=data_buffer
)
if float(sys.version[:3]) >= 2.7:
kwargs['mtime'] = 0
with gzip.GzipFile(**kwargs) as f:
f.write(six.binary_type(html))
# Write that buffer out to the filesystem
with self.fs.open(smart_text(target_path), 'wb') as outfile:
outfile.write(data_buffer.getvalue())
outfile.close() | python | def gzip_file(self, target_path, html):
"""
Zips up the provided HTML as a companion for the provided path.
Intended to take advantage of the peculiarities of
Amazon S3's GZIP service.
mtime, an option that writes a timestamp to the output file
is set to 0, to avoid having s3cmd do unnecessary uploads because
of differences in the timestamp
"""
logger.debug("Gzipping to {}{}".format(self.fs_name, target_path))
# Write GZIP data to an in-memory buffer
data_buffer = six.BytesIO()
kwargs = dict(
filename=path.basename(target_path),
mode='wb',
fileobj=data_buffer
)
if float(sys.version[:3]) >= 2.7:
kwargs['mtime'] = 0
with gzip.GzipFile(**kwargs) as f:
f.write(six.binary_type(html))
# Write that buffer out to the filesystem
with self.fs.open(smart_text(target_path), 'wb') as outfile:
outfile.write(data_buffer.getvalue())
outfile.close() | [
"def",
"gzip_file",
"(",
"self",
",",
"target_path",
",",
"html",
")",
":",
"logger",
".",
"debug",
"(",
"\"Gzipping to {}{}\"",
".",
"format",
"(",
"self",
".",
"fs_name",
",",
"target_path",
")",
")",
"# Write GZIP data to an in-memory buffer",
"data_buffer",
"=",
"six",
".",
"BytesIO",
"(",
")",
"kwargs",
"=",
"dict",
"(",
"filename",
"=",
"path",
".",
"basename",
"(",
"target_path",
")",
",",
"mode",
"=",
"'wb'",
",",
"fileobj",
"=",
"data_buffer",
")",
"if",
"float",
"(",
"sys",
".",
"version",
"[",
":",
"3",
"]",
")",
">=",
"2.7",
":",
"kwargs",
"[",
"'mtime'",
"]",
"=",
"0",
"with",
"gzip",
".",
"GzipFile",
"(",
"*",
"*",
"kwargs",
")",
"as",
"f",
":",
"f",
".",
"write",
"(",
"six",
".",
"binary_type",
"(",
"html",
")",
")",
"# Write that buffer out to the filesystem",
"with",
"self",
".",
"fs",
".",
"open",
"(",
"smart_text",
"(",
"target_path",
")",
",",
"'wb'",
")",
"as",
"outfile",
":",
"outfile",
".",
"write",
"(",
"data_buffer",
".",
"getvalue",
"(",
")",
")",
"outfile",
".",
"close",
"(",
")"
] | Zips up the provided HTML as a companion for the provided path.
Intended to take advantage of the peculiarities of
Amazon S3's GZIP service.
mtime, an option that writes a timestamp to the output file
is set to 0, to avoid having s3cmd do unnecessary uploads because
of differences in the timestamp | [
"Zips",
"up",
"the",
"provided",
"HTML",
"as",
"a",
"companion",
"for",
"the",
"provided",
"path",
"."
] | train | https://github.com/datadesk/django-bakery/blob/e2feb13a66552a388fbcfaaacdd504bba08d3c69/bakery/views/base.py#L97-L125 | [
"target_path",
"html"
] | What does this function do? | [
"Zips",
"up",
"the",
"provided",
"HTML",
"as",
"a",
"companion",
"for",
"the",
"provided",
"path",
"."
] |
datadesk/django-bakery | bakery/views/base.py | BuildableRedirectView.get_redirect_url | def get_redirect_url(self, *args, **kwargs):
"""
Return the URL redirect to. Keyword arguments from the
URL pattern match generating the redirect request
are provided as kwargs to this method.
"""
if self.url:
url = self.url % kwargs
elif self.pattern_name:
try:
url = reverse(self.pattern_name, args=args, kwargs=kwargs)
except NoReverseMatch:
return None
else:
return None
return url | python | def get_redirect_url(self, *args, **kwargs):
"""
Return the URL redirect to. Keyword arguments from the
URL pattern match generating the redirect request
are provided as kwargs to this method.
"""
if self.url:
url = self.url % kwargs
elif self.pattern_name:
try:
url = reverse(self.pattern_name, args=args, kwargs=kwargs)
except NoReverseMatch:
return None
else:
return None
return url | [
"def",
"get_redirect_url",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"self",
".",
"url",
":",
"url",
"=",
"self",
".",
"url",
"%",
"kwargs",
"elif",
"self",
".",
"pattern_name",
":",
"try",
":",
"url",
"=",
"reverse",
"(",
"self",
".",
"pattern_name",
",",
"args",
"=",
"args",
",",
"kwargs",
"=",
"kwargs",
")",
"except",
"NoReverseMatch",
":",
"return",
"None",
"else",
":",
"return",
"None",
"return",
"url"
] | Return the URL redirect to. Keyword arguments from the
URL pattern match generating the redirect request
are provided as kwargs to this method. | [
"Return",
"the",
"URL",
"redirect",
"to",
".",
"Keyword",
"arguments",
"from",
"the",
"URL",
"pattern",
"match",
"generating",
"the",
"redirect",
"request",
"are",
"provided",
"as",
"kwargs",
"to",
"this",
"method",
"."
] | train | https://github.com/datadesk/django-bakery/blob/e2feb13a66552a388fbcfaaacdd504bba08d3c69/bakery/views/base.py#L208-L223 | [
"args",
"kwargs"
] | What does this function do? | [
"Return",
"the",
"URL",
"redirect",
"to",
".",
"Keyword",
"arguments",
"from",
"the",
"URL",
"pattern",
"match",
"generating",
"the",
"redirect",
"request",
"are",
"provided",
"as",
"kwargs",
"to",
"this",
"method",
"."
] |
datadesk/django-bakery | bakery/models.py | BuildableModel.build | def build(self):
"""
Iterates through the views pointed to by self.detail_views, runs
build_object with `self`, and calls _build_extra()
and _build_related().
"""
for detail_view in self.detail_views:
view = self._get_view(detail_view)
view().build_object(self)
self._build_extra()
self._build_related() | python | def build(self):
"""
Iterates through the views pointed to by self.detail_views, runs
build_object with `self`, and calls _build_extra()
and _build_related().
"""
for detail_view in self.detail_views:
view = self._get_view(detail_view)
view().build_object(self)
self._build_extra()
self._build_related() | [
"def",
"build",
"(",
"self",
")",
":",
"for",
"detail_view",
"in",
"self",
".",
"detail_views",
":",
"view",
"=",
"self",
".",
"_get_view",
"(",
"detail_view",
")",
"view",
"(",
")",
".",
"build_object",
"(",
"self",
")",
"self",
".",
"_build_extra",
"(",
")",
"self",
".",
"_build_related",
"(",
")"
] | Iterates through the views pointed to by self.detail_views, runs
build_object with `self`, and calls _build_extra()
and _build_related(). | [
"Iterates",
"through",
"the",
"views",
"pointed",
"to",
"by",
"self",
".",
"detail_views",
"runs",
"build_object",
"with",
"self",
"and",
"calls",
"_build_extra",
"()",
"and",
"_build_related",
"()",
"."
] | train | https://github.com/datadesk/django-bakery/blob/e2feb13a66552a388fbcfaaacdd504bba08d3c69/bakery/models.py#L51-L61 | [] | What does this function do? | [
"Iterates",
"through",
"the",
"views",
"pointed",
"to",
"by",
"self",
".",
"detail_views",
"runs",
"build_object",
"with",
"self",
"and",
"calls",
"_build_extra",
"()",
"and",
"_build_related",
"()",
"."
] |
datadesk/django-bakery | bakery/models.py | BuildableModel.unbuild | def unbuild(self):
"""
Iterates through the views pointed to by self.detail_views, runs
unbuild_object with `self`, and calls _build_extra()
and _build_related().
"""
for detail_view in self.detail_views:
view = self._get_view(detail_view)
view().unbuild_object(self)
self._unbuild_extra()
# _build_related again to kill the object from RSS etc.
self._build_related() | python | def unbuild(self):
"""
Iterates through the views pointed to by self.detail_views, runs
unbuild_object with `self`, and calls _build_extra()
and _build_related().
"""
for detail_view in self.detail_views:
view = self._get_view(detail_view)
view().unbuild_object(self)
self._unbuild_extra()
# _build_related again to kill the object from RSS etc.
self._build_related() | [
"def",
"unbuild",
"(",
"self",
")",
":",
"for",
"detail_view",
"in",
"self",
".",
"detail_views",
":",
"view",
"=",
"self",
".",
"_get_view",
"(",
"detail_view",
")",
"view",
"(",
")",
".",
"unbuild_object",
"(",
"self",
")",
"self",
".",
"_unbuild_extra",
"(",
")",
"# _build_related again to kill the object from RSS etc.",
"self",
".",
"_build_related",
"(",
")"
] | Iterates through the views pointed to by self.detail_views, runs
unbuild_object with `self`, and calls _build_extra()
and _build_related(). | [
"Iterates",
"through",
"the",
"views",
"pointed",
"to",
"by",
"self",
".",
"detail_views",
"runs",
"unbuild_object",
"with",
"self",
"and",
"calls",
"_build_extra",
"()",
"and",
"_build_related",
"()",
"."
] | train | https://github.com/datadesk/django-bakery/blob/e2feb13a66552a388fbcfaaacdd504bba08d3c69/bakery/models.py#L63-L74 | [] | What does this function do? | [
"Iterates",
"through",
"the",
"views",
"pointed",
"to",
"by",
"self",
".",
"detail_views",
"runs",
"unbuild_object",
"with",
"self",
"and",
"calls",
"_build_extra",
"()",
"and",
"_build_related",
"()",
"."
] |
datadesk/django-bakery | bakery/models.py | AutoPublishingBuildableModel.save | def save(self, *args, **kwargs):
"""
A custom save that publishes or unpublishes the object where
appropriate.
Save with keyword argument obj.save(publish=False) to skip the process.
"""
from bakery import tasks
from django.contrib.contenttypes.models import ContentType
# if obj.save(publish=False) has been passed, we skip everything.
if not kwargs.pop('publish', True):
super(AutoPublishingBuildableModel, self).save(*args, **kwargs)
# Otherwise, for the standard obj.save(), here we go...
else:
# First figure out if the record is an addition, or an edit of
# a preexisting record.
try:
preexisting = self.__class__.objects.get(pk=self.pk)
except self.__class__.DoesNotExist:
preexisting = None
# If this is an addition...
if not preexisting:
# We will publish if that's the boolean
if self.get_publication_status():
action = 'publish'
# Otherwise we will do nothing do nothing
else:
action = None
# If this is an edit...
else:
# If it's being unpublished...
if not self.get_publication_status() and \
preexisting.get_publication_status():
action = 'unpublish'
# If it's being published...
elif self.get_publication_status():
action = 'publish'
# If it's remaining unpublished...
else:
action = None
# Now, no matter what, save it normally inside of a dedicated
# database transaction so that we are sure that the save will
# be complete before we trigger any task
with transaction.atomic():
super(AutoPublishingBuildableModel, self).save(*args, **kwargs)
# Finally, depending on the action, fire off a task
ct = ContentType.objects.get_for_model(self.__class__)
if action == 'publish':
tasks.publish_object.delay(ct.pk, self.pk)
elif action == 'unpublish':
tasks.unpublish_object.delay(ct.pk, self.pk) | python | def save(self, *args, **kwargs):
"""
A custom save that publishes or unpublishes the object where
appropriate.
Save with keyword argument obj.save(publish=False) to skip the process.
"""
from bakery import tasks
from django.contrib.contenttypes.models import ContentType
# if obj.save(publish=False) has been passed, we skip everything.
if not kwargs.pop('publish', True):
super(AutoPublishingBuildableModel, self).save(*args, **kwargs)
# Otherwise, for the standard obj.save(), here we go...
else:
# First figure out if the record is an addition, or an edit of
# a preexisting record.
try:
preexisting = self.__class__.objects.get(pk=self.pk)
except self.__class__.DoesNotExist:
preexisting = None
# If this is an addition...
if not preexisting:
# We will publish if that's the boolean
if self.get_publication_status():
action = 'publish'
# Otherwise we will do nothing do nothing
else:
action = None
# If this is an edit...
else:
# If it's being unpublished...
if not self.get_publication_status() and \
preexisting.get_publication_status():
action = 'unpublish'
# If it's being published...
elif self.get_publication_status():
action = 'publish'
# If it's remaining unpublished...
else:
action = None
# Now, no matter what, save it normally inside of a dedicated
# database transaction so that we are sure that the save will
# be complete before we trigger any task
with transaction.atomic():
super(AutoPublishingBuildableModel, self).save(*args, **kwargs)
# Finally, depending on the action, fire off a task
ct = ContentType.objects.get_for_model(self.__class__)
if action == 'publish':
tasks.publish_object.delay(ct.pk, self.pk)
elif action == 'unpublish':
tasks.unpublish_object.delay(ct.pk, self.pk) | [
"def",
"save",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"from",
"bakery",
"import",
"tasks",
"from",
"django",
".",
"contrib",
".",
"contenttypes",
".",
"models",
"import",
"ContentType",
"# if obj.save(publish=False) has been passed, we skip everything.",
"if",
"not",
"kwargs",
".",
"pop",
"(",
"'publish'",
",",
"True",
")",
":",
"super",
"(",
"AutoPublishingBuildableModel",
",",
"self",
")",
".",
"save",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"# Otherwise, for the standard obj.save(), here we go...",
"else",
":",
"# First figure out if the record is an addition, or an edit of",
"# a preexisting record.",
"try",
":",
"preexisting",
"=",
"self",
".",
"__class__",
".",
"objects",
".",
"get",
"(",
"pk",
"=",
"self",
".",
"pk",
")",
"except",
"self",
".",
"__class__",
".",
"DoesNotExist",
":",
"preexisting",
"=",
"None",
"# If this is an addition...",
"if",
"not",
"preexisting",
":",
"# We will publish if that's the boolean",
"if",
"self",
".",
"get_publication_status",
"(",
")",
":",
"action",
"=",
"'publish'",
"# Otherwise we will do nothing do nothing",
"else",
":",
"action",
"=",
"None",
"# If this is an edit...",
"else",
":",
"# If it's being unpublished...",
"if",
"not",
"self",
".",
"get_publication_status",
"(",
")",
"and",
"preexisting",
".",
"get_publication_status",
"(",
")",
":",
"action",
"=",
"'unpublish'",
"# If it's being published...",
"elif",
"self",
".",
"get_publication_status",
"(",
")",
":",
"action",
"=",
"'publish'",
"# If it's remaining unpublished...",
"else",
":",
"action",
"=",
"None",
"# Now, no matter what, save it normally inside of a dedicated",
"# database transaction so that we are sure that the save will",
"# be complete before we trigger any task",
"with",
"transaction",
".",
"atomic",
"(",
")",
":",
"super",
"(",
"AutoPublishingBuildableModel",
",",
"self",
")",
".",
"save",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"# Finally, depending on the action, fire off a task",
"ct",
"=",
"ContentType",
".",
"objects",
".",
"get_for_model",
"(",
"self",
".",
"__class__",
")",
"if",
"action",
"==",
"'publish'",
":",
"tasks",
".",
"publish_object",
".",
"delay",
"(",
"ct",
".",
"pk",
",",
"self",
".",
"pk",
")",
"elif",
"action",
"==",
"'unpublish'",
":",
"tasks",
".",
"unpublish_object",
".",
"delay",
"(",
"ct",
".",
"pk",
",",
"self",
".",
"pk",
")"
] | A custom save that publishes or unpublishes the object where
appropriate.
Save with keyword argument obj.save(publish=False) to skip the process. | [
"A",
"custom",
"save",
"that",
"publishes",
"or",
"unpublishes",
"the",
"object",
"where",
"appropriate",
"."
] | train | https://github.com/datadesk/django-bakery/blob/e2feb13a66552a388fbcfaaacdd504bba08d3c69/bakery/models.py#L117-L167 | [
"args",
"kwargs"
] | What does this function do? | [
"A",
"custom",
"save",
"that",
"publishes",
"or",
"unpublishes",
"the",
"object",
"where",
"appropriate",
"."
] |
datadesk/django-bakery | bakery/models.py | AutoPublishingBuildableModel.delete | def delete(self, *args, **kwargs):
"""
Triggers a task that will unpublish the object after it is deleted.
Save with keyword argument obj.delete(unpublish=False) to skip it.
"""
from bakery import tasks
from django.contrib.contenttypes.models import ContentType
# if obj.save(unpublish=False) has been passed, we skip the task.
unpublish = kwargs.pop('unpublish', True)
# Delete it from the database
super(AutoPublishingBuildableModel, self).delete(*args, **kwargs)
if unpublish:
ct = ContentType.objects.get_for_model(self.__class__)
tasks.unpublish_object.delay(ct.pk, self.pk) | python | def delete(self, *args, **kwargs):
"""
Triggers a task that will unpublish the object after it is deleted.
Save with keyword argument obj.delete(unpublish=False) to skip it.
"""
from bakery import tasks
from django.contrib.contenttypes.models import ContentType
# if obj.save(unpublish=False) has been passed, we skip the task.
unpublish = kwargs.pop('unpublish', True)
# Delete it from the database
super(AutoPublishingBuildableModel, self).delete(*args, **kwargs)
if unpublish:
ct = ContentType.objects.get_for_model(self.__class__)
tasks.unpublish_object.delay(ct.pk, self.pk) | [
"def",
"delete",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"from",
"bakery",
"import",
"tasks",
"from",
"django",
".",
"contrib",
".",
"contenttypes",
".",
"models",
"import",
"ContentType",
"# if obj.save(unpublish=False) has been passed, we skip the task.",
"unpublish",
"=",
"kwargs",
".",
"pop",
"(",
"'unpublish'",
",",
"True",
")",
"# Delete it from the database",
"super",
"(",
"AutoPublishingBuildableModel",
",",
"self",
")",
".",
"delete",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"if",
"unpublish",
":",
"ct",
"=",
"ContentType",
".",
"objects",
".",
"get_for_model",
"(",
"self",
".",
"__class__",
")",
"tasks",
".",
"unpublish_object",
".",
"delay",
"(",
"ct",
".",
"pk",
",",
"self",
".",
"pk",
")"
] | Triggers a task that will unpublish the object after it is deleted.
Save with keyword argument obj.delete(unpublish=False) to skip it. | [
"Triggers",
"a",
"task",
"that",
"will",
"unpublish",
"the",
"object",
"after",
"it",
"is",
"deleted",
"."
] | train | https://github.com/datadesk/django-bakery/blob/e2feb13a66552a388fbcfaaacdd504bba08d3c69/bakery/models.py#L169-L183 | [
"args",
"kwargs"
] | What does this function do? | [
"Triggers",
"a",
"task",
"that",
"will",
"unpublish",
"the",
"object",
"after",
"it",
"is",
"deleted",
"."
] |
datadesk/django-bakery | bakery/management/commands/build.py | Command.set_options | def set_options(self, *args, **options):
"""
Configure a few global options before things get going.
"""
self.verbosity = int(options.get('verbosity', 1))
# Figure out what build directory to use
if options.get("build_dir"):
self.build_dir = options.get("build_dir")
settings.BUILD_DIR = self.build_dir
else:
if not hasattr(settings, 'BUILD_DIR'):
raise CommandError(self.build_unconfig_msg)
self.build_dir = settings.BUILD_DIR
# Get the datatypes right so fs will be happy
self.build_dir = smart_text(self.build_dir)
self.static_root = smart_text(settings.STATIC_ROOT)
self.media_root = smart_text(settings.MEDIA_ROOT)
# Connect the BUILD_DIR with our filesystem backend
self.app = apps.get_app_config("bakery")
self.fs = self.app.filesystem
self.fs_name = self.app.filesystem_name
# If the build dir doesn't exist make it
if not self.fs.exists(self.build_dir):
self.fs.makedirs(self.build_dir)
# Figure out what views we'll be using
if options.get('view_list'):
self.view_list = options['view_list']
else:
if not hasattr(settings, 'BAKERY_VIEWS'):
raise CommandError(self.views_unconfig_msg)
self.view_list = settings.BAKERY_VIEWS
# Are we pooling?
self.pooling = options.get('pooling') | python | def set_options(self, *args, **options):
"""
Configure a few global options before things get going.
"""
self.verbosity = int(options.get('verbosity', 1))
# Figure out what build directory to use
if options.get("build_dir"):
self.build_dir = options.get("build_dir")
settings.BUILD_DIR = self.build_dir
else:
if not hasattr(settings, 'BUILD_DIR'):
raise CommandError(self.build_unconfig_msg)
self.build_dir = settings.BUILD_DIR
# Get the datatypes right so fs will be happy
self.build_dir = smart_text(self.build_dir)
self.static_root = smart_text(settings.STATIC_ROOT)
self.media_root = smart_text(settings.MEDIA_ROOT)
# Connect the BUILD_DIR with our filesystem backend
self.app = apps.get_app_config("bakery")
self.fs = self.app.filesystem
self.fs_name = self.app.filesystem_name
# If the build dir doesn't exist make it
if not self.fs.exists(self.build_dir):
self.fs.makedirs(self.build_dir)
# Figure out what views we'll be using
if options.get('view_list'):
self.view_list = options['view_list']
else:
if not hasattr(settings, 'BAKERY_VIEWS'):
raise CommandError(self.views_unconfig_msg)
self.view_list = settings.BAKERY_VIEWS
# Are we pooling?
self.pooling = options.get('pooling') | [
"def",
"set_options",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"options",
")",
":",
"self",
".",
"verbosity",
"=",
"int",
"(",
"options",
".",
"get",
"(",
"'verbosity'",
",",
"1",
")",
")",
"# Figure out what build directory to use",
"if",
"options",
".",
"get",
"(",
"\"build_dir\"",
")",
":",
"self",
".",
"build_dir",
"=",
"options",
".",
"get",
"(",
"\"build_dir\"",
")",
"settings",
".",
"BUILD_DIR",
"=",
"self",
".",
"build_dir",
"else",
":",
"if",
"not",
"hasattr",
"(",
"settings",
",",
"'BUILD_DIR'",
")",
":",
"raise",
"CommandError",
"(",
"self",
".",
"build_unconfig_msg",
")",
"self",
".",
"build_dir",
"=",
"settings",
".",
"BUILD_DIR",
"# Get the datatypes right so fs will be happy",
"self",
".",
"build_dir",
"=",
"smart_text",
"(",
"self",
".",
"build_dir",
")",
"self",
".",
"static_root",
"=",
"smart_text",
"(",
"settings",
".",
"STATIC_ROOT",
")",
"self",
".",
"media_root",
"=",
"smart_text",
"(",
"settings",
".",
"MEDIA_ROOT",
")",
"# Connect the BUILD_DIR with our filesystem backend",
"self",
".",
"app",
"=",
"apps",
".",
"get_app_config",
"(",
"\"bakery\"",
")",
"self",
".",
"fs",
"=",
"self",
".",
"app",
".",
"filesystem",
"self",
".",
"fs_name",
"=",
"self",
".",
"app",
".",
"filesystem_name",
"# If the build dir doesn't exist make it",
"if",
"not",
"self",
".",
"fs",
".",
"exists",
"(",
"self",
".",
"build_dir",
")",
":",
"self",
".",
"fs",
".",
"makedirs",
"(",
"self",
".",
"build_dir",
")",
"# Figure out what views we'll be using",
"if",
"options",
".",
"get",
"(",
"'view_list'",
")",
":",
"self",
".",
"view_list",
"=",
"options",
"[",
"'view_list'",
"]",
"else",
":",
"if",
"not",
"hasattr",
"(",
"settings",
",",
"'BAKERY_VIEWS'",
")",
":",
"raise",
"CommandError",
"(",
"self",
".",
"views_unconfig_msg",
")",
"self",
".",
"view_list",
"=",
"settings",
".",
"BAKERY_VIEWS",
"# Are we pooling?",
"self",
".",
"pooling",
"=",
"options",
".",
"get",
"(",
"'pooling'",
")"
] | Configure a few global options before things get going. | [
"Configure",
"a",
"few",
"global",
"options",
"before",
"things",
"get",
"going",
"."
] | train | https://github.com/datadesk/django-bakery/blob/e2feb13a66552a388fbcfaaacdd504bba08d3c69/bakery/management/commands/build.py#L117-L155 | [
"args",
"options"
] | What does this function do? | [
"Configure",
"a",
"few",
"global",
"options",
"before",
"things",
"get",
"going",
"."
] |
datadesk/django-bakery | bakery/management/commands/build.py | Command.init_build_dir | def init_build_dir(self):
"""
Clear out the build directory and create a new one.
"""
# Destroy the build directory, if it exists
logger.debug("Initializing %s" % self.build_dir)
if self.verbosity > 1:
self.stdout.write("Initializing build directory")
if self.fs.exists(self.build_dir):
self.fs.removetree(self.build_dir)
# Then recreate it from scratch
self.fs.makedirs(self.build_dir) | python | def init_build_dir(self):
"""
Clear out the build directory and create a new one.
"""
# Destroy the build directory, if it exists
logger.debug("Initializing %s" % self.build_dir)
if self.verbosity > 1:
self.stdout.write("Initializing build directory")
if self.fs.exists(self.build_dir):
self.fs.removetree(self.build_dir)
# Then recreate it from scratch
self.fs.makedirs(self.build_dir) | [
"def",
"init_build_dir",
"(",
"self",
")",
":",
"# Destroy the build directory, if it exists",
"logger",
".",
"debug",
"(",
"\"Initializing %s\"",
"%",
"self",
".",
"build_dir",
")",
"if",
"self",
".",
"verbosity",
">",
"1",
":",
"self",
".",
"stdout",
".",
"write",
"(",
"\"Initializing build directory\"",
")",
"if",
"self",
".",
"fs",
".",
"exists",
"(",
"self",
".",
"build_dir",
")",
":",
"self",
".",
"fs",
".",
"removetree",
"(",
"self",
".",
"build_dir",
")",
"# Then recreate it from scratch",
"self",
".",
"fs",
".",
"makedirs",
"(",
"self",
".",
"build_dir",
")"
] | Clear out the build directory and create a new one. | [
"Clear",
"out",
"the",
"build",
"directory",
"and",
"create",
"a",
"new",
"one",
"."
] | train | https://github.com/datadesk/django-bakery/blob/e2feb13a66552a388fbcfaaacdd504bba08d3c69/bakery/management/commands/build.py#L157-L168 | [] | What does this function do? | [
"Clear",
"out",
"the",
"build",
"directory",
"and",
"create",
"a",
"new",
"one",
"."
] |
datadesk/django-bakery | bakery/management/commands/build.py | Command.build_static | def build_static(self, *args, **options):
"""
Builds the static files directory as well as robots.txt and favicon.ico
"""
logger.debug("Building static directory")
if self.verbosity > 1:
self.stdout.write("Building static directory")
management.call_command(
"collectstatic",
interactive=False,
verbosity=0
)
# Set the target directory inside the filesystem.
target_dir = path.join(
self.build_dir,
settings.STATIC_URL.lstrip('/')
)
target_dir = smart_text(target_dir)
if os.path.exists(self.static_root) and settings.STATIC_URL:
if getattr(settings, 'BAKERY_GZIP', False):
self.copytree_and_gzip(self.static_root, target_dir)
# if gzip isn't enabled, just copy the tree straight over
else:
logger.debug("Copying {}{} to {}{}".format("osfs://", self.static_root, self.fs_name, target_dir))
copy.copy_dir("osfs:///", self.static_root, self.fs, target_dir)
# If they exist in the static directory, copy the robots.txt
# and favicon.ico files down to the root so they will work
# on the live website.
robots_src = path.join(target_dir, 'robots.txt')
if self.fs.exists(robots_src):
robots_target = path.join(self.build_dir, 'robots.txt')
logger.debug("Copying {}{} to {}{}".format(self.fs_name, robots_src, self.fs_name, robots_target))
self.fs.copy(robots_src, robots_target)
favicon_src = path.join(target_dir, 'favicon.ico')
if self.fs.exists(favicon_src):
favicon_target = path.join(self.build_dir, 'favicon.ico')
logger.debug("Copying {}{} to {}{}".format(self.fs_name, favicon_src, self.fs_name, favicon_target))
self.fs.copy(favicon_src, favicon_target) | python | def build_static(self, *args, **options):
"""
Builds the static files directory as well as robots.txt and favicon.ico
"""
logger.debug("Building static directory")
if self.verbosity > 1:
self.stdout.write("Building static directory")
management.call_command(
"collectstatic",
interactive=False,
verbosity=0
)
# Set the target directory inside the filesystem.
target_dir = path.join(
self.build_dir,
settings.STATIC_URL.lstrip('/')
)
target_dir = smart_text(target_dir)
if os.path.exists(self.static_root) and settings.STATIC_URL:
if getattr(settings, 'BAKERY_GZIP', False):
self.copytree_and_gzip(self.static_root, target_dir)
# if gzip isn't enabled, just copy the tree straight over
else:
logger.debug("Copying {}{} to {}{}".format("osfs://", self.static_root, self.fs_name, target_dir))
copy.copy_dir("osfs:///", self.static_root, self.fs, target_dir)
# If they exist in the static directory, copy the robots.txt
# and favicon.ico files down to the root so they will work
# on the live website.
robots_src = path.join(target_dir, 'robots.txt')
if self.fs.exists(robots_src):
robots_target = path.join(self.build_dir, 'robots.txt')
logger.debug("Copying {}{} to {}{}".format(self.fs_name, robots_src, self.fs_name, robots_target))
self.fs.copy(robots_src, robots_target)
favicon_src = path.join(target_dir, 'favicon.ico')
if self.fs.exists(favicon_src):
favicon_target = path.join(self.build_dir, 'favicon.ico')
logger.debug("Copying {}{} to {}{}".format(self.fs_name, favicon_src, self.fs_name, favicon_target))
self.fs.copy(favicon_src, favicon_target) | [
"def",
"build_static",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"options",
")",
":",
"logger",
".",
"debug",
"(",
"\"Building static directory\"",
")",
"if",
"self",
".",
"verbosity",
">",
"1",
":",
"self",
".",
"stdout",
".",
"write",
"(",
"\"Building static directory\"",
")",
"management",
".",
"call_command",
"(",
"\"collectstatic\"",
",",
"interactive",
"=",
"False",
",",
"verbosity",
"=",
"0",
")",
"# Set the target directory inside the filesystem.",
"target_dir",
"=",
"path",
".",
"join",
"(",
"self",
".",
"build_dir",
",",
"settings",
".",
"STATIC_URL",
".",
"lstrip",
"(",
"'/'",
")",
")",
"target_dir",
"=",
"smart_text",
"(",
"target_dir",
")",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"self",
".",
"static_root",
")",
"and",
"settings",
".",
"STATIC_URL",
":",
"if",
"getattr",
"(",
"settings",
",",
"'BAKERY_GZIP'",
",",
"False",
")",
":",
"self",
".",
"copytree_and_gzip",
"(",
"self",
".",
"static_root",
",",
"target_dir",
")",
"# if gzip isn't enabled, just copy the tree straight over",
"else",
":",
"logger",
".",
"debug",
"(",
"\"Copying {}{} to {}{}\"",
".",
"format",
"(",
"\"osfs://\"",
",",
"self",
".",
"static_root",
",",
"self",
".",
"fs_name",
",",
"target_dir",
")",
")",
"copy",
".",
"copy_dir",
"(",
"\"osfs:///\"",
",",
"self",
".",
"static_root",
",",
"self",
".",
"fs",
",",
"target_dir",
")",
"# If they exist in the static directory, copy the robots.txt",
"# and favicon.ico files down to the root so they will work",
"# on the live website.",
"robots_src",
"=",
"path",
".",
"join",
"(",
"target_dir",
",",
"'robots.txt'",
")",
"if",
"self",
".",
"fs",
".",
"exists",
"(",
"robots_src",
")",
":",
"robots_target",
"=",
"path",
".",
"join",
"(",
"self",
".",
"build_dir",
",",
"'robots.txt'",
")",
"logger",
".",
"debug",
"(",
"\"Copying {}{} to {}{}\"",
".",
"format",
"(",
"self",
".",
"fs_name",
",",
"robots_src",
",",
"self",
".",
"fs_name",
",",
"robots_target",
")",
")",
"self",
".",
"fs",
".",
"copy",
"(",
"robots_src",
",",
"robots_target",
")",
"favicon_src",
"=",
"path",
".",
"join",
"(",
"target_dir",
",",
"'favicon.ico'",
")",
"if",
"self",
".",
"fs",
".",
"exists",
"(",
"favicon_src",
")",
":",
"favicon_target",
"=",
"path",
".",
"join",
"(",
"self",
".",
"build_dir",
",",
"'favicon.ico'",
")",
"logger",
".",
"debug",
"(",
"\"Copying {}{} to {}{}\"",
".",
"format",
"(",
"self",
".",
"fs_name",
",",
"favicon_src",
",",
"self",
".",
"fs_name",
",",
"favicon_target",
")",
")",
"self",
".",
"fs",
".",
"copy",
"(",
"favicon_src",
",",
"favicon_target",
")"
] | Builds the static files directory as well as robots.txt and favicon.ico | [
"Builds",
"the",
"static",
"files",
"directory",
"as",
"well",
"as",
"robots",
".",
"txt",
"and",
"favicon",
".",
"ico"
] | train | https://github.com/datadesk/django-bakery/blob/e2feb13a66552a388fbcfaaacdd504bba08d3c69/bakery/management/commands/build.py#L170-L211 | [
"args",
"options"
] | What does this function do? | [
"Builds",
"the",
"static",
"files",
"directory",
"as",
"well",
"as",
"robots",
".",
"txt",
"and",
"favicon",
".",
"ico"
] |
datadesk/django-bakery | bakery/management/commands/build.py | Command.build_media | def build_media(self):
"""
Build the media files.
"""
logger.debug("Building media directory")
if self.verbosity > 1:
self.stdout.write("Building media directory")
if os.path.exists(self.media_root) and settings.MEDIA_URL:
target_dir = path.join(self.fs_name, self.build_dir, settings.MEDIA_URL.lstrip('/'))
logger.debug("Copying {}{} to {}{}".format("osfs://", self.media_root, self.fs_name, target_dir))
copy.copy_dir("osfs:///", smart_text(self.media_root), self.fs, smart_text(target_dir)) | python | def build_media(self):
"""
Build the media files.
"""
logger.debug("Building media directory")
if self.verbosity > 1:
self.stdout.write("Building media directory")
if os.path.exists(self.media_root) and settings.MEDIA_URL:
target_dir = path.join(self.fs_name, self.build_dir, settings.MEDIA_URL.lstrip('/'))
logger.debug("Copying {}{} to {}{}".format("osfs://", self.media_root, self.fs_name, target_dir))
copy.copy_dir("osfs:///", smart_text(self.media_root), self.fs, smart_text(target_dir)) | [
"def",
"build_media",
"(",
"self",
")",
":",
"logger",
".",
"debug",
"(",
"\"Building media directory\"",
")",
"if",
"self",
".",
"verbosity",
">",
"1",
":",
"self",
".",
"stdout",
".",
"write",
"(",
"\"Building media directory\"",
")",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"self",
".",
"media_root",
")",
"and",
"settings",
".",
"MEDIA_URL",
":",
"target_dir",
"=",
"path",
".",
"join",
"(",
"self",
".",
"fs_name",
",",
"self",
".",
"build_dir",
",",
"settings",
".",
"MEDIA_URL",
".",
"lstrip",
"(",
"'/'",
")",
")",
"logger",
".",
"debug",
"(",
"\"Copying {}{} to {}{}\"",
".",
"format",
"(",
"\"osfs://\"",
",",
"self",
".",
"media_root",
",",
"self",
".",
"fs_name",
",",
"target_dir",
")",
")",
"copy",
".",
"copy_dir",
"(",
"\"osfs:///\"",
",",
"smart_text",
"(",
"self",
".",
"media_root",
")",
",",
"self",
".",
"fs",
",",
"smart_text",
"(",
"target_dir",
")",
")"
] | Build the media files. | [
"Build",
"the",
"media",
"files",
"."
] | train | https://github.com/datadesk/django-bakery/blob/e2feb13a66552a388fbcfaaacdd504bba08d3c69/bakery/management/commands/build.py#L213-L223 | [] | What does this function do? | [
"Build",
"the",
"media",
"files",
"."
] |
datadesk/django-bakery | bakery/management/commands/build.py | Command.build_views | def build_views(self):
"""
Bake out specified buildable views.
"""
# Then loop through and run them all
for view_str in self.view_list:
logger.debug("Building %s" % view_str)
if self.verbosity > 1:
self.stdout.write("Building %s" % view_str)
view = get_callable(view_str)
self.get_view_instance(view).build_method() | python | def build_views(self):
"""
Bake out specified buildable views.
"""
# Then loop through and run them all
for view_str in self.view_list:
logger.debug("Building %s" % view_str)
if self.verbosity > 1:
self.stdout.write("Building %s" % view_str)
view = get_callable(view_str)
self.get_view_instance(view).build_method() | [
"def",
"build_views",
"(",
"self",
")",
":",
"# Then loop through and run them all",
"for",
"view_str",
"in",
"self",
".",
"view_list",
":",
"logger",
".",
"debug",
"(",
"\"Building %s\"",
"%",
"view_str",
")",
"if",
"self",
".",
"verbosity",
">",
"1",
":",
"self",
".",
"stdout",
".",
"write",
"(",
"\"Building %s\"",
"%",
"view_str",
")",
"view",
"=",
"get_callable",
"(",
"view_str",
")",
"self",
".",
"get_view_instance",
"(",
"view",
")",
".",
"build_method",
"(",
")"
] | Bake out specified buildable views. | [
"Bake",
"out",
"specified",
"buildable",
"views",
"."
] | train | https://github.com/datadesk/django-bakery/blob/e2feb13a66552a388fbcfaaacdd504bba08d3c69/bakery/management/commands/build.py#L231-L241 | [] | What does this function do? | [
"Bake",
"out",
"specified",
"buildable",
"views",
"."
] |
datadesk/django-bakery | bakery/management/commands/build.py | Command.copytree_and_gzip | def copytree_and_gzip(self, source_dir, target_dir):
"""
Copies the provided source directory to the provided target directory.
Gzips JavaScript, CSS and HTML and other files along the way.
"""
# Figure out what we're building...
build_list = []
# Walk through the source directory...
for (dirpath, dirnames, filenames) in os.walk(source_dir):
for f in filenames:
# Figure out what is going where
source_path = os.path.join(dirpath, f)
rel_path = os.path.relpath(dirpath, source_dir)
target_path = os.path.join(target_dir, rel_path, f)
# Add it to our list to build
build_list.append((source_path, target_path))
logger.debug("Gzipping {} files".format(len(build_list)))
# Build em all
if not getattr(self, 'pooling', False):
[self.copyfile_and_gzip(*u) for u in build_list]
else:
cpu_count = multiprocessing.cpu_count()
logger.debug("Pooling build on {} CPUs".format(cpu_count))
pool = ThreadPool(processes=cpu_count)
pool.map(self.pooled_copyfile_and_gzip, build_list) | python | def copytree_and_gzip(self, source_dir, target_dir):
"""
Copies the provided source directory to the provided target directory.
Gzips JavaScript, CSS and HTML and other files along the way.
"""
# Figure out what we're building...
build_list = []
# Walk through the source directory...
for (dirpath, dirnames, filenames) in os.walk(source_dir):
for f in filenames:
# Figure out what is going where
source_path = os.path.join(dirpath, f)
rel_path = os.path.relpath(dirpath, source_dir)
target_path = os.path.join(target_dir, rel_path, f)
# Add it to our list to build
build_list.append((source_path, target_path))
logger.debug("Gzipping {} files".format(len(build_list)))
# Build em all
if not getattr(self, 'pooling', False):
[self.copyfile_and_gzip(*u) for u in build_list]
else:
cpu_count = multiprocessing.cpu_count()
logger.debug("Pooling build on {} CPUs".format(cpu_count))
pool = ThreadPool(processes=cpu_count)
pool.map(self.pooled_copyfile_and_gzip, build_list) | [
"def",
"copytree_and_gzip",
"(",
"self",
",",
"source_dir",
",",
"target_dir",
")",
":",
"# Figure out what we're building...",
"build_list",
"=",
"[",
"]",
"# Walk through the source directory...",
"for",
"(",
"dirpath",
",",
"dirnames",
",",
"filenames",
")",
"in",
"os",
".",
"walk",
"(",
"source_dir",
")",
":",
"for",
"f",
"in",
"filenames",
":",
"# Figure out what is going where",
"source_path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"dirpath",
",",
"f",
")",
"rel_path",
"=",
"os",
".",
"path",
".",
"relpath",
"(",
"dirpath",
",",
"source_dir",
")",
"target_path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"target_dir",
",",
"rel_path",
",",
"f",
")",
"# Add it to our list to build",
"build_list",
".",
"append",
"(",
"(",
"source_path",
",",
"target_path",
")",
")",
"logger",
".",
"debug",
"(",
"\"Gzipping {} files\"",
".",
"format",
"(",
"len",
"(",
"build_list",
")",
")",
")",
"# Build em all",
"if",
"not",
"getattr",
"(",
"self",
",",
"'pooling'",
",",
"False",
")",
":",
"[",
"self",
".",
"copyfile_and_gzip",
"(",
"*",
"u",
")",
"for",
"u",
"in",
"build_list",
"]",
"else",
":",
"cpu_count",
"=",
"multiprocessing",
".",
"cpu_count",
"(",
")",
"logger",
".",
"debug",
"(",
"\"Pooling build on {} CPUs\"",
".",
"format",
"(",
"cpu_count",
")",
")",
"pool",
"=",
"ThreadPool",
"(",
"processes",
"=",
"cpu_count",
")",
"pool",
".",
"map",
"(",
"self",
".",
"pooled_copyfile_and_gzip",
",",
"build_list",
")"
] | Copies the provided source directory to the provided target directory.
Gzips JavaScript, CSS and HTML and other files along the way. | [
"Copies",
"the",
"provided",
"source",
"directory",
"to",
"the",
"provided",
"target",
"directory",
"."
] | train | https://github.com/datadesk/django-bakery/blob/e2feb13a66552a388fbcfaaacdd504bba08d3c69/bakery/management/commands/build.py#L243-L270 | [
"source_dir",
"target_dir"
] | What does this function do? | [
"Copies",
"the",
"provided",
"source",
"directory",
"to",
"the",
"provided",
"target",
"directory",
"."
] |