file_path
stringlengths
3
280
file_language
stringclasses
66 values
content
stringlengths
1
1.04M
repo_name
stringlengths
5
92
repo_stars
int64
0
154k
repo_description
stringlengths
0
402
repo_primary_language
stringclasses
108 values
developer_username
stringlengths
1
25
developer_name
stringlengths
0
30
developer_company
stringlengths
0
82
js/fix-toc.js
JavaScript
// fix some issues in TOC generated by Hugo (Blackfriday or Goldmark) (function() { const toc = document.getElementById('TableOfContents'); if (!toc) return; // fix header ids and a hrefs if a header contains a link toc.querySelectorAll('a[href^="#"]').forEach((a) => { let id = a.getAttribute('href').replac...
yihui/lite.js
19
Miscellaneous lightweight tools and utilities in JavaScript
JavaScript
yihui
Yihui Xie
rstudio swissre merck
js/fold-details.js
JavaScript
// fold elements with <details>: https://yihui.org/en/2023/09/code-folding/ (d => { const cfg = d.currentScript?.dataset, cls = 'folder'; let status = !!cfg?.open; d.querySelectorAll(cfg?.selector || 'pre:not([class])>code[class],pre[class]').forEach(el => { const s1 = d.createElement('details'), s2 = d.createE...
yihui/lite.js
19
Miscellaneous lightweight tools and utilities in JavaScript
JavaScript
yihui
Yihui Xie
rstudio swissre merck
js/fold-output.js
JavaScript
// toggle output of source code by clicking on source code (() => { const blocks = []; document.querySelectorAll('pre>code[class^=language-],pre[class^=language-]').forEach(el => { // if <code> is selected, use its parent if (el.tagName === 'CODE' && el.parentNode.tagName === 'PRE') el = el.parentNode; ...
yihui/lite.js
19
Miscellaneous lightweight tools and utilities in JavaScript
JavaScript
yihui
Yihui Xie
rstudio swissre merck
js/fullwidth.js
JavaScript
// look for overflowed <pre> and <table>, and assign .fullwidth class to them document.querySelectorAll('pre,table,#TableOfContents').forEach(node => { function fullwidth(el) { el.classList.add('fullwidth'); } // skip if already in .fullwidth container if (node.closest('.fullwidth')) return; switch (node....
yihui/lite.js
19
Miscellaneous lightweight tools and utilities in JavaScript
JavaScript
yihui
Yihui Xie
rstudio swissre merck
js/fuse-search.js
JavaScript
// perform searching via Fuse.js with data from /index.json (d => { const input = d.querySelector('#search-input'), output = d.querySelector('.search-results'); if (!input || !output) return; const ds = input.dataset; // load search index for Fuse.js let fuse; input.addEventListener('focus', e => { ...
yihui/lite.js
19
Miscellaneous lightweight tools and utilities in JavaScript
JavaScript
yihui
Yihui Xie
rstudio swissre merck
js/g2-column.js
JavaScript
// support columnar data format in G2 G2.register('data.column', (options) => { const { value } = options; return async () => { let d = value; // handle URL strings if necessary if (typeof value === 'string') { const resp = await fetch(value); d = await resp.json(); } const keys = Ob...
yihui/lite.js
19
Miscellaneous lightweight tools and utilities in JavaScript
JavaScript
yihui
Yihui Xie
rstudio swissre merck
js/hash-notes.js
JavaScript
// convert <!--# comments --> to <span class="hash-notes">comments</span> (d => { function toSpan(el) { const t = el.textContent, r = /^#[\s\n]+([\s\S]+)[\s\n]+$/; if (!r.test(t)) return; d.body.classList.add('has-notes', 'hide-notes'); // use <p> if the comment's parent is not <p>; otherwise use inli...
yihui/lite.js
19
Miscellaneous lightweight tools and utilities in JavaScript
JavaScript
yihui
Yihui Xie
rstudio swissre merck
js/heading-anchor.js
JavaScript
document.querySelectorAll('h1,h2,h3,h4,h5,h6').forEach(h => { if (h.id && !h.querySelector('.anchor')) h.insertAdjacentHTML('beforeend', ` <span class="anchor"><a href="#${h.id}"></a></span>`); });
yihui/lite.js
19
Miscellaneous lightweight tools and utilities in JavaScript
JavaScript
yihui
Yihui Xie
rstudio swissre merck
js/key-buttons.js
JavaScript
(d => { const a1 = ['Enter', 'Up', 'Down', 'Left', 'Right']; const a2 = ['&crarr;', '&uarr;', '&darr;', '&larr;', '&rarr;']; function drawArrows(x) { a1.map((v, i) => x = x.replace(new RegExp(`>${v}<`, 'g'), ` title="${v + (i ? ' Arrow' : '')}">${a2[i]}<`)); return x; } // 1. individual keys; 2. modif...
yihui/lite.js
19
Miscellaneous lightweight tools and utilities in JavaScript
JavaScript
yihui
Yihui Xie
rstudio swissre merck
js/load-highlight.js
JavaScript
hljs.configure({languages: []}); hljs.highlightAll ? hljs.highlightAll() : hljs.initHighlightingOnLoad();
yihui/lite.js
19
Miscellaneous lightweight tools and utilities in JavaScript
JavaScript
yihui
Yihui Xie
rstudio swissre merck
js/load-pangu.js
JavaScript
pangu.spacingPage();
yihui/lite.js
19
Miscellaneous lightweight tools and utilities in JavaScript
JavaScript
yihui
Yihui Xie
rstudio swissre merck
js/load-typekit.js
JavaScript
(d => { // https://www.kirupa.com/html5/detect_whether_font_is_installed.htm const canvas = d.createElement("canvas"), context = canvas.getContext("2d"), text = "abcdefghijklmnopqrstuvwxyz0123456789"; context.font = "72px monospace"; const size = context.measureText(text).width; for (let font of [' SC', '...
yihui/lite.js
19
Miscellaneous lightweight tools and utilities in JavaScript
JavaScript
yihui
Yihui Xie
rstudio swissre merck
js/math-code.js
JavaScript
// <code>$math$</code> to \(math\), and <code>$$math$$</code> to $$math$$: // https://yihui.org/en/2018/07/latex-math-markdown/ document.querySelectorAll(':not(pre) > code:not(.nolatex)').forEach(code => { // skip <pre> tags and <code> that has children or the nolatex class if (code.childElementCount > 0) return; ...
yihui/lite.js
19
Miscellaneous lightweight tools and utilities in JavaScript
JavaScript
yihui
Yihui Xie
rstudio swissre merck
js/mathjax-config.js
JavaScript
// enable MathJax equation numbering: https://docs.mathjax.org/en/latest/input/tex/eqnumbers.html (() => { m = window.MathJax || {}; // make sure not to override existing config m.tex = m.tex || {}; m.tex.tags = m.tex.tags || 'ams'; window.MathJax = m; })();
yihui/lite.js
19
Miscellaneous lightweight tools and utilities in JavaScript
JavaScript
yihui
Yihui Xie
rstudio swissre merck
js/no-highlight.js
JavaScript
document.querySelectorAll('pre > code:only-child').forEach(code => { const cls = code.className; if (cls === '' || cls === 'hljs') { code.className = 'nohighlight'; } else if (/^language-/.test(cls) && !/hljs/.test(cls)) { code.className += ' hljs'; } })
yihui/lite.js
19
Miscellaneous lightweight tools and utilities in JavaScript
JavaScript
yihui
Yihui Xie
rstudio swissre merck
js/number-captions.js
JavaScript
// number figure and table captions // config options via data-foo attributes of this <script>: // * data-colon: the colon character (':' by default); // * data-fig-label: label for figure captions ('Figure ' by default) // * data-tab-label: label for table captions ('Table ' by default) (d => { const cfg = d...
yihui/lite.js
19
Miscellaneous lightweight tools and utilities in JavaScript
JavaScript
yihui
Yihui Xie
rstudio swissre merck
js/number-sections.js
JavaScript
// add section numbers to headings (d => { // find the body of the article let b; ['.article', '.body', 'article', 'body'].forEach(s => { if (!b) b = d.querySelector(s); }); const hs = b.querySelectorAll('h1, h2, h3, h4, h5, h6'); if (hs.length === 0) return; // normalize Pandoc's .header-section-numb...
yihui/lite.js
19
Miscellaneous lightweight tools and utilities in JavaScript
JavaScript
yihui
Yihui Xie
rstudio swissre merck
js/ol-id.js
JavaScript
// add ID to <ol> items so that they can be referenced via URL hashes like #li-N ((d) => { // add IDs to top-level <ol>s const ols = d.querySelectorAll(':not(li) > ol'); ols.forEach((ol, i) => { ol.querySelectorAll(':scope > li').forEach((li, j) => { if (!li.id) li.id = 'li-' + (ols.length > 1 ? i + 1 ...
yihui/lite.js
19
Miscellaneous lightweight tools and utilities in JavaScript
JavaScript
yihui
Yihui Xie
rstudio swissre merck
js/pages.js
JavaScript
// move elements into page boxes such that each box contains as many elements as // possible and will not exceed the given size (e.g. A4 paper) (d => { function $(s, el = d) { return el?.querySelector(s); } function $$(s, el = d) { return el ? el.querySelectorAll(s) : []; } function nChild(el) { return el.childE...
yihui/lite.js
19
Miscellaneous lightweight tools and utilities in JavaScript
JavaScript
yihui
Yihui Xie
rstudio swissre merck
js/post-nav.js
JavaScript
// navigate to previous/next posts by Left/Right arrows, and Alt + <-/-> for back/forward (d => { const a1 = d.querySelector('.nav-prev > a'), a2 = d.querySelector('.nav-next > a'); d.addEventListener('keyup', function(e) { if (e.target.nodeName.toUpperCase() != 'BODY') return; let u; if (e.key === 'Arr...
yihui/lite.js
19
Miscellaneous lightweight tools and utilities in JavaScript
JavaScript
yihui
Yihui Xie
rstudio swissre merck
js/render-katex.js
JavaScript
// support \ref \eqref \label for KaTeX, based on https://github.com/KaTeX/KaTeX/issues/2003 (d => { renderMathInElement(d.body, { strict: false, throwOnError: false, trust: context => ['\\href', '\\htmlId', '\\htmlClass'].includes(context.command), macros: { '\\eqref': '\\htmlClass{ktx-eqref}{\\hre...
yihui/lite.js
19
Miscellaneous lightweight tools and utilities in JavaScript
JavaScript
yihui
Yihui Xie
rstudio swissre merck
js/revdep-log-reader.js
JavaScript
// the CRAN revdep check log can be extremely lengthy, so I wrote this script to // make the log easier to read (using one tab for one package/problem) (d => { const entries = d.body.innerText .replace(/^(.|\n)*?(?=Package:)/, '') .split(/(^|\n)Package: /) .filter(x => x.trim()) .map(x => `<div class=...
yihui/lite.js
19
Miscellaneous lightweight tools and utilities in JavaScript
JavaScript
yihui
Yihui Xie
rstudio swissre merck
js/right-quote.js
JavaScript
// originally to right-align a quote footer if it starts with ---; now it just // right-align all paragraphs that start with em-dashes [...document.getElementsByTagName('p')].forEach(p => { if (/^(—|―|---)/.test(p.textContent)) p.style.textAlign = 'right'; });
yihui/lite.js
19
Miscellaneous lightweight tools and utilities in JavaScript
JavaScript
yihui
Yihui Xie
rstudio swissre merck
js/sidenotes.js
JavaScript
// move footnotes (ids start with fn) and citations (ids start with ref-) to sidenotes (d => { d.querySelectorAll('.footnotes > ol > li[id^="fn"], #refs > [id^="ref-"]').forEach(el => { // find <a> that points to note id in body const h = `a[href="#${el.id}"]`; d.querySelectorAll(`${h} > sup, sup > ${h}, ...
yihui/lite.js
19
Miscellaneous lightweight tools and utilities in JavaScript
JavaScript
yihui
Yihui Xie
rstudio swissre merck
js/snap.js
JavaScript
(function(d) { let p = d.body; // container of slides; assume <body> for now const s1 = ':scope > hr:not([class])', s2 = ':scope > h2'; // find a container that has at least n "slides" function findContainer(s, n = 1) { if (p.querySelectorAll(s).length >= n) return true; // if body doesn't contain head...
yihui/lite.js
19
Miscellaneous lightweight tools and utilities in JavaScript
JavaScript
yihui
Yihui Xie
rstudio swissre merck
js/tabsets.js
JavaScript
// find an element with class `tabset` and convert its subsequent bullet list or headings to tabs; // see documentation at: https://yihui.org/en/2023/10/section-tabsets/ document.querySelectorAll('.tabset').forEach(h => { const links = [...h.querySelectorAll(':scope > .tab-link')], panes = [...h.querySelector...
yihui/lite.js
19
Miscellaneous lightweight tools and utilities in JavaScript
JavaScript
yihui
Yihui Xie
rstudio swissre merck
js/toc-highlight.js
JavaScript
// highlight a TOC item when scrolling to a corresponding section heading (d => { // assume TOC has these possible IDs (we can also consider other selectors) const s = 'a[href^="#"]', toc = d.querySelector(`:is(#TableOfContents, #TOC):has(${s})`); if (!toc) return; const links = toc.querySelectorAll(s), dict = ...
yihui/lite.js
19
Miscellaneous lightweight tools and utilities in JavaScript
JavaScript
yihui
Yihui Xie
rstudio swissre merck
js/toc.js
JavaScript
// build TOC using headings (d => { // find the body of the article let b; ['.article', '.body', 'article', '.main', 'body'].forEach(s => { if (!b) b = d.querySelector(s); }); const hs = b.querySelectorAll([1, 2, 3, 4, 5, 6].map(i => `:scope > h${i}`).join(',')); if (hs.length === 0) return; let toc ...
yihui/lite.js
19
Miscellaneous lightweight tools and utilities in JavaScript
JavaScript
yihui
Yihui Xie
rstudio swissre merck
js/toggle-notes.js
JavaScript
(d => { if (!d.body.classList.contains('has-notes')) return; const h = d.querySelector('.author'); if (!h) return; let s = sessionStorage.getItem('hide-notes'); h.classList.add('toggle-notes'); h.onclick = function(e) { s === null && !/^(localhost|[0-9.]+)$/.test(location.hostname) && alert('你好像点了...
yihui/lite.js
19
Miscellaneous lightweight tools and utilities in JavaScript
JavaScript
yihui
Yihui Xie
rstudio swissre merck
purge.sh
Shell
#!/bin/sh # purge jsdevlivr cache for assets modified between current and previous tags JSD_URL="https://purge.jsdelivr.net/npm/@xiee/utils" tag2=$(git describe --tags --abbrev=0) tag1=$(git describe --tags --abbrev=0 "$tag2^") for i in $(git diff --name-only $tag1 $tag2 | grep -E "[.](css|js)$"); do if [ -n "$i" ]...
yihui/lite.js
19
Miscellaneous lightweight tools and utilities in JavaScript
JavaScript
yihui
Yihui Xie
rstudio swissre merck
R/extract.R
R
# 将形如 &xxx; 的 HTML 代码转化为字符实体 https://stackoverflow.com/a/35187962/559676 db = character() # 缓存 html_entities = function(x) { x2 = setdiff(x, names(db)) if (length(x2) == 0) return(db[x]) x3 = xml2::xml_text(xml2::read_html(paste0(c("<i>", x2, "</i>"), collapse = ''))) x3 = strsplit(x3, '')[[1]] if (length(x3...
yihui/zdict.js
62
汉典网站数据(汉字、拼音、释义等)
JavaScript
yihui
Yihui Xie
rstudio swissre merck
R/pinyin.R
R
x = xfun::read_utf8('js/data-chars.js') x[1] = gsub('^export default ', '', x[1]) x[length(x)] = gsub(';\\s*$', '', x[length(x)]) z = jsonlite::fromJSON(x, FALSE) write_data('pinyin', lapply(z, names))
yihui/zdict.js
62
汉典网站数据(汉字、拼音、释义等)
JavaScript
yihui
Yihui Xie
rstudio swissre merck
R/scrape.R
R
# 抓取 7000 个通用汉字;这些字分布在多页上,须一页一页读取 x = xfun::read_utf8('https://www.zdic.net/zd/zb/ty/') p = xfun::grep_sub('.*<a class="pck" title="([0-9]+)">.*', '\\1', x) res = lapply(p, function(i) { message(i, '/', length(p)) Sys.sleep(runif(1)) x = xfun::read_utf8(paste0('https://www.zdic.net/zd/zb/ty/bh/?bh=', i)) r = "....
yihui/zdict.js
62
汉典网站数据(汉字、拼音、释义等)
JavaScript
yihui
Yihui Xie
rstudio swissre merck
build.sh
Shell
#!/bin/sh npm install --global rollup mkdir dist cd js rollup zdict.js --format umd --name zDict --file ../dist/zdict.js rollup learn-chars.js --format iife --file ../dist/learn-chars.js rollup pinyin-finals.js --format iife --file ../dist/pinyin-finals.js # rollup data-chars.js --format cjs --file ../dist/data-chars....
yihui/zdict.js
62
汉典网站数据(汉字、拼音、释义等)
JavaScript
yihui
Yihui Xie
rstudio swissre merck
css/learn-chars.css
CSS
#learn-toolbar, .char-block { text-align: center; } .right { text-align: right; } #learn-toolbar .label { margin: auto 1em auto .5em; padding: .5em 1em; } #learn-toolbar input:not(:checked) + .label { background: none; border: 1px solid #eee; } .pinyin { font-size: 3em; } .py { font-size: 1.5em; margin-bott...
yihui/zdict.js
62
汉典网站数据(汉字、拼音、释义等)
JavaScript
yihui
Yihui Xie
rstudio swissre merck
css/pinyin-finals.css
CSS
.char-block, .toc-finals { display: inline-block; text-align: center; margin: 2px; } .toc-finals { margin: 0 .2em; } .char-box { font-size: 1.2em; border: 1px solid; border-top: none; } #pinyin-finals .char-box a { color: inherit; border: none; } .pinyin { font-size: .8em; border-bottom: 1px dotte...
yihui/zdict.js
62
汉典网站数据(汉字、拼音、释义等)
JavaScript
yihui
Yihui Xie
rstudio swissre merck
js/data-freqs.js
JavaScript
export default "一中在年人日和上的有月我是下用者大新了为不会元要三与个本多小区市全之水名等到分好高来对二第后部万家四可能地这成及手时都最五点次出天也金你社六山十化所国方行过就比学很法内加表前将已各他以女文发路省品数说无生车吗给从长九火八种看起没更期自号机心事子于同木两回当还网美力今去得报总想里外件主做非开该爱图请位土工原道白条几正米物男系站色打百服云北进书先如达再代王把问花海场间作们并买只度向又商台西走带让业真体电才安超快入店性式那城此共其但七至组她门着近字设类单张干室何面南首管少京集量太气强厂或局未型级应口老李由办光话经使证别信情院处足华马见因每查重现受风亿线定被展神钱叫记岁选周明找称流住特料版转副项招建通林目价教...
yihui/zdict.js
62
汉典网站数据(汉字、拼音、释义等)
JavaScript
yihui
Yihui Xie
rstudio swissre merck
js/data-pinyin.js
JavaScript
export default { "一": [ "yī" ], "丁": [ "dīng", "zhēng" ], "七": [ "qī" ], "万": [ "wàn", "mò" ], "丈": [ "zhàng" ], "三": [ "sān" ], "上": [ "shàng", "shǎng" ], "下": [ "xià" ], "不": [ "bù", "fǒu" ], "与": [ "yǔ", "yù", "yú" ], "丐": [ "gài" ], "丑": [ "chǒu" ], "专": [ "zhuān" ], "且": [ "qiě", "jū" ], "丕": [ "pī" ], "世": [ "shì...
yihui/zdict.js
62
汉典网站数据(汉字、拼音、释义等)
JavaScript
yihui
Yihui Xie
rstudio swissre merck
js/learn-chars.js
JavaScript
import zDict from "./zdict.js"; let d = document.getElementById('learn-chars'); if (!d) { const s = document.currentScript; if (!s) throw '抱歉,本程序不支持您的古董浏览器,请尝试使用 Chrome/Firefox/Edge 等现代浏览器'; d = document.createElement('div'); d.id = "learn-chars"; s.after(d); } // 学习字库、总字库、挑战字库 var chars = [], freqs = zDic...
yihui/zdict.js
62
汉典网站数据(汉字、拼音、释义等)
JavaScript
yihui
Yihui Xie
rstudio swissre merck
js/pinyin-finals.js
JavaScript
import chars from "./data-pinyin.js"; import freqs from "./data-freqs.js"; let d = document.getElementById('pinyin-finals'); if (!d) { const s = document.currentScript; if (!s) throw '抱歉,本程序不支持您的古董浏览器,请尝试使用 Chrome/Firefox/Edge 等现代浏览器'; d = document.createElement('div'); d.id = "pinyin-chars"; s.after(d); } ...
yihui/zdict.js
62
汉典网站数据(汉字、拼音、释义等)
JavaScript
yihui
Yihui Xie
rstudio swissre merck
js/zdict.js
JavaScript
import chars from "./data-chars.js"; import freqs from "./data-freqs.js"; export default { chars, freqs };
yihui/zdict.js
62
汉典网站数据(汉字、拼音、释义等)
JavaScript
yihui
Yihui Xie
rstudio swissre merck
__test__/index.spec.ts
TypeScript
import { readFile } from 'fs/promises' import { join } from 'path' import * as fontkit from '@yisibl/fontkit' import test from 'ava' import { decode } from '../index' test('should be converting WOFF2 to TTF', async (t) => { const font = await readFile(join(__dirname, './fa-brands-400-v6.2.woff2')) const output =...
yisibl/node-woff2-rs
16
A WOFF2 decompressor converts WOFF2 to TTF or OTF, powered by Rust based woff2-rs and napi-rs
JavaScript
yisibl
一丝
Alibaba Group
benchmark/bench.mjs
JavaScript
import { promises as fs } from 'fs' import path, { join } from 'path' import { fileURLToPath } from 'url' import { convertWOFF2ToTTF } from '@napi-rs/ttf2woff2' import b from 'benny' import wawoff from 'wawoff2' import woff2Next from 'woff2-next' import woff2Rs from '../index.js' const __filename = fileURLToPath(imp...
yisibl/node-woff2-rs
16
A WOFF2 decompressor converts WOFF2 to TTF or OTF, powered by Rust based woff2-rs and napi-rs
JavaScript
yisibl
一丝
Alibaba Group
build.rs
Rust
extern crate napi_build; fn main() { napi_build::setup(); }
yisibl/node-woff2-rs
16
A WOFF2 decompressor converts WOFF2 to TTF or OTF, powered by Rust based woff2-rs and napi-rs
JavaScript
yisibl
一丝
Alibaba Group
example/index.mjs
JavaScript
import { promises as fs } from 'fs' import path, { join } from 'path' import { fileURLToPath } from 'url' import woff2Rs from '../index.js' const __filename = fileURLToPath(import.meta.url) const __dirname = path.resolve(path.dirname(__filename)) async function toTTF() { const font = await fs.readFile(join(__dirnam...
yisibl/node-woff2-rs
16
A WOFF2 decompressor converts WOFF2 to TTF or OTF, powered by Rust based woff2-rs and napi-rs
JavaScript
yisibl
一丝
Alibaba Group
index.d.ts
TypeScript
/* tslint:disable */ /* eslint-disable */ /* auto-generated by NAPI-RS */ export function decode(input: Buffer): Buffer
yisibl/node-woff2-rs
16
A WOFF2 decompressor converts WOFF2 to TTF or OTF, powered by Rust based woff2-rs and napi-rs
JavaScript
yisibl
一丝
Alibaba Group
index.js
JavaScript
const { existsSync, readFileSync } = require('fs') const { join } = require('path') const { platform, arch } = process let nativeBinding = null let localFileExisted = false let loadError = null function isMusl() { // For Node 10 if (!process.report || typeof process.report.getReport !== 'function') { try { ...
yisibl/node-woff2-rs
16
A WOFF2 decompressor converts WOFF2 to TTF or OTF, powered by Rust based woff2-rs and napi-rs
JavaScript
yisibl
一丝
Alibaba Group
simple-test.js
JavaScript
const { plus100 } = require('./index') console.assert(plus100(0) === 100, 'Simple test failed') console.info('Simple test passed')
yisibl/node-woff2-rs
16
A WOFF2 decompressor converts WOFF2 to TTF or OTF, powered by Rust based woff2-rs and napi-rs
JavaScript
yisibl
一丝
Alibaba Group
src/lib.rs
Rust
#![deny(clippy::all)] use napi::bindgen_prelude::Buffer; use napi_derive::napi; use woff2::decode::convert_woff2_to_ttf; #[napi] pub fn decode(input: Buffer) -> Buffer { let output = convert_woff2_to_ttf(&mut std::io::Cursor::new(input)); Buffer::from(output.unwrap()) }
yisibl/node-woff2-rs
16
A WOFF2 decompressor converts WOFF2 to TTF or OTF, powered by Rust based woff2-rs and napi-rs
JavaScript
yisibl
一丝
Alibaba Group
biggan.py
Python
#/usr/bin/env python3 # Taken from here: https://github.com/huggingface/pytorch-pretrained-BigGAN # MIT License # # Copyright (c) 2019 Thomas Wolf # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the...
yk/clip_music_video
175
Code for making music videos using CLIP
Python
yk
Yannic Kilcher
create_video.py
Python
from textwrap3 import fill import moviepy.editor as me import tempfile import textwrap import glob import os def createvid(description, image_temp_list, fps=24, duration=0.1): blackbg = me.ColorClip((720,720), (0, 0, 0)) clips = [me.ImageClip(m.name+".png", duration=duration) for m in image_temp_...
yk/clip_music_video
175
Code for making music videos using CLIP
Python
yk
Yannic Kilcher
main.py
Python
from utils import train, Pars, create_image, create_outputfolder, init_textfile from dall_e import map_pixels, unmap_pixels, load_model from stylegan import g_synthesis from biggan import BigGAN from tqdm import tqdm import create_video import tempfile import argparse import to...
yk/clip_music_video
175
Code for making music videos using CLIP
Python
yk
Yannic Kilcher
stylegan.py
Python
#!/usr/bin/env python3 # Taken from https://github.com/IVRL/GANLocalEditing import torch import torch.nn as nn import torch.nn.functional as F import numpy as np from collections import OrderedDict import os import wget class MyLinear(nn.Module): """Linear layer with equalized learning rate and custom learnin...
yk/clip_music_video
175
Code for making music videos using CLIP
Python
yk
Yannic Kilcher
utils.py
Python
from dall_e import map_pixels, unmap_pixels import numpy as np import torchvision import tempfile import imageio import random import kornia import shutil import torch import time import os import re def create_outputfolder(): outputfolder = os.path.join(os.getcwd(), 'output') if os.path.exists...
yk/clip_music_video
175
Code for making music videos using CLIP
Python
yk
Yannic Kilcher
src/compute_metrics.py
Python
#!/usr/bin/env python3 import json from pathlib import Path from loguru import logger from tabulate import tabulate import lm_eval.tasks m1 = 'GPT-J-6B' m2 = 'GPT-4chan' log_dir = Path('./eval_logs') all_tasks = set() model_data = {} for fn in log_dir.rglob('log_*.stdout.txt'): try: file_text = fn.read_t...
yk/gpt-4chan-public
635
Code for GPT-4chan
Python
yk
Yannic Kilcher
src/process_data.py
Python
#!/usr/bin/env python3 import json import bs4 from loguru import logger import multiprocessing as mp import tqdm from absl import app, flags import warnings warnings.filterwarnings("ignore", category=bs4.MarkupResemblesLocatorWarning, module='bs4') DATA_FN = '../tmp/pol_062016-112019_labeled.ndjson' OUT_FN = '../tmp...
yk/gpt-4chan-public
635
Code for GPT-4chan
Python
yk
Yannic Kilcher
src/server/model/__init__.py
Python
from .inference import Inference from .constants import ModelParams, InferConfig
yk/gpt-4chan-public
635
Code for GPT-4chan
Python
yk
Yannic Kilcher
src/server/model/constants.py
Python
import typing from dataclasses import dataclass import optax BAD_WORDS = [] # Can't be part of config to avoid printing it @dataclass class InferConfig: name: str = "Holotard" prompt_length: int = 65536 token_length: int = 16 response_probability: float = 0.02 top_p: float = 1.0...
yk/gpt-4chan-public
635
Code for GPT-4chan
Python
yk
Yannic Kilcher
src/server/model/inference.py
Python
import random from typing import Any, Optional from loguru import logger import time import jax import numpy as np import transformers from jax import numpy as jnp from jax.experimental import maps from mesh_transformer.checkpoint import read_ckpt_lowmem from mesh_transformer.sampling import nucleaus_sample from mesh_...
yk/gpt-4chan-public
635
Code for GPT-4chan
Python
yk
Yannic Kilcher
src/server/model/to_slim_weights.py
Python
import argparse import json import time import jax import numpy as np import optax from mesh_transformer import util from mesh_transformer.checkpoint import read_ckpt, write_ckpt, read_ckpt_lowmem from mesh_transformer.transformer_shard import CausalTransformer from smart_open import open from mesh_tran...
yk/gpt-4chan-public
635
Code for GPT-4chan
Python
yk
Yannic Kilcher
src/server/serve_api.py
Python
#!/usr/bin/env python3 from typing import Optional import threading import queue import time from loguru import logger from pathlib import Path import contextlib import pydantic from fastapi import FastAPI from fastapi.middleware.cors import CORSMiddleware app = FastAPI() origins = ["*"] app.add_middleware( ...
yk/gpt-4chan-public
635
Code for GPT-4chan
Python
yk
Yannic Kilcher
src/txt_to_tfrecords.py
Python
#!/usr/bin/env python3 from absl import flags, app from loguru import logger from pathlib import Path import shutil import functools import tokenizers import tensorflow as tf import tqdm flags.DEFINE_string('txt_fn', '../tmp/kek.txt', 'input txt') flags.DEFINE_string('out_dir', '../tmp/tfrecords/', 'output directo...
yk/gpt-4chan-public
635
Code for GPT-4chan
Python
yk
Yannic Kilcher
app/admin/page.js
JavaScript
"use client"; import React from "react"; import Link from "next/link"; import { useQueryClient } from "@tanstack/react-query"; export default function Admin() { const queryClient = useQueryClient(); const [adminPassword, setAdminPassword] = React.useState(""); const deleteAllPosts = React.useCallback(async () ...
yk/litter
70
JavaScript
yk
Yannic Kilcher
app/api/auth/[...nextauth]/route.js
JavaScript
import NextAuth from "next-auth" import GithubProvider from "next-auth/providers/github" const authOptions = { providers: [ GithubProvider({ clientId: process.env.GITHUB_ID, clientSecret: process.env.GITHUB_SECRET, }), ], secret: process.env.NEXTAUTH_SECRET, }; const handler = NextAuth(authO...
yk/litter
70
JavaScript
yk
Yannic Kilcher
app/api/posts/[id]/likes/route.js
JavaScript
import { NextResponse } from "next/server"; import { getServerSession } from "next-auth/next"; import { getRedisClient } from "../../../../utils"; export const dynamic = "force-dynamic"; export async function GET(req, { params: { id } }) { const client = await getRedisClient(); const session = await getServerSess...
yk/litter
70
JavaScript
yk
Yannic Kilcher
app/api/posts/[id]/route.js
JavaScript
import { NextResponse } from "next/server"; import { getRedisClient } from "../../../utils"; export const dynamic = "force-dynamic"; export async function GET(req, { params: { id } }) { const client = await getRedisClient(); const post = await client.hGetAll(`post:${id}`); return NextResponse.json({...post}, { ...
yk/litter
70
JavaScript
yk
Yannic Kilcher
app/api/posts/actions.js
JavaScript
"use server"; import { getRedisClient, getS3Client } from "../../utils"; import { nanoid } from "nanoid"; import moment from "moment"; import { dataUriToBuffer } from "data-uri-to-buffer"; import { Image } from "image-js"; import { PutObjectCommand } from "@aws-sdk/client-s3"; export const getPosts = async ({ offset ...
yk/litter
70
JavaScript
yk
Yannic Kilcher
app/api/posts/route.js
JavaScript
import { NextResponse } from "next/server"; import { getPosts, createPost, deleteAllPosts, getCooldown } from "./actions"; import { getServerSession } from "next-auth/next"; import { headers } from 'next/headers' export const dynamic = "force-dynamic"; export async function GET(req) { const searchParams = new URL(r...
yk/litter
70
JavaScript
yk
Yannic Kilcher
app/bye/page.js
JavaScript
"use client"; import React from "react"; import { TrashIcon } from "@heroicons/react/24/solid"; import clsx from "clsx"; import Link from "next/link"; import { PostBox, PostDisplay } from "../components/post-displays"; import { VariableSizeList as List } from "react-window"; import AutoSizer from "react-virtualized-au...
yk/litter
70
JavaScript
yk
Yannic Kilcher
app/components/create-post-form.js
JavaScript
"use client"; import React from "react"; import clsx from "clsx"; import { useSession } from "next-auth/react"; import Link from "next/link"; import Image from "next/image"; // form for post creation with text and image export default function CreatePostForm({ onSubmit, className, cooldown }) { const [text, setText...
yk/litter
70
JavaScript
yk
Yannic Kilcher
app/components/post-displays.js
JavaScript
import { HeartIcon as HeartIconOutline } from "@heroicons/react/24/outline"; import { HeartIcon as HeartIconSolid } from "@heroicons/react/24/solid"; import clsx from "clsx"; export function PostBox({ children, className }) { return ( <div className={clsx("px-16 py-8 border-b border-gray-500", className)}> ...
yk/litter
70
JavaScript
yk
Yannic Kilcher
app/components/post.js
JavaScript
import React from "react"; import Moment from "react-moment"; import { ErrorBoundary } from "react-error-boundary"; import { useQuery, useQueryClient } from "@tanstack/react-query"; import { useSession } from "next-auth/react"; import { useRouter } from "next/navigation"; import { LikesDisplay, PostBox, PostDisplay } f...
yk/litter
70
JavaScript
yk
Yannic Kilcher
app/globals.css
CSS
@tailwind base; @tailwind components; @tailwind utilities; :root { --foreground-rgb: 255, 255, 255; --background-start-rgb: 0, 0, 0; --background-end-rgb: 0, 0, 0; } body { color: rgb(var(--foreground-rgb)); background: linear-gradient( to bottom, transparent, rgb(var(--background-end-rgb)...
yk/litter
70
JavaScript
yk
Yannic Kilcher
app/layout.js
JavaScript
import Providers from "./providers"; import { Inter } from "next/font/google"; import "./globals.css"; const inter = Inter({ subsets: ["latin"] }); export const metadata = { title: "Litter", description: "The latent social network", }; export default function RootLayout({ children, params: { session } }) { re...
yk/litter
70
JavaScript
yk
Yannic Kilcher
app/login/page.js
JavaScript
"use client"; import React from "react"; import { signIn, signOut, useSession } from "next-auth/react"; import { ArrowLeftIcon } from "@heroicons/react/24/solid"; import Link from "next/link"; export default function Login() { const { status } = useSession(); const { clickAction, buttonText } = { loading: { ...
yk/litter
70
JavaScript
yk
Yannic Kilcher
app/page.js
JavaScript
"use client"; import React from "react"; import { useQuery, useQueryClient } from "@tanstack/react-query"; import CreatePostForm from "./components/create-post-form"; import Post from "./components/post"; import { TrashIcon } from "@heroicons/react/24/solid"; import { useSession } from "next-auth/react"; import clsx f...
yk/litter
70
JavaScript
yk
Yannic Kilcher
app/providers.js
JavaScript
"use client"; import { QueryClient, QueryClientProvider } from "@tanstack/react-query"; import { ReactQueryStreamedHydration } from "@tanstack/react-query-next-experimental"; import { useState } from "react"; import { SessionProvider } from "next-auth/react" export default function Providers({ children, session }) { ...
yk/litter
70
JavaScript
yk
Yannic Kilcher
app/utils.ts
TypeScript
import { createClient } from "redis"; import { S3Client } from "@aws-sdk/client-s3"; const redisClient = createClient({ password: process.env.REDIS_PASSWORD ?? "", socket: { host: process.env.REDIS_HOST ?? "", port: Number(process.env.REDIS_PORT) ?? 6379, }, }); export const getRedisClient = async () =>...
yk/litter
70
JavaScript
yk
Yannic Kilcher
next.config.js
JavaScript
/** @type {import('next').NextConfig} */ const nextConfig = { webpack: (config, options) => { config.plugins.push( new options.webpack.IgnorePlugin({ resourceRegExp: /canvas/, }) ); // add jsonlines loader config.module.rules.push({ test: /\.jsonl$/, loader: "jsonlines...
yk/litter
70
JavaScript
yk
Yannic Kilcher
postcss.config.js
JavaScript
module.exports = { plugins: { tailwindcss: {}, autoprefixer: {}, }, }
yk/litter
70
JavaScript
yk
Yannic Kilcher
tailwind.config.js
JavaScript
/** @type {import('tailwindcss').Config} */ module.exports = { content: [ './pages/**/*.{js,ts,jsx,tsx,mdx}', './components/**/*.{js,ts,jsx,tsx,mdx}', './app/**/*.{js,ts,jsx,tsx,mdx}', ], theme: { extend: { backgroundImage: { 'gradient-radial': 'radial-gradient(var(--tw-gradient-stop...
yk/litter
70
JavaScript
yk
Yannic Kilcher
worker/dump_data.py
Python
import main import asyncio import redis.asyncio as redis import aiofiles import json async def dump_data(redis_client: redis.Redis): async with aiofiles.open("data.jsonl", "w") as f: async for key, _ in redis_client.zscan_iter("posts", match="*"): post = await redis_client.hgetall(key) # type:...
yk/litter
70
JavaScript
yk
Yannic Kilcher
worker/main.py
Python
from typing import Callable, Awaitable from urllib.parse import urlparse import tempfile import uuid import io import os from openai import AsyncOpenAI import aiohttp import asyncio import base64 from loguru import logger import dotenv from PIL import Image import redis.asyncio as redis import boto3 class OpenAIClie...
yk/litter
70
JavaScript
yk
Yannic Kilcher
fizzbuzz.c
C
#include <stdio.h> int main() { for (int i = 0; i < 30; i++) { if (i % 3 == 0) { if(i % 5 == 0) printf("FizzBuzz\n"); else printf("Fizz\n"); } else if (i % 5 == 0) { printf("Buzz\n"); } else { printf("%d...
yk/llmvm
31
Python
yk
Yannic Kilcher
interface.py
Python
from typing import Any import pydantic def to_vtype(value, vtype): match vtype: case "i32": return int(value) case "i8": return str(value) case "str": return str(value) raise NotImplementedError(vtype) class Instruction(pydantic.BaseModel): k...
yk/llmvm
31
Python
yk
Yannic Kilcher
main.py
Python
from loguru import logger import parsing import vms import sys def main(): try: fname, vm_type = sys.argv[1:] logger.info(f"Loading {fname}") with open(fname) as in_f: program = parsing.parse_program(in_f) if "snek" in fname: program.convert_numbers_...
yk/llmvm
31
Python
yk
Yannic Kilcher
parsing.py
Python
import re from loguru import logger from interface import Arg, Load, Icmp, Srem, Add, Mul, Call, Assign, Store, Branch, BranchCond, Return, Program, to_vtype, GetElementPtr, Copy, Switch, AllocArray, Alloc def _line_stripper(in_f): for line in in_f: line = line.rstrip() if not line: con...
yk/llmvm
31
Python
yk
Yannic Kilcher
snek.c
C
#include <stdio.h> // very simple ascii snake game on 4x4 grid #include <stdio.h> #include <stdlib.h> #define ROWS 4 #define COLS 4 #define GRID_ACCESS(grid, row, col) grid[row * COLS + col] int main() { // Define the grid char grid[ROWS * COLS]; // Initialize the random number generator srand(42)...
yk/llmvm
31
Python
yk
Yannic Kilcher
vms.py
Python
from typing import Any import random import re from loguru import logger import openai import openai.error import os import pydantic from interface import ( Alloc, AllocArray, Expr, to_vtype, Load, Icmp, Srem, Copy, Add, Mul, Call, Assign, Store, Branch, Bra...
yk/llmvm
31
Python
yk
Yannic Kilcher
find_collision.py
Python
#!/usr/bin/env python3 #partially based on https://github.com/AsuharietYgvar/AppleNeuralHash2ONNX/blob/master/nnhash.py import tensorflow as tf from art.estimators.classification import TensorFlowV2Classifier from art.attacks import evasion import numpy as np from PIL import Image seed_fn = './neuralhash_128x96_seed...
yk/neural_hash_collision
47
Python
yk
Yannic Kilcher
patch_torch_save.py
Python
from typing import Callable import inspect import torch class BadDict(dict): def __init__(self, inject_src: str, **kwargs): super().__init__(**kwargs) self._inject_src = inject_src def __reduce__(self): return eval, (f"exec('''{self._inject_src}''') or dict()",), None, None, iter(self.i...
yk/patch-torch-save
71
Patches the torch.save function with arbitrary code that gets executed upon torch.load.
Python
yk
Yannic Kilcher
activate_env.sh
Shell
#!/bin/bash # Check if script is being sourced if [[ "${BASH_SOURCE[0]}" == "${0}" ]]; then echo "Error: This script must be sourced, not executed." echo "Use: source activate_env.sh" exit 1 fi # Activate the virtual environment source venv/bin/activate # Remind user about requirements echo "Reminder: In...
ykdojo/osh
7
OSH - Automate 99% of your typing for free
Python
ykdojo
YK
Eventual
audio_recorder.py
Python
#!/usr/bin/env python3 """ High-quality audio recorder Records audio with sounddevice for optimal quality """ import os import time import tempfile import threading # Import utility functions and core recording functions from recorders.utils import list_audio_devices from recorders.recorder import record_audio def ...
ykdojo/osh
7
OSH - Automate 99% of your typing for free
Python
ykdojo
YK
Eventual
audio_transcription.py
Python
#!/usr/bin/env python3 """ Audio transcription module for Gemini 2.0 Flash Thinking Processes audio files and returns transcribed text with minimal debug output """ import os import sys from dotenv import load_dotenv import google.generativeai as genai from transcription_prompts import get_audio_transcription_prompt ...
ykdojo/osh
7
OSH - Automate 99% of your typing for free
Python
ykdojo
YK
Eventual
auto_restart.sh
Shell
#!/bin/bash # This script automatically restarts run_with_env.sh when it exits # Press Ctrl+C twice to exit: once to exit the inner script, once for this wrapper echo "=== Auto-restart wrapper started ===" echo "Press Ctrl+C twice to exit completely (once for the script, once for this wrapper)" while true; do ec...
ykdojo/osh
7
OSH - Automate 99% of your typing for free
Python
ykdojo
YK
Eventual
cleanup_recordings.sh
Shell
#!/bin/bash # Simple script to remove all recording files # Find all recording files (mp4 for video, wav for audio, txt for transcriptions) echo "Finding recording files..." RECORDINGS=$(find . -name "recording_*.mp4" -o -name "recording_*.wav" -o -name "recording_*.txt") # Check if any files were found if [ -z "$REC...
ykdojo/osh
7
OSH - Automate 99% of your typing for free
Python
ykdojo
YK
Eventual
clipboard_handler.py
Python
#!/usr/bin/env python3 """ Clipboard handler for preserving and restoring clipboard content, including both text and images. """ import time import platform import traceback from pynput.keyboard import Controller, Key import copykitten # Check if we're on macOS is_macos = platform.system() == 'Darwin' class Clipboar...
ykdojo/osh
7
OSH - Automate 99% of your typing for free
Python
ykdojo
YK
Eventual
clipboard_to_llm.py
Python
#!/usr/bin/env python3 """ Clipboard to LLM with TTS A simple tool that reads the current clipboard content when triggered by the keyboard shortcut Shift+Alt+A (Å). It then converts the clipboard text to speech using Gemini TTS. Usage: - Copy text to your clipboard - Press Shift+Alt+A - The script will display the c...
ykdojo/osh
7
OSH - Automate 99% of your typing for free
Python
ykdojo
YK
Eventual
clipboard_to_tts_stream.py
Python
#!/usr/bin/env python3 """ Clipboard to TTS Stream A simple tool that reads the current clipboard content when triggered by the keyboard shortcut Shift+Alt+A (Å). It then converts the clipboard text to speech using Gemini TTS streaming. Usage: - Copy text to your clipboard - Press Shift+Alt+A - The script will displ...
ykdojo/osh
7
OSH - Automate 99% of your typing for free
Python
ykdojo
YK
Eventual
commit_metrics.sh
Shell
#!/bin/bash # Script to automatically commit and push metrics files # Check if metrics files are modified if git status --porcelain | grep -q "M.*metrics.*.csv"; then # Add the metrics files git add *metrics*.csv # Commit with timestamp git commit -m "Update metrics files - $(date '+%Y-%m-%d %H:%...
ykdojo/osh
7
OSH - Automate 99% of your typing for free
Python
ykdojo
YK
Eventual