-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathipythonblocks.py
1352 lines (1082 loc) · 38.3 KB
/
ipythonblocks.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""
ipythonblocks provides a BlockGrid class that displays a colored grid in the
IPython Notebook. The colors can be manipulated, making it useful for
practicing control flow stuctures and quickly seeing the results.
"""
# This file is copyright 2013 by Matt Davis and covered by the license at
# https://github.com/jiffyclub/ipythonblocks/blob/master/LICENSE.txt
import copy
import collections
import json
import numbers
import os
import sys
import time
import uuid
from collections import namedtuple
from operator import iadd
from functools import reduce
#from IPython.display import HTML, IFrame, display, clear_output
#from IPython.display import Image as ipyImage
__all__ = (
'Block',
'BlockGrid',
'Pixel',
'ImageGrid',
'InvalidColorSpec',
'ShapeMismatch',
'show_color',
'show_color_triple',
'embed_colorpicker',
'clear',
'colors',
'fui_colors',
'__version__',
)
__version__ = '1.9.dev'
_TABLE = ('<style type="text/css">'
'table.blockgrid {{border: none;}}'
' .blockgrid tr {{border: none;}}'
' .blockgrid td {{padding: 0px;}}'
' #blocks{0} td {{border: {1}px solid white;}}'
'</style>'
'<table id="blocks{0}" class="blockgrid"><tbody>{2}</tbody></table>')
_TR = '<tr>{0}</tr>'
_TD = ('<td title="{0}" style="width: {1}px; height: {1}px;'
'background-color: {2};"></td>')
_RGB = 'rgb({0}, {1}, {2})'
_TITLE = 'Index: [{0}, {1}] Color: ({2}, {3}, {4})'
_SINGLE_ITEM = 'single item'
_SINGLE_ROW = 'single row'
_ROW_SLICE = 'row slice'
_DOUBLE_SLICE = 'double slice'
_SMALLEST_BLOCK = 1
_POST_URL = 'http://www.ipythonblocks.org/post'
_GET_URL_PUBLIC = 'http://www.ipythonblocks.org/get/{0}'
_GET_URL_SECRET = 'http://www.ipythonblocks.org/get/secret/{0}'
class InvalidColorSpec(Exception):
"""
Error for a color value that is not a number.
"""
pass
class ShapeMismatch(Exception):
"""
Error for when a grid assigned to another doesn't have the same shape.
"""
pass
def clear():
"""
Clear the output of the current cell.
This is a thin wrapper around IPython.display.clear_output.
"""
clear_output()
def show_color(red, green, blue):
"""
Show a given color in the IPython Notebook.
Parameters
----------
red, green, blue : int
Integers on the range [0 - 255].
"""
div = ('<div style="height: 60px; min-width: 200px; '
'background-color: {0}"></div>')
display(HTML(div.format(_RGB.format(red, green, blue))))
def show_color_triple(rgb_triple):
"""
Show a given color in the IPython Notebook.
Parameters
----------
rgb_triple : iterable
A Python iterable containing three integers in the range [0 - 255]
representing red, green, and blue colors.
"""
return show_color(*rgb_triple)
def embed_colorpicker():
"""
Embed the web page www.colorpicker.com inside the IPython Notebook.
"""
display(
IFrame(src='http://www.colorpicker.com/', height='550px', width='100%')
)
def _color_property(name):
real_name = "_" + name
@property
def prop(self):
return getattr(self, real_name)
@prop.setter
def prop(self, value):
value = Block._check_value(value)
setattr(self, real_name, value)
return prop
def _flatten(thing, ignore_types=(str,)):
"""
Yield a single item or str/unicode or recursively yield from iterables.
Adapted from Beazley's Python Cookbook.
"""
if isinstance(thing, collections.Iterable) and \
not isinstance(thing, ignore_types):
for i in thing:
for x in _flatten(i):
yield x
else:
yield thing
def _parse_str_cell_spec(cells, length):
"""
Parse a single string cell specification representing either a single
integer or a slice.
Parameters
----------
cells : str
E.g. '5' for an int or '5:9' for a slice.
length : int
The number of items in the user's In history list. Used for
normalizing slices.
Returns
-------
cell_nos : list of int
"""
if ':' not in cells:
return _parse_cells_spec(int(cells), length)
else:
return _parse_cells_spec(slice(*[int(x) if x else None
for x in cells.split(':')]),
length)
def _parse_cells_spec(cells, length):
"""
Used by _get_code_cells to parse a cell specification string into an
ordered list of cell numbers.
Parameters
----------
cells : str, int, or slice
Specification of which cells to retrieve. Can be a single number,
a slice, or a combination of either separated by commas.
length : int
The number of items in the user's In history list. Used for
normalizing slices.
Returns
-------
cell_nos : list of int
Ordered list of cell numbers derived from spec.
"""
if isinstance(cells, int):
return [cells]
elif isinstance(cells, slice):
return list(range(*cells.indices(length)))
else:
# string parsing
return sorted(set(_flatten(_parse_str_cell_spec(s, length)
for s in cells.split(','))))
def _get_code_cells(cells):
"""
Get the inputs of the specified cells from the notebook.
Parameters
----------
cells : str, int, or slice
Specification of which cells to retrieve. Can be a single number,
a slice, or a combination of either separated by commas.
Returns
-------
code : list of str
Contents of cells as strings in chronological order.
"""
In = get_ipython().user_ns['In']
cells = _parse_cells_spec(cells, len(In))
return [In[x] for x in cells]
class Block(object):
"""
A colored square.
Parameters
----------
red, green, blue : int
Integers on the range [0 - 255].
size : int, optional
Length of the sides of this block in pixels. One is the lower limit.
Attributes
----------
red, green, blue : int
The color values for this `Block`. The color of the `Block` can be
updated by assigning new values to these attributes.
rgb : tuple of int
Tuple of (red, green, blue) values. Can be used to set all the colors
at once.
row, col : int
The zero-based grid position of this `Block`.
size : int
Length of the sides of this block in pixels. The block size can be
changed by modifying this attribute. Note that one is the lower limit.
"""
red = _color_property('red')
green = _color_property('green')
blue = _color_property('blue')
def __init__(self, red, green, blue, size=20):
self.red = red
self.green = green
self.blue = blue
self.size = size
self._row = None
self._col = None
@staticmethod
def _check_value(value):
"""
Check that a value is a number and constrain it to [0 - 255].
"""
if not isinstance(value, numbers.Number):
s = 'value must be a number. got {0}.'.format(value)
raise InvalidColorSpec(s)
return int(round(min(255, max(0, value))))
@property
def rgb(self):
return (self._red, self._green, self._blue)
@rgb.setter
def rgb(self, colors):
if len(colors) != 3:
s = 'Setting colors requires three values: (red, green, blue).'
raise ValueError(s)
self.red, self.green, self.blue = colors
@property
def row(self):
return self._row
@property
def col(self):
return self._col
@property
def size(self):
return self._size
@size.setter
def size(self, size):
self._size = max(_SMALLEST_BLOCK, size)
def set_colors(self, red, green, blue):
"""
Updated block colors.
Parameters
----------
red, green, blue : int
Integers on the range [0 - 255].
"""
self.red = red
self.green = green
self.blue = blue
def _update(self, other):
if isinstance(other, Block):
self.rgb = other.rgb
self.size = other.size
elif isinstance(other, collections.Sequence) and len(other) == 3:
self.rgb = other
else:
errmsg = (
'Value must be a Block or a sequence of 3 integers. '
'Got {0!r}.'
)
raise ValueError(errmsg.format(other))
@property
def _td(self):
"""
The HTML for a table cell with the background color of this Block.
"""
title = _TITLE.format(self._row, self._col,
self._red, self._green, self._blue)
rgb = _RGB.format(self._red, self._green, self._blue)
return _TD.format(title, self._size, rgb)
def _repr_html_(self):
return _TABLE.format(uuid.uuid4(), 0, _TR.format(self._td))
def show(self):
display(HTML(self._repr_html_()))
__hash__ = None
def __eq__(self, other):
if not isinstance(other, Block):
return False
return self.rgb == other.rgb and self.size == other.size
def __str__(self):
s = ['{0}'.format(self.__class__.__name__),
'Color: ({0}, {1}, {2})'.format(self._red,
self._green,
self._blue)]
# add position information if we have it
if self._row is not None:
s[0] += ' [{0}, {1}]'.format(self._row, self._col)
return os.linesep.join(s)
def __repr__(self):
type_name = type(self).__name__
return '{0}({1}, {2}, {3}, size={4})'.format(type_name,
self.red,
self.green,
self.blue,
self.size)
class BlockGrid(object):
"""
A grid of blocks whose colors can be individually controlled.
Parameters
----------
width : int
Number of blocks wide to make the grid.
height : int
Number of blocks high to make the grid.
fill : tuple of int, optional
An optional initial color for the grid, defaults to black.
Specified as a tuple of (red, green, blue). E.g.: (10, 234, 198)
block_size : int, optional
Length of the sides of grid blocks in pixels. One is the lower limit.
lines_on : bool, optional
Whether or not to display lines between blocks.
Attributes
----------
width : int
Number of blocks along the width of the grid.
height : int
Number of blocks along the height of the grid.
shape : tuple of int
A tuple of (width, height).
block_size : int
Length of the sides of grid blocks in pixels. The block size can be
changed by modifying this attribute. Note that one is the lower limit.
lines_on : bool
Whether lines are shown between blocks when the grid is displayed.
This attribute can used to toggle the whether the lines appear.
"""
def __init__(self, width, height, fill=(0, 0, 0),
block_size=20, lines_on=True):
self._width = width
self._height = height
self._block_size = block_size
self.lines_on = lines_on
self._initialize_grid(fill)
def _initialize_grid(self, fill):
grid = [[Block(*fill, size=self._block_size)
for col in range(self.width)]
for row in range(self.height)]
self._grid = grid
@property
def width(self):
return self._width
@property
def height(self):
return self._height
@property
def shape(self):
return (self._width, self._height)
@property
def block_size(self):
return self._block_size
@block_size.setter
def block_size(self, size):
self._block_size = size
for block in self:
block.size = size
@property
def lines_on(self):
return self._lines_on
@lines_on.setter
def lines_on(self, value):
if value not in (0, 1):
s = 'lines_on may only be True or False.'
raise ValueError(s)
self._lines_on = value
def __eq__(self, other):
if not isinstance(other, BlockGrid):
return False
else:
# compare the underlying grids
return self._grid == other._grid
def _view_from_grid(self, grid):
"""
Make a new grid from a list of lists of Block objects.
"""
new_width = len(grid[0])
new_height = len(grid)
new_BG = self.__class__(new_width, new_height,
block_size=self._block_size,
lines_on=self._lines_on)
new_BG._grid = grid
return new_BG
@staticmethod
def _categorize_index(index):
"""
Used by __getitem__ and __setitem__ to determine whether the user
is asking for a single item, single row, or some kind of slice.
"""
if isinstance(index, int):
return _SINGLE_ROW
elif isinstance(index, slice):
return _ROW_SLICE
elif isinstance(index, tuple):
if len(index) > 2:
s = 'Invalid index, too many dimensions.'
raise IndexError(s)
elif len(index) == 1:
s = 'Single indices must be integers, not tuple.'
raise TypeError(s)
if isinstance(index[0], slice):
if isinstance(index[1], (int, slice)):
return _DOUBLE_SLICE
if isinstance(index[1], slice):
if isinstance(index[0], (int, slice)):
return _DOUBLE_SLICE
elif isinstance(index[0], int) and isinstance(index[0], int):
return _SINGLE_ITEM
raise IndexError('Invalid index.')
def __getitem__(self, index):
ind_cat = self._categorize_index(index)
if ind_cat == _SINGLE_ROW:
return self._view_from_grid([self._grid[index]])
elif ind_cat == _SINGLE_ITEM:
block = self._grid[index[0]][index[1]]
block._row, block._col = index
return block
elif ind_cat == _ROW_SLICE:
return self._view_from_grid(self._grid[index])
elif ind_cat == _DOUBLE_SLICE:
new_grid = self._get_double_slice(index)
return self._view_from_grid(new_grid)
def __setitem__(self, index, value):
thing = self[index]
if isinstance(value, BlockGrid):
if isinstance(thing, BlockGrid):
if thing.shape != value.shape:
raise ShapeMismatch('Both sides of grid assignment must '
'have the same shape.')
for a, b in zip(thing, value):
a._update(b)
else:
raise TypeError('Cannot assign grid to single block.')
elif isinstance(value, (collections.Iterable, Block)):
for b in _flatten(thing):
b._update(value)
def _get_double_slice(self, index):
sl_height, sl_width = index
if isinstance(sl_width, int):
if sl_width == -1:
sl_width = slice(sl_width, None)
else:
sl_width = slice(sl_width, sl_width + 1)
if isinstance(sl_height, int):
if sl_height == -1:
sl_height = slice(sl_height, None)
else:
sl_height = slice(sl_height, sl_height + 1)
rows = self._grid[sl_height]
grid = [r[sl_width] for r in rows]
return grid
def __iter__(self):
for r in range(self.height):
for c in range(self.width):
yield self[r, c]
def animate(self, stop_time=0.2):
"""
Call this method in a loop definition to have your changes to the grid
animated in the IPython Notebook.
Parameters
----------
stop_time : float
Amount of time to pause between loop steps.
"""
for block in self:
self.show()
time.sleep(stop_time)
yield block
clear_output(wait=True)
self.show()
def _repr_html_(self):
rows = range(self._height)
cols = range(self._width)
html = reduce(iadd,
(_TR.format(reduce(iadd,
(self[r, c]._td
for c in cols)))
for r in rows))
return _TABLE.format(uuid.uuid4(), int(self._lines_on), html)
def __str__(self):
s = ['{0}'.format(self.__class__.__name__),
'Shape: {0}'.format(self.shape)]
return os.linesep.join(s)
def copy(self):
"""
Returns an independent copy of this BlockGrid.
"""
return copy.deepcopy(self)
def show(self):
"""
Display colored grid as an HTML table.
"""
display(HTML(self._repr_html_()))
def flash(self, display_time=0.2):
"""
Display the grid for a time.
Useful for making an animation or iteratively displaying changes.
Note that this will leave the grid in place until something replaces
it in the same cell. You can use the ``clear`` function to
manually clear output.
Parameters
----------
display_time : float
Amount of time, in seconds, to display the grid.
"""
self.show()
time.sleep(display_time)
clear_output(wait=True)
def _calc_image_size(self):
"""
Calculate the size, in pixels, of the grid as an image.
Returns
-------
px_width : int
px_height : int
"""
px_width = self._block_size * self._width
px_height = self._block_size * self._height
if self._lines_on:
px_width += self._width + 1
px_height += self._height + 1
return px_width, px_height
def _write_image(self, fp, format='png'):
"""
Write an image of the current grid to a file-object.
Parameters
----------
fp : file-like
A file-like object such as an open file pointer or
a StringIO/BytesIO instance.
format : str, optional
An image format that will be understood by PIL,
e.g. 'png', 'jpg', 'gif', etc.
"""
try:
# PIL
import Image
import ImageDraw
except ImportError:
# pillow
from PIL import Image, ImageDraw
im = Image.new(
mode='RGB', size=self._calc_image_size(), color=(255, 255, 255))
draw = ImageDraw.Draw(im)
_bs = self._block_size
for r in range(self._height):
for c in range(self._width):
px_r = r * _bs
px_c = c * _bs
if self._lines_on:
px_r += r + 1
px_c += c + 1
rect = ((px_c, px_r), (px_c + _bs - 1, px_r + _bs - 1))
draw.rectangle(rect, fill=self._grid[r][c].rgb)
im.save(fp, format=format)
def show_image(self):
"""
Embed grid in the notebook as a PNG image.
"""
if sys.version_info[0] == 2:
from StringIO import StringIO as BytesIO
elif sys.version_info[0] == 3:
from io import BytesIO
im = BytesIO()
self._write_image(im)
display(ipyImage(data=im.getvalue(), format='png'))
def save_image(self, filename):
"""
Save an image representation of the grid to a file.
Image format will be inferred from file extension.
Parameters
----------
filename : str
Name of file to save to.
"""
with open(filename, 'wb') as f:
self._write_image(f, format=filename.split('.')[-1])
def to_text(self, filename=None):
"""
Write a text file containing the size and block color information
for this grid.
If no file name is given the text is sent to stdout.
Parameters
----------
filename : str, optional
File into which data will be written. Will be overwritten if
it already exists.
"""
if filename:
f = open(filename, 'w')
else:
f = sys.stdout
s = ['# width height', '{0} {1}'.format(self.width, self.height),
'# block size', '{0}'.format(self.block_size),
'# initial color', '0 0 0',
'# row column red green blue']
f.write(os.linesep.join(s) + os.linesep)
for block in self:
things = [str(x) for x in (block.row, block.col) + block.rgb]
f.write(' '.join(things) + os.linesep)
if filename:
f.close()
def _to_simple_grid(self):
"""
Make a simple representation of the table: nested lists of
of the rows containing tuples of (red, green, blue, size)
for each of the blocks.
Returns
-------
grid : list of lists
No matter the class this method is called on the returned
grid will be Python-style: row oriented with the top-left
block in the [0][0] position.
"""
return [[(x.red, x.green, x.blue, x.size) for x in row]
for row in self._grid]
def _construct_post_request(self, code_cells, secret):
"""
Construct the request dictionary that will be posted
to ipythonblocks.org.
Parameters
----------
code_cells : int, str, slice, or None
Specify any code cells to be sent and displayed with the grid.
You can specify a single cell, a Python, slice, or a combination
as a string separated by commas.
For example, '3,5,8:10' would send cells 3, 5, 8, and 9.
secret : bool
If True, this grid will not be shown randomly on ipythonblocks.org.
Returns
-------
request : dict
"""
if code_cells is not None:
code_cells = _get_code_cells(code_cells)
req = {
'python_version': tuple(sys.version_info),
'ipb_version': __version__,
'ipb_class': self.__class__.__name__,
'code_cells': code_cells,
'secret': secret,
'grid_data': {
'lines_on': self.lines_on,
'width': self.width,
'height': self.height,
'blocks': self._to_simple_grid()
}
}
return req
def post_to_web(self, code_cells=None, secret=False):
"""
Post this grid to ipythonblocks.org and return a URL to
view the grid on the web.
Parameters
----------
code_cells : int, str, or slice, optional
Specify any code cells to be sent and displayed with the grid.
You can specify a single cell, a Python, slice, or a combination
as a string separated by commas.
For example, '3,5,8:10' would send cells 3, 5, 8, and 9.
secret : bool, optional
If True, this grid will not be shown randomly on ipythonblocks.org.
Returns
-------
url : str
URL to view your grid on ipythonblocks.org.
"""
import requests
req = self._construct_post_request(code_cells, secret)
response = requests.post(_POST_URL, data=json.dumps(req))
response.raise_for_status()
return response.json()['url']
def _load_simple_grid(self, block_data):
"""
Modify the grid to reflect the data in `block_data`, which
should be a nested list of tuples as produced by `_to_simple_grid`.
Parameters
----------
block_data : list of lists
Nested list of tuples as produced by `_to_simple_grid`.
"""
if len(block_data) != self.height or \
len(block_data[0]) != self.width:
raise ShapeMismatch('block_data must have same shape as grid.')
for row in range(self.height):
for col in range(self.width):
self._grid[row][col].rgb = block_data[row][col][:3]
self._grid[row][col].size = block_data[row][col][3]
@classmethod
def from_web(cls, grid_id, secret=False):
"""
Make a new BlockGrid from a grid on ipythonblocks.org.
Parameters
----------
grid_id : str
ID of a grid on ipythonblocks.org. This will be the part of the
URL after 'ipythonblocks.org/'.
secret : bool, optional
Whether or not the grid on ipythonblocks.org is secret.
Returns
-------
grid : BlockGrid
"""
import requests
get_url = _GET_URL_PUBLIC if not secret else _GET_URL_SECRET
resp = requests.get(get_url.format(grid_id))
resp.raise_for_status()
grid_spec = resp.json()
grid = cls(grid_spec['width'], grid_spec['height'],
lines_on=grid_spec['lines_on'])
grid._load_simple_grid(grid_spec['blocks'])
return grid
class Pixel(Block):
@property
def x(self):
"""
Horizontal coordinate of Pixel.
"""
return self._col
@property
def y(self):
"""
Vertical coordinate of Pixel.
"""
return self._row
@property
def _td(self):
"""
The HTML for a table cell with the background color of this Pixel.
"""
title = _TITLE.format(self._col, self._row,
self._red, self._green, self._blue)
rgb = _RGB.format(self._red, self._green, self._blue)
return _TD.format(title, self._size, rgb)
def __str__(self):
s = ['{0}'.format(self.__class__.__name__),
'Color: ({0}, {1}, {2})'.format(self._red,
self._green,
self._blue)]
# add position information if we have it
if self._row is not None:
s[0] += ' [{0}, {1}]'.format(self._col, self._row)
return os.linesep.join(s)
class ImageGrid(BlockGrid):
"""
A grid of blocks whose colors can be individually controlled.
Parameters
----------
width : int
Number of blocks wide to make the grid.
height : int
Number of blocks high to make the grid.
fill : tuple of int, optional
An optional initial color for the grid, defaults to black.
Specified as a tuple of (red, green, blue). E.g.: (10, 234, 198)
block_size : int, optional
Length of the sides of grid blocks in pixels. One is the lower limit.
lines_on : bool, optional
Whether or not to display lines between blocks.
origin : {'lower-left', 'upper-left'}, optional
Set the location of the grid origin.
Attributes
----------
width : int
Number of blocks along the width of the grid.
height : int
Number of blocks along the height of the grid.
shape : tuple of int
A tuple of (width, height).
block_size : int
Length of the sides of grid blocks in pixels.