September Morn Update

This commit is contained in:
Ingy döt Net 2019-09-12 10:33:56 -07:00
parent 4e2d22a71d
commit aac6731f2c
6856 changed files with 141342 additions and 21127 deletions

View file

@ -1,67 +1,206 @@
(function (lngCols, lngRows) {
(() => {
'use strict';
//range(5, 20) --> [5..20]
//range('a', 'n') --> ['a'..'n']
function range(m, n) {
var blnAlpha = typeof m === 'string',
iFirst = blnAlpha ? m.charCodeAt(0) : m,
lstInt = Array.apply(
null,
Array((blnAlpha ? n.charCodeAt(0) : n) - iFirst + 1)
).map(function (x, i) {
return iFirst + i;
});
// HTML ---------------------------------------------
return blnAlpha ? lstInt.map(
function (x) {
return String.fromCharCode(x);
}
) : lstInt;
}
// treeHTML :: tree
// {tag :: String, text :: String, kvs :: Dict}
// -> String
const treeHTML = tree =>
foldTree(
(x, xs) => `<${x.tag + attribString(x.kvs)}>` + (
'text' in x ? (
x.text
) : '\n'
) + concat(xs) + `</${x.tag}>\n`)(
tree
);
// Letter label for first column (last column will be 'Z')
var strFirstCol = String.fromCharCode('Z'.charCodeAt(0) - (lngCols - 1));
// attribString :: Dict -> String
const attribString = dct =>
dct ? (
' ' + Object.keys(dct)
.reduce(
(a, k) => a + k + '="' + dct[k] + '" ', ''
).trim()
) : '';
var lstData = [[''].concat(range(strFirstCol, 'Z'))].concat(
range(1, lngRows).map(
function (row) {
return [row].concat(
range(1, lngCols).map(
function () {
return Math.floor(
Math.random() * 9999
);
}
)
);
// TEST ---------------------------------------------
const main = () => {
const
tableStyle = {
style: "width:25%; border:2px solid silver;"
},
trStyle = {
style: "border:1px solid silver;text-align:right;"
},
strCaption = 'Table generated by JS';
const
n = 3,
colNames = take(n)(enumFrom('A')),
dataRows = map(
x => Tuple(x)(map(randomRInt(100)(9999))(
colNames
)))(take(n)(enumFrom(1)));
const
// TABLE AS TREE STRUCTURE -----------------
tableTree = Node({
tag: 'table',
kvs: tableStyle
},
append([
Node({
tag: 'caption',
text: 'Table source generated by JS'
}),
// HEADER ROW -----------------------
Node({
tag: 'tr',
},
map(k => Node({
tag: 'th',
kvs: {
style: "text-align:right;"
},
text: k
}))(cons('')(colNames))
)
// DATA ROWS ------------------------
])(map(tpl => Node({
tag: 'tr',
kvs: trStyle
}, cons(
Node({
tag: 'th',
text: fst(tpl)
}))(
map(v => Node({
tag: 'td',
text: v.toString()
}))(snd(tpl))
)))(dataRows))
);
// Return a value and/or apply console.log to it.
// (JS embeddings vary in their IO channels)
const strHTML = treeHTML(tableTree);
return (
console.log(strHTML)
//strHTML
);
};
// GENERIC FUNCTIONS --------------------------------
// Node :: a -> [Tree a] -> Tree a
const Node = (v, xs) => ({
type: 'Node',
root: v,
nest: xs || []
});
// Tuple (,) :: a -> b -> (a, b)
const Tuple = a => b => ({
type: 'Tuple',
'0': a,
'1': b,
length: 2
});
// append (++) :: [a] -> [a] -> [a]
// append (++) :: String -> String -> String
const append = xs => ys => xs.concat(ys);
// chr :: Int -> Char
const chr = String.fromCodePoint;
// concat :: [[a]] -> [a]
// concat :: [String] -> String
const concat = xs =>
0 < xs.length ? (() => {
const unit = 'string' !== typeof xs[0] ? (
[]
) : '';
return unit.concat.apply(unit, xs);
})() : [];
// cons :: a -> [a] -> [a]
const cons = x => xs => [x].concat(xs);
// enumFrom :: a -> [a]
function* enumFrom(x) {
let v = x;
while (true) {
yield v;
v = succ(v);
}
)
);
}
return [
'<table>',
// enumFromToChar :: Char -> Char -> [Char]
const enumFromToChar = m => n => {
const [intM, intN] = [m, n].map(
x => x.charCodeAt(0)
);
return Array.from({
length: Math.floor(intN - intM) + 1
}, (_, i) => String.fromCodePoint(intM + i));
};
' <thead style = "text-align: right;">',
' ' + lstData[0].reduce(
function (a, s) {
return a + '<th>' + s + '</th>';
}, '<tr>'
) + '</tr>',
' </thead>',
// foldTree :: (a -> [b] -> b) -> Tree a -> b
const foldTree = f => tree => {
const go = node =>
f(node.root, node.nest.map(go));
return go(tree);
};
' <tbody style = "text-align: right;">',
lstData.slice(1).map(
function (row) {
return ' ' + row.reduce(
function (a, s) {
return a + '<td>' + s + '</td>';
}, '<tr>'
) + '</tr>';
}
).join('\n'),
' </tbody>',
// fst :: (a, b) -> a
const fst = tpl => tpl[0];
'</table>'
].join('\n');
// isChar :: a -> Bool
const isChar = x =>
('string' === typeof x) && (1 === x.length);
})(3, 4); // (3 columns --> [X..Z]), (4 rows --> [1..4])
// map :: (a -> b) -> [a] -> [b]
const map = f => xs =>
(Array.isArray(xs) ? (
xs
) : xs.split('')).map(f);
// ord :: Char -> Int
const ord = c => c.codePointAt(0);
// randomRInt :: Int -> Int -> () -> Int
const randomRInt = low => high => () =>
low + Math.floor(
(Math.random() * ((high - low) + 1))
);
// snd :: (a, b) -> b
const snd = tpl => tpl[1];
// succ :: Enum a => a -> a
const succ = x =>
isChar(x) ? (
chr(1 + ord(x))
) : isNaN(x) ? (
undefined
) : 1 + x;
// take :: Int -> [a] -> [a]
// take :: Int -> String -> String
const take = n => xs =>
'GeneratorFunction' !== xs.constructor.constructor.name ? (
xs.slice(0, n)
) : [].concat.apply([], Array.from({
length: n
}, () => {
const x = xs.next();
return x.done ? [] : [x.value];
}));
// MAIN ---
return main();
})();

View file

@ -0,0 +1,11 @@
{table
{@ style="background:#ffe; width:50%;"}
{tr {@ style="text-align:right; font:bold 1.0em arial;"}
{td } {td X} {td Y} {td Z}}
{map {lambda {:i}
{tr {td {b :i}}
{map {lambda {_}
{td {@ style="text-align:right; font:italic 1.0em courier;"}
{floor {* {random} 10000}} }}
{serie 1 3}}}}
{serie 1 3}}}

View file

@ -1,4 +1,4 @@
puts(1,"<table>\n")
puts(1,"<table border=2>\n")
puts(1," <tr><th></th>")
for j=1 to 3 do
printf(1,"<th>%s</th>",'W'+j)

View file

@ -1,4 +1,4 @@
<table>
<table border=2>
<table>
<tr><th></th><th>X</th><th>Y</th><th>Z</th></tr>
<tr><td>1</td><td>3287</td><td>6480</td><td>6510</td></tr>

View file

@ -0,0 +1,16 @@
:- use_module(library(http/html_write)).
theader([]) --> []. theader([H|T]) --> html(th(H)), theader(T).
trows([],_) --> []. trows([R|T], N) --> html(tr([td(N),\trow(R)])), { N1 is N + 1 }, trows(T, N1).
trow([]) --> []. trow([E|T]) --> html(td(E)), trow(T).
table :-
Header = ['X','Y','Z'],
Rows = [
[7055,5334,5795],
[2895,3019,7747],
[140,7607,8144],
[7090,475,4140]
],
phrase(html(table([tr(\theader(Header)), \trows(Rows,1)])), Out, []),
print_html(Out).

View file

@ -0,0 +1,7 @@
<table>
<tr><th>X</th><th>Y</th><th>Z</th></tr>
<tr><td>1</td><td>7055</td><td>5334</td><td>5795</td></tr>
<tr><td>2</td><td>2895</td><td>3019</td><td>7747</td></tr>
<tr><td>3</td><td>140</td><td>7607</td><td>8144</td></tr>
<tr><td>4</td><td>7090</td><td>475</td><td>4140</td></tr>
</table>

View file

@ -0,0 +1,117 @@
from functools import (reduce)
import itertools
import random
# HTML RENDERING ----------------------------------------
# treeHTML :: tree
# {tag :: String, text :: String, kvs :: Dict}
# -> HTML String
def treeHTML(tree):
return foldTree(
lambda x: lambda xs: (
f"<{x['tag'] + attribString(x)}>" + (
str(x['text']) if 'text' in x else '\n'
) + ''.join(xs) + f"</{x['tag']}>\n"
)
)(tree)
# attribString :: Dict -> String
def attribString(dct):
kvs = dct['kvs'] if 'kvs' in dct else None
return ' ' + reduce(
lambda a, k: a + k + '="' + kvs[k] + '" ',
kvs.keys(), ''
).strip() if kvs else ''
# HTML TABLE FROM GENERATED DATA ------------------------
def main():
# Number of columns and rows to generate.
n = 3
# Table details -------------------------------------
strCaption = 'Table generated with Python'
colNames = take(n)(enumFrom('A'))
dataRows = map(
lambda x: (x, map(
lambda _: random.randint(100, 9999),
colNames
)), take(n)(enumFrom(1)))
tableStyle = {
'style': "width:25%; border:2px solid silver;"
}
trStyle = {
'style': "border:1px solid silver;text-align:right;"
}
# TREE STRUCTURE OF TABLE ---------------------------
tableTree = Node({'tag': 'table', 'kvs': tableStyle})([
Node({
'tag': 'caption',
'text': strCaption
})([]),
# HEADER ROW --------------------------------
(Node({'tag': 'tr'})(
Node({
'tag': 'th',
'kvs': {'style': 'text-align:right;'},
'text': k
})([]) for k in ([''] + colNames)
))
] +
# DATA ROWS ---------------------------------
list(Node({'tag': 'tr', 'kvs': trStyle})(
[Node({'tag': 'th', 'text': tpl[0]})([])] +
list(Node(
{'tag': 'td', 'text': str(v)})([]) for v in tpl[1]
)
) for tpl in dataRows)
)
print(
treeHTML(tableTree)
# dataRows
)
# GENERIC -----------------------------------------------
# Node :: a -> [Tree a] -> Tree a
def Node(v):
return lambda xs: {'type': 'Node', 'root': v, 'nest': xs}
# enumFrom :: Enum a => a -> [a]
def enumFrom(x):
return itertools.count(x) if type(x) is int else (
map(chr, itertools.count(ord(x)))
)
# foldTree :: (a -> [b] -> b) -> Tree a -> b
def foldTree(f):
def go(node):
return f(node['root'])(
list(map(go, node['nest']))
)
return lambda tree: go(tree)
# take :: Int -> [a] -> [a]
# take :: Int -> String -> String
def take(n):
return lambda xs: (
xs[0:n]
if isinstance(xs, list)
else list(itertools.islice(xs, n))
)
if __name__ == '__main__':
main()

View file

@ -0,0 +1,27 @@
<table style="width:25%; border:2px solid silver;">
<caption>Table generated with Python</caption>
<tr>
<th style="text-align:right;"></th>
<th style="text-align:right;">A</th>
<th style="text-align:right;">B</th>
<th style="text-align:right;">C</th>
</tr>
<tr style="border:1px solid silver;text-align:right;">
<th>1</th>
<td>7469</td>
<td>7407</td>
<td>6448</td>
</tr>
<tr style="border:1px solid silver;text-align:right;">
<th>2</th>
<td>4135</td>
<td>3299</td>
<td>6586</td>
</tr>
<tr style="border:1px solid silver;text-align:right;">
<th>3</th>
<td>8264</td>
<td>6951</td>
<td>8882</td>
</tr>
</table>

View file

@ -0,0 +1,45 @@
Create an HTML table
The table body should have at least three rows of three columns.
Each of these three columns should be labelled "X", "Y", and "Z".
An extra column should be added at either the extreme left or the extreme right
of the table that has no heading, but is filled with sequential row numbers.
The rows of the "X", "Y", and "Z" columns should be filled with random or
sequential integers having 4 digits or less.
The numbers should be aligned in the same fashion for all columns.
Red [
Problem: %http://www.rosettacode.org/wiki/Create_an_HTML_table
Code: %https://github.com/metaperl/red-rosetta/blob/master/html-table.r
Acknowledgements: "@endo64 @toomsav"
]
result: func[][simple-tag "table" trs]
trs: func [][rejoin [
first-tr
rand-tr 1
rand-tr 2
rand-tr 3
rand-tr 4
rand-tr 5
]]
table-data: func [][999 + (random 9000)]
rand-td: func [][simple-tag "td" table-data]
rand-tr: func [i][rejoin [
simple-tag "tr"
rejoin [(simple-tag "td" i) rand-td rand-td rand-td]
]]
first-tr: func[][rejoin [
simple-tag "tr" rejoin [
simple-tag "th" ""
simple-tag "th" "X"
simple-tag "th" "Y"
simple-tag "th" "Z"
]
]]
simple-tag: func [tag contents /attr a][rejoin
["<" tag (either attr [rejoin [" " a/1 "=" {"} a/2 {"}]][]) ">"
newline contents newline "</" tag ">"]]

View file

@ -0,0 +1,29 @@
Module Program
Sub Main()
Const ROWS = 3
Const COLS = 3
Dim rand As New Random(0)
Dim getNumber = Function() rand.Next(10000)
Dim result =
<table cellspacing="4" style="text-align:right; border:1px solid;">
<tr>
<th></th>
<th>X</th>
<th>Y</th>
<th>Z</th>
</tr>
<%= From c In Enumerable.Range(1, COLS) Select
<tr>
<th><%= c %></th>
<%= From r In Enumerable.Range(1, ROWS) Select
<td><%= getNumber() %></td>
%>
</tr>
%>
</table>
Console.WriteLine(result)
End Sub
End Module

View file

@ -0,0 +1,49 @@
Module Program
Sub Main()
Dim rand As Func(Of Integer, Integer) = AddressOf New Random(0).Next
Dim cols = {"", "X", "Y", "Z"}
Dim rows = 3
Dim result =
<html>
<body>
<table>
<colgroup>
<%= Iterator Function()
For Each col In cols
Yield <col style="text-align: left;" />
Next
End Function() %>
</colgroup>
<thead>
<tr>
<%= Iterator Function()
For Each col In cols
Yield <td><%= col %></td>
Next
End Function() %>
</tr>
</thead>
<tbody>
<%= Iterator Function()
For r = 1 To rows
Yield _
<tr>
<%= Iterator Function()
For key = 0 To cols.Length - 1
Dim col = cols(key)
Yield <td><%= If(key > 0, rand(10000), r) %></td>
Next
End Function() %>
</tr>
Next
End Function() %>
</tbody>
</table>
</body>
</html>
Console.WriteLine(result)
End Sub
End Module

View file

@ -0,0 +1,36 @@
Module Program
Sub Main()
Dim rand As Func(Of Integer, Integer) = AddressOf New Random(0).Next
Dim cols = {"", "X", "Y", "Z"}
Dim rows = 3
Dim result =
<html>
<body>
<table>
<colgroup>
<%= cols.Select(Function(__) <col style="text-align: left;"/>) %>
</colgroup>
<thead>
<tr>
<%= cols.Select(Function(col) <td><%= col %></td>) %>
</tr>
</thead>
<tbody>
<%= Enumerable.Range(1, rows).Select(
Function(r) _
<tr>
<%= cols.Select(
Function(col, key) <td><%= If(key > 0, rand(10000), r) %></td>)
%>
</tr>)
%>
</tbody>
</table>
</body>
</html>
Console.WriteLine(result)
End Sub
End Module