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
sequencelengths
15
672k
func_documentation_string
stringlengths
1
47.2k
func_documentation_tokens
sequencelengths
1
3.92k
split_name
stringclasses
1 value
func_code_url
stringlengths
85
339
gtaylor/python-colormath
colormath/chromatic_adaptation.py
_get_adaptation_matrix
def _get_adaptation_matrix(wp_src, wp_dst, observer, adaptation): """ Calculate the correct transformation matrix based on origin and target illuminants. The observer angle must be the same between illuminants. See colormath.color_constants.ADAPTATION_MATRICES for a list of possible adaptations. Detailed conversion documentation is available at: http://brucelindbloom.com/Eqn_ChromAdapt.html """ # Get the appropriate transformation matrix, [MsubA]. m_sharp = color_constants.ADAPTATION_MATRICES[adaptation] # In case the white-points are still input as strings # Get white-points for illuminant if isinstance(wp_src, str): orig_illum = wp_src.lower() wp_src = color_constants.ILLUMINANTS[observer][orig_illum] elif hasattr(wp_src, '__iter__'): wp_src = wp_src if isinstance(wp_dst, str): targ_illum = wp_dst.lower() wp_dst = color_constants.ILLUMINANTS[observer][targ_illum] elif hasattr(wp_dst, '__iter__'): wp_dst = wp_dst # Sharpened cone responses ~ rho gamma beta ~ sharpened r g b rgb_src = numpy.dot(m_sharp, wp_src) rgb_dst = numpy.dot(m_sharp, wp_dst) # Ratio of whitepoint sharpened responses m_rat = numpy.diag(rgb_dst / rgb_src) # Final transformation matrix m_xfm = numpy.dot(numpy.dot(pinv(m_sharp), m_rat), m_sharp) return m_xfm
python
def _get_adaptation_matrix(wp_src, wp_dst, observer, adaptation): """ Calculate the correct transformation matrix based on origin and target illuminants. The observer angle must be the same between illuminants. See colormath.color_constants.ADAPTATION_MATRICES for a list of possible adaptations. Detailed conversion documentation is available at: http://brucelindbloom.com/Eqn_ChromAdapt.html """ # Get the appropriate transformation matrix, [MsubA]. m_sharp = color_constants.ADAPTATION_MATRICES[adaptation] # In case the white-points are still input as strings # Get white-points for illuminant if isinstance(wp_src, str): orig_illum = wp_src.lower() wp_src = color_constants.ILLUMINANTS[observer][orig_illum] elif hasattr(wp_src, '__iter__'): wp_src = wp_src if isinstance(wp_dst, str): targ_illum = wp_dst.lower() wp_dst = color_constants.ILLUMINANTS[observer][targ_illum] elif hasattr(wp_dst, '__iter__'): wp_dst = wp_dst # Sharpened cone responses ~ rho gamma beta ~ sharpened r g b rgb_src = numpy.dot(m_sharp, wp_src) rgb_dst = numpy.dot(m_sharp, wp_dst) # Ratio of whitepoint sharpened responses m_rat = numpy.diag(rgb_dst / rgb_src) # Final transformation matrix m_xfm = numpy.dot(numpy.dot(pinv(m_sharp), m_rat), m_sharp) return m_xfm
[ "def", "_get_adaptation_matrix", "(", "wp_src", ",", "wp_dst", ",", "observer", ",", "adaptation", ")", ":", "# Get the appropriate transformation matrix, [MsubA].", "m_sharp", "=", "color_constants", ".", "ADAPTATION_MATRICES", "[", "adaptation", "]", "# In case the white-points are still input as strings", "# Get white-points for illuminant", "if", "isinstance", "(", "wp_src", ",", "str", ")", ":", "orig_illum", "=", "wp_src", ".", "lower", "(", ")", "wp_src", "=", "color_constants", ".", "ILLUMINANTS", "[", "observer", "]", "[", "orig_illum", "]", "elif", "hasattr", "(", "wp_src", ",", "'__iter__'", ")", ":", "wp_src", "=", "wp_src", "if", "isinstance", "(", "wp_dst", ",", "str", ")", ":", "targ_illum", "=", "wp_dst", ".", "lower", "(", ")", "wp_dst", "=", "color_constants", ".", "ILLUMINANTS", "[", "observer", "]", "[", "targ_illum", "]", "elif", "hasattr", "(", "wp_dst", ",", "'__iter__'", ")", ":", "wp_dst", "=", "wp_dst", "# Sharpened cone responses ~ rho gamma beta ~ sharpened r g b", "rgb_src", "=", "numpy", ".", "dot", "(", "m_sharp", ",", "wp_src", ")", "rgb_dst", "=", "numpy", ".", "dot", "(", "m_sharp", ",", "wp_dst", ")", "# Ratio of whitepoint sharpened responses", "m_rat", "=", "numpy", ".", "diag", "(", "rgb_dst", "/", "rgb_src", ")", "# Final transformation matrix", "m_xfm", "=", "numpy", ".", "dot", "(", "numpy", ".", "dot", "(", "pinv", "(", "m_sharp", ")", ",", "m_rat", ")", ",", "m_sharp", ")", "return", "m_xfm" ]
Calculate the correct transformation matrix based on origin and target illuminants. The observer angle must be the same between illuminants. See colormath.color_constants.ADAPTATION_MATRICES for a list of possible adaptations. Detailed conversion documentation is available at: http://brucelindbloom.com/Eqn_ChromAdapt.html
[ "Calculate", "the", "correct", "transformation", "matrix", "based", "on", "origin", "and", "target", "illuminants", ".", "The", "observer", "angle", "must", "be", "the", "same", "between", "illuminants", "." ]
train
https://github.com/gtaylor/python-colormath/blob/1d168613718d2d7d31ec4230524e987ef66823c7/colormath/chromatic_adaptation.py#L13-L51
gtaylor/python-colormath
colormath/chromatic_adaptation.py
apply_chromatic_adaptation
def apply_chromatic_adaptation(val_x, val_y, val_z, orig_illum, targ_illum, observer='2', adaptation='bradford'): """ Applies a chromatic adaptation matrix to convert XYZ values between illuminants. It is important to recognize that color transformation results in color errors, determined by how far the original illuminant is from the target illuminant. For example, D65 to A could result in very high maximum deviance. An informative article with estimate average Delta E values for each illuminant conversion may be found at: http://brucelindbloom.com/ChromAdaptEval.html """ # It's silly to have to do this, but some people may want to call this # function directly, so we'll protect them from messing up upper/lower case. adaptation = adaptation.lower() # Get white-points for illuminant if isinstance(orig_illum, str): orig_illum = orig_illum.lower() wp_src = color_constants.ILLUMINANTS[observer][orig_illum] elif hasattr(orig_illum, '__iter__'): wp_src = orig_illum if isinstance(targ_illum, str): targ_illum = targ_illum.lower() wp_dst = color_constants.ILLUMINANTS[observer][targ_illum] elif hasattr(targ_illum, '__iter__'): wp_dst = targ_illum logger.debug(" \* Applying adaptation matrix: %s", adaptation) # Retrieve the appropriate transformation matrix from the constants. transform_matrix = _get_adaptation_matrix(wp_src, wp_dst, observer, adaptation) # Stuff the XYZ values into a NumPy matrix for conversion. XYZ_matrix = numpy.array((val_x, val_y, val_z)) # Perform the adaptation via matrix multiplication. result_matrix = numpy.dot(transform_matrix, XYZ_matrix) # Return individual X, Y, and Z coordinates. return result_matrix[0], result_matrix[1], result_matrix[2]
python
def apply_chromatic_adaptation(val_x, val_y, val_z, orig_illum, targ_illum, observer='2', adaptation='bradford'): """ Applies a chromatic adaptation matrix to convert XYZ values between illuminants. It is important to recognize that color transformation results in color errors, determined by how far the original illuminant is from the target illuminant. For example, D65 to A could result in very high maximum deviance. An informative article with estimate average Delta E values for each illuminant conversion may be found at: http://brucelindbloom.com/ChromAdaptEval.html """ # It's silly to have to do this, but some people may want to call this # function directly, so we'll protect them from messing up upper/lower case. adaptation = adaptation.lower() # Get white-points for illuminant if isinstance(orig_illum, str): orig_illum = orig_illum.lower() wp_src = color_constants.ILLUMINANTS[observer][orig_illum] elif hasattr(orig_illum, '__iter__'): wp_src = orig_illum if isinstance(targ_illum, str): targ_illum = targ_illum.lower() wp_dst = color_constants.ILLUMINANTS[observer][targ_illum] elif hasattr(targ_illum, '__iter__'): wp_dst = targ_illum logger.debug(" \* Applying adaptation matrix: %s", adaptation) # Retrieve the appropriate transformation matrix from the constants. transform_matrix = _get_adaptation_matrix(wp_src, wp_dst, observer, adaptation) # Stuff the XYZ values into a NumPy matrix for conversion. XYZ_matrix = numpy.array((val_x, val_y, val_z)) # Perform the adaptation via matrix multiplication. result_matrix = numpy.dot(transform_matrix, XYZ_matrix) # Return individual X, Y, and Z coordinates. return result_matrix[0], result_matrix[1], result_matrix[2]
[ "def", "apply_chromatic_adaptation", "(", "val_x", ",", "val_y", ",", "val_z", ",", "orig_illum", ",", "targ_illum", ",", "observer", "=", "'2'", ",", "adaptation", "=", "'bradford'", ")", ":", "# It's silly to have to do this, but some people may want to call this", "# function directly, so we'll protect them from messing up upper/lower case.", "adaptation", "=", "adaptation", ".", "lower", "(", ")", "# Get white-points for illuminant", "if", "isinstance", "(", "orig_illum", ",", "str", ")", ":", "orig_illum", "=", "orig_illum", ".", "lower", "(", ")", "wp_src", "=", "color_constants", ".", "ILLUMINANTS", "[", "observer", "]", "[", "orig_illum", "]", "elif", "hasattr", "(", "orig_illum", ",", "'__iter__'", ")", ":", "wp_src", "=", "orig_illum", "if", "isinstance", "(", "targ_illum", ",", "str", ")", ":", "targ_illum", "=", "targ_illum", ".", "lower", "(", ")", "wp_dst", "=", "color_constants", ".", "ILLUMINANTS", "[", "observer", "]", "[", "targ_illum", "]", "elif", "hasattr", "(", "targ_illum", ",", "'__iter__'", ")", ":", "wp_dst", "=", "targ_illum", "logger", ".", "debug", "(", "\" \\* Applying adaptation matrix: %s\"", ",", "adaptation", ")", "# Retrieve the appropriate transformation matrix from the constants.", "transform_matrix", "=", "_get_adaptation_matrix", "(", "wp_src", ",", "wp_dst", ",", "observer", ",", "adaptation", ")", "# Stuff the XYZ values into a NumPy matrix for conversion.", "XYZ_matrix", "=", "numpy", ".", "array", "(", "(", "val_x", ",", "val_y", ",", "val_z", ")", ")", "# Perform the adaptation via matrix multiplication.", "result_matrix", "=", "numpy", ".", "dot", "(", "transform_matrix", ",", "XYZ_matrix", ")", "# Return individual X, Y, and Z coordinates.", "return", "result_matrix", "[", "0", "]", ",", "result_matrix", "[", "1", "]", ",", "result_matrix", "[", "2", "]" ]
Applies a chromatic adaptation matrix to convert XYZ values between illuminants. It is important to recognize that color transformation results in color errors, determined by how far the original illuminant is from the target illuminant. For example, D65 to A could result in very high maximum deviance. An informative article with estimate average Delta E values for each illuminant conversion may be found at: http://brucelindbloom.com/ChromAdaptEval.html
[ "Applies", "a", "chromatic", "adaptation", "matrix", "to", "convert", "XYZ", "values", "between", "illuminants", ".", "It", "is", "important", "to", "recognize", "that", "color", "transformation", "results", "in", "color", "errors", "determined", "by", "how", "far", "the", "original", "illuminant", "is", "from", "the", "target", "illuminant", ".", "For", "example", "D65", "to", "A", "could", "result", "in", "very", "high", "maximum", "deviance", "." ]
train
https://github.com/gtaylor/python-colormath/blob/1d168613718d2d7d31ec4230524e987ef66823c7/colormath/chromatic_adaptation.py#L55-L97
gtaylor/python-colormath
colormath/chromatic_adaptation.py
apply_chromatic_adaptation_on_color
def apply_chromatic_adaptation_on_color(color, targ_illum, adaptation='bradford'): """ Convenience function to apply an adaptation directly to a Color object. """ xyz_x = color.xyz_x xyz_y = color.xyz_y xyz_z = color.xyz_z orig_illum = color.illuminant targ_illum = targ_illum.lower() observer = color.observer adaptation = adaptation.lower() # Return individual X, Y, and Z coordinates. color.xyz_x, color.xyz_y, color.xyz_z = apply_chromatic_adaptation( xyz_x, xyz_y, xyz_z, orig_illum, targ_illum, observer=observer, adaptation=adaptation) color.set_illuminant(targ_illum) return color
python
def apply_chromatic_adaptation_on_color(color, targ_illum, adaptation='bradford'): """ Convenience function to apply an adaptation directly to a Color object. """ xyz_x = color.xyz_x xyz_y = color.xyz_y xyz_z = color.xyz_z orig_illum = color.illuminant targ_illum = targ_illum.lower() observer = color.observer adaptation = adaptation.lower() # Return individual X, Y, and Z coordinates. color.xyz_x, color.xyz_y, color.xyz_z = apply_chromatic_adaptation( xyz_x, xyz_y, xyz_z, orig_illum, targ_illum, observer=observer, adaptation=adaptation) color.set_illuminant(targ_illum) return color
[ "def", "apply_chromatic_adaptation_on_color", "(", "color", ",", "targ_illum", ",", "adaptation", "=", "'bradford'", ")", ":", "xyz_x", "=", "color", ".", "xyz_x", "xyz_y", "=", "color", ".", "xyz_y", "xyz_z", "=", "color", ".", "xyz_z", "orig_illum", "=", "color", ".", "illuminant", "targ_illum", "=", "targ_illum", ".", "lower", "(", ")", "observer", "=", "color", ".", "observer", "adaptation", "=", "adaptation", ".", "lower", "(", ")", "# Return individual X, Y, and Z coordinates.", "color", ".", "xyz_x", ",", "color", ".", "xyz_y", ",", "color", ".", "xyz_z", "=", "apply_chromatic_adaptation", "(", "xyz_x", ",", "xyz_y", ",", "xyz_z", ",", "orig_illum", ",", "targ_illum", ",", "observer", "=", "observer", ",", "adaptation", "=", "adaptation", ")", "color", ".", "set_illuminant", "(", "targ_illum", ")", "return", "color" ]
Convenience function to apply an adaptation directly to a Color object.
[ "Convenience", "function", "to", "apply", "an", "adaptation", "directly", "to", "a", "Color", "object", "." ]
train
https://github.com/gtaylor/python-colormath/blob/1d168613718d2d7d31ec4230524e987ef66823c7/colormath/chromatic_adaptation.py#L101-L119
gtaylor/python-colormath
examples/conversions.py
example_lab_to_xyz
def example_lab_to_xyz(): """ This function shows a simple conversion of an Lab color to an XYZ color. """ print("=== Simple Example: Lab->XYZ ===") # Instantiate an Lab color object with the given values. lab = LabColor(0.903, 16.296, -2.22) # Show a string representation. print(lab) # Convert to XYZ. xyz = convert_color(lab, XYZColor) print(xyz) print("=== End Example ===\n")
python
def example_lab_to_xyz(): """ This function shows a simple conversion of an Lab color to an XYZ color. """ print("=== Simple Example: Lab->XYZ ===") # Instantiate an Lab color object with the given values. lab = LabColor(0.903, 16.296, -2.22) # Show a string representation. print(lab) # Convert to XYZ. xyz = convert_color(lab, XYZColor) print(xyz) print("=== End Example ===\n")
[ "def", "example_lab_to_xyz", "(", ")", ":", "print", "(", "\"=== Simple Example: Lab->XYZ ===\"", ")", "# Instantiate an Lab color object with the given values.", "lab", "=", "LabColor", "(", "0.903", ",", "16.296", ",", "-", "2.22", ")", "# Show a string representation.", "print", "(", "lab", ")", "# Convert to XYZ.", "xyz", "=", "convert_color", "(", "lab", ",", "XYZColor", ")", "print", "(", "xyz", ")", "print", "(", "\"=== End Example ===\\n\"", ")" ]
This function shows a simple conversion of an Lab color to an XYZ color.
[ "This", "function", "shows", "a", "simple", "conversion", "of", "an", "Lab", "color", "to", "an", "XYZ", "color", "." ]
train
https://github.com/gtaylor/python-colormath/blob/1d168613718d2d7d31ec4230524e987ef66823c7/examples/conversions.py#L17-L30
gtaylor/python-colormath
examples/conversions.py
example_lchab_to_lchuv
def example_lchab_to_lchuv(): """ This function shows very complex chain of conversions in action. LCHab to LCHuv involves four different calculations, making this the conversion requiring the most steps. """ print("=== Complex Example: LCHab->LCHuv ===") # Instantiate an LCHab color object with the given values. lchab = LCHabColor(0.903, 16.447, 352.252) # Show a string representation. print(lchab) # Convert to LCHuv. lchuv = convert_color(lchab, LCHuvColor) print(lchuv) print("=== End Example ===\n")
python
def example_lchab_to_lchuv(): """ This function shows very complex chain of conversions in action. LCHab to LCHuv involves four different calculations, making this the conversion requiring the most steps. """ print("=== Complex Example: LCHab->LCHuv ===") # Instantiate an LCHab color object with the given values. lchab = LCHabColor(0.903, 16.447, 352.252) # Show a string representation. print(lchab) # Convert to LCHuv. lchuv = convert_color(lchab, LCHuvColor) print(lchuv) print("=== End Example ===\n")
[ "def", "example_lchab_to_lchuv", "(", ")", ":", "print", "(", "\"=== Complex Example: LCHab->LCHuv ===\"", ")", "# Instantiate an LCHab color object with the given values.", "lchab", "=", "LCHabColor", "(", "0.903", ",", "16.447", ",", "352.252", ")", "# Show a string representation.", "print", "(", "lchab", ")", "# Convert to LCHuv.", "lchuv", "=", "convert_color", "(", "lchab", ",", "LCHuvColor", ")", "print", "(", "lchuv", ")", "print", "(", "\"=== End Example ===\\n\"", ")" ]
This function shows very complex chain of conversions in action. LCHab to LCHuv involves four different calculations, making this the conversion requiring the most steps.
[ "This", "function", "shows", "very", "complex", "chain", "of", "conversions", "in", "action", "." ]
train
https://github.com/gtaylor/python-colormath/blob/1d168613718d2d7d31ec4230524e987ef66823c7/examples/conversions.py#L33-L49
gtaylor/python-colormath
examples/conversions.py
example_lab_to_rgb
def example_lab_to_rgb(): """ Conversions to RGB are a little more complex mathematically. There are also several kinds of RGB color spaces. When converting from a device-independent color space to RGB, sRGB is assumed unless otherwise specified with the target_rgb keyword arg. """ print("=== RGB Example: Lab->RGB ===") # Instantiate an Lab color object with the given values. lab = LabColor(0.903, 16.296, -2.217) # Show a string representation. print(lab) # Convert to XYZ. rgb = convert_color(lab, sRGBColor) print(rgb) print("=== End Example ===\n")
python
def example_lab_to_rgb(): """ Conversions to RGB are a little more complex mathematically. There are also several kinds of RGB color spaces. When converting from a device-independent color space to RGB, sRGB is assumed unless otherwise specified with the target_rgb keyword arg. """ print("=== RGB Example: Lab->RGB ===") # Instantiate an Lab color object with the given values. lab = LabColor(0.903, 16.296, -2.217) # Show a string representation. print(lab) # Convert to XYZ. rgb = convert_color(lab, sRGBColor) print(rgb) print("=== End Example ===\n")
[ "def", "example_lab_to_rgb", "(", ")", ":", "print", "(", "\"=== RGB Example: Lab->RGB ===\"", ")", "# Instantiate an Lab color object with the given values.", "lab", "=", "LabColor", "(", "0.903", ",", "16.296", ",", "-", "2.217", ")", "# Show a string representation.", "print", "(", "lab", ")", "# Convert to XYZ.", "rgb", "=", "convert_color", "(", "lab", ",", "sRGBColor", ")", "print", "(", "rgb", ")", "print", "(", "\"=== End Example ===\\n\"", ")" ]
Conversions to RGB are a little more complex mathematically. There are also several kinds of RGB color spaces. When converting from a device-independent color space to RGB, sRGB is assumed unless otherwise specified with the target_rgb keyword arg.
[ "Conversions", "to", "RGB", "are", "a", "little", "more", "complex", "mathematically", ".", "There", "are", "also", "several", "kinds", "of", "RGB", "color", "spaces", ".", "When", "converting", "from", "a", "device", "-", "independent", "color", "space", "to", "RGB", "sRGB", "is", "assumed", "unless", "otherwise", "specified", "with", "the", "target_rgb", "keyword", "arg", "." ]
train
https://github.com/gtaylor/python-colormath/blob/1d168613718d2d7d31ec4230524e987ef66823c7/examples/conversions.py#L52-L68
gtaylor/python-colormath
examples/conversions.py
example_rgb_to_xyz
def example_rgb_to_xyz(): """ The reverse is similar. """ print("=== RGB Example: RGB->XYZ ===") # Instantiate an Lab color object with the given values. rgb = sRGBColor(120, 130, 140) # Show a string representation. print(rgb) # Convert RGB to XYZ using a D50 illuminant. xyz = convert_color(rgb, XYZColor, target_illuminant='D50') print(xyz) print("=== End Example ===\n")
python
def example_rgb_to_xyz(): """ The reverse is similar. """ print("=== RGB Example: RGB->XYZ ===") # Instantiate an Lab color object with the given values. rgb = sRGBColor(120, 130, 140) # Show a string representation. print(rgb) # Convert RGB to XYZ using a D50 illuminant. xyz = convert_color(rgb, XYZColor, target_illuminant='D50') print(xyz) print("=== End Example ===\n")
[ "def", "example_rgb_to_xyz", "(", ")", ":", "print", "(", "\"=== RGB Example: RGB->XYZ ===\"", ")", "# Instantiate an Lab color object with the given values.", "rgb", "=", "sRGBColor", "(", "120", ",", "130", ",", "140", ")", "# Show a string representation.", "print", "(", "rgb", ")", "# Convert RGB to XYZ using a D50 illuminant.", "xyz", "=", "convert_color", "(", "rgb", ",", "XYZColor", ",", "target_illuminant", "=", "'D50'", ")", "print", "(", "xyz", ")", "print", "(", "\"=== End Example ===\\n\"", ")" ]
The reverse is similar.
[ "The", "reverse", "is", "similar", "." ]
train
https://github.com/gtaylor/python-colormath/blob/1d168613718d2d7d31ec4230524e987ef66823c7/examples/conversions.py#L71-L84
gtaylor/python-colormath
examples/conversions.py
example_spectral_to_xyz
def example_spectral_to_xyz(): """ Instantiate an Lab color object with the given values. Note that the spectral range can run from 340nm to 830nm. Any omitted values assume a value of 0.0, which is more or less ignored. For the distribution below, we are providing an example reading from an X-Rite i1 Pro, which only measures between 380nm and 730nm. """ print("=== Example: Spectral->XYZ ===") spc = SpectralColor( observer='2', illuminant='d50', spec_380nm=0.0600, spec_390nm=0.0600, spec_400nm=0.0641, spec_410nm=0.0654, spec_420nm=0.0645, spec_430nm=0.0605, spec_440nm=0.0562, spec_450nm=0.0543, spec_460nm=0.0537, spec_470nm=0.0541, spec_480nm=0.0559, spec_490nm=0.0603, spec_500nm=0.0651, spec_510nm=0.0680, spec_520nm=0.0705, spec_530nm=0.0736, spec_540nm=0.0772, spec_550nm=0.0809, spec_560nm=0.0870, spec_570nm=0.0990, spec_580nm=0.1128, spec_590nm=0.1251, spec_600nm=0.1360, spec_610nm=0.1439, spec_620nm=0.1511, spec_630nm=0.1590, spec_640nm=0.1688, spec_650nm=0.1828, spec_660nm=0.1996, spec_670nm=0.2187, spec_680nm=0.2397, spec_690nm=0.2618, spec_700nm=0.2852, spec_710nm=0.2500, spec_720nm=0.2400, spec_730nm=0.2300) xyz = convert_color(spc, XYZColor) print(xyz) print("=== End Example ===\n")
python
def example_spectral_to_xyz(): """ Instantiate an Lab color object with the given values. Note that the spectral range can run from 340nm to 830nm. Any omitted values assume a value of 0.0, which is more or less ignored. For the distribution below, we are providing an example reading from an X-Rite i1 Pro, which only measures between 380nm and 730nm. """ print("=== Example: Spectral->XYZ ===") spc = SpectralColor( observer='2', illuminant='d50', spec_380nm=0.0600, spec_390nm=0.0600, spec_400nm=0.0641, spec_410nm=0.0654, spec_420nm=0.0645, spec_430nm=0.0605, spec_440nm=0.0562, spec_450nm=0.0543, spec_460nm=0.0537, spec_470nm=0.0541, spec_480nm=0.0559, spec_490nm=0.0603, spec_500nm=0.0651, spec_510nm=0.0680, spec_520nm=0.0705, spec_530nm=0.0736, spec_540nm=0.0772, spec_550nm=0.0809, spec_560nm=0.0870, spec_570nm=0.0990, spec_580nm=0.1128, spec_590nm=0.1251, spec_600nm=0.1360, spec_610nm=0.1439, spec_620nm=0.1511, spec_630nm=0.1590, spec_640nm=0.1688, spec_650nm=0.1828, spec_660nm=0.1996, spec_670nm=0.2187, spec_680nm=0.2397, spec_690nm=0.2618, spec_700nm=0.2852, spec_710nm=0.2500, spec_720nm=0.2400, spec_730nm=0.2300) xyz = convert_color(spc, XYZColor) print(xyz) print("=== End Example ===\n")
[ "def", "example_spectral_to_xyz", "(", ")", ":", "print", "(", "\"=== Example: Spectral->XYZ ===\"", ")", "spc", "=", "SpectralColor", "(", "observer", "=", "'2'", ",", "illuminant", "=", "'d50'", ",", "spec_380nm", "=", "0.0600", ",", "spec_390nm", "=", "0.0600", ",", "spec_400nm", "=", "0.0641", ",", "spec_410nm", "=", "0.0654", ",", "spec_420nm", "=", "0.0645", ",", "spec_430nm", "=", "0.0605", ",", "spec_440nm", "=", "0.0562", ",", "spec_450nm", "=", "0.0543", ",", "spec_460nm", "=", "0.0537", ",", "spec_470nm", "=", "0.0541", ",", "spec_480nm", "=", "0.0559", ",", "spec_490nm", "=", "0.0603", ",", "spec_500nm", "=", "0.0651", ",", "spec_510nm", "=", "0.0680", ",", "spec_520nm", "=", "0.0705", ",", "spec_530nm", "=", "0.0736", ",", "spec_540nm", "=", "0.0772", ",", "spec_550nm", "=", "0.0809", ",", "spec_560nm", "=", "0.0870", ",", "spec_570nm", "=", "0.0990", ",", "spec_580nm", "=", "0.1128", ",", "spec_590nm", "=", "0.1251", ",", "spec_600nm", "=", "0.1360", ",", "spec_610nm", "=", "0.1439", ",", "spec_620nm", "=", "0.1511", ",", "spec_630nm", "=", "0.1590", ",", "spec_640nm", "=", "0.1688", ",", "spec_650nm", "=", "0.1828", ",", "spec_660nm", "=", "0.1996", ",", "spec_670nm", "=", "0.2187", ",", "spec_680nm", "=", "0.2397", ",", "spec_690nm", "=", "0.2618", ",", "spec_700nm", "=", "0.2852", ",", "spec_710nm", "=", "0.2500", ",", "spec_720nm", "=", "0.2400", ",", "spec_730nm", "=", "0.2300", ")", "xyz", "=", "convert_color", "(", "spc", ",", "XYZColor", ")", "print", "(", "xyz", ")", "print", "(", "\"=== End Example ===\\n\"", ")" ]
Instantiate an Lab color object with the given values. Note that the spectral range can run from 340nm to 830nm. Any omitted values assume a value of 0.0, which is more or less ignored. For the distribution below, we are providing an example reading from an X-Rite i1 Pro, which only measures between 380nm and 730nm.
[ "Instantiate", "an", "Lab", "color", "object", "with", "the", "given", "values", ".", "Note", "that", "the", "spectral", "range", "can", "run", "from", "340nm", "to", "830nm", ".", "Any", "omitted", "values", "assume", "a", "value", "of", "0", ".", "0", "which", "is", "more", "or", "less", "ignored", ".", "For", "the", "distribution", "below", "we", "are", "providing", "an", "example", "reading", "from", "an", "X", "-", "Rite", "i1", "Pro", "which", "only", "measures", "between", "380nm", "and", "730nm", "." ]
train
https://github.com/gtaylor/python-colormath/blob/1d168613718d2d7d31ec4230524e987ef66823c7/examples/conversions.py#L87-L113
gtaylor/python-colormath
examples/conversions.py
example_lab_to_ipt
def example_lab_to_ipt(): """ This function shows a simple conversion of an XYZ color to an IPT color. """ print("=== Simple Example: XYZ->IPT ===") # Instantiate an XYZ color object with the given values. xyz = XYZColor(0.5, 0.5, 0.5, illuminant='d65') # Show a string representation. print(xyz) # Convert to IPT. ipt = convert_color(xyz, IPTColor) print(ipt) print("=== End Example ===\n")
python
def example_lab_to_ipt(): """ This function shows a simple conversion of an XYZ color to an IPT color. """ print("=== Simple Example: XYZ->IPT ===") # Instantiate an XYZ color object with the given values. xyz = XYZColor(0.5, 0.5, 0.5, illuminant='d65') # Show a string representation. print(xyz) # Convert to IPT. ipt = convert_color(xyz, IPTColor) print(ipt) print("=== End Example ===\n")
[ "def", "example_lab_to_ipt", "(", ")", ":", "print", "(", "\"=== Simple Example: XYZ->IPT ===\"", ")", "# Instantiate an XYZ color object with the given values.", "xyz", "=", "XYZColor", "(", "0.5", ",", "0.5", ",", "0.5", ",", "illuminant", "=", "'d65'", ")", "# Show a string representation.", "print", "(", "xyz", ")", "# Convert to IPT.", "ipt", "=", "convert_color", "(", "xyz", ",", "IPTColor", ")", "print", "(", "ipt", ")", "print", "(", "\"=== End Example ===\\n\"", ")" ]
This function shows a simple conversion of an XYZ color to an IPT color.
[ "This", "function", "shows", "a", "simple", "conversion", "of", "an", "XYZ", "color", "to", "an", "IPT", "color", "." ]
train
https://github.com/gtaylor/python-colormath/blob/1d168613718d2d7d31ec4230524e987ef66823c7/examples/conversions.py#L116-L129
gtaylor/python-colormath
colormath/color_conversions.py
apply_RGB_matrix
def apply_RGB_matrix(var1, var2, var3, rgb_type, convtype="xyz_to_rgb"): """ Applies an RGB working matrix to convert from XYZ to RGB. The arguments are tersely named var1, var2, and var3 to allow for the passing of XYZ _or_ RGB values. var1 is X for XYZ, and R for RGB. var2 and var3 follow suite. """ convtype = convtype.lower() # Retrieve the appropriate transformation matrix from the constants. rgb_matrix = rgb_type.conversion_matrices[convtype] logger.debug(" \* Applying RGB conversion matrix: %s->%s", rgb_type.__class__.__name__, convtype) # Stuff the RGB/XYZ values into a NumPy matrix for conversion. var_matrix = numpy.array(( var1, var2, var3 )) # Perform the adaptation via matrix multiplication. result_matrix = numpy.dot(rgb_matrix, var_matrix) rgb_r, rgb_g, rgb_b = result_matrix # Clamp these values to a valid range. rgb_r = max(rgb_r, 0.0) rgb_g = max(rgb_g, 0.0) rgb_b = max(rgb_b, 0.0) return rgb_r, rgb_g, rgb_b
python
def apply_RGB_matrix(var1, var2, var3, rgb_type, convtype="xyz_to_rgb"): """ Applies an RGB working matrix to convert from XYZ to RGB. The arguments are tersely named var1, var2, and var3 to allow for the passing of XYZ _or_ RGB values. var1 is X for XYZ, and R for RGB. var2 and var3 follow suite. """ convtype = convtype.lower() # Retrieve the appropriate transformation matrix from the constants. rgb_matrix = rgb_type.conversion_matrices[convtype] logger.debug(" \* Applying RGB conversion matrix: %s->%s", rgb_type.__class__.__name__, convtype) # Stuff the RGB/XYZ values into a NumPy matrix for conversion. var_matrix = numpy.array(( var1, var2, var3 )) # Perform the adaptation via matrix multiplication. result_matrix = numpy.dot(rgb_matrix, var_matrix) rgb_r, rgb_g, rgb_b = result_matrix # Clamp these values to a valid range. rgb_r = max(rgb_r, 0.0) rgb_g = max(rgb_g, 0.0) rgb_b = max(rgb_b, 0.0) return rgb_r, rgb_g, rgb_b
[ "def", "apply_RGB_matrix", "(", "var1", ",", "var2", ",", "var3", ",", "rgb_type", ",", "convtype", "=", "\"xyz_to_rgb\"", ")", ":", "convtype", "=", "convtype", ".", "lower", "(", ")", "# Retrieve the appropriate transformation matrix from the constants.", "rgb_matrix", "=", "rgb_type", ".", "conversion_matrices", "[", "convtype", "]", "logger", ".", "debug", "(", "\" \\* Applying RGB conversion matrix: %s->%s\"", ",", "rgb_type", ".", "__class__", ".", "__name__", ",", "convtype", ")", "# Stuff the RGB/XYZ values into a NumPy matrix for conversion.", "var_matrix", "=", "numpy", ".", "array", "(", "(", "var1", ",", "var2", ",", "var3", ")", ")", "# Perform the adaptation via matrix multiplication.", "result_matrix", "=", "numpy", ".", "dot", "(", "rgb_matrix", ",", "var_matrix", ")", "rgb_r", ",", "rgb_g", ",", "rgb_b", "=", "result_matrix", "# Clamp these values to a valid range.", "rgb_r", "=", "max", "(", "rgb_r", ",", "0.0", ")", "rgb_g", "=", "max", "(", "rgb_g", ",", "0.0", ")", "rgb_b", "=", "max", "(", "rgb_b", ",", "0.0", ")", "return", "rgb_r", ",", "rgb_g", ",", "rgb_b" ]
Applies an RGB working matrix to convert from XYZ to RGB. The arguments are tersely named var1, var2, and var3 to allow for the passing of XYZ _or_ RGB values. var1 is X for XYZ, and R for RGB. var2 and var3 follow suite.
[ "Applies", "an", "RGB", "working", "matrix", "to", "convert", "from", "XYZ", "to", "RGB", ".", "The", "arguments", "are", "tersely", "named", "var1", "var2", "and", "var3", "to", "allow", "for", "the", "passing", "of", "XYZ", "_or_", "RGB", "values", ".", "var1", "is", "X", "for", "XYZ", "and", "R", "for", "RGB", ".", "var2", "and", "var3", "follow", "suite", "." ]
train
https://github.com/gtaylor/python-colormath/blob/1d168613718d2d7d31ec4230524e987ef66823c7/colormath/color_conversions.py#L31-L55
gtaylor/python-colormath
colormath/color_conversions.py
color_conversion_function
def color_conversion_function(start_type, target_type): """ Decorator to indicate a function that performs a conversion from one color space to another. This decorator will return the original function unmodified, however it will be registered in the _conversion_manager so it can be used to perform color space transformations between color spaces that do not have direct conversion functions (e.g., Luv to CMYK). Note: For a conversion to/from RGB supply the BaseRGBColor class. :param start_type: Starting color space type :param target_type: Target color space type """ def decorator(f): f.start_type = start_type f.target_type = target_type _conversion_manager.add_type_conversion(start_type, target_type, f) return f return decorator
python
def color_conversion_function(start_type, target_type): """ Decorator to indicate a function that performs a conversion from one color space to another. This decorator will return the original function unmodified, however it will be registered in the _conversion_manager so it can be used to perform color space transformations between color spaces that do not have direct conversion functions (e.g., Luv to CMYK). Note: For a conversion to/from RGB supply the BaseRGBColor class. :param start_type: Starting color space type :param target_type: Target color space type """ def decorator(f): f.start_type = start_type f.target_type = target_type _conversion_manager.add_type_conversion(start_type, target_type, f) return f return decorator
[ "def", "color_conversion_function", "(", "start_type", ",", "target_type", ")", ":", "def", "decorator", "(", "f", ")", ":", "f", ".", "start_type", "=", "start_type", "f", ".", "target_type", "=", "target_type", "_conversion_manager", ".", "add_type_conversion", "(", "start_type", ",", "target_type", ",", "f", ")", "return", "f", "return", "decorator" ]
Decorator to indicate a function that performs a conversion from one color space to another. This decorator will return the original function unmodified, however it will be registered in the _conversion_manager so it can be used to perform color space transformations between color spaces that do not have direct conversion functions (e.g., Luv to CMYK). Note: For a conversion to/from RGB supply the BaseRGBColor class. :param start_type: Starting color space type :param target_type: Target color space type
[ "Decorator", "to", "indicate", "a", "function", "that", "performs", "a", "conversion", "from", "one", "color", "space", "to", "another", "." ]
train
https://github.com/gtaylor/python-colormath/blob/1d168613718d2d7d31ec4230524e987ef66823c7/colormath/color_conversions.py#L152-L173
gtaylor/python-colormath
colormath/color_conversions.py
Spectral_to_XYZ
def Spectral_to_XYZ(cobj, illuminant_override=None, *args, **kwargs): """ Converts spectral readings to XYZ. """ # If the user provides an illuminant_override numpy array, use it. if illuminant_override: reference_illum = illuminant_override else: # Otherwise, look up the illuminant from known standards based # on the value of 'illuminant' pulled from the SpectralColor object. try: reference_illum = spectral_constants.REF_ILLUM_TABLE[cobj.illuminant] except KeyError: raise InvalidIlluminantError(cobj.illuminant) # Get the spectral distribution of the selected standard observer. if cobj.observer == '10': std_obs_x = spectral_constants.STDOBSERV_X10 std_obs_y = spectral_constants.STDOBSERV_Y10 std_obs_z = spectral_constants.STDOBSERV_Z10 else: # Assume 2 degree, since it is theoretically the only other possibility. std_obs_x = spectral_constants.STDOBSERV_X2 std_obs_y = spectral_constants.STDOBSERV_Y2 std_obs_z = spectral_constants.STDOBSERV_Z2 # This is a NumPy array containing the spectral distribution of the color. sample = cobj.get_numpy_array() # The denominator is constant throughout the entire calculation for X, # Y, and Z coordinates. Calculate it once and re-use. denom = std_obs_y * reference_illum # This is also a common element in the calculation whereby the sample # NumPy array is multiplied by the reference illuminant's power distribution # (which is also a NumPy array). sample_by_ref_illum = sample * reference_illum # Calculate the numerator of the equation to find X. x_numerator = sample_by_ref_illum * std_obs_x y_numerator = sample_by_ref_illum * std_obs_y z_numerator = sample_by_ref_illum * std_obs_z xyz_x = x_numerator.sum() / denom.sum() xyz_y = y_numerator.sum() / denom.sum() xyz_z = z_numerator.sum() / denom.sum() return XYZColor( xyz_x, xyz_y, xyz_z, observer=cobj.observer, illuminant=cobj.illuminant)
python
def Spectral_to_XYZ(cobj, illuminant_override=None, *args, **kwargs): """ Converts spectral readings to XYZ. """ # If the user provides an illuminant_override numpy array, use it. if illuminant_override: reference_illum = illuminant_override else: # Otherwise, look up the illuminant from known standards based # on the value of 'illuminant' pulled from the SpectralColor object. try: reference_illum = spectral_constants.REF_ILLUM_TABLE[cobj.illuminant] except KeyError: raise InvalidIlluminantError(cobj.illuminant) # Get the spectral distribution of the selected standard observer. if cobj.observer == '10': std_obs_x = spectral_constants.STDOBSERV_X10 std_obs_y = spectral_constants.STDOBSERV_Y10 std_obs_z = spectral_constants.STDOBSERV_Z10 else: # Assume 2 degree, since it is theoretically the only other possibility. std_obs_x = spectral_constants.STDOBSERV_X2 std_obs_y = spectral_constants.STDOBSERV_Y2 std_obs_z = spectral_constants.STDOBSERV_Z2 # This is a NumPy array containing the spectral distribution of the color. sample = cobj.get_numpy_array() # The denominator is constant throughout the entire calculation for X, # Y, and Z coordinates. Calculate it once and re-use. denom = std_obs_y * reference_illum # This is also a common element in the calculation whereby the sample # NumPy array is multiplied by the reference illuminant's power distribution # (which is also a NumPy array). sample_by_ref_illum = sample * reference_illum # Calculate the numerator of the equation to find X. x_numerator = sample_by_ref_illum * std_obs_x y_numerator = sample_by_ref_illum * std_obs_y z_numerator = sample_by_ref_illum * std_obs_z xyz_x = x_numerator.sum() / denom.sum() xyz_y = y_numerator.sum() / denom.sum() xyz_z = z_numerator.sum() / denom.sum() return XYZColor( xyz_x, xyz_y, xyz_z, observer=cobj.observer, illuminant=cobj.illuminant)
[ "def", "Spectral_to_XYZ", "(", "cobj", ",", "illuminant_override", "=", "None", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "# If the user provides an illuminant_override numpy array, use it.", "if", "illuminant_override", ":", "reference_illum", "=", "illuminant_override", "else", ":", "# Otherwise, look up the illuminant from known standards based", "# on the value of 'illuminant' pulled from the SpectralColor object.", "try", ":", "reference_illum", "=", "spectral_constants", ".", "REF_ILLUM_TABLE", "[", "cobj", ".", "illuminant", "]", "except", "KeyError", ":", "raise", "InvalidIlluminantError", "(", "cobj", ".", "illuminant", ")", "# Get the spectral distribution of the selected standard observer.", "if", "cobj", ".", "observer", "==", "'10'", ":", "std_obs_x", "=", "spectral_constants", ".", "STDOBSERV_X10", "std_obs_y", "=", "spectral_constants", ".", "STDOBSERV_Y10", "std_obs_z", "=", "spectral_constants", ".", "STDOBSERV_Z10", "else", ":", "# Assume 2 degree, since it is theoretically the only other possibility.", "std_obs_x", "=", "spectral_constants", ".", "STDOBSERV_X2", "std_obs_y", "=", "spectral_constants", ".", "STDOBSERV_Y2", "std_obs_z", "=", "spectral_constants", ".", "STDOBSERV_Z2", "# This is a NumPy array containing the spectral distribution of the color.", "sample", "=", "cobj", ".", "get_numpy_array", "(", ")", "# The denominator is constant throughout the entire calculation for X,", "# Y, and Z coordinates. Calculate it once and re-use.", "denom", "=", "std_obs_y", "*", "reference_illum", "# This is also a common element in the calculation whereby the sample", "# NumPy array is multiplied by the reference illuminant's power distribution", "# (which is also a NumPy array).", "sample_by_ref_illum", "=", "sample", "*", "reference_illum", "# Calculate the numerator of the equation to find X.", "x_numerator", "=", "sample_by_ref_illum", "*", "std_obs_x", "y_numerator", "=", "sample_by_ref_illum", "*", "std_obs_y", "z_numerator", "=", "sample_by_ref_illum", "*", "std_obs_z", "xyz_x", "=", "x_numerator", ".", "sum", "(", ")", "/", "denom", ".", "sum", "(", ")", "xyz_y", "=", "y_numerator", ".", "sum", "(", ")", "/", "denom", ".", "sum", "(", ")", "xyz_z", "=", "z_numerator", ".", "sum", "(", ")", "/", "denom", ".", "sum", "(", ")", "return", "XYZColor", "(", "xyz_x", ",", "xyz_y", ",", "xyz_z", ",", "observer", "=", "cobj", ".", "observer", ",", "illuminant", "=", "cobj", ".", "illuminant", ")" ]
Converts spectral readings to XYZ.
[ "Converts", "spectral", "readings", "to", "XYZ", "." ]
train
https://github.com/gtaylor/python-colormath/blob/1d168613718d2d7d31ec4230524e987ef66823c7/colormath/color_conversions.py#L178-L226
gtaylor/python-colormath
colormath/color_conversions.py
Lab_to_LCHab
def Lab_to_LCHab(cobj, *args, **kwargs): """ Convert from CIE Lab to LCH(ab). """ lch_l = cobj.lab_l lch_c = math.sqrt( math.pow(float(cobj.lab_a), 2) + math.pow(float(cobj.lab_b), 2)) lch_h = math.atan2(float(cobj.lab_b), float(cobj.lab_a)) if lch_h > 0: lch_h = (lch_h / math.pi) * 180 else: lch_h = 360 - (math.fabs(lch_h) / math.pi) * 180 return LCHabColor( lch_l, lch_c, lch_h, observer=cobj.observer, illuminant=cobj.illuminant)
python
def Lab_to_LCHab(cobj, *args, **kwargs): """ Convert from CIE Lab to LCH(ab). """ lch_l = cobj.lab_l lch_c = math.sqrt( math.pow(float(cobj.lab_a), 2) + math.pow(float(cobj.lab_b), 2)) lch_h = math.atan2(float(cobj.lab_b), float(cobj.lab_a)) if lch_h > 0: lch_h = (lch_h / math.pi) * 180 else: lch_h = 360 - (math.fabs(lch_h) / math.pi) * 180 return LCHabColor( lch_l, lch_c, lch_h, observer=cobj.observer, illuminant=cobj.illuminant)
[ "def", "Lab_to_LCHab", "(", "cobj", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "lch_l", "=", "cobj", ".", "lab_l", "lch_c", "=", "math", ".", "sqrt", "(", "math", ".", "pow", "(", "float", "(", "cobj", ".", "lab_a", ")", ",", "2", ")", "+", "math", ".", "pow", "(", "float", "(", "cobj", ".", "lab_b", ")", ",", "2", ")", ")", "lch_h", "=", "math", ".", "atan2", "(", "float", "(", "cobj", ".", "lab_b", ")", ",", "float", "(", "cobj", ".", "lab_a", ")", ")", "if", "lch_h", ">", "0", ":", "lch_h", "=", "(", "lch_h", "/", "math", ".", "pi", ")", "*", "180", "else", ":", "lch_h", "=", "360", "-", "(", "math", ".", "fabs", "(", "lch_h", ")", "/", "math", ".", "pi", ")", "*", "180", "return", "LCHabColor", "(", "lch_l", ",", "lch_c", ",", "lch_h", ",", "observer", "=", "cobj", ".", "observer", ",", "illuminant", "=", "cobj", ".", "illuminant", ")" ]
Convert from CIE Lab to LCH(ab).
[ "Convert", "from", "CIE", "Lab", "to", "LCH", "(", "ab", ")", "." ]
train
https://github.com/gtaylor/python-colormath/blob/1d168613718d2d7d31ec4230524e987ef66823c7/colormath/color_conversions.py#L231-L246
gtaylor/python-colormath
colormath/color_conversions.py
Lab_to_XYZ
def Lab_to_XYZ(cobj, *args, **kwargs): """ Convert from Lab to XYZ """ illum = cobj.get_illuminant_xyz() xyz_y = (cobj.lab_l + 16.0) / 116.0 xyz_x = cobj.lab_a / 500.0 + xyz_y xyz_z = xyz_y - cobj.lab_b / 200.0 if math.pow(xyz_y, 3) > color_constants.CIE_E: xyz_y = math.pow(xyz_y, 3) else: xyz_y = (xyz_y - 16.0 / 116.0) / 7.787 if math.pow(xyz_x, 3) > color_constants.CIE_E: xyz_x = math.pow(xyz_x, 3) else: xyz_x = (xyz_x - 16.0 / 116.0) / 7.787 if math.pow(xyz_z, 3) > color_constants.CIE_E: xyz_z = math.pow(xyz_z, 3) else: xyz_z = (xyz_z - 16.0 / 116.0) / 7.787 xyz_x = (illum["X"] * xyz_x) xyz_y = (illum["Y"] * xyz_y) xyz_z = (illum["Z"] * xyz_z) return XYZColor( xyz_x, xyz_y, xyz_z, observer=cobj.observer, illuminant=cobj.illuminant)
python
def Lab_to_XYZ(cobj, *args, **kwargs): """ Convert from Lab to XYZ """ illum = cobj.get_illuminant_xyz() xyz_y = (cobj.lab_l + 16.0) / 116.0 xyz_x = cobj.lab_a / 500.0 + xyz_y xyz_z = xyz_y - cobj.lab_b / 200.0 if math.pow(xyz_y, 3) > color_constants.CIE_E: xyz_y = math.pow(xyz_y, 3) else: xyz_y = (xyz_y - 16.0 / 116.0) / 7.787 if math.pow(xyz_x, 3) > color_constants.CIE_E: xyz_x = math.pow(xyz_x, 3) else: xyz_x = (xyz_x - 16.0 / 116.0) / 7.787 if math.pow(xyz_z, 3) > color_constants.CIE_E: xyz_z = math.pow(xyz_z, 3) else: xyz_z = (xyz_z - 16.0 / 116.0) / 7.787 xyz_x = (illum["X"] * xyz_x) xyz_y = (illum["Y"] * xyz_y) xyz_z = (illum["Z"] * xyz_z) return XYZColor( xyz_x, xyz_y, xyz_z, observer=cobj.observer, illuminant=cobj.illuminant)
[ "def", "Lab_to_XYZ", "(", "cobj", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "illum", "=", "cobj", ".", "get_illuminant_xyz", "(", ")", "xyz_y", "=", "(", "cobj", ".", "lab_l", "+", "16.0", ")", "/", "116.0", "xyz_x", "=", "cobj", ".", "lab_a", "/", "500.0", "+", "xyz_y", "xyz_z", "=", "xyz_y", "-", "cobj", ".", "lab_b", "/", "200.0", "if", "math", ".", "pow", "(", "xyz_y", ",", "3", ")", ">", "color_constants", ".", "CIE_E", ":", "xyz_y", "=", "math", ".", "pow", "(", "xyz_y", ",", "3", ")", "else", ":", "xyz_y", "=", "(", "xyz_y", "-", "16.0", "/", "116.0", ")", "/", "7.787", "if", "math", ".", "pow", "(", "xyz_x", ",", "3", ")", ">", "color_constants", ".", "CIE_E", ":", "xyz_x", "=", "math", ".", "pow", "(", "xyz_x", ",", "3", ")", "else", ":", "xyz_x", "=", "(", "xyz_x", "-", "16.0", "/", "116.0", ")", "/", "7.787", "if", "math", ".", "pow", "(", "xyz_z", ",", "3", ")", ">", "color_constants", ".", "CIE_E", ":", "xyz_z", "=", "math", ".", "pow", "(", "xyz_z", ",", "3", ")", "else", ":", "xyz_z", "=", "(", "xyz_z", "-", "16.0", "/", "116.0", ")", "/", "7.787", "xyz_x", "=", "(", "illum", "[", "\"X\"", "]", "*", "xyz_x", ")", "xyz_y", "=", "(", "illum", "[", "\"Y\"", "]", "*", "xyz_y", ")", "xyz_z", "=", "(", "illum", "[", "\"Z\"", "]", "*", "xyz_z", ")", "return", "XYZColor", "(", "xyz_x", ",", "xyz_y", ",", "xyz_z", ",", "observer", "=", "cobj", ".", "observer", ",", "illuminant", "=", "cobj", ".", "illuminant", ")" ]
Convert from Lab to XYZ
[ "Convert", "from", "Lab", "to", "XYZ" ]
train
https://github.com/gtaylor/python-colormath/blob/1d168613718d2d7d31ec4230524e987ef66823c7/colormath/color_conversions.py#L251-L280
gtaylor/python-colormath
colormath/color_conversions.py
Luv_to_LCHuv
def Luv_to_LCHuv(cobj, *args, **kwargs): """ Convert from CIE Luv to LCH(uv). """ lch_l = cobj.luv_l lch_c = math.sqrt(math.pow(cobj.luv_u, 2.0) + math.pow(cobj.luv_v, 2.0)) lch_h = math.atan2(float(cobj.luv_v), float(cobj.luv_u)) if lch_h > 0: lch_h = (lch_h / math.pi) * 180 else: lch_h = 360 - (math.fabs(lch_h) / math.pi) * 180 return LCHuvColor( lch_l, lch_c, lch_h, observer=cobj.observer, illuminant=cobj.illuminant)
python
def Luv_to_LCHuv(cobj, *args, **kwargs): """ Convert from CIE Luv to LCH(uv). """ lch_l = cobj.luv_l lch_c = math.sqrt(math.pow(cobj.luv_u, 2.0) + math.pow(cobj.luv_v, 2.0)) lch_h = math.atan2(float(cobj.luv_v), float(cobj.luv_u)) if lch_h > 0: lch_h = (lch_h / math.pi) * 180 else: lch_h = 360 - (math.fabs(lch_h) / math.pi) * 180 return LCHuvColor( lch_l, lch_c, lch_h, observer=cobj.observer, illuminant=cobj.illuminant)
[ "def", "Luv_to_LCHuv", "(", "cobj", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "lch_l", "=", "cobj", ".", "luv_l", "lch_c", "=", "math", ".", "sqrt", "(", "math", ".", "pow", "(", "cobj", ".", "luv_u", ",", "2.0", ")", "+", "math", ".", "pow", "(", "cobj", ".", "luv_v", ",", "2.0", ")", ")", "lch_h", "=", "math", ".", "atan2", "(", "float", "(", "cobj", ".", "luv_v", ")", ",", "float", "(", "cobj", ".", "luv_u", ")", ")", "if", "lch_h", ">", "0", ":", "lch_h", "=", "(", "lch_h", "/", "math", ".", "pi", ")", "*", "180", "else", ":", "lch_h", "=", "360", "-", "(", "math", ".", "fabs", "(", "lch_h", ")", "/", "math", ".", "pi", ")", "*", "180", "return", "LCHuvColor", "(", "lch_l", ",", "lch_c", ",", "lch_h", ",", "observer", "=", "cobj", ".", "observer", ",", "illuminant", "=", "cobj", ".", "illuminant", ")" ]
Convert from CIE Luv to LCH(uv).
[ "Convert", "from", "CIE", "Luv", "to", "LCH", "(", "uv", ")", "." ]
train
https://github.com/gtaylor/python-colormath/blob/1d168613718d2d7d31ec4230524e987ef66823c7/colormath/color_conversions.py#L285-L298
gtaylor/python-colormath
colormath/color_conversions.py
Luv_to_XYZ
def Luv_to_XYZ(cobj, *args, **kwargs): """ Convert from Luv to XYZ. """ illum = cobj.get_illuminant_xyz() # Without Light, there is no color. Short-circuit this and avoid some # zero division errors in the var_a_frac calculation. if cobj.luv_l <= 0.0: xyz_x = 0.0 xyz_y = 0.0 xyz_z = 0.0 return XYZColor( xyz_x, xyz_y, xyz_z, observer=cobj.observer, illuminant=cobj.illuminant) # Various variables used throughout the conversion. cie_k_times_e = color_constants.CIE_K * color_constants.CIE_E u_sub_0 = (4.0 * illum["X"]) / (illum["X"] + 15.0 * illum["Y"] + 3.0 * illum["Z"]) v_sub_0 = (9.0 * illum["Y"]) / (illum["X"] + 15.0 * illum["Y"] + 3.0 * illum["Z"]) var_u = cobj.luv_u / (13.0 * cobj.luv_l) + u_sub_0 var_v = cobj.luv_v / (13.0 * cobj.luv_l) + v_sub_0 # Y-coordinate calculations. if cobj.luv_l > cie_k_times_e: xyz_y = math.pow((cobj.luv_l + 16.0) / 116.0, 3.0) else: xyz_y = cobj.luv_l / color_constants.CIE_K # X-coordinate calculation. xyz_x = xyz_y * 9.0 * var_u / (4.0 * var_v) # Z-coordinate calculation. xyz_z = xyz_y * (12.0 - 3.0 * var_u - 20.0 * var_v) / (4.0 * var_v) return XYZColor( xyz_x, xyz_y, xyz_z, illuminant=cobj.illuminant, observer=cobj.observer)
python
def Luv_to_XYZ(cobj, *args, **kwargs): """ Convert from Luv to XYZ. """ illum = cobj.get_illuminant_xyz() # Without Light, there is no color. Short-circuit this and avoid some # zero division errors in the var_a_frac calculation. if cobj.luv_l <= 0.0: xyz_x = 0.0 xyz_y = 0.0 xyz_z = 0.0 return XYZColor( xyz_x, xyz_y, xyz_z, observer=cobj.observer, illuminant=cobj.illuminant) # Various variables used throughout the conversion. cie_k_times_e = color_constants.CIE_K * color_constants.CIE_E u_sub_0 = (4.0 * illum["X"]) / (illum["X"] + 15.0 * illum["Y"] + 3.0 * illum["Z"]) v_sub_0 = (9.0 * illum["Y"]) / (illum["X"] + 15.0 * illum["Y"] + 3.0 * illum["Z"]) var_u = cobj.luv_u / (13.0 * cobj.luv_l) + u_sub_0 var_v = cobj.luv_v / (13.0 * cobj.luv_l) + v_sub_0 # Y-coordinate calculations. if cobj.luv_l > cie_k_times_e: xyz_y = math.pow((cobj.luv_l + 16.0) / 116.0, 3.0) else: xyz_y = cobj.luv_l / color_constants.CIE_K # X-coordinate calculation. xyz_x = xyz_y * 9.0 * var_u / (4.0 * var_v) # Z-coordinate calculation. xyz_z = xyz_y * (12.0 - 3.0 * var_u - 20.0 * var_v) / (4.0 * var_v) return XYZColor( xyz_x, xyz_y, xyz_z, illuminant=cobj.illuminant, observer=cobj.observer)
[ "def", "Luv_to_XYZ", "(", "cobj", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "illum", "=", "cobj", ".", "get_illuminant_xyz", "(", ")", "# Without Light, there is no color. Short-circuit this and avoid some", "# zero division errors in the var_a_frac calculation.", "if", "cobj", ".", "luv_l", "<=", "0.0", ":", "xyz_x", "=", "0.0", "xyz_y", "=", "0.0", "xyz_z", "=", "0.0", "return", "XYZColor", "(", "xyz_x", ",", "xyz_y", ",", "xyz_z", ",", "observer", "=", "cobj", ".", "observer", ",", "illuminant", "=", "cobj", ".", "illuminant", ")", "# Various variables used throughout the conversion.", "cie_k_times_e", "=", "color_constants", ".", "CIE_K", "*", "color_constants", ".", "CIE_E", "u_sub_0", "=", "(", "4.0", "*", "illum", "[", "\"X\"", "]", ")", "/", "(", "illum", "[", "\"X\"", "]", "+", "15.0", "*", "illum", "[", "\"Y\"", "]", "+", "3.0", "*", "illum", "[", "\"Z\"", "]", ")", "v_sub_0", "=", "(", "9.0", "*", "illum", "[", "\"Y\"", "]", ")", "/", "(", "illum", "[", "\"X\"", "]", "+", "15.0", "*", "illum", "[", "\"Y\"", "]", "+", "3.0", "*", "illum", "[", "\"Z\"", "]", ")", "var_u", "=", "cobj", ".", "luv_u", "/", "(", "13.0", "*", "cobj", ".", "luv_l", ")", "+", "u_sub_0", "var_v", "=", "cobj", ".", "luv_v", "/", "(", "13.0", "*", "cobj", ".", "luv_l", ")", "+", "v_sub_0", "# Y-coordinate calculations.", "if", "cobj", ".", "luv_l", ">", "cie_k_times_e", ":", "xyz_y", "=", "math", ".", "pow", "(", "(", "cobj", ".", "luv_l", "+", "16.0", ")", "/", "116.0", ",", "3.0", ")", "else", ":", "xyz_y", "=", "cobj", ".", "luv_l", "/", "color_constants", ".", "CIE_K", "# X-coordinate calculation.", "xyz_x", "=", "xyz_y", "*", "9.0", "*", "var_u", "/", "(", "4.0", "*", "var_v", ")", "# Z-coordinate calculation.", "xyz_z", "=", "xyz_y", "*", "(", "12.0", "-", "3.0", "*", "var_u", "-", "20.0", "*", "var_v", ")", "/", "(", "4.0", "*", "var_v", ")", "return", "XYZColor", "(", "xyz_x", ",", "xyz_y", ",", "xyz_z", ",", "illuminant", "=", "cobj", ".", "illuminant", ",", "observer", "=", "cobj", ".", "observer", ")" ]
Convert from Luv to XYZ.
[ "Convert", "from", "Luv", "to", "XYZ", "." ]
train
https://github.com/gtaylor/python-colormath/blob/1d168613718d2d7d31ec4230524e987ef66823c7/colormath/color_conversions.py#L303-L337
gtaylor/python-colormath
colormath/color_conversions.py
LCHab_to_Lab
def LCHab_to_Lab(cobj, *args, **kwargs): """ Convert from LCH(ab) to Lab. """ lab_l = cobj.lch_l lab_a = math.cos(math.radians(cobj.lch_h)) * cobj.lch_c lab_b = math.sin(math.radians(cobj.lch_h)) * cobj.lch_c return LabColor( lab_l, lab_a, lab_b, illuminant=cobj.illuminant, observer=cobj.observer)
python
def LCHab_to_Lab(cobj, *args, **kwargs): """ Convert from LCH(ab) to Lab. """ lab_l = cobj.lch_l lab_a = math.cos(math.radians(cobj.lch_h)) * cobj.lch_c lab_b = math.sin(math.radians(cobj.lch_h)) * cobj.lch_c return LabColor( lab_l, lab_a, lab_b, illuminant=cobj.illuminant, observer=cobj.observer)
[ "def", "LCHab_to_Lab", "(", "cobj", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "lab_l", "=", "cobj", ".", "lch_l", "lab_a", "=", "math", ".", "cos", "(", "math", ".", "radians", "(", "cobj", ".", "lch_h", ")", ")", "*", "cobj", ".", "lch_c", "lab_b", "=", "math", ".", "sin", "(", "math", ".", "radians", "(", "cobj", ".", "lch_h", ")", ")", "*", "cobj", ".", "lch_c", "return", "LabColor", "(", "lab_l", ",", "lab_a", ",", "lab_b", ",", "illuminant", "=", "cobj", ".", "illuminant", ",", "observer", "=", "cobj", ".", "observer", ")" ]
Convert from LCH(ab) to Lab.
[ "Convert", "from", "LCH", "(", "ab", ")", "to", "Lab", "." ]
train
https://github.com/gtaylor/python-colormath/blob/1d168613718d2d7d31ec4230524e987ef66823c7/colormath/color_conversions.py#L342-L350
gtaylor/python-colormath
colormath/color_conversions.py
LCHuv_to_Luv
def LCHuv_to_Luv(cobj, *args, **kwargs): """ Convert from LCH(uv) to Luv. """ luv_l = cobj.lch_l luv_u = math.cos(math.radians(cobj.lch_h)) * cobj.lch_c luv_v = math.sin(math.radians(cobj.lch_h)) * cobj.lch_c return LuvColor( luv_l, luv_u, luv_v, illuminant=cobj.illuminant, observer=cobj.observer)
python
def LCHuv_to_Luv(cobj, *args, **kwargs): """ Convert from LCH(uv) to Luv. """ luv_l = cobj.lch_l luv_u = math.cos(math.radians(cobj.lch_h)) * cobj.lch_c luv_v = math.sin(math.radians(cobj.lch_h)) * cobj.lch_c return LuvColor( luv_l, luv_u, luv_v, illuminant=cobj.illuminant, observer=cobj.observer)
[ "def", "LCHuv_to_Luv", "(", "cobj", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "luv_l", "=", "cobj", ".", "lch_l", "luv_u", "=", "math", ".", "cos", "(", "math", ".", "radians", "(", "cobj", ".", "lch_h", ")", ")", "*", "cobj", ".", "lch_c", "luv_v", "=", "math", ".", "sin", "(", "math", ".", "radians", "(", "cobj", ".", "lch_h", ")", ")", "*", "cobj", ".", "lch_c", "return", "LuvColor", "(", "luv_l", ",", "luv_u", ",", "luv_v", ",", "illuminant", "=", "cobj", ".", "illuminant", ",", "observer", "=", "cobj", ".", "observer", ")" ]
Convert from LCH(uv) to Luv.
[ "Convert", "from", "LCH", "(", "uv", ")", "to", "Luv", "." ]
train
https://github.com/gtaylor/python-colormath/blob/1d168613718d2d7d31ec4230524e987ef66823c7/colormath/color_conversions.py#L355-L363
gtaylor/python-colormath
colormath/color_conversions.py
xyY_to_XYZ
def xyY_to_XYZ(cobj, *args, **kwargs): """ Convert from xyY to XYZ. """ # avoid division by zero if cobj.xyy_y == 0.0: xyz_x = 0.0 xyz_y = 0.0 xyz_z = 0.0 else: xyz_x = (cobj.xyy_x * cobj.xyy_Y) / cobj.xyy_y xyz_y = cobj.xyy_Y xyz_z = ((1.0 - cobj.xyy_x - cobj.xyy_y) * xyz_y) / cobj.xyy_y return XYZColor( xyz_x, xyz_y, xyz_z, illuminant=cobj.illuminant, observer=cobj.observer)
python
def xyY_to_XYZ(cobj, *args, **kwargs): """ Convert from xyY to XYZ. """ # avoid division by zero if cobj.xyy_y == 0.0: xyz_x = 0.0 xyz_y = 0.0 xyz_z = 0.0 else: xyz_x = (cobj.xyy_x * cobj.xyy_Y) / cobj.xyy_y xyz_y = cobj.xyy_Y xyz_z = ((1.0 - cobj.xyy_x - cobj.xyy_y) * xyz_y) / cobj.xyy_y return XYZColor( xyz_x, xyz_y, xyz_z, illuminant=cobj.illuminant, observer=cobj.observer)
[ "def", "xyY_to_XYZ", "(", "cobj", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "# avoid division by zero", "if", "cobj", ".", "xyy_y", "==", "0.0", ":", "xyz_x", "=", "0.0", "xyz_y", "=", "0.0", "xyz_z", "=", "0.0", "else", ":", "xyz_x", "=", "(", "cobj", ".", "xyy_x", "*", "cobj", ".", "xyy_Y", ")", "/", "cobj", ".", "xyy_y", "xyz_y", "=", "cobj", ".", "xyy_Y", "xyz_z", "=", "(", "(", "1.0", "-", "cobj", ".", "xyy_x", "-", "cobj", ".", "xyy_y", ")", "*", "xyz_y", ")", "/", "cobj", ".", "xyy_y", "return", "XYZColor", "(", "xyz_x", ",", "xyz_y", ",", "xyz_z", ",", "illuminant", "=", "cobj", ".", "illuminant", ",", "observer", "=", "cobj", ".", "observer", ")" ]
Convert from xyY to XYZ.
[ "Convert", "from", "xyY", "to", "XYZ", "." ]
train
https://github.com/gtaylor/python-colormath/blob/1d168613718d2d7d31ec4230524e987ef66823c7/colormath/color_conversions.py#L368-L383
gtaylor/python-colormath
colormath/color_conversions.py
XYZ_to_xyY
def XYZ_to_xyY(cobj, *args, **kwargs): """ Convert from XYZ to xyY. """ xyz_sum = cobj.xyz_x + cobj.xyz_y + cobj.xyz_z # avoid division by zero if xyz_sum == 0.0: xyy_x = 0.0 xyy_y = 0.0 else: xyy_x = cobj.xyz_x / xyz_sum xyy_y = cobj.xyz_y / xyz_sum xyy_Y = cobj.xyz_y return xyYColor( xyy_x, xyy_y, xyy_Y, observer=cobj.observer, illuminant=cobj.illuminant)
python
def XYZ_to_xyY(cobj, *args, **kwargs): """ Convert from XYZ to xyY. """ xyz_sum = cobj.xyz_x + cobj.xyz_y + cobj.xyz_z # avoid division by zero if xyz_sum == 0.0: xyy_x = 0.0 xyy_y = 0.0 else: xyy_x = cobj.xyz_x / xyz_sum xyy_y = cobj.xyz_y / xyz_sum xyy_Y = cobj.xyz_y return xyYColor( xyy_x, xyy_y, xyy_Y, observer=cobj.observer, illuminant=cobj.illuminant)
[ "def", "XYZ_to_xyY", "(", "cobj", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "xyz_sum", "=", "cobj", ".", "xyz_x", "+", "cobj", ".", "xyz_y", "+", "cobj", ".", "xyz_z", "# avoid division by zero", "if", "xyz_sum", "==", "0.0", ":", "xyy_x", "=", "0.0", "xyy_y", "=", "0.0", "else", ":", "xyy_x", "=", "cobj", ".", "xyz_x", "/", "xyz_sum", "xyy_y", "=", "cobj", ".", "xyz_y", "/", "xyz_sum", "xyy_Y", "=", "cobj", ".", "xyz_y", "return", "xyYColor", "(", "xyy_x", ",", "xyy_y", ",", "xyy_Y", ",", "observer", "=", "cobj", ".", "observer", ",", "illuminant", "=", "cobj", ".", "illuminant", ")" ]
Convert from XYZ to xyY.
[ "Convert", "from", "XYZ", "to", "xyY", "." ]
train
https://github.com/gtaylor/python-colormath/blob/1d168613718d2d7d31ec4230524e987ef66823c7/colormath/color_conversions.py#L388-L403
gtaylor/python-colormath
colormath/color_conversions.py
XYZ_to_Luv
def XYZ_to_Luv(cobj, *args, **kwargs): """ Convert from XYZ to Luv """ temp_x = cobj.xyz_x temp_y = cobj.xyz_y temp_z = cobj.xyz_z denom = temp_x + (15.0 * temp_y) + (3.0 * temp_z) # avoid division by zero if denom == 0.0: luv_u = 0.0 luv_v = 0.0 else: luv_u = (4.0 * temp_x) / denom luv_v = (9.0 * temp_y) / denom illum = cobj.get_illuminant_xyz() temp_y = temp_y / illum["Y"] if temp_y > color_constants.CIE_E: temp_y = math.pow(temp_y, (1.0 / 3.0)) else: temp_y = (7.787 * temp_y) + (16.0 / 116.0) ref_U = (4.0 * illum["X"]) / (illum["X"] + (15.0 * illum["Y"]) + (3.0 * illum["Z"])) ref_V = (9.0 * illum["Y"]) / (illum["X"] + (15.0 * illum["Y"]) + (3.0 * illum["Z"])) luv_l = (116.0 * temp_y) - 16.0 luv_u = 13.0 * luv_l * (luv_u - ref_U) luv_v = 13.0 * luv_l * (luv_v - ref_V) return LuvColor( luv_l, luv_u, luv_v, observer=cobj.observer, illuminant=cobj.illuminant)
python
def XYZ_to_Luv(cobj, *args, **kwargs): """ Convert from XYZ to Luv """ temp_x = cobj.xyz_x temp_y = cobj.xyz_y temp_z = cobj.xyz_z denom = temp_x + (15.0 * temp_y) + (3.0 * temp_z) # avoid division by zero if denom == 0.0: luv_u = 0.0 luv_v = 0.0 else: luv_u = (4.0 * temp_x) / denom luv_v = (9.0 * temp_y) / denom illum = cobj.get_illuminant_xyz() temp_y = temp_y / illum["Y"] if temp_y > color_constants.CIE_E: temp_y = math.pow(temp_y, (1.0 / 3.0)) else: temp_y = (7.787 * temp_y) + (16.0 / 116.0) ref_U = (4.0 * illum["X"]) / (illum["X"] + (15.0 * illum["Y"]) + (3.0 * illum["Z"])) ref_V = (9.0 * illum["Y"]) / (illum["X"] + (15.0 * illum["Y"]) + (3.0 * illum["Z"])) luv_l = (116.0 * temp_y) - 16.0 luv_u = 13.0 * luv_l * (luv_u - ref_U) luv_v = 13.0 * luv_l * (luv_v - ref_V) return LuvColor( luv_l, luv_u, luv_v, observer=cobj.observer, illuminant=cobj.illuminant)
[ "def", "XYZ_to_Luv", "(", "cobj", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "temp_x", "=", "cobj", ".", "xyz_x", "temp_y", "=", "cobj", ".", "xyz_y", "temp_z", "=", "cobj", ".", "xyz_z", "denom", "=", "temp_x", "+", "(", "15.0", "*", "temp_y", ")", "+", "(", "3.0", "*", "temp_z", ")", "# avoid division by zero", "if", "denom", "==", "0.0", ":", "luv_u", "=", "0.0", "luv_v", "=", "0.0", "else", ":", "luv_u", "=", "(", "4.0", "*", "temp_x", ")", "/", "denom", "luv_v", "=", "(", "9.0", "*", "temp_y", ")", "/", "denom", "illum", "=", "cobj", ".", "get_illuminant_xyz", "(", ")", "temp_y", "=", "temp_y", "/", "illum", "[", "\"Y\"", "]", "if", "temp_y", ">", "color_constants", ".", "CIE_E", ":", "temp_y", "=", "math", ".", "pow", "(", "temp_y", ",", "(", "1.0", "/", "3.0", ")", ")", "else", ":", "temp_y", "=", "(", "7.787", "*", "temp_y", ")", "+", "(", "16.0", "/", "116.0", ")", "ref_U", "=", "(", "4.0", "*", "illum", "[", "\"X\"", "]", ")", "/", "(", "illum", "[", "\"X\"", "]", "+", "(", "15.0", "*", "illum", "[", "\"Y\"", "]", ")", "+", "(", "3.0", "*", "illum", "[", "\"Z\"", "]", ")", ")", "ref_V", "=", "(", "9.0", "*", "illum", "[", "\"Y\"", "]", ")", "/", "(", "illum", "[", "\"X\"", "]", "+", "(", "15.0", "*", "illum", "[", "\"Y\"", "]", ")", "+", "(", "3.0", "*", "illum", "[", "\"Z\"", "]", ")", ")", "luv_l", "=", "(", "116.0", "*", "temp_y", ")", "-", "16.0", "luv_u", "=", "13.0", "*", "luv_l", "*", "(", "luv_u", "-", "ref_U", ")", "luv_v", "=", "13.0", "*", "luv_l", "*", "(", "luv_v", "-", "ref_V", ")", "return", "LuvColor", "(", "luv_l", ",", "luv_u", ",", "luv_v", ",", "observer", "=", "cobj", ".", "observer", ",", "illuminant", "=", "cobj", ".", "illuminant", ")" ]
Convert from XYZ to Luv
[ "Convert", "from", "XYZ", "to", "Luv" ]
train
https://github.com/gtaylor/python-colormath/blob/1d168613718d2d7d31ec4230524e987ef66823c7/colormath/color_conversions.py#L408-L439
gtaylor/python-colormath
colormath/color_conversions.py
XYZ_to_Lab
def XYZ_to_Lab(cobj, *args, **kwargs): """ Converts XYZ to Lab. """ illum = cobj.get_illuminant_xyz() temp_x = cobj.xyz_x / illum["X"] temp_y = cobj.xyz_y / illum["Y"] temp_z = cobj.xyz_z / illum["Z"] if temp_x > color_constants.CIE_E: temp_x = math.pow(temp_x, (1.0 / 3.0)) else: temp_x = (7.787 * temp_x) + (16.0 / 116.0) if temp_y > color_constants.CIE_E: temp_y = math.pow(temp_y, (1.0 / 3.0)) else: temp_y = (7.787 * temp_y) + (16.0 / 116.0) if temp_z > color_constants.CIE_E: temp_z = math.pow(temp_z, (1.0 / 3.0)) else: temp_z = (7.787 * temp_z) + (16.0 / 116.0) lab_l = (116.0 * temp_y) - 16.0 lab_a = 500.0 * (temp_x - temp_y) lab_b = 200.0 * (temp_y - temp_z) return LabColor( lab_l, lab_a, lab_b, observer=cobj.observer, illuminant=cobj.illuminant)
python
def XYZ_to_Lab(cobj, *args, **kwargs): """ Converts XYZ to Lab. """ illum = cobj.get_illuminant_xyz() temp_x = cobj.xyz_x / illum["X"] temp_y = cobj.xyz_y / illum["Y"] temp_z = cobj.xyz_z / illum["Z"] if temp_x > color_constants.CIE_E: temp_x = math.pow(temp_x, (1.0 / 3.0)) else: temp_x = (7.787 * temp_x) + (16.0 / 116.0) if temp_y > color_constants.CIE_E: temp_y = math.pow(temp_y, (1.0 / 3.0)) else: temp_y = (7.787 * temp_y) + (16.0 / 116.0) if temp_z > color_constants.CIE_E: temp_z = math.pow(temp_z, (1.0 / 3.0)) else: temp_z = (7.787 * temp_z) + (16.0 / 116.0) lab_l = (116.0 * temp_y) - 16.0 lab_a = 500.0 * (temp_x - temp_y) lab_b = 200.0 * (temp_y - temp_z) return LabColor( lab_l, lab_a, lab_b, observer=cobj.observer, illuminant=cobj.illuminant)
[ "def", "XYZ_to_Lab", "(", "cobj", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "illum", "=", "cobj", ".", "get_illuminant_xyz", "(", ")", "temp_x", "=", "cobj", ".", "xyz_x", "/", "illum", "[", "\"X\"", "]", "temp_y", "=", "cobj", ".", "xyz_y", "/", "illum", "[", "\"Y\"", "]", "temp_z", "=", "cobj", ".", "xyz_z", "/", "illum", "[", "\"Z\"", "]", "if", "temp_x", ">", "color_constants", ".", "CIE_E", ":", "temp_x", "=", "math", ".", "pow", "(", "temp_x", ",", "(", "1.0", "/", "3.0", ")", ")", "else", ":", "temp_x", "=", "(", "7.787", "*", "temp_x", ")", "+", "(", "16.0", "/", "116.0", ")", "if", "temp_y", ">", "color_constants", ".", "CIE_E", ":", "temp_y", "=", "math", ".", "pow", "(", "temp_y", ",", "(", "1.0", "/", "3.0", ")", ")", "else", ":", "temp_y", "=", "(", "7.787", "*", "temp_y", ")", "+", "(", "16.0", "/", "116.0", ")", "if", "temp_z", ">", "color_constants", ".", "CIE_E", ":", "temp_z", "=", "math", ".", "pow", "(", "temp_z", ",", "(", "1.0", "/", "3.0", ")", ")", "else", ":", "temp_z", "=", "(", "7.787", "*", "temp_z", ")", "+", "(", "16.0", "/", "116.0", ")", "lab_l", "=", "(", "116.0", "*", "temp_y", ")", "-", "16.0", "lab_a", "=", "500.0", "*", "(", "temp_x", "-", "temp_y", ")", "lab_b", "=", "200.0", "*", "(", "temp_y", "-", "temp_z", ")", "return", "LabColor", "(", "lab_l", ",", "lab_a", ",", "lab_b", ",", "observer", "=", "cobj", ".", "observer", ",", "illuminant", "=", "cobj", ".", "illuminant", ")" ]
Converts XYZ to Lab.
[ "Converts", "XYZ", "to", "Lab", "." ]
train
https://github.com/gtaylor/python-colormath/blob/1d168613718d2d7d31ec4230524e987ef66823c7/colormath/color_conversions.py#L444-L472
gtaylor/python-colormath
colormath/color_conversions.py
XYZ_to_RGB
def XYZ_to_RGB(cobj, target_rgb, *args, **kwargs): """ XYZ to RGB conversion. """ temp_X = cobj.xyz_x temp_Y = cobj.xyz_y temp_Z = cobj.xyz_z logger.debug(" \- Target RGB space: %s", target_rgb) target_illum = target_rgb.native_illuminant logger.debug(" \- Target native illuminant: %s", target_illum) logger.debug(" \- XYZ color's illuminant: %s", cobj.illuminant) # If the XYZ values were taken with a different reference white than the # native reference white of the target RGB space, a transformation matrix # must be applied. if cobj.illuminant != target_illum: logger.debug(" \* Applying transformation from %s to %s ", cobj.illuminant, target_illum) # Get the adjusted XYZ values, adapted for the target illuminant. temp_X, temp_Y, temp_Z = apply_chromatic_adaptation( temp_X, temp_Y, temp_Z, orig_illum=cobj.illuminant, targ_illum=target_illum) logger.debug(" \* New values: %.3f, %.3f, %.3f", temp_X, temp_Y, temp_Z) # Apply an RGB working space matrix to the XYZ values (matrix mul). rgb_r, rgb_g, rgb_b = apply_RGB_matrix( temp_X, temp_Y, temp_Z, rgb_type=target_rgb, convtype="xyz_to_rgb") # v linear_channels = dict(r=rgb_r, g=rgb_g, b=rgb_b) # V nonlinear_channels = {} if target_rgb == sRGBColor: for channel in ['r', 'g', 'b']: v = linear_channels[channel] if v <= 0.0031308: nonlinear_channels[channel] = v * 12.92 else: nonlinear_channels[channel] = 1.055 * math.pow(v, 1 / 2.4) - 0.055 elif target_rgb == BT2020Color: if kwargs.get('is_12_bits_system'): a, b = 1.0993, 0.0181 else: a, b = 1.099, 0.018 for channel in ['r', 'g', 'b']: v = linear_channels[channel] if v < b: nonlinear_channels[channel] = v * 4.5 else: nonlinear_channels[channel] = a * math.pow(v, 0.45) - (a - 1) else: # If it's not sRGB... for channel in ['r', 'g', 'b']: v = linear_channels[channel] nonlinear_channels[channel] = math.pow(v, 1 / target_rgb.rgb_gamma) return target_rgb( nonlinear_channels['r'], nonlinear_channels['g'], nonlinear_channels['b'])
python
def XYZ_to_RGB(cobj, target_rgb, *args, **kwargs): """ XYZ to RGB conversion. """ temp_X = cobj.xyz_x temp_Y = cobj.xyz_y temp_Z = cobj.xyz_z logger.debug(" \- Target RGB space: %s", target_rgb) target_illum = target_rgb.native_illuminant logger.debug(" \- Target native illuminant: %s", target_illum) logger.debug(" \- XYZ color's illuminant: %s", cobj.illuminant) # If the XYZ values were taken with a different reference white than the # native reference white of the target RGB space, a transformation matrix # must be applied. if cobj.illuminant != target_illum: logger.debug(" \* Applying transformation from %s to %s ", cobj.illuminant, target_illum) # Get the adjusted XYZ values, adapted for the target illuminant. temp_X, temp_Y, temp_Z = apply_chromatic_adaptation( temp_X, temp_Y, temp_Z, orig_illum=cobj.illuminant, targ_illum=target_illum) logger.debug(" \* New values: %.3f, %.3f, %.3f", temp_X, temp_Y, temp_Z) # Apply an RGB working space matrix to the XYZ values (matrix mul). rgb_r, rgb_g, rgb_b = apply_RGB_matrix( temp_X, temp_Y, temp_Z, rgb_type=target_rgb, convtype="xyz_to_rgb") # v linear_channels = dict(r=rgb_r, g=rgb_g, b=rgb_b) # V nonlinear_channels = {} if target_rgb == sRGBColor: for channel in ['r', 'g', 'b']: v = linear_channels[channel] if v <= 0.0031308: nonlinear_channels[channel] = v * 12.92 else: nonlinear_channels[channel] = 1.055 * math.pow(v, 1 / 2.4) - 0.055 elif target_rgb == BT2020Color: if kwargs.get('is_12_bits_system'): a, b = 1.0993, 0.0181 else: a, b = 1.099, 0.018 for channel in ['r', 'g', 'b']: v = linear_channels[channel] if v < b: nonlinear_channels[channel] = v * 4.5 else: nonlinear_channels[channel] = a * math.pow(v, 0.45) - (a - 1) else: # If it's not sRGB... for channel in ['r', 'g', 'b']: v = linear_channels[channel] nonlinear_channels[channel] = math.pow(v, 1 / target_rgb.rgb_gamma) return target_rgb( nonlinear_channels['r'], nonlinear_channels['g'], nonlinear_channels['b'])
[ "def", "XYZ_to_RGB", "(", "cobj", ",", "target_rgb", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "temp_X", "=", "cobj", ".", "xyz_x", "temp_Y", "=", "cobj", ".", "xyz_y", "temp_Z", "=", "cobj", ".", "xyz_z", "logger", ".", "debug", "(", "\" \\- Target RGB space: %s\"", ",", "target_rgb", ")", "target_illum", "=", "target_rgb", ".", "native_illuminant", "logger", ".", "debug", "(", "\" \\- Target native illuminant: %s\"", ",", "target_illum", ")", "logger", ".", "debug", "(", "\" \\- XYZ color's illuminant: %s\"", ",", "cobj", ".", "illuminant", ")", "# If the XYZ values were taken with a different reference white than the", "# native reference white of the target RGB space, a transformation matrix", "# must be applied.", "if", "cobj", ".", "illuminant", "!=", "target_illum", ":", "logger", ".", "debug", "(", "\" \\* Applying transformation from %s to %s \"", ",", "cobj", ".", "illuminant", ",", "target_illum", ")", "# Get the adjusted XYZ values, adapted for the target illuminant.", "temp_X", ",", "temp_Y", ",", "temp_Z", "=", "apply_chromatic_adaptation", "(", "temp_X", ",", "temp_Y", ",", "temp_Z", ",", "orig_illum", "=", "cobj", ".", "illuminant", ",", "targ_illum", "=", "target_illum", ")", "logger", ".", "debug", "(", "\" \\* New values: %.3f, %.3f, %.3f\"", ",", "temp_X", ",", "temp_Y", ",", "temp_Z", ")", "# Apply an RGB working space matrix to the XYZ values (matrix mul).", "rgb_r", ",", "rgb_g", ",", "rgb_b", "=", "apply_RGB_matrix", "(", "temp_X", ",", "temp_Y", ",", "temp_Z", ",", "rgb_type", "=", "target_rgb", ",", "convtype", "=", "\"xyz_to_rgb\"", ")", "# v", "linear_channels", "=", "dict", "(", "r", "=", "rgb_r", ",", "g", "=", "rgb_g", ",", "b", "=", "rgb_b", ")", "# V", "nonlinear_channels", "=", "{", "}", "if", "target_rgb", "==", "sRGBColor", ":", "for", "channel", "in", "[", "'r'", ",", "'g'", ",", "'b'", "]", ":", "v", "=", "linear_channels", "[", "channel", "]", "if", "v", "<=", "0.0031308", ":", "nonlinear_channels", "[", "channel", "]", "=", "v", "*", "12.92", "else", ":", "nonlinear_channels", "[", "channel", "]", "=", "1.055", "*", "math", ".", "pow", "(", "v", ",", "1", "/", "2.4", ")", "-", "0.055", "elif", "target_rgb", "==", "BT2020Color", ":", "if", "kwargs", ".", "get", "(", "'is_12_bits_system'", ")", ":", "a", ",", "b", "=", "1.0993", ",", "0.0181", "else", ":", "a", ",", "b", "=", "1.099", ",", "0.018", "for", "channel", "in", "[", "'r'", ",", "'g'", ",", "'b'", "]", ":", "v", "=", "linear_channels", "[", "channel", "]", "if", "v", "<", "b", ":", "nonlinear_channels", "[", "channel", "]", "=", "v", "*", "4.5", "else", ":", "nonlinear_channels", "[", "channel", "]", "=", "a", "*", "math", ".", "pow", "(", "v", ",", "0.45", ")", "-", "(", "a", "-", "1", ")", "else", ":", "# If it's not sRGB...", "for", "channel", "in", "[", "'r'", ",", "'g'", ",", "'b'", "]", ":", "v", "=", "linear_channels", "[", "channel", "]", "nonlinear_channels", "[", "channel", "]", "=", "math", ".", "pow", "(", "v", ",", "1", "/", "target_rgb", ".", "rgb_gamma", ")", "return", "target_rgb", "(", "nonlinear_channels", "[", "'r'", "]", ",", "nonlinear_channels", "[", "'g'", "]", ",", "nonlinear_channels", "[", "'b'", "]", ")" ]
XYZ to RGB conversion.
[ "XYZ", "to", "RGB", "conversion", "." ]
train
https://github.com/gtaylor/python-colormath/blob/1d168613718d2d7d31ec4230524e987ef66823c7/colormath/color_conversions.py#L477-L537
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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