Best Python code snippet using yandex-tank
volume.py
Source:volume.py
...136 self.shown = True137 def update_transferframe(self,fast=False):138 self.update_color_map()139 if not fast:140 self.update_color_ramp()141 self.update_events()142 # update the colors143 if self.active!=None:144 if self.active in self.cmd.get_names("public_objects"):145 self.cmd.volume_color(self.active, self.active_ramp.getRamp())146 self.cmd.set_volume_ramp(self.active, self.active_ramp.getRampList())147 self.cmd.recolor()148 def update_is_needed(self):149 # check removed objects150 pubObj = self.cmd.get_names("public_objects")151 if not pubObj:152 # if ModalDraw is set (e.g., a movie is running)153 # then API cannot be accessed and get_names() returns154 # None. In this case, the volume panel info does not155 # need to be updated156 return False157 for x in self.object_list:158 if x not in pubObj:159 return True160 # check new objects161 for x in self.cmd.get_names("public_objects"):162 if "object:volume"==cmd.get_type(x):163 if x not in self.object_list.keys():164 return True165 return False166 def update_object_list(self):167 """168 update the internal state list169 """170 # purge list of removed objects171 pubObj = self.cmd.get_names("public_objects")172 object_list_copy = self.object_list.copy()173 for x in object_list_copy:174 if x not in pubObj:175 del self.object_list[x]176 # for all VOLUME type objects not known to the list177 for x in self.cmd.get_names("public_objects"):178 if "object:volume"==cmd.get_type(x):179 if x not in self.object_list.keys(): 180 if self.cmd.get_volume_is_updated(x) == 0:181 continue 182 # make a default pair for this volume object183 tmpMap = VolumeHist(self.cmd.get_volume_histogram(x,self.cmd),nBins=64)184 tmpRamp = ColorRamp(360,name=x)185 self.object_list[x] = (tmpRamp,tmpMap)186 if self.ramp_update.has_key(x) and self.ramp_update[x]:187 tmpRamp.addColor(0, (0,0,1,0))188 tmpRamp.addColor(359, (0,0,1,0))189 for data, alpha, col, kind in self.ramp_update[x]:190 self.addWithoutGUINow(x, data, alpha, col, kind=kind)191 self.ramp_update[x] = []192 tmpRamp.updateRamp()193 self.cmd.volume_color(x, tmpRamp.getRamp())194 self.cmd.set_volume_ramp(x, tmpRamp.getRampList())195 else:196 ramp_list = self.cmd.get_volume_ramp(x, self.cmd)197 if ramp_list:198 while ramp_list:199 tmpRamp.addColor(ramp_list[0], 200 (ramp_list[1], ramp_list[2], ramp_list[3], ramp_list[4]))201 ramp_list = ramp_list[5:]202 else: 203 tmpRamp.addColor(0, (0,0,1,0))204 tmpRamp.addColor(359, (0,0,1,0))205 tmpRamp.addColor(200, (0.0, 0.0, 1.0, 0.0))206 tmpRamp.addColor(210, (0.0, 0.8, 1.0, 0.2))207 tmpRamp.addColor(220, (0.0, 0.0, 1.0, 0.0))208 else:209 # need to regenerate the histogram210 (tmpRamp,tmpMap) = self.object_list[x]211 tmpMap = VolumeHist(self.cmd.get_volume_histogram(x,self.cmd),nBins=64)212 self.object_list[x] = (tmpRamp,tmpMap) 213 if len(self.object_list.keys())!=0:214 # guaranteed to exist215 k = self.object_list.keys()[0]216 self.active_ramp, self.active_map = self.object_list[k]217 self.active = k218 self.update_transferframe()219 def update_listbox(self):220 if self.shown:221 self.list_box.delete(0,END)222 else:223 # create the listbox and append the names224 self.list_box = Listbox(self)225 for x in self.object_list.keys():226 self.list_box.insert(END,x)227 self.list_box.grid(row=0, column=2, rowspan=3, sticky=E)228 self.list_box.selection_set(0)229 def update_color_map(self):230 # update the histrogram and points on it231 h,w = self.COLOR_MAP_HEIGHT, self.COLOR_MAP_WIDTH232 # setup the histrogram233 if self.active_map!=None:234 self.active_map_canvas = self.active_map.toCanvas(self,H=h,W=w,padX=self.padX,padY=self.padY)235 else:236 self.active_map_canvas = Canvas(self,height=h,width=w,bg="white")237 # clear content if redrawing238 self.active_map_canvas.delete("colorPt")239 # add color points to the canvas240 if self.active_ramp!=None:241 self.active_ramp.toCanvas(self.active_map_canvas,w,h,self.padX,self.padY)242 self.active_map_canvas.grid(row=0, column=0, columnspan=2, rowspan=2, sticky=NW)243 def update_color_ramp(self):244 h,w = self.COLOR_RAMP_HEIGHT, self.COLOR_RAMP_WIDTH245 # create the color ramp's canvas246 self.color_ramp_canvas = Canvas(self, height=h, width=w)247 # if active ramp, show it; otherwise show blank canvas248 if self.active_ramp!=None:249 self.rampPhotoImg = self.active_ramp.toPhotoImage(nRows=h)250 self.rampImg = self.color_ramp_canvas.create_image((self.padX,0),image=self.rampPhotoImg,anchor=NW)251 # position the canvas on the frame's grid252 self.color_ramp_canvas.grid(row=2, column=0, columnspan=2, sticky=NW)253 def update_events(self):254 #255 # Add a Point -- left mouse CLICK256 # Remove a Point -- middle mouse CLICK or257 # -- SHIFT-left mouse CLICK...
gamma.py
Source:gamma.py
1#!/usr/bin/env python2# -*- coding: utf-8 -*-3# Part of the PsychoPy library4# Copyright (C) 2002-2018 Jonathan Peirce (C) 2019 Open Science Tools Ltd.5# Distributed under the terms of the GNU General Public License (GPL).6# set the gamma LUT using platform-specific hardware calls7from __future__ import absolute_import, division, print_function8from builtins import map9from builtins import range10import numpy11import sys12import platform13import ctypes14import ctypes.util15from psychopy import logging, prefs16import os17# import platform specific C++ libs for controlling gamma18if sys.platform == 'win32':19 from ctypes import windll20elif sys.platform == 'darwin':21 try:22 carbon = ctypes.CDLL(23 '/System/Library/Frameworks/CoreGraphics.framework/CoreGraphics')24 except OSError:25 try:26 carbon = ctypes.CDLL(27 '/System/Library/Frameworks/Carbon.framework/Carbon')28 except OSError:29 carbon = ctypes.CDLL('/System/Library/Carbon.framework/Carbon')30elif sys.platform.startswith('linux'):31 # we need XF86VidMode32 xf86vm = ctypes.CDLL(ctypes.util.find_library('Xxf86vm'))33_TravisTesting = os.environ.get('TRAVIS') == 'true' # in Travis-CI testing34# Handling what to do if gamma can't be set35if prefs.general['gammaErrorPolicy'] == 'abort': # more clear to Builder users36 defaultGammaErrorPolicy = 'raise' # more clear to Python coders37else:38 defaultGammaErrorPolicy = prefs.general['gammaErrorPolicy']39problem_msg = 'The hardware look-up table function ({func:s}) failed. '40raise_msg = (problem_msg +41 'If you would like to proceed without look-up table '42 '(gamma) changes, you can change your `defaultGammaFailPolicy` in the '43 'application preferences. For more information see\n'44 'https://www.psychopy.org/troubleshooting.html#errors-with-getting-setting-the-gamma-ramp '45 )46warn_msg = problem_msg + 'Proceeding without look-up table (gamma) changes.'47def setGamma(screenID=None, newGamma=1.0, rampType=None, rampSize=None,48 driver=None, xDisplay=None, gammaErrorPolicy=None):49 """Sets gamma to a given value50 :param screenID: The screen ID in the Operating system51 :param newGamma: numeric or triplet (for independent RGB gamma vals)52 :param rampType: see :ref:`createLinearRamp` for possible ramp types53 :param rampSize: how large is the lookup table on your system?54 :param driver: string describing your gfx card driver (e.g. from pyglet)55 :param xDisplay: for linux only56 :param gammaErrorPolicy: whether you want to raise an error or warning57 :return:58 """59 if not gammaErrorPolicy:60 gammaErrorPolicy = defaultGammaErrorPolicy61 # make sure gamma is 3x1 array62 if type(newGamma) in [float, int]:63 newGamma = numpy.tile(newGamma, [3, 1])64 elif type(newGamma) in [list, tuple]:65 newGamma = numpy.array(newGamma)66 newGamma.shape = [3, 1]67 elif type(newGamma) is numpy.ndarray:68 newGamma.shape = [3, 1]69 # create LUT from gamma values70 newLUT = numpy.tile(71 createLinearRamp(rampType=rampType, rampSize=rampSize, driver=driver),72 (3, 1)73 )74 if numpy.all(newGamma == 1.0) == False:75 # correctly handles 1 or 3x1 gamma vals76 newLUT = newLUT**(1.0/numpy.array(newGamma))77 setGammaRamp(screenID, newLUT,78 xDisplay=xDisplay, gammaErrorPolicy=gammaErrorPolicy)79def setGammaRamp(screenID, newRamp, nAttempts=3, xDisplay=None,80 gammaErrorPolicy=None):81 """Sets the hardware look-up table, using platform-specific functions.82 Ramp should be provided as 3xN array in range 0:1.083 On windows the first attempt to set the ramp doesn't always work. The84 parameter nAttemps allows the user to determine how many attempts should85 be made before failing86 """87 if not gammaErrorPolicy:88 gammaErrorPolicy = defaultGammaErrorPolicy89 LUTlength = newRamp.shape[1]90 if newRamp.shape[0] != 3 and newRamp.shape[1] == 3:91 newRamp = numpy.ascontiguousarray(newRamp.transpose())92 if sys.platform == 'win32':93 newRamp = (numpy.around(255.0 * newRamp)).astype(numpy.uint16)94 # necessary, according to pyglet post from Martin Spacek95 newRamp.byteswap(True)96 for n in range(nAttempts):97 success = windll.gdi32.SetDeviceGammaRamp(98 screenID, newRamp.ctypes) # FB 50499 if success:100 break101 if not success:102 func = 'SetDeviceGammaRamp'103 if gammaErrorPolicy == 'raise':104 raise OSError(raise_msg.format(func=func))105 elif gammaErrorPolicy == 'warn':106 logging.warning(warn_msg.format(func=func))107 if sys.platform == 'darwin':108 newRamp = (newRamp).astype(numpy.float32)109 error = carbon.CGSetDisplayTransferByTable(110 screenID, LUTlength,111 newRamp[0, :].ctypes,112 newRamp[1, :].ctypes,113 newRamp[2, :].ctypes)114 if error:115 func = 'CGSetDisplayTransferByTable'116 if gammaErrorPolicy == 'raise':117 raise OSError(raise_msg.format(func=func))118 elif gammaErrorPolicy == 'warn':119 logging.warning(warn_msg.format(func=func))120 if sys.platform.startswith('linux') and not _TravisTesting:121 newRamp = (numpy.around(65535 * newRamp)).astype(numpy.uint16)122 success = xf86vm.XF86VidModeSetGammaRamp(123 xDisplay, screenID, LUTlength,124 newRamp[0, :].ctypes,125 newRamp[1, :].ctypes,126 newRamp[2, :].ctypes)127 if not success:128 func = 'XF86VidModeSetGammaRamp'129 if gammaErrorPolicy == 'raise':130 raise OSError(raise_msg.format(func=func))131 elif gammaErrorPolicy == 'warn':132 logging.warning(raise_msg.format(func=func))133 elif _TravisTesting:134 logging.warn("It looks like we're running in the Travis-CI testing "135 "environment. Hardware gamma table cannot be set")136def getGammaRamp(screenID, xDisplay=None, gammaErrorPolicy=None):137 """Ramp will be returned as 3xN array in range 0:1138 screenID :139 ID of the given display as defined by the OS140 xDisplay :141 the identity (int?) of the X display142 gammaErrorPolicy : str143 'raise' (ends the experiment) or 'warn' (logs a warning)144 """145 if not gammaErrorPolicy:146 gammaErrorPolicy = defaultGammaErrorPolicy147 rampSize = getGammaRampSize(screenID, xDisplay=xDisplay)148 if sys.platform == 'win32':149 # init R, G, and B ramps150 origramps = numpy.empty((3, rampSize), dtype=numpy.uint16)151 success = windll.gdi32.GetDeviceGammaRamp(152 screenID, origramps.ctypes) # FB 504153 if not success:154 func = 'GetDeviceGammaRamp'155 if gammaErrorPolicy == 'raise':156 raise OSError(raise_msg.format(func=func))157 elif gammaErrorPolicy == 'warn':158 logging.warning(warn_msg.format(func=func))159 else:160 origramps.byteswap(True) # back to 0:255161 origramps = origramps/255.0 # rescale to 0:1162 if sys.platform == 'darwin':163 # init R, G, and B ramps164 origramps = numpy.empty((3, rampSize), dtype=numpy.float32)165 n = numpy.empty([1], dtype=numpy.int)166 error = carbon.CGGetDisplayTransferByTable(167 screenID, rampSize,168 origramps[0, :].ctypes,169 origramps[1, :].ctypes,170 origramps[2, :].ctypes, n.ctypes)171 if error:172 func = 'CGSetDisplayTransferByTable'173 if gammaErrorPolicy == 'raise':174 raise OSError(raise_msg.format(func=func))175 elif gammaErrorPolicy == 'warn':176 logging.warning(warn_msg.format(func=func))177 if sys.platform.startswith('linux') and not _TravisTesting:178 origramps = numpy.empty((3, rampSize), dtype=numpy.uint16)179 success = xf86vm.XF86VidModeGetGammaRamp(180 xDisplay, screenID, rampSize,181 origramps[0, :].ctypes,182 origramps[1, :].ctypes,183 origramps[2, :].ctypes)184 if not success:185 func = 'XF86VidModeGetGammaRamp'186 if gammaErrorPolicy == 'raise':187 raise OSError(raise_msg.format(func=func))188 elif gammaErrorPolicy == 'warn':189 logging.warning(warn_msg.format(func=func))190 else:191 origramps = origramps/65535.0 # rescale to 0:1192 elif _TravisTesting:193 logging.warn("It looks like we're running in the Travis-CI testing "194 "environment. Hardware gamma table cannot be retrieved")195 origramps = None196 return origramps197def createLinearRamp(rampType=None, rampSize=256, driver=None):198 """Generate the Nx3 values for a linear gamma ramp on the current platform.199 This uses heuristics about known graphics cards to guess the 'rampType' if200 none is explicitly given.201 Much of this work is ported from LoadIdentityClut.m, by Mario Kleiner202 for the psychtoolbox203 rampType 0 : an 8-bit CLUT ranging 0:1204 This is seems correct for most windows machines and older macOS systems205 Known to be used by:206 OSX 10.4.9 PPC with GeForceFX-5200207 rampType 1 : an 8-bit CLUT ranging (1/256.0):1208 For some reason a number of macs then had a CLUT that (erroneously?)209 started with 1/256 rather than 0. Known to be used by:210 OSX 10.4.9 with ATI Mobility Radeon X1600211 OSX 10.5.8 with ATI Radeon HD-2600212 maybe all ATI cards?213 rampType 2 : a 10-bit CLUT ranging 0:(1023/1024)214 A slightly odd 10-bit CLUT that doesn't quite finish on 1.0!215 Known to be used by:216 OSX 10.5.8 with Geforce-9200M (MacMini)217 OSX 10.5.8 with Geforce-8800218 rampType 3 : a nasty, bug-fixing 10bit CLUT for crumby macOS drivers219 Craziest of them all for Snow leopard. Like rampType 2, except that220 the upper half of the table has 1/256.0 removed?!!221 Known to be used by:222 OSX 10.6.0 with NVidia Geforce-9200M223 """224 def _versionTuple(v):225 # for proper sorting: _versionTuple('10.8') < _versionTuple('10.10')226 return tuple(map(int, v.split('.')))227 if rampType is None:228 # try to determine rampType from heuristics including sys info229 osxVer = platform.mac_ver()[0] # '' on non-Mac230 # OSX231 if osxVer:232 osxVerTuple = _versionTuple(osxVer)233 # driver provided234 if driver is not None:235 # nvidia236 if 'NVIDIA' in driver:237 # leopard nVidia cards don't finish at 1.0!238 if _versionTuple("10.5") < osxVerTuple < _versionTuple("10.6"):239 rampType = 2240 # snow leopard cards are plain crazy!241 elif _versionTuple("10.6") < osxVerTuple:242 rampType = 3243 else:244 rampType = 1245 # non-nvidia246 else: # is ATI or unknown manufacturer, default to (1:256)/256247 # this is certainly correct for radeon2600 on 10.5.8 and248 # radeonX1600 on 10.4.9249 rampType = 1250 # no driver info given251 else: # is ATI or unknown manufacturer, default to (1:256)/256252 # this is certainly correct for radeon2600 on 10.5.8 and253 # radeonX1600 on 10.4.9254 rampType = 1255 # win32 or linux256 else: # for win32 and linux this is sensible, not clear about Vista and Windows7257 rampType = 0258 if rampType == 0:259 ramp = numpy.linspace(0.0, 1.0, num=rampSize)260 elif rampType == 1:261 ramp = numpy.linspace(1/256.0, 1.0, num=256)262 elif rampType == 2:263 ramp = numpy.linspace(0, 1023.0/1024, num=1024)264 elif rampType == 3:265 ramp = numpy.linspace(0, 1023.0/1024, num=1024)266 ramp[512:] = ramp[512:] - 1/256.0267 logging.info('Using gamma ramp type: %i' % rampType)268 return ramp269def getGammaRampSize(screenID, xDisplay=None, gammaErrorPolicy=None):270 """Returns the size of each channel of the gamma ramp."""271 if not gammaErrorPolicy:272 gammaErrorPolicy = defaultGammaErrorPolicy273 if sys.platform == 'win32':274 # windows documentation (for SetDeviceGammaRamp) seems to indicate that275 # the LUT size is always 256276 rampSize = 256277 elif sys.platform == 'darwin':278 rampSize = carbon.CGDisplayGammaTableCapacity(screenID)279 elif sys.platform.startswith('linux') and not _TravisTesting:280 rampSize = ctypes.c_int()281 success = xf86vm.XF86VidModeGetGammaRampSize(282 xDisplay,283 screenID,284 ctypes.byref(rampSize)285 )286 if not success:287 func = 'XF86VidModeGetGammaRampSize'288 if gammaErrorPolicy == 'raise':289 raise OSError(raise_msg.format(func=func))290 elif gammaErrorPolicy == 'warn':291 logging.warning(warn_msg.format(func=func))292 else:293 rampSize = rampSize.value294 else:295 assert _TravisTesting296 rampSize = 256297 if rampSize == 0:298 logging.warn(299 "The size of the gamma ramp was reported as 0. This can " +300 "mean that gamma settings have no effect. Proceeding with " +301 "a default gamma ramp size."302 )303 rampSize = 256...
ColorRampModel.py
Source:ColorRampModel.py
1class ColorPoint:2 """3 Simple color-storage class; stores way-points on a color ramp4 """5 def __init__(self,idx,col,colType):6 # index, X-coordinate, on a palette7 self.idx = idx8 # color; usually an RGBA quad9 self.color = col10 # One of ColorTypes members11 self.colorType = colType12 def __str__(self):13 return "(Index=%d; Color=(%0.3f,%0.3f,%0.3f,%0.3f); ColorType=%d)" % (self.idx, self.color[0], self.color[1], self.color[2], self.color[3], self.colorType)14class ColorTypes:15 """16 Simple enumerated type for internal color formats17 """18 RGBAi = 019 RGBAf = 120 HEX6 = 221 HEX8 = 322class ColorRamp:23 """24 Model for a simple color ramp25 Typical usage:26 c = ColorRamp(nColors=256)27 28 # must add boundaries29 c.addPoint(0, (0,0,0,0))30 c.addPoint(255, (1,1,1,1))31 32 # now add other colors33 c.addPoint(32, (128,0,0,0), colType=ColorTypes.RGBAi, colScale=255)34 c.addPoint(64, (128,255,255,255), colType=ColorTypes.RGBAi, colScale=255)35 print c36 RGBAf_ColorRamp = c.getRamp()37 RGBAi_ColorRamp = c.getRamp(colType=ColorTypes.RGBAi, colScale=255)38 RGBAhex_ColorRamp = c.getRamp(colType=ColorTypes.HEX6)39 RGBAhex_ColorRamp = c.getRamp(colType=ColorTypes.HEX8)40 41 """42 # we assume linear ramps for now43 LINEAR = 044 GAUSSIAN = 145 EXPONENTIAL = 246 def __init__(self, nColors, *args, **kwargs):47 # size of this ramp48 self.nColors = nColors49 # the list of RGBA float values50 self.ramp = []51 # ordered array of color indices52 self.keys = {}53 # ready to use; boolean; we need at least two54 # color points to define a ramp55 self.ready = False56 #57 if 'handle' in kwargs:58 self.handle = kwargs['handle']59 def __str__(self):60 s = "Ready to use: " + str(self.ready) + "\n"61 s+= "Keys: " + str(self.keys.keys()) + "\n"62 for k in self.keys:63 s += "Color[%d] = %s\n" % (k,self.keys[k])64 s += "ColorRamp with %d colors follows...\n" % self.nColors65 if self.ready:66 s += str(self.getRamp()) + "\n"67 else:68 s += "[]\n"69 return s70 def addColor(self, idx, col, colType=ColorTypes.RGBAf, colScale=1.0):71 # check user input: color location72 if idx<0 or idx>self.nColors-1:73 print "Error: Invalid color idx given. Valid values for idx are "74 print "Error: [0,%d), but was given was idx=%d" % (self.nColors-1,idx)75 return76 # check user input: duplicate color77 if idx in self.keys:78 print "Error: Invalid index, a color already exists at this point."79 print "Error: Please remove the color at this index before adding."80 return81 # check user input: color format82 if type(col) != ().__class__ or len(col)!=4:83 print "Error: Colors must be spefied as a RGBA tuple with four values."84 print "Error: %s was given instead." % str(col)85 return86 # check user input: color type format87 if colType not in (ColorTypes.RGBAi, ColorTypes.RGBAf):88 print "Error: Color type specification must be either, "89 print "Error: ColorRamp.RGBAi or ColorRamp.RGBAf"90 return91 userCol = None92 # convert color type if needed93 if colType==ColorTypes.RGBAf:94 userCol = col95 elif colType==ColorTypes.RGBAi:96 userCol = map(lambda c: float(c)/float(colScale), col)97 98 # create a ColorPoint and insert it99 self.keys[idx] = ColorPoint(idx, userCol, colType)100 # is this ramp yet good to use?101 self.updateReady()102 # what else do we need to do to modify the model?103 104 def removeColor(self, idx):105 if idx<0 or idx>self.nColors-1:106 print "Error: Tried to remove a color at a place not on this color ramp."107 print "Error: Valid values for the idx are [0,%d) but idx was %d" % (self.nColors,idx)108 # check user input109 if idx not in self.keys: return110 if idx<0 or idx>self.nColors-1: return111 # remove the point112 del self.keys[idx]113 # is this ramp still good to use?114 self.updateReady()115 def updateReady(self):116 # are we ready to use?117 self.ready = (0 in self.keys and self.nColors-1 in self.keys)118 def updateRamp(self, idx=None):119 120 # if idx is specified then it was either added or removed121 # so adjust the ramp about that point122 123 if not self.ready: 124 # no use in updating a ramp w/o proper colors125 print "Msg: This color ramp is not yet ready to use. Please add"126 print "Msg: at least two colors at the ramp's extreme points 0 and %d" % (self.nColors-1)127 return128 129 # OPTIMIZATION TODO:130 # if idx!=None and idx no in self.keys, then the point131 # was removed, just update around those pts132 # if idx!=None and does exists in self.keys, then they133 # just added this point, so update the pts around it134 135 self.ramp = []136 137 keyList = self.keys.keys()138 keyList.sort()139 keyList.reverse()140 print "KeyList is: " + str(keyList)141 lowerId = keyList.pop()142 while len(keyList)>0:143 upperId = keyList.pop()144 # number of colors in between145 span = abs(upperId-lowerId)146 # get the actual colors147 lowerCol, upperCol = self.keys[lowerId].color, self.keys[upperId].color148 for x in range(span):149 # linear mixing components150 cUpper = float(x) / float(span)151 cLower = 1.0 - cUpper152 153 self.ramp.append((cLower * lowerCol[0] + cUpper * upperCol[0], 154 cLower * lowerCol[1] + cUpper * upperCol[1], 155 cLower * lowerCol[2] + cUpper * upperCol[2], 156 cLower * lowerCol[3] + cUpper * upperCol[3])) 157 lowerId = upperId158 159 # fix the off-by one error160 self.ramp.append(upperCol)161 assert len(self.ramp)==self.nColors, "ColorRamp Logic Error: This ramp supports %d colors ONLY, but %d were found in the ramp." % (self.nColors, len(self.ramp))162 def getRamp(self, colType=ColorTypes.RGBAf, colScale=1.0):163 # update the ramp and return it164 self.updateRamp()165 if colType==ColorTypes.RGBAf:166 if colScale==1.0:167 return self.ramp168 elif colType==ColorTypes.HEX6:169 colScale = 255170 return map(lambda col: "#%02x%02x%02x" % (colScale*col[0],colScale*col[1],colScale*col[2]), self.ramp)171 elif colType==ColorTypes.HEX8:172 colScale = 255173 return map(lambda col: "#%02x%02x%02x%02x" % (colScale*col[0],colScale*col[1],colScale*col[2],colScale*col[3]), self.ramp)174 def toPhotoImageString(self,nRows=1):175 oneLine = "{" + " ".join(self.getRamp(ColorTypes.HEX6)) + "}"176 if nRows==1:177 return oneLine178 else:179 return " ".join([oneLine]*nRows)180 181 # this belongs in the view182 def toPhotoImage(self,nRows=1,root=None):183 try:184 from Tkinter import PhotoImage185 except ImportError, e:186 print "Error: could not import Tk. No image."187 print "Error: ", e188 return None189 190 img = PhotoImage(width=self.nColors, height=nRows)191 img.put(self.toPhotoImageString(nRows))192 return img193 def getHandle(self):194 return self.handle195 def setHandle(self,handle):196 self.handle = handle197class ColorRampView:198 """199 This handles the UI for mapping the on-screen200 Tcl/Tk UI components to the model, in a usable fashion.201 """202 def __init__(self):203 pass204class ColorRampController:205 """206 Controller207 Takes Model output and makes a UI component208 that allows interaction; feeds results to 209 the controller210 M = ColorRampModel(256)211 ...212 C = ColorRampController(M)213 img = C.toPhotoImage(nRows=100)214 215 can = Canvas(...)216 can.create_image(img, to=(padX,padY), anchor=NW)217 can.setupHandlers(...)218 """219 def __init__(self):220 pass221if __name__=="__main__":222 c = ColorRamp(256)223 # add some colors224 c.addColor(1,(0,0,0,0))225 print c226 c.addColor(2,(1,1,1,1))227 print c228 c.addColor(250,(0.5, 0.5, 0.5, 0.5))229 print c230 # range checking231 c.addColor(-1, (0,0,0,0))232 print c233 c.addColor(256, (1,2,3,4))234 print c235 # color scaling236 c.addColor(45, (128, 255, 64, 32), colType=ColorTypes.RGBAi, colScale=255)237 print c238 # remove a color239 c.removeColor(2)240 print c241 # range checking242 c.removeColor(-1)243 print c244 # range checking245 c.removeColor(2000)246 print c247 # check ready to use248 c.addColor(0, (0,0,0,0))249 print c250 c.addColor(8, (1.0, 0.4, 0.0, 0.0))251 print c252 c.addColor(255, (1,1,1,1))253 print c254 # check ramp types255 d = ColorRamp(32)256 d.addColor(0, (0,0,0,0), colType=ColorTypes.RGBAi, colScale=255)257 d.addColor(31, (255,255,255,255), colType=ColorTypes.RGBAi, colScale=255)258 d.addColor(15, (1.0, 0.0, 0.0, 1.0))259 260 print "Color Ramp as RGAf"261 print d.getRamp()262 print "Color Ramp as HEX6"263 print d.getRamp(ColorTypes.HEX6)264 print "Color Ramp as HEX8"265 print d.getRamp(ColorTypes.HEX8)266 267 print "Does adding/removing a pt screw up the model?"268 f = ColorRamp(360)269 # end pts270 f.addColor(0, (0,0,0,0))271 f.addColor(359, (1,1,1,1))272 print f273 print "Adding a pt"274 f.addColor(7, (1.0, 0.0, 0.5, 0.25))275 print f276 print "Removing a pt"277 f.removeColor(7)278 print f279 print "Add some more colors"280 f.addColor(90, (1.0, 0.0, 0.0, 1.0))281 f.addColor(270, (0.0, 0.0, 1.0, 1.0))282 f.addColor(180, (0.0, 1.0, 0.0, 1.0))283 print "Checking hex8 vlaues"284 print f.getRamp(ColorTypes.HEX8)285 print "To PhotoImage String: nRows=1"286 print f.toPhotoImageString()287 print "To PhotoImage String: nRows=32"288 print f.toPhotoImageString(16)289 290 try:291 from Tkinter import *292 root = Tk()293 padX, padY = 30, 30294 canvas = Canvas(root,height=10+padY,width=360+padX)295 print "Try to make a color ramp image"296 img = f.toPhotoImage(10)297 canvas.create_image((padX/2, padY/2),image=img,anchor=NW)298 canvas.pack()299 root.mainloop()300 except ImportError, e:301 print "WARNING: Tkinter not installed for this Python version."302 print "WARNING: Skipping the Tkinter test"...
Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!