main
villares 2019-07-01 22:28:07 -03:00
rodzic a6f94c0ddc
commit b692d2cdcd
15 zmienionych plików z 8283 dodań i 0 usunięć

Plik binarny nie jest wyświetlany.

Wyświetl plik

@ -0,0 +1,21 @@
<!DOCTYPE html>
<!-- pyp5js index.html boilerplate -->
<html lang="">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>s190630web - pyp5js</title>
<style> body, html, canvas {padding: 0; margin: 0; overflow: hidden;} </style>
<script src="static/p5.js"></script>
<script src="target/target_sketch.js" type="module"></script>
</head>
<body>
<div id="sketch-holder">
<!-- You sketch will go here! -->
</div>
</body>
</html>

Wyświetl plik

@ -0,0 +1,79 @@
# Alexandre B A Villares - https://abav.lugaralgum.com/sketch-a-day
# More combinatorics of triangles in grids based on sketch_190629a
# Lerp to make intermediary triangles
from pytop5js import *
border = 50
two_triangle_combos = []
space = None
from itertools import product, combinations
def setup():
global two_triangle_combos, space, border
createCanvas(200, 200, WEBGL)
space = width - 2 * border
smooth(8)
blendMode(MULTIPLY)
strokeJoin(ROUND)
# points on a 3x3 grid
grid = product((-1, 0, 1), repeat=2)
# all 3-point combinations on the grid
points = combinations(grid, 3)
# identify triangles (discard colinear point triples)
triangles = []
for p in points:
area = (p[1][0] * (p[2][1] - p[0][1]) +
p[2][0] * (p[0][1] - p[1][1]) +
p[0][0] * (p[1][1] - p[2][1]))
if area != 0:
triangles.append(p)
println("Number of possible triangles: {}"
.format(len(triangles)))
# calculate 2-triangle combinations
two_triangle_combos = list(combinations(triangles, 2))
println("Number of 2-triangle combinations: {}"
.format(len(two_triangle_combos)))
def draw():
background(240)
ortho()
translate(width / 2, height / 2)
rotateY(radians(frameCount))
noFill()
i = (frameCount % len(two_triangle_combos)) // 90
draw_combo(two_triangle_combos[i])
def draw_combo(combo):
strokeWeight(border / 10)
noFill()
siz = space * .5 # .35
triangles = (combo[0],
lerp_poly(combo[0], combo[1], 0.33),
lerp_poly(combo[0], combo[1], 0.66),
combo[1])
for i, t in enumerate(triangles):
# colors for each of the triangles
colors = (color(200, 100, 0),
color(133, 100, 66),
color(66, 100, 133),
color(0, 100, 200))
stroke(colors[i])
draw_poly(scale_poly(t, siz))
def draw_poly(p_list):
beginShape()
for p in p_list:
vertex(p[0], p[1], p[0] * p[1] / space)
endShape(CLOSE)
def lerp_poly(p0, p1, t):
pt = []
for sp0, sp1 in zip(p0, p1):
pt.append((lerp(sp0[0], sp1[0], t),
lerp(sp0[1], sp1[1], t)))
return pt
def scale_poly(p_list, s):
return [(p[0] * s, p[1] * s) for p in p_list]

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

Wyświetl plik

@ -0,0 +1,298 @@
import {list, tuple, len, __kwargtrans__, set} from './org.transcrypt.__runtime__.js';
var __name__ = 'itertools';
export var count = function* (start, step) {
if (start == undefined) {
start = 0;
}
if (step == undefined) {
step = 1;
}
while (true) {
yield start;
start += step;
}
}
export var cycle = function* (iterable) {
let buffer = Array.from (iterable); // Can't reset, Chrome can't obtain iter from gener
while (true) {
for (let item of buffer) {
yield item;
}
}
}
export var repeat = function* (item, n) {
if (typeof n == 'undefined') {
while (true) {
yield item;
}
}
else {
for (let index = 0; index < n; index++) {
yield item;
}
}
}
export var accumulate = function* (iterable, func) {
let sum;
let first = true;
if (func) {
for (let item of iterable) {
if (first) {
sum = item;
first = false;
}
else {
sum = func (sum, item);
}
yield sum;
}
}
else {
for (let item of iterable) {
if (first) {
sum = item;
first = false;
}
else {
sum = sum + item;
}
yield sum;
}
}
}
export var chain = function* () {
let args = [] .slice.apply (arguments);
for (let arg of args) {
for (let item of arg) {
yield item;
}
}
}
chain.from_iterable = function* (iterable) {
for (let item of iterable) {
for (let subItem of item) {
yield subItem;
}
}
}
export var compress = function* (data, selectors) {
let dataIterator = data [Symbol.iterator] .call (data);
let selectorsIterator = selectors [Symbol.iterator] ();
while (true) {
let dataItem = dataIterator.next ();
let selectorsItem = selectorsIterator.next ();
if (dataItem.done || selectorsItem.done) {
break;
}
else {
if (selectorsItem.value) {
yield dataItem.value;
}
}
}
}
export var dropwhile = function* (pred, seq) {
let started = false;
for (let item of seq) {
if (started) {
yield item;
}
else if (!pred (item)) {
started = true;
yield item;
}
}
}
export var filterfalse = function* (pred, seq) {
for (let item of seq) {
if (!pred (item)) {
yield item;
}
}
}
export var groupby = function* (iterable, keyfunc) {
let anIterator = iterable [Symbol.iterator] ();
let item = anIterator.next ();
if (item.done) {
return;
}
let groupKey = keyfunc (item.value);
let more = true;
function* group () {
while (true) {
yield (item.value);
item = anIterator.next ();
if (item.done) {
more = false;
return;
}
let key = keyfunc (item.value);
if (key != groupKey) {
groupKey = key;
return;
}
}
}
while (more) {
yield tuple ([groupKey, group ()]);
}
}
export var islice = function* () {
let start; // Have to be defined at function level, or Closure compiler will loose them after a yield
let stop; //
let step; //
let args = [] .slice.apply (arguments);
let anIterator = args [0][Symbol.iterator] ();
if (args.length == 2) {
stop = args [1];
start = 0;
step = 1;
}
else {
start = args [1];
stop = args [2];
if (args.length == 4) {
step = args [3];
}
else {
step = 1;
}
}
for (let index = 0; index < start; index++) {
if (anIterator.next (). done) {
return;
}
}
for (let index = 0; index < stop - start; index++) {
let next = anIterator.next ();
if (next.done) {
return;
}
if (index % step == 0) {
yield next.value;
}
}
}
export var starmap = function* (func, seq) {
let anIterator = seq [Symbol.iterator] ();
while (true) {
let next = anIterator.next ()
if (next.done) {
return;
}
else {
yield func (...next.value);
}
}
}
export var takewhile = function* (pred, seq) {
for (let item of seq) {
if (pred (item)) {
yield item;
}
else {
return;
}
}
}
export var tee = function (iterable, n) {
if (n == undefined) {
n = 2;
}
let all = []; // Don't return iterator since destructuring assignment cannot yet deal with that
let one = list (iterable);
for (let i = 0; i < n; i++) {
all.append (one [Symbol.iterator] ()); // Iterator rather than list, exhaustable for semantic equivalence
}
return list (all);
}
export var product = function () {
let args = [] .slice.apply (arguments);
if (args.length && args [args.length - 1] .hasOwnProperty ('__kwargtrans__')) {
var repeat = args.pop () ['repeat'];
}
else {
var repeat = 1;
}
let oldMolecules = [tuple ([])];
for (let i = 0; i < repeat; i++) {
for (let arg of args) {
let newMolecules = [];
for (let oldMolecule of oldMolecules) {
for (let atom of arg) {
newMolecules.append (tuple (oldMolecule.concat (atom)));
}
}
oldMolecules = newMolecules;
}
}
return list (oldMolecules); // Also works if args is emptpy
}
export var permutations = function (iterable, r) {
if (r == undefined) {
try {
r = len (iterable);
}
catch (exception) {
r = len (list (iterable));
}
}
let aProduct = product (iterable, __kwargtrans__ ({repeat: r}));
let result = [];
for (let molecule of aProduct) {
if (len (set (molecule)) == r) { // Weed out doubles
result.append (molecule);
}
}
return list (result);
}
export var combinations = function (iterable, r) {
let tail = list (iterable);
function recurse (tail, molecule, rNext) {
for (let index = 0; index < len (tail) - rNext; index++) {
let newMolecule = molecule.concat (tail.slice (index, index + 1));
if (rNext) {
recurse (tail.slice (index + 1), newMolecule, rNext - 1);
}
else {
result.append (tuple (newMolecule));
}
}
}
let result = [];
recurse (tail, tail.slice (0, 0), r - 1);
return list (result);
}
export var combinations_with_replacement = function (iterable, r) {
let tail = list (iterable);
function recurse (tail, molecule, rNext) {
for (let index = 0; index < len (tail); index++) {
let newMolecule = molecule.concat (tail.slice (index, index + 1));
if (rNext) {
recurse (tail.slice (index), newMolecule, rNext - 1);
}
else {
result.append (tuple (newMolecule));
}
}
}
let result = [];
recurse (tail, tail.slice (0, 0), r - 1);
return list (result);
}
//# sourceMappingURL=itertools.map

File diff suppressed because one or more lines are too long

Wyświetl plik

@ -0,0 +1,285 @@
# Transcrypt runtime module
#__pragma__ ('js', 'export var __envir__ = {{}};\n{}', __include__ ('org/transcrypt/__envir__.js'))
#__pragma__ ('js', '{}', __include__ ('org/transcrypt/__core__.js'))
#__pragma__ ('js', '{}', __include__ ('org/transcrypt/__builtin__.js'))
#__pragma__ ('skip')
copy = Math = __typeof__ = __repr__ = document = console = window = 0
#__pragma__ ('noskip')
#__pragma__ ('notconv') # !!! tconv gives a problem with __terminal__, needs investigation
#__pragma__ ('nokwargs')
#__pragma__ ('noalias', 'sort')
class BaseException:
pass
class Exception (BaseException):
#__pragma__ ('kwargs')
def __init__ (self, *args, **kwargs):
self.__args__ = args
try:
self.stack = kwargs.error.stack # Integrate with JavaScript Error object
except:
self.stack = 'No stack trace available'
#__pragma__ ('nokwargs')
def __repr__ (self):
if len (self.__args__) > 1:
return '{}{}'.format (self.__class__.__name__, repr (tuple (self.__args__)))
elif len (self.__args__):
return '{}({})'.format (self.__class__.__name__, repr (self.__args__ [0]))
else:
return '{}()'.format (self.__class__.__name__)
def __str__ (self):
if len (self.__args__) > 1:
return str (tuple (self.__args__))
elif len (self.__args__):
return str (self.__args__ [0])
else:
return ''
class IterableError (Exception):
def __init__ (self, error):
Exception.__init__ (self, 'Can\'t iterate over non-iterable', error = error)
class StopIteration (Exception):
def __init__ (self, error):
Exception.__init__ (self, 'Iterator exhausted', error = error)
class ValueError (Exception):
def __init__ (self, message, error):
Exception.__init__ (self, message, error = error)
class KeyError (Exception):
def __init__ (self, message, error):
Exception.__init__ (self, message, error = error)
class AssertionError (Exception):
def __init__ (self, message, error):
if message:
Exception.__init__ (self, message, error = error)
else:
Exception.__init__ (self, error = error)
class NotImplementedError (Exception):
def __init__(self, message, error):
Exception.__init__(self, message, error = error)
class IndexError (Exception):
def __init__(self, message, error):
Exception.__init__(self, message, error = error)
class AttributeError (Exception):
def __init__(self, message, error):
Exception.__init__(self, message, error = error)
class TypeError (Exception):
def __init__(self, message, error):
Exception.__init__(self, message, error = error)
# Warnings Exceptions
# N.B. This is a limited subset of the warnings defined in
# the cpython implementation to keep things small for now.
class Warning (Exception):
''' Warning Base Class
'''
pass
class UserWarning (Warning):
pass
class DeprecationWarning (Warning):
pass
class RuntimeWarning (Warning):
pass
#__pragma__ ('kwargs')
def __sort__ (iterable, key = None, reverse = False): # Used by py_sort, can deal with kwargs
if key:
iterable.sort (lambda a, b: 1 if key (a) > key (b) else -1) # JavaScript sort, case '==' is irrelevant for sorting
else:
iterable.sort () # JavaScript sort
if reverse:
iterable.reverse ()
def sorted (iterable, key = None, reverse = False):
if type (iterable) == dict:
result = copy (iterable.keys ())
else:
result = copy (iterable)
__sort__ (result, key, reverse)
return result
#__pragma__ ('nokwargs')
def map (func, iterable):
return [func (item) for item in iterable]
def filter (func, iterable):
if func == None:
func = bool
return [item for item in iterable if func (item)]
def divmod (n, d):
return n // d, n % d
#__pragma__ ('ifdef', '__complex__')
class complex:
def __init__ (self, real, imag = None):
if imag == None:
if type (real) == complex:
self.real = real.real
self.imag = real.imag
else:
self.real = real
self.imag = 0
else:
self.real = real
self.imag = imag
def __neg__ (self):
return complex (-self.real, -self.imag)
def __exp__ (self):
modulus = Math.exp (self.real)
return complex (modulus * Math.cos (self.imag), modulus * Math.sin (self.imag))
def __log__ (self):
return complex (Math.log (Math.sqrt (self.real * self.real + self.imag * self.imag)), Math.atan2 (self.imag, self.real))
def __pow__ (self, other): # a ** b = exp (b log a)
return (self.__log__ () .__mul__ (other)) .__exp__ ()
def __rpow__ (self, real): # real ** comp -> comp.__rpow__ (real)
return self.__mul__ (Math.log (real)) .__exp__ ()
def __mul__ (self, other):
if __typeof__ (other) is 'number':
return complex (self.real * other, self.imag * other)
else:
return complex (self.real * other.real - self.imag * other.imag, self.real * other.imag + self.imag * other.real)
def __rmul__ (self, real): # real + comp -> comp.__rmul__ (real)
return complex (self.real * real, self.imag * real)
def __div__ (self, other):
if __typeof__ (other) is 'number':
return complex (self.real / other, self.imag / other)
else:
denom = other.real * other.real + other.imag * other.imag
return complex (
(self.real * other.real + self.imag * other.imag) / denom,
(self.imag * other.real - self.real * other.imag) / denom
)
def __rdiv__ (self, real): # real / comp -> comp.__rdiv__ (real)
denom = self.real * self.real
return complex (
(real * self.real) / denom,
(real * self.imag) / denom
)
def __add__ (self, other):
if __typeof__ (other) is 'number':
return complex (self.real + other, self.imag)
else: # Assume other is complex
return complex (self.real + other.real, self.imag + other.imag)
def __radd__ (self, real): # real + comp -> comp.__radd__ (real)
return complex (self.real + real, self.imag)
def __sub__ (self, other):
if __typeof__ (other) is 'number':
return complex (self.real - other, self.imag)
else:
return complex (self.real - other.real, self.imag - other.imag)
def __rsub__ (self, real): # real - comp -> comp.__rsub__ (real)
return complex (real - self.real, -self.imag)
def __repr__ (self):
return '({}{}{}j)'.format (self.real, '+' if self.imag >= 0 else '', self.imag)
def __str__ (self):
return __repr__ (self) [1 : -1]
def __eq__ (self, other):
if __typeof__ (other) is 'number':
return self.real == other
else:
return self.real == other.real and self.imag == other.imag
def __ne__ (self, other):
if __typeof__ (other) is 'number':
return self.real != other
else:
return self.real != other.real or self.imag != other.imag
def conjugate (self):
return complex (self.real, -self.imag)
def __conj__ (aNumber):
if isinstance (aNumber, complex):
return complex (aNumber.real, -aNumber.imag)
else:
return complex (aNumber, 0)
#__pragma__ ('endif')
class __Terminal__:
'''
Printing to either the console or to html happens async, but is blocked by calling window.prompt.
So while all input and print statements are encountered in normal order, the print's exit immediately without yet having actually printed
This means the next input takes control, blocking actual printing and so on indefinitely
The effect is that everything's only printed after all inputs are done
To prevent that, what's needed is to only execute the next window.prompt after actual printing has been done
Since we've no way to find out when that is, a timeout is used.
'''
def __init__ (self):
self.buffer = ''
try:
self.element = document.getElementById ('__terminal__')
except:
self.element = None
if self.element:
self.element.style.overflowX = 'auto'
self.element.style.boxSizing = 'border-box'
self.element.style.padding = '5px'
self.element.innerHTML = '_'
#__pragma__ ('kwargs')
def print (self, *args, sep = ' ', end = '\n'):
self.buffer = '{}{}{}'.format (self.buffer, sep.join ([str (arg) for arg in args]), end) [-4096 : ]
if self.element:
self.element.innerHTML = self.buffer.replace ('\n', '<br>') .replace (' ', '&nbsp')
self.element.scrollTop = self.element.scrollHeight
else:
console.log (sep.join ([str (arg) for arg in args]))
def input (self, question):
self.print ('{}'.format (question), end = '')
answer = window.prompt ('\n'.join (self.buffer.split ('\n') [-8:]))
self.print (answer)
return answer
#__pragma__ ('nokwargs')
__terminal__ = __Terminal__ ()
print = __terminal__.print
input = __terminal__.input

File diff suppressed because one or more lines are too long

Plik binarny nie jest wyświetlany.

Plik binarny nie jest wyświetlany.

Przed

Szerokość:  |  Wysokość:  |  Rozmiar: 4.3 MiB

Wyświetl plik

@ -0,0 +1,102 @@
# Alexandre B A Villares - https://abav.lugaralgum.com/sketch-a-day
# More combinatorics of polys in grids based on sektch_190630a
# Now quads in 3D
from itertools import product, combinations
def setup():
global two_poly_combos, polys, space, border
size(200, 200, P3D)
border = 50
space = width - 2 * border
smooth(8)
blendMode(MULTIPLY)
strokeJoin(ROUND)
# points on a 3x3 grid
grid = product((-1, 0, 1), repeat=2)
# all 3-point combinations on the grid
points = combinations(grid, 4)
# identify polys (discard colinear point triples)
polys = []
for p in points:
if area(p) != 0:
polys.append(p)
println("Number of possible quads: {}"
.format(len(polys)))
# calculate 2-poly combinations
two_poly_combos = list(combinations(polys, 2))
println("Number of 2-poly combinations: {}"
.format(len(two_poly_combos)))
def draw():
background(240)
ortho()
translate(width / 2, height / 2)
rotateY(radians(frameCount))
noFill()
i = (frameCount % len(two_poly_combos)) // 90
draw_combo(two_poly_combos[i])
def draw_combo(combo):
strokeWeight(border / 10)
noFill()
siz = space * .5 # .35
polys = (combo[0],
lerp_poly(combo[0], combo[1], 0.33),
lerp_poly(combo[0], combo[1], 0.66),
combo[1])
for i, t in enumerate(polys):
# colors for each of the polys
colors = (color(200, 100, 0),
color(133, 100, 66),
color(66, 100, 133),
color(0, 100, 200))
stroke(colors[i])
draw_poly(scale_poly(t, siz))
def draw_poly(p_list):
beginShape()
for p in p_list:
vertex(p[0], p[1], p[0] * p[1] / space)
endShape(CLOSE)
def lerp_poly(p0, p1, t):
pt = []
for sp0, sp1 in zip(p0, p1):
pt.append((lerp(sp0[0], sp1[0], t),
lerp(sp0[1], sp1[1], t)))
return pt
def scale_poly(p_list, s):
return [(p[0] * s, p[1] * s) for p in p_list]
def area(points):
n = len(points) # of points
a = 0.0
for i in range(n):
j = (i + 1) % n
a += points[i][0] * points[j][1]
a -= points[j][0] * points[i][1]
a /= 2.0
return a
def keyPressed():
if key == "s":
saveFrame(SKETCH_NAME + OUTPUT)
def settings():
""" print markdown to add at the sketch-a-day page"""
from os import path
global SKETCH_NAME, OUTPUT
SKETCH_NAME = path.basename(sketchPath())
OUTPUT = ".png"
println(
"""
![{0}]({2}/{0}/{0}{1})
[{0}](https://github.com/villares/sketch-a-day/tree/master/{2}/{0}) [[Py.Processing](https://villares.github.io/como-instalar-o-processing-modo-python/index-EN)]
""".format(SKETCH_NAME, OUTPUT, year())
)