Exemple #1
0
  def stop(self):
    try:
      pf = file(self.pidfile, 'r')
      pid = int(pf.read().strip())
      pf.close()
    except IOError:
      pid = None

    if not pid:
      print Color.colorear(MSG_PID_NO_EXISTE % self.pidfile, color=Color.WARNING)
      return # no es error en 'restart'

    # Matar el demonio
    try:
      while 1:
        os.kill(pid, SIGTERM)
        time.sleep(0.1)
    except OSError, err:
      codigo_error, msg_error = err
      if codigo_error == CODIGO_NO_SUCH_PROCESS:
        if os.path.exists(self.pidfile):
          os.remove(self.pidfile)
      else:
        print Color.colorear(msg_error)
        sys.exit(1)
Exemple #2
0
 def calcColor(self,red,green,blue):
     hsl = Hsl()
     color = Color()
     pix = "OTHER"
     HSL = hsl.rgb2hsl(red, green, blue)
     HSL[1] = round(HSL[1],2)
     HSL[2] = round(HSL[2],2)
     grayLevel = self.calcGrayLevel(red,green,blue)
     colorLevel = self.calcColorLevel(red,green,blue)
     grayLumLevel = self.calcGrayLumLevel(red, green, blue)
     for i in range(0,len(Hsl.__hueThresh__)):
         try:
             if(HSL[0]>=Hsl.__hueThresh__[i][0] and HSL[0]<=Hsl.__hueThresh__[i][1]):
                 if(HSL[1]>=Hsl.__satThresh__[i][0] and HSL[1]<Hsl.__satThresh__[i][1]):
                     if(HSL[2]>=Hsl.__lumThresh__[i][0] and HSL[2]<Hsl.__lumThresh__[i][1]):
                         pix = Hsl.__hslColors__[i]
                         if(grayLevel==0):
                             pix = Hsl.__hslColors__[i] + str(int(colorLevel))
                     
                         else:
                             if(pix=="Black" or pix=="White"):
                                 pix += str(colorLevel)
                             elif(pix=="Grey"):
                                 pix += str(colorLevel)
                             else:
                                 pix = "Gray" + str(grayLumLevel) + Hsl.__hslColors__[i] + str(colorLevel)
         
                         if(color.countColors(Hsl.__hslColors__[i])>=2):
                             pix = color.reassignLevels(pix,red,green,blue)
                         return str(int(grayLevel)) + pix 
         except IndexError:
             print "rgb::calcColor2() out of range!\n"
             print "__hueThresh__.Size: {}".format(len(Hsl.__hueThresh__))
Exemple #3
0
 def add_style(self, name="Default", fontname="Arial", fontsize=20,
               primarycolor="fff", secondarycolor="fff",
               bordcolor="000", shadowcolor="000",
               bold=False, italic=False, scalex=100, scaley=100,
               spacing=0, bord=2, shadow=0, alignment=2,
               marginl=10, marginr=20, marginv=10):
     if not isinstance(primarycolor, Color):
         primarycolor = Color.from_hex(primarycolor)
     if not isinstance(secondarycolor, Color):
         secondarycolor = Color.from_hex(secondarycolor)
     if not isinstance(bordcolor, Color):
         bordcolor = Color.from_hex(bordcolor)
     if not isinstance(shadowcolor, Color):
         shadowcolor = Color.from_hex(shadowcolor)
     style_item = {
         "name": name,
         "font": {"name": fontname, "size": fontsize},
         "color": {
             "primary": primarycolor.ass_long,
             "secondary": secondarycolor.ass_long,
             "bord": bordcolor.ass_long,
             "shadow": shadowcolor.ass_long},
         "bold": bold, "italic": italic, "scale": [scalex, scaley],
         "spacing": spacing, "bord": bord,
         "shadow": shadow, "alignment": alignment,
         "margin": {"l": marginl, "r": marginr, "v": marginv}}
     self._script_data["style"][name] = style_item
Exemple #4
0
 def testDefinesClamping(self):
     a, b, c = Color(0, 1, 0), Color(-0.4, 0.5, 8.2), Color(0.3, 3.9, -4.6)
     self.assEqual(a.clamped(), Color(0, 1, 0))
     self.assEqual(b.clamped(), Color(0, 0.5, 1))
     self.assEqual(c.clamped(), Color(0.3, 1, 0))
     self.assEqual(c, Color(0.3, 3.9, -4.6))
     c.clamp()
     self.assEqual(c, Color(0.3, 1, 0))
    def __init__(self, red=0.0, green=0.0, blue=0.0, alpha=1.0, position=0, string=None):
        Color.__init__(self, red, green, blue, alpha)
        self.position = position

        if string:
            array = string.split(':')
            #Color.set_color_as_hex(self, array[0])
            self.set_color_as_hex(array[0])
            self.position = array[1]
Exemple #6
0
 def __init__(self):
   self._theme = deepcopy(default)
   for scope in self._theme:
     for color_name in self._theme[scope]:
       # if color is hex rgb
       if re.search("#[0-90a-fA-F]{6}", self._theme[scope][color_name]):
         color = Color()
         color.fromRGBHex(default[scope][color_name])
         self._theme[scope][color_name] = color
Exemple #7
0
 def set_at(self, pos, color):
     """
     Set color of a surface pixel.
     The arguments represent position x,y and color of pixel.
     """
     color = Color(color)    #0.23
     try:
         self.setRGB(pos[0],pos[1],color.getRGB())  #0.23
     except:     #ArrayOutOfBoundsException
         raise IndexError
     return None
Exemple #8
0
 def get_at(self, pos):
     """
     Return color of a surface pixel.
     The pos argument represents x,y position of pixel.
     """
     x,y = pos       #*tuple unpack error in jython applet
     try:
         color = Color(self.getRGB(x,y))
     except:     #ArrayOutOfBoundsException
         raise IndexError
     return color.getRed(), color.getGreen(), color.getBlue(), color.getAlpha()  #0.23
Exemple #9
0
  def status(self):
    try:
      pf = file(self.pidfile, 'r')
      pid = int(pf.read().strip())
      pf.close()
    except IOError:
      pid = None
    print Color.colorear(MSJ_STATUS(self.__str__(), 
      pid and 'running' or 'stopped', 
      pid and ' with pid: {pid}.'.format(pid=pid) or '.'), color=pid and Color.OKGREEN or Color.WARNING)

    sys.exit()
Exemple #10
0
def gen_params(images):
    params = []
    c = Color()
    
    for i in range(0, images):
        el = {}
        el['color'] = c.rnd_color()
        el['contrast'] = c.contrast()
        el['id'] = gen_id()
        params.append(el)
    
    return params
Exemple #11
0
class ColorTestCase(unittest.TestCase):
    def setUp(self):
        self.red = Color(255, 0, 0)
        self.blue = Color(0, 0, 255)

    def test_get_red(self):
        self.assertEqual(self.red.get_red(), 255)

    def test_get_green(self):
        self.assertEqual(self.red.get_green(), 0)

    def test_get_blue(self):
        self.assertEqual(self.blue.get_blue(), 255)
Exemple #12
0
class TestColor(unittest.TestCase):

    def setUp(self):
        self.color1 = Color(42, 42, 42)
        self.color2 = Color(210, 210, 210)
        self.color3 = Color(42, 21, 58)
        self.color4 = Color(240, 41, 25)

    def tearDown(self):
        pass

    def test_color(self):
        self.assertTrue(self.color1.enough_contrast(self.color2))
        self.assertFalse(self.color3.enough_contrast(self.color4))
Exemple #13
0
  def start(self):
    try:
      pf = file(self.pidfile, 'r')
      pid = int(pf.read().strip())
      pf.close()
    except Exception as e:
      pid = None

    if pid:
      print Color.colorear(MSG_PID_EXISTE % self.pidfile)
      sys.exit(1)

    # start the daemon
    self.daemonize()
    self.run()
Exemple #14
0
 def replace_color(self, color, new_color=None):
     """
     Replace color with with new_color or with alpha.
     """
     pixels = self.getRGB(0,0,self.width,self.height,None,0,self.width)
     color1 = Color(color)    #0.23
     if new_color:
         color2 = Color(new_color)
     else:
         color2 = Color(color1.r,color1.g,color1.b,0)
     for i, pixel in enumerate(pixels):
         if pixel == color1.getRGB():
             pixels[i] = color2.getRGB()
     self.setRGB(0,0,self.width,self.height,pixels,0,self.width)
     return None
Exemple #15
0
 def __init__(self, position, color=Color.cyan()):
     """
     :type position: Vector
     :type color: Color
     """
     self.position = position
     self.color = color
Exemple #16
0
 def alpha_state(self, state, i, freq=0.3):
     """Return a state in which all strips brightness is set, cycling with i."""
     for s in range(self.strips):
         state = self.state_factory.set_strips(state, [s], Color.alpha(state[s], math.sin(freq * i) * 0.5 + 0.5))
         if DEBUG:
             print(state)
     return state
Exemple #17
0
 def __init__(self, strips, udp_address, udp_port):
     self.strips = strips
     self.network = Net(udp_address, udp_port)
     self.fft = None
     self.state_factory = State(strips)
     self.color = Color()
     self.groups = [[a] for a in list(range(strips))]
Exemple #18
0
    def __init__(self, 
                groups = [], 
                title = "", 
                description = "",
                default_color = "black", 
                alphabet = seq.generic_alphabet) :
        """  """
        self.title= title
        self.description = description
        self.default_color = Color.from_string(default_color)
        self.groups = groups
        self.alphabet = alphabet
            
        color = {}

        if alphabet in [seq.codon_dna_alphabet, seq.codon_rna_alphabet]:
            for cg in groups :
                color[cg.symbols] = cg.color
                if cg.symbols not in alphabet :
                    raise KeyError("Colored symbol does not exist in alphabet.")
        else:
            for cg in groups :
                for s in cg.symbols :
                    color[s] = cg.color
                    if s not in alphabet :
                        raise KeyError("Colored symbol does not exist in alphabet.")

        self._color = color
Exemple #19
0
  def __init__(self):
    self.palette = None
    self.color = Color()
    self.color.connect('changed', self.color_changed)

    self.icon_path = os.path.join(os.path.dirname(__file__), 'data', 'icons')

    self.init_config()
    self.build_gui()

    self.palette_dir = os.path.join(base.save_config_path(appinfo.pkgname), 'palettes')
    Palette.PaletteDir = self.palette_dir

    self.palette_list = PaletteList()
    self.palette_list.load(self.palette_dir)
    self.palette_combo.set_model(self.palette_list)

    # no palettes, so create default
    if len(self.palette_list) == 0:
      palette = Palette()
      palette.name = "Default Palette"
      palette.filename = os.path.join(self.palette_dir, 'default.gpl')
      self.palette_list.append(palette)

      self.palette_combo.select(0)

    self.colorpicker.set_color(self.color)

    self.load_config()
Exemple #20
0
    def __init__(self):
        self.palette = None
        self.color = Color()
        self.h_ids = {}
        self.color.connect("changed", self.color_changed)

        self.init_config()
        self.build_gui()

        self.palette_dir = os.path.join(base.save_config_path(appinfo.pkgname), "palettes")
        Palette.PaletteDir = self.palette_dir

        self.palette_list = PaletteList()
        self.palette_list.load(self.palette_dir)
        self.palette_combo.set_model(self.palette_list)

        # no palettes, so create default
        if len(self.palette_list) == 0:
            palette = Palette()
            palette.name = "Default Palette"
            palette.filename = os.path.join(self.palette_dir, "default.gpl")
            self.palette_list.append(palette)

            self.palette_combo.select(0)

        self.colorpicker.set_color(self.color)

        self.load_config()
    def compute(self, iterations, screen):
        # these are used for calculating the points corresponding to the pixels
        xStep = (self.xMax - self.xMin) / (screen.get_width() * 1.0)
        yStep = (self.yMax - self.yMin) / (screen.get_height() * 1.0)

        x = self.xMin * 1.0
        y = self.yMin * 1.0

        for i in range(0, screen.get_height()):
            for j in range(0, screen.get_width()):
                z = 0.0
                zi = 0.0
                inSet = True
                for k in range(0, iterations):
                    # z^2 = (a+bi)(a+bi) = a^2 + 2abi - b^2
                    newZ = (z*z) - (zi*zi) + x
                    newZI = 2*z*zi + y
                    z = newZ
                    zi = newZI
                    if ((z*z) + (zi*zi)) > 4:
                        inSet = False
                        colour = k
                        k = iterations

                if inSet:
                    pygame.draw.line(screen, Color.BLACK, (j,i),(j,i))
                else:
                    pygame.draw.line(screen, Color.to_RGB(colour), (j,i),(j,i))

                x += xStep

            y += yStep
            x = self.xMin
Exemple #22
0
    def __init__(self, pixels, width, height):
        self.pixels = pixels
        self.width = width
        self.height = height

        self.canvas = Canvas(width, height, pixels)

        # setup key handlers
        key_esc = 27
        self.handlers = {
            key_esc: self.exit
        }

        self.v1 = Vertex(Vector(0, 0), Color.cyan())
        self.v2 = Vertex(Vector(300, 100), Color.red())
        self.v3 = Vertex(Vector(200, 300), Color.green())
Exemple #23
0
  def cb_drag_data_received(self, widget, context, x, y, selection, target_type, time):
    success = False
    valid = False
    color = Color()

    if selection.data != None:
      try:
        if target_type == self.TARGET_TYPE_COLOR:
          col = struct.unpack("HHHH", selection.data)
          color.set_rgb16(*col[0:3])
          valid = True
        elif target_type == self.TARGET_TYPE_TEXT:
          color.set_hex(selection.data)
          valid = True
      except ValueError, struct.error:
        print("Invalid data dropped")
Exemple #24
0
  def load(self, filename):
    """
    Load the palette from a file

    The filename should be given as a the full path.
    """
    self.colors = []
    self.load_errors = []
    self.filename = filename

    try:
      with open(filename) as f:
        # Check that file is a palette file
        if f.readline().strip() != 'GIMP Palette':
          self.load_errors.append("Invalid file format.".format(filename))
          return False

        lineno = 0
        for line in f:
          lineno += 1
          if line[0] == '#': continue
          elif line[0:5] == 'Name:':
            self.name = line[5:].strip()
          elif line[0:8] == 'Columns:':
            try:
              self.columns = int(line[8:].strip())
            except ValueError:
              self.load_errors.append("Columns value (line {0}) must be integer. Using default value.".format(lineno))
              self.columns = 0
          else:
            try:
              r = int(line[0:3])
              g = int(line[4:7])
              b = int(line[8:11])
              cname = line[12:].strip()

              c = Color()
              c.name = cname
              c.set_rgb(r,g,b)
              self.colors.append(c)
            except: #XXX handle specific exceptions only
              self.load_errors.append("Invalid color entry on line {0}. Skipping.\n".format(lineno))
      self.emit('changed')
    except IOError:
        #if nonexistant filename is passed in, assume we want to save to that in the future
      pass
    return (len(self.load_errors) == 0)
Exemple #25
0
    def checkbox(self, value, checkmark='*'):
        if not value:
            return ' '

        if self.color:
            return Color.message(checkmark, Color.TEAL)
        else:
            return checkmark
Exemple #26
0
 def draw_point(self, point, color=Color.cyan()):
     """
     :type point: Vector
     :type color: Color
     :return: None
     """
     if 0 <= point.x < self.width and 0 <= point.y < self.height:
         self.put_pixel(point.x, point.y, color)
Exemple #27
0
    def ratio(self, value, maxval, pad=0):
        if pad > 1:
            value = self.pad(value, pad)

        if self.color:
            value = Color.ratio(value, maxval)

        return value
Exemple #28
0
    def out(self, msg, color=None, pad=0):
        if pad > 1:
            msg = self.pad(msg, pad)

        if self.color and color is not None:
            msg = Color.message(msg, color)

        return msg
Exemple #29
0
 def fft_pulse_color(self, color=Color.white, scale=1, delay=0.03, channel=0, threshold=0):
     self.fft_init()
     state = self.state_factory.state_off()
     while True:
         intensity = [((scale * i) if i > threshold else 0) for i in self.fft.intensity()]
         if DEBUG:
             print(intensity)
         state = self.state_factory.full_color(Color.alpha(color, intensity[channel] / 100))
         yield state
Exemple #30
0
 def __init__(self):
   """ Initialize color picker """
   super(ColorPicker, self).__init__()
   self.pick_rate = 60
   self.color = Color()
   self.mag = None
   self.picking = 0
   self.pick_timeout = None
   self.save_on_release = False
Exemple #31
0
 def test_can_convert_black_rgb_to_lab(self):
     color = Color()
     lab_color = self.converter.convert(color, ColorSpace("LAB"))
     self.assertEqual(lab_color,
                      Color(ColorSpace("LAB"), np.array([0, 128, 128])))
Exemple #32
0
 def test_can_convert_lab_to_rgb(self):
     color = Color(ColorSpace("LAB"), np.array([88, 148, 101]))
     rgb_color = self.converter.convert(color, ColorSpace("RGB"))
     self.assertEqual(rgb_color,
                      Color(ColorSpace("RGB"), np.array([90, 72, 124])))
Exemple #33
0
 def test_can_convert_lab_to_rgb_1(self):
     color = Color(ColorSpace("LAB"), np.array([80, 79, 185]))
     rgb_color = self.converter.convert(color, ColorSpace("RGB"))
     self.assertEqual(rgb_color,
                      Color(ColorSpace("RGB"), np.array([0, 89, 0])))
Exemple #34
0
 def test_can_convert_simple_rgb_to_lab(self):
     color = Color(ColorSpace("RGB"), np.array([0, 100, 0]))
     lab_color = self.converter.convert(color, ColorSpace("LAB"))
     self.assertEqual(lab_color,
                      Color(ColorSpace("LAB"), np.array([92, 85, 170])))
Exemple #35
0
 def get_properties(self):
     return Color.get_properties(self) + ['position']
"""
This program is so simple that I don't need the usual DISCLAIMER...

Example of using the Color and Picture data types from the booksite library.
"""

from color import Color
from picture import Picture
import stddraw

turquoise = Color(64, 224, 208)
stddraw.setPenColor(turquoise)
stddraw.setPenRadius(0.025)
stddraw.rectangle(.1, .1, .8, .8)

my_picture = Picture('karel.png')
stddraw.picture(my_picture, 0.5, 0.6)

stddraw.setPenColor(stddraw.BLACK)
stddraw.setFontSize(64)
stddraw.text(0.5, 0.25, 'I live!')
stddraw.show()
help(stddraw)

Exemple #37
0
 def test_can_convert_simple_hsv_to_rgb(self):
     color = Color(ColorSpace("HSV"), np.array([0, 100, 0]))
     rgb_color = self.converter.convert(color, ColorSpace("RGB"))
     self.assertEqual(rgb_color,
                      Color(ColorSpace("RGB"), np.array([0, 0, 0])))
Exemple #38
0
 def test_cannot_create_invalid_rgb_color_len(self):
     rand_color = np.random.randint(0, 255, size=(1, 10))
     with self.assertRaises(InvalidColorError):
         Color("RGB", rand_color)
Exemple #39
0
 def test_cannot_create_invalid_rgb_color_val_neg(self):
     rand_color = np.random.randint(-100, -10, size=(1, Color.COLOR_DIM))
     with self.assertRaises(InvalidColorError):
         Color(ColorSpace("RGB"), rand_color)
Exemple #40
0
 def test_can_create_rgb_color(self):
     color = Color(ColorSpace("RGB"), np.array([123, 45, 67]))
     self.assertEqual(
         str(color), "{} {}".format("RGB",
                                    np.array([123, 45, 67]).tolist()))
Exemple #41
0
 def test_can_create_default_lab_color(self):
     color = Color(ColorSpace("LAB"))
     self.assertEqual(str(color), "LAB [0, 0, 0]")
Exemple #42
0
 def test_can_create_default_hsv_color(self):
     color = Color(ColorSpace("HSV"))
     self.assertEqual(str(color), "HSV [0, 0, 0]")
Exemple #43
0
 def test_can_convert_hsv_to_rgb_6(self):
     color = Color(ColorSpace("HSV"), np.array([247, 108, 123]))
     rgb_color = self.converter.convert(color, ColorSpace("RGB"))
     self.assertEqual(rgb_color,
                      Color(ColorSpace("RGB"), np.array([123, 71, 81])))
    def grow(z, land1):
        deltatron = PGrid.get_deltatron()
        avg_slope = 0

        if Processing.get_processing_type() == Globals.mode_enum['predict']:
            Processing.set_current_year(
                Scenario.get_scen_value('prediction_start_date'))
        else:
            Processing.set_current_year(IGrid.igrid.get_urban_year(0))

        Utilities.init_grid(z.gridData)
        # print(z.gridData)
        if len(Scenario.get_scen_value('landuse_data_file')) > 0:
            Grow.landuse_init(deltatron.gridData, land1.gridData)

        seed = IGrid.igrid.get_urban_grid(0)
        Utilities.condition_gif(seed, z.gridData)

        if Scenario.get_scen_value('echo'):
            print("******************************************")
            if Processing.get_processing_type(
            ) == Globals.mode_enum['calibrate']:
                c_run = Processing.get_current_run()
                t_run = Processing.get_total_runs()
                print(f"Run = {c_run} of {t_run}"
                      f" ({100 * c_run / t_run:8.1f} percent complete)")

            print(
                f"Monte Carlo = {int(Processing.get_current_monte()) + 1} of "
                f"{Scenario.get_scen_value('monte_carlo_iterations')}")
            print(f"Processing.current_year = {Processing.get_current_year()}")
            print(f"Processing.stop_year = {Processing.get_stop_year()}")

        if Scenario.get_scen_value('logging') and int(
                Scenario.get_scen_value('log_processing_status')) > 0:
            Grow.completion_status()

        while Processing.get_current_year() < Processing.get_stop_year():
            # Increment Current Year
            Processing.increment_current_year()

            cur_yr = Processing.get_current_year()
            if Scenario.get_scen_value('echo'):
                print(f" {cur_yr}", end='')
                sys.stdout.flush()
                if (cur_yr +
                        1) % 10 == 0 or cur_yr == Processing.get_stop_year():
                    print()

            if Scenario.get_scen_value('logging'):
                Logger.log(f" {cur_yr}")
                if (cur_yr +
                        1) % 10 == 0 or cur_yr == Processing.get_stop_year():
                    Logger.log("")

            # Apply the Cellular Automaton Rules for this Year
            avg_slope, num_growth_pix, sng, sdc, og, rt, pop = Spread.spread(
                z, avg_slope)
            #print(f"rt: {rt}")
            sdg = 0  # this isn't passed into spread, but I don't know why then it's here
            Stats.set_sng(sng)
            Stats.set_sdg(sdc)
            #Stats.set_sdc(sdc)
            Stats.set_og(og)
            Stats.set_rt(rt)
            Stats.set_pop(pop)

            if Scenario.get_scen_value('view_growth_types'):
                if IGrid.using_gif:
                    filename = f"{Scenario.get_scen_value('output_dir')}z_growth_types" \
                               f"_{Processing.get_current_run()}_{Processing.get_current_monte()}_" \
                               f"{Processing.get_current_year()}.gif"
                else:
                    filename = f"{Scenario.get_scen_value('output_dir')}z_growth_types" \
                               f"_{Processing.get_current_run()}_{Processing.get_current_monte()}_" \
                               f"{Processing.get_current_year()}.tif"

                date = str(Processing.get_current_year())
                ImageIO.write_gif(z, Color.get_growth_table(), filename, date,
                                  IGrid.nrows, IGrid.ncols)

            if len(Scenario.get_scen_value('landuse_data_file')) > 0:
                Grow.grow_landuse(land1, num_growth_pix)
            else:
                Grow.grow_non_landuse(z.gridData)

            seed = IGrid.igrid.get_urban_grid(0)
            Utilities.condition_gif(seed, z.gridData)

            # do Statistics
            Stats.update(num_growth_pix)

            # do Self Modification
            Coeff.self_modify(Stats.get_growth_rate(),
                              Stats.get_percent_urban())
            Coeff.write_current_coeff(Processing.get_current_run(),
                                      Processing.get_current_monte(),
                                      Processing.get_current_year())
Exemple #45
0
 def test_can_convert_hsv_to_rgb_4(self):
     color = Color(ColorSpace("HSV"), np.array([142, 50, 60]))
     rgb_color = self.converter.convert(color, ColorSpace("RGB"))
     self.assertEqual(rgb_color,
                      Color(ColorSpace("RGB"), np.array([48, 56, 60])))
Exemple #46
0
 def test_cannot_create_unimplemented_converter(self):
     color = Color(ColorSpace("HSV"))
     with self.assertRaises(InvalidConversion):
         self.converter.convert(color, ColorSpace("LAB"))
Exemple #47
0
 def test_can_convert_rgb_to_rgb(self):
     color = Color()
     rgb_color = self.converter.convert(color, ColorSpace("RGB"))
     self.assertEqual(color, rgb_color)
Exemple #48
0
 def test_can_create_empty_color(self):
     color = Color()
     self.assertTrue(isinstance(color, Color))
 def __init__(self, ancho, alto, color):
     FiguraGeometrica.__init__(self, ancho, alto)
     Color.__init__(self, color)
Exemple #50
0
 def test_can_convert_black_rgb_to_hsv(self):
     color = Color()
     hsv_color = self.converter.convert(color, ColorSpace("HSV"))
     self.assertEqual(hsv_color, Color(ColorSpace("HSV")))
Exemple #51
0
 def _get_feat(self, db, f_class, sample_name=""):
     if f_class == 'color':
         f_c = Color()
     elif f_class == 'daisy':
         f_c = Daisy()
     return f_c.make_samples(db, verbose=False, sample_name=sample_name)
Exemple #52
0
 def test_can_convert_simple_rgb_to_hsv(self):
     color = Color(ColorSpace("RGB"), np.array([0, 100, 0]))
     hsv_color = self.converter.convert(color, ColorSpace("HSV"))
     self.assertEquals(hsv_color,
                       Color(ColorSpace("HSV"), np.array([85, 255, 100])))
Exemple #53
0
 def serialize(self):
     return Color.serialize(self) + ":%d" % int(self.position)
Exemple #54
0
 def test_can_convert_rgb_to_hsv_1(self):
     color = Color(ColorSpace("RGB"), np.array([191, 71, 123]))
     hsv_color = self.converter.convert(color, ColorSpace("HSV"))
     self.assertEquals(hsv_color,
                       Color(ColorSpace("HSV"), np.array([237, 160, 191])))
def drawPiece(x, y, ay):

    stddraw.setPenRadius(0.008)

    if board[y][x] == 0: #diamond
        FILL = Color(250,252,255)
        stddraw.setPenColor(FILL)
        xs = [x+0.5, x+0.2, x+0.35, x+0.65, x+0.8]
        ys = [y+ay+0.2, y+ay+0.5, y+ay+0.7, y+ay+0.7, y+ay+0.5]
        stddraw.filledPolygon(xs, ys)

        OUTLINE = Color(220,225,255)
        stddraw.setPenColor(OUTLINE)
        xs = [x+0.5, x+0.2, x+0.35, x+0.65, x+0.8]
        ys = [y+ay+0.2, y+ay+0.5, y+ay+0.7, y+ay+0.7, y+ay+0.5]
        stddraw.polygon(xs, ys)

    if board[y][x] == 1: #emerald
        FILL = Color(180,255,180)
        stddraw.setPenColor(FILL)
        xs = [x+0.5, x+0.7, x+0.7, x+0.5, x+0.3, x+0.3]
        ys = [y+ay+0.8, y+ay+0.6, y+ay+0.4, y+ay+0.2, y+ay+0.4, y+ay+0.6]
        stddraw.filledPolygon(xs, ys)

        FILL = Color(210,255,210)
        stddraw.setPenColor(FILL)
        xs = [x+0.5, x+0.7, x+0.5, x+0.3]
        ys = [y+ay+0.8, y+ay+0.6, y+ay+0.4, y+ay+0.6]
        stddraw.filledPolygon(xs, ys)

        OUTLINE = Color(100,225,100)
        stddraw.setPenColor(OUTLINE)
        xs = [x+0.5, x+0.7, x+0.7, x+0.5, x+0.3, x+0.3]
        ys = [y+ay+0.8, y+ay+0.6, y+ay+0.4, y+ay+0.2, y+ay+0.4, y+ay+0.6]
        stddraw.polygon(xs, ys)

    if board[y][x] == 2: #ruby
        FILL = Color(245,140,140)
        stddraw.setPenColor(FILL)
        xs = [x+0.65, x+0.75, x+0.75, x+0.65, x+0.35, x+0.25, x+0.25, x+0.35]
        ys = [y+ay+0.8, y+ay+0.7, y+ay+0.3, y+ay+0.2, y+ay+0.2, y+ay+0.3, y+ay+0.7, y+ay+0.8]
        stddraw.filledPolygon(xs, ys)

        FILL2 = Color(255,180,180)
        stddraw.setPenColor(FILL2)
        xs = [x+0.65, x+0.75, x+0.5, x+0.25, x+0.35]
        ys = [y+ay+0.8, y+ay+0.7, y+ay+0.5, y+ay+0.7, y+ay+0.8]
        stddraw.filledPolygon(xs, ys)

        OUTLINE = Color(205,80,80)
        stddraw.setPenColor(OUTLINE)
        xs = [x+0.65, x+0.75, x+0.75, x+0.65, x+0.35, x+0.25, x+0.25, x+0.35]
        ys = [y+ay+0.8, y+ay+0.7, y+ay+0.3, y+ay+0.2, y+ay+0.2, y+ay+0.3, y+ay+0.7, y+ay+0.8]
        stddraw.polygon(xs, ys)

    if board[y][x] == 3: #saphhire
        FILL = Color(60,120,255)
        stddraw.setPenColor(FILL)
        stddraw.filledCircle(x+0.5, y+ay+0.5, 0.3)

        FILL = Color(80,190,255) 
        stddraw.setPenColor(FILL)
        stddraw.filledCircle(x+0.4, y+ay+0.6, 0.1)

        OUTLINE = Color(20,50,255) 
        stddraw.setPenColor(OUTLINE)
        stddraw.circle(x+0.5, y+ay+0.5, 0.3)

    if board[y][x] == 4: #topaz
        FILL = Color(255,255,200)
        stddraw.setPenColor(FILL)
        xs = [x+0.5, x+0.2, x+0.3, x+0.7]
        ys = [y+ay+0.2, y+ay+0.5, y+ay+0.7, y+ay+0.7]
        stddraw.filledPolygon(xs, ys)

        OUTLINE = Color(225,225,100)
        stddraw.setPenColor(OUTLINE)
        stddraw.polygon(xs, ys)

    if board[y][x] == 5: #amethyst
        FILL = Color(225,170,225)
        stddraw.setPenColor(FILL)
        xs = [x+0.5, x+0.8, x+0.5, x+0.2]
        ys = [y+ay+0.8, y+ay+0.5, y+ay+0.2, y+ay+0.5]
        stddraw.filledPolygon(xs, ys)

        FILL = Color(245,180,245)
        stddraw.setPenColor(FILL)
        xs = [x+0.5, x+0.5, x+0.2]
        ys = [y+ay+0.8, y+ay+0.4, y+ay+0.5]
        stddraw.filledPolygon(xs, ys)

        OUTLINE = Color(155,100,155)
        stddraw.setPenColor(OUTLINE)
        xs = [x+0.5, x+0.8, x+0.5, x+0.2]
        ys = [y+ay+0.8, y+ay+0.5, y+ay+0.2, y+ay+0.5]
        stddraw.polygon(xs, ys)

    if board[y][x] == 6: #aquamarine
        FILL = Color(100,250,220)
        stddraw.setPenColor(FILL)
        xs = [x+0.5, x+0.8, x+0.7, x+0.3, x+0.2]
        ys = [y+ay+0.8, y+ay+0.4, y+ay+0.2, y+ay+0.2, y+ay+0.4]
        stddraw.filledPolygon(xs, ys)

        FILL = Color(190,255,250)
        stddraw.setPenColor(FILL)
        xs = [x+0.5, x+0.7, x+0.6, x+0.4, x+0.3]
        ys = [y+ay+0.7, y+ay+0.45, y+ay+0.3, y+ay+0.3, y+ay+0.45]
        stddraw.filledPolygon(xs, ys)

        OUTLINE = Color(50,200,170) 
        stddraw.setPenColor(OUTLINE)
        xs = [x+0.5, x+0.8, x+0.7, x+0.3, x+0.2]
        ys = [y+ay+0.8, y+ay+0.4, y+ay+0.2, y+ay+0.2, y+ay+0.4]
        stddraw.polygon(xs, ys)

    if board[y][x] == 7: #citrine
        FILL = Color(255,160,70)
        stddraw.setPenColor(FILL)
        xs = [x+0.3, x+0.2, x+0.7, x+0.7]
        ys = [y+ay+0.2, y+ay+0.6, y+ay+0.8, y+ay+0.3]
        stddraw.filledPolygon(xs, ys)

        FILL = Color(255,190,90)
        stddraw.setPenColor(FILL)
        xs = [x+0.5, x+0.2, x+0.7, x+0.7]
        ys = [y+ay+0.5, y+ay+0.6, y+ay+0.8, y+ay+0.6]
        stddraw.filledPolygon(xs, ys)

        OUTLINE = Color(205,100,30) 
        stddraw.setPenColor(OUTLINE)
        xs = [x+0.3, x+0.2, x+0.7, x+0.7]
        ys = [y+ay+0.2, y+ay+0.6, y+ay+0.8, y+ay+0.3]
        stddraw.polygon(xs, ys)
Exemple #56
0
 def test_can_convert_black_hsv_to_rgb(self):
     color = Color(ColorSpace("HSV"))
     rgb_color = self.converter.convert(color, ColorSpace("RGB"))
     self.assertEqual(rgb_color, Color(ColorSpace("RGB")))
"""Unittests (pytest format) for the controller_handler"""
from unittest.mock import Mock

import pytweening
from numpy import linspace

from exceptions.exceptions import ControllerSetLEDException, InvalidRequestException
from color import Color
from config import FPS
from controller_handler import ControllerHandler
from controller import DMX_controller

START_COLOR = Color(201, 117, 128)
FINAL_COLOR = Color(193, 109, 120)
DEFAULT_DURATION = 300
DEFAULT_EASE = 'linear'
DEFAULT_ANIMATE_JSON = {'color': '#C9751C', 'duration': '15', 'ease': 'linear'}
DEFAULT_ANIMATION = [
    Color(r=201, g=117, b=128),
    Color(r=200, g=116, b=127),
    Color(r=199, g=115, b=126),
    Color(r=198, g=114, b=125),
    Color(r=197, g=113, b=124),
    Color(r=196, g=112, b=123),
    Color(r=195, g=111, b=122),
    Color(r=194, g=110, b=121),
    Color(r=193, g=109, b=120)
]
DEFAULT_TOGGLE_JSON = {'color': '#C9751C'}

Exemple #58
0
def tuple_from_type(plane: PlaneType) -> tuple:
    unit = Color.convert_hue_to_unit(plane.hsv.hue)
    return unit, plane.hsv.saturation
Exemple #59
0
 def test_can_create_default_rgb_color(self):
     color = Color()
     self.assertEqual(str(color), "RGB [0, 0, 0]")
Exemple #60
0
 def test_can_convert_rgb_to_lab(self):
     color = Color(ColorSpace("RGB"), np.array([91, 71, 123]))
     lab_color = self.converter.convert(color, ColorSpace("LAB"))
     self.assertEqual(lab_color,
                      Color(ColorSpace("LAB"), np.array([88, 148, 101])))