-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.js
More file actions
2465 lines (2095 loc) · 125 KB
/
Copy pathapp.js
File metadata and controls
2465 lines (2095 loc) · 125 KB
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
// --- Core State & Configuration ---
let config = {
inkyUrl: localStorage.getItem('inkyUrl') || 'http://inky.local',
interval: parseInt(localStorage.getItem('inkyInterval')) || 15,
apiKeys: JSON.parse(localStorage.getItem('inkyApiKeys')) || {},
activePluginId: localStorage.getItem('inkyActivePlugin') || 'hello_world',
cors_proxy: localStorage.getItem('cors_proxy') || 'https://api.codetabs.com/v1/proxy/?quest='
};
let renderTimer = null;
let lastFrameData = null;
let searchQuery = '';
const canvas = document.getElementById('inkyCanvas');
const ctx = canvas.getContext('2d');
//canvas utilities
const canvasUtils = {
/**
* Shrinks font size until a single line of text fits within maxWidth.
*/
fitTextSingleLine: (ctx, text, x, y, maxWidth, maxFontSize, weight = 'normal', font = 'Arial') => {
let size = maxFontSize;
ctx.font = `${weight} ${size}px ${font}`;
while (ctx.measureText(text).width > maxWidth && size > 10) {
size--;
ctx.font = `${weight} ${size}px ${font}`;
}
ctx.fillText(text, x, y);
return size;
},
/**
* Standard text wrap. Useful when you know the text is short enough to not overflow Y.
*/
wrapText: (ctx, text, x, y, maxWidth, lineHeight) => {
const words = text.split(' ');
let line = '';
let currentY = y;
for (let n = 0; n < words.length; n++) {
const testLine = line + words[n] + ' ';
const metrics = ctx.measureText(testLine);
const testWidth = metrics.width;
if (testWidth > maxWidth && n > 0) {
ctx.fillText(line, x, currentY);
line = words[n] + ' ';
currentY += lineHeight;
} else {
line = testLine;
}
}
ctx.fillText(line, x, currentY);
return currentY;
},
/**
* The heavy lifter: Shrinks font size until a multi-line paragraph fits
* inside both maxWidth AND maxHeight.
*/
fitTextMultiLine: (ctx, text, x, y, maxWidth, maxHeight, maxFontSize, weight = 'normal', font = 'Arial', lineSpacing = 1.2) => {
let size = maxFontSize;
let lines = [];
let lineHeight = size * lineSpacing;
// Helper function to calculate wrapping at a specific font size
const calculateLines = (testSize) => {
ctx.font = `${weight} ${testSize}px ${font}`;
const words = text.split(' ');
let currentLines = [];
let currentLine = '';
for (let n = 0; n < words.length; n++) {
const testLine = currentLine + words[n] + ' ';
const metrics = ctx.measureText(testLine);
if (metrics.width > maxWidth && n > 0) {
currentLines.push(currentLine.trim());
currentLine = words[n] + ' ';
} else {
currentLine = testLine;
}
}
currentLines.push(currentLine.trim());
return currentLines;
};
// Shrink loop: Check total height against maxHeight
while (size > 10) {
lineHeight = size * lineSpacing;
lines = calculateLines(size);
const totalHeight = lines.length * lineHeight;
if (totalHeight <= maxHeight) {
break; // It fits perfectly!
}
size--; // Shrink font and try again
}
// Draw the final calculated lines
ctx.font = `${weight} ${size}px ${font}`;
ctx.textBaseline = 'top'; // Makes Y coordinate the top of the bounding box
for (let i = 0; i < lines.length; i++) {
ctx.fillText(lines[i], x, y + (i * lineHeight));
}
ctx.textBaseline = 'alphabetic'; // Reset to canvas default safely
return { sizeUsed: size, totalHeight: lines.length * lineHeight };
}
};
// --- Plugin Registry ---
// To add a new plugin, just add an object to this array.
const Plugins = [
{
id: 'hello_world',
name: 'Hello Inky',
minInterval : 10,
description: 'A simple text display to test connection.',
requiredKeys: [], // No API keys needed
render: async (ctx, width, height, apiKeys) => {
ctx.fillStyle = 'white';
ctx.fillRect(0, 0, width, height);
ctx.fillStyle = 'black';
ctx.font = 'bold 60px Arial';
ctx.textAlign = 'center';
ctx.fillText('Hello from Inky Hub!', width / 2, height / 2 - 20);
ctx.font = '30px Arial';
ctx.fillText(`Time: ${new Date().toLocaleTimeString()}`, width / 2, height / 2 + 40);
}
},
{
id: 'arxiv_ai',
theme: 'AI & Research', // <-- New Theme Property
name: 'ArXiv AI Latest',
description: 'Fetches the 3 latest cs.AI papers.',
doublePush: true,
minInterval: 3600,
requiredKeys: [],
render: async (ctx, width, height, apiKeys) => {
ctx.fillStyle = 'white';
ctx.fillRect(0, 0, width, height);
ctx.fillStyle = 'black';
// Using the new smart text to ensure the header never breaks
canvasUtils.fitTextSingleLine(ctx, 'Latest AI Research (cs.AI)', 30, 60, width - 60, 40, 'bold');
ctx.fillRect(30, 80, width - 60, 4);
try {
const targetUrl = 'https://export.arxiv.org/api/query?search_query=cat:cs.AI&max_results=3&sortBy=submittedDate&sortOrder=descending';
const proxiedUrl = `${config.cors_proxy}${encodeURIComponent(targetUrl)}`;
const res = await fetch(proxiedUrl);
const text = await res.text();
const parser = new DOMParser();
const xml = parser.parseFromString(text, "text/xml");
const entries = xml.querySelectorAll('entry');
let yPos = 140;
entries.forEach((entry, index) => {
let title = entry.querySelector('title').textContent.trim().replace(/\s+/g, ' ');
let author = entry.querySelector('author name').textContent;
// Use smart text for titles so we don't need manual truncation anymore
ctx.fillStyle = 'black';
canvasUtils.fitTextSingleLine(ctx, `${index + 1}. ${title}`, 30, yPos, width - 60, 28, 'bold');
ctx.fillStyle = '#333'; // Slightly lighter for authors (will dither nicely)
canvasUtils.fitTextSingleLine(ctx, `By: ${author}`, 60, yPos + 35, width - 90, 22, 'italic');
yPos += 100;
});
} catch (err) {
canvasUtils.fitTextSingleLine(ctx, 'Error fetching ArXiv data.', 30, 150, width - 60, 30);
console.error(err);
}
}
},
{
id: 'hn_top',
name: 'Hacker News Top',
theme: 'Tech & Dev',
description: 'Fetches the top 4 stories from Y Combinator.',
minInterval: 300,
requiredKeys: [],
render: async (ctx, width, height, apiKeys) => {
ctx.fillStyle = 'white';
ctx.fillRect(0, 0, width, height);
ctx.fillStyle = 'black';
canvasUtils.fitTextSingleLine(ctx, 'Hacker News Top Stories', 30, 60, width - 60, 40, 'bold');
ctx.fillRect(30, 80, width - 60, 4);
try {
// HN provides a free, CORS-friendly Firebase API
const res = await fetch('https://hacker-news.firebaseio.com/v0/topstories.json');
const topIds = (await res.json()).slice(0, 4);
let yPos = 140;
for (let i = 0; i < topIds.length; i++) {
const itemRes = await fetch(`https://hacker-news.firebaseio.com/v0/item/${topIds[i]}.json`);
const item = await itemRes.json();
ctx.fillStyle = 'black';
canvasUtils.fitTextSingleLine(ctx, `${i + 1}. ${item.title}`, 30, yPos, width - 60, 28, 'bold');
ctx.fillStyle = '#333';
canvasUtils.fitTextSingleLine(ctx, `${item.score} pts by ${item.by}`, 60, yPos + 35, width - 90, 22, 'italic');
yPos += 85;
}
} catch (err) {
ctx.fillStyle = 'black';
canvasUtils.fitTextSingleLine(ctx, 'Error fetching Hacker News.', 30, 150, width - 60, 30);
}
}
},
{
id: 'weather_dashboard',
theme: 'Daily Utility', // <-- New Theme Property
name: 'Current Weather',
description: 'Needs OpenWeather API key and City Name.',
doublePush:true,
minInterval: 3600,
requiredKeys: [
{ id: 'openweather_key', type: 'password', label: 'OpenWeather API Key', required:true },
{ id: 'city_name', type: 'text', label: 'City Name', placeholder: 'e.g., Khordha, IN' }
],
render: async (ctx, width, height, apiKeys) => {
ctx.fillStyle = 'white';
ctx.fillRect(0, 0, width, height);
ctx.fillStyle = 'black';
const key = apiKeys['openweather_key'];
// Default to Khordha if they leave it blank, since that's local context
const city = apiKeys['City_Name'] || 'Khordha';
try {
const url = `https://api.openweathermap.org/data/2.5/weather?q=${city}&appid=${key}&units=metric`;
const res = await fetch(`${config.cors_proxy}${encodeURIComponent(url)}`);
if (!res.ok) throw new Error('API Request Failed');
const data = await res.json();
// Draw huge temperature centered
ctx.textAlign = 'center';
canvasUtils.fitTextSingleLine(ctx, `${Math.round(data.main.temp)}°C`, width / 2, 220, width - 40, 140, 'bold');
// Draw City and Condition
canvasUtils.fitTextSingleLine(ctx, data.name.toUpperCase(), width / 2, 300, width - 40, 40, 'bold');
canvasUtils.fitTextSingleLine(ctx, data.weather[0].description, width / 2, 350, width - 40, 30, 'normal');
// Footer details
ctx.font = '24px Arial';
ctx.fillText(`Humidity: ${data.main.humidity}% | Wind: ${data.wind.speed} m/s`, width / 2, 420);
// Reset text align for the next render cycle
ctx.textAlign = 'left';
} catch (err) {
ctx.textAlign = 'left';
canvasUtils.fitTextSingleLine(ctx, 'Weather Error. Check API Key & City Name.', 30, 150, width - 60, 30);
}
}
},
{
id: 'github_activity',
theme: 'Tech & Dev',
name: 'GitHub Recent Commits',
description: 'Shows latest commits for a specific repo.',
minInterval: 300,
requiredKeys: [
{ id: 'github_repo', type: 'text', label: 'Target Repo (user/repo)', placeholder: 'e.g., Sarin-jacob/Inky', required: true },
{ id: 'commit_count', type: 'number', label: 'Number of Commits', placeholder: 'e.g., 4' }
],
render: async (ctx, width, height, apiKeys) => {
ctx.fillStyle = 'white';
ctx.fillRect(0, 0, width, height);
ctx.fillStyle = 'black';
// Default to your Inky repo if blank
const repo = apiKeys['github_repo'] || 'Sarin-jacob/Inky';
// Parse as integer to ensure .slice() and our math works correctly
const commit_count = parseInt(apiKeys['commit_count']) || 4;
canvasUtils.fitTextSingleLine(ctx, `Recent Commits: ${repo}`, 30, 60, width - 60, 40, 'bold');
ctx.fillRect(30, 80, width - 60, 4);
try {
const res = await fetch(`https://api.github.com/repos/${repo}/commits`);
const data = await res.json();
// Prevent crash if GitHub returns an error object (like rate limit hit or 404)
if (!Array.isArray(data)) throw new Error('Invalid repo or rate limit reached.');
const commits = data.slice(0, commit_count);
// Dynamically calculate vertical spacing so it never overflows the 480px canvas height
const availableHeight = height - 120; // Leave room for the header
const ySpacing = Math.min(85, availableHeight / commit_count);
let yPos = 120;
commits.forEach((c, index) => {
// Grab just the first line of the commit message
const msg = c.commit.message.split('\n')[0];
const author = c.commit.author.name;
const date = new Date(c.commit.author.date).toLocaleDateString();
ctx.fillStyle = 'black';
// Font size scales down slightly if we are packing a lot of commits into the screen
const titleSize = Math.min(28, ySpacing * 0.45);
canvasUtils.fitTextSingleLine(ctx, `${index + 1}. ${msg}`, 30, yPos, width - 60, titleSize, 'bold');
ctx.fillStyle = '#333';
const subSize = Math.min(22, ySpacing * 0.35);
canvasUtils.fitTextSingleLine(ctx, `${author} committed on ${date}`, 60, yPos + (ySpacing * 0.4), width - 90, subSize, 'italic');
yPos += ySpacing;
});
} catch (err) {
canvasUtils.fitTextSingleLine(ctx, 'Error fetching GitHub Repo. Is it public?', 30, 150, width - 60, 30);
console.error(err);
}
}
},
{
id: 'naruto_quotes',
theme: 'Fun & Aesthetic', // <-- New Theme Property
name: 'Naruto Wisdom',
description: 'Random quote generator using multi-line wrap.',
doublePush:true,
minInterval: 60,
requiredKeys: [],
render: async (ctx, width, height, apiKeys) => {
// A small sample, you can replace this by fetching your 500+ CSV later
const quotes = [
// Naruto Uzumaki
{ text: "Hard work is worthless for those that don't believe in themselves.", author: "Naruto Uzumaki" },
{ text: "If you don't like your destiny, don't accept it. Instead have the courage to change it.", author: "Naruto Uzumaki" },
{ text: "I'm not gonna run away, I never go back on my word! That's my nindo: my ninja way!", author: "Naruto Uzumaki" },
{ text: "Failing doesn't give you a reason to give up, as long as you believe.", author: "Naruto Uzumaki" },
{ text: "Once you question your own belief, it's over.", author: "Naruto Uzumaki" },
{ text: "While you're alive, you need a reason for your existence. Being unable to find one is the same as being dead.", author: "Naruto Uzumaki" },
// Itachi Uchiha
{ text: "People live their lives bound by what they accept as correct and true. That is how they define 'reality'.", author: "Itachi Uchiha" },
{ text: "It is not the face that makes someone a monster, it's the choices they make with their lives.", author: "Itachi Uchiha" },
{ text: "Those who forgive themselves, and are able to accept their true nature... They are the strong ones!", author: "Itachi Uchiha" },
{ text: "Even the strongest of opponents always has a weakness.", author: "Itachi Uchiha" },
{ text: "Knowledge and awareness are vague, and perhaps better called illusions. Everyone lives within their own subjective interpretation.", author: "Itachi Uchiha" },
// Pain / Nagato
{ text: "Sometimes you must hurt in order to know, fall in order to grow, lose in order to gain because life's greatest lessons are learned through pain.", author: "Pain" },
{ text: "Love is the reason why there is pain. When we lose someone precious to us, hate is born.", author: "Pain" },
{ text: "Those who do not understand true pain can never understand true peace.", author: "Pain" },
{ text: "Religion, ideology, resources, land, spite, love or just because... No matter how pathetic the reason, it's enough to start a war.", author: "Pain" },
// Madara Uchiha
{ text: "Wake up to reality! Nothing ever goes as planned in this accursed world.", author: "Madara Uchiha" },
{ text: "In this world, wherever there is light - there are also shadows.", author: "Madara Uchiha" },
{ text: "As long as the concept of winners exists, there must also be losers.", author: "Madara Uchiha" },
{ text: "Man seeks peace, yet at the same time yearning for war... Those are the two realms belonging solely to man.", author: "Madara Uchiha" },
// Kakashi Hatake
{ text: "Those who break the rules are scum, but those who abandon their friends are worse than scum.", author: "Kakashi Hatake" },
{ text: "In society, those who don't have many abilities, tend to complain more.", author: "Kakashi Hatake" },
{ text: "The next generation will always surpass the previous one. It's one of the never-ending cycles in life.", author: "Kakashi Hatake" },
{ text: "To know what is right and choose to ignore it is the act of a coward.", author: "Kakashi Hatake" },
// Jiraiya
{ text: "Knowing what it feels to be in pain, is exactly why we try to be kind to others.", author: "Jiraiya" },
{ text: "A person grows up when he's able to overcome hardships. Protection is important, but there are some things that a person must learn on his own.", author: "Jiraiya" },
{ text: "The true measure of a shinobi is not how he lives but how he dies.", author: "Jiraiya" },
// Gaara
{ text: "In order to escape a road of despair, one must pave a new one.", author: "Gaara" },
{ text: "Just because someone is important to you, it doesn't necessarily mean that, that person is good.", author: "Gaara" },
{ text: "We have walked through the darkness of this world, that's why we are able to see even a sliver of light.", author: "Gaara" },
// Rock Lee & Might Guy
{ text: "A drop of sweat from hard work is the most beautiful jewel.", author: "Rock Lee" },
{ text: "A genius, huh? What does that mean? 'Genius'? So I was not born with a whole lot of natural talent... but I work hard and I never give up!", author: "Rock Lee" },
{ text: "You're right, all efforts are pointless... if you don't believe in yourself.", author: "Might Guy" },
// Others
{ text: "When people are protecting something truly special to them, they truly can become as strong as they can be.", author: "Haku" },
{ text: "It's human nature not to realize the true value of something, unless they lose it.", author: "Orochimaru" },
{ text: "People become stronger because they have memories they can't forget.", author: "Tsunade" },
{ text: "Fear. That is what we live with. And we live it everyday. Only in death are we free of it.", author: "Neji Hyuga" },
{ text: "A smile is the easiest way out of a difficult situation.", author: "Sakura Haruno" },
{ text: "Laziness is the mother of all bad habits. But ultimately she is a mother and we should respect her.", author: "Shikamaru Nara" },
{ text: "I have long since closed my eyes... My only goal is in the darkness.", author: "Sasuke Uchiha" },
{ text: "There's no such thing as a life without regrets.", author: "Minato Namikaze" }
];
const q = quotes[Math.floor(Math.random() * quotes.length)];
ctx.fillStyle = 'white';
ctx.fillRect(0, 0, width, height);
ctx.fillStyle = 'black';
// Giant decorative quote mark in the background
ctx.fillStyle = '#ddd'; // Will dither to a light dot pattern
ctx.font = 'bold 250px Arial';
ctx.fillText('"', 50, 220);
ctx.fillStyle = 'black';
ctx.font = 'bold 45px Arial';
// Using the new wrapText utility: (ctx, text, x, y, maxWidth, lineHeight)
const finalY = canvasUtils.wrapText(ctx, q.text, 100, 180, width - 150, 60);
ctx.textAlign = 'right';
ctx.font = 'italic 30px Arial';
ctx.fillText(`- ${q.author}`, width - 100, finalY + 80);
ctx.textAlign = 'left'; // Always reset
}
},
{
id: 'conway_life',
theme: 'Fun & Aesthetic',
name: 'Conway\'s Game of Life',
description: 'Zero-player cellular automaton. Evolves every update.',
// minInterval: 5, // Faster updates look cool for automata
requiredKeys: [],
grid: null, // We store the state right here in the plugin object
cols: 50, // 800px / 16px
rows: 30, // 480px / 16px
cellSize: 16,
render: async function(ctx, width, height, apiKeys) {
// Note: using 'function' instead of '() =>' so 'this' refers to the plugin object
ctx.fillStyle = 'white';
ctx.fillRect(0, 0, width, height);
ctx.fillStyle = 'black';
// 1. Initialize random grid on first run or if it died out
if (!this.grid) {
this.grid = Array(this.cols).fill().map(() =>
Array(this.rows).fill(0).map(() => Math.random() > 0.85 ? 1 : 0)
);
}
let activeCells = 0;
// 2. Draw current grid
for(let i = 0; i < this.cols; i++) {
for(let j = 0; j < this.rows; j++) {
if(this.grid[i][j]) {
// Drawing rectangles with a 1px gap for a cool grid effect
ctx.fillRect((i * this.cellSize) + 1, (j * this.cellSize) + 1, this.cellSize - 2, this.cellSize - 2);
activeCells++;
}
}
}
// 3. Calculate next generation
let nextGen = Array(this.cols).fill().map(() => Array(this.rows).fill(0));
for(let i = 0; i < this.cols; i++) {
for(let j = 0; j < this.rows; j++) {
let state = this.grid[i][j];
let neighbors = 0;
// Count 8 neighbors with wrapping edges (toroidal array)
for(let x = -1; x <= 1; x++) {
for(let y = -1; y <= 1; y++) {
if(x === 0 && y === 0) continue;
let col = (i + x + this.cols) % this.cols;
let row = (j + y + this.rows) % this.rows;
neighbors += this.grid[col][row];
}
}
// Conway's Rules
if (state === 0 && neighbors === 3) nextGen[i][j] = 1;
else if (state === 1 && (neighbors < 2 || neighbors > 3)) nextGen[i][j] = 0;
else nextGen[i][j] = state;
}
}
this.grid = nextGen;
// Reset the grid if it completely dies so the screen isn't just blank forever
if (activeCells === 0) this.grid = null;
}
},
{
id: 'cricket_live',
theme: 'Sports & Live Events',
name: 'Live Cricket Scores',
description: 'Displays current match. Needs free key from cricketdata.org.',
minInterval: 60,
requiredKeys: [
{ id: 'cricketdata_key', type: 'password', label: 'CricketData.org API Key', required: true }
],
render: async (ctx, width, height, apiKeys) => {
const key = apiKeys['cricketdata_key'];
ctx.fillStyle = 'white';
ctx.fillRect(0, 0, width, height);
ctx.fillStyle = 'black';
canvasUtils.fitTextSingleLine(ctx, 'Live Cricket', 30, 60, width - 60, 40, 'bold');
ctx.fillRect(30, 80, width - 60, 4);
try {
// Fetch current matches
const url = `https://api.cricapi.com/v1/currentMatches?apikey=${key}&offset=0`;
const res = await fetch(`${config.cors_proxy}${encodeURIComponent(url)}`);
const data = await res.json();
if (!data.data || data.data.length === 0) {
canvasUtils.fitTextSingleLine(ctx, 'No live matches right now.', 30, 150, width - 60, 35);
return;
}
// Grab the first most relevant match
const match = data.data[0];
let yPos = 140;
// Match Title (e.g., India vs Australia)
canvasUtils.fitTextSingleLine(ctx, match.name, 30, yPos, width - 60, 35, 'bold');
yPos += 60;
// Loop through innings if scores exist
if (match.score && match.score.length > 0) {
match.score.forEach(inning => {
const scoreText = `${inning.inning}: ${inning.r}/${inning.w} (${inning.o} ov)`;
canvasUtils.fitTextSingleLine(ctx, scoreText, 30, yPos, width - 60, 45, 'bold');
yPos += 60;
});
} else {
canvasUtils.fitTextSingleLine(ctx, 'Match starting soon...', 30, yPos, width - 60, 30, 'italic');
yPos += 60;
}
// Match Status (e.g., "India require 34 runs to win from 12 balls")
// Using the multi-line utility because these statuses can be extremely long
ctx.fillStyle = '#333';
canvasUtils.fitTextMultiLine(ctx, match.status, 30, yPos + 20, width - 60, height - yPos - 40, 30, 'italic');
} catch (err) {
canvasUtils.fitTextMultiLine(ctx, 'Error fetching Cricket Data. Check your API key limits or proxy status.', 30, 150, width - 60, height - 200, 30);
console.error(err);
}
}
},
{
id: 'huggingface_trending',
theme: 'AI & Research',
name: 'Hugging Face Trending',
description: 'Top trending AI models from Hugging Face.',
doublePush:true,
minInterval: 3600, // 1 Hour (Trending doesn't change every 5 mins)
requiredKeys: [],
render: async (ctx, width, height, apiKeys) => {
ctx.fillStyle = 'white';
ctx.fillRect(0, 0, width, height);
ctx.fillStyle = 'black';
canvasUtils.fitTextSingleLine(ctx, 'Trending AI Models (Hugging Face)', 30, 60, width - 60, 40, 'bold');
ctx.fillRect(30, 80, width - 60, 4);
try {
// Hugging Face has a free, public API for this
const res = await fetch(`${config.cors_proxy}${encodeURIComponent('https://huggingface.co/models-json?sort=trending&withCount=true')}`);
const data = await res.json();
const models=data["models"].slice(0,4);
console.log(models);
let yPos = 140;
models.forEach((m, index) => {
// Extract model name and task (e.g., text-generation, image-classification)
let name = m.id;
let task = m.pipeline_tag ? m.pipeline_tag.toUpperCase() : 'UNKNOWN TASK';
let downloads = m.downloads ? m.downloads.toLocaleString() : 'N/A';
ctx.fillStyle = 'black';
canvasUtils.fitTextSingleLine(ctx, `${index + 1}. ${name}`, 30, yPos, width - 60, 28, 'bold');
ctx.fillStyle = '#333';
canvasUtils.fitTextSingleLine(ctx, `[${task}] | DLs: ${downloads}`, 60, yPos + 35, width - 90, 22, 'italic');
yPos += 85;
});
} catch (err) {
canvasUtils.fitTextSingleLine(ctx, 'Error fetching Hugging Face data.', 30, 150, width - 60, 30);
console.error(err);
}
}
},
{
id: 'latex_daily',
theme: 'AI & Research',
name: 'ML Equation of the Day',
description: 'Displays a beautiful AI/ML equation in LaTeX.',
minInterval: 3600, // 1 hour
doublePush: true,
requiredKeys: [],
render: async (ctx, width, height, apiKeys) => {
// A curated list of beautiful ML equations
const equations = [
// Foundational Math & Statistics
{ title: "Bayes' Theorem", formula: "P(A|B) = \\frac{P(B|A)P(A)}{P(B)}" },
{ title: "Normal Distribution (Gaussian)", formula: "f(x) = \\frac{1}{\\sigma\\sqrt{2\\pi}} \\exp\\left(-\\frac{(x-\\mu)^2}{2\\sigma^2}\\right)" },
{ title: "Covariance Matrix", formula: "\\Sigma = \\frac{1}{n-1} \\sum_{i=1}^n (x_i - \\bar{x})(x_i - \\bar{x})^T" },
{ title: "Cosine Similarity", formula: "\\text{sim}(A, B) = \\frac{A \\cdot B}{\\|A\\| \\|B\\|} = \\frac{\\sum A_i B_i}{\\sqrt{\\sum A_i^2}\\sqrt{\\sum B_i^2}}" },
{ title: "Pearson Correlation", formula: "r = \\frac{\\sum (x_i - \\bar{x})(y_i - \\bar{y})}{\\sqrt{\\sum (x_i - \\bar{x})^2 \\sum (y_i - \\bar{y})^2}}" },
{ title: "Markov Property", formula: "P(X_{n+1} = x | X_1, X_2, \\dots, X_n) = P(X_{n+1} = x | X_n)" },
// Loss Functions
{ title: "Mean Squared Error (MSE)", formula: "\\text{MSE} = \\frac{1}{n}\\sum_{i=1}^n(Y_i - \\hat{Y}_i)^2" },
{ title: "Cross-Entropy Loss", formula: "L = -\\sum_{c=1}^M y_{c} \\log(p_{c})" },
{ title: "Binary Cross-Entropy (Log Loss)", formula: "L = -\\frac{1}{N} \\sum_{i=1}^N \\left[ y_i \\log(\\hat{y}_i) + (1 - y_i) \\log(1 - \\hat{y}_i) \\right]" },
{ title: "Hinge Loss (SVM)", formula: "L = \\max(0, 1 - y \\cdot \\hat{y})" },
{ title: "Kullback-Leibler Divergence", formula: "D_{KL}(P||Q) = \\sum_{x} P(x) \\log\\left(\\frac{P(x)}{Q(x)}\right)" },
{ title: "Huber Loss", formula: "L_\\delta = \\begin{cases} \\frac{1}{2}(y - \\hat{y})^2 & \\text{for } |y - \\hat{y}| \\le \\delta \\\\ \\delta |y - \\hat{y}| - \\frac{1}{2}\\delta^2 & \\text{otherwise} \\end{cases}" },
// Activations
{ title: "Sigmoid Activation", formula: "\\sigma(x) = \\frac{1}{1 + e^{-x}}" },
{ title: "ReLU Activation", formula: "\\text{ReLU}(x) = \\max(0, x)" },
{ title: "Softmax Function", formula: "\\sigma(\\mathbf{z})_i = \\frac{e^{z_i}}{\\sum_{j=1}^K e^{z_j}}" },
{ title: "Hyperbolic Tangent (Tanh)", formula: "\\tanh(x) = \\frac{e^x - e^{-x}}{e^x + e^{-x}}" },
{ title: "GELU Activation", formula: "\\text{GELU}(x) = x \\cdot \\Phi(x) \\approx 0.5x \\left(1 + \\tanh\\left[\\sqrt{2/\\pi} (x + 0.044715 x^3)\\right]\\right)" },
{ title: "Swish Activation", formula: "\\text{Swish}(x) = x \\cdot \\sigma(\\beta x)" },
// Optimization & Learning
{ title: "Gradient Descent Update", formula: "\\theta_{t+1} = \\theta_t - \\eta \\nabla_{\\theta} J(\\theta_t)" },
{ title: "Backpropagation (Chain Rule)", formula: "\\frac{\\partial E}{\\partial w_{ij}} = \\frac{\\partial E}{\\partial o_j} \\frac{\\partial o_j}{\\partial net_j} \\frac{\\partial net_j}{\\partial w_{ij}}" },
{ title: "SGD with Momentum", formula: "v_t = \\gamma v_{t-1} + \\eta \\nabla_{\\theta} J(\\theta); \\quad \\theta_{t+1} = \\theta_t - v_t" },
{ title: "Adam Optimizer Update", formula: "\\theta_{t} = \\theta_{t-1} - \\frac{\\alpha \\cdot \\hat{m}_t}{\\sqrt{\\hat{v}_t} + \\epsilon}" },
{ title: "L2 Regularization (Ridge)", formula: "J(\\theta) = \\text{Loss}(\\theta) + \\lambda \\sum_{j=1}^p \\theta_j^2" },
// Transformers & NLP
{ title: "Scaled Dot-Product Attention", formula: "\\text{Attention}(Q, K, V) = \\text{softmax}\\left(\\frac{QK^T}{\\sqrt{d_k}}\\right)V" },
{ title: "Multi-Head Attention", formula: "\\text{MultiHead}(Q,K,V) = \\text{Concat}(\\text{head}_1, \\dots, \\text{head}_h)W^O" },
{ title: "Positional Encoding (Sine)", formula: "PE_{(pos, 2i)} = \\sin\\left(\\frac{pos}{10000^{2i/d_{\\text{model}}}}\\right)" },
{ title: "Positional Encoding (Cosine)", formula: "PE_{(pos, 2i+1)} = \\cos\\left(\\frac{pos}{10000^{2i/d_{\\text{model}}}}\\right)" },
{ title: "TF-IDF", formula: "\\text{tf-idf}(t, d, D) = \\text{tf}(t, d) \\times \\log\\left(\\frac{N}{|\\{d \\in D : t \\in d\\}|}\\right)" },
// Generative AI
{ title: "GAN Minimax Objective", formula: "\\min_G \\max_D V(D,G) = \\mathbb{E}_x[\\log D(x)] + \\mathbb{E}_z[\\log(1 - D(G(z)))]" },
{ title: "VAE ELBO (Evidence Lower Bound)", formula: "\\text{ELBO} = \\mathbb{E}_{q_\\phi}[\\log p_\\theta(x|z)] - D_{KL}(q_\\phi(z|x) || p(z))" },
{ title: "Diffusion Forward Process", formula: "q(x_t | x_{t-1}) = \\mathcal{N}(x_t; \\sqrt{1 - \\beta_t} x_{t-1}, \\beta_t I)" },
{ title: "Diffusion Reverse Process", formula: "p_\\theta(x_{t-1} | x_t) = \\mathcal{N}(x_{t-1}; \\mu_\\theta(x_t, t), \\Sigma_\\theta(x_t, t))" },
// Classic Machine Learning
{ title: "Logistic Regression", formula: "P(Y=1|X) = \\frac{1}{1 + e^{-(\\beta_0 + \\beta_1 X_1 + \\dots + \\beta_k X_k)}}" },
{ title: "K-Means Objective", formula: "J = \\sum_{j=1}^k \\sum_{i=1}^n \\|x_i^{(j)} - c_j\\|^2" },
{ title: "PCA Eigenvalue Problem", formula: "\\Sigma \\mathbf{v} = \\lambda \\mathbf{v}" },
{ title: "Bellman Equation (RL)", formula: "V(s) = \\max_a \\left( R(s,a) + \\gamma \\sum_{s'} P(s'|s,a) V(s') \\right)" },
{ title: "Q-Learning Update", formula: "Q(s,a) \\leftarrow Q(s,a) + \\alpha \\left[ r + \\gamma \\max_{a'} Q(s',a') - Q(s,a) \\right]" },
// Computer Vision / Matrices
{ title: "2D Convolution", formula: "(I * K)(i, j) = \\sum_m \\sum_n I(i - m, j - n) K(m, n)" },
{ title: "Intersection over Union (IoU)", formula: "\\text{IoU} = \\frac{\\text{Area of Overlap}}{\\text{Area of Union}}" },
{ title: "Frobenius Norm", formula: "\\|A\\|_F = \\sqrt{\\sum_{i=1}^m \\sum_{j=1}^n |a_{ij}|^2}" }
];
// Pick a random equation
const eq = equations[Math.floor(Math.random() * equations.length)];
ctx.fillStyle = 'white';
ctx.fillRect(0, 0, width, height);
// Header
ctx.fillStyle = 'black';
ctx.textAlign = 'center';
canvasUtils.fitTextSingleLine(ctx, eq.title, width / 2, 80, width - 40, 40, 'bold');
ctx.fillRect(40, 100, width - 80, 4);
ctx.textAlign = 'left'; // Reset
try {
// The Smarter Way: Waterfall Fetch
// Start massive, and step down only if the true pixel width is too large
const sizes = ['\\Huge', '\\huge', '\\LARGE', '\\large', '\\small'];
let bitmap = null;
const maxWidth = width - 80; // 40px margin on each side
for (let i = 0; i < sizes.length; i++) {
const sizeMod = sizes[i];
const latexUrl = `https://latex.codecogs.com/png.image?\\dpi{200}\\bg_white${sizeMod} ${encodeURIComponent(eq.formula)}`;
const res = await fetch(`${config.cors_proxy}${encodeURIComponent(latexUrl)}`);
const blob = await res.blob();
bitmap = await createImageBitmap(blob);
// If the image fits natively, or we've hit the smallest size, stop fetching!
if (bitmap.width <= maxWidth || i === sizes.length - 1) {
break;
}
}
// Optional: Gentle canvas scale just in case \small is STILL too wide
const finalScale = Math.min(1, maxWidth / bitmap.width);
const drawW = bitmap.width * finalScale;
const drawH = bitmap.height * finalScale;
// Center the equation
const imgX = (width - drawW) / 2;
const imgY = (height - drawH) / 2 + 40;
ctx.drawImage(bitmap, imgX, imgY, drawW, drawH);
} catch (err) {
ctx.textAlign = 'center';
canvasUtils.fitTextSingleLine(ctx, 'Failed to render LaTeX image.', width / 2, height / 2, width - 60, 30);
ctx.textAlign = 'left';
console.error(err);
}
}
},
{
id: 'pomodoro_timer',
theme: 'Productivity',
name: 'Pomodoro Tracker',
description: 'Deep work timer. Auto-switches between Work and Break.',
minInterval: 60, // Updates once a minute
requiredKeys: [
{ id: 'work_mins', type: 'number', label: 'Work Focus (Minutes)', placeholder: '25' },
{ id: 'break_mins', type: 'number', label: 'Break (Minutes)', placeholder: '5' }
],
// Internal state to track the timer across refresh cycles
state: { endTime: 0, mode: 'Idle', totalMins: 0 },
render: async function(ctx, width, height, apiKeys) {
const workMins = parseInt(apiKeys['work_mins']) || 25;
const breakMins = parseInt(apiKeys['break_mins']) || 5;
const now = Date.now();
// Initialize or switch modes if time is up
if (this.state.mode === 'Idle' || now >= this.state.endTime) {
this.state.mode = this.state.mode === 'Work' ? 'Break' : 'Work';
this.state.totalMins = this.state.mode === 'Work' ? workMins : breakMins;
this.state.endTime = now + (this.state.totalMins * 60 * 1000);
}
const remainingMs = this.state.endTime - now;
const remainingMins = Math.ceil(remainingMs / 60000);
// Calculate progress for the bar (0.0 to 1.0)
const progress = 1 - (remainingMins / this.state.totalMins);
// Draw Background
ctx.fillStyle = 'white';
ctx.fillRect(0, 0, width, height);
// Draw Mode Header
ctx.fillStyle = 'black';
ctx.textAlign = 'center';
canvasUtils.fitTextSingleLine(ctx, `${this.state.mode} Session`, width / 2, 100, width - 40, 60, 'bold');
// Draw Giant Remaining Minutes
canvasUtils.fitTextSingleLine(ctx, `${remainingMins} MIN`, width / 2, 280, width - 40, 160, 'bold');
// Reset text align
ctx.textAlign = 'left';
// Draw Progress Bar outline
const barX = 50;
const barY = 380;
const barW = width - 100;
const barH = 40;
ctx.lineWidth = 4;
ctx.strokeStyle = 'black';
ctx.strokeRect(barX, barY, barW, barH);
// Fill Progress Bar
ctx.fillStyle = 'black';
ctx.fillRect(barX + 4, barY + 4, (barW - 8) * progress, barH - 8);
}
},
{
id: 'desk_clock',
theme: 'Daily Utility',
name: 'Minimalist Desk Clock',
description: 'A massive, easy-to-read digital clock and date.',
minInterval: 60, // Updates every minute
requiredKeys: [],
render: async (ctx, width, height, apiKeys) => {
ctx.fillStyle = 'white';
ctx.fillRect(0, 0, width, height);
const now = new Date();
// Format Time (e.g., "10:15 AM")
const timeString = now.toLocaleTimeString('en-US', {
hour: 'numeric',
minute: '2-digit',
hour12: true
});
// Format Date (e.g., "Saturday, February 28")
const dateString = now.toLocaleDateString('en-US', {
weekday: 'long',
month: 'long',
day: 'numeric'
});
ctx.fillStyle = 'black';
ctx.textAlign = 'center';
// Giant Time
canvasUtils.fitTextSingleLine(ctx, timeString, width / 2, 240, width - 40, 180, 'bold');
// Subtitle Date
ctx.fillStyle = '#333';
canvasUtils.fitTextSingleLine(ctx, dateString, width / 2, 340, width - 40, 50, 'normal');
ctx.textAlign = 'left'; // Reset
}
},
{
id: 'ml_glossary',
theme: 'AI & Research',
name: 'ML Glossary',
description: 'Cycles through Machine Learning terminology.',
minInterval: 3600, // Update once an hour
doublePush: true,
requiredKeys: [],
render: async (ctx, width, height, apiKeys) => {
const terms = [
// Foundational Concepts
{ term: "Overfitting", def: "When a model learns the training data too well, including the noise, resulting in poor performance on unseen data." },
{ term: "Gradient Descent", def: "An optimization algorithm used to minimize the loss function by iteratively moving in the direction of steepest descent." },
{ term: "Epoch", def: "One complete pass of the training dataset through the machine learning algorithm." },
{ term: "Zero-Shot Learning", def: "A model's ability to recognize or categorize objects/concepts it has never seen during training, usually using semantic representations." },
{ term: "Hyperparameter", def: "A parameter whose value is set before the learning process begins, like learning rate or batch size (unlike weights which are derived)." },
{ term: "Bias-Variance Tradeoff", def: "The balance between a model's ability to capture underlying patterns (low bias) and its sensitivity to fluctuations in the training data (low variance)." },
{ term: "Cross-Validation", def: "A resampling procedure used to evaluate machine learning models on a limited data sample, often by splitting data into 'k' folds." },
{ term: "Regularization", def: "Techniques (like L1 or L2) used to penalize complex models to prevent overfitting and improve generalization." },
{ term: "Learning Rate", def: "A hyperparameter that determines the step size at each iteration while moving toward a minimum of a loss function." },
{ term: "Loss Function", def: "A method of evaluating how well your algorithm models your dataset. If predictions deviate too much from actual results, loss function would cough up a very large number." },
// Neural Network Basics
{ term: "Perceptron", def: "The simplest form of a neural network, consisting of a single layer of linear threshold units." },
{ term: "Activation Function", def: "A mathematical equation attached to each neuron in a network that determines whether it should be activated or not (e.g., ReLU, Sigmoid)." },
{ term: "Backpropagation", def: "The primary algorithm for training neural networks, computing the gradient of the loss function with respect to each weight by the chain rule." },
{ term: "Feedforward Network", def: "An artificial neural network wherein connections between the nodes do not form a cycle." },
{ term: "Dropout", def: "A regularization technique where randomly selected neurons are ignored during training to prevent co-adaptation of features." },
{ term: "Batch Normalization", def: "A technique that standardizes the inputs to a layer for each mini-batch, stabilizing the learning process and reducing the number of training epochs." },
{ term: "Stochastic Gradient Descent (SGD)", def: "A variant of gradient descent that updates the model parameters using only a single or a few training examples at a time." },
{ term: "Adam Optimizer", def: "An adaptive learning rate optimization algorithm that computes individual adaptive learning rates for different parameters from estimates of first and second moments of the gradients." },
{ term: "Softmax Function", def: "A function that turns a vector of K real values into a vector of K real values that sum to 1, often used as the output activation in multi-class classification." },
{ term: "Vanishing Gradient", def: "A difficulty in training deep neural networks where the gradient becomes incredibly small, preventing the weights from changing their value." },
// Vision & Spatial AI
{ term: "Convolutional Neural Network (CNN)", def: "A class of deep neural networks, most commonly applied to analyzing visual imagery through grid-like topology." },
{ term: "Pooling Layer", def: "A layer in a CNN that reduces the spatial dimensions (width and height) of the input volume, lowering computational cost." },
{ term: "Receptive Field", def: "The defined portion of the input space that a particular CNN feature is looking at." },
{ term: "Semantic Segmentation", def: "The process of classifying every pixel in an image to a specific class or object category." },
{ term: "U-Net", def: "A convolutional network architecture designed for fast and precise image segmentation, highly popular in biomedical image processing." },
{ term: "Object Detection", def: "A computer vision task that involves predicting the presence of multiple objects in an image and putting bounding boxes around them." },
{ term: "Voxel", def: "A value on a regular grid in three-dimensional space, essentially the 3D equivalent of a pixel." },
{ term: "Point Cloud", def: "A set of data points in space, usually produced by 3D scanners, representing the external surface of an object or scene." },
{ term: "Marching Cubes", def: "A computer graphics algorithm that extracts a polygonal mesh of an isosurface from a three-dimensional discrete scalar field (like medical DICOM scans)." },
{ term: "Intersection over Union (IoU)", def: "An evaluation metric used to measure the accuracy of an object detector on a particular dataset." },
// Transformers & NLP
{ term: "Transformer", def: "A deep learning architecture that relies entirely on self-attention mechanisms to draw global dependencies between input and output." },
{ term: "Self-Attention", def: "A mechanism relating different positions of a single sequence in order to compute a representation of the sequence." },
{ term: "Large Language Model (LLM)", def: "A computational model notable for its ability to achieve general-purpose language generation and other NLP tasks, scaled via massive parameters." },
{ term: "Tokenization", def: "The process of breaking down text into smaller units (tokens) such as words, subwords, or characters for processing by a model." },
{ term: "Embeddings", def: "Dense vectors of real numbers representing text or objects in a continuous vector space, capturing semantic meaning." },
{ term: "Fine-Tuning", def: "Taking a pre-trained model and training it further on a smaller, specific dataset to adapt it to a specialized task." },
{ term: "Recurrent Neural Network (RNN)", def: "A class of neural networks where connections between nodes form a directed graph along a temporal sequence." },
{ term: "Long Short-Term Memory (LSTM)", def: "An artificial RNN architecture capable of learning order dependence in sequence prediction problems." },
{ term: "BLEU Score", def: "An algorithm for evaluating the quality of text which has been machine-translated from one natural language to another." },
{ term: "Named Entity Recognition (NER)", def: "An information extraction task that seeks to locate and classify named entities in text into predefined categories (e.g., person, location)." },
// Generative AI
{ term: "Generative Adversarial Network (GAN)", def: "A class of machine learning frameworks designed by Goodfellow et al. wherein two neural networks contest with each other in a game." },
{ term: "Discriminator", def: "The network in a GAN whose goal is to distinguish between real data and the fake data generated by its adversary." },
{ term: "Generator", def: "The network in a GAN whose goal is to create synthetic data that is indistinguishable from real data to fool the discriminator." },
{ term: "Autoencoder", def: "A type of neural network used to learn efficient data codings in an unsupervised manner, typically for dimensionality reduction." },
{ term: "Variational Autoencoder (VAE)", def: "A generative model that provides a probabilistic manner for describing an observation in latent space." },
{ term: "Diffusion Model", def: "A class of generative models that learn to generate data by reversing a gradual noising process." },
{ term: "Latent Space", def: "A compressed, multidimensional space in which a machine learning model maps complex input data to internal representations." },
{ term: "Prompt Engineering", def: "The process of designing and optimizing input text prompts to elicit desired outputs from large language models." },
{ term: "Hallucination", def: "A phenomenon where an AI model generates false, nonsensical, or ungrounded information presented as fact." },
{ term: "Temperature", def: "A hyperparameter used in generative models to control the randomness of predictions; higher values lead to more diverse outputs." },
// Data & Engineering
{ term: "Feature Engineering", def: "The process of using domain knowledge to extract features (characteristics, properties, attributes) from raw data." },
{ term: "Dimensionality Reduction", def: "The transformation of data from a high-dimensional space into a low-dimensional space so that the low-dimensional representation retains meaningful properties." },
{ term: "Principal Component Analysis (PCA)", def: "A statistical procedure that uses an orthogonal transformation to convert observations into a set of values of linearly uncorrelated variables." },
{ term: "One-Hot Encoding", def: "A process of converting categorical data variables so they can be provided to machine learning algorithms to improve predictions." },
{ term: "Data Augmentation", def: "A set of techniques used to increase the amount of data by adding slightly modified copies of already existing data or newly created synthetic data." },
{ term: "Imputation", def: "The process of replacing missing data with substituted values." },
{ term: "Normalization", def: "Scaling individual samples to have unit norm, or scaling features to be between 0 and 1." },
{ term: "Standardization", def: "Transforming data to have a mean of zero and a standard deviation of one." },
{ term: "Outlier", def: "An observation that lies an abnormal distance from other values in a random sample from a population." },
{ term: "Ground Truth", def: "Information provided by direct observation or empirical evidence, considered to be the absolute truth for training algorithms." },
// Learning Paradigms
{ term: "Supervised Learning", def: "A machine learning paradigm where models are trained using labeled data." },
{ term: "Unsupervised Learning", def: "Training models on data that has no historical labels, asking the algorithm to find structures or patterns." },
{ term: "Reinforcement Learning", def: "An area of ML concerned with how intelligent agents ought to take actions in an environment to maximize the notion of cumulative reward." },
{ term: "Semi-Supervised Learning", def: "An approach to ML that combines a small amount of labeled data with a large amount of unlabeled data during training." },
{ term: "Transfer Learning", def: "A research problem in ML that focuses on storing knowledge gained while solving one problem and applying it to a different but related problem." },
{ term: "Active Learning", def: "A special case of ML in which a learning algorithm can interactively query a user to label new data points with the desired outputs." },
{ term: "Federated Learning", def: "A machine learning technique that trains an algorithm across multiple decentralized edge devices holding local data samples, without exchanging them." },
{ term: "Contrastive Learning", def: "A machine learning technique where a model learns to distinguish between similar and dissimilar data points." },
{ term: "Ensemble Learning", def: "A process using multiple learning algorithms to obtain better predictive performance than could be obtained from any of the constituent learning algorithms alone." },
{ term: "Few-Shot Learning", def: "Feeding a learning model with a very small amount of training data, contrary to the normal practice of using a large amount." },
// Hardware, Deployment & Edge
{ term: "Inference", def: "The process of running data through a trained machine learning model to make a prediction." },
{ term: "Quantization", def: "The process of reducing the precision of the weights, biases, and activations in a neural network to make it faster and smaller." },
{ term: "Model Pruning", def: "A technique to make neural networks smaller and faster by removing weights that contribute little to the model's output." },
{ term: "Edge AI", def: "The deployment of AI applications in devices throughout the physical world (edge computing) rather than strictly in the cloud." },
{ term: "TinyML", def: "A field of study in ML and embedded systems that explores the types of models you can run on small, low-power devices like microcontrollers." },
{ term: "Tensor Processing Unit (TPU)", def: "An AI accelerator application-specific integrated circuit (ASIC) developed by Google specifically for neural network machine learning." },
{ term: "ONNX", def: "Open Neural Network Exchange: An open-source ecosystem that gives AI developers the flexibility to move models between different tools and frameworks." },
{ term: "CUDA", def: "A parallel computing platform and API created by Nvidia, heavily used for training neural networks on GPUs." },
{ term: "Batch Size", def: "The number of training examples utilized in one iteration." },
{ term: "Containerization", def: "Packaging software code with just the operating system libraries and dependencies required to run the code to create a single lightweight executable (e.g., Docker)." },
// Evaluation Metrics
{ term: "Accuracy", def: "The ratio of correctly predicted observation to the total observations." },
{ term: "Precision", def: "The ratio of correctly predicted positive observations to the total predicted positive observations." },
{ term: "Recall (Sensitivity)", def: "The ratio of correctly predicted positive observations to the all observations in actual class." },
{ term: "F1 Score", def: "The weighted average of Precision and Recall, useful when you have an uneven class distribution." },
{ term: "Confusion Matrix", def: "A table that is often used to describe the performance of a classification model on a set of test data for which the true values are known." },
{ term: "ROC Curve", def: "Receiver Operating Characteristic curve: A graphical plot that illustrates the diagnostic ability of a binary classifier system." },
{ term: "AUC", def: "Area Under the Curve: Represents the degree or measure of separability, telling how much the model is capable of distinguishing between classes." },
{ term: "Mean Squared Error (MSE)", def: "A measure of the average of the squares of the errors—that is, the average squared difference between the estimated values and the actual value." },
{ term: "Mean Absolute Error (MAE)", def: "A measure of errors between paired observations expressing the same phenomenon." },
{ term: "R-Squared", def: "A statistical measure that represents the proportion of the variance for a dependent variable that's explained by an independent variable." },
// Advanced / Math Specifics
{ term: "Hessian Matrix", def: "A square matrix of second-order partial derivatives of a scalar-valued function, used in advanced optimization." },
{ term: "Entropy", def: "A measure of the unpredictability of the state, or equivalently, of its average information content." },
{ term: "Cross-Entropy Loss", def: "A metric used to measure how well a classification model in machine learning performs, calculating the difference between two probability distributions." },
{ term: "Kullback-Leibler (KL) Divergence", def: "A measure of how one probability distribution is different from a second, reference probability distribution." },
{ term: "Manifold Hypothesis", def: "The idea that many high-dimensional data sets that occur in the real world actually lie along low-dimensional latent manifolds." },
{ term: "Soft Margin", def: "A modification in Support Vector Machines allowing some data points to be misclassified in order to achieve a better overall fit." },
{ term: "Markov Decision Process (MDP)", def: "A discrete-time stochastic control process providing a mathematical framework for modeling decision making in situations where outcomes are partly random." },
{ term: "Exploration vs. Exploitation", def: "The dilemma in reinforcement learning between choosing an action with an unknown reward (exploration) or the action with the highest known reward (exploitation)." },
{ term: "Weight Initialization", def: "The procedure to set the initial values of a neural network's weights before training begins." },
{ term: "Early Stopping", def: "A form of regularization used to avoid overfitting when training a learner with an iterative method, stopping when performance on validation data degrades." }
];
const item = terms[Math.floor(Math.random() * terms.length)];
ctx.fillStyle = 'white';
ctx.fillRect(0, 0, width, height);
// Header
ctx.fillStyle = 'black';
canvasUtils.fitTextSingleLine(ctx, 'ML Term of the Day', 40, 60, width - 80, 35, 'bold');
ctx.fillRect(40, 80, width - 80, 4);
// The Term
canvasUtils.fitTextSingleLine(ctx, item.term, 40, 180, width - 80, 70, 'bold');
// The Definition (using the multi-line utility so it wraps nicely!)
ctx.fillStyle = '#333';
canvasUtils.fitTextMultiLine(ctx, item.def, 40, 240, width - 80, 200, 40, 'normal');
}
},
{
id: 'todoist_tasks',
theme: 'Productivity',
name: 'Todoist Active Tasks',
description: 'Pulls your top tasks directly from Todoist.',
minInterval: 300, // 5 minutes
requiredKeys: [
{ id: 'todoist_token', type: 'password', label: 'Todoist API Token (Bearer)', required: true }
],
render: async (ctx, width, height, apiKeys) => {
const token = apiKeys['todoist_token'];
ctx.fillStyle = 'white';
ctx.fillRect(0, 0, width, height);
ctx.fillStyle = 'black';
canvasUtils.fitTextSingleLine(ctx, 'Today\'s Focus', 30, 60, width - 60, 40, 'bold');
ctx.fillRect(30, 80, width - 60, 4);
try {
// Todoist API wrapped in our proxy
const url = 'https://api.todoist.com/api/v1/tasks?filter=today|overdue';
const res = await fetch(`${config.cors_proxy}${encodeURIComponent(url)}`, {
headers: { 'Authorization': `Bearer ${token}` }
});
if (!res.ok) throw new Error('Failed to fetch tasks');
const tasks = await res.json();
if (tasks.length === 0) {
canvasUtils.fitTextSingleLine(ctx, 'Inbox Zero! No tasks for today.', 30, 150, width - 60, 35, 'italic');
return;
}